<commit_before>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "WorldPinsScaleController.h"

#include <limits>

#include "IWorldPinsService.h"
#include "ScreenProperties.h"
#include "RenderCamera.h"
#include "IWorldPinsRepository.h"
#include "WorldPinsVisibilityMessage.h"

namespace ExampleApp
{
    namespace WorldPins
    {
        namespace SdkModel
        {
            WorldPinsScaleController::WorldPinsScaleController(IWorldPinsRepository& worldPinsRepository,
                                                               IWorldPinsService& worldPinsService,
                                                               ExampleAppMessaging::TMessageBus& messageBus,
                                                               Eegeo::Resources::Interiors::InteriorsController& interiorsController)
                : m_worldPinsRepository(worldPinsRepository)
                , m_worldPinsService(worldPinsService)
                , m_messageBus(messageBus)
                , m_visibilityMessageHandlerBinding(this, &WorldPinsScaleController::OnWorldPinsVisibilityMessage)
                , m_modality(0.f)
                , m_visibilityScale(0.f)
                , m_targetVisibilityScale(1.f)
                , m_visibilityAnimationDuration(0.2f)
                , m_interiorsController(interiorsController)
            {
                m_messageBus.SubscribeNative(m_visibilityMessageHandlerBinding);
            }

            WorldPinsScaleController::~WorldPinsScaleController()
            {
                m_messageBus.UnsubscribeNative(m_visibilityMessageHandlerBinding);
            }

            void WorldPinsScaleController::Update(float deltaSeconds, const Eegeo::Camera::RenderCamera& renderCamera)
            {
                if(m_visibilityScale < m_targetVisibilityScale)
                {
                    m_visibilityScale = Eegeo::Min(m_visibilityScale + deltaSeconds/m_visibilityAnimationDuration, m_targetVisibilityScale);
                }
                else if(m_visibilityScale > m_targetVisibilityScale)
                {
                    m_visibilityScale = Eegeo::Max(m_visibilityScale - deltaSeconds/m_visibilityAnimationDuration, m_targetVisibilityScale);
                }

                for(size_t i = 0; i < m_worldPinsRepository.GetItemCount(); ++i)
                {
                    WorldPinItemModel& worldPinItemModel = *m_worldPinsRepository.GetItemAtIndex(i);
                    UpdateWorldPin(worldPinItemModel, deltaSeconds, renderCamera);
                    const float globalScale = 1.f - m_modality;
                    float scale = globalScale  * worldPinItemModel.TransitionStateValue() * m_visibilityScale;
                    m_worldPinsService.UpdatePinScale(worldPinItemModel, scale);
                }
            }

            void WorldPinsScaleController::SetModality(float modality)
            {
                Eegeo_ASSERT(modality >= 0.f && modality <= 1.f, "Invalid modality value %f, valid range for modality is 0.0 to 1.0 inclusive.\n", modality);

                m_modality = modality;
            }

            void WorldPinsScaleController::UpdateWorldPin(WorldPinItemModel& worldPinItemModel,
                    float deltaSeconds,
                    const Eegeo::Camera::RenderCamera& renderCamera)
            {
                const bool showingInterior = m_interiorsController.ShowingInterior();
                bool shouldHideInteirorPin = worldPinItemModel.IsInterior();
                if( showingInterior == false)
                {
                    shouldHideInteirorPin = shouldHideInteirorPin && !worldPinItemModel.GetInteriorData().showInExterior;
                }
                else
                {
                    shouldHideInteirorPin = shouldHideInteirorPin && (worldPinItemModel.GetInteriorData().floor != m_interiorsController.GetCurrentFloorIndex());
                }

                Eegeo::v2 screenLocation;
                GetScreenLocation(worldPinItemModel, screenLocation, renderCamera);

                const float ratioX = screenLocation.GetX() / renderCamera.GetViewportWidth();
                const float ratioY = screenLocation.GetY() / renderCamera.GetViewportHeight();
                const bool shouldHide = (ratioX < 0.1f) || (ratioX > 0.9f) || (ratioY < 0.15f) || (ratioY > 0.9f) || shouldHideInteirorPin;

                if(shouldHide)
                {
                    worldPinItemModel.Hide();
                }
                else
                {
                    worldPinItemModel.Show();
                }

                worldPinItemModel.Update(deltaSeconds);
            }

            void WorldPinsScaleController::GetScreenLocation(const WorldPinItemModel& worldPinItemModel,
                    Eegeo::v2& screenLocation,
                    const Eegeo::Camera::RenderCamera& renderCamera) const
            {
                Eegeo::dv3 ecefLocation;
                m_worldPinsService.GetPinEcefAndScreenLocations(worldPinItemModel, ecefLocation, screenLocation);
                Eegeo::v3 cameraLocal = (ecefLocation - renderCamera.GetEcefLocation()).ToSingle();
                Eegeo::v3 screenPos;
                renderCamera.Project(cameraLocal, screenPos);
                screenLocation.Set(screenPos.GetX(), screenPos.GetY());
            }

            void WorldPinsScaleController::Show()
            {
                m_targetVisibilityScale = 1.0f;
            }

            void WorldPinsScaleController::Hide()
            {
                m_targetVisibilityScale = 0.0f;
            }

            void WorldPinsScaleController::OnWorldPinsVisibilityMessage(const WorldPinsVisibilityMessage &worldPinsVisibilityMessage)
            {
                if(worldPinsVisibilityMessage.ShouldSetVisible())
                {
                    Show();
                }
                else
                {
                    Hide();
                }
            }
        }
    }
}
<commit_msg>Hiding exterior pins in interior in WorldPinsScaleController. Buddy: Ian R<commit_after>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "WorldPinsScaleController.h"

#include <limits>

#include "IWorldPinsService.h"
#include "ScreenProperties.h"
#include "RenderCamera.h"
#include "IWorldPinsRepository.h"
#include "WorldPinsVisibilityMessage.h"

namespace ExampleApp
{
    namespace WorldPins
    {
        namespace SdkModel
        {
            WorldPinsScaleController::WorldPinsScaleController(IWorldPinsRepository& worldPinsRepository,
                                                               IWorldPinsService& worldPinsService,
                                                               ExampleAppMessaging::TMessageBus& messageBus,
                                                               Eegeo::Resources::Interiors::InteriorsController& interiorsController)
                : m_worldPinsRepository(worldPinsRepository)
                , m_worldPinsService(worldPinsService)
                , m_messageBus(messageBus)
                , m_visibilityMessageHandlerBinding(this, &WorldPinsScaleController::OnWorldPinsVisibilityMessage)
                , m_modality(0.f)
                , m_visibilityScale(0.f)
                , m_targetVisibilityScale(1.f)
                , m_visibilityAnimationDuration(0.2f)
                , m_interiorsController(interiorsController)
            {
                m_messageBus.SubscribeNative(m_visibilityMessageHandlerBinding);
            }

            WorldPinsScaleController::~WorldPinsScaleController()
            {
                m_messageBus.UnsubscribeNative(m_visibilityMessageHandlerBinding);
            }

            void WorldPinsScaleController::Update(float deltaSeconds, const Eegeo::Camera::RenderCamera& renderCamera)
            {
                if(m_visibilityScale < m_targetVisibilityScale)
                {
                    m_visibilityScale = Eegeo::Min(m_visibilityScale + deltaSeconds/m_visibilityAnimationDuration, m_targetVisibilityScale);
                }
                else if(m_visibilityScale > m_targetVisibilityScale)
                {
                    m_visibilityScale = Eegeo::Max(m_visibilityScale - deltaSeconds/m_visibilityAnimationDuration, m_targetVisibilityScale);
                }

                for(size_t i = 0; i < m_worldPinsRepository.GetItemCount(); ++i)
                {
                    WorldPinItemModel& worldPinItemModel = *m_worldPinsRepository.GetItemAtIndex(i);
                    UpdateWorldPin(worldPinItemModel, deltaSeconds, renderCamera);
                    const float globalScale = 1.f - m_modality;
                    float scale = globalScale  * worldPinItemModel.TransitionStateValue() * m_visibilityScale;
                    m_worldPinsService.UpdatePinScale(worldPinItemModel, scale);
                }
            }

            void WorldPinsScaleController::SetModality(float modality)
            {
                Eegeo_ASSERT(modality >= 0.f && modality <= 1.f, "Invalid modality value %f, valid range for modality is 0.0 to 1.0 inclusive.\n", modality);

                m_modality = modality;
            }

            void WorldPinsScaleController::UpdateWorldPin(WorldPinItemModel& worldPinItemModel,
                    float deltaSeconds,
                    const Eegeo::Camera::RenderCamera& renderCamera)
            {
                const bool showingInterior = m_interiorsController.ShowingInterior();

                const bool shouldHideExteriorPin = showingInterior && !worldPinItemModel.IsInterior();

                bool shouldHideInteirorPin = worldPinItemModel.IsInterior();
                if( showingInterior == false)
                {
                    shouldHideInteirorPin = shouldHideInteirorPin && !worldPinItemModel.GetInteriorData().showInExterior;
                }
                else
                {
                    shouldHideInteirorPin = shouldHideInteirorPin && (worldPinItemModel.GetInteriorData().floor != m_interiorsController.GetCurrentFloorIndex());
                }

                Eegeo::v2 screenLocation;
                GetScreenLocation(worldPinItemModel, screenLocation, renderCamera);

                const float ratioX = screenLocation.GetX() / renderCamera.GetViewportWidth();
                const float ratioY = screenLocation.GetY() / renderCamera.GetViewportHeight();
                const bool shouldHide = (ratioX < 0.1f) || (ratioX > 0.9f) || (ratioY < 0.15f) || (ratioY > 0.9f) || shouldHideInteirorPin || shouldHideExteriorPin;

                if(shouldHide)
                {
                    worldPinItemModel.Hide();
                }
                else
                {
                    worldPinItemModel.Show();
                }

                worldPinItemModel.Update(deltaSeconds);
            }

            void WorldPinsScaleController::GetScreenLocation(const WorldPinItemModel& worldPinItemModel,
                    Eegeo::v2& screenLocation,
                    const Eegeo::Camera::RenderCamera& renderCamera) const
            {
                Eegeo::dv3 ecefLocation;
                m_worldPinsService.GetPinEcefAndScreenLocations(worldPinItemModel, ecefLocation, screenLocation);
                Eegeo::v3 cameraLocal = (ecefLocation - renderCamera.GetEcefLocation()).ToSingle();
                Eegeo::v3 screenPos;
                renderCamera.Project(cameraLocal, screenPos);
                screenLocation.Set(screenPos.GetX(), screenPos.GetY());
            }

            void WorldPinsScaleController::Show()
            {
                m_targetVisibilityScale = 1.0f;
            }

            void WorldPinsScaleController::Hide()
            {
                m_targetVisibilityScale = 0.0f;
            }

