text:
#ifndef INCLUDE_ACKWARD_LOGGING_USERFILTER_HPP
#define INCLUDE_ACKWARD_LOGGING_USERFILTER_HPP

#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/python/default_call_policies.hpp>
#include <boost/python/make_function.hpp>
#include <boost/python/object.hpp>
#include <boost/shared_ptr.hpp>

#include <ackward/logging/Filter.hpp>
#include <ackward/logging/LogRecord.hpp>
#include <ackward/logging/Module.hpp>

namespace ackward {
namespace logging {

/** \rst

    A ``Filter`` subclass that allows you to define new ``Filter``\ s
    in C++.

    ``UserFilter`` forwards "filter" calls to a user-defined type which
    is passed as a template parameter to ``UserFilter``. To define a
    new ``Filter`` type, first create a class with a method ``int
    filter(const LogRecord&)``::

      struct MyFilterImpl
      {
          int filter(const LogRecord& lr) {
             ...do something...
          }
      }

    Then, create the UserHandler instance::

      typedef UserFilter<MyFilterImpl> MyFilter;

      Logger l = getLogger();
      MyFilter f;
      l.addFilter(f);

    \endrst
 */
template <typename T>
class UserFilter : public Filter
{
public:
    /** The pimpl-body for a UserFilter. */
    struct Body
    {
        Body(boost::python::object);

        // TODO: Does this need a destructor that replaces the target
        // function will something benign when this goes out of scope?

        static int filter(
            UserFilter<T>::Body* b,
            const LogRecord& lr);

        T impl_;

        // Python filter instance.
        boost::python::object filter_;
    };

public:
    UserFilter() :
        Filter( module().attr("Filter")() ),
        body_ (new Body(obj()))
        {}

    T& impl() { return body_->impl_; }
    const T& impl() const { return body_->impl_; }

private:
    boost::shared_ptr<Body> body_;
};

template <typename T>
UserFilter<T>::Body::Body(boost::python::object filter) :
    filter_ (filter)
{
    // Grab a pointer to the static filter() method.
    boost::function<int(Body*, const LogRecord&)> f =
        &UserFilter<T>::Body::filter;

    // These args tell make_function() the signature of filter() after
    // "this" is bound to the first argument.
    typedef boost::mpl::vector<
        int,
        const LogRecord&> FilterArgs;

    // This makes a python callable which calls the static filter
    // method.
    boost::python::object func =
        boost::python::make_function(
            boost::bind(f, this, _1),
            boost::python::default_call_policies(),
            FilterArgs());

    // Assign the python callable we just constructed to the "filter"
    // attribute of the handler.
    filter_.attr("filter") = func;
}

template <typename T>
int UserFilter<T>::Body::filter(
    UserFilter<T>::Body* b,
    const LogRecord& lr)
{
    // Body::emit() just forwards the call to the user-supplied impl.
    return b->impl_.filter(lr);
}

}
}

#endif /* INCLUDE_ACKWARD_LOGGING_USERFILTER_HPP */

max_stars_repo_name: abingham/ackward

max_issues_repo_name: abingham/ackward

max_forks_repo_name: abingham/ackward


text:
/* Copyright 2008 (C) Nicira, Inc.
 *
 * This file is part of NOX.
 *
 * NOX 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.
 *
 * NOX 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 NOX.  If not, see <http://www.gnu.org/licenses/>.
 */
#ifndef PACKET_IN_HH
#define PACKET_IN_HH 1

#include <memory>
#include <iostream>
#include <boost/shared_ptr.hpp>
#include <arpa/inet.h>
#include "openflow/openflow.h"
#include "buffer.hh"
#include "event.hh"
#include "netinet++/datapathid.hh"
#include "ofp-msg-event.hh"
#include "openflow.hh"
#include "flow.hh"

namespace vigil {

/** \ingroup noxevents
 *
 * Packet in events are thrown for each packet received by nox. The
 * packet buffer is stored in the parent class, Ofp_msg_event. To
 * access the buffer, use the get_buffer() member function.
 *
 * Unless a component retains a shared_ptr to the buffer, packets
 * are discarded after the Packet_in_event is thrown.  Sending
 * the packet back onto the network must be done explicitly.
 *
 */

struct Packet_in_event
    : public Event,
      public Ofp_msg_event
{
    Packet_in_event(datapathid datapath_id_, uint16_t in_port_,
                    std::auto_ptr<Buffer> buf_, size_t total_len_,
                    uint32_t buffer_id_, uint8_t reason_)
        : Event(static_get_name()), Ofp_msg_event((ofp_header*) NULL, buf_),
          datapath_id(datapath_id_), in_port(in_port_), total_len(total_len_),
          buffer_id(buffer_id_), reason(reason_), flow(htons(in_port), *buf)
        { }

    Packet_in_event(datapathid datapath_id_, uint16_t in_port_,
                    boost::shared_ptr<Buffer> buf_, size_t total_len_,
                    uint32_t buffer_id_, uint8_t reason_)
        : Event(static_get_name()), Ofp_msg_event((ofp_header*) NULL, buf_),
          datapath_id(datapath_id_), in_port(in_port_), total_len(total_len_),
          buffer_id(buffer_id_), reason(reason_), flow(htons(in_port), *buf)
        { }

    Packet_in_event(datapathid datapath_id_,
                    const ofp_packet_in *opi, std::auto_ptr<Buffer> buf_)
        : Event(static_get_name()), Ofp_msg_event(&opi->header, buf_),
          datapath_id(datapath_id_),
          in_port(ntohs(opi->in_port)),
          total_len(ntohs(opi->total_len)),
          buffer_id(ntohl(opi->buffer_id)),
          reason(opi->reason), flow(htons(in_port), *buf)
        { }

    virtual ~Packet_in_event() { }

    const boost::shared_ptr<Buffer>& get_buffer() const { return buf; }

    static const Event_name static_get_name() {
        return "Packet_in_event";
    }

    //! ID of switch the packet was received from
    datapathid datapath_id;
    //! Switch specific port number packet was received on
    uint16_t in_port;
    //! The total length of the packet including all headers
    size_t   total_len;
    uint32_t buffer_id;
    //! Did packet match an entry, or not?
    /*!
      One of ofp_packet_in_reason values describing why the packet was
      sent to the controller.  Possible values include:
      <ul>
        <li> OFPR_NO_MATCH : There was no matching entry
        <li> OFPR_ACTION : There was a match and the action was "send to controller"
      </ul>
     */
    uint8_t  reason;

    /** \brief Flow interpretation
     */
    Flow flow;

    Packet_in_event(const Packet_in_event&);
    Packet_in_event& operator=(const Packet_in_event&);
};

} // namespace vigil

#endif /* packet-in.hh */

ext: hh

max_stars_repo_name: ayjazz/OESS

max_issues_repo_name: ayjazz/OESS

max_forks_repo_name: ayjazz/OESS


text:
// Copyright 2010 The Trustees of Indiana University.

// 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)

//  Authors: Jeremiah Willcock
//           Andrew Lumsdaine

#include <boost/graph/random_spanning_tree.hpp>
#include <boost/graph/grid_graph.hpp>
#include <boost/array.hpp>
#include <boost/random.hpp>
#include <boost/property_map/shared_array_property_map.hpp>
#include <boost/property_map/dynamic_property_map.hpp>
#include <boost/graph/graphviz.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/graph/property_maps/constant_property_map.hpp>
#include <string>
#include <iostream>
#include <fstream>
#include <boost/graph/iteration_macros.hpp>

using namespace boost;
using namespace std;

typedef grid_graph<2> graph_type;
typedef graph_traits<graph_type> gt;

template <typename Graph, typename PredMap, typename WeightMap>
void write_spanning_tree(const Graph& g, PredMap pred, WeightMap weight, string filename) {
  shared_array_property_map<string, typename property_map<Graph, edge_index_t>::const_type> edge_style(num_edges(g), get(edge_index, g));
  shared_array_property_map<string, typename property_map<Graph, vertex_index_t>::const_type> vertex_pos(num_vertices(g), get(vertex_index, g));
  BGL_FORALL_EDGES_T(e, g, Graph) {
    put(edge_style, e, (get(pred, target(e, g)) == source(e, g) || get(pred, source(e, g)) == target(e, g)) ? "bold" : "dotted");
  }
  BGL_FORALL_VERTICES_T(v, g, Graph) {
    put(vertex_pos, v, lexical_cast<string>(v[0]) + "," + lexical_cast<string>(v[1]));
  }
  dynamic_properties dp;
  dp.property("style", edge_style);
  dp.property("pos", vertex_pos);
  dp.property("len", weight);
  dp.property("node_id", get(vertex_index, g));
  ofstream out(filename.c_str());
  write_graphviz_dp(out, g, dp);
}

int main(int, char**) {

  boost::array<size_t, 2> sizes = {{ 5, 5 }};
  graph_type g(sizes);

  shared_array_property_map<gt::vertex_descriptor, property_map<graph_type, vertex_index_t>::const_type> pred(num_vertices(g), get(vertex_index, g));
  shared_array_property_map<double, property_map<graph_type, edge_index_t>::const_type> weight(num_edges(g), get(edge_index, g));

  BGL_FORALL_EDGES(e, g, graph_type) {put(weight, e, (1. + get(edge_index, g, e)) / num_edges(g));}

  boost::mt19937 gen;
  random_spanning_tree(g, gen, predecessor_map(pred));
  // write_spanning_tree(g, pred, constant_property_map<gt::edge_descriptor, double>(1.), "unweight_random_st.dot");
  random_spanning_tree(g, gen, predecessor_map(pred));
  // write_spanning_tree(g, pred, constant_property_map<gt::edge_descriptor, double>(1.), "unweight_random_st2.dot");

  random_spanning_tree(g, gen, predecessor_map(pred).weight_map(weight));
  // write_spanning_tree(g, pred, weight, "weight_random_st.dot");

  return 0;
}

ext: cpp


text:
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdlib.h>
#include <Structs/Graphs/dynamicGraph.h>
#include <Structs/Graphs/adjacencyListImpl.h>
#include <Heuristics/blind.h>
#include <Heuristics/ideal.h>
#include <Heuristics/boundedIdeal.h>
#include <Algorithms/multicriteriaDijkstra.h>
#include <Algorithms/multicriteriaGraph.h>
#include <Algorithms/namoaStar2.h>
#include <Algorithms/namoaStar.h>
#include <Algorithms/multicriteriaArc.h>
#include <Utilities/timer.h>
#include <boost/program_options.hpp>

#define NUM_CRITERIA 2

namespace po = boost::program_options;

class Results
{
public:
    Results( const std::vector< std::pair<unsigned int, unsigned int> >& queries):m_queries(queries)
    {
    }

    void add( const std::string& header, const std::vector< double >& results)
    {
        m_headers.push_back(header);
        m_data.push_back(results);
    }

    void print(std::ostream& out)
    {
        out << "source\tdestination";
        for( unsigned int i = 0; i < m_headers.size(); ++i)
        {
            out << "\t" << m_headers[i];
        }
        out << "\n";
        for( unsigned int i = 0; i < m_queries.size(); ++i)
        {
            out << m_queries[i].first << "\t" << m_queries[i].second;
            for( unsigned int j = 0; j < m_data.size(); ++j)
            {
                out << "\t" << m_data[j][i];
            }
            out << "\n";
        }
    }

private:
    std::vector< std::string> m_headers;
    std::vector< std::vector<double> > m_data;
    const std::vector< std::pair<unsigned int, unsigned int> >& m_queries;
};

template< class DijkstraVariant, typename GraphType>
void runQueries( GraphType& G, std::vector< std::pair<unsigned int,unsigned int> >& queries, std::vector<typename GraphType::NodeDescriptor>& ids, Results& results, const std::string& graphname, const std::string& algoname)
{
    std::vector<double> times;
    std::vector<double> paths;
    std::vector<double> generatedLabels;
    typedef typename GraphType::NodeIterator NodeIterator;
    typename GraphType::NodeIterator s,t;
    unsigned int sourceId, targetId;
    unsigned int timestamp = 0;
    //create dijkstra
    DijkstraVariant dijkstra(G, NUM_CRITERIA, &timestamp);
    //create output message
    std::string message("Experiments at ");
    message.append( graphname + " " + algoname);
    ProgressBar show_progress( queries.size(), message);
    std::cout << message << std::endl;
    //run queries
    Timer timer;
    unsigned int query_n = 1;
    for( std::vector< std::pair<unsigned int,unsigned int> >::iterator it = queries.begin(); it != queries.end(); ++it)
    {
        //clear nodes
        NodeIterator u, lastnode;
        for( u = G.beginNodes(), lastnode = G.endNodes(); u != lastnode; ++u)
        {
            u->g_op.clear();
            u->g_cl.clear();
            u->labels.clear();
        }
        sourceId = it->first;
        targetId = it->second;
        std::cout << query_n << ") " << sourceId << "->" << targetId << std::endl;
        ++query_n;
        s = G.getNodeIterator( ids[sourceId]);
        t = G.getNodeIterator( ids[targetId]);
		std::cout << "Initializing...\n";
		timer.start();
        dijkstra.init( s, t, NUM_CRITERIA);
		std::cout << "Running query:\n";
        dijkstra.runQuery( s, t);
        times.push_back(timer.getElapsedTime());
        paths.push_back(t->g_cl.size());
        //paths.push_back(t->labels.size());
        generatedLabels.push_back(dijkstra.getGeneratedLabels());
        std::cout << "\tTime:\t" << times[times.size()-1] << "sec\n";
        std::cout << "\tNon-dominated solutions:\t" << t->g_cl.size() << "\n";
		std::cout << "\tGenerated labels: " << dijkstra.getGeneratedLabels() << "\n\n";
    }
    results.add(graphname + " " + algoname,times);
    results.add(graphname + " " + algoname,generatedLabels);
    results.add(graphname + " " + algoname + " |C|",paths);
}

