text:
/**************************************************************
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 *
 *************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_slideshow.hxx"

#include <boost/current_function.hpp>
#include <rtl/ustrbuf.hxx>
#include <vcl/svapp.hxx>
#include <vcl/gdimtf.hxx>
#include <vcl/virdev.hxx>
#include <vcl/metric.hxx>
#include <cppcanvas/vclfactory.hxx>
#include <cppcanvas/basegfxfactory.hxx>
#include <basegfx/range/b2drange.hxx>

#include <comphelper/anytostring.hxx>
#include <cppuhelper/exc_hlp.hxx>

#include <com/sun/star/awt/MouseButton.hpp>
#include <com/sun/star/awt/MouseEvent.hpp>
#include <com/sun/star/rendering/XBitmap.hpp>

#include "eventqueue.hxx"
#include "screenupdater.hxx"
#include "eventmultiplexer.hxx"
#include "activitiesqueue.hxx"
#include "slideshowcontext.hxx"
#include "mouseeventhandler.hxx"
#include "rehearsetimingsactivity.hxx"

#include <boost/bind.hpp>
#include <algorithm>

using namespace com::sun::star;
using namespace com::sun::star::uno;

namespace slideshow {
namespace internal {

class RehearseTimingsActivity::WakeupEvent : public Event,
                                             private ::boost::noncopyable
{
public:
    WakeupEvent( boost::shared_ptr< ::canvas::tools::ElapsedTime > const& pTimeBase,
                 ActivitySharedPtr const&                                 rActivity,
                 ActivitiesQueue &                                        rActivityQueue ) :
#if OSL_DEBUG_LEVEL > 1
        Event(::rtl::OUString::createFromAscii("WakeupEvent")),
#endif
        maTimer(pTimeBase),
        mnNextTime(0.0),
        mpActivity(rActivity),
        mrActivityQueue( rActivityQueue )
    {}

    virtual void dispose() {}
    virtual bool fire()
    {
        ActivitySharedPtr pActivity( mpActivity.lock() );
        if( !pActivity )
            return false;

        return mrActivityQueue.addActivity( pActivity );
    }

    virtual bool isCharged() const { return true; }
    virtual double getActivationTime( double nCurrentTime ) const
    {
        const double nElapsedTime( maTimer.getElapsedTime() );

        return ::std::max( nCurrentTime,
                           nCurrentTime - nElapsedTime + mnNextTime );
    }

    /// Start the internal timer
    void start() { maTimer.reset(); }

    /** Set the next timeout this object should generate.

        @param nextTime
        Absolute time, measured from the last start() call,
        when this event should wakeup the Activity again. If
        your time is relative, simply call start() just before
        every setNextTimeout() call.
    */
    void setNextTimeout( double nextTime ) { mnNextTime = nextTime; }

private:
    ::canvas::tools::ElapsedTime    maTimer;
    double                          mnNextTime;
    boost::weak_ptr<Activity>       mpActivity;
    ActivitiesQueue&                mrActivityQueue;
};

class RehearseTimingsActivity::MouseHandler : public MouseEventHandler,
                                              private boost::noncopyable
{
public:
    explicit MouseHandler( RehearseTimingsActivity& rta );

    void reset();
    bool hasBeenClicked() const { return mbHasBeenClicked; }

    // MouseEventHandler
    virtual bool handleMousePressed( awt::MouseEvent const & evt );
    virtual bool handleMouseReleased( awt::MouseEvent const & evt );
    virtual bool handleMouseEntered( awt::MouseEvent const & evt );
    virtual bool handleMouseExited( awt::MouseEvent const & evt );
    virtual bool handleMouseDragged( awt::MouseEvent const & evt );
    virtual bool handleMouseMoved( awt::MouseEvent const & evt );

private:
    bool isInArea( com::sun::star::awt::MouseEvent const & evt ) const;
    void updatePressedState( const bool pressedState ) const;

    RehearseTimingsActivity& mrActivity;
    bool                     mbHasBeenClicked;
    bool                     mbMouseStartedInArea;
};

const sal_Int32 LEFT_BORDER_SPACE  = 10;
const sal_Int32 LOWER_BORDER_SPACE = 30;

RehearseTimingsActivity::RehearseTimingsActivity( const SlideShowContext& rContext ) :
    mrEventQueue(rContext.mrEventQueue),
    mrScreenUpdater(rContext.mrScreenUpdater),
    mrEventMultiplexer(rContext.mrEventMultiplexer),
    mrActivitiesQueue(rContext.mrActivitiesQueue),
    maElapsedTime( rContext.mrEventQueue.getTimer() ),
    maViews(),
    maSpriteRectangle(),
    maFont( Application::GetSettings().GetStyleSettings().GetInfoFont() ),
    mpWakeUpEvent(),
    mpMouseHandler(),
    maSpriteSizePixel(),
    mnYOffset(0),
    mbActive(false),
    mbDrawPressed(false)
{
    maFont.SetHeight( maFont.GetHeight() * 2 );
    maFont.SetWidth( maFont.GetWidth() * 2 );
    maFont.SetAlign( ALIGN_BASELINE );
    maFont.SetColor( COL_BLACK );

    // determine sprite size (in pixel):
    VirtualDevice blackHole;
    blackHole.EnableOutput(false);
    blackHole.SetFont( maFont );
    blackHole.SetMapMode( MAP_PIXEL );
    Rectangle rect;
    const FontMetric metric( blackHole.GetFontMetric() );
    blackHole.GetTextBoundRect(
        rect, String(RTL_CONSTASCII_USTRINGPARAM("XX:XX:XX")) );
    maSpriteSizePixel.setX( rect.getWidth() * 12 / 10 );
    maSpriteSizePixel.setY( metric.GetLineHeight() * 11 / 10 );
    mnYOffset = (metric.GetAscent() + (metric.GetLineHeight() / 20));

    std::for_each( rContext.mrViewContainer.begin(),
                   rContext.mrViewContainer.end(),
                   boost::bind( &RehearseTimingsActivity::viewAdded,
                                this,
                                _1 ));
}

RehearseTimingsActivity::~RehearseTimingsActivity()
{
    try
    {
        stop();
    }
    catch (uno::Exception &)
    {
        OSL_ENSURE( false, rtl::OUStringToOString(
                        comphelper::anyToString(
                            cppu::getCaughtException() ),
                        RTL_TEXTENCODING_UTF8 ).getStr() );
    }
}

boost::shared_ptr<RehearseTimingsActivity> RehearseTimingsActivity::create(
    const SlideShowContext& rContext )
{
    boost::shared_ptr<RehearseTimingsActivity> pActivity(
        new RehearseTimingsActivity( rContext ));

    pActivity->mpMouseHandler.reset(
        new MouseHandler(*pActivity.get()) );
    pActivity->mpWakeUpEvent.reset(
        new WakeupEvent( rContext.mrEventQueue.getTimer(),
                         pActivity,
                         rContext.mrActivitiesQueue ));

    rContext.mrEventMultiplexer.addViewHandler( pActivity );

    return pActivity;
}

void RehearseTimingsActivity::start()
{
    maElapsedTime.reset();
    mbDrawPressed = false;
    mbActive = true;

    // paint and show all sprites:
    paintAllSprites();
    for_each_sprite( boost::bind( &cppcanvas::Sprite::show, _1 ) );

    mrActivitiesQueue.addActivity( shared_from_this() );

    mpMouseHandler->reset();
    mrEventMultiplexer.addClickHandler(
        mpMouseHandler, 42 /* highest prio of all, > 3.0 */ );
    mrEventMultiplexer.addMouseMoveHandler(
        mpMouseHandler, 42 /* highest prio of all, > 3.0 */ );
}

double RehearseTimingsActivity::stop()
{
    mrEventMultiplexer.removeMouseMoveHandler( mpMouseHandler );
    mrEventMultiplexer.removeClickHandler( mpMouseHandler );

    mbActive = false; // will be removed from queue

    for_each_sprite( boost::bind( &cppcanvas::Sprite::hide, _1 ) );

    return maElapsedTime.getElapsedTime();
}

bool RehearseTimingsActivity::hasBeenClicked() const
{
    if (mpMouseHandler)
        return mpMouseHandler->hasBeenClicked();
    return false;
}

// Disposable:
void RehearseTimingsActivity::dispose()
{
    stop();

    mpWakeUpEvent.reset();
    mpMouseHandler.reset();

    ViewsVecT().swap( maViews );
}

// Activity:
double RehearseTimingsActivity::calcTimeLag() const
{
    return 0.0;
}

bool RehearseTimingsActivity::perform()
{
    if( !isActive() )
        return false;

    if( !mpWakeUpEvent )
        return false;

    mpWakeUpEvent->start();
    mpWakeUpEvent->setNextTimeout( 0.5 );
    mrEventQueue.addEvent( mpWakeUpEvent );

    paintAllSprites();

    // sprites changed, need screen update
    mrScreenUpdater.notifyUpdate();

    return false; // don't reinsert, WakeupEvent will perform
                  // that after the given timeout
}

bool RehearseTimingsActivity::isActive() const
{
    return mbActive;
}

void RehearseTimingsActivity::dequeued()
{
    // not used here
}

void RehearseTimingsActivity::end()
{
    if (isActive())
    {
        stop();
        mbActive = false;
    }
}

basegfx::B2DRange RehearseTimingsActivity::calcSpriteRectangle( UnoViewSharedPtr const& rView ) const
{
    const Reference<rendering::XBitmap> xBitmap( rView->getCanvas()->getUNOCanvas(),
                                                 UNO_QUERY );
    if( !xBitmap.is() )
        return basegfx::B2DRange();

    const geometry::IntegerSize2D realSize( xBitmap->getSize() );
    // pixel:
    basegfx::B2DPoint spritePos(
        std::min<sal_Int32>( realSize.Width, LEFT_BORDER_SPACE ),
        std::max<sal_Int32>( 0, realSize.Height - maSpriteSizePixel.getY()
                                                - LOWER_BORDER_SPACE ) );
    basegfx::B2DHomMatrix transformation( rView->getTransformation() );
    transformation.invert();
    spritePos *= transformation;
    basegfx::B2DSize spriteSize( maSpriteSizePixel.getX(),
                                 maSpriteSizePixel.getY() );
    spriteSize *= transformation;
    return basegfx::B2DRange(
        spritePos.getX(), spritePos.getY(),
        spritePos.getX() + spriteSize.getX(),
        spritePos.getY() + spriteSize.getY() );
}

void RehearseTimingsActivity::viewAdded( const UnoViewSharedPtr& rView )
{
    cppcanvas::CustomSpriteSharedPtr sprite(
        rView->createSprite( basegfx::B2DSize(
                                 maSpriteSizePixel.getX()+2,
                                 maSpriteSizePixel.getY()+2 ),
                             1001.0 )); // sprite should be in front of all
                                        // other sprites
    sprite->setAlpha( 0.8 );
    const basegfx::B2DRange spriteRectangle(
        calcSpriteRectangle( rView ) );
    sprite->move( basegfx::B2DPoint(
                      spriteRectangle.getMinX(),
                      spriteRectangle.getMinY() ) );

    if( maViews.empty() )
        maSpriteRectangle = spriteRectangle;

    maViews.push_back( ViewsVecT::value_type( rView, sprite ) );

    if (isActive())
        sprite->show();
}

void RehearseTimingsActivity::viewRemoved( const UnoViewSharedPtr& rView )
{
    maViews.erase(
        std::remove_if(
            maViews.begin(), maViews.end(),
            boost::bind(
                std::equal_to<UnoViewSharedPtr>(),
                rView,
                // select view:
                boost::bind( std::select1st<ViewsVecT::value_type>(), _1 ))),
        maViews.end() );
}