            void WorldPinsScaleController::OnWorldPinsVisibilityMessage(const WorldPinsVisibilityMessage &worldPinsVisibilityMessage)
            {
                if(worldPinsVisibilityMessage.ShouldSetVisible())
                {
                    Show();
                }
                else
                {
                    Hide();
                }
            }
        }
    }
}
<|endoftext|>


<commit_before>/****************************************************************/
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*          All contents are licensed under LGPL V2.1           */
/*             See LICENSE for full restrictions                */
/****************************************************************/

#include "GenericConstantRankTwoTensor.h"

template<>
InputParameters validParams<GenericConstantRankTwoTensor>()
{
  InputParameters params = validParams<Material>();
  params.addRequiredParam<std::vector<Real> >("tensor_values", "Vector of values defining the constant rank two tensor");
  params.addRequiredParam<MaterialPropertyName>("tensor_name", "Name of teh tensor material property to be created");
  return params;
}

GenericConstantRankTwoTensor::GenericConstantRankTwoTensor(const InputParameters & parameters) :
    Material(parameters),
    _prop(declareProperty<RankTwoTensor>(getParam<MaterialPropertyName>("tensor_name")))
{
  _tensor.fillFromInputVector(getParam<std::vector<Real> >("tensor_values"));
}

void
GenericConstantRankTwoTensor::computeQpProperties()
{
  _prop[_qp] = _tensor;
}
<commit_msg>Address comments (#6205)<commit_after>/****************************************************************/
/* MOOSE - Multiphysics Object Oriented Simulation Environment  */
/*                                                              */
/*          All contents are licensed under LGPL V2.1           */
/*             See LICENSE for full restrictions                */
/****************************************************************/

#include "GenericConstantRankTwoTensor.h"

template<>
InputParameters validParams<GenericConstantRankTwoTensor>()
{
  InputParameters params = validParams<Material>();
  params.addRequiredParam<std::vector<Real> >("tensor_values", "Vector of values defining the constant rank two tensor");
  params.addRequiredParam<MaterialPropertyName>("tensor_name", "Name of the tensor material property to be created");
  return params;
}

GenericConstantRankTwoTensor::GenericConstantRankTwoTensor(const InputParameters & parameters) :
    Material(parameters),
    _prop(declareProperty<RankTwoTensor>(getParam<MaterialPropertyName>("tensor_name")))
{
  _tensor.fillFromInputVector(getParam<std::vector<Real> >("tensor_values"));
}

void
GenericConstantRankTwoTensor::computeQpProperties()
{
  _prop[_qp] = _tensor;
}
<|endoftext|>


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

/*!
 @file tcp_session.hpp
 @breif tcp 계열 세션 모음.
 @detail ssl 소켓 세션 클래스가 선언되어있다.
         추후 tcp 세션 클래스를 추가할 예정이다.
 @author GeunYoung Lim, interruping@naver.com
 @data 2017. 02. 09
*/

#ifndef SOLARCODE_LIVEMAP_TCP_SESSION
#define SOLARCODE_LIVEMAP_TCP_SESSION

#include "debug_utility.hpp"
#include "session_base.hpp"

namespace solarcode {
namespace livemap {
    /*!
     @breif ssl 소켓 세션 클래스
     @detail ssl 소켓을 이용하여 클라이언트와 통신하는 클래스.
             pimpl패턴으로 구현되어 별도의 구현 클래스로 상세 구현한다.
             디폴트 구현 클래스는 ssl_tcp_session_boost_impl 클래스.
     @see ssl_tcp_session_boost_impl
     */
    class ssl_tcp_session : public session_base {
    public:
        ssl_tcp_session(std::shared_ptr<void> socket);

        virtual ~ssl_tcp_session(){}

        /*!
         @ingroup session_base_require_impl
         @defgroup ssl_tcp_session_impl session_base로부터 상속받아 구현된 인터페이스 함수들.
         @{
         */
        //pimpl 패턴 구현.
        virtual void start() {
            _pimpl->start();
        }

        virtual void stop() {
            _pimpl->stop();
        }
        /*!
         @}
         */ //end of ssl_tcp_session_impl

        /*!
         @ingroup ssl_tcp_session_impl
         @defgroup ssl_tcp_session_imp_redef session_base의 구현을 재정의한 함수들.
         @{
         */
        //pimpl 패턴을 위한 재정의.
        virtual void set_delegate(session_io_delegate *delegate) {
            _pimpl->set_delegate(delegate);
        }

        virtual session_io_delegate* get_delegate() const {
            return _pimpl->get_delegate();
        }

        virtual std::shared_ptr<void> get_socket() const  {
            return _pimpl->get_socket();
        }

        virtual void set_expire_callback(std::function<void()> expire_callback) {
            _pimpl->set_expire_callback(expire_callback);
        }
        /*!
         @}
         */ //end of ssl_tcp_session_impl_redef

    private:
        /*!
         @breif 구현 클래스의 객체 포인터
         @details unique_ptr로 wrapping 됨.
                  ssl_tcp_session 클래스가 구현클래스의 수명을 관리한다.
                  ssl_tcp_session 클래스가 소멸되면 구현클래스도 소멸된다.
         */
        std::unique_ptr<session_base> _pimpl;
    };

}
}

#endif
<commit_msg>fix bug 'bad_weak_ptr' change pointer of implementaion type unique_ptr to shared_ptr.<commit_after>// Copyright 2017 GeunYoung Lim <interruping4dev@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/*!
 @file tcp_session.hpp
 @breif tcp 계열 세션 모음.
 @detail ssl 소켓 세션 클래스가 선언되어있다.
         추후 tcp 세션 클래스를 추가할 예정이다.
 @author GeunYoung Lim, interruping@naver.com
 @data 2017. 02. 09
*/

#ifndef SOLARCODE_LIVEMAP_TCP_SESSION
#define SOLARCODE_LIVEMAP_TCP_SESSION

#include "debug_utility.hpp"
#include "session_base.hpp"

namespace solarcode {
namespace livemap {
    /*!
     @breif ssl 소켓 세션 클래스
     @detail ssl 소켓을 이용하여 클라이언트와 통신하는 클래스.
             pimpl패턴으로 구현되어 별도의 구현 클래스로 상세 구현한다.
             디폴트 구현 클래스는 ssl_tcp_session_boost_impl 클래스.
     @see ssl_tcp_session_boost_impl
     */
    class ssl_tcp_session : public session_base {
    public:
        ssl_tcp_session(std::shared_ptr<void> socket);

        virtual ~ssl_tcp_session(){}

        /*!
         @ingroup session_base_require_impl
         @defgroup ssl_tcp_session_impl session_base로부터 상속받아 구현된 인터페이스 함수들.
         @{
         */
        //pimpl 패턴 구현.
        virtual void start() {
            _pimpl->start();
        }

        virtual void stop() {
            _pimpl->stop();
        }
        /*!
         @}
         */ //end of ssl_tcp_session_impl

        /*!
         @ingroup ssl_tcp_session_impl
         @defgroup ssl_tcp_session_imp_redef session_base의 구현을 재정의한 함수들.
         @{
         */
        //pimpl 패턴을 위한 재정의.
        virtual void set_delegate(session_io_delegate *delegate) {
            _pimpl->set_delegate(delegate);
        }

        virtual session_io_delegate* get_delegate() const {
            return _pimpl->get_delegate();
        }

        virtual std::shared_ptr<void> get_socket() const  {
            return _pimpl->get_socket();
        }

        virtual void set_expire_callback(std::function<void()> expire_callback) {
            _pimpl->set_expire_callback(expire_callback);
        }
        /*!
         @}
         */ //end of ssl_tcp_session_impl_redef

    private:
        /*!
         @breif 구현 클래스의 객체 포인터
         @details unique_ptr로 wrapping 됨.
                  ssl_tcp_session 클래스가 구현클래스의 수명을 관리한다.
                  ssl_tcp_session 클래스가 소멸되면 구현클래스도 소멸된다.
         */
        std::shared_ptr<session_base> _pimpl;
    };

}
}

#endif
<|endoftext|>


<commit_before>/*
    Copyright (c) 2014 Daniel Vrátil <dvratil@redhat.com>

    This library is free software; you can redistribute it and/or modify it
    under the terms of the GNU Library General Public License as published by
    the Free Software Foundation; either version 2 of the License, or (at your
    option) any later version.

    This library is distributed in the hope that it will be useful, but WITHOUT
    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Library General Public
    License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "tagappend.h"
#include "tagfetchhelper.h"
#include "akonadiconnection.h"
#include "imapstreamparser.h"
#include "response.h"
#include "storage/datastore.h"
#include "libs/protocol_p.h"

using namespace Akonadi::Server;

TagAppend::TagAppend()
  : Handler()
{
}

TagAppend::~TagAppend()
{
}

bool TagAppend::parseStream()
{
  m_streamParser->beginList();

  Tag insertedTag;
  typedef QPair<QByteArray, QByteArray> AttributePair;
  QList<AttributePair> attributes;
  QString remoteId;

  while ( !m_streamParser->atListEnd() ) {
    const QByteArray param = m_streamParser->readString();

    if ( param == AKONADI_PARAM_GID ) {
      insertedTag.setGid( QString::fromLatin1( m_streamParser->readString() ) );
    } else if ( param == AKONADI_PARAM_PARENT ) {
      insertedTag.setParentId( m_streamParser->readNumber() );
    } else if ( param == AKONADI_PARAM_REMOTEID ) {
      if ( !connection()->resourceContext().isValid() ) {
        throw HandlerException( "Only resource can create tag with remote ID" );
      }
      remoteId = QString::fromLatin1( m_streamParser->readString() );
    } else {
      attributes << qMakePair( param, m_streamParser->readString() );
    }
  }

  qint64 tagId = -1;
  if  ( !insertedTag.insert( &tagId ) ) {
    throw HandlerException( "Failed to store tag" );
  }

  if ( !remoteId.isEmpty() ) {
    Resource resource = Resource::retrieveByName( connection()->resourceContext().name() );
    TagRemoteIdResourceRelation rel;
    rel.setTagId( tagId );
    rel.setResourceId( resource.id() );
    rel.setRemoteId( remoteId );
    if ( !rel.insert() ) {
      throw HandlerException( "Failed to store tag remote ID" );
    }
  }

  Q_FOREACH ( const AttributePair &pair, attributes ) {
    TagAttribute attribute;
    attribute.setTagId( tagId );
    attribute.setType( pair.first );
    attribute.setValue( pair.second );
    if ( !attribute.insert() ) {
      throw HandlerException( "Failed to store tag attribute" );
    }
  }

  DataStore::self()->notificationCollector()->tagAdded( insertedTag );

  ImapSet set;
  set.add( QVector<qint64>() << tagId );
  TagFetchHelper helper( connection(), set );
  connect( &helper, SIGNAL(responseAvailable(Akonadi::Server::Response)),
           this, SIGNAL(responseAvailable(Akonadi::Server::Response)) );

  if ( !helper.fetchTags( AKONADI_CMD_TAGAPPEND ) ) {
    return false;
  }

  Response response;
  response.setTag( tag() );
  response.setSuccess();
  response.setString( "Append completed" );
  Q_EMIT responseAvailable( response );
  return true;
}

<commit_msg>Revert "Use TAGAPPEND as command name in the untagged response containing the appended item."<commit_after>/*
    Copyright (c) 2014 Daniel Vrátil <dvratil@redhat.com>

    This library is free software; you can redistribute it and/or modify it
    under the terms of the GNU Library General Public License as published by
    the Free Software Foundation; either version 2 of the License, or (at your
    option) any later version.

    This library is distributed in the hope that it will be useful, but WITHOUT
    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Library General Public
    License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "tagappend.h"
#include "tagfetchhelper.h"
#include "akonadiconnection.h"
#include "imapstreamparser.h"
#include "response.h"
#include "storage/datastore.h"
#include "libs/protocol_p.h"

using namespace Akonadi::Server;

TagAppend::TagAppend()
  : Handler()
{
}

TagAppend::~TagAppend()
{
}

bool TagAppend::parseStream()
{
  m_streamParser->beginList();

  Tag insertedTag;
  typedef QPair<QByteArray, QByteArray> AttributePair;
  QList<AttributePair> attributes;
  QString remoteId;

  while ( !m_streamParser->atListEnd() ) {
    const QByteArray param = m_streamParser->readString();

    if ( param == AKONADI_PARAM_GID ) {
      insertedTag.setGid( QString::fromLatin1( m_streamParser->readString() ) );
    } else if ( param == AKONADI_PARAM_PARENT ) {
      insertedTag.setParentId( m_streamParser->readNumber() );
    } else if ( param == AKONADI_PARAM_REMOTEID ) {
      if ( !connection()->resourceContext().isValid() ) {
        throw HandlerException( "Only resource can create tag with remote ID" );
      }
      remoteId = QString::fromLatin1( m_streamParser->readString() );
    } else {
      attributes << qMakePair( param, m_streamParser->readString() );
    }
  }

  qint64 tagId = -1;
  if  ( !insertedTag.insert( &tagId ) ) {
    throw HandlerException( "Failed to store tag" );
  }

  if ( !remoteId.isEmpty() ) {
    Resource resource = Resource::retrieveByName( connection()->resourceContext().name() );
    TagRemoteIdResourceRelation rel;
    rel.setTagId( tagId );
    rel.setResourceId( resource.id() );
    rel.setRemoteId( remoteId );
    if ( !rel.insert() ) {
      throw HandlerException( "Failed to store tag remote ID" );
    }
  }

  Q_FOREACH ( const AttributePair &pair, attributes ) {
    TagAttribute attribute;
    attribute.setTagId( tagId );
    attribute.setType( pair.first );
    attribute.setValue( pair.second );
    if ( !attribute.insert() ) {
      throw HandlerException( "Failed to store tag attribute" );
    }
  }

  DataStore::self()->notificationCollector()->tagAdded( insertedTag );

  ImapSet set;
  set.add( QVector<qint64>() << tagId );
  TagFetchHelper helper( connection(), set );
  connect( &helper, SIGNAL(responseAvailable(Akonadi::Server::Response)),
           this, SIGNAL(responseAvailable(Akonadi::Server::Response)) );

  if ( !helper.fetchTags( AKONADI_CMD_TAGFETCH ) ) {
    return false;
  }

  Response response;
  response.setTag( tag() );
  response.setSuccess();
  response.setString( "Append completed" );
  Q_EMIT responseAvailable( response );
  return true;
}

<|endoftext|>


<commit_before>/*******************************************************************************
 * Copyright (c) 2015 Wojciech Migda
 * All rights reserved
 * Distributed under the terms of the GNU LGPL v3
 *******************************************************************************
 *
 * Filename: linreg.hpp
 *
 * Description:
 *      description
 *
 * Authors:
 *          Wojciech Migda (wm)
 *
 *******************************************************************************
 * History:
 * --------
 * Date         Who  Ticket     Description
 * ----------   ---  ---------  ------------------------------------------------
 * 2015-02-22   wm              Initial version
 *
 ******************************************************************************/

#ifndef LINREG_HPP_
#define LINREG_HPP_

#include "array2d.hpp"
#include "fmincg.hpp"
#include "num.hpp"

#include <valarray>
#include <utility>
#include <cassert>

namespace num
{

template<typename _ValueType>
void
linreg_cost_grad(
    /// out
    _ValueType & out_cost,
    std::valarray<_ValueType> & out_grad,
    std::valarray<_ValueType> & tcol,
    /// in
    const std::valarray<_ValueType> theta,
    const array2d<_ValueType> X,
    const std::valarray<_ValueType> y,
    const _ValueType C
)
{
    typedef _ValueType value_type;
    typedef std::valarray<value_type> vector;

    const shape_type X_shape = X.shape();

    assert(y.size() == X_shape.first);
    assert(out_grad.size() == X_shape.second);
    assert(theta.size() == X_shape.second);

    assert(tcol.size() >= X_shape.first);

    vector & H = tcol;

    //    H = (theta' * X')' - y;
    for (size_type r{0}; r < X_shape.first; ++r)
    {
        H[r] = (X[X.row(r)] * theta).sum();
    }
    H -= y;

    //  sigma_i = sum(H .* H);
    const value_type Sigma = (H * H).sum();

    //  J = (sigma_i + sum(theta_for_reg .* theta_for_reg) / C) / (2 * m);
//    out_cost = (Sigma + (theta[std::slice(1, X_shape.second - 1, 1)] * theta[std::slice(1, X_shape.second - 1, 1)]).sum() / C) / (2.0 * X_shape.first);
    out_cost = (Sigma + ((theta * theta).sum() - theta[0] * theta[0]) / C) / (2.0 * X_shape.first);

    //  theta_for_reg = [0; theta(2:end)];
    //  grad = theta_for_reg' / C;
    out_grad = theta / C;
    out_grad[0] = 0.0;
    //  grad += (H)' * X;
    for (size_type r{0}; r < X_shape.second; ++r)
    {
        out_grad[r] += (X[X.column(r)] * H).sum();
    }
    //  grad /= m;
    out_grad /= X_shape.first;
}

template<typename _ValueType>
std::pair<_ValueType, std::valarray<_ValueType>>
linreg_cost_grad(
    const std::valarray<_ValueType> theta,
    const array2d<_ValueType> X,
    const std::valarray<_ValueType> y,
    const _ValueType C)
{
    typedef _ValueType value_type;
    typedef std::valarray<value_type> vector;

    const shape_type X_shape = X.shape();

    vector temp(X_shape.first);

    const double cost;
    const vector grad(X_shape.first);

    linreg_cost_grad(cost, grad, temp, theta, X, y, C);

    return std::make_pair(cost, grad);
}

template<typename _ValueType>
class LinearRegression
{
public:
    typedef _ValueType value_type;
    typedef std::valarray<value_type> vector_type;
    typedef array2d<value_type> array_type;

    LinearRegression(
        array_type && X,
        vector_type && y,
        vector_type && theta0,
        value_type C,
        size_type max_iter
    );

    vector_type
    fit(void) const;

    vector_type
    predict(const array_type & X, const vector_type & theta) const;

    vector_type
    predict(array_type && X, vector_type && theta) const;

private:
    const array_type m_X;
    const vector_type m_y;
    const vector_type m_theta0;
    const value_type m_C;
    const size_type m_max_iter;
};

template<typename _ValueType>
LinearRegression<_ValueType>::LinearRegression(
    array_type && X,
    vector_type && y,
    vector_type && theta0,
    value_type C,
    size_type max_iter
)
:
    m_X{std::move(X)},
    m_y{std::move(y)},
    m_theta0{m_theta0.size() == m_X.shape().second ? std::move(theta0) : vector_type(m_X.shape().second)},
    m_C{C},
    m_max_iter{max_iter}
{
}

template<typename _ValueType>
typename LinearRegression<_ValueType>::vector_type
LinearRegression<_ValueType>::fit(void) const
{
    vector_type tcol(m_y.size());

    std::function<std::pair<value_type, vector_type> (vector_type)>

    /* NOTE: Capturing member variables is always done via capturing this */
    cost_fn = [this, &tcol](const vector_type theta) -> std::pair<value_type, vector_type>
    {
        value_type cost;
        vector_type grad(theta.size());

        num::linreg_cost_grad(cost, grad, tcol, theta, this->m_X, this->m_y, this->m_C);

        return std::make_pair(cost, grad);
    };

    const vector_type theta = num::fmincg(cost_fn, m_theta0, m_max_iter, false);

    return theta;
}

template<typename _ValueType>
typename LinearRegression<_ValueType>::vector_type
LinearRegression<_ValueType>::predict(const array_type & X, const vector_type & theta) const
{
    assert(theta.size() == X.shape().second);

    vector_type H(X.shape().first);

    for (size_type r{0}; r < X.shape().first; ++r)
    {
        H[r] = (X[X.row(r)] * theta).sum();
    }

    return H;
}

template<typename _ValueType>
typename LinearRegression<_ValueType>::vector_type
LinearRegression<_ValueType>::predict(array_type && X, vector_type && theta) const
{
    return predict(X, theta);
}

} // namespace num

#endif /* LINREG_HPP_ */
<commit_msg>using intrinsic mul method for matrix / vector multiplication<commit_after>/*******************************************************************************
 * Copyright (c) 2015 Wojciech Migda
 * All rights reserved
 * Distributed under the terms of the GNU LGPL v3
 *******************************************************************************
 *
 * Filename: linreg.hpp
 *
 * Description:
 *      description
 *
 * Authors:
 *          Wojciech Migda (wm)
 *
 *******************************************************************************
 * History:
 * --------
 * Date         Who  Ticket     Description
 * ----------   ---  ---------  ------------------------------------------------
 * 2015-02-22   wm              Initial version
 *
 ******************************************************************************/

#ifndef LINREG_HPP_
#define LINREG_HPP_

#include "array2d.hpp"
#include "fmincg.hpp"
#include "num.hpp"

#include <valarray>
#include <utility>
#include <cassert>
#include <functional>

namespace num
{

template<typename _ValueType>
void
linreg_cost_grad(
    /// out
    _ValueType & out_cost,
    std::valarray<_ValueType> & out_grad,
    std::valarray<_ValueType> & tcol,
    /// in
    const std::valarray<_ValueType> theta,
    const array2d<_ValueType> X,
    const std::valarray<_ValueType> y,
    const _ValueType C
)
{
    typedef _ValueType value_type;
    typedef std::valarray<value_type> vector;

    const shape_type X_shape = X.shape();

    assert(y.size() == X_shape.first);
    assert(out_grad.size() == X_shape.second);
    assert(theta.size() == X_shape.second);

    assert(tcol.size() >= X_shape.first);

    vector & H = tcol;

    //    H = (theta' * X')' - y;
    X.mul(decltype(X)::Axis::Row, theta, H);
    H -= y;

    //  sigma_i = sum(H .* H);
    const value_type Sigma = (H * H).sum();

    //  J = (sigma_i + sum(theta_for_reg .* theta_for_reg) / C) / (2 * m);
//    out_cost = (Sigma + (theta[std::slice(1, X_shape.second - 1, 1)] * theta[std::slice(1, X_shape.second - 1, 1)]).sum() / C) / (2.0 * X_shape.first);
    out_cost = (Sigma + ((theta * theta).sum() - theta[0] * theta[0]) / C) / (2.0 * X_shape.first);

    //  theta_for_reg = [0; theta(2:end)];
    //  grad = theta_for_reg' / C;
    out_grad = theta / C;
    out_grad[0] = 0.0;
    //  grad += (H)' * X;
    X.mul(decltype(X)::Axis::Column, H, out_grad, std::plus<value_type>());
    //  grad /= m;
    out_grad /= X_shape.first;
}

template<typename _ValueType>
std::pair<_ValueType, std::valarray<_ValueType>>
linreg_cost_grad(
    const std::valarray<_ValueType> theta,
    const array2d<_ValueType> X,
    const std::valarray<_ValueType> y,
    const _ValueType C)
{
    typedef _ValueType value_type;
    typedef std::valarray<value_type> vector;

    const shape_type X_shape = X.shape();

    vector temp(X_shape.first);

    const double cost;
    const vector grad(X_shape.first);

    linreg_cost_grad(cost, grad, temp, theta, X, y, C);

    return std::make_pair(cost, grad);
}

template<typename _ValueType>
class LinearRegression
{
public:
    typedef _ValueType value_type;
    typedef std::valarray<value_type> vector_type;
    typedef array2d<value_type> array_type;

    LinearRegression(
        array_type && X,
        vector_type && y,
        vector_type && theta0,
        value_type C,
        size_type max_iter
    );

    vector_type
    fit(void) const;

    vector_type
    predict(const array_type & X, const vector_type & theta) const;

    vector_type
    predict(array_type && X, vector_type && theta) const;

private:
    const array_type m_X;
    const vector_type m_y;
    const vector_type m_theta0;
    const value_type m_C;
    const size_type m_max_iter;
};

template<typename _ValueType>
LinearRegression<_ValueType>::LinearRegression(
    array_type && X,
    vector_type && y,
    vector_type && theta0,
    value_type C,
    size_type max_iter
)
:
    m_X{std::move(X)},
    m_y{std::move(y)},
    m_theta0{m_theta0.size() == m_X.shape().second ? std::move(theta0) : vector_type(m_X.shape().second)},
    m_C{C},
    m_max_iter{max_iter}
{
}

template<typename _ValueType>
typename LinearRegression<_ValueType>::vector_type
LinearRegression<_ValueType>::fit(void) const
{
    vector_type tcol(m_y.size());

    std::function<std::pair<value_type, vector_type> (vector_type)>

    /* NOTE: Capturing member variables is always done via capturing this */
    cost_fn = [this, &tcol](const vector_type theta) -> std::pair<value_type, vector_type>
    {
        value_type cost;
        vector_type grad(theta.size());

        num::linreg_cost_grad(cost, grad, tcol, theta, this->m_X, this->m_y, this->m_C);

        return std::make_pair(cost, grad);
    };

    const vector_type theta = num::fmincg(cost_fn, m_theta0, m_max_iter, false);

    return theta;
}

template<typename _ValueType>
typename LinearRegression<_ValueType>::vector_type
LinearRegression<_ValueType>::predict(const array_type & X, const vector_type & theta) const
{
    assert(theta.size() == X.shape().second);

    vector_type H(X.shape().first);

    for (size_type r{0}; r < X.shape().first; ++r)
    {
        H[r] = (X[X.row(r)] * theta).sum();
    }

    return H;
}

template<typename _ValueType>
typename LinearRegression<_ValueType>::vector_type
LinearRegression<_ValueType>::predict(array_type && X, vector_type && theta) const
{
    return predict(X, theta);
}

} // namespace num

#endif /* LINREG_HPP_ */
<|endoftext|>


<commit_before>#include "Q1DTransferFunction.h"
#include <QtGui/QPainter>
#include <QtGui/QMouseEvent>

Q1DTransferFunction::Q1DTransferFunction(QWidget *parent) :
	QWidget(parent),
	m_iPaintmode(Q1DT_PAINT_NONE),
	m_bBackdropCacheUptodate(false),
	m_iCachedHeight(0),
	m_iCachedWidth(0),
	m_pBackdropCache(NULL),
	// borders, may be changed arbitrarly
	m_iLeftBorder(20),
	m_iBottomBorder(20),
	// automatically computed borders
	m_iRightBorder(0),
	m_iTopBorder(0),
	// colors, may be changed arbitrarily
	m_colorHistogram(50,50,50),
	m_colorBack(Qt::black),
	m_colorBorder(100, 100, 255),
	m_colorScale(100, 100, 255),
	m_colorLargeScale(180, 180, 180),
	m_colorRedLine(255, 0, 0),
	m_colorGreenLine(0, 255, 0),
	m_colorBlueLine(0, 0, 255),
	m_colorAlphaLine(Qt::white),
	// scale apearance, may be changed arbitrarily (except for the marker length wich should both be less or equal to m_iLeftBorder and m_iBottomBorder)
	m_iMarkersX(40),
	m_iMarkersY (40),
	m_iBigMarkerSpacingX(5),
	m_iBigMarkerSpacingY(5),
	m_iMarkerLength(5),
	m_iBigMarkerLength(m_iMarkerLength*3),
	// mouse motion
	m_iLastIndex(-1)
{
}

Q1DTransferFunction::~Q1DTransferFunction(void)
{
	// delete the backdrop cache pixmap
	delete m_pBackdropCache;
}

void Q1DTransferFunction::SetHistogram(std::vector<unsigned int> vHistrogram) {
	// resize the histogram vector
	m_vHistrogram.resize(vHistrogram.size());

	// also resize the transferfunction
	m_Trans.Resize(vHistrogram.size());

	// force the draw routine to recompute the backdrop cache
	m_bBackdropCacheUptodate = false;

	// if the histogram is empty we are done
	if (m_vHistrogram.size() == 0)  return;

	// rescale the histogram to the [0..1] range
	// first find min and max ...
	float fMax = float(vHistrogram[0]), fMin = float(vHistrogram[0]);
	for (size_t i = 0;i<m_vHistrogram.size();i++) {
		if (float(vHistrogram[i]) > fMax) fMax = float(vHistrogram[i]);
		if (float(vHistrogram[i]) < fMin) fMin = float(vHistrogram[i]);

		for (unsigned int j = 0;j<4;j++) m_Trans.pColorData[i][j] = 0.0f;
	}

	// ... than rescale
	float fDiff = fMax-fMin;
	for (size_t i = 0;i<m_vHistrogram.size();i++) {
		m_vHistrogram[i]  = vHistrogram[i] - fMin;
		m_vHistrogram[i] /= fDiff;
	}
}

void Q1DTransferFunction::DrawCoordinateSystem(QPainter& painter) {
	// adjust left and bottom border so that the marker count can be met
	m_iRightBorder   = (width()-(m_iLeftBorder+2))   %m_iMarkersX;
	m_iTopBorder     = (height()-(m_iBottomBorder+2))%m_iMarkersY;

	// compute the actual marker spaceing
	unsigned int iMarkerSpacingX = (width()-(m_iLeftBorder+2))/m_iMarkersX;
	unsigned int iMarkerSpacingY = (height()-(m_iBottomBorder+2))/m_iMarkersY;

	// draw background
	painter.setBrush(m_colorBack);
	QRect backRect(0,0,width(),height());
	painter.drawRect(backRect);

	// draw grid borders
	QPen borderPen(m_colorBorder, 1, Qt::SolidLine);
	painter.setPen(borderPen);
	QRect borderRect(m_iLeftBorder,m_iTopBorder, width()-(m_iLeftBorder+2+m_iRightBorder), height()-(m_iTopBorder+m_iBottomBorder+2));
	painter.drawRect(borderRect);

	// draw Y axis markers
	QPen penScale(m_colorScale, 1, Qt::SolidLine);
	QPen penLargeScale(m_colorLargeScale, 1, Qt::SolidLine);
	for (unsigned int i = 0;i<m_iMarkersY;i++) {
		int iPosY = height()-m_iBottomBorder-2 - i*iMarkerSpacingY;

		if (i%m_iBigMarkerSpacingY == 0) {
			painter.setPen(penLargeScale);
			painter.drawLine(m_iLeftBorder-m_iBigMarkerLength, iPosY, m_iLeftBorder, iPosY);
		} else {
			painter.setPen(penScale);
			painter.drawLine(m_iLeftBorder-m_iMarkerLength, iPosY, m_iLeftBorder, iPosY);
		}
	}

	// draw X axis markers
	unsigned int iStartY = height()-(m_iBottomBorder+2);
	for (unsigned int i = 0;i<m_iMarkersX;i++) {
		int iPosX = m_iLeftBorder+i*iMarkerSpacingX;
		if (i%m_iBigMarkerSpacingX == 0) {
			painter.setPen(penLargeScale);
			painter.drawLine(iPosX, iStartY+m_iBigMarkerLength, iPosX, iStartY);
		} else {
			painter.setPen(penScale);
			painter.drawLine(iPosX, iStartY+m_iMarkerLength, iPosX, iStartY);
		}
	}
}

void Q1DTransferFunction::DrawHistogram(QPainter& painter) {
	// nothing todo if the histogram is empty
	if (m_vHistrogram.size() == 0) return;

	// compute some grid dimensions
	unsigned int iGridWidth  = width()-(m_iLeftBorder+m_iRightBorder)-3;
	unsigned int iGridHeight = height()-(m_iBottomBorder+m_iTopBorder)-2;

	// draw the histogram a as large polygon
	// define the polygon ...
	std::vector<QPointF> pointList;
	pointList.push_back(QPointF(m_iLeftBorder+1, iGridHeight-m_iBottomBorder));
	for (size_t i = 0;i<m_vHistrogram.size();i++)
		pointList.push_back(QPointF(m_iLeftBorder+1+float(iGridWidth)*i/(m_vHistrogram.size()-1), m_iTopBorder+iGridHeight-m_vHistrogram[i]*iGridHeight));
	pointList.push_back(QPointF(m_iLeftBorder+iGridWidth, m_iTopBorder+iGridHeight));
	pointList.push_back(QPointF(m_iLeftBorder+1, m_iTopBorder+iGridHeight));

	// ... draw it
	painter.setPen(Qt::NoPen);
	painter.setBrush(m_colorHistogram);
	painter.drawPolygon(&pointList[0], pointList.size());
}

void Q1DTransferFunction::DrawFunctionPlots(QPainter& painter) {
	// nothing todo if the histogram is empty
	if (m_vHistrogram.size() == 0) return;

	// compute some grid dimensions
	unsigned int iGridWidth  = width()-(m_iLeftBorder+m_iRightBorder)-3;
	unsigned int iGridHeight = height()-(m_iBottomBorder+m_iTopBorder)-2;

	// draw the tranfer function as one larger polyline
	std::vector<QPointF> pointList(m_Trans.pColorData.size());
	QPen penCurve(m_colorBorder, 1, Qt::SolidLine);

	// for every component
	for (unsigned int j = 0;j<4;j++) {

		// select the color
		switch (j) {
			case 0  : penCurve.setColor(m_colorRedLine); break;
			case 1  : penCurve.setColor(m_colorGreenLine); break;
			case 2  : penCurve.setColor(m_colorBlueLine); break;
			default : penCurve.setColor(m_colorAlphaLine); break;
		}

		// define the polyline
		for (size_t i = 0;i<pointList.size();i++)
			pointList[i]= QPointF(m_iLeftBorder+1+float(iGridWidth)*i/(pointList.size()-1),
						          m_iTopBorder+iGridHeight-m_Trans.pColorData[i][j]*iGridHeight);

		// draw the polyline
		painter.setPen(penCurve);
		painter.drawPolyline(&pointList[0], pointList.size());
	}

}

void Q1DTransferFunction::mousePressEvent(QMouseEvent *event) {
	// call superclass method
	QWidget::mousePressEvent(event);
	// clear the "last position" index
	m_iLastIndex = -1;
}

void Q1DTransferFunction::mouseReleaseEvent(QMouseEvent *event) {
	// call superclass method
	QWidget::mouseReleaseEvent(event);
	// clear the "last position" index
	m_iLastIndex = -1;
}

void Q1DTransferFunction::mouseMoveEvent(QMouseEvent *event) {
	// call superclass method
	QWidget::mouseMoveEvent(event);

	// exit if nothing is to be painted
	if (m_iPaintmode == Q1DT_PAINT_NONE) return;

	// compute some grid dimensions
	unsigned int iGridWidth  = width()-(m_iLeftBorder+m_iRightBorder)-3;
	unsigned int iGridHeight = height()-(m_iBottomBorder+m_iTopBorder)-2;
	unsigned int iVectorSize = m_Trans.pColorData.size();

	// compute position in color array
	int iCurrentIndex = int((float(event->x())-float(m_iLeftBorder)-1.0f)*float(iVectorSize-1)/float(iGridWidth));
	iCurrentIndex = std::min<int>(iVectorSize-1, std::max<int>(0,iCurrentIndex));

	// ifnd out the range to change
	if (m_iLastIndex == -1) m_iLastIndex = iCurrentIndex;
	int iIndexMin = std::min(m_iLastIndex,iCurrentIndex);
	int iIndexMax = std::max(m_iLastIndex,iCurrentIndex);
	m_iLastIndex = iCurrentIndex;

	// compute actual color value
	float fValue = (float(m_iTopBorder)+float(iGridHeight)-float(event->y()))/float(iGridHeight);
	fValue	  = std::min<float>(1.0f, std::max<float>(0.0f,fValue));

	// update transfer function
	if (m_iPaintmode & Q1DT_PAINT_RED) {
		for (int iIndex = iIndexMin;iIndex<=iIndexMax;++iIndex) m_Trans.pColorData[iIndex].r = fValue;
	}
	if (m_iPaintmode & Q1DT_PAINT_GREEN) {
		for (int iIndex = iIndexMin;iIndex<=iIndexMax;++iIndex) m_Trans.pColorData[iIndex].g = fValue;
	}
	if (m_iPaintmode & Q1DT_PAINT_BLUE) {
		for (int iIndex = iIndexMin;iIndex<=iIndexMax;++iIndex) m_Trans.pColorData[iIndex].b = fValue;
	}
	if (m_iPaintmode & Q1DT_PAINT_ALPHA) {
		for (int iIndex = iIndexMin;iIndex<=iIndexMax;++iIndex) m_Trans.pColorData[iIndex].a = fValue;
	}

	// redraw this widget
	update();
}

void Q1DTransferFunction::paintEvent(QPaintEvent *event) {
	// call superclass method
	QWidget::paintEvent(event);

	// as drawing the histogram can become quite expensive we'll cache it in an image and only redraw if needed
	if (!m_bBackdropCacheUptodate || (unsigned int)height() != m_iCachedHeight || (unsigned int)width() != m_iCachedWidth) {

		// delete the old pixmap an create a new one if the size has changed
		if ((unsigned int)height() != m_iCachedHeight || (unsigned int)width() != m_iCachedWidth) {
			delete [] m_pBackdropCache;
			m_pBackdropCache = new QPixmap(width(),height());
		}

		// attach a painter to the pixmap
		QPainter image_painter(m_pBackdropCache);

		// draw the abckdrop into the image
		DrawCoordinateSystem(image_painter);
		DrawHistogram(image_painter);

		// update change detection states
		m_bBackdropCacheUptodate = true;
		m_iCachedHeight = height();
		m_iCachedWidth = width();
	}

	// now draw everything rest into this widget
	QPainter painter(this);

	// the image captured before (or cached from a previous call)
	painter.drawImage(0,0,m_pBackdropCache->toImage());

	// and the funtion plots
	DrawFunctionPlots(painter);
}

bool Q1DTransferFunction::LoadFromFile(const QString& strFilename) {
	// hand the load call over to the Transferfunction1D class
	return m_Trans.Load(strFilename.toStdString());
}

bool Q1DTransferFunction::SaveToFile(const QString& strFilename) {
	// hand the save call over to the Transferfunction1D class
	return m_Trans.Save(strFilename.toStdString());
}
<commit_msg><commit_after>#include "Q1DTransferFunction.h"
#include <QtGui/QPainter>
#include <QtGui/QMouseEvent>

Q1DTransferFunction::Q1DTransferFunction(QWidget *parent) :
	QWidget(parent),
	m_iPaintmode(Q1DT_PAINT_NONE),
	m_bBackdropCacheUptodate(false),
	m_iCachedHeight(0),
	m_iCachedWidth(0),
	m_pBackdropCache(NULL),
	// borders, may be changed arbitrarly
	m_iLeftBorder(20),
	m_iBottomBorder(20),
	// automatically computed borders
	m_iRightBorder(0),
	m_iTopBorder(0),
	// colors, may be changed arbitrarily
	m_colorHistogram(50,50,50),
	m_colorBack(Qt::black),
	m_colorBorder(100, 100, 255),
	m_colorScale(100, 100, 255),
	m_colorLargeScale(180, 180, 180),
	m_colorRedLine(255, 0, 0),
	m_colorGreenLine(0, 255, 0),
	m_colorBlueLine(0, 0, 255),
	m_colorAlphaLine(Qt::white),
	// scale apearance, may be changed arbitrarily (except for the marker length wich should both be less or equal to m_iLeftBorder and m_iBottomBorder)
	m_iMarkersX(40),
	m_iMarkersY (40),
	m_iBigMarkerSpacingX(5),
	m_iBigMarkerSpacingY(5),
	m_iMarkerLength(5),
	m_iBigMarkerLength(m_iMarkerLength*3),
	// mouse motion
	m_iLastIndex(-1)
{
}

Q1DTransferFunction::~Q1DTransferFunction(void)
{
	// delete the backdrop cache pixmap
	delete m_pBackdropCache;
}

void Q1DTransferFunction::SetHistogram(std::vector<unsigned int> vHistrogram) {
	// resize the histogram vector
	m_vHistrogram.resize(vHistrogram.size());

	// also resize the transferfunction
	m_Trans.Resize(vHistrogram.size());

	// force the draw routine to recompute the backdrop cache
	m_bBackdropCacheUptodate = false;

	// if the histogram is empty we are done
	if (m_vHistrogram.size() == 0)  return;

	// rescale the histogram to the [0..1] range
	// first find min and max ...
	float fMax = float(vHistrogram[0]), fMin = float(vHistrogram[0]);
	for (size_t i = 0;i<m_vHistrogram.size();i++) {
		if (float(vHistrogram[i]) > fMax) fMax = float(vHistrogram[i]);
		if (float(vHistrogram[i]) < fMin) fMin = float(vHistrogram[i]);

		for (unsigned int j = 0;j<4;j++) m_Trans.pColorData[i][j] = 0.0f;
	}

	// ... than rescale
	float fDiff = fMax-fMin;
	for (size_t i = 0;i<m_vHistrogram.size();i++) {
		m_vHistrogram[i]  = vHistrogram[i] - fMin;
		m_vHistrogram[i] /= fDiff;
	}
}

void Q1DTransferFunction::DrawCoordinateSystem(QPainter& painter) {
	// adjust left and bottom border so that the marker count can be met
	m_iRightBorder   = (width()-(m_iLeftBorder+2))   %m_iMarkersX;
	m_iTopBorder     = (height()-(m_iBottomBorder+2))%m_iMarkersY;

	// compute the actual marker spaceing
	unsigned int iMarkerSpacingX = (width()-(m_iLeftBorder+2))/m_iMarkersX;
	unsigned int iMarkerSpacingY = (height()-(m_iBottomBorder+2))/m_iMarkersY;

	// draw background
	painter.setBrush(m_colorBack);
	QRect backRect(0,0,width(),height());
	painter.drawRect(backRect);

	// draw grid borders
	QPen borderPen(m_colorBorder, 1, Qt::SolidLine);
	painter.setPen(borderPen);
	QRect borderRect(m_iLeftBorder,m_iTopBorder, width()-(m_iLeftBorder+2+m_iRightBorder), height()-(m_iTopBorder+m_iBottomBorder+2));
	painter.drawRect(borderRect);

	// draw Y axis markers
	QPen penScale(m_colorScale, 1, Qt::SolidLine);
	QPen penLargeScale(m_colorLargeScale, 1, Qt::SolidLine);
	for (unsigned int i = 0;i<m_iMarkersY;i++) {
		int iPosY = height()-m_iBottomBorder-2 - i*iMarkerSpacingY;

		if (i%m_iBigMarkerSpacingY == 0) {
			painter.setPen(penLargeScale);
			painter.drawLine(m_iLeftBorder-m_iBigMarkerLength, iPosY, m_iLeftBorder, iPosY);
		} else {
			painter.setPen(penScale);
			painter.drawLine(m_iLeftBorder-m_iMarkerLength, iPosY, m_iLeftBorder, iPosY);
		}
	}

	// draw X axis markers
	unsigned int iStartY = height()-(m_iBottomBorder+2);
	for (unsigned int i = 0;i<m_iMarkersX;i++) {
		int iPosX = m_iLeftBorder+i*iMarkerSpacingX;
		if (i%m_iBigMarkerSpacingX == 0) {
			painter.setPen(penLargeScale);
			painter.drawLine(iPosX, iStartY+m_iBigMarkerLength, iPosX, iStartY);
		} else {
			painter.setPen(penScale);
			painter.drawLine(iPosX, iStartY+m_iMarkerLength, iPosX, iStartY);
		}
	}
}

void Q1DTransferFunction::DrawHistogram(QPainter& painter) {
	// nothing todo if the histogram is empty
	if (m_vHistrogram.size() == 0) return;

	// compute some grid dimensions
	unsigned int iGridWidth  = width()-(m_iLeftBorder+m_iRightBorder)-3;
	unsigned int iGridHeight = height()-(m_iBottomBorder+m_iTopBorder)-2;

	// draw the histogram a as large polygon
	// define the polygon ...
	std::vector<QPointF> pointList;
	pointList.push_back(QPointF(m_iLeftBorder+1, iGridHeight-m_iBottomBorder));
	for (size_t i = 0;i<m_vHistrogram.size();i++)
		pointList.push_back(QPointF(m_iLeftBorder+1+float(iGridWidth)*i/(m_vHistrogram.size()-1), m_iTopBorder+iGridHeight-m_vHistrogram[i]*iGridHeight));
	pointList.push_back(QPointF(m_iLeftBorder+iGridWidth, m_iTopBorder+iGridHeight));
	pointList.push_back(QPointF(m_iLeftBorder+1, m_iTopBorder+iGridHeight));

	// ... draw it
	painter.setPen(Qt::NoPen);
	painter.setBrush(m_colorHistogram);
	painter.drawPolygon(&pointList[0], pointList.size());
}

void Q1DTransferFunction::DrawFunctionPlots(QPainter& painter) {
	// nothing todo if the histogram is empty
	if (m_vHistrogram.size() == 0) return;

	// compute some grid dimensions
	unsigned int iGridWidth  = width()-(m_iLeftBorder+m_iRightBorder)-3;
	unsigned int iGridHeight = height()-(m_iBottomBorder+m_iTopBorder)-2;

	// draw the tranfer function as one larger polyline
	std::vector<QPointF> pointList(m_Trans.pColorData.size());
	QPen penCurve(m_colorBorder, 1, Qt::SolidLine);

	// for every component
	for (unsigned int j = 0;j<4;j++) {

		// select the color
		switch (j) {
			case 0  : penCurve.setColor(m_colorRedLine); break;
			case 1  : penCurve.setColor(m_colorGreenLine); break;
			case 2  : penCurve.setColor(m_colorBlueLine); break;
			default : penCurve.setColor(m_colorAlphaLine); break;
		}

		// define the polyline
		for (size_t i = 0;i<pointList.size();i++)
			pointList[i]= QPointF(m_iLeftBorder+1+float(iGridWidth)*i/(pointList.size()-1),
						          m_iTopBorder+iGridHeight-m_Trans.pColorData[i][j]*iGridHeight);

		// draw the polyline
		painter.setPen(penCurve);
		painter.drawPolyline(&pointList[0], pointList.size());
	}

}

void Q1DTransferFunction::mousePressEvent(QMouseEvent *event) {
	// call superclass method
	QWidget::mousePressEvent(event);
	// clear the "last position" index
	m_iLastIndex = -1;
}

void Q1DTransferFunction::mouseReleaseEvent(QMouseEvent *event) {
	// call superclass method
	QWidget::mouseReleaseEvent(event);
	// clear the "last position" index
	m_iLastIndex = -1;
}

void Q1DTransferFunction::mouseMoveEvent(QMouseEvent *event) {
	// call superclass method
	QWidget::mouseMoveEvent(event);

	// exit if nothing is to be painted
	if (m_iPaintmode == Q1DT_PAINT_NONE) return;

	// compute some grid dimensions
	unsigned int iGridWidth  = width()-(m_iLeftBorder+m_iRightBorder)-3;
	unsigned int iGridHeight = height()-(m_iBottomBorder+m_iTopBorder)-2;
	unsigned int iVectorSize = m_Trans.pColorData.size();

	// compute position in color array
	int iCurrentIndex = int((float(event->x())-float(m_iLeftBorder)-1.0f)*float(iVectorSize-1)/float(iGridWidth));
	iCurrentIndex = std::min<int>(iVectorSize-1, std::max<int>(0,iCurrentIndex));

	// ifnd out the range to change
	if (m_iLastIndex == -1) m_iLastIndex = iCurrentIndex;
	int iIndexMin = std::min(m_iLastIndex,iCurrentIndex);
	int iIndexMax = std::max(m_iLastIndex,iCurrentIndex);
	m_iLastIndex = iCurrentIndex;

	// compute actual color value
	float fValue = (float(m_iTopBorder)+float(iGridHeight)-float(event->y()))/float(iGridHeight);
	fValue	  = std::min<float>(1.0f, std::max<float>(0.0f,fValue));

	// update transfer function
	if (m_iPaintmode & Q1DT_PAINT_RED) {
		for (int iIndex = iIndexMin;iIndex<=iIndexMax;++iIndex) m_Trans.pColorData[iIndex].r = fValue;
	}
	if (m_iPaintmode & Q1DT_PAINT_GREEN) {
		for (int iIndex = iIndexMin;iIndex<=iIndexMax;++iIndex) m_Trans.pColorData[iIndex].g = fValue;
	}
	if (m_iPaintmode & Q1DT_PAINT_BLUE) {
		for (int iIndex = iIndexMin;iIndex<=iIndexMax;++iIndex) m_Trans.pColorData[iIndex].b = fValue;
	}
	if (m_iPaintmode & Q1DT_PAINT_ALPHA) {
		for (int iIndex = iIndexMin;iIndex<=iIndexMax;++iIndex) m_Trans.pColorData[iIndex].a = fValue;
	}

	// redraw this widget
	update();
}

void Q1DTransferFunction::paintEvent(QPaintEvent *event) {
	// call superclass method
	QWidget::paintEvent(event);

	// as drawing the histogram can become quite expensive we'll cache it in an image and only redraw if needed
	if (!m_bBackdropCacheUptodate || (unsigned int)height() != m_iCachedHeight || (unsigned int)width() != m_iCachedWidth) {

		// delete the old pixmap an create a new one if the size has changed
		if ((unsigned int)height() != m_iCachedHeight || (unsigned int)width() != m_iCachedWidth) {
			delete m_pBackdropCache;
			m_pBackdropCache = new QPixmap(width(),height());
		}

		// attach a painter to the pixmap
		QPainter image_painter(m_pBackdropCache);

		// draw the abckdrop into the image
		DrawCoordinateSystem(image_painter);
		DrawHistogram(image_painter);

		// update change detection states
		m_bBackdropCacheUptodate = true;
		m_iCachedHeight = height();
		m_iCachedWidth = width();
	}

	// now draw everything rest into this widget
	QPainter painter(this);

	// the image captured before (or cached from a previous call)
	painter.drawImage(0,0,m_pBackdropCache->toImage());

	// and the funtion plots
	DrawFunctionPlots(painter);
}

bool Q1DTransferFunction::LoadFromFile(const QString& strFilename) {
	// hand the load call over to the Transferfunction1D class
	return m_Trans.Load(strFilename.toStdString());
}

bool Q1DTransferFunction::SaveToFile(const QString& strFilename) {
	// hand the save call over to the Transferfunction1D class
	return m_Trans.Save(strFilename.toStdString());
}
<|endoftext|>


<commit_before>#include "socket.h"
#include "database.h"
#include "configuration.h"
#include "extern.h"
#include "enum.h"

#include <stdio.h>

extern "C" {
#include <unistd.h>
}

extern int run_the_game();

#ifndef LOWTOOLS

int main(int argc, char *argv[])
{
  int a;

  if (!Config::doConfiguration(argc, argv))
    exit(1);

  if (chdir(Config::DataDir().c_str()) < 0) {
    std::cout << format("Failed to chdir to lib directory '%s'\n") % Config::DataDir();
    perror("chdir");
    exit(1);
  }

  vlogf(LOG_MISC, format("Using %s as data directory.") % Config::DataDir());

  if (Config::NoSpecials())
    vlogf(LOG_MISC, "Suppressing assignment of special routines.");

  Uptime = time(0);
  srand(Uptime);

  vlogf(LOG_MISC, format("Running %s on port %d.") %  MUD_NAME_VERS % gamePort);

  if (WizLock)
    vlogf(LOG_MISC, "Starting with wizlock enabled");

  vlogf(LOG_MISC, "Blanking denied hosts.");
  for (a = 0; a < MAX_BAN_HOSTS; a++) {
    strcpy(hostLogList[a], "");
    strcpy(hostlist[a], "");
  }
  numberhosts = 0;
  numberLogHosts = 0;

#if 0
  // graceful, but too bad its not informative about the exception
  // (could try vlogf_trace here instead of assert?)
  try {
    run_the_game();
  } catch (...) {
    mud_assert(0, "Caught an exception");
  }
#else
  run_the_game();
#endif

  generic_cleanup();

  return (0);
}

#endif
<commit_msg>wrap server main in exception-catching block<commit_after>#include <errno.h>

#include "configuration.h"
#include "extern.h"
#include "enum.h"
#include "comm.h"
#include "socket.h"

int game_main(int argc, char *argv[])
{
  if (!Config::doConfiguration(argc, argv)) {
    vlogf(LOG_FILE, "failed configuration");
    exit(1);
  }

  if (!chdir(Config::DataDir().c_str())) {
    vlogf(LOG_FILE, format("failed chdir to lib directory '%s': %s") %
            Config::DataDir() % strerror(errno));
    exit(1);
  }

  vlogf(LOG_MISC, format("Using %s as data directory.") % Config::DataDir());

  if (Config::NoSpecials())
    vlogf(LOG_MISC, "Suppressing assignment of special routines.");

  if (WizLock)
    vlogf(LOG_MISC, "Starting with wizlock enabled");

  Uptime = time(0);
  srand(Uptime);

  run_the_game();

  generic_cleanup();

  return 0;
}

int main(int argc, char **argv)
{
  try {
    return game_main(argc, argv);
  } catch (const std::exception &e) {
    vlogf_trace(LOG_BUG, format("Exception (std::exception) thrown: %s") % e.what() );
  } catch (const char *s) {
    vlogf_trace(LOG_BUG, format("Exception (char *) thrown: %s") % s );
  } catch (const std::string &s) {
    vlogf_trace(LOG_BUG, format("Exception (std::string) thrown: %s") % s );
  }
  return -1;
}
<|endoftext|>


<commit_before><commit_msg>Revert of Return an accessible value for all HTML input elements. (patchset #2 id:20001 of https://codereview.chromium.org/739753002/)<commit_after><|endoftext|>


<commit_before>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)
*
* All rights reserved.
*
* 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 name of Hobu, Inc. or Flaxen Geo Consulting 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 <iostream>

#include <boost/scoped_ptr.hpp>

#include <pdal/Stage.hpp>
#include <pdal/StageIterator.hpp>
#include <pdal/SchemaLayout.hpp>
#include <pdal/FileUtils.hpp>
#include <pdal/PointBuffer.hpp>
#include <pdal/filters/StatsFilter.hpp>

#include "AppSupport.hpp"
#include "Application.hpp"

class PcInfo : public Application
{
public:
    PcInfo(int argc, char* argv[]);
    int execute();

private:
    void addOptions();
    void validateOptions();
    void readOnePoint();
    void readAllPoints();

    pdal::Stage* m_reader;
    std::string m_inputFile;
    boost::uint64_t m_pointNumber;
    boost::scoped_ptr<pdal::filters::StatsFilter> m_filter;
};

PcInfo::PcInfo(int argc, char* argv[])
    : Application(argc, argv, "pcinfo")
    , m_reader(NULL)
    , m_inputFile("")
    , m_pointNumber(0)
{
    return;
}

void PcInfo::validateOptions()
{
    if (!hasOption("input"))
    {
        throw app_usage_error("input file name required");
    }

    return;
}

void PcInfo::addOptions()
{
    namespace po = boost::program_options;

    po::options_description* file_options = new po::options_description("file options");

    file_options->add_options()
        ("input,i", po::value<std::string>(&m_inputFile), "input file name")
        ("liblas", "use libLAS driver (not PDAL native driver)")
        ;

    addOptionSet(file_options);

    po::options_description* processing_options = new po::options_description("processing options");

    processing_options->add_options()
        ("point,p", po::value<boost::uint64_t>(&m_pointNumber), "point to dump")
        ("points,a", "dump stats on all points (read entire dataset)")
        ;

    addOptionSet(processing_options);

    addPositionalOption("input", 1);

    return;
}

void PcInfo::readOnePoint()
{
    const pdal::Schema& schema = m_reader->getSchema();
    pdal::SchemaLayout layout(schema);

    pdal::PointBuffer data(layout, 1);

    boost::scoped_ptr<pdal::StageSequentialIterator> iter(m_reader->createSequentialIterator());
    iter->skip(m_pointNumber);

    const boost::uint32_t numRead = iter->read(data);
    if (numRead != 1)
    {
        throw app_runtime_error("problem reading point number " + m_pointNumber);
    }

    std::cout << "Read point " << m_pointNumber << "\n";

    return;
}

void PcInfo::readAllPoints()
{
    const pdal::Schema& schema = m_reader->getSchema();
    pdal::SchemaLayout layout(schema);

    boost::scoped_ptr<pdal::StageSequentialIterator> iter(m_reader->createSequentialIterator());

    boost::uint64_t totRead = 0;
    while (!iter->atEnd())
    {
        pdal::PointBuffer data(layout, 1024);

        const boost::uint32_t numRead = iter->read(data);
        totRead += numRead;
    }

    std::cout << "Read " << totRead << " points\n";

    return;
}

int PcInfo::execute()
{
    if (!pdal::FileUtils::fileExists(m_inputFile))
    {
        throw app_runtime_error("file not found: " + m_inputFile);
    }

    std::string driver = AppSupport::inferReaderDriver(m_inputFile);

    if (driver == "")
    {
        throw app_runtime_error("Cannot determine file type of " + m_inputFile);
    }

    if (hasOption("liblas") && driver == "drivers.las.reader")
    {
        driver = "drivers.liblas.reader";
    }

    pdal::Options options;
    options.add<bool>("debug", isDebug());
    options.add<boost::uint8_t>("verbose", getVerboseLevel());

    m_reader = AppSupport::createReader(driver, m_inputFile, options);

    m_reader->initialize();

    if (hasOption("point"))
    {
        readOnePoint();
    }

    if (hasOption("points"))
    {
        readAllPoints();
    }

    {
        const boost::uint64_t numPoints = m_reader->getNumPoints();
        const pdal::SpatialReference& srs = m_reader->getSpatialReference();

        std::cout << "driver type: " << m_reader->getName() << "\n";
        std::cout << numPoints << " points\n";
        std::cout << "WKT: " << srs.getWKT() << "\n";
    }

    return 0;
}

int main(int argc, char* argv[])
{
    PcInfo app(argc, argv);
    return app.run();
}

#if 0

liblas::Summary check_points(   liblas::Reader& reader,
                                std::vector<liblas::FilterPtr>& filters,
                                std::vector<liblas::TransformPtr>& transforms,
                                bool verbose)
{

    liblas::Summary summary;

    reader.SetFilters(filters);
    reader.SetTransforms(transforms);

    if (verbose)
    std::cout << "Scanning points:"
        << "\n - : "
        << std::endl;

    //
    // Translation of points cloud to features set
    //
    boost::uint32_t i = 0;
    boost::uint32_t const size = reader.GetHeader().GetPointRecordsCount();

    while (reader.ReadNextPoint())
    {
        liblas::Point const& p = reader.GetPoint();
        summary.AddPoint(p);
        if (verbose)
            term_progress(std::cout, (i + 1) / static_cast<double>(size));
        i++;

    }
    if (verbose)
        std::cout << std::endl;

    return summary;

}

void PrintVLRs(std::ostream& os, liblas::Header const& header)
{
    if (!header.GetRecordsCount())
        return ;

    os << "---------------------------------------------------------" << std::endl;
    os << "  VLR Summary" << std::endl;
    os << "---------------------------------------------------------" << std::endl;

    typedef std::vector<VariableRecord>::size_type size_type;
    for(size_type i = 0; i < header.GetRecordsCount(); i++) {
        liblas::VariableRecord const& v = header.GetVLR(i);
        os << v;
    }

}

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

    std::string input;

    bool verbose = false;
    bool check = true;
    bool show_vlrs = true;
    bool show_schema = true;
    bool output_xml = false;
    bool output_json = false;
    bool show_point = false;
    bool use_locale = false;
    boost::uint32_t point = 0;

        file_options.add_options()
            ("no-vlrs", po::value<bool>(&show_vlrs)->zero_tokens()->implicit_value(false), "Don't show VLRs")
            ("no-schema", po::value<bool>(&show_schema)->zero_tokens()->implicit_value(false), "Don't show schema")
            ("no-check", po::value<bool>(&check)->zero_tokens()->implicit_value(false), "Don't scan points")
            ("xml", po::value<bool>(&output_xml)->zero_tokens()->implicit_value(true), "Output as XML")
            ("point,p", po::value<boost::uint32_t>(&point), "Display a point with a given id.  --point 44")

            ("locale", po::value<bool>(&use_locale)->zero_tokens()->implicit_value(true), "Use the environment's locale for output")

// --xml
// --json
// --restructured text output

        if (vm.count("point"))
        {
            show_point = true;
        }

        if (show_point)
        {
            try
            {
                reader.ReadPointAt(point);
                liblas::Point const& p = reader.GetPoint();
                if (output_xml) {
                    liblas::property_tree::ptree tree;
                    tree = p.GetPTree();
                    liblas::property_tree::write_xml(std::cout, tree);
                    exit(0);
                }
                else
                {
                    if (use_locale)
                    {
                        std::locale l("");
                        std::cout.imbue(l);
                    }
                    std::cout <<  p << std::endl;
                    exit(0);
                }

            } catch (std::out_of_range const& e)
            {
                std::cerr << "Unable to read point at index " << point << ": " << e.what() << std::endl;
                exit(1);

            }

        }

        liblas::Summary summary;
        if (check)
            summary = check_points(  reader,
                            filters,
                            transforms,
                            verbose
                            );

        liblas::Header const& header = reader.GetHeader();

        // Add the header to the summary so we can get more detailed
        // info
        summary.SetHeader(header);

        if (output_xml && output_json) {
            std::cerr << "both JSON and XML output cannot be chosen";
            return 1;
        }
        if (output_xml) {
            liblas::property_tree::ptree tree;
            if (check)
                tree = summary.GetPTree();
            else
            {
                tree.add_child("summary.header", header.GetPTree());
            }

            liblas::property_tree::write_xml(std::cout, tree);
            return 0;
        }

        if (use_locale)
        {
            std::locale l("");
            std::cout.imbue(l);
        }

        std::cout << header << std::endl;
        if (show_vlrs)
            PrintVLRs(std::cout, header);

        if (show_schema)
            std::cout << header.GetSchema();

        if (check) {
            std::cout << summary << std::endl;

        }
    }

