text:
//          Copyright Oliver Kowalke 2009.
// 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)

#ifndef BOOST_COROUTINES_DETAIL_PUSH_COROUTINE_SYNTHESIZED_H
#define BOOST_COROUTINES_DETAIL_PUSH_COROUTINE_SYNTHESIZED_H

#include <boost/config.hpp>

#include <boost/coroutine/detail/config.hpp>
#include <boost/coroutine/detail/coroutine_context.hpp>
#include <boost/coroutine/detail/push_coroutine_impl.hpp>

#ifdef BOOST_HAS_ABI_HEADERS
#include BOOST_ABI_PREFIX
#endif

namespace boost {
namespace coroutines {
namespace detail {

template <typename R>
class push_coroutine_synthesized : public push_coroutine_impl<R> {
private:
  typedef push_coroutine_impl<R> impl_t;

public:
  push_coroutine_synthesized(coroutine_context *caller,
                             coroutine_context *callee, bool unwind)
      : impl_t(caller, callee, unwind) {}

  void destroy() {}
};

template <typename R>
class push_coroutine_synthesized<R &> : public push_coroutine_impl<R &> {
private:
  typedef push_coroutine_impl<R &> impl_t;

public:
  push_coroutine_synthesized(coroutine_context *caller,
                             coroutine_context *callee, bool unwind)
      : impl_t(caller, callee, unwind) {}

  void destroy() {}
};

template <>
class push_coroutine_synthesized<void> : public push_coroutine_impl<void> {
private:
  typedef push_coroutine_impl<void> impl_t;

public:
  push_coroutine_synthesized(coroutine_context *caller,
                             coroutine_context *callee, bool unwind)
      : impl_t(caller, callee, unwind) {}

  inline void destroy() {}
};

} // namespace detail
} // namespace coroutines
} // namespace boost

#ifdef BOOST_HAS_ABI_HEADERS
#include BOOST_ABI_SUFFIX
#endif

#endif // BOOST_COROUTINES_DETAIL_PUSH_COROUTINE_SYNTHESIZED_H

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


text:
// Copyright 2008-2010 Gordon Woodhull
// 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/msm/mpl_graph/depth_first_search.hpp>
#include <boost/msm/mpl_graph/adjacency_list_graph.hpp>
#include <boost/msm/mpl_graph/incidence_list_graph.hpp>

#include <iostream>

namespace mpl_graph = boost::msm::mpl_graph;
namespace mpl = boost::mpl;

// vertices
struct A{}; struct B{}; struct C{}; struct D{}; struct E{}; struct F{}; struct G{};

// edges
struct A_B{}; struct B_C{}; struct C_D{}; struct C_E{}; struct C_F{}; struct B_F{};

/*
    incidence list test graph:
    A -> B -> C -\--> D
           \     |--> E
            \    \--> F
             \-----/
    G
*/

typedef mpl::vector<mpl::vector<A_B,A,B>,
               mpl::vector<B_C,B,C>,
               mpl::vector<C_D,C,D>,
               mpl::vector<C_E,C,E>,
               mpl::vector<C_F,C,F>,
               mpl::vector<B_F,B,F> >
    some_incidence_list;
typedef mpl_graph::incidence_list_graph<some_incidence_list> some_incidence_list_graph;

/*
    adjacency list test graph:
    A -> B -> C -\--> D
           \     |--> E
            \    \--> F
             \-----/
    G
*/

typedef mpl::vector<
            mpl::pair<A, mpl::vector<mpl::pair<A_B, B> > >,
            mpl::pair<B, mpl::vector<mpl::pair<B_C, C>,
                                     mpl::pair<B_F, F> > >,
            mpl::pair<C, mpl::vector<mpl::pair<C_D, D>,
                                     mpl::pair<C_E, E>,
                                     mpl::pair<C_F, F> > >,
            mpl::pair<G, mpl::vector<> > >
    some_adjacency_list;
typedef mpl_graph::adjacency_list_graph<some_adjacency_list> some_adjacency_list_graph;

struct preordering_visitor : mpl_graph::dfs_default_visitor_operations {
    template<typename Node, typename Graph, typename State>
    struct discover_vertex :
        mpl::push_back<State, Node>
    {};
};

struct postordering_visitor : mpl_graph::dfs_default_visitor_operations {
    template<typename Node, typename Graph, typename State>
    struct finish_vertex :
        mpl::push_back<State, Node>
    {};
};

// adjacency list tests

// preordering, default start node (first)
typedef mpl::first<mpl_graph::
    depth_first_search_all<some_adjacency_list_graph,
                           preordering_visitor,
                           mpl::vector<> >::type>::type
                    preorder_adj;
BOOST_MPL_ASSERT(( mpl::equal<preorder_adj::type, mpl::vector<A,B,C,D,E,F,G> > ));

// postordering, default start node
typedef mpl::first<mpl_graph::
    depth_first_search_all<some_adjacency_list_graph,
                           postordering_visitor,
                           mpl::vector<> >::type>::type
                    postorder_adj;
BOOST_MPL_ASSERT(( mpl::equal<postorder_adj::type, mpl::vector<D,E,F,C,B,A,G> > ));

// preordering all starting at C
typedef mpl::first<mpl_graph::
    depth_first_search_all<some_adjacency_list_graph,
                           preordering_visitor,
                           mpl::vector<>,
                           C>::type>::type
                    preorder_adj_all_from_c;
BOOST_MPL_ASSERT(( mpl::equal<preorder_adj_all_from_c::type, mpl::vector<C,D,E,F,A,B,G> > ));

// preordering just those starting at C
typedef mpl::first<mpl_graph::
    depth_first_search<some_adjacency_list_graph,
                       preordering_visitor,
                       mpl::vector<>,
                       C>::type>::type
                preorder_adj_from_c;
BOOST_MPL_ASSERT(( mpl::equal<preorder_adj_from_c::type, mpl::vector<C,D,E,F> > ));

// incidence list tests

// preordering, default start node (first)
typedef mpl::first<mpl_graph::
    depth_first_search_all<some_incidence_list_graph,
                           preordering_visitor,
                           mpl::vector<> >::type>::type
                    preorder_inc;
BOOST_MPL_ASSERT(( mpl::equal<preorder_inc::type, mpl::vector<A,B,C,D,E,F> > ));

// postordering, default start node
typedef mpl::first<mpl_graph::
    depth_first_search_all<some_incidence_list_graph,
                           postordering_visitor,
                           mpl::vector<> >::type>::type
                    postorder_inc;
BOOST_MPL_ASSERT(( mpl::equal<postorder_inc::type, mpl::vector<D,E,F,C,B,A> > ));

// preordering starting at C
typedef mpl::first<mpl_graph::
    depth_first_search_all<some_incidence_list_graph,
                           preordering_visitor,
                           mpl::vector<>,
                           C>::type>::type
                    preorder_inc_all_from_c;
BOOST_MPL_ASSERT(( mpl::equal<preorder_inc_all_from_c::type, mpl::vector<C,D,E,F,A,B> > ));

// preordering starting at B
typedef mpl::first<mpl_graph::
    depth_first_search<some_incidence_list_graph,
                       preordering_visitor,
                       mpl::vector<>,
                       B>::type>::type
                preorder_inc_from_b;
BOOST_MPL_ASSERT(( mpl::equal<preorder_inc_from_b::type, mpl::vector<B,C,D,E,F> > ));

int main() {
    return 0;
}

ext: cpp


text:
/******************************************************************************\
 *                                                                            *
 *           ____                  _        _        _                        *
 *          | __ )  ___   ___  ___| |_     / \   ___| |_ ___  _ __            *
 *          |  _ \ / _ \ / _ \/ __| __|   / _ \ / __| __/ _ \| '__|           *
 *          | |_) | (_) | (_) \__ \ |_ _ / ___ \ (__| || (_) | |              *
 *          |____/ \___/ \___/|___/\__(_)_/   \_\___|\__\___/|_|              *
 *                                                                            *
 *                                                                            *
 *                                                                            *
 * Copyright (C) 2011 - 2014                                                  *
 * Dominik Charousset <dominik.charousset@haw-hamburg.de>                     *
 *                                                                            *
 * Distributed under the Boost Software License, Version 1.0. See             *
 * accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt  *
\******************************************************************************/

#include "boost/actor/config.hpp"
#include "boost/actor/detail/get_root_uuid.hpp"

namespace {
constexpr char uuid_format[] = "FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF";
} // namespace <anonmyous>

#ifdef BOOST_ACTOR_MACOS

namespace {

inline void erase_trailing_newline(std::string& str) {
    while (!str.empty() && (*str.rbegin()) == '\n') {
        str.resize(str.size() - 1);
    }
}

constexpr const char* s_get_uuid = "/usr/sbin/diskutil info / | "
                                   "/usr/bin/awk '$0 ~ /UUID/ { print $3 }'";

} // namespace <anonymous>

namespace boost {
namespace actor {
namespace detail {

std::string get_root_uuid() {
    char cbuf[100];
    // fetch hd serial
    std::string uuid;
    FILE* get_uuid_cmd = popen(s_get_uuid, "r");
    while (fgets(cbuf, 100, get_uuid_cmd) != 0) {
        uuid += cbuf;
    }
    pclose(get_uuid_cmd);
    erase_trailing_newline(uuid);
    return uuid;
}

} // namespace detail
} // namespace actor
} // namespace boost

#elif defined(BOOST_ACTOR_LINUX)

#include <vector>
#include <string>
#include <cctype>
#include <fstream>
#include <sstream>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <stdio.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <net/if.h>
#include <cstring>
#include <unistd.h>
#include <iostream>

#include <boost/algorithm/string.hpp>

using std::vector;
using std::string;
using std::ifstream;

struct columns_iterator : std::iterator<std::forward_iterator_tag, vector<string>> {

    columns_iterator(ifstream* s = nullptr) : fs(s) { }

    vector<string>& operator*() { return cols; }

    columns_iterator& operator++() {
        string line;
        if (!std::getline(*fs, line)) fs = nullptr;
        else {
            using namespace boost::algorithm;
            split(cols, line, is_any_of(" "), token_compress_on);
        }
        return *this;
    }

    ifstream* fs;
    vector<string> cols;

};

bool operator==(const columns_iterator& lhs, const columns_iterator& rhs) {
    return lhs.fs == rhs.fs;
}

bool operator!=(const columns_iterator& lhs, const columns_iterator& rhs) {
    return !(lhs == rhs);
}

