<commit_before>#ifndef MJOLNIR_READ_INTEGRATOR
#define MJOLNIR_READ_INTEGRATOR
#include <extlib/toml/toml.hpp>
#include <mjolnir/core/VelocityVerletStepper.hpp>
#include <mjolnir/core/UnderdampedLangevinStepper.hpp>
#include <mjolnir/util/get_toml_value.hpp>

namespace mjolnir
{

template<typename traitsT>
VelocityVerletStepper<traitsT>
read_velocity_verlet_stepper(const toml::Table& simulator)
{
    MJOLNIR_GET_DEFAULT_LOGGER();
    MJOLNIR_SCOPE(read_velocity_verlet_stepper(), 0);
    typedef typename traitsT::real_type real_type;

    const real_type delta_t =
        get_toml_value<real_type>(simulator, "delta_t", "[simulator]");
    MJOLNIR_LOG_INFO("delta_t = ", delta_t);

    return VelocityVerletStepper<traitsT>(delta_t);
}

template<typename traitsT>
UnderdampedLangevinStepper<traitsT>
read_underdamped_langevin_stepper(const toml::Table& simulator)
{
    MJOLNIR_GET_DEFAULT_LOGGER();
    MJOLNIR_SCOPE(read_underdamped_langevin_stepper(), 0);
    typedef typename traitsT::real_type real_type;

    const auto& parameters = // array of tables
        get_toml_value<toml::Array>(simulator, "parameters", "[simulator]");
    const auto  seed =
        get_toml_value<std::uint32_t>(simulator, "seed", "[simulator]");

    std::vector<real_type> gamma(parameters.size());
    for(const auto& tab : parameters)
    {
        const auto& params = tab.cast<toml::value_t::Table>();
        const std::size_t idx = get_toml_value<std::size_t>(
                params, "index", "<anonymous> in register");
        const real_type    gm = get_toml_value<real_type>(
                params, "gamma", "<anonymous> in register");

        if(gamma.size() <= idx){gamma.resize(idx+1);}
        gamma.at(idx) = gm;
        MJOLNIR_LOG_INFO("idx = ", idx, ", gamma = ", gamma);
    }

    const real_type delta_t =
        get_toml_value<real_type>(simulator, "delta_t", "[simulator]");
    MJOLNIR_LOG_INFO("delta_t = ", delta_t);

    return UnderdampedLangevinStepper<traitsT>(delta_t, std::move(gamma),
            RandomNumberGenerator<traitsT>(seed));
}

}
#endif// MJOLNIR_READ_INTEGRATOR
<commit_msg>fix logging in read_integrator<commit_after>#ifndef MJOLNIR_READ_INTEGRATOR
#define MJOLNIR_READ_INTEGRATOR
#include <extlib/toml/toml.hpp>
#include <mjolnir/core/VelocityVerletStepper.hpp>
#include <mjolnir/core/UnderdampedLangevinStepper.hpp>
#include <mjolnir/util/get_toml_value.hpp>

namespace mjolnir
{

template<typename traitsT>
VelocityVerletStepper<traitsT>
read_velocity_verlet_stepper(const toml::Table& simulator)
{
    MJOLNIR_GET_DEFAULT_LOGGER();
    MJOLNIR_SCOPE(read_velocity_verlet_stepper(), 0);
    typedef typename traitsT::real_type real_type;

    const real_type delta_t =
        get_toml_value<real_type>(simulator, "delta_t", "[simulator]");
    MJOLNIR_LOG_INFO("delta_t = ", delta_t);

    return VelocityVerletStepper<traitsT>(delta_t);
}

template<typename traitsT>
UnderdampedLangevinStepper<traitsT>
read_underdamped_langevin_stepper(const toml::Table& simulator)
{
    MJOLNIR_GET_DEFAULT_LOGGER();
    MJOLNIR_SCOPE(read_underdamped_langevin_stepper(), 0);
    typedef typename traitsT::real_type real_type;

    const auto& parameters = // array of tables
        get_toml_value<toml::Array>(simulator, "parameters", "[simulator]");
    const auto  seed =
        get_toml_value<std::uint32_t>(simulator, "seed", "[simulator]");

    std::vector<real_type> gamma(parameters.size());
    for(const auto& tab : parameters)
    {
        const auto& params = tab.cast<toml::value_t::Table>();
        const std::size_t idx = get_toml_value<std::size_t>(
                params, "index", "<anonymous> in register");
        const real_type    gm = get_toml_value<real_type>(
                params, "gamma", "<anonymous> in register");

        if(gamma.size() <= idx){gamma.resize(idx+1);}
        gamma.at(idx) = gm;
        MJOLNIR_LOG_INFO("idx = ", idx, ", gamma = ", gm);
    }

    const real_type delta_t =
        get_toml_value<real_type>(simulator, "delta_t", "[simulator]");
    MJOLNIR_LOG_INFO("delta_t = ", delta_t);

    return UnderdampedLangevinStepper<traitsT>(delta_t, std::move(gamma),
            RandomNumberGenerator<traitsT>(seed));
}

}
#endif// MJOLNIR_READ_INTEGRATOR
<|endoftext|>


<commit_before>#pragma once

#include <cstddef>
#include <initializer_list>
#include <type_traits>
#include <stdexcept>

namespace cu
{

/// A view into an array of contiguous elements.
///
/// It contains a pointer and a size as information and supports reference
/// semantics to the underlying storage. It is similiar to std::string_view
/// or std::array_view.
template <typename T>
struct Slice
{
    Slice() noexcept = default;

    Slice( T * ptr, std::size_t size ) noexcept
        : ptr_ (ptr )
        , size_(size)
    {}

    Slice( T * first, T * last ) noexcept
      : Slice( first, last-first )
    {}

    Slice( std::initializer_list<T> list )
      : Slice( list.begin(), list.size() )
    {}

    template <typename Container,
              typename std::enable_if<
                std::is_same<T*,typename Container::pointer>::value,int>::type = 0>
    Slice( Container & container ) noexcept
      : Slice( container.data(), container.size() )
    {}

    template <typename Container,
              typename std::enable_if<
                std::is_same<T*,typename Container::const_pointer>::value,int>::type = 0>
    Slice( const Container & container ) noexcept
      : Slice( container.data(), container.size() )
    {}

    template <std::size_t N>
    Slice( T(&arr)[N] ) noexcept
      : Slice( arr, N )
    {}

    T * begin() const noexcept
    {
        return ptr_;
    }

    T * end() const noexcept
    {
        return ptr_ + size_;
    }

    T * data() const noexcept
    {
      return ptr_;
    }

    std::size_t size() const noexcept
    {
      return size_;
    }

    bool empty() const noexcept
    {
      return size_ == 0;
    }

    void swap( Slice & other ) noexcept
    {
      Slice tmp = other;
      other = *this;
      *this = tmp;
    }

    T & operator[]( std::size_t index ) const noexcept
    {
      return ptr_[index];
    }

    T & at( std::size_t index ) const
    {
      if ( index >= size_ )
        throw std::out_of_range("cu::Slice access out of range.");
    }

    T & front() const noexcept
    {
      return *ptr_;
    }

    T & back() const noexcept
    {
      return ptr_[size_-1];
    }

    Slice withoutHead() const noexcept
    {
      return { ptr_+1, size_-1 };
    }

    Slice withoutTail() const noexcept
    {
      return { ptr_, size_-1 };
    }

private:
    T * ptr_ = nullptr;
    std::size_t size_ = 0;
};

template <typename T>
Slice<T> makeSlice( T * ptr, std::size_t size )
{
    return { ptr, size };
};

template <typename T>
Slice<T> makeSlice( T * first, T * last )
{
    return { first, last };
};

template <typename Container>
Slice<typename Container::value_type> makeSlice( Container & container )
{
  return { container };
}

template <typename Container>
Slice<const typename Container::value_type> makeSlice( const Container & container )
{
  return { container };
}

template <typename T, std::size_t N>
Slice<T> makeSlice( T(&arr)[N] )
{
  return { arr };
}

template <typename T>
void swap( Slice<T> & lhs, Slice<T> rhs )
{
  lhs.swap( rhs );
}

} // namespace cu
<commit_msg>Added optional parameter to Slice::withoutHead() and Slice::withoutTail() and added Slice::truncated().<commit_after>#pragma once

#include <cstddef>
#include <initializer_list>
#include <type_traits>
#include <stdexcept>

namespace cu
{

/// A view into an array of contiguous elements.
///
/// It contains a pointer and a size as information and supports reference
/// semantics to the underlying storage. It is similiar to std::string_view
/// or std::array_view.
template <typename T>
struct Slice
{
    Slice() noexcept = default;

    Slice( T * ptr, std::size_t size ) noexcept
        : ptr_ (ptr )
        , size_(size)
    {}

    Slice( T * first, T * last ) noexcept
      : Slice( first, last-first )
    {}

    Slice( std::initializer_list<T> list )
      : Slice( list.begin(), list.size() )
    {}

    template <typename Container,
              typename std::enable_if<
                std::is_same<T*,typename Container::pointer>::value,int>::type = 0>
    Slice( Container & container ) noexcept
      : Slice( container.data(), container.size() )
    {}

    template <typename Container,
              typename std::enable_if<
                std::is_same<T*,typename Container::const_pointer>::value,int>::type = 0>
    Slice( const Container & container ) noexcept
      : Slice( container.data(), container.size() )
    {}

    template <std::size_t N>
    Slice( T(&arr)[N] ) noexcept
      : Slice( arr, N )
    {}

    T * begin() const noexcept
    {
        return ptr_;
    }

    T * end() const noexcept
    {
        return ptr_ + size_;
    }

    T * data() const noexcept
    {
      return ptr_;
    }

    std::size_t size() const noexcept
    {
      return size_;
    }

    bool empty() const noexcept
    {
      return size_ == 0;
    }

    void swap( Slice & other ) noexcept
    {
      Slice tmp = other;
      other = *this;
      *this = tmp;
    }

    T & operator[]( std::size_t index ) const noexcept
    {
      return ptr_[index];
    }

    T & at( std::size_t index ) const
    {
      if ( index >= size_ )
        throw std::out_of_range("cu::Slice access out of range.");
    }

    T & front() const noexcept
    {
      return *ptr_;
    }

    T & back() const noexcept
    {
      return ptr_[size_-1];
    }

    Slice withoutHead( std::size_t nElems = 1 ) const noexcept
    {
      assert( nElems <= size_ );
      return { ptr_+nElems, size_-nElems };
    }

    Slice withoutTail( std::size_t nElems = 1 ) const noexcept
    {
      assert( nElems <= size_ );
      return { ptr_, size_-nElems };
    }

    Slice truncated( std::size_t index ) const noexcept
    {
      assert( index <= size_ );
      return { ptr_, index };
    }

private:
    T * ptr_ = nullptr;
    std::size_t size_ = 0;
};

template <typename T>
Slice<T> makeSlice( T * ptr, std::size_t size )
{
    return { ptr, size };
};

template <typename T>
Slice<T> makeSlice( T * first, T * last )
{
    return { first, last };
};

template <typename Container>
Slice<typename Container::value_type> makeSlice( Container & container )
{
  return { container };
}

template <typename Container>
Slice<const typename Container::value_type> makeSlice( const Container & container )
{
  return { container };
}

template <typename T, std::size_t N>
Slice<T> makeSlice( T(&arr)[N] )
{
  return { arr };
}

template <typename T>
void swap( Slice<T> & lhs, Slice<T> rhs )
{
  lhs.swap( rhs );
}

} // namespace cu
<|endoftext|>


<commit_before>#include "widgets/AccountSwitchPopupWidget.hpp"
#include "debug/Log.hpp"
#include "widgets/dialogs/SettingsDialog.hpp"

#include <QHBoxLayout>
#include <QLayout>
#include <QPainter>
#include <QPushButton>
#include <QVBoxLayout>

namespace chatterino {

AccountSwitchPopupWidget::AccountSwitchPopupWidget(QWidget *parent)
    : QWidget(parent)
{
    this->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);

    this->setContentsMargins(0, 0, 0, 0);