#endif
<commit_msg>dump a point<commit_after>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)
*
* All rights reserved.
*
* 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 name of Hobu, Inc. or Flaxen Geo Consulting 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 <iostream>

#include <boost/scoped_ptr.hpp>

#include <pdal/Stage.hpp>
#include <pdal/StageIterator.hpp>
#include <pdal/SchemaLayout.hpp>
#include <pdal/FileUtils.hpp>
#include <pdal/PointBuffer.hpp>
#include <pdal/filters/StatsFilter.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/property_tree/json_parser.hpp>

#include "AppSupport.hpp"
#include "Application.hpp"

class PcInfo : public Application
{
public:
    PcInfo(int argc, char* argv[]);
    int execute();

private:
    void addOptions();
    void validateOptions();
    void readOnePoint();
    void readAllPoints();

    pdal::Stage* m_reader;
    std::string m_inputFile;
    boost::uint64_t m_pointNumber;
    boost::scoped_ptr<pdal::filters::StatsFilter> m_filter;
};

PcInfo::PcInfo(int argc, char* argv[])
    : Application(argc, argv, "pcinfo")
    , m_reader(NULL)
    , m_inputFile("")
    , m_pointNumber(0)
{
    return;
}

void PcInfo::validateOptions()
{
    if (!hasOption("input"))
    {
        throw app_usage_error("input file name required");
    }

    return;
}