void RehearseTimingsActivity::viewChanged( const UnoViewSharedPtr& rView )
{
    // find entry corresponding to modified view
    ViewsVecT::iterator aModifiedEntry(
        std::find_if(
            maViews.begin(),
            maViews.end(),
            boost::bind(
                std::equal_to<UnoViewSharedPtr>(),
                rView,
                // select view:
                boost::bind( std::select1st<ViewsVecT::value_type>(), _1 ))));

    OSL_ASSERT( aModifiedEntry != maViews.end() );
    if( aModifiedEntry == maViews.end() )
        return;

    // new sprite pos, transformation might have changed:
    maSpriteRectangle = calcSpriteRectangle( rView );

    // reposition sprite:
    aModifiedEntry->second->move( maSpriteRectangle.getMinimum() );

    // sprites changed, need screen update
    mrScreenUpdater.notifyUpdate( rView );
}

void RehearseTimingsActivity::viewsChanged()
{
    if( !maViews.empty() )
    {
        // new sprite pos, transformation might have changed:
        maSpriteRectangle = calcSpriteRectangle( maViews.front().first );

        // reposition sprites
        for_each_sprite( boost::bind( &cppcanvas::Sprite::move,
                                      _1,
                                      boost::cref(maSpriteRectangle.getMinimum())) );

        // sprites changed, need screen update
        mrScreenUpdater.notifyUpdate();
    }
}

void RehearseTimingsActivity::paintAllSprites() const
{
    for_each_sprite(
        boost::bind( &RehearseTimingsActivity::paint, this,
                     // call getContentCanvas() on each sprite:
                     boost::bind(
                         &cppcanvas::CustomSprite::getContentCanvas, _1 ) ) );
}

void RehearseTimingsActivity::paint( cppcanvas::CanvasSharedPtr const & canvas ) const
{
    // build timer string:
    const sal_Int32 nTimeSecs =
        static_cast<sal_Int32>(maElapsedTime.getElapsedTime());
    rtl::OUStringBuffer buf;
    sal_Int32 n = (nTimeSecs / 3600);
    if (n < 10)
        buf.append( static_cast<sal_Unicode>('0') );
    buf.append( n );
    buf.append( static_cast<sal_Unicode>(':') );
    n = ((nTimeSecs % 3600) / 60);
    if (n < 10)
        buf.append( static_cast<sal_Unicode>('0') );
    buf.append( n );
    buf.append( static_cast<sal_Unicode>(':') );
    n = (nTimeSecs % 60);
    if (n < 10)
        buf.append( static_cast<sal_Unicode>('0') );
    buf.append( n );
    const rtl::OUString time = buf.makeStringAndClear();

	// create the MetaFile:
	GDIMetaFile metaFile;
	VirtualDevice blackHole;
	metaFile.Record( &blackHole );
    metaFile.SetPrefSize( Size( 1, 1 ) );
	blackHole.EnableOutput(false);
    blackHole.SetMapMode( MAP_PIXEL );
    blackHole.SetFont( maFont );
    Rectangle rect = Rectangle( 0,0,
                                maSpriteSizePixel.getX(),
                                maSpriteSizePixel.getY());
    if (mbDrawPressed)
    {
        blackHole.SetTextColor( COL_BLACK );
        blackHole.SetFillColor( COL_LIGHTGRAY );
        blackHole.SetLineColor( COL_GRAY );
    }
    else
    {
        blackHole.SetTextColor( COL_BLACK );
        blackHole.SetFillColor( COL_WHITE );
        blackHole.SetLineColor( COL_GRAY );
    }
    blackHole.DrawRect( rect );
    blackHole.GetTextBoundRect( rect, time );
    blackHole.DrawText(
        Point( (maSpriteSizePixel.getX() - rect.getWidth()) / 2,
               mnYOffset ), time );

	metaFile.Stop();
	metaFile.WindStart();

    cppcanvas::RendererSharedPtr renderer(
        cppcanvas::VCLFactory::getInstance().createRenderer(
            canvas, metaFile, cppcanvas::Renderer::Parameters() ) );
    const bool succ = renderer->draw();
    OSL_ASSERT( succ );
    (void)succ;
}

RehearseTimingsActivity::MouseHandler::MouseHandler( RehearseTimingsActivity& rta ) :
    mrActivity(rta),
    mbHasBeenClicked(false),
    mbMouseStartedInArea(false)
{}

void RehearseTimingsActivity::MouseHandler::reset()
{
    mbHasBeenClicked = false;
    mbMouseStartedInArea = false;
}

bool RehearseTimingsActivity::MouseHandler::isInArea(
    awt::MouseEvent const & evt ) const
{
    return mrActivity.maSpriteRectangle.isInside(
        basegfx::B2DPoint( evt.X, evt.Y ) );
}

void RehearseTimingsActivity::MouseHandler::updatePressedState(
    const bool pressedState ) const
{
    if( pressedState != mrActivity.mbDrawPressed )
    {
        mrActivity.mbDrawPressed = pressedState;
        mrActivity.paintAllSprites();

        mrActivity.mrScreenUpdater.notifyUpdate();
    }
}

// MouseEventHandler
bool RehearseTimingsActivity::MouseHandler::handleMousePressed(
    awt::MouseEvent const & evt )
{
    if( evt.Buttons == awt::MouseButton::LEFT && isInArea(evt) )
    {
        mbMouseStartedInArea = true;
        updatePressedState(true);
        return true; // consume event
    }
    return false;
}

bool RehearseTimingsActivity::MouseHandler::handleMouseReleased(
    awt::MouseEvent const & evt )
{
    if( evt.Buttons == awt::MouseButton::LEFT && mbMouseStartedInArea )
    {
        mbHasBeenClicked = isInArea(evt); // fini if in
        mbMouseStartedInArea = false;
        updatePressedState(false);
        if( !mbHasBeenClicked )
            return true; // consume event, else next slide (manual advance)
    }
    return false;
}

bool RehearseTimingsActivity::MouseHandler::handleMouseEntered(
    awt::MouseEvent const & /*evt*/ )
{
    return false;
}

bool RehearseTimingsActivity::MouseHandler::handleMouseExited(
    awt::MouseEvent const & /*evt*/ )
{
    return false;
}

bool RehearseTimingsActivity::MouseHandler::handleMouseDragged(
    awt::MouseEvent const & evt )
{
    if( mbMouseStartedInArea )
        updatePressedState( isInArea(evt) );
    return false;
}

bool RehearseTimingsActivity::MouseHandler::handleMouseMoved(
    awt::MouseEvent const & /*evt*/ )
{
    return false;
}

} // namespace internal
} // namespace presentation

ext: cxx


text:
#include <iostream>
#include <string>
#include <cstring>
#include <boost/filesystem.hpp>
#include <boost/version.hpp>

#define API  __attribute__ ((visibility ("default")))

struct API UseBoostFS
{
   static const char* concat_path( int argc, char** argv );
   static void dump_file_size(const char* path);
   static void dump_version();
   static std::string prepare_path(const char* dir_, const char* reldir_, const char* name );
};

namespace fs = boost::filesystem;

void UseBoostFS::dump_file_size(const char* path)
{
    std::cout << "UseBoostFS::dump_file_size: \"" << path  << "\" " << fs::file_size(path) << '\n';
}

const char* UseBoostFS::concat_path(int argc, char** argv)
{
    fs::path p ;
    for(int i=1 ; i < argc ; i++)
    {
         char* a = argv[i] ;
         if(a) p /= a ;
    }

    std::string x = p.string() ;
    return strdup(x.c_str());
}

void UseBoostFS::dump_version()
{
   std::cout
          << "UseBoostFS::dump_version "
          << BOOST_VERSION / 100000     << "."  // major version
          << BOOST_VERSION / 100 % 1000 << "."  // minor version
          << BOOST_VERSION % 100                // patch level
          << std::endl;
}

std::string UseBoostFS::prepare_path(const char* dir_, const char* reldir_, const char* name )
{
    fs::path fdir(dir_);
    if(reldir_) fdir /= reldir_ ;

    if(!fs::exists(fdir))
    {
        if (fs::create_directories(fdir))
        {
            std::cout << "created directory " << fdir.string().c_str() << std::endl  ;
        }
    }

    fs::path fpath(fdir);
    fpath /= name ;

    return fpath.string();
}

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

   const char* path =  argc < 2 ? argv[0] : UseBoostFS::concat_path( argc, argv );

   UseBoostFS::dump_file_size(path);
   UseBoostFS::dump_version();

   std::string p0 = UseBoostFS::prepare_path("/tmp/UseBoostFSManual", "red",  "name.txt" );
   std::cout << " p0 " << p0 << std::endl ;

   std::string p1 = UseBoostFS::prepare_path("/tmp/UseBoostFSManual", "red", "name.txt" );
   std::cout << " p1 " << p1 << std::endl ;

   return 0;

}

ext: cc

max_stars_repo_name: hanswenzel/opticks

max_issues_repo_name: hanswenzel/opticks

max_forks_repo_name: hanswenzel/opticks


text:
#include <boost/asio.hpp>
#include <iostream>

using namespace boost;

void callback(const boost::system::error_code &ec, std::size_t bytes_transferred);

int main()
{
    std::string raw_ip_address = "127.0.0.1";
    unsigned short port_num = 9000;

    try
    {
        std::string message = "HELLOWORLD";
        asio::ip::tcp::endpoint ep(asio::ip::address_v4::from_string(raw_ip_address), port_num);
        asio::io_service ios;
        asio::ip::tcp::socket sock(ios, ep.protocol());
        sock.connect(ep);
        asio::async_write(sock, asio::buffer(message), callback);

        // asio::os_service::run returns after the last asynchronous callback is finished
        ios.run();
    }
    catch (const system::system_error &e)
    {
        std::cout << "Error code: " << e.code() << ", error message: " << e.what() << std::endl;
    }

    return 0;
}

void callback(const boost::system::error_code &ec, std::size_t bytes_transferred)
{
    if (ec.value() != 0)
    {
        std::cout << "Error occured! Error code = " << ec.value() << ". Message: " << ec.message();
        return;
    }
    return;
}

ext: cpp

max_stars_repo_name: lolyu/aoi

max_issues_repo_name: lolyu/aoi

max_forks_repo_name: lolyu/aoi


text:
/*
All modification made by Intel Corporation: © 2016 Intel Corporation

All contributions by the University of California:
Copyright (c) 2014, 2015, The Regents of the University of California (Regents)
All rights reserved.

All other contributions:
Copyright (c) 2014, 2015, the respective contributors
All rights reserved.
For the list of contributors go to https://github.com/BVLC/caffe/blob/master/CONTRIBUTORS.md

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 Intel Corporation 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.
*/

#ifndef CAFFE_PYTHON_LAYER_HPP_
#define CAFFE_PYTHON_LAYER_HPP_

#include <boost/python.hpp>
#include <vector>

#include "caffe/layer.hpp"

namespace bp = boost::python;

namespace caffe {

template <typename Dtype>
class PythonLayer : public Layer<Dtype> {
 public:
  PythonLayer(PyObject* self, const LayerParameter& param)
      : Layer<Dtype>(param), self_(bp::handle<>(bp::borrowed(self))) { }

  virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top) {
    // Disallow PythonLayer in MultiGPU training stage, due to GIL issues
    // Details: https://github.com/BVLC/caffe/issues/2936
    if (this->phase_ == TRAIN && Caffe::solver_count() > 1
        && !Caffe::multiprocess()) {
      LOG(FATAL) << "PythonLayer does not support CLI Multi-GPU, use train.py";
    }
    self_.attr("param_str") = bp::str(
        this->layer_param_.python_param().param_str());
    self_.attr("phase") = static_cast<int>(this->phase_);
    self_.attr("setup")(bottom, top);
  }
  virtual void Reshape(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top) {
    self_.attr("reshape")(bottom, top);
  }

  virtual inline const char* type() const { return "Python"; }

 protected:
  virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
      const vector<Blob<Dtype>*>& top) {
    self_.attr("forward")(bottom, top);
  }
  virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
      const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {
    self_.attr("backward")(top, propagate_down, bottom);
  }

 private:
  bp::object self_;
};

}  // namespace caffe

#endif

ext: hpp


