text:
// graph-tool -- a general graph modification and manipulation thingy
//
// Copyright (C) 2006-2015 Tiago de Paula Peixoto <tiago@skewed.de>
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

#include "graph_filtering.hh"
#include "graph.hh"
#include "graph_python_interface.hh"

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

using namespace std;
using namespace boost;
using namespace graph_tool;

namespace boost
{
size_t hash_value(const boost::python::object& o)
{
    return std::hash<boost::python::object>()(o);
}
}

namespace graph_tool
{

struct get_vertex_iterator
{
    template <class Graph>
    void operator()(Graph& g, python::object& pg,
                    python::object& iter) const
    {
        typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator;
        iter = python::object(PythonIterator<PythonVertex,
                                             vertex_iterator>(pg, vertices(g)));
    }
};

python::object get_vertices(python::object g)
{
    GraphInterface& gi = python::extract<GraphInterface&>(g().attr("_Graph__graph"));
    python::object iter;
    run_action<>()(gi, std::bind(get_vertex_iterator(), placeholders::_1,
                                 std::ref(g),
                                 std::ref(iter)))();
    return iter;
}

struct get_vertex_soft
{
    template <class Graph>
    void operator()(Graph& g,
                    python::object& pg,
                    size_t i, python::object& v) const
    {
        v = python::object(PythonVertex(pg, vertex(i, g)));
    }
};

struct get_vertex_hard
{
    template <class Graph>
    void operator()(Graph& g, python::object& pg, size_t i,
                    python::object& v) const
    {
        size_t c = 0;
        typename graph_traits<Graph>::vertex_iterator vi, v_end;
        for (tie(vi, v_end) = vertices(g); vi != v_end; ++vi)
        {
            if (c == i)
            {
                v = python::object(PythonVertex(pg, *vi));
                return;
            }
            ++c;
        }
        v = python::object(PythonVertex(pg,
                                        graph_traits<Graph>::null_vertex()));
    }
};

python::object get_vertex(python::object g, size_t i)
{
    GraphInterface& gi = python::extract<GraphInterface&>(g().attr("_Graph__graph"));
    python::object v;
    if (gi.IsVertexFilterActive())
        run_action<>()(gi,
                       std::bind(get_vertex_hard(), placeholders::_1,
                                 std::ref(g), i, std::ref(v)))();
    else
        run_action<>()(gi,
                       std::bind(get_vertex_soft(), placeholders::_1,
                                 std::ref(g), i, std::ref(v)))();
    return v;
}

struct get_edge_iterator
{
    template <class Graph>
    void operator()(Graph& g, const python::object& pg, python::object& iter)
        const
    {
        typedef typename graph_traits<Graph>::edge_iterator edge_iterator;
        iter = python::object(PythonIterator<PythonEdge<Graph>,
                                             edge_iterator>(pg, edges(g)));
    }
};

python::object get_edges(python::object g)
{
    GraphInterface& gi = python::extract<GraphInterface&>(g().attr("_Graph__graph"));
    python::object iter;
    run_action<>()(gi,
                   std::bind(get_edge_iterator(), placeholders::_1,
                             std::ref(g), std::ref(iter)))();
    return iter;
}

python::object add_vertex(python::object g, size_t n)
{
    GraphInterface& gi = python::extract<GraphInterface&>(g().attr("_Graph__graph"));

    if (n > 1)
    {
        for (size_t i = 0; i < n; ++i)
            add_vertex(gi.GetGraph());
        return python::object();
    }
    return python::object(PythonVertex(g, add_vertex(gi.GetGraph())));
}

void remove_vertex(GraphInterface& gi, const python::object& oindex, bool fast)
{
    boost::multi_array_ref<int64_t,1> index = get_array<int64_t,1>(oindex);
    auto& g = gi.GetGraph();
    if (fast)
    {
        for (auto v : index)
            remove_vertex_fast(vertex(v, g), g);
    }
    else
    {
        for (auto v : index)
            remove_vertex(vertex(v, g), g);
    }
}

struct add_new_edge
{
    template <class Graph, class EdgeIndexMap>
    void operator()(Graph& g, python::object& pg, GraphInterface&,
                    const PythonVertex& s, const PythonVertex& t,
                    EdgeIndexMap, python::object& new_e) const
    {
        typename graph_traits<Graph>::edge_descriptor e =
            add_edge(s.GetDescriptor(), t.GetDescriptor(), g).first;
        new_e = python::object(PythonEdge<Graph>(pg, e));
    }
};

python::object add_edge(python::object g, const python::object& s,
                        const python::object& t)
{
    PythonVertex& src = python::extract<PythonVertex&>(s);
    PythonVertex& tgt = python::extract<PythonVertex&>(t);
    src.CheckValid();
    tgt.CheckValid();
    GraphInterface& gi = python::extract<GraphInterface&>(g().attr("_Graph__graph"));
    python::object new_e;
    run_action<>()(gi, std::bind(add_new_edge(), placeholders::_1, std::ref(g),
                                 std::ref(gi), src, tgt, gi.GetEdgeIndex(),
                                 std::ref(new_e)))();
    return new_e;
}

struct get_edge_descriptor
{
    template <class Graph>
    void operator()(const Graph&, const python::object& e,
                    typename GraphInterface::edge_t& edge,
                    bool& found)  const
    {
        PythonEdge<Graph>& pe = python::extract<PythonEdge<Graph>&>(e);
        pe.CheckValid();
        pe.SetValid(false);
        edge = pe.GetDescriptor();
        found = true;
    }
};

void remove_edge(GraphInterface& gi, const python::object& e)
{
    GraphInterface::edge_t de;
    bool found = false;
    run_action<>()(gi, std::bind(get_edge_descriptor(), placeholders::_1,
                                 std::ref(e), std::ref(de), std::ref(found)))();
    remove_edge(de, gi.GetGraph());
    if (!found)
        throw ValueException("invalid edge descriptor");
}

struct get_edge_dispatch
{
    template <class Graph>
    void operator()(Graph& g, const python::object& pg, size_t s, size_t t,
                    bool all_edges, boost::python::list& es) const
    {
        for (auto e : out_edges_range(vertex(s, g), g))
        {
            if (target(e, g) == vertex(t, g))
            {
                es.append(PythonEdge<Graph>(pg, e));
                if (!all_edges)
                    break;
            }
        }
    }
};

python::object get_edge(python::object g, size_t s, size_t t, bool all_edges)
{
    GraphInterface& gi = python::extract<GraphInterface&>(g().attr("_Graph__graph"));
    python::list es;
    run_action<>()(gi,
                   std::bind(get_edge_dispatch(), placeholders::_1,
                             std::ref(g), s, t, all_edges, std::ref(es)))();
    return es;
}

struct get_degree_map
{
    template <class Graph, class DegS, class Weight>
    void operator()(const Graph& g, python::object& odeg_map, DegS deg, Weight weight) const
    {
        typedef typename detail::get_weight_type<Weight>::type weight_t;
        typedef typename mpl::if_<std::is_same<weight_t, size_t>, int32_t, weight_t>::type deg_t;

        typedef typename property_map_type::apply<deg_t,
                                                  GraphInterface::vertex_index_map_t>::type
            map_t;

        map_t cdeg_map(get(vertex_index, g));
        typename map_t::unchecked_t deg_map = cdeg_map.get_unchecked(num_vertices(g));

        int i, N = num_vertices(g);
        #pragma omp parallel for default(shared) private(i) schedule(runtime) if (N > 100)
        for (i = 0; i < N; ++i)
        {
            typename graph_traits<Graph>::vertex_descriptor v = vertex(i, g);
            if (v == graph_traits<Graph>::null_vertex())
                continue;
            deg_map[v] = deg(v, g, weight);
        }

        odeg_map = python::object(PythonPropertyMap<map_t>(cdeg_map));
    }
};

python::object GraphInterface::DegreeMap(string deg, boost::any weight) const
{

    python::object deg_map;

    typedef mpl::push_back<edge_scalar_properties,
                           detail::no_weightS>::type weight_t;
    if (weight.empty())
        weight = detail::no_weightS();

    if (deg == "in")
        run_action<>()(const_cast<GraphInterface&>(*this),
                       std::bind(get_degree_map(), placeholders::_1,
                                 std::ref(deg_map), in_degreeS(), placeholders::_2), weight_t())
            (weight);
    else if (deg == "out")
        run_action<>()(const_cast<GraphInterface&>(*this),
                       std::bind(get_degree_map(), placeholders::_1,
                                 std::ref(deg_map), out_degreeS(), placeholders::_2), weight_t())
            (weight);
    else if (deg == "total")
        run_action<>()(const_cast<GraphInterface&>(*this),
                       std::bind(get_degree_map(), placeholders::_1,
                                 std::ref(deg_map), total_degreeS(), placeholders::_2), weight_t())
            (weight);
    return deg_map;
}

//
// Below are the functions with will properly register all the types to python,
// for every filter, type, etc.
//

// this will register all the Vertex/Edge classes to python
struct export_python_interface
{
    template <class Graph>
    void operator()(const Graph*, set<string>& v_iterators) const
    {
        using namespace boost::python;

        class_<PythonEdge<Graph>, bases<EdgeBase> >
            ("Edge", no_init)
            .def("source", &PythonEdge<Graph>::GetSource,
                 "Return the source vertex.")
            .def("target", &PythonEdge<Graph>::GetTarget,
                 "Return the target vertex.")
            .def("is_valid", &PythonEdge<Graph>::IsValid,
                 "Return whether the edge is valid.")
            .def("get_graph", &PythonEdge<Graph>::GetGraph,
                 "Return the graph to which the edge belongs.")
            .def("__str__", &PythonEdge<Graph>::GetString)
            .def("__hash__", &PythonEdge<Graph>::GetHash);

        typedef typename graph_traits<Graph>::vertex_iterator vertex_iterator;
        if (v_iterators.find(typeid(vertex_iterator).name()) ==
            v_iterators.end())
        {
            class_<PythonIterator<PythonVertex, vertex_iterator> >
                ("VertexIterator", no_init)
                .def("__iter__", objects::identity_function())
                .def("__next__", &PythonIterator<PythonVertex,
                                                 vertex_iterator>::Next)
                .def("next", &PythonIterator<PythonVertex,
                                             vertex_iterator>::Next);
            v_iterators.insert(typeid(vertex_iterator).name());
        }

        typedef typename graph_traits<Graph>::edge_iterator edge_iterator;
        class_<PythonIterator<PythonEdge<Graph>,
                              edge_iterator> >("EdgeIterator", no_init)
            .def("__iter__", objects::identity_function())
            .def("__next__", &PythonIterator<PythonEdge<Graph>,
                                         edge_iterator>::Next)
            .def("next", &PythonIterator<PythonEdge<Graph>,
                                         edge_iterator>::Next);

        typedef typename graph_traits<Graph>::out_edge_iterator
            out_edge_iterator;
        class_<PythonIterator<PythonEdge<Graph>,
                              out_edge_iterator> >("OutEdgeIterator", no_init)
            .def("__iter__", objects::identity_function())
            .def("__next__", &PythonIterator<PythonEdge<Graph>,
                                             out_edge_iterator>::Next)
            .def("next", &PythonIterator<PythonEdge<Graph>,
                                         out_edge_iterator>::Next);

        typedef typename graph_traits<Graph>::directed_category
            directed_category;
        typedef typename std::is_convertible<directed_category,
                                             boost::directed_tag>::type is_directed;
        if (is_directed::value)
        {
            typedef typename in_edge_iteratorS<Graph>::type in_edge_iterator;
            class_<PythonIterator<PythonEdge<Graph>,
                                  in_edge_iterator> >("InEdgeIterator", no_init)
                .def("__iter__", objects::identity_function())
                .def("__next__", &PythonIterator<PythonEdge<Graph>,
                                                 in_edge_iterator>::Next)
                .def("next", &PythonIterator<PythonEdge<Graph>,
                                             in_edge_iterator>::Next);
        }
    }
};

PythonPropertyMap<GraphInterface::vertex_index_map_t>
get_vertex_index(GraphInterface& g)
{
    return PythonPropertyMap<GraphInterface::vertex_index_map_t>
        (g.GetVertexIndex());
}

PythonPropertyMap<GraphInterface::edge_index_map_t>
do_get_edge_index(GraphInterface& g)
{
    return PythonPropertyMap<GraphInterface::edge_index_map_t>
        (g.GetEdgeIndex());
}

template <class ValueList>
struct add_edge_list
{
    template <class Graph>
    void operator()(Graph& g, python::object aedge_list, bool& found) const
    {
        boost::mpl::for_each<ValueList>(std::bind(dispatch(), std::ref(g),
                                                  std::ref(aedge_list),
                                                  std::ref(found), placeholders::_1));
    }