void PcInfo::addOptions()
{
    namespace po = boost::program_options;

    po::options_description* file_options = new po::options_description("file options");

    file_options->add_options()
        ("input,i", po::value<std::string>(&m_inputFile), "input file name")
        ("liblas", "use libLAS driver (not PDAL native driver)")
        ;

    addOptionSet(file_options);

    po::options_description* processing_options = new po::options_description("processing options");

    processing_options->add_options()
        ("point,p", po::value<boost::uint64_t>(&m_pointNumber), "point to dump")
        ("points,a", "dump stats on all points (read entire dataset)")
        ;

    addOptionSet(processing_options);

    addPositionalOption("input", 1);

    return;
}

void PcInfo::readOnePoint()
{
    const pdal::Schema& schema = m_reader->getSchema();
    pdal::SchemaLayout layout(schema);

    pdal::PointBuffer data(layout, 1);

    boost::scoped_ptr<pdal::StageSequentialIterator> iter(m_reader->createSequentialIterator());
    iter->skip(m_pointNumber);

    const boost::uint32_t numRead = iter->read(data);
    if (numRead != 1)
    {
        throw app_runtime_error("problem reading point number " + m_pointNumber);
    }

    std::cout << "Read point " << m_pointNumber << ":\n";

    boost::property_tree::ptree t = data.toPTree();
    write_json(std::cout, t.get_child("0"));

    std::cout << "\n";

    return;
}