text:
#include "dbm/dbm.hpp"
#include "db_settings.h"
#ifdef DBM_MYSQL
#include <dbm/drivers/mysql/mysql_session.hpp>
#endif
#ifdef DBM_SQLITE3
#include <dbm/drivers/sqlite/sqlite_session.hpp>
#endif

#include <boost/test/unit_test.hpp>

using namespace boost::unit_test;

db_settings::db_settings()
{
    initialize();
}

db_settings& db_settings::instance()
{
    static db_settings inst;
    return inst;
}

#ifdef DBM_MYSQL
void db_settings::init_mysql_session(dbm::mysql_session& session, std::string const& db_name)
{
    session.connect(mysql_host, mysql_username, mysql_password, db_name, mysql_port, std::nullopt, 0);
}

void db_settings::init_mysql_session(dbm::session& session, std::string const& db_name)
{
    init_mysql_session(dynamic_cast<dbm::mysql_session&>(session), db_name);
}

std::unique_ptr<dbm::session> db_settings::get_mysql_session()
{
    auto db = std::make_unique<dbm::mysql_session>();
    db_settings::instance().init_mysql_session(*db, test_db_name);
    db->create_database(test_db_name, true);
    return db;
}
#endif

#ifdef DBM_SQLITE3
void db_settings::init_sqlite_session(dbm::sqlite_session& session)
{
    session.connect(test_db_file_name);
}

void db_settings::init_sqlite_session(dbm::session& session)
{
    init_sqlite_session(dynamic_cast<dbm::sqlite_session&>(session));
}

std::unique_ptr<dbm::session> db_settings::get_sqlite_session()
{
    auto db = std::make_unique<dbm::sqlite_session>();
    db->connect(test_db_file_name);
    return db;
}
#endif

void db_settings::initialize()
{
#ifdef DBM_MYSQL
    int argc = framework::master_test_suite().argc;

    for (int i = 0; i < argc - 1; i++) {
        std::string arg = framework::master_test_suite().argv[i];

        if (arg == "--mysql-host") {
            mysql_host = framework::master_test_suite().argv[i + 1];
        }
        else if (arg == "--mysql-username" || arg == "--db-username") {
            mysql_username = framework::master_test_suite().argv[i + 1];
        }
        else if (arg == "--mysql-password" || arg == "--db-password") {
            mysql_password = framework::master_test_suite().argv[i + 1];
        }
    }

    if (mysql_host.empty()) {
        BOOST_FAIL("mysql host name not defined");
    }
    if (mysql_username.empty()) {
        BOOST_FAIL("mysql username not defined");
    }
    if (mysql_password.empty()) {
        BOOST_TEST_MESSAGE("mysql password not defined - using blank password");
    }
#endif
}

max_stars_repo_name: ipeperko/dbm

max_issues_repo_name: ipeperko/dbm

max_forks_repo_name: ipeperko/dbm


text:
/**
 * @file ElemArray.hpp
 * @author Adam Li (adamli@umich.edu)
 * @date 2021-11-11
 * @brief The template class definition for static and dynamic size ElemArray.
 *
 * ElemArray is written to behave somewhat similarly to a standard vector
 * at the highest level, but it's really just a custom datatype made
 * specifically for the mesh components of sel_map. Raw memory access is allowed
 * for mapping to eigen (an later a simple function to do this is probably going
 * to be added). The goal is to try to optimize the use of memory and keep things
 * aligned for vectorizing and automatic optimization.
 *
 */
#pragma once

// First include the base definition, which we will extend here
#include "ElemArrayBase.hpp"
// Include the Eigen memory definitions, which allows for aligned allocation
#include <Eigen/Core>
#include <Eigen/Dense>

// And now include the rest of the standard library needed to make this work
#include <cstddef>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <algorithm>
#include <cassert>

namespace sel_map::core {
    //Forward declare ElemArray helpers.
    template <typename ElemArray_t, typename Tprimative_t, std::size_t Tsize_el>
    class ElemArrayHelper;
    // So code is more readable
    static const int ElemArrayDynamic = 0;
    // If Tsize_el is set to zero, this is effectively a dynamic length el vector
    // an extra typedef for ElemArrayDyn is made just for that case at the end.
    // I lied, typedefs with template parameters is not a thing.
    template <typename Tprimative_t, std::size_t Tsize_el>
    class ElemArray : public ElemArrayBase {

        // Helpers for static/dynamic functions
        friend class ElemArrayHelper<ElemArray<Tprimative_t, Tsize_el>, Tprimative_t, Tsize_el>;
        using Helper = ElemArrayHelper<ElemArray<Tprimative_t, Tsize_el>, Tprimative_t, Tsize_el>;

        public:
        // Extra eigen intercompat for nanoflann
        typedef Tprimative_t Scalar;
        constexpr static const int ColsAtCompileTime = Tsize_el;

        //==============================================//
        //       EIGEN TYPEDEFS FOR READABILITY         //
        //==============================================//
        // Make life easier by typedef'ing the vectors and matrix here for static and dynamic case
        typedef typename std::conditional<Tsize_el == ElemArrayDynamic,
                    Eigen::Matrix<Tprimative_t, Eigen::Dynamic, 1>, // Dynamic Row Vec (as eigen col vec)
                    Eigen::Matrix<Tprimative_t, Tsize_el, 1>        // Static Row Vec (as eigen col vec)
                    >::type EigenRowVec_t;

        // All column vectors will be dynamic because length can change
        typedef Eigen::Matrix<Tprimative_t, Eigen::Dynamic, 1> EigenColVec_t;

        // Matrix typedef
        typedef typename std::conditional<Tsize_el == ElemArrayDynamic,
                    Eigen::Matrix<Tprimative_t, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>,    //Matrix with dynamic row size
                    Eigen::Matrix<Tprimative_t, Eigen::Dynamic, Tsize_el, Eigen::RowMajor>           //Matrix with static row size
                    >::type EigenMatrix_t;

        // Array typedef
        typedef typename std::conditional<Tsize_el == ElemArrayDynamic,
                    Eigen::Array<Tprimative_t, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>,    //Array with dynamic row size
                    Eigen::Array<Tprimative_t, Eigen::Dynamic, Tsize_el, Eigen::RowMajor>           //Array with static row size
                    >::type EigenArray_t;

        // Chose the right innerstride
        typedef typename std::conditional<Tsize_el == ElemArrayDynamic,
                    Eigen::InnerStride<>,           //Dynamic inner stride
                    Eigen::InnerStride<Tsize_el>    //Static inner stride
                    >::type EigenInnerStride_t;

        //==============================================//
        //       HELPER OBJECTS / NESTED CLASSES        //
        //               IMPLEMENTATION                 //
        //==============================================//
        class Iterator;
        // Each element in this ElemArray (used as return type)
        // Necessary operators are added to this as needed
        class Elem : public ElemArrayBase::ElemBase {
            friend class Iterator;
            friend class ElemArray;
            protected:
            // The size of a singular element
            std::size_t _size_el;
            bool temporary;

            // Main constructor, protected
            Elem(std::size_t size_el = Tsize_el) : _size_el(size_el), temporary(false) {
                // If you see this, you might be trying to directly create an Elem
                // This isn't valid though. Elem is simply a middleman object for access.
                // Also something had to go terribly wrong, because this is protected.
                // Nevermind
                // Apparently MinMax needs this.
                //assert(size_el && "If you see this, something broke! Dynamic Elem's must have size_el greater than 0!");
            };

            public:
            // This object isn't supposed to be constructable from scratch!
            // Copy things
            Elem(const Elem& other) {
                if (Tsize_el && Tsize_el != other._size_el)
                    throw std::invalid_argument("Element sizes must match for static copy of Elem Accessor");
                this->_size_el = other._size_el;
                temporary = true;
                _elem = (void*)new Tprimative_t[_size_el];
                std::copy(other.begin(), other.end(), begin());
            };
            Elem& operator=(const Elem& rhs) {
                if (this != &rhs){
                    if (Tsize_el && Tsize_el != rhs._size_el)
                        throw std::invalid_argument("Element sizes must match for static Elem Copy Assignment");
                    this->_size_el = rhs._size_el;
                    this->_elem = rhs._elem;
                    //std::copy(rhs.begin(), rhs.end(), begin());
                }
                return *this;
            };

            // Move things (this is just masking a copy)
            Elem(Elem&& other){
                if (Tsize_el && Tsize_el != other._size_el)
                    throw std::invalid_argument("Element sizes must match for static move of Elem Accessor");
                this->_size_el = other._size_el;
                temporary = true;
                _elem = (void*)new Tprimative_t[_size_el];
                std::swap_ranges(other.begin(), other.end(), begin());
            };
            Elem& operator=(Elem&& rhs){
                if (this != &rhs){
                    swap(rhs);
                }
                return *this;
            };
            ~Elem(){
                if (temporary) delete[] (Tprimative_t*)_elem;
            }

            // Typed, unchecked accessor for the internal element pointer
            Tprimative_t* ptr(){
                return ptr(_elem);
            };
            Tprimative_t* const_ptr() const {
                return const_ptr(_elem);
            };

            // Typed, unchecked accessor for arbitrary pointer of same type
            Tprimative_t* ptr(void* elem){
                return (Tprimative_t*)elem;
            };
            Tprimative_t* const_ptr(void* elem) const {
                return (Tprimative_t*)elem;
            };

            // Typed, unchecked accessor to next Elem following structure
            // Assumes the same exact types along bounds
            Tprimative_t* shift(int pos){
                return shift(_elem, pos);
            };
            Tprimative_t* const_shift(int pos) const{
                return const_shift(_elem, pos);
            };

            // Typed, unchecked accessor to next Elem following structure
            // Assumes the same exact types for arbitrary pointer of same type
            Tprimative_t* shift(const void* elem, int pos){
                return ((Tprimative_t*)elem) + pos*_size_el;
            };
            Tprimative_t* const_shift(const void* elem, int pos) const{
                return ((Tprimative_t*)elem) + pos*_size_el;
            };

            // Compute the wraparound index and return the relevant element
            Tprimative_t& operator[](int idx){
                return ptr()[((idx % int(_size_el)) + _size_el) % _size_el];
            };
            Tprimative_t operator[](int idx) const{
                return (*this)[idx];
            };

            // Get the mapped Eigen Vector relating to the Elem
            Eigen::Map<EigenRowVec_t> toEigen(){
                return Eigen::Map<EigenRowVec_t>(ptr(), _size_el);
            };

            // Gets pointers mapped to begin and end of elem
            Tprimative_t* begin(){
                return ptr();
            };
            Tprimative_t* end(){
                return shift(1);
            };
            Tprimative_t* begin() const{
                return const_ptr();
            };
            Tprimative_t* end() const{
                return const_shift(1);
            };

            //Swap function
            void swap(Elem& other) {
                if (other._size_el != _size_el)
                    throw std::invalid_argument("Element sizes must match for swap");
                std::swap_ranges(other.begin(), other.end(), begin());
            }

            // Size accessor
            std::size_t size() const{ return _size_el; };
        };

        //Custom iterator for use with STL algorithms
        struct Iterator
        {
            // Thank you https://internalpointers.com/post/writing-custom-iterators-modern-cpp
            // https://stackoverflow.com/questions/12092448/code-for-a-basic-random-access-iterator-based-on-pointers/31886483
            using iterator_category = std::random_access_iterator_tag;
            using difference_type   = std::ptrdiff_t;
            using value_type        = Elem;
            using pointer           = Elem*;
            using reference         = Elem&;

            public:

            Iterator(std::size_t size_el = 0) : internal_elem(size_el) { internal_elem._elem =  nullptr; };
            Iterator(Tprimative_t* ptr, std::size_t size_el = 0) : internal_elem(size_el) { internal_elem._elem = (void*)ptr; };
            Iterator(const Iterator& ptr) : internal_elem(ptr.internal_elem._size_el) { internal_elem._elem = ptr.internal_elem._elem; };