    struct dispatch
    {
        template <class Graph, class Value>
        void operator()(Graph& g, python::object& aedge_list, bool& found, Value) const
        {
            if (found)
                return;
            try
            {
                boost::multi_array_ref<Value, 2> edge_list = get_array<Value, 2>(aedge_list);

                if (edge_list.shape()[1] < 2)
                    throw GraphException("Second dimension in edge list must be of size (at least) two");

                for (size_t i = 0; i < edge_list.shape()[0]; ++i)
                {
                    size_t s = edge_list[i][0];
                    size_t t = edge_list[i][1];
                    while (s >= num_vertices(g) || t >= num_vertices(g))
                        add_vertex(g);
                    add_edge(vertex(s, g), vertex(t, g), g);
                }
                found = true;
            }
            catch (invalid_numpy_conversion& e) {}
        }
    };
};

void do_add_edge_list(GraphInterface& gi, python::object aedge_list)
{
    typedef mpl::vector<bool, uint8_t, uint32_t, int16_t, int32_t, int64_t, uint64_t,
                        unsigned long int, double, long double> vals_t;
    bool found = false;
    run_action<>()(gi, std::bind(add_edge_list<vals_t>(), placeholders::_1, aedge_list,
                                 std::ref(found)))();
    if (!found)
        throw GraphException("Invalid type for edge list; must be two-dimensional with a scalar type");
}

} // namespace graph_tool

// register everything

void export_python_properties();

void export_python_interface()
{
    using namespace boost::python;

    class_<PythonVertex>
        ("Vertex", no_init)
        .def("__in_degree", &PythonVertex::GetInDegree,
             "Return the in-degree.")
        .def("__weighted_in_degree", &PythonVertex::GetWeightedInDegree,
             "Return the weighted in-degree.")
        .def("__out_degree", &PythonVertex::GetOutDegree,
             "Return the out-degree.")
        .def("__weighted_out_degree", &PythonVertex::GetWeightedOutDegree,
             "Return the weighted out-degree.")
        .def("in_edges", &PythonVertex::InEdges,
             "Return an iterator over the in-edges.")
        .def("out_edges", &PythonVertex::OutEdges,
             "Return an iterator over the out-edges.")
        .def("is_valid", &PythonVertex::IsValid,
             "Return whether the vertex is valid.")
        .def("get_graph", &PythonVertex::GetGraph,
             "Return the graph to which the vertex belongs.")
        .def("__str__", &PythonVertex::GetString)
        .def("__int__", &PythonVertex::GetIndex)
        .def("__hash__", &PythonVertex::GetHash);
    class_<EdgeBase>("EdgeBase", no_init);

    set<string> v_iterators;
    typedef boost::mpl::transform<graph_tool::detail::all_graph_views,
                                  boost::mpl::quote1<std::add_pointer> >::type graph_views;
    boost::mpl::for_each<graph_views>(std::bind(graph_tool::export_python_interface(),
                                      placeholders::_1, std::ref(v_iterators)));
    export_python_properties();
    def("new_vertex_property",
        &new_property<GraphInterface::vertex_index_map_t>);
    def("new_edge_property", &new_property<GraphInterface::edge_index_map_t>);
    def("new_graph_property",
        &new_property<ConstantPropertyMap<size_t,graph_property_tag> >);

    def("get_vertex", get_vertex);
    def("get_vertices", get_vertices);
    def("get_edges", get_edges);
    def("add_vertex", graph_tool::add_vertex);
    def("add_edge", graph_tool::add_edge);
    def("remove_vertex", graph_tool::remove_vertex);
    def("remove_edge", graph_tool::remove_edge);
    def("add_edge_list", graph_tool::do_add_edge_list);
    def("get_edge", get_edge);

    def("get_vertex_index", get_vertex_index);
    def("get_edge_index", do_get_edge_index);
}

max_stars_repo_name: johankaito/fufuka

max_issues_repo_name: johankaito/fufuka

max_forks_repo_name: johankaito/fufuka


text:
// Copyright (c) 2009 Jaroslav Gresula
//
// Distributed under the MIT license (See accompanying file
// LICENSE.txt or copy at http://jagpdf.org/LICENSE.txt)
//

// Portions of this code are
//  Copyright (c) 2001, 2002 Peter Dimov and Multi Media Ltd.
//
#ifndef REFCOUNTEDIMPL_PTHREADS_JG818_HPP__
#define REFCOUNTEDIMPL_PTHREADS_JG818_HPP__

#include <core/generic/assert.h>
#include <pthread.h>
#include <interfaces/refcounted.h>
#include <boost/noncopyable.hpp>

namespace jag {
namespace detail {

//
//
//
class scoped_lock
{
public:
    scoped_lock(pthread_mutex_t & m)
        : m_(m)
    {
        pthread_mutex_lock(&m_);
    }

    ~scoped_lock()
    {
        pthread_mutex_unlock(&m_);
    }

private:
    pthread_mutex_t & m_;
};

} // namespace detail

//
//
//
class RefCountMT
    : public IRefCounted
{
public:
    RefCountMT()
        : value_(0)
    {
        pthread_mutex_init(&mutex_, 0);
    }

    virtual ~RefCountMT()
    {
        pthread_mutex_destroy(&mutex_);
    }

    void AddRef()
    {
        detail::scoped_lock lock(mutex_);
        ++value_;
    }

    void Release()
    {
        detail::scoped_lock lock(mutex_);
        JAG_ASSERT(value_ > 0);
        if (0 == --value_)
            delete this;
    }

private:
    pthread_mutex_t mutex_;
    long value_;
};

//
// thread-safe implementation of reference counting; it does not perform any
// action on addref, release; just signals when the counter is addrefed from 0
// to 1 and released from 1 to 0
//
class RefCountMTSignal
    : public boost::noncopyable
{
public:
    RefCountMTSignal()
        : value_(0)
    {
        pthread_mutex_init(&mutex_, 0);
    }

    ~RefCountMTSignal()
    {
        pthread_mutex_destroy(&mutex_);
    }

    // returns true if counter goes from 0 -> 1, false otherwise
    bool addref()
    {
        detail::scoped_lock lock(mutex_);
        return 1 == ++value_;
    }

    // return true if counter goes from 1 -> 0, false otherwise
    bool release()
    {
        detail::scoped_lock lock(mutex_);
        return 0 == --value_;
    }

private:
    pthread_mutex_t mutex_;
    long value_;
};

} // namespace jag::detail

#endif // REFCOUNTEDIMPL_PTHREADS_JG818_HPP__

/** EOF @file */

ext: hpp

max_stars_repo_name: jgresula/jagpdf

max_issues_repo_name: jgresula/jagpdf

max_forks_repo_name: jgresula/jagpdf


text:
#include <cassert>

#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/range/adaptor/transformed.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/variant/static_visitor.hpp>
#include <boost/variant/apply_visitor.hpp>

#include "dachs/ast/ast.hpp"
#include "dachs/fatal.hpp"
#include "dachs/semantics/scope.hpp"
#include "dachs/semantics/type.hpp"