    this->ui_.accountSwitchWidget = new AccountSwitchWidget(this);
    QVBoxLayout *vbox = new QVBoxLayout(this);
    this->ui_.accountSwitchWidget->setFocusPolicy(Qt::NoFocus);
    vbox->addWidget(this->ui_.accountSwitchWidget);

    // vbox->setSizeConstraint(QLayout::SetMinimumSize);

    auto hbox = new QHBoxLayout();
    auto manageAccountsButton = new QPushButton(this);
    manageAccountsButton->setText("Manage Accounts");
    hbox->addWidget(manageAccountsButton);
    vbox->addLayout(hbox);

    connect(manageAccountsButton, &QPushButton::clicked, []() {
        SettingsDialog::showDialog(SettingsDialogPreference::Accounts);  //
    });

    this->setLayout(vbox);

    //    this->setStyleSheet("background: #333");
}

void AccountSwitchPopupWidget::refresh()
{
    this->ui_.accountSwitchWidget->refresh();
}

void AccountSwitchPopupWidget::focusOutEvent(QFocusEvent *)
{
    this->hide();
}

void AccountSwitchPopupWidget::paintEvent(QPaintEvent *)
{
    QPainter painter(this);

    painter.setPen(QColor("#999"));
    painter.drawRect(0, 0, this->width() - 1, this->height() - 1);
}

}  // namespace chatterino
<commit_msg>add account switcher popup flag for linux<commit_after>#include "widgets/AccountSwitchPopupWidget.hpp"
#include "debug/Log.hpp"
#include "widgets/dialogs/SettingsDialog.hpp"

#include <QHBoxLayout>
#include <QLayout>
#include <QPainter>
#include <QPushButton>
#include <QVBoxLayout>

namespace chatterino {

AccountSwitchPopupWidget::AccountSwitchPopupWidget(QWidget *parent)
    : QWidget(parent)
{
    this->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
#ifdef Q_OS_LINUX
    this->setWindowFlag(Qt::Popup);
#endif

    this->setContentsMargins(0, 0, 0, 0);

    this->ui_.accountSwitchWidget = new AccountSwitchWidget(this);
    QVBoxLayout *vbox = new QVBoxLayout(this);
    this->ui_.accountSwitchWidget->setFocusPolicy(Qt::NoFocus);
    vbox->addWidget(this->ui_.accountSwitchWidget);

    // vbox->setSizeConstraint(QLayout::SetMinimumSize);

    auto hbox = new QHBoxLayout();
    auto manageAccountsButton = new QPushButton(this);
    manageAccountsButton->setText("Manage Accounts");
    hbox->addWidget(manageAccountsButton);
    vbox->addLayout(hbox);

    connect(manageAccountsButton, &QPushButton::clicked, []() {
        SettingsDialog::showDialog(SettingsDialogPreference::Accounts);  //
    });

    this->setLayout(vbox);

    //    this->setStyleSheet("background: #333");
}

void AccountSwitchPopupWidget::refresh()
{
    this->ui_.accountSwitchWidget->refresh();
}

void AccountSwitchPopupWidget::focusOutEvent(QFocusEvent *)
{
    this->hide();
}

void AccountSwitchPopupWidget::paintEvent(QPaintEvent *)
{
    QPainter painter(this);

    painter.setPen(QColor("#999"));
    painter.drawRect(0, 0, this->width() - 1, this->height() - 1);
}

}  // namespace chatterino
<|endoftext|>


<commit_before>/*
 * 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.
 */

#include <xalanc/Include/PlatformDefinitions.hpp>

#include <cassert>
#include <ctime>
#include <vector>

#if defined(XALAN_CLASSIC_IOSTREAMS)
#include <fstream.h>
#include <iostream.h>
#include <strstream.h>
#else
#include <fstream>
#include <iostream>
#include <strstream>
#endif

#include <xercesc/util/PlatformUtils.hpp>

#include <xalanc/XalanTransformer/XalanTransformer.hpp>

//This is here for the Windows threads.
#if defined(WINDOWS_THREAD_FUNCTIONS)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winbase.h>
#define THREADFUNCTIONRETURN DWORD WINAPI
typedef   DWORD      theThreadIDType;
typedef   HANDLE     theThreadType;

//This is here for Unix threads
#elif defined(XALAN_POSIX2_AVAILABLE)

// This is a workaround for a Tru64 compiler bug...
#if defined(TRU64)
#if  defined(XALAN_STRICT_ANSI_HEADERS)
#include <csetjmp>
typedef long sigjmp_buf[_JBLEN];
#endif
extern "C" void  *theThread(void   *param);
#endif

#include <pthread.h>
#include <unistd.h>
    typedef   pthread_t     theThreadIDType;
    typedef   pthread_t     theThreadType;

#else
//error Unsupported Platform!
#endif

#if  defined(XALAN_STRICT_ANSI_HEADERS)
    using std::perror;
#endif

#define NUM_THREADS 10

XALAN_USING_STD(cerr)
XALAN_USING_STD(cout)
XALAN_USING_STD(endl)
XALAN_USING_STD(ostrstream)

XALAN_USING_XALAN(XalanCompiledStylesheet)
XALAN_USING_XALAN(XalanDOMString)
XALAN_USING_XALAN(XalanParsedSource)
XALAN_USING_XALAN(XalanTransformer)
XALAN_USING_XALAN(XSLTInputSource)
XALAN_USING_XALAN(XSLTResultTarget)

// Used to hold compiled stylesheet and XML source document.
const XalanCompiledStylesheet*  glbCompiledStylesheet = 0;
const XalanParsedSource*        glbParsedSource = 0;
int                             glbError = 0;

// Print messages tracking the progress of each thread, and the
// beginning and end of the entire operation.
void
outputMessage(
            theThreadIDType    id,
            const char         msg[])
{
    ostrstream threadMsg;

    threadMsg << "\n" << msg << " Thread: " << id << '\0';

    cout << threadMsg.str();

    #if defined(HPUX)
    threadMsg.rdbuf() -> freeze(false);
    #else
    threadMsg.freeze(false);
    #endif
}

#if defined(WINDOWS_THREAD_FUNCTIONS)
THREADFUNCTIONRETURN
theThread(LPVOID    param)
#elif defined(XALAN_POSIX2_AVAILABLE)
  void  *theThread(void   *param)
#endif
{
// This routine uses a compiled stylesheet (glbCompiledStylesheet),
// and a binary source tree (glbParsedSource) to perform the
// transformation.

    int theResult = 0;

    const size_t    number = reinterpret_cast<size_t>(param);

#if defined(WINDOWS_THREAD_FUNCTIONS)
    const theThreadIDType         theThreadID = GetCurrentThreadId();

#elif defined(XALAN_POSIX2_AVAILABLE)
    const theThreadIDType         theThreadID = pthread_self();

#endif

    outputMessage(theThreadID, "Starting ");

    // Create a XalanTransformer.
    XalanTransformer    theXalanTransformer;

    // Generate the output file name for this thread.
    ostrstream  theFormatterOut;
    theFormatterOut << "birds" << number << ".out" << '\0';

    // Generate the XML output object.
    const XSLTResultTarget  theResultTarget(XalanDOMString(theFormatterOut.str()));

    // Unfreeze the ostrstream, so memory is returned...
     #if defined(HPUX)
        theFormatterOut.rdbuf() -> freeze(false);
     #else
    theFormatterOut.freeze(false);
     #endif

    outputMessage(theThreadID, "Transforming");

    // Do the transform.
    theResult = theXalanTransformer.transform(*glbParsedSource, glbCompiledStylesheet, theResultTarget);

    if(theResult != 0)
    {
        cerr << "ThreadSafe Error: \n" << theXalanTransformer.getLastError()
             << endl
             << endl;

        glbError = theResult;
    }

    outputMessage(theThreadID, "Finishing");

#if defined(WINDOWS_THREAD_FUNCTION)
    return theResult;
#elif defined(XALAN_POSIX2_AVAILABLE)
    return 0;
#endif
}

// Create and run the threads...
// Print messages tracking the progress of each thread and of the
// overall operation...
void
doThreads(size_t    nThreads)
{
    size_t   i = 0;
    cout << endl << "Clock before starting threads: " << clock() << endl;

    XALAN_USING_STD(vector)

    vector<theThreadType>   hThreads;

    hThreads.reserve(nThreads);

#if defined(WINDOWS_THREAD_FUNCTIONS)

    for (; i < nThreads; ++i)
    {
                theThreadIDType  threadID;

                const theThreadType  hThread = CreateThread(
                0,
                4096,                           // Stack size for thread.
                theThread,                      // pointer to thread function
                reinterpret_cast<LPVOID>(i),    // argument for new thread
                0,                              // creation flags
                &threadID);

        assert(hThread != 0);

        hThreads.push_back(hThread);
    }

    WaitForMultipleObjects(hThreads.size(), &hThreads[0], TRUE, INFINITE);

    for (i = 0; i < nThreads; ++i)
    {
        CloseHandle(hThreads[i]);
    }

#elif defined(XALAN_POSIX2_AVAILABLE)

    int     result;
    void*   thread_result;

    for (; i < nThreads; ++i)
    {
        result = pthread_create(
                          &hThreads[i],    //thread pointer
                          NULL,            //thread's attribute default
                          theThread,       //thread function
                          (void *)&i);     //thread function argument

        if (result != 0)
        {
            perror ("Thread creation failed");
            exit(EXIT_FAILURE);
        }
    }

    cout << endl << "Waiting for threads to finish..." << endl << endl;

    for (i = nThreads; i > 0; --i)
    {
        result = pthread_join(
                           hThreads[i - 1],
                           &thread_result);

        if (result != 0)
        {
            perror ("Thread join failed");
            exit(EXIT_FAILURE);
        }
        //for UNIX debugging
        // cout << "Thread joined, return value: " << (char *)thread_result << endl;
    }
#endif

    cout << endl << endl << "Clock after threads: " << clock() << endl;
}

int
main(
            int     argc,
            char*   /* argv */[])
{
    if (argc != 1)
    {
        cerr << "Usage: ThreadTest"
             << endl
             << endl;
    }
    else
    {
        try
        {
            XALAN_USING_XERCES(XMLPlatformUtils)

            // Call the static initializer for Xerces.
            XMLPlatformUtils::Initialize();

            // Initialize Xalan.
            XalanTransformer::initialize();

            {
                // Create a XalanTransformer.  We won't actually use this to transform --
                // it's just acting likely a factory for the compiled stylesheet and
                // pre-parsed source.
                XalanTransformer    theXalanTransformer;

                glbError = theXalanTransformer.compileStylesheet("birds.xsl", glbCompiledStylesheet);

                if (glbError != 0)
                {
                    cerr << "ThreadSafe Error: \n" << theXalanTransformer.getLastError()
                         << endl
                         << endl;
                }
                else
                {
                    assert(glbCompiledStylesheet != 0);

                    // Compile the XML source document as well. All threads will use
                    // this binary representation of the source tree.
                    glbError = theXalanTransformer.parseSource("birds.xml", glbParsedSource);

                    if (glbError != 0)
                    {
                        cerr << "ThreadSafe Error: \n" << theXalanTransformer.getLastError()
                             << endl
                             << endl;
                    }
                    else
                    {
                        assert(glbParsedSource != 0);

                        // Create and run the threads...
                        // Each thread uses the same document and
                        // stylesheet to perform a transformation.
                                    doThreads(NUM_THREADS);

                    }
                }
            }

            // Terminate Xalan...
            XalanTransformer::terminate();

            // Terminate Xerces...
            XMLPlatformUtils::Terminate();

            // Clean up the ICU, if it's integrated...
            XalanTransformer::ICUCleanUp();
        }
        catch(...)
        {
            cerr << "Initialization failed!" << endl;

            glbError = -1;
        }
    }

    return glbError;
}
<commit_msg>Fixed typo in macro.<commit_after>/*
 * 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.
 */

#include <xalanc/Include/PlatformDefinitions.hpp>

#include <cassert>
#include <ctime>
#include <vector>

#if defined(XALAN_CLASSIC_IOSTREAMS)
#include <fstream.h>
#include <iostream.h>
#include <strstream.h>
#else
#include <fstream>
#include <iostream>
#include <strstream>
#endif

#include <xercesc/util/PlatformUtils.hpp>

#include <xalanc/XalanTransformer/XalanTransformer.hpp>

//This is here for the Windows threads.
#if defined(WINDOWS_THREAD_FUNCTIONS)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winbase.h>
#define THREADFUNCTIONRETURN DWORD WINAPI
typedef   DWORD      theThreadIDType;
typedef   HANDLE     theThreadType;

//This is here for Unix threads
#elif defined(XALAN_POSIX2_AVAILABLE)

// This is a workaround for a Tru64 compiler bug...
#if defined(TRU64)
#if  defined(XALAN_STRICT_ANSI_HEADERS)
#include <csetjmp>
typedef long sigjmp_buf[_JBLEN];
#endif
extern "C" void  *theThread(void   *param);
#endif

#include <pthread.h>
#include <unistd.h>
    typedef   pthread_t     theThreadIDType;
    typedef   pthread_t     theThreadType;

#else
//error Unsupported Platform!
#endif

#if  defined(XALAN_STRICT_ANSI_HEADERS)
    using std::perror;
#endif

#define NUM_THREADS 10

XALAN_USING_STD(cerr)
XALAN_USING_STD(cout)
XALAN_USING_STD(endl)
XALAN_USING_STD(ostrstream)

XALAN_USING_XALAN(XalanCompiledStylesheet)
XALAN_USING_XALAN(XalanDOMString)
XALAN_USING_XALAN(XalanParsedSource)
XALAN_USING_XALAN(XalanTransformer)
XALAN_USING_XALAN(XSLTInputSource)
XALAN_USING_XALAN(XSLTResultTarget)

// Used to hold compiled stylesheet and XML source document.
const XalanCompiledStylesheet*  glbCompiledStylesheet = 0;
const XalanParsedSource*        glbParsedSource = 0;
int                             glbError = 0;

// Print messages tracking the progress of each thread, and the
// beginning and end of the entire operation.
void
outputMessage(
            theThreadIDType    id,
            const char         msg[])
{
    ostrstream threadMsg;

    threadMsg << "\n" << msg << " Thread: " << id << '\0';

    cout << threadMsg.str();

    #if defined(HPUX)
    threadMsg.rdbuf() -> freeze(false);
    #else
    threadMsg.freeze(false);
    #endif
}

#if defined(WINDOWS_THREAD_FUNCTIONS)
THREADFUNCTIONRETURN
theThread(LPVOID    param)
#elif defined(XALAN_POSIX2_AVAILABLE)
  void  *theThread(void   *param)
#endif
{
// This routine uses a compiled stylesheet (glbCompiledStylesheet),
// and a binary source tree (glbParsedSource) to perform the
// transformation.

    int theResult = 0;

    const size_t    number = reinterpret_cast<size_t>(param);

#if defined(WINDOWS_THREAD_FUNCTIONS)
    const theThreadIDType         theThreadID = GetCurrentThreadId();

#elif defined(XALAN_POSIX2_AVAILABLE)
    const theThreadIDType         theThreadID = pthread_self();

#endif

    outputMessage(theThreadID, "Starting ");

    // Create a XalanTransformer.
    XalanTransformer    theXalanTransformer;

    // Generate the output file name for this thread.
    ostrstream  theFormatterOut;
    theFormatterOut << "birds" << number << ".out" << '\0';

    // Generate the XML output object.
    const XSLTResultTarget  theResultTarget(XalanDOMString(theFormatterOut.str()));

    // Unfreeze the ostrstream, so memory is returned...
     #if defined(HPUX)
        theFormatterOut.rdbuf() -> freeze(false);
     #else
    theFormatterOut.freeze(false);
     #endif

    outputMessage(theThreadID, "Transforming");

    // Do the transform.
    theResult = theXalanTransformer.transform(*glbParsedSource, glbCompiledStylesheet, theResultTarget);

    if(theResult != 0)
    {
        cerr << "ThreadSafe Error: \n" << theXalanTransformer.getLastError()
             << endl
             << endl;

        glbError = theResult;
    }

    outputMessage(theThreadID, "Finishing");

#if defined(WINDOWS_THREAD_FUNCTIONS)
    return theResult;
#elif defined(XALAN_POSIX2_AVAILABLE)
    return 0;
#endif
}

// Create and run the threads...
// Print messages tracking the progress of each thread and of the
// overall operation...
void
doThreads(size_t    nThreads)
{
    size_t   i = 0;
    cout << endl << "Clock before starting threads: " << clock() << endl;

    XALAN_USING_STD(vector)

    vector<theThreadType>   hThreads;

    hThreads.reserve(nThreads);

#if defined(WINDOWS_THREAD_FUNCTIONS)

    for (; i < nThreads; ++i)
    {
                theThreadIDType  threadID;

                const theThreadType  hThread = CreateThread(
                0,
                4096,                           // Stack size for thread.
                theThread,                      // pointer to thread function
                reinterpret_cast<LPVOID>(i),    // argument for new thread
                0,                              // creation flags
                &threadID);

        assert(hThread != 0);

        hThreads.push_back(hThread);
    }

    WaitForMultipleObjects(hThreads.size(), &hThreads[0], TRUE, INFINITE);

    for (i = 0; i < nThreads; ++i)
    {
        CloseHandle(hThreads[i]);
    }

#elif defined(XALAN_POSIX2_AVAILABLE)

    int     result;
    void*   thread_result;

    for (; i < nThreads; ++i)
    {
        result = pthread_create(
                          &hThreads[i],    //thread pointer
                          NULL,            //thread's attribute default
                          theThread,       //thread function
                          (void *)&i);     //thread function argument

        if (result != 0)
        {
            perror ("Thread creation failed");
            exit(EXIT_FAILURE);
        }
    }

    cout << endl << "Waiting for threads to finish..." << endl << endl;

    for (i = nThreads; i > 0; --i)
    {
        result = pthread_join(
                           hThreads[i - 1],
                           &thread_result);

        if (result != 0)
        {
            perror ("Thread join failed");
            exit(EXIT_FAILURE);
        }
        //for UNIX debugging
        // cout << "Thread joined, return value: " << (char *)thread_result << endl;
    }
#endif

    cout << endl << endl << "Clock after threads: " << clock() << endl;
}

int
main(
            int     argc,
            char*   /* argv */[])
{
    if (argc != 1)
    {
        cerr << "Usage: ThreadTest"
             << endl
             << endl;
    }
    else
    {
        try
        {
            XALAN_USING_XERCES(XMLPlatformUtils)

            // Call the static initializer for Xerces.
            XMLPlatformUtils::Initialize();

            // Initialize Xalan.
            XalanTransformer::initialize();

            {
                // Create a XalanTransformer.  We won't actually use this to transform --
                // it's just acting likely a factory for the compiled stylesheet and
                // pre-parsed source.
                XalanTransformer    theXalanTransformer;

                glbError = theXalanTransformer.compileStylesheet("birds.xsl", glbCompiledStylesheet);

                if (glbError != 0)
                {
                    cerr << "ThreadSafe Error: \n" << theXalanTransformer.getLastError()
                         << endl
                         << endl;
                }
                else
                {
                    assert(glbCompiledStylesheet != 0);

                    // Compile the XML source document as well. All threads will use
                    // this binary representation of the source tree.
                    glbError = theXalanTransformer.parseSource("birds.xml", glbParsedSource);

                    if (glbError != 0)
                    {
                        cerr << "ThreadSafe Error: \n" << theXalanTransformer.getLastError()
                             << endl
                             << endl;
                    }
                    else
                    {
                        assert(glbParsedSource != 0);

                        // Create and run the threads...
                        // Each thread uses the same document and
                        // stylesheet to perform a transformation.
                                    doThreads(NUM_THREADS);

                    }
                }
            }

            // Terminate Xalan...
            XalanTransformer::terminate();

            // Terminate Xerces...
            XMLPlatformUtils::Terminate();

            // Clean up the ICU, if it's integrated...
            XalanTransformer::ICUCleanUp();
        }
        catch(...)
        {
            cerr << "Initialization failed!" << endl;

            glbError = -1;
        }
    }

    return glbError;
}
<|endoftext|>


<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/eval/eval/function.h>
#include <vespa/eval/eval/llvm/compiled_function.h>
#include <vespa/vespalib/util/benchmark_timer.h>
#include <vespa/eval/eval/interpreted_function.h>
#include <vespa/vespalib/util/benchmark_timer.h>
#include <vespa/eval/tensor/default_tensor_engine.h>

using namespace vespalib::eval;
using vespalib::BenchmarkTimer;
using vespalib::tensor::DefaultTensorEngine;

double budget = 0.25;

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

const char *function_str = "(0.35*p + 0.15*o + 0.30*q + 0.20*f) * w";

double gcc_function(double p, double o, double q, double f, double w) {
    return (0.35*p + 0.15*o + 0.30*q + 0.20*f) * w;
}

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

const char *big_function_str = "(0.35*p + 0.15*o + 0.30*q + 0.20*f) * w + "
    "(0.35*p + 0.15*o + 0.30*q + 0.20*f) * w + "
    "(0.35*p + 0.15*o + 0.30*q + 0.20*f) * w + "
    "(0.35*p + 0.15*o + 0.30*q + 0.20*f) * w";

double big_gcc_function(double p, double o, double q, double f, double w) {
    return (0.35*p + 0.15*o + 0.30*q + 0.20*f) * w +
        (0.35*p + 0.15*o + 0.30*q + 0.20*f) * w +
        (0.35*p + 0.15*o + 0.30*q + 0.20*f) * w +
        (0.35*p + 0.15*o + 0.30*q + 0.20*f) * w;
}

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

struct Fixture {
    Function function;
    InterpretedFunction interpreted;
    InterpretedFunction interpreted_simple;
    CompiledFunction separate;
    CompiledFunction array;
    CompiledFunction lazy;
    Fixture(const vespalib::string &expr)
        : function(Function::parse(expr)),
          interpreted(DefaultTensorEngine::ref(), function, NodeTypes()),
          interpreted_simple(SimpleTensorEngine::ref(), function, NodeTypes()),
          separate(function, PassParams::SEPARATE),
          array(function, PassParams::ARRAY),
          lazy(function, PassParams::LAZY) {}
};

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

Fixture small(function_str);
Fixture big(big_function_str);
std::vector<double> test_params = {1.0, 2.0, 3.0, 4.0, 5.0};

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

double empty_function_5(double, double, double, double, double) { return 0.0; }
double estimate_cost_us(const std::vector<double> &params, CompiledFunction::expand<5>::type function) {
    CompiledFunction::expand<5>::type empty = empty_function_5;
    auto actual = [&](){function(params[0], params[1], params[2], params[3], params[4]);};
    auto baseline = [&](){empty(params[0], params[1], params[2], params[3], params[4]);};
    return BenchmarkTimer::benchmark(actual, baseline, budget) * 1000.0 * 1000.0;
}

TEST("measure small function eval/jit/gcc speed") {
    Fixture &fixture = small;
    CompiledFunction::expand<5>::type fun = gcc_function;

    EXPECT_EQUAL(fixture.separate.get_function<5>()(1,2,3,4,5), fun(1,2,3,4,5));
    EXPECT_EQUAL(fixture.separate.get_function<5>()(5,4,3,2,1), fun(5,4,3,2,1));

    double interpret_time = fixture.interpreted.estimate_cost_us(test_params, budget);
    fprintf(stderr, "interpret: %g us\n", interpret_time);
    double interpret_simple_time = fixture.interpreted_simple.estimate_cost_us(test_params, budget);
    fprintf(stderr, "interpret (simple): %g us\n", interpret_simple_time);
    double jit_time = estimate_cost_us(test_params, fixture.separate.get_function<5>());
    fprintf(stderr, "jit compiled: %g us\n", jit_time);
    double gcc_time = estimate_cost_us(test_params, fun);
    fprintf(stderr, "gcc compiled: %g us\n", gcc_time);
    double simple_vs_default_speed = (1.0/interpret_simple_time)/(1.0/interpret_time);
    double jit_vs_interpret_speed = (1.0/jit_time)/(1.0/interpret_time);
    double gcc_vs_jit_speed = (1.0/gcc_time)/(1.0/jit_time);
    fprintf(stderr, "simple vs default interpret speed: %g\n", simple_vs_default_speed);
    fprintf(stderr, "jit speed compared to interpret: %g\n", jit_vs_interpret_speed);
    fprintf(stderr, "gcc speed compared to jit: %g\n", gcc_vs_jit_speed);

    double jit_time_separate = fixture.separate.estimate_cost_us(test_params, budget);
    fprintf(stderr, "jit compiled: %g (separate) us\n", jit_time_separate);
    double jit_time_array = fixture.array.estimate_cost_us(test_params, budget);
    fprintf(stderr, "jit compiled: %g (array) us\n", jit_time_array);
    double jit_time_lazy = fixture.lazy.estimate_cost_us(test_params, budget);
    fprintf(stderr, "jit compiled: %g (lazy) us\n", jit_time_lazy);
    double separate_vs_array_speed = (1.0/jit_time_separate)/(1.0/jit_time_array);
    double array_vs_lazy_speed = (1.0/jit_time_array)/(1.0/jit_time_lazy);
    fprintf(stderr, "seperate params speed compared to array params: %g\n", separate_vs_array_speed);
    fprintf(stderr, "array params speed compared to lazy params: %g\n", array_vs_lazy_speed);
}

TEST("measure big function eval/jit/gcc speed") {
    Fixture &fixture = big;
    CompiledFunction::expand<5>::type fun = big_gcc_function;

    EXPECT_EQUAL(fixture.separate.get_function<5>()(1,2,3,4,5), fun(1,2,3,4,5));
    EXPECT_EQUAL(fixture.separate.get_function<5>()(5,4,3,2,1), fun(5,4,3,2,1));

    double interpret_time = fixture.interpreted.estimate_cost_us(test_params, budget);
    fprintf(stderr, "interpret: %g us\n", interpret_time);
    double interpret_simple_time = fixture.interpreted_simple.estimate_cost_us(test_params, budget);
    fprintf(stderr, "interpret (simple): %g us\n", interpret_time);
    double jit_time = estimate_cost_us(test_params, fixture.separate.get_function<5>());
    fprintf(stderr, "jit compiled: %g us\n", jit_time);
    double gcc_time = estimate_cost_us(test_params, fun);
    fprintf(stderr, "gcc compiled: %g us\n", gcc_time);
    double simple_vs_default_speed = (1.0/interpret_simple_time)/(1.0/interpret_time);
    double jit_vs_interpret_speed = (1.0/jit_time)/(1.0/interpret_time);
    double gcc_vs_jit_speed = (1.0/gcc_time)/(1.0/jit_time);
    fprintf(stderr, "simple vs default interpret speed: %g\n", simple_vs_default_speed);
    fprintf(stderr, "jit speed compared to interpret: %g\n", jit_vs_interpret_speed);
    fprintf(stderr, "gcc speed compared to jit: %g\n", gcc_vs_jit_speed);

    double jit_time_separate = fixture.separate.estimate_cost_us(test_params, budget);
    fprintf(stderr, "jit compiled: %g (separate) us\n", jit_time_separate);
    double jit_time_array = fixture.array.estimate_cost_us(test_params, budget);
    fprintf(stderr, "jit compiled: %g (array) us\n", jit_time_array);
    double jit_time_lazy = fixture.lazy.estimate_cost_us(test_params, budget);
    fprintf(stderr, "jit compiled: %g (lazy) us\n", jit_time_lazy);
    double separate_vs_array_speed = (1.0/jit_time_separate)/(1.0/jit_time_array);
    double array_vs_lazy_speed = (1.0/jit_time_array)/(1.0/jit_time_lazy);
    fprintf(stderr, "seperate params speed compared to array params: %g\n", separate_vs_array_speed);
    fprintf(stderr, "array params speed compared to lazy params: %g\n", array_vs_lazy_speed);
}

TEST_MAIN() { TEST_RUN_ALL(); }
<commit_msg>test interpret speed for untyped simple and typed default<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/vespalib/testkit/test_kit.h>
#include <vespa/eval/eval/function.h>
#include <vespa/eval/eval/llvm/compiled_function.h>
#include <vespa/vespalib/util/benchmark_timer.h>
#include <vespa/eval/eval/interpreted_function.h>
#include <vespa/vespalib/util/benchmark_timer.h>
#include <vespa/eval/tensor/default_tensor_engine.h>

using namespace vespalib::eval;
using vespalib::BenchmarkTimer;
using vespalib::tensor::DefaultTensorEngine;

double budget = 0.25;

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

const char *function_str = "(0.35*p + 0.15*o + 0.30*q + 0.20*f) * w";

double gcc_function(double p, double o, double q, double f, double w) {
    return (0.35*p + 0.15*o + 0.30*q + 0.20*f) * w;
}

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

const char *big_function_str = "(0.35*p + 0.15*o + 0.30*q + 0.20*f) * w + "
    "(0.35*p + 0.15*o + 0.30*q + 0.20*f) * w + "
    "(0.35*p + 0.15*o + 0.30*q + 0.20*f) * w + "
    "(0.35*p + 0.15*o + 0.30*q + 0.20*f) * w";

double big_gcc_function(double p, double o, double q, double f, double w) {
    return (0.35*p + 0.15*o + 0.30*q + 0.20*f) * w +
        (0.35*p + 0.15*o + 0.30*q + 0.20*f) * w +
        (0.35*p + 0.15*o + 0.30*q + 0.20*f) * w +
        (0.35*p + 0.15*o + 0.30*q + 0.20*f) * w;
}

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

struct Fixture {
    Function function;
    InterpretedFunction interpreted_simple;
    InterpretedFunction interpreted;
    CompiledFunction separate;
    CompiledFunction array;
    CompiledFunction lazy;
    Fixture(const vespalib::string &expr)
        : function(Function::parse(expr)),
          interpreted_simple(SimpleTensorEngine::ref(), function, NodeTypes()),
          interpreted(DefaultTensorEngine::ref(), function,
                      NodeTypes(function, std::vector<ValueType>(function.num_params(), ValueType::double_type()))),
          separate(function, PassParams::SEPARATE),
          array(function, PassParams::ARRAY),
          lazy(function, PassParams::LAZY) {}
};

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

Fixture small(function_str);
Fixture big(big_function_str);
std::vector<double> test_params = {1.0, 2.0, 3.0, 4.0, 5.0};

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

double empty_function_5(double, double, double, double, double) { return 0.0; }
double estimate_cost_us(const std::vector<double> &params, CompiledFunction::expand<5>::type function) {
    CompiledFunction::expand<5>::type empty = empty_function_5;
    auto actual = [&](){function(params[0], params[1], params[2], params[3], params[4]);};
    auto baseline = [&](){empty(params[0], params[1], params[2], params[3], params[4]);};
    return BenchmarkTimer::benchmark(actual, baseline, budget) * 1000.0 * 1000.0;
}

TEST("measure small function eval/jit/gcc speed") {
    Fixture &fixture = small;
    CompiledFunction::expand<5>::type fun = gcc_function;

    EXPECT_EQUAL(fixture.separate.get_function<5>()(1,2,3,4,5), fun(1,2,3,4,5));
    EXPECT_EQUAL(fixture.separate.get_function<5>()(5,4,3,2,1), fun(5,4,3,2,1));

    double interpret_simple_time = fixture.interpreted_simple.estimate_cost_us(test_params, budget);
    fprintf(stderr, "interpret (simple): %g us\n", interpret_simple_time);
    double interpret_time = fixture.interpreted.estimate_cost_us(test_params, budget);
    fprintf(stderr, "interpret: %g us\n", interpret_time);
    double jit_time = estimate_cost_us(test_params, fixture.separate.get_function<5>());
    fprintf(stderr, "jit compiled: %g us\n", jit_time);
    double gcc_time = estimate_cost_us(test_params, fun);
    fprintf(stderr, "gcc compiled: %g us\n", gcc_time);
    double default_vs_simple_speed = (1.0/interpret_time)/(1.0/interpret_simple_time);
    double jit_vs_interpret_speed = (1.0/jit_time)/(1.0/interpret_time);
    double gcc_vs_jit_speed = (1.0/gcc_time)/(1.0/jit_time);
    fprintf(stderr, "default typed vs simple untyped interpret speed: %g\n", default_vs_simple_speed);
    fprintf(stderr, "jit speed compared to interpret: %g\n", jit_vs_interpret_speed);
    fprintf(stderr, "gcc speed compared to jit: %g\n", gcc_vs_jit_speed);

    double jit_time_separate = fixture.separate.estimate_cost_us(test_params, budget);
    fprintf(stderr, "jit compiled: %g (separate) us\n", jit_time_separate);
    double jit_time_array = fixture.array.estimate_cost_us(test_params, budget);
    fprintf(stderr, "jit compiled: %g (array) us\n", jit_time_array);
    double jit_time_lazy = fixture.lazy.estimate_cost_us(test_params, budget);
    fprintf(stderr, "jit compiled: %g (lazy) us\n", jit_time_lazy);
    double separate_vs_array_speed = (1.0/jit_time_separate)/(1.0/jit_time_array);
    double array_vs_lazy_speed = (1.0/jit_time_array)/(1.0/jit_time_lazy);
    fprintf(stderr, "seperate params speed compared to array params: %g\n", separate_vs_array_speed);
    fprintf(stderr, "array params speed compared to lazy params: %g\n", array_vs_lazy_speed);
}

TEST("measure big function eval/jit/gcc speed") {
    Fixture &fixture = big;
    CompiledFunction::expand<5>::type fun = big_gcc_function;

    EXPECT_EQUAL(fixture.separate.get_function<5>()(1,2,3,4,5), fun(1,2,3,4,5));
    EXPECT_EQUAL(fixture.separate.get_function<5>()(5,4,3,2,1), fun(5,4,3,2,1));

    double interpret_simple_time = fixture.interpreted_simple.estimate_cost_us(test_params, budget);
    fprintf(stderr, "interpret (simple): %g us\n", interpret_simple_time);
    double interpret_time = fixture.interpreted.estimate_cost_us(test_params, budget);
    fprintf(stderr, "interpret: %g us\n", interpret_time);
    double jit_time = estimate_cost_us(test_params, fixture.separate.get_function<5>());
    fprintf(stderr, "jit compiled: %g us\n", jit_time);
    double gcc_time = estimate_cost_us(test_params, fun);
    fprintf(stderr, "gcc compiled: %g us\n", gcc_time);
    double default_vs_simple_speed = (1.0/interpret_time)/(1.0/interpret_simple_time);
    double jit_vs_interpret_speed = (1.0/jit_time)/(1.0/interpret_time);
    double gcc_vs_jit_speed = (1.0/gcc_time)/(1.0/jit_time);
    fprintf(stderr, "default typed vs simple untyped interpret speed: %g\n", default_vs_simple_speed);
    fprintf(stderr, "jit speed compared to interpret: %g\n", jit_vs_interpret_speed);
    fprintf(stderr, "gcc speed compared to jit: %g\n", gcc_vs_jit_speed);

    double jit_time_separate = fixture.separate.estimate_cost_us(test_params, budget);
    fprintf(stderr, "jit compiled: %g (separate) us\n", jit_time_separate);
    double jit_time_array = fixture.array.estimate_cost_us(test_params, budget);
    fprintf(stderr, "jit compiled: %g (array) us\n", jit_time_array);
    double jit_time_lazy = fixture.lazy.estimate_cost_us(test_params, budget);
    fprintf(stderr, "jit compiled: %g (lazy) us\n", jit_time_lazy);
    double separate_vs_array_speed = (1.0/jit_time_separate)/(1.0/jit_time_array);
    double array_vs_lazy_speed = (1.0/jit_time_array)/(1.0/jit_time_lazy);
    fprintf(stderr, "seperate params speed compared to array params: %g\n", separate_vs_array_speed);
    fprintf(stderr, "array params speed compared to lazy params: %g\n", array_vs_lazy_speed);
}