void PcInfo::readAllPoints()
{
    const pdal::Schema& schema = m_reader->getSchema();
    pdal::SchemaLayout layout(schema);

    boost::scoped_ptr<pdal::StageSequentialIterator> iter(m_reader->createSequentialIterator());

    boost::uint64_t totRead = 0;
    while (!iter->atEnd())
    {
        pdal::PointBuffer data(layout, iter->getChunkSize());

        const boost::uint32_t numRead = iter->read(data);
        totRead += numRead;
    }

    std::cout << "Read " << totRead << " points\n";

    return;
}

int PcInfo::execute()
{
    if (!pdal::FileUtils::fileExists(m_inputFile))
    {
        throw app_runtime_error("file not found: " + m_inputFile);
    }

    std::string driver = AppSupport::inferReaderDriver(m_inputFile);

    if (driver == "")
    {
        throw app_runtime_error("Cannot determine file type of " + m_inputFile);
    }

    if (hasOption("liblas") && driver == "drivers.las.reader")
    {
        driver = "drivers.liblas.reader";
    }

    pdal::Options options;
    options.add<bool>("debug", isDebug());
    options.add<boost::uint8_t>("verbose", getVerboseLevel());

    m_reader = AppSupport::createReader(driver, m_inputFile, options);

    m_reader->initialize();

    if (hasOption("point"))
    {
        readOnePoint();
    }

    if (hasOption("points"))
    {
        readAllPoints();
    }

    {
        const boost::uint64_t numPoints = m_reader->getNumPoints();
        const pdal::SpatialReference& srs = m_reader->getSpatialReference();

        std::cout << "driver type: " << m_reader->getName() << "\n";
        std::cout << numPoints << " points\n";
        std::cout << "WKT: " << srs.getWKT() << "\n";
    }

    return 0;
}

