text:
// Copyright 2005-2009 Daniel James.
// 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 "./books.hpp"
#include <boost/functional/hash.hpp>
#include <cassert>

// If std::unordered_set was available:
//#include <unordered_set>

// This example illustrates how to use boost::hash with a custom hash function.
// For full details, see the tutorial.

int main()
{
    library::book knife(3458, "Zane Grey", "The Hash Knife Outfit");
    library::book dandelion(1354, "Paul J. Shanley", "Hash & Dandelion Greens");

    boost::hash<library::book> book_hasher;
    std::size_t knife_hash_value = book_hasher(knife);

    // If std::unordered_set was available:
    //
    //std::unordered_set<library::book, boost::hash<library::book> > books;
    //books.insert(knife);
    //books.insert(library::book(2443, "Lindgren, Torgny", "Hash"));
    //books.insert(library::book(1953, "Snyder, Bernadette M.",
    //    "Heavenly Hash: A Tasty Mix of a Mother's Meditations"));

    //assert(books.find(knife) != books.end());
    //assert(books.find(dandelion) == books.end());

    return 0;
}

namespace library
{
    bool operator==(book const& a, book const& b)
    {
        return a.id == b.id;
    }

    std::size_t hash_value(book const& b)
    {
        boost::hash<int> hasher;
        return hasher(b.id);
    }
}

ext: cpp

max_issues_repo_name: boost-cmake/vintage

max_forks_repo_name: boost-cmake/vintage


text:
#pragma once
#include <Eigen/Dense>
#include <Eigen/Cholesky>
#include "serializer.hpp"

namespace tomoto
{
	namespace math
	{
		template<typename _Ty = float>
		struct MultiNormalDistribution
		{
			static constexpr _Ty log2pi = (_Ty)1.83787706641;
			Eigen::Matrix<_Ty, -1, 1> mean;
			Eigen::Matrix<_Ty, -1, -1> cov, l;
			_Ty logDet = 0;

			MultiNormalDistribution(size_t k = 0) :
				mean{ Eigen::Matrix<_Ty, -1, 1>::Zero(k) },
				cov{ Eigen::Matrix<_Ty, -1, -1>::Identity(k, k) },
				l{ Eigen::Matrix<_Ty, -1, -1>::Identity(k, k) }
			{
			}

			_Ty getLL(const Eigen::Matrix<_Ty, -1, 1>& x) const
			{
				_Ty ll = -((x - mean).transpose() * cov.inverse() * (x - mean))[0] / 2;
				ll -= log2pi * mean.size() / 2 + logDet;
				return ll;
			}

			const Eigen::Matrix<_Ty, -1, -1>& getCovL() const
			{
				return l;
			}

			template<typename _List>
			static MultiNormalDistribution<_Ty> estimate(_List list, size_t len)
			{
				MultiNormalDistribution<_Ty> newDist;
				if (len)
				{
					newDist.mean = list(0);
					for (size_t i = 1; i < len; ++i) newDist.mean += list(i);
					newDist.mean /= len;
					newDist.cov = Eigen::Matrix<_Ty, -1, -1>::Identity(newDist.mean.size(), newDist.mean.size());
					for (size_t i = 0; i < len; ++i)
					{
						Eigen::Matrix<_Ty, -1, 1> o = list(i) - newDist.mean;
						newDist.cov += o * o.transpose();
					}
					if (len > 1) newDist.cov /= len - 1;
				}
				Eigen::MatrixXd l = newDist.cov.template cast<double>().llt().matrixL();
				newDist.l = l.template cast<float>();
				newDist.logDet = l.diagonal().array().log().sum();
				return newDist;
			}

			DEFINE_SERIALIZER_CALLBACK(onRead, mean, cov);
		private:
			void onRead()
			{
				l = cov.llt().matrixL();
				logDet = l.diagonal().array().log().sum();
			}
		};

	}
}

ext: hpp


text:
// Enable 64-bit file offsets on Linux.
#define _FILE_OFFSET_BITS 64

#include <cradle/io/file.hpp>
#include <cstring>
#include <boost/format.hpp>

namespace boost { namespace CRADLE_IO_BOOST_FILESYSTEM_NAMESPACE {

size_t deep_sizeof(path const& x)
{
    return cradle::deep_sizeof(x.string());
}

void to_value(cradle::value* v, path const& x)
{
    to_value(v, x.string());
}
void from_value(path* x, cradle::value const& v)
{
    cradle::string s;
    from_value(&s, v);
    *x = path(s);
}

alia::string to_string(path const& x)
{
    return x.string();
}
void from_string(path* x, alia::string const& s)
{
    *x = path(s);
}

}}

namespace cradle {

string get_extension(file_path const& path)
{
    return get_extension(path.filename().string());
}

string get_extension(string const& name)
{
    size_t pos = name.rfind('.');
    if (pos == string::npos)
        return "";
    else
        return name.substr(pos + 1);
}

// OPEN

// Convert an open mode to a string.
static string openmode_to_string(std::ios::openmode mode)
{
    string str;

    if ((mode & std::ios::app) != 0)
        str += "app";
    if ((mode & std::ios::ate) != 0)
    {
        if (str != "")
            str += "|";
        str += "ate";
    }
    if ((mode & std::ios::binary) != 0)
    {
        if (str != "")
            str += "|";
        str += "binary";
    }
    if ((mode & std::ios::in) != 0)
    {
        if (str != "")
            str += "|";
        str += "in";
    }
    if ((mode & std::ios::out) != 0)
    {
        if (str != "")
            str += "|";
        str += "out";
    }
    if ((mode & std::ios::trunc) != 0)
    {
        if (str != "")
            str += "|";
        str += "trunc";
    }
    return str;
}

// When using fstream, you can pass in the mode of the failed open
// operation, and it will be used to format the error message.
open_file_error::open_file_error(file_path const& file,
    std::fstream::openmode mode, string const& msg)
  : file_error(file, msg + " (mode: " + openmode_to_string(mode) + ")")
{}

void open(std::fstream& file, file_path const& path,
    std::ios::openmode mode)
{
    file.open(path.c_str(), mode);
    if (!file)
        throw open_file_error(path, mode);
    file.exceptions(std::ios::eofbit | std::ios::failbit | std::ios::badbit);
}

void open(std::ifstream& file, file_path const& path,
    std::ios::openmode mode)
{
    file.open(path.c_str(), mode);
    if (!file)
        throw open_file_error(path, mode);
    file.exceptions(std::ios::eofbit | std::ios::failbit | std::ios::badbit);
}

void open(std::ofstream& file, file_path const& path,
    std::ios::openmode mode)
{
    file.open(path.c_str(), mode);
    if (!file)
        throw open_file_error(path, mode);
    file.exceptions(std::ios::eofbit | std::ios::failbit | std::ios::badbit);
}

// C_FILE

c_file::c_file(file_path const& file, const char* mode)
{
    f_ = fopen(file.string<string>().c_str(), mode);
    if (f_ == NULL)
    {
        throw file_error(file, string("unable to open file (mode '")
            + mode + "')");
    }
    path_ = file;
}

void c_file::read(void* data, size_t size)
{
    // MS can't deal with large blocks of data, so we need to break it up for
    // them.
    size_t max_block_size = 0x40000000; // 1GB
    while (size > max_block_size)
    {
        if (fread(data, 1, max_block_size, f_) != max_block_size)
            throw_error("fread failed");
        data = reinterpret_cast<uint8_t*>(data) + max_block_size;
        size -= max_block_size;
    }
    if (fread(data, 1, size, f_) != size)
        throw_error("fread failed");
}

void c_file::write(void const* data, size_t size)
{
    // MS can't deal with large blocks of data, so we need to break it up for
    // them.
    size_t max_block_size = 0x40000000; // 1GB
    while (size > max_block_size)
    {
        if (fwrite(data, 1, max_block_size, f_) != max_block_size)
            throw_error("fwrite failed");
        data = reinterpret_cast<uint8_t const*>(data) + max_block_size;
        size -= max_block_size;
    }
    if (fwrite(data, 1, size, f_) != size)
        throw_error("fwrite failed");
}

string c_file::read_line()
{
    char buf[1024];
    if (fgets(buf, 1023, f_) == NULL)
        throw_error("fgets failed");
    buf[strlen(buf) - 1] = '\0';
    return buf;
}

void c_file::seek(int64_t offset, int whence)
{
  #ifdef WIN32
    if (_fseeki64(f_, offset, whence) != 0)
        throw_error("fseek failed");
  #else
    if (fseeko(f_, offset, whence) != 0)
        throw_error("fseek failed");
  #endif
}

int64_t c_file::tell()
{
  #ifdef WIN32
    int64_t p = _ftelli64(f_);
  #else
    int64_t p = ftello(f_);
  #endif
    if (p < 0)
        throw_error("ftell failed");
    return p;
}

int64_t c_file::length()
{
    int64_t cur = tell();
    seek(0, SEEK_END);
    int64_t end = tell();
    seek(cur, SEEK_SET);
    return end;
}

void c_file::throw_error(string const& msg)
{
    int error = ferror(f_);
    if (error != 0)
        throw file_error(path_, msg + std::strerror(error));
    else if (feof(f_))
        throw file_error(path_, msg + ": EOF");
    else
        throw file_error(path_, msg);
}

// SIMPLE_PARSER

simple_file_parser::simple_file_parser(file_path const& file_path)
{
    file_path_ = file_path;
    f_ = std::fopen(file_path.string<string>().c_str(), "rt");
    if (f_ == NULL)
        throw file_error(file_path, "unable to open file");
    line_n_ = col_n_ = 0;
    buffer_.resize(1, '\0');
    p_ = &buffer_[0];
    eof_ = false;
    mode_ = LINE_BY_LINE;
}

void simple_file_parser::get_line()
{
    if (!eof_)
    {
        line_n_++;
        buffer_.clear();
        while (1)
        {
            int c = fgetc(f_);
            if (c == EOF)
            {
                if (ferror(f_))
                {
                    throw_error("disk access error");
                }
                else
                {
                    buffer_.push_back('\0');
                    eof_ = true;
                    break;
                }
            }
            else if (c == '\n')
            {
                buffer_.push_back('\0');
                break;
            }
            else
            {
                buffer_.push_back(char(c));
            }
        }
        p_ = &buffer_[0];
    }
}

char simple_file_parser::peek()
{
    skip_space();
    return *p_;
}

void simple_file_parser::check_char(char expected)
{
    skip_space();
    if (*p_ != expected)
        throw_unexpected_char();
    ++p_;
}

void simple_file_parser::skip_char()
{
    if (*p_ == '\0')
        throw_error("unexpected EOL");
    ++p_;
}

bool simple_file_parser::eol()
{
    skip_space();
    return *p_ == '\0';
}

void simple_file_parser::check_eol()
{
    if (!eol())
        throw_unexpected_char();
}

int simple_file_parser::read_int()
{
    skip_space();
    char *end;
    int i = strtol(p_, &end, 10);
    if (end == p_)
        throw_error("missing integer");
    p_ = end;
    return i;
}

unsigned simple_file_parser::read_unsigned()
{
    int i = read_int();
    if (i < 0)
        throw_error("expected natural number; got negative");
    return unsigned(i);
}

double simple_file_parser::read_double()
{
    skip_space();
    char *end;
    double d = strtod(p_, &end);
    if (end == p_)
        throw_error("missing number");
    p_ = end;
    return d;
}

string simple_file_parser::read_string(int end_marker)
{
    skip_space();
    if (*p_ == '\0')
        throw_error("missing string");
    char *start = p_;
    if (end_marker == -1)
    {
        while (!isspace (*p_) && *p_ != '\0')
            ++p_;
    }
    else
    {
        while (*p_ != (char) end_marker && *p_ != '\0')
            ++p_;
    }
    if (*p_ != '\0')
    {
        *p_ = '\0';
        ++p_;
    }
    return start;
}

string simple_file_parser::read_rest_of_line()
{
    char *start = p_;
    while (*p_ != '\r' && *p_ != '\n' && *p_ != '\0')
        ++p_;
    if (*p_ != '\0')
    {
        *p_ = '\0';
        ++p_;
    }
    return start;
}

string simple_file_parser::read_identifier()
{
    skip_space();
    if (!isalpha(*p_) && *p_ != '_')
        throw_error("missing identifier");
    char *start = p_;
    while (isalnum (*p_) || *p_ == '_')
        ++p_;
    char buf[1024];
    std::memcpy(buf, start, p_ - start);
    buf[p_ - start] = '\0';
    return buf;
}

simple_file_parser::~simple_file_parser()
{
    if (f_ != NULL)
        std::fclose (f_);
}

void simple_file_parser::skip_space()
{
start:
    while (isspace(*p_))
        ++p_;

    if ((mode_ & POUND_COMMENTS) != 0 && *p_ == '#')
    {
        get_line();
        goto start;
    }

    if ((mode_ & CONTINUOUS) != 0 && *p_ == '\0' && !eof_)
    {
        get_line();
        goto start;
    }
}

bool simple_file_parser::eof()
{
    skip_space();
    return eof_;
}

void simple_file_parser::throw_error(string const& msg) const
{
    throw file_error(file_path_, (boost::format("%i:%i: error: %s")
        % line_n_ % (p_ - &buffer_[0]) % msg).str());
}

void simple_file_parser::throw_unexpected_char() const
{
    if (*p_ == '\0')
    {
        throw_error("unexpected EOL");
    }
    else
    {
        throw_error((boost::format("unexpected character: %c (0x%02x)")
            % *p_ % static_cast<int>(*p_)).str());
    }
}

string get_file_contents(file_path const& path)
{
    std::ifstream in;
    open(in, path, std::ios::in | std::ios::binary);
    if (in)
    {
        string contents;
        in.seekg(0, std::ios::end);
        contents.resize(in.tellg());
        in.seekg(0, std::ios::beg);
        in.read(&contents[0], contents.size());
        in.close();
        return contents;
    }
    throw(errno);
}

}

