text:
/********************************************************************
 * Copyright (c) 2013 - 2014, Pivotal Inc.
 * All rights reserved.
 *
 * Author: Zhanwei Wang
 ********************************************************************/
/********************************************************************
 * 2014 -
 * open source under Apache License Version 2.0
 ********************************************************************/
/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "Exception.h"
#include "ExceptionInternal.h"
#include "Logger.h"
#include "Memory.h"
#include "RpcClient.h"
#include "Thread.h"

#include <boost/uuid/uuid_generators.hpp>

namespace Hdfs {
namespace Internal {

once_flag RpcClient::once;
shared_ptr<RpcClient> RpcClient::client;

void RpcClient::createSinglten() {
    client = shared_ptr < RpcClient > (new RpcClientImpl());
}

RpcClient & RpcClient::getClient() {
    call_once(once, &RpcClientImpl::createSinglten);
    assert(client);
    return *client;
}

RpcClientImpl::RpcClientImpl() :
    cleaning(false), running(true), count(0) {
    auto id = boost::uuids::random_generator()();
    clientId.resize(boost::uuids::uuid::static_size());
    memcpy(&clientId[0], id.begin(), boost::uuids::uuid::static_size());
#ifdef MOCK
    stub = NULL;
#endif
}

RpcClientImpl::~RpcClientImpl() {
    running = false;
    cond.notify_all();

    if (cleaner.joinable()) {
        cleaner.join();
    }

    close();
}

void RpcClientImpl::clean() {
    assert(cleaning);

    try {
        while (running) {
            try {
                unique_lock<mutex> lock(mut);
                cond.wait_for(lock, seconds(1));

                if (!running || allChannels.empty()) {
                    break;
                }

                unordered_map<RpcChannelKey, shared_ptr<RpcChannel> >::iterator s, e;
                e = allChannels.end();

                for (s = allChannels.begin(); s != e;) {
                    if (s->second->checkIdle()) {
                        s->second.reset();
                        s = allChannels.erase(s);
                    } else {
                        ++s;
                    }
                }
            } catch (const HdfsCanceled & e) {
                /*
                 * ignore cancel signal here.
                 */
            }
        }
    } catch (const Hdfs::HdfsException & e) {
        std::string buffer;
        LOG(LOG_ERROR, "RpcClientImpl's idle cleaner exit: %s",
            GetExceptionDetail(e, buffer));
    } catch (const std::exception & e) {
        LOG(LOG_ERROR, "RpcClientImpl's idle cleaner exit: %s", e.what());
    }

    cleaning = false;
}

void RpcClientImpl::close() {
    lock_guard<mutex> lock(mut);
    running = false;
    unordered_map<RpcChannelKey, shared_ptr<RpcChannel> >::iterator s, e;
    e = allChannels.end();

    for (s = allChannels.begin(); s != e; ++s) {
        s->second->waitForExit();
    }

    allChannels.clear();
}

bool RpcClientImpl::isRunning() {
    return running;
}

RpcChannel & RpcClientImpl::getChannel(const RpcAuth & auth,
                                       const RpcProtocolInfo & protocol, const RpcServerInfo & server,
                                       const RpcConfig & conf) {
    shared_ptr<RpcChannel> rc;
    RpcChannelKey key(auth, protocol, server, conf);

    try {
        lock_guard<mutex> lock(mut);

        if (!running) {
            THROW(Hdfs::HdfsRpcException,
                  "Cannot Setup RPC channel to \"%s:%s\" since RpcClient is closing",
                  key.getServer().getHost().c_str(), key.getServer().getPort().c_str());
        }

        unordered_map<RpcChannelKey, shared_ptr<RpcChannel> >::iterator it;
        it = allChannels.find(key);

        if (it != allChannels.end()) {
            rc = it->second;
        } else {
            rc = createChannelInternal(key);
            allChannels[key] = rc;
        }

        rc->addRef();

        if (!cleaning) {
            cleaning = true;

            if (cleaner.joinable()) {
                cleaner.join();
            }

            CREATE_THREAD(cleaner, bind(&RpcClientImpl::clean, this));
        }
    } catch (const HdfsRpcException & e) {
        throw;
    } catch (...) {
        NESTED_THROW(HdfsRpcException,
                     "RpcClient failed to create a channel to \"%s:%s\"",
                     server.getHost().c_str(), server.getPort().c_str());
    }

    return *rc;
}

shared_ptr<RpcChannel> RpcClientImpl::createChannelInternal(
    const RpcChannelKey & key) {
    shared_ptr<RpcChannel> channel;
#ifdef MOCK

    if (stub) {
        channel = shared_ptr < RpcChannel > (stub->getChannel(key, *this));
    } else {
        channel = shared_ptr < RpcChannel > (new RpcChannelImpl(key, *this));
    }

#else
    channel = shared_ptr<RpcChannel>(new RpcChannelImpl(key, *this));
#endif
    return channel;
}

}
}


text: #include <boost/algorithm/string/constants.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include <stan/math/mix/mat.hpp>
#include <gtest/gtest.h>
#include <boost/random/mersenne_twister.hpp>
#include <boost/math/distributions.hpp>

using Eigen::Matrix;
using Eigen::Dynamic;

TEST(ProbDistributionsMultinomial,fvar_var) {
  using stan::math::var;
  using stan::math::fvar;
  std::vector<int> ns;
  ns.push_back(1);
  ns.push_back(2);
  ns.push_back(3);
  Matrix<fvar<var>,Dynamic,1> theta(3,1);
  theta << 0.2, 0.3, 0.5;
  for (int i = 0; i < 3; i++)
    theta(i).d_ = 1.0;

  EXPECT_FLOAT_EQ(-2.002481, stan::math::multinomial_log(ns,theta).val_.val());
  EXPECT_FLOAT_EQ(17.666666, stan::math::multinomial_log(ns,theta).d_.val());
}

TEST(ProbDistributionsMultinomial,fvar_fvar_var) {
  using stan::math::var;
  using stan::math::fvar;
  std::vector<int> ns;
  ns.push_back(1);
  ns.push_back(2);
  ns.push_back(3);
  Matrix<fvar<fvar<var> >,Dynamic,1> theta(3,1);
  theta << 0.2, 0.3, 0.5;
  for (int i = 0; i < 3; i++)
    theta(i).d_.val_ = 1.0;

  EXPECT_FLOAT_EQ(-2.002481, stan::math::multinomial_log(ns,theta).val_.val_.val());
  EXPECT_FLOAT_EQ(17.666666, stan::math::multinomial_log(ns,theta).d_.val_.val());
}

ext: cpp

max_stars_repo_name: yizhang-cae/torsten

max_issues_repo_name: yizhang-cae/torsten

max_forks_repo_name: yizhang-cae/torsten


text:
//
//=======================================================================
// Copyright 2012-2104
// Author: Alex Hagen-Zanker
//
// 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)
//=======================================================================
//
// Demonstrates different ways of using the resumable dijkstra classes
//
//=======================================================================
//
#include <blink/graph/resumable_dijkstra.hpp>
#include <blink/graph/dijkstra_object.hpp>
#include <blink/graph/dijkstra_functions.hpp>
#include <blink/graph/dijkstra_state.hpp>
#include <blink/graph/dijkstra_heap_wrapper.hpp>
#include <blink/graph/dijkstra_visitor/distance_visitor.hpp>
#include <blink/graph/dijkstra_visitor/joined_visitor.hpp>
#include <blink/graph/dijkstra_visitor/logging_visitor.hpp>
#include <blink/graph/dijkstra_visitor/target_visitor.hpp>
#include <blink/graph/dijkstra_visitor/nearest_source_visitor.hpp>

#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/iteration_macros.hpp>
#include <boost/graph/properties.hpp>
#include <boost/heap/d_ary_heap.hpp>
#include <boost/ref.hpp>

#include <iostream>
#include <vector>

template<typename Graph, typename DistanceMap, typename ColorMap>
void report_progress(const Graph& g, DistanceMap d, ColorMap c)
{
  std::cout <<"Vertex" <<'\t' << "Color" <<'\t' << "Distance" << std::endl;
  BGL_FORALL_VERTICES_T(v, g, Graph) {
    std::cout << v <<'\t' << get(c,v) <<'\t' << get(d,v) << std::endl;
  }
  std::cout << std::endl;
}

template<typename Graph, typename DistanceMap, typename ColorMap,
  typename NearestMap>
void report_progress(const Graph& g, DistanceMap d, ColorMap c, NearestMap n)
{
  std::cout <<"Vertex" <<'\t' << "Color" <<'\t' << "Distance" << std::endl;
  BGL_FORALL_VERTICES_T(v, g, Graph) {
    std::cout << v <<'\t' << get(c,v) <<'\t' << get(d,v) <<'\t' << get(n,v)
      << std::endl;
  }
  std::cout << std::endl;
}

typedef boost::property<boost::edge_weight_t, double> edge_prop;
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, boost::no_property, edge_prop>
  graph_type;

typedef boost::graph_traits<graph_type>::vertex_descriptor vertex_descriptor;
typedef boost::property_map<graph_type, boost::vertex_index_t>::type  vertex_index_map_type;
typedef boost::shared_array_property_map<vertex_descriptor, vertex_index_map_type>
  predecessor_map_type;

typedef boost::shared_array_property_map<double, vertex_index_map_type>
  distance_map_type;

typedef boost::two_bit_color_map<vertex_index_map_type> color_map_type;

graph_type make_a_simple_graph(size_t n)
{
  graph_type g(n);
  for(size_t i = 0; i < n; ++i) {
    const vertex_descriptor a = i;
    const vertex_descriptor b = (i + 1) % n;
    const double w = 1.0;

    boost::add_edge(a, b, w, g);
    boost::add_edge(b, a, w, g);
  }
  return g;
}

void test_target_visitor(int n)
{
  std::cout << "Test Target Visitor" << std::endl;

  typedef blink::target_helper_indirect<graph_type, boost::no_named_parameters>::visitor_type visitor_type;
  typedef blink::resumable_dijkstra_helper<graph_type, boost::no_named_parameters>::type dijkstra_type;

  graph_type g = make_a_simple_graph(n);
  dijkstra_type dijkstra = blink::make_resumable_dijkstra(g);

  visitor_type vis = blink::make_target_visitor(dijkstra.get_dijkstra_state());

  vis.add_target(3);
  vis.add_target(6);

  dijkstra.init_from_source(4, vis);

  dijkstra_type::param<boost::vertex_distance_t>::type& distance_map = dijkstra.get(boost::vertex_distance_t() );
  dijkstra_type::param<boost::vertex_color_t>::type& color_map = dijkstra.get(boost::vertex_color_t() );

  dijkstra.expand(vis, vis); // vis doubles as interruptor
  std::cout << "Must reach targets 3 and 6" << std::endl;

  report_progress(g, distance_map, color_map);

  vis.add_target(5);
  dijkstra.expand(vis, vis); // vis doubles as interruptor
  std::cout << "Must reach target 5 too" << std::endl;
  report_progress(g, distance_map, color_map);

  vis.add_target(8);
  dijkstra.expand(vis, vis); // vis doubles as interruptor
  std::cout << "Must reach target 8 too" << std::endl;
  report_progress(g, distance_map, color_map);

  dijkstra.expand();
  std::cout << "Must reach all targets" << std::endl;
  report_progress(g, distance_map, color_map);
}

void test_target_visitor_auto(int n)
{
  std::cout << "Test Target Visitor" << std::endl;

  auto g = make_a_simple_graph(n);

  auto dijkstra = blink::make_resumable_dijkstra(g);
  auto vis = blink::make_target_visitor(dijkstra.get_dijkstra_state());

  vis.add_target(3);
  vis.add_target(6);

  dijkstra.init_from_source(4, vis);
  dijkstra.expand(vis,vis ); // vis doubles as interruptor

  auto distance_map = dijkstra.get(boost::vertex_distance_t());
  auto color_map = dijkstra.get(boost::vertex_color_t());

  report_progress(g, distance_map, color_map);

  vis.add_target(5);
  dijkstra.expand(vis, vis); // vis doubles as interruptor
  report_progress(g, distance_map, color_map);

  vis.add_target(8);
  dijkstra.expand(vis, vis); // vis doubles as interruptor
  report_progress(g, distance_map, color_map);

  dijkstra.expand();
  report_progress(g, distance_map, color_map);
 }

void test_target_visitor_convenience(int n)
{
  std::cout << "Test Target Visitor - Convenience" << std::endl;

  graph_type g = make_a_simple_graph(n);
  distance_map_type distance(n, get(boost::vertex_index_t(), g) );
  color_map_type color(n, get(boost::vertex_index_t(), g) );

  std::vector<int> targets;
  targets.push_back(5);
  targets.push_back(6);

  vertex_descriptor orig = 4;

  blink::dijkstra_shortest_path_targets(g, orig, targets,
    distance_map(distance).color_map(color) );

  report_progress(g, distance, color);
}