int main(int argc, char* argv[])
{
    PcInfo app(argc, argv);
    return app.run();
}

#if 0

liblas::Summary check_points(   liblas::Reader& reader,
                                std::vector<liblas::FilterPtr>& filters,
                                std::vector<liblas::TransformPtr>& transforms,
                                bool verbose)
{

    liblas::Summary summary;

    reader.SetFilters(filters);
    reader.SetTransforms(transforms);

    if (verbose)
    std::cout << "Scanning points:"
        << "\n - : "
        << std::endl;

    //
    // Translation of points cloud to features set
    //
    boost::uint32_t i = 0;
    boost::uint32_t const size = reader.GetHeader().GetPointRecordsCount();

    while (reader.ReadNextPoint())
    {
        liblas::Point const& p = reader.GetPoint();
        summary.AddPoint(p);
        if (verbose)
            term_progress(std::cout, (i + 1) / static_cast<double>(size));
        i++;

    }
    if (verbose)
        std::cout << std::endl;

    return summary;

}

void PrintVLRs(std::ostream& os, liblas::Header const& header)
{
    if (!header.GetRecordsCount())
        return ;

    os << "---------------------------------------------------------" << std::endl;
    os << "  VLR Summary" << std::endl;
    os << "---------------------------------------------------------" << std::endl;

    typedef std::vector<VariableRecord>::size_type size_type;
    for(size_type i = 0; i < header.GetRecordsCount(); i++) {
        liblas::VariableRecord const& v = header.GetVLR(i);
        os << v;
    }

}

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

    std::string input;

    bool verbose = false;
    bool check = true;
    bool show_vlrs = true;
    bool show_schema = true;
    bool output_xml = false;
    bool output_json = false;
    bool show_point = false;
    bool use_locale = false;
    boost::uint32_t point = 0;

        file_options.add_options()
            ("no-vlrs", po::value<bool>(&show_vlrs)->zero_tokens()->implicit_value(false), "Don't show VLRs")
            ("no-schema", po::value<bool>(&show_schema)->zero_tokens()->implicit_value(false), "Don't show schema")
            ("no-check", po::value<bool>(&check)->zero_tokens()->implicit_value(false), "Don't scan points")
            ("xml", po::value<bool>(&output_xml)->zero_tokens()->implicit_value(true), "Output as XML")
            ("point,p", po::value<boost::uint32_t>(&point), "Display a point with a given id.  --point 44")

            ("locale", po::value<bool>(&use_locale)->zero_tokens()->implicit_value(true), "Use the environment's locale for output")