            inline Iterator& operator+=(difference_type rhs) {internal_elem._elem = (void*) internal_elem.shift(rhs); return *this;};
            inline Iterator& operator-=(difference_type rhs) {internal_elem._elem = (void*) internal_elem.shift(-rhs); return *this;};
            inline reference operator*() {return internal_elem;};
            inline pointer operator->() const {return &internal_elem;};
            inline reference operator[](difference_type rhs) const {value_type ret; ret._elem = (void*) internal_elem.shift(internal_elem._elem, rhs); return ret;};

            inline Iterator& operator++() {internal_elem._elem = (void*) internal_elem.shift(1); return *this;};
            inline Iterator& operator--() {internal_elem._elem = (void*) internal_elem.shift(-1); return *this;};
            inline Iterator operator++(int) {Iterator tmp(*this); ++(*this); return tmp;};
            inline Iterator operator--(int) {Iterator tmp(*this); --(*this); return tmp;};

            inline difference_type operator-(const Iterator& rhs) const
                {return ((int)(internal_elem.const_ptr()-rhs.internal_elem.const_ptr())) / internal_elem.size();};
            inline Iterator operator+(difference_type rhs) const {return Iterator(internal_elem.const_shift(internal_elem._elem, rhs), internal_elem._size_el);};
            inline Iterator operator-(difference_type rhs) const {return Iterator(internal_elem.const_shift(internal_elem._elem, -rhs), internal_elem._size_el);};
            friend inline Iterator operator+(difference_type lhs, const Iterator& rhs) {return Iterator(rhs.internal_elem.shift(rhs.internal_elem._elem, lhs), rhs.internal_elem._size_el);};
            /*friend inline Iterator operator-(difference_type lhs, const Iterator& rhs) {return Iterator((Tprimative_t*)(lhs*internal_elem.size()) - Elem::pts(rhs.internal_elem.elem));};*/

            inline bool operator==(const Iterator& rhs) const {return internal_elem._elem == rhs.internal_elem._elem;};
            inline bool operator!=(const Iterator& rhs) const {return internal_elem._elem != rhs.internal_elem._elem;};
            inline bool operator>(const Iterator& rhs) const {return internal_elem._elem > rhs.internal_elem._elem;};
            inline bool operator<(const Iterator& rhs) const {return internal_elem._elem < rhs.internal_elem._elem;};
            inline bool operator>=(const Iterator& rhs) const {return internal_elem._elem >= rhs.internal_elem._elem;};
            inline bool operator<=(const Iterator& rhs) const {return internal_elem._elem <= rhs.internal_elem._elem;};

            friend bool operator== (const Iterator& a, const Iterator& b) { return a.internal_elem._elem == b.internal_elem._elem; };
            friend bool operator!= (const Iterator& a, const Iterator& b) { return a.internal_elem._elem != b.internal_elem._elem; };

            void swap(Iterator& other) {
                internal_elem.swap(other.internal_elem);
            }
        private:
            value_type internal_elem;
        };

        protected:
        //==============================================//
        //            PROTECTED RAW STORAGE             //
        //==============================================//
        // The raw storage for the N-length array of elements
        // The total size of this will be N*size_el.
        //Tprimative_t *arr;
        void* arr;

        private:
        //==============================================//
        //          PRIVATE HELPER FUNCTIONS            //
        //      LOW LEVEL MEMORY SPECIALIZATIONS        //
        //             FOWARD DECLARATIONS              //
        //==============================================//
        /**
         * @brief sizeof wrapper. Returns the sizeof(Tprimative_t)*size_el
         *
         */
        unsigned int _sizeof(){
            return Helper::_sizeof(this);
        }

        /**
         * @brief Returns the apropriate index to start a row.
         *
         * @param idx row index to get the raw index of
         * @return unsigned int
         */
        unsigned int rowIdx(unsigned int idx){
            return Helper::rowIdx(this, idx);
        }

        /**
         * @brief Wrapper for malloc
         *
         * @param new_size
         *      New length of the internal vector (in units of Elem)
         */
        void allocArr(std::size_t new_size){
            //arr = (Tprimative_t*) std::malloc(_sizeof()*(new_size+1));
            //arr = (void*) std::malloc(_sizeof()*(new_size+1));
            arr = (void*) Eigen::internal::aligned_malloc(_sizeof()*(new_size+1));
        };

        /**
         * @brief Wrapper for realloc
         *
         * @param new_size
         *      New length of the internal vector (in units of Elem)
         */
        void reallocArr(std::size_t new_size) {
            //arr = (Tprimative_t*) std::realloc(arr, _sizeof()*(new_size+1));
            //arr = (void*) std::realloc(arr, _sizeof()*(new_size+1));
            arr = (void*) Eigen::internal::aligned_realloc(arr, _sizeof()*(new_size+1), _sizeof()*(length_real+1));
        };

        /**
         * @brief Wrapper for memcpy
         *
         * @param start
         *      Start position in Elem to copy to
         * @param length
         *      # of Elem to copy
         * @param from_arr
         *      Arr to copy from
         */
        void memcpyArr(std::size_t start, std::size_t length, void* from_arr){
            std::memcpy(dptr(rowIdx(start)), from_arr, _sizeof()*length);
        };

        //==============================================//
        //          PRIVATE HELPER FUNCTIONS            //
        //       HIGHER LEVEL CODE DEDUPLICATION        //
        //==============================================//
        // helper function to copy arr and reduce code duplication
        /**
         * @brief Copies/append from add_arr to arr with copy_len Elem's
         *
         * @param add_arr
         *      Pointer to the start of the new_arr data
         * @param copy_len
         *      Number of Elem's to copy
         */
        void copyAppendArr(void* add_arr, std::size_t copy_len){
            // Create the memory needed, if needed
            if (!arr){
                allocArr(copy_len);
                length_real = copy_len;
            }

            // If there isn't enough space at the end to add, then just get space
            else if (length_real - len < copy_len) {
                // Use realloc to try to expand the same space of memory.
                reallocArr(len + copy_len);
                length_real = len + copy_len;
            }

            // Make sure the allocations worked
            if (!arr) throw std::bad_alloc();

            // Then just copy the memory
            memcpyArr(len, copy_len, add_arr);
            len += copy_len;
        };

        /**
         * @brief Copies from ElemArrayBase to this ElemArray.
         * Reduces code duplication
         *
         * @param toCopy ElemArrayBase to copy from
         */
        void copyAll(const ElemArrayBase& toCopy){
            // Copy only the relevant length & size
            length_real = len = toCopy.len;
            size_el = toCopy.elem_size();
            arr = nullptr;

            // If there's anything worth copying, then allocate (and throw bad alloc if it fails)
            if(len != 0){
                allocArr(len);
                if (!arr) throw std::bad_alloc();

                // and copy the data
                memcpyArr(0, len, (Tprimative_t*)toCopy.getRawMemory());
            }
        };

        /**
         * @brief Swaps the key parameters between the two ElemArray's
         *
         * @param toSwap
         */
        void swapAll(ElemArrayBase& toSwap){
            std::swap(size_el, toSwap.size_el);
            std::swap(len, toSwap.len);
            std::swap(length_real, toSwap.length_real);
            // void* tmp = toSwap.getRawMemory();
            // toSwap.getRawMemory() = (void*)arr;
            // arr = (Tprimative_t*)tmp;
            std::swap(arr, toSwap.getRawMemory());
        }

        public:
        //==============================================//
        //          CONSTRUCTION/DESTRUCTION            //
        //      + RELATED OPERATORS & UTIL FUNCS        //
        //==============================================//
        // Deletes the memory used by the array & resets everything to 0
        /**
         * @brief Clears the memory used by the array, setting lengths to 0.
         *
         * This doesn't change the size_el, and the ElemArray still retains the same
         * elem_size for other operations like append.
         *
         */
        void clear() {
            if (arr) {
                //std::free(arr);
                Eigen::internal::aligned_free(arr);
                arr = nullptr;
            }
            length_real = len = 0;
        };

        /**
         * @brief Returns the length of a singular element
         *
         * @return std::size_t size of an element
         */
        std::size_t elem_size() const{
            return Helper::elem_size(this);
        }
        void resize_elem(std::size_t new_size_el) {
            if (Tsize_el)
                throw std::invalid_argument("Static ElemArray's cannot be resized!");
            // invalidate the entire elemArray
            clear();
            size_el = new_size_el;
        }

        /**
         * @brief Provides raw memory access to the internal storage. (Element-major)
         *
         * @return void*& generic pointer to the internal storage
         */
        void*& getRawMemory() { return arr; };
        void* getRawMemory() const { return (void*)arr; };

        /**
         * @brief Construct a new ElemArray object.
         *
         * @param size_el
         *      If using a static ElemArray, this does nothing. If using a dynamic
         *      ElemArray, or an ElemArrayDyn object, this sets the size of a single element.
         *
         */
        ElemArray(std::size_t size_el = Tsize_el)
                  : ElemArrayBase(size_el), arr(nullptr)
        {
            // Default constructor, make sure everything is zeros except for size_el.
            if (!size_el)
                throw std::invalid_argument("Dynamic ElemArray's must have an element size greater than 0!");
        };

        // Copy things
        /**
         * @brief Generic copy constructor
         *
         * @param other Base ElemArray object to copy.
         */
        ElemArray(const ElemArrayBase& other) {
            // Check validity
            if (Tsize_el && Tsize_el != other.elem_size())
                throw std::invalid_argument("Element sizes must match to copy to static ElemArray's.");

            // Copy
            copyAll(other);
        };
        /**
         * @brief Specialized copy constructor
         *
         * @param other ElemArray object to copy.
         */
        ElemArray(const ElemArray<Tprimative_t, Tsize_el>& other) { copyAll(other); };
        /**
         * @brief Generic copy assignment
         *
         * @param rhs Base ElemArray object to copy.
         * @return self
         */
        ElemArray<Tprimative_t, Tsize_el>& operator=(const ElemArrayBase& rhs) {
            if (this != &rhs){
                // Check validity
                if (Tsize_el && Tsize_el != rhs.elem_size())
                    throw std::invalid_argument("Element sizes must match to copy to static ElemArray's.");
                // Clear the current one
                clear();
                copyAll(rhs);
            }
            return *this;
        };
        /**
         * @brief Specialized copy assignment
         *
         * @param rhs ElemArray object to copy.
         * @return self
         */
        ElemArray<Tprimative_t, Tsize_el>& operator=(const ElemArray<Tprimative_t, Tsize_el>& rhs) {
            if (this != &rhs){
                // Clear the current one
                clear();
                copyAll(rhs);
            }
            return *this;
        };

        // Move things
        /**
         * @brief Generic move constructor
         *
         * @param other Base ElemArray to move
         */
        ElemArray(ElemArrayBase&& other) : ElemArray(other.size_el) {
            if (Tsize_el && Tsize_el != other.elem_size())
                throw std::invalid_argument("Element sizes must match to move to static ElemArray's.");
            // Move everything
            swapAll(other);
        };
        /**
         * @brief Specialized move constructor
         *
         * @param other ElemArray to move
         */
        ElemArray(ElemArray<Tprimative_t, Tsize_el>&& other) : ElemArray() {
            swapAll(other);
        };
        /**
         * @brief Generic move assignment
         *
         * @param rhs Base ElemArray to move
         * @return self
         */
        ElemArray<Tprimative_t, Tsize_el>& operator=(ElemArrayBase&& rhs){
            if (this != &rhs){
                if (Tsize_el && Tsize_el != rhs.elem_size())
                    throw std::invalid_argument("Element sizes must match to move to static ElemArray's.");
                // Clear the current one
                clear();
                // Move it all
                swapAll(rhs);
            }
            return *this;
        };
        /**
         * @brief Specialized move assignment
         *
         * @param rhs ElemArray to move
         * @return self
         */
        ElemArray<Tprimative_t, Tsize_el>& operator=(ElemArray<Tprimative_t, Tsize_el>&& rhs){
            if (this != &rhs){
                // Clear the current one
                clear();
                // Move it all
                swapAll(rhs);
            }
            return *this;
        };