max_stars_repo_name: dotdecimal/open-cradle

max_issues_repo_name: dotdecimal/open-cradle

max_forks_repo_name: dotdecimal/open-cradle


text:
/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2017 Nathan Osman
 *
 * 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/endian/conversion.hpp>

#include <win32pe/fileheader.h>

#include "fileheader_p.h"

using namespace win32pe;

FileHeaderPrivate::FileHeaderPrivate()
    : mMachine(0),
      mNumberOfSections(0),
      mTimeDateStamp(0),
      mPointerToSymbolTable(0),
      mNumberOfSymbols(0),
      mSizeOfOptionalHeader(0),
      mCharacteristics(0)
{
}

bool FileHeaderPrivate::read(std::istream &istream)
{
    if (!istream.read(reinterpret_cast<char*>(this), sizeof(*this))) {
        return false;
    }

    boost::endian::little_to_native_inplace(mMachine);
    boost::endian::little_to_native_inplace(mNumberOfSections);
    boost::endian::little_to_native_inplace(mTimeDateStamp);
    boost::endian::little_to_native_inplace(mPointerToSymbolTable);
    boost::endian::little_to_native_inplace(mNumberOfSymbols);
    boost::endian::little_to_native_inplace(mSizeOfOptionalHeader);
    boost::endian::little_to_native_inplace(mCharacteristics);

    return true;
}

FileHeader::FileHeader()
    : d(new FileHeaderPrivate)
{
}

FileHeader::FileHeader(const FileHeader &other)
    : d(new FileHeaderPrivate(*other.d))
{
}

FileHeader::~FileHeader()
{
    delete d;
}

FileHeader &FileHeader::operator=(const FileHeader &other)
{
    *d = *other.d;
    return *this;
}

uint16_t FileHeader::machine() const
{
    return d->mMachine;
}

uint32_t FileHeader::timeDateStamp() const
{
    return d->mTimeDateStamp;
}

uint16_t FileHeader::characteristics() const
{
    return d->mCharacteristics;
}


text:
#include <iostream>
#include <vector>
#include <cassert>
#include <cmath>

#include "config.h"
#ifdef HAVE_MPI
#include <boost/mpi.hpp>
#endif
#include <boost/program_options.hpp>
#include <boost/program_options/variables_map.hpp>

#include "cllh_observer.h"
#include "sentence_metadata.h"
#include "verbose.h"
#include "hg.h"
#include "prob.h"
#include "inside_outside.h"
#include "ff_register.h"
#include "decoder.h"
#include "filelib.h"
#include "weights.h"

using namespace std;
namespace po = boost::program_options;

bool InitCommandLine(int argc, char** argv, po::variables_map* conf) {
  po::options_description opts("Configuration options");
  opts.add_options()
        ("weights,w",po::value<string>(),"Input feature weights file")
        ("training_data,t",po::value<string>(),"Training data corpus")
        ("decoder_config,c",po::value<string>(),"Decoder configuration file");
  po::options_description clo("Command line options");
  clo.add_options()
        ("config", po::value<string>(), "Configuration file")
        ("help,h", "Print this help message and exit");
  po::options_description dconfig_options, dcmdline_options;
  dconfig_options.add(opts);
  dcmdline_options.add(opts).add(clo);

  po::store(parse_command_line(argc, argv, dcmdline_options), *conf);
  if (conf->count("config")) {
    ifstream config((*conf)["config"].as<string>().c_str());
    po::store(po::parse_config_file(config, dconfig_options), *conf);
  }
  po::notify(*conf);

  if (conf->count("help") || !conf->count("training_data") || !conf->count("decoder_config")) {
    cerr << dcmdline_options << endl;
    return false;
  }
  return true;
}

void ReadInstances(const string& fname, int rank, int size, vector<string>* c) {
  assert(fname != "-");
  ReadFile rf(fname);
  istream& in = *rf.stream();
  string line;
  int lc = 0;
  while(in) {
    getline(in, line);
    if (!in) break;
    if (lc % size == rank) c->push_back(line);
    ++lc;
  }
}

static const double kMINUS_EPSILON = -1e-6;

#ifdef HAVE_MPI
namespace mpi = boost::mpi;
#endif

int main(int argc, char** argv) {
#ifdef HAVE_MPI
  mpi::environment env(argc, argv);
  mpi::communicator world;
  const int size = world.size();
  const int rank = world.rank();
#else
  const int size = 1;
  const int rank = 0;
#endif
  if (size > 1) SetSilent(true);  // turn off verbose decoder output
  register_feature_functions();

  po::variables_map conf;
  if (!InitCommandLine(argc, argv, &conf))
    return false;

  // load cdec.ini and set up decoder
  ReadFile ini_rf(conf["decoder_config"].as<string>());
  Decoder decoder(ini_rf.stream());
  if (decoder.GetConf()["input"].as<string>() != "-") {
    cerr << "cdec.ini must not set an input file\n";
    abort();
  }

  // load weights
  vector<weight_t>& weights = decoder.CurrentWeightVector();
  if (conf.count("weights"))
    Weights::InitFromFile(conf["weights"].as<string>(), &weights);

  vector<string> corpus;
  ReadInstances(conf["training_data"].as<string>(), rank, size, &corpus);
  assert(corpus.size() > 0);

  if (rank == 0)
    cerr << "Each processor is decoding ~" << corpus.size() << " training examples...\n";

  ConditionalLikelihoodObserver observer;
  for (int i = 0; i < corpus.size(); ++i)
    decoder.Decode(corpus[i], &observer);

  double objective = 0;
  unsigned total_words = 0;
#ifdef HAVE_MPI
  reduce(world, observer.acc_obj, objective, std::plus<double>(), 0);
  reduce(world, observer.trg_words, total_words, std::plus<unsigned>(), 0);
#else
  objective = observer.acc_obj;
  total_words = observer.trg_words;
#endif

  if (rank == 0) {
    cout << "CONDITIONAL LOG_e LIKELIHOOD: " << objective << endl;
    cout << "CONDITIONAL LOG_2 LIKELIHOOD: " << (objective/log(2)) << endl;
    cout << "         CONDITIONAL ENTROPY: " << (objective/log(2) / total_words) << endl;
    cout << "                  PERPLEXITY: " << pow(2, (objective/log(2) / total_words)) << endl;
  }

  return 0;
}

ext: cc

max_stars_repo_name: kho/cdec

max_issues_repo_name: kho/cdec

max_forks_repo_name: kho/cdec


text:
//  ================================================================
//  Created by Gregory Kramida on 10/24/18.
//  Copyright (c) 2018 Gregory Kramida
//  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.
//  ================================================================
#pragma once

//libraries
#include <Eigen/Eigen>
#include <unsupported/Eigen/CXX11/Tensor>

//local
#include "vector2.hpp"
#include "vector3.hpp"
#include "matrix2.hpp"
#include "matrix3.hpp"
#include "nestable_type_metainfo.hpp"