template< typename GraphType>
void runExperimentsAt( GraphType& G, std::vector< std::pair<unsigned int,unsigned int> >& queries, std::vector<typename GraphType::NodeDescriptor>& ids, Results& results, const std::string& name, const unsigned int& algorithmVariant)
{
    switch( algorithmVariant)
    {
    case 1:
        // output message for all queries
        std::cout << "with NAMOA* (blind) ...\n\n";
        runQueries<NamoaStar2<GraphType,BlindHeuristic> >( G, queries, ids, results, name, "NAMOA*2_Blind");
        break;
    case 2:
        std::cout << "with NAMOA*_tc ...\n\n";
        runQueries<NamoaStar2<GraphType,TCHeuristic> >( G, queries, ids, results, name, "NAMOA*2_TC");
        break;
    case 3:
        std::cout << "with NAMOA*_bound_tc ...\n\n";
        runQueries<NamoaStar2<GraphType,BoundedTCHeuristic> >( G, queries, ids, results, name, "NAMOA*2_BTC");
        //std::cout << "with NAMOA* Arc Flags (" << name << ") ...\n\n";
        //runQueries<NamoaStarArc<GraphType,GreatCircleHeuristic> >( G, queries, ids, gChecker, showOnScreen);
        break;
    case 0: // default
        std::cout << "with NAMOA* (blind) ...\n\n";
        runQueries<NamoaStar2<GraphType,BlindHeuristic> >( G, queries, ids, results, name, "NAMOA*2_Blind");
        std::cout << "with NAMOA*_tc ...\n\n";
        runQueries<NamoaStar2<GraphType,TCHeuristic> >( G, queries, ids, results, name, "NAMOA*2_TC");
        std::cout << "with NAMOA*_bound_tc ...\n\n";
        runQueries<NamoaStar2<GraphType,BoundedTCHeuristic> >( G, queries, ids, results, name, "NAMOA*2_BTC");
        break;
    }
}

void readQueries( std::vector< std::pair<unsigned int,unsigned int> >& queries, const std::string& filename, const unsigned int& numQueries)
{
	std::string token;
	unsigned int uID,vID;
	std::ifstream in;
    in.exceptions ( std::ifstream::failbit | std::ifstream::badbit );
    std::cout << "Reading queries from " << filename << std::endl;
	unsigned int readQueries = 0;

	try {
    	in.open( filename.c_str());
        assert( in.good());
        while ( ((readQueries < numQueries) || numQueries == 0) && getline(in,token))
        {
			std::stringstream graphinfo;
			graphinfo.str(token);
        	graphinfo >> uID >> vID;
			queries.push_back( std::pair<unsigned int, unsigned int>( uID, vID));
			++readQueries;
        }
        in.close();
    }
    catch (std::ifstream::failure e) {
        std::cerr << "Exception opening/reading file '" << filename << "'\n";
        throw e;
    }
}

typedef DynamicGraph< AdjacencyListImpl, Node, Edge>       Graph;
typedef Graph::NodeIterator                                NodeIterator;
typedef Graph::EdgeIterator                                EdgeIterator;
typedef Graph::NodeDescriptor                              NodeDescriptor;

int main( int argc, char* argv[])
{
    std::string basePath = std::string(getenv("HOME")) + "/Projects/Graphs/DIMACS9/";
    // Set default parameters
    unsigned int numQueries = 50;
    unsigned int algorithmVariant = 0;
    std::string map ="NY";
    // Declare the supported options.
    po::options_description desc("Allowed options");
    desc.add_options()
        ("size,s", po::value< unsigned int>(), "number of queries. Default:50")
        ("algorithm,a", po::value< unsigned int>(), "NAMOA* algorithm. All[0], NAMOA* blind[1], NAMOA* TC[2], NAMOA* Bounded TC[3]. Default:0")
        ("map,m", po::value< std::string>(), "Input map. The name of the map to read. Maps must be in '$HOME/Projects/Graphs/DIMACS9/");
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);
    if (vm.empty()) {
        std::cout << desc << "\n";
        return 0;
    }
    if (vm.count("size"))       numQueries = vm["size"].as<unsigned int>();
    if (vm.count("algorithm"))  algorithmVariant = vm["algorithm"].as<unsigned int>();
    if (vm.count("map"))        map = vm["map"].as<std::string>();
    Graph G;
    DIMACS9DoubleReader<Graph> reader( basePath + map + "/" + map + "_dist.gr",
                                basePath + map + "/" + map + "_travel.gr", basePath + map + "/" + map + ".co");
    filetrace = map + "_trace.dat";
    o_debug.open(filetrace.c_str(), std::fstream::app);
    Timer timer;
    // read the input graph and store it in memory
    timer.start();
    G.read(&reader);
    std::cout << "Graph has " << (double)G.memUsage()/1048576 << " Mbytes. Time spent to read:\t" << timer.getElapsedTime() << "sec" << std::endl;
	std::vector< std::pair<unsigned int,unsigned int> > queries;
    readQueries( queries, basePath + map + "/" + map+ "_queries", numQueries);
    Results results(queries);
    runExperimentsAt( G, queries, reader.getIds(), results, "ADJ", algorithmVariant);
    map += "_results";
    // print results
    std::ofstream out(map.c_str(), std::fstream::app);
    results.print(out);
    out.close();
    o_debug.close();
    return 0;
}


text:
// (C) Copyright 2010 Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk
// (C) Copyright 2012 Vicente Botet
//
//  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)

#define BOOST_THREAD_VERSION 4

#include <iostream>
#include <string>
#include <boost/thread/synchronized_value.hpp>

  void addTrailingSlashIfMissing(boost::synchronized_value<std::string> & path)
  {
    boost::strict_lock_ptr<std::string> u=path.synchronize();

    if(u->empty() || (*u->rbegin()!='/'))
    {
      *u+='/';
    }
  }

void f(const boost::synchronized_value<int> &v) {
  std::cout<<"v="<<*v<<std::endl;
}

void g(const boost::const_strict_lock_ptr<int> &v) {
  std::cout<<"v="<<*v<<std::endl;
}

bool checkIfMissingTrailingSlash(boost::synchronized_value<std::string> & path)
{
  boost::strict_lock_ptr<std::string> u=path.synchronize();

  return (u->empty() || (*u->rbegin()!='/'));
}

int main()
{
  {
    boost::synchronized_value<int> v1;
    *v1=42;
    std::cout<<"v1="<<*v1<<std::endl;
    f(v1);
    int i=*v1;
    std::cout<<"i="<<i<<std::endl;

    {
      boost::strict_lock_ptr<int> u=v1.synchronize();

      *u+=43;
      std::cout<<"v1="<<*u<<std::endl;
      g(u);
    }
    boost::synchronized_value<int> v2(2);
    std::cout<<"v2="<<*v2<<std::endl;
    v2 = 3;
    std::cout<<"v2="<<*v2<<std::endl;

    boost::synchronized_value<int> v3(v2);
    std::cout<<"v3="<<*v3<<std::endl;
    v3 = v1;
    std::cout<<"v3="<<*v3<<std::endl;

    std::cout<<"v2="<<*v3<<std::endl;
    std::cout<<"v3="<<*v3<<std::endl;
    swap(v3,v2);
    v1.swap(v2);
    std::cout<<"v3="<<*v3<<std::endl;
  }
  {
    boost::synchronized_value<std::string> s;
    addTrailingSlashIfMissing(s);
    std::cout<<"s="<<std::string(*s)<<std::endl;
  }
  {
    boost::synchronized_value<std::string> s;
    s->append("foo/");
    s.synchronize()->append("foo");
    addTrailingSlashIfMissing(s);
    std::cout<<"s="<<std::string(*s)<<std::endl;
  }
  {
    boost::synchronized_value<std::string> s;
    s = std::string("foo/");
    std::cout<<"ss="<< s << std::endl;
  }
  {
    boost::synchronized_value<std::string> s;
    s = "foo/";
    std::cout<<"ss="<< s << std::endl;
  }
  {
    boost::synchronized_value<std::string> s1("a");
    boost::synchronized_value<std::string> s2;
    s2=s1;
    std::cout<<"s1="<< s1 << std::endl;
    std::cout<<"s2="<< s2 << std::endl;
  }
  {
    boost::synchronized_value<std::string> s1("a");
    boost::synchronized_value<std::string> s2("b");
    std::cout<<"s1="<< s1 << std::endl;
    std::cout<<"s2="<< s2 << std::endl;
    swap(s1,s2);
    std::cout<<"s1="<< s1 << std::endl;
    std::cout<<"s2="<< s2 << std::endl;
  }
#if ! defined(BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS)
  {
    boost::synchronized_value<std::string> sts("a");
    std::string s(sts);
    std::cout<<"ssts="<< s << std::endl;
  }
#endif
  {
    boost::synchronized_value<int> s1(1);
    boost::synchronized_value<int> s2(1);
    BOOST_ASSERT(s1==s2);
    BOOST_ASSERT(s1<=s2);
    BOOST_ASSERT(s1>=s2);
    BOOST_ASSERT(s1==1);
    BOOST_ASSERT(s1<=1);
    BOOST_ASSERT(s1>=1);
  }
  {
    boost::synchronized_value<int> s1(1);
    boost::synchronized_value<int> s2(2);
    BOOST_ASSERT(s1!=s2);
    BOOST_ASSERT(s1!=2);
    BOOST_ASSERT(2!=s1);
  }
  {
    boost::synchronized_value<int> s1(1);
    boost::synchronized_value<int> s2(2);
    BOOST_ASSERT(s1<s2);
    BOOST_ASSERT(s1<=s2);
    BOOST_ASSERT(s2>s1);
    BOOST_ASSERT(s2>=s1);
    BOOST_ASSERT(s1<2);
    BOOST_ASSERT(s1<=2);
    BOOST_ASSERT(s2>1);
    BOOST_ASSERT(s2>=1);
  }
  return 0;
}


text:
//               Copyright Ross MacGregor 2013
// 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 "AsioExpressTest/pch.hpp"

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

#include "AsioExpress/ErrorCodes.hpp"
#include "AsioExpress/Testing/AutoCompletionHandler.hpp"
#include "AsioExpress/Testing/TestCompletionHandler.hpp"
#include "AsioExpress/Yield.hpp"
#include "AsioExpress/Proc/RunProcWithErrors.hpp"

using namespace AsioExpress;
using namespace AsioExpress::Testing;
using namespace std;

class ExternComponent
{
public:
  void AsyncDoThis(
      int n,
      AsioExpress::CompletionHandler completionHandler)
  {
    if (n==0)
      completionHandler(AsioExpress::Error(AsioExpress::ErrorCode::EventQueueTimeout));
    else
      completionHandler(AsioExpress::Error());
  }

  void AsyncDoThat(
      int n,
      AsioExpress::CompletionHandler completionHandler)
  {
    if (n==0)
      completionHandler(AsioExpress::Error(AsioExpress::ErrorCode::EventQueueTimeout));
    else
      completionHandler(AsioExpress::Error());
  }
};

typedef std::vector<std::string> StringList;
typedef boost::shared_ptr<StringList> StringListPointer;

static void MyProcessor(
  AsioExpress::Error error,
  AsioExpress::Proc::Context context,
  ExternComponent * externComponent,
  int n,
  StringListPointer list)
{
  REENTER(context.Coroutine())
  {
    for (int i=0; i<n; ++i)
      list->push_back(boost::lexical_cast<std::string>(i));

    YIELD
    {
      externComponent->AsyncDoThis(
        n,
        PushProcWithErrors(&MyProcessor,context,externComponent,n,list));
    }
    if (error)
    {
      // ignore
    }

    YIELD
    {
      externComponent->AsyncDoThat(
        n,
        PushProcWithErrors(&MyProcessor,context,externComponent,n,list));
    }
    if (error)
    {
      context.Complete(error);
      return;
    }

    context.Complete();
  }
}