        // Destructor
        ~ElemArray() {
            clear();
        };

        //
        //==============================================//
        //           ITERATORS AND ACCESSORS            //
        //==============================================//
        Tprimative_t* dptr(unsigned int i = 0){
            return ((Tprimative_t*)arr) + i;
        }
        // Direct coefficient access without wraparound (eigen intercompat for nanoflann)
        Tprimative_t& coeff(unsigned int row, unsigned int col){
            return *dptr(rowIdx(row)+col);
        }
        Tprimative_t coeff(unsigned int row, unsigned int col) const{
            return coeff(row,col);
        }
        // Access row as Eigen col vector, with wraparound
        Eigen::Map<EigenRowVec_t> getVecElem(int idx){
            int a = ((idx % int(len)) + len) % len;
            return Eigen::Map<EigenRowVec_t>(dptr(rowIdx(a)), elem_size());
        };
        // Access col as Eigen col vector, with wraparound
        Eigen::Map<EigenColVec_t, Eigen::AlignmentType::Unaligned, EigenInnerStride_t > getVecIdx(int idx){
            int a = ((idx % int(elem_size())) + elem_size()) % elem_size();
            return Eigen::Map<EigenColVec_t, Eigen::AlignmentType::Unaligned, EigenInnerStride_t >(dptr(a), len, EigenInnerStride_t(elem_size()));
        };

        // Access data as Eigen Matrix, each row is the element
        Eigen::Map<EigenMatrix_t, Eigen::AlignmentType::Aligned16> getEigenMatrix(){
            return Eigen::Map<EigenMatrix_t, Eigen::AlignmentType::Aligned16 >(dptr(0), len, elem_size());
        };
        Eigen::Map<EigenArray_t, Eigen::AlignmentType::Aligned16> getEigenArray(){
            return Eigen::Map<EigenArray_t, Eigen::AlignmentType::Aligned16 >(dptr(0), len, elem_size());
        };
        // Access row as Elem, with wraparound
        // contains pointer to same memory space, do not store as reference!
        Elem operator[](int idx){
            int a = ((idx % int(len)) + len) % len;
            Elem ret(elem_size());
            ret._elem = (void*)dptr(rowIdx(a));
            return ret;
        };
        // Iterators
        Iterator begin() { return Iterator(dptr(0), elem_size()); };
        Iterator end() { return Iterator(dptr(rowIdx(len)), elem_size()); };

        //==============================================//
        //     OPERATIONS THAT MANIPULATE THE DATA      //
        //==============================================//
        /**
         * @brief Appends to the end of the ElemArray based on length for a generic ElemArray.
         *
         * @param toAdd ElemArrayBase to append
         * @return self for chaining
         */
        ElemArray<Tprimative_t, Tsize_el>& append(const ElemArrayBase& toAdd) {
            if (toAdd.elem_size() != elem_size())
                throw std::invalid_argument("Element sizes must match to append to ElemArray.");

            //Append the data
            copyAppendArr(toAdd.getRawMemory(), toAdd.len);

            // Return this in case we want to do some chaining.
            return *this;
        };
        /**
         * @brief Appends to the end of the ElemArray based on length for the matching ElemArray.
         *
         * @param toAdd ElemArrayBase to append
         * @return self for chaining
         */
        ElemArray<Tprimative_t, Tsize_el>& append(const ElemArray<Tprimative_t, Tsize_el>& toAdd) {
            return Helper::append(this, toAdd);
        };

        /**
         * @brief Trims the array to the set indices, with wraparound support.
         *
         * @param start Start index, included
         * @param end End index, not included
         * @return self for chaining
         */
        ElemArray<Tprimative_t, Tsize_el>& trim(int start, int end) {
            // find the wraparound indices, then move with memmove
            int a = ((start % int(len)) + len) % len;
            len = (((end - 1) % int(len)) + len) % len - a + 1;
            std::memmove(dptr(), dptr(rowIdx(a)), len*_sizeof());
            return *this;
        };

        /**
         * @brief Generates a comparison function for a specific index
         * of an element, with wraparound support.
         *
         * @param idx Index to be compared
         * @return ElemArrayBase::ElemBase::CompareFcn_t
         */
        ElemArrayBase::ElemBase::CompareFcn_t compareIdx(int idx) {
            // compute the index and capture that
            idx = ((idx % int(elem_size())) + elem_size()) % elem_size();
            // Then return the direct access lambda function
            return [idx](const ElemBase& a, const ElemBase& b) -> bool
                    { return ((Tprimative_t*)a._elem)[idx] < ((Tprimative_t*)b._elem)[idx]; };
        };

        /**
         * @brief Performs a std::sort on a specific index. Wrapper function
         * that enables chaining and performs index wraparound.
         *
         * @param idx Index to sort across
         * @return self for chaining
         */
        ElemArray<Tprimative_t, Tsize_el>& sortIdx(int idx) {
            std::sort(begin(), end(), compareIdx(idx));
            return *this;
        };

        /**
         * @brief Performs a std::shuffle in place using the provided
         * mt19937 generator. Does not have a built in one.
         *
         * @param gen mt19937 random number generator.
         * @return self for chaining
         */
        ElemArray<Tprimative_t, Tsize_el>& shuffle(std::mt19937& gen) {
            std::shuffle(begin(), end(), gen);
            return *this;
        };

        /**
         * @brief Creates a clone of this ElemArray. Cloned version is
         * dynamically allocated and it's memory must be freed with the delete keyword.
         *
         * @return ElemArray<Tprimative_t, Tsize_el>*
         */
        ElemArray<Tprimative_t, Tsize_el>* clone() const {
            return new ElemArray<Tprimative_t, Tsize_el>(*this);
        };

        /**
         * @brief Empties the ElemArray by setting it to zero length.
         * Does not free memory or shrink the real size.
         *
         * @return self for chaining
         */
        ElemArray<Tprimative_t, Tsize_el>& setEmpty() {
            len = 0;
            return *this;
        };

        /**
         * @brief Reserves space of length without initializing any of it.
         * Updates the length of the ElemArray if expand_length is true.
         * Does not initialize any of the space reserved!
         *
         * @param toReserve # of elem's to expand to
         * @param expand_length Whether or not to update the displayed length
         * @return self for chaining
         */
        ElemArray<Tprimative_t, Tsize_el>& reserve(std::size_t toReserve, bool expand_length = false) {
            // Create the memory needed, if needed
            if (!arr){
                allocArr(toReserve);
                length_real = toReserve;
            }

            // If there isn't enough space at the end to add, then just get space
            else if (length_real < toReserve) {
                // Use realloc to try to expand the same space of memory.
                reallocArr(toReserve);
                length_real = toReserve;
            }

            // Make sure the allocations worked
            if (!arr) throw std::bad_alloc();

            // Then update the length if requested
            if (expand_length)
                len = toReserve;
            // Return self for chaining
            return *this;
        };

        /**
         * @brief Construct a new ElemArray object based on the Eigen Matrix / Array
         *
         * @param mat
         *      The EigenBase object to copy from.
         *
         */
        template <typename Derived>
        ElemArray(const Eigen::EigenBase<Derived>& mat)
                  : ElemArrayBase(Tsize_el), arr(nullptr)
        {
            int cols = mat.cols();
            int rows = mat.rows();
            // If this is the static case, check that the cols match, or that it's size 1 with matching rows
            if (Tsize_el){
                if (cols == Tsize_el){
                    reserve(rows, true);
                }else if(cols == 1 && rows == Tsize_el){
                    reserve(1, true);
                }else{
                    throw std::invalid_argument("Eigen cols must match size or must be 1 with matching length cols to copy to static ElemArray's.");
                }
            }
            // If this is the dynamic case, check if cols is size 1. if it is, then size_el is the rows
            else{
                if (cols == 1){
                    size_el = rows;
                    reserve(1, true);
                } else{
                    size_el = cols;
                    reserve(rows, true);
                }
            }
            // Copy it (this means sparse matrices also work)
            // Force dynamic
            Eigen::Map<Eigen::Array<Tprimative_t, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>, Eigen::AlignmentType::Aligned16>
                eigenArr(dptr(0), len, elem_size());
            // Account for column vector case.
            if(cols == 1){
                eigenArr = mat.derived().transpose();
            }else{
                eigenArr = mat.derived();
            }
        };

        /**
         * @brief Appends Eigen to end of ElemArray
         *
         * @param toAdd Eigen thingamabobber to append
         * @return self for chaining
         */
        template <typename Derived>
        ElemArray<Tprimative_t, Tsize_el>& append(const Eigen::EigenBase<Derived>& toAdd) {
            int cols = toAdd.cols();
            int rows = toAdd.rows();
            auto len = length();
            // check that the cols match, or that it's size 1 with matching rows
            if (cols == elem_size()){
                reserve(len + rows, true);
            }else if(cols == 1 && rows == elem_size()){
                reserve(len + 1, true);
            }else{
                throw std::invalid_argument("Eigen cols must match size or must be 1 with matching length cols to copy to static ElemArray's.");
            }
            // Copy it (this means sparse matrices also work)
            // Force dynamic (also works for column case)
            Eigen::Map<Eigen::Array<Tprimative_t, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>, Eigen::AlignmentType::Unaligned>
                eigenArr(dptr(rowIdx(len)), rows, cols);
            eigenArr = toAdd.derived();

            return *this;
        };

    };

    //===================================//
    //         Stupid Templates          //
    //      Special Helper Classes       //
    //===================================//

    template <typename ElemArray_t, typename Tprimative_t, std::size_t Tsize_el>
    class ElemArrayHelper {
        public:
        // Static version for _sizeof()
        static unsigned int _sizeof(const ElemArray_t *parent)
        { return sizeof(Tprimative_t)*Tsize_el; };

        // Static version of elem_size()
        static std::size_t elem_size(const ElemArray_t *parent)
        { return Tsize_el; };

        // Static version of rowIdx()
        static unsigned int rowIdx(const ElemArray_t *parent, unsigned int idx)
        { return Tsize_el*idx; };

        // Static version of append
        static ElemArray_t& append(ElemArray_t *parent, const ElemArray_t& toAdd) {
            parent->copyAppendArr(toAdd.arr, toAdd.len);
            return *parent;
        }
    };

    template <typename ElemArray_t, typename Tprimative_t>
    class ElemArrayHelper<ElemArray_t, Tprimative_t, 0> {
        public:
        // Dynamic version for _sizeof()
        static unsigned int _sizeof(const ElemArray_t *parent)
        { return sizeof(Tprimative_t)*(parent->size_el); };

        // Dynamic version of elem_size()
        static std::size_t elem_size(const ElemArray_t *parent)
        { return (parent->size_el); };

        // Dynamic version of rowIdx()
        static unsigned int rowIdx(const ElemArray_t *parent, unsigned int idx)
        { return (parent->size_el)*idx; };

        // Dynamic version of append
        static ElemArray_t& append(ElemArray_t *parent, const ElemArray_t& toAdd) {
            if (toAdd.elem_size() != parent->size_el)
                throw std::invalid_argument("Element sizes must match to append to ElemArray.");
            parent->copyAppendArr(toAdd.arr, toAdd.len);
            return *parent;
        }
    };
};

//Swap
namespace std{
    template <typename Tprimative_t, std::size_t Tsize_el>
    void swap(typename sel_map::core::ElemArray<Tprimative_t, Tsize_el>::Elem& lhs, typename sel_map::core::ElemArray<Tprimative_t, Tsize_el>::Elem& rhs) {
        lhs.swap(rhs);
    };
    template <typename Tprimative_t, std::size_t Tsize_el>
    void swap(typename sel_map::core::ElemArray<Tprimative_t, Tsize_el>::Iterator& lhs, typename sel_map::core::ElemArray<Tprimative_t, Tsize_el>::Iterator& rhs) {
        lhs.swap(rhs);
    };
};
// Specific typedef for the dynamic ElemArrays
//template <typename Tprimative_t>
//using sel_map::core::ElemArrayDyn = sel_map::core::ElemArray<Tprimative_t, 0>;