namespace math{
typedef unsigned char uchar;
typedef unsigned short ushort;
typedef unsigned int uint;
typedef unsigned long ulong;

typedef class math::Vector2<short> Vector2s;
typedef class math::Vector2<int> Vector2i;
typedef class math::Vector2<float> Vector2f;
typedef class math::Vector2<double> Vector2d;

typedef class math::Vector3<short> Vector3s;
typedef class math::Vector3<double> Vector3d;
typedef class math::Vector3<int> Vector3i;
typedef class math::Vector3<uint> Vector3ui;
typedef class math::Vector3<uchar> Vector3u;
typedef class math::Vector3<float> Vector3f;
typedef class math::Matrix2<float> Matrix2f;
typedef class math::Matrix3<float> Matrix3f;

typedef Eigen::MatrixXf MatrixXf;
typedef Eigen::MatrixXd MatrixXd;
typedef Eigen::Matrix<math::Vector2<float>, Eigen::Dynamic, Eigen::Dynamic> MatrixXv2f;
typedef Eigen::Matrix<math::Vector2<float>, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> MatrixXv2f_rm;
typedef Eigen::Matrix<math::Matrix2<float>, Eigen::Dynamic, Eigen::Dynamic> MatrixXm2f;

typedef class Eigen::Tensor<float,3> Tensor3f;
typedef class Eigen::Tensor<float,0> Tensor0f;
typedef Eigen::Tensor<math::Vector2<float>,3> Tensor3v2f;
typedef Eigen::Tensor<math::Vector3<float>,3> Tensor3v3f;
typedef Eigen::Tensor<math::Matrix3<float>,3> Tensor3m3f;

typedef class Eigen::Matrix<unsigned short, Eigen::Dynamic,Eigen::Dynamic> MatrixXus;
typedef class Eigen::Matrix<unsigned short, Eigen::Dynamic,1> MatrixX1us;
typedef class Eigen::Matrix<unsigned short, 1, Eigen::Dynamic> Matrix1Xus;
typedef class Eigen::Matrix<unsigned char, Eigen::Dynamic,Eigen::Dynamic> MatrixXuc;
typedef class Eigen::Matrix<unsigned char, Eigen::Dynamic,1> MatrixX1uc;
typedef class Eigen::Matrix<unsigned char, 1, Eigen::Dynamic> Matrix1Xuc;
typedef class Eigen::Matrix<unsigned char, Eigen::Dynamic,Eigen::Dynamic> MatrixXuc;

}//namespace math

max_stars_repo_name: Algomorph/LevelSetFusionExperimentsCPP

max_issues_repo_name: Algomorph/LevelSetFusionExperimentsCPP

max_forks_repo_name: Algomorph/LevelSetFusionExperimentsCPP


text:
#include <boost/test/unit_test.hpp>
#include <algorithm>

#include "main.h"
#include "vote.h"

using namespace std;

BOOST_AUTO_TEST_SUITE(vote_tests)

BOOST_AUTO_TEST_CASE(reload_vote_from_script_tests)
{
    CVote vote;

    CCustodianVote custodianVote;
    CBitcoinAddress custodianAddress(CKeyID(123465), 'B');
    custodianVote.SetAddress(custodianAddress);
    custodianVote.nAmount = 100 * COIN;
    vote.vCustodianVote.push_back(custodianVote);

    CCustodianVote custodianVote2;
    CBitcoinAddress custodianAddress2(CKeyID(555555555), 'B');
    custodianVote2.SetAddress(custodianAddress2);
    custodianVote2.nAmount = 5.5 * COIN;
    vote.vCustodianVote.push_back(custodianVote2);

    CParkRateVote parkRateVote;
    parkRateVote.cUnit = 'B';
    parkRateVote.vParkRate.push_back(CParkRate(13, 3));
    parkRateVote.vParkRate.push_back(CParkRate(14, 6));
    parkRateVote.vParkRate.push_back(CParkRate(15, 13));
    vote.vParkRateVote.push_back(parkRateVote);

    vote.vMotion.push_back(uint160(123456));
    vote.vMotion.push_back(uint160(3333));

    CScript script = vote.ToScript();

    CVote voteResult;
    BOOST_CHECK(ExtractVote(script, voteResult));

#undef CHECK_VOTE_EQUAL
#define CHECK_VOTE_EQUAL(value) BOOST_CHECK(voteResult.value == vote.value);
    CHECK_VOTE_EQUAL(vCustodianVote.size());
    for (int i=0; i<vote.vCustodianVote.size(); i++)
    {
        CHECK_VOTE_EQUAL(vCustodianVote[i].cUnit);
        CHECK_VOTE_EQUAL(vCustodianVote[i].hashAddress);
        CHECK_VOTE_EQUAL(vCustodianVote[i].GetAddress().ToString());
        CHECK_VOTE_EQUAL(vCustodianVote[i].nAmount);
    }
    BOOST_CHECK_EQUAL(custodianAddress.ToString(), vote.vCustodianVote[0].GetAddress().ToString());
    BOOST_CHECK_EQUAL(custodianAddress2.ToString(), vote.vCustodianVote[1].GetAddress().ToString());

    CHECK_VOTE_EQUAL(vParkRateVote.size());
    for (int i=0; i<vote.vParkRateVote.size(); i++)
    {
        CHECK_VOTE_EQUAL(vParkRateVote[i].cUnit);
        CHECK_VOTE_EQUAL(vParkRateVote[i].vParkRate.size());
        for (int j=0; j<vote.vParkRateVote[i].vParkRate.size(); j++)
        {
            CHECK_VOTE_EQUAL(vParkRateVote[i].vParkRate[j].nCompactDuration);
            CHECK_VOTE_EQUAL(vParkRateVote[i].vParkRate[j].nRate);
        }
    }

    CHECK_VOTE_EQUAL(vMotion.size());
    CHECK_VOTE_EQUAL(vMotion[0]);
    CHECK_VOTE_EQUAL(vMotion[1]);
#undef CHECK_VOTE_EQUAL
}

BOOST_AUTO_TEST_CASE(reload_park_rates_from_script_tests)
{
    CParkRateVote parkRateVote;
    parkRateVote.cUnit = 'B';
    parkRateVote.vParkRate.push_back(CParkRate(13, 3));
    parkRateVote.vParkRate.push_back(CParkRate(14, 6));
    parkRateVote.vParkRate.push_back(CParkRate(15, 13));

    CScript script = parkRateVote.ToParkRateResultScript();
    BOOST_CHECK(IsParkRateResult(script));

    CParkRateVote parkRateVoteResult;
    BOOST_CHECK(ExtractParkRateResult(script, parkRateVoteResult));

#undef CHECK_PARK_RATE_EQUAL
#define CHECK_PARK_RATE_EQUAL(value) BOOST_CHECK(parkRateVoteResult.value == parkRateVote.value);
    CHECK_PARK_RATE_EQUAL(cUnit);
    CHECK_PARK_RATE_EQUAL(vParkRate.size());
    for (int i=0; i<parkRateVote.vParkRate.size(); i++)
    {
        CHECK_PARK_RATE_EQUAL(vParkRate[i].nCompactDuration);
        CHECK_PARK_RATE_EQUAL(vParkRate[i].nRate);
    }
#undef CHECK_PARK_RATE_EQUAL
}

template< class T >
static void shuffle(vector<T> v)
{
    random_shuffle(v.begin(), v.end());
}

BOOST_AUTO_TEST_CASE(rate_calculation_from_votes)
{
    vector<CVote> vVote;
    vector<CParkRateVote> results;
    map<unsigned char, vector<const CParkRateVote*> > previousRates;

    // Use very high previous rates to avoid rate limitation (tested elsewhere)
    CParkRateVote previousRate;
    previousRate.cUnit = 'B';
    for (int i = 0; i < 256; i++)
    {
        CParkRate parkRate;
        parkRate.nCompactDuration = i;
        parkRate.nRate = std::numeric_limits<unsigned int>::max();
        previousRate.vParkRate.push_back(parkRate);
    }
    previousRates['B'].push_back(&previousRate);

    // Result of empty vote is empty
    BOOST_CHECK(CalculateParkRateResults(vVote, previousRates, results));
    BOOST_CHECK_EQUAL(0, results.size());

    CParkRateVote parkRateVote;
    parkRateVote.cUnit = 'B';
    parkRateVote.vParkRate.push_back(CParkRate( 8, 100));

    CVote vote;
    vote.vParkRateVote.push_back(parkRateVote);
    vote.nCoinAgeDestroyed = 1000;

    vVote.push_back(vote);

    // Single vote: same result as vote
    BOOST_CHECK(CalculateParkRateResults(vVote, previousRates, results));
    BOOST_CHECK_EQUAL(  1, results.size());
    BOOST_CHECK_EQUAL(  1, results[0].vParkRate.size());
    BOOST_CHECK_EQUAL(  8, results[0].vParkRate[0].nCompactDuration);
    BOOST_CHECK_EQUAL(100, results[0].vParkRate[0].nRate);

    // New vote with same weight and bigger rate
    parkRateVote.vParkRate.clear();
    vote.vParkRateVote.clear();
    parkRateVote.vParkRate.push_back(CParkRate(8, 200));
    vote.vParkRateVote.push_back(parkRateVote);
    vVote.push_back(vote);

    // Two votes of same weight, the median is the first one
    BOOST_CHECK(CalculateParkRateResults(vVote, previousRates, results));
    BOOST_CHECK_EQUAL(  1, results.size());
    BOOST_CHECK_EQUAL(  1, results[0].vParkRate.size());
    BOOST_CHECK_EQUAL(  8, results[0].vParkRate[0].nCompactDuration);
    BOOST_CHECK_EQUAL(100, results[0].vParkRate[0].nRate);

    // Vote 2 has a little more weight
    vVote[1].nCoinAgeDestroyed = 1001;

    // Each coin age has a vote. So the median is the second vote rate.
    BOOST_CHECK(CalculateParkRateResults(vVote, previousRates, results));
    BOOST_CHECK_EQUAL(  1, results.size());
    BOOST_CHECK_EQUAL(  1, results[0].vParkRate.size());
    BOOST_CHECK_EQUAL(  8, results[0].vParkRate[0].nCompactDuration);
    BOOST_CHECK_EQUAL(200, results[0].vParkRate[0].nRate);

    // New vote with small weight and rate between the 2 first
    parkRateVote.vParkRate.clear();
    vote.vParkRateVote.clear();
    parkRateVote.vParkRate.push_back(CParkRate(8, 160));
    vote.vParkRateVote.push_back(parkRateVote);
    vote.nCoinAgeDestroyed = 3;
    vVote.push_back(vote);

    // The median is the middle rate
    BOOST_CHECK(CalculateParkRateResults(vVote, previousRates, results));
    BOOST_CHECK_EQUAL(  1, results.size());
    BOOST_CHECK_EQUAL(  1, results[0].vParkRate.size());
    BOOST_CHECK_EQUAL(  8, results[0].vParkRate[0].nCompactDuration);
    BOOST_CHECK_EQUAL(160, results[0].vParkRate[0].nRate);

    // New vote with another duration
    parkRateVote.vParkRate.clear();
    vote.vParkRateVote.clear();
    parkRateVote.vParkRate.push_back(CParkRate(9, 300));
    vote.vParkRateVote.push_back(parkRateVote);
    vote.nCoinAgeDestroyed = 100;
    vVote.push_back(vote);

    // It votes for 0 on duration 8, so the result is back to 100
    // On duration 9 everybody else vote for 0, so the median is 0, so there's no result
    BOOST_CHECK(CalculateParkRateResults(vVote, previousRates, results));
    BOOST_CHECK_EQUAL(  1, results.size());
    BOOST_CHECK_EQUAL(  1, results[0].vParkRate.size());
    BOOST_CHECK_EQUAL(  8, results[0].vParkRate[0].nCompactDuration);
    BOOST_CHECK_EQUAL(100, results[0].vParkRate[0].nRate);

    // New vote with multiple durations unordered
    parkRateVote.vParkRate.clear();
    vote.vParkRateVote.clear();
    parkRateVote.vParkRate.push_back(CParkRate(13, 500));
    parkRateVote.vParkRate.push_back(CParkRate(9, 400));
    parkRateVote.vParkRate.push_back(CParkRate(8, 200));
    vote.vParkRateVote.push_back(parkRateVote);
    vote.nCoinAgeDestroyed = 2050;
    vVote.push_back(vote);

    BOOST_CHECK(CalculateParkRateResults(vVote, previousRates, results));
    BOOST_CHECK_EQUAL(  1, results.size());
    // On duration 8:
    // Vote weights: 0: 100, 100: 1000, 160: 3, 200: 3051
    // So median is 200
    BOOST_CHECK_EQUAL(  8, results[0].vParkRate[0].nCompactDuration);
    BOOST_CHECK_EQUAL(200, results[0].vParkRate[0].nRate);
    // On duration 9:
    // Vote weights: 0: 2004, 300: 100, 400: 2050
    // So median is 300
    BOOST_CHECK_EQUAL(  9, results[0].vParkRate[1].nCompactDuration);
    BOOST_CHECK_EQUAL(300, results[0].vParkRate[1].nRate);
    // On duration 13: only last vote is positive and it has not the majority, so median is 0
    BOOST_CHECK_EQUAL(  2, results[0].vParkRate.size());

    // Shuffle all the votes
    srand(1234);
    BOOST_FOREACH(const CVote& vote, vVote)
    {
        BOOST_FOREACH(const CParkRateVote& parkRateVote, vote.vParkRateVote)
            shuffle(parkRateVote.vParkRate);
        shuffle(vote.vParkRateVote);
    }
    shuffle(vVote);

    // The result should not be changed
    vector<CParkRateVote> newResults;
    BOOST_CHECK(CalculateParkRateResults(vVote, previousRates, newResults));
    BOOST_CHECK(results == newResults);

    // New vote with duplicate duration makes the result invalid
    parkRateVote.vParkRate.clear();
    vote.vParkRateVote.clear();
    parkRateVote.vParkRate.push_back(CParkRate(13, 500));
    parkRateVote.vParkRate.push_back(CParkRate(13, 400));
    vote.vParkRateVote.push_back(parkRateVote);
    vVote.push_back(vote);

    BOOST_CHECK(!CalculateParkRateResults(vVote, previousRates, results));
    BOOST_CHECK_EQUAL(0, results.size());

    vVote.pop_back();
    // New vote on another unit is invalid
    parkRateVote.vParkRate.clear();
    vote.vParkRateVote.clear();
    parkRateVote.cUnit = 'A';
    parkRateVote.vParkRate.push_back(CParkRate(13, 500));
    vote.vParkRateVote.push_back(parkRateVote);
    vVote.push_back(vote);

    BOOST_CHECK(!CalculateParkRateResults(vVote, previousRates, results));
    BOOST_CHECK_EQUAL(0, results.size());
}