namespace dachs {
namespace ast {
namespace symbol {

std::string to_string(if_kind const k)
{
    switch(k) {
    case if_kind::if_:    return "if";
    case if_kind::unless: return "unless";
    case if_kind::case_:  return "case";
    default:
        DACHS_RAISE_INTERNAL_COMPILATION_ERROR
        return "unknown";
    }
}

std::string to_string(qualifier const o)
{
    switch(o) {
    case qualifier::maybe: return "?";
    default:
        DACHS_RAISE_INTERNAL_COMPILATION_ERROR
        return "unknown";
    }
}

std::string to_string(func_kind const o)
{
    switch(o) {
    case func_kind::func: return "func";
    case func_kind::proc: return "proc";
    default:
        DACHS_RAISE_INTERNAL_COMPILATION_ERROR
        return "unknown";
    }
}

} // namespace symbol

namespace node_type {

std::size_t generate_id() noexcept
{
    static std::size_t current_id = 0;
    return ++current_id;
}

std::string primary_literal::to_string() const noexcept
{
    struct primary_literal_stringizer
        : public boost::static_visitor<std::string> {

        std::string operator()(char const c) const noexcept
        {
            return " char: "
                + (
                    c == '\f' ? "'\\f'" :
                    c == '\b' ? "'\\b'" :
                    c == '\n' ? "'\\n'" :
                    c == '\r' ? "'\\r'" :
                                    std::string{'\'', c, '\''}
                );
        }

        std::string operator()(double const d) const noexcept
        {
            return " float: " + std::to_string(d);
        }

        std::string operator()(bool const b) const noexcept
        {
            return std::string{" bool: "} + (b ? "true" : "false");
        }

        std::string operator()(std::string s) const noexcept
        {
            boost::algorithm::replace_all(s, "\\", "\\\\");
            boost::algorithm::replace_all(s, "\"", "\\\"");
            boost::algorithm::replace_all(s, "\b", "\\b");
            boost::algorithm::replace_all(s, "\f", "\\f");
            boost::algorithm::replace_all(s, "\n", "\\n");
            boost::algorithm::replace_all(s, "\r", "\\r");
            return " string: \"" + s + '"';
        }

        std::string operator()(int const i) const noexcept
        {
            return " int: " + std::to_string(i);
        }

        std::string operator()(unsigned int const ui) const noexcept
        {
            return " uint: " + std::to_string(ui);
        }

    } v;

    return "PRIMARY_LITERAL: " + boost::apply_visitor(v, value);
}

bool function_definition::is_template() noexcept
{
    if (!is_template_memo) {
        is_template_memo =
            any_of(
                params,
                [](auto const& p){ return p->type.is_template(); }
            );
    }

    return *is_template_memo;
}

} // namespace node_type
} // namespace ast
} // namespace dachs

ext: cpp

max_stars_repo_name: rhysd/Dachs

max_stars_repo_licenses: NCSA MIT

max_issues_repo_name: maekawatoshiki/Dachs

max_issues_repo_licenses: NCSA MIT

max_forks_repo_name: maekawatoshiki/Dachs

max_forks_repo_licenses: NCSA MIT


text:
/*

PICCANTE
The hottest HDR imaging library!
http://vcg.isti.cnr.it/piccante

Copyright (C) 2014-2016
Visual Computing Laboratory - ISTI CNR
http://vcg.isti.cnr.it
Library author: Francesco Banterle
This file author: Giorgio Marcias

This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.

*/

#ifndef PIC_ALGORITHMS_MITSUNAGA_NAYAR_CRF_HPP
#define PIC_ALGORITHMS_MITSUNAGA_NAYAR_CRF_HPP

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

#include "../base.hpp"

#ifndef PIC_DISABLE_EIGEN

#ifndef PIC_EIGEN_NOT_BUNDLED
    #include "../externals/Eigen/LU"
#else
    #include <Eigen/LU>
#endif

#endif

namespace pic {

/**
 * @brief MitsunagaNayarClassic computes the inverse CRF of a camera as a polynomial function.
 * @param samples           Sample array of size nSamples x #exposures.
 * @param nSamples          Number of samples, for each exposure.
 * @param exposures         Array of exposure timings (size: #exposures = 'Q' as in the Mitsunaga & Nayar paper).
 * @param coefficients      The output coefficients ('c' in the paper) resulting from the computation.
 * @param computeRatios     false if exact exposures are passed, true to approximate exposure ratios as in the paper.
 * @param R                 The output estimated exposure ratios, i.e. R[q1][q2] = 'R_{q1,q2}' as in the book.
 * @param eps               Threshold for stopping the approximation process.
 * @param max_iterations    Maximum number of iterations.
 * @return The error as in the paper.
 */
PIC_INLINE float MitsunagaNayarClassic(int *samples, const std::size_t nSamples, const std::vector<float> &exposures,
                                   std::vector<float> &coefficients, const bool computeRatios, std::vector<float> &R,
                                   const float eps, const std::size_t max_iterations)
{
#ifndef PIC_DISABLE_EIGEN
    float eval, val, tmp1, tmp2;
    const std::size_t Q = exposures.size();
    const std::size_t N = coefficients.size() - 1;

    const float Mmax = 1.f;

    for (float &_c : coefficients) {
        _c = 0.f;
    }

    if (!samples || Q < 2 || coefficients.size() < 2) {
        return std::numeric_limits<float>::infinity();
    }

    R.assign(Q < 2 ? 0 : Q - 1, 1.f);
    for (int q = 0; q < R.size(); ++q) {
        R[q] = exposures[q] / exposures[q+1];
    }

    //Check valid samples
    std::vector<std::vector<float>> g(nSamples, std::vector<float>(Q, 0.f));
    std::size_t P = 0;
    for (std::size_t p = 0; p < nSamples; ++p) {
        bool valid = false;
        for (std::size_t q = 0; q < Q-1; ++q) {
            if (samples[p * Q + q] >= 0 && samples[p * Q + q+1] >= 0) {
                valid = true;
                break;
            }
        }
        if (valid) {
            for (std::size_t q = 0; q < Q; ++q) {
                if (samples[p * Q + q] >= 0) {
                    g[P][q] = samples[p * Q + q] / 255.f;
                } else {
                    g[P][q] = -1.f;
                }
            }
            ++P;
        }
    }
    g.resize(P);

    if (g.empty()) {
        return std::numeric_limits<float>::infinity();
    }

    //Precompute test with exponentials
    std::vector<Eigen::VectorXf> test;
    if (computeRatios) {
        test.assign(256, Eigen::VectorXf::Zero(N+1));
        for (std::size_t i = 0; i < 256; ++i) {
            test[i][0] = 1.f;
            for (std::size_t n = 1; n <= N; ++n) {
                test[i][n] = (i / 255.f) * test[i][n-1];
            }
        }
    }

    //Precompute M with exponentials
    std::vector<std::vector<std::vector<float>>> M(P,
                                                   std::vector<std::vector<float>>(Q,
                                                                                std::vector<float>(N+1, 0.f)));
    for (std::size_t p = 0; p < P; ++p) {
        for (std::size_t q = 0; q < Q; ++q) {
            M[p][q][0] = 1.f;
            for (std::size_t n = 1; n <= N; ++n) {
                M[p][q][n] = g[p][q] * M[p][q][n-1];
            }
        }
    }

    std::vector<std::vector<std::vector<float>>> d(P,
                                                   std::vector<std::vector<float>>(Q-1,
                                                                                std::vector<float>(N+1, 1.f)));
    Eigen::MatrixXf A = Eigen::MatrixXf::Zero(N, N);
    Eigen::VectorXf x, b = Eigen::VectorXf::Zero(N);
    Eigen::VectorXf c(N+1), prev_c = Eigen::VectorXf::Zero(N+1);

    std::size_t iter = 0;

    do {
        //Compute d
        for (std::size_t p = 0; p < P; ++p) {
            for (std::size_t q = 0; q < Q-1; ++q) {
                if (g[p][q] >= 0.f && g[p][q+1] >= 0.f) {
                    for (std::size_t n = 0; n <= N; ++n) {
                        d[p][q][n] = M[p][q][n] - R[q] * M[p][q+1][n];
                    }
                } else {
                    d[p][q].assign(N+1, 0.f);
                }
            }
        }

        //Build the matrix A of the linear system
        A.setZero(N, N);
        for (std::size_t i = 0; i < N; ++i) {
            for (std::size_t j = 0; j < N; ++j) {
                for (std::size_t p = 0; p < P; ++p) {
                    for (std::size_t q = 0; q < Q - 1; ++q) {
                        A(i, j) += d[p][q][i] * (d[p][q][j] - d[p][q][N]);
                    }
                }
            }
        }

        //Build the vector of knowns b
        b.setZero(N);
        for (std::size_t i = 0; i < N; ++i) {
            for (std::size_t p = 0; p < P; ++p) {
                for (std::size_t q = 0; q < Q - 1; ++q) {
                    b(i) -= Mmax * d[p][q][i] * d[p][q][N];
                }
            }
        }

        //Solve the linear system
        x = A.partialPivLu().solve(b);
        c << x, Mmax - x.sum();

        if (computeRatios) {
            //Evaluate approximation increment
            eval = std::numeric_limits<float>::lowest();
            for (const Eigen::VectorXf &_M : test) {
                val = std::abs((c - prev_c).dot(_M));
                if (val > eval) {
                    eval = val;
                }
            }

            //Update R
            for (std::size_t q = 0; q < Q-1; ++q) {
                R[q] = 0.f;
                tmp1 = 0.f;
                tmp2 = 0.f;
                for (std::size_t p = 0; p < P; ++p) {
                    if (g[p][q] >= 0.f && g[p][q+1] >= 0.f) {
                        for (std::size_t n = 0; n <= N; ++n) {
                            tmp1 += c[n] * M[p][q][n];
                            tmp2 += c[n] * M[p][q+1][n];
                        }
                    }
                }
                R[q] += tmp1 / tmp2;
            }

            ++iter;
        }
    } while (computeRatios && eval > eps && iter < max_iterations);

    for (std::size_t n = 0; n <= N; ++n) {
        coefficients[n] = c[n];
    }

    //Evaluate error
    eval = 0.f;
    for (std::size_t q = 0; q < Q-1; ++q) {
        for (std::size_t p = 0; p < P; ++p) {
            if (g[p][q] >= 0.f && g[p][q+1] >= 0.f) {
                val = 0.f;
                for (std::size_t n = 0; n <= N; ++n) {
                    val += coefficients[n] * (M[p][q][n] - R[q] * M[p][q+1][n]);
                }
                eval += val * val;
            }
        }
    }

    return eval;
#else
    return -1.0f;
#endif
}

/**
 * @brief MitsunagaNayarFull computes the inverse CRF of a camera as a polynomial function, using all exposure ratios.
 * @param samples           Sample array of size nSamples x #exposures.
 * @param nSamples          Number of samples, for each exposure.
 * @param exposures         Array of exposure timings (size: #exposures = 'Q' as in the Mitsunaga & Nayar paper).
 * @param coefficients      The output coefficients ('c' in the paper) resulting from the computation.
 * @param computeRatios     false if exact exposures are passed, true to approximate exposure ratios as in the paper.
 * @param R                 The output estimated exposure ratios, i.e. R[q1][q2] = 'R_{q1,q2}' as in the book.
 * @param eps               Threshold for stopping the approximation process.
 * @param max_iterations    Maximum number of iterations.
 * @return The error as in the paper.
 */
PIC_INLINE float MitsunagaNayarFull(int *samples, const std::size_t nSamples, const std::vector<float> &exposures,
                                std::vector<float> &coefficients, bool computeRatios, std::vector<std::vector<float>> &R,
                                const float eps, const std::size_t max_iterations)
{
#ifndef PIC_DISABLE_EIGEN
    float eval, val, tmp1, tmp2;
    const std::size_t Q = exposures.size();
    const std::size_t N = coefficients.size() - 1;

    const float Mmax = 1.f;

    for (float &_c : coefficients) {
        _c = 0.f;
    }
    R.assign(Q < 2 ? 0 : Q, std::vector<float>(Q < 2 ? 0 : Q, 1.f));
    for (int q1 = 0; q1 < R.size(); ++q1) {
        for (int q2 = 0; q2 < R[q1].size(); ++q2) {
            if (q2 == q1) {
                R[q1][q2] = 1.f;
            } else {
                R[q1][q2] = exposures[q1] / exposures[q2];
            }
        }
    }
    if (!samples || Q < 2 || coefficients.size() < 2) {
        return std::numeric_limits<float>::infinity();
    }

    //Check valid samples
    std::vector<std::vector<float>> g(nSamples, std::vector<float>(Q, 0.f));
    std::size_t P = 0;
    for (std::size_t p = 0; p < nSamples; ++p) {
        std::size_t valid = 0;
        for (std::size_t q = 0; q < Q; ++q) {
            if (samples[p * Q + q] >= 0) {
                ++valid;
            }
        }
        if (valid > 1) {
            for (std::size_t q = 0; q < Q; ++q) {
                if (samples[p * Q + q] >= 0) {
                    g[P][q] = samples[p * Q + q] / 255.f;
                } else {
                    g[P][q] = -1.f;
                }
            }
            ++P;
        }
    }
    g.resize(P);

    if (g.empty()) {
        return std::numeric_limits<float>::infinity();
    }

    //Precompute test with exponentials
    std::vector<Eigen::VectorXf> test;
    if (computeRatios) {
        test.assign(256, Eigen::VectorXf::Zero(N+1));
        for (std::size_t i = 0; i < 256; ++i) {
            test[i][0] = 1.f;
            for (std::size_t n = 1; n <= N; ++n) {
                test[i][n] = (i / 255.f) * test[i][n-1];
            }
        }
    }

    //Precompute M with exponentials
    std::vector<std::vector<std::vector<float>>> M(P,
                                                   std::vector<std::vector<float>>(Q,
                                                                                std::vector<float>(N+1, 0.f)));
    for (std::size_t p = 0; p < P; ++p) {
        for (std::size_t q = 0; q < Q; ++q) {
            M[p][q][0] = 1.f;
            for (std::size_t n = 1; n <= N; ++n) {
                M[p][q][n] = g[p][q] * M[p][q][n-1];
            }
        }
    }

    std::vector<std::vector<std::vector<std::vector<float>>>> d(P,
                                                                std::vector<std::vector<std::vector<float>>>(Q,
                                                                            std::vector<std::vector<float>>(Q,
                                                                                std::vector<float>(N+1, 1.f))));
    Eigen::MatrixXf A = Eigen::MatrixXf::Zero(N, N);
    Eigen::VectorXf x, b = Eigen::VectorXf::Zero(N);
    Eigen::VectorXf c(N+1), prev_c = Eigen::VectorXf::Zero(N+1);

    std::size_t iter = 0;

    do {
        //Compute d
        for (std::size_t p = 0; p < P; ++p) {
            for (std::size_t q1 = 0; q1 < Q; ++q1) {
                for (std::size_t q2 = 0; q2 < Q; ++q2) {
                    d[p][q1][q2].assign(N+1, 0.f);
                    if (q2 != q1) {
                        for (std::size_t n = 0; n <= N; ++n) {
                            if (g[p][q1] >= 0.f && g[p][q2] >= 0.f) {
                                d[p][q1][q2][n] = M[p][q1][n] - R[q1][q2] * M[p][q2][n];
                            } else {
                                d[p][q1][q2][n] = 0.f;
                            }
                        }
                    }
                }
            }
        }

        //Build the matrix A of the linear system
        A.setZero(N, N);
        for (std::size_t i = 0; i < N; ++i) {
            for (std::size_t j = 0; j < N; ++j) {
                for (std::size_t p = 0; p < P; ++p) {
                    for (std::size_t q1 = 0; q1 < Q; ++q1) {
                        for (std::size_t q2 = 0; q2 < Q; ++q2) {
                            if (q2 != q1) {
                                A(i, j) += d[p][q1][q2][i] * (d[p][q1][q2][j] - d[p][q1][q2][N]);
                            }
                        }
                    }
                }
            }
        }

        //Build the vector of knowns b
        b.setZero(N);
        for (std::size_t i = 0; i < N; ++i) {
            for (std::size_t p = 0; p < P; ++p) {
                for (std::size_t q1 = 0; q1 < Q; ++q1) {
                    for (std::size_t q2 = 0; q2 < Q; ++q2) {
                        if (q2 != q1) {
                            b(i) -= Mmax * d[p][q1][q2][i] * d[p][q1][q2][N];
                        }
                    }
                }
            }
        }

        //Solve the linear system
        x = A.partialPivLu().solve(b);
        c << x, Mmax - x.sum();

        if (computeRatios) {
            //Evaluate approximation increment
            eval = std::numeric_limits<float>::lowest();
            for (const Eigen::VectorXf &_M : test) {
                val = std::abs((c - prev_c).dot(_M));
                if (val > eval) {
                    eval = val;
                }
            }

            //Update R
            for (std::size_t q1 = 0; q1 < Q; ++q1) {
                for (std::size_t q2 = 0; q2 < Q; ++q2) {
                    R[q1][q2] = 0.f;
                    tmp1 = 0.f;
                    tmp2 = 0.f;
                    for (std::size_t p = 0; p < P; ++p) {
                        if (g[p][q1] >= 0.f && g[p][q2] >= 0.f) {
                            for (std::size_t n = 0; n <= N; ++n) {
                                tmp1 += c[n] * M[p][q1][n];
                                tmp2 += c[n] * M[p][q2][n];
                            }
                        }
                    }
                    R[q1][q2] += tmp1 / tmp2;
                }
            }

            ++iter;
        }
    } while (computeRatios && eval > eps && iter < max_iterations);

    for (std::size_t n = 0; n <= N; ++n) {
        coefficients[n] = c[n];
    }

    //Evaluate error
    eval = 0.f;
    for (std::size_t q1 = 0; q1 < Q; ++q1) {
        for (std::size_t q2 = 0; q2 < Q; ++q2) {
            if (q2 != q1) {
                for (std::size_t p = 0; p < P; ++p) {
                    if (g[p][q1] >= 0.f && g[p][q2] >= 0.f) {
                        val = 0.f;
                        for (std::size_t n = 0; n <= N; ++n) {
                            val += coefficients[n] * (M[p][q1][n] - R[q1][q2] * M[p][q2][n]);
                        }
                        eval += val * val;
                    }
                }
            }
        }
    }

    return eval;
#else
    return -1.0f;
#endif
}

}

#endif // PIC_ALGORITHMS_MITSUNAGA_NAYAR_CRF_HPP


text:
// Copyright (c) 2014-2015, Pacific Biosciences of California, Inc.
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted (subject to the limitations in the
// disclaimer below) 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 Pacific Biosciences nor the names of its
//    contributors may be used to endorse or promote products derived
//    from this software without specific prior written permission.
//
// NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE
// GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY PACIFIC
// BIOSCIENCES AND ITS 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 PACIFIC BIOSCIENCES OR ITS
// 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.

// Author: Lance Hepler

#include <climits>
#include <cstdlib>
#include <fstream>

#include <sys/stat.h>

#include <boost/algorithm/string.hpp>

#include <pacbio/ccs/Utility.h>

using namespace std;

namespace PacBio {
namespace CCS {

string AbsolutePath(const string& path)
{
    char buf[PATH_MAX + 1];
    char *res = realpath(path.c_str(), buf);

    if (res != nullptr)
    {
        string abspath(res);
        return abspath;
    }

    return path;
}

bool FileExists(const string& path)
{
    struct stat buffer;
    return stat(path.c_str(), &buffer) == 0;
}

#if 0
ConsensusCore::Read SMRTSequenceToRead(const SMRTSequence& seq,
                                       const shared_ptr<ChemistryTriple>& triple,
                                       const ChemistryMapping& mapper)
{
    using ConsensusCore::QvSequenceFeatures;
    using ConsensusCore::Read;

    string bases(reinterpret_cast<const char*>(seq.seq));
    boost::to_upper(bases);
    QvSequenceFeatures features(bases,
                                seq.insertionQV.data,
                                seq.substitutionQV.data,
                                seq.deletionQV.data,
                                seq.deletionTag,
                                seq.mergeQV.data);
    Read read(features, seq.GetTitle(), mapper.MapTriple(*triple));

    return read;
}
#endif

void FlattenFofn(vector<string>& res, const string& file)
{
    using boost::algorithm::iends_with;
    using boost::algorithm::trim;

    if (iends_with(file, ".fofn"))
    {
        ifstream fofn(file);
        string line;
        while (getline(fofn, line))
        {
            trim(line);
            FlattenFofn(res, line);
        }
    }
    else if (iends_with(file, ".bam"))
        res.push_back(file);
    else
        throw invalid_argument("not a .fofn or .bam file!");
}

vector<string> FlattenFofn(const vector<string>& files)
{
    vector<string> res;

    for (const auto& file : files)
    {
        FlattenFofn(res, file);
    }

    return res;
}

} // namespace CCS
} // namespace PacBio

max_stars_repo_name: pb-cdunn/pbccs

max_issues_repo_name: pb-cdunn/pbccs

max_forks_repo_name: pb-cdunn/pbccs


text:
//==================================================================================================
/*!
  @file

  @copyright 2016 NumScale SAS
  @copyright 2016 J.T. Lapreste

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_CSC_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_CSC_HPP_INCLUDED

#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{

 /*!

    @ingroup group-trigonometric
    Function object implementing csc capabilities

    cosecante of the input in radian.

    @par Semantic:

    For every parameter of floating type T

    @code
    T r = csc(x);
    @endcode

    is similar to:

    @code
    T r = rec(sin(x));
    @endcode

    As most other trigonometric function csc can be called with a second optional parameter
    which is a tag on speed and accuracy (see @ref cos for further details)

    @see cscd, cscpi,

  **/
  const boost::dispatch::functor<tag::csc_> csc = {};
} }
#endif

