<commit_before>/*=========================================================================
*
*  Copyright Insight Software Consortium
*
*  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.txt
*
*  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 "sitkProcessObject.h"
#include "sitkCommand.h"

#include "itkProcessObject.h"
#include "itkCommand.h"
#include "itkImageToImageFilter.h"

#include <iostream>
#include <algorithm>

#include "nsstd/functional.h"

namespace itk {
namespace simple {

namespace
{
static bool GlobalDefaultDebug = false;

static itk::AnyEvent eventAnyEvent;
static itk::AbortEvent eventAbortEvent;
static itk::DeleteEvent eventDeleteEvent;
static itk::EndEvent eventEndEvent;
static itk::IterationEvent eventIterationEvent;
static itk::ProgressEvent eventProgressEvent;
static itk::StartEvent eventStartEvent;
static itk::UserEvent eventUserEvent;
static itk::MultiResolutionIterationEvent eventMultiResolutionIterationEvent;

// Local class to adapt a sitk::Command to ITK's command.
// It utilizes a raw pointer, and relies on the sitk
// ProcessObject<->Command reference to automatically remove it.
class SimpleAdaptorCommand
  : public itk::Command
{
public:

  typedef SimpleAdaptorCommand Self;
  typedef SmartPointer< Self > Pointer;

  itkNewMacro(Self);

  itkTypeMacro(SimpleAdaptorCommand, Command);

  void SetSimpleCommand( itk::simple::Command *cmd )
    {
      m_That=cmd;
    }

  /**  Invoke the member function. */
  virtual void Execute(Object *, const EventObject & ) SITK_OVERRIDE
  {
    if (m_That)
      {
      m_That->Execute();
      }
  }

  /**  Invoke the member function with a const object */
  virtual void Execute(const Object *, const EventObject & ) SITK_OVERRIDE
  {
    if ( m_That )
      {
      m_That->Execute();
      }
  }

protected:
  itk::simple::Command *                    m_That;
  SimpleAdaptorCommand():m_That(0) {}
  virtual ~SimpleAdaptorCommand() {}

private:
  SimpleAdaptorCommand(const Self &); //purposely not implemented
  void operator=(const Self &);        //purposely not implemented
};

} // end anonymous namespace

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

//
// Default constructor that initializes parameters
//
ProcessObject::ProcessObject ()
  : m_Debug(ProcessObject::GetGlobalDefaultDebug()),
    m_NumberOfThreads(ProcessObject::GetGlobalDefaultNumberOfThreads()),
    m_ActiveProcess(SITK_NULLPTR),
    m_ProgressMeasurement(0.0)
{
}

//
// Destructor
//
ProcessObject::~ProcessObject ()
{
  // ensure to remove reference between sitk commands and process object
  Self::RemoveAllCommands();
}

std::string ProcessObject::ToString() const
{
  std::ostringstream out;

  out << "  Debug: ";
  this->ToStringHelper(out, this->m_Debug) << std::endl;

  out << "  NumberOfThreads: ";
  this->ToStringHelper(out, this->m_NumberOfThreads) << std::endl;

  out << "  Commands:" << (m_Commands.empty()?" (none)":"") << std::endl;
  for( std::list<EventCommand>::const_iterator i = m_Commands.begin();
       i != m_Commands.end();
       ++i)
    {
    assert( i->m_Command );
    out << "    Event: " << i->m_Event << " Command: " << i->m_Command->GetName() << std::endl;
    }

  out << "  ProgressMeasurement: ";
  this->ToStringHelper(out, this->m_ProgressMeasurement) << std::endl;

  out << "  ActiveProcess:" << (this->m_ActiveProcess?"":" (none)") <<std::endl;
  if( this->m_ActiveProcess )
    {
    this->m_ActiveProcess->Print(out, itk::Indent(4));
    }

  return out.str();
}

std::ostream & ProcessObject::ToStringHelper(std::ostream &os, const char &v)
{
  os << int(v);
  return os;
}

std::ostream & ProcessObject::ToStringHelper(std::ostream &os, const signed char &v)
{
  os << int(v);
  return os;
}

std::ostream & ProcessObject::ToStringHelper(std::ostream &os, const unsigned char &v)
{
  os << int(v);
  return os;
}

void ProcessObject::DebugOn()
{
  this->m_Debug = true;
}

void ProcessObject::DebugOff()
{
  this->m_Debug = false;
}

bool ProcessObject::GetDebug() const
{
  return this->m_Debug;
}

void ProcessObject::SetDebug(bool debugFlag)
{
  this->m_Debug = debugFlag;
}

void ProcessObject::GlobalDefaultDebugOn()
{
  GlobalDefaultDebug = true;
}

void ProcessObject::GlobalDefaultDebugOff()

{
  GlobalDefaultDebug = false;
}

bool ProcessObject::GetGlobalDefaultDebug()
{
  return GlobalDefaultDebug;
}

void ProcessObject::SetGlobalDefaultDebug(bool debugFlag)
{
  GlobalDefaultDebug = debugFlag;
}

void ProcessObject::GlobalWarningDisplayOn()
{
  itk::Object::GlobalWarningDisplayOn();
}

void ProcessObject::GlobalWarningDisplayOff()
{
  itk::Object::GlobalWarningDisplayOff();
}

bool ProcessObject::GetGlobalWarningDisplay()
{
  return itk::Object::GetGlobalWarningDisplay();
}

void ProcessObject::SetGlobalWarningDisplay(bool flag)
{
  itk::Object::SetGlobalWarningDisplay(flag);
}

double ProcessObject::GetGlobalDefaultCoordinateTolerance()
{
  return itk::ImageToImageFilterCommon::GetGlobalDefaultCoordinateTolerance();
}

void ProcessObject::SetGlobalDefaultCoordinateTolerance(double tolerance)
{
  return itk::ImageToImageFilterCommon::SetGlobalDefaultCoordinateTolerance(tolerance);
}

double ProcessObject::GetGlobalDefaultDirectionTolerance()
{
  return itk::ImageToImageFilterCommon::GetGlobalDefaultDirectionTolerance();
}

void ProcessObject::SetGlobalDefaultDirectionTolerance(double tolerance)
{
  return itk::ImageToImageFilterCommon::SetGlobalDefaultDirectionTolerance(tolerance);
}

void ProcessObject::SetGlobalDefaultNumberOfThreads(unsigned int n)
{
  MultiThreader::SetGlobalDefaultNumberOfThreads(n);
}

unsigned int ProcessObject::GetGlobalDefaultNumberOfThreads()
{
  return MultiThreader::GetGlobalDefaultNumberOfThreads();
}

void ProcessObject::SetNumberOfThreads(unsigned int n)
{
  m_NumberOfThreads = n;
}

unsigned int ProcessObject::GetNumberOfThreads() const
{
  return m_NumberOfThreads;
}

int ProcessObject::AddCommand(EventEnum event, Command &cmd)
{
  // add to our list of event, command pairs
  m_Commands.push_back(EventCommand(event,&cmd));

  // register ourselves with the command
  cmd.AddProcessObject(this);

  if (this->m_ActiveProcess)
    {
    this->AddObserverToActiveProcessObject( m_Commands.back() );
    }
  else
    {
    m_Commands.back().m_ITKTag = std::numeric_limits<unsigned long>::max();
    }

  return 0;
}

void ProcessObject::RemoveAllCommands()
{
  // set's the m_Commands to an empty list via a swap
  std::list<EventCommand> oldCommands;
  swap(oldCommands, m_Commands);

  // remove commands from active process object
  std::list<EventCommand>::iterator i = oldCommands.begin();
  while( i != oldCommands.end() && this->m_ActiveProcess )
    {
    this->RemoveObserverFromActiveProcessObject(*i);
    ++i;
    }

  // we must only call RemoveProcessObject once for each command
  // so make a unique list of the Commands.
  oldCommands.sort();
  oldCommands.unique();
  i = oldCommands.begin();
  while( i != oldCommands.end() )
    {
    // note: this may call onCommandDelete, but we have already copied
    // this->m_Command will be empty
    i++->m_Command->RemoveProcessObject(this);
    }
}

bool ProcessObject::HasCommand( EventEnum event ) const
{
  std::list<EventCommand>::const_iterator i = m_Commands.begin();
  while( i != m_Commands.end() )
    {
    if (i->m_Event == event)
      {
      return true;
      }
    ++i;
    }
  return false;
}

float ProcessObject::GetProgress( ) const
{
  if ( this->m_ActiveProcess )
    {
    return this->m_ActiveProcess->GetProgress();
    }
  return m_ProgressMeasurement;
}

void ProcessObject::Abort()
{
  if ( this->m_ActiveProcess )
    {
    this->m_ActiveProcess->AbortGenerateDataOn();
    }
}

void ProcessObject::PreUpdate(itk::ProcessObject *p)
{
  assert(p);

  // propagate number of threads
  p->SetNumberOfThreads(this->GetNumberOfThreads());

  try
    {
    this->m_ActiveProcess = p;

    // add command on active process deletion
    itk::SimpleMemberCommand<Self>::Pointer onDelete = itk::SimpleMemberCommand<Self>::New();
    onDelete->SetCallbackFunction(this, &Self::OnActiveProcessDelete);
    p->AddObserver(itk::DeleteEvent(), onDelete);

    // register commands
    for (std::list<EventCommand>::iterator i = m_Commands.begin();
         i != m_Commands.end();
         ++i)
      {
      this->AddObserverToActiveProcessObject(*i);
      }

    }
  catch (...)
    {
    this->m_ActiveProcess = SITK_NULLPTR;
    throw;
    }

  sitkDebugMacro( "Executing ITK filter:\n" << *p );

}

unsigned long ProcessObject::AddITKObserver( const itk::EventObject &e,
                                             itk::Command *c)
{
  assert(this->m_ActiveProcess);
  return this->m_ActiveProcess->AddObserver(e,c);
}

void ProcessObject::RemoveITKObserver( EventCommand &e )
{
  assert(this->m_ActiveProcess);
  this->m_ActiveProcess->RemoveObserver(e.m_ITKTag);
}

const itk::EventObject &ProcessObject::GetITKEventObject(EventEnum e)
{
  switch (e)
    {
    case sitkAnyEvent:
      return eventAnyEvent;
    case sitkAbortEvent:
      return eventAbortEvent;
    case sitkDeleteEvent:
      return eventDeleteEvent;
    case sitkEndEvent:
      return eventEndEvent;
    case sitkIterationEvent:
      return eventIterationEvent;
    case sitkProgressEvent:
      return eventProgressEvent;
    case sitkStartEvent:
      return eventStartEvent;
    case sitkUserEvent:
      return eventUserEvent;
    case sitkMultiResolutionIterationEvent:
      return eventMultiResolutionIterationEvent;
    default:
      sitkExceptionMacro("LogicError: Unexpected event case!");
    }
}

itk::ProcessObject *ProcessObject::GetActiveProcess( )
{
  if (this->m_ActiveProcess)
    {
    return this->m_ActiveProcess;
    }
  sitkExceptionMacro("No active process for \"" << this->GetName() << "\"!");
}

void ProcessObject::OnActiveProcessDelete( )
{
  if (this->m_ActiveProcess)
    {
    this->m_ProgressMeasurement = this->m_ActiveProcess->GetProgress();
    }
  else
    {
    this->m_ProgressMeasurement = 0.0f;
    }

  // clear registered command IDs
  for (std::list<EventCommand>::iterator i = m_Commands.begin();
         i != m_Commands.end();
         ++i)
      {
      i->m_ITKTag = std::numeric_limits<unsigned long>::max();
      }

  this->m_ActiveProcess = SITK_NULLPTR;
}

void ProcessObject::onCommandDelete(const itk::simple::Command *cmd) SITK_NOEXCEPT
{
  // remove command from m_Command book keeping list, and remove it
  // from the  ITK ProcessObject
  std::list<EventCommand>::iterator i =  this->m_Commands.begin();
  while ( i !=  this->m_Commands.end() )
    {
    if ( cmd == i->m_Command )
      {
      if ( this->m_ActiveProcess )
        {
        this->RemoveObserverFromActiveProcessObject( *i );
        }
      this->m_Commands.erase(i++);
      }
    else
      {
      ++i;
      }

    }
}

unsigned long ProcessObject::AddObserverToActiveProcessObject( EventCommand &eventCommand )
{
  assert( this->m_ActiveProcess );

  if (eventCommand.m_ITKTag != std::numeric_limits<unsigned long>::max())
    {
    sitkExceptionMacro("Commands already registered to another process object!");
    }

  const itk::EventObject &itkEvent = GetITKEventObject(eventCommand.m_Event);

  // adapt sitk command to itk command
  SimpleAdaptorCommand::Pointer itkCommand = SimpleAdaptorCommand::New();
  itkCommand->SetSimpleCommand(eventCommand.m_Command);
  itkCommand->SetObjectName(eventCommand.m_Command->GetName()+" "+itkEvent.GetEventName());

  return eventCommand.m_ITKTag = this->AddITKObserver( itkEvent, itkCommand );
}

void ProcessObject::RemoveObserverFromActiveProcessObject( EventCommand &e )
 {
   assert( this->m_ActiveProcess );

   if (e.m_ITKTag != std::numeric_limits<unsigned long>::max() )
     {
     this->RemoveITKObserver(e);
     e.m_ITKTag = std::numeric_limits<unsigned long>::max();
     }

 }

} // end namespace simple
} // end namespace itk
<commit_msg>Use MultiThreader typedef for future ITK compatibility.<commit_after>/*=========================================================================
*
*  Copyright Insight Software Consortium
*
*  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.txt
*
*  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 "sitkProcessObject.h"
#include "sitkCommand.h"

#include "itkProcessObject.h"
#include "itkCommand.h"
#include "itkImageToImageFilter.h"

#include <iostream>
#include <algorithm>

#include "nsstd/functional.h"

namespace itk {
namespace simple {

namespace
{
static bool GlobalDefaultDebug = false;

static itk::AnyEvent eventAnyEvent;
static itk::AbortEvent eventAbortEvent;
static itk::DeleteEvent eventDeleteEvent;
static itk::EndEvent eventEndEvent;
static itk::IterationEvent eventIterationEvent;
static itk::ProgressEvent eventProgressEvent;
static itk::StartEvent eventStartEvent;
static itk::UserEvent eventUserEvent;
static itk::MultiResolutionIterationEvent eventMultiResolutionIterationEvent;

// Local class to adapt a sitk::Command to ITK's command.
// It utilizes a raw pointer, and relies on the sitk
// ProcessObject<->Command reference to automatically remove it.
class SimpleAdaptorCommand
  : public itk::Command
{
public:

  typedef SimpleAdaptorCommand Self;
  typedef SmartPointer< Self > Pointer;

  itkNewMacro(Self);

  itkTypeMacro(SimpleAdaptorCommand, Command);

  void SetSimpleCommand( itk::simple::Command *cmd )
    {
      m_That=cmd;
    }

  /**  Invoke the member function. */
  virtual void Execute(Object *, const EventObject & ) SITK_OVERRIDE
  {
    if (m_That)
      {
      m_That->Execute();
      }
  }

  /**  Invoke the member function with a const object */
  virtual void Execute(const Object *, const EventObject & ) SITK_OVERRIDE
  {
    if ( m_That )
      {
      m_That->Execute();
      }
  }

protected:
  itk::simple::Command *                    m_That;
  SimpleAdaptorCommand():m_That(0) {}
  virtual ~SimpleAdaptorCommand() {}

private:
  SimpleAdaptorCommand(const Self &); //purposely not implemented
  void operator=(const Self &);        //purposely not implemented
};

} // end anonymous namespace

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

//
// Default constructor that initializes parameters
//
ProcessObject::ProcessObject ()
  : m_Debug(ProcessObject::GetGlobalDefaultDebug()),
    m_NumberOfThreads(ProcessObject::GetGlobalDefaultNumberOfThreads()),
    m_ActiveProcess(SITK_NULLPTR),
    m_ProgressMeasurement(0.0)
{
}

//
// Destructor
//
ProcessObject::~ProcessObject ()
{
  // ensure to remove reference between sitk commands and process object
  Self::RemoveAllCommands();
}

std::string ProcessObject::ToString() const
{
  std::ostringstream out;

  out << "  Debug: ";
  this->ToStringHelper(out, this->m_Debug) << std::endl;

  out << "  NumberOfThreads: ";
  this->ToStringHelper(out, this->m_NumberOfThreads) << std::endl;

  out << "  Commands:" << (m_Commands.empty()?" (none)":"") << std::endl;
  for( std::list<EventCommand>::const_iterator i = m_Commands.begin();
       i != m_Commands.end();
       ++i)
    {
    assert( i->m_Command );
    out << "    Event: " << i->m_Event << " Command: " << i->m_Command->GetName() << std::endl;
    }

  out << "  ProgressMeasurement: ";
  this->ToStringHelper(out, this->m_ProgressMeasurement) << std::endl;

  out << "  ActiveProcess:" << (this->m_ActiveProcess?"":" (none)") <<std::endl;
  if( this->m_ActiveProcess )
    {
    this->m_ActiveProcess->Print(out, itk::Indent(4));
    }

  return out.str();
}

std::ostream & ProcessObject::ToStringHelper(std::ostream &os, const char &v)
{
  os << int(v);
  return os;
}

std::ostream & ProcessObject::ToStringHelper(std::ostream &os, const signed char &v)
{
  os << int(v);
  return os;
}

std::ostream & ProcessObject::ToStringHelper(std::ostream &os, const unsigned char &v)
{
  os << int(v);
  return os;
}

void ProcessObject::DebugOn()
{
  this->m_Debug = true;
}

void ProcessObject::DebugOff()
{
  this->m_Debug = false;
}

bool ProcessObject::GetDebug() const
{
  return this->m_Debug;
}

void ProcessObject::SetDebug(bool debugFlag)
{
  this->m_Debug = debugFlag;
}

void ProcessObject::GlobalDefaultDebugOn()
{
  GlobalDefaultDebug = true;
}

void ProcessObject::GlobalDefaultDebugOff()

{
  GlobalDefaultDebug = false;
}

bool ProcessObject::GetGlobalDefaultDebug()
{
  return GlobalDefaultDebug;
}

void ProcessObject::SetGlobalDefaultDebug(bool debugFlag)
{
  GlobalDefaultDebug = debugFlag;
}

void ProcessObject::GlobalWarningDisplayOn()
{
  itk::Object::GlobalWarningDisplayOn();
}

void ProcessObject::GlobalWarningDisplayOff()
{
  itk::Object::GlobalWarningDisplayOff();
}

bool ProcessObject::GetGlobalWarningDisplay()
{
  return itk::Object::GetGlobalWarningDisplay();
}

void ProcessObject::SetGlobalWarningDisplay(bool flag)
{
  itk::Object::SetGlobalWarningDisplay(flag);
}

double ProcessObject::GetGlobalDefaultCoordinateTolerance()
{
  return itk::ImageToImageFilterCommon::GetGlobalDefaultCoordinateTolerance();
}

void ProcessObject::SetGlobalDefaultCoordinateTolerance(double tolerance)
{
  return itk::ImageToImageFilterCommon::SetGlobalDefaultCoordinateTolerance(tolerance);
}

double ProcessObject::GetGlobalDefaultDirectionTolerance()
{
  return itk::ImageToImageFilterCommon::GetGlobalDefaultDirectionTolerance();
}

void ProcessObject::SetGlobalDefaultDirectionTolerance(double tolerance)
{
  return itk::ImageToImageFilterCommon::SetGlobalDefaultDirectionTolerance(tolerance);
}

void ProcessObject::SetGlobalDefaultNumberOfThreads(unsigned int n)
{
  itk::ProcessObject::MultiThreaderType::SetGlobalDefaultNumberOfThreads(n);
}

unsigned int ProcessObject::GetGlobalDefaultNumberOfThreads()
{
  return itk::ProcessObject::MultiThreaderType::GetGlobalDefaultNumberOfThreads();
}

void ProcessObject::SetNumberOfThreads(unsigned int n)
{
  m_NumberOfThreads = n;
}

unsigned int ProcessObject::GetNumberOfThreads() const
{
  return m_NumberOfThreads;
}

int ProcessObject::AddCommand(EventEnum event, Command &cmd)
{
  // add to our list of event, command pairs
  m_Commands.push_back(EventCommand(event,&cmd));

  // register ourselves with the command
  cmd.AddProcessObject(this);

  if (this->m_ActiveProcess)
    {
    this->AddObserverToActiveProcessObject( m_Commands.back() );
    }
  else
    {
    m_Commands.back().m_ITKTag = std::numeric_limits<unsigned long>::max();
    }

  return 0;
}

void ProcessObject::RemoveAllCommands()
{
  // set's the m_Commands to an empty list via a swap
  std::list<EventCommand> oldCommands;
  swap(oldCommands, m_Commands);

  // remove commands from active process object
  std::list<EventCommand>::iterator i = oldCommands.begin();
  while( i != oldCommands.end() && this->m_ActiveProcess )
    {
    this->RemoveObserverFromActiveProcessObject(*i);
    ++i;
    }

  // we must only call RemoveProcessObject once for each command
  // so make a unique list of the Commands.
  oldCommands.sort();
  oldCommands.unique();
  i = oldCommands.begin();
  while( i != oldCommands.end() )
    {
    // note: this may call onCommandDelete, but we have already copied
    // this->m_Command will be empty
    i++->m_Command->RemoveProcessObject(this);
    }
}

bool ProcessObject::HasCommand( EventEnum event ) const
{
  std::list<EventCommand>::const_iterator i = m_Commands.begin();
  while( i != m_Commands.end() )
    {
    if (i->m_Event == event)
      {
      return true;
      }
    ++i;
    }
  return false;
}

float ProcessObject::GetProgress( ) const
{
  if ( this->m_ActiveProcess )
    {
    return this->m_ActiveProcess->GetProgress();
    }
  return m_ProgressMeasurement;
}

void ProcessObject::Abort()
{
  if ( this->m_ActiveProcess )
    {
    this->m_ActiveProcess->AbortGenerateDataOn();
    }
}

void ProcessObject::PreUpdate(itk::ProcessObject *p)
{
  assert(p);

  // propagate number of threads
  p->SetNumberOfThreads(this->GetNumberOfThreads());

  try
    {
    this->m_ActiveProcess = p;

    // add command on active process deletion
    itk::SimpleMemberCommand<Self>::Pointer onDelete = itk::SimpleMemberCommand<Self>::New();
    onDelete->SetCallbackFunction(this, &Self::OnActiveProcessDelete);
    p->AddObserver(itk::DeleteEvent(), onDelete);

    // register commands
    for (std::list<EventCommand>::iterator i = m_Commands.begin();
         i != m_Commands.end();
         ++i)
      {
      this->AddObserverToActiveProcessObject(*i);
      }

    }
  catch (...)
    {
    this->m_ActiveProcess = SITK_NULLPTR;
    throw;
    }

  sitkDebugMacro( "Executing ITK filter:\n" << *p );

}

unsigned long ProcessObject::AddITKObserver( const itk::EventObject &e,
                                             itk::Command *c)
{
  assert(this->m_ActiveProcess);
  return this->m_ActiveProcess->AddObserver(e,c);
}

void ProcessObject::RemoveITKObserver( EventCommand &e )
{
  assert(this->m_ActiveProcess);
  this->m_ActiveProcess->RemoveObserver(e.m_ITKTag);
}

const itk::EventObject &ProcessObject::GetITKEventObject(EventEnum e)
{
  switch (e)
    {
    case sitkAnyEvent:
      return eventAnyEvent;
    case sitkAbortEvent:
      return eventAbortEvent;
    case sitkDeleteEvent:
      return eventDeleteEvent;
    case sitkEndEvent:
      return eventEndEvent;
    case sitkIterationEvent:
      return eventIterationEvent;
    case sitkProgressEvent:
      return eventProgressEvent;
    case sitkStartEvent:
      return eventStartEvent;
    case sitkUserEvent:
      return eventUserEvent;
    case sitkMultiResolutionIterationEvent:
      return eventMultiResolutionIterationEvent;
    default:
      sitkExceptionMacro("LogicError: Unexpected event case!");
    }
}

itk::ProcessObject *ProcessObject::GetActiveProcess( )
{
  if (this->m_ActiveProcess)
    {
    return this->m_ActiveProcess;
    }
  sitkExceptionMacro("No active process for \"" << this->GetName() << "\"!");
}

void ProcessObject::OnActiveProcessDelete( )
{
  if (this->m_ActiveProcess)
    {
    this->m_ProgressMeasurement = this->m_ActiveProcess->GetProgress();
    }
  else
    {
    this->m_ProgressMeasurement = 0.0f;
    }

  // clear registered command IDs
  for (std::list<EventCommand>::iterator i = m_Commands.begin();
         i != m_Commands.end();
         ++i)
      {
      i->m_ITKTag = std::numeric_limits<unsigned long>::max();
      }

  this->m_ActiveProcess = SITK_NULLPTR;
}

void ProcessObject::onCommandDelete(const itk::simple::Command *cmd) SITK_NOEXCEPT
{
  // remove command from m_Command book keeping list, and remove it
  // from the  ITK ProcessObject
  std::list<EventCommand>::iterator i =  this->m_Commands.begin();
  while ( i !=  this->m_Commands.end() )
    {
    if ( cmd == i->m_Command )
      {
      if ( this->m_ActiveProcess )
        {
        this->RemoveObserverFromActiveProcessObject( *i );
        }
      this->m_Commands.erase(i++);
      }
    else
      {
      ++i;
      }

    }
}

unsigned long ProcessObject::AddObserverToActiveProcessObject( EventCommand &eventCommand )
{
  assert( this->m_ActiveProcess );

  if (eventCommand.m_ITKTag != std::numeric_limits<unsigned long>::max())
    {
    sitkExceptionMacro("Commands already registered to another process object!");
    }

  const itk::EventObject &itkEvent = GetITKEventObject(eventCommand.m_Event);

  // adapt sitk command to itk command
  SimpleAdaptorCommand::Pointer itkCommand = SimpleAdaptorCommand::New();
  itkCommand->SetSimpleCommand(eventCommand.m_Command);
  itkCommand->SetObjectName(eventCommand.m_Command->GetName()+" "+itkEvent.GetEventName());

  return eventCommand.m_ITKTag = this->AddITKObserver( itkEvent, itkCommand );
}

void ProcessObject::RemoveObserverFromActiveProcessObject( EventCommand &e )
 {
   assert( this->m_ActiveProcess );

   if (e.m_ITKTag != std::numeric_limits<unsigned long>::max() )
     {
     this->RemoveITKObserver(e);
     e.m_ITKTag = std::numeric_limits<unsigned long>::max();
     }

 }

} // end namespace simple
} // end namespace itk
<|endoftext|>


<commit_before>// RUN: clang-cc -fsyntax-only -verify %s
// XFAIL

template<typename T>
struct X0 {
  typedef int size_type;

  size_type f0() const;
};

template<typename T>
typename X0<T>::size_type X0<T>::f0() const { }
<commit_msg>Make the recanonicalization-for-an-out-of-line-definition test case a bit trickier<commit_after>// RUN: clang-cc -fsyntax-only -verify %s
// XFAIL

template<typename T> struct X1 { };

template<typename T>
struct X0 {
  typedef int size_type;
  typedef T value_type;

  size_type f0() const;
  value_type *f1();
  X1<value_type*> f2();
};

template<typename T>
typename X0<T>::size_type X0<T>::f0() const {
  return 0;
}

template<typename U>
typename X0<U>::value_type *X0<U>::f1() {
  return 0;
};

template<typename U>
X1<typename X0<U>::value_type*> X0<U>::f2() {
  return 0;
};
<|endoftext|>


<commit_before>/**
 * @file log_softmax_layer.hpp
 * @author Marcus Edel
 *
 * Definition of the LogSoftmaxLayer class.
 */
#ifndef __MLPACK_METHODS_ANN_LAYER_LOG_SOFTMAX_LAYER_HPP
#define __MLPACK_METHODS_ANN_LAYER_LOG_SOFTMAX_LAYER_HPP

#include <mlpack/core.hpp>

namespace mlpack {
namespace ann /** Artificial Neural Network. */ {

/**
 * Implementation of the log softmax layer. The log softmax loss layer computes
 * the multinomial logistic loss of the softmax of its inputs. This layer is
 * meant to be used in combination with the negative log likelihood layer
 * (NegativeLogLikelihoodLayer), which expects that the input contains
 * log-probabilities for each class.
 *
 * @tparam InputDataType Type of the input data (arma::colvec, arma::mat,
 *         arma::sp_mat or arma::cube).
 * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat,
 *         arma::sp_mat or arma::cube).
 */
template <
    typename InputDataType = arma::mat,
    typename OutputDataType = arma::mat
>
class LogSoftmaxLayer
{
 public:
  /**
   * Create the LogSoftmaxLayer object.
   */
  LogSoftmaxLayer() { /* Nothing to do here. */ }

  /**
   * Ordinary feed forward pass of a neural network, evaluating the function
   * f(x) by propagating the activity forward through f.
   *
   * @param input Input data used for evaluating the specified function.
   * @param output Resulting output activation.
   */
  template<typename eT>
  void Forward(const arma::Mat<eT>& input, arma::Mat<eT>& output)
  {
    arma::mat maxInput = arma::repmat(arma::max(input), input.n_rows, 1);
    output = (maxInput - input);

    // Approximation of the hyperbolic tangent. The acuracy however is
    // about 0.00001 lower as using tanh. Credits go to Leon Bottou.
    output.transform( [](double x)
    {
      //! Fast approximation of exp(-x) for x positive.
      constexpr double A0 = 1.0;
      constexpr double A1 = 0.125;
      constexpr double A2 = 0.0078125;
      constexpr double A3 = 0.00032552083;
      constexpr double A4 = 1.0172526e-5;

      if (x < 13.0)
      {
        double y = A0 + x * (A1 + x * (A2 + x * (A3 + x * A4)));
        y *= y;
        y *= y;
        y *= y;
        y = 1 / y;

        return y;
      }

      return 0.0;
    } );

    output = input - (maxInput + std::log(arma::accu(output)));
  }

  /**
   * Ordinary feed backward pass of a neural network, calculating the function
   * f(x) by propagating x backwards trough f. Using the results from the feed
   * forward pass.
   *
   * @param input The propagated input activation.
   * @param gy The backpropagated error.
   * @param g The calculated gradient.
   */
  template<typename eT>
  void Backward(const arma::Mat<eT>& input,
                const arma::Mat<eT>& gy,
                arma::Mat<eT>& g)
  {
    g = gy - arma::exp(input) * arma::accu(gy);
  }

  //! Get the input parameter.
  InputDataType& InputParameter() const { return inputParameter; }
  //! Modify the input parameter.
  InputDataType& InputParameter() { return inputParameter; }

  //! Get the output parameter.
  OutputDataType& OutputParameter() const { return outputParameter; }
  //! Modify the output parameter.
  OutputDataType& OutputParameter() { return outputParameter; }

  //! Get the delta.
  InputDataType& Delta() const { return delta; }
  //! Modify the delta.
  InputDataType& Delta() { return delta; }

 private:
  //! Locally-stored delta object.
  OutputDataType delta;

  //! Locally-stored input parameter object.
  InputDataType inputParameter;

  //! Locally-stored output parameter object.
  OutputDataType outputParameter;
}; // class LogSoftmaxLayer

}; // namespace ann
}; // namespace mlpack

#endif
<commit_msg>only initialize variable once<commit_after>/**
 * @file log_softmax_layer.hpp
 * @author Marcus Edel
 *
 * Definition of the LogSoftmaxLayer class.
 */
#ifndef __MLPACK_METHODS_ANN_LAYER_LOG_SOFTMAX_LAYER_HPP
#define __MLPACK_METHODS_ANN_LAYER_LOG_SOFTMAX_LAYER_HPP

#include <mlpack/core.hpp>

namespace mlpack {
namespace ann /** Artificial Neural Network. */ {

/**
 * Implementation of the log softmax layer. The log softmax loss layer computes
 * the multinomial logistic loss of the softmax of its inputs. This layer is
 * meant to be used in combination with the negative log likelihood layer
 * (NegativeLogLikelihoodLayer), which expects that the input contains
 * log-probabilities for each class.
 *
 * @tparam InputDataType Type of the input data (arma::colvec, arma::mat,
 *         arma::sp_mat or arma::cube).
 * @tparam OutputDataType Type of the output data (arma::colvec, arma::mat,
 *         arma::sp_mat or arma::cube).
 */
template <
    typename InputDataType = arma::mat,
    typename OutputDataType = arma::mat
>
class LogSoftmaxLayer
{
 public:
  /**
   * Create the LogSoftmaxLayer object.
   */
  LogSoftmaxLayer() { /* Nothing to do here. */ }

  /**
   * Ordinary feed forward pass of a neural network, evaluating the function
   * f(x) by propagating the activity forward through f.
   *
   * @param input Input data used for evaluating the specified function.
   * @param output Resulting output activation.
   */
  template<typename eT>
  void Forward(const arma::Mat<eT>& input, arma::Mat<eT>& output)
  {
    arma::mat maxInput = arma::repmat(arma::max(input), input.n_rows, 1);
    output = (maxInput - input);

    // Approximation of the hyperbolic tangent. The acuracy however is
    // about 0.00001 lower as using tanh. Credits go to Leon Bottou.
    output.transform( [](double x)
    {
      //! Fast approximation of exp(-x) for x positive.
      static constexpr double A0 = 1.0;
      static constexpr double A1 = 0.125;
      static constexpr double A2 = 0.0078125;
      static constexpr double A3 = 0.00032552083;
      static constexpr double A4 = 1.0172526e-5;

      if (x < 13.0)
      {
        double y = A0 + x * (A1 + x * (A2 + x * (A3 + x * A4)));
        y *= y;
        y *= y;
        y *= y;
        y = 1 / y;

        return y;
      }

      return 0.0;
    } );

    output = input - (maxInput + std::log(arma::accu(output)));
  }

  /**
   * Ordinary feed backward pass of a neural network, calculating the function
   * f(x) by propagating x backwards trough f. Using the results from the feed
   * forward pass.
   *
   * @param input The propagated input activation.
   * @param gy The backpropagated error.
   * @param g The calculated gradient.
   */
  template<typename eT>
  void Backward(const arma::Mat<eT>& input,
                const arma::Mat<eT>& gy,
                arma::Mat<eT>& g)
  {
    g = gy - arma::exp(input) * arma::accu(gy);
  }

  //! Get the input parameter.
  InputDataType& InputParameter() const { return inputParameter; }
  //! Modify the input parameter.
  InputDataType& InputParameter() { return inputParameter; }

  //! Get the output parameter.
  OutputDataType& OutputParameter() const { return outputParameter; }
  //! Modify the output parameter.
  OutputDataType& OutputParameter() { return outputParameter; }

  //! Get the delta.
  InputDataType& Delta() const { return delta; }
  //! Modify the delta.
  InputDataType& Delta() { return delta; }

 private:
  //! Locally-stored delta object.
  OutputDataType delta;

  //! Locally-stored input parameter object.
  InputDataType inputParameter;

  //! Locally-stored output parameter object.
  OutputDataType outputParameter;
}; // class LogSoftmaxLayer

}; // namespace ann
}; // namespace mlpack

#endif
<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// <forward_list>

// explicit forward_list(size_type n);
// explicit forward_list(size_type n, const Alloc& a);

#include <forward_list>
#include <cassert>
#include <cstddef>

#include "test_macros.h"
#include "DefaultOnly.h"
#include "min_allocator.h"

template <class T, class Allocator>
void check_allocator(unsigned n, Allocator const &alloc = Allocator())
{
#if TEST_STD_VER > 11
    typedef std::forward_list<T, Allocator> C;
    C d(n, alloc);
    assert(d.get_allocator() == alloc);
    assert(static_cast<std::size_t>(std::distance(d.begin(), d.end())) == n);
#endif
}

int main()
{
    {
        typedef DefaultOnly T;
        typedef std::forward_list<T> C;
        unsigned N = 10;
        C c(N);
        unsigned n = 0;
        for (C::const_iterator i = c.begin(), e = c.end(); i != e; ++i, ++n)
#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
            assert(*i == T());
#else
            ;
#endif
        assert(n == N);
    }
#if TEST_STD_VER >= 11
    {
        typedef DefaultOnly T;
        typedef std::forward_list<T, min_allocator<T>> C;
        unsigned N = 10;
        C c(N);
        unsigned n = 0;
        for (C::const_iterator i = c.begin(), e = c.end(); i != e; ++i, ++n)
#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
            assert(*i == T());
#else
            ;
#endif
        assert(n == N);
        check_allocator<T, min_allocator<T>> ( 0 );
        check_allocator<T, min_allocator<T>> ( 3 );
    }
#endif
}
<commit_msg>Fix yet another missed -Wunused warning. Hopefully this is the last one<commit_after>//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// <forward_list>

// explicit forward_list(size_type n);
// explicit forward_list(size_type n, const Alloc& a);

#include <forward_list>
#include <cassert>
#include <cstddef>

#include "test_macros.h"
#include "DefaultOnly.h"
#include "min_allocator.h"

template <class T, class Allocator>
void check_allocator(unsigned n, Allocator const &alloc = Allocator())
{
#if TEST_STD_VER > 11
    typedef std::forward_list<T, Allocator> C;
    C d(n, alloc);
    assert(d.get_allocator() == alloc);
    assert(static_cast<std::size_t>(std::distance(d.begin(), d.end())) == n);
#else
    ((void)n);
    ((void)alloc);
#endif
}

int main()
{
    {
        typedef DefaultOnly T;
        typedef std::forward_list<T> C;
        unsigned N = 10;
        C c(N);
        unsigned n = 0;

        for (C::const_iterator i = c.begin(), e = c.end(); i != e; ++i, ++n) {
#if TEST_STD_VER >= 11
            assert(*i == T());
#else
            ((void)0);
#endif
        }
        assert(n == N);
    }
#if TEST_STD_VER >= 11
    {
        typedef DefaultOnly T;
        typedef std::forward_list<T, min_allocator<T>> C;
        unsigned N = 10;
        C c(N);
        unsigned n = 0;
        for (C::const_iterator i = c.begin(), e = c.end(); i != e; ++i, ++n)
            assert(*i == T());
        assert(n == N);
        check_allocator<T, min_allocator<T>> ( 0 );
        check_allocator<T, min_allocator<T>> ( 3 );
    }
#endif
}
<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

// <random>

// template<class RealType, size_t bits, class URNG>
//     RealType generate_canonical(URNG& g);

#include <random>
#include <cassert>

#include "test_macros.h"
#include "truncate_fp.h"

int main(int, char**)
{
    {
        typedef std::minstd_rand0 E;
        typedef float F;
        E r;
        F f = std::generate_canonical<F, 0>(r);
        assert(f == truncate_fp((16807 - E::min()) / (E::max() - E::min() + F(1))));
    }
    {
        typedef std::minstd_rand0 E;
        typedef float F;
        E r;
        F f = std::generate_canonical<F, 1>(r);
        assert(f == truncate_fp((16807 - E::min()) / (E::max() - E::min() + F(1))));
    }
    {
        typedef std::minstd_rand0 E;
        typedef float F;
        E r;
        F f = std::generate_canonical<F, std::numeric_limits<F>::digits - 1>(r);
        assert(f == truncate_fp((16807 - E::min()) / (E::max() - E::min() + F(1))));
    }
    {
        typedef std::minstd_rand0 E;
        typedef float F;
        E r;
        F f = std::generate_canonical<F, std::numeric_limits<F>::digits>(r);
        assert(f == truncate_fp((16807 - E::min()) / (E::max() - E::min() + F(1))));
    }
    {
        typedef std::minstd_rand0 E;
        typedef float F;
        E r;
        F f = std::generate_canonical<F, std::numeric_limits<F>::digits + 1>(r);
        assert(f == truncate_fp((16807 - E::min()) / (E::max() - E::min() + F(1))));
    }

    {
        typedef std::minstd_rand0 E;
        typedef double F;
        E r;
        F f = std::generate_canonical<F, 0>(r);
        assert(f == truncate_fp((16807 - E::min()) / (E::max() - E::min() + F(1))));
    }
    {
        typedef std::minstd_rand0 E;
        typedef double F;
        E r;
        F f = std::generate_canonical<F, 1>(r);
        assert(f == truncate_fp((16807 - E::min()) / (E::max() - E::min() + F(1))));
    }
    {
        typedef std::minstd_rand0 E;
        typedef double F;
        E r;
        F f = std::generate_canonical<F, std::numeric_limits<F>::digits - 1>(r);
        assert(f == truncate_fp(
            (16807 - E::min() +
            (282475249 - E::min()) * (E::max() - E::min() + F(1))) /
            ((E::max() - E::min() + F(1)) * (E::max() - E::min() + F(1)))));
    }
    {
        typedef std::minstd_rand0 E;
        typedef double F;
        E r;
        F f = std::generate_canonical<F, std::numeric_limits<F>::digits>(r);
        assert(f == truncate_fp(
            (16807 - E::min() +
            (282475249 - E::min()) * (E::max() - E::min() + F(1))) /
            ((E::max() - E::min() + F(1)) * (E::max() - E::min() + F(1)))));
    }
    {
        typedef std::minstd_rand0 E;
        typedef double F;
        E r;
        F f = std::generate_canonical<F, std::numeric_limits<F>::digits + 1>(r);
        assert(f == truncate_fp(
            (16807 - E::min() +
            (282475249 - E::min()) * (E::max() - E::min() + F(1))) /
            ((E::max() - E::min() + F(1)) * (E::max() - E::min() + F(1)))));
    }

  return 0;
}
<commit_msg>[libc++] Avoid implicit conversion warning in a <random> test<commit_after>//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

// <random>

// template<class RealType, size_t bits, class URNG>
//     RealType generate_canonical(URNG& g);

#include <random>
#include <cassert>

#include "test_macros.h"
#include "truncate_fp.h"

int main(int, char**)
{
    typedef std::minstd_rand0 E;
    auto range = E::max() - E::min();

    {
        typedef float F;
        E r;
        F f = std::generate_canonical<F, 0>(r);
        assert(f == truncate_fp((16807 - E::min()) / (range + F(1))));
    }
    {
        typedef float F;
        E r;
        F f = std::generate_canonical<F, 1>(r);
        assert(f == truncate_fp((16807 - E::min()) / (range + F(1))));
    }
    {
        typedef float F;
        E r;
        F f = std::generate_canonical<F, std::numeric_limits<F>::digits - 1>(r);
        assert(f == truncate_fp((16807 - E::min()) / (range + F(1))));
    }
    {
        typedef float F;
        E r;
        F f = std::generate_canonical<F, std::numeric_limits<F>::digits>(r);
        assert(f == truncate_fp((16807 - E::min()) / (range + F(1))));
    }
    {
        typedef float F;
        E r;
        F f = std::generate_canonical<F, std::numeric_limits<F>::digits + 1>(r);
        assert(f == truncate_fp((16807 - E::min()) / (range + F(1))));
    }

    {
        typedef double F;
        E r;
        F f = std::generate_canonical<F, 0>(r);
        assert(f == truncate_fp((16807 - E::min()) / (range + F(1))));
    }
    {
        typedef double F;
        E r;
        F f = std::generate_canonical<F, 1>(r);
        assert(f == truncate_fp((16807 - E::min()) / (range + F(1))));
    }
    {
        typedef double F;
        E r;
        F f = std::generate_canonical<F, std::numeric_limits<F>::digits - 1>(r);
        assert(f == truncate_fp(
            (16807 - E::min() +
            (282475249 - E::min()) * (range + F(1))) /
            ((range + F(1)) * (range + F(1)))));
    }
    {
        typedef double F;
        E r;
        F f = std::generate_canonical<F, std::numeric_limits<F>::digits>(r);
        assert(f == truncate_fp(
            (16807 - E::min() +
            (282475249 - E::min()) * (range + F(1))) /
            ((range + F(1)) * (range + F(1)))));
    }
    {
        typedef double F;
        E r;
        F f = std::generate_canonical<F, std::numeric_limits<F>::digits + 1>(r);
        assert(f == truncate_fp(
            (16807 - E::min() +
            (282475249 - E::min()) * (range + F(1))) /
            ((range + F(1)) * (range + F(1)))));
    }

  return 0;
}
<|endoftext|>


<commit_before>#pragma once

#include "xyz/openbmc_project/PLDM/PDR/server.hpp"

#include <sdbusplus/bus.hpp>
#include <sdbusplus/server/object.hpp>
#include <vector>

#include "libpldm/pdr.h"
#include "libpldm/platform.h"

namespace pldm
{
namespace dbus_api
{

using PdrIntf = sdbusplus::server::object::object<
    sdbusplus::xyz::openbmc_project::PLDM::server::PDR>;

/** @class Pdr
 *  @brief OpenBMC PLDM.PDR Implementation
 *  @details A concrete implementation for the
 *  xyz.openbmc_project.PLDM.PDR DBus APIs.
 */
class Pdr : public PdrIntf
{
  public:
    Pdr() = delete;
    Pdr(const Pdr&) = delete;
    Pdr& operator=(const Pdr&) = delete;
    Pdr(Pdr&&) = delete;
    Pdr& operator=(Pdr&&) = delete;
    virtual ~Pdr() = default;

    /** @brief Constructor to put object onto bus at a dbus path.
     *  @param[in] bus - Bus to attach to.
     *  @param[in] path - Path to attach at.
     *  @param[in] repo - pointer to BMC's primary PDR repo
     */
    Pdr(sdbusplus::bus::bus& bus, const std::string& path,
        const pldm_pdr* repo) :
        PdrIntf(bus, path.c_str(), repo),
        pdrRepo(repo){};

    /** @brief Implementation for PdrIntf.FindStateEffecterPDR
     *  @param[in] tid - PLDM terminus ID.
     *  @param[in] entityID - entity that can be associated with PLDM State set.
     *  @param[in] stateSetId - value that identifies PLDM State set.
     */
    std::vector<std::vector<uint8_t>>
        findStateEffecterPDR(uint8_t tid, uint16_t entityID,
                             uint16_t stateSetId) override;

  private:
    /** @brief pointer to BMC's primary PDR repo */
    const pldm_pdr* pdrRepo;
};

} // namespace dbus_api
} // namespace pldm
<commit_msg>Fix OpenBMC CI fail<commit_after>#pragma once

#include "xyz/openbmc_project/PLDM/PDR/server.hpp"

#include <sdbusplus/bus.hpp>
#include <sdbusplus/server/object.hpp>
#include <vector>

#include "libpldm/pdr.h"
#include "libpldm/platform.h"

namespace pldm
{
namespace dbus_api
{

using PdrIntf = sdbusplus::server::object::object<
    sdbusplus::xyz::openbmc_project::PLDM::server::PDR>;

/** @class Pdr
 *  @brief OpenBMC PLDM.PDR Implementation
 *  @details A concrete implementation for the
 *  xyz.openbmc_project.PLDM.PDR DBus APIs.
 */
class Pdr : public PdrIntf
{
  public:
    Pdr() = delete;
    Pdr(const Pdr&) = delete;
    Pdr& operator=(const Pdr&) = delete;
    Pdr(Pdr&&) = delete;
    Pdr& operator=(Pdr&&) = delete;
    virtual ~Pdr() = default;

    /** @brief Constructor to put object onto bus at a dbus path.
     *  @param[in] bus - Bus to attach to.
     *  @param[in] path - Path to attach at.
     *  @param[in] repo - pointer to BMC's primary PDR repo
     */
    Pdr(sdbusplus::bus::bus& bus, const std::string& path,
        const pldm_pdr* repo) :
        PdrIntf(bus, path.c_str(), repo),
        pdrRepo(repo){};

    /** @brief Implementation for PdrIntf.FindStateEffecterPDR
     *  @param[in] tid - PLDM terminus ID.
     *  @param[in] entityID - entity that can be associated with PLDM State set.
     *  @param[in] stateSetId - value that identifies PLDM State set.
     */
    std::vector<std::vector<uint8_t>>
        findStateEffecterPDR(uint8_t tid, uint16_t entityID,
                             uint16_t stateSetId) override;

    /** @brief Implementation for PdrIntf.FindStateSensorPDR
     *  @param[in] tid - PLDM terminus ID.
     *  @param[in] entityID - entity that can be associated with PLDM State set.
     *  @param[in] stateSetId - value that identifies PLDM State set.
     */
    std::vector<std::vector<uint8_t>>
        findStateSensorPDR(uint8_t tid, uint16_t entityID,
                             uint16_t stateSetId) override
    {
        return {};
    }

  private:
    /** @brief pointer to BMC's primary PDR repo */
    const pldm_pdr* pdrRepo;
};

} // namespace dbus_api
} // namespace pldm
<|endoftext|>


<commit_before>/*
 * (c) Copyright Ascensio System SIA 2010-2019
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
 * street, Riga, Latvia, EU, LV-1050.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

#if defined(__ANDROID__) && !defined (NOT_USE_PTHREAD_CANCEL)
#include <pthread_setcanceltype.h>
#endif

#include "./BaseThread.h"

#if defined(_WIN32) || defined(_WIN64) ||defined(_WIN32_WCE)

#include <winbase.h>

#else

#include <signal.h>
#include "time.h"

#endif

namespace NSThreads
{
    class CThreadDescriptor
    {
    public:
        CThreadDescriptor()
        {
        }
        virtual ~CThreadDescriptor()
        {
        }
    };

    ASC_THREAD_ID GetCurrentThreadId()
    {
#if defined(_WIN32) || defined (_WIN64)
        return ::GetCurrentThreadId();
#else
        return pthread_self();
#endif
    }

    void Sleep(int nMilliseconds)
	{
#if defined(_WIN32) || defined(_WIN64) || defined(_WIN32_WCE)
		::Sleep((DWORD)nMilliseconds);
#else
		struct timespec tim, tim2;
        tim.tv_sec = nMilliseconds / 1000;
        tim.tv_nsec = (nMilliseconds % 1000) * 1000000;

		::nanosleep(&tim , &tim2);
#endif
	}

#if defined(_WIN32) || defined(_WIN64) || defined(_WIN32_WCE)
    DWORD WINAPI CBaseThread::__ThreadProc(void* pv)
    {
        CBaseThread* pThis = (CBaseThread*)pv;
        DWORD value = pThis->ThreadProc();
        if (pThis->m_bIsNeedDestroy)
            delete pThis;
        return value;
    }

    class __native_thread : public CThreadDescriptor
    {
        friend class CBaseThread;
    private:
        HANDLE m_thread = nullptr;

    public:
        __native_thread() : CThreadDescriptor()
        {
        }
        virtual ~__native_thread()
        {
            if (m_thread)
            {
                CloseHandle(m_thread);
                m_thread = NULL;
            }
        }
    };
#else
    void* CBaseThread::__ThreadProc(void* pv)
    {
#ifndef NOT_USE_PTHREAD_CANCEL
        int old_thread_type;
        pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &old_thread_type);
#endif

        CBaseThread* pThis = (CBaseThread*)pv;
        pThis->ThreadProc();

        if (pThis->m_bIsNeedDestroy)
            delete pThis;

        return NULL;
    }
    class __native_thread : public CThreadDescriptor
    {
        friend class CBaseThread;
    private:
        pthread_t m_thread;

    public:
        __native_thread() : CThreadDescriptor()
        {
            m_thread = NULL;
        }
        virtual ~__native_thread()
        {
        }
    };
#endif

    CBaseThread::CBaseThread()
    {
        m_hThread		= NULL;
        m_bRunThread	= FALSE;
        m_bSuspend		= FALSE;

        m_lError			= 0;
        m_lThreadPriority	= 0;

        m_bIsNeedDestroy = false;
    }
    CBaseThread::~CBaseThread()
    {
        Stop();
    }
    void CBaseThread::Start(int lPriority)
    {
        if (m_bRunThread)
            return;
        m_lError = 0;
        m_bSuspend = FALSE;

        m_hThread = new __native_thread();

        m_bRunThread = TRUE;

        m_bIsExit.store(false);
#if defined(_WIN32) || defined(_WIN64) || defined(_WIN32_WCE)
        DWORD dwTemp;
        ((__native_thread*)m_hThread)->m_thread = CreateThread(NULL, 0, &__ThreadProc, (void*)this, 0, &dwTemp);
        SetThreadPriority(((__native_thread*)m_hThread)->m_thread, lPriority);
#else
        pthread_create(&((__native_thread*)m_hThread)->m_thread, 0, &__ThreadProc, (void*)this);
#endif
        m_lThreadPriority = lPriority;
    }
    void CBaseThread::Suspend()
    {
        m_bSuspend = TRUE;
    }
    void CBaseThread::Resume()
    {
        m_bSuspend = FALSE;
    }
    void CBaseThread::Stop()
    {
        if (!m_bRunThread)
            return;

        m_bIsExit.store(true);
        m_bRunThread = FALSE;

        Join();
        RELEASEOBJECT(m_hThread);
    }
    void CBaseThread::StopNoJoin()
    {
        m_bRunThread = FALSE;
        RELEASEOBJECT(m_bIsExit);
        RELEASEOBJECT(m_hThread);
    }
    void CBaseThread::DestroyOnFinish()
    {
        m_bIsNeedDestroy = true;
    }

    INT CBaseThread::IsSuspended() { return m_bSuspend; }
    INT CBaseThread::IsRunned() { return m_bRunThread; }
    int CBaseThread::GetError() { return m_lError; }
    bool CBaseThread::isAborted() {return m_bIsExit && m_bIsExit.load();}

    CThreadDescriptor* CBaseThread::GetDescriptor() { return m_hThread; }
    int CBaseThread::GetPriority() { return m_lThreadPriority; }

    void CBaseThread::CheckSuspend()
    {
        while (m_bSuspend && m_bRunThread)
            NSThreads::Sleep(10);
    }

    void CBaseThread::Join()
    {
        if (NULL == m_hThread)
            return;

#if defined(_WIN32) || defined(_WIN64) || defined(_WIN32_WCE)
        WaitForSingleObject(((__native_thread*)m_hThread)->m_thread, INFINITE);
#else
        pthread_join(((__native_thread*)m_hThread)->m_thread, 0);
#endif
    }

    void CBaseThread::Cancel()
    {
        if (NULL == m_hThread)
            return;

         m_bIsExit.store(true);

         m_bRunThread = FALSE;

         Join();
         RELEASEOBJECT(m_hThread);
    }
}
<commit_msg>[Network] debug<commit_after>/*
 * (c) Copyright Ascensio System SIA 2010-2019
 *
 * This program is a free software product. You can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License (AGPL)
 * version 3 as published by the Free Software Foundation. In accordance with
 * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
 * that Ascensio System SIA expressly excludes the warranty of non-infringement
 * of any third-party rights.
 *
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR  PURPOSE. For
 * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
 *
 * You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
 * street, Riga, Latvia, EU, LV-1050.
 *
 * The  interactive user interfaces in modified source and object code versions
 * of the Program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU AGPL version 3.
 *
 * Pursuant to Section 7(b) of the License you must retain the original Product
 * logo when distributing the program. Pursuant to Section 7(e) we decline to
 * grant you any rights under trademark law for use of our trademarks.
 *
 * All the Product's GUI elements, including illustrations and icon sets, as
 * well as technical writing content are licensed under the terms of the
 * Creative Commons Attribution-ShareAlike 4.0 International. See the License
 * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
 *
 */

#if defined(__ANDROID__) && !defined (NOT_USE_PTHREAD_CANCEL)
#include <pthread_setcanceltype.h>
#endif

#include "./BaseThread.h"

#if defined(_WIN32) || defined(_WIN64) ||defined(_WIN32_WCE)

#include <winbase.h>

#else

#include <signal.h>
#include "time.h"

#endif

namespace NSThreads
{
    class CThreadDescriptor
    {
    public:
        CThreadDescriptor()
        {
        }
        virtual ~CThreadDescriptor()
        {
        }
    };

    ASC_THREAD_ID GetCurrentThreadId()
    {
#if defined(_WIN32) || defined (_WIN64)
        return ::GetCurrentThreadId();
#else
        return pthread_self();
#endif
    }

    void Sleep(int nMilliseconds)
	{
#if defined(_WIN32) || defined(_WIN64) || defined(_WIN32_WCE)
		::Sleep((DWORD)nMilliseconds);
#else
		struct timespec tim, tim2;
        tim.tv_sec = nMilliseconds / 1000;
        tim.tv_nsec = (nMilliseconds % 1000) * 1000000;

		::nanosleep(&tim , &tim2);
#endif
	}

#if defined(_WIN32) || defined(_WIN64) || defined(_WIN32_WCE)
    DWORD WINAPI CBaseThread::__ThreadProc(void* pv)
    {
        CBaseThread* pThis = (CBaseThread*)pv;
        DWORD value = pThis->ThreadProc();
        if (pThis->m_bIsNeedDestroy)
            delete pThis;
        return value;
    }

    class __native_thread : public CThreadDescriptor
    {
        friend class CBaseThread;
    private:
        HANDLE m_thread = nullptr;

    public:
        __native_thread() : CThreadDescriptor()
        {
        }
        virtual ~__native_thread()
        {
            if (m_thread)
            {
                CloseHandle(m_thread);
                m_thread = NULL;
            }
        }
    };
#else
    void* CBaseThread::__ThreadProc(void* pv)
    {
#ifndef NOT_USE_PTHREAD_CANCEL
        int old_thread_type;
        pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &old_thread_type);
#endif

        CBaseThread* pThis = (CBaseThread*)pv;
        pThis->ThreadProc();

        if (pThis->m_bIsNeedDestroy)
            delete pThis;

        return NULL;
    }
    class __native_thread : public CThreadDescriptor
    {
        friend class CBaseThread;
    private:
        pthread_t m_thread;

    public:
        __native_thread() : CThreadDescriptor()
        {
            m_thread = NULL;
        }
        virtual ~__native_thread()
        {
        }
    };
#endif

    CBaseThread::CBaseThread()
    {
        m_hThread		= NULL;
        m_bRunThread	= FALSE;
        m_bSuspend		= FALSE;

        m_lError			= 0;
        m_lThreadPriority	= 0;

        m_bIsNeedDestroy = false;
    }
    CBaseThread::~CBaseThread()
    {
        Stop();
    }
    void CBaseThread::Start(int lPriority)
    {
        if (m_bRunThread)
            return;
        m_lError = 0;
        m_bSuspend = FALSE;

        m_hThread = new __native_thread();

        m_bRunThread = TRUE;

        m_bIsExit.store(false);
#if defined(_WIN32) || defined(_WIN64) || defined(_WIN32_WCE)
        DWORD dwTemp;
        ((__native_thread*)m_hThread)->m_thread = CreateThread(NULL, 0, &__ThreadProc, (void*)this, 0, &dwTemp);
        SetThreadPriority(((__native_thread*)m_hThread)->m_thread, lPriority);
#else
        pthread_create(&((__native_thread*)m_hThread)->m_thread, 0, &__ThreadProc, (void*)this);
#endif
        m_lThreadPriority = lPriority;
    }
    void CBaseThread::Suspend()
    {
        m_bSuspend = TRUE;
    }
    void CBaseThread::Resume()
    {
        m_bSuspend = FALSE;
    }
    void CBaseThread::Stop()
    {
        if (!m_bRunThread)
            return;

        m_bIsExit.store(true);
        m_bRunThread = FALSE;

        Join();
        RELEASEOBJECT(m_hThread);
    }
    void CBaseThread::StopNoJoin()
    {
        m_bRunThread = FALSE;
        m_bIsExit.store(true);
        RELEASEOBJECT(m_hThread);
    }
    void CBaseThread::DestroyOnFinish()
    {
        m_bIsNeedDestroy = true;
    }

    INT CBaseThread::IsSuspended() { return m_bSuspend; }
    INT CBaseThread::IsRunned() { return m_bRunThread; }
    int CBaseThread::GetError() { return m_lError; }
    bool CBaseThread::isAborted() {return m_bIsExit && m_bIsExit.load();}

    CThreadDescriptor* CBaseThread::GetDescriptor() { return m_hThread; }
    int CBaseThread::GetPriority() { return m_lThreadPriority; }

    void CBaseThread::CheckSuspend()
    {
        while (m_bSuspend && m_bRunThread)
            NSThreads::Sleep(10);
    }

    void CBaseThread::Join()
    {
        if (NULL == m_hThread)
            return;

#if defined(_WIN32) || defined(_WIN64) || defined(_WIN32_WCE)
        WaitForSingleObject(((__native_thread*)m_hThread)->m_thread, INFINITE);
#else
        pthread_join(((__native_thread*)m_hThread)->m_thread, 0);
#endif
    }

    void CBaseThread::Cancel()
    {
        if (NULL == m_hThread)
            return;

         m_bIsExit.store(true);

         m_bRunThread = FALSE;

         Join();
         RELEASEOBJECT(m_hThread);
    }
}
<|endoftext|>


<commit_before>#include <fstream>
#include <math.h>
#include <uWS/uWS.h>
#include <chrono>
#include <iostream>
#include <thread>
#include <vector>
#include "Eigen-3.3/Eigen/Core"
#include "Eigen-3.3/Eigen/QR"
#include "json.hpp"

using namespace std;

// for convenience
using json = nlohmann::json;

// For converting back and forth between radians and degrees.
constexpr double pi() { return M_PI; }
double deg2rad(double x) { return x * pi() / 180; }
double rad2deg(double x) { return x * 180 / pi(); }

// Checks if the SocketIO event has JSON data.
// If there is data the JSON object in string format will be returned,
// else the empty string "" will be returned.
string hasData(string s)
{
  auto found_null = s.find("null");
  auto b1 = s.find_first_of("[");
  auto b2 = s.find_first_of("}");
  if (found_null != string::npos)
  {
    return "";
  } else if (b1 != string::npos && b2 != string::npos)
  {
    return s.substr(b1, b2 - b1 + 2);
  }
  return "";
}

double distance(double x1, double y1, double x2, double y2)
{
  return sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
}

int ClosestWaypoint(double x, double y, const vector<double> &maps_x, const vector<double> &maps_y)
{
  double closestLen = 100000; //large number
  int closestWaypoint = 0;

  for(int i = 0; i < maps_x.size(); i++)
  {
    double map_x = maps_x[i];
    double map_y = maps_y[i];
    double dist = distance(x,y,map_x,map_y);
    if(dist < closestLen)
    {
      closestLen = dist;
      closestWaypoint = i;
    }
  }
  return closestWaypoint;
}

int NextWaypoint(double x, double y, double theta, const vector<double> &maps_x, const vector<double> &maps_y)
{
  int closestWaypoint = ClosestWaypoint(x,y,maps_x,maps_y);

  double map_x = maps_x[closestWaypoint];
  double map_y = maps_y[closestWaypoint];

  double heading = atan2((map_y-y),(map_x-x));

  double angle = fabs(theta-heading);
  angle = min(2*pi() - angle, angle);

  if(angle > pi()/4)
  {
    closestWaypoint++;
    if (closestWaypoint == maps_x.size())
    {
      closestWaypoint = 0;
    }
  }
  return closestWaypoint;
}

// Transform from Cartesian x,y coordinates to Frenet s,d coordinates
vector<double> getFrenet(double x, double y, double theta, const vector<double> &maps_x, const vector<double> &maps_y)
{
  int next_wp = NextWaypoint(x,y, theta, maps_x,maps_y);

  int prev_wp;
  prev_wp = next_wp-1;

  if(next_wp == 0)
  {
    prev_wp  = maps_x.size()-1;
  }

  double n_x = maps_x[next_wp]-maps_x[prev_wp];
  double n_y = maps_y[next_wp]-maps_y[prev_wp];
  double x_x = x - maps_x[prev_wp];
  double x_y = y - maps_y[prev_wp];

  // find the projection of x onto n
  double proj_norm = (x_x*n_x+x_y*n_y)/(n_x*n_x+n_y*n_y);
  double proj_x = proj_norm*n_x;
  double proj_y = proj_norm*n_y;

  double frenet_d = distance(x_x,x_y,proj_x,proj_y);

  //see if d value is positive or negative by comparing it to a center point

  double center_x = 1000-maps_x[prev_wp];
  double center_y = 2000-maps_y[prev_wp];
  double centerToPos = distance(center_x,center_y,x_x,x_y);
  double centerToRef = distance(center_x,center_y,proj_x,proj_y);

  if(centerToPos <= centerToRef)
  {
    frenet_d *= -1;
  }

  // calculate s value
  double frenet_s = 0;
  for(int i = 0; i < prev_wp; i++)
  {
    frenet_s += distance(maps_x[i],maps_y[i],maps_x[i+1],maps_y[i+1]);
  }

  frenet_s += distance(0,0,proj_x,proj_y);

  return {frenet_s,frenet_d};
}

// Transform from Frenet s,d coordinates to Cartesian x,y
vector<double> getXY(double s, double d, const vector<double> &maps_s, const vector<double> &maps_x, const vector<double> &maps_y)
{
  int prev_wp = -1;

  while(s > maps_s[prev_wp+1] && (prev_wp < (int)(maps_s.size()-1) ))
  {
    prev_wp++;
  }

  int wp2 = (prev_wp+1)%maps_x.size();

  double heading = atan2((maps_y[wp2]-maps_y[prev_wp]),(maps_x[wp2]-maps_x[prev_wp]));
  // the x,y,s along the segment
  double seg_s = (s-maps_s[prev_wp]);

  double seg_x = maps_x[prev_wp]+seg_s*cos(heading);
  double seg_y = maps_y[prev_wp]+seg_s*sin(heading);

  double perp_heading = heading-pi()/2;

  double x = seg_x + d*cos(perp_heading);
  double y = seg_y + d*sin(perp_heading);

  return {x,y};
}

int main() {
  uWS::Hub h;

  // Load up map values for waypoint's x,y,s and d normalized normal vectors
  vector<double> map_waypoints_x;
  vector<double> map_waypoints_y;
  vector<double> map_waypoints_s;
  vector<double> map_waypoints_dx;
  vector<double> map_waypoints_dy;

  // Waypoint map to read from
  string map_file_ = "../data/highway_map.csv";
  // The max s value before wrapping around the track back to 0
  double max_s = 6945.554;

  ifstream in_map_(map_file_.c_str(), ifstream::in);

  string line;

  while (getline(in_map_, line))
  {
    istringstream iss(line);
    double x;
    double y;
    float s;
    float d_x;
    float d_y;
    iss >> x;
    iss >> y;
    iss >> s;
    iss >> d_x;
    iss >> d_y;
    map_waypoints_x.push_back(x);
    map_waypoints_y.push_back(y);
    map_waypoints_s.push_back(s);
    map_waypoints_dx.push_back(d_x);
    map_waypoints_dy.push_back(d_y);
  }

  h.onMessage([&map_waypoints_x, &map_waypoints_y, &map_waypoints_s, &map_waypoints_dx, &map_waypoints_dy]
    (uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length, uWS::OpCode opCode)
    {
    // "42" at the start of the message means there's a websocket message event.
    // The 4 signifies a websocket message
    // The 2 signifies a websocket event
    //auto sdata = string(data).substr(0, length);
    //cout << sdata << endl;
      if (length && length > 2 && data[0] == '4' && data[1] == '2') {
        auto s = hasData(data);

        if (s != "")
        {
          auto j = json::parse(s);
          string event = j[0].get<string>();

          if (event == "telemetry")
          {
          // j[1] is the data JSON object

          // Main car's localization Data
            double car_x = j[1]["x"];
            double car_y = j[1]["y"];
            double car_s = j[1]["s"];
            double car_d = j[1]["d"];
            double car_yaw = j[1]["yaw"];
            double car_speed = j[1]["speed"];

            // Previous path data given to the Planner
            auto previous_path_x = j[1]["previous_path_x"];
            auto previous_path_y = j[1]["previous_path_y"];

            // Previous path's end s and d values
            double end_path_s = j[1]["end_path_s"];
            double end_path_d = j[1]["end_path_d"];

            // Sensor Fusion Data, a list of all other cars on the same side of the road.
            auto sensor_fusion = j[1]["sensor_fusion"];

            json msgJson;

            vector<double> next_x_vals;
            vector<double> next_y_vals;

            // TODO: define a path made up of (x,y) points that the car will visit sequentially every .02 seconds

            // Experimental: Drive at current car yaw i.e. in a straight line
            double d_inc = 0.44; // spacing between subsequent points, controls car speed

            for(int i = 0; i < 50; i++)
            {
              double next_x = car_x + (i + 1) * d_inc * cos(deg2rad(car_yaw));
              double next_y = car_y + (i + 1) * d_inc * sin(deg2rad(car_yaw));
              next_x_vals.push_back(next_x);
              next_y_vals.push_back(next_y);
            }

            // END

            msgJson["next_x"] = next_x_vals;
            msgJson["next_y"] = next_y_vals;

            auto msg = "42[\"control\","+ msgJson.dump()+"]";

            //this_thread::sleep_for(chrono::milliseconds(1000));
            ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
          }

        } // end hasData() check in s

        else
        {
        // Manual driving
          std::string msg = "42[\"manual\",{}]";
          ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
        } // end Manual driving
      } // end websocket message event
    }); // end onMessage

  // We don't need this since we're not using HTTP but if it's removed the
  // program doesn't compile :-(
  h.onHttpRequest([](uWS::HttpResponse *res, uWS::HttpRequest req, char *data, size_t, size_t)
  {
    const std::string s = "
Hello world!
";
    if (req.getUrl().valueLength == 1)
    {
      res->end(s.data(), s.length());
    } else
    {
      // i guess this should be done more gracefully?
      res->end(nullptr, 0);
    }
  });

  h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req)
  {
    std::cout << "Connected!!!" << std::endl;
  });

  h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code, char *message, size_t length)
  {
    ws.close();
    std::cout << "Disconnected" << std::endl;
  });

  int port = 4567;

  if (h.listen(port))
  {
    std::cout << "Listening to port " << port << std::endl;
  }

  else
  {
    std::cerr << "Failed to listen to port" << std::endl;
    return -1;
  }

  h.run();
}
<commit_msg>feat: add experimental code to drive in current lane<commit_after>#include <fstream>
#include <math.h>
#include <uWS/uWS.h>
#include <chrono>
#include <iostream>
#include <thread>
#include <vector>
#include "Eigen-3.3/Eigen/Core"
#include "Eigen-3.3/Eigen/QR"
#include "json.hpp"

using namespace std;

// for convenience
using json = nlohmann::json;

// For converting back and forth between radians and degrees.
constexpr double pi() { return M_PI; }
double deg2rad(double x) { return x * pi() / 180; }
double rad2deg(double x) { return x * 180 / pi(); }

// Checks if the SocketIO event has JSON data.
// If there is data the JSON object in string format will be returned,
// else the empty string "" will be returned.
string hasData(string s)
{
  auto found_null = s.find("null");
  auto b1 = s.find_first_of("[");
  auto b2 = s.find_first_of("}");
  if (found_null != string::npos)
  {
    return "";
  } else if (b1 != string::npos && b2 != string::npos)
  {
    return s.substr(b1, b2 - b1 + 2);
  }
  return "";
}

double distance(double x1, double y1, double x2, double y2)
{
  return sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
}

int ClosestWaypoint(double x, double y, const vector<double> &maps_x, const vector<double> &maps_y)
{
  double closestLen = 100000; //large number
  int closestWaypoint = 0;

  for(int i = 0; i < maps_x.size(); i++)
  {
    double map_x = maps_x[i];
    double map_y = maps_y[i];
    double dist = distance(x,y,map_x,map_y);
    if(dist < closestLen)
    {
      closestLen = dist;
      closestWaypoint = i;
    }
  }
  return closestWaypoint;
}

int NextWaypoint(double x, double y, double theta, const vector<double> &maps_x, const vector<double> &maps_y)
{
  int closestWaypoint = ClosestWaypoint(x,y,maps_x,maps_y);

  double map_x = maps_x[closestWaypoint];
  double map_y = maps_y[closestWaypoint];

  double heading = atan2((map_y-y),(map_x-x));

  double angle = fabs(theta-heading);
  angle = min(2*pi() - angle, angle);

  if(angle > pi()/4)
  {
    closestWaypoint++;
    if (closestWaypoint == maps_x.size())
    {
      closestWaypoint = 0;
    }
  }
  return closestWaypoint;
}

// Transform from Cartesian x,y coordinates to Frenet s,d coordinates
vector<double> getFrenet(double x, double y, double theta, const vector<double> &maps_x, const vector<double> &maps_y)
{
  int next_wp = NextWaypoint(x,y, theta, maps_x,maps_y);

  int prev_wp;
  prev_wp = next_wp-1;

  if(next_wp == 0)
  {
    prev_wp  = maps_x.size()-1;
  }

  double n_x = maps_x[next_wp]-maps_x[prev_wp];
  double n_y = maps_y[next_wp]-maps_y[prev_wp];
  double x_x = x - maps_x[prev_wp];
  double x_y = y - maps_y[prev_wp];

  // find the projection of x onto n
  double proj_norm = (x_x*n_x+x_y*n_y)/(n_x*n_x+n_y*n_y);
  double proj_x = proj_norm*n_x;
  double proj_y = proj_norm*n_y;

  double frenet_d = distance(x_x,x_y,proj_x,proj_y);

  //see if d value is positive or negative by comparing it to a center point

  double center_x = 1000-maps_x[prev_wp];
  double center_y = 2000-maps_y[prev_wp];
  double centerToPos = distance(center_x,center_y,x_x,x_y);
  double centerToRef = distance(center_x,center_y,proj_x,proj_y);

  if(centerToPos <= centerToRef)
  {
    frenet_d *= -1;
  }

  // calculate s value
  double frenet_s = 0;
  for(int i = 0; i < prev_wp; i++)
  {
    frenet_s += distance(maps_x[i],maps_y[i],maps_x[i+1],maps_y[i+1]);
  }

  frenet_s += distance(0,0,proj_x,proj_y);

  return {frenet_s,frenet_d};
}

// Transform from Frenet s,d coordinates to Cartesian x,y
vector<double> getXY(double s, double d, const vector<double> &maps_s, const vector<double> &maps_x, const vector<double> &maps_y)
{
  int prev_wp = -1;

  while(s > maps_s[prev_wp+1] && (prev_wp < (int)(maps_s.size()-1) ))
  {
    prev_wp++;
  }

  int wp2 = (prev_wp+1)%maps_x.size();

  double heading = atan2((maps_y[wp2]-maps_y[prev_wp]),(maps_x[wp2]-maps_x[prev_wp]));
  // the x,y,s along the segment
  double seg_s = (s-maps_s[prev_wp]);

  double seg_x = maps_x[prev_wp]+seg_s*cos(heading);
  double seg_y = maps_y[prev_wp]+seg_s*sin(heading);

  double perp_heading = heading-pi()/2;

  double x = seg_x + d*cos(perp_heading);
  double y = seg_y + d*sin(perp_heading);

  return {x,y};
}

int main() {
  uWS::Hub h;

  // Load up map values for waypoint's x,y,s and d normalized normal vectors
  vector<double> map_waypoints_x;
  vector<double> map_waypoints_y;
  vector<double> map_waypoints_s;
  vector<double> map_waypoints_dx;
  vector<double> map_waypoints_dy;

  // Waypoint map to read from
  string map_file_ = "../data/highway_map.csv";
  // The max s value before wrapping around the track back to 0
  double max_s = 6945.554;

  ifstream in_map_(map_file_.c_str(), ifstream::in);

  string line;

  while (getline(in_map_, line))
  {
    istringstream iss(line);
    double x;
    double y;
    float s;
    float d_x;
    float d_y;
    iss >> x;
    iss >> y;
    iss >> s;
    iss >> d_x;
    iss >> d_y;
    map_waypoints_x.push_back(x);
    map_waypoints_y.push_back(y);
    map_waypoints_s.push_back(s);
    map_waypoints_dx.push_back(d_x);
    map_waypoints_dy.push_back(d_y);
  }

  h.onMessage([&map_waypoints_x, &map_waypoints_y, &map_waypoints_s, &map_waypoints_dx, &map_waypoints_dy]
    (uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length, uWS::OpCode opCode)
    {
    // "42" at the start of the message means there's a websocket message event.
    // The 4 signifies a websocket message
    // The 2 signifies a websocket event
    //auto sdata = string(data).substr(0, length);
    //cout << sdata << endl;
      if (length && length > 2 && data[0] == '4' && data[1] == '2') {
        auto s = hasData(data);

        if (s != "")
        {
          auto j = json::parse(s);
          string event = j[0].get<string>();

          if (event == "telemetry")
          {
          // j[1] is the data JSON object

          // Main car's localization Data
            double car_x = j[1]["x"];
            double car_y = j[1]["y"];
            double car_s = j[1]["s"];
            double car_d = j[1]["d"];
            double car_yaw = j[1]["yaw"];
            double car_speed = j[1]["speed"];

            // Previous path data given to the Planner
            auto previous_path_x = j[1]["previous_path_x"];
            auto previous_path_y = j[1]["previous_path_y"];

            // Previous path's end s and d values
            double end_path_s = j[1]["end_path_s"];
            double end_path_d = j[1]["end_path_d"];

            // Sensor Fusion Data, a list of all other cars on the same side of the road.
            auto sensor_fusion = j[1]["sensor_fusion"];

            json msgJson;

            vector<double> next_x_vals;
            vector<double> next_y_vals;

            // TODO: define a path made up of (x,y) points that the car will visit sequentially every .02 seconds

            // Experimental: Drive in current lane
            double d_inc = 0.44; // spacing between subsequent points, controls car speed

            for(int i = 0; i < 50; i++)
            {
              double next_s = car_s + (i + 1) * d_inc;
              double next_d = 6; // assuming car starts in middle lane and a lane width of 4m
              vector<double> xy = getXY(next_s, next_d, map_waypoints_s, map_waypoints_x, map_waypoints_y);
              next_x_vals.push_back(xy[0]);
              next_y_vals.push_back(xy[1]);
            }
            // end drive in current lane

            // // Experimental: Drive at current car yaw i.e. in a straight line
            // double d_inc = 0.44; // spacing between subsequent points, controls car speed

            // for(int i = 0; i < 50; i++)
            // {
            //   double next_x = car_x + (i + 1) * d_inc * cos(deg2rad(car_yaw));
            //   double next_y = car_y + (i + 1) * d_inc * sin(deg2rad(car_yaw));
            //   next_x_vals.push_back(next_x);
            //   next_y_vals.push_back(next_y);
            // }
            // // end drive in straight line

            msgJson["next_x"] = next_x_vals;
            msgJson["next_y"] = next_y_vals;

            auto msg = "42[\"control\","+ msgJson.dump()+"]";

            //this_thread::sleep_for(chrono::milliseconds(1000));
            ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
          }

        } // end hasData() check in s

        else
        {
        // Manual driving
          std::string msg = "42[\"manual\",{}]";
          ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
        } // end Manual driving
      } // end websocket message event
    }); // end onMessage

  // We don't need this since we're not using HTTP but if it's removed the
  // program doesn't compile :-(
  h.onHttpRequest([](uWS::HttpResponse *res, uWS::HttpRequest req, char *data, size_t, size_t)
  {
    const std::string s = "
Hello world!
";
    if (req.getUrl().valueLength == 1)
    {
      res->end(s.data(), s.length());
    } else
    {
      // i guess this should be done more gracefully?
      res->end(nullptr, 0);
    }
  });

  h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req)
  {
    std::cout << "Connected!!!" << std::endl;
  });

  h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code, char *message, size_t length)
  {
    ws.close();
    std::cout << "Disconnected" << std::endl;
  });

  int port = 4567;

  if (h.listen(port))
  {
    std::cout << "Listening to port " << port << std::endl;
  }

  else
  {
    std::cerr << "Failed to listen to port" << std::endl;
    return -1;
  }

  h.run();
}
<|endoftext|>


<commit_before>#include <iostream>
#include "shared.h"

#include "v8.h"

int main() {
  v8::HandleScope handle_scope;

  std::cout << "Hello world!\n";
  return 0;
}<commit_msg>removed failing code<commit_after>#include <iostream>
#include "shared.h"

#include "v8.h"

int main() {
  std::cout << "Hello world!\n";
  return 0;
}<|endoftext|>


<commit_before>/*!
  \copyright (c) RDO-Team, 2011
  \file      main.cpp
  \authors     (rdo@rk9.bmstu.ru)
  \authors     (impus@hotbox.ru)
  \date      2.10.2011
  \brief
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
// ----------------------------------------------------------------------- INCLUDES
#define BOOST_TEST_MODULE RDOSequencesTest
#include <iostream>
#include <fstream>
#include <list>
#include <math.h>
#include <boost/test/included/unit_test.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
// ----------------------------------------------------------------------- SYNOPSIS
#include "utils/rdofile.h"
#include "simulator/runtime/rdo_random_distribution.h"
// --------------------------------------------------------------------------------

typedef std::list<double> Container;
typedef const tstring contstr;

const long int g_seed                 = 123456789;                  //!<
contstr        g_fileNormalName       = _T("data_normal.txt");      //!<
contstr        g_fileUniformName      = _T("data_uniform.txt");     //!<
contstr        g_fileExponentialName  = _T("data_exponential.txt"); //!<
contstr        g_fileTriangularName   = _T("data_trinagular.txt");  //!<
const ruint    g_count                = 100000;                     //!<
const double   g_main                 = 10.0;                       //!<
const double   g_var                  = 1.0;                        //!<
const double   g_from                 = 1.0;                        //!<
const double   g_to                   = 7.0;                        //!<
const double   g_top                  = 5.0;                        //!<
const ruint    g_precision            = 20;                         //!<
const ruint    g_countOfExamples      = 2000;                       //!<
const ruint    g_countOfFree          = 39;                         //!<
const double   pi                     = 3.141592653;                //!<

// --------------------------------------------------------------------------------
// -------Templates
// --------------------------------------------------------------------------------
template <class T, class F, class contstr>
void onGenerateData(F binder, contstr g_fileName)
{
	if (rdo::File::exist(g_fileName.c_str()))
		return;

	T sequence(g_seed);
	Container test;

	for (ruint i = 0; i < g_count; ++i)
	{
		test.push_back(binder.operator()(&sequence));
	}

	std::ofstream stream(g_fileName.c_str());
	stream.precision(g_precision);
	STL_FOR_ALL(test, it)
	{
		stream << *it << std::endl;
	}
}

template <class T, class F, class contstr>
void onCheckData(F binder, contstr g_fileName)
{
	std::ifstream stream(g_fileName.c_str());
	BOOST_CHECK(stream.good());

	Container test;
	T sequence(g_seed);
	for (ruint i = 0; i < g_count; ++i)
	{
		test.push_back(binder.operator()(&sequence));
	}

	stream.precision(g_precision);
	STL_FOR_ALL(test, it)
	{
		BOOST_CHECK(stream.good());
		tstring str;
		stream >> str;

		double val;
		BOOST_CHECK(sscanf_s(str.c_str(), _T("%lf"), &val) == 1);
		BOOST_CHECK(val == *it);
				if (val != *it)
		{
			std::cout.precision(g_precision);
			std::cout << *it << std::endl;
			std::cout << val << std::endl;
		}
	}
}

template <class T,class F>
double  area (F binder, double elem, double n, double m)
{
	double S1 = 1;
	double S2 = 0;
	ruint t = (n-m)/elem;
	while (fabs(S1-S2)/S1 > 0.01)
	{
		S2 = S1;
		S1 = 0;
		for (ruint i = 0; i < t; ++i)
		{
			T sequnece(i*(n-m)/t);
			S1 += binder.operator()(&sequence);
		}
		S1 *= 0.5*(m-n);
		t  *= 10;
	}
	return S1;
}

template <class T,class F>
void onCheckKsi(F binder, double left, double right)
{
	Container xITemp;								//   ,
	double elem = (right-left)/(1000*g_countOfFree);//    ,
	for (ruint i = 0; i < g_countOfFree*1000+1; ++i)//    . ,       (  )
	{
		xITemp.push_back(elem*i);
	}

	Container xI;							//   ,
	Container::iterator it = xI.begin();
	xI.push_back(left);						//     ,        - right

	STL_FOR_ALL(xITemp, itTemp)
	{
		if (fabs(area(binder, elem, *it, *itTemp) - 1/g_countOfFree) < fabs(area(binder, elem, *it, *(++itTemp)) - 1/g_countOfFree))
		{
			xI.push_back(*((--itTemp)++);
			++it;
		}
		--itTemp;
	}
	if(xI.size() == (g_countOfFree - 1))	// ,             .     - .          .
	{
		xI.push_back(right);
	}

//,         right   , ..   .  ,
}
// --------------------------------------------------------------------------------

class SequenceNormal
{
public:
	SequenceNormal(double x): m_x(x)
	{}
	double next(double main, double var)
	{
		return 1/(sqrt(2*pi)*sqrt(var)*exp((m_x - main)*(m_x - main)/(2*var))); //   .    .    3 .
	}
private:
	double m_x;
};

BOOST_AUTO_TEST_SUITE(RDOSequencesTest)

// --------------------------------------------------------------------------------
// -------Normal sequence
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(RDONormalTestCreate)
{
	onGenerateData<rdoRuntime::RandGeneratorNormal>
		(boost::bind(&rdoRuntime::RandGeneratorNormal::next, _1, g_main, g_var), g_fileNormalName);
}

BOOST_AUTO_TEST_CASE(RDONormalTestCheck)
{
	onCheckData<rdoRuntime::RandGeneratorNormal>
		(boost::bind(&rdoRuntime::RandGeneratorNormal::next, _1, g_main, g_var), g_fileNormalName);
	onCheckKsi<SequenceNormal>
		(boost::bind(&SequenceNormal::next, _1, g_main, g_var), g_main-4*sqrt(g_var), g_main+4*sqrt(g_var));
}
// --------------------------------------------------------------------------------

// --------------------------------------------------------------------------------
// -------Uniform sequence
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(RDOUniformTestCreate)
{
	onGenerateData<rdoRuntime::RandGeneratorUniform>
		(boost::bind(&rdoRuntime::RandGeneratorUniform::next, _1, g_from, g_to), g_fileUniformName);
}

BOOST_AUTO_TEST_CASE(RDOUniformTestCheck)
{
	onCheckData<rdoRuntime::RandGeneratorUniform>
		(boost::bind(&rdoRuntime::RandGeneratorUniform::next, _1, g_from, g_to), g_fileUniformName);
}
// --------------------------------------------------------------------------------

// --------------------------------------------------------------------------------
// -------Exponential sequence
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(RDOExponentialTestCreate)
{
	onGenerateData<rdoRuntime::RandGeneratorExponential>
		(boost::bind(&rdoRuntime::RandGeneratorExponential::next, _1, g_main), g_fileExponentialName);
}

BOOST_AUTO_TEST_CASE(RDOExponentialTestCheck)
{
	onCheckData<rdoRuntime::RandGeneratorExponential>
		(boost::bind(&rdoRuntime::RandGeneratorExponential::next, _1, g_main), g_fileExponentialName);
}
// --------------------------------------------------------------------------------

// --------------------------------------------------------------------------------
// -------Triangular sequence
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(RDOTriangularTestCreate)
{
	onGenerateData<rdoRuntime::RandGeneratorTriangular>
		(boost::bind(&rdoRuntime::RandGeneratorTriangular::next, _1, g_from, g_top, g_to), g_fileTriangularName);
}

BOOST_AUTO_TEST_CASE(RDOTriangularTestCheck)
{
	onCheckData<rdoRuntime::RandGeneratorTriangular>
		(boost::bind(&rdoRuntime::RandGeneratorTriangular::next, _1, g_from, g_top, g_to), g_fileTriangularName);
}
// --------------------------------------------------------------------------------

BOOST_AUTO_TEST_SUITE_END()<commit_msg> - исправлено вычисление площади<commit_after>/*!
  \copyright (c) RDO-Team, 2011
  \file      main.cpp
  \authors     (rdo@rk9.bmstu.ru)
  \authors     (impus@hotbox.ru)
  \date      2.10.2011
  \brief
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
// ----------------------------------------------------------------------- INCLUDES
#define BOOST_TEST_MODULE RDOSequencesTest
#include <iostream>
#include <fstream>
#include <list>
#include <math.h>
#include <boost/test/included/unit_test.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
// ----------------------------------------------------------------------- SYNOPSIS
#include "utils/rdofile.h"
#include "simulator/runtime/rdo_random_distribution.h"
// --------------------------------------------------------------------------------

typedef std::list<double> Container;
typedef const tstring contstr;

const long int g_seed                 = 123456789;                  //!<
contstr        g_fileNormalName       = _T("data_normal.txt");      //!<
contstr        g_fileUniformName      = _T("data_uniform.txt");     //!<
contstr        g_fileExponentialName  = _T("data_exponential.txt"); //!<
contstr        g_fileTriangularName   = _T("data_trinagular.txt");  //!<
const ruint    g_count                = 100000;                     //!<
const double   g_main                 = 10.0;                       //!<
const double   g_var                  = 1.0;                        //!<
const double   g_from                 = 1.0;                        //!<
const double   g_to                   = 7.0;                        //!<
const double   g_top                  = 5.0;                        //!<
const ruint    g_precision            = 20;                         //!<
const ruint    g_countOfExamples      = 2000;                       //!<
const ruint    g_countOfFree          = 39;                         //!<
const double   pi                     = 3.141592653;                //!<

// --------------------------------------------------------------------------------
// -------Templates
// --------------------------------------------------------------------------------
template <class T, class F, class contstr>
void onGenerateData(F binder, contstr g_fileName)
{
	if (rdo::File::exist(g_fileName.c_str()))
		return;

	T sequence(g_seed);
	Container test;

	for (ruint i = 0; i < g_count; ++i)
	{
		test.push_back(binder.operator()(&sequence));
	}

	std::ofstream stream(g_fileName.c_str());
	stream.precision(g_precision);
	STL_FOR_ALL(test, it)
	{
		stream << *it << std::endl;
	}
}

template <class T, class F, class contstr>
void onCheckData(F binder, contstr g_fileName)
{
	std::ifstream stream(g_fileName.c_str());
	BOOST_CHECK(stream.good());

	Container test;
	T sequence(g_seed);
	for (ruint i = 0; i < g_count; ++i)
	{
		test.push_back(binder.operator()(&sequence));
	}

	stream.precision(g_precision);
	STL_FOR_ALL(test, it)
	{
		BOOST_CHECK(stream.good());
		tstring str;
		stream >> str;

		double val;
		BOOST_CHECK(sscanf_s(str.c_str(), _T("%lf"), &val) == 1);
		BOOST_CHECK(val == *it);
				if (val != *it)
		{
			std::cout.precision(g_precision);
			std::cout << *it << std::endl;
			std::cout << val << std::endl;
		}
	}
}

template <class T,class F>
double  area (F binder, double elem, double n, double m)
{
	int k = 1;
	double S1 = 1;
	double S2 = 0;
	ruint t = (m-n)/elem;
	while (fabs(S1-S2)/S1 > 0.01)
	{
		S2 = S1;
		S1 = 0;
		for (ruint i = 1; i < t-1; ++i)
		{
			if ((i == 0) || (i == t - 1))
				k = 0.5;
			T sequence(i*(m-n)/t);
			S1 += k*(binder.operator()(&sequence));
			k = 1;
		}
		S1 *= (m-n);
		t  *= 10;
	}
	return S1;
}

template <class T,class F>
void onCheckKsi(F binder, double left, double right)
{
	Container xITemp;								//   ,
	double elem = (right-left)/(1000*g_countOfFree);//    ,
	for (ruint i = 0; i < g_countOfFree*1000+1; ++i)//    . ,       (  )
	{
		xITemp.push_back(elem*i);
	}

	Container xI;							//   ,
	Container::iterator it = xI.begin();
	xI.push_back(left);						//     ,        - right

	STL_FOR_ALL(xITemp, itTemp)
	{
		if (fabs(area(binder, elem, *it, *itTemp) - 1/g_countOfFree) < fabs(area(binder, elem, *it, *(++itTemp)) - 1/g_countOfFree))
		{
			xI.push_back(*((--itTemp)++);
			++it;
		}
		--itTemp;
	}
	if(xI.size() == (g_countOfFree - 1))	// ,             .     - .          .
	{
		xI.push_back(right);
	}

//,         right   , ..   .  ,
}
// --------------------------------------------------------------------------------

class SequenceNormal
{
public:
	SequenceNormal(double x): m_x(x)
	{}
	double next(double main, double var)
	{
		return 1/(sqrt(2*pi)*sqrt(var)*exp((m_x - main)*(m_x - main)/(2*var))); //   .    .    3 .
	}
private:
	double m_x;
};

BOOST_AUTO_TEST_SUITE(RDOSequencesTest)

// --------------------------------------------------------------------------------
// -------Normal sequence
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(RDONormalTestCreate)
{
	onGenerateData<rdoRuntime::RandGeneratorNormal>
		(boost::bind(&rdoRuntime::RandGeneratorNormal::next, _1, g_main, g_var), g_fileNormalName);
}

BOOST_AUTO_TEST_CASE(RDONormalTestCheck)
{
	onCheckData<rdoRuntime::RandGeneratorNormal>
		(boost::bind(&rdoRuntime::RandGeneratorNormal::next, _1, g_main, g_var), g_fileNormalName);
	onCheckKsi<SequenceNormal>
		(boost::bind(&SequenceNormal::next, _1, g_main, g_var), g_main-4*sqrt(g_var), g_main+4*sqrt(g_var));
}
// --------------------------------------------------------------------------------

// --------------------------------------------------------------------------------
// -------Uniform sequence
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(RDOUniformTestCreate)
{
	onGenerateData<rdoRuntime::RandGeneratorUniform>
		(boost::bind(&rdoRuntime::RandGeneratorUniform::next, _1, g_from, g_to), g_fileUniformName);
}

BOOST_AUTO_TEST_CASE(RDOUniformTestCheck)
{
	onCheckData<rdoRuntime::RandGeneratorUniform>
		(boost::bind(&rdoRuntime::RandGeneratorUniform::next, _1, g_from, g_to), g_fileUniformName);
}
// --------------------------------------------------------------------------------

// --------------------------------------------------------------------------------
// -------Exponential sequence
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(RDOExponentialTestCreate)
{
	onGenerateData<rdoRuntime::RandGeneratorExponential>
		(boost::bind(&rdoRuntime::RandGeneratorExponential::next, _1, g_main), g_fileExponentialName);
}

BOOST_AUTO_TEST_CASE(RDOExponentialTestCheck)
{
	onCheckData<rdoRuntime::RandGeneratorExponential>
		(boost::bind(&rdoRuntime::RandGeneratorExponential::next, _1, g_main), g_fileExponentialName);
}
// --------------------------------------------------------------------------------

// --------------------------------------------------------------------------------
// -------Triangular sequence
// --------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(RDOTriangularTestCreate)
{
	onGenerateData<rdoRuntime::RandGeneratorTriangular>
		(boost::bind(&rdoRuntime::RandGeneratorTriangular::next, _1, g_from, g_top, g_to), g_fileTriangularName);
}

BOOST_AUTO_TEST_CASE(RDOTriangularTestCheck)
{
	onCheckData<rdoRuntime::RandGeneratorTriangular>
		(boost::bind(&rdoRuntime::RandGeneratorTriangular::next, _1, g_from, g_top, g_to), g_fileTriangularName);
}
// --------------------------------------------------------------------------------

BOOST_AUTO_TEST_SUITE_END()<|endoftext|>


<commit_before><commit_msg>When parsing the type declaration for a new variable, there comes a point where we have thrown away a space character after seeing "operator<" and we must put it back, because it might actually be "operator< <int>(" and removing the space is fatal in that case.<commit_after><|endoftext|>