text:
/*
 * Copyright 2017 Scoop Technologies
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
#pragma once
#ifndef _NODE_EVENT_RINGBUFFER_H
#define _NODE_EVENT_RINGBUFFER_H

#include <algorithm>
#include <condition_variable>
#include <array>
#include <memory>
#include <mutex>
#include <thread>

#ifdef HAVE_BOOST

/// XXX(jrb): This fundamentally changes the behavior of this ringbuffer to single-producer/single-consumer. You must
/// ensure that there can only ever be a single producer at a time via external synchronization.
///
/// Sadly, cannot use the multi-producer/multi-consumer because boost::lockfree::queue doesn't allow non-trivial
/// destructors.
#include <boost/lockfree/spsc_queue.hpp>
#include <boost/lockfree/policies.hpp>
////single-consumer, single-producer low-latency lockfree ringbuffer from boost
template <typename T, size_t SIZE>
using RingBuffer = boost::lockfree::spsc_queue<T, boost::lockfree::capacity<SIZE> >;

#else

/// Multi-consumer, multi-producer, condition_variable signalled Shared
/// ringbuffer (contiguous memory; mutex)
template <typename T, size_t SIZE>
class RingBuffer {
    constexpr static bool divides_evenly(size_t v) { return (static_cast<size_t>(-1) % v) == v - 1; }
    static_assert(divides_evenly(SIZE), "SIZE does not divide $2^{sizeof(size_t)*8}$, so behavior on overrun would be erratic");

 public:
    RingBuffer() : lock_(), notifier_(), read_idx_(0), write_idx_(0), buf_() {}

    /// Move val into the ringbuffer. If this fails, the object is still moved
    /// (and so, effectively lost at this point). If this is a problem, make a
    /// copy and move that copy
    ///
    /// @param[in] val - the value to try to push
    ///
    /// @returns true if successful, false if the buffer was full
    bool push(T&& val) {
        std::unique_lock<std::mutex> guard{lock_};
        return unlocked_enqueue(std::move(val));
    }

    /// Move the value into the queue
    /// (no boost equiv)
    /// @param[in] val - the value to enqueue
    void push_blocking(T&& val) {
        std::unique_lock<std::mutex> guard{lock_};
        while (!unlocked_enqueue(std::move(val))) {
            notifier_.wait(guard);
        }
    }

    /// Dequeue an element into val
    ///
    /// @param[out] val - place to put item from the queue
    ///
    /// @returns true if there was something to dequeue, false otherwise
    bool pop(T& val) {
        std::unique_lock<std::mutex> guard{lock_};
        if (!unlocked_read_available()) {
            return false;
        }
        val = unlocked_dequeue();
        return true;
    }

    /// Blocking attempt to dequeue an item
    /// (no boost equiv)
    /// @returns the dequeued element
    T&& pop_blocking() {
        std::unique_lock<std::mutex> guard{lock_};
        while (!unlocked_read_available()) {
            notifier_.wait(guard);
        }
        return unlocked_dequeue();
    }

    /// @returns true if the ringbuffer is empty
    inline bool read_available() {
        std::unique_lock<std::mutex> guard{lock_};
        return unlocked_read_available();
    }

 private:
    inline bool unlocked_enqueue(T&& val) {
        // read_idx_ & write_idx_ are unsigned so this subtraction is in the
        // group $\mathbb{Z}_{2^64}$, and so is overrun safe as long as $buf_.size() \divides 2^64$
        if (write_idx_ - read_idx_ >= buf_.size()) {
            return false;
        }

        buf_[write_idx_ % buf_.size()] = std::move(val);
        ++write_idx_;

        // Notify under mutex to ensure consistent behavior; rely on wait-morphing for performance
        notifier_.notify_one();
        return true;
    }

    inline T&& unlocked_dequeue() {
        auto&& v = std::move(buf_[read_idx_++ % buf_.size()]);
        // notify all blocked writers
        notifier_.notify_all();
        return std::move(v);
    }

    inline bool unlocked_read_available() { return write_idx_ - read_idx_ != 0; }

    std::mutex lock_;
    std::condition_variable notifier_;
    size_t read_idx_;
    size_t write_idx_;
    std::array<T, SIZE> buf_;
};
#endif

#endif

max_stars_repo_name: TakeScoop/cpp-eventemitter

max_issues_repo_name: TakeScoop/cpp-eventemitter

max_forks_repo_name: TakeScoop/cpp-eventemitter


text:
/*    Copyright (c) 2010-2019, Delft University of Technology
 *    All rigths reserved
 *
 *    This file is part of the Tudat. Redistribution and use in source and
 *    binary forms, with or without modification, are permitted exclusively
 *    under the terms of the Modified BSD license. You should have received
 *    a copy of the license with this file. If not, please or visit:
 *    http://tudat.tudelft.nl/LICENSE.
 *
 *    References
 *      E.H. Hirschel and C. Weiland, Selected Aerothermodynamic Design Problems of Hypersonic
 *          Flight Vehicles (chapter 5), Springer/AIAA, 2009.
 *      D. Dirkx, Continuous Shape Optimization of Entry Vehicles, MSc thesis, Delft University
 *          of Technology, 2011 (Unpublished).
 *
 */

#include <cmath>
#include <iostream>

#include <boost/make_shared.hpp>
#include <memory>

#include <Eigen/Core>

#include "Tudat/Mathematics/BasicMathematics/mathematicalConstants.h"

#include "Tudat/Mathematics/GeometricShapes/capsule.h"
#include "Tudat/Mathematics/GeometricShapes/conicalFrustum.h"
#include "Tudat/Mathematics/GeometricShapes/sphereSegment.h"
#include "Tudat/Mathematics/GeometricShapes/torus.h"

namespace tudat
{
namespace geometric_shapes
{

//! Default constructor.
Capsule::Capsule( const double noseRadius,
                  const double middleRadius,
                  const double rearLength,
                  const double rearAngle,
                  const double sideRadius )
{
    using std::sin;
    using std::cos;
    using mathematical_constants::PI;

    // Call set functions for number of single and composite surface geometries
    // with predetermined values.
    setNumberOfCompositeSurfaceGeometries( 0 );
    setNumberOfSingleSurfaceGeometries( 4 );

    // Set member shape variables
    noseRadius_ = noseRadius;
    middleRadius_ = middleRadius;
    rearLength_ = rearLength;
    rearAngle_ = rearAngle;
    sideRadius_ = sideRadius;

    // Determine and set extent of spherical nose part.
    double noseSphereAngle_ = asin( ( middleRadius_ - sideRadius_ )
                                    / ( noseRadius_ - sideRadius_ ) );

    // Create nose sphere.
    std::shared_ptr< SphereSegment > noseSphere_ = std::make_shared< SphereSegment >(
                noseRadius_, 0, 2 * PI, 0, noseSphereAngle_ );

    // Declare translation vector.
    Eigen::VectorXd translationVector_ = Eigen::VectorXd( 3 );
    translationVector_( 2 ) = 0.0;
    translationVector_( 1 ) = 0.0;
    translationVector_( 0 ) = - noseRadius_ * cos( noseSphereAngle_ );

    // Set nose translation vector.
    noseSphere_->setOffset( translationVector_ );

    // Set noseSphere_ in singleSurfaceList_.
    setSingleSurfaceGeometry( noseSphere_, 0 );

    //Calculate noseSphere volume
    double noseSphereHeight_ = noseRadius_ * (1.0 - cos( noseSphereAngle_ ));
    double noseSphereVolume_ = (PI / 3.0) * pow(noseSphereHeight_, 2.0) * (
                3.0 * noseRadius - noseSphereHeight_ );

    // Create rear cone, fully revolved.
    std::shared_ptr< ConicalFrustum > cone_ = std::make_shared< ConicalFrustum >(
                rearAngle_, middleRadius_ - sideRadius_ * ( 1.0 - cos( rearAngle_ ) ),
                rearLength_ );

    // Set translation vector of cone.
    translationVector_( 0 ) = -sideRadius_ * ( sin( PI / 2.0 - noseSphereAngle_ )
                                               + sin ( -rearAngle_ ) );
    cone_->setOffset( translationVector_ );

    // Set cone in singleSurfaceList_.
    setSingleSurfaceGeometry( cone_, 1 );

    // Obtain start radius of cone.
    double startRadius_ = cone_->getStartRadius( );

    // Calculate end radius of cone.
    double endRadius_ = startRadius_ + rearLength_ * tan( rearAngle_ );

    // Calculate volume of cone.
    double fullConeLength_ = rearLength_ + endRadius_ / tan( -rearAngle_ );
    double coneVolume_ = (PI / 3.0) *
            ( pow(startRadius_, 2.0) * fullConeLength_ -
              pow(endRadius_, 2.0) * ( fullConeLength_ - rearLength_ ));

    // Calculate rear sphere radius.
    double rearNoseRadius_ = endRadius_ / cos( -rearAngle_ );

    // Create rear sphere ( "end cap" ), fully revolved.
    std::shared_ptr< SphereSegment > rearSphere_ = std::make_shared< SphereSegment >(
                rearNoseRadius_, 0.0, 2.0 * PI, PI / 2.0 - rearAngle_, PI );

    // Set translation vector of rear sphere.
    translationVector_( 0 ) =  ( rearNoseRadius_ * sin( -rearAngle_ ) ) - rearLength_
            - ( sideRadius_ * ( sin( PI / 2.0 - noseSphereAngle_ ) + sin ( -rearAngle_ ) ) );
    rearSphere_->setOffset( translationVector_ );
    setSingleSurfaceGeometry( rearSphere_, 2 );

    // Calcualte volume of rear sphere
    double rearSphereHeight_ = rearNoseRadius_ * ( 1.0 - cos( (PI / 2.0) + rearAngle));
    double rearSphereVolume_ = (PI / 3.0 ) * pow( rearSphereHeight_, 2.0 ) * (
                3.0 * rearNoseRadius_ - rearSphereHeight_);

    // Create torus section of capsule.
    double torusMajorRadius_ = ( noseRadius_ - sideRadius_ ) * sin( noseSphereAngle_ );
    std::shared_ptr< Torus > torus_ = std::make_shared< Torus >(
       torusMajorRadius_, sideRadius_, 0.0, 2.0 * PI, PI / 2.0 - noseSphereAngle_, rearAngle_ );

    //Calculate torus volume
    double minimumDiskRadius_ = middleRadius_ - sideRadius_;
    double integrationLowerLimit_ = -1.0 * sideRadius_ * cos( noseSphereAngle_ );
    double integrationUpperLimit_ = sideRadius_ * sin( -rearAngle_ );
    double torusVolume_ = PI * (
            pow( minimumDiskRadius_, 2.0 ) * (integrationUpperLimit_ - integrationLowerLimit_ )
            + minimumDiskRadius_ * pow( sideRadius_, 2.0 ) * (
                (asin( integrationUpperLimit_ / sideRadius_) + 0.5* sin( 2* asin(integrationUpperLimit_ / sideRadius_)))
                - (asin( integrationLowerLimit_ / sideRadius_) + 0.5* sin( 2* asin(integrationLowerLimit_ / sideRadius_)))
                )
            + pow( sideRadius_, 2.0 ) * ( integrationUpperLimit_ - integrationLowerLimit_ )
            - (pow( integrationUpperLimit_, 3.0 ) - pow( integrationLowerLimit_, 3.0 )) / 3.0
                );

    //Calculate total capsule volume
    capsuleVolume_ = noseSphereVolume_ + coneVolume_ + rearSphereVolume_ + torusVolume_;

    //Calculate total capsule length
    totalLength_ = noseSphereHeight_ - integrationLowerLimit_ + integrationUpperLimit_ +
            rearLength_ + rearSphereHeight_;

    //Calculate frontal area
    frontalArea_ = PI * pow( middleRadius_, 2.0 );

    // Set translation vector of rear sphere.
    translationVector_( 0 ) = -cos( noseSphereAngle_ ) * sideRadius_;
    torus_->setOffset( translationVector_ );
    setSingleSurfaceGeometry( torus_, 3 );

    // Set rotation matrix fo each part to be compatible with flow direction in
    // aerodynamic analysis.
    Eigen::MatrixXd rotationMatrix = Eigen::MatrixXd( 3, 3 );
    double angle_ = PI / 2.0;
    rotationMatrix( 0, 0 ) = cos( angle_ );
    rotationMatrix( 0, 1 ) = 0.0;
    rotationMatrix( 0, 2 ) = sin( angle_ );
    rotationMatrix( 1, 0 ) = 0.0;
    rotationMatrix( 1, 1 ) = 1.0;
    rotationMatrix( 1, 2 ) = 0.0;
    rotationMatrix( 2, 0 ) = -sin( angle_ );
    rotationMatrix( 2, 1 ) = 0.0;
    rotationMatrix( 2, 2 ) = cos( angle_ );

    // Set rotation matrix for single surface geometries.
    for ( unsigned i = 0; i < numberOfSingleSurfaceGeometries_ ; i++ )
    {
        singleSurfaceGeometryList_[ i ]->setRotationMatrix( rotationMatrix );
    }
}

//! Overload ostream to print class information.
std::ostream &operator << ( std::ostream &stream, Capsule& capsule )
{
    stream << "This is a capsule." << std::endl;
    stream << "The defining parameters are: " << std::endl
           << "Nose radius: " << capsule.getNoseRadius( ) << std::endl
           << "Mid radius: " << capsule.getMiddleRadius( ) << std::endl
           << "Rear length: " << capsule.getRearLength( ) << std::endl
           << "Rear angle: " << capsule.getRearAngle( ) << std::endl
           << "Side radius: " << capsule.getSideRadius( ) << std::endl;

    return stream;
}

} // namespace geometric_shapes
} // namespace tudat