#include <boost/simd/function/scalar/csc.hpp>
#include <boost/simd/function/simd/csc.hpp>

#endif


text:
#pragma once

#ifndef _node_ip_address_hpp
#define _node_ip_address_hpp

#include "../common/fast_hash.hpp"
#include "../common/term_serializer.hpp" // buffer_t
#include "../common/utime.hpp"

#include "asio_win32_check.hpp"
#include <boost/asio/ip/address.hpp>
#include <boost/asio/ip/address_v4.hpp>
#include <boost/asio/ip/address_v6.hpp>

namespace prologcoin { namespace node {

//
// This class abstracts IP addresses and normalize them to IPv6.
// We also add a bunch of useful predicates and other information
// extracting properties. If you look carefully at bitcoind you'll
// see that addresses are pretty complicated. Something that you first
// perceive as something easy, is not when you scratch its surface.
//
class ip_address {
public:
    inline ip_address()
    { memset(addr_, 0, sizeof(addr_)); }

    inline ip_address(const ip_address &other)
    { set_addr(other); }

    inline ip_address(const boost::asio::ip::address_v4 &v4)
    { set_addr(v4); }

    inline ip_address(const boost::asio::ip::address_v6 &v6)
    { set_addr(v6); }

    inline ip_address(const boost::asio::ip::address &ip)
    { set_addr(ip); }

    ip_address(const std::string &str);

    boost::asio::ip::address to_addr() const;

    inline void set_addr(const ip_address &other)
    { set_addr(other.to_bytes(), sizeof(addr_)); }

    inline void set_addr(const boost::asio::ip::address_v4 &v4)
    { set_addr(&v4.to_bytes()[0], 4); }

    inline void set_addr(const boost::asio::ip::address_v6 &v6)
    { set_addr(&v6.to_bytes()[0], 16); }

    inline void set_addr( const uint8_t *bytes, size_t n)
    {   assert(n == 4 || n == 16);
	if (n == 4) {
	    memcpy(&addr_[0], &AS_IP4[0], sizeof(AS_IP4));
	}
	memcpy(at_byte(-n), &bytes[0], n);
    }

    inline void set_addr( uint32_t value )
    { uint8_t bytes[4] = { static_cast<uint8_t>((value >> 24) & 0xff),
			   static_cast<uint8_t>((value >> 16) & 0xff),
			   static_cast<uint8_t>((value >> 8) & 0xff),
			   static_cast<uint8_t>(value & 0xff) };
	set_addr(bytes, 4);
    }

    inline const uint8_t * to_bytes() const { return &addr_[0]; }
    inline uint8_t * to_bytes() { return &addr_[0]; }
    inline size_t bytes_size() const { return sizeof(addr_); }

    inline bool operator == (const ip_address &other) const {
	return memcmp(to_bytes(), other.to_bytes(), sizeof(addr_)) == 0;
    }
    inline bool operator != (const ip_address &other) const {
	return memcmp(to_bytes(), other.to_bytes(), sizeof(addr_)) != 0;
    }
    inline bool operator < (const ip_address &other) const {
	return memcmp(to_bytes(), other.to_bytes(), sizeof(addr_)) < 0;
    }
    inline bool operator <= (const ip_address &other) const {
	return memcmp(to_bytes(), other.to_bytes(), sizeof(addr_)) <= 0;
    }
    inline bool operator > (const ip_address &other) const {
	return memcmp(to_bytes(), other.to_bytes(), sizeof(addr_)) > 0;
    }
    inline bool operator >= (const ip_address &other) const {
	return memcmp(to_bytes(), other.to_bytes(), sizeof(addr_)) >= 0;
    }

    bool is_zero() const;  // 0.0.0.0 (or 16 bytes with 0s)

    bool is_v4() const;
    bool is_v6() const;

    bool is_valid() const;
    bool is_local() const;
    bool is_routable() const;
    bool is_tor() const;

    bool is_rfc_1918() const; // IP4 private networks (10.0.0.0/8,
                              // 192.168.0.0/16, 172.16.0.0.12)
    bool is_rfc_2544() const; // IP4 inter-network (192.18.0.0/15)
    bool is_rfc_3927() const; // IP4 autoconfig (169.254.0.0/16)
    bool is_rfc_5737() const; // IP4 documentation (192.0.2.0/24,
                              // 198.51.100.0/24, 203.0.113.0/24)
    bool is_rfc_6598() const; // IP4 ISP-level NAT (100.64.0.0/10)

    bool is_rfc_3849() const; // IP6 documentation (2001:0DB8::/32)
    bool is_rfc_3964() const; // IP6 6to4 tunnelling (2002::/16)
    bool is_rfc_4193() const; // IP6 unique local (FC00::/7)
    bool is_rfc_4380() const; // IP6 Teredo tunnelling (2001::/32)
    bool is_rfc_4843() const; // IP6 ORCHID deprecated (2001:10::/28)
    bool is_rfc_4862() const; // IP6 autoconfig (FF80::/64)
    bool is_rfc_6052() const; // IP6 well known prefix (64:FF9b::/96)
    bool is_rfc_6145() const; // IP6 IP4-translated (::FFFF:0:0:0/96)
    bool is_rfc_7343() const; // IP6 ORCHID2 (2001:20::/28)
    bool is_he_net() const;   // 2001:470::/36

    uint64_t group() const; // Return unique value for network group

    std::string str(size_t maxlen = std::string::npos) const;

    static std::string group_str(uint64_t group);

private:
    void set_addr(const boost::asio::ip::address &addr);

    inline const unsigned char * at_byte(int index) const {
	if (index < 0) return &addr_[MAX+index]; else return &addr_[index];
    }

    inline unsigned char * at_byte(int index) {
	if (index < 0) return &addr_[MAX+index]; else return &addr_[index];
    }

    inline unsigned char b(int index) const {
	if (index < 0) return addr_[MAX+index]; else return addr_[index];
    }

    inline uint64_t u(int index) const {
	return static_cast<uint64_t>(b(index));
    }

    static const size_t MAX = 16;
    static const unsigned char AS_IP4 [12];
    unsigned char addr_[MAX];

    static const unsigned char AS_ONION [12];
};

}}

namespace std {
    template<> struct hash<prologcoin::node::ip_address> {
        size_t operator()(const prologcoin::node::ip_address &addr) const {
	    prologcoin::common::fast_hash h;
	    h.update(addr.to_bytes(), 16);
	    return static_cast<uint32_t>(h);
	}
    };
}

#endif

max_stars_repo_name: datavetaren/prologcoin

max_issues_repo_name: datavetaren/prologcoin

max_forks_repo_name: datavetaren/prologcoin


text:
#ifndef CLP_UTILS_HPP
#define CLP_UTILS_HPP

// C++ standard libraries
#include <string>

// Boost libraries
#include <boost/filesystem/path.hpp>

// Project headers
#include "../streaming_archive/writer/Archive.hpp"
#include "../streaming_archive/writer/File.hpp"
#include "FileToCompress.hpp"

namespace clp {
    /**
     * Recursively finds all files and empty directories at the given path
     * @param path_prefix_to_remove
     * @param path
     * @param file_paths
     * @param empty_directory_paths
     * @return true on success, false otherwise
     */
    bool find_all_files_and_empty_directories (boost::filesystem::path& path_prefix_to_remove, const std::string& path, std::vector<FileToCompress>& file_paths,
                                               std::vector<std::string>& empty_directory_paths);

    /**
     * Checks if the given sequence is valid UTF-8
     * @param sequence_length
     * @param sequence
     * @return true if valid, false otherwise
     */
    bool is_utf8_sequence (size_t sequence_length, const char* sequence);

    /**
     * Reads a list of input paths
     * @param list_path
     * @param paths
     * @return true on success, false otherwise
     */
    bool read_input_paths (const std::string& list_path, std::vector<std::string>& paths);

    /**
     * Removes the given prefix from the given path and cleans the path as follows:
     * - Removes redundant '.' and ".."
     * - Makes the path absolute
     * @param prefix_to_remove
     * @param path
     * @param path_without_prefix_string
     * @return false if the path didn't contain the prefix or it didn't contain anything besides the prefix, true otherwise
     */
    bool remove_prefix_and_clean_up_path (const boost::filesystem::path& prefix_to_remove, const boost::filesystem::path& path,
                                          std::string& path_without_prefix_string);

    /**
     * Validates that all paths in the given list exist
     * @param paths
     * @return true if they all exist, false otherwise
     */
    bool validate_paths_exist (const std::vector<std::string>& paths);

    /**
     * Creates and opens a file within the given archive
     * @param archive
     * @param path_for_compression
     * @param group_id
     * @param orig_file_id
     * @param split_ix
     * @return A pointer to the file
     */
    streaming_archive::writer::File* create_and_open_file (streaming_archive::writer::Archive& archive, const std::string& path_for_compression,
                                                           group_id_t group_id, const boost::uuids::uuid& orig_file_id, size_t split_ix);

    /**
     * Closes the given encoded file and marks it ready for a segment
     * @param archive
     * @param file
     */
    void close_file_and_mark_ready_for_segment (streaming_archive::writer::Archive& archive, streaming_archive::writer::File*& file);

    /**
     * Closes the current archive and starts a new one
     * @param archive_user_config
     * @param archive_writer
     */
    void split_archive (streaming_archive::writer::Archive::UserConfig& archive_user_config, streaming_archive::writer::Archive& archive_writer);

    /**
     * Closes the current encoded file and starts a new one
     * @param path_for_compression
     * @param group_id
     * @param last_timestamp_pattern
     * @param archive_writer
     * @param file
     */
    void split_file (const std::string& path_for_compression, group_id_t group_id, const TimestampPattern* last_timestamp_pattern,
                     streaming_archive::writer::Archive& archive_writer, streaming_archive::writer::File*& file);

    /**
     * Closes both the current encoded file and archive, then starts a new archive and encoded file
     * @param archive_user_config
     * @param path_for_compression
     * @param group_id
     * @param last_timestamp_pattern
     * @param archive_writer
     * @param file
     */
    void split_file_and_archive (streaming_archive::writer::Archive::UserConfig& archive_user_config, const std::string& path_for_compression,
                                 group_id_t group_id, const TimestampPattern* last_timestamp_pattern, streaming_archive::writer::Archive& archive_writer,
                                 streaming_archive::writer::File*& file);
}

#endif // CLP_UTILS_HPP

max_stars_repo_name: y-scope/clp-core

max_issues_repo_name: y-scope/clp-core

max_forks_repo_name: y-scope/clp-core


text:
//  Copyright (c) 2006 Ole Christian Weidner (oweidner@cct.lsu.edu)
//
//  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 <fstream>

#include <saga/saga/util.hpp>
#include <saga/saga/adaptors/adaptor.hpp>
#include <saga/saga/path_leaf.hpp>

#include "default_test_helper_utils.hpp"

#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>

SAGA_TEST_HELPER_REGISTER(file_test_helper_utils_impl);

///////////////////////////////////////////////////////////////////////////////
//
void file_test_helper_utils_impl::delete_temp_file (saga::url path)
{
    mutex_type::scoped_lock lock(mtx_);
    boost::filesystem::remove(boost::filesystem::path(path.get_path()));
}
//
///////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////
//
void file_test_helper_utils_impl::delete_temp_dir  (saga::url path)
{
    mutex_type::scoped_lock lock(mtx_);
    boost::filesystem::remove_all(boost::filesystem::path(path.get_path()));
}
//
///////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////
//
saga::url
file_test_helper_utils_impl::create_temp_file_for_exception( const saga::error & e )
{
  mutex_type::scoped_lock lock(mtx_);
  std::string unique_path = get_unique_path_name();
  saga::url unique_url;

  switch (e) {

     case saga::adaptors::Success:
     {
       unique_url = saga::url(unique_path);
       unique_url.set_scheme("file");
       unique_url.set_host("localhost");

#if BOOST_FILESYSTEM_VERSION == 3
       boost::filesystem::path p (saga::url::unescape(unique_url.get_path()));
#else
       boost::filesystem::path p (saga::url::unescape(unique_url.get_path()),
                                boost::filesystem::native);
#endif

       std::fstream file;

       file.open (p.string().c_str (), std::ios::out);
       file.close();
     }
       break;

     case saga::IncorrectState:
     {
       unique_url = saga::url(unique_path);
       unique_url.set_scheme("file");
       unique_url.set_host("localhost");

#if BOOST_FILESYSTEM_VERSION == 3
       boost::filesystem::path p (saga::url::unescape(unique_url.get_path()));
#else
       boost::filesystem::path p (saga::url::unescape(unique_url.get_path()),
                                boost::filesystem::native);
#endif

       std::fstream file;

       file.open (p.string().c_str (), std::ios::out);
       file.close();
     }
       break;

     case saga::BadParameter:
     {
       unique_url = saga::url(unique_path);
       unique_url.set_scheme("file");
       unique_url.set_host("localhost");

#if BOOST_FILESYSTEM_VERSION == 3
       boost::filesystem::path p (saga::url::unescape(unique_url.get_path()));
#else
       boost::filesystem::path p (saga::url::unescape(unique_url.get_path()),
                                boost::filesystem::native);
#endif

       std::fstream file;

       file.open (p.string().c_str (), std::ios::out);
       file.close();
     }
       break;
     case saga::DoesNotExist:
     {
       unique_url = saga::url(unique_path);
       unique_url.set_scheme("file");
       unique_url.set_host("localhost");
     }
       break;

     case saga::IncorrectURL:
     {
       unique_url = saga::url("file:local:-host/~.../");

     }
       break;

     case saga::PermissionDenied:
     {
       // create a file with insufficient permissions and return the url
     }
       break;

     default:
     {
       unique_url = saga::url("");
     }
       break;
   }

  return unique_url;
}
//
///////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////
//
saga::url
file_test_helper_utils_impl::create_temp_dir_for_exception( const saga::error & e )
{
  mutex_type::scoped_lock lock(mtx_);
  std::string unique_path = get_unique_path_name();
  saga::url unique_url;

  switch (e) {

     case saga::adaptors::Success:
     {
        unique_url = saga::url(unique_path);
        unique_url.set_scheme("file");
        unique_url.set_host("localhost");
        unique_path = saga::url::unescape(unique_path);
        std::string::size_type pos = unique_path.find_first_of(SAGA_PATH_DELIMITERS);
        if (unique_path.size()-1 != pos)
            unique_path += "/";
        boost::filesystem::path p (saga::url::unescape(unique_url.get_path()));
        try {
           boost::filesystem::create_directory(unique_path);
        }
        catch(boost::filesystem::filesystem_error const& e) {
           std::cerr << e.what() << std::endl;
        }
     }
       break;
     //Just make a normal one and let tests take care of rest
     case saga::AlreadyExists:
     {
        unique_url = saga::url(unique_path);
        unique_url.set_scheme("file");
        unique_url.set_host("localhost");
        unique_path = saga::url::unescape(unique_path);
        std::string::size_type pos = unique_path.find_first_of(SAGA_PATH_DELIMITERS);
        if (unique_path.size()-1 != pos)
            unique_path += "/";
        boost::filesystem::path p (saga::url::unescape(unique_url.get_path()));
        try {
           boost::filesystem::create_directory(unique_path);
        }
        catch(boost::filesystem::filesystem_error const& e) {
           std::cerr << e.what() << std::endl;
        }
     }
       break;

     case saga::IncorrectState:
     {
        unique_url = saga::url(unique_path);
        unique_url.set_scheme("file");
        unique_url.set_host("localhost");
        unique_path = saga::url::unescape(unique_path);
        std::string::size_type pos = unique_path.find_first_of(SAGA_PATH_DELIMITERS);
        if (unique_path.size()-1 != pos)
            unique_path += "/";
        boost::filesystem::path p(unique_path);
        try {
           saga::detail::remove_trailing_dot(p);
           boost::filesystem::create_directory(p);
        }
        catch(boost::filesystem::filesystem_error const& e) {
           std::cerr << e.what() << std::endl;
        }
     }
       break;

     case saga::BadParameter:
     {
        unique_url = saga::url(unique_path);
        unique_url.set_scheme("file");
        unique_url.set_host("localhost");
        unique_path = saga::url::unescape(unique_path);
        std::string::size_type pos = unique_path.find_first_of(SAGA_PATH_DELIMITERS);
        if (unique_path.size()-1 != pos)
            unique_path += "/";
        boost::filesystem::path p(unique_path);
        try {
           saga::detail::remove_trailing_dot(p);
           boost::filesystem::create_directory(p);
        }
        catch(boost::filesystem::filesystem_error const& e) {
           std::cerr << e.what() << std::endl;
        }
     }
       break;
     case saga::DoesNotExist:
     {
        unique_url = saga::url(unique_path);
        unique_url.set_scheme("file");
        unique_url.set_host("localhost");
        std::string::size_type pos = unique_path.find_first_of(SAGA_PATH_DELIMITERS);
        if (unique_path.size()-1 != pos)
            unique_path += "/";
     }
       break;

     case saga::IncorrectURL:
     {
       unique_url = saga::url("file:local:-host/~.../");

     }
       break;

     case saga::PermissionDenied:
     {
       // create a file with insufficent permissions and return the url
     }
       break;

     default:
     {
       unique_url = std::string("");
     }
       break;
   }
//   return unique_path;
   return unique_url;
}
//
///////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////
//
saga::url file_test_helper_utils_impl::create_temp_file_name (bool create)
{
  mutex_type::scoped_lock lock(mtx_);
  std::string unique_path = get_unique_path_name();
  saga::url unique_url(unique_path);
  unique_url.set_scheme("file");
  unique_url.set_host("localhost");

  if(create) {
#if BOOST_FILESYSTEM_VERSION == 3
       boost::filesystem::path p (saga::url::unescape(unique_url.get_path()));
#else
       boost::filesystem::path p (saga::url::unescape(unique_url.get_path()),
                                boost::filesystem::native);
#endif

    std::fstream file;
    file.open (p.string().c_str (), std::ios::out);
    file.close();
  }
  return unique_url;
}
//
///////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////
//
saga::url file_test_helper_utils_impl::create_temp_dir_name (bool create)
{
  mutex_type::scoped_lock lock(mtx_);
  std::string unique_path = get_unique_path_name();
  saga::url unique_url(unique_path);
  unique_url.set_scheme("file");
  unique_url.set_host("localhost");

  std::string::size_type pos = unique_path.find_first_of(SAGA_PATH_DELIMITERS);
  if (unique_path.size()-1 != pos)
      unique_path += "/";
  if(create) {
    unique_path = saga::url::unescape(unique_path);
    boost::filesystem::path p(unique_url.get_path());
    try {
        boost::filesystem::create_directory(unique_path);
    }
    catch(boost::filesystem::filesystem_error const& e) {
        std::cerr << e.what() << std::endl;
    }
  }
  return unique_url;
}

max_stars_repo_name: saga-project/saga-cpp

max_issues_repo_name: saga-project/saga-cpp

max_forks_repo_name: saga-project/saga-cpp


text:
// Copyright 2018 Noud Aldenhoven
//
// Using boost with using-declarations seems almost impossible to me. Therefore
// disable the cpplint error.
//
// cpplint: --filter=-build/namespaces

#include <sqlite3.h>

#include <cmath>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>

#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/range/combine.hpp>
#include <boost/tokenizer.hpp>
using namespace boost;

#include "./stats.h"
#include "./tools.h"

template <typename T>
std::ostream &operator<<(std::ostream &out, const std::vector<T> &v) {
  out << "[";

  if (!v.empty()) {
    std::copy(v.begin(), v.end(), std::ostream_iterator<T>(out, ", "));
    out << "\b\b";
  }

  out << "]";
  return out;
}

ProblemStats::ProblemStats(std::string p, std::string a) {
  problem = p;
  answer = a;
  number_of_tries = 0;
  number_of_correct_tries = 0;
}

std::string ProblemStats::getProblem() { return problem; }

std::string ProblemStats::getAnswer() { return answer; }