// --xml
// --json
// --restructured text output

        if (vm.count("point"))
        {
            show_point = true;
        }

        if (show_point)
        {
            try
            {
                reader.ReadPointAt(point);
                liblas::Point const& p = reader.GetPoint();
                if (output_xml) {
                    liblas::property_tree::ptree tree;
                    tree = p.GetPTree();
                    liblas::property_tree::write_xml(std::cout, tree);
                    exit(0);
                }
                else
                {
                    if (use_locale)
                    {
                        std::locale l("");
                        std::cout.imbue(l);
                    }
                    std::cout <<  p << std::endl;
                    exit(0);
                }

            } catch (std::out_of_range const& e)
            {
                std::cerr << "Unable to read point at index " << point << ": " << e.what() << std::endl;
                exit(1);

            }

        }

        liblas::Summary summary;
        if (check)
            summary = check_points(  reader,
                            filters,
                            transforms,
                            verbose
                            );

        liblas::Header const& header = reader.GetHeader();

        // Add the header to the summary so we can get more detailed
        // info
        summary.SetHeader(header);

        if (output_xml && output_json) {
            std::cerr << "both JSON and XML output cannot be chosen";
            return 1;
        }
        if (output_xml) {
            liblas::property_tree::ptree tree;
            if (check)
                tree = summary.GetPTree();
            else
            {
                tree.add_child("summary.header", header.GetPTree());
            }

            liblas::property_tree::write_xml(std::cout, tree);
            return 0;
        }

        if (use_locale)
        {
            std::locale l("");
            std::cout.imbue(l);
        }

        std::cout << header << std::endl;
        if (show_vlrs)
            PrintVLRs(std::cout, header);

        if (show_schema)
            std::cout << header.GetSchema();

        if (check) {
            std::cout << summary << std::endl;

        }
    }