max_stars_repo_name: sebranchett/tudat

max_issues_repo_name: sebranchett/tudat

max_forks_repo_name: sebranchett/tudat


text:
#pragma once
#include <string>
#include <boost/variant.hpp>
#include <cstdint>
#include <map>
#include <unordered_map>
#include <vector>
#include <sstream>
#include <boost/core/noncopyable.hpp>
#include "comboaddress.hh"
#include <atomic>
#include <json.hpp>

extern bool g_kolmoRuntimeDeclared;

class KolmoVal
{
public:
  virtual std::unique_ptr<KolmoVal> clone() const =0;
  void copyInBasics(const KolmoVal& rhs)
  {
    *((KolmoVal*)this)=rhs;
    /*
    mandatory = rhs.mandatory;
    runtime = rhs.runtime;
    defaultValue = rhs.defaultValue;
    description = rhs.description;
    cmdline = rhs.cmdline;
    check = rhs.check;
    unit = rhs.unit;
    */
  }
  bool mandatory{false};
  bool runtime{false};
  std::string defaultValue; // I know
  std::string description;
  std::string unit;
  std::string cmdline;
  std::string check;
  virtual std::string getTypename() const = 0;
  virtual void setValue(const std::string&)=0;
  virtual std::string getValue() const=0;
  virtual std::string display(int indent=0) const=0;
  void tie(std::function<void(KolmoVal*)> v)
  {
    d_ties.push_back(v);
    v(this);
  }

  virtual bool operator==(const KolmoVal& rhs) const=0;
  virtual bool operator==(const std::unique_ptr<KolmoVal>& rhs) const
  {
    return operator==(*rhs.get());
  }

  bool operator!=(const KolmoVal& rhs) const
  {
    return !this->operator==(rhs);
  }

  bool operator!=(const std::unique_ptr<KolmoVal>& rhs) const
  {
    return !this->operator==(*rhs.get());
  }

protected:
  void runTies()
  {
    for(auto& t : d_ties)
      t(this);
  }

  void checkRuntime();

private:
  std::vector<std::function<void(KolmoVal*)> > d_ties;
};

class KolmoBool : public KolmoVal
{
public:
  explicit KolmoBool(bool v) : d_v(v)
  {}

  std::unique_ptr<KolmoVal> clone() const
  {
    auto ret= std::make_unique<KolmoBool>(d_v);
    ret->copyInBasics(*this);
    return ret;
  }

  std::string getTypename() const override
  {
    return "bool";
  }

  std::string getValue() const override
  {
    return d_v ? "true" : "false";
  }

  void setValue(const std::string& str)
  {
    if(str=="true")
      d_v = true;
    else if(str=="false")
      d_v = false;
    else
      throw std::runtime_error("Attempt to set bool to something not true or false");

    checkRuntime();

    runTies();
  }

  static std::unique_ptr<KolmoVal> make(bool v)
  {
    KolmoBool ret(v);
    return ret.clone();
  }

  std::string display(int indent=0) const
  {
    std::ostringstream ret;
    ret<<std::string(indent, ' ')<<(d_v ? "true" : "false")<<" ["<<description<<"], default="<<defaultValue<<std::endl;
    return ret.str();
  }

  bool getBool() const
  {
    return d_v;
  }
  void setBool(bool v)
  {
    d_v=v;
    runTies();
  }

  bool operator==(const KolmoVal& rhs) const override
  {
    return typeid(*this) == typeid(rhs) && d_v == dynamic_cast<const KolmoBool&>(rhs).d_v;
  }

private:
  bool d_v;

};

class KolmoString : public KolmoVal
{
public:
  explicit KolmoString(const std::string& s) : d_v(s)
  {}

  static std::unique_ptr<KolmoVal> make(const std::string& s)
  {
    return std::make_unique<KolmoString>(s);
  }
  void setValue(const std::string& str)
  {
    checkRuntime();
    d_v = str;
  }

  std::string getTypename() const override
  {
    return "string";
  }

  std::string getValue() const override
  {
    return d_v;
  }

  std::unique_ptr<KolmoVal> clone() const
  {
    auto ret=std::make_unique<KolmoString>(d_v);
    ret->copyInBasics(*this);
    return ret;
  }
  std::string display(int indent=0) const
  {
    std::ostringstream ret;
    ret<<std::string(indent, ' ')<<d_v<<" ["<<description<<"]"<<std::endl;
    return ret.str();
  }

  bool operator==(const KolmoVal& rhs) const override
  {
    return typeid(*this) == typeid(rhs) && d_v == dynamic_cast<const KolmoString&>(rhs).d_v;
  }

  std::string d_v;
};

class KolmoIPEndpoint : public KolmoVal
{
public:
  explicit KolmoIPEndpoint(const std::string& str)
  {
    if(str.empty())
      d_v.sin4.sin_family=0;
    else
      d_v=ComboAddress(str, d_defaultPort);
  }

  explicit KolmoIPEndpoint(const ComboAddress& ca) : d_v(ca)
  {}

  std::string getTypename() const override
  {
    return "ipendpoint";
  }

  explicit KolmoIPEndpoint()
  {
    d_v.sin4.sin_family=0;
  }

  static std::unique_ptr<KolmoVal> make(const std::string& str)
  {
    return std::make_unique<KolmoIPEndpoint>(str);
  }

  std::unique_ptr<KolmoVal> clone() const
  {
    auto ret=std::make_unique<KolmoIPEndpoint>(d_v);
    ret->copyInBasics(*this);
    ret->d_defaultPort = d_defaultPort;
    return ret;
  }

  void setValue(const std::string& in)
  {
    checkRuntime();
    if(in.empty())
      d_v.sin4.sin_family=0;
    else
      d_v=ComboAddress(in, d_defaultPort);
  }

  std::string getValue() const override
  {
    if(d_v.sin4.sin_family)
      return d_v.toStringWithPort();
    else
      return "";
  }

  std::string display(int indent=0) const
  {
    std::ostringstream ret;
    ret<<std::string(indent, ' ')<<d_v.toStringWithPort()<<" ["<<description<<"] default="<<defaultValue<<std::endl;
    return ret.str();
  }

  void setIPEndpoint(const ComboAddress& ca)
  {
    d_v=ca;
  }

  ComboAddress getIPEndpoint() const
  {
    return d_v;
  }

  bool operator==(const KolmoVal& rhs) const override
  {
    const auto& casted = dynamic_cast<const KolmoIPEndpoint&>(rhs);
    return typeid(*this) == typeid(rhs) && ((d_v.sin4.sin_family ==0 && casted.d_v.sin4.sin_family ==0) || d_v == casted.d_v);
  }

  void setDefaultPort(uint16_t port)
  {
    d_defaultPort = port;
  }

private:
  ComboAddress d_v;
  uint16_t d_defaultPort{0};
};

class KolmoIPAddress : public KolmoVal
{
public:
  explicit KolmoIPAddress(const std::string& str)
  {
    d_v.sin4.sin_port=0;
    if(str.empty())
      d_v.sin4.sin_family=0;
    else
      d_v=ComboAddress(str);

    if(d_v.sin4.sin_port)
      throw std::runtime_error("An IP address has no port number");
  }

  explicit KolmoIPAddress(const ComboAddress& ca) : d_v(ca)
  {}

  std::string getTypename() const override
  {
    return "ipaddress";
  }

  explicit KolmoIPAddress()
  {
    d_v.sin4.sin_family=0;
  }

  static std::unique_ptr<KolmoVal> make(const std::string& str)
  {
    return std::make_unique<KolmoIPAddress>(str);
  }

  std::unique_ptr<KolmoVal> clone() const
  {
    auto ret=std::make_unique<KolmoIPAddress>(d_v);
    ret->copyInBasics(*this);
    return ret;
  }

  void setValue(const std::string& in)
  {
    checkRuntime();
    if(in.empty())
      d_v.sin4.sin_family=0;
    else
      setIPAddress(ComboAddress(in));
  }

  std::string getValue() const override
  {
    if(d_v.sin4.sin_family)
      return d_v.toString();
    else
      return "";
  }

  std::string display(int indent=0) const
  {
    std::ostringstream ret;
    ret<<std::string(indent, ' ')<<getValue()<<" ["<<description<<"] default="<<defaultValue<<std::endl;
    return ret.str();
  }

  void setIPAddress(const ComboAddress& ca)
  {
    if(ca.sin4.sin_port)
      throw std::runtime_error("An IP address has no port number");
    d_v=ca;
  }

  ComboAddress getIPAddress() const
  {
    return d_v;
  }

  bool operator==(const KolmoVal& rhs) const override
  {
    const auto& casted = dynamic_cast<const KolmoIPAddress&>(rhs);
    return typeid(*this) == typeid(rhs) && ((d_v.sin4.sin_family ==0 && casted.d_v.sin4.sin_family ==0) || d_v == casted.d_v);
  }

private:
  ComboAddress d_v;
};

class KolmoNetmask : public KolmoVal
{
public:
  explicit KolmoNetmask(const std::string& str)
  {
    if(!str.empty())
      d_v=Netmask(str);
  }

  explicit KolmoNetmask(const Netmask& ca) : d_v(ca)
  {}

  std::string getTypename() const override
  {
    return "netmask";
  }

  explicit KolmoNetmask()
  {
  }

  static std::unique_ptr<KolmoVal> make(const std::string& str)
  {
    return std::make_unique<KolmoNetmask>(str);
  }

  std::unique_ptr<KolmoVal> clone() const
  {
    auto ret=std::make_unique<KolmoNetmask>(d_v);
    ret->copyInBasics(*this);
    return ret;
  }

  void setValue(const std::string& in)
  {
    checkRuntime();
    if(!in.empty()) {
      d_v=Netmask(in);
    }
  }

  std::string getValue() const override
  {
    return d_v.toString();
  }

  std::string display(int indent=0) const
  {
    std::ostringstream ret;
    ret<<std::string(indent, ' ')<<d_v.toString()<<" ["<<description<<"] default="<<defaultValue<<std::endl;
    return ret.str();
  }

  void setNetmask(const Netmask& ca)
  {
    d_v=ca;
  }

  Netmask getNetmask() const
  {
    return d_v;
  }