BOOST_AUTO_TEST_CASE(rate_limitation)
{
    vector<CVote> vVote;
    vector<CParkRateVote> results;
    map<unsigned char, vector<const CParkRateVote*> > previousRates;

    CVote vote;
    CParkRateVote parkRateVote;

    parkRateVote.cUnit = 'B';
    parkRateVote.vParkRate.push_back(CParkRate(15, 1000 * COIN_PARK_RATE / COIN)); // 1 month
    parkRateVote.vParkRate.push_back(CParkRate(18, 1000 * COIN_PARK_RATE / COIN)); // 6 months
    parkRateVote.vParkRate.push_back(CParkRate(19, 1000 * COIN_PARK_RATE / COIN)); // 1 year
    vote.vParkRateVote.push_back(parkRateVote);
    vote.nCoinAgeDestroyed = 1000;
    vVote.push_back(vote);

    int64 maxIncreaseDuration15 = pow(2, 15) / 365.25 / 24 / 60 / 60 * STAKE_TARGET_SPACING * COIN_PARK_RATE / 100;
    int64 maxIncreaseDuration18 = pow(2, 18) / 365.25 / 24 / 60 / 60 * STAKE_TARGET_SPACING * COIN_PARK_RATE / 100;
    int64 maxIncreaseDuration19 = pow(2, 19) / 365.25 / 24 / 60 / 60 * STAKE_TARGET_SPACING * COIN_PARK_RATE / 100;

    // Without previous rates, the previous rates are all considered 0 so the rate increase is limited
    BOOST_CHECK(CalculateParkRateResults(vVote, previousRates, results));
    BOOST_CHECK_EQUAL(   1, results.size());
    BOOST_CHECK_EQUAL(   3, results[0].vParkRate.size());
    BOOST_CHECK_EQUAL(  15, results[0].vParkRate[0].nCompactDuration);
    BOOST_CHECK_EQUAL(maxIncreaseDuration15, results[0].vParkRate[0].nRate);
    BOOST_CHECK_EQUAL(  18, results[0].vParkRate[1].nCompactDuration);
    BOOST_CHECK_EQUAL(maxIncreaseDuration18, results[0].vParkRate[1].nRate);
    BOOST_CHECK_EQUAL(  19, results[0].vParkRate[2].nCompactDuration);
    BOOST_CHECK_EQUAL(maxIncreaseDuration19, results[0].vParkRate[2].nRate);

    // With an empty previous rate (meaning the rates are all 0), the rate increase is limited
    CParkRateVote previousRate;
    previousRate.cUnit = 'B';
    previousRates['B'].push_back(&previousRate);

    BOOST_CHECK(CalculateParkRateResults(vVote, previousRates, results));
    BOOST_CHECK_EQUAL(   1, results.size());
    BOOST_CHECK_EQUAL(   3, results[0].vParkRate.size());
    BOOST_CHECK_EQUAL(  15, results[0].vParkRate[0].nCompactDuration);
    BOOST_CHECK_EQUAL(maxIncreaseDuration15, results[0].vParkRate[0].nRate);
    BOOST_CHECK_EQUAL(  18, results[0].vParkRate[1].nCompactDuration);
    BOOST_CHECK_EQUAL(maxIncreaseDuration18, results[0].vParkRate[1].nRate);
    BOOST_CHECK_EQUAL(  19, results[0].vParkRate[2].nCompactDuration);
    BOOST_CHECK_EQUAL(maxIncreaseDuration19, results[0].vParkRate[2].nRate);

    // With some previous rates
    previousRate.vParkRate.push_back(CParkRate(10, 100 * COIN_PARK_RATE / COIN));
    previousRate.vParkRate.push_back(CParkRate(15, 3 * COIN_PARK_RATE / COIN));
    previousRate.vParkRate.push_back(CParkRate(19, 950 * COIN_PARK_RATE / COIN));

    BOOST_CHECK(CalculateParkRateResults(vVote, previousRates, results));
    BOOST_CHECK_EQUAL(   1, results.size());
    BOOST_CHECK_EQUAL(   3, results[0].vParkRate.size());
    BOOST_CHECK_EQUAL(  15, results[0].vParkRate[0].nCompactDuration);
    BOOST_CHECK_EQUAL(3 * COIN_PARK_RATE / COIN + maxIncreaseDuration15, results[0].vParkRate[0].nRate);
    BOOST_CHECK_EQUAL(  18, results[0].vParkRate[1].nCompactDuration);
    BOOST_CHECK_EQUAL(maxIncreaseDuration18, results[0].vParkRate[1].nRate);
    BOOST_CHECK_EQUAL(  19, results[0].vParkRate[2].nCompactDuration);
    BOOST_CHECK_EQUAL(1000 * COIN_PARK_RATE / COIN, results[0].vParkRate[2].nRate);

    // With multiple previous rates
    previousRate.vParkRate.push_back(CParkRate(15, 2 * COIN_PARK_RATE / COIN));
    previousRate.vParkRate.push_back(CParkRate(19, 150 * COIN_PARK_RATE / COIN));

    BOOST_CHECK(CalculateParkRateResults(vVote, previousRates, results));
    BOOST_CHECK_EQUAL(   1, results.size());
    BOOST_CHECK_EQUAL(   3, results[0].vParkRate.size());
    BOOST_CHECK_EQUAL(  15, results[0].vParkRate[0].nCompactDuration);
    BOOST_CHECK_EQUAL(2 * COIN_PARK_RATE / COIN + maxIncreaseDuration15, results[0].vParkRate[0].nRate);
    BOOST_CHECK_EQUAL(  18, results[0].vParkRate[1].nCompactDuration);
    BOOST_CHECK_EQUAL(maxIncreaseDuration18, results[0].vParkRate[1].nRate);
    BOOST_CHECK_EQUAL(  19, results[0].vParkRate[2].nCompactDuration);
    BOOST_CHECK_EQUAL(150 * COIN_PARK_RATE / COIN + maxIncreaseDuration19, results[0].vParkRate[2].nRate);

}

BOOST_AUTO_TEST_CASE(vote_validity_tests)
{
    CVote vote;
    CParkRateVote parkRateVote;

    // An empty vote is valid
    BOOST_CHECK(vote.IsValid());

    // A park rate vote on share is invalid
    parkRateVote.cUnit = 'S';
    vote.vParkRateVote.push_back(parkRateVote);
    BOOST_CHECK(!vote.IsValid());

    // A park rate vote on unknown unit is invalid
    vote.vParkRateVote[0].cUnit = 'A';
    BOOST_CHECK(!vote.IsValid());

    // A park rate vote on nubits is valid
    vote.vParkRateVote[0].cUnit = 'B';
    BOOST_CHECK(vote.IsValid());

    // Two park rate vote on nubits is invalid
    parkRateVote.cUnit = 'B';
    vote.vParkRateVote.push_back(parkRateVote);
    BOOST_CHECK(!vote.IsValid());

    // Park rate with duration and 0 rate is valid
    vote.vParkRateVote.erase(vote.vParkRateVote.end());
    CParkRate parkRate;
    parkRate.nCompactDuration = 0;
    parkRate.nRate = 0;
    vote.vParkRateVote[0].vParkRate.push_back(parkRate);
    BOOST_CHECK(vote.IsValid());

    // Two valid park rates
    parkRate.nCompactDuration = 4;
    parkRate.nRate = 100;
    vote.vParkRateVote[0].vParkRate.push_back(parkRate);
    BOOST_CHECK(vote.IsValid());

    // Two times the same duration is invalid
    parkRate.nCompactDuration = 4;
    parkRate.nRate = 200;
    vote.vParkRateVote[0].vParkRate.push_back(parkRate);
    BOOST_CHECK(!vote.IsValid());
    vote.vParkRateVote[0].vParkRate.pop_back();

    // A valid custodian vote
    CCustodianVote custodianVote;
    custodianVote.cUnit = 'B';
    custodianVote.hashAddress = uint160(1);
    custodianVote.nAmount = 8 * COIN;
    vote.vCustodianVote.push_back(custodianVote);
    BOOST_CHECK(vote.IsValid());

    // Another unit is invalid
    vote.vCustodianVote[0].cUnit = 'S';
    BOOST_CHECK(!vote.IsValid());
    vote.vCustodianVote[0].cUnit = 'A';
    BOOST_CHECK(!vote.IsValid());
    vote.vCustodianVote[0].cUnit = 'B';

    // Voting for the same custodian and amount twice is invalid
    vote.vCustodianVote.push_back(custodianVote);
    BOOST_CHECK(!vote.IsValid());

    // If the amount is different it is valid
    vote.vCustodianVote[0].nAmount++;
    BOOST_CHECK(vote.IsValid());
    vote.vCustodianVote[0].nAmount--;

    // If the address is different it is valid
    vote.vCustodianVote[0].hashAddress++;
    BOOST_CHECK(vote.IsValid());
    vote.vCustodianVote[0].hashAddress--;
}

BOOST_AUTO_TEST_CASE(create_currency_coin_bases)
{
    vector<CVote> vVote;
    std::map<CBitcoinAddress, CBlockIndex*> mapAlreadyElected;

    // Zero vote results in no new currency
    vector<CTransaction> vCurrencyCoinBase;
    BOOST_CHECK(GenerateCurrencyCoinBases(vVote, mapAlreadyElected, vCurrencyCoinBase));
    BOOST_CHECK_EQUAL(0, vCurrencyCoinBase.size());

    // Add a vote without custodian vote
    CVote vote;
    vote.nCoinAgeDestroyed = 1000;
    vVote.push_back(vote);

    // Still no currency created
    BOOST_CHECK(GenerateCurrencyCoinBases(vVote, mapAlreadyElected, vCurrencyCoinBase));
    BOOST_CHECK_EQUAL(0, vCurrencyCoinBase.size());

    // Add a custodian vote with the same coin age
    CCustodianVote custodianVote;
    custodianVote.cUnit = 'B';
    custodianVote.hashAddress = uint160(1);
    custodianVote.nAmount = 8 * COIN;
    vote.vCustodianVote.push_back(custodianVote);
    vVote.push_back(vote);

    // Still no currency created
    BOOST_CHECK(GenerateCurrencyCoinBases(vVote, mapAlreadyElected, vCurrencyCoinBase));
    BOOST_CHECK_EQUAL(0, vCurrencyCoinBase.size());

    // The last vote has a little more weight
    vVote.back().nCoinAgeDestroyed++;

    // Still no currency created because this vote does not have the majority of blocks (we have 2 votes)
    BOOST_CHECK(GenerateCurrencyCoinBases(vVote, mapAlreadyElected, vCurrencyCoinBase));
    BOOST_CHECK_EQUAL(0, vCurrencyCoinBase.size());

    // Add a 3rd vote for the same custodian
    vVote.back().nCoinAgeDestroyed--;
    vote.nCoinAgeDestroyed = 1;
    vVote.push_back(vote);

    // This custodian should win and currecy should be created
    BOOST_CHECK(GenerateCurrencyCoinBases(vVote, mapAlreadyElected, vCurrencyCoinBase));
    BOOST_CHECK_EQUAL(1, vCurrencyCoinBase.size());
    CTransaction& tx = vCurrencyCoinBase[0];
    BOOST_CHECK(tx.IsCurrencyCoinBase());
    BOOST_CHECK_EQUAL('B', tx.cUnit);
    BOOST_CHECK_EQUAL(1, tx.vout.size());
    BOOST_CHECK_EQUAL(8 * COIN, tx.vout[0].nValue);
    CTxDestination address;
    BOOST_CHECK(ExtractDestination(tx.vout[0].scriptPubKey, address));
    BOOST_CHECK_EQUAL(uint160(1).ToString(), boost::get<CKeyID>(address).ToString());

    // This custodian has already been elected
    mapAlreadyElected[CBitcoinAddress(address, 'B')] = new CBlockIndex;

    // He should not receive any new currency
    BOOST_CHECK(GenerateCurrencyCoinBases(vVote, mapAlreadyElected, vCurrencyCoinBase));
    BOOST_CHECK_EQUAL(0, vCurrencyCoinBase.size());

    // Add a vote for another custodian to the existing votes
    custodianVote.hashAddress = uint160(2);
    custodianVote.nAmount = 5 * COIN;
    vVote[0].vCustodianVote.push_back(custodianVote);
    vVote[1].vCustodianVote.push_back(custodianVote);

    // And clear the already elected
    mapAlreadyElected.clear();

    // Both should receive new currency
    BOOST_CHECK(GenerateCurrencyCoinBases(vVote, mapAlreadyElected, vCurrencyCoinBase));
    BOOST_CHECK_EQUAL(1, vCurrencyCoinBase.size());
    tx = vCurrencyCoinBase[0];
    BOOST_CHECK(tx.IsCurrencyCoinBase());
    BOOST_CHECK_EQUAL('B', tx.cUnit);
    BOOST_CHECK_EQUAL(2, tx.vout.size());
    BOOST_CHECK_EQUAL(8 * COIN, tx.vout[0].nValue);
    BOOST_CHECK(ExtractDestination(tx.vout[0].scriptPubKey, address));
    BOOST_CHECK_EQUAL(uint160(1).ToString(), boost::get<CKeyID>(address).ToString());
    BOOST_CHECK_EQUAL(5 * COIN, tx.vout[1].nValue);
    BOOST_CHECK(ExtractDestination(tx.vout[1].scriptPubKey, address));
    BOOST_CHECK_EQUAL(uint160(2).ToString(), boost::get<CKeyID>(address).ToString());

    // But if they have the same address
    uint160 hashAddress = vVote[1].vCustodianVote.front().hashAddress;
    vVote[0].vCustodianVote.back().hashAddress = hashAddress;
    vVote[1].vCustodianVote.back().hashAddress = hashAddress;
    vVote[2].vCustodianVote.back().hashAddress = hashAddress;

    /*
    BOOST_FOREACH(const CVote& vote, vVote)
        BOOST_FOREACH(const CCustodianVote& custodianVote, vote.vCustodianVote)
            printf("addr=%d, amount=%d, weight=%d\n", custodianVote.hashAddress.Get64(), custodianVote.nAmount, vote.nCoinAgeDestroyed);
    */

    // Only the amount with the highest coin age is granted
    BOOST_CHECK(GenerateCurrencyCoinBases(vVote, mapAlreadyElected, vCurrencyCoinBase));
    BOOST_CHECK_EQUAL(1, vCurrencyCoinBase.size());

    tx = vCurrencyCoinBase[0];
    BOOST_CHECK(tx.IsCurrencyCoinBase());
    BOOST_CHECK_EQUAL('B', tx.cUnit);
    BOOST_CHECK_EQUAL(1, tx.vout.size());
    BOOST_CHECK_EQUAL(5 * COIN, tx.vout[0].nValue);
    BOOST_CHECK(ExtractDestination(tx.vout[0].scriptPubKey, address));
    BOOST_CHECK_EQUAL(uint160(1).ToString(), boost::get<CKeyID>(address).ToString());

    // If any vote is invalid the generation should fail
    vVote[1].vCustodianVote.back().cUnit = 'S';
    BOOST_CHECK(!GenerateCurrencyCoinBases(vVote, mapAlreadyElected, vCurrencyCoinBase));
    BOOST_CHECK_EQUAL(0, vCurrencyCoinBase.size());
}

BOOST_AUTO_TEST_CASE(premium_calculation)
{
    vector<CParkRateVote> vParkRateResult;
    CParkRateVote parkRateResult;
    parkRateResult.cUnit = 'B';
    parkRateResult.vParkRate.push_back(CParkRate( 2,  5 * COIN_PARK_RATE / COIN));
    parkRateResult.vParkRate.push_back(CParkRate( 5, 50 * COIN_PARK_RATE / COIN));
    parkRateResult.vParkRate.push_back(CParkRate( 3, 10 * COIN_PARK_RATE / COIN));
    parkRateResult.vParkRate.push_back(CParkRate(10,  1 * COIN_PARK_RATE));
    parkRateResult.vParkRate.push_back(CParkRate(12,  2 * COIN_PARK_RATE));
    parkRateResult.vParkRate.push_back(CParkRate(13,  5 * COIN_PARK_RATE));
    parkRateResult.vParkRate.push_back(CParkRate(15, 50 * COIN_PARK_RATE));
    parkRateResult.vParkRate.push_back(CParkRate(16, 40 * COIN_PARK_RATE));
    parkRateResult.vParkRate.push_back(CParkRate(17, 50 * COIN_PARK_RATE));
    vParkRateResult.push_back(parkRateResult);

    // Below minimum rate
    BOOST_CHECK_EQUAL( 0, GetPremium( 1 * COIN, 0, 'B', vParkRateResult));
    BOOST_CHECK_EQUAL( 0, GetPremium( 1 * COIN, 1, 'B', vParkRateResult));
    BOOST_CHECK_EQUAL( 0, GetPremium( 1 * COIN, 3, 'B', vParkRateResult));
    BOOST_CHECK_EQUAL( 0, GetPremium(10 * COIN, 3, 'B', vParkRateResult));

    // Above maximum rate
    BOOST_CHECK_EQUAL( 0, GetPremium(   1 * COIN, (1<<17)+1, 'B', vParkRateResult));
    BOOST_CHECK_EQUAL( 0, GetPremium(1000 * COIN, (1<<17)+1, 'B', vParkRateResult));
    BOOST_CHECK_EQUAL( 0, GetPremium(   1 * COIN,   1000000, 'B', vParkRateResult));

    // Exact durations
    BOOST_CHECK_EQUAL( 5, GetPremium(1   * COIN,  4, 'B', vParkRateResult));
    BOOST_CHECK_EQUAL(10, GetPremium(2   * COIN,  4, 'B', vParkRateResult));
    BOOST_CHECK_EQUAL( 0, GetPremium(0.1 * COIN,  4, 'B', vParkRateResult));
    BOOST_CHECK_EQUAL(10, GetPremium(1   * COIN,  8, 'B', vParkRateResult));
    BOOST_CHECK_EQUAL(99, GetPremium(9.9 * COIN,  8, 'B', vParkRateResult));
    BOOST_CHECK_EQUAL(50, GetPremium(1   * COIN, 32, 'B', vParkRateResult));
    BOOST_CHECK_EQUAL( 1 * COIN, GetPremium(1 * COIN,  1024, 'B', vParkRateResult));
    BOOST_CHECK_EQUAL( 2 * COIN, GetPremium(1 * COIN,  4096, 'B', vParkRateResult));
    BOOST_CHECK_EQUAL( 5 * COIN, GetPremium(1 * COIN,  8192, 'B', vParkRateResult));
    BOOST_CHECK_EQUAL(50 * COIN, GetPremium(1 * COIN, 1<<15, 'B', vParkRateResult));
    BOOST_CHECK_EQUAL(40 * COIN, GetPremium(1 * COIN, 1<<16, 'B', vParkRateResult));
    BOOST_CHECK_EQUAL(50 * COIN, GetPremium(1 * COIN, 1<<17, 'B', vParkRateResult));

    // Intermediate durations
    BOOST_CHECK_EQUAL( 6, GetPremium(1   * COIN,  5, 'B', vParkRateResult));
    BOOST_CHECK_EQUAL( 9, GetPremium(1.5 * COIN,  5, 'B', vParkRateResult));
    BOOST_CHECK_EQUAL(25, GetPremium(4   * COIN,  5, 'B', vParkRateResult));
    BOOST_CHECK_EQUAL( 8, GetPremium(1   * COIN,  7, 'B', vParkRateResult));
    BOOST_CHECK_EQUAL( 8, GetPremium(1   * COIN,  7, 'B', vParkRateResult));
    BOOST_CHECK_EQUAL(21, GetPremium(1   * COIN, 15, 'B', vParkRateResult));
    BOOST_CHECK_EQUAL(38, GetPremium(1   * COIN, 25, 'B', vParkRateResult));
    BOOST_CHECK_EQUAL((int64)(3.39453125 * COIN), GetPremium(1 * COIN, 6000, 'B', vParkRateResult));
    BOOST_CHECK_EQUAL((int64)(49.69482421875 * COIN), GetPremium(1 * COIN, (1<<15) + 1000, 'B', vParkRateResult));
}

BOOST_AUTO_TEST_CASE(vote_v1_unserialization)
{
    // Serialized with vote v1 code:
    /* {
    CVote vote;
    CCustodianVote custodianVote;
    custodianVote.cUnit = 'B';
    custodianVote.hashAddress = uint160(123465);
    custodianVote.nAmount = 100 * COIN;
    vote.vCustodianVote.push_back(custodianVote);
    printf("%s\n", vote.ToScript().ToString().c_str());
    printf("%s\n", HexStr(vote.ToScript()).c_str());
    } */
    vector<unsigned char> voteV1String = ParseHex("6a513701000000014249e201000000000000000000000000000000000040420f0000000000000000000000000000000000000000000000000000");

    CScript voteV1Script(voteV1String.begin(), voteV1String.end());

    CVote vote;
    BOOST_CHECK(ExtractVote(voteV1Script, vote));

    BOOST_CHECK_EQUAL(CBitcoinAddress(CKeyID(123465), 'B').ToString(), vote.vCustodianVote[0].GetAddress().ToString());
}

BOOST_AUTO_TEST_CASE(vote_before_multi_motion_unserialization)
{
    // Serialized with v0.4.2 vote code:
    /* {
    CVote vote;
    CCustodianVote custodianVote;
    custodianVote.cUnit = 'B';
    custodianVote.hashAddress = uint160(123465);
    custodianVote.nAmount = 100 * COIN;
    vote.vCustodianVote.push_back(custodianVote);
    vote.hashMotion = uint160("3f786850e387550fdab836ed7e6dc881de23001b");
    printf("%s\n", vote.ToScript().ToString().c_str());
    printf("%s\n", HexStr(vote.ToScript()).c_str());
    } */
    vector<unsigned char> oldVoteString = ParseHex("6a5138089d000001420049e201000000000000000000000000000000000040420f0000000000001b0023de81c86d7eed36b8da0f5587e35068783f");

    CScript oldVoteScript(oldVoteString.begin(), oldVoteString.end());

    CVote vote;
    BOOST_CHECK(ExtractVote(oldVoteScript, vote));

    BOOST_CHECK_EQUAL(1, vote.vMotion.size());
    BOOST_CHECK_EQUAL(uint160("3f786850e387550fdab836ed7e6dc881de23001b").ToString(), vote.vMotion[0].ToString());
}

BOOST_AUTO_TEST_SUITE_END()


text: #include <boost/preprocessor/if.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// Copyright (c) 2016 The Bitcoin XT developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/test/unit_test.hpp>

#include "test/dummyconnman.h"
#include "test/thinblockutil.h"
#include "compactblockprocessor.h"
#include "blockheaderprocessor.h"
#include "streams.h"
#include "txmempool.h"
#include "compactthin.h"
#include "chainparams.h"
#include "consensus/consensus.h"
#include "chain.h"

struct CmpctDummyHeaderProcessor : public BlockHeaderProcessor {

    CmpctDummyHeaderProcessor() : reqConnHeadResp(false) { }

    CBlockIndex* operator()(const std::vector<CBlockHeader>&, bool, bool) override {
        static CBlockIndex index;
        index.nHeight = 2;
        return &index;
    }
    bool requestConnectHeaders(const CBlockHeader& h, CConnman&, CNode& from, bool) override {
        return reqConnHeadResp;
    }
    bool reqConnHeadResp;
};

struct CBProcessorFixture {

    CBProcessorFixture() :
        thinmg(GetDummyThinBlockMg()),
        mpool(CFeeRate(0))
    {
        // test assert when pushing ping to pfrom if consensus params
        // are not set.
        SelectParams(CBaseChainParams::MAIN);

        // asserts if fPrintToDebugLog is true
        fPrintToDebugLog = false;
    }

    CDataStream toStream(const CompactBlock& b) {
        CDataStream blockstream(SER_NETWORK, PROTOCOL_VERSION);
        blockstream << b;
        return blockstream;
    }

    std::unique_ptr<ThinBlockManager> thinmg;
    CmpctDummyHeaderProcessor headerp;
    CTxMemPool mpool;
    DummyConnman connman;
};

BOOST_FIXTURE_TEST_SUITE(compactblockprocessor_tests, CBProcessorFixture);

BOOST_AUTO_TEST_CASE(accepts_parallel_compacts) {

    // We may receive a block announcement
    // as a compact block while we've already
    // requested a different block as compact.
    // We need to be willing to receive both.

    DummyNode node(42, thinmg.get());
    CompactWorker w(*thinmg, node.id);

    // start work on first block.
    uint256 block1 = uint256S("0xf00");
    w.addWork(block1);

    CompactBlockProcessor p(connman, node, w, headerp);

    CBlock block2 = TestBlock1();
    CDataStream blockstream = toStream(
            CompactBlock(block2, CoinbaseOnlyPrefiller{}));

    // cblock2 is announced, should start work on
    // that too.
    p(blockstream, mpool, MAX_BLOCK_SIZE, 1);

    BOOST_CHECK(w.isWorkingOn(block1));
    BOOST_CHECK(w.isWorkingOn(block2.GetHash()));
    BOOST_CHECK_EQUAL(1, thinmg->numWorkers(block1));
    BOOST_CHECK_EQUAL(1, thinmg->numWorkers(block2.GetHash()));
    w.stopAllWork();
    thinmg.reset();
}

BOOST_AUTO_TEST_CASE(two_process_same) {
    // Check that two nodes can process the same block at the same time,
    // even though it's two compact blocks with different idks

    CBlock block = TestBlock1();

    DummyNode node1(12, thinmg.get());
    DummyNode node2(21, thinmg.get());

    CompactWorker w1(*thinmg, node1.id);
    CompactWorker w2(*thinmg, node2.id);

    CompactBlock c1(block, CoinbaseOnlyPrefiller{});
    CompactBlock c2(block, CoinbaseOnlyPrefiller{}); // Has differet idks

    CompactBlockProcessor p1(connman, node1, w1, headerp);
    CompactBlockProcessor p2(connman, node2, w2, headerp);

    CDataStream s1 = toStream(c1);
    CDataStream s2 = toStream(c2);
    p1(s1, mpool, MAX_BLOCK_SIZE, 1);
    p2(s2, mpool, MAX_BLOCK_SIZE, 1);

    // both should be working on the block still
    BOOST_CHECK(w1.isWorkingOn(block.GetHash()));
    BOOST_CHECK(w2.isWorkingOn(block.GetHash()));

    // both should have sent a transaction re-request
    BOOST_CHECK(connman.MsgWasSent(node1, "getblocktxn"));
    BOOST_CHECK(connman.MsgWasSent(node2, "getblocktxn"));
};

BOOST_AUTO_TEST_CASE(discard_if_missing_prev) {
    // discard block (stop working on it) if we don't
    // have header for the previous block.

    CBlock block = TestBlock1();

    DummyNode node(11, thinmg.get());
    DummyConnman connman;
    CompactWorker w(*thinmg, node.id);
    CompactBlock c(block, CoinbaseOnlyPrefiller{});
    CDataStream s = toStream(c);

    headerp.reqConnHeadResp = true; // we need to request prev header (we don't have it)

    CompactBlockProcessor p(connman, node, w, headerp);
    p(s, mpool, MAX_BLOCK_SIZE, 1);

    // should have discarded block.
    BOOST_CHECK(!w.isWorkingOn(block.GetHash()));
};

BOOST_AUTO_TEST_SUITE_END();


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.

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

// 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_MULTI_ALGORITHMS_APPEND_HPP
#define BOOST_GEOMETRY_MULTI_ALGORITHMS_APPEND_HPP

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

#include <boost/geometry/core/tags.hpp>
#include <boost/geometry/geometries/concepts/check.hpp>

namespace boost { namespace geometry
{

#ifndef DOXYGEN_NO_DETAIL
namespace detail { namespace append
{

template <typename MultiGeometry, typename RangeOrPoint>
struct append_to_multigeometry
{
    static inline void apply(MultiGeometry& multigeometry,
                             RangeOrPoint const& range_or_point,
                             int ring_index, int multi_index)
    {

        dispatch::append
            <
                typename boost::range_value<MultiGeometry>::type,
                RangeOrPoint
            >::apply(multigeometry[multi_index], range_or_point, ring_index);
    }
};

}} // namespace detail::append
#endif // DOXYGEN_NO_DETAIL

#ifndef DOXYGEN_NO_DISPATCH
namespace dispatch
{

namespace splitted_dispatch
{

template <typename Geometry, typename Point>
struct append_point<multi_point_tag, Geometry, Point>
    : detail::append::append_point<Geometry, Point>
{};

template <typename Geometry, typename Range>
struct append_range<multi_point_tag, Geometry, Range>
    : detail::append::append_range<Geometry, Range>
{};

template <typename MultiGeometry, typename RangeOrPoint>
struct append_point<multi_linestring_tag, MultiGeometry, RangeOrPoint>
    : detail::append::append_to_multigeometry<MultiGeometry, RangeOrPoint>
{};

template <typename MultiGeometry, typename RangeOrPoint>
struct append_range<multi_linestring_tag, MultiGeometry, RangeOrPoint>
    : detail::append::append_to_multigeometry<MultiGeometry, RangeOrPoint>
{};

template <typename MultiGeometry, typename RangeOrPoint>
struct append_point<multi_polygon_tag, MultiGeometry, RangeOrPoint>
    : detail::append::append_to_multigeometry<MultiGeometry, RangeOrPoint>
{};

template <typename MultiGeometry, typename RangeOrPoint>
struct append_range<multi_polygon_tag, MultiGeometry, RangeOrPoint>
    : detail::append::append_to_multigeometry<MultiGeometry, RangeOrPoint>
{};

}

} // namespace dispatch
#endif // DOXYGEN_NO_DISPATCH

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_MULTI_ALGORITHMS_APPEND_HPP

max_stars_repo_name: cooparation/caffe-android

max_issues_repo_name: cooparation/caffe-android

max_forks_repo_name: cooparation/caffe-android


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

#include "typename.h"

#include <boost/core/demangle.hpp>

#include <stdexcept>

namespace tigl
{

std::string typeName(const std::type_info& ti)
{
    // name holds fully qualified class name
    // boost::demangle is required for GCC, just passes through string on VC++
    std::string name = boost::core::demangle(ti.name()); // e.g. "[class] tigl::CCPACSWing"

    // strip leading "class" (VC++)
    const size_t  pos = name.find_last_of(' ');
    if (pos != std::string::npos) {
        name = name.substr(pos + 1); // e.g. "tigl::CCPACSWing"
    }

    return name;
}

} // namespace tigl

max_stars_repo_name: cfsengineering/tigl

max_issues_repo_name: cfsengineering/tigl

max_forks_repo_name: cfsengineering/tigl


text:
//
//  steps.cpp
//  yamcmc++
//
//  Created by Brandon Kelly on 3/2/13.
//  Copyright (c) 2013 Brandon Kelly. All rights reserved.
//

#include <boost/timer.hpp>
// Local includes
#include "include/steps.hpp"

// Global random number generator object, instantiated in random.cpp
extern boost::random::mt19937 rng;

// Object containing some common random number generators.
RandomGenerator RandGen;

/* ****** Methods of AdaptiveMetro class ********* */

// Constructor, requires a parameter object, a proposal object, an initial
// covariance matrix for the multivariate proposals, a target acceptance rate,
// and the maximum number of iterations to perform the adaptations for.
AdaptiveMetro::AdaptiveMetro(Parameter<arma::vec>& parameter, Proposal<double>& proposal,
                             arma::mat proposal_covar, double target_rate, int maxiter) :
parameter_(parameter), proposal_(proposal),
target_rate_(target_rate), maxiter_(maxiter)
{
	gamma_ = 2.0 / 3.0;
	niter_ = 0;
	naccept_ = 0;
	chol_factor_ = arma::chol(proposal_covar);
}

// Method to calculate whether the proposal is accepted
bool AdaptiveMetro::Accept(arma::vec new_value, arma::vec old_value) {

	// MH accept/reject criteria: Proposal must be symmetric!!
	alpha_ = (parameter_.LogDensity(new_value) - parameter_.GetLogDensity()) / parameter_.GetTemperature();

	if (!arma::is_finite(alpha_)) {
		// New value of the log-posterior is not finite, so reject this
		// proposal
        alpha_ = 0.0;
		return false;
	}

	double unif = uniform_(rng);
	alpha_ = std::min(exp(alpha_), 1.0);
	if (unif < alpha_) {
		naccept_++;
		return true;
	} else {
		return false;
	}
}

// Method to perform the RAM step. This involves a standard Metropolis-Hastings update, followed
// by an update to the proposal scale matrix so long as niter < maxiter
void AdaptiveMetro::DoStep()
{
	arma::vec old_value = parameter_.Value();

	// Draw a new parameter vector
	arma::vec unit_proposal(old_value.n_rows);
	for (int i=0; i<old_value.n_rows; i++) {
		// Unscaled proposal
		unit_proposal(i) = proposal_.Draw(0.0);
	}

	// Scaled proposal vector
	arma::vec scaled_proposal = chol_factor_.t() * unit_proposal;
	arma::vec new_value = old_value + scaled_proposal;

	// MH accept/reject criteria
	if (Accept(new_value, old_value)) {
		parameter_.Save(new_value);
	}

    double step_size, unit_norm;

	if ((niter_ < maxiter_) && arma::is_finite(alpha_)) {
		// Still in the adaptive stage, so update the scale matrix cholesky factor

		// The step size sequence for the scale matrix update. This is eta_n in the
		// notation of Vihola (2012)
		step_size = std::min(1.0, new_value.n_rows / pow(niter_, gamma_));

		unit_norm = arma::norm(unit_proposal, 2);

		// Rescale the proposal vector for updating the scale matrix cholesky factor
		scaled_proposal = sqrt(step_size * fabs(alpha_ - target_rate_)) / unit_norm * scaled_proposal;

		// Update or downdate the Cholesky factor?
		bool downdate = (alpha_ < target_rate_);

		// Perform the rank-1 update (downdate) of the scale matrix Cholesky factor
		CholUpdateR1(chol_factor_, scaled_proposal, downdate);
	}

	niter_++;

	if (niter_ == maxiter_) {
		double arate = ((double)(naccept_)) / ((double)(niter_));
		std::cout << "Average RAM Acceptance Rate is " << arate << std::endl;
	}
}

// Function to perform the rank-1 Cholesky update, needed for updating the
// proposal covariance matrix
void CholUpdateR1(arma::mat& L, arma::vec& v, bool downdate)
{
	double sign = 1.0;
	if (downdate) {
		// Perform the downdate instead
		sign = -1.0;
	}
	for (int k=0; k<L.n_rows; k++) {
		double r = sqrt( L(k,k) * L(k,k) + sign * v(k) * v(k) );
		double c = r / L(k,k);
		double s = v(k) / L(k,k);
		L(k,k) = r;
		if (k < L.n_rows-1) {
			L(k,arma::span(k+1,L.n_rows-1)) = (L(k,arma::span(k+1,L.n_rows-1)) +
                                               sign * s * v(arma::span(k+1,v.n_elem-1)).t()) / c;
			v(arma::span(k+1,v.n_elem-1)) = c * v(arma::span(k+1,v.n_elem-1)) -
			s * L(k,arma::span(k+1,L.n_rows-1)).t();
		}

	}
}


text:
#include "teca_table_to_stream.h"

#include "teca_table.h"
#include "teca_array_collection.h"
#include "teca_variant_array.h"
#include "teca_metadata.h"

#include <algorithm>
#include <iostream>
#include <string>
#include <set>
#include <cmath>

#if defined(TECA_HAS_BOOST)
#include <boost/program_options.hpp>
#endif

#if defined(TECA_HAS_MPI)
#include <mpi.h>
#endif

using std::string;
using std::vector;
using std::set;
using std::cerr;
using std::endl;

//#define TECA_DEBUG

// --------------------------------------------------------------------------
teca_table_to_stream::teca_table_to_stream() : stream(&std::cerr)
{
    this->set_number_of_input_connections(1);
    this->set_number_of_output_ports(1);
}

// --------------------------------------------------------------------------
teca_table_to_stream::~teca_table_to_stream()
{}

#if defined(TECA_HAS_BOOST)
// --------------------------------------------------------------------------
void teca_table_to_stream::get_properties_description(
    const string &prefix, options_description &global_opts)
{
    options_description opts("Options for "
        + (prefix.empty()?"teca_table_to_stream":prefix));

    opts.add_options()
        TECA_POPTS_GET(std::string, prefix, header,
            "text to precede table output")
        TECA_POPTS_GET(std::string, prefix, footer,
            "text to follow table output")
        TECA_POPTS_GET(std::string, prefix, stream,
            "name of stream to send output to. stderr, stdout")
        ;
    global_opts.add(opts);
}

// --------------------------------------------------------------------------
void teca_table_to_stream::set_properties(
    const string &prefix, variables_map &opts)
{
    TECA_POPTS_SET(opts, std::string, prefix, header)
    TECA_POPTS_SET(opts, std::string, prefix, footer)
    TECA_POPTS_SET(opts, std::string, prefix, stream)
}
#endif

// --------------------------------------------------------------------------
void teca_table_to_stream::set_stream(std::ostream &s)
{
    this->stream = &s;
}

// --------------------------------------------------------------------------
void teca_table_to_stream::set_stream(const std::string &s)
{
    if ((s == "stderr") || (s == "err") || (s == "cerr") || (s == "std::cerr"))
    {
        this->set_stream_to_stderr();
    }
    else
    if ((s == "stdout") || (s == "out") || (s == "cout") || (s == "std::cout"))
    {
        this->set_stream_to_stdout();
    }
    else
    {
        TECA_ERROR("unknown stream requested \"" << s << "\"")
    }
}

// --------------------------------------------------------------------------
void teca_table_to_stream::set_stream_to_stderr()
{
    this->stream = &std::cerr;
}

// --------------------------------------------------------------------------
void teca_table_to_stream::set_stream_to_stdout()
{
    this->stream = &std::cout;
}

// --------------------------------------------------------------------------
const_p_teca_dataset teca_table_to_stream::execute(
    unsigned int port,
    const std::vector<const_p_teca_dataset> &input_data,
    const teca_metadata &request)
{
#ifdef TECA_DEBUG
    cerr << teca_parallel_id() << "teca_table_to_stream::execute" << endl;
#endif
    (void)port;
    (void)request;

    if (!this->stream)
    {
        TECA_ERROR("output stream not set")
        return nullptr;
    }

    // get the input
    const_p_teca_table in_table
        = std::dynamic_pointer_cast<const teca_table>(input_data[0]);

    // in parallel only rank 0 is required to have data
    int rank = 0;
#if defined(TECA_HAS_MPI)
    int init = 0;
    MPI_Initialized(&init);
    if (init)
        MPI_Comm_rank(this->get_communicator(), &rank);
#endif
    if (!in_table)
    {
        if (rank == 0)
        {
            TECA_ERROR("empty input")
        }
        return nullptr;
    }

    // pass the data through so this can sit anywhere in the pipeline
    p_teca_table out_table = teca_table::New();
    out_table->shallow_copy(std::const_pointer_cast<teca_table>(in_table));

    if (!this->header.empty())
        *this->stream << this->header << std::endl;
    out_table->to_stream(*this->stream);
    if (!this->footer.empty())
        *this->stream << this->footer << std::endl;

    return out_table;
}

ext: cxx


text:
#include "Config.h"
#include "Debug.h"
#include <boost/algorithm/string.hpp>
#include <iostream>
#include <fstream>

namespace cdtags {

fs::path
configFile()
{
  static const fs::path file = ".config/cdtags/config";
  // Read configuration
  fs::path home(getenv("HOME"));
  return home / file;
}

Config
parseConfig()
{
  namespace alg = boost::algorithm;
  // Check to see if the file exits...
  if (!fs::is_regular_file(configFile())) {
    return Config();
  }

  Config cfg;

  std::ifstream in(configFile().c_str());
  std::string line;
  size_t lineNo = 0;
  while (std::getline(in, line)) {
    lineNo++;
    alg::trim(line);
    // ignore blank lines or comments.
    if (line.empty() || line[0] == '#') {
      continue;
    }
    std::vector<std::string> fields;
    alg::split(fields, line, alg::is_any_of(","));

    if (fields.size() < 2) {
      std::cerr << "Warning : (" << lineNo << ") Insufficient fields" << line
                << std::endl;
      continue;
    }

    for (int i = 1; i < fields.size(); ++i) {
      if (fields[i].empty())
        continue; // ignore empty tags
      cfg.paths[fields[i]] = fields[0];
      cfg.aliases[fields[0]].insert(fields[i]);
    }
  }
  return cfg;
}

void
saveConfig(const Config& m)
{

  if (!fs::is_directory(configFile().parent_path())) {
    std::cout << "Creating: " << configFile().parent_path() << std::endl;
    fs::create_directories(configFile().parent_path());
  }

  std::ofstream out(configFile().c_str());
  for (const auto& path : m.aliases) {
    DEBUG("Path: " << path.first);
    out << path.first.string() << ",";
    for (const auto& p : path.second) {
      DEBUG(p);
      out << p << ",";
    }
    out << '\n';
  }
}
}


text:
// (c) Copyright Juergen Hunold 2016
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE.txt or copy at
// https://www.bfgroup.xyz/b2/LICENSE.txt)

#define BOOST_TEST_MODULE QtBluetooth

#include <QtBluetooth>

#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_CASE( defines)
{
    BOOST_CHECK_EQUAL(BOOST_IS_DEFINED(QT_CORE_LIB), true);
    BOOST_CHECK_EQUAL(BOOST_IS_DEFINED(QT_BLUETOOTH_LIB), true);
}

/*!
  Try to detect a device
 */
BOOST_AUTO_TEST_CASE( bluetooth )
{
    QList<QBluetoothHostInfo> localAdapters = QBluetoothLocalDevice::allDevices();

    if (!localAdapters.empty())
    {
        QBluetoothLocalDevice adapter(localAdapters.at(0).address());
        adapter.setHostMode(QBluetoothLocalDevice::HostDiscoverable);
    }
    else
    {
        BOOST_TEST(localAdapters.size() == 0);
    }
}

max_stars_repo_name: loongson-zn/build

max_issues_repo_name: loongson-zn/build

max_forks_repo_name: loongson-zn/build


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

#include <boost/simd/include/functor.hpp>
#include <boost/dispatch/include/functor.hpp>

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

      Represents the slide function in generic contexts.

      @par Models:
      Hierarchy
    **/
    struct slide_ : ext::abstract_<slide_>
    {
      /// @brief Parent hierarchy
      typedef ext::abstract_<slide_> parent;
      template<class... Args>
      static BOOST_FORCEINLINE BOOST_AUTO_DECLTYPE dispatch(Args&&... args)
      BOOST_AUTO_DECLTYPE_BODY( dispatching_slide_( ext::adl_helper(), static_cast<Args&&>(args)... ) )
    };
  }
  namespace ext
  {
    template<class Site, class... Ts>
    BOOST_FORCEINLINE generic_dispatcher<tag::slide_, Site> dispatching_slide_(adl_helper, boost::dispatch::meta::unknown_<Site>, boost::dispatch::meta::unknown_<Ts>...)
    {
      return generic_dispatcher<tag::slide_, Site>();
    }
    template<class... Args>
    struct impl_slide_;
  }

  /*!
    @brief Shifted truncation of two vectors

    Compute a vector made of the first elements of the vector obtained by
    shifting the concatenation of @c a0 and @c a1 by @c N elements on the left
    or on the right depending on the sign of @c N.

    @par Semantic:

    @tparam N
    @param  a0
    @param  a1
  **/
  template<int N, typename A0, typename A1>
  BOOST_FORCEINLINE
  typename boost::dispatch::meta
                ::call<tag::slide_( A0 const&, A1 const&
                                  , mpl::int_<N> const&
                                  )>::type
  slide(A0 const& a0, A1 const& a1)
  {
    typename  boost::dispatch::meta
            ::dispatch_call<tag::slide_ ( A0 const&, A1 const&
                                        , mpl::int_<N> const&
                                        )>::type          callee;

    return callee(a0, a1, mpl::int_<N>());
  }

  /*!
    @brief Global vector shifting

    Compute a vector made of the first elements of the vector obtained by
    shifting left the concatenation of @c a0 by @c N elements on the left or
    on the right depending on the sign of @c N.

    @tparam N
    @param  a0
  **/
  template<int N, typename A0>
  BOOST_FORCEINLINE
  typename boost::dispatch::meta
                ::call<tag::slide_(A0 const&, mpl::int_<N> const&)>::type
  slide(A0 const& a0)
  {
    typename  boost::dispatch::meta
            ::dispatch_call<tag::slide_ ( A0 const&
                                        , mpl::int_<N> const&
                                        )>::type          callee;

    return callee(a0, mpl::int_<N>());
  }
} }

#endif


text:
/**
 * This file contains summary statistics template functions for Eigen::Matrix data types.
 *
 * More functions are added once a need for the particular function necessitates their development. In other words,
 * until there is a use for developing a summary statistic, I will not implement it. For example, as of right now, there
 * is no kurtosis function, because there are no clients nor any other functions within the library requiring a kurtosis
 * function.
 */

#ifndef PROMETHEUS_SUMMARY_STATISTICS_HPP
#define PROMETHEUS_SUMMARY_STATISTICS_HPP

#include <Eigen/Dense>

// zach's-attempt-at-math
namespace zaamath {
    /**
     * computes the sample mean of a given dataset represented by a matrix whose columns represent different populations
     * @tparam T the datatype of the input matrix (int, float, double, custom, etc.)
     * @tparam RowIndexType the number of rows of the input datatype
     * @tparam ColIndexType the number of columns of the input datatype
     * @param data the data represented by an Eigen::Matrix (vector or matrix)
     * @return the sample mean of the data
     */
    template <class T, int RowIndexType, int ColIndexType>
    Eigen::Matrix<T, 1, ColIndexType> sample_mean(const Eigen::Matrix<T, RowIndexType, ColIndexType>& data) {
        return data.colwise().mean();
    }

    /**
     * computes the sample variance of a given dataset represented by a matrix whose columns represent different
     * populations
     * @tparam T the datatype of the input matrix (int, float, double, custom, etc.)
     * @tparam RowIndexType the number of rows of the input datatype
     * @tparam ColIndexType the number of columns of the input datatype
     * @param data the data represented by an Eigen::Matrix (vector or matrix)
     * @return the sample variance of the data
     */
    template <class T, int RowIndexType, int ColIndexType>
    Eigen::Matrix<T, 1, ColIndexType> sample_var(const Eigen::Matrix<T, RowIndexType, ColIndexType>& data) {
        auto means = data.colwise().mean();
        return (data.rowwise() - means).colwise().squaredNorm() / (data.rows() - 1);
    }

    /**
     * computes the sample standard deviation of a given dataset represented by a matrix whose columns represent
     * different populations
     * @tparam T the datatype of the input matrix (int, float, double, custom, etc.)
     * @tparam RowIndexType the number of rows of the input datatype
     * @tparam ColIndexType the number of columns of the input datatype
     * @param data the data represented by an Eigen::Matrix (vector or matrix)
     * @return the sample standard deviation of the data
     */
    template <class T, int RowIndexType, int ColIndexType>
    Eigen::Matrix<T, 1, ColIndexType> sample_std_dev(const Eigen::Matrix<T, RowIndexType, ColIndexType>& data) {
        auto var = sample_var(data);
        return var.array().sqrt();
    }

    /**
     * computes the range of a given dataset represented by a matrix whose columns represent different populations
     * @tparam T the datatype of the input matrix (int, float, double, custom, etc.)
     * @tparam RowIndexType the number of rows of the input datatype
     * @tparam ColIndexType the number of columns of the input datatype
     * @param data the data represnted by an Eigen::Matrix (vector or matrix)
     * @return the range of each column (max element - min element)
     */
    template <class T, int RowIndexType, int ColIndexType>
    Eigen::Matrix<T, 1, ColIndexType> range(const Eigen::Matrix<T, RowIndexType, ColIndexType>& data) {
        return data.colwise().maxCoeff() - data.colwise().minCoeff();
    }

};

#endif //PROMETHEUS_SUMMARY_STATISTICS_HPP

max_stars_repo_name: zborffs/AsterionEngine

max_issues_repo_name: zborffs/AsterionEngine

max_forks_repo_name: zborffs/AsterionEngine


text:
////////////////////////////////////////////////////////////////////////////////
///
/// \file posix/error.hpp
/// ---------------------
///
/// Copyright (c) Domagoj Saric 2010 - 2015.
///
/// 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)
///
/// For more information, see http://www.boost.org
///
////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------
#ifndef error_hpp__F043103F_57C5_4EFA_A947_15EE812CF090
#define error_hpp__F043103F_57C5_4EFA_A947_15EE812CF090
#pragma once
//------------------------------------------------------------------------------
#include "boost/mmap/detail/impl_selection.hpp"

#include <boost/err/errno.hpp>
//------------------------------------------------------------------------------
namespace boost
{
//------------------------------------------------------------------------------
namespace mmap
{
//------------------------------------------------------------------------------
BOOST_MMAP_POSIX_INLINE
namespace posix
{
//------------------------------------------------------------------------------

using error = err::last_errno;

//------------------------------------------------------------------------------
} // namespace posix
//------------------------------------------------------------------------------
} // namespace mmap
//------------------------------------------------------------------------------
} // namespace boost
//------------------------------------------------------------------------------
#endif // errno_hpp

max_stars_repo_name: microblink/mmap

max_issues_repo_name: microblink/mmap

max_forks_repo_name: microblink/mmap