struct Setup
{
  Setup() :
    m_externComponent(new ExternComponent)
  {
  }

  ~Setup()
  {
    delete m_externComponent;
    m_externComponent = 0;
  }

  ExternComponent * m_externComponent;
};

BOOST_FIXTURE_TEST_SUITE(RunProcTest, Setup)

BOOST_AUTO_TEST_CASE(TestRunProcWithErrors)
{
  using namespace AsioExpress::Proc;
  using namespace AsioExpress;

  boost::asio::io_service ioService;
  int const N = 5;
  StringListPointer list(new StringList);
  AsioExpress::Testing::AutoCompletionHandler completionHandler(__FILE__,__LINE__);

  RunProcWithErrors(
    &MyProcessor,
    Context(ioService,__FUNCTION__,completionHandler),
    m_externComponent,
    N,
    list);

  BOOST_CHECK_EQUAL(completionHandler.Calls(), 1);
}

BOOST_AUTO_TEST_CASE(TestRunProcWithErrorsError)
{
  using namespace AsioExpress::Proc;
  using namespace AsioExpress;

  boost::asio::io_service ioService;
  int const N = 0;
  StringListPointer list(new StringList);
  AsioExpress::Testing::TestCompletionHandler completionHandler;

  RunProcWithErrors(
    &MyProcessor,
    Context(ioService,__FUNCTION__,completionHandler),
    m_externComponent,
    N,
    list);

  BOOST_CHECK_EQUAL(completionHandler.Calls(), 1);
  BOOST_CHECK(completionHandler.LastError() == AsioExpress::ErrorCode::EventQueueTimeout);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: suhao/asioexpress

max_issues_repo_name: suhao/asioexpress

max_forks_repo_name: suhao/asioexpress


text:
// Filename: init_list_example.cpp (part of MTL4)

#include <iostream>
#include <boost/numeric/mtl/mtl.hpp>

template <typename Matrix>
void p(const Matrix& A)
{
    std::cout << A;
}

int main()
{
#if defined(MTL_WITH_INITLIST) && defined(MTL_WITH_AUTO) && defined(MTL_WITH_RANGEDFOR)
    const mtl::dense2D<double> A={{3, 4},
	  	                 {5, 6}};
    mtl::dense2D<double>       B;
    B= {{3, 4},
	{5, 6}};

    mtl::dense_vector<double> v= {2, 3, 4, 5};

    p(mtl::dense2D<double>{{1, 2}, {2, 3}});
#endif
    return 0;
}


text:
// Copyright Ricardo Calheiros de Miranda Cosme 2017.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

#pragma once

#include "observable/traits.hpp"
#include "observable/types.hpp"

#include <boost/fusion/include/at_key.hpp>
#include <boost/fusion/include/for_each.hpp>
#include <boost/fusion/include/map.hpp>
#include <boost/fusion/include/move.hpp>
#include <boost/fusion/include/pair.hpp>
#include <boost/signals2.hpp>

#include <array>
#include <type_traits>

namespace observable {

template<typename>
struct map;

template<typename>
struct unordered_map;

template<typename>
struct unordered_set;

template<typename>
struct variant;

template<typename>
struct vector;

template<typename Parent>
struct set_on_change
{
    set_on_change(Parent& p)
        : _parent(p)
        , _it(_parent.observable_on_change_conns.begin())
    {}

    template<typename T>
    void operator()(T& o) const
    {
        auto& parent = _parent;
        *_it++ =
            o.second.on_change(
            [&parent](const typename T::second_type::Observed&)
            { parent._on_change(parent.get()); });
    }

    Parent& _parent;
    mutable typename Parent::observable_on_change_conns_t::iterator _it;
};

template<typename Observed>
struct observable_of<
    Observed,
    typename std::enable_if<is_class<Observed>::value>::type
>
{
    using type = typename is_class<Observed>::type;
};

template<typename Observed_, typename... Members>
class class_
{
public:
    using Observed = Observed_;
    using Tag2Observable = boost::fusion::map<
        boost::fusion::pair<
            typename Members::second_type,
            observable_of_t<typename Members::first_type>
        >...>;

    class_() = default;

    template<typename... Observeds>
    class_(Observed& observed,
           Observeds&&... observeds)
        : _observed(&observed)
        , _tag2observable
          (boost::fusion::pair<
           typename Members::second_type,
           observable_of_t<typename std::decay<Observeds>::type>>
           (observable_of_t<typename std::decay<Observeds>::type>
            (observable_factory(std::forward<Observeds>(observeds))))...)
    {
        set_on_change<class_<Observed_, Members...>> visitor{*this};
        boost::fusion::for_each(_tag2observable, visitor);
    }

    class_(class_&& rhs) noexcept
        : _observed(rhs._observed)
        , _on_change(std::move(rhs._on_change))
    {
        rhs.observable_on_change_conns.swap(observable_on_change_conns);
        set_on_change<class_<Observed_, Members...>> visitor{*this};
        boost::fusion::for_each(rhs._tag2observable, visitor);
        boost::fusion::move(std::move(rhs._tag2observable), _tag2observable);
    }

    class_& operator=(class_&& rhs) noexcept
    {
        _observed = rhs._observed;
        rhs.observable_on_change_conns.swap(observable_on_change_conns);
        set_on_change<class_<Observed_, Members...>> visitor{*this};
        boost::fusion::for_each(rhs._tag2observable, visitor);
        boost::fusion::move(std::move(rhs._tag2observable), _tag2observable);
        _on_change = std::move(rhs._on_change);
        return *this;
    }

    template<typename Tag, typename T>
    void assign(T o)
    { return boost::fusion::at_key<Tag>(_tag2observable).assign(std::move(o)); }

    template<typename Tag>
    auto get() ->
        decltype(boost::fusion::at_key<Tag>(
                     std::declval<
                     typename std::add_lvalue_reference<Tag2Observable>::type>()))
    { return boost::fusion::at_key<Tag>(_tag2observable); }

    template<typename Tag, typename F>
    boost::signals2::connection on_change(F&& f)
    {
        return boost::fusion::at_key<Tag>
            (_tag2observable).on_change(std::forward<F>(f));
    }

    template<typename F>
    boost::signals2::connection on_change(F&& f)
    { return _on_change.connect(std::forward<F>(f)); }

    const Observed& get() const noexcept
    { return *_observed; }

private:

    Observed* _observed{nullptr};
    Tag2Observable _tag2observable;
    boost::signals2::signal<void(const Observed&)> _on_change;

    using observable_on_change_conns_t =
        std::array<boost::signals2::scoped_connection, sizeof...(Members)>;

    observable_on_change_conns_t observable_on_change_conns;

    template<typename>
    friend struct observable::map;

    template<typename>
    friend struct observable::value;

    template<typename>
    friend struct observable::variant;

    template<typename>
    friend struct observable::vector;

    template<typename>
    friend struct observable::unordered_map;

    template<typename>
    friend struct observable::unordered_set;

    template<typename>
    friend struct set_on_change;
};

}

ext: hpp

max_stars_repo_name: ricardocosme/observable

max_issues_repo_name: ricardocosme/observable

max_forks_repo_name: ricardocosme/observable


text:
//
// Created by michel on 21-11-19.
//

#include <boost/test/unit_test.hpp>
#include <iostream>
#include <simple-dsp/util/guards.h>

using FlagGuard = simpledsp::util::FlagGuard;

static simpledsp::util::FlagGuard getGuard(std::atomic_flag &flag) {
  return simpledsp::util::FlagGuard(flag);
}

BOOST_AUTO_TEST_SUITE(SpinGuardTests)

BOOST_AUTO_TEST_CASE(testFirstAndOnlyIsSet) {
  std::atomic_flag flag = ATOMIC_FLAG_INIT;
  {
    FlagGuard guard(flag);

    BOOST_CHECK(guard.isSet());
    BOOST_CHECK(flag.test_and_set());
  }
  BOOST_CHECK_MESSAGE(!flag.test_and_set(), "Scope end dit not clear flag");
}

BOOST_AUTO_TEST_CASE(testFirstAndOnlyOutOfScopeIsNotSet) {
  std::atomic_flag flag = ATOMIC_FLAG_INIT;
  {
    FlagGuard guard(flag);
    BOOST_CHECK(guard.isSet());
  }
  BOOST_CHECK(!flag.test_and_set());
}

BOOST_AUTO_TEST_CASE(testSecondNotSet) {
  std::atomic_flag flag = ATOMIC_FLAG_INIT;
  {
    FlagGuard first(flag);
    FlagGuard second(flag);

    BOOST_CHECK(!second.isSet());
    BOOST_CHECK(flag.test_and_set());
  }
  BOOST_CHECK_MESSAGE(!flag.test_and_set(), "Scope end dit not clear flag");
}

BOOST_AUTO_TEST_CASE(testSecondNotSetThenClearedAndSetAgainIsSet) {
  std::atomic_flag flag = ATOMIC_FLAG_INIT;
  FlagGuard first(flag);
  FlagGuard second(flag); // flag still set by first guard

  flag.clear();

  BOOST_CHECK(second.set());
}

BOOST_AUTO_TEST_CASE(testMoveTargetSetSourceNotSet) {
  std::atomic_flag flag = ATOMIC_FLAG_INIT;
  {
    FlagGuard first(flag);
    FlagGuard second = std::move(first);

    BOOST_CHECK(second.isSet());
    BOOST_CHECK(!first.isSet());
    BOOST_CHECK(flag.test_and_set());
  }
  BOOST_CHECK_MESSAGE(!flag.test_and_set(), "Scope end dit not clear flag");
}

BOOST_AUTO_TEST_CASE(testFirstGuardFromFunctionIsSet) {
  std::atomic_flag flag = ATOMIC_FLAG_INIT;
  {
    FlagGuard first = getGuard(flag);

    BOOST_CHECK(first.isSet());
    BOOST_CHECK(flag.test_and_set());
  }
  BOOST_CHECK_MESSAGE(!flag.test_and_set(), "Scope end dit not clear flag");
}

BOOST_AUTO_TEST_SUITE_END()

ext: cc

max_stars_repo_name: emmef/simple-dsp

max_issues_repo_name: emmef/simple-dsp

max_forks_repo_name: emmef/simple-dsp


text:
//---------------------------------------------------------------------------//
// Copyright (c) 2013-2014 Kyle Lutz <kyle.r.lutz@gmail.com>
//
// 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
//
// See http://kylelutz.github.com/compute for more information.
//---------------------------------------------------------------------------//

#ifndef BOOST_COMPUTE_DETAIL_SHA1_HPP
#define BOOST_COMPUTE_DETAIL_SHA1_HPP

#include <sstream>
#include <iomanip>
#include <boost/uuid/sha1.hpp>

namespace boost {
namespace compute {
namespace detail {

// Returns SHA1 hash of the string parameter.
inline std::string sha1(const std::string &src) {
    boost::uuids::detail::sha1 sha1;
    sha1.process_bytes(src.c_str(), src.size());

    unsigned int hash[5];
    sha1.get_digest(hash);

    std::ostringstream buf;
    for(int i = 0; i < 5; ++i)
        buf << std::hex << std::setfill('0') << std::setw(8) << hash[i];

    return buf.str();
}

} // end detail namespace
} // end compute namespace
} // end boost namespace

#endif // BOOST_COMPUTE_DETAIL_SHA1_HPP

max_stars_repo_name: bastiankoe/compute

max_issues_repo_name: bastiankoe/compute

max_forks_repo_name: bastiankoe/compute


text:
/**
 *  This file is part of dvo.
 *
 *  Copyright 2012 Christian Kerl <christian.kerl@in.tum.de> (Technical University of Munich)
 *  For more information see <http://vision.in.tum.de/data/software/dvo>.
 *
 *  dvo 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.
 *
 *  dvo 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 dvo.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <dvo/core/rgbd_image.h>

#include <assert.h>

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

#include <dvo/core/interpolation.h>

//#include "../util.h"
//#include "../stopwatch.h"

namespace dvo
{
namespace core
{

template<typename T>
static void pyrDownMeanSmooth(const cv::Mat& in, cv::Mat& out)
{
  out.create(cv::Size(in.size().width / 2, in.size().height / 2), in.type());

  for(int y = 0; y < out.rows; ++y)
  {
    for(int x = 0; x < out.cols; ++x)
    {
      int x0 = x * 2;
      int x1 = x0 + 1;
      int y0 = y * 2;
      int y1 = y0 + 1;

      out.at<T>(y, x) = (T) ( (in.at<T>(y0, x0) + in.at<T>(y0, x1) + in.at<T>(y1, x0) + in.at<T>(y1, x1)) / 4.0f );
    }
  }
}

template<typename T>
static void pyrDownMeanSmoothIgnoreInvalid(const cv::Mat& in, cv::Mat& out)
{
  out.create(cv::Size(in.size().width / 2, in.size().height / 2), in.type());

  for(int y = 0; y < out.rows; ++y)
  {
    for(int x = 0; x < out.cols; ++x)
    {
      int x0 = x * 2;
      int x1 = x0 + 1;
      int y0 = y * 2;
      int y1 = y0 + 1;

      T total = 0;
      int cnt = 0;

      if(std::isfinite(in.at<T>(y0, x0)))
      {
        total += in.at<T>(y0, x0);
        cnt++;
      }

      if(std::isfinite(in.at<T>(y0, x1)))
      {
        total += in.at<T>(y0, x1);
        cnt++;
      }

      if(std::isfinite(in.at<T>(y1, x0)))
      {
        total += in.at<T>(y1, x0);
        cnt++;
      }

      if(std::isfinite(in.at<T>(y1, x1)))
      {
        total += in.at<T>(y1, x1);
        cnt++;
      }

      if(cnt > 0)
      {
        out.at<T>(y, x) = (T) ( total / cnt );
      }
      else
      {
        out.at<T>(y, x) = InvalidDepth;
      }
    }
  }
}

template<typename T>
static void pyrDownMedianSmooth(const cv::Mat& in, cv::Mat& out)
{
  out.create(cv::Size(in.size().width / 2, in.size().height / 2), in.type());

  cv::Mat in_smoothed;
  cv::medianBlur(in, in_smoothed, 3);

  for(int y = 0; y < out.rows; ++y)
  {
    for(int x = 0; x < out.cols; ++x)
    {
      out.at<T>(y, x) = in_smoothed.at<T>(y * 2, x * 2);
    }
  }
}

template<typename T>
static void pyrDownSubsample(const cv::Mat& in, cv::Mat& out)
{
  out.create(cv::Size(in.size().width / 2, in.size().height / 2), in.type());

  for(int y = 0; y < out.rows; ++y)
  {
    for(int x = 0; x < out.cols; ++x)
    {
      out.at<T>(y, x) = in.at<T>(y * 2, x * 2);
    }
  }
}

RgbdImagePyramid::RgbdImagePyramid(RgbdCameraPyramid& camera, const cv::Mat& intensity, const cv::Mat& depth) :
    camera_(camera)
{
  levels_.push_back(camera_.level(0).create(intensity, depth));
}

RgbdImagePyramid::~RgbdImagePyramid()
{
}

void RgbdImagePyramid::compute(const size_t num_levels)
{
  build(num_levels);
}

void RgbdImagePyramid::build(const size_t num_levels)
{
  if(levels_.size() >= num_levels) return;

  // if we already have some levels, we just need to compute the coarser levels
  size_t first = levels_.size();

  for(size_t idx = first; idx < num_levels; ++idx)
  {
    levels_.push_back(camera_.level(idx).create());

    pyrDownMeanSmooth<IntensityType>(levels_[idx - 1]->intensity, levels_[idx]->intensity);
    //pyrDownMeanSmoothIgnoreInvalid<float>(levels[idx - 1].depth, levels[idx].depth);
    pyrDownSubsample<float>(levels_[idx - 1]->depth, levels_[idx]->depth);
    levels_[idx]->initialize();
  }
}

RgbdImage& RgbdImagePyramid::level(size_t idx)
{
  assert(idx < levels_.size());

  return *levels_[idx];
}

double RgbdImagePyramid::timestamp() const
{
  return !levels_.empty() ? levels_[0]->timestamp: 0.0;
}

RgbdCamera::RgbdCamera(size_t width, size_t height, const IntrinsicMatrix& intrinsics) :
    width_(width),
    height_(height),
    intrinsics_(intrinsics)
{
  pointcloud_template_.resize(Eigen::NoChange, width_ * height_);
  int idx = 0;

  for(size_t y = 0; y < height_; ++y)
  {
    for(size_t x = 0; x < width_; ++x, ++idx)
    {
      pointcloud_template_(0, idx) = (x - intrinsics_.ox()) / intrinsics_.fx();
      pointcloud_template_(1, idx) = (y - intrinsics_.oy()) / intrinsics_.fy();
      pointcloud_template_(2, idx) = 1.0;
      pointcloud_template_(3, idx) = 0.0;
    }
  }
}

RgbdCamera::~RgbdCamera()
{
}

size_t RgbdCamera::width() const
{
  return width_;
}

size_t RgbdCamera::height() const
{
  return height_;
}

const dvo::core::IntrinsicMatrix& RgbdCamera::intrinsics() const
{
  return intrinsics_;
}

RgbdImagePtr RgbdCamera::create(const cv::Mat& intensity, const cv::Mat& depth) const
{
  RgbdImagePtr result(new RgbdImage(*this));
  result->intensity = intensity;
  result->depth = depth;
  result->initialize();

  return result;
}

RgbdImagePtr RgbdCamera::create() const
{
  return boost::make_shared<RgbdImage>(*this);
}

bool RgbdCamera::hasSameSize(const cv::Mat& img) const
{
  return img.cols == width_ && img.rows == height_;
}

void RgbdCamera::buildPointCloud(const cv::Mat &depth, PointCloud& pointcloud) const
{
  assert(hasSameSize(depth));

  pointcloud.resize(Eigen::NoChange, width_ * height_);

  const float* depth_ptr = depth.ptr<float>();
  int idx = 0;

  for(size_t y = 0; y < height_; ++y)
  {
    for(size_t x = 0; x < width_; ++x, ++depth_ptr, ++idx)
    {
      pointcloud.col(idx) = pointcloud_template_.col(idx) * (*depth_ptr);
      pointcloud(3, idx) = 1.0;
    }
  }
}

RgbdCameraPyramid::RgbdCameraPyramid(const RgbdCamera& base)
{
  levels_.push_back(boost::make_shared<RgbdCamera>(base));
}

RgbdCameraPyramid::RgbdCameraPyramid(size_t base_width, size_t base_height, const dvo::core::IntrinsicMatrix& base_intrinsics)
{
  levels_.push_back(boost::make_shared<RgbdCamera>(base_width, base_height, base_intrinsics));
}

RgbdCameraPyramid::~RgbdCameraPyramid()
{
}

RgbdImagePyramidPtr RgbdCameraPyramid::create(const cv::Mat& base_intensity, const cv::Mat& base_depth)
{
  return RgbdImagePyramidPtr(new RgbdImagePyramid(*this, base_intensity, base_depth));
}

void RgbdCameraPyramid::build(size_t levels)
{
  size_t start = levels_.size();

  for(size_t idx = start; idx < levels; ++idx)
  {
    RgbdCameraPtr& previous = levels_[idx - 1];

    dvo::core::IntrinsicMatrix intrinsics(previous->intrinsics());
    intrinsics.scale(0.5f);

    levels_.push_back(boost::make_shared<RgbdCamera>(previous->width() / 2, previous->height() / 2, intrinsics));
  }
}

const RgbdCamera& RgbdCameraPyramid::level(size_t level)
{
  build(level + 1);

  return *levels_[level];
}

const RgbdCamera& RgbdCameraPyramid::level(size_t level) const
{
  return *levels_[level];
}
/*
RgbdImage::RgbdImage() :
  camera_(0),
  intensity_requires_calculation_(true),
  depth_requires_calculation_(true),
  pointcloud_requires_build_(true),
  width(0),
  height(0)
{
}
*/
RgbdImage::RgbdImage(const RgbdCamera& camera) :
  camera_(camera),
  intensity_requires_calculation_(true),
  depth_requires_calculation_(true),
  pointcloud_requires_build_(true),
  width(0),
  height(0)
{
}

RgbdImage::~RgbdImage()
{
}

const RgbdCamera& RgbdImage::camera() const
{
  return camera_;
}

void RgbdImage::initialize()
{
  assert(hasIntensity() || hasDepth());

  if(hasIntensity() && hasDepth())
  {
    assert(intensity.size() == depth.size());
  }

  if(hasIntensity())
  {
    assert(intensity.type() == cv::DataType<IntensityType>::type && intensity.channels() == 1);
    width = intensity.cols;
    height = intensity.rows;
  }
  if(hasDepth())
  {
    assert(depth.type() == cv::DataType<DepthType>::type && depth.channels() == 1);
    width = depth.cols;
    height = depth.rows;
  }

  intensity_requires_calculation_ = true;
  depth_requires_calculation_ = true;
  pointcloud_requires_build_ = true;
}

bool RgbdImage::hasIntensity() const
{
  return !intensity.empty();
}

bool RgbdImage::hasRgb() const
{
  return !rgb.empty();
}

bool RgbdImage::hasDepth() const
{
  return !depth.empty();
}

void RgbdImage::calculateDerivatives()
{
  calculateIntensityDerivatives();
  calculateDepthDerivatives();
}

bool RgbdImage::calculateIntensityDerivatives()
{
  if(!intensity_requires_calculation_) return false;

  assert(hasIntensity());

  calculateDerivativeX<IntensityType>(intensity, intensity_dx);
  //calculateDerivativeY<IntensityType>(intensity, intensity_dy);
  calculateDerivativeYSseFloat(intensity, intensity_dy);
  /*
  cv::Mat dy_ref, diff;
  calculateDerivativeY<IntensityType>(intensity, dy_ref);
  cv::absdiff(dy_ref, intensity_dy, diff);
  tracker::util::show("diff", diff);
  cv::waitKey(0);
   */
  intensity_requires_calculation_ = false;
  return true;
}

void RgbdImage::calculateDepthDerivatives()
{
  if(!depth_requires_calculation_) return;

  assert(hasDepth());

  calculateDerivativeX<DepthType>(depth, depth_dx);
  calculateDerivativeY<DepthType>(depth, depth_dy);

  depth_requires_calculation_ = false;
}

template<typename T>
void RgbdImage::calculateDerivativeX(const cv::Mat& img, cv::Mat& result)
{
  result.create(img.size(), img.type());

  for(int y = 0; y < img.rows; ++y)
  {
    for(int x = 0; x < img.cols; ++x)
    {
      int prev = std::max(x - 1, 0);
      int next = std::min(x + 1, img.cols - 1);

      result.at<T>(y, x) = (T) (img.at<T>(y, next) - img.at<T>(y, prev)) * 0.5f;
    }
  }

  //cv::Sobel(img, result, -1, 1, 0, 3, 1.0f / 4.0f, 0, cv::BORDER_REPLICATE);

  // compiler auto-vectorization
  /*
  const float* img_ptr = img.ptr<float>();
  float* result_ptr = result.ptr<float>();

  for(int y = 0; y < img.rows; ++y)
  {
    *result_ptr++ = img_ptr[1] - img_ptr[0];

    for(int x = 1; x < img.cols - 1; ++x, ++img_ptr)
    {
      *result_ptr++ = img_ptr[2] - img_ptr[0];
    }

    *result_ptr++ = img_ptr[1] - img_ptr[0];

    img_ptr++;
  }
   */
}

template<typename T>
void RgbdImage::calculateDerivativeY(const cv::Mat& img, cv::Mat& result)
{
  result.create(img.size(), img.type());

  for(int y = 0; y < img.rows; ++y)
  {
    for(int x = 0; x < img.cols; ++x)
    {
      int prev = std::max(y - 1, 0);
      int next = std::min(y + 1, img.rows - 1);

      result.at<T>(y, x) = (T) (img.at<T>(next, x) - img.at<T>(prev, x)) * 0.5f;
    }
  }
  //cv::Sobel(img, result, -1, 0, 1, 3, 1.0f / 4.0f, 0, cv::BORDER_REPLICATE);

  // compiler auto-vectorization
  /*
  for(int y = 0; y < img.rows; ++y)
  {
    const float* prev_row = img.ptr<float>(std::max(y - 1, 0), 0);
    const float* next_row = img.ptr<float>(std::min(y + 1, img.rows - 1), 0);
    float* cur_row = result.ptr<float>(y, 0);

    for(int x = 0; x < img.cols; ++x)
    {
      *cur_row++ = *next_row++ - *prev_row++;
    }
  }
   */
}

void RgbdImage::buildPointCloud()
{
  if(!pointcloud_requires_build_) return;

  assert(hasDepth());

  camera_.buildPointCloud(depth, pointcloud);

  pointcloud_requires_build_ = false;
}

void RgbdImage::calculateNormals()
{
  if(angles.total() == 0)
  {
    normals = cv::Mat::zeros(depth.size(), CV_32FC4);
    angles.create(depth.size(), CV_32FC1);

    float *angle_ptr = angles.ptr<float>();
    cv::Vec4f *normal_ptr = normals.ptr<cv::Vec4f>();

    int x_max = depth.cols - 1;
    int y_max = depth.rows - 1;

    for(int y = 0; y < depth.rows; ++y)
    {
      for(int x = 0; x < depth.cols; ++x, ++angle_ptr, ++normal_ptr)
      {
        int idx1 = y * depth.cols + std::max(x-1, 0);
        int idx2 = y * depth.cols + std::min(x+1, x_max);
        int idx3 = std::max(y-1, 0) * depth.cols + x;
        int idx4 = std::min(y+1, y_max) * depth.cols + x;

        Eigen::Vector4f::AlignedMapType n(normal_ptr->val);
        n = (pointcloud.col(idx2) - pointcloud.col(idx1)).cross3(pointcloud.col(idx4) - pointcloud.col(idx3));
        n.normalize();

        *angle_ptr = std::abs(n(2));
      }
    }
  }
}

void RgbdImage::buildAccelerationStructure()
{
  if(acceleration.total() == 0)
  {
    calculateDerivatives();
    cv::Mat zeros = cv::Mat::zeros(intensity.size(), intensity.type());
    cv::Mat channels[8] = { intensity, depth, intensity_dx, intensity_dy, depth_dx, depth_dy, zeros, zeros};
    cv::merge(channels, 8, acceleration);
  }
}

void RgbdImage::warpIntensity(const AffineTransform& transformationd, const PointCloud& reference_pointcloud, const IntrinsicMatrix& intrinsics, RgbdImage& result, PointCloud& transformed_pointcloud)
{
  Eigen::Affine3f transformation = transformationd.cast<float>();

  cv::Mat warped_image(intensity.size(), intensity.type());
  cv::Mat warped_depth(depth.size(), depth.type());

  float ox = intrinsics.ox();
  float oy = intrinsics.oy();

  float* warped_intensity_ptr = warped_image.ptr<IntensityType>();
  float* warped_depth_ptr = warped_depth.ptr<DepthType>();

  int outliers = 0;
  int total = 0;
  int idx = 0;

  transformed_pointcloud = transformation * reference_pointcloud;

  for(size_t y = 0; y < height; ++y)
  {
    for(size_t x = 0; x < width; ++x, ++idx, ++warped_intensity_ptr, ++warped_depth_ptr)
    {

      const Eigen::Vector4f& p3d = transformed_pointcloud.col(idx);

      if(!std::isfinite(p3d(2)))
      {
        *warped_intensity_ptr = Invalid;
        *warped_depth_ptr = InvalidDepth;
        continue;
      }

      float x_projected = (float) (p3d(0) * intrinsics.fx() / p3d(2) + ox);
      float y_projected = (float) (p3d(1) * intrinsics.fy() / p3d(2) + oy);

      if(inImage(x_projected, y_projected))
      {
        float z = (float) p3d(2);

        *warped_intensity_ptr = Interpolation::bilinearWithDepthBuffer(this->intensity, this->depth, x_projected, y_projected, z);
        *warped_depth_ptr = z;
      }
      else
      {
        *warped_intensity_ptr = Invalid;
        *warped_depth_ptr = InvalidDepth;
        //outliers++;
      }

      //total++;
    }
  }

  result.intensity = warped_image;
  result.depth = warped_depth;
  result.initialize();
}

void RgbdImage::warpDepthForward(const AffineTransform& transformationx, const IntrinsicMatrix& intrinsics, RgbdImage& result, cv::Mat_<cv::Vec3d>& cloud)
{
  Eigen::Affine3d transformation = transformationx.cast<double>();

  cloud = cv::Mat_<cv::Vec3d>(depth.size(), cv::Vec3d(0, 0, 0));
  cv::Mat warped_depth = cv::Mat::zeros(depth.size(), depth.type());
  warped_depth.setTo(InvalidDepth);

  float ox = intrinsics.ox();
  float oy = intrinsics.oy();

  const float* depth_ptr = depth.ptr<float>();
  int outliers = 0;
  int total = 0;

  for(size_t y = 0; y < height; ++y)
  {
    for(size_t x = 0; x < width; ++x, ++depth_ptr)
    {
      if(!std::isfinite(*depth_ptr))
      {
        continue;
      }

      float depth = *depth_ptr;
      Eigen::Vector3d p3d((x - ox) * depth / intrinsics.fx(), (y - oy) * depth / intrinsics.fy(), depth);
      Eigen::Vector3d p3d_transformed = transformation * p3d;

      float x_projected = (float) (p3d_transformed(0) * intrinsics.fx() / p3d_transformed(2) + ox);
      float y_projected = (float) (p3d_transformed(1) * intrinsics.fy() / p3d_transformed(2) + oy);

      if(inImage(x_projected, y_projected))
      {
        int yi = (int) y_projected, xi = (int) x_projected;

        if(!std::isfinite(warped_depth.at<DepthType>(yi, xi)) || (warped_depth.at<DepthType>(yi, xi) - 0.05) > depth)
          warped_depth.at<DepthType>(yi, xi) = depth;
      }

      p3d = p3d_transformed;

      total++;
      cloud(y, x) = cv::Vec3d(p3d(0), p3d(1), p3d(2));
    }
  }

  result.depth = warped_depth;
  result.initialize();
}

void RgbdImage::warpIntensityForward(const AffineTransform& transformationx, const IntrinsicMatrix& intrinsics, RgbdImage& result, cv::Mat_<cv::Vec3d>& cloud)
{
  Eigen::Affine3d transformation = transformationx.cast<double>();

  bool identity = transformation.affine().isIdentity(1e-6);

  cloud = cv::Mat_<cv::Vec3d>(intensity.size(), cv::Vec3d(0, 0, 0));
  cv::Mat warped_image = cv::Mat::zeros(intensity.size(), intensity.type());

  float ox = intrinsics.ox();
  float oy = intrinsics.oy();

  const float* depth_ptr = depth.ptr<float>();
  int outliers = 0;
  int total = 0;

  for(size_t y = 0; y < height; ++y)
  {
    for(size_t x = 0; x < width; ++x, ++depth_ptr)
    {
      if(*depth_ptr <= 1e-6f) continue;

      float depth = *depth_ptr;
      Eigen::Vector3d p3d((x - ox) * depth / intrinsics.fx(), (y - oy) * depth / intrinsics.fy(), depth);

      if(!identity)
      {
        Eigen::Vector3d p3d_transformed = transformation * p3d;

        float x_projected = (float) (p3d_transformed(0) * intrinsics.fx() / p3d_transformed(2) + ox);
        float y_projected = (float) (p3d_transformed(1) * intrinsics.fy() / p3d_transformed(2) + oy);

        if(inImage(x_projected, y_projected))
        {
          int xp, yp;
          xp = (int) std::floor(x_projected);
          yp = (int) std::floor(y_projected);

          warped_image.at<IntensityType>(yp, xp) = intensity.at<IntensityType>(y, x);
        }
        else
        {
          outliers++;
        }

        p3d = p3d_transformed;
      }

      total++;
      cloud(y, x) = cv::Vec3d(p3d(0), p3d(1), p3d(2));
    }
  }

  //std::cerr << "warp out: " << outliers << " total: " << total << std::endl;

  if(identity)
  {
    warped_image = intensity;
  }
  else
  {
    //std::cerr << "did warp" << std::endl;
  }

  result.intensity = warped_image;
  result.depth = depth;
  result.initialize();
}

void RgbdImage::warpDepthForwardAdvanced(const AffineTransform& transformation, const IntrinsicMatrix& intrinsics, RgbdImage& result)
{
  assert(hasDepth());

  this->buildPointCloud();

  PointCloud transformed_pointcloud = transformation.cast<float>() * pointcloud;

  cv::Mat warped_depth(depth.size(), depth.type());
  warped_depth.setTo(InvalidDepth);

  float z_factor1 = transformation.rotation()(0, 0) + transformation.rotation()(0, 1) * (intrinsics.fx() / intrinsics.fy());
  float x_factor1 = -transformation.rotation()(2, 0) - transformation.rotation()(2, 1) * (intrinsics.fx() / intrinsics.fy());

  float z_factor2 = transformation.rotation()(1, 1) + transformation.rotation()(1, 0) * (intrinsics.fy() / intrinsics.fx());
  float y_factor2 = -transformation.rotation()(2, 1) - transformation.rotation()(2, 0) * (intrinsics.fy() / intrinsics.fx());

  for(int idx = 0; idx < height * width; ++idx)
  {
    Vector4 p3d = pointcloud.col(idx);
    NumType z = p3d(2);

    if(!std::isfinite(z)) continue;

    int x_length = (int) std::ceil(z_factor1 + x_factor1 * p3d(0) / z) + 1; // magic +1
    int y_length = (int) std::ceil(z_factor2 + y_factor2 * p3d(1) / z) + 1; // magic +1

    Vector4 p3d_transformed = transformed_pointcloud.col(idx);
    NumType z_transformed = p3d_transformed(2);

    int x_projected = (int) std::floor(p3d_transformed(0) * intrinsics.fx() / z_transformed + intrinsics.ox());
    int y_projected = (int) std::floor(p3d_transformed(1) * intrinsics.fy() / z_transformed + intrinsics.oy());

    // TODO: replace inImage(...) checks, with max(..., 0) on initial value of x_, y_ and  min(..., width/height) for their respective upper bound
    //for (int y_ = y_projected; y_ < y_projected + y_length; y_++)
    //  for (int x_ = x_projected; x_ < x_projected + x_length; x_++)

    int x_begin = std::max(x_projected, 0);
    int y_begin = std::max(y_projected, 0);
    int x_end = std::min(x_projected + x_length, (int) width);
    int y_end = std::min(y_projected + y_length, (int) height);

    for (int y = y_begin; y < y_end; ++y)
    {
      DepthType* v = warped_depth.ptr<DepthType>(y, x_begin);

      for (int x = x_begin; x < x_end; ++x, ++v)
      {
        if(!std::isfinite(*v) || (*v) > z_transformed)
        {
          (*v) = (DepthType) z_transformed;
        }
      }
    }
  }

  result.depth = warped_depth;
  result.initialize();
}

bool RgbdImage::inImage(const float& x, const float& y) const
{
  return x >= 0 && x < width && y >= 0 && y < height;
}

} /* namespace core */
} /* namespace dvo */