  bool operator==(const KolmoVal& rhs) const override
  {
    const auto& casted = dynamic_cast<const KolmoNetmask&>(rhs);
    return typeid(*this) == typeid(rhs) && d_v == casted.d_v;
  }

private:
  Netmask d_v;
};

class KolmoInteger : public KolmoVal
{
public:
  explicit KolmoInteger(int64_t v) : d_v(v)
  {}

  static std::unique_ptr<KolmoVal> make(uint64_t v)
  {
    return std::make_unique<KolmoInteger>(v);
  }
  std::string getTypename() const override
  {
    return "integer";
  }

  std::unique_ptr<KolmoVal> clone() const
  {
    auto ret=std::make_unique<KolmoInteger>(d_v);
    ret->copyInBasics(*this);
    return ret;
  }

  void setValue(const std::string& in)
  {
    checkRuntime();
    setInteger(atoi(in.c_str())); // XXX 64 bit
  }

  std::string getValue() const override
  {
    return std::to_string(d_v);
  }

  uint64_t getInteger() const
  {
    return d_v;
  }

  void setInteger(int64_t v);

  std::string display(int indent=0) const
  {
    std::ostringstream ret;
    ret<<std::string(indent, ' ')<<d_v<<" ["<<description<<"] default="<<defaultValue;
    if(!unit.empty())
      ret<<" unit="<<unit;
    ret<<std::endl;
    return ret.str();
  }

  bool operator==(const KolmoVal& rhs) const override
  {
    return typeid(*this) == typeid(rhs) && d_v == dynamic_cast<const KolmoInteger&>(rhs).d_v;
  }

private:

  int64_t d_v;
};

class KolmoStruct : public KolmoVal, public boost::noncopyable
{
public:
  KolmoStruct() {}
  bool getBool(const std::string& name) const;
  ComboAddress getIPEndpoint(const std::string& name) const;
  ComboAddress getIPAddress(const std::string& name) const;
  int64_t getInteger(const std::string& name) const;
  Netmask getNetmask(const std::string& name) const;
  std::string getString(const std::string& name) const;
  void setString(const std::string& name, const std::string& value);
  void setBool(const std::string& name, bool v);
  void tieBool(const std::string& name, std::atomic<bool>* target);
  void setIPEndpoint(const std::string& name, const std::string& value);
  void setIPEndpointCA(const std::string& name, const ComboAddress& ca);
  void setIPAddressCA(const std::string& name, const ComboAddress& ca);
  void setStruct(const std::string& name, std::unique_ptr<KolmoStruct> s);
  void setInteger(const std::string& name, uint64_t value);
  KolmoVal* getMember(const std::string& name) const;
  bool isMember(const std::string& name) const
  {
    return d_store.count(name);
  }

  std::string getTypename() const override
  {
    return "struct";
  }

  KolmoStruct* getStruct(const std::string& name) const;
  void registerVariableLua(const std::string& name, const std::string& type, std::unordered_map<std::string, boost::variant<std::string,bool,double> > attributes);
  void registerBool(const std::string& name, bool v);
  void registerString(const std::string& name, const std::string& );
  void registerIPEndpoint(const std::string& name, const std::string& );
  void registerStruct(const std::string& name, const std::string& );
  void registerStructMember(const std::string& name, KolmoStruct* s);
  void addValueToStruct(const std::string& name, const std::string& val);
  void addValue(const std::string& val);

  KolmoStruct* getNewMember() const;
  std::string getValue() const override
  {
    return "{struct}";
  }
  void unregisterVariable(const std::string& name)
  {
    d_store.erase(name);
  }

  std::unique_ptr<KolmoStruct> diff(const KolmoStruct& temp, const KolmoStruct& rhs, int nest=0) const;

  std::unique_ptr<KolmoVal> clone() const;

  std::vector<std::string> getMembers() const
  {
    std::vector<std::string> ret;
    for(const auto& m : d_store)
      ret.push_back(m.first);
    return ret;
  }

  std::vector<std::pair<std::string, KolmoVal*> > getAll() const
  {
    std::vector<std::pair<std::string, KolmoVal*>> ret;
    for(const auto& m : d_store)
      ret.push_back({m.first, m.second.get()});
    return ret;
  }

  void setValue(const std::string& )
  {
    checkRuntime();
    // should maybe do JSON
    abort();
  }
  void setValueAt(const std::string& str, const std::string& val);
  void rmValueAt(const std::string& str);
  KolmoVal* getValueAt(const std::string& name) const;
  std::string display(int indent=0) const
  {
    std::ostringstream ret;
    ret<<std::string(indent, ' ')<<"["<<description<<"]"<<std::endl;
    for(const auto& m : d_store) {
      ret<<std::string(indent, ' ')<<m.first<<":"<<std::endl;
      ret<<m.second->display(indent+8);
    }

    return ret.str();
  }
  void setMemberType(const std::string& str)
  {
    d_membertype = str;
  }
  std::string getMemberType() const
  {
    return d_membertype;
  }

  bool empty() const
  {
    return d_store.empty();
  }

  bool operator==(const KolmoVal& rhs) const override
  {
    return typeid(*this) == typeid(rhs) && d_store == dynamic_cast<const KolmoStruct&>(rhs).d_store;
  }

  std::string d_membertype, d_mytype;
private:

  std::map<std::string, std::unique_ptr<KolmoVal>> d_store;
};

/* idea
   The schema is a Lua file that creates KolmoClasses
   Some classes exist already: bool, ComboAddress, String

   There is an empty global namespace which is vector of KolmoClasses.
   To keep things exciting, a KolmoClass can also be a vector of KolmoClasses.

   The schema file populates the global namespace with named global settings,
   and their defaults, and also creates empty holders (with a name)
   for things the target program needs: service endpoints, rules etc.

   So a sample configuration may be:

   "verbose": bool
   define Site
   "sites": vector<Site>
*/

class LuaContext;
extern std::map<std::string, std::unique_ptr<KolmoVal> > d_prototypes; // XXX NO NO NO, has to be in kolmoconf!
const KolmoStruct* getPrototype(const std::string& name);
class KolmoConf
{
public:
  KolmoConf();
  ~KolmoConf();
  void initSchemaFromString(const std::string& str);
  void initSchemaFromFile(const std::string& str);
  void initConfigFromLua(const std::string& str);
  void initConfigFromJSON(const std::string& str);
  void initConfigFromCmdline(int argc, char**argv);

  KolmoStruct d_main;

  void declareRuntime()
  {
    d_startup = std::move(d_main.clone());
    g_kolmoRuntimeDeclared=true;
  }

  std::unique_ptr<KolmoStruct> getRuntimeDiff() const
  {
    return dynamic_cast<const KolmoStruct*>(d_startup.get())->diff(
								   *dynamic_cast<const KolmoStruct*>(d_default.get()),
								   d_main);
  }

  std::unique_ptr<KolmoStruct> getMinimalConfig() const
  {
    //    return d_main.diff(*dynamic_cast<const KolmoStruct*>(d_default.get()), *dynamic_cast<const KolmoStruct*>(d_default.get()));
    return dynamic_cast<const KolmoStruct*>(d_default.get())->diff(
    								   *dynamic_cast<const KolmoStruct*>(d_default.get()),
    								   d_main);
  }

private:
  void luaInit();
  std::unique_ptr<KolmoVal> d_default, d_startup;

  LuaContext* d_lua{0};
};

void KSToJson(KolmoStruct* ks, nlohmann::json& x);
void JsonToKS(nlohmann::json& x, KolmoStruct* ks, int indent=0);

ext: hh

max_stars_repo_name: ahupowerdns/kolmo

max_issues_repo_name: ahupowerdns/kolmo

max_forks_repo_name: ahupowerdns/kolmo


text:
////////////////////////////////////////////////////////////////////////////////////
//  Geometric utilities for multicamera calibration
//
//  Copyright (C) 2016  David Alejo, Fernando Caballero, Luis Merino
//  Universidad Pablo de Olavide
//  Seville, Spain.
//
//  This program is free software; you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation; either version 2 of the License, or
//  (at your option) any later version.
//
//  This program 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 General Public License for more details.
//
////////////////////////////////////////////////////////////////////////////////////

#ifndef GEOMETRIC_UTILS__
#define GEOMETRIC_UTILS__

#include <boost/random/normal_distribution.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/variate_generator.hpp>
#include <boost/concept_check.hpp>
#include <Eigen/Core>
#include <Eigen/Geometry>

#ifndef  CALI_VEC_SIZE
#define CALI_VEC_SIZE 7
#endif

typedef boost::variate_generator<boost::mt19937, boost::normal_distribution<> > NormalDist;
static NormalDist norm_dist(boost::mt19937(time(0)), boost::normal_distribution<>(0, 1.0));

// --------------------------- General utilities ----------------------------------
double f_rand(double fMin = 0.0, double fMax = 1.0)
{
  static bool init = false;
  if (!init) {
    init = true;
    srand(time(NULL));
  }
  double f = (double)rand() / RAND_MAX;
  return fMin + f * (fMax - fMin);
}

std::vector<double> eigen2stdvec(const Eigen::Vector3d &v) {
  std::vector<double> ret;
  ret.resize(3);
  for (int i = 0; i < 3; i++) {
    ret[i] = v[i];
  }
  return ret;
}

// ----------------- Geometric utilities ------------------------------

//! Gets a transformation from a parameter
Eigen::Affine3d getTransform(const double *p)
{
  // Get the transformation matrix T from p vector
  Eigen::Affine3d T = Eigen::Affine3d::Identity();
  Eigen::Quaterniond R(p[0], p[1], p[2], p[3]);
  T.rotate(R);
  T.pretranslate(Eigen::Vector3d(p[4], p[5], p[6]));

  return T;
}

void decomposeTransform(const Eigen::Affine3d &T, Eigen::Quaterniond &q, Eigen::Vector3d &v) {
  Eigen::Quaterniond d(T.rotation( ));
  q = d;
  v[0] = T(0,3);
  v[1] = T(1,3);
  v[2] = T(2,3);
}

bool quat2rotvec(const Eigen::Quaterniond &q, Eigen::Vector3d &v) {
  double norm = sqrt(1 - q.w());
  if (norm < 1e-4) {
    // Too small rotation
    v[0] = v[1] = v[2] = 0.0;
    return false;
  }
  norm = 1 / norm;
  v[0] = q.x() * norm;
  v[1] = q.y() * norm;
  v[2] = q.z() * norm;

  return true;
}

Eigen::Quaterniond euler2quat(double roll, double pitch, double yaw) {
  Eigen::AngleAxisd yawAngle(yaw, Eigen::Vector3d(0.0, 0.0, 1.0));
  Eigen::AngleAxisd rollAngle(roll, Eigen::Vector3d(1.0, 0.0, 0.0));
  Eigen::AngleAxisd pitchAngle(pitch, Eigen::Vector3d(0.0, 1.0, 0.0));
  Eigen::Quaterniond q =  yawAngle * pitchAngle * rollAngle; // 3-2-1

  return q;
}

// Returns the 3-2-1 body angles in [roll, pitch, yaw]
Eigen::Vector3d quat2euler(const Eigen::Quaterniond &q) {
  Eigen::Vector3d ret;
  double w = q.w(), x = q.x(), y = q.y(), z = q.z();

  ret[0] = atan2(2*(w*x + y*z), 1 - 2*(x*x + y*y));
  ret[1] = asin(0.9999999* (2*(w*y - z*x)));
//   cout << "x = " << asin(1.0) << endl;
  ret[2] = atan2(2*(w*z + x*y), 1 - 2*(y*y + z*z));

  return ret;
}

#endif


text:
#include <boost/python/object.hpp>

inline boost::python::object get_as_bpo(PyObject* o) {
        return boost::python::object(boost::python::handle<>(boost::python::borrowed(o)));
}

max_stars_repo_name: sergiik/OMPEval

max_issues_repo_name: sergiik/OMPEval

max_forks_repo_name: sergiik/OMPEval