#endif
<|endoftext|>


<commit_before>//===-- interception_linux_test.cc ----------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file is a part of ThreadSanitizer/AddressSanitizer runtime.
// Tests for interception_linux.h.
//
//===----------------------------------------------------------------------===//

// Do not declare isdigit in ctype.h.
#define __NO_CTYPE

#include "interception/interception.h"

#include "gtest/gtest.h"

// Too slow for debug build
#if !SANITIZER_DEBUG
#if SANITIZER_LINUX

static int InterceptorFunctionCalled;

DECLARE_REAL(int, isdigit, int);

INTERCEPTOR(int, isdigit, int d) {
  ++InterceptorFunctionCalled;
  return d >= '0' && d <= '9';
}

namespace __interception {

TEST(Interception, GetRealFunctionAddress) {
  uptr malloc_address = 0;
  EXPECT_TRUE(GetRealFunctionAddress("malloc", &malloc_address, 0, 0));
  EXPECT_NE(0U, malloc_address);

  uptr dummy_address = 0;
  EXPECT_TRUE(
      GetRealFunctionAddress("dummy_doesnt_exist__", &dummy_address, 0, 0));
  EXPECT_EQ(0U, dummy_address);
}

TEST(Interception, GetFuncAddr) {
  EXPECT_NE(GetFuncAddr("malloc"), nullptr);
  EXPECT_EQ(GetFuncAddr("does_not_exist"), nullptr);
}

TEST(Interception, Basic) {
  // After interception, the counter should be incremented.
  InterceptorFunctionCalled = 0;
  EXPECT_NE(0, isdigit('1'));
  EXPECT_EQ(1, InterceptorFunctionCalled);
  EXPECT_EQ(0, isdigit('a'));
  EXPECT_EQ(2, InterceptorFunctionCalled);

  // Calling the REAL function should not affect the counter.
  InterceptorFunctionCalled = 0;
  EXPECT_NE(0, REAL(isdigit)('1'));
  EXPECT_EQ(0, REAL(isdigit)('a'));
  EXPECT_EQ(0, InterceptorFunctionCalled);
}

}  // namespace __interception

#endif  // SANITIZER_LINUX
#endif  // #if !SANITIZER_DEBUG
<commit_msg>[Sanitizer] Fix test<commit_after>//===-- interception_linux_test.cc ----------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file is a part of ThreadSanitizer/AddressSanitizer runtime.
// Tests for interception_linux.h.
//
//===----------------------------------------------------------------------===//

// Do not declare isdigit in ctype.h.
#define __NO_CTYPE

#include "interception/interception.h"

#include "gtest/gtest.h"

// Too slow for debug build
#if !SANITIZER_DEBUG
#if SANITIZER_LINUX

static int InterceptorFunctionCalled;

DECLARE_REAL(int, isdigit, int);

INTERCEPTOR(int, isdigit, int d) {
  ++InterceptorFunctionCalled;
  return d >= '0' && d <= '9';
}

namespace __interception {

TEST(Interception, GetRealFunctionAddress) {
  uptr malloc_address = 0;
  EXPECT_TRUE(GetRealFunctionAddress("malloc", &malloc_address, 0, 0));
  EXPECT_NE(0U, malloc_address);

  uptr dummy_address = 0;
  EXPECT_TRUE(
      GetRealFunctionAddress("dummy_doesnt_exist__", &dummy_address, 0, 0));
  EXPECT_EQ(0U, dummy_address);
}

TEST(Interception, GetFuncAddr) {
  EXPECT_NE(GetFuncAddr("malloc"), nullptr);
  EXPECT_EQ(GetFuncAddr("does_not_exist"), nullptr);
}

TEST(Interception, Basic) {
  INTERCEPT_FUNCTION(isdigit);

  // After interception, the counter should be incremented.
  InterceptorFunctionCalled = 0;
  EXPECT_NE(0, isdigit('1'));
  EXPECT_EQ(1, InterceptorFunctionCalled);
  EXPECT_EQ(0, isdigit('a'));
  EXPECT_EQ(2, InterceptorFunctionCalled);

  // Calling the REAL function should not affect the counter.
  InterceptorFunctionCalled = 0;
  EXPECT_NE(0, REAL(isdigit)('1'));
  EXPECT_EQ(0, REAL(isdigit)('a'));
  EXPECT_EQ(0, InterceptorFunctionCalled);
}

}  // namespace __interception

#endif  // SANITIZER_LINUX
#endif  // #if !SANITIZER_DEBUG
<|endoftext|>