void test_nearest_visitor(int n)
{
  std::cout << "Test Nearest Visitor" << std::endl;
  typedef blink::nearest_source_helper_indirect<graph_type, boost::no_named_parameters>::visitor_type visitor_type;
  typedef blink::resumable_dijkstra_helper<graph_type, boost::no_named_parameters>::type dijkstra_type;

  graph_type g = make_a_simple_graph(n);
  dijkstra_type dijkstra = blink::make_resumable_dijkstra(g);
  visitor_type vis = blink::make_nearest_source_visitor(dijkstra.get_dijkstra_state());

  std::vector<vertex_descriptor> sources;

  sources.push_back(4);
  sources.push_back(7);
  sources.push_back(11);

  dijkstra.init_from_sources(sources, vis);
  dijkstra.expand(blink::default_interruptor(), vis);

  dijkstra_type::param<boost::vertex_distance_t>::type  distance_map
    = dijkstra.get(boost::vertex_distance_t() );
  dijkstra_type::param<boost::vertex_color_t>::type  color_map
    = dijkstra.get(boost::vertex_color_t() );

  report_progress(g, distance_map, color_map, vis.m_nearest_source_map);
}

void test_nearest_visitor_convenience(int n)
{
  std::cout << "Test Nearest Visitor - Convenience Function" << std::endl;

  graph_type g = make_a_simple_graph(n);

  typedef blink::dijkstra_state_helper<graph_type, boost::no_named_parameters>::type state_type;
  typedef blink::nearest_source_helper<state_type>::visitor_type visitor_type;
  typedef blink::nearest_source_helper<state_type>::map_type map_type;

  std::vector<vertex_descriptor> sources;

  sources.push_back(4);
  sources.push_back(7);
  sources.push_back(11);

  std::pair<state_type, visitor_type> result = blink::dijkstra_shortest_path_nearest_source(g, sources);

  state_type::param<boost::vertex_distance_t>::type distance_map
    = result.first.get<boost::vertex_distance_t>();

  state_type::param<boost::vertex_color_t>::type color_map
    = result.first.get<boost::vertex_color_t>();

  report_progress(g, distance_map, color_map, result.second.m_nearest_source_map);
}

void test_distance_visitor(int n)
{
  typedef blink::resumable_dijkstra_helper<graph_type, boost::no_named_parameters>::type dijkstra_type;
  typedef blink::distance_visitor_helper_indirect<graph_type, boost::no_named_parameters> helper;
  typedef helper::type visitor_type;

  std::cout << "Test Distance Visitor" << std::endl;
  graph_type g = make_a_simple_graph(n);

  double first_target_distance = 2.0;
  double second_target_distance = 4.0;

  dijkstra_type dijkstra = blink::make_resumable_dijkstra(g);
  visitor_type visitor = helper::make(dijkstra.get_dijkstra_state(), first_target_distance);

  vertex_descriptor orig = 4;
  dijkstra.init_from_source(orig, visitor);
  dijkstra.expand(visitor, visitor); // vis doubles as interrupetor

  dijkstra_type::param<boost::vertex_distance_t>::type  distance_map
    = dijkstra.get(boost::vertex_distance_t() );

  dijkstra_type::param<boost::vertex_color_t>::type  color_map
    = dijkstra.get(boost::vertex_color_t() );

  std::cout << "must reach distance 2" << std::endl;
  report_progress(g, distance_map, color_map);

  visitor_type second_visitor = helper::make(dijkstra.get_dijkstra_state(), second_target_distance);

  dijkstra.expand(second_visitor, second_visitor); // now secondvis is the interruptor
  std::cout << "must reach distance 4" << std::endl;
  report_progress(g, distance_map, color_map);
}

void test_classic_boost(int n)
{
  std::cout << "Test Classic Boost(note the faulty colormap)" << std::endl;

  graph_type g = make_a_simple_graph(n);
  distance_map_type distance(n, get(boost::vertex_index, g));
  color_map_type color(n, get(boost::vertex_index, g) );
  vertex_descriptor orig = 4;
  boost::dijkstra_shortest_paths(g, orig, distance_map(distance).color_map(color));

  report_progress(g, distance, color);
}

void test_classic_blink(int n)
{
  std::cout << "Test Classic Blink" << std::endl;

  graph_type g = make_a_simple_graph(n);
  typedef blink::dijkstra_state_helper<graph_type, boost::no_named_parameters>::type state_type;
  vertex_descriptor orig = 4;
  state_type state = blink::dijkstra_shortest_path_plain(g, orig);

  report_progress(g, state.get<boost::vertex_distance_t>(), state.get<boost::vertex_color_t>());
}

void test_distance_visitor_convenience(int n)
{
  std::cout << "Test Distance Visitor - Convenience" << std::endl;
  graph_type g = make_a_simple_graph(n);
  distance_map_type distance(n, get(boost::vertex_index, g));
  color_map_type color(n, get(boost::vertex_index, g) );

  double target_distance = 4;
  vertex_descriptor orig = 4;

  blink::dijkstra_shortest_path_distance(g, orig, target_distance, distance_map(distance).color_map(color));

  std::cout << "must reach distance 4" << std::endl;
  report_progress(g, distance, color );
}

void test_dijkstra_object(int n)
{
  std::cout << "Test Dijkstra Object" << std::endl;
  graph_type g = make_a_simple_graph(n);

  typedef std::vector<vertex_descriptor> source_range_type;
  typedef blink::only_finish_vertex_type control_map_type;
  typedef boost::no_named_parameters parameters_type;
  typedef blink::dijkstra_object_helper<
      graph_type,
      source_range_type,
      control_map_type,
      parameters_type>::type dijkstra_object_type;

  double target_distance = 4;
  vertex_descriptor orig = 4;
  source_range_type sources(1,orig);

  dijkstra_object_type dijkstra = blink::make_dijkstra_object(g, sources, blink::only_finish_vertex_type());

  dijkstra_object_type::param<boost::vertex_distance_t>::type  distance_map = dijkstra.get(boost::vertex_distance_t() );
  dijkstra_object_type::param<boost::vertex_color_t   >::type  color_map    = dijkstra.get(boost::vertex_color_t()    );

  while(dijkstra()) {
    const double distance = get(distance_map, dijkstra.get_u());
    if(distance >= target_distance) {
      break;
    }
  }
  std::cout << "must reach distance " << target_distance << std::endl;
  report_progress(g, distance_map, color_map );
}

void test_dijkstra_object2(int n)
{
  std::cout << "Test Dijkstra Object - yielding at all visitor positions" << std::endl;
  std::cout << "Every action should be logged twice once by the object and once by the object user" << std::endl;

  typedef blink::logging_visitor<std::ostream> visitor_type;
  typedef boost::bgl_named_params<visitor_type, boost::graph_visitor_t> parameters_type;
  typedef std::vector<vertex_descriptor> source_range_type;
  typedef blink::dijkstra_visitor_control_point_vector control_map_type;

  typedef blink::dijkstra_object_helper<
    graph_type,
    source_range_type,
    control_map_type,
    parameters_type>::type dijkstra_object_type;

  graph_type g = make_a_simple_graph(n);
  visitor_type vis(std::cout);

  vertex_descriptor orig = 4;
  source_range_type sources(1,orig);

  dijkstra_object_type dijkstra = blink::make_dijkstra_object(g, sources, control_map_type(), boost::visitor(vis) );

  while(dijkstra()) {
    switch(dijkstra.get_control_point())
    {
    case blink::cp_initialize_vertex:
      vis.initialize_vertex(dijkstra.get_v(), g);
      break;
    case blink::cp_examine_vertex:
      vis.examine_vertex(dijkstra.get_u(), g);
      break;
    case blink::cp_examine_edge:
      vis.examine_edge(dijkstra.get_e(), g);
      break;
    case blink::cp_discover_vertex:
      vis.discover_vertex(dijkstra.get_v(), g);
      break;
    case blink::cp_edge_relaxed:
      vis.edge_relaxed(dijkstra.get_e(), g);
      break;
    case blink::cp_edge_not_relaxed:
      vis.edge_not_relaxed(dijkstra.get_e(), g);
      break;
    case blink::cp_finish_vertex:
      vis.finish_vertex(dijkstra.get_u(), g);
      break;
    default : std::cout << "other control_point" << std::endl;
    }
  }
}

void test_with_boost_heap(int n)
{
  typedef boost::indirect_cmp<distance_map_type, std::greater<double> > indirect_compare;
  typedef boost::heap::d_ary_heap
    < vertex_descriptor
    , boost::heap::compare<indirect_compare>
    , boost::heap::mutable_<true>
    , boost::heap::arity<4>
    , boost::heap::store_parent_pointer<false>
    , boost::heap::constant_time_size<false>
    > heap_type;

  typedef blink::dijkstra_heap_wrapper<heap_type, graph_type, vertex_index_map_type> wrapped_heap_type;
  typedef boost::bgl_named_params<boost::reference_wrapper<wrapped_heap_type>, boost::max_priority_queue_t,
    boost::bgl_named_params<distance_map_type, boost::vertex_distance_t> > parameters_type;
  typedef blink::dijkstra_state_helper<graph_type, parameters_type>::type state_type;

  graph_type g = make_a_simple_graph(n);
  vertex_index_map_type index = get(boost::vertex_index, g);
  distance_map_type distance(n, index);
  vertex_descriptor orig = 4;
  wrapped_heap_type heap(g, index, distance);
  state_type state = blink::dijkstra_shortest_path_plain(g, orig,
    boost::max_priority_queue(heap).distance_map(distance));
  report_progress(g, state.get<boost::vertex_distance_t>(), state.get<boost::vertex_color_t>());
}

void test_dijkstra_object3(int n)
{
  std::cout << "Test Dijkstra Object - Simplest Demo" << std::endl;

  graph_type g = make_a_simple_graph(n);
  vertex_descriptor orig = 4;
  std::vector<vertex_descriptor> sources(1, orig);

  auto dijkstra = blink::make_dijkstra_object(g, sources);

  while (dijkstra()) {
    auto v = dijkstra.get_vertex();
    auto distance_map = dijkstra.get<boost::vertex_distance_t>();
    if (get(distance_map, v) >= 2) break;
  }
  report_progress(g, dijkstra.get<boost::vertex_distance_t>(), dijkstra.get<boost::vertex_color_t>());
}

int main()
{
  int n = 12;

  test_target_visitor(n);
  test_target_visitor_convenience(n);

  test_distance_visitor(n);
  test_distance_visitor_convenience(n);

  test_classic_boost(n);
  test_classic_blink(n);

  test_nearest_visitor(n);
  test_nearest_visitor_convenience(n);

  test_dijkstra_object(n);
  test_dijkstra_object2(n);
  test_dijkstra_object3(n);
  test_with_boost_heap(n);

  return 0;
}


text: #include <boost/mpl/aux_/preprocessed/msvc70/advance_forward.hpp>