void ProblemStats::addTry(unsigned int tries, double total_time) {
  number_of_tries += tries;
  number_of_correct_tries++;
  acc(total_time);
  time_per_try.push_back(total_time);
}

void ProblemStats::addTry(unsigned int tries, double total_time,
                          std::string date) {
  date_per_try.push_back(date);
  addTry(tries, total_time);
}

unsigned int ProblemStats::getNumberOfTries() { return number_of_tries; }

unsigned int ProblemStats::getNumberOfCorrectTries() {
  return number_of_correct_tries;
}

std::vector<double> ProblemStats::getTimePerTry() { return time_per_try; }

std::vector<std::string> ProblemStats::getDatePerTry() { return date_per_try; }

double ProblemStats::getMean() { return mean(acc); }

double ProblemStats::getMedian() { return median(acc); }

double ProblemStats::getStd() { return sqrt(variance(acc)); }

MemoryStats::MemoryStats(std::string const &p, std::string const &a,
                         std::string const &d, unsigned int c) {
  problem = p;
  answer = a;
  date = d;
  correct = c;
}

std::string const MemoryStats::getProblem() { return problem; }

std::string const MemoryStats::getAnswer() { return answer; }

std::string const MemoryStats::getDate() { return date; }

unsigned int MemoryStats::getCorrect() { return correct; }

void Statistics::readSpeedCSV(std::string const &csv_path) {
  std::ifstream csv;
  csv.open(csv_path.c_str());

  typedef tokenizer<escaped_list_separator<char>> Tokenizer;
  std::vector<std::string> svec;
  std::string line;

  // Get header, and drop it.
  getline(csv, line);

  std::string date, problem, answer;
  unsigned int tries;
  double time;
  while (getline(csv, line)) {
    Tokenizer tok(line);
    svec.assign(tok.begin(), tok.end());

    date = svec.at(0);
    problem = svec.at(1);
    answer = svec.at(2);
    tries = lexical_cast<unsigned int>(svec.at(3));
    time = lexical_cast<double>(svec.at(4));

    auto const search = problem_statistics.find(problem);
    if (search == problem_statistics.end()) {
      problem_statistics.emplace(problem, new ProblemStats(problem, answer));
    }
    problem_statistics[problem]->addTry(tries, time, date);
  }

  csv.close();
}

void Statistics::readSpeedSQL(std::string const &sql_path) {
  sqlite3 *db;
  sqlite3_stmt *stmt;

  if (sqlite3_open(sql_path.c_str(), &db) != SQLITE_OK) {
    std::string const err_msg =
        "readSpeedSQL(): could not open SQLite database " + sql_path + ".";
    throw std::runtime_error(err_msg);
  }

  std::string const query =
      "select date, problem, solution, number_of_tries, time_to_solve from "
      "speed;";
  if (sqlite3_prepare_v2(db, query.c_str(), -1, &stmt, NULL) != SQLITE_OK) {
    std::string const err_msg = "readSpeedSQL(): could not execute query '" +
                                query + "', compiling error: '" +
                                sqlite3_errmsg(db) + "'.";
    sqlite3_close(db);
    sqlite3_finalize(stmt);
    throw std::runtime_error(err_msg);
  }

  int ret_code;
  while ((ret_code = sqlite3_step(stmt)) == SQLITE_ROW) {
    const std::string date = std::string(
        reinterpret_cast<const char *>(sqlite3_column_text(stmt, 0)));
    const std::string problem = std::string(
        reinterpret_cast<const char *>(sqlite3_column_text(stmt, 1)));
    const std::string solution = std::string(
        reinterpret_cast<const char *>(sqlite3_column_text(stmt, 2)));
    const int tries = sqlite3_column_int(stmt, 3);
    const double time = sqlite3_column_double(stmt, 4);

    auto const search = problem_statistics.find(problem);
    if (search == problem_statistics.end()) {
      problem_statistics.emplace(problem, new ProblemStats(problem, solution));
    }
    problem_statistics[problem]->addTry(tries, time, date);
  }

  if (ret_code != SQLITE_DONE) {
    std::string const err_msg =
        "readSpeedSQL(): error while executing query '" + query +
        "', compiling error: '" + sqlite3_errmsg(db) + "'.";
    sqlite3_close(db);
    sqlite3_finalize(stmt);
    throw std::runtime_error(err_msg);
  }

  sqlite3_close(db);
  sqlite3_finalize(stmt);
}

void Statistics::readMemoryCSV(std::string const &csv_path) {
  std::ifstream csv;
  csv.open(csv_path.c_str());

  typedef tokenizer<escaped_list_separator<char>> Tokenizer;
  std::vector<std::string> svec;
  std::string line;

  // Get the header, and drop it.
  getline(csv, line);

  std::string data, problem, answer;
  unsigned int correct;
  while (getline(csv, line)) {
    Tokenizer tok(line);
    svec.assign(tok.begin(), tok.end());

    data = svec.at(0);
    problem = svec.at(1);
    answer = svec.at(2);
    correct = lexical_cast<unsigned int>(svec.at(3));

    MemoryStats memory_stat(problem, answer, data, correct);
    memory_statistics.push_back(memory_stat);
  }

  csv.close();
}

void Statistics::readMemorySQL(std::string const &sql_path) {
  throw std::runtime_error("readMemorySQL(): Not implemented.");
}

void Statistics::printProblemMeanHistogram() {
  // Number of bins to show maximal in histogram
  auto const bins = 50;

  // Minimal number of elements in a histogram bin.
  auto const min_hist_size = 10;

  std::vector<float> time_per_question;
  for (auto const &ps : problem_statistics) {
    for (auto const &time : ps.second->getTimePerTry()) {
      time_per_question.push_back(time);
    }
  }

  auto const min =
      *std::min_element(time_per_question.begin(), time_per_question.end());
  auto const max =
      *std::max_element(time_per_question.begin(), time_per_question.end());
  auto const bin_length = (max - min) / bins;

  if (max <= min) {
    std::string const err_msg =
        "printProblemMeanHistogram(): maximum value "
        "should be bigger than minimum value."
        " !(" +
        std::to_string(max) + " > " + std::to_string(min) + ")";
    throw std::runtime_error(err_msg);
  }

  std::vector<int> histogram(bins + 1);
  for (auto const time : time_per_question) {
    auto const which_bin = static_cast<int>((time - min) / bin_length);
    histogram.at(which_bin)++;
  }

  auto const hist_max_size =
      *std::max_element(histogram.begin(), histogram.end());
  for (unsigned int i = 0; i <= bins; i++) {
    if (histogram.at(i) < min_hist_size) {
      continue;
    }

    std::cout << format("%-4f - %-4f: ") % (min + i * bin_length) %
                     (min + (i + 1) * bin_length);

    unsigned int const hist_bar_size =
        (bar_width * histogram.at(i)) / hist_max_size;
    for (unsigned int j = 0; j < hist_bar_size; j++) {
      std::cout << "-";
    }

    std::cout << "| (" << histogram.at(i) << ")" << std::endl;
  }
}

void Statistics::printMemoryHistogram() {
  // Number of bins to show maximal in histogram.
  auto const bins = 10;

  // Maximum bin length.

  std::vector<unsigned int> histogram(bins + 1);
  for (auto &ms : memory_statistics) {
    auto hist_bin = ms.getCorrect();
    histogram.at(hist_bin)++;
  }

  auto const min = 0;
  auto const max = *std::max_element(histogram.begin(), histogram.end());

  if (!(max > min)) {
    std::string const err_msg =
        "printmemoryHistogram(): maximum value is not "
        "larger than minimum value."
        "!(" +
        std::to_string(max) + " > " + std::to_string(min) + ")";
    throw std::runtime_error(err_msg);
  }

  for (unsigned int i = 0; i <= bins; i++) {
    std::cout << format("%-2i") % i << " correct : ";
    unsigned int const hist_bar_size = (bar_width * histogram.at(i)) / max;
    for (unsigned int j = 0; j < hist_bar_size; j++) {
      std::cout << "-";
    }

    std::cout << "| (" << histogram.at(i) << ")" << std::endl;
  }
}

void Statistics::printSpeedProblemPerDay() {
  // Choose Median as default.
  printSpeedProblemPerDay(StatsType::Median);
}

void Statistics::printSpeedProblemPerDay(StatsType const &stats_type) {
  auto const min_tries_threshold = 10;

  std::vector<std::string> days_of_the_week{"Mon", "Tue", "Wed", "Thu",
                                            "Fri", "Sat", "Sun"};

  using acc = accumulator_set<double, features<tag::mean, tag::median>>;

  std::map<std::string, acc> time_per_day;
  std::map<std::string, unsigned int> num_of_tries_per_day;

  for (auto const &day : days_of_the_week) {
    acc new_acc;
    time_per_day[day] = new_acc;
    num_of_tries_per_day[day] = 0;
  }

  double time;
  std::string date;
  for (auto const &ps : problem_statistics) {
    auto const &time_per_try = ps.second->getTimePerTry();
    auto const &date_per_try = ps.second->getDatePerTry();
    for (auto const &time_date : boost::combine(time_per_try, date_per_try)) {
      boost::tie(time, date) = time_date;
      auto const pdate = ptimeFromString(date);
      auto const day = getDayOfWeek(pdate);

      time_per_day[day](time);
      num_of_tries_per_day[day]++;
    }
  }

  double min = 0;
  double max = 0;
  std::map<std::string, double> value_time_per_day;
  for (auto const &day : days_of_the_week) {
    if (num_of_tries_per_day[day] > min_tries_threshold) {
      double value;

      if (stats_type == StatsType::Median) {
        value = median(time_per_day[day]);
      } else if (stats_type == StatsType::Mean) {
        value = mean(time_per_day[day]);
      } else {
        throw std::runtime_error("StatsType not implemented.");
      }

      value_time_per_day[day] = value;

      min = (min == 0 || min > value) ? value : min;
      max = max < value ? value : max;
    } else {
      value_time_per_day[day] = 0.0;
    }
  }

  for (auto const &day : days_of_the_week) {
    if (num_of_tries_per_day[day] < min_tries_threshold) {
      continue;
    }

    std::cout << day << ": ";

    auto const value = value_time_per_day[day];
    auto const total_tries = num_of_tries_per_day[day];
    auto const width = (value - min) / (max - min) * bar_width;
    for (unsigned int i = 0; i < width; i++) {
      std::cout << "-";
    }
    std::cout << "| (" << value << "/" << total_tries << ")" << std::endl;
  }
}

void Statistics::printSpeedProblemPerHour() {
  // Choose median per default.
  printSpeedProblemPerHour(StatsType::Median);
}

void Statistics::printSpeedProblemPerHour(StatsType const &stats_type) {
  auto const min_tries_threshold = 10;

  using acc =
      accumulator_set<double, features<tag::mean, tag::median, tag::count>>;

  std::vector<acc> acc_per_hour;
  acc_per_hour.resize(24);

  double time;
  std::string date;
  for (auto const &ps : problem_statistics) {
    auto const &time_per_try = ps.second->getTimePerTry();
    auto const &date_per_try = ps.second->getDatePerTry();
    for (auto const &time_date : boost::combine(time_per_try, date_per_try)) {
      boost::tie(time, date) = time_date;
      auto const pdate = ptimeFromString(date);
      auto const hour = getHourOfDay(pdate);

      acc_per_hour.at(hour)(time);
    }
  }

  std::vector<double> value_per_hour;
  float min = 0;
  float max = 0;
  for (unsigned int hour = 0; hour < 24; hour++) {
    auto const total_tries = boost::accumulators::count(acc_per_hour.at(hour));

    if (total_tries > min_tries_threshold) {
      double value;
      if (stats_type == StatsType::Median) {
        value = median(acc_per_hour.at(hour));
      } else if (stats_type == StatsType::Mean) {
        value = mean(acc_per_hour.at(hour));
      } else {
        throw std::runtime_error("StatsType not implemented.");
      }
      value_per_hour.push_back(value);

      min = (min == 0 || min > value) ? value : min;
      max = (max < value) ? value : max;
    } else {
      value_per_hour.push_back(0);
    }
  }

  for (unsigned int hour = 0; hour < 24; hour++) {
    auto const value_time = value_per_hour.at(hour);
    auto const total_tries = boost::accumulators::count(acc_per_hour.at(hour));

    if (total_tries < min_tries_threshold) {
      continue;
    }

    std::cout << format("%-2i:00-%-2i:00: ") % hour % (hour + 1);

    auto const width = (value_time - min) / (max - min) * bar_width;
    for (unsigned int i = 0; i < width; i++) {
      std::cout << "-";
    }
    std::cout << "| (" << value_time << "/" << total_tries << ")" << std::endl;
  }
}

void Statistics::printSpeedProblemPerProblem() {
  for (auto const &sp : problem_statistics) {
    std::cout << format("%-5s %-4f %-4f %i") % sp.first % sp.second->getMean() %
                     sp.second->getMedian() % sp.second->getNumberOfTries()
              << std::endl;
  }
}

void Statistics::printSpeedProblemPerWeek(unsigned int const back) {
  printSpeedProblemPerWeek(back, StatsType::Median);
}

void Statistics::printSpeedProblemPerWeek(unsigned int const back,
                                          StatsType const &stats_type) {
  using acc =
      accumulator_set<double, features<tag::mean, tag::median, tag::count>>;
  std::vector<std::pair<boost::posix_time::ptime, acc>> results_per_week;

  auto const now_time = ptimeFromString(getCurrentTime());
  auto const t = boost::posix_time::hours(7 * 24);
  auto cur_time = now_time - boost::posix_time::hours(back * 7 * 24);

  double time;
  std::string date;
  for (unsigned int i = 0; i < back; i++) {
    auto const cur_year = getYear(cur_time);
    auto const cur_week = getWeek(cur_time);

    acc cur_week_acc;
    for (auto const &ps : problem_statistics) {
      auto const &time_per_try = ps.second->getTimePerTry();
      auto const &date_per_try = ps.second->getDatePerTry();
      for (auto const &time_date : boost::combine(time_per_try, date_per_try)) {
        boost::tie(time, date) = time_date;
        auto const pdate = ptimeFromString(date);
        auto const pweek = getWeek(pdate);
        auto const pyear = getYear(pdate);

        if (pweek == cur_week && pyear == cur_year) {
          cur_week_acc(time);
        }
      }
    }

    results_per_week.push_back(
        std::pair<boost::posix_time::ptime, acc>{cur_time, cur_week_acc});

    cur_time += t;
  }

  for (auto const &pta : results_per_week) {
    auto const cur_year = getYear(pta.first);
    auto const cur_week = getWeek(pta.first);
    auto const num_tries = boost::accumulators::count(pta.second);

    double value;
    if (stats_type == StatsType::Median) {
      value = median(pta.second);
    } else if (stats_type == StatsType::Mean) {
      value = mean(pta.second);
    } else {
      throw std::runtime_error("StatsType not implemented.");
    }

    std::cout << cur_year << " " << cur_week << " " << num_tries << " " << value
              << std::endl;
  }
}

std::vector<float> Statistics::getSpeedData() {
  std::vector<float> speed_data;

  for (auto const &ps : problem_statistics) {
    auto const &time_per_try = ps.second->getTimePerTry();
    for (auto const &t : time_per_try) {
      speed_data.push_back(t);
    }
  }

  return speed_data;
}

max_stars_repo_name: noudald/fatigue

max_issues_repo_name: noudald/fatigue

max_forks_repo_name: jwaixs/fatigue


text:
//==============================================================================
//         Copyright 2003 - 2011   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_SIMD_CONSTANT_CONSTANTS_FACT_7_HPP_INCLUDED
#define BOOST_SIMD_CONSTANT_CONSTANTS_FACT_7_HPP_INCLUDED

#include <boost/simd/include/functor.hpp>
#include <boost/simd/constant/register.hpp>
#include <boost/simd/constant/hierarchy.hpp>
#include <boost/config.hpp>

#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable: 4310) // truncation of constant
#endif

namespace boost { namespace simd
{
  namespace tag
  {
   /*!
     @brief Fact_7 generic tag

     Represents the Fact_7 constant in generic contexts.

     @par Models:
        Hierarchy
   **/
    BOOST_SIMD_CONSTANT_REGISTER( Fact_7,double
                                , 5040, 0x459d8000, 0x40b3b00000000000ll
                                )
  }
  namespace ext
  {
   template<class Site>
   BOOST_FORCEINLINE generic_dispatcher<tag::Fact_7, Site> dispatching_Fact_7(adl_helper, boost::dispatch::meta::unknown_<Site>, ...)
   {
     return generic_dispatcher<tag::Fact_7, Site>();
   }
   template<class... Args>
   struct impl_Fact_7;
  }
  /*!
    Generates 7! that is 5040

    @par Semantic:

    @code
    T r = Fact_7<T>();
    @endcode

    is similar to:

    @code
    T r = T(5040);
    @endcode
  **/
  BOOST_SIMD_CONSTANT_IMPLEMENTATION(boost::simd::tag::Fact_7, Fact_7)
} }

#ifdef BOOST_MSVC
#pragma warning(pop)
#endif

#include <boost/simd/constant/common.hpp>

#endif


text:
#pragma once

#include <bunsan/error.hpp>

#include <boost/optional.hpp>
#include <boost/property_tree/ptree.hpp>

#include <string>

namespace bunsan {

struct uninitialized_optional_error : virtual error {};

template <typename T, typename Error = uninitialized_optional_error>
const T &get(const boost::optional<T> &o, const std::string &msg) {
  if (!o) BOOST_THROW_EXCEPTION(Error() << error::message(msg));
  return o.get();
}

template <typename T, typename Error = uninitialized_optional_error>
const T &get(const boost::optional<T> &o) {
  if (!o) BOOST_THROW_EXCEPTION(Error());
  return o.get();
}

template <typename T, typename Error = uninitialized_optional_error>
T &get(boost::optional<T> &o, const std::string &msg) {
  if (!o) BOOST_THROW_EXCEPTION(Error() << error::message(msg));
  return o.get();
}

template <typename T, typename Error = uninitialized_optional_error>
T &get(boost::optional<T> &o) {
  if (!o) BOOST_THROW_EXCEPTION(Error());
  return o.get();
}

/*!
 * \brief if node does not exists, set it to value (empty Ptree by default),
 * return node
 */
template <typename Ptree>
Ptree &ptree_get(Ptree &ptree, const typename Ptree::path_type &path,
                 const Ptree &value = Ptree()) {
  return ptree.put_child(path, ptree.get_child(path, value));
}

}  // namespace bunsan


text:
/******************************************************
 *
 *
 *
 * mex -I/usr/include/eigen3 ssimcpp.cpp
 ******************************************************/

#include <iostream>
#include <math.h>
#include <Eigen/Dense>
#include "mex.h"

using namespace Eigen;
using namespace std;

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{

  const mwSize *dim;
  dim = mxGetDimensions(prhs[0]);

  double *Aptr, *Bptr;
  Aptr = mxGetPr(prhs[0]);
  Bptr = mxGetPr(prhs[1]);

  MatrixXd A, B, A2, B2;
  A.resize(dim[0],dim[1]);
  A << Map<MatrixXd>(Aptr, dim[0], dim[1]);
  B.resize(dim[0],dim[1]);
  B << Map<MatrixXd>(Bptr, dim[0], dim[1]);

  A2.resize(dim[0],dim[1]);
  B2.resize(dim[0],dim[1]);

  const double mA = A.mean();
  const double mB = B.mean();

  A2 = (A- mA*MatrixXd::Ones(dim[0], dim[1]));
  B2 = (B- mB*MatrixXd::Ones(dim[0], dim[1]));

  const double N = dim[0]*dim[1];
  const double sA = A2.cwiseAbs2().sum()/N;
  const double sB = B2.cwiseAbs2().sum()/N;

  double sAB = 0.0;
  uint i, j;
  for (i=0; i<N; i++){
      for (j=0; j<N; j++){
          if (j>i) sAB = sAB+(A(i)-A(j))*(B(i)-B(j));
      }
  }
  sAB = sAB/(N*N);

  plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
  double *Out;
  Out = mxGetPr(plhs[0]);
  MatrixXd::Map(Out, 1, 1) << (2*mA*mB+0.001)*(2*sAB+0.009)/((mB*mB+mA*mA+0.001)*(sB+sA+0.009));
  return;

}

//EOF

max_stars_repo_name: ysraell/gcbsrd

max_issues_repo_name: ysraell/gcbsrd

max_forks_repo_name: ysraell/gcbsrd