namespace boost {
namespace actor {
namespace detail {

std::string get_root_uuid() {
    int sck = socket(AF_INET, SOCK_DGRAM, 0);
    if (sck < 0) {
        perror("socket");
        return "";
    }
    // query available interfaces
    char buf[1024];
    ifconf ifc;
    ifc.ifc_len = sizeof(buf);
    ifc.ifc_buf = buf;
    if (ioctl(sck, SIOCGIFCONF, &ifc) < 0) {
        perror("ioctl(SIOCGIFCONF)");
        return "";
    }
    vector<string> hw_addresses;
    auto ctoi = [](char c) -> unsigned {
        return static_cast<unsigned char>(c);
    };
    // iterate through interfaces.
    auto ifr = ifc.ifc_req;
    size_t num_interfaces = ifc.ifc_len / sizeof(ifreq);
    for (size_t i = 0; i < num_interfaces; i++) {
        auto& item = ifr[i];
        // get MAC address
        if (ioctl(sck, SIOCGIFHWADDR, &item) < 0) {
            perror("ioctl(SIOCGIFHWADDR)");
            return "";
        }
        // convert MAC address to standard string representation
        std::ostringstream oss;
        oss << std::hex;
        oss.width(2);
        oss << ctoi(item.ifr_hwaddr.sa_data[0]);
        for (size_t i = 1; i < 6; ++i) {
            oss << ":";
            oss.width(2);
            oss << ctoi(item.ifr_hwaddr.sa_data[i]);
        }
        auto addr = oss.str();
        if (addr != "00:00:00:00:00:00") {
            hw_addresses.push_back(std::move(addr));
        }
    }
    string uuid;
    ifstream fs;
    fs.open("/etc/fstab", std::ios_base::in);
    columns_iterator end;
    auto i = find_if(columns_iterator{&fs}, end, [](const vector<string>& cols) {
        return cols.size() == 6 && cols[1] == "/";
    });
    if (i != end) {
        uuid = move((*i)[0]);
        const char cstr[] = { "UUID=" };
        auto slen = sizeof(cstr) - 1;
        if (uuid.compare(0, slen, cstr) == 0) uuid.erase(0, slen);
        // UUIDs are formatted as 8-4-4-4-12 hex digits groups
        auto cpy = uuid;
        replace_if(cpy.begin(), cpy.end(), ::isxdigit, 'F');
        // discard invalid UUID
        if (cpy != uuid_format) uuid.clear();
 //     "\\?\Volume{5ec70abf-058c-11e1-bdda-806e6f6e6963}\"

    }
    return uuid;
}

} // namespace detail
} // namespace actor
} // namespace boost

#elif defined(BOOST_ACTOR_WINDOWS)

#include <string>
#include <iostream>
#include <algorithm>

#include <windows.h>
#include <tchar.h>

using namespace std;

namespace boost {
namespace actor { namespace detail {

namespace { constexpr size_t max_drive_name = MAX_PATH; }

// if TCHAR is indeed a char, we can simply move rhs
void mv(std::string& lhs, std::string&& rhs) {
    lhs = std::move(rhs);
}

// if TCHAR is defined as WCHAR, we have to do unicode conversion
void mv(std::string& lhs, const std::basic_string<WCHAR>& rhs) {
    auto size_needed = WideCharToMultiByte(CP_UTF8, 0, rhs.c_str(),
                                           static_cast<int>(rhs.size()),
                                           nullptr, 0, nullptr, nullptr);
    lhs.resize(size_needed);
    WideCharToMultiByte(CP_UTF8, 0, rhs.c_str(), static_cast<int>(rhs.size()),
                        &lhs[0], size_needed, nullptr, nullptr);
}

std::string get_root_uuid() {
    typedef std::basic_string<TCHAR> tchar_str;
    string uuid;
    TCHAR buf[max_drive_name]; // temporary buffer for volume name
    tchar_str drive = TEXT("c:\\");   // string "template" for drive specifier
    // walk through legal drive letters, skipping floppies
    for (TCHAR i = TEXT('c'); i < TEXT('z');  i++ )  {
        // Stamp the drive for the appropriate letter.
        drive[0] = i;
        if (GetVolumeNameForVolumeMountPoint(drive.c_str(), buf, max_drive_name)) {
            tchar_str drive_name = buf;
            auto first = drive_name.find(TEXT("Volume{"));
            if (first != std::string::npos) {
                first += 7;
                auto last = drive_name.find(TEXT("}"), first);
                if (last != std::string::npos && last > first) {
                    mv(uuid, drive_name.substr(first, last - first));
                    // UUIDs are formatted as 8-4-4-4-12 hex digits groups
                    auto cpy = uuid;
                    replace_if(cpy.begin(), cpy.end(), ::isxdigit, 'F');
                    // discard invalid UUID
                    if (cpy != uuid_format) uuid.clear();
                    else return uuid; // return first valid UUID we get
                }
            }
        }
    }
    return uuid;
}

} } // namespace actor
} // namespace boost::util

#endif // BOOST_ACTOR_WINDOWS


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

#if defined(__unix__) || defined(__unix) || defined(unix)
#include <sys/time.h>
#include <sys/resource.h>
#endif

#include <NTL/BasicThreadPool.h>
#include "helib.h"
#include "matmul.h"
#include "debugging.h"
#include "fhe_stats.h"
#include "ArgMap.h"

#include <algorithm>
#include <cmath>
#include <string>

NTL_CLIENT
using namespace helib;

static bool noPrint = false;
static bool dry = false; // a dry-run flag
static bool debug = 0;   // a debug flag
static int scale = 0;

static string v_values_name = "";

static long OUTER_REP = 1;

static Vec<long> global_mvec, global_gens, global_ords;
static int c_m = 100;

static void
dump_v_values()
{
  const vector<double> *v_values = fetch_saved_values("v_values");
  if (v_values && v_values_name != "") {
    // write v_values to a file

    cerr << "writing v_values to " << v_values_name << "\n";

    ofstream F;
    F.open(v_values_name.c_str());
    for (long i: range(v_values->size()))
      F << (*v_values)[i] << "\n";
  }
}

static void
anderson_darling(const vector<double>& X, double& AD, double& p_val)
{
  long N = X.size();

  if (N < 2) {
    AD = 0;
    p_val = 1;
    return;
  }

  vector<double> Y(X);
  sort(Y.begin(), Y.end());

  // compute the sample mean
  double SM = 0;
  for (long i: range(N)) SM += Y[i];
  SM /= N;

  // compute the sample variance
  double SV = 0;
  for (long i: range(N)) SV += (Y[i]-SM)*(Y[i]-SM);
  SV /= (N-1);

  // replace Y[i] by CDF of Y[i]
  for (long i: range(N))
    Y[i] = 0.5*(1 + erf((Y[i]-SM)/sqrt(2*SV)));

  double S = 0;
  for (long i: range(N)) {
    S += (2*i+1)*(log(Y[i]) + log1p(-Y[N-1-i]));
  }
  AD = -N - S/N;

  AD *= (1 + 0.75/N + 2.25/N/N);
  // This adjustment and the p-values below come from:
  // R.B. D'Augostino and M.A. Stephens, Eds., 1986,
  // Goodness-of-Fit Techniques, Marcel Dekker.

  if (AD >= 0.6)
    p_val = exp(1.2937 - 5.709*(AD)+ 0.0186*fsquare(AD));
  else if (AD > 0.34)
    p_val = exp(0.9177 - 4.279*(AD) - 1.38*fsquare(AD));
  else if (AD > 0.2)
    p_val = 1 - exp(-8.318 + 42.796*(AD)- 59.938*fsquare(AD));
  else
    p_val = 1 - exp(-13.436 + 101.14*(AD)- 223.73*fsquare(AD));
}

static void
print_anderson_darling()
{
  const vector<double> *v_values = fetch_saved_values("v_values");
  if (v_values) {
    double AD, p_val;
    anderson_darling(*v_values, AD, p_val);
    cout << "AD=" << AD << ", p_val=" << p_val << "\n";
  }
  else
    cout << "\n";
}

void TestIt(long p, long r, long L, long c, long skHwt, int build_cache=0)
{
  Vec<long> mvec;
  vector<long> gens;
  vector<long> ords;

  long m, phim;

    mvec = global_mvec;
    convert(gens, global_gens);
    convert(ords, global_ords);

    m = computeProd(mvec);
    phim = phi_N(m);
    helib::assertTrue(GCD(p, m) == 1, "GCD(p, m) == 1");

  if (!noPrint) {
    cout << "*** TestIt";
    if (isDryRun()) cout << " (dry run)";
    cout << ": p=" << p
	 << ", r=" << r
	 << ", L=" << L
	 << ", t=" << skHwt
	 << ", c=" << c
	 << ", m=" << m
	 << " (=" << mvec << "), gens="<<gens<<", ords="<<ords
	 << endl;
    cout << "Computing key-independent tables..." << std::flush;
  }
  setTimersOn();
  setDryRun(false); // Need to get a "real context" to test bootstrapping

  double t = -GetTime();
  FHEcontext context(m, p, r, gens, ords);
  if (scale) {
    context.scale = scale;
  }

  context.zMStar.set_cM(c_m/100.0);
  buildModChain(context, L, c, /*willBeBootstrappable=*/true, /*t=*/skHwt);

  if (!noPrint) {
    std::cout << "security=" << context.securityLevel()<<endl;
    std::cout << "# small primes = " << context.smallPrimes.card() << "\n";
    std::cout << "# ctxt primes = " << context.ctxtPrimes.card() << "\n";
    std::cout << "# bits in ctxt primes = "
         << long(context.logOfProduct(context.ctxtPrimes)/log(2.0) + 0.5) << "\n";
    std::cout << "# special primes = " << context.specialPrimes.card() << "\n";
    std::cout << "# bits in special primes = "
         << long(context.logOfProduct(context.specialPrimes)/log(2.0) + 0.5) << "\n";
    std::cout << "scale=" << context.scale<<endl;
  }

  context.makeBootstrappable(mvec,/*t=*/skHwt,build_cache,/*alsoThick=*/false);
  // save time...disable some fat boot precomputation

  t += GetTime();

  //if (skHwt>0) context.rcData.skHwt = skHwt;
  if (!noPrint) {
    cout << " done in "<<t<<" seconds\n";
    cout << "  e="    << context.rcData.e
	 << ", e'="   << context.rcData.ePrime
	 << ", t="    << context.rcData.skHwt
	 << "\n  ";
    context.zMStar.printout();
  }
  setDryRun(dry); // Now we can set the dry-run flag if desired

  long p2r = context.alMod.getPPowR();

  if (!noPrint) fhe_stats = true;

  for (long numkey=0; numkey<OUTER_REP; numkey++) { // test with 3 keys
  if (1 && fhe_stats && numkey > 0 && numkey%100 == 0) {
    print_stats(cout);
    cout << "mvec=" << mvec << ", ";
    print_anderson_darling();
    dump_v_values();
  }

  if (!noPrint) cerr << "*********** iter=" << (numkey+1) << "\n";

  t = -GetTime();
  if (!noPrint) cout << "Generating keys, " << std::flush;
  FHESecKey secretKey(context);
  secretKey.GenSecKey(skHwt);      // A Hamming-weight-64 secret key
  addSome1DMatrices(secretKey); // compute key-switching matrices that we need
  addFrbMatrices(secretKey);
  if (!noPrint) cout << "computing key-dependent tables..." << std::flush;
  secretKey.genRecryptData();
  t += GetTime();
  if (!noPrint) cout << " done in "<<t<<" seconds\n";

#ifdef DEBUG_PRINTOUT
      dbgEa = (EncryptedArray*) context.ea;
      dbgKey = &secretKey;
#endif

  FHEPubKey publicKey = secretKey;

  long d = context.zMStar.getOrdP();
  long phim = context.zMStar.getPhiM();
  long nslots = phim/d;

  // GG defines the plaintext space Z_p[X]/GG(X)
  ZZX GG;
  GG = context.alMod.getFactorsOverZZ()[0];
  EncryptedArray ea(context, GG);

  if (debug) {
    dbgKey = &secretKey;
    dbgEa = &ea;
  }

  zz_p::init(p2r);
  Vec<zz_p> val0(INIT_SIZE, nslots);
  for (auto& x: val0)
    random(x);

  vector<ZZX> val1;
  val1.resize(nslots);
  for (long i = 0; i < nslots; i++) {
    val1[i] = conv<ZZX>(conv<ZZ>(rep(val0[i])));
  }

  Ctxt c1(publicKey);
  ea.encrypt(c1, publicKey, val1);

  // Make some noise!
  // This ensures that we do not start the sequence of squarings
  // from a "fresh" ciphertext (which may not be representive).
  ea.rotate(c1, 1);
  ea.rotate(c1, -1);

  Ctxt c2(c1);

  if (!noPrint) CheckCtxt(c2, "before squarings");

  long sqr_count = -1;
  Ctxt next_c2(c2);
  do {
    c2 = next_c2;
    next_c2.multiplyBy(next_c2);
    sqr_count++;
  }
  while (next_c2.bitCapacity() >= 100);

  if (!noPrint) {
    // compute minimal capacity before bootstrapping (rawModSwitch)
    long e = context.rcData.e;
    long q = power_long(p, e) + 1;
    double Bnd = context.boundForRecryption();
    double mfac = context.zMStar.getNormBnd();
    double min_bit_cap = log(  mfac*q / (p2r*Bnd*FHE_MIN_CAP_FRAC) )/log(2.0);

    cout << "min_bit_cap=" << min_bit_cap << "\n";

    cout << "log2(modSwitchAddedNoiseBound)="
         << log(c1.modSwitchAddedNoiseBound())/log(2.0) << "\n";
    cout << "sqr_count=" << sqr_count << "\n";
    if (sqr_count > 0) {
      cout << "BITS-PER-LEVEL: "
           << ((c1.bitCapacity()-c2.bitCapacity())/double(sqr_count)) << "\n";
    }
    CheckCtxt(c2, "before recryption");
  }

  resetAllTimers();

  { FHE_NTIMER_START(AAA_thinRecrypt);

  publicKey.thinReCrypt(c2);

  }

  if (!noPrint) CheckCtxt(c2, "after recryption");

  for (auto& x: val0) {
    for (long i: range(sqr_count)) x = x*x;
  }

  for (long i = 0; i < nslots; i++) {
    val1[i] = conv<ZZX>(conv<ZZ>(rep(val0[i])));
  }

  vector<ZZX> val2;
  ea.decrypt(c2, secretKey, val2);

  if (val1 == val2)
    cout << "GOOD\n";
  else
    cout << "BAD\n";
  }

  if (!noPrint) printAllTimers();

#if (defined(__unix__) || defined(__unix) || defined(unix))
    struct rusage rusage;
    getrusage( RUSAGE_SELF, &rusage );
    if (!noPrint) cout << "  rusage.ru_maxrss="<<rusage.ru_maxrss << endl;
#endif

  if (fhe_stats) {
    print_stats(cout);
    cout << "mvec=" << mvec << ", ";
    print_anderson_darling();
    dump_v_values();
  }

}

//extern long fhe_disable_intFactor;
// extern long fhe_disable_fat_boot;
// extern long fhe_force_chen_han;

/********************************************************************
 ********************************************************************/
int main(int argc, char *argv[])
{
  ArgMap amap;

  long p=2;
  long r=1;
  long c=3;
  long L=600;
  long N=0;
  long t=64;
  long nthreads=1;

  long seed=0;
  long useCache=1;

  amap.arg("p", p, "plaintext base");

  amap.arg("r", r,  "exponent");
  amap.note("p^r is the plaintext-space modulus");

  amap.arg("c", c, "number of columns in the key-switching matrices");
  amap.arg("L", L, "# of levels in the modulus chain");
  amap.arg("t", t, "Hamming weight of recryption secret key");
  amap.arg("dry", dry, "dry=1 for a dry-run");
  amap.arg("nthreads", nthreads, "number of threads");
  amap.arg("seed", seed, "random number seed");
  amap.arg("noPrint", noPrint, "suppress printouts");
  amap.arg("useCache", useCache, "0: zzX cache, 1: DCRT cache");

  amap.arg("force_bsgs", fhe_test_force_bsgs);
  amap.arg("force_hoist", fhe_test_force_hoist);

  //  amap.arg("disable_intFactor", fhe_disable_intFactor);
  amap.arg("chen_han", fhe_force_chen_han);

  amap.arg("debug", debug, "generate debugging output");
  amap.arg("scale", scale, "scale parameter");

  amap.arg("gens", global_gens);
  amap.arg("ords", global_ords);
  amap.arg("mvec", global_mvec);
  amap.arg("c_m", c_m);

  amap.arg("iter", OUTER_REP);

  amap.arg("v_values", v_values_name);

  amap.parse(argc, argv);

  if (global_gens.length() == 0 || global_ords.length() == 0 || global_mvec.length() == 0)
    Error("gens, ords, and mvec must be initialized");

  if (seed)
    SetSeed(ZZ(seed));

  SetNumThreads(nthreads);

  TestIt(p,r,L,c,t,useCache);

  return 0;
}

max_stars_repo_name: patrick-schwarz/HElib


text:
/* vim:set ts=3 sw=3 sts=3 et: */
/**
 * Copyright © 2008-2013 Last.fm Limited
 *
 * This file is part of libmoost.
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge,
 * publish, distribute, sublicense, and/or sell copies of the Software,
 * and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

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

#include <vector>
#include "../../include/moost/container/geo_map.hpp"

using namespace moost::container;

BOOST_AUTO_TEST_SUITE( geo_map_test )

struct Fixture
{
   geo_map<int> table;
   geo_map<int>::location query1;
   geo_map<int>::location query2;
   std::vector< geo_map<int>::value_type > results;

   Fixture()
   : query1(-20.3F, 40.9F),
     query2(-19.9F, 48.4F)
   {
      // add some test data
      table.insert(geo_map<int>::value_type(geo_map<int>::location(-20.1F, 45.3F), 1));
      table.insert(geo_map<int>::value_type(geo_map<int>::location(-20.1F, 48.3F), 2));
      table.insert(geo_map<int>::value_type(geo_map<int>::location(13.3F, -12.0F), 3));

      geo_map<int>::const_iterator it = table.begin();
      BOOST_CHECK(it != table.end());
   }
};

// what happens when we search something empty?
BOOST_FIXTURE_TEST_CASE( test_empty, Fixture )
{
   table.clear();
   table.find(query1, 100.0F, std::back_inserter(results));

   BOOST_CHECK(results.empty());
}

// find nothing!
BOOST_FIXTURE_TEST_CASE( test_not_found, Fixture )
{
   table.find(query1, 100.0F, std::back_inserter(results));

   BOOST_CHECK(results.empty());
}

// find something!
BOOST_FIXTURE_TEST_CASE( test_found, Fixture )
{
   table.find(query1, 460.0F, std::back_inserter(results));

   BOOST_REQUIRE_EQUAL(results.size(), 1);
   BOOST_CHECK(results[0].second == 1);
}

// find nothing! (bounds search)
BOOST_FIXTURE_TEST_CASE( test_not_found_bounding, Fixture )
{
   table.find(query1, query1, std::back_inserter(results));

   BOOST_CHECK(results.empty());
}

// find something! (bounds search)
BOOST_FIXTURE_TEST_CASE( test_found_bounding, Fixture )
{
   table.find(query1, query2, std::back_inserter(results));

   BOOST_REQUIRE_EQUAL(results.size(), 2);
   BOOST_CHECK(results[0].second == 1);
   BOOST_CHECK(results[1].second == 2);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: lastfm/libmoost

max_issues_repo_name: lastfm/libmoost

max_forks_repo_name: lastfm/libmoost


text:
/*
 *  Enhance v0.1 - Test suite
 *
 *  This file is a badly hacked together, unorganized collection of
 *  tests.
 *
 *  ----------------------------------------------------------
 *  Copyright (c) 2016 Johannes Gerer.
 *
 *  Distributed under the MIT License. (See accompanying file
 *  LICENSE.txt)
 *
 */
#include "../enhance.hpp"
#include "dependencies/catch.hpp"
#include "dependencies/prettyprint.hpp"

#include <iostream>
#include <vector>
#include <tuple>
#include <array>
#include <utility>
#include <string>
#include <iostream>
#include <set>
#include <unordered_set>

#ifndef ENHANCE_NO_SERIALIZE
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#endif // ENHANCE_NO_SERIALIZE

using namespace enhance;
using std::cout;
using std::endl;
using std::string;
using std::vector;
using std::tuple;

template<class X>
string toString(X&& x){
  std::ostringstream s;
  s << std::forward<X>(x);
  return s.str();
}

struct C{
    typedef bool result_t;

  template<class A>
  static bool init(A){
    return false;
  }

  template<class T>
  static bool apply(bool& result, const T& t)
  {
    result=true;
    return false;
  }
};

struct T : LessComparable<T>,
           GreaterEqualPWComparable<T>,
           EqualComparable<T>,
           UnequalComparable<T> {
  public:
  int i;

  T(int i):i(i){}

  int get_i() const
  {
    return i;
  }

  template<class C>
  void enhance(C& t) const{
    t([](const T& asd){ return 123;}, &T::i, &T::get_i);
    // t([](const T& asd){ return 123;});
  }

  // void enhance(Less<T>& t) const{
  //   // t(&T::i);
  //   t([](const T& asd){ return 123;});
  // }
};

struct U : LessPWComparable<U>, GreaterPWComparable<U>,
           EqualComparable<U> {
  int i;
  const int j;

  U(int i,int j):i(i),j(j){}

  template<class C>
  void enhance(C& t) const{
    REQUIRE(false); //should never be called
    t(&U::i, &U::j);
  }

  void enhance(Hash<U>& t) const{
    t(&U::i, &U::j);
  }

  template<class C>
  void enhance(Comparison<C,U>& t) const{
    t(&U::i, &U::j);
  }

  void enhance(Copy<U>& t){
    t(&U::i, constCast(&U::j),
      [](const U& q) -> int& { return const_cast<int&>(q.j);});
  }

  U& operator=(const U& y){
    return copy(*this, y);
  }

  U(const U& y) : j(999){
    copy(*this, y).callEnhance();
  }
};

TEST_CASE( "Assignment operators" ) {
  const U u1(3,8);
  U u2(4,9);
  U u3(u1);
  u2 = u1;

  REQUIRE(u2.i == 3);
  REQUIRE(u2 == u1);
  REQUIRE(u3 == u1);

  u2.i=10;

  REQUIRE(u3 == u1);
  REQUIRE(!(u2 == u1));
  REQUIRE(!(u3 == u2));

  REQUIRE(false == u1 < u2);
  REQUIRE(false == u2 > u2);
  REQUIRE(less(u1,u2) == true);
  REQUIRE(lessPW(u1,u2) == false);
}

struct P : Serializable<P>, EqualComparable<P> {
  int i, j;

  P(int i,int j):i(i),j(j){}

  template<class C>
  void enhance(C& t) const{
    t(&P::i, &P::j);
  }
};

struct H : EqualComparable<H> {
  int i, j;
  int& get_i(){
    return i;
  }

  const int& get_const_i() const{
    return i;
  }

  int get_j() const{
    return j;
  }

  H(int i,int j):i(i),j(j){}
  H(){}

  template<class C>
  void enhance(C& t) const{
    t(&H::get_const_i, &H::j, &H::get_j);
  }
};

template<class Archive>
void serialize(Archive& ar, H& a, const unsigned int version){
  enhance::serialize(a,ar)(&H::j, &H::get_i);
}

typedef UnaryCombiner<C, T> asd;

ENHANCE_STD_HASH(T)

TEST_CASE( "Some hashing and comparing" ) {
  T a={9};
  const T a2={19};
  asd b(a);

  auto r = (b(&T::i));

  std::set<U,Greater<P>::Functor> st;

  std::unordered_set<U,Hash<U>::Functor> mt={U(234,21)};

  std::unordered_set<T> mt2={T{321}};

  REQUIRE ( Hash<T>::Functor()(a) == std::hash<T>()(a) );

  std::set<U,Less<U>::Functor> mt3;

  REQUIRE(r == true);
  REQUIRE(1 == 1);
  REQUIRE(less(a2,a)(&T::i) == false);
  REQUIRE(less(a2,a) == false);
  REQUIRE(less(a2,a) == a2 < a);
  REQUIRE(less(a,a2) == a < a2);
  REQUIRE(equal(a,a2) == false);
  REQUIRE(unequal(a,a2) == false);
  REQUIRE(unequal(a,a2) == (a!=a2));
  REQUIRE(unequal(a,a2)(&T::i) == true);
  REQUIRE(less(a,a2) == true);
  REQUIRE(lessPW(a2,a) == false);
  REQUIRE(lessPW(a,a2) == false);
  REQUIRE(greater(a2,a)(&T::i) == true);
  REQUIRE(greater(a2,a) == true);
  REQUIRE(greaterEqualPW(a2,a) == (a2 >= a));

#ifndef ENHANCE_NO_SERIALIZE
  {
    std::stringstream ss;
    P p(123,789), q(2,45);

    boost::archive::text_oarchive oa(ss);
    oa << p;

    boost::archive::text_iarchive ia(ss);
    ia >> q;

    REQUIRE(p == q);
  }

  {
    std::stringstream ss;
    H p(123,789), q;
    boost::archive::text_oarchive oa(ss);
    oa << p;

    boost::archive::text_iarchive ia(ss);
    ia >> q;

    REQUIRE(p == q);
  }
#endif // ENHANCE_NO_SERIALIZE
}

struct Q : EqualComparable<Q>, Serializable<Q> {
  int i, j;
  const int k;
  int get_i() const{
    return i;
  }

  int& set_i(){
    return i;
  }

  Q(int i,int j, int k):i(i),j(j), k(k){}
  Q():k(149){}

  template<class Archive>
  void enhance(Save<Archive, Q>& t) const{
    t(&Q::get_i, &Q::j, &Q::k);
  }

  template<class Archive>
  void enhance(Load<Archive, Q>& t) const{
    t(&Q::set_i, &Q::j, constCast(&Q::k) );
  }

  template<class C>
  void enhance(C& t) const{
    t(&Q::get_i, &Q::j, &Q::k );
  }
};

#ifndef ENHANCE_NO_SERIALIZE
TEST_CASE( "Serialize" ) {
  std::stringstream ss;
  Q p(123,789,3), q;
  boost::archive::text_oarchive oa(ss);
  oa << p;

  boost::archive::text_iarchive ia(ss);
  ia >> q;

  REQUIRE(p == q);

}
#endif // ENHANCE_NO_SERIALIZE

struct K : LessPWComparable<K>, GreaterPWComparable<K> {
  int i;
  int* j;

  const int* get_i() const{
    return &i;
  }

  K(int i,int j):i(i),j(new int(j)){}

  template<class C>
  void enhance(C& t) const{
    t(&K::i, dereference(&K::get_i), dereference(&K::j));
  }
};

TEST_CASE( "Dereference" ) {
  REQUIRE(K(10,9) < K(11,12));
  REQUIRE(false == K(10,12) < K(11,12));
  REQUIRE(true  == lessPW(K(10,9),K(11,12)));
  K a(10,9), b(11,12);
  REQUIRE( (&a.i < &b.i) == lessPW(a,b)(&K::get_i));
}

struct W : LessPWComparable<W>, GreaterPWComparable<W>,
           Insertable<'{', ',', ' ','}',W> {
  int i;
  int* j;
  int k[3];
  vector<int> l;

  const int* get_i() const{
    return &i;
  }

  W(int i,int j)
    :i(i)
    ,j(new int(j))
    ,k{9,5,1}
    ,l({0,1,0}){
  }

  template<class C>
  void enhance(C& t) const{
    t(&W::i, dereference(&W::get_i), dereference(&W::j),
      range(&W::k,[](const W& w){ return w.k+3;})
      , range(begin(&W::l),end(&W::l))
      ,container(&W::l)
      );
  }
};

TEST_CASE( "pretty print" ) {
  W k(843,901);
  vector<int> v={1,4,5};
  tuple<vector<int>,vector<int>,int, string> t{v,v,4, "asd"};
  // cout << v << endl<< t << endl;

  std::ostringstream os, os2;
  insertion<'<', ';', ' ','>'>(k, os).callEnhance();
  REQUIRE(os.str() == "<843; 843; 901; <9; 5; 1>; <0; 1; 0>; <0; 1; 0>>");
  // cout<<os.str()<<endl;

  os2 << k;
  REQUIRE(os2.str() == "{843, 843, 901, {9, 5, 1}, {0, 1, 0}, {0, 1, 0}}");
  // cout<<os2.str()<<endl;
}

//##########   Readme / Basic Usage   #################

struct Point2D : Subtractable<Point2D>,
                   Addible<Point2D>,
                   ScalarDividable<int, Point2D>,
                   ScalarMultiplicable<int, Point2D>,
                   WithScalarProduct<int, Point2D>,
                   Insertable<'[',',',' ',']',Point2D>,
                   EqualComparable<Point2D>,
                   LessComparable<Point2D>
{
  int x,y;

  Point2D(int x, int y):x(x), y(y) {}

  template<class C>
  void enhance(C& t) const{
    t(&Point2D::x, &Point2D::y);
  }

  ENHANCE_COPY_ASSIGMENT(, Point2D)

  ENHANCE_COPY_CONSTRUCTOR(const, Point2D)

};

TEST_CASE( "Basic Usage", "[Readme]" ) {
  Point2D v{2,3}, w{2,3}, q{20,30};
  std::set<Point2D> points = {Point2D{4,5}, Point2D{10,0}, v, w, q};
  // cout<< std::boolalpha << (v < w )<< endl;
  REQUIRE( v < w );
  const Point2D k = v;
  Point2D j(k);
  REQUIRE(k == v);
  REQUIRE(k == j);
  REQUIRE(v == w);
  v *= 10;
  REQUIRE(v == q);
  v /= 10;
  REQUIRE(v == w);
  REQUIRE(v * q == 130);
  REQUIRE((v-= w) == Point2D(0,0));
  REQUIRE((v+= q) == q);
}

struct Vector : Insertable<'<',' ',' ','>',Vector,false>{
  int data[3];

  Vector():data{4,9,2}{}

  template<class C> void enhance(C& c) const{
    c(range(&Vector::data,
            [](const Vector& v){ return v.data+3;}));
  }
};

TEST_CASE( "5.3.1 iterators and containers", "[Readme]" ) {
  // cout<< Vector()<<endl;
  REQUIRE(toString(Vector()) == "<4  9  2>");
}

template<class R>
const int& function2(const R& r){
   return r.k;
}

struct functor1{
  int i;
  template<class R>
  int operator()(const R& r){
    return r.k + i;
  }
};

struct R;

const int& function(const R& r);

struct R2 : GreaterEqualPWComparable<R2>,
            Insertable<'{', ',', ' ','}',R2> {
  std::tuple<int,double,char> m;
  R2() : m(std::make_tuple(42,1.1,'g')) {}

  template<class C>
  void enhance(C& c) const{
    c(range<1,2>(&R2::m),
      range<>(&R2::m));
  }
};

struct R : LessPWComparable<R>,
           Insertable<'{', ',', ' ','}',R> {
  std::array<int,2> l;
  std::tuple<int,double> m;
  int k;

  R(std::array<int,2> l, std::tuple<int,double> m)
    :l(l), m(m),k(939){}

  template<class C>
  void enhance(C& t) const{
    t([](const R& p){return std::get<0>(p.m);},
      [](const R& p){return std::get<1>(p.m);},
      range<1,2>(&R::m),
      range<>(&R::m),
      container(&R::l),
      &R::l,
      dereference(begin(&R::l)),
      functor1({3}),
      function,
      function2<R>
      );
  }
};

const int& function(const R& r){
   return r.k;
}

TEST_CASE( "Tuples and Arrays, and function and functor accessors" ) {
  R l(std::array<int,2>{{4,9}}, std::tuple<int,double>(6,1.2));
  std::ostringstream os;
  os<<l;
  // cout<<(size_t(-1))<<endl;
  REQUIRE(os.str() == "{6, 1.2, {1.2}, {6, 1.2}, {4, 9}, [4, 9], 4, 942, 939, 939}");
  // cout<<os.str()<<endl;
  REQUIRE( toString(R2()) == "{{1.1}, {42, 1.1, g}}");
  REQUIRE( R2() >= R2() );
  R2 a, b;
  std::get<1>(a.m) = 10;
  REQUIRE( less(b,a)(range<>(&R2::m)) );
  REQUIRE( ! lessPW(b,a)(range<>(&R2::m)) );
  REQUIRE( lessPW(b,a)(range<1,2>(&R2::m)) );
  // cout << R2() << endl;
}

struct R3 : Insertable<'{', ',', ' ','}',R3> {
  std::shared_ptr<int> i;
  int* j;

  R3() : i(std::make_shared<int>(3)), j(new int(4)) {}

  template<class C> void enhance(C& c) const{
    c(dereference(&R3::i), dereference(&R3::j));
  }
};

TEST_CASE( "Dereference Documentation" ) {
  // insertion<'[',',',' ',']'>(R3(), cout)(&R3::i);
  REQUIRE( toString(R3()) == "{3, 4}");
}

TEST_CASE( "arithmetic" ) {
  typedef std::pair<int,double> T;
  T p(1,4.4);
  addition(p, {2,5.5})(&T::first, &T::second);
  // cout<< p << endl;
  // Vector addition

  // ScalarMultiply<int, Point2D>::Functor()(v); not possible
  Point2D v{2,3}, w{2,3}, q{20,30};
  REQUIRE( ( ScalarProduct<double,Point2D>::Functor()(v,q) ) == 130 );
  const int k = 3;
  scalarDivide(v, k).callEnhance();
  REQUIRE(v == Point2D( 0, 1));
  Subtraction<Point2D>::Functor()(v, w);
  REQUIRE(v == Point2D( -2, -2));
}

struct CA {
  int i, j;

  CA(int i, int j): i(i), j(j) {}

  template<class C> void enhance(C& c) const{
    c(&CA::i);
  }

  ENHANCE_COPY_ASSIGMENT(,CA)

  ENHANCE_COPY_CONSTRUCTOR(const, CA)
};

TEST_CASE( "copy assignment" ) {
  CA p1(4,12);
  CA const p2(p1);
  CA p3 = p2;
  REQUIRE( equal(p1, p3)(&CA::i) ) ;
  REQUIRE( unequal(p1, p3)(&CA::j) ) ;
}

struct Person : EqualComparable<Person> {
  string name;
  uint age;

  Person(string name, uint age): name(name), age(age) {}

  template<class C> void enhance(C& c) const{
    c(&Person::name, &Person::age);
  }
};

ENHANCE_STD_HASH(Person)

TEST_CASE( "hash" ) {
  Person p1{"Frank", 21}, p2{"Frank", 21}, p3{"Frank", 22};

  std::unordered_set<Person> mt2{p1, p2, p3};

  REQUIRE( mt2.size() == 2);

  REQUIRE( hash(p1) == hash(p2) );
  REQUIRE( hash(p1) == std::hash<Person>()(p2) );
  REQUIRE( hash(p1) != hash(p3) );
  REQUIRE( hash(p1)(&Person::name) == hash(p3)(&Person::name) );
}

max_stars_repo_name: johannesgerer/enhance

max_issues_repo_name: johannesgerer/enhance

max_forks_repo_name: johannesgerer/enhance


text:
//  Copyright (c) 2007-2012 Hartmut Kaiser
//
//  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)

#if !defined(HPX_FILESYSTEM_COMPATIBILITY_JAN_28_2010_0833PM)
#define HPX_FILESYSTEM_COMPATIBILITY_JAN_28_2010_0833PM

#include <string>

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

namespace hpx { namespace util
{
#if BOOST_VERSION >= 105000
#define HPX_FILESYSTEM3 filesystem
#else
#define HPX_FILESYSTEM3 filesystem3
#endif

///////////////////////////////////////////////////////////////////////////////
// filesystem wrappers allowing to handle different Boost versions
#if !defined(BOOST_FILESYSTEM_NO_DEPRECATED)
// interface wrappers for older Boost versions
    inline boost::filesystem::path initial_path()
    {
        return boost::filesystem::initial_path();
    }

    inline boost::filesystem::path current_path()
    {
        return boost::filesystem::current_path();
    }

    inline boost::filesystem::path create_path(std::string const& p)
    {
        char back = p[p.length()-1];
#if BOOST_FILESYSTEM_VERSION >= 3
        return boost::filesystem::path(back == ':' ? p.substr(0, p.size()-1) : p);
#else
        return boost::filesystem::path(back == ':' ? p.substr(0, p.size()-1) : p, boost::filesystem::native);
#endif
    }

    inline std::string leaf(boost::filesystem::path const& p)
    {
#if BOOST_FILESYSTEM_VERSION >= 3
        return p.leaf().string();
#else
        return p.leaf();
#endif
    }

    inline boost::filesystem::path branch_path(boost::filesystem::path const& p)
    {
        return p.branch_path();
    }

    inline boost::filesystem::path normalize(boost::filesystem::path& p)
    {
        return p.normalize();
    }

    inline std::string native_file_string(boost::filesystem::path const& p)
    {
#if BOOST_FILESYSTEM_VERSION >= 3
        return p.string();
#else
        return p.native_file_string();
#endif
    }

    inline boost::filesystem::path complete_path(
        boost::filesystem::path const& p)
    {
#if BOOST_FILESYSTEM_VERSION >= 3
        return boost::HPX_FILESYSTEM3::complete(p, initial_path());
#else
        return boost::filesystem::complete(p, initial_path());
#endif
    }

    inline boost::filesystem::path complete_path(
        boost::filesystem::path const& p, boost::filesystem::path const& base)
    {
#if BOOST_FILESYSTEM_VERSION >= 3
        return boost::HPX_FILESYSTEM3::complete(p, base);
#else
        return boost::filesystem::complete(p, base);
#endif
    }

#else

// interface wrappers if deprecated functions do not exist
    inline boost::filesystem::path initial_path()
    {
#if BOOST_FILESYSTEM_VERSION >= 3
        return boost::HPX_FILESYSTEM3::detail::initial_path();
#else
        return boost::filesystem::initial_path<boost::filesystem::path>();
#endif
    }

    inline boost::filesystem::path current_path()
    {
#if BOOST_FILESYSTEM_VERSION >= 3
        return boost::HPX_FILESYSTEM3::current_path();
#else
        return boost::filesystem::current_path<boost::filesystem::path>();
#endif
    }

    template <typename String>
    inline boost::filesystem::path create_path(String const& p)
    {
        return boost::filesystem::path(p);
    }

    inline std::string leaf(boost::filesystem::path const& p)
    {
#if BOOST_FILESYSTEM_VERSION >= 3
        return p.filename().string();
#else
        return p.filename();
#endif
    }

    inline boost::filesystem::path branch_path(boost::filesystem::path const& p)
    {
        return p.parent_path();
    }

    inline boost::filesystem::path normalize(boost::filesystem::path& p)
    {
        return p; // function doesn't exist anymore
    }

    inline std::string native_file_string(boost::filesystem::path const& p)
    {
        return p.string();
    }

    inline boost::filesystem::path complete_path(
        boost::filesystem::path const& p)
    {
#if BOOST_FILESYSTEM_VERSION >= 3
        return boost::filesystem::absolute(p, initial_path());
#else
        return boost::filesystem::complete(p, initial_path());
#endif
    }

    inline boost::filesystem::path complete_path(
        boost::filesystem::path const& p, boost::filesystem::path const& base)
    {
#if BOOST_FILESYSTEM_VERSION >= 3
        return boost::filesystem::absolute(p, base);
#else
        return boost::filesystem::complete(p, base);
#endif
    }
#endif

#if BOOST_VERSION <= 104900 || BOOST_FILESYSTEM_VERSION < 3
    inline boost::filesystem::path resolve(
        boost::filesystem::path const& p,
        boost::filesystem::path const& base = current_path())
    {
        boost::filesystem::path abspath = boost::filesystem::absolute(p, base);
        boost::filesystem::path result;
        for(boost::filesystem::path::iterator it = abspath.begin();
            it != abspath.end(); ++it)
        {
            if (*it == "..")
            {
                // /a/b/.. is not necessarily /a if b is a symbolic link
                if (boost::filesystem::is_symlink(result))
                    result /= *it;

                // /a/b/../.. is not /a/b/.. under most circumstances
                // We can end up with ..s in our result because of symbolic links
                else if (result.filename() == "..")
                    result /= *it;

                // Otherwise it should be safe to resolve the parent
                else
                    result = result.parent_path();
            }
            else if (*it == ".")
            {
                // Ignore
            }
            else
            {
                // Just cat other path entries
                result /= *it;
            }
        }
        return result;
    }
#endif

    inline boost::filesystem::path canonical_path(
        boost::filesystem::path const& p, boost::system::error_code& ec)
    {
#if BOOST_VERSION > 104900 && BOOST_FILESYSTEM_VERSION >= 3
        return boost::filesystem::canonical(p, initial_path(), ec);
#else
        return resolve(p, initial_path());
#endif
    }

#undef HPX_FILESYSTEM3
}}

#endif

ext: hpp

max_stars_repo_name: akemp/hpx

max_issues_repo_name: akemp/hpx

max_forks_repo_name: akemp/hpx


text:
#ifndef MATH_QUAT_HPP
#define MATH_QUAT_HPP

#include <boost/operators.hpp>

namespace Math {

	template<typename R = float>
	struct quat: public boost::operators<quat<R>> {
		R w, x, y, z;

		/* Unary operators */

		/** Multiplicative inverse */
		quat<R> operator!(void) const;
		/** Additive inverse */
		quat<R> operator-(void) const;
		/** Conjugate */
		quat<R> operator~(void) const;
		/** Cast operator, as Euclidean norm */
		explicit operator R(void) const;
		/** Squared Euclidean norm */
		R operator()(void) const;
		/** Simple promotion */
		explicit operator dual<R>(void) const;

		/** Distributes equality test */
		bool operator==(quat<R> const& rhs) const;
		/** Apply (lhs * rhs * ~lhs) */
		quat<R> operator()(quat<R> const& rhs) const;
		/** Apply (lhs * rhs * ~lhs) */
		dual<R> operator()(dual<R> const& rhs) const;

		/*quat<R> operator+(quat<R> const& rhs) const;
		quat<R> operator-(quat<R> const& rhs) const;
		quat<R> operator/(quat<R> const& rhs) const;
		quat<R> operator/(R const& rhs) const;*/

		quat<R>& operator+=(quat<R> const& rhs);
		quat<R>& operator-=(quat<R> const& rhs);
		quat<R>& operator*=(R const& rhs);
		quat<R>& operator*=(quat<R> const& rhs);
		quat<R>& operator/=(R const& rhs);
		quat<R>& operator/=(quat<R> const& rhs);

		quat(void) = default;
		quat(const R w, const R x = 0, const R y = 0, const R z = 0):
			w(w), x(x), y(y), z(z) {}
	};
	template<typename R>
	quat<R> quat<R>::operator-(void) const {
		return {-w,-x,-y,-z};
	}
	template<typename R>
	quat<R> quat<R>::operator!(void) const {
		return ~(*this)/((*this)());
	}
	template<typename R>
	quat<R> quat<R>::operator~(void) const {
		return {w,-x,-y,-z};
	}
	template<typename R>
	quat<R>::operator R(void) const {
		return sqrt((*this)());
	}
	template<typename R>
	R quat<R>::operator()(void) const {
		return w*w + x*x + y*y + z*z;
	}
	template<typename R>
	quat<R>::operator dual<R>(void) const {
		return {*this, 0};
	}

	template<typename R>
	bool quat<R>::operator==(quat<R> const& rhs) const {
		return w == rhs.w && x == rhs.x
			&& y == rhs.y && z == rhs.z;
	}
	template<typename R>
	quat<R> quat<R>::operator()(quat<R> const& rhs) const {
		return *this * rhs * ~*this;
	}

	template<typename R>
	quat<R>& quat<R>::operator+=(quat<R> const& rhs) {
		w += rhs.w; x += rhs.x; y += rhs.y; z += rhs.z;
		return *this;
	}
	template<typename R>
	quat<R>& quat<R>::operator-=(quat<R> const& rhs) {
		w -= rhs.w; x -= rhs.x; y -= rhs.y; z -= rhs.z;
		return *this;
	}
	template<typename R>
	quat<R>& quat<R>::operator*=(R const& rhs) {
		w *= rhs; x *= rhs;
		y *= rhs; z *= rhs;
		return *this;
	}
	template<typename R>
	quat<R>& quat<R>::operator*=(quat<R> const& r) {
		R lw = w, lx = x, ly = y, lz = z,
		  rw = r.w, rx = r.x, ry = r.y, rz = r.z;
		w = lw*rw - lx*rx - ly*ry - lz*rz;
		x = lw*rx + lx*rw + ly*rz - lz*ry;
		y = lw*ry - lx*rz + ly*rw + lz*rx;
		z = lw*rz + lx*ry - ly*rx + lz*rw;
		return *this;
	}
}

#endif

max_stars_repo_name: XPCX/CitaDel

max_issues_repo_name: XPCX/CitaDel

max_forks_repo_name: XPCX/CitaDel


text:
#include "SVMPixelClassifier.h"
#include <libsvm/svm.h>
#include "log4cxx/logger.h"
#include <boost/filesystem.hpp>
#include <iostream>

void SVMPixelClassifier::load(const std::string dir)
{
	boost::filesystem::path path = boost::filesystem::path(dir) / "svm.model";
	svm_model *m;
	if((m = svm_load_model(path.native().c_str())) == 0)
		throw std::runtime_error("Cannot load the SVM from " + path.native());
	else
		model = boost::shared_ptr<struct svm_model>(m, svm_free_model_content);

	m_NumberOfClasses = svm_get_nr_class(model.get());
	m_InputSize = 0;

	if(svm_check_probability_model(model.get()) == 0)
		throw std::runtime_error("Model does not support probabiliy estimates.");
}

void SVMPixelClassifier::save(const std::string dir)
{
	boost::filesystem::path path = boost::filesystem::path(dir) / "svm.model";

	if(0 != svm_save_model(path.native().c_str(), model.get()))
	{
		throw std::runtime_error("Cannot save the SVM in " + path.native());
	}
}

std::vector<float> SVMPixelClassifier::classify(const std::vector< InputValueType > &input) const
{
	double estimates[m_NumberOfClasses];
	struct svm_node x[input.size()+1];
	for(int i = 0; i < input.size(); ++i)
	{
		x[i].index = i+1;
		x[i].value = input[i];
	}
	x[input.size()].index = -1;

	svm_predict_probability(model.get(), x, estimates);

	std::vector<float> output(m_NumberOfClasses, 0);
	for(int i = 0; i < m_NumberOfClasses; ++i)
	{
		output[i] = (float)estimates[i];
	}

	return output;
}

bool SVMPixelClassifier::train(LibSVMClassificationDataset *trainingSet)
{
	log4cxx::LoggerPtr logger(log4cxx::Logger::getLogger("main"));

	struct svm_parameter param;
	param.svm_type = C_SVC;
	param.kernel_type = RBF;
	param.degree = 3;
	param.gamma = 1.0 / (trainingSet->getInputSize() + 1);        // 1/num_features
	param.coef0 = 0;
	param.nu = 0.5;
	param.cache_size = 100;
	param.C = 1;
	param.eps = 1e-3;
	param.p = 0.1;
	param.shrinking = 1;
	param.probability = 1; // Compute probabilities
	param.nr_weight = 0;
	param.weight_label = NULL;
	param.weight = NULL;

	const char *error_msg;
	error_msg = svm_check_parameter(trainingSet->getProblem(), &param);

	if(error_msg) {
		LOG4CXX_FATAL(logger, error_msg);
		return false;
	}
	svm_set_print_string_function(NULL);

	struct svm_model *m = svm_train(trainingSet->getProblem(), &param);
	boost::filesystem::path ph = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path();
	if(0 != svm_save_model(ph.native().c_str(), m))
		throw std::runtime_error("Cannot temporary save the SVM in " + ph.native());

	svm_free_and_destroy_model(&m);

	if((m = svm_load_model(ph.native().c_str())) == 0)
		throw std::runtime_error("Cannot load the temporary SVM from " + ph.native());
	else
		model = boost::shared_ptr<struct svm_model>(m, svm_free_model_content);

	boost::filesystem::remove(ph);

	//model = boost::shared_ptr<struct svm_model>(svm_train(trainingSet->getProblem(), &param), svm_free_model_content);

	m_NumberOfClasses = svm_get_nr_class(model.get());

	return true;
}

max_stars_repo_name: Sigill/isgcr

max_issues_repo_name: Sigill/isgcr

max_forks_repo_name: Sigill/isgcr


text:
// Copyright (c) 2016 Klemens D. Morgenstern
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#define BOOST_TEST_MAIN
#define BOOST_TEST_IGNORE_SIGCHLD
#include <boost/test/included/unit_test.hpp>

#include <boost/process/error.hpp>
#include <boost/process/io.hpp>
#include <boost/process/async.hpp>
#include <boost/process/child.hpp>
#include <boost/process/async_system.hpp>

#include <string>
#include <boost/asio/io_context.hpp>
#include <boost/asio/spawn.hpp>
#include <boost/asio/coroutine.hpp>
#include <boost/asio/use_future.hpp>
#include <boost/asio/yield.hpp>

#include <vector>
#include <array>

namespace bp = boost::process;
BOOST_AUTO_TEST_SUITE( async );

BOOST_AUTO_TEST_CASE(future, *boost::unit_test::timeout(15))
{
    using boost::unit_test::framework::master_test_suite;

    boost::asio::io_context ios;

    std::future<int> fut = bp::async_system(
                              ios, boost::asio::use_future,
                              master_test_suite().argv[1],
                              "test", "--exit-code", "42");

    ios.run();

    int exit_code = 0;
    BOOST_CHECK_NO_THROW(exit_code = fut.get());

    BOOST_CHECK_EQUAL(exit_code, 42);
}

BOOST_AUTO_TEST_CASE(future_error, *boost::unit_test::timeout(15))
{
    using boost::unit_test::framework::master_test_suite;

    boost::asio::io_context ios;

    std::future<int> fut = bp::async_system(
                              ios, boost::asio::use_future,
                              "invalid-command");

    ios.run();

    int exit_code = 0;
    BOOST_CHECK_THROW(exit_code = fut.get(), boost::system::system_error);
}

BOOST_AUTO_TEST_SUITE_END();


text:
#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK

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

#include "Map/2d/RayToPixelMask.h"
#include "Map/2d/MapLimits.h"

namespace {

bool isEqual(const Eigen::Array2i & lhs, const Eigen::Array2i & rhs) {
    return ((lhs - rhs).matrix().lpNorm<1>() == 0);
}

}

BOOST_AUTO_TEST_CASE(EQUAL) {
    BOOST_CHECK(isEqual(Eigen::Array2i(1,3), Eigen::Array2i(1,3)) == true);
}

BOOST_AUTO_TEST_CASE(SingleCell) {
    const Eigen::Array2i & begin = {1, 1};
    const Eigen::Array2i & end = {1, 1};
    const int subPixelScale = 1;

    std::vector<Eigen::Array2i> ray = VISFS::Map::rayToPixelMask(begin, end, subPixelScale);
    BOOST_CHECK(isEqual(ray[0], begin) == true);
}

BOOST_AUTO_TEST_CASE(AxisAlginedX) {
    const Eigen::Array2i & begin = {1, 1};
    const Eigen::Array2i & end = {3, 1};
    const int subPixelScale = 1;
    std::vector<Eigen::Array2i> ray = VISFS::Map::rayToPixelMask(begin, end, subPixelScale);
    for (int i = 0; i < ray.size(); ++i) {
        BOOST_CHECK(isEqual(ray[i], Eigen::Array2i({(1+i), 1})));
    }
    ray.clear();
    ray = VISFS::Map::rayToPixelMask(end, begin, subPixelScale);
    for (int i = 0; i < ray.size(); ++i) {
        BOOST_CHECK(isEqual(ray[i], Eigen::Array2i({(1+i), 1})));
    }
}

BOOST_AUTO_TEST_CASE(AxisAlginedY) {
    const Eigen::Array2i & begin = {1, 1};
    const Eigen::Array2i & end = {1, 3};
    const int subPixelScale = 1;
    std::vector<Eigen::Array2i> ray = VISFS::Map::rayToPixelMask(begin, end, subPixelScale);
    for (int i = 0; i < ray.size(); ++i) {
        BOOST_CHECK(isEqual(ray[i], Eigen::Array2i({1, 1+i})));
    }
    ray.clear();
    ray = VISFS::Map::rayToPixelMask(end, begin, subPixelScale);
    for (int i = 0; i < ray.size(); ++i) {
        BOOST_CHECK(isEqual(ray[i], Eigen::Array2i({1, 1+i})));
    }
}

BOOST_AUTO_TEST_CASE(Digonal) {
    Eigen::Array2i begin = {1, 1};
    Eigen::Array2i end = {3, 3};
    const int subPixelScale = 1;
    std::vector<Eigen::Array2i> rayReference = std::vector<Eigen::Array2i>{
        Eigen::Array2i({1, 1}), Eigen::Array2i({2, 2}), Eigen::Array2i({3, 3})};
    std::vector<Eigen::Array2i> ray = VISFS::Map::rayToPixelMask(begin, end, subPixelScale);
    BOOST_REQUIRE(ray.size() == rayReference.size());
    for (int i = 0; i < ray.size(); ++i) {
        BOOST_CHECK(isEqual(ray[i], rayReference[i]));
    }
    ray.clear();
    ray = VISFS::Map::rayToPixelMask(end, begin, subPixelScale);
    BOOST_REQUIRE(ray.size() == rayReference.size());
    for (int i = 0; i < ray.size(); ++i) {
        BOOST_CHECK(isEqual(ray[i], rayReference[i]));
    }

    begin = Eigen::Array2i({1, 3});
    end = Eigen::Array2i({3, 1});
    rayReference = std::vector<Eigen::Array2i>{
        Eigen::Array2i({1, 3}), Eigen::Array2i({2, 2}), Eigen::Array2i({3, 1})};
    ray = VISFS::Map::rayToPixelMask(begin, end, subPixelScale);
    BOOST_REQUIRE(ray.size() == rayReference.size());
    for (int i = 0; i < ray.size(); ++i) {
        BOOST_CHECK(isEqual(ray[i], rayReference[i]));
    }
    ray = VISFS::Map::rayToPixelMask(end, begin, subPixelScale);
    BOOST_REQUIRE(ray.size() == rayReference.size());
    for (int i = 0; i < ray.size(); ++i) {
        BOOST_CHECK(isEqual(ray[i], rayReference[i]));
    }
}

BOOST_AUTO_TEST_CASE(SteepLine) {
    Eigen::Array2i begin = {1, 1};
    Eigen::Array2i end = {2, 5};
    const int subPixelScale = 1;
    std::vector<Eigen::Array2i> rayReference = std::vector<Eigen::Array2i>{
        Eigen::Array2i({1, 1}), Eigen::Array2i({1, 2}), Eigen::Array2i({1, 3}),
        Eigen::Array2i({2, 3}), Eigen::Array2i({2, 4}), Eigen::Array2i({2, 5})};
    std::vector<Eigen::Array2i> ray = VISFS::Map::rayToPixelMask(begin, end, subPixelScale);
    BOOST_REQUIRE(ray.size() == rayReference.size());
    for (int i = 0; i < ray.size(); ++i) {
        BOOST_CHECK(isEqual(ray[i], rayReference[i]));
    }
    begin = {1, 1};
    end = {2, 4};
    rayReference = std::vector<Eigen::Array2i>{
        Eigen::Array2i({1, 1}), Eigen::Array2i({1, 2}), Eigen::Array2i({2, 3}),
        Eigen::Array2i({2, 4})};
    ray = VISFS::Map::rayToPixelMask(begin, end, subPixelScale);
    BOOST_REQUIRE(ray.size() == rayReference.size());
    for (int i = 0; i < ray.size(); ++i) {
        BOOST_CHECK(isEqual(ray[i], rayReference[i]));
    }
}

BOOST_AUTO_TEST_CASE(FlatLine) {
    Eigen::Array2i begin = {1, 1};
    Eigen::Array2i end = {5, 2};
    const int subPixelScale = 1;
    std::vector<Eigen::Array2i> rayReference = std::vector<Eigen::Array2i>{
        Eigen::Array2i({1, 1}), Eigen::Array2i({2, 1}), Eigen::Array2i({3, 1}),
        Eigen::Array2i({3, 2}), Eigen::Array2i({4, 2}), Eigen::Array2i({5, 2})};
    std::vector<Eigen::Array2i> ray = VISFS::Map::rayToPixelMask(begin, end, subPixelScale);
    BOOST_REQUIRE(ray.size() == rayReference.size());
    for (int i = 0; i < ray.size(); ++i) {
        BOOST_CHECK(isEqual(ray[i], rayReference[i]));
    }
    begin = {1, 1};
    end = {4, 2};
    rayReference = std::vector<Eigen::Array2i>{
        Eigen::Array2i({1, 1}), Eigen::Array2i({2, 1}), Eigen::Array2i({3, 2}),
        Eigen::Array2i({4, 2})};
    ray = VISFS::Map::rayToPixelMask(begin, end, subPixelScale);
    BOOST_REQUIRE(ray.size() == rayReference.size());
    for (int i = 0; i < ray.size(); ++i) {
        BOOST_CHECK(isEqual(ray[i], rayReference[i]));
    }
}

BOOST_AUTO_TEST_CASE(MultiScaleAxisAlignedX) {
    int subPixelScale;
    const int numCellsX = 10;
    const int numCellsY = 10;
    double resolution = 0.1;
    Eigen::Vector2d max = {1.0, 1.0};
    std::vector<Eigen::Array2i> rayReference = std::vector<Eigen::Array2i>{
        Eigen::Array2i({9, 6}), Eigen::Array2i({9, 7}), Eigen::Array2i({9, 8}), Eigen::Array2i({9, 9})};
    for (subPixelScale = 1; subPixelScale < 10000; subPixelScale *= 2) {
        double superscaledResolution  = resolution / subPixelScale;
        VISFS::Map::MapLimits superScaledLimits(superscaledResolution, max,
            VISFS::Map::CellLimits(numCellsX * subPixelScale, numCellsY * subPixelScale));
        Eigen::Array2i begin = superScaledLimits.getCellIndex(Eigen::Vector2d({0.05, 0.05}));
        Eigen::Array2i end = superScaledLimits.getCellIndex(Eigen::Vector2d({0.35, 0.05}));
        std::vector<Eigen::Array2i> ray = VISFS::Map::rayToPixelMask(begin, end, subPixelScale);
        BOOST_REQUIRE(ray.size() == rayReference.size());
        for (int i = 0; i < ray.size(); ++i) {
            BOOST_CHECK(isEqual(ray[i], rayReference[i]));
            // Eigen::Vector2d center = superScaledLimits.getCellCenter(ray[i]);
            // std::cout << "center: " << center.transpose() << std::endl;
        }
    }
}

BOOST_AUTO_TEST_CASE(MultiScaleSkewedLine) {
    int subPixelScale;
    const int numCellsX = 1;
    const int numCellsY = 1;
    double resolution = 0.1;
    Eigen::Vector2d max = {1.0, 1.0};
    std::vector<Eigen::Array2i> rayReference = std::vector<Eigen::Array2i>{
        Eigen::Array2i({8, 7}), Eigen::Array2i({8, 8}), Eigen::Array2i({9, 8}), Eigen::Array2i({9, 9})};
    for (subPixelScale = 1; subPixelScale < 2; subPixelScale *= 2) {
        double superscaledResolution  = resolution / subPixelScale;
        VISFS::Map::MapLimits superScaledLimits(superscaledResolution, max,
            VISFS::Map::CellLimits(numCellsX * subPixelScale, numCellsY * subPixelScale));
        Eigen::Array2i begin = superScaledLimits.getCellIndex(Eigen::Vector2d({0.01, 0.09}));
        Eigen::Array2i end = superScaledLimits.getCellIndex(Eigen::Vector2d({0.21, 0.19}));
        std::vector<Eigen::Array2i> ray = VISFS::Map::rayToPixelMask(begin, end, subPixelScale);
        BOOST_REQUIRE(ray.size() == rayReference.size());
        for (int i = 0; i < ray.size(); ++i) {
            BOOST_CHECK(isEqual(ray[i], rayReference[i]));
        }
    }

    std::vector<Eigen::Array2i> rayReference2 = std::vector<Eigen::Array2i>{
        Eigen::Array2i({8, 7}), Eigen::Array2i({8, 8}), Eigen::Array2i({8, 9}), Eigen::Array2i({9, 9})};
    for (subPixelScale = 20; subPixelScale < 1000; subPixelScale *= 2) {
        double superscaledResolution  = resolution / subPixelScale;
        VISFS::Map::MapLimits superScaledLimits(superscaledResolution, max,
            VISFS::Map::CellLimits(numCellsX * subPixelScale, numCellsY * subPixelScale));
        Eigen::Array2i begin = superScaledLimits.getCellIndex(Eigen::Vector2d({0.01, 0.09}));
        Eigen::Array2i end = superScaledLimits.getCellIndex(Eigen::Vector2d({0.21, 0.19}));
        std::vector<Eigen::Array2i> ray = VISFS::Map::rayToPixelMask(begin, end, subPixelScale);
        BOOST_REQUIRE(ray.size() == rayReference2.size());
        for (int i = 0; i < ray.size(); ++i) {
            BOOST_CHECK(isEqual(ray[i], rayReference2[i]));
        }
    }
}

max_stars_repo_name: supersaiyajinggod/VISFS

max_issues_repo_name: supersaiyajinggod/VISFS

max_forks_repo_name: supersaiyajinggod/VISFS


text:
#include <iostream>
#include <ISOBMFF.hpp>
#include <algorithm>
#include <numeric>
#include <cassert>
#include <boost/iostreams/stream.hpp>

int main() {

    ISOBMFF::Parser parser;

    parser.Parse("tests/output.m4s");

    std::cout << *parser.GetFile() << std::endl;
    return 0;
}

max_issues_repo_name: milos-pesic-sc/ISOBMFF

max_forks_repo_name: milos-pesic-sc/ISOBMFF


text:
//  Copyright (c) 2013-2015 Hartmut Kaiser
//  Copyright (c) 2013 Thomas Heller
//
//  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)

// Bidirectional network bandwidth test

#include <hpx/hpx.hpp>
#include <hpx/include/iostreams.hpp>
#include <hpx/include/serialization.hpp>
#include <hpx/include/parallel_for_each.hpp>

#include <boost/range/irange.hpp>

#include <cstddef>
#include <cstdint>
#include <vector>

///////////////////////////////////////////////////////////////////////////////
#define LOOP_SMALL  100
#define WINDOW_SIZE_SMALL  2048
#define SKIP_SMALL  10

#define LOOP_LARGE  20
#define WINDOW_SIZE_LARGE  2048
#define SKIP_LARGE  2

#define LARGE_MESSAGE_SIZE  8192

#define MAX_MSG_SIZE (1<<22)
#define MAX_ALIGNMENT 65536
#define SEND_BUFSIZE (MAX_MSG_SIZE + MAX_ALIGNMENT)

char send_buffer[SEND_BUFSIZE];

///////////////////////////////////////////////////////////////////////////////
void isend(hpx::serialization::serialize_buffer<char> const& receive_buffer) {}
HPX_PLAIN_ACTION(isend);

///////////////////////////////////////////////////////////////////////////////
hpx::future<void>
send_async(hpx::naming::id_type dest, std::size_t size, std::size_t window_size)
{
    typedef hpx::serialization::serialize_buffer<char> buffer_type;

    using hpx::parallel::for_each;
    using hpx::parallel::execution::par;
    using hpx::parallel::execution::task;

    std::size_t const start = 0;

    auto range = boost::irange(start, window_size);
    return for_each(
        par(task), boost::begin(range), boost::end(range),
        [=](std::uint64_t j)
        {
            // Note: The original benchmark uses MPI_Isend which does not
            //       create a copy of the passed buffer.
            isend_action send;
            send(dest, buffer_type(send_buffer, size, buffer_type::reference));
        });
}

///////////////////////////////////////////////////////////////////////////////
hpx::serialization::serialize_buffer<char> irecv(std::size_t size)
{
    typedef hpx::serialization::serialize_buffer<char> buffer_type;
    return buffer_type(send_buffer, size, buffer_type::reference);
}
HPX_PLAIN_ACTION(irecv);

///////////////////////////////////////////////////////////////////////////////
hpx::future<void>
recv_async(hpx::naming::id_type dest, std::size_t size, std::size_t window_size)
{
    typedef hpx::serialization::serialize_buffer<char> buffer_type;

    using hpx::parallel::for_each;
    using hpx::parallel::execution::par;
    using hpx::parallel::execution::task;

    std::size_t const start = 0;

    auto range = boost::irange(start, window_size);
    return for_each(
        par(task), boost::begin(range), boost::end(range),
        [=](std::uint64_t j)
        {
            irecv_action recv;
            recv(dest, size);
        });
}

///////////////////////////////////////////////////////////////////////////////
void print_header()
{
    hpx::cout << "# OSU HPX Bi-Directional Test\n"
              << "# Size    Bandwidth (MB/s)"
              << std::endl;
}

///////////////////////////////////////////////////////////////////////////////
void run_benchmark(boost::program_options::variables_map & vm)
{
    // use the first remote locality to bounce messages, if possible
    hpx::id_type here = hpx::find_here();

    hpx::id_type there = here;
    std::vector<hpx::id_type> localities = hpx::find_remote_localities();
    if (!localities.empty())
        there = localities[0];

    // perform actual measurements
    for (std::size_t size = 1; size <= MAX_MSG_SIZE; size *= 2)
    {
        std::size_t loop = LOOP_SMALL;
        std::size_t skip = SKIP_SMALL;
        std::size_t window_size = WINDOW_SIZE_SMALL;

        if (size > LARGE_MESSAGE_SIZE) {
            loop = LOOP_LARGE;
            skip = SKIP_LARGE;
            window_size = WINDOW_SIZE_LARGE;
        }

        hpx::util::high_resolution_timer t;

        for(std::size_t i = 0; i < loop + skip; ++i)
        {
            if (i == skip)      // don't measure during warm-up phase
                t.restart();

            hpx::future<void> recv =
                hpx::async(recv_async, there, size, window_size);

            send_async(there, size, window_size);

            recv.wait();
        }

        double bw = (size / 1e6 * loop * window_size * 2) / t.elapsed();

        hpx::cout << std::left << std::setw(10) << size << bw << std::endl;
    }
}

max_stars_repo_name: STEllAR-GROUP/hpxML

max_issues_repo_name: STEllAR-GROUP/hpxML

max_forks_repo_name: STEllAR-GROUP/hpxML


text:
/*
    BSD 3-Clause License
    Copyright (c) 2018, Roboy
            All rights reserved.
    Redistribution and use in source and binary forms, with or without
            modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright notice, this
    list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.
    * Neither the name of the copyright holder nor the names of its
    contributors may be used to endorse or promote products derived from
    this software without specific prior written permission.
    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
    AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
            IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
            FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
            DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
            SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
            CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
    OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    author: Simon Trendel ( st@gi.ai ), 2018
    description: Cable and Viapoint classes for CARDSflow robots
*/

#pragma once

#include <Eigen/Core>
#include <Eigen/Dense>
#include <vector>

using namespace std;
using namespace Eigen;

namespace cardsflow {
    namespace kindyn {

        struct ViaPoint {
            /**
             *
             * @param link_name
             * @param local_coordinates
             * @param fixed_to_world
             */
            ViaPoint(string link_name, Vector3d &local_coordinates, bool fixed_to_world = false) :
                    link_name(link_name), local_coordinates(local_coordinates),
                    global_coordinates(local_coordinates),fixed_to_world(fixed_to_world) {};
            string link_name; /// the name of the link the viapoint belongs to
            int link_index; /// the index of the link the viapoint belongs to wrt. the robot model
            bool fixed_to_world; /// indicates if the viapoint if moving with the link or is fixed to the world
            Vector3d local_coordinates; /// the local coordinates in the link frame
            Vector3d global_coordinates; /// the globale coordinates of the viapoint
        };

        typedef boost::shared_ptr<ViaPoint> ViaPointPtr;

        struct Cable {
            string name; /// name of the cable
            vector<ViaPointPtr> viaPoints; /// viapoints it consists of
        };

    }
}

max_stars_repo_name: NexusReflex/VRpuppet

max_issues_repo_name: NexusReflex/VRpuppet

max_forks_repo_name: NexusReflex/VRpuppet


text:
/* Copyright 2016 Guillem Pascual */

#pragma once

#include "map/offset.hpp"
#include "debug/debug.hpp"

#include <array>
#include <list>
#include <utility>
#include <unordered_map>
#include <vector>

#include "defs/common.hpp"

INCL_NOWARN
#include "defs/intrusive.hpp"
#include <boost/intrusive_ptr.hpp>
INCL_WARN

class Cell;
class Cluster;
struct ClusterCenter;
class Map;
class MapAwareEntity;
class Packet;
template <int E, int D>
class RadialQuadTree;

enum class RequestType
{
    SPAWN,
    DESPAWN
};

struct Request
{
    MapAwareEntity* who;
    RequestType type;
};

class Cell
{
    friend class Map;
    friend class Cluster;

    static constexpr const int MaxQuadrantEntities = 5;
    static constexpr const int MaxQuadtreeDepth = 10;

    struct StallInformation
    {
        bool isRegistered;
        bool isOnCooldown;
        uint64_t remaining;
    };

public:
    explicit Cell(Map* map, const Offset& offset);
    virtual ~Cell();

    inline const uint64_t hash() const { return _offset.hash(); }
    inline const Offset& offset() const { return _offset; }
    inline Map* map() const { return _map; }
    inline RadialQuadTree<MaxQuadrantEntities, MaxQuadtreeDepth>* quadtree() { return _quadTree; }

    virtual void update(uint64_t elapsed);
    virtual void physics(uint64_t elapsed);
    virtual void cleanup(uint64_t elapsed);

    inline const std::unordered_map<uint64_t /*id*/, MapAwareEntity*>& entities() { return _entities; }

    void addEntity(MapAwareEntity* entity);
    void removeEntity(MapAwareEntity* entity);

    void request(MapAwareEntity* who, RequestType type);
    void broadcast(boost::intrusive_ptr<Packet> packet);
    void clearQueues();

    std::vector<Cell*> inRadius(uint16_t radius = 1);
    std::vector<Cell*> ring(uint16_t radius = 1);

private:
    void processRequests(MapAwareEntity* entity);

protected:
    const Offset _offset;

    Map* _map;

    RadialQuadTree<MaxQuadrantEntities, MaxQuadtreeDepth>* _quadTree;
    std::unordered_map<uint64_t /*id*/, MapAwareEntity*> _entities;
    uint16_t _clientsCount;

    // Use double lists to avoid locking and/or non-desired cleanups
    std::list<boost::intrusive_ptr<Packet>> _broadcastQueue1;
    std::list<boost::intrusive_ptr<Packet>> _broadcastQueue2;
    std::list<boost::intrusive_ptr<Packet>>* _broadcast;

    std::list<Request> _requests;

public:
    // TODO(gpascualg): Better encapsulation for stall information?
    StallInformation stall;
};

max_stars_repo_name: gpascualg/Shinzui

max_issues_repo_name: gpascualg/Shinzui

max_forks_repo_name: gpascualg/Shinzui


text:
/**
 *  @file
 *  @copyright defined in eos/LICENSE.txt
 */
#include <eosio/chain/contracts/producer_objects.hpp>
#include <eosio/chain/contracts/staked_balance_objects.hpp>

#include <eosio/chain/producer_object.hpp>

#include <boost/range/adaptors.hpp>
#include <boost/range/algorithm.hpp>
#include <boost/range/algorithm_ext.hpp>

namespace eosio { namespace chain { namespace contracts {

} } } // namespace eosio::chain::contracts

max_stars_repo_name: anauman/eosio

max_issues_repo_name: anauman/eosio

max_forks_repo_name: anauman/eosio


text:
//-----------------------------------------------------------------------------
// Copyright (c) 2018 Benjamin Buch
//
// https://github.com/bebuch/webservice
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
//-----------------------------------------------------------------------------
#ifndef _webservice__error_printing_ws_service__hpp_INCLUDED_
#define _webservice__error_printing_ws_service__hpp_INCLUDED_

#include <webservice/ws_identifier.hpp>

#include <boost/system/error_code.hpp>
#include <boost/system/system_error.hpp>

#include <exception>
#include <iostream>
#include <string>

namespace webservice{

	template < typename Base >
	struct error_printing_ws_service: Base{
		using Base::Base;

		void on_exception(std::exception_ptr error)noexcept override{
			try{
				std::rethrow_exception(error);
			}catch(std::exception const& e){
				std::cout << "\033[1;31mfail ws_service: unexpected exception: "
					<< e.what() << "\033[0m\n";
			}catch(...){
				std::cout << "\033[1;31mfail ws_service: unexpected unknown "
					"exception\033[0m\n";
			}
		}

		void on_exception(
			ws_identifier,
			std::exception_ptr error
		)noexcept override{
			on_exception(error);
		}
	};

}

#endif

max_stars_repo_name: kindlychung/mediasoup-sfu-cpp

max_issues_repo_name: kindlychung/mediasoup-sfu-cpp

max_forks_repo_name: kindlychung/mediasoup-sfu-cpp