text:
/*  $Id: stlsurf.cpp 745 2011-05-16 10:32:25Z anders.e.e.wallin $
 *
 *  Copyright 2010 Anders Wallin (anders.e.e.wallin "at" gmail.com)
 *
 *  This file is part of OpenCAMlib.
 *
 *  OpenCAMlib 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.
 *
 *  OpenCAMlib 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 OpenCAMlib.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <list>
#include <cassert>

#include <boost/foreach.hpp>

#include "point.h"
#include "triangle.h"
#include "stlsurf.h"

namespace ocl
{

void STLSurf::addTriangle(const Triangle &t) {

    // some sanity-checking:
    assert( (t.p[0]-t.p[1]).norm() > 0.0 );
    assert( (t.p[1]-t.p[2]).norm() > 0.0 );
    assert( (t.p[2]-t.p[0]).norm() > 0.0 );

    tris.push_back(t);
    bb.addTriangle(t);
    return;
}

void STLSurf::rotate(double xr, double yr, double zr) {
    //std::cout << " before " << t << "\n";
    bb.clear();
    BOOST_FOREACH(Triangle& t, tris) {
        //std::cout << " before " << t << "\n";
        t.rotate(xr,yr,zr);
        //std::cout << " after " << t << "\n";
        //char c;
        //std::cin >> c;
        bb.addTriangle(t);
    }
}

unsigned int STLSurf::size() const {
    return tris.size();
}

std::ostream &operator<<(std::ostream &stream, const STLSurf s) {
  stream << "STLSurf(N="<< s.tris.size() <<")";
  return stream;
}

} // end namespace
// end file stlsurf.cpp


text:
#include "../benchmarks_general.h"

#include <Fastor/Fastor.h>
#include <Eigen/Core>
#include <Eigen/Dense>

template<typename T, size_t M, size_t N>
void benchmark_lu_eigen() {
    using namespace Eigen;
    Matrix<T,M,N,RowMajor> a;
    std::iota(a.data(),a.data()+M*N,0);
    for (size_t i=0; i<M; ++i) a(i,i) = 100 + i;
    auto lu = a.lu();
    Eigen::Matrix<T,N,M,RowMajor> lum = lu.matrixLU();
    Eigen::Matrix<T,N,M,RowMajor> pm  = lu.permutationP();
    benchmarks_general::unused(lum);
    benchmarks_general::unused(pm);
}

template<typename T, size_t M, size_t N>
void benchmark_lu_fastor() {
    using namespace Fastor;
    Tensor<T,M,N> a;
    std::iota(a.data(),a.data()+M*N,0);
    for (size_t i=0; i<M; ++i) a(i,i) = 100 + i;
    Tensor<T,M,N> l, u;
    Tensor<size_t,M> p;
    lu<LUCompType::BlockLUPiv>(a, l, u, p);
    benchmarks_general::unused(l);
    benchmarks_general::unused(u);
    benchmarks_general::unused(p);
}

template<typename T, size_t M>
void benchmark_run() {

    using benchmarks_general::println;
    using benchmarks_general::rtimeit;

    println("Testing size (M, N)", M, M,'\n');

    double etime = rtimeit(static_cast<void (*)()>(&benchmark_lu_eigen<T,M,M>));
    double ftime = rtimeit(static_cast<void (*)()>(&benchmark_lu_fastor<T,M,M>));

    println("Elapsed time -> Eigen, Fastor\n", etime, ftime,'\n');
}

template<size_t step, size_t from, size_t to>
struct benchmark_generate {
    template<typename T>
    static inline void generate() {
        benchmark_run<T,from>();
        benchmark_generate<step,from+step,to>::template generate<T>();
    }
};
template<size_t step, size_t from>
struct benchmark_generate<step,from,from> {
    template<typename T>
    static inline void generate() {
        benchmark_run<T,from>();
    }
};

int main () {

#ifdef RUN_SINGLE
    benchmark_generate<2,2,32>::template generate<float>();
#else
    benchmark_generate<2,2,32>::template generate<double>();
#endif

    return 0;
}

max_stars_repo_name: mablanchard/Fastor

max_issues_repo_name: manodeep/Fastor

max_forks_repo_name: manodeep/Fastor


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)

// Copyright (c) 2007-2014 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2008-2014 Bruno Lalande, Paris, France.
// Copyright (c) 2009-2014 Mateusz Loskot, London, UK.
// Copyright (c) 2013-2014 Adam Wulkiewicz, Lodz, Poland.

// This file was modified by Oracle on 2013-2017.
// Modifications copyright (c) 2013-2017, Oracle and/or its affiliates.

// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle

// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.

// Use, modification and distribution is subject to 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)

#ifndef BOOST_GEOMETRY_ALGORITHMS_DISPATCH_DISJOINT_HPP
#define BOOST_GEOMETRY_ALGORITHMS_DISPATCH_DISJOINT_HPP

#include <cstddef>

#include <boost/geometry/core/tag.hpp>
#include <boost/geometry/core/tag_cast.hpp>
#include <boost/geometry/core/tags.hpp>
#include <boost/geometry/core/reverse_dispatch.hpp>

#include <boost/geometry/algorithms/not_implemented.hpp>

namespace boost { namespace geometry
{

#ifndef DOXYGEN_NO_DISPATCH
namespace dispatch
{

template
<
    typename Geometry1, typename Geometry2,
    std::size_t DimensionCount = dimension<Geometry1>::type::value,
    typename Tag1 = typename tag_cast
        <
            typename tag<Geometry1>::type,
            segment_tag, box_tag, linear_tag, areal_tag
        >::type,
    typename Tag2 = typename tag_cast
        <
            typename tag<Geometry2>::type,
            segment_tag, box_tag, linear_tag, areal_tag
        >::type,
    bool Reverse = reverse_dispatch<Geometry1, Geometry2>::type::value
>
struct disjoint
    : not_implemented<Geometry1, Geometry2>
{};

// If reversal is needed, perform it
template
<
    typename Geometry1, typename Geometry2,
    std::size_t DimensionCount,
    typename Tag1, typename Tag2
>
struct disjoint<Geometry1, Geometry2, DimensionCount, Tag1, Tag2, true>
{
    template <typename Strategy>
    static inline bool apply(Geometry1 const& g1, Geometry2 const& g2, Strategy const& strategy)
    {
        return disjoint
            <
                Geometry2, Geometry1,
                DimensionCount,
                Tag2, Tag1
            >::apply(g2, g1, strategy);
    }
};

} // namespace dispatch
#endif // DOXYGEN_NO_DISPATCH

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_ALGORITHMS_DISPATCH_DISJOINT_HPP


text:
#include "NetworkClient.h"

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

#include "Message.h"
#include "Logging.h"

////////////////////////////////////////////////////////////////////////////////
//
// NetworkClient
//
////////////////////////////////////////////////////////////////////////////////

NetworkClient::NetworkClient()
{
	boost::lock_guard<boost::mutex> lock(m_isConnectedMutex);
	m_isConnected = false;
}

////////////////////////////////////////////////////////////////////////////////

void NetworkClient::run()
{
	Logging::info("Network client thread is running.");

	while (true)
	{
		boost::unique_lock<boost::mutex> lock(m_waitForConnectionMutex);

		while (m_serverAddress == "")
			m_waitForConnectionCondition.wait(lock);

		try
		{
			// Set up the connection
			load();

			// Start waiting for the connection to establish
			startAccept();

			// Start the network service
			m_ioService->run();

			m_ioService.reset();
		}
		catch (std::exception &e)
		{
			Logging::error(e.what());

			stop(true);
		}

		m_serverAddress = "";
	}

	Logging::info("Network client thread finished.");
}

////////////////////////////////////////////////////////////////////////////////

void NetworkClient::stop(bool failed)
{
	// Unload the connection in the network client's thread

	// If there is an active connection, close it
	if (m_ioService)
		m_ioService->post(boost::bind(&NetworkClient::unload, this, failed));
	// Otherwise, just notify that a new connection can be established
	else
		onConnectionClosed();
}

////////////////////////////////////////////////////////////////////////////////

bool NetworkClient::isConnected()
{
	boost::lock_guard<boost::mutex> lock(m_isConnectedMutex);
	return m_isConnected;
}

////////////////////////////////////////////////////////////////////////////////

bool NetworkClient::acceptsConnection()
{
	return m_ioService != NULL;
}

////////////////////////////////////////////////////////////////////////////////

void NetworkClient::load()
{
	// Create a network service and a socket
	m_ioService = boost::shared_ptr<boost::asio::io_service>(
		new boost::asio::io_service);

	// Connect to the server
	boost::asio::ip::tcp::resolver resolver(*m_ioService);
	boost::asio::ip::tcp::resolver::query query(m_serverAddress, "8642");
	m_iterator = resolver.resolve(query);

	m_socket = boost::shared_ptr<boost::asio::ip::tcp::socket>(
		new boost::asio::ip::tcp::socket(*m_ioService));
}

////////////////////////////////////////////////////////////////////////////////

void NetworkClient::unload(bool failed)
{
	Logging::info("Closing the active connection.");

	// Stop the network service
	if (m_ioService)
		m_ioService->stop();

	boost::system::error_code errorCode;

	// Close the socket carefully
	if (m_socket)
		m_socket->shutdown(boost::asio::ip::tcp::socket::shutdown_both,
			errorCode);

	if (errorCode)
	{
		Logging::warning("The network client socket could not be closed:");
		Logging::warning((std::string)"\t" + errorCode.message());
	}

	if (m_socket)
		m_socket->close();

	m_socket.reset();
	m_ioService.reset();

	if (failed)
	{
		stop();
		onConnectionFailed();
	}

	onConnectionClosed();

	m_isConnectedMutex.lock();
	m_isConnected = false;
	m_isConnectedMutex.unlock();
}

////////////////////////////////////////////////////////////////////////////////

void NetworkClient::startAccept()
{
	// Wait for connection to establish and start accepting server messages
	m_socket->async_connect(*m_iterator,
		boost::bind(&NetworkClient::handleConnect, this,
			boost::asio::placeholders::error));
}

////////////////////////////////////////////////////////////////////////////////

void NetworkClient::handleConnect(const boost::system::error_code &error)
{
	if (error)
	{
		Logging::info("Connection to server refused.");

		stop();

		// If server is not started yet or error occurred, try to connect again
		onConnectionFailed();
		return;
	}

	// Wait for first incoming message and read its header
	boost::asio::async_read(
		*m_socket,
		boost::asio::buffer(&m_readBuffer, m_currentMessage.headerLength()),
		boost::bind(&NetworkClient::handleReadHeader, this,
			boost::asio::placeholders::error));

	m_isConnectedMutex.lock();
	m_isConnected = true;
	m_isConnectedMutex.unlock();

	// Inform connected objects about the new connection
	onConnectionEstablished();
}

////////////////////////////////////////////////////////////////////////////////

void NetworkClient::handleReadHeader(const boost::system::error_code &error)
{
	if (error)
	{
		Logging::warning((std::string)"Error occurred while reading message "
			+ "header on client.");

		onConnectionClosed();
		return;
	}

	// Copy message header into currently handled message
	m_currentMessage.copyHeaderFrom(m_readBuffer);

	// Wait for rest of the message and read its content
	boost::asio::async_read(
		*m_socket,
		boost::asio::buffer(&m_readBuffer, m_currentMessage.contentLength()),
		boost::bind(&NetworkClient::handleReadBody, this,
			boost::asio::placeholders::error));
}

////////////////////////////////////////////////////////////////////////////////

void NetworkClient::handleReadBody(const boost::system::error_code &error)
{
	if (error)
	{
		Logging::warning((std::string)"Error occurred while reading message "
			+ "body on client.");

		onConnectionClosed();
		return;
	}

	// Read the message's content
	m_currentMessage.copyContentFrom(m_readBuffer);

	onMessageReceived(m_currentMessage);

	// Wait for next incoming message and read its header
	boost::asio::async_read(
		*m_socket,
		boost::asio::buffer(&m_readBuffer, m_currentMessage.headerLength()),
		boost::bind(&NetworkClient::handleReadHeader, this,
			boost::asio::placeholders::error));
}

////////////////////////////////////////////////////////////////////////////////

void NetworkClient::send(MessageData messageData)
{
	// Wait until the setup is finished
	while (! m_isConnected)
		boost::this_thread::sleep(boost::posix_time::seconds(0));

	// Deliver the message in the network client's thread
	m_ioService->post(boost::bind(&NetworkClient::deliver, this, messageData));
}

////////////////////////////////////////////////////////////////////////////////

void NetworkClient::connectToServer(std::string serverAddress)
{
	m_waitForConnectionMutex.lock();
	m_serverAddress = serverAddress;
	m_waitForConnectionMutex.unlock();

	m_waitForConnectionCondition.notify_one();
}

////////////////////////////////////////////////////////////////////////////////

void NetworkClient::disconnectFromServer()
{
	stop();
}

////////////////////////////////////////////////////////////////////////////////

void NetworkClient::reconnectToServer()
{
	startAccept();
}

////////////////////////////////////////////////////////////////////////////////

void NetworkClient::deliver(MessageData messageData)
{
	boost::lock_guard<boost::mutex> writeMessageQueueLock(m_writeMessageQueueMutex);

	bool isWriteInProgress = !m_writeMessageQueue.empty();

	// Insert requested message into sending queue
	m_writeMessageQueue.push_back(messageData);

	// Wait for the queue to be empty before sending
	boost::lock_guard<boost::mutex> isConnectedLock(m_isConnectedMutex);

	if (!m_isConnected || isWriteInProgress)
		return;

	int dataLength = m_currentMessage.headerLength()
		+ m_writeMessageQueue.front().contentLength();

	// Write message via network eventually
	boost::asio::async_write(
		*m_socket,
		boost::asio::buffer(&m_writeMessageQueue.front(), dataLength),
		boost::bind(&NetworkClient::handleWrite, this,
			boost::asio::placeholders::error));
}

////////////////////////////////////////////////////////////////////////////////

void NetworkClient::handleWrite(const boost::system::error_code &error)
{
	if (error)
	{
		Logging::warning((std::string)"Error occurred while writing message "
			+ "for server.");

		onConnectionClosed();
		return;
	}

	boost::lock_guard<boost::mutex> lock(m_writeMessageQueueMutex);

	// If last message has been sent, remove it from the queue's beginning
	m_writeMessageQueue.pop_front();

	if (m_writeMessageQueue.empty())
		return;

	int dataLength = m_currentMessage.headerLength()
		+ m_writeMessageQueue.front().contentLength();

	// Send next messages if there are remaining ones in the queue
	boost::asio::async_write(
		*m_socket,
		boost::asio::buffer(&m_writeMessageQueue.front(), dataLength),
		boost::bind(&NetworkClient::handleWrite, this,
			boost::asio::placeholders::error));
}

max_issues_repo_name: ad-si/hci-assignments

max_forks_repo_name: ad-si/hci-assignments


text:
// Copyright (c) 2012, Thomas Goyne <plorkyeran@aegisub.org>
//
// Permission to use, copy, modify, and distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
// Aegisub Project http://www.aegisub.org/

/// @file font_file_lister_fontconfig.cpp
/// @brief Font Config-based font collector
/// @ingroup font_collector
///

#include "config.h"

#include "font_file_lister_fontconfig.h"

#include <fontconfig/fontconfig.h>

#include <libaegisub/log.h>
#include <libaegisub/util.h>

#ifdef __APPLE__
#include <libaegisub/util_osx.h>
#endif

#include <boost/algorithm/string/case_conv.hpp>
#include <boost/filesystem/path.hpp>

#include <wx/intl.h>

namespace {
FcConfig *init_fontconfig() {
#ifdef __APPLE__
	FcConfig *config = FcConfigCreate();
	std::string conf_path = agi::util::GetBundleResourcesDirectory() + "/etc/fonts/fonts.conf";
	if (FcConfigParseAndLoad(config, (unsigned char *)conf_path.c_str(), FcTrue))
		return config;

	LOG_E("font_collector/fontconfig") << "Loading fontconfig configuration file failed";
	FcConfigDestroy(config);
#endif
	return FcInitLoadConfig();
}

void find_font(FcFontSet *src, FcFontSet *dst, std::string const& family) {
	if (!src) return;

	for (FcPattern *pat : boost::make_iterator_range(&src->fonts[0], &src->fonts[src->nfont])) {
		int val;
		if (FcPatternGetBool(pat, FC_OUTLINE, 0, &val) != FcResultMatch || val != FcTrue) continue;

		FcChar8 *str;
		for (int i = 0; FcPatternGetString(pat, FC_FULLNAME, i, &str) == FcResultMatch; ++i) {
			if (boost::to_lower_copy(std::string((char *)str)) == family) {
				FcFontSetAdd(dst, FcPatternDuplicate(pat));
				goto skip_family;
			}
		}

		for (int i = 0; FcPatternGetString(pat, FC_FAMILY, i, &str) == FcResultMatch; ++i) {
			if (boost::to_lower_copy(std::string((char *)str)) == family) {
				FcFontSetAdd(dst, FcPatternDuplicate(pat));
				break;
			}
		}

		skip_family:;
	}
}

}

FontConfigFontFileLister::FontConfigFontFileLister(FontCollectorStatusCallback cb)
: config(init_fontconfig(), FcConfigDestroy)
{
	cb(_("Updating font cache\n"), 0);
	FcConfigBuildFonts(config);
}

FontFileLister::CollectionResult FontConfigFontFileLister::GetFontPaths(std::string const& facename, int bold, bool italic, std::set<wxUniChar> const& characters) {
	CollectionResult ret;

	std::string family(facename);
	if (family[0] == '@')
		family.erase(0, 1);
	boost::to_lower(family);

	int weight = bold == 0 ? 80 :
	             bold == 1 ? 200 :
	                         bold;
	int slant  = italic ? 110 : 0;

	// Create a fontconfig pattern to match the desired weight/slant
	agi::scoped_holder<FcPattern*> pat(FcPatternCreate(), FcPatternDestroy);
	if (!pat) return ret;

	FcPatternAddBool(pat, FC_OUTLINE, true);
	FcPatternAddInteger(pat, FC_SLANT, slant);
	FcPatternAddInteger(pat, FC_WEIGHT, weight);

	FcDefaultSubstitute(pat);
	if (!FcConfigSubstitute(config, pat, FcMatchPattern)) return ret;

	// Create a font set with only correctly named fonts
	// This is needed because the patterns returned by font matching only
	// include the first family and fullname, so we can't always verify that
	// we got the actual font we were asking for after the fact
	agi::scoped_holder<FcFontSet*> fset(FcFontSetCreate(), FcFontSetDestroy);
	find_font(FcConfigGetFonts(config, FcSetApplication), fset, family);
	find_font(FcConfigGetFonts(config, FcSetSystem), fset, family);

	// Get the best match from fontconfig
	FcResult result;
	FcFontSet *sets[] = { (FcFontSet*)fset };
	agi::scoped_holder<FcPattern*> match(FcFontSetMatch(config, sets, 1, pat, &result), FcPatternDestroy);
	if (!match)
		return ret;

	FcChar8 *file;
	if(FcPatternGetString(match, FC_FILE, 0, &file) != FcResultMatch)
		return ret;

	FcCharSet *charset;
	if (FcPatternGetCharSet(match, FC_CHARSET, 0, &charset) == FcResultMatch) {
		for (wxUniChar chr : characters) {
			if (!FcCharSetHasChar(charset, chr))
				ret.missing += chr;
		}
	}

	ret.paths.emplace_back((const char *)file);
	return ret;
}

max_stars_repo_name: rcombs/Aegisub

max_issues_repo_name: rcombs/Aegisub

max_forks_repo_name: rcombs/Aegisub


text: #include <boost/units/physical_dimensions/heat_capacity.hpp>


text:
#include <iostream>
#include <string>
#include <cmath>
#include "base_types.hpp"
#include "instruments.hpp"
#ifdef HAS_NEXUS
#  include "nexus.hpp"
#endif // HAS_NEXUS
#include "utils.hpp"
#include "ui_calls.hpp"

#ifdef WIN32
#  ifdef AMIRA64
#include <boost/math/special_functions/asinh.hpp>
//#    include <boost/math/tr1.hpp>
//using boost::math::tr1::asinh;
#  endif // AVIZO/AMIRA
#endif // WINDOWS
#include<boost/lexical_cast.hpp>
bool CCPi::Diamond::setup_experimental_geometry(const std::string path,
						const std::string file,
						const real rotation_centre,
						const int pixels_per_voxel,
						const bool phantom)
{
  if (phantom)
    return create_phantom();
  else {
    name = file;
    return read_data_size(path, rotation_centre, pixels_per_voxel);
  }
}

bool CCPi::Diamond::setup_experimental_geometry(const numpy_3d &pix_array,
						const numpy_1d &angle_array,
						const real rotation_centre,
						const int pixels_per_voxel)
{
  bool ok = true;
  int nangles = (int)angle_array.shape()[0];
  if (nangles < 1) {
    report_error("Bad angle array");
    ok = false;
  } else {
    const pixel_data::size_type *s = pix_array.shape();
    int na = (int)s[0];
    int nv_pixels = (int)s[1];
    int nh_pixels = (int)s[2];
    if (na != nangles) {
      report_error("Number of projections doesn't match angle array");
	  report_error(boost::lexical_cast<std::string>(na));
	  report_error(boost::lexical_cast<std::string>(nangles));
      ok = false;
    } else if (nh_pixels < 1 or nv_pixels < 1) {
      report_error("Bad array index for pixels");
      ok = false;
    } else {
      // dummy
      real hsize = 1.0;
      real vsize = 1.0;
      // copied from read_data_size
      nv_pixels = calc_v_alignment(nv_pixels, pixels_per_voxel, false);
      real shift = 0.0;
      if (rotation_centre > 0.0) {
	// shift h_pixels
	// if 4 pixels and centre = 2.0 nothing happens
	real pixel_shift = rotation_centre - real(nh_pixels) / 2.0;
	shift = hsize * pixel_shift;
      }
      // store data in class
      real_1d &h_pixels = set_h_pixels(nh_pixels);
      h_pixels[0] = - ((nh_pixels - 1) * hsize) / real(2.0) - shift;
      for (int i = 1; i < nh_pixels; i++)
	h_pixels[i] = h_pixels[0] + real(i) * hsize;
      real_1d &v_pixels = set_v_pixels(nv_pixels);
      v_pixels[0] = - ((nv_pixels - 1) * vsize) / real(2.0);
      for (int i = 1; i < nv_pixels; i++)
	v_pixels[i] = v_pixels[0] + real(i) * vsize;
      real_1d &angles = set_phi(nangles);
      for (int i = 0; i < nangles; i++)
	angles[i] = M_PI * (angle_array[i] / 180.0);
    }
  }
  return ok;
}

bool CCPi::Diamond::setup_experimental_geometry(const numpy_3d &pix_array,
						const numpy_1d &angle_array,
						const numpy_1d &h_offsets,
						const numpy_1d &v_offsets,
						const int pixels_per_voxel,
						const real source_x,
						const real detector_x,
						const real pixel_h_size,
						const real pixel_v_size,
						const real m_radius,
						const bool has_offsets)
{
  report_error("Diamond Avizo interface not implemented");
  return false;
}

bool CCPi::Diamond::create_phantom()
{
  //set_source(-250.0, 0.0, 0.0);
  //set_detector(737.0);
  int c;
  for (c = 0; c < 1000; c++) {
    //real p = -100.0 + c * 0.250;
    real p = -99.8046875 + real(c) * 0.390625;
    if (p >= 100.0 + 0.001)
      break;
  }
  real_1d &h_pixels = set_h_pixels(c);
  for (int i = 0; i < c; i++) {
    //real p = -100.0 + i * 0.250;
    h_pixels[i] = -99.8046875 + real(i) * 0.390625;
  }
  for (c = 0; c < 1000; c++) {
    //real p = -100.0 + real(c) * 0.250;
    real p = -99.8046875 + real(c) * 0.390625;
    if (p >= 100.0 + 0.001)
      break;
  }
  real_1d &v_pixels = set_v_pixels(c);
  for (int i = 0; i < c; i++) {
    //real p = -100.0 + real(i) * 0.250;
    v_pixels[i] = -99.8046875 + real(i) * 0.390625;
  }
  // 501 values from 0 to 2pi
  //geom.angles = linspace(0,2*pi,501);
  // lose the 2pi which is a duplicate of 0
  //geom.angles = geom.angles(1:500);
  const int nangles = 250;
  real_1d &pangles = set_phi(nangles);
  real step = M_PI / real(nangles);
  for (int i = 0; i < nangles; i++)
    pangles[i] = real(i) * step;
  return true;
}

bool CCPi::Diamond::read_data_size(const std::string path,
				   const real rotation_centre,
				   const int pixels_per_voxel)
{
  bool ok = false;
  std::string fullname;
  combine_path_and_name(path, name,fullname);
  pixel_data pixels(boost::extents[1][1][1]);
  int nh_pixels = 0;
  int nv_pixels = 0;
  std::vector<real> angles;
  int nangles = 0;
  real hsize = 0.0;
  real vsize = 0.0;
  pixel_2d i_dark(boost::extents[1][1]);
  pixel_2d f_dark(boost::extents[1][1]);
  pixel_2d i_bright(boost::extents[1][1]);
  pixel_2d f_bright(boost::extents[1][1]);
#ifdef HAS_NEXUS
  ok = read_NeXus(pixels, i_dark, f_dark, i_bright, f_bright, nh_pixels,
		  nv_pixels, angles, nangles, hsize, vsize, fullname,
		  false, false, 0, 10000, 0);
#endif // HAS_NEXUS
  if (ok) {
    nv_pixels = calc_v_alignment(nv_pixels, pixels_per_voxel, false);
    real shift = 0.0;
    if (rotation_centre > 0.0) {
      // shift h_pixels
      // if 4 pixels and centre = 2.0 nothing happens
      real pixel_shift = rotation_centre - real(nh_pixels) / 2.0;
      shift = hsize * pixel_shift;
    }
    // store data in class
    real_1d &h_pixels = set_h_pixels(nh_pixels);
    h_pixels[0] = - ((nh_pixels - 1) * hsize) / real(2.0) - shift;
    for (int i = 1; i < nh_pixels; i++)
      h_pixels[i] = h_pixels[0] + real(i) * hsize;
    real_1d &v_pixels = set_v_pixels(nv_pixels);
    v_pixels[0] = - ((nv_pixels - 1) * vsize) / real(2.0);
    for (int i = 1; i < nv_pixels; i++)
      v_pixels[i] = v_pixels[0] + real(i) * vsize;
    real_1d &phi = set_phi(nangles);
    for (int i = 0; i < nangles; i++)
      phi[i] = angles[i];
  }
  return ok;
}

bool CCPi::Diamond::read_scans(const std::string path, const int offset,
			       const int block_size, const bool first,
			       const bool phantom)
{
  if (phantom)
    return build_phantom(offset, block_size);
  else
    return read_data(path, offset, block_size, first);
}

bool CCPi::Diamond::build_phantom(const int offset, const int block_size)
{
  // build small voxel set to project to produce initial pixels
  int nx = 512;
  int ny = 512;
  int nz = 512;

  const real_1d &h_pixels = get_h_pixels();
  const real_1d &v_pixels = get_all_v_pixels();
  int nh = get_num_h_pixels();
  int nv = total_num_v_pixels();
  real hmin = std::abs(h_pixels[0]);
  real hmax = h_pixels[nh - 1] + (h_pixels[1] - h_pixels[0]);
  real vmin = std::abs(v_pixels[0]);
  real vmax = v_pixels[nv - 1] + (v_pixels[1] - v_pixels[0]);
  real hlim = std::max(hmax, hmin);
  real vlim = std::max(vmax, vmin);
  real lim = std::max(hlim, vlim);
  real voxel_size[3];
  voxel_size[0] = real(2.0) * lim / real(nx);
  voxel_size[1] = voxel_size[0];
  voxel_size[2] = voxel_size[0];
  real image_vol[3];
  image_vol[0] = voxel_size[0] * nx;
  image_vol[1] = voxel_size[1] * ny;
  image_vol[2] = voxel_size[2] * nz;
  real image_offset[3];
  image_offset[0] = -image_vol[0] / 2;
  image_offset[1] = -image_vol[1] / 2;
  image_offset[2] = -image_vol[2] / 2;

  // set up phantom volume
  voxel_data x(boost::extents[nx][ny][nz], boost::c_storage_order());
  //sl_int n_vox = nx * ny * nz;
  for (sl_int k = 0; k < nx; k++)
    for (sl_int j = 0; j < ny; j++)
      for (sl_int i = 0; i < nz; i++)
	x[k][j][i] = 0.0;

  // add cubes - column major
  for (int i = 108-1; i < 189; i++) {
    for (int j = 108-1; j < 189; j++) {
      for (int k = 58-1; k < 139; k++) {
        x[i][j][k] = 1;
      }
    }
  }
  for (int i = 190-1; i < 271; i++) {
    for (int j = 190-1; j < 271; j++) {
      for (int k = 140-1; k < 221; k++) {
        x[i][j][k] = 1;
      }
    }
  }
  for (int i = 272-1; i < 353; i++) {
    for (int j = 272-1; j < 353; j++) {
      for (int k = 222-1; k < 303; k++) {
        x[i][j][k] = 1;
      }
    }
  }

  set_v_offset(offset);
  pixel_data &pixels = create_pixel_data();
  // perform projection step
  safe_forward_project(pixels, x, image_offset, voxel_size, nx, ny, nz);
  //delete [] x;
  return true;
}

bool CCPi::Diamond::read_data(const std::string path, const int offset,
			      const int block_size, const bool first)
{
  bool ok = false;
  std::string fullname;
  combine_path_and_name(path, name,fullname);
#ifdef HAS_NEXUS
  real hsize = 0.0;
  real vsize = 0.0;
  int nh_pixels = 0;
  int nv_pixels = 0;
#endif // HAS_NEXUS
  std::vector<real> angles(2 * get_num_angles());
  int nangles = 0;
  int nv = get_num_v_pixels();
  int nh = get_num_h_pixels();
  if (first)
    (void) create_pixel_data();
  pixel_data &pixels = get_pixel_data();
  pixel_2d i_dark(boost::extents[nh][nv]);
  pixel_2d f_dark(boost::extents[nh][nv]);
  pixel_2d i_bright(boost::extents[nh][nv]);
  pixel_2d f_bright(boost::extents[nh][nv]);
  for (sl_int i = 0; i < nh; i++) {
    for (sl_int j = 0; j < nv; j++) {
      i_dark[i][j] = 0.0;
      f_dark[i][j] = 0.0;
      i_bright[i][j] = 0.0;
      f_bright[i][j] = 0.0;
    }
  }
  int v_offset = get_data_v_offset();
  int v_size = get_data_v_size();
  int v_end = v_offset + v_size;
#ifdef HAS_NEXUS
  int bsize = block_size;
  // need to be careful that we only read bits for the data set range
  if (block_size > v_size)
    bsize = v_size;
  else if (offset + bsize > v_end)
    bsize = v_end - offset;
  else if (offset == 0)
    bsize = block_size - v_offset;
  if (bsize > 0)
    ok = read_NeXus(pixels, i_dark, f_dark, i_bright, f_bright, nh_pixels,
		    nv_pixels, angles, nangles, hsize, vsize, fullname,
		    false, true, offset, bsize, v_offset);
  else // Its an empty data range
    ok = true;
#endif // HAS_NEXUS
  nangles = get_num_angles();
  // store data in class - now done by read_data_sizes
  set_v_offset(offset);
  if (ok) {
    const real_1d &angles = get_phi();
    // linear interpolate bright/dark frames. Todo - something else?
    // Todo, also use initial final bright/dark angles? rather than assuming
    // initial/final sample angles?
    pixel_2d dark(boost::extents[nh][nv]);
    pixel_2d bright(boost::extents[nh][nv]);
    for (int i = 0; i < nangles; i++) {
      // Based on fbp code, interpolate bright/dark
      real w = (angles[i] - angles[0]) / (angles[nangles - 1] - angles[0]);
      for (sl_int k = 0; k < nh; k++)
	for (sl_int j = v_offset; j < v_end; j++)
	  dark[k][j] = i_dark[k][j] * (real(1.0) - w) + f_dark[k][j] * w;
      for (sl_int k = 0; k < nh; k++)
	for (sl_int j = v_offset; j < v_end; j++)
	  bright[k][j] = i_bright[k][j] * (real(1.0) - w) + f_bright[k][j] * w;
      // subtract dark from data/bright
      // and clamp min data/bright value to 0.1
      for (sl_int k = 0; k < nh; k++) {
	for (sl_int j = v_offset; j < v_end; j++) {
	  bright[k][j] -= dark[k][j];
	  if (bright[k][j] < real(0.1))
	    bright[k][j] = 0.1;
	}
      }
      for (sl_int k = 0; k < nh; k++) {
	for (sl_int j = v_offset; j < v_end; j++) {
	  pixels[i][k][j] -= dark[k][j];
	  if (pixels[i][k][j] < real(0.1))
	    pixels[i][k][j] = 0.1;
	}
      }
      // scale each data pixel by bright pixel
      for (sl_int k = 0; k < nh; k++)
	for (sl_int j = v_offset; j < v_end; j++)
	  pixels[i][k][j] /= bright[k][j];
      // clamp to 1.0
      for (sl_int k = 0; k < nh; k++) {
	for (sl_int j = v_offset; j < v_end; j++) {
	  if (pixels[i][k][j] > real(1.0))
	    pixels[i][k][j] = 1.0;
	}
      }
    }
    // take -ve log, due to exponential extinction in sample.
    for (int i = 0; i < nangles; i++) {
      for (sl_int k = 0; k < nh; k++) {
	// initialise aligned bits that don't contain data
	for (sl_int j = 0; j < v_offset; j++) {
	  pixels[i][k][j] = 0.0;
	}
	for (sl_int j = v_offset; j < v_end; j++)
	  pixels[i][k][j] = - std::log(pixels[i][k][j]);
	for (sl_int j = v_end; j < nv; j++) {
	  pixels[i][k][j] = 0.0;
	}
      }
    }
    //find_centre(get_num_v_pixels() / 2 + 1);
    if (use_high_peaks)
      high_peaks_before(hp_jump, hp_num_pix);
    if (use_ring_artefacts)
      ring_artefact_removal(ra_algorithm, aml_param_n, aml_param_r,
			    ra_num_series);
    //if (use_intensity_norm) - port fbp intensity_norm routine
    //normalise_intensity();
  }
  return ok;
}

bool CCPi::Diamond::read_scans(const numpy_3d &pixel_array,
			       const int offset, const int block_size, bool is_pixel_in_log)
{
  // bits from read_data
  int nv = get_num_v_pixels();
  int nh = get_num_h_pixels();
  int nangles = get_num_angles();
  int v_offset = get_data_v_offset();
  int v_size = get_data_v_size();
  int v_end = v_offset + v_size;
  /*
  int bsize = block_size;
  if (block_size > v_size)
    bsize = v_size;
  else if (offset + bsize > v_end)
    bsize = v_end - offset;
  else if (offset == 0)
    bsize = block_size - v_offset;
  */
  set_v_offset(offset);
  // Copy pixels
  pixel_data &pixels = create_pixel_data();

  if (is_pixel_in_log) {
	  for (int i = 0; i < nangles; i++) {
		  for (sl_int j = 0; j < nh; j++) {
			  // initialise aligned bits that don't contain data
			  for (sl_int k = 0; k < v_offset; k++) {
				  pixels[i][j][k] = 0.0;
			  }
			  for (sl_int k = v_offset; k < v_end; k++) {
				  pixels[i][j][k] = pixel_array[i][k - v_offset][j];
			  }
			  for (sl_int k = v_end; k < nv; k++) {
				  pixels[i][j][k] = 0.0;
			  }
		  }
	  }
  }
  else
  {
	  for (int i = 0; i < nangles; i++) {
		  for (sl_int j = 0; j < nh; j++) {
			  // initialise aligned bits that don't contain data
			  for (sl_int k = 0; k < v_offset; k++) {
				  pixels[i][j][k] = 0.0;
			  }
			  for (sl_int k = v_offset; k < v_end; k++) {
				  pixels[i][j][k] = -std::log(pixel_array[i][k - v_offset][j]);
			  }
			  for (sl_int k = v_end; k < nv; k++) {
				  pixels[i][j][k] = 0.0;
			  }
		  }
	  }
  }
  return true;
}

bool CCPi::Diamond::finish_voxel_geometry(real voxel_origin[3],
					  real voxel_size[3], const int nx,
					  const int ny, const int nz) const
{
  /*
  const real_1d &h_pixels = get_h_pixels();
  const real_1d &v_pixels = get_all_v_pixels();
  int nh = get_num_h_pixels();
  int nv = total_num_v_pixels();
  real hrange = std::abs(h_pixels[nh - 1] - h_pixels[0]);
  real hsize = hrange / (nh - 1);
  real vrange = std::abs(v_pixels[nv - 1] - v_pixels[0]);
  real vsize = vrange / (nv - 1);
  int hs = std::min(nx, ny);
  hsize *= (real(nh) / real(hs));
  vsize *= (real(nv) / nz);
  */
  voxel_size[0] = h_vox_size;
  voxel_size[1] = h_vox_size;
  voxel_size[2] = v_vox_size;
  voxel_origin[0] = -voxel_size[0] * real(nx) / real(2.0); // + offset[0];
  voxel_origin[1] = -voxel_size[1] * real(ny) / real(2.0); // + offset[1];
  voxel_origin[2] = -voxel_size[2] * real(nz) / real(2.0); // + offset[2];
  return true;
}

void CCPi::Diamond::get_xy_size(int &nx, int &ny, const int pixels_per_voxel)
{
  const real_1d &h_pixels = get_h_pixels();
  int nh = get_num_h_pixels();
  real hrange = h_pixels[1] - h_pixels[0];
  real hmax = std::max(std::abs(h_pixels[0]), std::abs(h_pixels[nh - 1]));
  int n = int(std::ceil((2.0 * hmax) / hrange));
  nx = n / pixels_per_voxel;
  if (n % pixels_per_voxel != 0)
    nx++;
  h_vox_size = hrange * real(pixels_per_voxel);
  // check that we've covered a big enough region
  real xmin = -h_vox_size * real(nx) / real(2.0);
  real xmax =  h_vox_size * real(nx) / real(2.0);
  while (xmin >= h_pixels[0] or xmax <= h_pixels[nh - 1]) {
    nx++;
    xmin = -h_vox_size * real(nx) / real(2.0);
    xmax =  h_vox_size * real(nx) / real(2.0);
  }
  ny = nx;
  const real_1d &v_pixels = get_all_v_pixels();
  v_vox_size = (v_pixels[1] - v_pixels[0]) * real(pixels_per_voxel);
}

void CCPi::Diamond::apply_beam_hardening()
{
  // Todo - does this belong in the base class?
  pixel_data &pixels = get_pixel_data();
  for (sl_int i = 0; i < get_num_angles(); i++)
    for (sl_int k = 0; k < get_num_h_pixels(); k++)
      for (sl_int j = 0; j < get_num_v_pixels(); j++)
	pixels[i][k][j] = pixels[i][k][j] * pixels[i][k][j];
}

void CCPi::Diamond::high_peaks_before(const real jump, const int num_pix)
{
  // ported from high_peaks_before routine in Manchester/Diamond FBP code
  sl_int nh = get_num_h_pixels();
  sl_int nv = get_num_v_pixels();
  sl_int nangles = get_num_angles();
  if (jump < 0.0) {
    report_error("High peaks - negative jump");
    return;
  }
  if (num_pix < 1 or num_pix >= nangles) {
    report_error("High peaks - wrong number of neighbours");
    return;
  }
  pixel_data &pixels = get_pixel_data();
  // correct each slice
  pixel_2d temp1(boost::extents[nangles - 1][nh]);
  //pixel_2d temp2(boost::extents[nangles - 1][nh]);
  // Todo - better loop structure - might require larger temp space.
  for (int v = 0; v < nv; v++) {
    // iterate num_pix times
    for (int k = 0; k < num_pix; k++) {
      // ToptoBottom
      //ippsSub
      for (int a = 0; a < nangles - 1; a++) {
	for (int h = 0; h < nh; h++)
	  temp1[a][h] = pixels[a][h][v] - pixels[a + 1][h][v];
      }
      /*
      // ippsThreshold_LTValGTVal
      for (int a = 0; a < nangles - 1; a++) {
	for (int h = 0; h < nh; h++) {
	  if (temp1[a][h] < -jump)
	    temp2[a][h] = 1.0;
	  else if (temp2[a][h] > -jump)
	    temp2[a][h] = 0.0;
	  else
	    temp2[a][h] = temp1[a][h];
	}
      }
      */
      // ippsTheshold_LT
      for (int a = 0; a < nangles - 1; a++) {
	for (int h = 0; h < nh; h++) {
	  if (temp1[a][h] < -jump)
	    temp1[a][h] = -jump;
	}
      }
      /*
      // ippsSum - could probably do this with LTValGTVal
      pixel_type sum = 0.0;
      for (int a = 0; a < nangles - 1; a++) {
	for (int h = 0; h < nh; h++) {
	  sum += temp2[a][h];
	}
      }
      */
      // ippsAdd
      for (int a = 0; a < nangles - 1; a++) {
	for (int h = 0; h < nh; h++)
	  pixels[a][h][v] = pixels[a + 1][h][v] + temp1[a][h];
      }
      //BottomtoTop
      //ippsSub
      for (int a = 0; a < nangles - 1; a++) {
	for (int h = 0; h < nh; h++)
	  temp1[a][h] = pixels[a + 1][h][v] - pixels[a][h][v];
      }
      /*
      // ippsThreshold_LTValGTVal
      for (int a = 0; a < nangles - 1; a++) {
	for (int h = 0; h < nh; h++) {
	  if (temp1[a][h] < -jump)
	    temp2[a][h] = 1.0;
	  else if (temp2[a][h] > -jump)
	    temp2[a][h] = 0.0;
	  else
	    temp2[a][h] = temp1[a][h];
	}
      }
      */
      // ippsTheshold_LT
      for (int a = 0; a < nangles - 1; a++) {
	for (int h = 0; h < nh; h++) {
	  if (temp1[a][h] < -jump)
	    temp1[a][h] = -jump;
	}
      }
      /*
      // ippsSum - could probably do this with LTValGTVal
      pixel_type sum = 0.0;
      for (int a = 0; a < nangles - 1; a++) {
	for (int h = 0; h < nh; h++) {
	  sum += temp2[a][h];
	}
      }
      */
      // ippsAdd
      for (int a = nangles - 2; a >= 0; a--) {
	for (int h = 0; h < nh; h++)
	  pixels[a + 1][h][v] = pixels[a][h][v] + temp1[a][h];
      }
    }
  }
}

void CCPi::remove_column_ring_artefacts(pixel_data &pixels,
					const sl_int nangles, const sl_int nh,
					const sl_int nv)
{
  //sl_int nh = get_num_h_pixels(); // nxi
  //sl_int nv = get_num_v_pixels();
  //sl_int nangles = get_num_angles(); // ny
  //pixel_data &pixels = get_pixel_data();
  const int crop_left = 0;
  const int crop_right = 0;
  const int nx = nh - (crop_left + crop_right);
  real_1d vec_res(nx);
  real_1d vec64(nx);
  pixel_1d vec32(nx);
  // ippsZero
  for (int v = 0; v < nv; v++) {
    for (int h = 0; h < nx; h++)
      vec_res[h] = real(0.0);
    // Todo - don't need vec64 really
    for (int a = 0; a < nangles; a++) {
      // ippsConvert
      for (int h = 0; h < nx; h++)
	vec64[h] = real(pixels[a][h + crop_left][v]);
      // ippsAdd
      for (int h = 0; h < nx; h++)
	vec_res[h] += vec64[h];
    }
    // ippsDivC
    for (int h = 0; h < nx; h++)
      vec_res[h] /= real(nangles);
    // ippsConvert
    for (int h = 0; h < nx; h++)
      vec32[h] = pixel_type(vec_res[h]);
    // ippsSub
    for (int a = 0; a < nangles; a++) {
      for (int h = 0; h < nx; h++)
	pixels[a][h + crop_left][v] -= vec32[h];
    }
  }
}

void CCPi::remove_aml_ring_artefacts(pixel_data &pixels, const sl_int nangles,
				     const sl_int nh, const sl_int nv,
				     const real param_n, const real param_r,
				     const int num_series)
{
  //sl_int nh = get_num_h_pixels(); // nxi
  //sl_int nv = get_num_v_pixels();
  //sl_int nangles = get_num_angles(); // ny
  if (param_n < -1e-10) {
    report_error("Ring artefacts - wrong param N");
    return;
  }
  if (param_r < 1e-8) {
    report_error("Ring artefacts - wrong param R");
    return;
  }
  if (num_series < 1 or num_series > 100) {
    report_error("High peaks - num series out of range");
    return;
  }
  //pixel_data &pixels = get_pixel_data();
  const int crop_left = 0;
  const int crop_right = 0;
  const int nx = nh - (crop_left + crop_right);
  // based on Applied Mathematics Letters v23 p1489
  // Init
  real_3d mata(boost::extents[num_series][nx][nx]);
  real_2d vecRS(boost::extents[2 * num_series][nangles]);
  {
    // Todo - can combine a lot of this
    for(int s = 1; s < num_series; s++) {
      // ippsVectorSlope
      real slope = real(s) * M_PI / real(nangles);
      for (int i = 0; i < nangles; i++)
	vecRS[0][i] = real(i) * slope; // + 0.0
      // ippsSinCos
      for (int i = 0; i < nangles; i++) {
	vecRS[2 * s - 1][i] = std::sin(vecRS[0][i]);
	vecRS[2 * s - 0][i] = std::cos(vecRS[0][i]);
      }
      // ippsMulC
      real sqrt2 = std::sqrt(real(2.0));
      for (int i = 0; i < nangles; i++)
	vecRS[2 * s - 1][i] *= sqrt2;
      for (int i = 0; i < nangles; i++)
	vecRS[2 * s - 0][i] *= sqrt2;
    }
    // ippsSet
    for (int i = 0; i < nangles; i++)
      vecRS[0][i] = 1.0;
    real_1d vec_exp(2 * nx + 2);
    for (int s = 1; s <= num_series; s++) {
      real alpha = (param_n + param_r) * real(s * s);
      real mdiv = std::sqrt(alpha * (alpha + real(4.0)));
      real vec1 = std::sqrt(alpha) / real(2.0);
      //ippsAsinh
      real vec2 = asinh(vec1); // ln(x + sqrt(x * x + 1))
      real tau = 2.0 * vec2;
      // ippsVectorSlope
      for (int i = 0; i < 2 * nx + 2; i++)
	vec_exp[i] = -tau * real(i); // + 0.0
      // ippsExp
      for (int i = 0; i < 2 * nx + 2; i++)
	vec_exp[i] = std::exp(vec_exp[i]);
      int ii;
      int jj;
      for (int i = 0; i < nx; i++) {
	for (int j = 0; j < nx; j++) {
	  if (j > i) {
	    ii = i;
	    jj = j;
	  } else {
	    ii = j;
	    jj = i;
	  }
	  ii++;
	  jj++;
	  mata[s - 1][i][j] = vec_exp[abs(jj - ii)] *
	    (1.0 + vec_exp[2 * nx - 2 * jj + 1]) * (1.0 + vec_exp[2 * ii - 1]);
	}
      }
      // ippsDivC
      real dv = mdiv * (1.0 - vec_exp[2 * nx]);
      for (int i = 0; i < nx; i++)
	for (int j = 0; j < nx; j++)
	  mata[s - 1][i][j] /= dv;
    }
  }
  // per slice code
  real_1d vec_res(nx);
  real_1d vec64(nx);
  pixel_1d vec32(nx);
  int n = 2 * num_series - 1;
  for (int v = 0; v < nv; v++) {
    for (int s = 0; s < n; s++) {
      int ss = (s + 2) / 2;
      for (int h = 0; h < nx; h++)
	vec_res[h] = real(0.0);
      for (int a = 0; a < nangles; a++) {
	// ippsConvert
	for (int h = 0; h < nx; h++)
	  vec64[h] = real(pixels[a][h + crop_left][v]);
	// ippsMul
	for (int h = 0; h < nx; h++)
	  vec64[h] *= vecRS[s][a];
	// ippsAdd
	for (int h = 0; h < nx; h++)
	  vec_res[h] += vec64[h];
      }
      // ippsDivC
      for (int h = 0; h < nx; h++)
	vec_res[h] /= real(nangles);
      // ippsMulC
      for (int h = 0; h < nx; h++)
	vec64[h] = param_n * real(ss * ss) * vec_res[h];
      // ippsAdd
      for (int h = 0; h < nx - 1; h++)
	vec64[h] += vec_res[h];
      // ippsSub
      for (int h = 0; h < nx - 1; h++)
	vec64[h] -= vec_res[h + 1];
      // ippsAdd
      for (int h = 1; h < nx; h++)
	vec64[h] += vec_res[h];
      // ippsSub
      for (int h = 0; h < nx - 1; h++)
	vec64[h + 1] -= vec_res[h];
      // ippsDotProd
      // Todo - we don't seem to use mata[>0][][], why?, and can we avoid calc?
      for (int i = 0; i < nx; i++) {
	real dp = 0.0;
	for (int h = 0; h < nx; h++)
	  dp += vec64[h] * mata[0][i][h];
	vec_res[i] = dp;
      }
      // ippsConvert
      for (int h = 0; h < nx; h++)
	vec32[h] = pixel_type(vec_res[h]);
      for (int a = 0; a < nangles; a++) {
	// ippsAddProductC
	for (int h = 0; h < nx; h++)
	  pixels[a][h + crop_left][v] -= pixel_type(vecRS[s][a]) * vec32[h];
      }
    }
  }
}

// Todo - virtual fns and Diamond sub-classes for each alg?
void CCPi::Diamond::ring_artefact_removal(const ring_artefact_alg alg,
					  const real param_n,
					  const real param_r,
					  const int num_series)
{
  // ported from ring_artefacts routine in Manchester/Diamond FBP code
  if (alg == ring_artefacts_column)
    remove_column_ring_artefacts(get_pixel_data(), get_num_angles(),
				 get_num_h_pixels(), get_num_v_pixels());
  else if (alg == ring_artefacts_aml)
    remove_aml_ring_artefacts(get_pixel_data(), get_num_angles(),
			      get_num_h_pixels(), get_num_v_pixels(),
			      param_n, param_r, num_series);
}

max_stars_repo_name: vais-ral/CCPi-Reconstruction

max_issues_repo_name: vais-ral/CCPi-Reconstruction

max_forks_repo_name: vais-ral/CCPi-Reconstruction


text:
/*
 [auto_generated]
 libs/numeric/odeint/test/runge_kutta_concepts.cpp

 [begin_description]
 This file tests the Stepper concepts of odeint with all Runge-Kutta steppers. It's one of the main tests
 of odeint.
 [end_description]

 Copyright 2012 Karsten Ahnert
 Copyright 2012-2013 Mario Mulansky

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

// disable checked iterator warning for msvc
#include <boost/config.hpp>
#ifdef BOOST_MSVC
    #pragma warning(disable:4996)
#endif

#define BOOST_TEST_MODULE odeint_runge_kutta_concepts

#include <vector>
#include <cmath>
#include <iostream>

#include <boost/numeric/odeint/config.hpp>

#include <boost/array.hpp>

#include <boost/test/unit_test.hpp>

#include <boost/ref.hpp>
#include <boost/bind.hpp>
#include <boost/utility.hpp>
#include <boost/type_traits/add_reference.hpp>

#include <boost/mpl/vector.hpp>
#include <boost/mpl/for_each.hpp>
#include <boost/mpl/insert_range.hpp>
#include <boost/mpl/end.hpp>
#include <boost/mpl/copy.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/mpl/inserter.hpp>

#include <boost/numeric/odeint/stepper/euler.hpp>
#include <boost/numeric/odeint/stepper/modified_midpoint.hpp>
#include <boost/numeric/odeint/stepper/runge_kutta4_classic.hpp>
#include <boost/numeric/odeint/stepper/runge_kutta4.hpp>
#include <boost/numeric/odeint/stepper/runge_kutta_cash_karp54_classic.hpp>
#include <boost/numeric/odeint/stepper/runge_kutta_cash_karp54.hpp>
#include <boost/numeric/odeint/stepper/runge_kutta_dopri5.hpp>
#include <boost/numeric/odeint/stepper/runge_kutta_fehlberg78.hpp>

#include <boost/numeric/odeint/algebra/detail/extract_value_type.hpp>

#include "prepare_stepper_testing.hpp"
#include "dummy_odes.hpp"

using std::vector;

using namespace boost::unit_test;
using namespace boost::numeric::odeint;
namespace mpl = boost::mpl;

const double result = 2.2;

const double eps = 1.0e-14;

template< class Stepper , class System >
void check_stepper_concept( Stepper &stepper , System system , typename Stepper::state_type &x )
{
    typedef Stepper stepper_type;
    typedef typename stepper_type::deriv_type container_type;
    typedef typename stepper_type::order_type order_type;
    typedef typename stepper_type::time_type time_type;

    stepper.do_step( system , x , static_cast<time_type>(0.0) , static_cast<time_type>(0.1) );
}

// default case is used for vector space types like plain double
template< class Stepper , typename T >
struct perform_stepper_test
{
    typedef T vector_space_type;
    void operator()( void ) const
    {
        vector_space_type x;
        x = 2.0;
        Stepper stepper;
        constant_system_functor_vector_space sys;
#ifndef _MSC_VER
        // dont run this for MSVC due to compiler bug 697006
        check_stepper_concept( stepper , constant_system_vector_space< vector_space_type , vector_space_type , typename Stepper::time_type > , x );
#else
        check_stepper_concept( stepper , boost::cref( sys ) , x );
#endif
        check_stepper_concept( stepper , boost::cref( sys ) , x );
        std::cout << x << " ?= " << result << std::endl;
        BOOST_CHECK( (abs( x - result )) < eps );
    }
};

template< class Stepper , typename T >
struct perform_stepper_test< Stepper , std::vector<T> >
{
    typedef std::vector<T> vector_type;
    void operator()( void )
    {
        using std::abs;
        vector_type x( 1 , static_cast<T>(2.0) );
        Stepper stepper;
        constant_system_functor_standard sys;
#ifndef _MSC_VER
        // dont run this for MSVC due to compiler bug 697006
        check_stepper_concept( stepper , constant_system_standard< vector_type , vector_type , typename Stepper::time_type > , x );
#else
        check_stepper_concept( stepper , boost::cref( sys ) , x );
#endif
        check_stepper_concept( stepper , boost::cref( sys ) , x );
        std::cout << x[0] << " ?= " << result << std::endl;
        BOOST_CHECK( (abs( x[0] - result )) < eps );
    }
};

template< class Stepper , typename T >
struct perform_stepper_test< Stepper , boost::array<T,1> >
{
    typedef boost::array<T,1> array_type;
    void operator()( void )
    {
        using std::abs;
        array_type x;
        x[0] = static_cast<T>(2.0);
        Stepper stepper;
        constant_system_functor_standard sys;
#ifndef _MSC_VER
        // dont run this for MSVC due to compiler bug 697006
        check_stepper_concept( stepper , constant_system_standard< array_type , array_type , typename Stepper::time_type > , x );
#else
        check_stepper_concept( stepper , boost::cref( sys ) , x );
#endif
        check_stepper_concept( stepper , boost::cref( sys ) , x );
        std::cout << x[0] << " ?= " << result << std::endl;
        BOOST_CHECK( (abs( x[0] - result )) < eps );
    }
};

// split stepper methods to ensure the final vector has less than 30(?) elements
// (stepper_methods*container_types) < 30(?)
template< class State > class stepper_methods1 : public mpl::vector<
    euler< State , typename detail::extract_value_type<State>::type > ,
    modified_midpoint< State , typename detail::extract_value_type<State>::type > ,
    runge_kutta4< State , typename detail::extract_value_type<State>::type > ,
    runge_kutta4_classic< State , typename detail::extract_value_type<State>::type >
    > { };

template< class State > class stepper_methods2 : public mpl::vector<
    runge_kutta_cash_karp54_classic< State , typename detail::extract_value_type<State>::type > ,
    runge_kutta_cash_karp54< State , typename detail::extract_value_type<State>::type > ,
    runge_kutta_dopri5< State , typename detail::extract_value_type<State>::type > ,
    runge_kutta_fehlberg78< State , typename detail::extract_value_type<State>::type >
    > { };

typedef mpl::copy
<
  container_types ,
  mpl::inserter
  <
    mpl::vector0<> ,
    mpl::insert_range
    <
      mpl::_1 ,
      mpl::end< mpl::_1 > ,
      stepper_methods1< mpl::_2 >
    >
  >
>::type stepper_combinations1;

typedef mpl::copy
<
  container_types ,
  mpl::inserter
  <
    mpl::vector0<> ,
    mpl::insert_range
    <
      mpl::_1 ,
      mpl::end< mpl::_1 > ,
      stepper_methods2< mpl::_2 >
    >
  >
>::type stepper_combinations2;

BOOST_AUTO_TEST_SUITE( runge_kutta_concept_test )

BOOST_AUTO_TEST_CASE_TEMPLATE( stepper_test1 , Stepper, stepper_combinations1 )
{
    perform_stepper_test< Stepper , typename Stepper::deriv_type > tester;
    tester();
}

BOOST_AUTO_TEST_CASE_TEMPLATE( stepper_test2 , Stepper, stepper_combinations2 )
{
    perform_stepper_test< Stepper , typename Stepper::deriv_type > tester;
    tester();
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: lijgame/boost

max_issues_repo_name: nxplatform/nx-mobile

max_forks_repo_name: nxplatform/nx-mobile


text:
#ifndef FVMSCALAR1D_SNAPSHOT_WRITER_HPP
#define FVMSCALAR1D_SNAPSHOT_WRITER_HPP

#include <Eigen/Dense>
#include <ancse/grid.hpp>
#include <ancse/simulation_time.hpp>
#include <memory>

/// Interface for outputting snapshots.
class SnapshotWriter {
  public:
    virtual ~SnapshotWriter() = default;

    virtual void operator()(const Eigen::VectorXd &u) const = 0;
};

class JSONSnapshotWriter : public SnapshotWriter {
  public:
    JSONSnapshotWriter(const Grid &grid,
                      std::shared_ptr<SimulationTime> simulation_time,
                       std::string basename);

    virtual void operator()(const Eigen::VectorXd &u) const override;

  private:
    Grid grid;
    std::shared_ptr<SimulationTime> simulation_time;

    std::string basename;
    mutable int k_output = 0;
};

#endif // FVMSCALAR1D_SNAPSHOT_WRITER_HPP


text:
//------------------------------------------------------------------------------
/// \file SetSocketOptions_tests.cpp
/// \author Ernest Yeung
/// \email  ernestyalumni@gmail.com
//------------------------------------------------------------------------------
#include "IPC/Sockets/SetSocketOptions.h"

#include "IPC/Sockets/InternetAddress.h"
#include "IPC/Sockets/ParameterFamilies.h"
#include "IPC/Sockets/Socket.h"

#include <boost/test/unit_test.hpp>

using IPC::Sockets::Domain;
using IPC::Sockets::InternetSocketAddress;
using IPC::Sockets::SetReusableAddressAndPort;
using IPC::Sockets::SetReusableSocketAddress;
using IPC::Sockets::SetSocketOptions;
using IPC::Sockets::Socket;
using IPC::Sockets::Type;

BOOST_AUTO_TEST_SUITE(IPC)
BOOST_AUTO_TEST_SUITE(Sockets)
BOOST_AUTO_TEST_SUITE(SetSocketOptions_tests)

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(SetSocketOptions)
{
  {
    Socket socket {Domain::ipv4, Type::datagram};
    BOOST_TEST_REQUIRE(socket.domain() == AF_INET);
    BOOST_TEST_REQUIRE(socket.type() == SOCK_DGRAM);

    const InternetSocketAddress internet_socket_address {0};

    const auto result = SetReusableSocketAddress()(socket);
    BOOST_TEST(!static_cast<bool>(result));
  }
}

BOOST_AUTO_TEST_SUITE_END() // SetSocketOptions_tests
BOOST_AUTO_TEST_SUITE_END() // Sockets
BOOST_AUTO_TEST_SUITE_END() // IPC

max_stars_repo_name: ernestyalumni/HrdwCCppCUDA

max_issues_repo_name: ernestyalumni/HrdwCCppCUDA

max_forks_repo_name: ernestyalumni/HrdwCCppCUDA


text:
#include "../Block_Info.hxx"

#include <boost/filesystem/fstream.hpp>

std::vector<Block_Cost>
Block_Info::read_block_costs(const boost::filesystem::path &sdp_path,
                             const boost::filesystem::path &checkpoint_in)
{
  const boost::filesystem::path sdp_block_timings_path(sdp_path
                                                       / "block_timings"),
    checkpoint_block_timings_path(checkpoint_in / "block_timings");

  if(exists(checkpoint_in / ("checkpoint." + std::to_string(El::mpi::Rank()))))
    {
      if(exists(checkpoint_block_timings_path))
        {
          block_timings_filename = checkpoint_block_timings_path;
        }
    }
  else
    {
      block_timings_filename
        = (exists(checkpoint_block_timings_path)
             ? checkpoint_block_timings_path
             : (exists(sdp_block_timings_path) ? sdp_block_timings_path : ""));
    }

  std::vector<Block_Cost> result;
  if(!block_timings_filename.empty())
    {
      size_t index(0), cost;
      boost::filesystem::ifstream costs(block_timings_filename);
      costs >> cost;
      while(costs.good())
        {
          result.emplace_back(cost, index);
          ++index;
          costs >> cost;
        }
      if(result.size() != num_points.size())
        {
          throw std::runtime_error(
            "Incompatible number of entries in '"
            + block_timings_filename.string() + "'. Expected "
            + std::to_string(num_points.size()) + " but found "
            + std::to_string(result.size()));
        }
    }
  else
    {
      // If no information, assign a cost proportional to the matrix
      // size.  This should balance out memory use when doing a timing
      // run.
      auto schur_sizes(schur_block_sizes());
      for(size_t block = 0; block < schur_sizes.size(); ++block)
        {
          result.emplace_back(schur_sizes[block] * schur_sizes[block], block);
        }
    }
  return result;
}

ext: cxx

max_stars_repo_name: ChrisPattison/sdpb

max_issues_repo_name: ChrisPattison/sdpb

max_forks_repo_name: ChrisPattison/sdpb


text:
#ifndef BOOST_METAPARSE_V1_IMPL_STRING_ITERATOR_HPP
#define BOOST_METAPARSE_V1_IMPL_STRING_ITERATOR_HPP

// Copyright Abel Sinkovics (abel@sinkovics.hu)  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 <boost/metaparse/v1/impl/string_iterator_tag.hpp>
#include <boost/metaparse/v1/impl/at_c.hpp>

#include <boost/mpl/iterator_tags.hpp>
#include <boost/mpl/int.hpp>
#include <boost/mpl/bool.hpp>

#include <boost/type_traits/is_same.hpp>

namespace boost
{
  namespace metaparse
  {
    namespace v1
    {
      namespace impl
      {
        // string_iterator
        template <class S, int N>
        struct string_iterator
        {
          typedef string_iterator type;
          typedef string_iterator_tag tag;
          typedef boost::mpl::random_access_iterator_tag category;
        };

        // advance_c

        template <class S, int N>
        struct advance_c;

        template <class S, int N, int P>
        struct advance_c<string_iterator<S, N>, P> :
          string_iterator<S, N + P>
        {};

        // distance

        template <class A, class B>
        struct distance;

        template <class S, int A, int B>
        struct distance<string_iterator<S, A>, string_iterator<S, B> > :
          boost::mpl::int_<B - A>
        {};
      }
    }
  }
}

namespace boost
{
  namespace mpl
  {
    // advance
    template <class S>
    struct advance_impl;

    template <>
    struct advance_impl<boost::metaparse::v1::impl::string_iterator_tag>
    {
      typedef advance_impl type;

      template <class S, class N>
      struct apply :
        boost::metaparse::v1::impl::advance_c<
          typename S::type, N::type::value
        >
      {};
    };

    // distance
    template <class S>
    struct distance_impl;

    template <>
    struct distance_impl<boost::metaparse::v1::impl::string_iterator_tag>
    {
      typedef distance_impl type;

      template <class A, class B>
      struct apply :
        boost::metaparse::v1::impl::distance<
          typename A::type,
          typename B::type
        >
      {};
    };

    // next
    template <class S>
    struct next;

    template <class S, int N>
    struct next<boost::metaparse::v1::impl::string_iterator<S, N> > :
      boost::metaparse::v1::impl::string_iterator<S, N + 1>
    {};

    // prior
    template <class S>
    struct prior;

    template <class S, int N>
    struct prior<boost::metaparse::v1::impl::string_iterator<S, N> > :
      boost::metaparse::v1::impl::string_iterator<S, N - 1>
    {};

    // deref
    template <class S>
    struct deref;

    template <class S, int N>
    struct deref<boost::metaparse::v1::impl::string_iterator<S, N> > :
      boost::metaparse::v1::impl::at_c<S, N>
    {};

    // equal_to
    template <class A, class B>
    struct equal_to_impl;

    template <>
    struct equal_to_impl<
      boost::metaparse::v1::impl::string_iterator_tag,
      boost::metaparse::v1::impl::string_iterator_tag
    >
    {
      typedef equal_to_impl type;

      template <class A, class B>
      struct apply : is_same<typename A::type, typename B::type> {};
    };

    template <class T>
    struct equal_to_impl<boost::metaparse::v1::impl::string_iterator_tag, T>
    {
      typedef equal_to_impl type;

      template <class, class>
      struct apply : false_ {};
    };

    template <class T>
    struct equal_to_impl<T, boost::metaparse::v1::impl::string_iterator_tag> :
      equal_to_impl<boost::metaparse::v1::impl::string_iterator_tag, T>
    {};
  }
}

#endif


text:
/*
 * cycle_finder.hpp
 *
 *  Created on: Apr 2, 2011
 *      Author: stewie
 */

#ifndef CYCLE_FINDER_HPP_
#define CYCLE_FINDER_HPP_

#include <cstddef>
#include <utility>

#include <boost/iterator/iterator_facade.hpp>
#include <boost/range/adaptor/argument_fwd.hpp>
#include <boost/range/adaptor/transformed.hpp>
#include <boost/range/adaptor/filtered.hpp>
#include <boost/mpl/void_fwd.hpp>

#include "cycle_finder/naive.hpp"
#include "cycle_finder/brent.hpp"

namespace bn {

namespace detail {

template<class It, class Strategy> struct AttractorIterator : boost::iterator_facade<
		AttractorIterator<It, Strategy> , const Attractor,
		boost::single_pass_traversal_tag> {
public:
	// begin
	AttractorIterator(const It iter, const It e, const Strategy& st) :
		it(iter), end(e), s(st) {
		ensureInvariant();
	}

	// end
	AttractorIterator(const It e, const Strategy& st) :
		it(e), end(e), s(st) {
	}

private:
	typedef boost::iterator_facade<AttractorIterator<It, Strategy> ,
			const Attractor, boost::forward_traversal_tag> base;
	friend class boost::iterator_core_access;
	It it, end;
	Strategy s;
	Attractor current;

	void ensureInvariant() {
		while (it != end && (current = s(*it)) == EMPTY_ATTRACTOR)
			++it;
	}

	typename base::reference dereference() const {
		return current;
	}

	bool equal(const AttractorIterator& other) const {
		return it == other.it;
	}

	void increment() {
		++it;
		ensureInvariant();
	}
};

template<class It, class Strategy> AttractorIterator<It, Strategy> operator++(
		AttractorIterator<It, Strategy>& it, int) {
	AttractorIterator<It, Strategy> temp(it);
	++it;
	return temp;
}

template<class StateRange, class Strategy> struct AttractorRange : boost::iterator_range<
		AttractorIterator<typename boost::range_iterator<StateRange>::type,
				Strategy> > {
private:
	typedef boost::iterator_range<AttractorIterator<
			typename boost::range_iterator<StateRange>::type, Strategy> > base;

public:
	AttractorRange(const StateRange& r, const Strategy& s) :
				base(typename base::iterator(r.begin(), r.end(), s),
						typename base::iterator(r.end(), s)) {
	}
};

template<class Strategy, class Terminator> struct CycleFinder {
	typedef Attractor result_type;
	BooleanDynamics& dyn;
	Terminator t;
	CycleFinder(BooleanDynamics& dyn, const Terminator& t) :
		dyn(dyn), t(t) {
	}
	result_type operator()(const State& s) const {
		return Strategy::call(dyn, s, t);
	}
};

template<class Strategy> struct CycleFinder<Strategy, boost::mpl::void_> {
	typedef Attractor result_type;
	BooleanDynamics& dyn;
	CycleFinder(BooleanDynamics& dyn) :
		dyn(dyn) {
	}
	result_type operator()(const State& s) const {
		return Strategy::call(dyn, s);
	}
};

struct NaiveStrategy {
	template<class Terminator> static Attractor call(BooleanDynamics& dyn,
			const State& s, const Terminator& t) {
		return cycle_finder::naive(dyn, s, t);
	}

	static Attractor call(BooleanDynamics& dyn, const State& s) {
		return cycle_finder::naive(dyn, s);
	}
};

struct BrentStrategy {
	template<class Terminator> static Attractor call(BooleanDynamics& dyn,
			const State& s, const Terminator& t) {
		return cycle_finder::brent(dyn, s, t);
	}

	static Attractor call(BooleanDynamics& dyn, const State& s) {
		return cycle_finder::brent(dyn, s);
	}
};

} // namespace detail

template<class SR, class S> detail::AttractorRange<SR, S> find_attractors(
		const SR& r, const S& s) {
	return detail::AttractorRange<SR, S>(r, s);
}

struct MaxIter {
	const size_t m;
	MaxIter(const size_t m) :
		m(m) {
	}
	bool operator()(const size_t iter) const {
		return iter < m;
	}
};

struct NotNone {
	bool operator()(const Attractor& a) const {
		return a != EMPTY_ATTRACTOR;
	}
};

typedef detail::CycleFinder<detail::NaiveStrategy, boost::mpl::void_>
		NaiveCycleFinder;

NaiveCycleFinder naive(BooleanDynamics& dyn) {
	return NaiveCycleFinder(dyn);
}

template<class Terminator> detail::CycleFinder<detail::NaiveStrategy,
		Terminator> naive(BooleanDynamics& dyn, const Terminator& t) {
	return detail::CycleFinder<detail::NaiveStrategy, Terminator>(dyn, t);
}

detail::CycleFinder<detail::BrentStrategy, boost::mpl::void_> brent(
		BooleanDynamics& dyn) {
	return detail::CycleFinder<detail::BrentStrategy, boost::mpl::void_>(dyn);
}

template<class Terminator> detail::CycleFinder<detail::BrentStrategy,
		Terminator> brent(BooleanDynamics& dyn, const Terminator& t) {
	return detail::CycleFinder<detail::BrentStrategy, Terminator>(dyn, t);
}

template<class SinglePassRange, class Strategy, class Terminator>
detail::AttractorRange<SinglePassRange, Strategy> operator|(
		SinglePassRange& rng,
		const detail::CycleFinder<Strategy, Terminator>& f) {
	return find_attractors(rng, f);
}

template<class SinglePassRange, class Strategy, class Terminator>
detail::AttractorRange<SinglePassRange, Strategy> operator|(
		const SinglePassRange& rng,
		const detail::CycleFinder<Strategy, Terminator>& f) {
	return find_attractors(rng, f);
}

} // namespace bn

#endif /* CYCLE_FINDER_HPP_ */

max_stars_repo_name: Markfrancisrogers/BooleanNetwork

max_issues_repo_name: Markfrancisrogers/BooleanNetwork

max_forks_repo_name: Markfrancisrogers/BooleanNetwork


text:
#include <NTL/ZZ_pXFactoring.h>
#include <NTL/ZZ_pEX.h>
#include <NTL/ZZ.h>
#include <iostream>
#include <random>
#include <vector>
#include "nativeNtl.hpp"

inline int GetRandom()
{
    std::random_device rd;
    std::mt19937 rng(rd());
    std::uniform_int_distribution<int> uni(0,8);
    auto random_integer = uni(rng);
    return random_integer;
}
class Ntru_native
{

public:
    //分圆不等式 X^( n - 1 )
    Ntru_native():n(8),q(1117),l()
    {
        l={static_cast<int>(std::log2(q))-1};
        init();

    }
    void init()
    {
        NTL::ZZ_p::init(NTL::ZZ(q));
        NTL::ZZ_pX  tmp;

        SetCoeff(ring, 0, -1);
        SetCoeff(ring,n, 1);
        NTL::ZZ_p::init(NTL::ZZ(2));

        //fuck1 represent  f`
        long idx=GetRandom()%n;
        if(!idx)idx+=1;
        NTL::SetCoeff(fuck1, idx, 1);
        NTL::SetCoeff(fuck1, 0, 1);

        long idx1=GetRandom()%n;
        if(!idx1)idx1+=1;
        NTL::SetCoeff(gfuck, idx1, 1);
        NTL::SetCoeff(gfuck, 0, 0);

        KeyGen();
    }

    //compute KeyGen
    void   KeyGen()
    {

        //store result represent f^{-1}
        NTL::ZZ_pX x;

        NTL::ZZ_pX t;

        //prime poly reprensent 1
        NTL::ZZ_pX d;

        //random init three zz_px
        long idx=GetRandom()%n;
        if(!idx)idx+=1;
        NTL::SetCoeff(t, idx, 1);

        NTL::SetCoeff(d, 0, 1);

        /***
            copy f
         ****/
        tmpfuck=fuck1;

        NTL::XGCD(d, x, t, fuck1, ring);

        keygen= NTL::MulMod( x, gfuck,ring);

        Enc();
    }

//    inline void  handle_pex(NTL::ZZ_pEX &s,NTL::ZZ_pEX &e)
//    {
//
//    }

    void set_vec(std::vector<NTL::ZZ_pX> &s,std::vector<NTL::ZZ_pX>& e)
    {
        NTL::ZZ_pX m1,m2;

        NTL::ZZ_p::init(NTL::ZZ(2));

        for(int i=0;i<l+1;++i)
        {

            BuildIrred(m1, n-1);
            s.push_back(m1);
            BuildIrred(m2, n-1);
            e.push_back(m2);
        }

    }
    void Enc()
    {

        //密文
        NTL::ZZ_pX message;

        NTL::SetCoeff(message, 0, 1);

        NTL::ZZ_p::init(NTL::ZZ(2));

        NTL::ZZ_pX PP;
        BuildIrred(PP, n);

        NTL::ZZ_pE::init(PP);

//        NTL::ZZ_pEX s;
//        NTL::ZZ_pEX e;
//        random(s, l+1);
//        random(e,l+1);

        set_vec(s, e);

        NTL::ZZ_p::init(NTL::ZZ(q));
        NTL::ZZ_pX tmp;

        for(int i=0;i<l;++i)
        {

            NTL::SetCoeff(tmp, 0, std::pow(2, i));
            Encc.push_back(NTL::MulMod(message,tmp,ring)+NTL::MulMod(keygen,s[i],ring)+e[i]);
        }
        add();
        Dec();
    }

    void add()
    {
        NTL::ZZ_pX add_res;
        NTL::add(add_res, Encc.at(0), Encc.at(1));
        std::cout<<"C1+C2 = "<<add_res<<std::endl;
    }

    void Dec()
    {

        NTL::ZZ_p::init(NTL::ZZ(q));
        NTL::ZZ_pX tmp;
        NTL::SetCoeff(tmp, 0, std::pow(2, (-l-1)));

        /**
             test
         **/
//        std::cout<<"-l -1 "<<-(l-1)<<std::endl;
//        std::cout<<std::pow(2, -(l-1))<<std::endl;

        NTL::ZZ_p::init(NTL::ZZ(q));
        std::cout<< NTL::MulMod(Encc.at(l-1), tmpfuck, ring)<<"\n";
        auto &item=Encc.at(l-1);
        std::cout<< item[0]<<std::endl;
        NTL::SetCoeff(tmp, 0, 1);
//        std::cout<<"tmp"<<tmp<<std::endl;

    }

private:
    //环基于这个质数
    //环上多项式的系数

    //最高项次为4次
    int n,q,l;
    //标准偏移
    NTL::ZZ_pX fuck1,gfuck,tmpfuck ;
    //keygen
    NTL::ZZ_pX keygen;
    //分圆式
    NTL::ZZ_pX ring;

    //密文向量
    std::vector<NTL::ZZ_pX> Encc;

    std::vector<NTL::ZZ_pX> s;
    std::vector<NTL::ZZ_pX> e;

};
int main()
{
    for(int i=0;i<1000;++i)
    Ntru_native Nn;
    return 0;
}

max_stars_repo_name: fushenshen/ENC-AND-DEC

max_issues_repo_name: fushenshen/ENC-AND-DEC

max_forks_repo_name: fushenshen/ENC-AND-DEC


text:
// Boost uuid_generators.hpp header file  ----------------------------------------------//

// Copyright 2006 Andy Tompkins.
// 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)

// Revision History
//  06 Feb 2006 - Initial Revision

#ifndef BOOST_UUID_GENERATORS_HPP
#define BOOST_UUID_GENERATORS_HPP

#include <boost/uuid/nil_generator.hpp>
#include <boost/uuid/string_generator.hpp>
#include <boost/uuid/name_generator.hpp>
#include <boost/uuid/random_generator.hpp>

#endif //BOOST_UUID_GENERATORS_HPP

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema