text:
/**************************************************************
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 *************************************************************/

#ifndef _DXCANVAS_BITMAPCANVASHELPER_HXX_
#define _DXCANVAS_BITMAPCANVASHELPER_HXX_

#include <com/sun/star/rendering/XCanvas.hpp>

#include <basegfx/vector/b2isize.hxx>
#include <basegfx/vector/b2dsize.hxx>

#include "dx_graphicsprovider.hxx"
#include "dx_ibitmap.hxx"
#include "dx_gdiplususer.hxx"
#include "dx_impltools.hxx"
#include "dx_canvashelper.hxx"

#include <boost/utility.hpp>

namespace dxcanvas
{
    /** Helper class for basic canvas functionality. Also offers
        optional backbuffer painting, when providing it with a second
        HDC to render into.
     */
    class BitmapCanvasHelper : public CanvasHelper
    {
    public:
        BitmapCanvasHelper();

        /// Release all references
        void disposing();

        /** Set the target for rendering operations

            @param rTarget
            Render target
         */
        void setTarget( const IBitmapSharedPtr& rTarget );

        /** Set the target for rendering operations

            @param rTarget
            Render target

            @param rOutputOffset
            Output offset in pixel
         */
        void setTarget( const IBitmapSharedPtr&   rTarget,
                        const ::basegfx::B2ISize& rOutputOffset );

        // CanvasHelper functionality is implementation-inherited. yuck.
        // =============================================================
        void clear();

        ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XCachedPrimitive >
        	drawTextLayout( const ::com::sun::star::rendering::XCanvas* 	pCanvas,
                            const ::com::sun::star::uno::Reference<
                            	::com::sun::star::rendering::XTextLayout >& layoutetText,
                            const ::com::sun::star::rendering::ViewState& 	viewState,
                            const ::com::sun::star::rendering::RenderState& renderState );

        // BitmapCanvasHelper functionality
        // ================================

        void copyRect( const ::com::sun::star::rendering::XCanvas* 			pCanvas,
                       const ::com::sun::star::uno::Reference<
                       		::com::sun::star::rendering::XBitmapCanvas >& 	sourceCanvas,
                       const ::com::sun::star::geometry::RealRectangle2D& 	sourceRect,
                       const ::com::sun::star::rendering::ViewState& 		sourceViewState,
                       const ::com::sun::star::rendering::RenderState& 		sourceRenderState,
                       const ::com::sun::star::geometry::RealRectangle2D& 	destRect,
                       const ::com::sun::star::rendering::ViewState& 		destViewState,
                       const ::com::sun::star::rendering::RenderState& 		destRenderState );

        ::com::sun::star::geometry::IntegerSize2D getSize();

        ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XBitmap >
        	getScaledBitmap( const ::com::sun::star::geometry::RealSize2D& 	newSize,
                             sal_Bool 										beFast );

        ::com::sun::star::uno::Sequence< sal_Int8 >
	        getData( ::com::sun::star::rendering::IntegerBitmapLayout& 		bitmapLayout,
                     const ::com::sun::star::geometry::IntegerRectangle2D&  rect );

        void setData( const ::com::sun::star::uno::Sequence< sal_Int8 >&         data,
                      const ::com::sun::star::rendering::IntegerBitmapLayout&    bitmapLayout,
                      const ::com::sun::star::geometry::IntegerRectangle2D&      rect );

        void setPixel( const ::com::sun::star::uno::Sequence< sal_Int8 >&        color,
                       const ::com::sun::star::rendering::IntegerBitmapLayout&   bitmapLayout,
                       const ::com::sun::star::geometry::IntegerPoint2D&         pos );

        ::com::sun::star::uno::Sequence< sal_Int8 >
	        getPixel( ::com::sun::star::rendering::IntegerBitmapLayout& bitmapLayout,
                      const ::com::sun::star::geometry::IntegerPoint2D& pos );

        ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XBitmapPalette > getPalette();

        ::com::sun::star::rendering::IntegerBitmapLayout getMemoryLayout();

        bool hasAlpha() const;

    protected:
        /// Render target
        IBitmapSharedPtr mpTarget;
    };
}

#endif /* _DXCANVAS_BITMAPCANVASHELPER_HXX_ */

ext: hxx

max_stars_repo_name: Grosskopf/openoffice

max_issues_repo_name: Grosskopf/openoffice

max_forks_repo_name: Grosskopf/openoffice


text:
// This code is licensed under the MIT License (MIT). See LICENCE.txt for details
#pragma once

#include <algorithm>
#include <cstdint>
#include <exception>
#include <iostream>
#include <numeric>
#include <sstream>
#include <string>

#include <boost/lexical_cast.hpp>

namespace collatzOpenCL
{

class ValidateErr : public std::exception {
public:
  ValidateErr(const std::string& val, unsigned int expectedStep, unsigned int calculatedStep)
  {
    std::stringstream ss("Value :");
    ss << val << "\nExpected Step: " << expectedStep << "\nCalculated Step: " << calculatedStep << '\n';
    errMsg_.assign(ss.str());
  }
  const char* what() const override { return errMsg_.c_str(); }
private:
  std::string errMsg_;
};

template<typename MaxStepTy = uint32_t, typename MaxPosTy = uint64_t, typename TotalStepsTy = uint64_t>
struct Result {
  MaxStepTy maxStep = 0;
  MaxPosTy maxPos = 0;
  TotalStepsTy totalSteps = 0;
};

template<typename T, typename U, typename V>
inline decltype(auto) operator << (std::ostream& os, const Result<T,U,V>& result)
{
  return os << result.maxStep << '\n' << result.maxPos << '\n' << result.totalSteps;
}
template<typename T, typename U, typename V>
inline decltype(auto) operator >> (std::istream& is, Result<T,U,V>& result)
{
  return is >> result.maxStep >> result.maxPos >> result.totalSteps;
}

template<typename T, typename U, typename V, typename ValGen, typename CollatzFunc>
inline auto compare_and_validate(const Result<T,U,V>& oldRes, const Result<T,U,V>& newRes, ValGen&& get_val, CollatzFunc&& collatz_step)
{
  //Only validate the results when new champion arrives
  if (newRes.maxStep > oldRes.maxStep) {
    auto val = get_val(newRes); //synthesize the value from the results
    auto expectedStep = collatz_step(val);
    if (newRes.maxStep != expectedStep) {
      throw ValidateErr{ boost::lexical_cast<std::string>(val), expectedStep, newRes.maxStep };
    }
    return Result<T, U, V>{ newRes.maxStep, newRes.maxPos, newRes.totalSteps + oldRes.totalSteps };
  } else {
    return Result<T, U, V>{ oldRes.maxStep, oldRes.maxPos, newRes.totalSteps + oldRes.totalSteps };
  }
}

template <typename MaxStepVec, typename MaxPosVec, typename TotalStepsVec> inline
auto gather_results(MaxStepVec&& maxStep, MaxPosVec&& maxPos, TotalStepsVec&& totalSteps)
{
  using std::cbegin; using std::cend; using std::next;
  auto pos = std::distance(cbegin(maxStep), std::max_element(cbegin(maxStep), cend(maxStep)));
  return Result<decltype(maxStep[0]), decltype(maxPos[0]), decltype(totalSteps[0])> {
    *next(cbegin(maxStep), pos),
    *next(cbegin(maxPos), pos),
    std::accumulate(cbegin(totalSteps), cend(totalSteps), 0)
  };
}

}

ext: hpp

max_stars_repo_name: sosiristseng/collatz-cpp

max_issues_repo_name: sosiristseng/collatz-cpp

max_forks_repo_name: sosiristseng/collatz-cpp


text:
#pragma once

#include <vpx/vpx_codec.h>
#include <vpx/vpx_encoder.h>
#include <vpx/vpx_image.h>

#include <cstdint>
#include <queue>
#include <vector>

#include <boost/cstdint.hpp>
#include <boost/rational.hpp>

#include "constants.hpp"
#include "video/encoder.hpp"

namespace hisui {

struct Frame;

}

namespace hisui::video {

class VPXEncoderConfig;

class BufferVPXEncoder : public Encoder {
 public:
  BufferVPXEncoder(
      std::queue<hisui::Frame>*,
      const VPXEncoderConfig&,
      const std::uint64_t timescale = hisui::Constants::NANO_SECOND);
  ~BufferVPXEncoder();

  void outputImage(const std::vector<unsigned char>&);
  void flush();
  std::uint32_t getFourcc() const;
  void setResolutionAndBitrate(const std::uint32_t,
                               const std::uint32_t,
                               const std::uint32_t);

 private:
  std::queue<hisui::Frame>* m_buffer;
  std::uint32_t m_width;
  std::uint32_t m_height;
  std::uint32_t m_bitrate;
  boost::rational<std::uint64_t> m_fps;
  std::uint32_t m_fourcc;
  int m_frame = 0;
  ::vpx_codec_ctx_t m_codec;
  ::vpx_codec_enc_cfg_t m_cfg;
  ::vpx_image_t m_raw_vpx_image;
  std::uint64_t m_sum_of_bits = 0;
  const std::uint64_t m_timescale;

  bool encodeFrame(::vpx_codec_ctx_t*, ::vpx_image_t*, const int, const int);
};

}  // namespace hisui::video

max_stars_repo_name: kounoike/hisui

max_issues_repo_name: kounoike/hisui

max_forks_repo_name: kounoike/hisui


text:
#ifndef RABBITXX_IO_GRAPH_HPP
#define RABBITXX_IO_GRAPH_HPP

#include <boost/graph/adjacency_list.hpp>

#include <rabbitxx/graph/bgl_base_graph.hpp>
#include <rabbitxx/graph/otf2_io_graph_properties.hpp>

namespace rabbitxx {

namespace graph { namespace detail {

    using io_graph_impl = boost::adjacency_list<
                                                    boost::vecS, // store out-edges of vertex in std::vector
                                                    boost::vecS, // store vertices in a std::vector
                                                    boost::directedS, // the graph is directed
                                                    otf2_trace_event, // use otf2_trace_event as vertex property
                                                    boost::no_property, // no edge property
                                                    app_info>; // use app_info as graph property
}} // namespace graph::detail

using IoGraph = graph::graph<graph::detail::io_graph_impl>;
// try to define the vertex_descriptor type to avoid templates!
// since we dependet on an integral vertex descriptor type.
using VertexDescriptor = typename IoGraph::vertex_descriptor;

io_event_property get_io_property(const IoGraph& graph, const VertexDescriptor vd);

sync_event_property get_sync_property(const IoGraph& graph, const VertexDescriptor vd);

/**
 * @brief Find the synthetic root node of a given graph.
 *
 * Root node is the only vertex with a `vertex_kind::synthetic`.
 *
 * @param graph: A reference to the Graph.
 * @return The vertex descriptor of the root node.
 */
VertexDescriptor find_root(const IoGraph& graph);

/**
 * @brief Get the number of processes involved, in a given I/O Graph.
 *
 * Therefore we take the synthetic root vertex and count the out-going edges.
 *
 * @param graph: A reference to the graph.
 * @return The number of processes that have events in the graph.
 */
std::uint64_t num_procs(const IoGraph& graph) noexcept;

/**
 * @brief Get all processes which are involved in a given synchronization event.
 *
 * Return vector containing all the process id's of the processes participating
 * within a given synchronization event.
 *
 * @param sevt: Reference to a synchronization event.
 * @return Vector of process ids, which are involved in the synchronization.
 * If the sync-event is wether a collective nor a peer2peer event the returned
 * vector is empty.
 */
std::vector<std::uint64_t> procs_in_sync_involved(const sync_event_property& sevt);

/**
 * @return The number of processes involved in a given synchronization routine.
 */
std::uint64_t num_procs_in_sync_involved(const sync_event_property& sevt);

/**
* Checks if the start event of a set `of_v` is an adjacent vertex of the current
* event `cur_v`.
*/
template <typename Vertex, typename Graph>
bool
is_adjacent_event_of(const Vertex of_v, const Vertex cur_v, const Graph& g)
{
    const auto adjacent_r = boost::adjacent_vertices(cur_v, g);
    return std::any_of(
        adjacent_r.first, adjacent_r.second, [&of_v](const Vertex vd) { return vd == of_v; });
}

/**
 * @brief Get the `sync_scope` of a synchronization event.
 *
 * @param g: An `IoGraph` object.
 * @param sevt: A `sync_event_property` object.
 *
 * @return The corresponding `sync_scope` of the synchronization event.
 * Either `sync_scope::local` or `sync_scope::global`.
 */
sync_scope
classify_sync(const IoGraph& g, const sync_event_property& sevt);

// What should be returned in the case that `v` is referencing an I/O-Event?
// One option might be to throw an exception.
// Another option might be to introduce a `sync_scope::None` enumeration. On
// which can be checked outside.
sync_scope classify_sync(const IoGraph& g, const VertexDescriptor& v);

} // namespace rabbitxx

#endif /* RABBITXX_IO_GRAPH_HPP */

max_stars_repo_name: blastmaster/rabbitxx

max_issues_repo_name: blastmaster/rabbitxx

max_forks_repo_name: blastmaster/rabbitxx


text:
#include <boost/lockfree/ringbuffer.hpp>

#include <climits>
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>

#include <boost/thread.hpp>
#include <iostream>
#include <memory>

#include "test_helpers.hpp"

using namespace boost;
using namespace boost::lockfree;
using namespace std;

BOOST_AUTO_TEST_CASE( simple_ringbuffer_test )
{
    ringbuffer<int, 64> f;

    BOOST_REQUIRE(f.empty());
    f.enqueue(1);
    f.enqueue(2);

    int i1(0), i2(0);

    BOOST_REQUIRE(f.dequeue(i1));
    BOOST_REQUIRE_EQUAL(i1, 1);

    BOOST_REQUIRE(f.dequeue(i2));
    BOOST_REQUIRE_EQUAL(i2, 2);
    BOOST_REQUIRE(f.empty());
}

enum {
    pointer_and_size,
    reference_to_array,
    iterator_pair,
    output_iterator
};

template <int EnqueueMode>
void ringbuffer_buffer_enqueue_return_value(void)
{
    const size_t xqueue_size = 64;
    const size_t buffer_size = 100;
    ringbuffer<int, 100> rb;

    int data[xqueue_size];
    for (size_t i = 0; i != xqueue_size; ++i)
        data[i] = i*2;

    switch (EnqueueMode) {
    case pointer_and_size:
        BOOST_REQUIRE_EQUAL(rb.enqueue(data, xqueue_size), xqueue_size);
        break;

    case reference_to_array:
        BOOST_REQUIRE_EQUAL(rb.enqueue(data), xqueue_size);
        break;

    case iterator_pair:
        BOOST_REQUIRE_EQUAL(rb.enqueue(data, data + xqueue_size), data + xqueue_size);
        break;

    default:
        assert(false);
    }

    switch (EnqueueMode) {
    case pointer_and_size:
        BOOST_REQUIRE_EQUAL(rb.enqueue(data, xqueue_size), buffer_size - xqueue_size - 1);
        break;

    case reference_to_array:
        BOOST_REQUIRE_EQUAL(rb.enqueue(data), buffer_size - xqueue_size - 1);
        break;

    case iterator_pair:
        BOOST_REQUIRE_EQUAL(rb.enqueue(data, data + xqueue_size), data + buffer_size - xqueue_size - 1);
        break;

    default:
        assert(false);
    }
}

BOOST_AUTO_TEST_CASE( ringbuffer_buffer_enqueue_return_value_test )
{
    ringbuffer_buffer_enqueue_return_value<pointer_and_size>();
    ringbuffer_buffer_enqueue_return_value<reference_to_array>();
    ringbuffer_buffer_enqueue_return_value<iterator_pair>();
}

template <int EnqueueMode,
          int ElementCount,
          int BufferSize,
          int NumberOfIterations
         >
void ringbuffer_buffer_enqueue(void)
{
    const size_t xqueue_size = ElementCount;
    ringbuffer<int, BufferSize> rb;

    int data[xqueue_size];
    for (size_t i = 0; i != xqueue_size; ++i)
        data[i] = i*2;

    std::vector<int> vdata(data, data + xqueue_size);

    for (int i = 0; i != NumberOfIterations; ++i) {
        BOOST_REQUIRE(rb.empty());
        switch (EnqueueMode) {
        case pointer_and_size:
            BOOST_REQUIRE_EQUAL(rb.enqueue(data, xqueue_size), xqueue_size);
            break;

        case reference_to_array:
            BOOST_REQUIRE_EQUAL(rb.enqueue(data), xqueue_size);
            break;

        case iterator_pair:
            BOOST_REQUIRE_EQUAL(rb.enqueue(data, data + xqueue_size), data + xqueue_size);
            break;

        default:
            assert(false);
        }

        int out[xqueue_size];
        BOOST_REQUIRE_EQUAL(rb.dequeue(out, xqueue_size), xqueue_size);
        for (size_t i = 0; i != xqueue_size; ++i)
            BOOST_REQUIRE_EQUAL(data[i], out[i]);
    }
}

BOOST_AUTO_TEST_CASE( ringbuffer_buffer_enqueue_test )
{
    ringbuffer_buffer_enqueue<pointer_and_size, 7, 16, 64>();
    ringbuffer_buffer_enqueue<reference_to_array, 7, 16, 64>();
    ringbuffer_buffer_enqueue<iterator_pair, 7, 16, 64>();
}

template <int EnqueueMode,
          int ElementCount,
          int BufferSize,
          int NumberOfIterations
         >
void ringbuffer_buffer_dequeue(void)
{
    const size_t xqueue_size = ElementCount;
    ringbuffer<int, BufferSize> rb;

    int data[xqueue_size];
    for (size_t i = 0; i != xqueue_size; ++i)
        data[i] = i*2;

    std::vector<int> vdata(data, data + xqueue_size);

    for (int i = 0; i != NumberOfIterations; ++i) {
        BOOST_REQUIRE(rb.empty());
        BOOST_REQUIRE_EQUAL(rb.enqueue(data), xqueue_size);

        int out[xqueue_size];
        vector<int> vout;

        switch (EnqueueMode) {
        case pointer_and_size:
            BOOST_REQUIRE_EQUAL(rb.dequeue(out, xqueue_size), xqueue_size);
            break;

        case reference_to_array:
            BOOST_REQUIRE_EQUAL(rb.dequeue(out), xqueue_size);
            break;

        case output_iterator:
            BOOST_REQUIRE_EQUAL(rb.dequeue(std::back_inserter(vout)), xqueue_size);
            break;

        default:
            assert(false);
        }

        if (EnqueueMode == output_iterator) {
            BOOST_REQUIRE_EQUAL(vout.size(), xqueue_size);
            for (size_t i = 0; i != xqueue_size; ++i)
                BOOST_REQUIRE_EQUAL(data[i], vout[i]);
        } else {
            for (size_t i = 0; i != xqueue_size; ++i)
                BOOST_REQUIRE_EQUAL(data[i], out[i]);
        }
    }
}

BOOST_AUTO_TEST_CASE( ringbuffer_buffer_dequeue_test )
{
    ringbuffer_buffer_dequeue<pointer_and_size, 7, 16, 64>();
    ringbuffer_buffer_dequeue<reference_to_array, 7, 16, 64>();
    ringbuffer_buffer_dequeue<output_iterator, 7, 16, 64>();
}

static const uint nodes_per_thread = 500000;

struct ringbuffer_tester
{
    ringbuffer<int, 128> sf;

    atomic<long> ringbuffer_cnt, received_nodes;

    static_hashed_set<int, 1<<16 > working_set;

    ringbuffer_tester(void):
        ringbuffer_cnt(0), received_nodes(0)
    {}

    void add(void)
    {
        for (uint i = 0; i != nodes_per_thread; ++i)
        {
            int id = generate_id<int>();

            working_set.insert(id);

            while (sf.enqueue(id) == false)
            {}

            ++ringbuffer_cnt;
        }
    }

    bool get_element(void)
    {
        int data;

        bool success = sf.dequeue(data);

        if (success)
        {
            ++received_nodes;
            --ringbuffer_cnt;
            bool erased = working_set.erase(data);
            assert(erased);
            return true;
        }
        else
            return false;
    }

    boost::atomic<bool> running;

    void get(void)
    {
        for(;;)
        {
            bool success = get_element();
            if (not running and not success)
                return;
        }
    }

    void run(void)
    {
        running = true;

        BOOST_REQUIRE(sf.empty());

        thread reader(boost::bind(&ringbuffer_tester::get, this));
        thread writer(boost::bind(&ringbuffer_tester::add, this));
        cout << "reader and writer threads created" << endl;

        writer.join();
        cout << "writer threads joined. waiting for readers to finish" << endl;

        running = false;
        reader.join();

        BOOST_REQUIRE_EQUAL(received_nodes, nodes_per_thread);
        BOOST_REQUIRE_EQUAL(ringbuffer_cnt, 0);
        BOOST_REQUIRE(sf.empty());
        BOOST_REQUIRE(working_set.count_nodes() == 0);
    }
};

BOOST_AUTO_TEST_CASE( ringbuffer_test_caching )
{
//     ringbuffer_tester test1;
    //test1.run();
}

struct ringbuffer_tester_buffering
{
    ringbuffer<int, 128> sf;

    atomic<long> ringbuffer_cnt;

    static_hashed_set<int, 1<<16 > working_set;
    atomic<long> received_nodes;

    ringbuffer_tester_buffering(void):
        ringbuffer_cnt(0), received_nodes(0)
    {}

    static const size_t buf_size = 5;

    void add(void)
    {
        boost::array<int, buf_size> input_buffer;
        for (uint i = 0; i != nodes_per_thread; i+=buf_size)
        {
            for (size_t i = 0; i != buf_size; ++i)
            {
                int id = generate_id<int>();
                working_set.insert(id);
                input_buffer[i] = id;
            }

            size_t enqueued = 0;

            do
            {
                enqueued += sf.enqueue(input_buffer.c_array() + enqueued,
                                       input_buffer.size()    - enqueued);
            }
            while (enqueued != buf_size);

            ringbuffer_cnt+=buf_size;
        }
    }

    bool get_elements(void)
    {
        boost::array<int, buf_size> output_buffer;

        size_t dequeued = sf.dequeue(output_buffer.c_array(), output_buffer.size());

        if (dequeued)
        {
            received_nodes += dequeued;
            ringbuffer_cnt -= dequeued;

            for (size_t i = 0; i != dequeued; ++i)
            {
                bool erased = working_set.erase(output_buffer[i]);
                assert(erased);
            }

            return true;
        }
        else
            return false;
    }

    boost::atomic<bool> running;

    void get(void)
    {
        for(;;)
        {
            bool success = get_elements();
            if (not running and not success)
                return;
        }
    }

    void run(void)
    {
        running = true;

        thread reader(boost::bind(&ringbuffer_tester_buffering::get, this));
        thread writer(boost::bind(&ringbuffer_tester_buffering::add, this));
        cout << "reader and writer threads created" << endl;

        writer.join();
        cout << "writer threads joined. waiting for readers to finish" << endl;

        running = false;
        reader.join();

        BOOST_REQUIRE_EQUAL(received_nodes, nodes_per_thread);
        BOOST_REQUIRE_EQUAL(ringbuffer_cnt, 0);
        BOOST_REQUIRE(sf.empty());
        BOOST_REQUIRE(working_set.count_nodes() == 0);
    }
};

BOOST_AUTO_TEST_CASE( ringbuffer_test_buffering )
{
    ringbuffer_tester_buffering test1;
    test1.run();
}

ext: cpp


text:
/*
 *  Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License
 */
/*
 * @file       test_encryption-scheme.cpp
 * @author     Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
 * @version    1.0
 */

#include <boost/test/unit_test.hpp>
#include <boost/test/results_reporter.hpp>

#include <scheme-test.h>

using namespace CKM;

namespace {
// this is done to limit the amount of code included in binary
const int OLD_ENC_SCHEME  = 0;
const int NEW_ENC_SCHEME  = 1;
} // namespace anonymous

BOOST_AUTO_TEST_SUITE(ENCRYPTION_SCHEME_TEST)

// Test database should have the old scheme
BOOST_AUTO_TEST_CASE(T010_Check_old_scheme) {
    SchemeTest test;
    test.RestoreDb();

    ItemFilter filter;
    test.CheckSchemeVersion(filter, OLD_ENC_SCHEME);
}

// Newly written data should use the new scheme
BOOST_AUTO_TEST_CASE(T020_Check_new_scheme) {
    SchemeTest test;
    test.RemoveUserData();
    test.FillDb();

    ItemFilter filter;
    test.CheckSchemeVersion(filter, NEW_ENC_SCHEME);
}

BOOST_AUTO_TEST_CASE(T030_Remove_old_scheme) {
    SchemeTest test;
    test.RestoreDb();
    test.RemoveAll();

    size_t aliases = test.CountObjects();
    BOOST_REQUIRE_MESSAGE(aliases == 0, "All aliases should be removed");
}

BOOST_AUTO_TEST_CASE(T040_Remove_new_scheme) {
    SchemeTest test;
    test.RemoveUserData();
    test.FillDb();
    test.RemoveAll();

    size_t aliases = test.CountObjects();
    BOOST_REQUIRE_MESSAGE(aliases == 0, "All aliases should be removed");
}

// Reading old db should reencrypt objects with new scheme
BOOST_AUTO_TEST_CASE(T100_Read) {
    SchemeTest test;
    test.RestoreDb();
    test.ReadAll();

    ItemFilter filter;
    filter.exportableOnly = true;
    test.CheckSchemeVersion(filter, NEW_ENC_SCHEME);
}

BOOST_AUTO_TEST_CASE(T110_Count_objects_after_read) {
    SchemeTest test;
    test.RestoreDb();
    size_t orig = test.CountObjects();
    BOOST_REQUIRE_MESSAGE(orig > 0, "No objects in db");

    test.ReadAll();

    size_t current = test.CountObjects();
    BOOST_REQUIRE_MESSAGE(current == orig,
                          "Original number of objects: " << orig << " Current: " << current);
}

// Reading old db with incorrect passwords should leave the scheme unchanged
BOOST_AUTO_TEST_CASE(T120_Read_wrong_pass) {
    SchemeTest test;
    test.RestoreDb();
    test.ReadAll(true);

    ItemFilter filter;
    test.CheckSchemeVersion(filter, OLD_ENC_SCHEME);
}

// Signing/verification should reencrypt objects with new scheme
BOOST_AUTO_TEST_CASE(T200_SignVerify) {
    SchemeTest test;
    test.RestoreDb();
    test.SignVerify();

    ItemFilter filter(DataType::KEY_RSA_PUBLIC, DataType::KEY_RSA_PRIVATE);
    test.CheckSchemeVersion(filter, NEW_ENC_SCHEME);
}

// Encryption/decryption should reencrypt objects with new scheme
BOOST_AUTO_TEST_CASE(T210_EncryptDecrypt) {
    SchemeTest test;
    test.RestoreDb();
    test.EncryptDecrypt();

    ItemFilter filter1(DataType::KEY_RSA_PUBLIC, DataType::KEY_RSA_PRIVATE);
    test.CheckSchemeVersion(filter1, NEW_ENC_SCHEME);

    ItemFilter filter2(DataType::KEY_AES);
    test.CheckSchemeVersion(filter2, NEW_ENC_SCHEME);
}

// Chain creation should reencrypt objects with new scheme
BOOST_AUTO_TEST_CASE(T220_CreateChain) {
    SchemeTest test;
    test.RestoreDb();
    test.CreateChain();

    // non exportable certificates and certificates protected with passwords can't be used for chain
    // creation
    ItemFilter filter1(DataType::CERTIFICATE);
    filter1.exportableOnly = true;
    filter1.noPassword = true;
    test.CheckSchemeVersion(filter1, NEW_ENC_SCHEME);

    ItemFilter filter2(DataType::CHAIN_CERT_0, DataType::CHAIN_CERT_15);
    filter2.exportableOnly = true;
    filter2.noPassword = true;
    test.CheckSchemeVersion(filter2, NEW_ENC_SCHEME);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: Samsung/ckm

max_issues_repo_name: Samsung/ckm

max_forks_repo_name: Samsung/ckm


text:
#include <cstring>
#include <array>
#include <stdexcept>
#include <string>
#include <tuple>
#include <boost/algorithm/string.hpp>
#include <gtest/gtest.h>
#include <ka/conceptpredicate.hpp>
#include <ka/errorhandling.hpp>
#include <ka/scoped.hpp>
#include <ka/unit.hpp>
#include <qi/clock.hpp>
#include "test_qilog.hpp"
#include "../../src/log_p.hpp"

struct boost_error_t : boost::exception
{
  std::string msg;
  boost_error_t(std::string s = {}) : msg(std::move(s))
  {
  }
  std::ostream& operator<<(std::ostream& o) const
  {
    return o << "BoostError{\"" << msg << "\"}";
  }
};

namespace
{
  using qi::LogLevel;

  template<LogLevel L>
  using Constant = std::integral_constant<LogLevel, L>;

  // For a given log level, `ExceptionLog` type and its corresponding alias.
#define QI_DERIVE_EXCEPTIONLOG_TYPES(LOG_LEVEL)              \
  qi::ExceptionLog<qi::LogLevel_ ## LOG_LEVEL, std::string>, \
  qi::ExceptionLog ## LOG_LEVEL<std::string>

// Used to avoid finishing the type list with an extraneous comma.
#define QI_TEST_COMMA

  using ExceptionLogTypes = testing::Types<
#ifndef NO_QI_SILENT
    QI_TEST_COMMA QI_DERIVE_EXCEPTIONLOG_TYPES(Silent)
# undef QI_TEST_COMMA
# define QI_TEST_COMMA ,
#endif

#ifndef NO_QI_FATAL
    QI_TEST_COMMA QI_DERIVE_EXCEPTIONLOG_TYPES(Fatal)
# undef QI_TEST_COMMA
# define QI_TEST_COMMA ,
#endif

#ifndef NO_QI_ERROR
    QI_TEST_COMMA QI_DERIVE_EXCEPTIONLOG_TYPES(Error)
# undef QI_TEST_COMMA
# define QI_TEST_COMMA ,
#endif

#ifndef NO_QI_WARNING
    QI_TEST_COMMA QI_DERIVE_EXCEPTIONLOG_TYPES(Warning)
# undef QI_TEST_COMMA
# define QI_TEST_COMMA ,
#endif

#ifndef NO_QI_INFO
    QI_TEST_COMMA QI_DERIVE_EXCEPTIONLOG_TYPES(Info)
# undef QI_TEST_COMMA
# define QI_TEST_COMMA ,
#endif

#ifndef NO_QI_VERBOSE
    QI_TEST_COMMA QI_DERIVE_EXCEPTIONLOG_TYPES(Verbose)
# undef QI_TEST_COMMA
# define QI_TEST_COMMA ,
#endif

#if !defined(NO_QI_DEBUG) && !defined(NDEBUG)
    QI_TEST_COMMA QI_DERIVE_EXCEPTIONLOG_TYPES(Debug)
# undef QI_TEST_COMMA
# define QI_TEST_COMMA ,
#endif
  >;

#undef QI_TEST_COMMA
#undef QI_DERIVE_EXCEPTIONLOG_TYPES

  template<typename T>
  struct TestExceptionLogRegular : ::testing::Test
  {
  };
}

TYPED_TEST_SUITE(TestExceptionLogRegular, ExceptionLogTypes);

TYPED_TEST(TestExceptionLogRegular, Basic)
{
  using F = TypeParam;
  // This test is partial but representative.
  ASSERT_TRUE(ka::is_regular(
    {F{"a", "a"}, F{"a", "b"}, F{"b", "b"}, F{"ab", "b"}}));
}

namespace
{
  // For a given log level, sets all combinations of `ExceptionLog` types
  // (canonical and alias) and exception types (standard, boost, unknown).
  // Note: Unknown exception type is represented by `ka::unit_t`.
#define QI_DERIVE_LOG_TEST_TYPES(LOG_LEVEL)                                                       \
  std::tuple<Constant<qi::LogLevel_ ## LOG_LEVEL>, qi::ExceptionLog<qi::LogLevel_ ## LOG_LEVEL, std::string>, std::runtime_error>, \
  std::tuple<Constant<qi::LogLevel_ ## LOG_LEVEL>, qi::ExceptionLog<qi::LogLevel_ ## LOG_LEVEL, std::string>, boost_error_t>, \
  std::tuple<Constant<qi::LogLevel_ ## LOG_LEVEL>, qi::ExceptionLog<qi::LogLevel_ ## LOG_LEVEL, std::string>, ka::unit_t>, \
  std::tuple<Constant<qi::LogLevel_ ## LOG_LEVEL>, qi::ExceptionLog ## LOG_LEVEL<std::string>, std::runtime_error>, \
  std::tuple<Constant<qi::LogLevel_ ## LOG_LEVEL>, qi::ExceptionLog ## LOG_LEVEL<std::string>, boost_error_t>, \
  std::tuple<Constant<qi::LogLevel_ ## LOG_LEVEL>, qi::ExceptionLog ## LOG_LEVEL<std::string>, ka::unit_t>

// Used to avoid finishing the type list with an extraneous comma.
#define QI_TEST_COMMA

  using LogCombinationTypes = testing::Types<
#ifndef NO_QI_SILENT
    QI_TEST_COMMA QI_DERIVE_LOG_TEST_TYPES(Silent)
# undef QI_TEST_COMMA
# define QI_TEST_COMMA ,
#endif

#ifndef NO_QI_FATAL
    QI_TEST_COMMA QI_DERIVE_LOG_TEST_TYPES(Fatal)
# undef QI_TEST_COMMA
# define QI_TEST_COMMA ,
#endif

#ifndef NO_QI_ERROR
    QI_TEST_COMMA QI_DERIVE_LOG_TEST_TYPES(Error)
# undef QI_TEST_COMMA
# define QI_TEST_COMMA ,
#endif

#ifndef NO_QI_WARNING
    QI_TEST_COMMA QI_DERIVE_LOG_TEST_TYPES(Warning)
# undef QI_TEST_COMMA
# define QI_TEST_COMMA ,
#endif

#ifndef NO_QI_INFO
    QI_TEST_COMMA QI_DERIVE_LOG_TEST_TYPES(Info)
# undef QI_TEST_COMMA
# define QI_TEST_COMMA ,
#endif

#ifndef NO_QI_VERBOSE
    QI_TEST_COMMA QI_DERIVE_LOG_TEST_TYPES(Verbose)
# undef QI_TEST_COMMA
# define QI_TEST_COMMA ,
#endif

#if !defined(NO_QI_DEBUG) && !defined(NDEBUG)
    QI_TEST_COMMA QI_DERIVE_LOG_TEST_TYPES(Debug)
# undef QI_TEST_COMMA
# define QI_TEST_COMMA ,
#endif
  >;

#undef QI_TEST_COMMA
#undef QI_DERIVE_LOG_TEST_TYPES

  template<typename T>
  struct TestExceptionLog : ::testing::Test
  {
  };

  // Calls an exception-handling procedure with the right exception.
  template<typename Proc>
  void call(Proc proc, ka::type_t<std::runtime_error>, std::string msg)
  {
    proc(std::runtime_error{std::move(msg)});
  }

  template<typename Proc>
  void call(Proc proc, ka::type_t<boost_error_t>, std::string msg)
  {
    proc(boost_error_t{std::move(msg)});
  }

  template<typename Proc>
  void call(Proc proc, ka::type_t<ka::unit_t>, const std::string&)
  {
    // This is the 'unknown exception' case, so there is no exception to provide
    // to the procedure.
    proc();
  }

  using StrPair = std::pair<std::string, std::string>;

  // Exception kind and message that are expected in logs.
  StrPair str(ka::type_t<std::runtime_error>, std::string msg)
  {
    return {"standard exception", std::move(msg)};
  }

  StrPair str(ka::type_t<boost_error_t>, const std::string&)
  {
    // No expected message, because `boost` won't provide it in this test
    // context ("no known throw location"-like reason).
    return {"boost exception", ""};
  }

  StrPair str(ka::type_t<ka::unit_t>, const std::string&)
  {
    return {"unknown exception", ""};
  }

  // Begin and end variants that handle standard containers and C-strings.
  template<typename C>
  auto myBegin(const C& c) -> decltype(std::begin(c))
  {
    return std::begin(c);
  }

  template<typename C>
  auto myEnd(const C& c) -> decltype(std::end(c))
  {
    return std::end(c);
  }

  auto myBegin(const char* c) -> const char*
  {
    return c;
  }

  auto myEnd(const char* c) -> const char*
  {
    return c + std::strlen(c);
  }

  // True iff `c0` contains `c1`.
  template<typename C0, typename C1>
  bool contains(const C0& c0, const C1& c1)
  {
    return std::search(myBegin(c0), myEnd(c0), myBegin(c1), myEnd(c1)) != myEnd(c0);
  }

  // GTest predicate that matches a log.
  // Checks that the log contains the expected components.
  template<typename Exception>
  struct LogApproxMatcher
  {
    std::string _logPrefix, _exceptionMsg;

    template<typename S>
    bool MatchAndExplain(const S& s,
                         ::testing::MatchResultListener* /* listener */) const
    {
      std::string except, msg;
      std::tie(except, msg) = str(ka::type_t<Exception>{}, std::move(_exceptionMsg));
      return contains(s, _logPrefix)
          && contains(s, except)
          && contains(s, msg);
    }
    void DescribeTo(::std::ostream* os) const
    {
      *os << "has right format.";
    }
    void DescribeNegationTo(::std::ostream* os) const
    {
      *os << "has not right format.";
    }
  };
} // namespace

TYPED_TEST_SUITE(TestExceptionLog, LogCombinationTypes);

// Expected: Log is done, in the right log level, with (approximately) the right
// message.
TYPED_TEST(TestExceptionLog, Basic)
{
  // Extract type parameters.
  using ConstantLogLevel = typename std::tuple_element<0, TypeParam>::type;
  using ExceptionLog = typename std::tuple_element<1, TypeParam>::type;
  using Exception = typename std::tuple_element<2, TypeParam>::type;

  // Setup log handler to avoid any unwanted filtering (hence, set `debug` log level).
  MockLogHandler handler("no more cookie");
  qi::log::setLogLevel(qi::LogLevel_Debug, handler.id);

  // Set expected log message components.
  const auto logCat = "cat";
  const auto logPrefix = "prefix";
  const auto exceptionMsg = "this is not a string";

  // Expect a log only if not 'silent'.
  using ::testing::Exactly;
  using ::testing::StrEq;
  auto LogApproxEq = [](std::string prefix, std::string msg) {
    return ::testing::MakePolymorphicMatcher(
      LogApproxMatcher<Exception>{std::move(prefix), std::move(msg)}
    );
  };
  static const auto logLevel = ConstantLogLevel::value;
  if (logLevel != qi::LogLevel_Silent)
  {
    EXPECT_CALL(handler, log(
      logLevel,
      StrEq(logCat),
      LogApproxEq(logPrefix, exceptionMsg))).Times(Exactly(1));
  }

  // Call the procedure that logs the exception.
  call(ExceptionLog{logCat, logPrefix}, ka::type_t<Exception>{}, exceptionMsg);
}

max_stars_repo_name: Maelic/libqi

max_issues_repo_name: Maelic/libqi

max_forks_repo_name: Maelic/libqi


text:
#include "util/coordinate_calculation.hpp"

#include "util/string_util.hpp"
#include "util/trigonometry_table.hpp"

#include <boost/assert.hpp>
#include <boost/math/constants/constants.hpp>

#include <cmath>

#include <limits>

namespace osrm
{
namespace util
{
namespace coordinate_calculation
{

double haversineDistance(const int lat1, const int lon1, const int lat2, const int lon2)
{
    BOOST_ASSERT(lat1 != std::numeric_limits<int>::min());
    BOOST_ASSERT(lon1 != std::numeric_limits<int>::min());
    BOOST_ASSERT(lat2 != std::numeric_limits<int>::min());
    BOOST_ASSERT(lon2 != std::numeric_limits<int>::min());
    const double lt1 = lat1 / COORDINATE_PRECISION;
    const double ln1 = lon1 / COORDINATE_PRECISION;
    const double lt2 = lat2 / COORDINATE_PRECISION;
    const double ln2 = lon2 / COORDINATE_PRECISION;
    const double dlat1 = lt1 * (RAD);

    const double dlong1 = ln1 * (RAD);
    const double dlat2 = lt2 * (RAD);
    const double dlong2 = ln2 * (RAD);

    const double dlong = dlong1 - dlong2;
    const double dlat = dlat1 - dlat2;

    const double aharv = std::pow(std::sin(dlat / 2.0), 2.0) +
                         std::cos(dlat1) * std::cos(dlat2) * std::pow(std::sin(dlong / 2.), 2);
    const double charv = 2. * std::atan2(std::sqrt(aharv), std::sqrt(1.0 - aharv));
    return EARTH_RADIUS * charv;
}

double haversineDistance(const FixedPointCoordinate coordinate_1,
                         const FixedPointCoordinate coordinate_2)
{
    return haversineDistance(coordinate_1.lat, coordinate_1.lon, coordinate_2.lat,
                             coordinate_2.lon);
}

double greatCircleDistance(const FixedPointCoordinate coordinate_1,
                           const FixedPointCoordinate coordinate_2)
{
    return greatCircleDistance(coordinate_1.lat, coordinate_1.lon, coordinate_2.lat,
                               coordinate_2.lon);
}

double greatCircleDistance(const int lat1, const int lon1, const int lat2, const int lon2)
{
    BOOST_ASSERT(lat1 != std::numeric_limits<int>::min());
    BOOST_ASSERT(lon1 != std::numeric_limits<int>::min());
    BOOST_ASSERT(lat2 != std::numeric_limits<int>::min());
    BOOST_ASSERT(lon2 != std::numeric_limits<int>::min());

    const double float_lat1 = (lat1 / COORDINATE_PRECISION) * RAD;
    const double float_lon1 = (lon1 / COORDINATE_PRECISION) * RAD;
    const double float_lat2 = (lat2 / COORDINATE_PRECISION) * RAD;
    const double float_lon2 = (lon2 / COORDINATE_PRECISION) * RAD;

    const double x_value = (float_lon2 - float_lon1) * std::cos((float_lat1 + float_lat2) / 2.0);
    const double y_value = float_lat2 - float_lat1;
    return std::hypot(x_value, y_value) * EARTH_RADIUS;
}

double perpendicularDistance(const FixedPointCoordinate source_coordinate,
                             const FixedPointCoordinate target_coordinate,
                             const FixedPointCoordinate query_location)
{
    double ratio;
    FixedPointCoordinate nearest_location;

    return perpendicularDistance(source_coordinate, target_coordinate, query_location,
                                 nearest_location, ratio);
}

double perpendicularDistance(const FixedPointCoordinate segment_source,
                             const FixedPointCoordinate segment_target,
                             const FixedPointCoordinate query_location,
                             FixedPointCoordinate &nearest_location,
                             double &ratio)
{
    using namespace coordinate_calculation;

    return perpendicularDistanceFromProjectedCoordinate(
        segment_source, segment_target, query_location,
        {mercator::latToY(query_location.lat / COORDINATE_PRECISION),
         query_location.lon / COORDINATE_PRECISION},
        nearest_location, ratio);
}

double
perpendicularDistanceFromProjectedCoordinate(const FixedPointCoordinate source_coordinate,
                                             const FixedPointCoordinate target_coordinate,
                                             const FixedPointCoordinate query_location,
                                             const std::pair<double, double> projected_coordinate)
{
    double ratio;
    FixedPointCoordinate nearest_location;

    return perpendicularDistanceFromProjectedCoordinate(source_coordinate, target_coordinate,
                                                        query_location, projected_coordinate,
                                                        nearest_location, ratio);
}

double
perpendicularDistanceFromProjectedCoordinate(const FixedPointCoordinate segment_source,
                                             const FixedPointCoordinate segment_target,
                                             const FixedPointCoordinate query_location,
                                             const std::pair<double, double> projected_coordinate,
                                             FixedPointCoordinate &nearest_location,
                                             double &ratio)
{
    using namespace coordinate_calculation;

    BOOST_ASSERT(query_location.IsValid());

    // initialize values
    const double x = projected_coordinate.first;
    const double y = projected_coordinate.second;
    const double a = mercator::latToY(segment_source.lat / COORDINATE_PRECISION);
    const double b = segment_source.lon / COORDINATE_PRECISION;
    const double c = mercator::latToY(segment_target.lat / COORDINATE_PRECISION);
    const double d = segment_target.lon / COORDINATE_PRECISION;
    double p, q /*,mX*/, new_y;
    if (std::abs(a - c) > std::numeric_limits<double>::epsilon())
    {
        const double m = (d - b) / (c - a); // slope
        // Projection of (x,y) on line joining (a,b) and (c,d)
        p = ((x + (m * y)) + (m * m * a - m * b)) / (1.0 + m * m);
        q = b + m * (p - a);
    }
    else
    {
        p = c;
        q = y;
    }
    new_y = (d * p - c * q) / (a * d - b * c);

    // discretize the result to coordinate precision. it's a hack!
    if (std::abs(new_y) < (1.0 / COORDINATE_PRECISION))
    {
        new_y = 0.0;
    }

    // compute ratio
    ratio = static_cast<double>((p - new_y * a) /
                                c); // These values are actually n/m+n and m/m+n , we need
    // not calculate the explicit values of m an n as we
    // are just interested in the ratio
    if (std::isnan(ratio))
    {
        ratio = (segment_target == query_location ? 1.0 : 0.0);
    }
    else if (std::abs(ratio) <= std::numeric_limits<double>::epsilon())
    {
        ratio = 0.0;
    }
    else if (std::abs(ratio - 1.0) <= std::numeric_limits<double>::epsilon())
    {
        ratio = 1.0;
    }

    // compute nearest location
    BOOST_ASSERT(!std::isnan(ratio));
    if (ratio <= 0.0)
    {
        nearest_location = segment_source;
    }
    else if (ratio >= 1.0)
    {
        nearest_location = segment_target;
    }
    else
    {
        // point lies in between
        nearest_location.lat = static_cast<int>(mercator::yToLat(p) * COORDINATE_PRECISION);
        nearest_location.lon = static_cast<int>(q * COORDINATE_PRECISION);
    }
    BOOST_ASSERT(nearest_location.IsValid());

    const double approximate_distance = greatCircleDistance(query_location, nearest_location);
    BOOST_ASSERT(0.0 <= approximate_distance);
    return approximate_distance;
}

double degToRad(const double degree)
{
    using namespace boost::math::constants;
    return degree * (pi<double>() / 180.0);
}

double radToDeg(const double radian)
{
    using namespace boost::math::constants;
    return radian * (180.0 * (1. / pi<double>()));
}

double bearing(const FixedPointCoordinate first_coordinate,
               const FixedPointCoordinate second_coordinate)
{
    const double lon_diff =
        second_coordinate.lon / COORDINATE_PRECISION - first_coordinate.lon / COORDINATE_PRECISION;
    const double lon_delta = degToRad(lon_diff);
    const double lat1 = degToRad(first_coordinate.lat / COORDINATE_PRECISION);
    const double lat2 = degToRad(second_coordinate.lat / COORDINATE_PRECISION);
    const double y = std::sin(lon_delta) * std::cos(lat2);
    const double x =
        std::cos(lat1) * std::sin(lat2) - std::sin(lat1) * std::cos(lat2) * std::cos(lon_delta);
    double result = radToDeg(std::atan2(y, x));
    while (result < 0.0)
    {
        result += 360.0;
    }

    while (result >= 360.0)
    {
        result -= 360.0;
    }
    return result;
}

double computeAngle(const FixedPointCoordinate first,
                    const FixedPointCoordinate second,
                    const FixedPointCoordinate third)
{
    using namespace boost::math::constants;
    using namespace coordinate_calculation;

    const double v1x = (first.lon - second.lon) / COORDINATE_PRECISION;
    const double v1y = mercator::latToY(first.lat / COORDINATE_PRECISION) -
                       mercator::latToY(second.lat / COORDINATE_PRECISION);
    const double v2x = (third.lon - second.lon) / COORDINATE_PRECISION;
    const double v2y = mercator::latToY(third.lat / COORDINATE_PRECISION) -
                       mercator::latToY(second.lat / COORDINATE_PRECISION);

    double angle = (atan2_lookup(v2y, v2x) - atan2_lookup(v1y, v1x)) * 180. / pi<double>();

    while (angle < 0.)
    {
        angle += 360.;
    }

    return angle;
}

namespace mercator
{
double yToLat(const double value)
{
    using namespace boost::math::constants;

    return 180. * (1. / pi<long double>()) *
           (2. * std::atan(std::exp(value * pi<double>() / 180.)) - half_pi<double>());
}

double latToY(const double latitude)
{
    using namespace boost::math::constants;

    return 180. * (1. / pi<double>()) *
           std::log(std::tan((pi<double>() / 4.) + latitude * (pi<double>() / 180.) / 2.));
}
} // ns mercato // ns mercatorr
} // ns coordinate_calculation
} // ns util
} // ns osrm

max_stars_repo_name: mortada/osrm-backend

max_issues_repo_name: mortada/osrm-backend

max_forks_repo_name: mortada/osrm-backend


text:
#include "xthread.h"
#include "watch.h"
#include <boost/thread/tss.hpp>

namespace global
{
	using namespace std;

	class quick_int_stack
	{
	public:

		quick_int_stack()
			: top_pos(-1)
		{
		}

		bool empty()
		{
			return (top_pos == -1);
		}

		int top()
		{
			return elements[top_pos];
		}

		void push(int i)
		{
			elements[++ top_pos] = i;
		}

		void pop()
		{
			-- top_pos;
		}

	private:

		enum {MAX_STACK_ELEMENT = 1024};
		int elements[MAX_STACK_ELEMENT];
		int top_pos;
	};

	boost::thread_specific_ptr<global::quick_int_stack> locks_hold_by_current_thread;

	void xrecursive_mutex::lock()
	{
		mutex.lock();
		++ recursion_count;
		if (pri_level != NOCARE_PRIMARY_LEVEL)
		{
			if (recursion_count == 1)
			{
				quick_int_stack* pri_levels = locks_hold_by_current_thread.get();
				if (pri_levels == NULL)
				{
					pri_levels = new quick_int_stack();
					locks_hold_by_current_thread.reset(pri_levels);
				}
				if (!pri_levels->empty() && pri_levels->top() >= pri_level)
				{	//	wrong order, lock failed
					-- recursion_count;
					mutex.unlock();
					XASSERT(false);
				}
				pri_levels->push(pri_level);
			}
		}
	}

	void xrecursive_mutex::unlock()
	{
		quick_int_stack* pri_levels;
		if (pri_level != NOCARE_PRIMARY_LEVEL && recursion_count == 1 &&
			((pri_levels = locks_hold_by_current_thread.get()) != NULL))
		{
			if (!pri_levels->empty()
				&& (pri_levels->top() == pri_level))
			{
				pri_levels->pop();
			}
			else
			{
				stacktrace::call_stack st;
				LErr(st.to_string());
			}
		}
		-- recursion_count;
		mutex.unlock();
	}

	void condition_variable_recursive_mutex::check(xrecursive_mutex& mtx)
	{
		if (mtx.pri_level != xrecursive_mutex::NOCARE_PRIMARY_LEVEL)
		{
			quick_int_stack* pri_levels = locks_hold_by_current_thread.get();
			XASSERT((pri_levels != NULL) && (!pri_levels->empty()) &&
				(pri_levels->top() == mtx.pri_level));
		}
	}

	void condition_variable_recursive_mutex::wait(xrecursive_mutex& mtx)
	{
		check(mtx);
		int extra_lock = mtx.get_recursion_count() - 1;
		for (int i = 0; i < extra_lock; i++)
		{
			mtx.unlock();
		}
		XASSERT(mtx.get_recursion_count() == 1);
		cond.wait(mtx);
		for (int i = 0; i < extra_lock; i++)
		{
			mtx.lock();
		}
	}

	//false if the call is returning because the time period specified by duration has elapsed, true otherwise.
	bool condition_variable_recursive_mutex::timed_wait(xrecursive_mutex& mtx, int duration)
	{
		check(mtx);
		int extra_lock = mtx.get_recursion_count() - 1;
		bool ret = false;
		for (int i = 0; i < extra_lock; i++)
		{
			mtx.unlock();
		}
		XASSERT(mtx.get_recursion_count() == 1);
		ret = cond.timed_wait(mtx, boost::posix_time::millisec(duration));
		for (int i = 0; i < extra_lock; i++)
		{
			mtx.lock();
		}
		return ret;
	}

	void condition_variable_recursive_mutex::notify_one()
	{
		cond.notify_one();
	}

	void condition_variable_recursive_mutex::notify_all()
	{
		cond.notify_all();
	}

}

max_stars_repo_name: netaudio/TCP-UDP-Proxy

max_issues_repo_name: netaudio/TCP-UDP-Proxy

max_forks_repo_name: netaudio/TCP-UDP-Proxy


text:
// Copyright 2016, Tobias Hermann.
// https://github.com/Dobiasd/frugally-deep
// Distributed under the MIT License.
// (See accompanying LICENSE file or at
//  https://opensource.org/licenses/MIT)

#pragma once

#if defined(__GNUC__) || defined(__GNUG__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wctor-dtor-privacy"
#pragma GCC diagnostic ignored "-Wold-style-cast"
#pragma GCC diagnostic ignored "-Wsign-conversion"
#pragma GCC diagnostic ignored "-Weffc++"
#pragma GCC diagnostic ignored "-Wconversion"
#pragma GCC diagnostic ignored "-Wshadow"
#endif
#if defined _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4706)
#pragma warning(disable : 4996)
#endif
#include <Eigen/Core>
#if defined _MSC_VER
#pragma warning(pop)
#endif
#if defined(__GNUC__) || defined(__GNUG__)
#pragma GCC diagnostic pop
#endif

#include <fplus/fplus.hpp>

#include <cmath>
#include <memory>
#include <vector>
#include <string>
#include <stdexcept>

#if defined(__GNUC__) || defined(__GNUG__)
#define FDEEP_FORCE_INLINE __attribute__((always_inline)) inline
#elif defined(_MSC_VER)
#define FDEEP_FORCE_INLINE __forceinline
#else
#define FDEEP_FORCE_INLINE inline
#endif

namespace fdeep { namespace internal
{

inline std::runtime_error error(const std::string& error)
{
    return std::runtime_error(error);
}

inline void raise_error(const std::string& msg)
{
    throw error(msg);
}

inline void assertion(bool cond, const std::string& error)
{
    if (!cond)
    {
        raise_error(error);
    }
}

#ifdef FDEEP_FLOAT_TYPE
    typedef FDEEP_FLOAT_TYPE float_type;
#else
    typedef float float_type;
#endif

#if EIGEN_VERSION_AT_LEAST(3,3,0)
    typedef Eigen::Index EigenIndex;
#else
    typedef Eigen::DenseIndex EigenIndex;
#endif

typedef std::vector<float_type> float_vec;
typedef fplus::shared_ref<float_vec> shared_float_vec;

using ColMajorMatrixXf = Eigen::Matrix<float_type, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor>;
using RowMajorMatrixXf = Eigen::Matrix<float_type, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>;
using MappedRowMajorMatrixXf = Eigen::Map<RowMajorMatrixXf, Eigen::Unaligned>;

} } // namespace fdeep, namespace internal


text:
// Copyright 2018 Hans Dembinski
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/core/lightweight_test.hpp>
#include <boost/histogram/axis/option.hpp>
#include <iostream>

using namespace boost::histogram::axis;

template <unsigned N, unsigned M>
bool operator==(option::bitset<N>, option::bitset<M>) {
  return N == M;
}

template <unsigned N>
std::ostream& operator<<(std::ostream& os, option::bitset<N>) {
  os << "underflow " << static_cast<bool>(N & option::underflow) << " "
     << "overflow " << static_cast<bool>(N & option::overflow) << " "
     << "circular " << static_cast<bool>(N & option::circular) << " "
     << "growth " << static_cast<bool>(N & option::growth);
  return os;
}

int main() {
  using namespace option;
  using uoflow = decltype(underflow | overflow);
  constexpr auto uoflow_growth = uoflow{} | growth;

  BOOST_TEST_EQ(uoflow::value, underflow | overflow);
  BOOST_TEST_EQ(underflow | overflow, overflow | underflow);

  BOOST_TEST(underflow.test(underflow));
  BOOST_TEST_NOT(underflow.test(overflow));
  BOOST_TEST(uoflow::test(underflow));
  BOOST_TEST(uoflow::test(overflow));
  BOOST_TEST_NOT(uoflow::test(circular));
  BOOST_TEST_NOT(uoflow::test(growth));
  BOOST_TEST(uoflow_growth.test(underflow));
  BOOST_TEST(uoflow_growth.test(overflow));
  BOOST_TEST(uoflow_growth.test(growth));
  BOOST_TEST_NOT(uoflow_growth.test(circular));

  BOOST_TEST_EQ(uoflow_growth & uoflow_growth, uoflow_growth);
  BOOST_TEST_EQ(uoflow_growth & growth, growth);
  BOOST_TEST_EQ(uoflow_growth & uoflow{}, uoflow::value);

  BOOST_TEST_EQ(uoflow_growth - growth, uoflow{});
  BOOST_TEST_EQ(uoflow_growth - uoflow{}, growth);
  BOOST_TEST_EQ(uoflow_growth - underflow, growth | overflow);

  return boost::report_errors();
}


text:
/*
 * movestest.cpp
 *
 *  Created on: Jun 12, 2011
 *      Author: joe
 */

#define BOOST_TEST_MODULE Moves
#define BOOST_TEST_MAIN
#include "../src/config.h"
#ifdef USE_DYNAMIC_UNIT_TEST
#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#else
#include <boost/test/included/unit_test.hpp>
#endif
#include <boost/optional.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <cstdio>
#include <vector>
#include "logic/ELSyntax.h"
#include "logic/Moves.h"
#include "inference/MaxWalkSat.h"
#include "TestUtilities.h"

BOOST_AUTO_TEST_CASE(liquidLitMovesTest) {
    std::string facts("P(a,b) @ [1:5]\n"
            "S(a) @ [1:2]\n"
            "S(a) @ [4:4]\n");
    std::string formulas("1: [Q(a,b) ]\n"
            "1: [!Q(a,b)]\n"
            "1: [!P(a,b)]\n"
            "1: [S(a)]");

    Domain d = loadDomainWithStreams(facts, formulas);
    d.setDontModifyObsPreds(false);
    std::vector<ELSentence> formSet(d.formulas_begin(), d.formulas_end());
    ELSentence form1 = formSet.at(0);
    ELSentence form2 = formSet.at(1);
    ELSentence form3 = formSet.at(2);
    ELSentence form4 = formSet.at(3);

    std::vector<Move> moves;
    Move move;

    BOOST_CHECK_EQUAL(d.defaultModel().toString(),  "P(a, b) @ {[1:5]}\n"
                                                    "S(a) @ {[1:2], [4:4]}\n");
    BOOST_CHECK_EQUAL(d.maxInterval(), Interval(1,5));

    // initialize seed
    boost::mt19937 rng;
    moves = findMovesFor(d, d.defaultModel(), form1, rng);
    BOOST_REQUIRE_EQUAL(moves.size(), 1);
    move = moves[0];
    BOOST_CHECK_EQUAL(move.toString(), "toAdd: {Q(a, b) @ [1:5]}, toDel: {}");

    moves = findMovesFor(d, d.defaultModel(), form2, rng);
    BOOST_CHECK_EQUAL(moves.size(), 0);

    moves = findMovesFor(d, d.defaultModel(), form3, rng);
    BOOST_REQUIRE_EQUAL(moves.size(), 1);
    move = moves[0];
    BOOST_CHECK_EQUAL(move.toString(), "toAdd: {}, toDel: {P(a, b) @ [1:5]}");

    moves = findMovesFor(d, d.defaultModel(), form4, rng);
    BOOST_REQUIRE_EQUAL(moves.size(), 1);
    move = moves[0];
    BOOST_CHECK_EQUAL(move.toString(), "toAdd: {S(a) @ [5:5]}, toDel: {}");
}

BOOST_AUTO_TEST_CASE(liquidConjMovesTest) {
    std::string facts("P(a,b) @ [1:5]\n"
            "S(a) @ [1:2]\n");
    std::string formulas("1: [P(a,b) & !S(a)]");

    Domain d = loadDomainWithStreams(facts, formulas);
    d.setMaxInterval(Interval(1,10));
    d.setDontModifyObsPreds(false);
    ELSentence form1 = *d.formulas_begin();

    boost::mt19937 rng;

    Move move;
    move = findMovesFor(d, d.defaultModel(), form1, rng)[0];
    BOOST_CHECK_EQUAL(move.toString(), "toAdd: {P(a, b) @ [6:10]}, toDel: {S(a) @ [6:10]}" );
}

BOOST_AUTO_TEST_CASE(liquidDisjMovesTest) {
    std::string facts("P(a,b) @ [1:5]\n"
            "S(a) @ [1:2]\n");
    std::string formulas("1: [!P(a,b) v S(a)]");

    Domain d = loadDomainWithStreams(facts, formulas);
    d.setMaxInterval(Interval(1,10));
    d.setDontModifyObsPreds(false);
    ELSentence form1 = *d.formulas_begin();
    boost::mt19937 rng;

    std::vector<Move> moves = findMovesFor(d, d.defaultModel(), form1, rng);
    BOOST_REQUIRE_EQUAL(moves.size(), 2);
    BOOST_CHECK_EQUAL(moves[0].toString(), "toAdd: {}, toDel: {P(a, b) @ [3:5]}" );
    BOOST_CHECK_EQUAL(moves[1].toString(), "toAdd: {S(a) @ [3:5]}, toDel: {}" );

}

BOOST_AUTO_TEST_CASE(pelCNFAtomTest) {
    std::string facts("P(a,b) @ [1:5]\n"
            "S(a) @ [1:2]\n");
    std::string formulas("1: S(a)");

    Domain d = loadDomainWithStreams(facts, formulas);
    d.setDontModifyObsPreds(false);
    ELSentence form1 = *d.formulas_begin();

    boost::mt19937 rng;

    std::vector<Move> moves = findMovesFor(d, d.defaultModel(), form1, rng);
    BOOST_CHECK_EQUAL(moves.size(), 1);
    BOOST_CHECK_EQUAL(moves[0].toString(), "toAdd: {S(a) @ [3:5]}, toDel: {}");
}

BOOST_AUTO_TEST_CASE(pelCNFNegAtomTest) {
    std::string facts("P(a,b) @ [1:5]\n"
            "S(a) @ [1:2]\n");
    std::string formulas("1: !S(a)");

    Domain d = loadDomainWithStreams(facts, formulas);
    d.setDontModifyObsPreds(false);
    ELSentence form1 = *d.formulas_begin();
    boost::mt19937 rng;

    std::vector<Move> moves = findMovesFor(d, d.defaultModel(), form1, rng);
    BOOST_REQUIRE_EQUAL(moves.size(), 1);
    BOOST_CHECK_EQUAL(moves[0].toString(), "toAdd: {}, toDel: {S(a) @ [1:2]}");
}

BOOST_AUTO_TEST_CASE(pelCNFDisjunctionTest) {
    std::string facts("P(a,b) @ [1:5]\n"
            "S(a) @ [1:2]\n");
    std::string formulas("1: [P(a,b) v S(a)]");

    Domain d = loadDomainWithStreams(facts, formulas);
    d.setMaxInterval(Interval(1,10));
    d.setDontModifyObsPreds(false);
    ELSentence form1 = *d.formulas_begin();

    boost::mt19937 rng;

    std::vector<Move> moves = findMovesFor(d, d.defaultModel(), form1, rng);
    BOOST_REQUIRE_EQUAL(moves.size(), 2);
    BOOST_CHECK_EQUAL(moves[0].toString(), "toAdd: {P(a, b) @ [6:10]}, toDel: {}");
    BOOST_CHECK_EQUAL(moves[1].toString(), "toAdd: {S(a) @ [6:10]}, toDel: {}");

}

BOOST_AUTO_TEST_CASE(pelCNFDiamondTestTest) {
    std::string facts("Huddle(a)  @ [2:2]\n"
            "Dig(a) @ [4:5]\n"
            "Spike(a) @ [6:6]\n");
    std::string formulas("1: Huddle(a) -> !(<>{>} [Dig(a) v Spike(a)])");

    Domain d = loadDomainWithStreams(facts, formulas);
    d.setDontModifyObsPreds(false);
    ELSentence form1 = *d.formulas_begin();
    boost::mt19937 rng;

    std::vector<Move> moves = findMovesFor(d, d.defaultModel(), form1, rng);
    BOOST_CHECK_EQUAL(moves.size(), 2);
    BOOST_CHECK_EQUAL(moves[0].toString(), "toAdd: {}, toDel: {Dig(a) @ [4:6], Spike(a) @ [4:6]}");
    BOOST_CHECK_EQUAL(moves[1].toString(), "toAdd: {}, toDel: {Huddle(a) @ [2:2]}");
}

BOOST_AUTO_TEST_CASE(pelCNFDiamondConjTest) {
    std::string facts(  "GoingUp(a) @ [1:1]\n"
                        "GoingDown(a) @ [3:3]\n"
                        "GoingDown(a) @ [5:5]\n"
                        "GoingUp(a) @ [8:8]\n"
    );
    std::string formulas("1: GoingDown(a) ^{<} GoingDown(a) -> <>{d} GoingUp(a)");

    Domain d = loadDomainWithStreams(facts, formulas);
    BOOST_CHECK_EQUAL(d.defaultModel().toString(),  "GoingDown(a) @ {[3:3], [5:5]}\n"
                                                    "GoingUp(a) @ {[1:1], [8:8]}\n");
    d.setDontModifyObsPreds(false);
    ELSentence form1 = *d.formulas_begin();
    SISet sat = form1.sentence()->dSatisfied(d.defaultModel(), d);
    std::cout << "sat = " << sat.toString() << std::endl;
    std::cout << "sat compliment is = " << sat.compliment().toString() << std::endl;

    boost::mt19937 rng;
    std::vector<Move> moves = findMovesFor(d, d.defaultModel(), form1, rng);
    BOOST_REQUIRE_EQUAL(moves.size(), 3);

    BOOST_CHECK_EQUAL(moves[0].toString(), "toAdd: {GoingUp(a) @ [4:4]}, toDel: {}");
    BOOST_CHECK_EQUAL(moves[1].toString(), "toAdd: {}, toDel: {GoingDown(a) @ [3:3]}");
    BOOST_CHECK_EQUAL(moves[2].toString(), "toAdd: {}, toDel: {GoingDown(a) @ [5:5]}");
}

BOOST_AUTO_TEST_CASE(pelCNFDisjLiqTest) {
    std::string facts("D-Driving(t1) @ [35:50]\n"
                      "HasTrack(p1,t1) @ [1:50]\n"
                      "Driving(p1) @ [35:50]");
    std::string formulas("1: [!Driving(p1)] v [HasTrack(p1, t1) ^ D-Driving(t1)]");

    Domain d = loadDomainWithStreams(facts, formulas);
    d.setDontModifyObsPreds(false);
    ELSentence form1 = *d.formulas_begin();
    SISet sat = form1.sentence()->dSatisfied(d.defaultModel(), d);
    BOOST_CHECK_EQUAL(sat.toString(), "{[1:34], [35:50]}");
}

BOOST_AUTO_TEST_CASE(maxWalkSatTest) {
    boost::mt19937 rng;

    std::string facts(  "D_P(a) @ [1:5]\n"
                        "D_P(b) @ [4:7]\n");
    std::string formulas(
                            "1: [D_P(a) -> P(a)]\n"
                            "1: [D_P(b) -> P(b)]\n"
                            "100: [(P(a) & !P(b)) v (P(b) & !P(a)) v (!P(a) & !P(b))]\n");

    Domain d = loadDomainWithStreams(facts, formulas);
    srand(7);
    Model init = d.defaultModel();
    MWSSolver solver(100, 0.5, &d);
    Model m = solver.run(rng, init);
    std::cout << m.toString() << std::endl;
}

BOOST_AUTO_TEST_CASE(maxWalkSatTestForm1mi) {
    std::string facts(  "P(a) @ [1:4]\n"
                        "P(b) @ [6:7]\n");
    std::string formulas("100: P(a) -> <>{mi} [P(a) v P(b)]\n");

    Domain d = loadDomainWithStreams(facts, formulas);
    d.setDontModifyObsPreds(false);
    boost::mt19937 rng;

    std::vector<Move> moves = findMovesFor(d, d.defaultModel(), *d.formulas_begin(), rng);
    BOOST_FOREACH(Move move, moves) {
        std::cout << "move: " << move.toString() << std::endl;
    }
}

BOOST_AUTO_TEST_CASE(maxWalkSatTestForm1m) {
    std::string facts(  "P(a) @ [1:4]\n"
                        "P(b) @ [6:7]\n");
    std::string formulas("100: P(b) -> <>{m} [P(a) v P(b)]\n");

    Domain d = loadDomainWithStreams(facts, formulas);
    d.setDontModifyObsPreds(false);
    boost::mt19937 rng;

    std::vector<Move> moves = findMovesFor(d, d.defaultModel(), *d.formulas_begin(), rng);
    BOOST_FOREACH(Move move, moves) {
        std::cout << "move: " << move.toString() << std::endl;
    }
}

BOOST_AUTO_TEST_CASE(maxWalkSatTestForm1f) {
    std::string facts(  "P(a) @ [1:4]\n"
                        "P(b) @ [6:7]\n");
    std::string formulas("100: P(b) -> <>{f} [P(a) v P(b)]\n");

    Domain d = loadDomainWithStreams(facts, formulas);
    d.setDontModifyObsPreds(false);
    boost::mt19937 rng;

    std::vector<Move> moves = findMovesFor(d, d.defaultModel(), *d.formulas_begin(), rng);
    BOOST_FOREACH(Move move, moves) {
        std::cout << "finish move: " << move.toString() << std::endl;
    }
}

BOOST_AUTO_TEST_CASE(maxWalkSatTestForm1fi) {
    std::string facts(  "P(a) @ [1:4]\n"
                        "P(a) @ [7:7]\n"
                        "P(b) @ [6:8]\n");
    std::string formulas("100: P(b) -> <>{fi} [P(a) v P(b)]\n");

    Domain d = loadDomainWithStreams(facts, formulas);
    d.setDontModifyObsPreds(false);
    boost::mt19937 rng;

    std::vector<Move> moves = findMovesFor(d, d.defaultModel(), *d.formulas_begin(), rng);
    BOOST_FOREACH(Move move, moves) {
        std::cout << "finish move: " << move.toString() << std::endl;
    }
}

BOOST_AUTO_TEST_CASE(maxWalkSatTestForm2) {
    std::string facts(  "P(a) @ [1:4]\n"
                        "P(b) @ [1:1]\n"
                        "P(b) @ [5:6]\n"
                        "P(c) @ [9:10]\n");
    std::string formulas("100: P(a) ; P(b) -> <>{mi} [P(b) v P(c)]\n");

    Domain d = loadDomainWithStreams(facts, formulas);
    d.setDontModifyObsPreds(false);
    boost::mt19937 rng;

    std::vector<Move> moves = findMovesFor(d, d.defaultModel(), *d.formulas_begin(), rng);
    BOOST_FOREACH(Move move, moves) {
        std::cout << "form2 move: " << move.toString() << std::endl;
    }
}

BOOST_AUTO_TEST_CASE(maxWalkSatTestForm3) {
    std::string facts(  "P(a) @ [1:3]\n"
                        "P(b) @ [1:8]\n"
                        "P(c) @ [4:5]\n"
                        "P(d) @ [6:8]");

    std::string formulas("100: P(b) -> !(P(a) ; P(c); P(d))\n");

    Domain d = loadDomainWithStreams(facts, formulas);
    d.setDontModifyObsPreds(false);
    boost::mt19937 rng;

    std::vector<Move> moves = findMovesFor(d, d.defaultModel(), *d.formulas_begin(), rng);
    BOOST_FOREACH(Move move, moves) {
        std::cout << "form3 move: " << move.toString() << std::endl;
    }
}

BOOST_AUTO_TEST_CASE(diamondLessThan) {
    std::string facts(  "ElevatorEnter(a) @ [1:5]");
    std::string formulas("100: [ !ElevatorEnter(a) ] v <>{>} [ GateExit(a) ]");

    Domain d = loadDomainWithStreams(facts, formulas);
    d.setDontModifyObsPreds(false);
    boost::mt19937 rng;
    d.setMaxInterval(Interval(1,10));

    std::vector<Move> moves = findMovesFor(d, d.defaultModel(), *d.formulas_begin(), rng);
    BOOST_CHECK(moves.size()!=0);
    BOOST_FOREACH(Move m, moves) {
        std::cout << "move = " << m.toString() << std::endl;
    }
}

max_stars_repo_name: JunLi-Galios/repel

max_issues_repo_name: JunLi-Galios/repel

max_forks_repo_name: JunLi-Galios/repel


text:
/*
Copyright 2009-2021 Nicolas Colombe

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include <engine/map/dungeongraph_res.hpp>

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/identity.hpp>

#include <math/math.hpp>

#include <gen/graphutils.hpp>

namespace eXl
{
  DungeonGraph::ContentName DungeonGraph_Res::Resource() { return ContentName("Resource"); }
  DungeonGraph::ContentName DungeonGraph_Res::ResourceRelay() { return ContentName("ResourceRelay"); }
  DungeonGraph::ContentName DungeonGraph_Res::ThroneRoom() { return ContentName("ThroneRoom"); }
  DungeonGraph::ContentName DungeonGraph_Res::TreasureRoom() { return ContentName("TreasureRoom"); }
  DungeonGraph::ContentName DungeonGraph_Res::Library() { return ContentName("Library"); }
  DungeonGraph::ContentName DungeonGraph_Res::RestRoom() { return ContentName("RestRoom"); }

  IMPLEMENT_RTTI(DungeonGraph_Res::EdgeProperties_Res);

  struct NodeIdentity
  {
    typedef DungeonGraph::Graph::vertex_descriptor result_type;
    result_type operator()(std::pair<DungeonGraph::GraphVtx, DungeonGraph::NodeProperties*> const& iEntry) const
    {
      return iEntry.first;
    }
  };

  struct NodeSize
  {
    typedef uint32_t result_type;
    result_type operator()(std::pair<DungeonGraph::GraphVtx, DungeonGraph::NodeProperties*> const& iEntry) const
    {
      return iEntry.second->GetSize();
    }
  };

  typedef boost::multi_index::multi_index_container<std::pair<DungeonGraph::GraphVtx, DungeonGraph::NodeProperties*>,
    boost::multi_index::indexed_by<
    boost::multi_index::hashed_unique<NodeIdentity>
    ,boost::multi_index::ordered_non_unique<NodeSize>
    >
  > NodeSizeMap;

  void DungeonGraph_Res::NodeAdded(Graph& iGraph, GraphVtx iVtx)
  {
    DungeonGraph::NodeAdded(iGraph, iVtx);
    uint32_t nodeId = GetIndex(iVtx);
    m_Nodes.resize(Mathi::Max(nodeId + 1, m_MaxVtxId));
    m_Nodes[nodeId] = std::make_unique<NodeProperties>();
    m_Nodes[nodeId]->SetPhysical(true);
    boost::put(boost::vertex_name, iGraph, iVtx, m_Nodes[nodeId].get());
  }

  void DungeonGraph_Res::EdgeAdded(Graph& iGraph, GraphEdge iEdge)
  {
    DungeonGraph::EdgeAdded(iGraph, iEdge);
    uint32_t edgeId = GetIndex(iEdge);
    m_Edges.resize(Mathi::Max(edgeId + 1, m_MaxEdgeId));
    m_Edges[edgeId] = std::make_unique<EdgeProperties_Res>();
    boost::put(boost::edge_name, iGraph, iEdge, m_Edges[edgeId].get());
  }

  void DungeonGraph_Res::NodeRemoved(Graph const& iGraph, GraphVtx iVtx)
  {
    m_Nodes[GetIndex(iVtx)] = nullptr;
    DungeonGraph::NodeRemoved(iGraph, iVtx);
  }

  void DungeonGraph_Res::EdgeRemoved(Graph const& iGraph, GraphEdge iEdge)
  {
    m_Edges[GetIndex(iEdge)] = nullptr;
    DungeonGraph::EdgeRemoved(iGraph, iEdge);
  }

  void DungeonGraph_Res::NodeIdxChanged(Graph& iGraph, GraphVtx iVtx, uint32_t iFrom, uint32_t iTo)
  {
    std::swap(m_Nodes[iFrom], m_Nodes[iTo]);
  }

  void DungeonGraph_Res::EdgeIdxChanged(Graph& iGraph, GraphEdge iEdge, uint32_t iFrom, uint32_t iTo)
  {
    std::swap(m_Edges[iFrom], m_Edges[iTo]);
  }

  std::pair<DungeonGraph::GraphVtx, DungeonGraph::NodeProperties*> DungeonGraph_Res::AddNode()
  {
    auto newVtx = boost::add_vertex(m_Graph);
    NodeAdded(m_Graph, newVtx);

    return std::make_pair(newVtx, GetProperties(newVtx));
  }

  std::pair<DungeonGraph::GraphEdge, DungeonGraph_Res::EdgeProperties_Res*> DungeonGraph_Res::AddEdge(GraphVtx iNode1, GraphVtx iNode2)
  {
    auto newEdge = boost::add_edge(iNode1, iNode2, m_Graph).first;

    EdgeAdded(m_Graph, newEdge);

    return std::make_pair(newEdge, EdgeProperties_Res::DynamicCast(GetProperties(newEdge)));
  }

  void DungeonGraph_Res::MakeSingleRoom(unsigned int iRoomSize)
  {
    auto throneRoom = AddNode();
    throneRoom.second->AddContent(ThroneRoom(), iRoomSize);
  }

  void DungeonGraph_Res::InitRes()
  {
    eXl_ASSERT_REPAIR_BEGIN(m_Desc.m_MaxRelayDegree * m_Desc.m_MaxRelaySize >= m_Desc.m_Resources)
    {
      m_Desc.m_Resources = m_Desc.m_MaxRelayDegree * m_Desc.m_MaxRelaySize;
    }

    auto throneRoom = AddNode();
    throneRoom.second->AddContent(ThroneRoom(), m_Desc.m_Resources);

    auto resources = AddNode();
    resources.second->AddContent(Resource(), m_Desc.m_Resources);

    auto relay = AddNode();
    relay.second->AddContent(ResourceRelay(), m_Desc.m_Resources);

    //At least one relay between resources and throne.

    auto relayEdge = AddEdge(throneRoom, relay);
    relayEdge.second->m_ResourceFlow = m_Desc.m_Resources;
    relayEdge.second->m_ResourceSrc = relay.first;

    auto resourceEdge = AddEdge(relay, resources);
    resourceEdge.second->m_ResourceFlow = m_Desc.m_Resources;
    resourceEdge.second->m_ResourceSrc = resources.first;
  }

  UnorderedSet<DungeonGraph::Graph::vertex_descriptor> FitNodesTo(uint32_t iValue, NodeSizeMap const& iNodes, uint32_t iNodesTot)
  {
    typedef UnorderedSet<DungeonGraph::Graph::vertex_descriptor> ResultType;

    if(iValue == 0 || iNodes.empty() || iNodesTot < iValue)
    {
      return ResultType();
    }

    auto iter = iNodes.get<1>().lower_bound(iValue);
    if(iter == iNodes.get<1>().end())
    {
      if(!iNodes.empty())
      {
        iter = std::prev(iter);
      }
      else
      {
        return ResultType();
      }
    }
    else
    {
      if(iter->second->GetSize() == iValue)
      {
        ResultType res;
        res.insert(iter->first);
        return res;
      }

      if(iter != iNodes.get<1>().begin())
      {
        --iter;
      }
    }

    uint32_t candidateSize = iter->second->GetSize();
    uint32_t nodesTotAfterRem = iNodesTot - candidateSize;

    if((candidateSize < iValue)
    && (iNodes.size() > 1)
    && (nodesTotAfterRem >= (iValue - candidateSize)))
    {
      NodeSizeMap smallerMap = iNodes;
      smallerMap.get<0>().erase(iter->first);

      auto subRes1 = FitNodesTo(iValue, smallerMap, nodesTotAfterRem);
      auto subRes2 = FitNodesTo(iValue - candidateSize, smallerMap, nodesTotAfterRem);

      if(!subRes1.empty())
      {
        if(subRes2.empty() || subRes1.size() <= subRes2.size() )
        {
          return subRes1;
        }
      }
      else if(!subRes2.empty())
      {
        subRes2.insert(iter->first);
        return subRes2;
      }
    }

    return ResultType();
  }

  void DungeonGraph_Res::ExpandResources(Random& iRand)
  {
    Map<uint32_t, GraphVtx> vertexToInspect;

    auto addVertexToInspect = [this, &vertexToInspect](GraphVtx iVtx)
    {
      vertexToInspect.insert(std::make_pair(GetIndexMap()[iVtx], iVtx));
    };

    for(auto vtx : VerticesIter(m_Graph))
    {
      addVertexToInspect(vtx);
    }

    while(!vertexToInspect.empty())
    {
      auto vtx = vertexToInspect.begin()->second;
      vertexToInspect.erase(vertexToInspect.begin());

      std::function<bool(GraphVtx, bool)> splitFunction;
      splitFunction = [&](GraphVtx vtx, bool forceSplit)
      {
        NodeProperties* descPtr = GetProperties(vtx);
        eXl_ASSERT(descPtr != nullptr);
        NodeProperties& desc = *descPtr;

        auto rscNode = desc.GetContent(ResourceRelay());
        rscNode = rscNode ? rscNode : desc.GetContent(Resource());

        if(rscNode)
        {
          bool nodeTooBig = forceSplit ? (forceSplit && rscNode->m_Size > 1) : rscNode->m_Type == ResourceRelay() ? rscNode->m_Size > m_Desc.m_MaxRelaySize : rscNode->m_Size > m_Desc.m_MaxResourceSize;
          bool randomSplit = nodeTooBig ?
            false :
            rscNode->m_Size > 1 && float(iRand() % m_Desc.m_MaxRelaySize) < rscNode->m_Size * m_Desc.m_RandomRelaySplitChance;

          if(randomSplit)
          {
            // Check that someone down the road does not have a too big degree to no randomly undo the work.
            for(auto edge : OutEdgesIter(m_Graph, vtx))
            {
              auto& edgeDesc = m_Edges[GetIndex(edge)];
              auto target = GetTarget(vtx, edge);
              if(edgeDesc->m_ResourceSrc == vtx)
              {
                if(boost::degree(target, m_Graph) < m_Desc.m_MaxRelayDegree)
                {
                  randomSplit = false;
                }
              }
            }
          }

          if(nodeTooBig || randomSplit)
          {
            uint32_t split = (iRand() % (rscNode->m_Size - 1)) + 1;
            uint32_t splitRem = rscNode->m_Size - split;

            auto newRsc = AddNode();

            addVertexToInspect(newRsc.first);
            addVertexToInspect(vtx);

            newRsc.second->AddContent(rscNode->m_Type, splitRem);

            desc.SetContentSize(rscNode->m_Type, split);

            while(true)
            {
              NodeSizeMap sources;

              //Follow the chain to split the source.
              for(auto edge : OutEdgesIter(m_Graph, vtx))
              {
                auto& edgeDesc = m_Edges[GetIndex(edge)];
                if(edgeDesc->m_ResourceSrc == GetTarget(vtx, edge))
                {
                  uint32_t nodeIdx = GetIndex(edgeDesc->m_ResourceSrc);
                  sources.insert(std::make_pair(edgeDesc->m_ResourceSrc, m_Nodes[nodeIdx].get()));
                }
              }

              if(sources.empty())
              {
                //No need to fit, just split.

                // Adjust outgoing edges.
                List<Graph::vertex_descriptor> edgesToAdd;
                for(auto edge : OutEdgesIter(m_Graph, vtx))
                {
                  auto& edgeDesc = m_Edges[GetIndex(edge)];
                  auto target = GetTarget(edgeDesc->m_ResourceSrc, edge);
                  edgeDesc->m_ResourceFlow = split;

                  auto newEdge = AddEdge(target, newRsc.first);
                  newEdge.second->m_ResourceSrc = newRsc.first;
                  newEdge.second->m_ResourceFlow = splitRem;

                  addVertexToInspect(target);
                }

                return true;
              }
              else
              {
                auto resSplit = FitNodesTo(split, sources, rscNode->m_Size);
                if(resSplit.empty())
                {
                  resSplit = FitNodesTo(splitRem, sources, rscNode->m_Size);
                  if(!resSplit.empty())
                  {
                    std::swap(split, splitRem);
                  }
                }

                if(resSplit.empty())
                {
                  //Split bigger node.
                  auto vtxToSplit = sources.get<1>().rbegin()->first;
                  //for(auto iter = sources.begin(); iter != sources.end(); ++iter)
                  {
                    //if(iter->second.GetSize() > 1)
                    {
                      //auto vtxToSplit = iter->first;
                      splitFunction(vtxToSplit, true);
                    }
                  }
                }
                else
                {
                  List<Graph::edge_descriptor> edgesToRemove;

                  // Adjust incoming and outgoing edges.
                  for(auto edge : OutEdgesIter(m_Graph, vtx))
                  {
                    auto& edgeDesc = m_Edges[GetIndex(edge)];
                    auto target = GetTarget(vtx, edge);

                    // vertex is a source fot the target
                    if(edgeDesc->m_ResourceSrc == vtx)
                    {
                      edgeDesc->m_ResourceFlow = split;

                      auto newEdge = AddEdge(target, newRsc.first);
                      newEdge.second->m_ResourceSrc = newRsc.first;
                      newEdge.second->m_ResourceFlow = splitRem;
                    }
                    else
                    {
                      // target is a source.
                      if(resSplit.count(target) == 0)
                      {
                        edgesToRemove.push_back(edge);
                        //Source assigned to the other node
                        auto newEdge = AddEdge(target, newRsc.first);
                        newEdge.second->m_ResourceSrc = target;
                        newEdge.second->m_ResourceFlow = edgeDesc->m_ResourceFlow;
                      }
                    }

                    addVertexToInspect(target);
                  }

                  for(auto edgeRemoved : edgesToRemove)
                  {
                    EdgeRemoved(m_Graph, edgeRemoved);
                    boost::remove_edge(edgeRemoved, m_Graph);
                  }
                  DefragIds(m_Graph);

                  return true;
                }
              }
            }
          }
        }
        return false;
      };

      //Check for degree.
      if(boost::degree(vtx, m_Graph) > m_Desc.m_MaxRelayDegree)
      {
        Graph::edge_descriptor srcEdgeToRemove;
        Graph::vertex_descriptor toMove;
        uint32_t nodeToMoveSize = m_Desc.m_Resources;

        // Move one relay/resource to another source.
        for(auto edge : OutEdgesIter(m_Graph, vtx))
        {
          //Move smaller nodes in priority
          auto target = GetTarget(vtx, edge);
          auto const& edgeDesc = m_Edges[GetIndex(edge)];
          auto targetDesc = GetProperties(target);

          if(edgeDesc->m_ResourceSrc == target)
          {
            if(targetDesc->GetSize() < nodeToMoveSize)
            {
              srcEdgeToRemove = edge;
              toMove = target;
              nodeToMoveSize = targetDesc->GetSize();
            }
          }
        }

        Vector<Graph::vertex_descriptor> moveDests;

        auto getDests = [&](bool allowNonRelay)
        {
          for(auto edge : OutEdgesIter(m_Graph, vtx))
          {
            auto target = GetTarget(vtx, edge);
            if(target != toMove)
            {
              auto const& edgeDesc = m_Edges[GetIndex(edge)];
              auto targetDesc = GetProperties(target);

              if(edgeDesc->m_ResourceSrc == target)
              {
                if((allowNonRelay || targetDesc->HasContent(ResourceRelay()))
                && targetDesc->GetSize() + nodeToMoveSize <= m_Desc.m_MaxRelaySize)
                {
                  moveDests.push_back(target);
                }
              }
            }
          }
        };

        auto sortBySizeAndDegree = [&](GraphVtx const& iNode1, GraphVtx const& iNode2)
        {
          auto desc1 = GetProperties(iNode1);
          auto desc2 = GetProperties(iNode2);

          return desc1->GetSize() + boost::degree(iNode1, m_Graph) < desc2->GetSize() + boost::degree(iNode2, m_Graph);
        };

        boost::optional<Graph::vertex_descriptor> dest = boost::none;

        getDests(false);
        std::sort(moveDests.begin(), moveDests.end(), sortBySizeAndDegree);
        if(moveDests.empty())
        {
          getDests(true);
          std::sort(moveDests.begin(), moveDests.end(), sortBySizeAndDegree);
        }
        else
        {
          dest = [&]() -> boost::optional<Graph::vertex_descriptor>
          {
            for(auto dest : moveDests)
            {
              auto targetDesc = GetProperties(dest);
              if(targetDesc->HasContent(ResourceRelay())
                && (boost::degree(dest, m_Graph) + 1) < m_Desc.m_MaxRelayDegree)
              {
                return dest;
              }
            }
            return boost::none;
          }();
        }

        eXl_ASSERT(!moveDests.empty());

        if (!dest)
        {
          auto newNode = AddNode();
          addVertexToInspect(newNode.first);

          auto nodeToMoveAway = moveDests[0];
          auto nodeToMoveAwayDesc = GetProperties(nodeToMoveAway);
          auto rscNode = nodeToMoveAwayDesc->GetContent(ResourceRelay());
          rscNode = rscNode ? rscNode : nodeToMoveAwayDesc->GetContent(Resource());

          eXl_ASSERT(rscNode);

          newNode.second->AddContent(ResourceRelay(), rscNode->m_Size);

          auto destEdgeToRemove = boost::edge(vtx, moveDests[0], m_Graph).first;
          {
            auto const& oldEdgeDesc = m_Edges[GetIndex(destEdgeToRemove)];

            auto newEdge1 = AddEdge(vtx, newNode.first);
            newEdge1.second->m_ResourceFlow = oldEdgeDesc->m_ResourceFlow;
            newEdge1.second->m_ResourceSrc = newNode.first;

            auto newEdge2 = AddEdge(newNode.first, nodeToMoveAway);
            newEdge2.second->m_ResourceFlow = oldEdgeDesc->m_ResourceFlow;
            newEdge2.second->m_ResourceSrc = nodeToMoveAway;
          }
          EdgeRemoved(m_Graph, destEdgeToRemove);
          boost::remove_edge(destEdgeToRemove, m_Graph);

          dest = newNode.first;

          DefragIds(m_Graph);
        }

        eXl_ASSERT_REPAIR_RET(!(!dest),)
        {
          {
            auto const& oldEdgeDesc = m_Edges[GetIndex(srcEdgeToRemove)];

            auto newEdge = AddEdge(toMove, *dest);
            newEdge.second->m_ResourceFlow = oldEdgeDesc->m_ResourceFlow;
            newEdge.second->m_ResourceSrc = toMove;
          }
          EdgeRemoved(m_Graph, srcEdgeToRemove);
          boost::remove_edge(srcEdgeToRemove, m_Graph);

          DefragIds(m_Graph);

          auto destNodeDesc = GetProperties(*dest);
          auto relayPtr = destNodeDesc->GetContent(ResourceRelay());
          eXl_ASSERT(relayPtr);
          destNodeDesc->SetContentSize(ResourceRelay(), nodeToMoveSize + relayPtr->m_Size);

          addVertexToInspect(vtx);
          addVertexToInspect(*dest);

        }

      }

      //Check for resource/relay size
      splitFunction(vtx, false);

    }
  }

  void DungeonGraph_Res::ExpandRooms(Random& iRand)
  {

  }
}

max_stars_repo_name: eXl-Nic/eXl

max_issues_repo_name: eXl-Nic/eXl

max_forks_repo_name: eXl-Nic/eXl


text:
/*
 * This file is part of the statismo library.
 *
 * Author: Marcel Luethi (marcel.luethi@unibas.ch)
 *
 * Copyright (c) 2011 University of Basel
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 *
 * Neither the name of the project's author nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */
#include <iostream>
#include <ostream>

#include <boost/scoped_ptr.hpp>

#include <vtkPolyDataReader.h>
#include <vtkPolyData.h>

#include "DataManager.h"
#include "PCAModelBuilder.h"
#include "StatisticalModel.h"

#include "vtkStandardMeshRepresenter.h"

using namespace statismo;
using boost::scoped_ptr;

vtkPolyData* loadVTKPolyData(const std::string& filename) {
    vtkPolyDataReader* reader = vtkPolyDataReader::New();
    reader->SetFileName(filename.c_str());
    reader->Update();
    vtkPolyData* pd = vtkPolyData::New();
    pd->ShallowCopy(reader->GetOutput());
    return pd;
}

// illustrates the crossvalidation functionality of the data manager
int main(int argc, char** argv) {

    if (argc < 2) {
        std::cout << "Usage " << argv[0] << " datadir" << std::endl;
        exit(-1);
    }
    std::string datadir(argv[1]);

    // All the statismo classes have to be parameterized with the RepresenterType.
    typedef vtkStandardMeshRepresenter RepresenterType;
    typedef DataManager<vtkPolyData> DataManagerType;
    typedef StatisticalModel<vtkPolyData> StatisticalModelType;
    typedef PCAModelBuilder<vtkPolyData> ModelBuilderType;
    typedef DataManagerType::CrossValidationFoldListType CVFoldListType;
    typedef DataManagerType::DataItemListType DataItemListType;

    try {
        vtkPolyData* reference = loadVTKPolyData(datadir +"/hand-0.vtk");
        boost::scoped_ptr<RepresenterType> representer(RepresenterType::Create(reference));

        // create a data manager and add a number of datasets for model building
        boost::scoped_ptr<DataManagerType> dataManager(DataManagerType::Create(representer.get()));

        for (unsigned i = 0; i < 17; i++) {

            std::ostringstream ss;
            ss << datadir +"/hand-" << i << ".vtk";
            const std::string datasetFilename = ss.str();
            vtkPolyData* dataset = loadVTKPolyData(datasetFilename);

            // We provde the filename as a second argument.
            // It will be written as metadata, and allows us to more easily figure out what we did later.
            dataManager->AddDataset(dataset, datasetFilename);

            // it is save to delete the dataset after it was added, as the datamanager direclty copies it.
            dataset->Delete();
        }

        std::cout << "succesfully loaded "<< dataManager->GetNumberOfSamples() << " samples "<< std::endl;

        // create the model builder
        boost::scoped_ptr<ModelBuilderType> pcaModelBuilder(ModelBuilderType::Create());

        // We perform 4-fold cross validation
        CVFoldListType cvFoldList = dataManager->GetCrossValidationFolds(4, true);

        // the CVFoldListType is a standard stl list over which we can iterate to get all the folds
        for (CVFoldListType::const_iterator it = cvFoldList.begin();
                it != cvFoldList.end();
                ++it) {
            // build the model as usual
            boost::scoped_ptr<StatisticalModelType> model(pcaModelBuilder->BuildNewModel(it->GetTrainingData(), 0.01));
            std::cout << "built model with  " << model->GetNumberOfPrincipalComponents() << " principal components"<< std::endl;

            // Now we can iterate over the test data and do whatever validation we would like to do.
            const DataItemListType testSamplesList = it->GetTestingData();

            for (DataItemListType::const_iterator it = testSamplesList.begin();
                    it != testSamplesList.end();
                    ++it) {
                vtkPolyData* testSample = (*it)->GetSample();
                std::cout << "probability of test sample under the model: " << model->ComputeProbability(testSample) << std::endl;

                // We are responsible for deleting the sample.
                testSample->Delete();
            }
        }
        reference->Delete();
    } catch (StatisticalModelException& e) {
        std::cout << "Exception occured while building the shape model" << std::endl;
        std::cout << e.what() << std::endl;
    }
}

ext: cxx


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

#include "kudu/util/net/dns_resolver.h"

#include <boost/bind.hpp>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <vector>

#include "kudu/util/flag_tags.h"
#include "kudu/util/threadpool.h"
#include "kudu/util/net/net_util.h"
#include "kudu/util/net/sockaddr.h"

DEFINE_int32(dns_num_resolver_threads, 1, "The number of threads to use for DNS resolution");
TAG_FLAG(dns_num_resolver_threads, advanced);

using std::vector;

namespace kudu {

DnsResolver::DnsResolver() {
  CHECK_OK(ThreadPoolBuilder("dns-resolver")
           .set_max_threads(FLAGS_dns_num_resolver_threads)
           .Build(&pool_));
}

DnsResolver::~DnsResolver() {
  pool_->Shutdown();
}

namespace {
static void DoResolution(const HostPort &hostport, vector<Sockaddr>* addresses,
                         StatusCallback cb) {
  cb.Run(hostport.ResolveAddresses(addresses));
}
} // anonymous namespace

void DnsResolver::ResolveAddresses(const HostPort& hostport,
                                   vector<Sockaddr>* addresses,
                                   const StatusCallback& cb) {
  Status s = pool_->SubmitFunc(boost::bind(&DoResolution, hostport, addresses, cb));
  if (!s.ok()) {
    cb.Run(s);
  }
}

} // namespace kudu

ext: cc

max_stars_repo_name: kv-zuiwanyuan/kudu

max_issues_repo_name: kv-zuiwanyuan/kudu

max_forks_repo_name: kv-zuiwanyuan/kudu