text:
//============================================================================
// Name        :
// Author      : Avi
// Revision    : $Revision: #27 $
//
// Copyright 2009- ECMWF.
// This software is licensed under the terms of the Apache Licence version 2.0
// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
// In applying this licence, ECMWF does not waive the privileges and immunities
// granted to it by virtue of its status as an intergovernmental organisation
// nor does it submit to any jurisdiction.
//
// Description :
//============================================================================
#include <iostream>

#include "boost/filesystem/operations.hpp"
#include "boost/filesystem/path.hpp"
#include <boost/lexical_cast.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>

#include "ServerTestHarness.hpp"
#include "TestFixture.hpp"

#include "Defs.hpp"
#include "Suite.hpp"
#include "Family.hpp"
#include "Task.hpp"
#include "DurationTimer.hpp"
#include "PrintStyle.hpp"
#include "ClientToServerCmd.hpp"
#include "AssertTimer.hpp"
#include "Limit.hpp"
#include "WhyCmd.hpp"
#include "VerifyAttr.hpp"

using namespace std;
using namespace ecf;
using namespace boost::gregorian;
using namespace boost::posix_time;
namespace fs = boost::filesystem;

BOOST_AUTO_TEST_SUITE( TestSuite )

static unsigned int waitForWhy(const std::string& path, const std::string& why, int max_time_to_wait)
{
   unsigned int updateCalendarCount = 0;
   TestFixture::client().set_throw_on_error( false );
   AssertTimer assertTimer(max_time_to_wait,false); // Bomb out after n seconds, fall back if test fail
   while (1) {

      /// Why command relies on the Suite serializing the calendar. If this is changed we need to get the full defs
      BOOST_REQUIRE_MESSAGE(TestFixture::client().sync_local() == 0, "sync_local failed should return 0\n" << TestFixture::client().errorMsg());

      /// called to test that sync suite clock works
      BOOST_REQUIRE_MESSAGE(TestFixture::client().sync_local(true/*sync suite clock*/) == 0, "sync_local failed should return 0\n" << TestFixture::client().errorMsg());
      defs_ptr server_defs = TestFixture::client().defs();
      updateCalendarCount = server_defs->updateCalendarCount();

      WhyCmd whyCmd( server_defs, path);
      std::string reason = whyCmd.why();
      // std::cout << reason;

      if (reason.find(why) != std::string::npos) {
         // see the reason why job is not running
         std::cout << reason;
         break;
      }

      BOOST_REQUIRE_MESSAGE(assertTimer.duration() <  assertTimer.timeConstraint(),
               "waitForWhy Test wait " << assertTimer.duration() <<
               " taking longer than time constraint of " << assertTimer.timeConstraint() <<
               " aborting\n" << *server_defs);
      sleep(1);
   }
   return updateCalendarCount;
}

BOOST_AUTO_TEST_CASE( test_why_day )
{
   DurationTimer timer;
   cout << "Test:: ...test_why_day "<< flush;
   TestClean clean_at_start_and_end;

   Defs theDefs;
   {
      boost::posix_time::ptime today = Calendar::second_clock_time();
      suite_ptr suite  = Suite::create("test_why_day" ) ;
      family_ptr fam = Family::create(  "family" );
      task_ptr task = Task::create(  "t1" );

      // Dont use hybrid for day dependency as that will force node to complete if days is not the same
      ClockAttr clockAttr(today, false);
      suite->addClock( clockAttr );

      // ** add tomorrow days so that node stays queued **
      task->addDay( DayAttr( today.date() +  boost::gregorian::date_duration(1 ) ) );

      fam->addTask( task );
      suite->addFamily( fam );
      theDefs.addSuite( suite );
   }

   ServerTestHarness serverTestHarness;
   serverTestHarness.run(theDefs,
                         ServerTestHarness::testDataDefsLocation("test_why_day.def"),
                         1/*timeout*/,
                         false /* waitForTestCompletion*/);

   // The job should not be submitted and should stay queued since the day does not match
   // running the why command, should report dependency on day
   unsigned int updateCalendarCount = waitForWhy("/test_why_day/family/t1", "day", 10);

   cout << " " << timer.duration() << " update-calendar-count(" << updateCalendarCount << ")\n";
}

BOOST_AUTO_TEST_CASE( test_why_date )
{
   DurationTimer timer;
   cout << "Test:: ...test_why_date "<< flush;

   Defs theDefs;
   {
      suite_ptr suite  = Suite::create("test_why_date" ) ;
      family_ptr fam = Family::create(  "family" );
      task_ptr task = Task::create(  "t1" );

      // Don't use hybrid for date dependency as that will force node to complete if date is not the same
      boost::posix_time::ptime today = Calendar::second_clock_time();
      ClockAttr clockAttr(today, false);
      suite->addClock( clockAttr );

      // ** add tomorrow date so that node stays queued **
      task->addDate( DateAttr( today.date() + boost::gregorian::date_duration(1 )) );
      fam->addTask( task );
      suite->addFamily( fam );
      theDefs.addSuite( suite );
   }

   ServerTestHarness serverTestHarness;
   serverTestHarness.run(theDefs,
                         ServerTestHarness::testDataDefsLocation("test_why_date.def"),
                         1/*timeout*/,
                         false /* waitForTestCompletion*/);

   // The job should not be submitted and should stay queued since the day does not match
   // running the why command, should report dependency on day
   unsigned int updateCalendarCount = waitForWhy("/test_why_date/family/t1", "date", 10);

   cout << " " << timer.duration() << " update-calendar-count(" << updateCalendarCount << ")\n";
}

BOOST_AUTO_TEST_CASE( test_why_time )
{
   DurationTimer timer;
   cout << "Test:: ...test_why_time "<< flush;

   Defs theDefs;
   {
      boost::posix_time::ptime   theLocalTime =  Calendar::second_clock_time();
      boost::posix_time::ptime   time1 =  theLocalTime -  hours(1);

      suite_ptr suite  = Suite::create("test_why_time" ) ;
      family_ptr fam = Family::create(  "family" );
      task_ptr task = Task::create(  "t1" );

      ClockAttr clockAttr(theLocalTime);
      suite->addClock( clockAttr );

      task->addTime( ecf::TimeAttr(  ecf::TimeSlot(time1.time_of_day()) ) );
      fam->addTask( task );
      suite->addFamily( fam );
      theDefs.addSuite( suite );
   }

   ServerTestHarness serverTestHarness;
   serverTestHarness.run(theDefs,
                         ServerTestHarness::testDataDefsLocation("test_why_time.def"),
                         1/*timeout*/,
                         false /* waitForTestCompletion*/);

   // The job should not be submitted and should stay queued since the time does not match
   // running the why command, should report dependency on time
   unsigned int updateCalendarCount = waitForWhy("/test_why_time/family/t1", "time", 10);

   cout << " " << timer.duration() << " update-calendar-count(" << updateCalendarCount << ")\n";
}

BOOST_AUTO_TEST_CASE( test_why_today )
{
   DurationTimer timer;
   cout << "Test:: ...test_why_today "<< flush;

   Defs theDefs;
   {
      // IMPORTANT: A Node with a today attribute is *free* to run *IF* the suite
      //            calendar time is greater than the today date.
      //            Hence if we start this test just before midnight i.e 11.20,
      //            and add hour , then the today time would be 00:20
      //            *i.e node is free to run*
      // This is not what we want for this test. i.e we depend on node being queued
      // in order to test the why command. Also the following tests, start
      // by deleting all nodes. This will fail due to active/submitted tasks
      // Hence can *NOT* use:
      // boost::posix_time::ptime theLocalTime =  Calendar::second_clock_time();
      // boost::posix_time::ptime time1 =  theLocalTime + hours(1);

      // Use a hard coded a time, to avoid failure if test is run just before midnight
      boost::posix_time::ptime theLocalTime(date(2010,2,10), hours(1));
      boost::posix_time::ptime time1 =  theLocalTime + hours(1);

      suite_ptr suite  = theDefs.add_suite("test_why_today" ) ;
      ClockAttr clockAttr(theLocalTime);
      suite->addClock( clockAttr );

      family_ptr fam = suite->add_family(  "family" );
      task_ptr task = fam->add_task(  "t1" );
      task->addToday( ecf::TodayAttr(  ecf::TimeSlot(time1.time_of_day()) ) );
   }

   ServerTestHarness serverTestHarness;
   serverTestHarness.run(theDefs,
                         ServerTestHarness::testDataDefsLocation("test_why_today.def"),
                         1/*timeout*/,
                         false /* waitForTestCompletion*/);

   // The job should not be submitted and should stay queued since the time does not match
   // running the why command, should report dependency on time
   unsigned int updateCalendarCount = waitForWhy("/test_why_today/family/t1", "today", 10);

   cout << " " << timer.duration() << " update-calendar-count(" << updateCalendarCount << ")\n";
}

BOOST_AUTO_TEST_CASE( test_why_cron )
{
   DurationTimer timer;
   cout << "Test:: ...test_why_cron "<< flush;

   Defs theDefs;
   {
      boost::posix_time::ptime   theLocalTime =  boost::posix_time::ptime(date(2010,6,21),time_duration(11,0,0));
      boost::posix_time::ptime   time1 =  theLocalTime - hours(3);
      boost::posix_time::ptime   time2 =  theLocalTime -  hours(1);
      boost::gregorian::date todaysDate = theLocalTime.date();

      suite_ptr suite  = Suite::create("test_why_cron" ) ;
      family_ptr fam = Family::create(  "family" );
      task_ptr task = Task::create(  "t1" );

      ClockAttr clockAttr(theLocalTime,false/*real*/);
      suite->addClock( clockAttr );

      // ** IMPORTANT **, for a date in the future we must match day of week,
      // ***************  day of month, and year, i.e the results are ANDED
      // ***************  this can lead to unexpected time in the future
      // ***************  if all 3 dependencies are present, as *below*
      ecf::CronAttr cronAttr;
      ecf::TimeSlot start( time1.time_of_day() );  // in the past
      ecf::TimeSlot finish( time2.time_of_day() ); // in the past
      ecf::TimeSlot incr( 0, 5 );
      cronAttr.addTimeSeries(start,finish,incr);

      std::vector<int> weekDays; weekDays.push_back(todaysDate.day_of_week().as_number());
      std::vector<int> daysOfMonth; daysOfMonth.push_back( todaysDate.day() );
      std::vector<int> months; months.push_back( todaysDate.month() );
      cronAttr.addWeekDays(     weekDays  );
      cronAttr.addDaysOfMonth(  daysOfMonth );
      cronAttr.addMonths(       months );

      task->addCron(cronAttr);

      fam->addTask( task );
      suite->addFamily( fam );
      theDefs.addSuite( suite );
   }

   ServerTestHarness serverTestHarness;
   serverTestHarness.run(theDefs,
                         ServerTestHarness::testDataDefsLocation("test_why_cron.def"),
                         1/*timeout*/,
                         false /* waitForTestCompletion*/);

   // The job should not be submitted and should stay queued we are past the cron time
   // running the why command, should report dependency on cron
   unsigned int updateCalendarCount = waitForWhy("/test_why_cron/family/t1", "cron", 10);

   cout << " " << timer.duration() << " update-calendar-count(" << updateCalendarCount << ")\n";
}

BOOST_AUTO_TEST_CASE( test_why_limit )
{
   DurationTimer timer;
   cout << "Test:: ...test_why_limit "<< flush;

   // Testing for limits requires that we have least some jobs are submitted.
   // we need to kill these jobs, at the end of test.

   //	suite test_why_limit
   //    limit disk 50
   //	   family family
   //          inlimit /suite1:disk 50
   //	   		task t0
   //	   		task t1
   //	   		task t2
   //	   		task t3
   //	   		task t4
   //	   		task t5
   //	   endfamily
   //	endsuite

   Defs theDefs;
   {
      std::string suiteName = "test_why_limit";
      std::string pathToLimit = "/" + suiteName;
      suite_ptr suite = theDefs.add_suite(suiteName );
      suite->addVariable( Variable("ECF_TRIES","1") );
      suite->addLimit(Limit("disk",50));

      family_ptr fam = suite->add_family( "family");
      fam->addInLimit(InLimit("disk",pathToLimit,50));
      int taskSize = 6;
      for(int i=0; i < taskSize; i++) {
         fam->addTask( Task::create("t" + boost::lexical_cast<std::string>(i))  );
      }
   }

   ServerTestHarness serverTestHarness;
   serverTestHarness.run(theDefs,
                         ServerTestHarness::testDataDefsLocation( "test_why_limit.def" ),
                         1/*timeout*/,
                         false /* waitForTestCompletion*/);

   // Only one job should be submitted, at a time, we will query on task t5, which
   // should still be queued because the limit is full
   // running the why command, should report dependency on limit
   waitForWhy("/test_why_limit/family/t5", "limit", 10);

   // The main check is over. Wait for jobs to complete
   int updateCalendarCount = 0;
   TestFixture::client().set_throw_on_error(false) ;
   {
      AssertTimer assertTimer(50,false); // Bomb out after n seconds, fall back if test fail
      while (1) {
         BOOST_REQUIRE_MESSAGE(TestFixture::client().getDefs() == 0,CtsApi::get() << " failed should return 0\n" << TestFixture::client().errorMsg());
         defs_ptr defs = TestFixture::client().defs();
         updateCalendarCount = defs->updateCalendarCount();
         bool wait = false;
         vector<Task*> tasks; defs->getAllTasks(tasks);
         for(Task* task: tasks) {
            if (task->state() != NState::COMPLETE) wait = true;
         }
         if (!wait) break;
         if ( assertTimer.duration() >=  assertTimer.timeConstraint()) {
            cout << "waitFor jobs to complete, wait time of " << assertTimer.duration() <<
                               " taking longer than time constraint of " << assertTimer.timeConstraint() <<
                               " aborting, ......breaking out\n" << *defs << "\n";
         }
         sleep(1);
      }
   }
   cout << " " << timer.duration() << " update-calendar-count(" << updateCalendarCount << ")\n";
}

BOOST_AUTO_TEST_CASE( test_why_trigger )
{
   DurationTimer timer;
   cout << "Test:: ...test_why_trigger "<< flush;

   Defs theDefs;
   {
      suite_ptr suite  = Suite::create("test_why_trigger" ) ;
      family_ptr fam = Family::create(  "family" );
      task_ptr task = Task::create(  "t1" );
      task->add_trigger(  "1 == 0");
      fam->addTask( task );
      suite->addFamily( fam );
      theDefs.addSuite( suite );
   }

   ServerTestHarness serverTestHarness;
   serverTestHarness.run(theDefs,
                         ServerTestHarness::testDataDefsLocation("test_why_trigger.def"),
                         1/*timeout*/,
                         false /* waitForTestCompletion*/);

   // Waiting for a trigger expression which will never evaluate
   unsigned int updateCalendarCount = waitForWhy("/test_why_trigger/family/t1", "expression", 10);

   cout << " " << timer.duration() << " update-calendar-count(" << updateCalendarCount << ")\n";
}

BOOST_AUTO_TEST_CASE( test_why_meter )
{
   DurationTimer timer;
   cout << "Test:: ...test_why_meter "<< flush;

   Defs theDefs;
   {
      suite_ptr suite  = Suite::create("test_why_meter" ) ;
      family_ptr fam = Family::create(  "family" );
      fam->addMeter( Meter("meter",0,100,100) );
      task_ptr task = Task::create(  "t1" );
      task->add_trigger(  "/test_why_meter/family:meter > 20");
      fam->addTask( task );
      suite->addFamily( fam );
      theDefs.addSuite( suite );
   }

   ServerTestHarness serverTestHarness;
   serverTestHarness.run(theDefs,
                         ServerTestHarness::testDataDefsLocation("test_why_meter.def"),
                         1/*timeout*/,
                         false /* waitForTestCompletion*/);

   // Waiting for a trigger expression which references a meter.
   unsigned int updateCalendarCount = waitForWhy("/test_why_meter/family/t1", "/test_why_meter/family:meter", 10);

   cout << " " << timer.duration() << " update-calendar-count(" << updateCalendarCount << ")\n";
}

BOOST_AUTO_TEST_CASE( test_why_event )
{
   DurationTimer timer;
   cout << "Test:: ...test_why_event "<< flush;

   Defs theDefs;
   {
      suite_ptr suite  = Suite::create("test_why_event" ) ;
      family_ptr fam = Family::create(  "family" );
      task_ptr t1 = Task::create(  "t1" );
      task_ptr t2 = Task::create(  "t2" );
      t2->addEvent( Event(1,"theEvent") );
      t2->add_trigger(   "1 == 0" ); // make sure task t2 never runs
      t1->add_trigger(   "/test_why_event/family/t2:theEvent == set" );
      fam->addTask( t1 );
      fam->addTask( t2 );
      suite->addFamily( fam );
      theDefs.addSuite( suite );
   }

   ServerTestHarness serverTestHarness;
   serverTestHarness.run(theDefs,
                         ServerTestHarness::testDataDefsLocation("test_why_event.def"),
                         1/*timeout*/,
                         false /* waitForTestCompletion*/);

   // Task t1, should stay queued because the event on task t2 is never set.
   unsigned int updateCalendarCount = waitForWhy("/test_why_event/family/t1", "/test_why_event/family/t2:theEvent", 10);

   cout << " " << timer.duration() << " update-calendar-count(" << updateCalendarCount << ")\n";
}

BOOST_AUTO_TEST_CASE( test_why_user_var )
{
   DurationTimer timer;
   cout << "Test:: ...test_why_user_var "<< flush;

   Defs theDefs;
   {
      suite_ptr suite  = Suite::create("test_why_user_var" ) ;
      family_ptr fam = Family::create(  "family" );
      task_ptr t1 = Task::create(  "t1" );
      suite->addVariable( Variable("user_var","10") );
      t1->add_trigger(  "/test_why_user_var:user_var eq 100" );
      fam->addTask( t1 );
      suite->addFamily( fam );
      theDefs.addSuite( suite );
   }

   ServerTestHarness serverTestHarness;
   serverTestHarness.run(theDefs,
                         ServerTestHarness::testDataDefsLocation("test_why_user_var.def"),
                         1/*timeout*/,
                         false /* waitForTestCompletion*/);

   // Task t1, should stay queued because the user variable 'user_var' value  = 10, is not 100
   unsigned int updateCalendarCount = waitForWhy("/test_why_user_var/family/t1", "/test_why_user_var:user_var", 10);

   cout << " " << timer.duration() << " update-calendar-count(" << updateCalendarCount << ")\n";
}

BOOST_AUTO_TEST_CASE( test_why_gen_var )
{
   DurationTimer timer;
   cout << "Test:: ...test_why_gen_var "<< flush;

   Defs theDefs;
   {
      suite_ptr suite  = Suite::create("test_why_gen_var" ) ;
      family_ptr fam = Family::create(  "family" );
      task_ptr t1 = Task::create(  "t1" );
      t1->add_trigger( "/test_why_gen_var/family/t1:ECF_TRYNO eq 100" );
      fam->addTask( t1 );
      suite->addFamily( fam );
      theDefs.addSuite( suite );
   }

   ServerTestHarness serverTestHarness;
   serverTestHarness.run(theDefs,
                         ServerTestHarness::testDataDefsLocation("test_why_gen_var.def"),
                         1/*timeout*/,
                         false /* waitForTestCompletion*/);

   // Task t1, should stay queued because the generated variable 'ECF_TRYNO' value  = 0, is not 100
   unsigned int updateCalendarCount = waitForWhy("/test_why_gen_var/family/t1", "/test_why_gen_var/family/t1:ECF_TRYNO", 10);

   cout << " " << timer.duration() << " update-calendar-count(" << updateCalendarCount << ")\n";
}

BOOST_AUTO_TEST_CASE( test_why_repeat )
{
   DurationTimer timer;
   cout << "Test:: ...test_why_repeat "<< flush;

   Defs theDefs;
   {
      suite_ptr suite  = Suite::create("test_why_repeat" ) ;
      family_ptr fam = Family::create(  "family" );
      task_ptr t1 = Task::create(  "t1" );
      suite->addRepeat( RepeatInteger("suite_repeat_var",0,3,1));
      fam->addRepeat( RepeatInteger("family_repeat_var",0,3,1));
      t1->add_trigger( "/test_why_repeat/family:family_repeat_var eq 100  or /test_why_repeat:suite_repeat_var eq 100" );
      fam->addTask( t1 );
      suite->addFamily( fam );
      theDefs.addSuite( suite );
   }

   ServerTestHarness serverTestHarness;
   serverTestHarness.run(theDefs,
                         ServerTestHarness::testDataDefsLocation("test_why_repeat.def"),
                         1/*timeout*/,
                         false /* waitForTestCompletion*/);

   // Task t1, should stay queued because the repeat variable on the suite and family do not match
   unsigned int updateCalendarCount = waitForWhy("/test_why_repeat/family/t1", "/test_why_repeat/family:family_repeat_var", 10);

   cout << " " << timer.duration() << " update-calendar-count(" << updateCalendarCount << ")\n";
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: mpartio/ecflow

max_issues_repo_name: mpartio/ecflow

max_forks_repo_name: mpartio/ecflow


text:
/*
 * Copyright 2011 Inalogic® Inc.
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License, as
 * published by the  Free Software Foundation; either version 2.1 or 3.0
 * of the License.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranties of
 * MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR
 * PURPOSE.  See the applicable version of the GNU Lesser General Public
 * License for more details.
 *
 * You should have received a copy of both the GNU Lesser General Public
 * License along with this program. If not, see <http://www.gnu.org/licenses/>
 *
 * Authored by: Tim Penhey <tim.penhey@canonical.com>
 *
 */
#ifndef OPENASR_UTILS_LOGGER_PRIVATE_H
#define OPENASR_UTILS_LOGGER_PRIVATE_H

#include <string>
#include <map>
#include <boost/utility.hpp>

#include "Logger.hpp"
#include "LoggingWriter.hpp"

namespace openasr {
namespace logging {

class LoggerModule
{
public:
  LoggerModule(std::string const& module, LoggerModulePtr const& parent);

  std::string const& module() const;

  bool IsErrorEnabled() const;
  bool IsWarningEnabled() const;
  bool IsInfoEnabled() const;
  bool IsDebugEnabled() const;
  bool IsTraceEnabled() const;

  void SetLogLevel(Level level);
  Level GetLogLevel() const;
  Level GetEffectiveLogLevel() const;

private:
  std::string module_;
  Level level_;
  LoggerModulePtr parent_;
  // An attempt to make sure the writer is around for as long as the loggers.
  Writer& writer_;
};

class LoggerModules : boost::noncopyable
{
public:
  static LoggerModules& Instance();

  LoggerModulePtr const& GetModule(std::string const& module);

  void Reset();
  std::string DumpLoggingLevels(std::string const& prefix) const;

  bool HasModule(std::string const& module) const;

private:
  LoggerModules();

private:
  typedef std::map<std::string, LoggerModulePtr> ModuleMap;
  ModuleMap modules_;
  LoggerModulePtr root_;
};

}
}

#endif


text:
/*
 * Copyright 2015 Aldebaran
 *
 * 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.
 *
*/

/*
* LOCAL includes
*/
#include "camera.hpp"
#include "camera_info_definitions.hpp"
#include "../tools/alvisiondefinitions.h" // for kTop...
#include "../tools/from_any_value.hpp"

/*
* ROS includes
*/
#include <cv_bridge/cv_bridge.h>

/*
* CV includes
*/
#include <opencv2/imgproc/imgproc.hpp>

/*
* BOOST includes
*/
#include <boost/foreach.hpp>
#define for_each BOOST_FOREACH

namespace naoqi
{
namespace converter
{

namespace camera_info_definitions
{

const sensor_msgs::CameraInfo& getEmptyInfo()
{
  static const sensor_msgs::CameraInfo cam_info_msg;
  return cam_info_msg;
}

const sensor_msgs::CameraInfo& getCameraInfo( int camera_source, int resolution )
{
  /** RETURN VALUE OPTIMIZATION (RVO)
  * since there is no C++11 initializer list nor lamda functions
  */
  if ( camera_source == AL::kTopCamera)
  {
    if ( resolution == AL::kVGA )
    {
      static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoTOPVGA();
      return cam_info_msg;
    }
    else if( resolution == AL::kQVGA )
    {
      static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoTOPQVGA();
      return cam_info_msg;
    }
    else if( resolution == AL::kQQVGA )
    {
      static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoTOPQQVGA();
      return cam_info_msg;
    }
  }
  else if ( camera_source == AL::kBottomCamera )
  {
    if ( resolution == AL::kVGA )
    {
      static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoBOTTOMVGA();
      return cam_info_msg;
    }
    else if( resolution == AL::kQVGA )
    {
      static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoBOTTOMQVGA();
      return cam_info_msg;
    }
    else if( resolution == AL::kQQVGA )
    {
      static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoBOTTOMQQVGA();
      return cam_info_msg;
    }
  }
  else if ( camera_source == AL::kDepthCamera )
  {
    if ( resolution == AL::kVGA )
    {
      static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoDEPTHVGA();
      return cam_info_msg;
    }
    else if( resolution == AL::kQVGA )
    {
      static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoDEPTHQVGA();
      return cam_info_msg;
    }
    else if( resolution == AL::kQQVGA )
    {
      static const sensor_msgs::CameraInfo cam_info_msg = createCameraInfoDEPTHQQVGA();
      return cam_info_msg;
    }
  }
  else{
    std::cout << "no camera information found for camera_source " << camera_source << " and res: " << resolution << std::endl;
    return getEmptyInfo();
  }
}

} // camera_info_definitions

CameraConverter::CameraConverter( const std::string& name, const float& frequency, const qi::SessionPtr& session, const int& camera_source, const int& resolution )
  : BaseConverter( name, frequency, session ),
    p_video_( session->service("ALVideoDevice") ),
    camera_source_(camera_source),
    resolution_(resolution),
    // change in case of depth camera
    colorspace_( (camera_source_!=AL::kDepthCamera)?AL::kRGBColorSpace:AL::kRawDepthColorSpace ),
    msg_colorspace_( (camera_source_!=AL::kDepthCamera)?"rgb8":"16UC1" ),
    cv_mat_type_( (camera_source_!=AL::kDepthCamera)?CV_8UC3:CV_16U ),
    camera_info_( camera_info_definitions::getCameraInfo(camera_source, resolution) )
{
  if ( camera_source == AL::kTopCamera )
  {
    msg_frameid_ = "CameraTop_optical_frame";
  }
  else if (camera_source == AL::kBottomCamera )
  {
    msg_frameid_ = "CameraBottom_optical_frame";
  }
  else if (camera_source_ == AL::kDepthCamera )
  {
    msg_frameid_ = "CameraDepth_optical_frame";
  }
  // Overwrite the parameters for the infrared
  else if (camera_source_ == AL::kInfraredCamera )
  {
    // Reset to kDepth since it's the same device handle
    camera_source_ = AL::kDepthCamera;
    msg_frameid_ = "CameraDepth_optical_frame";
    colorspace_ = AL::kInfraredColorSpace;
    msg_colorspace_ = "16UC1";
    cv_mat_type_ = CV_16U;
    camera_info_ = camera_info_definitions::getCameraInfo(camera_source_, resolution_);
  }
}

CameraConverter::~CameraConverter()
{
  if (!handle_.empty())
  {
    std::cout << "Unsubscribe camera handle " << handle_ << std::endl;
    p_video_.call<qi::AnyValue>("unsubscribe", handle_);
    handle_.clear();
  }
}

void CameraConverter::reset()
{
  if (!handle_.empty())
  {
    p_video_.call<qi::AnyValue>("unsubscribe", handle_);
    handle_.clear();
  }

  handle_ = p_video_.call<std::string>(
                         "subscribeCamera",
                          name_,
                          camera_source_,
                          resolution_,
                          colorspace_,
                          frequency_
                          );
}

void CameraConverter::registerCallback( const message_actions::MessageAction action, Callback_t cb )
{
  callbacks_[action] = cb;
}

void CameraConverter::callAll( const std::vector<message_actions::MessageAction>& actions )
{

  if (handle_.empty() )
  {
    std::cerr << name_ << "Camera Handle is empty - cannot retrieve image" << std::endl;
    std::cerr << name_ << "Might be a NAOqi problem. Try to restart the ALVideoDevice." << std::endl;
    return;
  }

  qi::AnyValue image_anyvalue = p_video_.call<qi::AnyValue>("getImageRemote", handle_);
  tools::NaoqiImage image;
  try{
      image = tools::fromAnyValueToNaoqiImage(image_anyvalue);
  }
  catch(std::runtime_error& e)
  {
    std::cout << "Cannot retrieve image" << std::endl;
    return;
  }

  // Create a cv::Mat of the right dimensions
  cv::Mat cv_img(image.height, image.width, cv_mat_type_, image.buffer);
  msg_ = cv_bridge::CvImage(std_msgs::Header(), msg_colorspace_, cv_img).toImageMsg();
  msg_->header.frame_id = msg_frameid_;

  msg_->header.stamp = ros::Time::now();
  //msg_->header.stamp.sec = image.timestamp_s;
  //msg_->header.stamp.nsec = image.timestamp_us*1000;
  camera_info_.header.stamp = msg_->header.stamp;

  for_each( const message_actions::MessageAction& action, actions )
  {
    callbacks_[action]( msg_, camera_info_ );
  }
}

} // publisher
} //naoqi


text:
////////////////////////////////////////////////////////////////////////////////////////////////////
// ExtractData.cpp
// Copyright (c) 2020 Pdfix. All Rights Reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////

#include "pdfixsdksamples/ExtractData.h"

#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/xml_parser.hpp>
// project
#include "Pdfix.h"

namespace ExtractData {

  void ExtractStructElement(PdsStructElement* elem, ptree &node, const DataType& data_types) {
    auto put_non_empty = [&](const auto &key, const auto &value) {
      if (!value.length()) return;
      node.put(key, EncodeText(value));
    };
    put_non_empty("type", elem->GetType(true));
    put_non_empty("title", elem->GetTitle());
    put_non_empty("lang", elem->GetLang());
    put_non_empty("id", elem->GetId());
    put_non_empty("alt", elem->GetAlt());
    put_non_empty("actual_text", elem->GetActualText());

    ptree kids_node;
    for (int i = 0; i < elem->GetNumChildren(); i++) {
      ptree kid_node;
      switch (elem->GetChildType(i)) {
        case kPdsStructChildElement: {
          // structure element reference
          kid_node.put("kid_type", "element");
          auto kid_obj = elem->GetChildObject(i);
          ExtractStructObject(elem->GetStructTree(), kid_obj, kid_node, data_types);
          break;
        }
        case kPdsStructChildStreamContent: {
          kid_node.put("kid_type", "stream_content");
          // object reference
          auto kid_obj = elem->GetChildObject(i);
          kid_node.put("obj", kid_obj->GetId());
          break;
        }
        case kPdsStructChildObject: {
          kid_node.put("kid_type", "object");
          // object reference
          auto kid_obj = elem->GetChildObject(i);
          kid_node.put("obj", kid_obj->GetId());
          break;
        }
        case kPdsStructChildPageContent: {
          kid_node.put("kid_type", "page_content");
          // content element reference
          kid_node.put("mcid", elem->GetChildMcid(i));
          kid_node.put("page_num", elem->GetChildPageNumber(i));
          break;
        }
        default:; // unknown/invalid reference
      }
      kids_node.push_back(std::make_pair("", kid_node));
    }
    if (!kids_node.empty())
      node.put_child("kids", kids_node);
  }

  void ExtractStructObject(PdsStructTree* struct_tree, PdsObject* object, ptree &node,
    const DataType& data_types) {
    auto elem = struct_tree->GetStructElementFromObject(object);
    if (!elem)
      throw PdfixException();
    ExtractStructElement(elem, node, data_types);
  }

  void ExtractStructTree(PdsStructTree* struct_tree, ptree &node, const DataType& data_types) {
    ptree kids_node;
    for (int i = 0; i < struct_tree->GetNumChildren(); i++) {
      auto struct_elem_obj = struct_tree->GetChildObject(i);
      ptree kid_node;
      ExtractStructObject(struct_tree, struct_elem_obj, kid_node, data_types);
      kids_node.push_back(std::make_pair("", kid_node));
    }
    if (!kids_node.empty())
      node.put_child("kids", kids_node);
  }
}

max_stars_repo_name: laoola/ProjectCode

max_issues_repo_name: laoola/ProjectCode

max_forks_repo_name: laoola/ProjectCode


text:
#include "stdafx.h"
#include <conio.h>
#include "runtime_include/NSDriverApi.h"
#include <memory>
#include <boost/dll.hpp>
#include <functional>
#include "PluginInstance.h"
#include "IdentificationService.h"
#include "WaveformGenerators.h"
int main()
{

	using driver_create_t = std::function<int(hvr_platform**)>;
	using driver_start_t = std::function<int(hvr_platform*)>;
	using driver_stop_t = std::function<int(hvr_platform*)>;
	using driver_destroy_t = std::function<void(hvr_platform**)>;
	using driver_version_t = std::function<unsigned int(void)>;

	using driver_setupdiag_t = std::function<int(hvr_platform*, hvr_diagnostics_ui*)>;
	using driver_drawdiag_t = std::function<int(hvr_platform*)>;

	boost::system::error_code loadFailure;
	auto driver = std::make_unique<boost::dll::shared_library>("HardlightPlatform", boost::dll::load_mode::append_decorations, loadFailure);
	if (loadFailure) {
		std::cout << "Couldn't load HardlightPlatform.dll\n";
	}

	driver_create_t driver_create;

	if (!tryLoad(driver, "hvr_platform_create", driver_create)) {
		std::cout << "Couldn't find NSVR_Driver_Create()\n";
	}

	driver_start_t driver_start;

	if (!tryLoad(driver, "hvr_platform_startup", driver_start)) {
		std::cout << "Couldn't find NSVR_Driver_Create()\n";
	}
	driver_stop_t driver_stop;

	if (!tryLoad(driver, "hvr_platform_shutdown", driver_stop)) {
		std::cout << "Couldn't find NSVR_Driver_Shutdown()\n";
	}
	driver_destroy_t driver_destroy;

	if (!tryLoad(driver, "hvr_platform_destroy", driver_destroy)) {
		std::cout << "Couldn't find NSVR_Driver_Destroy()\n";
	}

	driver_version_t driver_getversion;
	if (!tryLoad(driver, "hvr_platform_getversion", driver_getversion)) {
		std::cout << "Couldn't find NSVR_Driver_GetVersion()\n";
	}

	driver_setupdiag_t driver_setupdiag;
	if (!tryLoad(driver, "hvr_platform_setupdiagnostics", driver_setupdiag)) {
		std::cout << "Couldn't find NSVR_Driver_SetupDiagnostics()\n";
	}

	driver_drawdiag_t driver_drawdiag;
	if (!tryLoad(driver, "hvr_platform_updatediagnostics", driver_drawdiag)) {
		std::cout << "Couldn't find NSVR_Driver_DrawDiagnostics()\n";
	}

	std::cout << "========= NSVREngine Version " << HVR_VERSION_STRING << " =========\n";
	hvr_platform* context = nullptr;
	if (driver_create(&context) < 0) {
		std::cout << "Engine had fatal error starting; check logs [enter to close]\n";
		std::cin.get();
	}
	else {
		driver_start(context);
		std::cin.get();
		driver_stop(context);
		driver_destroy(&context);
	}
	return 0;
}

max_stars_repo_name: cwaldren/HL-engine

max_issues_repo_name: cwaldren/HL-engine

max_forks_repo_name: cwaldren/HL-engine


text:
#include "zinfandel.h"

#include "parse_args.h"
#include "tensorOps.h"
#include "threads.h"

#include <Eigen/SVD>
#include <complex>

// Helper Functions
Eigen::MatrixXcf GrabSources(
    Cx3 const &ks,
    float const scale,
    long const n_src,
    long const s_read,
    long const n_read,
    std::vector<long> const &spokes)
{
  assert((s_read + n_read + n_src) < ks.dimension(1));
  long const n_chan = ks.dimension(0);
  long const n_spoke = spokes.size();
  Eigen::MatrixXcf S(n_chan * n_src, n_read * n_spoke);
  S.setZero();
  for (long i_spoke = 0; i_spoke < n_spoke; i_spoke++) {
    long const col_spoke = i_spoke * n_read;
    long const ind_spoke = spokes[i_spoke];
    assert(ind_spoke < ks.dimension(2));
    for (long i_read = 0; i_read < n_read; i_read++) {
      long const col = col_spoke + i_read;
      for (long i_coil = 0; i_coil < n_chan; i_coil++) {
        long const row_coil = i_coil * n_src;
        for (long i_src = 0; i_src < n_src; i_src++) {
          long const row = row_coil + i_src;
          S(row, col) = ks(i_coil, s_read + i_read + i_src, ind_spoke) / scale;
        }
      }
    }
  }
  return S;
}

Eigen::MatrixXcf GrabTargets(
    Cx3 const &ks,
    float const scale,
    long const s_read,
    long const n_read,
    std::vector<long> const &spokes)
{
  long const n_chan = ks.dimension(0);
  long const n_spoke = spokes.size();
  Eigen::MatrixXcf T(n_chan, n_read * n_spoke);
  T.setZero();
  for (long i_spoke = 0; i_spoke < n_spoke; i_spoke++) {
    long const col_spoke = i_spoke * n_read;
    long const ind_spoke = spokes[i_spoke];
    for (long i_read = 0; i_read < n_read; i_read++) {
      long const col = col_spoke + i_read;
      for (long i_coil = 0; i_coil < n_chan; i_coil++) {
        T(i_coil, col) = ks(i_coil, s_read + i_read, ind_spoke) / scale;
      }
    }
  }
  return T;
}

Eigen::MatrixXcf
CalcWeights(Eigen::MatrixXcf const &src, Eigen::MatrixXcf const tgt, float const lambda)
{
  if (lambda > 0.f) {
    auto const reg = lambda * src.norm() * Eigen::MatrixXcf::Identity(src.rows(), src.rows());
    auto const rhs = src * src.adjoint() + reg;
    Eigen::MatrixXcf pinv = rhs.completeOrthogonalDecomposition().pseudoInverse();
    return tgt * src.adjoint() * pinv;
  } else {
    Eigen::MatrixXcf const pinv = src.completeOrthogonalDecomposition().pseudoInverse();
    return tgt * pinv;
  }
}

std::vector<long>
FindClosest(R3 const &traj, long const &tgt, long const &n_spoke, std::vector<long> &all_spokes)
{
  std::vector<long> spokes(n_spoke);
  R1 const end_is = traj.chip(tgt, 2).chip(traj.dimension(1) - 1, 1);
  std::partial_sort(
      all_spokes.begin(),
      all_spokes.begin() + n_spoke,
      all_spokes.end(),
      [&traj, end_is](long const a, long const b) {
        auto const &end_a = traj.chip(a, 2).chip(traj.dimension(1) - 1, 1);
        auto const &end_b = traj.chip(b, 2).chip(traj.dimension(1) - 1, 1);
        return Norm(end_a - end_is) < Norm(end_b - end_is);
      });
  std::copy_n(all_spokes.begin(), n_spoke, spokes.begin());
  return spokes;
}

// Actual calculation
void zinfandel(
    long const gap_sz,
    long const n_src,
    long const n_spoke,
    long const n_read1,
    float const lambda,
    R3 const &traj,
    Cx3 &ks,
    Log &log)
{
  long const n_read = n_read1 < 1 ? ks.dimension(1) - (gap_sz + n_src) : n_read1;

  log.info(
      FMT_STRING("ZINFANDEL Gap {} Sources {} Cal Spokes/Read {}/{} "),
      gap_sz,
      n_src,
      n_spoke,
      n_read);

  for (long ig = gap_sz; ig > 0; ig--) {
    auto spoke_task = [&](long const spoke_lo, long const spoke_hi) {
      std::vector<long> all_spokes(ks.dimension(2)); // Need a thread-local copy of the indices
      std::iota(all_spokes.begin(), all_spokes.end(), 0L);
      for (auto is = spoke_lo; is < spoke_hi; is++) {
        float const scale = R0(ks.chip(is, 2).abs().maximum())();
        auto const spokes = FindClosest(traj, is, n_spoke, all_spokes);
        auto const calS = GrabSources(ks, scale, n_src, ig + 1, n_read, spokes);
        auto const calT = GrabTargets(ks, scale, ig, n_read, spokes);
        auto const W = CalcWeights(calS, calT, lambda);
        auto const S = GrabSources(ks, scale, n_src, ig, 1, {is});
        auto const T = W * S;
        for (long icoil = 0; icoil < ks.dimension(0); icoil++) {
          ks(icoil, ig - 1, is) = T(icoil) * scale;
        }
      }
    };
    Threads::RangeFor(spoke_task, 0, ks.dimension(2));
  }
}


text: #include <boost/throw_exception.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino