<commit_before>#ifndef ALEPH_PERSISTENCE_DIAGRAMS_PERSISTENCE_INDICATOR_FUNCTION_HH__
#define ALEPH_PERSISTENCE_DIAGRAMS_PERSISTENCE_INDICATOR_FUNCTION_HH__

#include "math/StepFunction.hh"

#include "persistenceDiagrams/PersistenceDiagram.hh"

#include <algorithm>
#include <limits>
#include <utility>
#include <vector>

#include <cmath>

namespace aleph
{

namespace detail
{

template <class T> struct EventPoint
{
  T value;
  bool destroyer;

  bool operator<( const EventPoint& other ) const noexcept
  {
    // Sort event point by their corresponding values. In case of ties,
    // consider creators to come after destroyers. This makes sense, as
    // a creator may increase the number of active intervals again.
    return value < other.value || ( value == other.value && destroyer && !other.destroyer );
  }
};

template <class T> T next( T x )
{
  if( std::numeric_limits<T>::is_integer )
    return x+1;
  else
    return std::nextafter( x, std::numeric_limits<T>::max() );
}

} // namespace detail

/**
  Calculates the persistence indicator function of a persistence
  diagram. This function counts the number of 'active' intervals
  for every parameter value. It is a stable summary of a diagram
  and may be used to discern more information about the topology
  and its variation over time.
*/

template <class DataType> aleph::math::StepFunction<DataType> persistenceIndicatorFunction( const PersistenceDiagram<DataType>& D )
{
  using namespace detail;
  using namespace math;

  using EP = EventPoint<DataType>;

  std::vector<EP> eventPoints;
  eventPoints.reserve( 2 * D.size() );

  for( auto&& p : D )
  {
    eventPoints.push_back( { p.x(), false } );
    eventPoints.push_back( { p.y(), true  } );
  }

  std::sort( eventPoints.begin(), eventPoints.end() );

  unsigned numActiveFeatures = 0;
  bool isDegenerate          = false;

  // Sanity check: A destroyer and a creator should never have the same
  // function value. Else, the number of 'active' intervals will behave
  // somewhat strangely.
  if( eventPoints.size() >= 2 )
  {
    for( std::size_t i = 0; i < eventPoints.size(); i += 2 )
    {
      if( eventPoints[i].value == eventPoints[i+1].value )
      {
        if( eventPoints[i].destroyer != eventPoints[i+1].destroyer )
        {
          isDegenerate = true;
          break;
        }
      }
    }
  }

  // Lambda expression for counting duplicate event points that appear after a
  // certain index in the vector of event points. Duplicate event points occur
  // if the persistence diagram contains points with equal values.
  auto numDuplicateValues = [&eventPoints] ( std::size_t i )
  {
    auto eventPoint         = eventPoints.at(i);
    unsigned numOccurrences = 0;
    unsigned numDestroyers  = 0;
    do
    {
      numDestroyers += eventPoints.at(i).destroyer;

      ++numOccurrences;
      ++i;
    }
    while( i < eventPoints.size() && eventPoints.at(i).value == eventPoint.value );

    return std::make_pair( numOccurrences, numDestroyers );
  };

  StepFunction<DataType> f;

  // Previous interval end point. This is required in order to create proper
  // indicator functions later on.
  DataType previous = DataType();

  for( std::size_t i = 0; i < eventPoints.size(); )
  {
    auto pair        = numDuplicateValues(i);
    auto occurrences = pair.first;
    auto destroyers  = pair.second;
    auto creators    = occurrences - destroyers;

    bool useNextPoint = false;

    // Case 1: No duplicates or duplicates of the same type. In this case, the
    // number of active intervals changes and we add an interval. It comprises
    // the number of active intervals up to this point.
    if( occurrences == 1 || creators == occurrences || creators == 0 )
    {
      if( i != 0 )
        f.add( previous, eventPoints.at(i).value, static_cast<DataType>( numActiveFeatures ) );
    }

    // Case 2: There are duplicate creation & destruction values. This
    // necessitates the creation of two intervals: one interval at the
    // current even point, with the proper number of active intervals,
    // the other one *directly* afterwards to indicate the destruction
    // implied by the values.
    else
    {
      f.add( previous, eventPoints.at(i).value, static_cast<DataType>( numActiveFeatures + creators ) );
      useNextPoint = true;
    }

    numActiveFeatures += creators;
    numActiveFeatures -= destroyers;

    previous  = useNextPoint ? next( eventPoints.at(i).value ) : eventPoints.at(i).value;
    i        += occurrences;
  }

  return f;
}

} // namespace aleph

#endif
<commit_msg>Removed obsolete sanity check for persistence indicator function<commit_after>#ifndef ALEPH_PERSISTENCE_DIAGRAMS_PERSISTENCE_INDICATOR_FUNCTION_HH__
#define ALEPH_PERSISTENCE_DIAGRAMS_PERSISTENCE_INDICATOR_FUNCTION_HH__

#include "math/StepFunction.hh"

#include "persistenceDiagrams/PersistenceDiagram.hh"

#include <algorithm>
#include <limits>
#include <utility>
#include <vector>

#include <cmath>

namespace aleph
{

namespace detail
{

template <class T> struct EventPoint
{
  T value;
  bool destroyer;

  bool operator<( const EventPoint& other ) const noexcept
  {
    // Sort event point by their corresponding values. In case of ties,
    // consider creators to come after destroyers. This makes sense, as
    // a creator may increase the number of active intervals again.
    return value < other.value || ( value == other.value && destroyer && !other.destroyer );
  }
};

template <class T> T next( T x )
{
  if( std::numeric_limits<T>::is_integer )
    return x+1;
  else
    return std::nextafter( x, std::numeric_limits<T>::max() );
}

} // namespace detail

/**
  Calculates the persistence indicator function of a persistence
  diagram. This function counts the number of 'active' intervals
  for every parameter value. It is a stable summary of a diagram
  and may be used to discern more information about the topology
  and its variation over time.
*/

template <class DataType> aleph::math::StepFunction<DataType> persistenceIndicatorFunction( const PersistenceDiagram<DataType>& D )
{
  using namespace detail;
  using namespace math;

  using EP = EventPoint<DataType>;

  std::vector<EP> eventPoints;
  eventPoints.reserve( 2 * D.size() );

  for( auto&& p : D )
  {
    eventPoints.push_back( { p.x(), false } );
    eventPoints.push_back( { p.y(), true  } );
  }

  std::sort( eventPoints.begin(), eventPoints.end() );

  unsigned numActiveFeatures = 0;

  // Lambda expression for counting duplicate event points that appear after a
  // certain index in the vector of event points. Duplicate event points occur
  // if the persistence diagram contains points with equal values.
  auto numDuplicateValues = [&eventPoints] ( std::size_t i )
  {
    auto eventPoint         = eventPoints.at(i);
    unsigned numOccurrences = 0;
    unsigned numDestroyers  = 0;
    do
    {
      numDestroyers += eventPoints.at(i).destroyer;

      ++numOccurrences;
      ++i;
    }
    while( i < eventPoints.size() && eventPoints.at(i).value == eventPoint.value );

    return std::make_pair( numOccurrences, numDestroyers );
  };

  StepFunction<DataType> f;

  // Previous interval end point. This is required in order to create proper
  // indicator functions later on.
  DataType previous = DataType();

  for( std::size_t i = 0; i < eventPoints.size(); )
  {
    auto pair        = numDuplicateValues(i);
    auto occurrences = pair.first;
    auto destroyers  = pair.second;
    auto creators    = occurrences - destroyers;

    bool useNextPoint = false;

    // Case 1: No duplicates or duplicates of the same type. In this case, the
    // number of active intervals changes and we add an interval. It comprises
    // the number of active intervals up to this point.
    if( occurrences == 1 || creators == occurrences || creators == 0 )
    {
      if( i != 0 )
        f.add( previous, eventPoints.at(i).value, static_cast<DataType>( numActiveFeatures ) );
    }

    // Case 2: There are duplicate creation & destruction values. This
    // necessitates the creation of two intervals: one interval at the
    // current even point, with the proper number of active intervals,
    // the other one *directly* afterwards to indicate the destruction
    // implied by the values.
    else
    {
      f.add( previous, eventPoints.at(i).value, static_cast<DataType>( numActiveFeatures + creators ) );
      useNextPoint = true;
    }

    numActiveFeatures += creators;
    numActiveFeatures -= destroyers;

    previous  = useNextPoint ? next( eventPoints.at(i).value ) : eventPoints.at(i).value;
    i        += occurrences;
  }

  return f;
}

} // namespace aleph

#endif
<|endoftext|>


<commit_before>#include "eigenvalue/k_effective/updater_via_rayleigh_quotient.hpp"

#include "system/system.h"
#include "system/moments/tests/spherical_harmonic_mock.h"
#include "test_helpers/gmock_wrapper.h"

namespace  {

using namespace bart;

using ::testing::DoDefault, ::testing::NiceMock, ::testing::ReturnRef;

class K_EffectiveUpdaterViaRayleighQuotientTest : public ::testing::Test {
 public:
  using SphericalHarmonicMock = NiceMock<system::moments::SphericalHarmonicMock>;
  using Vector = dealii::Vector<double>;

  static constexpr int total_groups_{ 2 };
  static constexpr int vector_size_{ 3 };
  const double initial_k_effective_{ 1.0235 };
  const double expected_k_effective_{ 0.4094 };
  std::array<Vector, total_groups_> current_moments_, previous_moments_;

  system::System test_system_ { .k_effective = initial_k_effective_, .total_groups = total_groups_ };

  SphericalHarmonicMock* current_moments_obs_ptr_;
  SphericalHarmonicMock* previous_moments_obs_ptr_;

  auto SetUp() -> void override;
};

auto K_EffectiveUpdaterViaRayleighQuotientTest::SetUp() -> void {
  for (int group = 0; group < total_groups_; ++group) {
    Vector current_group_moment(vector_size_), previous_group_moment(vector_size_);
    for (int i = 0; i < vector_size_; ++i) {
      if (group == 0) {
        current_group_moment[i] = (i + 1);
        previous_group_moment[i] = (i + 1 + vector_size_);
      } else {
        current_group_moment[i] = vector_size_ - i;
        previous_group_moment[i] = 2 * vector_size_ - i;
      }
    }
    current_moments_.at(group) = current_group_moment;
    previous_moments_.at(group) = previous_group_moment;
  }

  test_system_.current_moments = std::make_unique<SphericalHarmonicMock>();
  test_system_.previous_moments = std::make_unique<SphericalHarmonicMock>();
  current_moments_obs_ptr_ = dynamic_cast<SphericalHarmonicMock*>(test_system_.current_moments.get());
  previous_moments_obs_ptr_ = dynamic_cast<SphericalHarmonicMock*>(test_system_.previous_moments.get());

  for (int group = 0; group < total_groups_; ++group) {
    std::array<int, 3> index{ group, 0, 0 };
    ON_CALL(*current_moments_obs_ptr_, GetMoment(index)).WillByDefault(ReturnRef(current_moments_.at(group)));
    ON_CALL(*previous_moments_obs_ptr_, GetMoment(index)).WillByDefault(ReturnRef(previous_moments_.at(group)));
  }
}

TEST_F(K_EffectiveUpdaterViaRayleighQuotientTest, Calculate) {
  eigenvalue::k_effective::UpdaterViaRayleighQuotient test_updater;
  EXPECT_FALSE(test_updater.k_effective().has_value());

  for (int group = 0; group < total_groups_; ++group) {
    std::array<int, 3> index{ group, 0, 0 };
    EXPECT_CALL(*current_moments_obs_ptr_, GetMoment(index)).WillOnce(DoDefault());
    EXPECT_CALL(*previous_moments_obs_ptr_, GetMoment(index)).WillOnce(DoDefault());
  }

  auto calculated_k_effective = test_updater.CalculateK_Effective(test_system_);
  EXPECT_NEAR(calculated_k_effective, expected_k_effective_, 1e-8);
  ASSERT_TRUE(test_updater.k_effective().has_value());
  EXPECT_EQ(calculated_k_effective, test_updater.k_effective().value());
}

TEST_F(K_EffectiveUpdaterViaRayleighQuotientTest, ZeroCurrentFlux) {
  eigenvalue::k_effective::UpdaterViaRayleighQuotient test_updater;
  EXPECT_FALSE(test_updater.k_effective().has_value());

  Vector zero_flux(vector_size_);

  for (int group = 0; group < total_groups_; ++group) {
    std::array<int, 3> index{ group, 0, 0 };
    EXPECT_CALL(*current_moments_obs_ptr_, GetMoment(index)).WillOnce(ReturnRef(zero_flux));
    EXPECT_CALL(*previous_moments_obs_ptr_, GetMoment(index)).WillOnce(DoDefault());
  }

  auto calculated_k_effective = test_updater.CalculateK_Effective(test_system_);
  EXPECT_NEAR(calculated_k_effective, 0, 1e-8);
  ASSERT_TRUE(test_updater.k_effective().has_value());
  EXPECT_EQ(calculated_k_effective, test_updater.k_effective().value());
}

TEST_F(K_EffectiveUpdaterViaRayleighQuotientTest, ZeroPreviousFlux) {
  eigenvalue::k_effective::UpdaterViaRayleighQuotient test_updater;
  EXPECT_FALSE(test_updater.k_effective().has_value());

  Vector zero_flux(vector_size_);

  for (int group = 0; group < total_groups_; ++group) {
    std::array<int, 3> index{ group, 0, 0 };
    EXPECT_CALL(*current_moments_obs_ptr_, GetMoment(index)).WillOnce(DoDefault());
    EXPECT_CALL(*previous_moments_obs_ptr_, GetMoment(index)).WillOnce(ReturnRef(zero_flux));
  }

  auto calculated_k_effective = test_updater.CalculateK_Effective(test_system_);
  EXPECT_NEAR(calculated_k_effective, initial_k_effective_, 1e-8);
  ASSERT_TRUE(test_updater.k_effective().has_value());
  EXPECT_EQ(calculated_k_effective, test_updater.k_effective().value());
}

} // namespace
<commit_msg>fixed system.hpp name in updater_via_rayleigh_quotient_test.cpp<commit_after>#include "eigenvalue/k_effective/updater_via_rayleigh_quotient.hpp"

#include "system/system.hpp"
#include "system/moments/tests/spherical_harmonic_mock.h"
#include "test_helpers/gmock_wrapper.h"

namespace  {

using namespace bart;

using ::testing::DoDefault, ::testing::NiceMock, ::testing::ReturnRef;

class K_EffectiveUpdaterViaRayleighQuotientTest : public ::testing::Test {
 public:
  using SphericalHarmonicMock = NiceMock<system::moments::SphericalHarmonicMock>;
  using Vector = dealii::Vector<double>;

  static constexpr int total_groups_{ 2 };
  static constexpr int vector_size_{ 3 };
  const double initial_k_effective_{ 1.0235 };
  const double expected_k_effective_{ 0.4094 };
  std::array<Vector, total_groups_> current_moments_, previous_moments_;

  system::System test_system_ { .k_effective = initial_k_effective_, .total_groups = total_groups_ };

  SphericalHarmonicMock* current_moments_obs_ptr_;
  SphericalHarmonicMock* previous_moments_obs_ptr_;

  auto SetUp() -> void override;
};

auto K_EffectiveUpdaterViaRayleighQuotientTest::SetUp() -> void {
  for (int group = 0; group < total_groups_; ++group) {
    Vector current_group_moment(vector_size_), previous_group_moment(vector_size_);
    for (int i = 0; i < vector_size_; ++i) {
      if (group == 0) {
        current_group_moment[i] = (i + 1);
        previous_group_moment[i] = (i + 1 + vector_size_);
      } else {
        current_group_moment[i] = vector_size_ - i;
        previous_group_moment[i] = 2 * vector_size_ - i;
      }
    }
    current_moments_.at(group) = current_group_moment;
    previous_moments_.at(group) = previous_group_moment;
  }

  test_system_.current_moments = std::make_unique<SphericalHarmonicMock>();
  test_system_.previous_moments = std::make_unique<SphericalHarmonicMock>();
  current_moments_obs_ptr_ = dynamic_cast<SphericalHarmonicMock*>(test_system_.current_moments.get());
  previous_moments_obs_ptr_ = dynamic_cast<SphericalHarmonicMock*>(test_system_.previous_moments.get());

  for (int group = 0; group < total_groups_; ++group) {
    std::array<int, 3> index{ group, 0, 0 };
    ON_CALL(*current_moments_obs_ptr_, GetMoment(index)).WillByDefault(ReturnRef(current_moments_.at(group)));
    ON_CALL(*previous_moments_obs_ptr_, GetMoment(index)).WillByDefault(ReturnRef(previous_moments_.at(group)));
  }
}

TEST_F(K_EffectiveUpdaterViaRayleighQuotientTest, Calculate) {
  eigenvalue::k_effective::UpdaterViaRayleighQuotient test_updater;
  EXPECT_FALSE(test_updater.k_effective().has_value());

  for (int group = 0; group < total_groups_; ++group) {
    std::array<int, 3> index{ group, 0, 0 };
    EXPECT_CALL(*current_moments_obs_ptr_, GetMoment(index)).WillOnce(DoDefault());
    EXPECT_CALL(*previous_moments_obs_ptr_, GetMoment(index)).WillOnce(DoDefault());
  }

  auto calculated_k_effective = test_updater.CalculateK_Effective(test_system_);
  EXPECT_NEAR(calculated_k_effective, expected_k_effective_, 1e-8);
  ASSERT_TRUE(test_updater.k_effective().has_value());
  EXPECT_EQ(calculated_k_effective, test_updater.k_effective().value());
}

TEST_F(K_EffectiveUpdaterViaRayleighQuotientTest, ZeroCurrentFlux) {
  eigenvalue::k_effective::UpdaterViaRayleighQuotient test_updater;
  EXPECT_FALSE(test_updater.k_effective().has_value());

  Vector zero_flux(vector_size_);

  for (int group = 0; group < total_groups_; ++group) {
    std::array<int, 3> index{ group, 0, 0 };
    EXPECT_CALL(*current_moments_obs_ptr_, GetMoment(index)).WillOnce(ReturnRef(zero_flux));
    EXPECT_CALL(*previous_moments_obs_ptr_, GetMoment(index)).WillOnce(DoDefault());
  }

  auto calculated_k_effective = test_updater.CalculateK_Effective(test_system_);
  EXPECT_NEAR(calculated_k_effective, 0, 1e-8);
  ASSERT_TRUE(test_updater.k_effective().has_value());
  EXPECT_EQ(calculated_k_effective, test_updater.k_effective().value());
}

TEST_F(K_EffectiveUpdaterViaRayleighQuotientTest, ZeroPreviousFlux) {
  eigenvalue::k_effective::UpdaterViaRayleighQuotient test_updater;
  EXPECT_FALSE(test_updater.k_effective().has_value());

  Vector zero_flux(vector_size_);

  for (int group = 0; group < total_groups_; ++group) {
    std::array<int, 3> index{ group, 0, 0 };
    EXPECT_CALL(*current_moments_obs_ptr_, GetMoment(index)).WillOnce(DoDefault());
    EXPECT_CALL(*previous_moments_obs_ptr_, GetMoment(index)).WillOnce(ReturnRef(zero_flux));
  }

  auto calculated_k_effective = test_updater.CalculateK_Effective(test_system_);
  EXPECT_NEAR(calculated_k_effective, initial_k_effective_, 1e-8);
  ASSERT_TRUE(test_updater.k_effective().has_value());
  EXPECT_EQ(calculated_k_effective, test_updater.k_effective().value());
}

} // namespace
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qcontactactionservicemanager_p.h"

#include "qcontactaction.h"
#include "qcontactactiondescriptor.h"
#include "qcontactactionfactory.h"

#include "qservicemanager.h"

#include <QMutexLocker>

QTM_BEGIN_NAMESPACE

Q_GLOBAL_STATIC(QContactActionServiceManager, contactActionServiceManagerInstance)
Q_EXPORT_PLUGIN2(qtcontacts_serviceactionmanager, QContactActionServiceManager);

/*!
  \internal
  \class QContactActionServiceManager
  This class uses the service framework to discover contact actions which are
  provided by third parties.  It is an implementation detail of QContactAction.
 */

QContactActionServiceManager* QContactActionServiceManager::instance()
{
    return contactActionServiceManagerInstance();
}

QContactActionServiceManager::QContactActionServiceManager()
    : QObject(), initLock(false)
{
}

QContactActionServiceManager::~QContactActionServiceManager()
{
    // we don't use qDeleteAll() because some factories produce more than one action descriptor.
    QList<QContactActionDescriptor> keys = m_actionFactoryHash.keys();
    QSet<QContactActionFactory*> deletedFactories;
    foreach (const QContactActionDescriptor& key, keys) {
        QContactActionFactory *curr = m_actionFactoryHash.value(key);
        if (!deletedFactories.contains(curr)) {
            deletedFactories.insert(curr);
            delete curr;
        }
    }
}

void QContactActionServiceManager::init()
{
    // XXX NOTE: should already be locked PRIOR to entering this function.
    if (!initLock) {
        initLock = true;
        // fill up our hashes
        QList<QServiceInterfaceDescriptor> sids = m_serviceManager.findInterfaces(); // all services, all interfaces.
        foreach (const QServiceInterfaceDescriptor& sid, sids) {
            if (sid.interfaceName() == QContactActionFactory::InterfaceName) {
                QContactActionFactory* actionFactory = qobject_cast<QContactActionFactory*>(m_serviceManager.loadInterface(sid));
                if (actionFactory) {
                    // if we cannot get the action factory from the service manager, then we don't add it to our hash.
                    QList<QContactActionDescriptor> descriptors = actionFactory->actionDescriptors();
                    foreach (const QContactActionDescriptor& ad, descriptors) {
                        m_descriptorHash.insert(ad.actionName(), ad); // multihash insert.
                        m_actionFactoryHash.insert(ad, actionFactory);
                    }
                }
            }
        }

        // and listen for signals.
        connect(&m_serviceManager, SIGNAL(serviceAdded(QString, QService::Scope)), this, SLOT(serviceAdded(QString)));
        connect(&m_serviceManager, SIGNAL(serviceRemoved(QString, QService::Scope)), this, SLOT(serviceRemoved(QString)));
    }
}

QHash<QContactActionDescriptor, QContactActionFactory*> QContactActionServiceManager::actionFactoryHash()
{
    QMutexLocker locker(&m_instanceMutex);
    init();
    return m_actionFactoryHash;
}

QMultiHash<QString, QContactActionDescriptor> QContactActionServiceManager::descriptorHash()
{
    QMutexLocker locker(&m_instanceMutex);
    init();
    return m_descriptorHash;
}

void QContactActionServiceManager::serviceAdded(const QString& serviceName)
{
    QMutexLocker locker(&m_instanceMutex);
    QList<QServiceInterfaceDescriptor> sids = m_serviceManager.findInterfaces(serviceName);
    foreach (const QServiceInterfaceDescriptor& sid, sids) {
        if (sid.interfaceName().startsWith(QString(QLatin1String("com.nokia.qt.mobility.contacts")))) {
            QContactActionFactory* actionFactory = qobject_cast<QContactActionFactory*>(m_serviceManager.loadInterface(sid));
            if (actionFactory) {
                // if we cannot get the action factory from the service manager, then we don't add it to our hash.
                QList<QContactActionDescriptor> descriptors = actionFactory->actionDescriptors();
                foreach (const QContactActionDescriptor& ad, descriptors) {
                    m_descriptorHash.insert(ad.actionName(), ad); // multihash insert.
                    m_actionFactoryHash.insert(ad, actionFactory);
                }
            }
        }
    }
}

void QContactActionServiceManager::serviceRemoved(const QString& serviceName)
{
    QMutexLocker locker(&m_instanceMutex);
    QList<QServiceInterfaceDescriptor> sids = m_serviceManager.findInterfaces(serviceName);
    foreach (const QServiceInterfaceDescriptor& sid, sids) {
        if (sid.interfaceName().startsWith(QString(QLatin1String("com.nokia.qt.mobility.contacts")))) {
            QList<QContactActionDescriptor> cads = m_actionFactoryHash.keys();
            foreach (const QContactActionDescriptor& cad, cads) {
                if (cad.serviceName() != serviceName)
                    continue;
                delete m_actionFactoryHash.value(cad);
                m_actionFactoryHash.remove(cad);
                m_descriptorHash.remove(cad.actionName(), cad);
            }
        }
    }
}

#include "moc_qcontactactionservicemanager_p.cpp"

QTM_END_NAMESPACE
<commit_msg>Ensure that contact action factory services are provided in-process<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qcontactactionservicemanager_p.h"

#include "qcontactaction.h"
#include "qcontactactiondescriptor.h"
#include "qcontactactionfactory.h"

#include "qservicemanager.h"

#include <QMutexLocker>

QTM_BEGIN_NAMESPACE

Q_GLOBAL_STATIC(QContactActionServiceManager, contactActionServiceManagerInstance)
Q_EXPORT_PLUGIN2(qtcontacts_serviceactionmanager, QContactActionServiceManager);

/*!
  \internal
  \class QContactActionServiceManager
  This class uses the service framework to discover contact actions which are
  provided by third parties.  It is an implementation detail of QContactAction.
 */

QContactActionServiceManager* QContactActionServiceManager::instance()
{
    return contactActionServiceManagerInstance();
}

QContactActionServiceManager::QContactActionServiceManager()
    : QObject(), initLock(false)
{
}

QContactActionServiceManager::~QContactActionServiceManager()
{
    // we don't use qDeleteAll() because some factories produce more than one action descriptor.
    QList<QContactActionDescriptor> keys = m_actionFactoryHash.keys();
    QSet<QContactActionFactory*> deletedFactories;
    foreach (const QContactActionDescriptor& key, keys) {
        QContactActionFactory *curr = m_actionFactoryHash.value(key);
        if (!deletedFactories.contains(curr)) {
            deletedFactories.insert(curr);
            delete curr;
        }
    }
}

void QContactActionServiceManager::init()
{
    // XXX NOTE: should already be locked PRIOR to entering this function.
    if (!initLock) {
        initLock = true;
        // fill up our hashes
        QList<QServiceInterfaceDescriptor> sids = m_serviceManager.findInterfaces(); // all services, all interfaces.
        foreach (const QServiceInterfaceDescriptor& sid, sids) {
            if (sid.interfaceName() == QContactActionFactory::InterfaceName) {
                if (static_cast<QService::Type>(sid.attribute(QServiceInterfaceDescriptor::ServiceType).toInt()) != QService::Plugin) {
                    continue; // we don't allow IPC contact action factories.
                }
                QContactActionFactory* actionFactory = qobject_cast<QContactActionFactory*>(m_serviceManager.loadInterface(sid));
                if (actionFactory) {
                    // if we cannot get the action factory from the service manager, then we don't add it to our hash.
                    QList<QContactActionDescriptor> descriptors = actionFactory->actionDescriptors();
                    foreach (const QContactActionDescriptor& ad, descriptors) {
                        m_descriptorHash.insert(ad.actionName(), ad); // multihash insert.
                        m_actionFactoryHash.insert(ad, actionFactory);
                    }
                }
            }
        }

        // and listen for signals.
        connect(&m_serviceManager, SIGNAL(serviceAdded(QString, QService::Scope)), this, SLOT(serviceAdded(QString)));
        connect(&m_serviceManager, SIGNAL(serviceRemoved(QString, QService::Scope)), this, SLOT(serviceRemoved(QString)));
    }
}

QHash<QContactActionDescriptor, QContactActionFactory*> QContactActionServiceManager::actionFactoryHash()
{
    QMutexLocker locker(&m_instanceMutex);
    init();
    return m_actionFactoryHash;
}

QMultiHash<QString, QContactActionDescriptor> QContactActionServiceManager::descriptorHash()
{
    QMutexLocker locker(&m_instanceMutex);
    init();
    return m_descriptorHash;
}

void QContactActionServiceManager::serviceAdded(const QString& serviceName)
{
    QMutexLocker locker(&m_instanceMutex);
    QList<QServiceInterfaceDescriptor> sids = m_serviceManager.findInterfaces(serviceName);
    foreach (const QServiceInterfaceDescriptor& sid, sids) {
        if (sid.interfaceName() == QContactActionFactory::InterfaceName) {
            if (static_cast<QService::Type>(sid.attribute(QServiceInterfaceDescriptor::ServiceType).toInt()) != QService::Plugin) {
                continue; // we don't allow IPC contact action factories.
            }
            QContactActionFactory* actionFactory = qobject_cast<QContactActionFactory*>(m_serviceManager.loadInterface(sid));
            if (actionFactory) {
                // if we cannot get the action factory from the service manager, then we don't add it to our hash.
                QList<QContactActionDescriptor> descriptors = actionFactory->actionDescriptors();
                foreach (const QContactActionDescriptor& ad, descriptors) {
                    m_descriptorHash.insert(ad.actionName(), ad); // multihash insert.
                    m_actionFactoryHash.insert(ad, actionFactory);
                }
            }
        }
    }
}

void QContactActionServiceManager::serviceRemoved(const QString& serviceName)
{
    QMutexLocker locker(&m_instanceMutex);
    QList<QServiceInterfaceDescriptor> sids = m_serviceManager.findInterfaces(serviceName);
    foreach (const QServiceInterfaceDescriptor& sid, sids) {
        if (sid.interfaceName() == QContactActionFactory::InterfaceName) {
            if (static_cast<QService::Type>(sid.attribute(QServiceInterfaceDescriptor::ServiceType).toInt()) != QService::Plugin) {
                continue; // we don't allow IPC contact action factories.
            }
            QList<QContactActionDescriptor> cads = m_actionFactoryHash.keys();
            foreach (const QContactActionDescriptor& cad, cads) {
                if (cad.serviceName() != serviceName)
                    continue;
                delete m_actionFactoryHash.value(cad);
                m_actionFactoryHash.remove(cad);
                m_descriptorHash.remove(cad.actionName(), cad);
            }
        }
    }
}

#include "moc_qcontactactionservicemanager_p.cpp"

QTM_END_NAMESPACE
<|endoftext|>


<commit_before>#include <libdvid/DVIDNode.h>

#include <iostream>
#include <string>
#include <fstream>

#include <vector>
#include <tr1/unordered_map>
#include <tr1/unordered_set>

using std::cout; using std::endl;
using std::ifstream;

using std::string;
using std::tr1::unordered_map;
using std::tr1::unordered_set;
using std::vector;
using std::pair;
using std::make_pair;
using std::cin;

const char * USAGE = "<prog> <dvid-server> <uuid> <label name> <sparse file> <body ID>";
const char * HELP = "Program takes a sparse volume and loads it into DVID";

int read_int(ifstream& fin)
{
    char buffer[4]; // reading signed ints
    fin.read(buffer, 4);
    return *((int*) buffer);
}

int main(int argc, char** argv)
{
    if (argc != 6) {
        cout << USAGE << endl;
        cout << HELP << endl;
        exit(1);
    }

    // create DVID node accessor
    libdvid::DVIDServer server(argv[1]);
    libdvid::DVIDNode dvid_node(server, argv[2]);
    string label_name = string(argv[3]);

    ifstream fin(argv[4]);

    unsigned long long new_body_id = (unsigned long long)(atoi(argv[5]));

    // read sparse volume one at a time
    int num_stripes = read_int(fin);
    typedef vector<pair<int, int> > segments_t;
    typedef unordered_map<int, segments_t> segmentsets_t;
    typedef unordered_map<int, segmentsets_t > sparse_t;
    sparse_t plane2segments;

    for (int i = 0; i < num_stripes; ++i) {
        int z = read_int(fin);
        int y = read_int(fin);
        // will same z,y appear multiple times
        segments_t segment_list;
        int num_segments = read_int(fin);
        for (int j = 0; j < num_segments; ++j) {
            int x1 = read_int(fin);
            int x2 = read_int(fin);
            segment_list.push_back(make_pair(x1, x2));
        }
        plane2segments[z][y] = segment_list;
    }
    fin.close();

    libdvid::tuple channels; channels.push_back(0);
    channels.push_back(1); channels.push_back(2);
    // iterate each z, load appropriate slice of a given size, relabel sparsely
    for (sparse_t::iterator iter = plane2segments.begin(); iter != plane2segments.end(); ++iter) {
        // get bounds
        int maxy = 0;
        int miny = INT_MAX;
        int maxx = 0;
        int minx = INT_MAX;
        for (segmentsets_t::iterator iter2 = iter->second.begin(); iter2 != iter->second.end(); ++iter2) {
            if (iter2->first < miny) {
                miny = iter2->first;
            }
            if (iter2->first > maxy) {
                maxy = iter2->first;
            }
            segments_t& segment_list = iter2->second;

            for (int i = 0; i < segment_list.size(); ++i) {
                if (segment_list[i].first < minx) {
                    minx = segment_list[i].first;
                }
                if (segment_list[i].second > maxx) {
                    maxx = segment_list[i].second;
                }
            }
        }

        // create dvid size and start points (X, Y, Z)
        libdvid::tuple sizes; sizes.push_back(maxx-minx+1);
        sizes.push_back(maxy-miny+1); sizes.push_back(1);

        libdvid::tuple start; start.push_back(minx);
        start.push_back(miny); sizes.push_back(iter->first);

        // retrieve dvid slice
        libdvid::DVIDLabelPtr label_data;
        dvid_node.get_volume_roi(label_name, start, sizes, channels, label_data);

        unsigned long long* ldata_raw = label_data->get_raw();
        int width = maxx-minx+1;

        // rewrite body id in label data
        for (segmentsets_t::iterator iter2 = iter->second.begin(); iter2 != iter->second.end(); ++iter2) {
            segments_t& segment_list = iter2->second;
            int offset = (iter2->first - miny)*width;
            for (int i = 0; i < segment_list.size(); ++i) {
                for (int j = segment_list[i].first; j <= segment_list[i].second; ++j) {
                    ldata_raw[offset + (j-minx)] = new_body_id;
                }
            }
        }

        // write new volume back
        libdvid::BinaryDataPtr labelbin = libdvid::BinaryData::create_binary_data((char*)(ldata_raw),
                sizeof(unsigned long long)*(width)*(maxy-miny+1));

        dvid_node.write_volume_roi(label_name, start, sizes, channels, labelbin);
    }

    return 0;
}

<commit_msg>small bug fix and disabling throttling in load sparse<commit_after>#include <libdvid/DVIDNode.h>

#include <iostream>
#include <string>
#include <fstream>

#include <vector>
#include <tr1/unordered_map>
#include <tr1/unordered_set>

using std::cout; using std::endl;
using std::ifstream;

using std::string;
using std::tr1::unordered_map;
using std::tr1::unordered_set;
using std::vector;
using std::pair;
using std::make_pair;
using std::cin;

const char * USAGE = "<prog> <dvid-server> <uuid> <label name> <sparse file> <body ID>";
const char * HELP = "Program takes a sparse volume and loads it into DVID";

int read_int(ifstream& fin)
{
    char buffer[4]; // reading signed ints
    fin.read(buffer, 4);
    return *((int*) buffer);
}

int main(int argc, char** argv)
{
    if (argc != 6) {
        cout << USAGE << endl;
        cout << HELP << endl;
        exit(1);
    }

    // create DVID node accessor
    libdvid::DVIDServer server(argv[1]);
    libdvid::DVIDNode dvid_node(server, argv[2]);
    string label_name = string(argv[3]);

    ifstream fin(argv[4]);

    unsigned long long new_body_id = (unsigned long long)(atoi(argv[5]));

    // read sparse volume one at a time
    int num_stripes = read_int(fin);
    //cout << num_stripes << endl;
    typedef vector<pair<int, int> > segments_t;
    typedef unordered_map<int, segments_t> segmentsets_t;
    typedef unordered_map<int, segmentsets_t > sparse_t;
    sparse_t plane2segments;

    for (int i = 0; i < num_stripes; ++i) {
        int z = read_int(fin);
        int y = read_int(fin);
        //cout << z << " " << y << endl;
        // will same z,y appear multiple times
        segments_t segment_list;
        int num_segments = read_int(fin);
        for (int j = 0; j < num_segments; ++j) {
            int x1 = read_int(fin);
            int x2 = read_int(fin);
            segment_list.push_back(make_pair(x1, x2));
        }
        plane2segments[z][y] = segment_list;
    }
    fin.close();

    //return 0;
    libdvid::tuple channels; channels.push_back(0);
    channels.push_back(1); channels.push_back(2);
    // iterate each z, load appropriate slice of a given size, relabel sparsely
    for (sparse_t::iterator iter = plane2segments.begin(); iter != plane2segments.end(); ++iter) {
        // get bounds
        int maxy = 0;
        int miny = INT_MAX;
        int maxx = 0;
        int minx = INT_MAX;
        for (segmentsets_t::iterator iter2 = iter->second.begin(); iter2 != iter->second.end(); ++iter2) {
            if (iter2->first < miny) {
                miny = iter2->first;
            }
            if (iter2->first > maxy) {
                maxy = iter2->first;
            }
            segments_t& segment_list = iter2->second;

            for (int i = 0; i < segment_list.size(); ++i) {
                if (segment_list[i].first < minx) {
                    minx = segment_list[i].first;
                }
                if (segment_list[i].second > maxx) {
                    maxx = segment_list[i].second;
                }
            }
        }
        //cout << "z: " << iter->first << " y: " << miny << " x: " << minx << endl;
        //cout << maxx-minx+1 << "x" << maxy-miny+1 << "x1" << endl;

        // create dvid size and start points (X, Y, Z)
        libdvid::tuple sizes; sizes.push_back(maxx-minx+1);
        sizes.push_back(maxy-miny+1); sizes.push_back(1);

        libdvid::tuple start; start.push_back(minx);
        start.push_back(miny); start.push_back(iter->first);

        // retrieve dvid slice
        libdvid::DVIDLabelPtr label_data;
        dvid_node.get_volume_roi(label_name, start, sizes, channels, label_data, false);

        unsigned long long* ldata_raw = label_data->get_raw();
        int width = maxx-minx+1;

        // rewrite body id in label data
        for (segmentsets_t::iterator iter2 = iter->second.begin(); iter2 != iter->second.end(); ++iter2) {
            segments_t& segment_list = iter2->second;
            int offset = (iter2->first - miny)*width;
            for (int i = 0; i < segment_list.size(); ++i) {
                for (int j = segment_list[i].first; j <= segment_list[i].second; ++j) {
                    ldata_raw[offset + (j-minx)] = new_body_id;
                }
            }
        }

        // write new volume back
        libdvid::BinaryDataPtr labelbin = libdvid::BinaryData::create_binary_data((char*)(ldata_raw),
                sizeof(unsigned long long)*(width)*(maxy-miny+1));

        dvid_node.write_volume_roi(label_name, start, sizes, channels, labelbin, false);
    }

    return 0;
}

<|endoftext|>


<commit_before>// REQUIRES: x86-registered-target
// RUN: %clang_cc1 -triple x86_64-apple-darwin10  -g -fstandalone-debug -S -mllvm -generate-dwarf-pub-sections=Enable %s -o - | FileCheck %s

// FIXME: This testcase shouldn't rely on assembly emission.
//CHECK: Lpubtypes_begin[[SECNUM:[0-9]:]]
//CHECK:         .asciz   "G"
//CHECK-NEXT:    .long   0
//CHECK-NEXT: Lpubtypes_end[[SECNUM]]

class G {
public:
  void foo();
};

void G::foo() {
}
<commit_msg>DebugInfo: Fix test for LLVM change r203619<commit_after>// REQUIRES: x86-registered-target
// RUN: %clang_cc1 -triple x86_64-apple-darwin10  -g -fstandalone-debug -S -mllvm -generate-dwarf-pub-sections=Enable %s -o - | FileCheck %s

// FIXME: This testcase shouldn't rely on assembly emission.
//CHECK: LpubTypes_begin[[SECNUM:[0-9]:]]
//CHECK:         .asciz   "G"
//CHECK-NEXT:    .long   0
//CHECK-NEXT: LpubTypes_end[[SECNUM]]

class G {
public:
  void foo();
};

void G::foo() {
}
<|endoftext|>


<commit_before>// RUN: %clang_cc1 -std=c++17 -fprofile-instrument=clang -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -main-file-name default-method.cpp -w %s | FileCheck %s -implicit-check-not="->"

namespace PR39822 {
  struct unique_ptr {
    unique_ptr &operator=(unique_ptr &);
  };

  class foo {
    foo &operator=(foo &);
    unique_ptr convertable_values_[2];
  };

  // CHECK: _ZN7PR398223fooaSERS0_:
  // CHECK-NEXT: File 0, [[@LINE+1]]:28 -> [[@LINE+1]]:29 = #0
  foo &foo::operator=(foo &) = default;
} // namespace PR39822

<commit_msg>[Coverage] Specify the Itanium ABI triple for a C++ test<commit_after>// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++17 -fprofile-instrument=clang -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -main-file-name default-method.cpp -w %s | FileCheck %s -implicit-check-not="->"

namespace PR39822 {
  struct unique_ptr {
    unique_ptr &operator=(unique_ptr &);
  };

  class foo {
    foo &operator=(foo &);
    unique_ptr convertable_values_[2];
  };

  // CHECK: _ZN7PR398223fooaSERS0_:
  // CHECK-NEXT: File 0, [[@LINE+1]]:28 -> [[@LINE+1]]:29 = #0
  foo &foo::operator=(foo &) = default;
} // namespace PR39822

<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/logging.h"
#include "views/window/client_view.h"
#if defined(OS_LINUX)
#include "views/window/hit_test.h"
#endif
#include "views/window/window.h"
#include "views/window/window_delegate.h"

namespace views {

///////////////////////////////////////////////////////////////////////////////
// ClientView, public:

ClientView::ClientView(Window* window, View* contents_view)
    : window_(window),
      contents_view_(contents_view) {
}

int ClientView::NonClientHitTest(const gfx::Point& point) {
  return bounds().Contains(point) ? HTCLIENT : HTNOWHERE;
}

void ClientView::WindowClosing() {
  window_->GetDelegate()->WindowClosing();
}

///////////////////////////////////////////////////////////////////////////////
// ClientView, View overrides:

gfx::Size ClientView::GetPreferredSize() {
  // |contents_view_| is allowed to be NULL up until the point where this view
  // is attached to a Container.
  if (contents_view_)
    return contents_view_->GetPreferredSize();
  return gfx::Size();
}

void ClientView::Layout() {
  // |contents_view_| is allowed to be NULL up until the point where this view
  // is attached to a Container.
  if (contents_view_)
    contents_view_->SetBounds(0, 0, width(), height());
}

void ClientView::ViewHierarchyChanged(bool is_add, View* parent, View* child) {
  if (is_add && child == this) {
    DCHECK(GetWidget());
    DCHECK(contents_view_); // |contents_view_| must be valid now!
    AddChildView(contents_view_);
  }
}

void ClientView::DidChangeBounds(const gfx::Rect& previous,
                                 const gfx::Rect& current) {
  // Overridden to do nothing. The NonClientView manually calls Layout on the
  // ClientView when it is itself laid out, see comment in
  // NonClientView::Layout.
}

bool ClientView::GetAccessibleRole(AccessibilityTypes::Role* role) {
  *role = AccessibilityTypes::ROLE_CLIENT;
  return true;
}

}  // namespace views
<commit_msg>Fix focus traversal order in dialogs. In a dialog, the contents view is added after the buttons have been added. That would mess up the focus traversal order. The problem was particularly visible in the basic auth dialog. This CL ensures the contents is added as the first view so the focus chain is right.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/logging.h"
#include "views/window/client_view.h"
#if defined(OS_LINUX)
#include "views/window/hit_test.h"
#endif
#include "views/window/window.h"
#include "views/window/window_delegate.h"

namespace views {

///////////////////////////////////////////////////////////////////////////////
// ClientView, public:

ClientView::ClientView(Window* window, View* contents_view)
    : window_(window),
      contents_view_(contents_view) {
}

int ClientView::NonClientHitTest(const gfx::Point& point) {
  return bounds().Contains(point) ? HTCLIENT : HTNOWHERE;
}

void ClientView::WindowClosing() {
  window_->GetDelegate()->WindowClosing();
}

///////////////////////////////////////////////////////////////////////////////
// ClientView, View overrides:

gfx::Size ClientView::GetPreferredSize() {
  // |contents_view_| is allowed to be NULL up until the point where this view
  // is attached to a Container.
  if (contents_view_)
    return contents_view_->GetPreferredSize();
  return gfx::Size();
}

void ClientView::Layout() {
  // |contents_view_| is allowed to be NULL up until the point where this view
  // is attached to a Container.
  if (contents_view_)
    contents_view_->SetBounds(0, 0, width(), height());
}

void ClientView::ViewHierarchyChanged(bool is_add, View* parent, View* child) {
  if (is_add && child == this) {
    DCHECK(GetWidget());
    DCHECK(contents_view_); // |contents_view_| must be valid now!
    // Insert |contents_view_| at index 0 so it is first in the focus chain.
    // (the OK/Cancel buttons are inserted before contents_view_)
    AddChildView(0, contents_view_);
  }
}

void ClientView::DidChangeBounds(const gfx::Rect& previous,
                                 const gfx::Rect& current) {
  // Overridden to do nothing. The NonClientView manually calls Layout on the
  // ClientView when it is itself laid out, see comment in
  // NonClientView::Layout.
}

bool ClientView::GetAccessibleRole(AccessibilityTypes::Role* role) {
  *role = AccessibilityTypes::ROLE_CLIENT;
  return true;
}

}  // namespace views
<|endoftext|>


<commit_before>/**
 *  Copyright (c) 2014-present, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under both the Apache 2.0 license (found in the
 *  LICENSE file in the root directory of this source tree) and the GPLv2 (found
 *  in the COPYING file in the root directory of this source tree).
 *  You may select, at your option, one of the above-listed licenses.
 */

#include <asm/unistd_64.h>

#include <osquery/logger.h>
#include <osquery/registry_factory.h>
#include <osquery/sql.h>

#include "osquery/tables/events/linux/process_events.h"

namespace osquery {

FLAG(bool,
     audit_allow_process_events,
     true,
     "Allow the audit publisher to install process event monitoring rules");

// Depend on the external getUptime table method.
namespace tables {
extern long getUptime();
}

REGISTER(AuditProcessEventSubscriber, "event_subscriber", "process_events");

Status AuditProcessEventSubscriber::init() {
  if (!FLAGS_audit_allow_process_events) {
    return Status(1, "Subscriber disabled via configuration");
  }

  auto sc = createSubscriptionContext();
  subscribe(&AuditProcessEventSubscriber::Callback, sc);

  return Status(0, "OK");
}

Status AuditProcessEventSubscriber::Callback(const ECRef& ec, const SCRef& sc) {
  std::vector<Row> emitted_row_list;
  auto status = ProcessEvents(emitted_row_list, ec->audit_events);
  if (!status.ok()) {
    return status;
  }

  addBatch(emitted_row_list);
  return Status(0, "Ok");
}

Status AuditProcessEventSubscriber::ProcessEvents(
    std::vector<Row>& emitted_row_list,
    const std::vector<AuditEvent>& event_list) noexcept {
  // clang-format off
  /*
    1300 audit(1502125323.756:6): arch=c000003e syscall=59 success=yes exit=0 a0=23eb8e0 a1=23ebbc0 a2=23c9860 a3=7ffe18d32ed0 items=2 ppid=6882 pid=7841 auid=1000 uid=1000 gid=1000 euid=1000 suid=1000 fsuid=1000 egid=1000 sgid=1000 fsgid=1000 tty=pts1 ses=2 comm="sh" exe="/usr/bin/bash" subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 key=(null)
    1309 audit(1502125323.756:6): argc=1 a0="sh"
    1307 audit(1502125323.756:6):  cwd="/home/alessandro"
    1302 audit(1502125323.756:6): item=0 name="/usr/bin/sh" inode=18867 dev=fd:00 mode=0100755 ouid=0 ogid=0 rdev=00:00 obj=system_u:object_r:shell_exec_t:s0 objtype=NORMAL
    1302 audit(1502125323.756:6): item=1 name="/lib64/ld-linux-x86-64.so.2" inode=33604032 dev=fd:00 mode=0100755 ouid=0 ogid=0 rdev=00:00 obj=system_u:object_r:ld_so_t:s0 objtype=NORMAL
    1320 audit(1502125323.756:6):
  */
  // clang-format on

  emitted_row_list.clear();

  emitted_row_list.reserve(event_list.size());

  for (const auto& event : event_list) {
    if (event.type != AuditEvent::Type::Syscall) {
      continue;
    }

    const auto& event_data = boost::get<SyscallAuditEventData>(event.data);
    if (event_data.syscall_number != __NR_execve) {
      continue;
    }

    const AuditEventRecord* syscall_event_record =
        GetEventRecord(event, AUDIT_SYSCALL);
    if (syscall_event_record == nullptr) {
      VLOG(1) << "Malformed AUDIT_SYSCALL event";
      continue;
    }

    const AuditEventRecord* execve_event_record =
        GetEventRecord(event, AUDIT_EXECVE);
    if (execve_event_record == nullptr) {
      VLOG(1) << "Malformed AUDIT_EXECVE event";
      continue;
    }

    const AuditEventRecord* first_path_event_record =
        GetEventRecord(event, AUDIT_PATH);
    if (first_path_event_record == nullptr) {
      VLOG(1) << "Malformed AUDIT_PATH event";
      continue;
    }

    Row row = {};

    CopyFieldFromMap(row, syscall_event_record->fields, "auid", "0");
    CopyFieldFromMap(row, syscall_event_record->fields, "pid", "0");
    CopyFieldFromMap(row, syscall_event_record->fields, "ppid", "0");
    CopyFieldFromMap(row, syscall_event_record->fields, "uid", "0");
    CopyFieldFromMap(row, syscall_event_record->fields, "euid", "0");
    CopyFieldFromMap(row, syscall_event_record->fields, "gid", "0");
    CopyFieldFromMap(row, syscall_event_record->fields, "egid", "0");

    std::string field_value;
    GetStringFieldFromMap(field_value, syscall_event_record->fields, "exe", "");
    row["path"] = DecodeAuditPathValues(field_value);

    auto qd = SQL::selectAllFrom("file", "path", EQUALS, row.at("path"));
    if (qd.size() == 1) {
      row["ctime"] = qd.front().at("ctime");
      row["atime"] = qd.front().at("atime");
      row["mtime"] = qd.front().at("mtime");
      row["btime"] = "0";
    }

    row["overflows"] = "";
    row["env_size"] = "0";
    row["env_count"] = "0";
    row["env"] = "";
    row["uptime"] = std::to_string(tables::getUptime());

    // build the command line from the AUDIT_EXECVE record
    row["cmdline"] = "";

    for (const auto& arg : execve_event_record->fields) {
      if (arg.first == "argc") {
        continue;
      }

      // Amalgamate all the "arg*" fields.
      if (row.at("cmdline").size() > 0) {
        row["cmdline"] += " ";
      }

      row["cmdline"] += DecodeAuditPathValues(arg.second);
    }

    // There may be a better way to calculate actual size from audit.
    // Then an overflow could be calculated/determined based on
    // actual/expected.
    row["cmdline_size"] = std::to_string(row.at("cmdline").size());

    // Get the remaining data from the first AUDIT_PATH record
    CopyFieldFromMap(row, first_path_event_record->fields, "mode", "");
    GetStringFieldFromMap(
        row["owner_uid"], first_path_event_record->fields, "ouid", "0");
    GetStringFieldFromMap(
        row["owner_gid"], first_path_event_record->fields, "ogid", "0");

    // Parent is currently not supported on Linux.
    row["parent"] = "-1";

    emitted_row_list.push_back(row);
  }

  return Status(0, "Ok");
}

const std::set<int>& AuditProcessEventSubscriber::GetSyscallSet() noexcept {
  static const std::set<int> syscall_set = {__NR_execve};
  return syscall_set;
}
} // namespace osquery
<commit_msg>Add ppid and cwd field for each new created process (#4784)<commit_after>/**
 *  Copyright (c) 2014-present, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under both the Apache 2.0 license (found in the
 *  LICENSE file in the root directory of this source tree) and the GPLv2 (found
 *  in the COPYING file in the root directory of this source tree).
 *  You may select, at your option, one of the above-listed licenses.
 */

#include <asm/unistd_64.h>

#include <osquery/logger.h>
#include <osquery/registry_factory.h>
#include <osquery/sql.h>

#include "osquery/tables/events/linux/process_events.h"

namespace osquery {

FLAG(bool,
     audit_allow_process_events,
     true,
     "Allow the audit publisher to install process event monitoring rules");

// Depend on the external getUptime table method.
namespace tables {
extern long getUptime();
}

REGISTER(AuditProcessEventSubscriber, "event_subscriber", "process_events");

Status AuditProcessEventSubscriber::init() {
  if (!FLAGS_audit_allow_process_events) {
    return Status(1, "Subscriber disabled via configuration");
  }

  auto sc = createSubscriptionContext();
  subscribe(&AuditProcessEventSubscriber::Callback, sc);

  return Status(0, "OK");
}

Status AuditProcessEventSubscriber::Callback(const ECRef& ec, const SCRef& sc) {
  std::vector<Row> emitted_row_list;
  auto status = ProcessEvents(emitted_row_list, ec->audit_events);
  if (!status.ok()) {
    return status;
  }

  addBatch(emitted_row_list);
  return Status(0, "Ok");
}

Status AuditProcessEventSubscriber::ProcessEvents(
    std::vector<Row>& emitted_row_list,
    const std::vector<AuditEvent>& event_list) noexcept {
  // clang-format off
  /*
    1300 audit(1502125323.756:6): arch=c000003e syscall=59 success=yes exit=0 a0=23eb8e0 a1=23ebbc0 a2=23c9860 a3=7ffe18d32ed0 items=2 ppid=6882 pid=7841 auid=1000 uid=1000 gid=1000 euid=1000 suid=1000 fsuid=1000 egid=1000 sgid=1000 fsgid=1000 tty=pts1 ses=2 comm="sh" exe="/usr/bin/bash" subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 key=(null)
    1309 audit(1502125323.756:6): argc=1 a0="sh"
    1307 audit(1502125323.756:6):  cwd="/home/alessandro"
    1302 audit(1502125323.756:6): item=0 name="/usr/bin/sh" inode=18867 dev=fd:00 mode=0100755 ouid=0 ogid=0 rdev=00:00 obj=system_u:object_r:shell_exec_t:s0 objtype=NORMAL
    1302 audit(1502125323.756:6): item=1 name="/lib64/ld-linux-x86-64.so.2" inode=33604032 dev=fd:00 mode=0100755 ouid=0 ogid=0 rdev=00:00 obj=system_u:object_r:ld_so_t:s0 objtype=NORMAL
    1320 audit(1502125323.756:6):
  */
  // clang-format on

  emitted_row_list.clear();

  emitted_row_list.reserve(event_list.size());

  for (const auto& event : event_list) {
    if (event.type != AuditEvent::Type::Syscall) {
      continue;
    }

    const auto& event_data = boost::get<SyscallAuditEventData>(event.data);
    if (event_data.syscall_number != __NR_execve) {
      continue;
    }

    const AuditEventRecord* syscall_event_record =
        GetEventRecord(event, AUDIT_SYSCALL);
    if (syscall_event_record == nullptr) {
      VLOG(1) << "Malformed AUDIT_SYSCALL event";
      continue;
    }

    const AuditEventRecord* execve_event_record =
        GetEventRecord(event, AUDIT_EXECVE);
    if (execve_event_record == nullptr) {
      VLOG(1) << "Malformed AUDIT_EXECVE event";
      continue;
    }

    const AuditEventRecord* first_path_event_record =
        GetEventRecord(event, AUDIT_PATH);
    if (first_path_event_record == nullptr) {
      VLOG(1) << "Malformed AUDIT_PATH event";
      continue;
    }

    const AuditEventRecord* cwd_event_record = GetEventRecord(event, AUDIT_CWD);
    if (cwd_event_record == nullptr) {
      VLOG(1) << "Malformed AUDIT_CWD event";
      continue;
    }

    Row row = {};

    CopyFieldFromMap(row, syscall_event_record->fields, "auid", "0");
    CopyFieldFromMap(row, syscall_event_record->fields, "pid", "0");
    CopyFieldFromMap(row, syscall_event_record->fields, "uid", "0");
    CopyFieldFromMap(row, syscall_event_record->fields, "euid", "0");
    CopyFieldFromMap(row, syscall_event_record->fields, "gid", "0");
    CopyFieldFromMap(row, syscall_event_record->fields, "egid", "0");
    CopyFieldFromMap(row, cwd_event_record->fields, "cwd", "0");

    std::uint64_t parent_process_id;
    GetIntegerFieldFromMap(
        parent_process_id, syscall_event_record->fields, "ppid");
    row["parent"] = std::to_string(parent_process_id);

    std::string field_value;
    GetStringFieldFromMap(field_value, syscall_event_record->fields, "exe", "");
    row["path"] = DecodeAuditPathValues(field_value);

    auto qd = SQL::selectAllFrom("file", "path", EQUALS, row.at("path"));
    if (qd.size() == 1) {
      row["ctime"] = qd.front().at("ctime");
      row["atime"] = qd.front().at("atime");
      row["mtime"] = qd.front().at("mtime");
      row["btime"] = "0";
    }

    row["overflows"] = "";
    row["env_size"] = "0";
    row["env_count"] = "0";
    row["env"] = "";
    row["uptime"] = std::to_string(tables::getUptime());

    // build the command line from the AUDIT_EXECVE record
    row["cmdline"] = "";

    for (const auto& arg : execve_event_record->fields) {
      if (arg.first == "argc") {
        continue;
      }

      // Amalgamate all the "arg*" fields.
      if (row.at("cmdline").size() > 0) {
        row["cmdline"] += " ";
      }

      row["cmdline"] += DecodeAuditPathValues(arg.second);
    }

    // There may be a better way to calculate actual size from audit.
    // Then an overflow could be calculated/determined based on
    // actual/expected.
    row["cmdline_size"] = std::to_string(row.at("cmdline").size());

    // Get the remaining data from the first AUDIT_PATH record
    CopyFieldFromMap(row, first_path_event_record->fields, "mode", "");
    GetStringFieldFromMap(
        row["owner_uid"], first_path_event_record->fields, "ouid", "0");
    GetStringFieldFromMap(
        row["owner_gid"], first_path_event_record->fields, "ogid", "0");

    emitted_row_list.push_back(row);
  }

  return Status(0, "Ok");
}

const std::set<int>& AuditProcessEventSubscriber::GetSyscallSet() noexcept {
  static const std::set<int> syscall_set = {__NR_execve};
  return syscall_set;
}
} // namespace osquery
<|endoftext|>


<commit_before>#include "objectives/noisy/genetic-noise/NonNoisyGeneticSource.hpp"

NonNoisyGeneticSource::NonNoisyGeneticSource() : GeneticNoiseSource() {};

Genome NonNoisyGeneticSource::addNoise(Genome * target) {
	return Genome(target);
}
<commit_msg>[NonNoisyGeneticSource]: Dropped unnecessary semicolon<commit_after>#include "objectives/noisy/genetic-noise/NonNoisyGeneticSource.hpp"

NonNoisyGeneticSource::NonNoisyGeneticSource() : GeneticNoiseSource() {}

Genome NonNoisyGeneticSource::addNoise(Genome * target) {
	return Genome(target);
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (ivan.frade@nokia.com)
**
** This file is part of the QtSparql module (not yet part of the Qt Toolkit).
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at ivan.frade@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qsparql_tracker_direct.h"
#include "qsparql_tracker_direct_p.h"

#include <qsparqlerror.h>
#include <qsparqlbinding.h>
#include <qsparqlquery.h>
#include <qsparqlresultrow.h>

#include <qcoreapplication.h>
#include <qvariant.h>
#include <qstringlist.h>
#include <qvector.h>

#include <qdebug.h>

QT_BEGIN_NAMESPACE

static void
async_cursor_next_callback( GObject *source_object,
                            GAsyncResult *result,
                            gpointer user_data)
{
    Q_UNUSED(source_object);
    QTrackerDirectResultPrivate *data = static_cast<QTrackerDirectResultPrivate*>(user_data);
    GError *error = NULL;
    gboolean active = tracker_sparql_cursor_next_finish(data->cursor, result, &error);

    if (error != NULL) {
        QSparqlError e(QString::fromLatin1(error ? error->message : "unknown error"));
        e.setType(QSparqlError::BackendError);
        data->setLastError(e);
        data->terminate();
        return;
    }

    if (!active) {
        if (data->q->isBool()) {
            data->setBoolValue(data->results.count() == 1
                                    && data->results[0].count() == 1
                                    && data->results[0].value(0).toString() == QLatin1String("1"));
        }

        data->terminate();
        return;
    }

    QSparqlResultRow resultRow;
    gint n_columns = tracker_sparql_cursor_get_n_columns(data->cursor);

    for (int i = 0; i < n_columns; i++) {
        // As Tracker doesn't return the variable names in the query yet, call
        // the variables $1, $2, $3.. as that is better than no names
        QString name = QString::fromLatin1("$%1").arg(i + 1);
        QString value = QString::fromUtf8(tracker_sparql_cursor_get_string(data->cursor, i, NULL));

        if (value.startsWith(QLatin1String("_:"))) {
            QSparqlBinding binding(name);
            binding.setBlankNodeLabel(value.mid(2));
            resultRow.append(binding);
        } else if (value.startsWith(QLatin1String("http:")) || value.startsWith(QLatin1String("urn:"))) {
            resultRow.append(QSparqlBinding(name, QUrl(value)));
        } else {
            resultRow.append(QSparqlBinding(name, value));
        }

    }

    data->results.append(resultRow);
    data->dataReady(data->results.count());
    tracker_sparql_cursor_next_async(data->cursor, NULL, async_cursor_next_callback, data);
}

static void
async_query_callback(   GObject *source_object,
                        GAsyncResult *result,
                        gpointer user_data)
{
    Q_UNUSED(source_object);
    QTrackerDirectResultPrivate *data = static_cast<QTrackerDirectResultPrivate*>(user_data);
    GError *error = NULL;
    data->cursor = tracker_sparql_connection_query_finish(data->driverPrivate->connection, result, &error);

    if (error != NULL || data->cursor == NULL) {
        QSparqlError e(QString::fromLatin1(error ? error->message : "unknown error"));
        e.setType(QSparqlError::StatementError);
        data->setLastError(e);
        data->terminate();
        return;
    }

    tracker_sparql_cursor_next_async(data->cursor, NULL, async_cursor_next_callback, data);
}

static void
async_update_callback( GObject *source_object,
                       GAsyncResult *result,
                       gpointer user_data)
{
    Q_UNUSED(source_object);
    QTrackerDirectResultPrivate *data = static_cast<QTrackerDirectResultPrivate*>(user_data);
    GError *error = NULL;
    tracker_sparql_connection_update_finish(data->driverPrivate->connection, result, &error);

    if (error != NULL) {
        QSparqlError e(QString::fromLatin1(error ? error->message : "unknown error"));
        e.setType(QSparqlError::StatementError);
        data->setLastError(e);
        data->terminate();
        return;
    }

    data->terminate();
}

QTrackerDirectResultPrivate::QTrackerDirectResultPrivate(QTrackerDirectResult* result, QTrackerDirectDriverPrivate *dpp)
: isFinished(false), loop(0), q(result), driverPrivate(dpp)
{
}

QTrackerDirectResultPrivate::~QTrackerDirectResultPrivate()
{
}

void QTrackerDirectResultPrivate::terminate()
{
    isFinished = true;
    q->emit finished();

    if (loop != 0)
        loop->exit();
}

void QTrackerDirectResultPrivate::setLastError(const QSparqlError& e)
{
    q->setLastError(e);
}

void QTrackerDirectResultPrivate::setBoolValue(bool v)
{
    q->setBoolValue(v);
}

void QTrackerDirectResultPrivate::dataReady(int totalCount)
{
    emit q->dataReady(totalCount);
}

QTrackerDirectResult::QTrackerDirectResult(QTrackerDirectDriverPrivate* p)
{
    d = new QTrackerDirectResultPrivate(this, p);
}

QTrackerDirectResult::~QTrackerDirectResult()
{
    delete d;
}

QTrackerDirectResult* QTrackerDirectDriver::exec(const QString& query,
                          QSparqlQuery::StatementType type)
{
    QTrackerDirectResult* res = new QTrackerDirectResult(d);
    res->setStatementType(type);

    switch (type) {
    case QSparqlQuery::AskStatement:
    case QSparqlQuery::SelectStatement:
    {
        tracker_sparql_connection_query_async(  d->connection,
                                                query.toLatin1().constData(),
                                                NULL,
                                                async_query_callback,
                                                res->d);
        break;
    }
    case QSparqlQuery::InsertStatement:
    case QSparqlQuery::DeleteStatement:
        tracker_sparql_connection_update_async( d->connection,
                                                query.toLatin1().constData(),
                                                0,
                                                NULL,
                                                async_update_callback,
                                                res->d);
    {
        break;
    }
    default:
        qWarning() << "Tracker backend: unsupported statement type";
        res->setLastError(QSparqlError(
                              QLatin1String("Unsupported statement type"),
                              QSparqlError::BackendError));
        break;
    }
    return res;
}

void QTrackerDirectResult::cleanup()
{
    setPos(QSparql::BeforeFirstRow);
}

bool QTrackerDirectResult::fetch(int i)
{
    if (i < 0) {
        setPos(QSparql::BeforeFirstRow);
        return false;
    }
    if (i >= d->results.size()) {
        setPos(QSparql::AfterLastRow);
        return false;
    }
    setPos(i);
    return true;
}

bool QTrackerDirectResult::fetchLast()
{
    if (d->results.count() == 0)
        return false;
    setPos(d->results.count() - 1);
    return true;
}

bool QTrackerDirectResult::fetchFirst()
{
    if (pos() == 0)
        return true;
    return fetch(0);
}

QVariant QTrackerDirectResult::data(int field) const
{
    if (field >= d->results[pos()].count() || field < 0) {
        qWarning() << "QTrackerDirectResult::data[" << pos() << "]: column" << field << "out of range";
        return QVariant();
    }

    return d->results[pos()].binding(field).value();
}

void QTrackerDirectResult::waitForFinished()
{
    if (d->isFinished)
        return;

    QEventLoop loop;
    d->loop = &loop;
    loop.exec();
    d->loop = 0;
}

bool QTrackerDirectResult::isFinished() const
{
//    if (d->watcher)
//        return d->watcher->isFinished();
    return true;
}

bool QTrackerDirectResult::isNull(int field) const
{
    Q_UNUSED(field);
    return false;
}

int QTrackerDirectResult::size() const
{
    return d->results.count();
}

QSparqlResultRow QTrackerDirectResult::resultRow() const
{
    QSparqlResultRow info;
    if (pos() < 0 || pos() >= d->results.count())
        return info;

    return d->results[pos()];
}

QTrackerDirectDriverPrivate::QTrackerDirectDriverPrivate()
{
}

QTrackerDirectDriverPrivate::~QTrackerDirectDriverPrivate()
{
}

QTrackerDirectDriver::QTrackerDirectDriver(QObject* parent)
    : QSparqlDriver(parent)
{
    d = new QTrackerDirectDriverPrivate();
    /* Initialize GLib type system */
    g_type_init();

}

QTrackerDirectDriver::~QTrackerDirectDriver()
{
    delete d;
}

bool QTrackerDirectDriver::hasFeature(QSparqlConnection::Feature f) const
{
    switch (f) {
    case QSparqlConnection::QuerySize:
        return true;
    case QSparqlConnection::AskQueries:
        return true;
    case QSparqlConnection::ConstructQueries:
        return false;
    case QSparqlConnection::UpdateQueries:
        return true;
    case QSparqlConnection::DefaultGraph:
        return true;
    }
    return false;
}

QAtomicInt connectionCounter = 0;

bool QTrackerDirectDriver::open(const QSparqlConnectionOptions& options)
{
    Q_UNUSED(options);

    if (isOpen())
        close();

    GError *error = NULL;
    d->connection = tracker_sparql_connection_get(&error);
    if (!d->connection) {
        qWarning("Couldn't obtain a direct connection to the Tracker store: %s",
                    error ? error->message : "unknown error");

        return false;
    }

    setOpen(true);
    setOpenError(false);

    return true;
}

void QTrackerDirectDriver::close()
{
    if (isOpen()) {
        setOpen(false);
        setOpenError(false);
    }
}

QT_END_NAMESPACE
<commit_msg>* Call g_object_unref() on the tracker connection in the driver close() method<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (ivan.frade@nokia.com)
**
** This file is part of the QtSparql module (not yet part of the Qt Toolkit).
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at ivan.frade@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qsparql_tracker_direct.h"
#include "qsparql_tracker_direct_p.h"

#include <qsparqlerror.h>
#include <qsparqlbinding.h>
#include <qsparqlquery.h>
#include <qsparqlresultrow.h>

#include <qcoreapplication.h>
#include <qvariant.h>
#include <qstringlist.h>
#include <qvector.h>

#include <qdebug.h>

QT_BEGIN_NAMESPACE

static void
async_cursor_next_callback( GObject *source_object,
                            GAsyncResult *result,
                            gpointer user_data)
{
    Q_UNUSED(source_object);
    QTrackerDirectResultPrivate *data = static_cast<QTrackerDirectResultPrivate*>(user_data);
    GError *error = NULL;
    gboolean active = tracker_sparql_cursor_next_finish(data->cursor, result, &error);

    if (error != NULL) {
        QSparqlError e(QString::fromLatin1(error ? error->message : "unknown error"));
        e.setType(QSparqlError::BackendError);
        data->setLastError(e);
        data->terminate();
        return;
    }

    if (!active) {
        if (data->q->isBool()) {
            data->setBoolValue(data->results.count() == 1
                                    && data->results[0].count() == 1
                                    && data->results[0].value(0).toString() == QLatin1String("1"));
        }

        data->terminate();
        return;
    }

    QSparqlResultRow resultRow;
    gint n_columns = tracker_sparql_cursor_get_n_columns(data->cursor);

    for (int i = 0; i < n_columns; i++) {
        // As Tracker doesn't return the variable names in the query yet, call
        // the variables $1, $2, $3.. as that is better than no names
        QString name = QString::fromLatin1("$%1").arg(i + 1);
        QString value = QString::fromUtf8(tracker_sparql_cursor_get_string(data->cursor, i, NULL));

        if (value.startsWith(QLatin1String("_:"))) {
            QSparqlBinding binding(name);
            binding.setBlankNodeLabel(value.mid(2));
            resultRow.append(binding);
        } else if (value.startsWith(QLatin1String("http:")) || value.startsWith(QLatin1String("urn:"))) {
            resultRow.append(QSparqlBinding(name, QUrl(value)));
        } else {
            resultRow.append(QSparqlBinding(name, value));
        }

    }

    data->results.append(resultRow);
    data->dataReady(data->results.count());
    tracker_sparql_cursor_next_async(data->cursor, NULL, async_cursor_next_callback, data);
}

static void
async_query_callback(   GObject *source_object,
                        GAsyncResult *result,
                        gpointer user_data)
{
    Q_UNUSED(source_object);
    QTrackerDirectResultPrivate *data = static_cast<QTrackerDirectResultPrivate*>(user_data);
    GError *error = NULL;
    data->cursor = tracker_sparql_connection_query_finish(data->driverPrivate->connection, result, &error);

    if (error != NULL || data->cursor == NULL) {
        QSparqlError e(QString::fromLatin1(error ? error->message : "unknown error"));
        e.setType(QSparqlError::StatementError);
        data->setLastError(e);
        data->terminate();
        return;
    }

    tracker_sparql_cursor_next_async(data->cursor, NULL, async_cursor_next_callback, data);
}

static void
async_update_callback( GObject *source_object,
                       GAsyncResult *result,
                       gpointer user_data)
{
    Q_UNUSED(source_object);
    QTrackerDirectResultPrivate *data = static_cast<QTrackerDirectResultPrivate*>(user_data);
    GError *error = NULL;
    tracker_sparql_connection_update_finish(data->driverPrivate->connection, result, &error);

    if (error != NULL) {
        QSparqlError e(QString::fromLatin1(error ? error->message : "unknown error"));
        e.setType(QSparqlError::StatementError);
        data->setLastError(e);
        data->terminate();
        return;
    }

    data->terminate();
}

QTrackerDirectResultPrivate::QTrackerDirectResultPrivate(QTrackerDirectResult* result, QTrackerDirectDriverPrivate *dpp)
: isFinished(false), loop(0), q(result), driverPrivate(dpp)
{
}

QTrackerDirectResultPrivate::~QTrackerDirectResultPrivate()
{
}

void QTrackerDirectResultPrivate::terminate()
{
    isFinished = true;
    q->emit finished();

    if (loop != 0)
        loop->exit();
}

void QTrackerDirectResultPrivate::setLastError(const QSparqlError& e)
{
    q->setLastError(e);
}

void QTrackerDirectResultPrivate::setBoolValue(bool v)
{
    q->setBoolValue(v);
}

void QTrackerDirectResultPrivate::dataReady(int totalCount)
{
    emit q->dataReady(totalCount);
}

QTrackerDirectResult::QTrackerDirectResult(QTrackerDirectDriverPrivate* p)
{
    d = new QTrackerDirectResultPrivate(this, p);
}

QTrackerDirectResult::~QTrackerDirectResult()
{
    delete d;
}

QTrackerDirectResult* QTrackerDirectDriver::exec(const QString& query,
                          QSparqlQuery::StatementType type)
{
    QTrackerDirectResult* res = new QTrackerDirectResult(d);
    res->setStatementType(type);

    switch (type) {
    case QSparqlQuery::AskStatement:
    case QSparqlQuery::SelectStatement:
    {
        tracker_sparql_connection_query_async(  d->connection,
                                                query.toLatin1().constData(),
                                                NULL,
                                                async_query_callback,
                                                res->d);
        break;
    }
    case QSparqlQuery::InsertStatement:
    case QSparqlQuery::DeleteStatement:
        tracker_sparql_connection_update_async( d->connection,
                                                query.toLatin1().constData(),
                                                0,
                                                NULL,
                                                async_update_callback,
                                                res->d);
    {
        break;
    }
    default:
        qWarning() << "Tracker backend: unsupported statement type";
        res->setLastError(QSparqlError(
                              QLatin1String("Unsupported statement type"),
                              QSparqlError::BackendError));
        break;
    }
    return res;
}

void QTrackerDirectResult::cleanup()
{
    setPos(QSparql::BeforeFirstRow);
}

bool QTrackerDirectResult::fetch(int i)
{
    if (i < 0) {
        setPos(QSparql::BeforeFirstRow);
        return false;
    }
    if (i >= d->results.size()) {
        setPos(QSparql::AfterLastRow);
        return false;
    }
    setPos(i);
    return true;
}

bool QTrackerDirectResult::fetchLast()
{
    if (d->results.count() == 0)
        return false;
    setPos(d->results.count() - 1);
    return true;
}

bool QTrackerDirectResult::fetchFirst()
{
    if (pos() == 0)
        return true;
    return fetch(0);
}

QVariant QTrackerDirectResult::data(int field) const
{
    if (field >= d->results[pos()].count() || field < 0) {
        qWarning() << "QTrackerDirectResult::data[" << pos() << "]: column" << field << "out of range";
        return QVariant();
    }

    return d->results[pos()].binding(field).value();
}

void QTrackerDirectResult::waitForFinished()
{
    if (d->isFinished)
        return;

    QEventLoop loop;
    d->loop = &loop;
    loop.exec();
    d->loop = 0;
}

bool QTrackerDirectResult::isFinished() const
{
//    if (d->watcher)
//        return d->watcher->isFinished();
    return true;
}

bool QTrackerDirectResult::isNull(int field) const
{
    Q_UNUSED(field);
    return false;
}

int QTrackerDirectResult::size() const
{
    return d->results.count();
}

QSparqlResultRow QTrackerDirectResult::resultRow() const
{
    QSparqlResultRow info;
    if (pos() < 0 || pos() >= d->results.count())
        return info;

    return d->results[pos()];
}

QTrackerDirectDriverPrivate::QTrackerDirectDriverPrivate()
{
}

QTrackerDirectDriverPrivate::~QTrackerDirectDriverPrivate()
{
}

QTrackerDirectDriver::QTrackerDirectDriver(QObject* parent)
    : QSparqlDriver(parent)
{
    d = new QTrackerDirectDriverPrivate();
    /* Initialize GLib type system */
    g_type_init();

}

QTrackerDirectDriver::~QTrackerDirectDriver()
{
    delete d;
}

bool QTrackerDirectDriver::hasFeature(QSparqlConnection::Feature f) const
{
    switch (f) {
    case QSparqlConnection::QuerySize:
        return true;
    case QSparqlConnection::AskQueries:
        return true;
    case QSparqlConnection::ConstructQueries:
        return false;
    case QSparqlConnection::UpdateQueries:
        return true;
    case QSparqlConnection::DefaultGraph:
        return true;
    }
    return false;
}

QAtomicInt connectionCounter = 0;

bool QTrackerDirectDriver::open(const QSparqlConnectionOptions& options)
{
    Q_UNUSED(options);

    if (isOpen())
        close();

    GError *error = NULL;
    d->connection = tracker_sparql_connection_get(&error);
    if (!d->connection) {
        qWarning("Couldn't obtain a direct connection to the Tracker store: %s",
                    error ? error->message : "unknown error");

        return false;
    }

    setOpen(true);
    setOpenError(false);

    return true;
}

void QTrackerDirectDriver::close()
{
    g_object_unref(d->connection);

    if (isOpen()) {
        setOpen(false);
        setOpenError(false);
    }
}

QT_END_NAMESPACE
<|endoftext|>


<commit_before>/****************************************************************************
 * Copyright (c) 2012-2019 by the DataTransferKit authors                   *
 * All rights reserved.                                                     *
 *                                                                          *
 * This file is part of the DataTransferKit library. DataTransferKit is     *
 * distributed under a BSD 3-clause license. For the licensing terms see    *
 * the LICENSE file in the top-level directory.                             *
 *                                                                          *
 * SPDX-License-Identifier: BSD-3-Clause                                    *
 ****************************************************************************/

#include "DTK_BoostRangeAdapters.hpp"
#include "DTK_EnableViewComparison.hpp"

#include <DTK_Box.hpp>
#include <DTK_DetailsAlgorithms.hpp>
#include <DTK_Point.hpp>

#include <Kokkos_Core.hpp>
#include <Teuchos_UnitTestHarness.hpp>

#include <boost/range/algorithm.hpp> // reverse_copy, replace_if, count, generate, count_if
#include <boost/range/algorithm_ext.hpp> // iota
#include <boost/range/numeric.hpp>       // accumulate
#include <boost/test/unit_test.hpp>

#include <random>
#include <sstream>

#define BOOST_TEST_MODULE BoostRangeAdapters

namespace tt = boost::test_tools;

BOOST_AUTO_TEST_CASE( range_algorithms )
{
    Kokkos::View<int[4], Kokkos::HostSpace> w( "w" );

    boost::iota( w, 0 );
    std::stringstream ss;
    boost::reverse_copy( w, std::ostream_iterator<int>( ss, " " ) );
    BOOST_TEST( ss.str() == "3 2 1 0 " );

    boost::replace_if( w, []( int i ) { return ( i > 1 ); }, -1 );
    BOOST_TEST( w == std::vector<int>( {0, 1, -1, -1} ), tt::per_element() );

    BOOST_TEST( boost::count( w, -1 ), 2 );
    BOOST_TEST( boost::accumulate( w, 5 ), 4 );
}

BOOST_AUTO_TEST_CASE( point_cloud )
{
    using DataTransferKit::Point;
    using DataTransferKit::Details::distance;
    double const seed = 3.14;
    std::default_random_engine generator( seed );
    std::uniform_real_distribution<double> distribution( -1., 1. );
    int const n = 10000;
    Kokkos::View<Point *, Kokkos::HostSpace> cloud( "cloud", n );
    boost::generate( cloud, [&distribution, &generator]() {
        Point p;
        p[0] = distribution( generator );
        p[1] = distribution( generator );
        p[2] = distribution( generator );
        return p;
    } );

    Point const origin = {0., 0., 0.};
    double const radius = 1.;
    // 4/3 pi 1^3 / 2^3
    double const pi = 6. *
                      static_cast<double>( boost::count_if(
                          cloud,
                          [origin, radius]( Point point ) {
                              return ( distance( point, origin ) <= radius );
                          } ) ) /
                      static_cast<double>( n );

    double const relative_tolerance = .05;
    BOOST_TEST( pi == 3.14, tt::tolerance( relative_tolerance ) );
}
<commit_msg>Get rid of last Teuchos header that slipped through the cracks<commit_after>/****************************************************************************
 * Copyright (c) 2012-2019 by the DataTransferKit authors                   *
 * All rights reserved.                                                     *
 *                                                                          *
 * This file is part of the DataTransferKit library. DataTransferKit is     *
 * distributed under a BSD 3-clause license. For the licensing terms see    *
 * the LICENSE file in the top-level directory.                             *
 *                                                                          *
 * SPDX-License-Identifier: BSD-3-Clause                                    *
 ****************************************************************************/

#include "DTK_BoostRangeAdapters.hpp"
#include "DTK_EnableViewComparison.hpp"

#include <DTK_Box.hpp>
#include <DTK_DetailsAlgorithms.hpp>
#include <DTK_Point.hpp>

#include <Kokkos_Core.hpp>

#include <boost/range/algorithm.hpp> // reverse_copy, replace_if, count, generate, count_if
#include <boost/range/algorithm_ext.hpp> // iota
#include <boost/range/numeric.hpp>       // accumulate
#include <boost/test/unit_test.hpp>

#include <random>
#include <sstream>

#define BOOST_TEST_MODULE BoostRangeAdapters

namespace tt = boost::test_tools;

BOOST_AUTO_TEST_CASE( range_algorithms )
{
    Kokkos::View<int[4], Kokkos::HostSpace> w( "w" );

    boost::iota( w, 0 );
    std::stringstream ss;
    boost::reverse_copy( w, std::ostream_iterator<int>( ss, " " ) );
    BOOST_TEST( ss.str() == "3 2 1 0 " );

    boost::replace_if( w, []( int i ) { return ( i > 1 ); }, -1 );
    BOOST_TEST( w == std::vector<int>( {0, 1, -1, -1} ), tt::per_element() );

    BOOST_TEST( boost::count( w, -1 ), 2 );
    BOOST_TEST( boost::accumulate( w, 5 ), 4 );
}

BOOST_AUTO_TEST_CASE( point_cloud )
{
    using DataTransferKit::Point;
    using DataTransferKit::Details::distance;
    double const seed = 3.14;
    std::default_random_engine generator( seed );
    std::uniform_real_distribution<double> distribution( -1., 1. );
    int const n = 10000;
    Kokkos::View<Point *, Kokkos::HostSpace> cloud( "cloud", n );
    boost::generate( cloud, [&distribution, &generator]() {
        Point p;
        p[0] = distribution( generator );
        p[1] = distribution( generator );
        p[2] = distribution( generator );
        return p;
    } );

    Point const origin = {0., 0., 0.};
    double const radius = 1.;
    // 4/3 pi 1^3 / 2^3
    double const pi = 6. *
                      static_cast<double>( boost::count_if(
                          cloud,
                          [origin, radius]( Point point ) {
                              return ( distance( point, origin ) <= radius );
                          } ) ) /
                      static_cast<double>( n );

    double const relative_tolerance = .05;
    BOOST_TEST( pi == 3.14, tt::tolerance( relative_tolerance ) );
}
<|endoftext|>


<commit_before>#include "setup/scheduler.hpp"
#include "setup/interop.hpp"

#include <SFML/OpenGL.hpp>

#if defined _WIN32 || defined _WIN64
    #include <Wingdi.h>
#endif

static GLuint texture;

void interop::initialize(const cl::Device &device, sf::WindowHandle handle)
{
#if defined _WIN32 || defined _WIN64
    cl_context_properties props[] =
    {
        CL_GL_CONTEXT_KHR, (cl_context_properties)wglGetCurrentContext(),
        CL_WGL_HDC_KHR,    (cl_context_properties)GetDC(handle),
        0
    };

    scheduler::setup(device, props);
#elif defined __linux__
    #error "Linux interop support not implemented yet!"
#else
    #error "Platform not supported!"
#endif
}

cl::ImageGL interop::get_image(std::size_t width, std::size_t height)
{
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);
    glViewport(0, 0, (GLint)width, (GLint)height);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height,
                                0, GL_RGBA,  GL_UNSIGNED_BYTE, 0);
    return scheduler::alloc_gl_image(CL_MEM_WRITE_ONLY, texture);
}

void interop::free_image(const cl::ImageGL &/*image*/)
{
    glDeleteTextures(1, &texture);
}

void interop::draw_image(const cl::ImageGL &/*image*/)
{
    glEnable(GL_TEXTURE_2D);
    glBegin(GL_QUADS);

    glTexCoord2d(0, 0); glVertex2d(-1, -1);
    glTexCoord2d(1, 0); glVertex2d(+1, -1);
    glTexCoord2d(1, 1); glVertex2d(+1, +1);
    glTexCoord2d(0, 1); glVertex2d(-1, +1);

    glEnd();
    glDisable(GL_TEXTURE_2D);
}
<commit_msg>Added tentative interop support for Linux<commit_after>#include "setup/scheduler.hpp"
#include "setup/interop.hpp"

#include <SFML/OpenGL.hpp>

#if defined _WIN32 || defined _WIN64
    #include <Wingdi.h>
#elif defined __linux__
    #include <GL/glx.h>
#endif

static GLuint texture;

void interop::initialize(const cl::Device &device, sf::WindowHandle handle)
{
#if defined _WIN32 || defined _WIN64
    cl_context_properties props[] =
    {
        CL_GL_CONTEXT_KHR, (cl_context_properties)wglGetCurrentContext(),
        CL_WGL_HDC_KHR,    (cl_context_properties)GetDC(handle),
        0
    };

    scheduler::setup(device, props);
#elif defined __linux__
    cl_context_properties props[] =
    {
       CL_GL_CONTEXT_KHR,(cl_context_properties)glXGetCurrentContext(),
       CL_GLX_DISPLAY_KHR, (cl_context_properties)glXGetCurrentDisplay(),
       0
    };

    scheduler::setup(device, props);
#else
    #error "Interop not supported for your platform!"
#endif
}

cl::ImageGL interop::get_image(std::size_t width, std::size_t height)
{
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);
    glViewport(0, 0, (GLint)width, (GLint)height);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height,
                                0, GL_RGBA,  GL_UNSIGNED_BYTE, 0);
    return scheduler::alloc_gl_image(CL_MEM_WRITE_ONLY, texture);
}

void interop::free_image(const cl::ImageGL &/*image*/)
{
    glDeleteTextures(1, &texture);
}

void interop::draw_image(const cl::ImageGL &/*image*/)
{
    glEnable(GL_TEXTURE_2D);
    glBegin(GL_QUADS);

    glTexCoord2d(0, 0); glVertex2d(-1, -1);
    glTexCoord2d(1, 0); glVertex2d(+1, -1);
    glTexCoord2d(1, 1); glVertex2d(+1, +1);
    glTexCoord2d(0, 1); glVertex2d(-1, +1);

    glEnd();
    glDisable(GL_TEXTURE_2D);
}
<|endoftext|>


<commit_before><commit_msg>Delete test2.cpp<commit_after><|endoftext|>


<commit_before>/*
* Copyright (C) 2008, Morgan Quigley and Willow Garage, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the names of Stanford University or Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/

#include "ros/ros.h"
#include <transitbuddy_robot_publisher/robot_publisher_node.h>

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

    ros::init ( argc, argv, "robot_publisher" );
    ros::NodeHandle n;
    RobotPublisherNode bridge ( n );
    ros::Rate rate ( bridge.frequency() );
    while ( ros::ok() ) {
        bridge.publishRobotPose();
        ros::spinOnce();
        rate.sleep();
    }
    return 0;
}

RobotPublisherNode::RobotPublisherNode(ros::NodeHandle & n) : n_ ( n ), n_param_ ( "~" ), frequency_ ( DEFAUTL_FRQ), publish_(false), frame_id_(DEFAULT_FRAME_ID) {

    n_param_.getParam ( "frequency", frequency_ );
    ROS_INFO ( "frequency: %5.2f", frequency_ );

    n_param_.getParam ( "publish", publish_ );
    ROS_INFO ( "publish: %s", (publish_?"true":"false") );

    n_param_.getParam ( "frame_id", frame_id_ );
    ROS_INFO ( "frame_id: %s", frame_id_.c_str() );

    sub_ = n_.subscribe( NAME_SUB, 1, &RobotPublisherNode::callbackHumanPose, this );
    pub_ = n_param_.advertise<transitbuddy_msgs::PoseWithIDArray> ( NAME_PUB, 1 );
}

RobotPublisherNode::~RobotPublisherNode(){
}

void RobotPublisherNode::callbackHumanPose(const transitbuddy_msgs::PoseWithIDArray::ConstPtr& msg){
    ROS_INFO ( "robotPoseCallback");
}

void RobotPublisherNode::publishRobotPose(){
    if(publish_ == false) return;
    ROS_INFO ( "publishHumanPose");
    transitbuddy_msgs::PoseWithIDArray poses;
    poses.header.stamp = ros::Time::now();
    poses.header.frame_id = frame_id_;
    poses.poses.resize(2);
    poses.poses[0].id = 10;
    poses.poses[0].valid = true;
    poses.poses[0].pose.position.x = -12.0;
    poses.poses[1].id = 12;
    poses.poses[1].valid = false;
    poses.poses[1].pose.position.x = 24.0;
    pub_.publish(poses);
}
<commit_msg>robot pose publisher dummy<commit_after>/*
* Copyright (C) 2008, Morgan Quigley and Willow Garage, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the names of Stanford University or Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/

#include "ros/ros.h"
#include <transitbuddy_robot_publisher/robot_publisher_node.h>

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

    ros::init ( argc, argv, "robot_publisher" );
    ros::NodeHandle n;
    RobotPublisherNode bridge ( n );
    ros::Rate rate ( bridge.frequency() );
    while ( ros::ok() ) {
        bridge.publishRobotPose();
        ros::spinOnce();
        rate.sleep();
    }
    return 0;
}

RobotPublisherNode::RobotPublisherNode(ros::NodeHandle & n) : n_ ( n ), n_param_ ( "~" ), frequency_ ( DEFAUTL_FRQ), publish_(true), frame_id_(DEFAULT_FRAME_ID) {

    n_param_.getParam ( "frequency", frequency_ );
    ROS_INFO ( "frequency: %5.2f", frequency_ );

    n_param_.getParam ( "publish", publish_ );
    ROS_INFO ( "publish: %s", (publish_?"true":"false") );

    n_param_.getParam ( "frame_id", frame_id_ );
    ROS_INFO ( "frame_id: %s", frame_id_.c_str() );

    sub_ = n_.subscribe( NAME_SUB, 1, &RobotPublisherNode::callbackHumanPose, this );
    pub_ = n_param_.advertise<transitbuddy_msgs::PoseWithIDArray> ( NAME_PUB, 1 );
}

RobotPublisherNode::~RobotPublisherNode(){
}

void RobotPublisherNode::callbackHumanPose(const transitbuddy_msgs::PoseWithIDArray::ConstPtr& msg){
    ROS_INFO ( "robotPoseCallback");
}

void RobotPublisherNode::publishRobotPose(){
    if(publish_ == false) return;
    ROS_INFO ( "publishHumanPose");
    transitbuddy_msgs::PoseWithIDArray poses;
    poses.header.stamp = ros::Time::now();
    poses.header.frame_id = frame_id_;
    poses.poses.resize(2);
    poses.poses[0].id = 10;
    poses.poses[0].valid = true;
    poses.poses[0].pose.position.x = -12.0;
    poses.poses[1].id = 12;
    poses.poses[1].valid = false;
    poses.poses[1].pose.position.x = 24.0;
    pub_.publish(poses);
}
<|endoftext|>