<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: stlsheet.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2008-03-12 11:22:55 $
 *
 *  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 _SD_STLSHEET_HXX
#define _SD_STLSHEET_HXX

#include <rtl/ref.hxx>

#include <com/sun/star/style/XStyle.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/beans/XPropertyState.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/util/XModifyBroadcaster.hpp>

#include <cppuhelper/interfacecontainer.h>
#include <cppuhelper/implbase5.hxx>
#include <cppuhelper/basemutex.hxx>

#include <svtools/style.hxx>

#include <svx/unoipset.hxx>

#include <boost/scoped_ptr.hpp>

class ModifyListenerForewarder;

typedef cppu::ImplInheritanceHelper5< SfxUnoStyleSheet,
                                    ::com::sun::star::beans::XPropertySet,
                                    ::com::sun::star::lang::XServiceInfo,
                                    ::com::sun::star::beans::XPropertyState,
                                    ::com::sun::star::util::XModifyBroadcaster,
                                    ::com::sun::star::lang::XComponent > SdStyleSheetBase ;

class SdStyleSheet : public SdStyleSheetBase, private ::cppu::BaseMutex
{
public:
    SdStyleSheet( const rtl::OUString& rDisplayName, SfxStyleSheetBasePool& rPool, SfxStyleFamily eFamily, USHORT nMask );
    SdStyleSheet( const SdStyleSheet& );

    virtual BOOL        SetParent (const String& rParentName);
    virtual SfxItemSet& GetItemSet();
    virtual BOOL        IsUsed() const;
    virtual BOOL        HasFollowSupport() const;
    virtual BOOL        HasParentSupport() const;
    virtual BOOL        HasClearParentSupport() const;
    virtual BOOL        SetName( const UniString& );
    virtual void        SetHelpId( const String& r, ULONG nId );

    void        AdjustToFontHeight(SfxItemSet& rSet, BOOL bOnlyMissingItems = TRUE);

    SdStyleSheet* GetRealStyleSheet() const;
    SdStyleSheet* GetPseudoStyleSheet() const;

    void SetApiName( const ::rtl::OUString& rApiName );
    rtl::OUString GetApiName() const { return msApiName; }

    static rtl::OUString GetFamilyString( SfxStyleFamily eFamily );

    static SdStyleSheet* CreateEmptyUserStyle( SfxStyleSheetBasePool& rPool, SfxStyleFamily eFamily );

    // XInterface
    virtual void SAL_CALL release(  ) throw ();

    // XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);

    // XNamed
    virtual ::rtl::OUString SAL_CALL getName(  ) throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setName( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException);

    // XStyle
    virtual sal_Bool SAL_CALL isUserDefined(  ) throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL isInUse(  ) throw(::com::sun::star::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getParentStyle(  ) throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setParentStyle( const ::rtl::OUString& aParentStyle ) throw(::com::sun::star::container::NoSuchElementException, ::com::sun::star::uno::RuntimeException);

    // XPropertySet
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& xListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    // XPropertyState
    virtual ::com::sun::star::beans::PropertyState SAL_CALL getPropertyState( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyState > SAL_CALL getPropertyStates( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aPropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setPropertyToDefault( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL getPropertyDefault( const ::rtl::OUString& aPropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    // XModifyBroadcaster
    virtual void SAL_CALL addModifyListener( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removeModifyListener( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);

    // XComponent
    virtual void SAL_CALL dispose(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);

    void notifyModifyListener();

protected:
    const SfxItemPropertyMap* getPropertyMapEntry( const ::rtl::OUString& rPropertyName ) const throw();

    virtual void Load (SvStream& rIn, USHORT nVersion);
    virtual void Store(SvStream& rOut);

    virtual void SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType);
    virtual             ~SdStyleSheet();

    void throwIfDisposed() throw (::com::sun::star::uno::RuntimeException);

    virtual void disposing();

    rtl::OUString   msApiName;
    rtl::Reference< SfxStyleSheetBasePool > mxPool;

    /** boradcast helper for events */
    ::cppu::OBroadcastHelper mrBHelper;

    boost::scoped_ptr< ModifyListenerForewarder > mpModifyListenerForewarder;

private:
    SdStyleSheet& operator=( const SdStyleSheet& ); // not implemented
};

typedef rtl::Reference< SdStyleSheet > SdStyleSheetRef;
typedef std::vector< SdStyleSheetRef > SdStyleSheetVector;

#endif     // _SD_STLSHEET_HXX

<commit_msg>INTEGRATION: CWS impress140 (1.4.18); FILE MERGED 2008/04/03 09:32:19 cl 1.4.18.1: #i87588# fixed empty api name problem and set parent problem<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: stlsheet.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: kz $ $Date: 2008-04-04 12:44:44 $
 *
 *  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 _SD_STLSHEET_HXX
#define _SD_STLSHEET_HXX

#include <rtl/ref.hxx>

#include <com/sun/star/style/XStyle.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/beans/XPropertyState.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/util/XModifyBroadcaster.hpp>

#include <cppuhelper/interfacecontainer.h>
#include <cppuhelper/implbase5.hxx>
#include <cppuhelper/basemutex.hxx>

#include <svtools/style.hxx>

#include <svx/unoipset.hxx>

#include <boost/scoped_ptr.hpp>

class ModifyListenerForewarder;

typedef cppu::ImplInheritanceHelper5< SfxUnoStyleSheet,
                                    ::com::sun::star::beans::XPropertySet,
                                    ::com::sun::star::lang::XServiceInfo,
                                    ::com::sun::star::beans::XPropertyState,
                                    ::com::sun::star::util::XModifyBroadcaster,
                                    ::com::sun::star::lang::XComponent > SdStyleSheetBase ;

class SdStyleSheet : public SdStyleSheetBase, private ::cppu::BaseMutex
{
public:
    SdStyleSheet( const rtl::OUString& rDisplayName, SfxStyleSheetBasePool& rPool, SfxStyleFamily eFamily, USHORT nMask );
    SdStyleSheet( const SdStyleSheet& );

    virtual BOOL        SetParent (const String& rParentName);
    virtual SfxItemSet& GetItemSet();
    virtual BOOL        IsUsed() const;
    virtual BOOL        HasFollowSupport() const;
    virtual BOOL        HasParentSupport() const;
    virtual BOOL        HasClearParentSupport() const;
    virtual BOOL        SetName( const UniString& );
    virtual void        SetHelpId( const String& r, ULONG nId );

    void        AdjustToFontHeight(SfxItemSet& rSet, BOOL bOnlyMissingItems = TRUE);

    SdStyleSheet* GetRealStyleSheet() const;
    SdStyleSheet* GetPseudoStyleSheet() const;

    void SetApiName( const ::rtl::OUString& rApiName );
    rtl::OUString GetApiName() const;

    static rtl::OUString GetFamilyString( SfxStyleFamily eFamily );

    static SdStyleSheet* CreateEmptyUserStyle( SfxStyleSheetBasePool& rPool, SfxStyleFamily eFamily );

    // XInterface
    virtual void SAL_CALL release(  ) throw ();

    // XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);

    // XNamed
    virtual ::rtl::OUString SAL_CALL getName(  ) throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setName( const ::rtl::OUString& aName ) throw(::com::sun::star::uno::RuntimeException);

    // XStyle
    virtual sal_Bool SAL_CALL isUserDefined(  ) throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL isInUse(  ) throw(::com::sun::star::uno::RuntimeException);
    virtual ::rtl::OUString SAL_CALL getParentStyle(  ) throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setParentStyle( const ::rtl::OUString& aParentStyle ) throw(::com::sun::star::container::NoSuchElementException, ::com::sun::star::uno::RuntimeException);

    // XPropertySet
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& xListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    // XPropertyState
    virtual ::com::sun::star::beans::PropertyState SAL_CALL getPropertyState( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyState > SAL_CALL getPropertyStates( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aPropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setPropertyToDefault( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL getPropertyDefault( const ::rtl::OUString& aPropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    // XModifyBroadcaster
    virtual void SAL_CALL addModifyListener( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removeModifyListener( const ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);

    // XComponent
    virtual void SAL_CALL dispose(  ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);

    void notifyModifyListener();

protected:
    const SfxItemPropertyMap* getPropertyMapEntry( const ::rtl::OUString& rPropertyName ) const throw();

    virtual void Load (SvStream& rIn, USHORT nVersion);
    virtual void Store(SvStream& rOut);

    virtual void SFX_NOTIFY(SfxBroadcaster& rBC, const TypeId& rBCType, const SfxHint& rHint, const TypeId& rHintType);
    virtual             ~SdStyleSheet();

    void throwIfDisposed() throw (::com::sun::star::uno::RuntimeException);

    virtual void disposing();

    rtl::OUString   msApiName;
    rtl::Reference< SfxStyleSheetBasePool > mxPool;

    /** boradcast helper for events */
    ::cppu::OBroadcastHelper mrBHelper;

    boost::scoped_ptr< ModifyListenerForewarder > mpModifyListenerForewarder;

private:
    SdStyleSheet& operator=( const SdStyleSheet& ); // not implemented
};

typedef rtl::Reference< SdStyleSheet > SdStyleSheetRef;
typedef std::vector< SdStyleSheetRef > SdStyleSheetVector;

#endif     // _SD_STLSHEET_HXX

<|endoftext|>


<commit_before>// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#include "include/dart_native_api.h"

#include "platform/assert.h"
#include "vm/dart_api_impl.h"
#include "vm/dart_api_message.h"
#include "vm/dart_api_state.h"
#include "vm/message.h"
#include "vm/native_message_handler.h"
#include "vm/port.h"

namespace dart {

// --- Message sending/receiving from native code ---

static uint8_t* allocator(uint8_t* ptr, intptr_t old_size, intptr_t new_size) {
  void* new_ptr = realloc(reinterpret_cast<void*>(ptr), new_size);
  return reinterpret_cast<uint8_t*>(new_ptr);
}

class IsolateSaver {
 public:
  explicit IsolateSaver(Isolate* current_isolate)
      : saved_isolate_(current_isolate) {
    if (current_isolate != NULL) {
      ASSERT(current_isolate == Isolate::Current());
      Thread::ExitIsolate();
    }
  }
  ~IsolateSaver() {
    if (saved_isolate_ != NULL) {
      Thread::EnterIsolate(saved_isolate_);
    }
  }
 private:
  Isolate* saved_isolate_;

  DISALLOW_COPY_AND_ASSIGN(IsolateSaver);
};

DART_EXPORT bool Dart_PostCObject(Dart_Port port_id, Dart_CObject* message) {
  uint8_t* buffer = NULL;
  ApiMessageWriter writer(&buffer, allocator);
  bool success = writer.WriteCMessage(message);

  if (!success) return success;

  // Post the message at the given port.
  return PortMap::PostMessage(new Message(
      port_id, buffer, writer.BytesWritten(), Message::kNormalPriority));
}

DART_EXPORT bool Dart_PostInteger(Dart_Port port_id, int64_t message) {
  if (Smi::IsValid(message)) {
    return PortMap::PostMessage(new Message(
        port_id, Smi::New(message), Message::kNormalPriority));
  }
  Dart_CObject cobj;
  cobj.type = Dart_CObject_kInt64;
  cobj.value.as_int64 = message;
  return Dart_PostCObject(port_id, &cobj);
}

DART_EXPORT Dart_Port Dart_NewNativePort(const char* name,
                                         Dart_NativeMessageHandler handler,
                                         bool handle_concurrently) {
  if (name == NULL) {
    name = "<UnnamedNativePort>";
  }
  if (handler == NULL) {
    OS::PrintErr("%s expects argument 'handler' to be non-null.\n",
                 CURRENT_FUNC);
    return ILLEGAL_PORT;
  }
  // Start the native port without a current isolate.
  IsolateSaver saver(Isolate::Current());

  NativeMessageHandler* nmh = new NativeMessageHandler(name, handler);
  Dart_Port port_id = PortMap::CreatePort(nmh);
  nmh->Run(Dart::thread_pool(), NULL, NULL, 0);
  return port_id;
}

DART_EXPORT bool Dart_CloseNativePort(Dart_Port native_port_id) {
  // Close the native port without a current isolate.
  IsolateSaver saver(Isolate::Current());

  // TODO(turnidge): Check that the port is native before trying to close.
  return PortMap::ClosePort(native_port_id);
}

// --- Verification tools ---

static void CompileAll(Thread* thread, Dart_Handle* result) {
  ASSERT(thread != NULL);
  const Error& error = Error::Handle(thread->zone(), Library::CompileAll());
  if (error.IsNull()) {
    *result = Api::Success();
  } else {
    *result = Api::NewHandle(thread, error.raw());
  }
}

DART_EXPORT Dart_Handle Dart_CompileAll() {
  DARTSCOPE(Thread::Current());
  Dart_Handle result = Api::CheckAndFinalizePendingClasses(T);
  if (::Dart_IsError(result)) {
    return result;
  }
  CHECK_CALLBACK_STATE(T);
  CompileAll(T, &result);
  return result;
}

}  // namespace dart
<commit_msg>Fix build<commit_after>// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#include "include/dart_native_api.h"

#include "platform/assert.h"
#include "vm/dart_api_impl.h"
#include "vm/dart_api_message.h"
#include "vm/dart_api_state.h"
#include "vm/message.h"
#include "vm/native_message_handler.h"
#include "vm/port.h"

namespace dart {

// --- Message sending/receiving from native code ---

static uint8_t* allocator(uint8_t* ptr, intptr_t old_size, intptr_t new_size) {
  void* new_ptr = realloc(reinterpret_cast<void*>(ptr), new_size);
  return reinterpret_cast<uint8_t*>(new_ptr);
}

class IsolateSaver {
 public:
  explicit IsolateSaver(Isolate* current_isolate)
      : saved_isolate_(current_isolate) {
    if (current_isolate != NULL) {
      ASSERT(current_isolate == Isolate::Current());
      Thread::ExitIsolate();
    }
  }
  ~IsolateSaver() {
    if (saved_isolate_ != NULL) {
      Thread::EnterIsolate(saved_isolate_);
    }
  }
 private:
  Isolate* saved_isolate_;

  DISALLOW_COPY_AND_ASSIGN(IsolateSaver);
};

static bool PostCObjectHelper(Dart_Port port_id, Dart_CObject* message) {
  uint8_t* buffer = NULL;
  ApiMessageWriter writer(&buffer, allocator);
  bool success = writer.WriteCMessage(message);

  if (!success) return success;

  // Post the message at the given port.
  return PortMap::PostMessage(new Message(
      port_id, buffer, writer.BytesWritten(), Message::kNormalPriority));
}

DART_EXPORT bool Dart_PostCObject(Dart_Port port_id, Dart_CObject* message) {
  return PostCObjectHelper(port_id, message);
}

DART_EXPORT bool Dart_PostInteger(Dart_Port port_id, int64_t message) {
  if (Smi::IsValid(message)) {
    return PortMap::PostMessage(new Message(
        port_id, Smi::New(message), Message::kNormalPriority));
  }
  Dart_CObject cobj;
  cobj.type = Dart_CObject_kInt64;
  cobj.value.as_int64 = message;
  return PostCObjectHelper(port_id, &cobj);
}

DART_EXPORT Dart_Port Dart_NewNativePort(const char* name,
                                         Dart_NativeMessageHandler handler,
                                         bool handle_concurrently) {
  if (name == NULL) {
    name = "<UnnamedNativePort>";
  }
  if (handler == NULL) {
    OS::PrintErr("%s expects argument 'handler' to be non-null.\n",
                 CURRENT_FUNC);
    return ILLEGAL_PORT;
  }
  // Start the native port without a current isolate.
  IsolateSaver saver(Isolate::Current());

  NativeMessageHandler* nmh = new NativeMessageHandler(name, handler);
  Dart_Port port_id = PortMap::CreatePort(nmh);
  nmh->Run(Dart::thread_pool(), NULL, NULL, 0);
  return port_id;
}

DART_EXPORT bool Dart_CloseNativePort(Dart_Port native_port_id) {
  // Close the native port without a current isolate.
  IsolateSaver saver(Isolate::Current());

  // TODO(turnidge): Check that the port is native before trying to close.
  return PortMap::ClosePort(native_port_id);
}

// --- Verification tools ---

static void CompileAll(Thread* thread, Dart_Handle* result) {
  ASSERT(thread != NULL);
  const Error& error = Error::Handle(thread->zone(), Library::CompileAll());
  if (error.IsNull()) {
    *result = Api::Success();
  } else {
    *result = Api::NewHandle(thread, error.raw());
  }
}

DART_EXPORT Dart_Handle Dart_CompileAll() {
  DARTSCOPE(Thread::Current());
  Dart_Handle result = Api::CheckAndFinalizePendingClasses(T);
  if (::Dart_IsError(result)) {
    return result;
  }
  CHECK_CALLBACK_STATE(T);
  CompileAll(T, &result);
  return result;
}

}  // namespace dart
<|endoftext|>


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

#include "trainer.h"

#include <QtCore/QtMath>
#include <QDate>

Trainer::Trainer(QObject *parent) : QObject(parent),
    _modus(GUESS_TRANSLATION),
    _index(0),
    _vocabulary(),
    _sum(0),
    _rnd(),
    _settings()
{
}

QString Trainer::word()
{
    if(_vocabulary.size() == 0)
    {
        return "";
    }
    return _vocabulary[_index].word;
}

QString Trainer::translation()
{
    if(_vocabulary.size() == 0)
    {
        return "";
    }
    return _vocabulary[_index].translation;
}

Trainer::trainings_modus Trainer::modus()
{
    return _modus;
}

int Trainer::language()
{
    if(_vocabulary.size() == 0)
    {
        return -1;
    }
    return _vocabulary[_index].language;
}

bool Trainer::load_vocabulary(QVariantList filter_type, QVariantList filter_argv)
{
    if(filter_type.size() != filter_argv.size())
    {
        WARNING("filter_type and filter_argv must have same size!" << filter_type.size() << filter_argv.size());
        return false;
    }

    // Init vocabulary list
    bool first_where = true;
    QString s = "SELECT rowid,word,translation,priority,language FROM vocabulary";
    QSqlQuery q(database);

    for(int i = 0; i < filter_type.size(); ++i)
    {
        if(first_where)
        {
            s.append(" WHERE ");
        }
        else
        {
            s.append(" AND ");
        }

        if(!filter_type[i].canConvert<int>())
        {
            WARNING(QString("Can not convert %1 to filter").arg(filter_type[i].typeName()));
            return false;
        }
        int int_type = filter_type[i].toInt();
        if(int_type <= 0 || int_type >= filters_after_enum)
        {
            WARNING("Filter type" << int_type << "out of range");
            return false;
        }

        switch(static_cast<filters>(int_type))
        {
            case LANGUAGE:
                s.append("language=?");
                break;
            case MODIFICATION_SINCE:
                s.append("modification >= ?");
                break;
            case MODIFICATION_UNTIL:
                s.append("modification <= ?");
                break;
            case CREATION_SINCE:
                s.append("creation >= ?");
                break;
            case CREATION_UNTIL:
                s.append("creation <= ?");
                break;
            case filters_after_enum:
                WARNING("filters_after_enum received");
                return false;
                break;
            default:
                Q_UNREACHABLE();
                WARNING("Impossible filter type");
                return false;
                break;
        }
    }

    DEBUG(s);

    q.prepare(s);

    for(int i = 0; i < filter_type.size(); ++i)
    {
        if(first_where)
        {
            s.append(" WHERE ");
        }
        else
        {
            s.append(" AND ");
        }

        if(!filter_type[i].canConvert<int>())
        {
            WARNING(QString("Can not convert %1 to filter").arg(filter_type[i].typeName()));
            return false;
        }
        int int_type = filter_type[i].toInt();
        if(int_type <= 0 || int_type >= filters_after_enum)
        {
            WARNING("Filter type" << int_type << "out of range");
            return false;
        }

        switch(static_cast<filters>(int_type))
        {
            case LANGUAGE:
                q.addBindValue(filter_argv[i].toInt());
                break;
            case MODIFICATION_SINCE:
            case MODIFICATION_UNTIL:
            case CREATION_SINCE:
            case CREATION_UNTIL:
                q.addBindValue(filter_argv[i].toDate().toJulianDay());
                break;
            case filters_after_enum:
                WARNING("filters_after_enum received");
                return false;
                break;
            default:
                Q_UNREACHABLE();
                WARNING("Impossible filter type");
                return false;
                break;
        }
    }

    if(!q.exec())
    {
        QString error = s;
        error.append(": ").append(q.lastError().text());
        WARNING(error);
        return false;
    }
    else
    {
        if(!q.isSelect())
        {
            QString error = s;
            error.append(": No select");
            WARNING(error);
            return false;
        }
        else
        {
            while(q.next())
            {
                vocabulary v;
                v.id = q.value(0).toInt();
                v.word = q.value(1).toString();
                v.translation = q.value(2).toString();
                v.priority = q.value(3).toInt();
                v.language = q.value(4).toInt();
                _sum += v.priority;
                _vocabulary.append(v);
            }
        }
    }

    return _vocabulary.size() != 0;
}

int Trainer::count_vocabulary(QVariantList filter_type, QVariantList filter_argv)
{
    if(filter_type.size() != filter_argv.size())
    {
        WARNING("filter_type and filter_argv must have same size!" << filter_type.size() << filter_argv.size());
        return 0;
    }

    // Init vocabulary list
    bool first_where = true;
    QString s = "SELECT count(*) FROM vocabulary";
    QSqlQuery q(database);

    for(int i = 0; i < filter_type.size(); ++i)
    {
        if(first_where)
        {
            s.append(" WHERE ");
        }
        else
        {
            s.append(" AND ");
        }

        if(!filter_type[i].canConvert<int>())
        {
            WARNING(QString("Can not convert %1 to filter").arg(filter_type[i].typeName()));
            return 0;
        }
        int int_type = filter_type[i].toInt();
        if(int_type <= 0 || int_type >= filters_after_enum)
        {
            WARNING("Filter type" << int_type << "out of range");
            return 0;
        }

        switch(static_cast<filters>(int_type))
        {
            case LANGUAGE:
                s.append("language=?");
                break;
            case MODIFICATION_SINCE:
                s.append("modification >= ?");
                break;
            case MODIFICATION_UNTIL:
                s.append("modification <= ?");
                break;
            case CREATION_SINCE:
                s.append("creation >= ?");
                break;
            case CREATION_UNTIL:
                s.append("creation <= ?");
                break;
            case filters_after_enum:
                WARNING("filters_after_enum received");
                return 0;
                break;
            default:
                Q_UNREACHABLE();
                WARNING("Impossible filter type");
                return 0;
                break;
        }
    }

    DEBUG(s);

    q.prepare(s);

    for(int i = 0; i < filter_type.size(); ++i)
    {
        if(first_where)
        {
            s.append(" WHERE ");
        }
        else
        {
            s.append(" AND ");
        }

        if(!filter_type[i].canConvert<int>())
        {
            WARNING(QString("Can not convert %1 to filter").arg(filter_type[i].typeName()));
            return 0;
        }
        int int_type = filter_type[i].toInt();
        if(int_type <= 0 || int_type >= filters_after_enum)
        {
            WARNING("Filter type" << int_type << "out of range");
            return 0;
        }

        switch(static_cast<filters>(int_type))
        {
            case LANGUAGE:
                q.addBindValue(filter_argv[i].toInt());
                break;
            case MODIFICATION_SINCE:
            case MODIFICATION_UNTIL:
            case CREATION_SINCE:
            case CREATION_UNTIL:
                q.addBindValue(filter_argv[i].toDate().toJulianDay());
                break;
            case filters_after_enum:
                WARNING("filters_after_enum received");
                return 0;
                break;
            default:
                Q_UNREACHABLE();
                WARNING("Impossible filter type");
                return 0;
                break;
        }
    }

    if(!q.exec())
    {
        QString error = s;
        error.append(": ").append(q.lastError().text());
        WARNING(error);
        return 0;
    }
    else
    {
        if(!q.isSelect())
        {
            QString error = s;
            error.append(": No select");
            WARNING(error);
            return 0;
        }
        else
        {
            if(!q.next())
            {
                QString error = s;
                error.append(" - no value: ").append(q.lastError().text());
                WARNING(error);
                return 0;

            }
            return q.value(0).toInt();
        }
    }

    return 0;
}

void Trainer::next()
{
    std::uniform_int_distribution<int> distribution;
    if(_settings.adaptiveTrainingEnabled())
    {
        // Use adaptive mode
        distribution = std::uniform_int_distribution<int>(1, _sum);
        int selected_priority = distribution(_rnd);
        int sum = 0;

        for(int i = 0; i < _vocabulary.size(); ++i)
        {
            sum += _vocabulary[i].priority;
            if(sum >= selected_priority)
            {
                _index = i;
                break;
            }
        }
    }
    else
    {
        // Select random (no adaptive mode)
        distribution = std::uniform_int_distribution<int>(0, _vocabulary.size() - 1);
        _index = distribution(_rnd);
    }

    distribution = std::uniform_int_distribution<int>(0, 1);
    if(distribution(_rnd) == 0)
    {
        _modus = GUESS_TRANSLATION;
    }
    else
    {
        _modus = GUESS_WORD;
    }

    emit wordChanged(_vocabulary[_index].word);
    emit translationChanged(_vocabulary[_index].translation);
    emit modusChanged(_modus);
    emit languageChanged(_vocabulary[_index].language);
}

void Trainer::correct()
{
    if(_settings.adaptiveTrainingEnabled())
    {
        _sum -= _vocabulary[_index].priority;
        _vocabulary[_index].priority = qMax(1, _vocabulary[_index].priority - _settings.adaptiveTrainingCorrectPoints());
        _sum += _vocabulary[_index].priority;

        QString s = "UPDATE vocabulary SET priority=:p WHERE rowid=:id";
        QSqlQuery q(database);
        q.prepare(s);
        q.bindValue(":p", _vocabulary[_index].priority);
        q.bindValue(":id", _vocabulary[_index].id);

        if(!q.exec())
        {
            QString error = s;
            error.append(": ").append(q.lastError().text());
            WARNING(error);
        }
    }
}

void Trainer::wrong()
{
    if(_settings.adaptiveTrainingEnabled())
    {
        _sum -= _vocabulary[_index].priority;
        _vocabulary[_index].priority = qMin(100, _vocabulary[_index].priority + _settings.adaptiveTrainingWrongPoints());
        _sum += _vocabulary[_index].priority;

        QString s = "UPDATE vocabulary SET priority=:p WHERE rowid=:id";
        QSqlQuery q(database);
        q.prepare(s);
        q.bindValue(":p", _vocabulary[_index].priority);
        q.bindValue(":id", _vocabulary[_index].id);

        if(!q.exec())
        {
            QString error = s;
            error.append(": ").append(q.lastError().text());
            WARNING(error);
        }
    }
}
<commit_msg>Fixed SQL commands<commit_after>/*
 * Copyright 2016,2017 Marcus Soll
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "trainer.h"

#include <QtCore/QtMath>
#include <QDate>

Trainer::Trainer(QObject *parent) : QObject(parent),
    _modus(GUESS_TRANSLATION),
    _index(0),
    _vocabulary(),
    _sum(0),
    _rnd(),
    _settings()
{
}

QString Trainer::word()
{
    if(_vocabulary.size() == 0)
    {
        return "";
    }
    return _vocabulary[_index].word;
}

QString Trainer::translation()
{
    if(_vocabulary.size() == 0)
    {
        return "";
    }
    return _vocabulary[_index].translation;
}

Trainer::trainings_modus Trainer::modus()
{
    return _modus;
}

int Trainer::language()
{
    if(_vocabulary.size() == 0)
    {
        return -1;
    }
    return _vocabulary[_index].language;
}

bool Trainer::load_vocabulary(QVariantList filter_type, QVariantList filter_argv)
{
    if(filter_type.size() != filter_argv.size())
    {
        WARNING("filter_type and filter_argv must have same size!" << filter_type.size() << filter_argv.size());
        return false;
    }

    // Init vocabulary list
    bool first_where = true;
    QString s = "SELECT rowid,word,translation,priority,language FROM vocabulary";
    QSqlQuery q(database);

    for(int i = 0; i < filter_type.size(); ++i)
    {
        if(first_where)
        {
            s.append(" WHERE ");
        }
        else
        {
            s.append(" AND ");
        }
        first_where = false;

        if(!filter_type[i].canConvert<int>())
        {
            WARNING(QString("Can not convert %1 to filter").arg(filter_type[i].typeName()));
            return false;
        }
        int int_type = filter_type[i].toInt();
        if(int_type <= 0 || int_type >= filters_after_enum)
        {
            WARNING("Filter type" << int_type << "out of range");
            return false;
        }

        switch(static_cast<filters>(int_type))
        {
            case LANGUAGE:
                s.append("language=?");
                break;
            case MODIFICATION_SINCE:
                s.append("modification >= ?");
                break;
            case MODIFICATION_UNTIL:
                s.append("modification <= ?");
                break;
            case CREATION_SINCE:
                s.append("creation >= ?");
                break;
            case CREATION_UNTIL:
                s.append("creation <= ?");
                break;
            case filters_after_enum:
                WARNING("filters_after_enum received");
                return false;
                break;
            default:
                Q_UNREACHABLE();
                WARNING("Impossible filter type");
                return false;
                break;
        }
    }

    DEBUG(s);

    q.prepare(s);

    for(int i = 0; i < filter_type.size(); ++i)
    {
        if(!filter_type[i].canConvert<int>())
        {
            WARNING(QString("Can not convert %1 to filter").arg(filter_type[i].typeName()));
            return false;
        }
        int int_type = filter_type[i].toInt();
        if(int_type <= 0 || int_type >= filters_after_enum)
        {
            WARNING("Filter type" << int_type << "out of range");
            return false;
        }

        switch(static_cast<filters>(int_type))
        {
            case LANGUAGE:
                q.addBindValue(filter_argv[i].toInt());
                break;
            case MODIFICATION_SINCE:
            case MODIFICATION_UNTIL:
            case CREATION_SINCE:
            case CREATION_UNTIL:
                q.addBindValue(filter_argv[i].toDate().toJulianDay());
                break;
            case filters_after_enum:
                WARNING("filters_after_enum received");
                return false;
                break;
            default:
                Q_UNREACHABLE();
                WARNING("Impossible filter type");
                return false;
                break;
        }
    }

    if(!q.exec())
    {
        QString error = s;
        error.append(": ").append(q.lastError().text());
        WARNING(error);
        return false;
    }
    else
    {
        if(!q.isSelect())
        {
            QString error = s;
            error.append(": No select");
            WARNING(error);
            return false;
        }
        else
        {
            while(q.next())
            {
                vocabulary v;
                v.id = q.value(0).toInt();
                v.word = q.value(1).toString();
                v.translation = q.value(2).toString();
                v.priority = q.value(3).toInt();
                v.language = q.value(4).toInt();
                _sum += v.priority;
                _vocabulary.append(v);
            }
        }
    }

    return _vocabulary.size() != 0;
}

int Trainer::count_vocabulary(QVariantList filter_type, QVariantList filter_argv)
{
    if(filter_type.size() != filter_argv.size())
    {
        WARNING("filter_type and filter_argv must have same size!" << filter_type.size() << filter_argv.size());
        return 0;
    }

    // Init vocabulary list
    bool first_where = true;
    QString s = "SELECT count(*) FROM vocabulary";
    QSqlQuery q(database);

    for(int i = 0; i < filter_type.size(); ++i)
    {
        if(first_where)
        {
            s.append(" WHERE ");
        }
        else
        {
            s.append(" AND ");
        }
        first_where = false;

        if(!filter_type[i].canConvert<int>())
        {
            WARNING(QString("Can not convert %1 to filter").arg(filter_type[i].typeName()));
            return 0;
        }
        int int_type = filter_type[i].toInt();
        if(int_type <= 0 || int_type >= filters_after_enum)
        {
            WARNING("Filter type" << int_type << "out of range");
            return 0;
        }

        switch(static_cast<filters>(int_type))
        {
            case LANGUAGE:
                s.append("language=?");
                break;
            case MODIFICATION_SINCE:
                s.append("modification >= ?");
                break;
            case MODIFICATION_UNTIL:
                s.append("modification <= ?");
                break;
            case CREATION_SINCE:
                s.append("creation >= ?");
                break;
            case CREATION_UNTIL:
                s.append("creation <= ?");
                break;
            case filters_after_enum:
                WARNING("filters_after_enum received");
                return 0;
                break;
            default:
                Q_UNREACHABLE();
                WARNING("Impossible filter type");
                return 0;
                break;
        }
    }

    DEBUG(s);

    q.prepare(s);

    for(int i = 0; i < filter_type.size(); ++i)
    {
        if(!filter_type[i].canConvert<int>())
        {
            WARNING(QString("Can not convert %1 to filter").arg(filter_type[i].typeName()));
            return 0;
        }
        int int_type = filter_type[i].toInt();
        if(int_type <= 0 || int_type >= filters_after_enum)
        {
            WARNING("Filter type" << int_type << "out of range");
            return 0;
        }

        switch(static_cast<filters>(int_type))
        {
            case LANGUAGE:
                q.addBindValue(filter_argv[i].toInt());
                break;
            case MODIFICATION_SINCE:
            case MODIFICATION_UNTIL:
            case CREATION_SINCE:
            case CREATION_UNTIL:
                q.addBindValue(filter_argv[i].toDate().toJulianDay());
                break;
            case filters_after_enum:
                WARNING("filters_after_enum received");
                return 0;
                break;
            default:
                Q_UNREACHABLE();
                WARNING("Impossible filter type");
                return 0;
                break;
        }
    }

    if(!q.exec())
    {
        QString error = s;
        error.append(": ").append(q.lastError().text());
        WARNING(error);
        return 0;
    }
    else
    {
        if(!q.isSelect())
        {
            QString error = s;
            error.append(": No select");
            WARNING(error);
            return 0;
        }
        else
        {
            if(!q.next())
            {
                QString error = s;
                error.append(" - no value: ").append(q.lastError().text());
                WARNING(error);
                return 0;

            }
            return q.value(0).toInt();
        }
    }

    return 0;
}

void Trainer::next()
{
    std::uniform_int_distribution<int> distribution;
    if(_settings.adaptiveTrainingEnabled())
    {
        // Use adaptive mode
        distribution = std::uniform_int_distribution<int>(1, _sum);
        int selected_priority = distribution(_rnd);
        int sum = 0;

        for(int i = 0; i < _vocabulary.size(); ++i)
        {
            sum += _vocabulary[i].priority;
            if(sum >= selected_priority)
            {
                _index = i;
                break;
            }
        }
    }
    else
    {
        // Select random (no adaptive mode)
        distribution = std::uniform_int_distribution<int>(0, _vocabulary.size() - 1);
        _index = distribution(_rnd);
    }

    distribution = std::uniform_int_distribution<int>(0, 1);
    if(distribution(_rnd) == 0)
    {
        _modus = GUESS_TRANSLATION;
    }
    else
    {
        _modus = GUESS_WORD;
    }

    emit wordChanged(_vocabulary[_index].word);
    emit translationChanged(_vocabulary[_index].translation);
    emit modusChanged(_modus);
    emit languageChanged(_vocabulary[_index].language);
}

void Trainer::correct()
{
    if(_settings.adaptiveTrainingEnabled())
    {
        _sum -= _vocabulary[_index].priority;
        _vocabulary[_index].priority = qMax(1, _vocabulary[_index].priority - _settings.adaptiveTrainingCorrectPoints());
        _sum += _vocabulary[_index].priority;

        QString s = "UPDATE vocabulary SET priority=:p WHERE rowid=:id";
        QSqlQuery q(database);
        q.prepare(s);
        q.bindValue(":p", _vocabulary[_index].priority);
        q.bindValue(":id", _vocabulary[_index].id);

        if(!q.exec())
        {
            QString error = s;
            error.append(": ").append(q.lastError().text());
            WARNING(error);
        }
    }
}

void Trainer::wrong()
{
    if(_settings.adaptiveTrainingEnabled())
    {
        _sum -= _vocabulary[_index].priority;
        _vocabulary[_index].priority = qMin(100, _vocabulary[_index].priority + _settings.adaptiveTrainingWrongPoints());
        _sum += _vocabulary[_index].priority;

        QString s = "UPDATE vocabulary SET priority=:p WHERE rowid=:id";
        QSqlQuery q(database);
        q.prepare(s);
        q.bindValue(":p", _vocabulary[_index].priority);
        q.bindValue(":id", _vocabulary[_index].id);

        if(!q.exec())
        {
            QString error = s;
            error.append(": ").append(q.lastError().text());
            WARNING(error);
        }
    }
}
<|endoftext|>


<commit_before>#ifdef HAVE_CMAKE_CONFIG
  #include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
  #include <config.h>
#endif // HAVE_CMAKE_CONFIG

#include <iostream>

#include <boost/filesystem.hpp>

#include <dune/common/exceptions.hh>
#include <dune/common/shared_ptr.hh>
#include <dune/common/mpihelper.hh>
#include <dune/common/timer.hh>

#include <dune/stuff/common/parameter/tree.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/common/filesystem.hh>
#include <dune/stuff/common/string.hh>
#include <dune/stuff/grid/provider.hh>

const std::string id = "grid.providers";

/**
  \brief      Creates a parameter file if it does not exist.

              Nothing is done if the file already exists. If not, a parameter file will be created with all neccessary
              keys and values.
  \param[in]  filename
              (Relative) path to the file.
  **/
void ensureParamFile(std::string filename)
{
  Dune::Stuff::Common::testCreateDirectory(filename);
  if (!boost::filesystem::exists(filename)) {
    std::ofstream file;
    file.open(filename);
    file << "[" << id << "]" << std::endl;
    file << "grid = stuff.grid.provider.cube" << std::endl;
    file << "filename = " << id << ".grid"<< std::endl;
    file << "[stuff.grid.provider.cube]" << std::endl;
    file << "lowerLeft = [0.0; 0.0; 0.0]" << std::endl;
    file << "upperRight = [1.0; 1.0; 1.0]" << std::endl;
    file << "numElements = [4; 4; 4]" << std::endl;
    file << "[stuff.grid.provider.gmsh]" << std::endl;
    file << "filename = curved2d.msh" << std::endl;
    file.close();
  } // only write param file if there is none
} // void ensureParamFile()

template< class GridViewType >
unsigned int measureTiming(const GridViewType& gridView)
{
  unsigned int elements = 0;
  for (typename GridViewType::template Codim< 0 >::Iterator it = gridView.template begin< 0 >();
       it != gridView.template end< 0 >();
       ++it)
    ++elements;
  return elements;
} // unsigned int measureTiming(const GridViewType& gridView)

/**
 * \todo  Move gmsh into seperate examples, since it does not compile with YaspGrid and SGrid!
 */
int main(int argc, char** argv)
{
  try {
    // mpi
    Dune::MPIHelper::instance(argc, argv);

    // parameter
    const std::string filename = id + ".param";
    ensureParamFile(filename);
    Dune::Stuff::Common::ExtendedParameterTree paramTree(argc, argv, filename);
    if (!paramTree.hasSub(id))
      DUNE_THROW(Dune::RangeError,
                 "\nMissing sub '" << id << "' in the following Dune::ParameterTree:\n" << paramTree.reportString("  "));

    // logger
    Dune::Stuff::Common::Logger().create(Dune::Stuff::Common::LOG_INFO |
                                         Dune::Stuff::Common::LOG_CONSOLE |
                                         Dune::Stuff::Common::LOG_DEBUG);
    Dune::Stuff::Common::LogStream& info = Dune::Stuff::Common::Logger().info();

    // timer
    Dune::Timer timer;

    // grid
    info << "setting up grid... ";
    typedef Dune::Stuff::Grid::Provider::Interface<> GridProviderType;
    const GridProviderType* gridProvider =
        Dune::Stuff::Grid::Provider::create<>(paramTree.get(id + ".grid", "stuff.grid.provider.cube"),
                                              paramTree);
    typedef GridProviderType::GridType GridType;
    const Dune::shared_ptr< const GridType > grid = gridProvider->grid();
    info << "  done (has " << grid->size(0) << " elements, took " << timer.elapsed() << " sec)" << std::endl;

    info << "visualizing grid... " << std::flush;
    timer.reset();
    gridProvider->visualize(paramTree.sub(id).get("filename", id + ".grid"));
    info << " done (took " << timer.elapsed() << " sek)" << std::endl;

    info << "walking leaf grid view... " << std::flush;
    timer.reset();
    const unsigned int leafElements = measureTiming(grid->leafView());
    info << " done (has " << leafElements << " elements, took " << timer.elapsed() << " sek)" << std::endl;

    // if we came that far we can as well be happy about it
    return 0;
  } catch(Dune::Exception& e) {
    std::cerr << "Dune reported error: " << e.what() << std::endl;
  } catch(std::exception& e) {
    std::cerr << e.what() << std::endl;
  } catch(...) {
    std::cerr << "Unknown exception thrown!" << std::endl;
  } // try
} // main
<commit_msg>[examples.grid.provider] added gmsh option<commit_after>#ifdef HAVE_CMAKE_CONFIG
  #include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
  #include <config.h>
#endif // HAVE_CMAKE_CONFIG

#include <iostream>

#include <boost/filesystem.hpp>

#include <dune/common/exceptions.hh>
#include <dune/common/shared_ptr.hh>
#include <dune/common/mpihelper.hh>
#include <dune/common/timer.hh>

#include <dune/stuff/common/parameter/tree.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/common/filesystem.hh>
#include <dune/stuff/common/string.hh>
#include <dune/stuff/grid/provider.hh>

const std::string id = "grid.providers";

/**
  \brief      Creates a parameter file if it does not exist.

              Nothing is done if the file already exists. If not, a parameter file will be created with all neccessary
              keys and values.
  \param[in]  filename
              (Relative) path to the file.
  **/
void ensureParamFile(std::string filename)
{
  Dune::Stuff::Common::testCreateDirectory(filename);
  if (!boost::filesystem::exists(filename)) {
    std::ofstream file;
    file.open(filename);
    file << "[" << id << "]" << std::endl;
    file << "grid = stuff.grid.provider.cube" << std::endl;
    file << "       stuff.grid.provider.gmsh" << std::endl;
    file << "filename = " << id << ".grid"<< std::endl;
    file << "[stuff.grid.provider.cube]" << std::endl;
    file << "lowerLeft = [0.0; 0.0; 0.0]" << std::endl;
    file << "upperRight = [1.0; 1.0; 1.0]" << std::endl;
    file << "numElements = [4; 4; 4]" << std::endl;
    file << "[stuff.grid.provider.gmsh]" << std::endl;
    file << "filename = curved2d.msh" << std::endl;
    file.close();
  } // only write param file if there is none
} // void ensureParamFile()

template< class GridViewType >
unsigned int measureTiming(const GridViewType& gridView)
{
  unsigned int elements = 0;
  for (typename GridViewType::template Codim< 0 >::Iterator it = gridView.template begin< 0 >();
       it != gridView.template end< 0 >();
       ++it)
    ++elements;
  return elements;
} // unsigned int measureTiming(const GridViewType& gridView)

int main(int argc, char** argv)
{
  try {
    // mpi
    Dune::MPIHelper::instance(argc, argv);

    // parameter
    const std::string filename = id + ".param";
    ensureParamFile(filename);
    Dune::Stuff::Common::ExtendedParameterTree paramTree(argc, argv, filename);
    if (!paramTree.hasSub(id))
      DUNE_THROW(Dune::RangeError,
                 "\nMissing sub '" << id << "' in the following Dune::ParameterTree:\n" << paramTree.reportString("  "));

    // logger
    Dune::Stuff::Common::Logger().create(Dune::Stuff::Common::LOG_INFO |
                                         Dune::Stuff::Common::LOG_CONSOLE |
                                         Dune::Stuff::Common::LOG_DEBUG);
    Dune::Stuff::Common::LogStream& info = Dune::Stuff::Common::Logger().info();

    // timer
    Dune::Timer timer;

    // grid
    info << "setting up grid... ";
    typedef Dune::Stuff::Grid::Provider::Interface<> GridProviderType;
    const GridProviderType* gridProvider =
        Dune::Stuff::Grid::Provider::create<>(paramTree.get(id + ".grid", "stuff.grid.provider.cube"),
                                              paramTree);
    typedef GridProviderType::GridType GridType;
    const Dune::shared_ptr< const GridType > grid = gridProvider->grid();
    info << "  done (has " << grid->size(0) << " elements, took " << timer.elapsed() << " sec)" << std::endl;

    info << "visualizing grid... " << std::flush;
    timer.reset();
    gridProvider->visualize(paramTree.sub(id).get("filename", id + ".grid"));
    info << " done (took " << timer.elapsed() << " sek)" << std::endl;

    info << "walking leaf grid view... " << std::flush;
    timer.reset();
    const unsigned int leafElements = measureTiming(grid->leafView());
    info << " done (has " << leafElements << " elements, took " << timer.elapsed() << " sek)" << std::endl;

    // if we came that far we can as well be happy about it
    return 0;
  } catch(Dune::Exception& e) {
    std::cerr << "Dune reported error: " << e.what() << std::endl;
  } catch(std::exception& e) {
    std::cerr << e.what() << std::endl;
  } catch(...) {
    std::cerr << "Unknown exception thrown!" << std::endl;
  } // try
} // main
<|endoftext|>


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

#include "modules/planning/integration_tests/planning_test_base.h"

#include <cstdlib>

#include "cybertron/common/log.h"

#include "modules/canbus/proto/chassis.pb.h"
#include "modules/localization/proto/localization.pb.h"
#include "modules/perception/proto/traffic_light_detection.pb.h"
#include "modules/prediction/proto/prediction_obstacle.pb.h"
#include "modules/routing/proto/routing.pb.h"

#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/util/file.h"
#include "modules/planning/common/planning_gflags.h"

namespace apollo {
namespace planning {

using apollo::canbus::Chassis;
using apollo::common::time::Clock;
using apollo::localization::LocalizationEstimate;
using apollo::perception::TrafficLightDetection;
using apollo::prediction::PredictionObstacles;
using apollo::routing::RoutingResponse;

DEFINE_string(test_data_dir, "", "the test data folder");
DEFINE_bool(test_update_golden_log, false,
            "true to update decision golden log file.");
DEFINE_string(test_routing_response_file, "", "The routing file used in test");
DEFINE_string(test_localization_file, "", "The localization test file");
DEFINE_string(test_chassis_file, "", "The chassis test file");
DEFINE_string(test_prediction_file, "", "The prediction module test file");
DEFINE_string(test_traffic_light_file, "", "The traffic light test file");
DEFINE_string(test_relative_map_file, "", "The relative map test file");
DEFINE_string(test_previous_planning_file, "",
              "The previous planning test file");

void PlanningTestBase::SetUpTestCase() {
  FLAGS_use_multi_thread_to_add_obstacles = false;
  FLAGS_enable_multi_thread_in_dp_poly_path = false;
  FLAGS_enable_multi_thread_in_dp_st_graph = false;
  FLAGS_planning_config_file =
      "/apollo/modules/planning/conf/planning_config.pb.txt";
  FLAGS_traffic_rule_config_filename =
      "/apollo/modules/planning/conf/traffic_rule_config.pb.txt";
  FLAGS_smoother_config_filename =
      "modules/planning/conf/qp_spline_smoother_config.pb.txt";
  FLAGS_map_dir = "modules/planning/testdata";
  FLAGS_test_localization_file = "";
  FLAGS_test_chassis_file = "";
  FLAGS_test_routing_response_file = "";
  FLAGS_test_prediction_file = "";
  FLAGS_align_prediction_time = false;
  FLAGS_estimate_current_vehicle_state = false;
  FLAGS_enable_reference_line_provider_thread = false;
  // FLAGS_enable_trajectory_check is temporarily disabled, otherwise EMPlanner
  // and LatticePlanner can't pass the unit test.
  FLAGS_enable_trajectory_check = false;
  FLAGS_planning_test_mode = true;
  FLAGS_enable_lag_prediction = false;
}

bool PlanningTestBase::FeedTestData() {
  // chassis
  Chassis chassis;
  if (!apollo::common::util::GetProtoFromFile(
          FLAGS_test_data_dir + "/" + FLAGS_test_chassis_file, &chassis)) {
    AERROR << "failed to load file: " << FLAGS_test_chassis_file;
    return false;
  }
  // localization
  LocalizationEstimate localization;
  if (!apollo::common::util::GetProtoFromFile(
          FLAGS_test_data_dir + "/" + FLAGS_test_localization_file,
          &localization)) {
    AERROR << "failed to load file: " << FLAGS_test_localization_file;
    return false;
  }

  Clock::SetNowInSeconds(localization.header().timestamp_sec());

  // prediction
  PredictionObstacles prediction;
  if (!apollo::common::util::GetProtoFromFile(
          FLAGS_test_data_dir + "/" + FLAGS_test_prediction_file,
          &prediction)) {
    AERROR << "failed to load file: " << FLAGS_test_prediction_file;
    return false;
  }
  // routing_response
  RoutingResponse routing_response;
  if (!apollo::common::util::GetProtoFromFile(
          FLAGS_test_data_dir + "/" + FLAGS_test_routing_response_file,
          &routing_response)) {
    AERROR << "failed to load file: " << FLAGS_test_routing_response_file;
    return false;
  }
  // traffic_light_detection
  TrafficLightDetection traffic_light_detection;
  if (!apollo::common::util::GetProtoFromFile(
          FLAGS_test_data_dir + "/" + FLAGS_test_traffic_light_file,
          &traffic_light_detection)) {
    AERROR << "failed to load file: " << FLAGS_test_traffic_light_file;
    return false;
  }

  local_view_.prediction_obstacles =
      std::make_shared<PredictionObstacles>(prediction);
  local_view_.chassis = std::make_shared<Chassis>(chassis);
  local_view_.localization_estimate =
      std::make_shared<LocalizationEstimate>(localization);
  local_view_.routing =
      std::make_shared<routing::RoutingResponse>(routing_response);
  local_view_.traffic_light =
      std::make_shared<TrafficLightDetection>(traffic_light_detection);

  AINFO << "Successfully feed proto files.";
  return true;
}

void PlanningTestBase::SetUp() {
  if (FLAGS_use_navigation_mode) {
    // TODO(all)
    // planning_ = std::unique_ptr<PlanningBase>(new NaviPlanning());
  } else {
    planning_ = std::unique_ptr<PlanningBase>(new StdPlanning());
  }

  CHECK(FeedTestData()) << "Failed to feed test data";

  CHECK(apollo::common::util::GetProtoFromFile(FLAGS_planning_config_file,
                                               &config_))
      << "failed to load planning config file " << FLAGS_planning_config_file;

  CHECK(planning_->Init(config_).ok()) << "Failed to init planning module";

  // Do not use fallback trajectory during testing
  FLAGS_use_planning_fallback = false;

  if (!FLAGS_test_previous_planning_file.empty()) {
    const auto prev_planning_file =
        FLAGS_test_data_dir + "/" + FLAGS_test_previous_planning_file;
    ADCTrajectory prev_planning;
    CHECK(common::util::GetProtoFromFile(prev_planning_file, &prev_planning));
    planning_->last_publishable_trajectory_.reset(
        new PublishableTrajectory(prev_planning));
  }
  for (auto& config : *(planning_->traffic_rule_configs_.mutable_config())) {
    auto iter = rule_enabled_.find(config.rule_id());
    if (iter != rule_enabled_.end()) {
      config.set_enabled(iter->second);
    }
  }
}

void PlanningTestBase::UpdateData() {
  CHECK(FeedTestData()) << "Failed to feed test data";

  if (!FLAGS_test_previous_planning_file.empty()) {
    const auto prev_planning_file =
        FLAGS_test_data_dir + "/" + FLAGS_test_previous_planning_file;
    ADCTrajectory prev_planning;
    CHECK(common::util::GetProtoFromFile(prev_planning_file, &prev_planning));
    planning_->last_publishable_trajectory_.reset(
        new PublishableTrajectory(prev_planning));
  }
  for (auto& config : *planning_->traffic_rule_configs_.mutable_config()) {
    auto iter = rule_enabled_.find(config.rule_id());
    if (iter != rule_enabled_.end()) {
      config.set_enabled(iter->second);
    }
  }
}

void PlanningTestBase::TrimPlanning(ADCTrajectory* origin,
                                    bool no_trajectory_point) {
  origin->clear_latency_stats();
  origin->clear_debug();
  origin->mutable_header()->clear_radar_timestamp();
  origin->mutable_header()->clear_lidar_timestamp();
  origin->mutable_header()->clear_timestamp_sec();
  origin->mutable_header()->clear_camera_timestamp();
  origin->mutable_header()->clear_sequence_num();

  if (no_trajectory_point) {
    origin->clear_total_path_length();
    origin->clear_total_path_time();
    origin->clear_trajectory_point();
  }
}

bool PlanningTestBase::RunPlanning(const std::string& test_case_name,
                                   int case_num, bool no_trajectory_point) {
  const std::string golden_result_file = apollo::common::util::StrCat(
      "result_", test_case_name, "_", case_num, ".pb.txt");

  std::string full_golden_path = FLAGS_test_data_dir + "/" + golden_result_file;

  ADCTrajectory adc_trajectory_pb;
  planning_->RunOnce(local_view_, &adc_trajectory_pb);

  if (!IsValidTrajectory(adc_trajectory_pb)) {
    AERROR << "Fail to pass trajectory check.";
    return false;
  }

  adc_trajectory_ = adc_trajectory_pb;
  TrimPlanning(&adc_trajectory_, no_trajectory_point);
  if (FLAGS_test_update_golden_log) {
    AINFO << "The golden file is regenerated:" << full_golden_path;
    common::util::SetProtoToASCIIFile(adc_trajectory_, full_golden_path);
  } else {
    ADCTrajectory golden_result;
    bool load_success =
        common::util::GetProtoFromASCIIFile(full_golden_path, &golden_result);
    TrimPlanning(&golden_result, no_trajectory_point);
    if (!load_success ||
        !common::util::IsProtoEqual(golden_result, adc_trajectory_)) {
      char tmp_fname[100] = "/tmp/XXXXXX";
      int fd = mkstemp(tmp_fname);
      if (!common::util::SetProtoToASCIIFile(adc_trajectory_, fd)) {
        AERROR << "Failed to write to file " << tmp_fname;
      }
      AERROR << "found\ndiff " << tmp_fname << " " << full_golden_path;
      AERROR << "visualize diff\n/usr/bin/python "
                "modules/tools/plot_trace/plot_planning_result.py "
             << tmp_fname << " " << full_golden_path;
      return false;
    }
  }
  return true;
}

bool PlanningTestBase::IsValidTrajectory(const ADCTrajectory& trajectory) {
  for (int i = 0; i < trajectory.trajectory_point_size(); ++i) {
    const auto& point = trajectory.trajectory_point(i);

    const double kMaxAccelThreshold =
        FLAGS_longitudinal_acceleration_upper_bound;
    const double kMinAccelThreshold =
        FLAGS_longitudinal_acceleration_lower_bound;
    if (point.a() > kMaxAccelThreshold || point.a() < kMinAccelThreshold) {
      AERROR << "Invalid trajectory point because accel out of range: "
             << point.DebugString();
      return false;
    }

    if (!point.has_path_point()) {
      AERROR << "Invalid trajectory point because NO path_point in "
                "trajectory_point: "
             << point.DebugString();
      return false;
    }

    if (i > 0) {
      const double kPathSEpsilon = 1e-3;
      const auto& last_point = trajectory.trajectory_point(i - 1);
      if (point.path_point().s() + kPathSEpsilon <
          last_point.path_point().s()) {
        AERROR << "Invalid trajectory point because s value error. last point: "
               << last_point.DebugString()
               << ", curr point: " << point.DebugString();
        return false;
      }
    }
  }
  return true;
}

TrafficRuleConfig* PlanningTestBase::GetTrafficRuleConfig(
    const TrafficRuleConfig::RuleId& rule_id) {
  for (auto& config : *planning_->traffic_rule_configs_.mutable_config()) {
    if (config.rule_id() == rule_id) {
      return &config;
    }
  }
  return nullptr;
}

}  // namespace planning
}  // namespace apollo
<commit_msg>planning: fix a path bug (#1099)<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/planning/integration_tests/planning_test_base.h"

#include <cstdlib>

#include "cybertron/common/log.h"

#include "modules/canbus/proto/chassis.pb.h"
#include "modules/localization/proto/localization.pb.h"
#include "modules/perception/proto/traffic_light_detection.pb.h"
#include "modules/prediction/proto/prediction_obstacle.pb.h"
#include "modules/routing/proto/routing.pb.h"

#include "modules/common/adapters/adapter_gflags.h"
#include "modules/common/util/file.h"
#include "modules/planning/common/planning_gflags.h"

namespace apollo {
namespace planning {

using apollo::canbus::Chassis;
using apollo::common::time::Clock;
using apollo::localization::LocalizationEstimate;
using apollo::perception::TrafficLightDetection;
using apollo::prediction::PredictionObstacles;
using apollo::routing::RoutingResponse;

DEFINE_string(test_data_dir, "", "the test data folder");
DEFINE_bool(test_update_golden_log, false,
            "true to update decision golden log file.");
DEFINE_string(test_routing_response_file, "", "The routing file used in test");
DEFINE_string(test_localization_file, "", "The localization test file");
DEFINE_string(test_chassis_file, "", "The chassis test file");
DEFINE_string(test_prediction_file, "", "The prediction module test file");
DEFINE_string(test_traffic_light_file, "", "The traffic light test file");
DEFINE_string(test_relative_map_file, "", "The relative map test file");
DEFINE_string(test_previous_planning_file, "",
              "The previous planning test file");

void PlanningTestBase::SetUpTestCase() {
  FLAGS_use_multi_thread_to_add_obstacles = false;
  FLAGS_enable_multi_thread_in_dp_poly_path = false;
  FLAGS_enable_multi_thread_in_dp_st_graph = false;
  FLAGS_planning_config_file =
      "/apollo/modules/planning/conf/planning_config.pb.txt";
  FLAGS_traffic_rule_config_filename =
      "/apollo/modules/planning/conf/traffic_rule_config.pb.txt";
  FLAGS_smoother_config_filename =
      "/apollo/modules/planning/conf/qp_spline_smoother_config.pb.txt";
  FLAGS_map_dir = "/apollo/modules/planning/testdata";
  FLAGS_test_localization_file = "";
  FLAGS_test_chassis_file = "";
  FLAGS_test_routing_response_file = "";
  FLAGS_test_prediction_file = "";
  FLAGS_align_prediction_time = false;
  FLAGS_estimate_current_vehicle_state = false;
  FLAGS_enable_reference_line_provider_thread = false;
  // FLAGS_enable_trajectory_check is temporarily disabled, otherwise EMPlanner
  // and LatticePlanner can't pass the unit test.
  FLAGS_enable_trajectory_check = false;
  FLAGS_planning_test_mode = true;
  FLAGS_enable_lag_prediction = false;
}

bool PlanningTestBase::FeedTestData() {
  // chassis
  Chassis chassis;
  if (!apollo::common::util::GetProtoFromFile(
          FLAGS_test_data_dir + "/" + FLAGS_test_chassis_file, &chassis)) {
    AERROR << "failed to load file: " << FLAGS_test_chassis_file;
    return false;
  }
  // localization
  LocalizationEstimate localization;
  if (!apollo::common::util::GetProtoFromFile(
          FLAGS_test_data_dir + "/" + FLAGS_test_localization_file,
          &localization)) {
    AERROR << "failed to load file: " << FLAGS_test_localization_file;
    return false;
  }

  Clock::SetNowInSeconds(localization.header().timestamp_sec());

  // prediction
  PredictionObstacles prediction;
  if (!apollo::common::util::GetProtoFromFile(
          FLAGS_test_data_dir + "/" + FLAGS_test_prediction_file,
          &prediction)) {
    AERROR << "failed to load file: " << FLAGS_test_prediction_file;
    return false;
  }
  // routing_response
  RoutingResponse routing_response;
  if (!apollo::common::util::GetProtoFromFile(
          FLAGS_test_data_dir + "/" + FLAGS_test_routing_response_file,
          &routing_response)) {
    AERROR << "failed to load file: " << FLAGS_test_routing_response_file;
    return false;
  }
  // traffic_light_detection
  TrafficLightDetection traffic_light_detection;
  if (!apollo::common::util::GetProtoFromFile(
          FLAGS_test_data_dir + "/" + FLAGS_test_traffic_light_file,
          &traffic_light_detection)) {
    AERROR << "failed to load file: " << FLAGS_test_traffic_light_file;
    return false;
  }

  local_view_.prediction_obstacles =
      std::make_shared<PredictionObstacles>(prediction);
  local_view_.chassis = std::make_shared<Chassis>(chassis);
  local_view_.localization_estimate =
      std::make_shared<LocalizationEstimate>(localization);
  local_view_.routing =
      std::make_shared<routing::RoutingResponse>(routing_response);
  local_view_.traffic_light =
      std::make_shared<TrafficLightDetection>(traffic_light_detection);

  AINFO << "Successfully feed proto files.";
  return true;
}

void PlanningTestBase::SetUp() {
  if (FLAGS_use_navigation_mode) {
    // TODO(all)
    // planning_ = std::unique_ptr<PlanningBase>(new NaviPlanning());
  } else {
    planning_ = std::unique_ptr<PlanningBase>(new StdPlanning());
  }

  CHECK(FeedTestData()) << "Failed to feed test data";

  CHECK(apollo::common::util::GetProtoFromFile(FLAGS_planning_config_file,
                                               &config_))
      << "failed to load planning config file " << FLAGS_planning_config_file;

  CHECK(planning_->Init(config_).ok()) << "Failed to init planning module";

  // Do not use fallback trajectory during testing
  FLAGS_use_planning_fallback = false;

  if (!FLAGS_test_previous_planning_file.empty()) {
    const auto prev_planning_file =
        FLAGS_test_data_dir + "/" + FLAGS_test_previous_planning_file;
    ADCTrajectory prev_planning;
    CHECK(common::util::GetProtoFromFile(prev_planning_file, &prev_planning));
    planning_->last_publishable_trajectory_.reset(
        new PublishableTrajectory(prev_planning));
  }
  for (auto& config : *(planning_->traffic_rule_configs_.mutable_config())) {
    auto iter = rule_enabled_.find(config.rule_id());
    if (iter != rule_enabled_.end()) {
      config.set_enabled(iter->second);
    }
  }
}

void PlanningTestBase::UpdateData() {
  CHECK(FeedTestData()) << "Failed to feed test data";

  if (!FLAGS_test_previous_planning_file.empty()) {
    const auto prev_planning_file =
        FLAGS_test_data_dir + "/" + FLAGS_test_previous_planning_file;
    ADCTrajectory prev_planning;
    CHECK(common::util::GetProtoFromFile(prev_planning_file, &prev_planning));
    planning_->last_publishable_trajectory_.reset(
        new PublishableTrajectory(prev_planning));
  }
  for (auto& config : *planning_->traffic_rule_configs_.mutable_config()) {
    auto iter = rule_enabled_.find(config.rule_id());
    if (iter != rule_enabled_.end()) {
      config.set_enabled(iter->second);
    }
  }
}

void PlanningTestBase::TrimPlanning(ADCTrajectory* origin,
                                    bool no_trajectory_point) {
  origin->clear_latency_stats();
  origin->clear_debug();
  origin->mutable_header()->clear_radar_timestamp();
  origin->mutable_header()->clear_lidar_timestamp();
  origin->mutable_header()->clear_timestamp_sec();
  origin->mutable_header()->clear_camera_timestamp();
  origin->mutable_header()->clear_sequence_num();

  if (no_trajectory_point) {
    origin->clear_total_path_length();
    origin->clear_total_path_time();
    origin->clear_trajectory_point();
  }
}

bool PlanningTestBase::RunPlanning(const std::string& test_case_name,
                                   int case_num, bool no_trajectory_point) {
  const std::string golden_result_file = apollo::common::util::StrCat(
      "result_", test_case_name, "_", case_num, ".pb.txt");

  std::string full_golden_path = FLAGS_test_data_dir + "/" + golden_result_file;

  ADCTrajectory adc_trajectory_pb;
  planning_->RunOnce(local_view_, &adc_trajectory_pb);

  if (!IsValidTrajectory(adc_trajectory_pb)) {
    AERROR << "Fail to pass trajectory check.";
    return false;
  }

  adc_trajectory_ = adc_trajectory_pb;
  TrimPlanning(&adc_trajectory_, no_trajectory_point);
  if (FLAGS_test_update_golden_log) {
    AINFO << "The golden file is regenerated:" << full_golden_path;
    common::util::SetProtoToASCIIFile(adc_trajectory_, full_golden_path);
  } else {
    ADCTrajectory golden_result;
    bool load_success =
        common::util::GetProtoFromASCIIFile(full_golden_path, &golden_result);
    TrimPlanning(&golden_result, no_trajectory_point);
    if (!load_success ||
        !common::util::IsProtoEqual(golden_result, adc_trajectory_)) {
      char tmp_fname[100] = "/tmp/XXXXXX";
      int fd = mkstemp(tmp_fname);
      if (!common::util::SetProtoToASCIIFile(adc_trajectory_, fd)) {
        AERROR << "Failed to write to file " << tmp_fname;
      }
      AERROR << "found\ndiff " << tmp_fname << " " << full_golden_path;
      AERROR << "visualize diff\n/usr/bin/python "
                "modules/tools/plot_trace/plot_planning_result.py "
             << tmp_fname << " " << full_golden_path;
      return false;
    }
  }
  return true;
}

bool PlanningTestBase::IsValidTrajectory(const ADCTrajectory& trajectory) {
  for (int i = 0; i < trajectory.trajectory_point_size(); ++i) {
    const auto& point = trajectory.trajectory_point(i);

    const double kMaxAccelThreshold =
        FLAGS_longitudinal_acceleration_upper_bound;
    const double kMinAccelThreshold =
        FLAGS_longitudinal_acceleration_lower_bound;
    if (point.a() > kMaxAccelThreshold || point.a() < kMinAccelThreshold) {
      AERROR << "Invalid trajectory point because accel out of range: "
             << point.DebugString();
      return false;
    }

    if (!point.has_path_point()) {
      AERROR << "Invalid trajectory point because NO path_point in "
                "trajectory_point: "
             << point.DebugString();
      return false;
    }

    if (i > 0) {
      const double kPathSEpsilon = 1e-3;
      const auto& last_point = trajectory.trajectory_point(i - 1);
      if (point.path_point().s() + kPathSEpsilon <
          last_point.path_point().s()) {
        AERROR << "Invalid trajectory point because s value error. last point: "
               << last_point.DebugString()
               << ", curr point: " << point.DebugString();
        return false;
      }
    }
  }
  return true;
}

TrafficRuleConfig* PlanningTestBase::GetTrafficRuleConfig(
    const TrafficRuleConfig::RuleId& rule_id) {
  for (auto& config : *planning_->traffic_rule_configs_.mutable_config()) {
    if (config.rule_id() == rule_id) {
      return &config;
    }
  }
  return nullptr;
}

}  // namespace planning
}  // namespace apollo
<|endoftext|>


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

#include "modules/planning/integration_tests/planning_test_base.h"

#include <cstdlib>

#include "google/protobuf/io/zero_copy_stream_impl.h"
#include "modules/common/log.h"
#include "modules/common/vehicle_state/vehicle_state.h"
#include "modules/planning/common/planning_gflags.h"

namespace apollo {
namespace planning {

using common::adapter::AdapterManager;

DEFINE_string(test_data_dir, "", "the test data folder");
DEFINE_bool(test_update_golden_log, false,
            "true to update decision golden log file.");
DEFINE_string(test_routing_response_file, "garage_routing.pb.txt",
              "The routing file used in test");
DEFINE_string(test_localization_file, "garage_localization.pb.txt",
              "The localization test file");
DEFINE_string(test_chassis_file, "garage_chassis.pb.txt",
              "The chassis test file");
DEFINE_string(test_prediction_file, "", "The prediction module test file");

void PlanningTestBase::SetUpTestCase() {
  FLAGS_planning_config_file = "modules/planning/conf/planning_config.pb.txt";
  FLAGS_adapter_config_filename = "modules/planning/testdata/conf/adapter.conf";
  FLAGS_map_dir = "modules/planning/testdata";
  FLAGS_test_localization_file = "garage_localization.pb.txt";
  FLAGS_test_chassis_file = "garage_chassis.pb.txt";
  FLAGS_test_prediction_file = "garage_prediction.pb.txt";
  FLAGS_align_prediction_time = false;
  FLAGS_enable_reference_line_provider_thread = false;
  FLAGS_enable_trajectory_check = true;
}

bool PlanningTestBase::SetUpAdapters() {
  if (!AdapterManager::Initialized()) {
    AdapterManager::Init(FLAGS_adapter_config_filename);
  }
  if (!AdapterManager::GetRoutingResponse()) {
    AERROR << "routing is not registered in adapter manager, check adapter "
              "config file."
           << FLAGS_adapter_config_filename;
    return false;
  }
  auto routing_response_file =
      FLAGS_test_data_dir + "/" + FLAGS_test_routing_response_file;
  if (!AdapterManager::FeedRoutingResponseFile(routing_response_file)) {
    AERROR << "failed to routing file: " << routing_response_file;
    return false;
  }
  AINFO << "Using Routing " << routing_response_file;
  auto localization_file =
      FLAGS_test_data_dir + "/" + FLAGS_test_localization_file;
  if (!AdapterManager::FeedLocalizationFile(localization_file)) {
    AERROR << "Failed to load localization file: " << localization_file;
    return false;
  }
  AINFO << "Using Localization file: " << localization_file;
  auto chassis_file = FLAGS_test_data_dir + "/" + FLAGS_test_chassis_file;
  if (!AdapterManager::FeedChassisFile(chassis_file)) {
    AERROR << "Failed to load chassis file: " << chassis_file;
    return false;
  }
  AINFO << "Using Chassis file: " << chassis_file;
  auto prediction_file = FLAGS_test_data_dir + "/" + FLAGS_test_prediction_file;
  if (!FLAGS_test_prediction_file.empty() &&
      !AdapterManager::FeedPredictionFile(prediction_file)) {
    AERROR << "Failed to load prediction file: " << prediction_file;
    return false;
  }
  AINFO << "Using Prediction file: " << prediction_file;
  return true;
}

void PlanningTestBase::SetUp() {
  planning_.Stop();
  CHECK(SetUpAdapters()) << "Failed to setup adapters";
  planning_.Init();
}

void PlanningTestBase::TrimPlanning(ADCTrajectory* origin) {
  origin->clear_latency_stats();
  origin->clear_debug();
  origin->mutable_header()->clear_radar_timestamp();
  origin->mutable_header()->clear_lidar_timestamp();
  origin->mutable_header()->clear_timestamp_sec();
  origin->mutable_header()->clear_camera_timestamp();
  origin->mutable_header()->clear_sequence_num();
}

bool PlanningTestBase::RunPlanning(const std::string& test_case_name,
                                   int case_num) {
  const std::string golden_result_file = apollo::common::util::StrCat(
      "result_", test_case_name, "_", case_num, ".pb.txt");

  std::string full_golden_path = FLAGS_test_data_dir + "/" + golden_result_file;
  planning_.RunOnce();

  const ADCTrajectory* trajectory_pointer =
      AdapterManager::GetPlanning()->GetLatestPublished();

  if (!trajectory_pointer) {
    AERROR << " did not get latest adc trajectory";
    return false;
  }

  if (!IsValidTrajectory(*trajectory_pointer)) {
    AERROR << "Fail to pass trajectory check.";
    return false;
  }

  adc_trajectory_ = *trajectory_pointer;
  TrimPlanning(&adc_trajectory_);
  if (FLAGS_test_update_golden_log) {
    AINFO << "The golden file is regenerated:" << full_golden_path;
    common::util::SetProtoToASCIIFile(adc_trajectory_, full_golden_path);
  } else {
    ADCTrajectory golden_result;
    bool load_success =
        common::util::GetProtoFromASCIIFile(full_golden_path, &golden_result);
    TrimPlanning(&golden_result);
    if (!load_success ||
        !common::util::IsProtoEqual(golden_result, adc_trajectory_)) {
      char tmp_fname[100] = "/tmp/XXXXXX";
      int fd = mkstemp(tmp_fname);
      if (!common::util::SetProtoToASCIIFile(adc_trajectory_, fd)) {
        AERROR << "Failed to write to file " << tmp_fname;
      }
      AERROR << "found\ndiff " << tmp_fname << " " << full_golden_path;
      AERROR << "visualize diff\npython "
                "modules/tools/plot_trace/plot_planning_result.py "
             << tmp_fname << " " << full_golden_path;
      return false;
    }
  }
  return true;
}

bool PlanningTestBase::IsValidTrajectory(const ADCTrajectory& trajectory) {
  if (trajectory.trajectory_point().empty()) {
    AERROR << "trajectory has NO point.";
    return false;
  }

  for (int i = 0; i < trajectory.trajectory_point_size(); ++i) {
    const auto& point = trajectory.trajectory_point(i);

    const double kMaxAccelThreshold =
        FLAGS_longitudinal_acceleration_upper_bound;
    const double kMinAccelThreshold =
        FLAGS_longitudinal_acceleration_lower_bound;
    if (point.a() > kMaxAccelThreshold || point.a() < kMinAccelThreshold) {
      AERROR << "Invalid trajectory point because accel out of range: "
             << point.DebugString();
      return false;
    }

    if (!point.has_path_point()) {
      AERROR << "Invalid trajectory point because NO path_point in "
                "trajectory_point: "
             << point.DebugString();
      return false;
    }

    const double kDkappaThreshold = 0.1;
    if (point.path_point().dkappa() > kDkappaThreshold ||
        point.path_point().dkappa() < -kDkappaThreshold) {
      AERROR << "Invalid trajectory point because dkappa out of range: "
             << point.DebugString();
      return false;
    }

    if (i > 0) {
      const double kPathSEpsilon = 1e-3;
      const auto& last_point = trajectory.trajectory_point(i - 1);
      if (point.path_point().s() + kPathSEpsilon <
          last_point.path_point().s()) {
        AERROR << "Invalid trajectory point because s value error. last point: "
               << last_point.DebugString()
               << ", curr point: " << point.DebugString();
        return false;
      }
    }
  }
  return true;
}

}  // namespace planning
}  // namespace apollo
<commit_msg>planning: quit integration test if failed to init<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/planning/integration_tests/planning_test_base.h"

#include <cstdlib>

#include "google/protobuf/io/zero_copy_stream_impl.h"
#include "modules/common/log.h"
#include "modules/common/vehicle_state/vehicle_state.h"
#include "modules/planning/common/planning_gflags.h"

namespace apollo {
namespace planning {

using common::adapter::AdapterManager;

DEFINE_string(test_data_dir, "", "the test data folder");
DEFINE_bool(test_update_golden_log, false,
            "true to update decision golden log file.");
DEFINE_string(test_routing_response_file, "garage_routing.pb.txt",
              "The routing file used in test");
DEFINE_string(test_localization_file, "garage_localization.pb.txt",
              "The localization test file");
DEFINE_string(test_chassis_file, "garage_chassis.pb.txt",
              "The chassis test file");
DEFINE_string(test_prediction_file, "", "The prediction module test file");

void PlanningTestBase::SetUpTestCase() {
  FLAGS_planning_config_file = "modules/planning/conf/planning_config.pb.txt";
  FLAGS_adapter_config_filename = "modules/planning/testdata/conf/adapter.conf";
  FLAGS_map_dir = "modules/planning/testdata";
  FLAGS_test_localization_file = "garage_localization.pb.txt";
  FLAGS_test_chassis_file = "garage_chassis.pb.txt";
  FLAGS_test_prediction_file = "garage_prediction.pb.txt";
  FLAGS_align_prediction_time = false;
  FLAGS_enable_reference_line_provider_thread = false;
  FLAGS_enable_trajectory_check = true;
}

bool PlanningTestBase::SetUpAdapters() {
  if (!AdapterManager::Initialized()) {
    AdapterManager::Init(FLAGS_adapter_config_filename);
  }
  if (!AdapterManager::GetRoutingResponse()) {
    AERROR << "routing is not registered in adapter manager, check adapter "
              "config file."
           << FLAGS_adapter_config_filename;
    return false;
  }
  auto routing_response_file =
      FLAGS_test_data_dir + "/" + FLAGS_test_routing_response_file;
  if (!AdapterManager::FeedRoutingResponseFile(routing_response_file)) {
    AERROR << "failed to routing file: " << routing_response_file;
    return false;
  }
  AINFO << "Using Routing " << routing_response_file;
  auto localization_file =
      FLAGS_test_data_dir + "/" + FLAGS_test_localization_file;
  if (!AdapterManager::FeedLocalizationFile(localization_file)) {
    AERROR << "Failed to load localization file: " << localization_file;
    return false;
  }
  AINFO << "Using Localization file: " << localization_file;
  auto chassis_file = FLAGS_test_data_dir + "/" + FLAGS_test_chassis_file;
  if (!AdapterManager::FeedChassisFile(chassis_file)) {
    AERROR << "Failed to load chassis file: " << chassis_file;
    return false;
  }
  AINFO << "Using Chassis file: " << chassis_file;
  auto prediction_file = FLAGS_test_data_dir + "/" + FLAGS_test_prediction_file;
  if (!FLAGS_test_prediction_file.empty() &&
      !AdapterManager::FeedPredictionFile(prediction_file)) {
    AERROR << "Failed to load prediction file: " << prediction_file;
    return false;
  }
  AINFO << "Using Prediction file: " << prediction_file;
  return true;
}

void PlanningTestBase::SetUp() {
  planning_.Stop();
  CHECK(SetUpAdapters()) << "Failed to setup adapters";
  CHECK(planning_.Init().ok()) << "Failed to init planning module";
}

void PlanningTestBase::TrimPlanning(ADCTrajectory* origin) {
  origin->clear_latency_stats();
  origin->clear_debug();
  origin->mutable_header()->clear_radar_timestamp();
  origin->mutable_header()->clear_lidar_timestamp();
  origin->mutable_header()->clear_timestamp_sec();
  origin->mutable_header()->clear_camera_timestamp();
  origin->mutable_header()->clear_sequence_num();
}

bool PlanningTestBase::RunPlanning(const std::string& test_case_name,
                                   int case_num) {
  const std::string golden_result_file = apollo::common::util::StrCat(
      "result_", test_case_name, "_", case_num, ".pb.txt");

  std::string full_golden_path = FLAGS_test_data_dir + "/" + golden_result_file;
  planning_.RunOnce();

  const ADCTrajectory* trajectory_pointer =
      AdapterManager::GetPlanning()->GetLatestPublished();

  if (!trajectory_pointer) {
    AERROR << " did not get latest adc trajectory";
    return false;
  }

  if (!IsValidTrajectory(*trajectory_pointer)) {
    AERROR << "Fail to pass trajectory check.";
    return false;
  }

  adc_trajectory_ = *trajectory_pointer;
  TrimPlanning(&adc_trajectory_);
  if (FLAGS_test_update_golden_log) {
    AINFO << "The golden file is regenerated:" << full_golden_path;
    common::util::SetProtoToASCIIFile(adc_trajectory_, full_golden_path);
  } else {
    ADCTrajectory golden_result;
    bool load_success =
        common::util::GetProtoFromASCIIFile(full_golden_path, &golden_result);
    TrimPlanning(&golden_result);
    if (!load_success ||
        !common::util::IsProtoEqual(golden_result, adc_trajectory_)) {
      char tmp_fname[100] = "/tmp/XXXXXX";
      int fd = mkstemp(tmp_fname);
      if (!common::util::SetProtoToASCIIFile(adc_trajectory_, fd)) {
        AERROR << "Failed to write to file " << tmp_fname;
      }
      AERROR << "found\ndiff " << tmp_fname << " " << full_golden_path;
      AERROR << "visualize diff\npython "
                "modules/tools/plot_trace/plot_planning_result.py "
             << tmp_fname << " " << full_golden_path;
      return false;
    }
  }
  return true;
}

bool PlanningTestBase::IsValidTrajectory(const ADCTrajectory& trajectory) {
  if (trajectory.trajectory_point().empty()) {
    AERROR << "trajectory has NO point.";
    return false;
  }

  for (int i = 0; i < trajectory.trajectory_point_size(); ++i) {
    const auto& point = trajectory.trajectory_point(i);

    const double kMaxAccelThreshold =
        FLAGS_longitudinal_acceleration_upper_bound;
    const double kMinAccelThreshold =
        FLAGS_longitudinal_acceleration_lower_bound;
    if (point.a() > kMaxAccelThreshold || point.a() < kMinAccelThreshold) {
      AERROR << "Invalid trajectory point because accel out of range: "
             << point.DebugString();
      return false;
    }

    if (!point.has_path_point()) {
      AERROR << "Invalid trajectory point because NO path_point in "
                "trajectory_point: "
             << point.DebugString();
      return false;
    }

    const double kDkappaThreshold = 0.1;
    if (point.path_point().dkappa() > kDkappaThreshold ||
        point.path_point().dkappa() < -kDkappaThreshold) {
      AERROR << "Invalid trajectory point because dkappa out of range: "
             << point.DebugString();
      return false;
    }

    if (i > 0) {
      const double kPathSEpsilon = 1e-3;
      const auto& last_point = trajectory.trajectory_point(i - 1);
      if (point.path_point().s() + kPathSEpsilon <
          last_point.path_point().s()) {
        AERROR << "Invalid trajectory point because s value error. last point: "
               << last_point.DebugString()
               << ", curr point: " << point.DebugString();
        return false;
      }
    }
  }
  return true;
}

}  // namespace planning
}  // namespace apollo
<|endoftext|>