TEST_MAIN() { TEST_RUN_ALL(); }
<|endoftext|>


<commit_before>// This file is part of the "libxzero" project
//   (c) 2009-2015 Christian Parpart <https://github.com/christianparpart>
//
// libxzero is free software: you can redistribute it and/or modify it under
// the terms of the GNU Affero General Public License v3.0.
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

#include <xzero/http/client/Http1Connection.h>
#include <xzero/http/HttpRequestInfo.h>
#include <xzero/http/HttpRequestInfo.h>
#include <xzero/net/EndPoint.h>
#include <xzero/logging.h>
#include <xzero/Buffer.h>

namespace xzero {
namespace http {
namespace client {

#ifndef NDEBUG
#define TRACE(msg...) logTrace("http.client.Http1Connection", msg)
#else
#define TRACE(msg...) do {} while (0)
#endif

Http1Connection::Http1Connection(HttpListener* channel,
                                 EndPoint* endpoint,
                                 Executor* executor)
    : Connection(endpoint, executor),
      channel_(channel),
      onComplete_(),
      writer_(),
      generator_(&writer_),
      parser_(http1::Parser::RESPONSE, this),
      inputBuffer_(),
      inputOffset_(0),
      expectsBody_(true),
      responseComplete_(false),
      keepAliveCount_(0) {
}

Http1Connection::~Http1Connection() {
}

void Http1Connection::send(HttpRequestInfo&& requestInfo,
                           CompletionHandler onComplete) {
  setCompleter(onComplete);
  expectsBody_ = requestInfo.method() != "HEAD";
  generator_.generateRequest(requestInfo);
  wantFlush();
}

void Http1Connection::send(HttpRequestInfo&& requestInfo,
                           const BufferRef& chunk,
                           CompletionHandler onComplete) {
  setCompleter(onComplete);
  expectsBody_ = requestInfo.method() != "HEAD";
  generator_.generateRequest(requestInfo, chunk);
  wantFlush();
}

void Http1Connection::send(HttpRequestInfo&& requestInfo,
                           Buffer&& chunk,
                           CompletionHandler onComplete) {
  setCompleter(onComplete);
  expectsBody_ = requestInfo.method() != "HEAD";
  generator_.generateRequest(requestInfo, chunk);
  wantFlush();
}

void Http1Connection::send(HttpRequestInfo&& requestInfo,
                           FileRef&& chunk,
                           CompletionHandler onComplete) {
  setCompleter(onComplete);
  expectsBody_ = requestInfo.method() != "HEAD";
  generator_.generateRequest(requestInfo, std::move(chunk));
  wantFlush();
}

void Http1Connection::send(const BufferRef& chunk, CompletionHandler onComplete) {
  setCompleter(onComplete);
  generator_.generateBody(std::move(chunk));
  wantFlush();
}

void Http1Connection::send(Buffer&& chunk, CompletionHandler onComplete) {
  setCompleter(onComplete);
  generator_.generateBody(std::move(chunk));
  wantFlush();
}

void Http1Connection::send(FileRef&& chunk, CompletionHandler onComplete) {
  setCompleter(onComplete_);
  generator_.generateBody(std::move(chunk));
  wantFlush();
}

void Http1Connection::completed() {
  setCompleter(std::bind(&Http1Connection::onRequestComplete, this,
                         std::placeholders::_1));

  if (!generator_.isChunked() && generator_.pendingContentLength() > 0)
    RAISE(IllegalStateError, "Invalid State. Request not fully written but completed() invoked.");

  //generator_.generateTrailer(channel_->requestInfo()->trailers());
  wantFlush();
}

void Http1Connection::onRequestComplete(bool success) {
  TRACE("onRequestComplete($0)", success ? "success" : "failed");
  if (success)
    wantFill();
}

void Http1Connection::onResponseComplete(bool success) {
  // channel_->responseEnd();

  if (!keepAliveCount_) {
    close();
  }
}

void Http1Connection::abort() {
  close();
}

void Http1Connection::setInputBufferSize(size_t size) {
  inputBuffer_.reserve(size);
}

void Http1Connection::onFillable() {
  TRACE("onFillable()");

  size_t n = endpoint()->fill(&inputBuffer_);

  if (n == 0) {
    abort();
    return;
  }

  parseFragment();

  if (!responseComplete_) {
    wantFill();
  }
}

void Http1Connection::parseFragment() {
  size_t n = parser_.parseFragment(inputBuffer_.ref(inputOffset_));
  inputOffset_ += n;
}

void Http1Connection::onFlushable() {
  TRACE("onFlushable()");
  const bool complete = writer_.flush(endpoint());
  TRACE("onFlushable: $0", complete ? "completed" : "needs-more-to-flush");

  if (complete) {
    wantFill();
  } else {
    wantFlush();
  }
}

void Http1Connection::onInterestFailure(const std::exception& error) {
  logError("http.client.Http1Connection", error, "Unhandled exception caught in I/O loop");

  notifyFailure(); // notify the callback that we failed doing something wrt. I/O.
  abort();
}

void Http1Connection::setCompleter(CompletionHandler onComplete) {
  if (onComplete && onComplete_)
    RAISE(IllegalStateError, "There is still another completion hook.");

  onComplete_ = std::move(onComplete);
}

void Http1Connection::invokeCompleter(bool success) {
  if (onComplete_) {
    auto cb = std::move(onComplete_);
    onComplete_ = nullptr;
    cb(success);
  }
}

// {{{ HttpListener overrides
void Http1Connection::onMessageBegin(HttpVersion version,
                                     HttpStatus code,
                                     const BufferRef& text) {
  switch (code) {
    case /*100*/ HttpStatus::ContinueRequest:
    case /*101*/ HttpStatus::SwitchingProtocols:
    case /*204*/ HttpStatus::NoContent:
    case /*205*/ HttpStatus::ResetContent:
    case /*304*/ HttpStatus::NotModified:
      expectsBody_ = false;
      break;
    default:
      break;
  }
  channel_->onMessageBegin(version, code, text);
}

void Http1Connection::onMessageHeader(const BufferRef& name,
                                      const BufferRef& value) {
  channel_->onMessageHeader(name, value);
}

void Http1Connection::onMessageHeaderEnd() {
  TRACE("onMessageHeaderEnd! expectsBody=$0", expectsBody_);
  channel_->onMessageHeaderEnd();
  if (expectsBody_ == false) {
    onMessageEnd();
  }
}

void Http1Connection::onMessageContent(const BufferRef& chunk) {
  channel_->onMessageContent(chunk);
}

void Http1Connection::onMessageEnd() {
  TRACE("onMessageEnd!");
  responseComplete_ = true;
  channel_->onMessageEnd();
}

void Http1Connection::onProtocolError(HttpStatus code,
                                      const std::string& message) {
  channel_->onProtocolError(code, message);
}
// }}}

} // namespace client
} // namespace http
} // namespace xzero
<commit_msg>fixes HEAD proxying<commit_after>// This file is part of the "libxzero" project
//   (c) 2009-2015 Christian Parpart <https://github.com/christianparpart>
//
// libxzero is free software: you can redistribute it and/or modify it under
// the terms of the GNU Affero General Public License v3.0.
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

#include <xzero/http/client/Http1Connection.h>
#include <xzero/http/HttpRequestInfo.h>
#include <xzero/http/HttpRequestInfo.h>
#include <xzero/net/EndPoint.h>
#include <xzero/logging.h>
#include <xzero/Buffer.h>

namespace xzero {
namespace http {
namespace client {

#ifndef NDEBUG
#define TRACE(msg...) logTrace("http.client.Http1Connection", msg)
#else
#define TRACE(msg...) do {} while (0)
#endif

Http1Connection::Http1Connection(HttpListener* channel,
                                 EndPoint* endpoint,
                                 Executor* executor)
    : Connection(endpoint, executor),
      channel_(channel),
      onComplete_(),
      writer_(),
      generator_(&writer_),
      parser_(http1::Parser::RESPONSE, this),
      inputBuffer_(),
      inputOffset_(0),
      expectsBody_(true),
      responseComplete_(false),
      keepAliveCount_(0) {
}

Http1Connection::~Http1Connection() {
}

void Http1Connection::send(HttpRequestInfo&& requestInfo,
                           CompletionHandler onComplete) {
  setCompleter(onComplete);
  expectsBody_ = requestInfo.method() != "HEAD";
  generator_.generateRequest(requestInfo);
  wantFlush();
}

void Http1Connection::send(HttpRequestInfo&& requestInfo,
                           const BufferRef& chunk,
                           CompletionHandler onComplete) {
  setCompleter(onComplete);
  expectsBody_ = requestInfo.method() != "HEAD";
  generator_.generateRequest(requestInfo, chunk);
  wantFlush();
}

void Http1Connection::send(HttpRequestInfo&& requestInfo,
                           Buffer&& chunk,
                           CompletionHandler onComplete) {
  setCompleter(onComplete);
  expectsBody_ = requestInfo.method() != "HEAD";
  generator_.generateRequest(requestInfo, chunk);
  wantFlush();
}

void Http1Connection::send(HttpRequestInfo&& requestInfo,
                           FileRef&& chunk,
                           CompletionHandler onComplete) {
  setCompleter(onComplete);
  expectsBody_ = requestInfo.method() != "HEAD";
  generator_.generateRequest(requestInfo, std::move(chunk));
  wantFlush();
}

void Http1Connection::send(const BufferRef& chunk, CompletionHandler onComplete) {
  setCompleter(onComplete);
  generator_.generateBody(std::move(chunk));
  wantFlush();
}

void Http1Connection::send(Buffer&& chunk, CompletionHandler onComplete) {
  setCompleter(onComplete);
  generator_.generateBody(std::move(chunk));
  wantFlush();
}

void Http1Connection::send(FileRef&& chunk, CompletionHandler onComplete) {
  setCompleter(onComplete_);
  generator_.generateBody(std::move(chunk));
  wantFlush();
}

void Http1Connection::completed() {
  setCompleter(std::bind(&Http1Connection::onRequestComplete, this,
                         std::placeholders::_1));

  if (!generator_.isChunked() && generator_.pendingContentLength() > 0)
    RAISE(IllegalStateError, "Invalid State. Request not fully written but completed() invoked.");

  //generator_.generateTrailer(channel_->requestInfo()->trailers());
  wantFlush();
}

void Http1Connection::onRequestComplete(bool success) {
  TRACE("onRequestComplete($0)", success ? "success" : "failed");
  if (success)
    wantFill();
}

void Http1Connection::onResponseComplete(bool success) {
  // channel_->responseEnd();

  if (!keepAliveCount_) {
    close();
  }
}

void Http1Connection::abort() {
  close();
}

void Http1Connection::setInputBufferSize(size_t size) {
  inputBuffer_.reserve(size);
}

void Http1Connection::onFillable() {
  TRACE("onFillable()");

  size_t n = endpoint()->fill(&inputBuffer_);

  if (n == 0) {
    abort();
    return;
  }

  parseFragment();

  if (!responseComplete_) {
    wantFill();
  }
}

void Http1Connection::parseFragment() {
  size_t n = parser_.parseFragment(inputBuffer_.ref(inputOffset_));
  inputOffset_ += n;
}

void Http1Connection::onFlushable() {
  TRACE("onFlushable()");
  const bool complete = writer_.flush(endpoint());
  TRACE("onFlushable: $0", complete ? "completed" : "needs-more-to-flush");

  if (complete) {
    wantFill();
  } else {
    wantFlush();
  }
}

void Http1Connection::onInterestFailure(const std::exception& error) {
  logError("http.client.Http1Connection", error, "Unhandled exception caught in I/O loop");

  notifyFailure(); // notify the callback that we failed doing something wrt. I/O.
  abort();
}

void Http1Connection::setCompleter(CompletionHandler onComplete) {
  if (onComplete && onComplete_)
    RAISE(IllegalStateError, "There is still another completion hook.");

  onComplete_ = std::move(onComplete);
}

void Http1Connection::invokeCompleter(bool success) {
  if (onComplete_) {
    auto cb = std::move(onComplete_);
    onComplete_ = nullptr;
    cb(success);
  }
}

// {{{ HttpListener overrides
void Http1Connection::onMessageBegin(HttpVersion version,
                                     HttpStatus code,
                                     const BufferRef& text) {
  switch (code) {
    case /*100*/ HttpStatus::ContinueRequest:
    case /*101*/ HttpStatus::SwitchingProtocols:
    case /*204*/ HttpStatus::NoContent:
    case /*205*/ HttpStatus::ResetContent:
    case /*304*/ HttpStatus::NotModified:
      expectsBody_ = false;
      break;
    default:
      break;
  }
  channel_->onMessageBegin(version, code, text);
}

void Http1Connection::onMessageHeader(const BufferRef& name,
                                      const BufferRef& value) {
  channel_->onMessageHeader(name, value);
}

void Http1Connection::onMessageHeaderEnd() {
  TRACE("onMessageHeaderEnd! expectsBody=$0", expectsBody_);
  channel_->onMessageHeaderEnd();
  if (parser_.isContentExpected() && !expectsBody_) {
    onMessageEnd();
  }
}

void Http1Connection::onMessageContent(const BufferRef& chunk) {
  channel_->onMessageContent(chunk);
}

void Http1Connection::onMessageEnd() {
  TRACE("onMessageEnd!");
  responseComplete_ = true;
  channel_->onMessageEnd();
}

void Http1Connection::onProtocolError(HttpStatus code,
                                      const std::string& message) {
  channel_->onProtocolError(code, message);
}
// }}}

} // namespace client
} // namespace http
} // namespace xzero
<|endoftext|>


<commit_before>#include "clientGeoJsonSource.h"
#include "mapbox/geojsonvt/geojsonvt_convert.hpp"
#include "mapbox/geojsonvt/geojsonvt_types.hpp"
#include "platform.h"
#include "util/geom.h"

using namespace mapbox::util;

namespace Tangram {

const double extent = 4096;
const uint8_t maxZoom = 18;
const uint8_t indexMaxZoom = 18;
const uint32_t indexMaxPoints = 100000;
double tolerance = 0.01;

Point ClientGeoJsonSource::transformPoint(geojsonvt::TilePoint pt) const {
    return { 2 * pt.x / extent - 1, 1 - 2 * pt.y / extent, 0 };
}

ClientGeoJsonSource::ClientGeoJsonSource(const std::string& _name, const std::string& _url)
    : DataSource(_name, _url) {

    if (!_url.empty()) {
        // Load from file
        const auto& string = stringFromResource(_url.c_str());
        addData(string);
    }
}

void ClientGeoJsonSource::addData(const std::string& _data) {

    m_features = geojsonvt::GeoJSONVT::convertFeatures(_data);
    m_store = std::make_unique<GeoJSONVT>(m_features, maxZoom, indexMaxZoom, indexMaxPoints, tolerance);

}

bool ClientGeoJsonSource::loadTileData(std::shared_ptr<TileTask>&& _task, TileTaskCb _cb) {

    _cb(std::move(_task));

    return true;
}

bool ClientGeoJsonSource::getTileData(std::shared_ptr<TileTask>& _task) {

    return true;
}

void ClientGeoJsonSource::clearData() {

    m_features.clear();
    m_store.reset();

}

void ClientGeoJsonSource::addPoint(double* _coords) {

    auto container = geojsonvt::Convert::project({ geojsonvt::LonLat(_coords[0], _coords[1]) }, tolerance);

    auto feature = geojsonvt::Convert::create(geojsonvt::Tags(),
                                              geojsonvt::ProjectedFeatureType::Point,
                                              container.members);

    m_features.push_back(std::move(feature));
    m_store = std::make_unique<GeoJSONVT>(m_features, maxZoom, indexMaxZoom, indexMaxPoints, tolerance);

}

void ClientGeoJsonSource::addLine(double* _coords, int _lineLength) {

    std::vector<geojsonvt::LonLat> line(_lineLength, { 0, 0 });
    for (int i = 0; i < _lineLength; i++) {
        line[i] = { _coords[2 * i], _coords[2 * i + 1] };
    }

    std::vector<geojsonvt::ProjectedGeometry> geometry = { geojsonvt::Convert::project(line, tolerance) };

    auto feature = geojsonvt::Convert::create(geojsonvt::Tags(),
                                              geojsonvt::ProjectedFeatureType::LineString,
                                              geometry);

    m_features.push_back(std::move(feature));
    m_store = std::make_unique<GeoJSONVT>(m_features, maxZoom, indexMaxZoom, indexMaxPoints, tolerance);
}

void ClientGeoJsonSource::addPoly(double* _coords, int* _ringLengths, int _rings) {

    geojsonvt::ProjectedGeometryContainer geometry;
    double* ringCoords = _coords;
    for (int i = 0; i < _rings; i++) {
        int ringLength = _ringLengths[i];
        std::vector<geojsonvt::LonLat> ring(ringLength, { 0, 0 });
        for (int j = 0; j < ringLength; j++) {
            ring[j] = { ringCoords[2 * j], ringCoords[2 * j + 1] };
        }
        geometry.members.push_back(geojsonvt::Convert::project(ring, tolerance));
        ringCoords += 2 * ringLength;
    }

    auto feature = geojsonvt::Convert::create(geojsonvt::Tags(),
                                              geojsonvt::ProjectedFeatureType::Polygon,
                                              geometry);

    m_features.push_back(std::move(feature));
    m_store = std::make_unique<GeoJSONVT>(m_features, maxZoom, indexMaxZoom, indexMaxPoints, tolerance);
}

std::shared_ptr<TileData> ClientGeoJsonSource::parse(const Tile& _tile, std::vector<char>& _rawData) const {

    if (!m_store) { return nullptr; }

    auto data = std::make_shared<TileData>();

    auto id = _tile.getID();

    auto tile = m_store->getTile(id.z, id.x, id.y); // uses a mutex lock internally for thread-safety

    Layer layer(""); // empty name will skip filtering by 'collection'

    for (auto& it : tile.features) {

        Feature feat;

        const auto& geom = it.tileGeometry;
        const auto type = it.type;

        switch (type) {
            case geojsonvt::TileFeatureType::Point: {
                feat.geometryType = GeometryType::points;
                for (const auto& pt : geom) {
                    const auto& point = pt.get<geojsonvt::TilePoint>();
                    feat.points.push_back(transformPoint(point));
                }
                break;
            }
            case geojsonvt::TileFeatureType::LineString: {
                feat.geometryType = GeometryType::lines;
                for (const auto& r : geom) {
                    Line line;
                    for (const auto& pt : r.get<geojsonvt::TileRing>().points) {
                        line.push_back(transformPoint(pt));
                    }
                    feat.lines.emplace_back(std::move(line));
                }
                break;
            }
            case geojsonvt::TileFeatureType::Polygon: {
                feat.geometryType = GeometryType::polygons;
                for (const auto& r : geom) {
                    Line line;
                    for (const auto& pt : r.get<geojsonvt::TileRing>().points) {
                        line.push_back(transformPoint(pt));
                    }
                    // Polygons are in a flat list of rings, with ccw rings indicating
                    // the beginning of a new polygon
                    if (signedArea(line) >= 0 || feat.polygons.empty()) {
                        feat.polygons.emplace_back();
                    }
                    feat.polygons.back().push_back(std::move(line));
                }
                break;
            }
            default: break;
        }

        std::vector<Properties::Item> items;
        items.reserve(it.tags.size());

        for (auto& tag : it.tags) {
            items.emplace_back(tag.first, tag.second);
        }

        feat.props = Properties(std::move(items));

        layer.features.emplace_back(std::move(feat));

    }

    data->layers.emplace_back(std::move(layer));

    return data;

}

}
<commit_msg>Fix tolerance value for geojson-vt-cpp<commit_after>#include "clientGeoJsonSource.h"
#include "mapbox/geojsonvt/geojsonvt_convert.hpp"
#include "mapbox/geojsonvt/geojsonvt_types.hpp"
#include "platform.h"
#include "util/geom.h"

using namespace mapbox::util;

namespace Tangram {

const double extent = 4096;
const uint8_t maxZoom = 18;
const uint8_t indexMaxZoom = 18;
const uint32_t indexMaxPoints = 100000;
double tolerance = 1E-8;

Point ClientGeoJsonSource::transformPoint(geojsonvt::TilePoint pt) const {
    return { 2 * pt.x / extent - 1, 1 - 2 * pt.y / extent, 0 };
}

ClientGeoJsonSource::ClientGeoJsonSource(const std::string& _name, const std::string& _url)
    : DataSource(_name, _url) {

    if (!_url.empty()) {
        // Load from file
        const auto& string = stringFromResource(_url.c_str());
        addData(string);
    }
}

void ClientGeoJsonSource::addData(const std::string& _data) {

    m_features = geojsonvt::GeoJSONVT::convertFeatures(_data);
    m_store = std::make_unique<GeoJSONVT>(m_features, maxZoom, indexMaxZoom, indexMaxPoints, tolerance);

}

bool ClientGeoJsonSource::loadTileData(std::shared_ptr<TileTask>&& _task, TileTaskCb _cb) {

    _cb(std::move(_task));

    return true;
}

bool ClientGeoJsonSource::getTileData(std::shared_ptr<TileTask>& _task) {

    return true;
}

void ClientGeoJsonSource::clearData() {

    m_features.clear();
    m_store.reset();

}

void ClientGeoJsonSource::addPoint(double* _coords) {

    auto container = geojsonvt::Convert::project({ geojsonvt::LonLat(_coords[0], _coords[1]) }, tolerance);

    auto feature = geojsonvt::Convert::create(geojsonvt::Tags(),
                                              geojsonvt::ProjectedFeatureType::Point,
                                              container.members);

    m_features.push_back(std::move(feature));
    m_store = std::make_unique<GeoJSONVT>(m_features, maxZoom, indexMaxZoom, indexMaxPoints, tolerance);

}

void ClientGeoJsonSource::addLine(double* _coords, int _lineLength) {

    std::vector<geojsonvt::LonLat> line(_lineLength, { 0, 0 });
    for (int i = 0; i < _lineLength; i++) {
        line[i] = { _coords[2 * i], _coords[2 * i + 1] };
    }

    std::vector<geojsonvt::ProjectedGeometry> geometry = { geojsonvt::Convert::project(line, tolerance) };

    auto feature = geojsonvt::Convert::create(geojsonvt::Tags(),
                                              geojsonvt::ProjectedFeatureType::LineString,
                                              geometry);

    m_features.push_back(std::move(feature));
    m_store = std::make_unique<GeoJSONVT>(m_features, maxZoom, indexMaxZoom, indexMaxPoints, tolerance);
}

void ClientGeoJsonSource::addPoly(double* _coords, int* _ringLengths, int _rings) {

    geojsonvt::ProjectedGeometryContainer geometry;
    double* ringCoords = _coords;
    for (int i = 0; i < _rings; i++) {
        int ringLength = _ringLengths[i];
        std::vector<geojsonvt::LonLat> ring(ringLength, { 0, 0 });
        for (int j = 0; j < ringLength; j++) {
            ring[j] = { ringCoords[2 * j], ringCoords[2 * j + 1] };
        }
        geometry.members.push_back(geojsonvt::Convert::project(ring, tolerance));
        ringCoords += 2 * ringLength;
    }

    auto feature = geojsonvt::Convert::create(geojsonvt::Tags(),
                                              geojsonvt::ProjectedFeatureType::Polygon,
                                              geometry);

    m_features.push_back(std::move(feature));
    m_store = std::make_unique<GeoJSONVT>(m_features, maxZoom, indexMaxZoom, indexMaxPoints, tolerance);
}

std::shared_ptr<TileData> ClientGeoJsonSource::parse(const Tile& _tile, std::vector<char>& _rawData) const {

    if (!m_store) { return nullptr; }

    auto data = std::make_shared<TileData>();

    auto id = _tile.getID();

    auto tile = m_store->getTile(id.z, id.x, id.y); // uses a mutex lock internally for thread-safety

    Layer layer(""); // empty name will skip filtering by 'collection'

    for (auto& it : tile.features) {

        Feature feat;

        const auto& geom = it.tileGeometry;
        const auto type = it.type;

        switch (type) {
            case geojsonvt::TileFeatureType::Point: {
                feat.geometryType = GeometryType::points;
                for (const auto& pt : geom) {
                    const auto& point = pt.get<geojsonvt::TilePoint>();
                    feat.points.push_back(transformPoint(point));
                }
                break;
            }
            case geojsonvt::TileFeatureType::LineString: {
                feat.geometryType = GeometryType::lines;
                for (const auto& r : geom) {
                    Line line;
                    for (const auto& pt : r.get<geojsonvt::TileRing>().points) {
                        line.push_back(transformPoint(pt));
                    }
                    feat.lines.emplace_back(std::move(line));
                }
                break;
            }
            case geojsonvt::TileFeatureType::Polygon: {
                feat.geometryType = GeometryType::polygons;
                for (const auto& r : geom) {
                    Line line;
                    for (const auto& pt : r.get<geojsonvt::TileRing>().points) {
                        line.push_back(transformPoint(pt));
                    }
                    // Polygons are in a flat list of rings, with ccw rings indicating
                    // the beginning of a new polygon
                    if (signedArea(line) >= 0 || feat.polygons.empty()) {
                        feat.polygons.emplace_back();
                    }
                    feat.polygons.back().push_back(std::move(line));
                }
                break;
            }
            default: break;
        }

        std::vector<Properties::Item> items;
        items.reserve(it.tags.size());

        for (auto& tag : it.tags) {
            items.emplace_back(tag.first, tag.second);
        }

        feat.props = Properties(std::move(items));

        layer.features.emplace_back(std::move(feat));

    }

    data->layers.emplace_back(std::move(layer));

    return data;

}

}
<|endoftext|>


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

#include "itkCenteredAffineTransform.h"
#include "itkCenteredEuler3DTransform.h"
#include "itkCenteredRigid2DTransform.h"
#include "itkCenteredSimilarity2DTransform.h"
#include "itkEuler2DTransform.h"
#include "itkFixedCenterOfRotationAffineTransform.h"
#include "itkIdentityTransform.h"
#include "itkQuaternionRigidTransform.h"
#include "itkv3Rigid3DTransform.h"
#include "itkRigid3DPerspectiveTransform.h"
#include "itkScaleLogarithmicTransform.h"
#include "itkScaleVersor3DTransform.h"
#include "itkScaleSkewVersor3DTransform.h"
#include "itkTranslationTransform.h"
#include "itkBSplineTransform.h"
#include "itkCompositeTransform.h"

#if defined( ITKV3_COMPATIBILITY )
#endif

namespace itk
{
TransformFactoryBase *TransformFactoryBase:: m_Factory = 0;

namespace TransformFactoryBasePrivate
{
bool DefaultTransformsRegistered = false;
}

TransformFactoryBase::TransformFactoryBase()
{}

TransformFactoryBase::~TransformFactoryBase()
{}

void TransformFactoryBase::RegisterDefaultTransforms()
{
  //
  // make sure that the the factory instance has
  // been created. All normal paths to this method
  // already do this but this makes certain sure it's done
  (void)TransformFactoryBase::GetFactory();

  if ( !TransformFactoryBasePrivate::DefaultTransformsRegistered )
    {
    TransformFactory< IdentityTransform< double, 2 > >::RegisterTransform ();
    TransformFactory< IdentityTransform< double, 3 > >::RegisterTransform ();
    TransformFactory< IdentityTransform< double, 4 > >::RegisterTransform ();
    TransformFactory< IdentityTransform< double, 5 > >::RegisterTransform ();
    TransformFactory< IdentityTransform< double, 6 > >::RegisterTransform ();
    TransformFactory< IdentityTransform< double, 7 > >::RegisterTransform ();
    TransformFactory< IdentityTransform< double, 8 > >::RegisterTransform ();
    TransformFactory< IdentityTransform< double, 9 > >::RegisterTransform ();
    TransformFactory< AffineTransform< double, 2 > >::RegisterTransform ();
    TransformFactory< AffineTransform< double, 3 > >::RegisterTransform ();
    TransformFactory< AffineTransform< double, 4 > >::RegisterTransform ();
    TransformFactory< AffineTransform< double, 5 > >::RegisterTransform ();
    TransformFactory< AffineTransform< double, 6 > >::RegisterTransform ();
    TransformFactory< AffineTransform< double, 7 > >::RegisterTransform ();
    TransformFactory< AffineTransform< double, 8 > >::RegisterTransform ();
    TransformFactory< AffineTransform< double, 9 > >::RegisterTransform ();

    TransformFactory< ScaleTransform< double, 2 > >::RegisterTransform ();
    TransformFactory< ScaleTransform< double, 3 > >::RegisterTransform ();
    TransformFactory< ScaleTransform< double, 4 > >::RegisterTransform ();

    TransformFactory< CenteredAffineTransform< double, 2 > >::RegisterTransform ();
    TransformFactory< CenteredAffineTransform< double, 3 > >::RegisterTransform ();
    TransformFactory< CenteredEuler3DTransform< double > >::RegisterTransform ();
    TransformFactory< CenteredRigid2DTransform< double > >::RegisterTransform();
    TransformFactory< CenteredSimilarity2DTransform< double > >::RegisterTransform ();
    TransformFactory< Similarity2DTransform< double > >::RegisterTransform ();
    TransformFactory< Euler2DTransform< double > >::RegisterTransform ();
    TransformFactory< Euler3DTransform< double > >::RegisterTransform ();
    TransformFactory< FixedCenterOfRotationAffineTransform< double > >::RegisterTransform ();
    TransformFactory< QuaternionRigidTransform< double > >::RegisterTransform ();
    TransformFactory< Rigid2DTransform< double > >::RegisterTransform ();

    TransformFactory< BSplineTransform< double, 2, 2 > >::RegisterTransform ();
    TransformFactory< BSplineTransform< double, 3, 3 > >::RegisterTransform ();
#ifdef ITKV3_COMPATIBILITY
    TransformFactory< BSplineDeformableTransform< double, 2, 2 > >::RegisterTransform ();
    TransformFactory< BSplineDeformableTransform< double, 3, 3 > >::RegisterTransform ();
#endif

    // We cannot register both Rigid3DTransform and
    // itkv3::Rigid3DTransform because they both have the same name
#ifdef ITKV3_COMPATIBILITY
    TransformFactory< Rigid3DTransform< double > >::RegisterTransform ();
#else
    TransformFactory< itkv3::Rigid3DTransform< double > >::RegisterTransform ();
#endif
    TransformFactory< Rigid3DPerspectiveTransform< double > >::RegisterTransform ();
    TransformFactory< ScalableAffineTransform< double > >::RegisterTransform ();
    TransformFactory< ScaleLogarithmicTransform< double > >::RegisterTransform ();
    TransformFactory< ScaleVersor3DTransform< double > >::RegisterTransform ();
    TransformFactory< ScaleSkewVersor3DTransform< double > >::RegisterTransform ();
    TransformFactory< TranslationTransform< double > >::RegisterTransform ();
    TransformFactory< VersorRigid3DTransform< double > >::RegisterTransform ();
    TransformFactory< VersorTransform< double > >::RegisterTransform ();

    TransformFactory< AffineTransform< float, 2 > >::RegisterTransform ();
    TransformFactory< AffineTransform< float, 3 > >::RegisterTransform ();
    TransformFactory< AffineTransform< float, 4 > >::RegisterTransform ();
    TransformFactory< AffineTransform< float, 5 > >::RegisterTransform ();
    TransformFactory< AffineTransform< float, 6 > >::RegisterTransform ();
    TransformFactory< AffineTransform< float, 7 > >::RegisterTransform ();
    TransformFactory< AffineTransform< float, 8 > >::RegisterTransform ();
    TransformFactory< AffineTransform< float, 9 > >::RegisterTransform ();

    TransformFactory< IdentityTransform< float, 2 > >::RegisterTransform ();
    TransformFactory< IdentityTransform< float, 3 > >::RegisterTransform ();
    TransformFactory< IdentityTransform< float, 4 > >::RegisterTransform ();
    TransformFactory< IdentityTransform< float, 5 > >::RegisterTransform ();
    TransformFactory< IdentityTransform< float, 6 > >::RegisterTransform ();
    TransformFactory< IdentityTransform< float, 7 > >::RegisterTransform ();
    TransformFactory< IdentityTransform< float, 8 > >::RegisterTransform ();
    TransformFactory< IdentityTransform< float, 9 > >::RegisterTransform ();

    TransformFactory< CenteredAffineTransform< float, 2 > >::RegisterTransform ();
    TransformFactory< CenteredAffineTransform< float, 3 > >::RegisterTransform ();

    TransformFactory< ScaleTransform< float, 2 > >::RegisterTransform ();
    TransformFactory< ScaleTransform< float, 3 > >::RegisterTransform ();
    TransformFactory< ScaleTransform< float, 4 > >::RegisterTransform ();

    TransformFactory< CenteredEuler3DTransform< float > >::RegisterTransform ();
    TransformFactory< CenteredRigid2DTransform< float > >::RegisterTransform();
    TransformFactory< CenteredSimilarity2DTransform< float > >::RegisterTransform ();
    TransformFactory< Similarity2DTransform< float > >::RegisterTransform ();
    TransformFactory< Euler2DTransform< float > >::RegisterTransform ();
    TransformFactory< Euler3DTransform< float > >::RegisterTransform ();
    TransformFactory< FixedCenterOfRotationAffineTransform< float > >::RegisterTransform ();
    TransformFactory< QuaternionRigidTransform< float > >::RegisterTransform ();
    TransformFactory< Rigid2DTransform< float > >::RegisterTransform ();

    TransformFactory< BSplineTransform< float, 2, 2 > >::RegisterTransform ();
    TransformFactory< BSplineTransform< float, 3, 3 > >::RegisterTransform ();
#ifdef ITKV3_COMPATIBILITY
    TransformFactory< BSplineDeformableTransform< float, 2, 2 > >::RegisterTransform ();
    TransformFactory< BSplineDeformableTransform< float, 3, 3 > >::RegisterTransform ();
#endif
    // We cannot register both Rigid3DTransform and
    // itkv3::Rigid3DTransform because they both have the same name
#ifdef ITKV3_COMPATIBILITY
    TransformFactory< Rigid3DTransform< float > >::RegisterTransform ();
#else
    TransformFactory< itkv3::Rigid3DTransform< float > >::RegisterTransform ();
#endif
    TransformFactory< Rigid3DPerspectiveTransform< float > >::RegisterTransform ();
    TransformFactory< ScalableAffineTransform< float > >::RegisterTransform ();
    TransformFactory< ScaleLogarithmicTransform< float > >::RegisterTransform ();
    TransformFactory< ScaleVersor3DTransform< float > >::RegisterTransform ();
    TransformFactory< ScaleSkewVersor3DTransform< float > >::RegisterTransform ();
    TransformFactory< TranslationTransform< float > >::RegisterTransform ();
    TransformFactory< VersorRigid3DTransform< float > >::RegisterTransform ();
    TransformFactory< VersorTransform< float > >::RegisterTransform ();
    //
    // register composite transform
    TransformFactory<CompositeTransform<double, 2> >::RegisterTransform();
    TransformFactory<CompositeTransform<double, 3> >::RegisterTransform();
    TransformFactory<CompositeTransform<double, 4> >::RegisterTransform();
    TransformFactory<CompositeTransform<double, 5> >::RegisterTransform();
    TransformFactory<CompositeTransform<double, 6> >::RegisterTransform();
    TransformFactory<CompositeTransform<double, 7> >::RegisterTransform();
    TransformFactory<CompositeTransform<double, 8> >::RegisterTransform();
    TransformFactory<CompositeTransform<double, 9> >::RegisterTransform();
    TransformFactory<CompositeTransform<float, 2> >::RegisterTransform();
    TransformFactory<CompositeTransform<float, 3> >::RegisterTransform();
    TransformFactory<CompositeTransform<float, 4> >::RegisterTransform();
    TransformFactory<CompositeTransform<float, 5> >::RegisterTransform();
    TransformFactory<CompositeTransform<float, 6> >::RegisterTransform();
    TransformFactory<CompositeTransform<float, 7> >::RegisterTransform();
    TransformFactory<CompositeTransform<float, 8> >::RegisterTransform();
    TransformFactory<CompositeTransform<float, 9> >::RegisterTransform();

    }
  TransformFactoryBasePrivate::DefaultTransformsRegistered = true;
}

const char *
TransformFactoryBase::GetITKSourceVersion(void) const
{
  return ITK_SOURCE_VERSION;
}

const char *
TransformFactoryBase::GetDescription() const
{
  return "Transform FactoryBase";
}
} // end namespace itk
<commit_msg>COMP: Missing header when ITKV3_COMPATIBILITY is ON<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/
#include "itkTransformFactory.h"
#include "itkVersion.h"

#include "itkCenteredAffineTransform.h"
#include "itkCenteredEuler3DTransform.h"
#include "itkCenteredRigid2DTransform.h"
#include "itkCenteredSimilarity2DTransform.h"
#include "itkEuler2DTransform.h"
#include "itkFixedCenterOfRotationAffineTransform.h"
#include "itkIdentityTransform.h"
#include "itkQuaternionRigidTransform.h"
#include "itkv3Rigid3DTransform.h"
#include "itkRigid3DPerspectiveTransform.h"
#include "itkScaleLogarithmicTransform.h"
#include "itkScaleVersor3DTransform.h"
#include "itkScaleSkewVersor3DTransform.h"
#include "itkTranslationTransform.h"
#include "itkBSplineTransform.h"
#include "itkCompositeTransform.h"

#if defined( ITKV3_COMPATIBILITY )
#include "itkBSplineDeformableTransform.h"
#endif

namespace itk
{
TransformFactoryBase *TransformFactoryBase:: m_Factory = 0;

namespace TransformFactoryBasePrivate
{
bool DefaultTransformsRegistered = false;
}

TransformFactoryBase::TransformFactoryBase()
{}

TransformFactoryBase::~TransformFactoryBase()
{}

void TransformFactoryBase::RegisterDefaultTransforms()
{
  //
  // make sure that the the factory instance has
  // been created. All normal paths to this method
  // already do this but this makes certain sure it's done
  (void)TransformFactoryBase::GetFactory();

  if ( !TransformFactoryBasePrivate::DefaultTransformsRegistered )
    {
    TransformFactory< IdentityTransform< double, 2 > >::RegisterTransform ();
    TransformFactory< IdentityTransform< double, 3 > >::RegisterTransform ();
    TransformFactory< IdentityTransform< double, 4 > >::RegisterTransform ();
    TransformFactory< IdentityTransform< double, 5 > >::RegisterTransform ();
    TransformFactory< IdentityTransform< double, 6 > >::RegisterTransform ();
    TransformFactory< IdentityTransform< double, 7 > >::RegisterTransform ();
    TransformFactory< IdentityTransform< double, 8 > >::RegisterTransform ();
    TransformFactory< IdentityTransform< double, 9 > >::RegisterTransform ();
    TransformFactory< AffineTransform< double, 2 > >::RegisterTransform ();
    TransformFactory< AffineTransform< double, 3 > >::RegisterTransform ();
    TransformFactory< AffineTransform< double, 4 > >::RegisterTransform ();
    TransformFactory< AffineTransform< double, 5 > >::RegisterTransform ();
    TransformFactory< AffineTransform< double, 6 > >::RegisterTransform ();
    TransformFactory< AffineTransform< double, 7 > >::RegisterTransform ();
    TransformFactory< AffineTransform< double, 8 > >::RegisterTransform ();
    TransformFactory< AffineTransform< double, 9 > >::RegisterTransform ();

    TransformFactory< ScaleTransform< double, 2 > >::RegisterTransform ();
    TransformFactory< ScaleTransform< double, 3 > >::RegisterTransform ();
    TransformFactory< ScaleTransform< double, 4 > >::RegisterTransform ();

    TransformFactory< CenteredAffineTransform< double, 2 > >::RegisterTransform ();
    TransformFactory< CenteredAffineTransform< double, 3 > >::RegisterTransform ();
    TransformFactory< CenteredEuler3DTransform< double > >::RegisterTransform ();
    TransformFactory< CenteredRigid2DTransform< double > >::RegisterTransform();
    TransformFactory< CenteredSimilarity2DTransform< double > >::RegisterTransform ();
    TransformFactory< Similarity2DTransform< double > >::RegisterTransform ();
    TransformFactory< Euler2DTransform< double > >::RegisterTransform ();
    TransformFactory< Euler3DTransform< double > >::RegisterTransform ();
    TransformFactory< FixedCenterOfRotationAffineTransform< double > >::RegisterTransform ();
    TransformFactory< QuaternionRigidTransform< double > >::RegisterTransform ();
    TransformFactory< Rigid2DTransform< double > >::RegisterTransform ();

    TransformFactory< BSplineTransform< double, 2, 2 > >::RegisterTransform ();
    TransformFactory< BSplineTransform< double, 3, 3 > >::RegisterTransform ();
#ifdef ITKV3_COMPATIBILITY
    TransformFactory< BSplineDeformableTransform< double, 2, 2 > >::RegisterTransform ();
    TransformFactory< BSplineDeformableTransform< double, 3, 3 > >::RegisterTransform ();
#endif

    // We cannot register both Rigid3DTransform and
    // itkv3::Rigid3DTransform because they both have the same name
#ifdef ITKV3_COMPATIBILITY
    TransformFactory< Rigid3DTransform< double > >::RegisterTransform ();
#else
    TransformFactory< itkv3::Rigid3DTransform< double > >::RegisterTransform ();
#endif
    TransformFactory< Rigid3DPerspectiveTransform< double > >::RegisterTransform ();
    TransformFactory< ScalableAffineTransform< double > >::RegisterTransform ();
    TransformFactory< ScaleLogarithmicTransform< double > >::RegisterTransform ();
    TransformFactory< ScaleVersor3DTransform< double > >::RegisterTransform ();
    TransformFactory< ScaleSkewVersor3DTransform< double > >::RegisterTransform ();
    TransformFactory< TranslationTransform< double > >::RegisterTransform ();
    TransformFactory< VersorRigid3DTransform< double > >::RegisterTransform ();
    TransformFactory< VersorTransform< double > >::RegisterTransform ();

    TransformFactory< AffineTransform< float, 2 > >::RegisterTransform ();
    TransformFactory< AffineTransform< float, 3 > >::RegisterTransform ();
    TransformFactory< AffineTransform< float, 4 > >::RegisterTransform ();
    TransformFactory< AffineTransform< float, 5 > >::RegisterTransform ();
    TransformFactory< AffineTransform< float, 6 > >::RegisterTransform ();
    TransformFactory< AffineTransform< float, 7 > >::RegisterTransform ();
    TransformFactory< AffineTransform< float, 8 > >::RegisterTransform ();
    TransformFactory< AffineTransform< float, 9 > >::RegisterTransform ();

    TransformFactory< IdentityTransform< float, 2 > >::RegisterTransform ();
    TransformFactory< IdentityTransform< float, 3 > >::RegisterTransform ();
    TransformFactory< IdentityTransform< float, 4 > >::RegisterTransform ();
    TransformFactory< IdentityTransform< float, 5 > >::RegisterTransform ();
    TransformFactory< IdentityTransform< float, 6 > >::RegisterTransform ();
    TransformFactory< IdentityTransform< float, 7 > >::RegisterTransform ();
    TransformFactory< IdentityTransform< float, 8 > >::RegisterTransform ();
    TransformFactory< IdentityTransform< float, 9 > >::RegisterTransform ();

    TransformFactory< CenteredAffineTransform< float, 2 > >::RegisterTransform ();
    TransformFactory< CenteredAffineTransform< float, 3 > >::RegisterTransform ();

    TransformFactory< ScaleTransform< float, 2 > >::RegisterTransform ();
    TransformFactory< ScaleTransform< float, 3 > >::RegisterTransform ();
    TransformFactory< ScaleTransform< float, 4 > >::RegisterTransform ();

    TransformFactory< CenteredEuler3DTransform< float > >::RegisterTransform ();
    TransformFactory< CenteredRigid2DTransform< float > >::RegisterTransform();
    TransformFactory< CenteredSimilarity2DTransform< float > >::RegisterTransform ();
    TransformFactory< Similarity2DTransform< float > >::RegisterTransform ();
    TransformFactory< Euler2DTransform< float > >::RegisterTransform ();
    TransformFactory< Euler3DTransform< float > >::RegisterTransform ();
    TransformFactory< FixedCenterOfRotationAffineTransform< float > >::RegisterTransform ();
    TransformFactory< QuaternionRigidTransform< float > >::RegisterTransform ();
    TransformFactory< Rigid2DTransform< float > >::RegisterTransform ();

    TransformFactory< BSplineTransform< float, 2, 2 > >::RegisterTransform ();
    TransformFactory< BSplineTransform< float, 3, 3 > >::RegisterTransform ();
#ifdef ITKV3_COMPATIBILITY
    TransformFactory< BSplineDeformableTransform< float, 2, 2 > >::RegisterTransform ();
    TransformFactory< BSplineDeformableTransform< float, 3, 3 > >::RegisterTransform ();
#endif
    // We cannot register both Rigid3DTransform and
    // itkv3::Rigid3DTransform because they both have the same name
#ifdef ITKV3_COMPATIBILITY
    TransformFactory< Rigid3DTransform< float > >::RegisterTransform ();
#else
    TransformFactory< itkv3::Rigid3DTransform< float > >::RegisterTransform ();
#endif
    TransformFactory< Rigid3DPerspectiveTransform< float > >::RegisterTransform ();
    TransformFactory< ScalableAffineTransform< float > >::RegisterTransform ();
    TransformFactory< ScaleLogarithmicTransform< float > >::RegisterTransform ();
    TransformFactory< ScaleVersor3DTransform< float > >::RegisterTransform ();
    TransformFactory< ScaleSkewVersor3DTransform< float > >::RegisterTransform ();
    TransformFactory< TranslationTransform< float > >::RegisterTransform ();
    TransformFactory< VersorRigid3DTransform< float > >::RegisterTransform ();
    TransformFactory< VersorTransform< float > >::RegisterTransform ();
    //
    // register composite transform
    TransformFactory<CompositeTransform<double, 2> >::RegisterTransform();
    TransformFactory<CompositeTransform<double, 3> >::RegisterTransform();
    TransformFactory<CompositeTransform<double, 4> >::RegisterTransform();
    TransformFactory<CompositeTransform<double, 5> >::RegisterTransform();
    TransformFactory<CompositeTransform<double, 6> >::RegisterTransform();
    TransformFactory<CompositeTransform<double, 7> >::RegisterTransform();
    TransformFactory<CompositeTransform<double, 8> >::RegisterTransform();
    TransformFactory<CompositeTransform<double, 9> >::RegisterTransform();
    TransformFactory<CompositeTransform<float, 2> >::RegisterTransform();
    TransformFactory<CompositeTransform<float, 3> >::RegisterTransform();
    TransformFactory<CompositeTransform<float, 4> >::RegisterTransform();
    TransformFactory<CompositeTransform<float, 5> >::RegisterTransform();
    TransformFactory<CompositeTransform<float, 6> >::RegisterTransform();
    TransformFactory<CompositeTransform<float, 7> >::RegisterTransform();
    TransformFactory<CompositeTransform<float, 8> >::RegisterTransform();
    TransformFactory<CompositeTransform<float, 9> >::RegisterTransform();

    }
  TransformFactoryBasePrivate::DefaultTransformsRegistered = true;
}

const char *
TransformFactoryBase::GetITKSourceVersion(void) const
{
  return ITK_SOURCE_VERSION;
}

const char *
TransformFactoryBase::GetDescription() const
{
  return "Transform FactoryBase";
}
} // end namespace itk
<|endoftext|>


<commit_before><commit_msg>Fix for Canvas::DrawBitmap that I broke when adding adding pitch to Texture2D::Lock<commit_after><|endoftext|>