text:
#pragma once

#include <boost/bimap.hpp>
#include <boost/bimap/list_of.hpp>
#include <boost/bimap/set_of.hpp>
#include <boost/function.hpp>

#include "config.hpp"
#include "misc.hpp"
#include "numerics.hpp"
#include "cycletimer.hpp"

#if ENABLE_MULTITHREADING && ENABLE_OPENMP
#include <omp.h>
#endif

/// This header file implements multiple versions of an LRU cache.
///
/// SingleCache is the basic cache implementation, where all threads
/// are expected to access a single cache.
///
/// MultiCache implements 1 SingleCache for each thread, avoiding the
/// need for locking in each of the Caches.
///
/// MultiRingCache implements 1 SingleCache for each thread, however, each
/// cache is responsible for a sequential set of key values (instead of
/// each cache being responsible for a thread) arranged in a ring.
/// However, each SingleCache must be lock protected, since multiple threads
/// may map their keys to the same cache.
///
/// MultiRingPriorityCache implements the same thing as the MultiRingCache
/// except there are no locks within each SingleCache.  Instead the lock
/// exists within the ring such that a thread will try to choose the cache
/// that has been assigned to the key value if possible, otherwise it will just
/// query the next non locked cache.

/// Defines an LRU cache.
/// If B is true, this class is thread safe, else it is not thread safe.
/// K is the key type, V is the value type, and SET is the SET storage type, ex. boost::bimap::set_of
template <bool B, typename K, typename V>
class SingleCache {
 public:
  typedef boost::bimaps::bimap<boost::bimaps::set_of<K>, boost::bimaps::list_of<V> > container_type;

  // Constuctor specifies the cached function and
  // the maximum number of records to be stored.
  SingleCache(const boost::function<V(const K&)>& f, size_t c) : _fn(f), _capacity(c) {
    _hits = 0;
    _misses = 0;
  }

  // Non locking version
  template<typename U = V> typename std::enable_if<!B, U>::type operator()(const K& k) {
    SCOPED_TIMER

    const typename container_type::left_iterator it = _container.left.find(k);
    if (it == _container.left.end()) {
      V v = _fn(k);
      insert(k,v);
      _misses++;
      return v;
    } else {
      _container.right.relocate(_container.right.end(), _container.project_right(it));
      _hits++;
      return it->second;
    }

  }

  template<typename U = std::vector<V> > typename std::enable_if<!B, U>::type operator()(const std::vector<K> &k) {
    U u(k.size());
    for(size_t i=0; i<k.size(); i++) {
      u[i] = (*this)(k);
    }
    return u;
  }

  // Locking version
  template<typename U = V> typename std::enable_if<B, U>::type operator()(const K& k) {
    SCOPED_TIMER

    V v;
    #pragma omp critical
    {
      const typename container_type::left_iterator it = _container.left.find(k);
      if (it == _container.left.end()) {
        v = _fn(k);
        insert(k,v);
        // _misses++;
      } else {
        _container.right.relocate(_container.right.end(), _container.project_right(it));
        v = it->second;
        // _hits++;
      }
    }
    return v;
  }

  template<typename U = std::vector<V> > typename std::enable_if<B, U>::type operator()(const std::vector<K> &k) {
    U u(k.size());
    for(size_t i=0; i<k.size(); i++) {
      u[i] = (*this)(k);
    }
    return u;
  }

  uint64_t capacity()         const { return _capacity; }
  // uint64_t hits() const { return _hits; }
  // uint64_t misses() const { return _misses; }

 private:
  void insert(const K& k, const V& v) {
    if (_container.size() == _capacity) {
      _container.right.erase(_container.right.begin());
    }
    _container.insert(typename container_type::value_type(k,v));
  }

  const boost::function<V(const K&)> _fn;
  const size_t _capacity;
  container_type _container;
  uint64_t _hits, _misses;
};

#if ENABLE_MULTITHREADING && ENABLE_OPENMP
/// Implements a SingleCache for each OpenMP thread.
template <typename K, typename V>
class MultiCache {
 public:

  MultiCache(const boost::function<V(const K&)>& f, size_t c) : _fn(f), _capacity(c) {
    for(int i=0; i < omp_get_max_threads(); i++){
      _caches.push_back(PTR_LIB::make_shared<SingleCache<false, K, V>>(f, c / omp_get_max_threads()));
    }
  }

  // Obtain value of the cached function for k
  V operator()(const K& k) {
    SCOPED_TIMER
    return (*_caches[omp_get_thread_num()])(k);
  }

  uint64_t capacity() const { return _capacity; }

 private:

  std::vector< PTR_LIB::shared_ptr<SingleCache<false, K, V> > > _caches;
  const boost::function<V(const K&)> _fn;
  const size_t _capacity;
};

/// Implements a SingleCache for each OpenMP thread, where each cache is responsible
/// for sequential ranges of items, this requires that K has modulo operator % and a relation operator <.
/// This is essentially a bunch of caches arranged in a ring topology.
template <typename K, typename V>
class MultiRingCache {
 public:

  MultiRingCache(const boost::function<V(const K&)>& f, size_t c) : _fn(f), _capacity(c), _single_capacity(c / omp_get_max_threads()) {
    for(int i=0; i < omp_get_max_threads(); i++){
      _caches.push_back(PTR_LIB::make_shared<SingleCache<false, K, V>>(f, _single_capacity));
    }
  }

  // Obtain value of the cached function for k
  V operator()(const K& k) {
    SCOPED_TIMER
    return (*_caches[(size_t)(k / _single_capacity) % omp_get_max_threads()])(k);
  }

  uint64_t capacity() const { return _capacity; }

 private:
  std::vector< PTR_LIB::shared_ptr<SingleCache<false, K, V> > > _caches;
  const boost::function<V(const K&)> _fn;
  const size_t _capacity, _single_capacity;
};

/// Implements a SingleCache for each OpenMP thread, where each cache is responsible
/// for sequential ranges of items, this requires that K has modulo operator % and a relation operator <.
/// This is essentially a bunch of caches arranged in a ring topology.
template <typename K, typename V>
class MultiRingPriorityCache {
 public:

  MultiRingPriorityCache(const boost::function<V(const K&)>& f, size_t c) : _fn(f), _capacity(c),
    _single_capacity(c / omp_get_max_threads()) {

    _locks.resize(omp_get_max_threads());
    for(int i=0; i < omp_get_max_threads(); i++){
      _caches.push_back(PTR_LIB::make_shared<SingleCache<false, K, V>>(f, _single_capacity));
      omp_init_lock(&_locks[i]);
    }
  }

  // Obtain value of the cached function for k
  V operator()(const K& k) {
    SCOPED_TIMER
    // double startlookup = CycleTimer::currentSeconds();
    for(size_t i = 0; i<omp_get_max_threads(); i++) {
      size_t cache_idx = ((size_t)(k / _single_capacity)+i) % omp_get_max_threads();
      int lock_acquired = omp_test_lock(&_locks[cache_idx]);
      if(lock_acquired) {
        V v = (*_caches[cache_idx])(k);
        omp_unset_lock(&_locks[cache_idx]);
        return v;
      }
    }

    size_t cache_idx = ((size_t)(k / _single_capacity)) % omp_get_max_threads();
    omp_set_lock(&_locks[cache_idx]);
    V v = (*_caches[cache_idx])(k);
    omp_unset_lock(&_locks[cache_idx]);

    return v;
  }

  uint64_t capacity() const { return _capacity; }

 private:

  std::vector< PTR_LIB::shared_ptr<SingleCache<false, K, V> > > _caches;
  std::vector<omp_lock_t> _locks;

  const boost::function<V(const K&)> _fn;
  const size_t _capacity, _single_capacity;
  double _lookup_time_total;
};

typedef MultiRingPriorityCache<uint64_t, numerics::sparse_vector_t> bow_ring_priority_cache_t;
typedef MultiRingCache<uint64_t, numerics::sparse_vector_t> bow_ring_cache_t;
typedef MultiCache<uint64_t, numerics::sparse_vector_t> bow_multi_cache_t;

typedef MultiRingPriorityCache<uint64_t,  std::vector<float>> vec_ring_priority_cache_t;
typedef MultiRingCache<uint64_t,  std::vector<float>> vec_ring_cache_t;
typedef MultiCache<uint64_t, std::vector<float>> vec_multi_cache_t;

#endif

typedef SingleCache<true, uint64_t, numerics::sparse_vector_t> bow_single_cache_t;
typedef SingleCache<true, uint64_t, std::vector<float>> vec_single_cache_t;

max_stars_repo_name: psastras/vocabtree

max_issues_repo_name: psastras/vocabtree

max_forks_repo_name: psastras/vocabtree


text:
/*=============================================================================
    Copyright (c) 2001-2007 Joel de Guzman

    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(BOOST_SPIRIT_LIT_APR_18_2006_1125PM)
#define BOOST_SPIRIT_LIT_APR_18_2006_1125PM

#include <boost/spirit/home/qi/domain.hpp>
#include <boost/spirit/home/qi/skip.hpp>
#include <boost/spirit/home/qi/detail/string_parse.hpp>
#include <boost/spirit/home/support/char_class.hpp>
#include <boost/spirit/home/support/modifier.hpp>
#include <boost/spirit/home/support/unused.hpp>
#include <boost/spirit/home/support/detail/to_narrow.hpp>
#include <boost/fusion/include/at.hpp>
#include <boost/fusion/include/value_at.hpp>
#include <boost/fusion/include/vector.hpp>
#include <boost/type_traits/remove_reference.hpp>
#include <string>

namespace boost { namespace spirit { namespace qi
{
    ///////////////////////////////////////////////////////////////////////////
    // parse literal strings
    ///////////////////////////////////////////////////////////////////////////
    template <typename Char>
    struct literal_string
    {
        template <typename Component, typename Context, typename Iterator>
        struct attribute
        {
            typedef unused_type type;   // literal parsers have no attribute
        };

        template <
            typename Component
          , typename Iterator, typename Context
          , typename Skipper, typename Attribute>
        static bool parse(
            Component const& component
          , Iterator& first, Iterator const& last
          , Context& /*context*/, Skipper const& skipper
          , Attribute& attr)
        {
            qi::skip(first, last, skipper);
            return detail::string_parse(
                fusion::at_c<0>(component.elements)
              , first
              , last
              , attr
            );
        }

        template <typename Component, typename Context>
        static std::string what(Component const& component, Context const& ctx)
        {
            return std::string("\"")
                + spirit::detail::to_narrow_string(
                    fusion::at_c<0>(component.elements))
                + std::string("\"")
            ;
        }
    };

    ///////////////////////////////////////////////////////////////////////////
    // parse lazy strings
    ///////////////////////////////////////////////////////////////////////////
    struct lazy_string
    {
        template <typename Component, typename Context, typename Iterator>
        struct attribute
        {
            typedef typename
                result_of::subject<Component>::type
            subject_type;

            typedef typename
                remove_reference<
                    typename boost::result_of<subject_type(unused_type, Context)>::type
                >::type
            type;
        };

        template <
            typename Component
          , typename Iterator, typename Context
          , typename Skipper, typename Attribute>
        static bool parse(
            Component const& component
          , Iterator& first, Iterator const& last
          , Context& context, Skipper const& skipper
          , Attribute& attr)
        {
            qi::skip(first, last, skipper);
            return detail::string_parse(
                fusion::at_c<0>(component.elements)(unused, context)
              , first
              , last
              , attr
            );
        }

        template <typename Component, typename Context>
        static std::string what(Component const& component, Context const& ctx)
        {
            return std::string("\"")
                + spirit::detail::to_narrow_string(
                    fusion::at_c<0>(component.elements)(unused, ctx))
                + std::string("\"")
            ;
        }
    };

    ///////////////////////////////////////////////////////////////////////////
    // no_case literal_string version
    ///////////////////////////////////////////////////////////////////////////
    template <typename Char>
    struct no_case_literal_string
    {
        template <typename Component, typename Context, typename Iterator>
        struct attribute
        {
            typedef unused_type type;   // literal parsers have no attribute
        };

        template <
            typename Component
          , typename Iterator, typename Context
          , typename Skipper, typename Attribute>
        static bool parse(
            Component const& component
          , Iterator& first, Iterator const& last
          , Context& /*context*/, Skipper const& skipper
          , Attribute& attr)
        {
            qi::skip(first, last, skipper);
            return detail::string_parse(
                fusion::at_c<0>(component.elements)
              , fusion::at_c<1>(component.elements)
              , first
              , last
              , attr
            );
        }

        template <typename Component, typename Context>
        static std::string what(Component const& component, Context const& ctx)
        {
            return std::string("case-insensitive \"")
                + spirit::detail::to_narrow_string(
                    fusion::at_c<0>(component.elements))
                + std::string("\"")
            ;
        }
    };
}}}

namespace boost { namespace spirit { namespace traits
{
    ///////////////////////////////////////////////////////////////////////////
    // no_case_literal_string generator
    ///////////////////////////////////////////////////////////////////////////
    template <
        typename Domain, typename Elements, typename Modifier, typename Char
    >
    struct make_modified_component<
        Domain, qi::literal_string<Char>, Elements, Modifier
      , typename enable_if<
            is_member_of_modifier<Modifier, spirit::char_class::no_case_base_tag>
        >::type
    >
    {
        typedef std::basic_string<Char> string_type;
        typedef fusion::vector<string_type, string_type> vector_type;
        typedef
            component<qi::domain, qi::no_case_literal_string<Char>, vector_type>
        type;

        static type
        call(Elements const& elements)
        {
            typedef typename Modifier::char_set char_set;

            Char const* in = fusion::at_c<0>(elements);
            string_type lo(in);
            string_type hi(in);

            typename string_type::iterator loi = lo.begin();
            typename string_type::iterator hii = hi.begin();

            for (; loi != lo.end(); ++loi, ++hii, ++in)
            {
                *loi = char_set::tolower(*loi);
                *hii = char_set::toupper(*hii);
            }

            return type(vector_type(lo, hi));
        }
    };
}}}

#endif

ext: hpp


text:
//  Copyright (c) 2021, Qualcomm Innovation Center, Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//  1. Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//  2. 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.
//
//  3. 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.
//
//  SPDX-License-Identifier: BSD-3-Clause

#define _GNU_SOURCE 1

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <poll.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
#include <sched.h>
#include <netdb.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>

#include <boost/program_options.hpp>

#include <fstream>

#include <hogl/format-basic.hpp>
#include <hogl/format-raw.hpp>
#include <hogl/output-stdout.hpp>
#include <hogl/output-stderr.hpp>
#include <hogl/output-plainfile.hpp>
#include <hogl/output-pipe.hpp>
#include <hogl/engine.hpp>
#include <hogl/area.hpp>
#include <hogl/mask.hpp>
#include <hogl/post.hpp>
#include <hogl/flush.hpp>
#include <hogl/ring.hpp>
#include <hogl/platform.hpp>

#include "iodme/timesource.hpp"
#include "iodme/buffer.hpp"
#include "iodme/queue.hpp"
#include "iodme/pump.hpp"
#include "iodme/nettx.hpp"

////////
using iodme::buffer;
using iodme::queue;

////////
namespace po = boost::program_options;

static const hogl::area *area = nullptr;
static po::variables_map optmap;

static volatile bool killed = false;

// Catch most signal to terminate gracefully.
static inline void sig_handler(int signum)
{
	killed = true;
}

static inline void catch_signals()
{
	struct sigaction sa = {{0}};
	sa.sa_handler = sig_handler;
	sigemptyset(&sa.sa_mask);
	sigaction(SIGINT, &sa, NULL);
	sigaction(SIGHUP, &sa, NULL);
	sigaction(SIGTERM, &sa, NULL);
}

static void setup_rt_sched()
{
	// Need to be higher than most threads in the system
	struct sched_param sp = { 0 };
	sp.sched_priority = 90;
	if (sched_setscheduler(0, SCHED_FIFO, &sp) < 0)
		hogl::post(area, area->WARN, "failed to set scheduling policy and priority: %s(%d).",
		strerror(errno), errno);

	if (mlockall(MCL_CURRENT | MCL_FUTURE) < 0)
		hogl::post(area, area->WARN, "failed to lock process memory: %s(%d).",
		strerror(errno), errno);
}

static bool run()
{
	// Setup RT scheduling and lock ourselves in memory to minimize latencies.
	setup_rt_sched();

	// Connect to the sink
	int sk = socket(PF_INET, SOCK_STREAM, 0);
	if (sk < 0) {
		hogl::post(area, area->ERROR, "failed to create socket: %s(%d).",
			   strerror(errno), errno);
		return false;
	}

	unsigned int sndbuf = optmap["frame-size"].as<unsigned int>() * 2;
	if (setsockopt(sk, SOL_SOCKET, SO_SNDBUFFORCE, &sndbuf, sizeof(sndbuf)) < 0) {
		hogl::post(area, area->WARN, "Failed to set socket sndbuf depth: %s(%d).",
			   strerror(errno), errno);
	}
	hogl::post(area, area->INFO, "socket: snd-buffer %u", sndbuf);

	std::string host = optmap["sink-host"].as<std::string>();
	std::string port = optmap["sink-port"].as<std::string>();
	struct addrinfo *ai;
	if (getaddrinfo(host.c_str(), port.c_str(), 0, &ai) < 0) {
		hogl::post(area, area->ERROR, "Failed to resolve destination address %s: %s(%d).",
			   host.c_str(), strerror(errno), errno);
		return false;
	}

	int r = connect(sk, ai->ai_addr, ai->ai_addrlen);
	int r_errno = errno;

	freeaddrinfo(ai);

	if (r < 0) {
		hogl::post(area, area->ERROR, "Failed to connect the socket: %s(%d).", strerror(r_errno), r_errno);
		return false;
	}

	auto d_queue = std::make_unique<iodme::queue>();
	auto d_nettx = std::make_unique<iodme::nettx>(sk, *d_queue);
	auto d_pump  = std::make_unique<iodme::pump>(
			optmap["frame-size"].as<unsigned int>(),
			1000000000.0 / optmap["frame-rate"].as<float>(),
			*d_queue);

	d_nettx->start();
	if (d_nettx->failed() || !d_nettx->running()) {
		hogl::post(area, area->ERROR, "data-nettx failed/stopped");
		return false;
	}

	d_pump->start();
	if (d_pump->failed() || !d_pump->running()) {
		hogl::post(area, area->ERROR, "data-pump failed/stopped");
		return false;
	}

	while (!killed) {
		if (!d_nettx->running() || !d_pump->running()) {
			break;
		}
		iodme::thread::do_nanosleep(250*1000*1000);
	}

	return 0;
}

static std::vector<std::string> log_mask;
int main(int argc, char *argv[])
{
	// **** Parse command line arguments ****
	po::options_description optdesc("Data generator test app");
	optdesc.add_options()
		("help", "Print this message")
		("log-output", po::value<std::string>()->default_value("-"), "Log output file name or - for stdout")
		("log-format", po::value<std::string>()->default_value("timespec,timedelta,area,section"), "Log output format")
		("log-mask",   po::value<std::vector<std::string> >(&log_mask)->composing(), "Log mask. Multiple masks can be specified.")
		("timesource,T", po::value<std::string>()->default_value("realtime"),"Timesource (clockid: realtime, monotonic)")
		("sink-port,P",  po::value<std::string>()->default_value("15740"),  "Sink TCP port to use")
		("sink-host,A",  po::value<std::string>(), "Sink hostname (IP address or hostname)")
		("frame-size,s", po::value<unsigned int>()->default_value(4 * 1024 * 1024), "Size of the data frames to generate")
		("frame-rate,r", po::value<float>()->default_value(30), "Frame rate in FPS")
		("name,n",  po::value<std::string>(), "Name of data stream");

	po::store(po::parse_command_line(argc, argv, optdesc), optmap);
	po::notify(optmap);

	// ** All argument values (including the defaults) are now storred in 'optmap' **

	if (optmap.count("help")) {
		std::cout << optdesc << std::endl;
		exit(1);
	}

	if (!optmap.count("sink-host")) {
		std::cout << optdesc << std::endl;
		std::cout << "*** Sink hostname must be specified" << std::endl;
		exit(1);
	}

	iodme::timesource *my_clock;
	if (optmap["timesource"].as<std::string>() == "realtime")
		my_clock = new iodme::timesource(CLOCK_REALTIME);
	else if (optmap["timesource"].as<std::string>() == "monotonic")
		my_clock = new iodme::timesource(CLOCK_MONOTONIC);
	else {
		std::cerr << "Unsupported timesource/clockid " << optmap["timesource"].as<std::string>() << std::endl;
		exit(1);
	}

	catch_signals();

	hogl::format *lf;
	hogl::output *lo;

	lf = new hogl::format_basic(optmap["log-format"].as<std::string>().c_str());
	if (optmap["log-output"].as<std::string>() == "-")
		lo = new hogl::output_stdout(*lf, 64 * 1024);
	else if (optmap["log-output"].as<std::string>()[0] == '|')
		lo = new hogl::output_pipe(optmap["log-output"].as<std::string>().c_str(), *lf, 64 * 1024);
	else
		lo = new hogl::output_plainfile(optmap["log-output"].as<std::string>().c_str(), *lf, 64 * 1024);

	hogl::engine::options eng_opts = hogl::engine::default_options;
	for (auto &m : log_mask)
		eng_opts.default_mask << m;

	hogl::activate(*lo, eng_opts);

	hogl::change_timesource(my_clock);

	// *****
	// HOGL engine is running now. Avoid exit()ing from the process
	// without going through hogl shutdown sequence below.

	area = hogl::add_area("IODME-GENERATOR");

	hogl::ringbuf::options ring_opts = { capacity: 1024 * 8, prio: 100, flags: 0, record_tailroom: 128 };
	hogl::tls *tls = new hogl::tls("MAIN-THREAD", ring_opts);

	run();

	delete tls;

	hogl::deactivate();

	delete lo;
	delete lf;
	delete my_clock;

	return 0;
}

ext: cc

max_stars_repo_name: maxk-org/iodme

max_issues_repo_name: maxk-org/iodme

max_forks_repo_name: maxk-org/iodme


text:
/**************************************************************
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 *************************************************************/

#ifndef _SFXSTYLE_HXX
#define _SFXSTYLE_HXX

#include <com/sun/star/style/XStyle.hpp>
#include <com/sun/star/lang/XUnoTunnel.hpp>
#include <rtl/ref.hxx>
#include <vector>
#include <comphelper/weak.hxx>
#include <cppuhelper/implbase2.hxx>
#include <svl/svldllapi.h>
#include <rsc/rscsfx.hxx>
#include <tools/string.hxx>
#include <svl/hint.hxx>
#include <svl/lstner.hxx>
#include <svl/brdcst.hxx>
#include <svl/poolitem.hxx>
#include <svl/style.hrc>
#include <boost/shared_ptr.hpp>

class SfxItemSet;
class SfxItemPool;
class SfxStyleSheetBasePool;
class SvStream;

/*
Everyone changing instances of SfxStyleSheetBasePool or SfxStyleSheetBase
mußt broadcast this using <SfxStyleSheetBasePool::GetBroadcaster()> broadcasten.
The class <SfxStyleSheetHint> is used for this, it contains an Action-Id and a
pointer to the <SfxStyleSheetBase>. The actions are:

#define SFX_STYLESHEET_CREATED      // style is created
#define SFX_STYLESHEET_MODIFIED     // style is modified
#define SFX_STYLESHEET_CHANGED      // style is replaced
#define SFX_STYLESHEET_ERASED       // style is deleted

The following methods already broadcast themself

SfxStyleSheetHint(SFX_STYLESHEET_MODIFIED) from:
   SfxStyleSheetBase::SetName( const String& rName )
   SfxStyleSheetBase::SetParent( const String& rName )
   SfxStyleSheetBase::SetFollow( const String& rName )

SfxSimpleHint(SFX_HINT_DYING) from:
   SfxStyleSheetBasePool::~SfxStyleSheetBasePool()

SfxStyleSheetHint( SFX_STYLESHEET_CREATED, *p ) from:
   SfxStyleSheetBasePool::Make( const String& rName,
   SfxStyleFamily eFam, sal_uInt16 mask, sal_uInt16 nPos)

SfxStyleSheetHint( SFX_STYLESHEET_CHANGED, *pNew ) from:
   SfxStyleSheetBasePool::Add( SfxStyleSheetBase& rSheet )

SfxStyleSheetHint( SFX_STYLESHEET_ERASED, *p ) from:
   SfxStyleSheetBasePool::Erase( SfxStyleSheetBase* p )
   SfxStyleSheetBasePool::Clear()
*/

#define VIRTUAL510 virtual

class SVL_DLLPUBLIC SfxStyleSheetBase : public comphelper::OWeakTypeObject
{
	friend class SfxStyleSheetBasePool;

protected:
	SfxStyleSheetBasePool& 	rPool;			// zugehoeriger Pool
	SfxStyleFamily 			nFamily;		// Familie

	UniString				aName, aParent, aFollow;
	rtl::OUString			maDisplayName;
	String 					aHelpFile;		// Name der Hilfedatei
	SfxItemSet* 			pSet;           // ItemSet
	sal_uInt16  				nMask;			// Flags

	sal_uLong 					nHelpId;		// Hilfe-ID

	sal_Bool   					bMySet;			// sal_True: Set loeschen im dtor

	SfxStyleSheetBase(); // do not use!
	SfxStyleSheetBase( const UniString&, SfxStyleSheetBasePool&, SfxStyleFamily eFam, sal_uInt16 mask );
	SfxStyleSheetBase( const SfxStyleSheetBase& );
	virtual ~SfxStyleSheetBase();
	virtual void Load( SvStream&, sal_uInt16 );
	virtual void Store( SvStream& );

public:
	TYPEINFO();

	// returns the internal name of this style
	virtual const UniString& GetName() const;

	// sets the internal name of this style
	virtual sal_Bool SetName( const UniString& );

	/** returns the display name of this style, it is used at the user interface.
		If the display name is empty, this method returns the internal name. */
	virtual rtl::OUString GetDisplayName() const;

	// sets the display name of this style
	virtual void SetDisplayName( const rtl::OUString& );

	virtual const UniString& GetParent() const;
	virtual sal_Bool SetParent( const UniString& );
	virtual const UniString& GetFollow() const;
	virtual sal_Bool SetFollow( const UniString& );
	virtual sal_Bool HasFollowSupport() const;		// Default sal_True
	virtual sal_Bool HasParentSupport() const;		// Default sal_True
	virtual sal_Bool HasClearParentSupport() const;	// Default sal_False
	virtual sal_Bool IsUsed() const;				// Default sal_True
		// Default aus dem Itemset; entweder dem uebergebenen
		// oder aus dem per GetItemSet() zurueckgelieferten Set
	virtual UniString GetDescription();
	virtual	UniString GetDescription( SfxMapUnit eMetric );

	SfxStyleSheetBasePool& GetPool() { return rPool;   }
	SfxStyleFamily GetFamily() const     { return nFamily; }
	sal_uInt16 	 GetMask() const     { return nMask; }
	void	 SetMask( sal_uInt16 mask) { nMask = mask; }
	sal_Bool   IsUserDefined() const
		   { return sal_Bool( ( nMask & SFXSTYLEBIT_USERDEF) != 0 ); }

	virtual sal_uLong GetHelpId( String& rFile );
	virtual void   SetHelpId( const String& r, sal_uLong nId );

	virtual SfxItemSet& GetItemSet();
	virtual sal_uInt16 GetVersion() const;
};

//=========================================================================

typedef std::vector< rtl::Reference< SfxStyleSheetBase > > SfxStyles;

//=========================================================================

class SVL_DLLPUBLIC SfxStyleSheetIterator

/*	[Beschreibung]

	Klasse zum Iterieren und Suchen auf einem SfxStyleSheetBasePool.

*/

{
public:
	SfxStyleSheetIterator(SfxStyleSheetBasePool *pBase,
						  SfxStyleFamily eFam, sal_uInt16 n=0xFFFF );
	virtual sal_uInt16 GetSearchMask() const;
	virtual SfxStyleFamily GetSearchFamily() const;
	virtual sal_uInt16 Count();
	virtual SfxStyleSheetBase *operator[](sal_uInt16 nIdx);
	virtual SfxStyleSheetBase* First();
	virtual SfxStyleSheetBase* Next();
	virtual SfxStyleSheetBase* Find(const UniString& rStr);
	virtual ~SfxStyleSheetIterator();

protected:

	SfxStyleSheetBasePool*	pBasePool;
	SfxStyleFamily 			nSearchFamily;
	sal_uInt16 					nMask;
	sal_Bool                    SearchUsed() const { return bSearchUsed; }

private:
	sal_uInt16 					GetPos(){return nAktPosition;}
	SVL_DLLPRIVATE sal_Bool 					IsTrivialSearch();
	SVL_DLLPRIVATE sal_Bool 					DoesStyleMatch(SfxStyleSheetBase *pStyle);

	void*					pImp;
	SfxStyleSheetBase*		pAktStyle;
	sal_uInt16 					nAktPosition;
	sal_Bool 					bSearchUsed;

friend class SfxStyleSheetBasePool;
};

typedef ::boost::shared_ptr< SfxStyleSheetIterator > SfxStyleSheetIteratorPtr;
//=========================================================================

class SfxStyleSheetBasePool_Impl;

class SVL_DLLPUBLIC SfxStyleSheetBasePool: public SfxBroadcaster, public comphelper::OWeakTypeObject
{
friend class SfxStyleSheetIterator;
friend class SfxStyleSheetBase;

	SfxStyleSheetBasePool_Impl *pImp;

private:
	SVL_DLLPRIVATE sal_Bool 						Load1_Impl( SvStream& );
	SVL_DLLPRIVATE SfxStyleSheetIterator&      GetIterator_Impl();
protected:
	String 						aAppName;
	SfxItemPool& 				rPool;
	SfxStyles	 				aStyles;
	SfxStyleFamily 				nSearchFamily;
	sal_uInt16 		 				nMask;

	SfxStyleSheetBase& 			Add( SfxStyleSheetBase& );
	void 						ChangeParent( const UniString&, const UniString&, sal_Bool bVirtual = sal_True );
	virtual SfxStyleSheetBase* 	Create( const UniString&, SfxStyleFamily, sal_uInt16 );
	virtual SfxStyleSheetBase* 	Create( const SfxStyleSheetBase& );

								~SfxStyleSheetBasePool();

public:
								SfxStyleSheetBasePool( SfxItemPool& );
								SfxStyleSheetBasePool( const SfxStyleSheetBasePool& );

	static String 				GetStreamName();

	const String& 				GetAppName() const { return aAppName; 	}

	SfxItemPool& 				GetPool();
	const SfxItemPool& 			GetPool() const;

	virtual SfxStyleSheetIteratorPtr CreateIterator(SfxStyleFamily, sal_uInt16 nMask);
	virtual sal_uInt16 				Count();
	virtual SfxStyleSheetBase*	operator[](sal_uInt16 nIdx);

	virtual SfxStyleSheetBase& 	Make(const UniString&,
									 SfxStyleFamily eFam,
									 sal_uInt16 nMask = 0xffff ,
									 sal_uInt16 nPos = 0xffff);

	virtual void             Replace(
		SfxStyleSheetBase& rSource, SfxStyleSheetBase& rTarget );

	virtual void				Remove( SfxStyleSheetBase* );
	virtual void 				Insert( SfxStyleSheetBase* );

	virtual void 				Clear();

	SfxStyleSheetBasePool& 		operator=( const SfxStyleSheetBasePool& );
	SfxStyleSheetBasePool& 		operator+=( const SfxStyleSheetBasePool& );

	const SfxStyles&	 		GetStyles();
	virtual SfxStyleSheetBase* 	First();
	virtual SfxStyleSheetBase* 	Next();
	virtual SfxStyleSheetBase* 	Find( const UniString&, SfxStyleFamily eFam, sal_uInt16 n=0xFFFF );

	virtual sal_Bool                SetParent(SfxStyleFamily eFam,
										  const UniString &rStyle,
										  const UniString &rParent);

	SfxStyleSheetBase* 			Find(const UniString& rStr)
								{ return Find(rStr, nSearchFamily, nMask); }

	void   						SetSearchMask(SfxStyleFamily eFam, sal_uInt16 n=0xFFFF );
	sal_uInt16 						GetSearchMask() const;
	SfxStyleFamily 				GetSearchFamily() const  { return nSearchFamily; }

	sal_Bool 						Load( SvStream& );
	sal_Bool 						Store( SvStream&, sal_Bool bUsed = sal_True );
};

//=========================================================================

class SVL_DLLPUBLIC SfxStyleSheet: public SfxStyleSheetBase,
					 public SfxListener, public SfxBroadcaster
{
public:
						TYPEINFO();

						SfxStyleSheet( const UniString&, const SfxStyleSheetBasePool&, SfxStyleFamily, sal_uInt16 );
						SfxStyleSheet( const SfxStyleSheet& );

	virtual void 		Notify( SfxBroadcaster& rBC, const SfxHint& rHint );
	virtual sal_Bool 		SetParent( const UniString& );

protected:
	SfxStyleSheet(); // do not use!
	virtual 			~SfxStyleSheet();
};

//=========================================================================

class SVL_DLLPUBLIC SfxStyleSheetPool: public SfxStyleSheetBasePool
{
protected:
    using SfxStyleSheetBasePool::Create;
	virtual SfxStyleSheetBase* Create(const UniString&, SfxStyleFamily, sal_uInt16 mask);
	virtual SfxStyleSheetBase* Create(const SfxStyleSheet &);

public:
	SfxStyleSheetPool( SfxItemPool const& );

//	virtual sal_Bool CopyTo(SfxStyleSheetPool &rDest, const String &rSourceName);
};

//=========================================================================

#define SFX_STYLESHEET_CREATED		 1	// neu
#define SFX_STYLESHEET_MODIFIED      2	// ver"andert
#define SFX_STYLESHEET_CHANGED       3	// gel"oscht und neu (ausgetauscht)
#define SFX_STYLESHEET_ERASED        4	// gel"oscht
#define SFX_STYLESHEET_INDESTRUCTION 5	// wird gerade entfernt

#define SFX_STYLESHEETPOOL_CHANGES  1  // Aenderungen, die den Zustand
									   // des Pools anedern, aber nicht
									   // ueber die STYLESHEET Hints
									   // verschickt werden sollen.

//========================================================================

class SVL_DLLPUBLIC SfxStyleSheetPoolHint : public SfxHint
{
	sal_uInt16 nHint;

public:
	TYPEINFO();

						SfxStyleSheetPoolHint(sal_uInt16 nArgHint) :  nHint(nArgHint){}
	sal_uInt16				GetHint() const
						{ return nHint; }
};

//=========================================================================

class SVL_DLLPUBLIC SfxStyleSheetHint: public SfxHint
{
	SfxStyleSheetBase*	pStyleSh;
	sal_uInt16              nHint;

public:
						TYPEINFO();

						SfxStyleSheetHint( sal_uInt16 );
						SfxStyleSheetHint( sal_uInt16, SfxStyleSheetBase& );
	SfxStyleSheetBase*	GetStyleSheet() const
						{ return pStyleSh; }
	sal_uInt16				GetHint() const
						{ return nHint; }
};

class SVL_DLLPUBLIC SfxStyleSheetHintExtended: public SfxStyleSheetHint
{
	String              aName;

public:
						TYPEINFO();

						SfxStyleSheetHintExtended(
							sal_uInt16, const String& rOld );
						SfxStyleSheetHintExtended(
							sal_uInt16, const String& rOld,
							SfxStyleSheetBase& );
	const String&       GetOldName() { return aName; }
};

class SVL_DLLPUBLIC SfxUnoStyleSheet : public ::cppu::ImplInheritanceHelper2< SfxStyleSheet, ::com::sun::star::style::XStyle, ::com::sun::star::lang::XUnoTunnel >
{
public:
	SfxUnoStyleSheet( const UniString& _rName, const SfxStyleSheetBasePool& _rPool, SfxStyleFamily _eFamily, sal_uInt16 _nMaske );
	SfxUnoStyleSheet( const SfxStyleSheet& _rSheet );

	static SfxUnoStyleSheet* getUnoStyleSheet( const ::com::sun::star::uno::Reference< ::com::sun::star::style::XStyle >& xStyle );

    // XUnoTunnel
    virtual ::sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< ::sal_Int8 >& aIdentifier ) throw (::com::sun::star::uno::RuntimeException);

private:
	SfxUnoStyleSheet(); // not implemented

	static const ::com::sun::star::uno::Sequence< ::sal_Int8 >& getIdentifier();
};

#endif

ext: hxx

max_stars_repo_name: Grosskopf/openoffice

max_issues_repo_name: Grosskopf/openoffice

max_forks_repo_name: Grosskopf/openoffice


text:
#include "Core/agents/Chest.h"
#include "OrderDig.h"
#include <boost/format/format_fwd.hpp>
#include <glm/gtx/string_cast.hpp>
#include "Core/agents/PositionAgent.h"
#include "core/agents/Ore.h"
#include <core/World.h>

OrderDig::OrderDig(glm::vec3 v) : pos(v)
{
}

std::string OrderDig::to_string() const
{
	return (boost::format("OrderDig: pos = %1%") % glm::to_string(pos)).str() + Order::to_string();
}

void OrderDig::Perform(const GameObjectParams & params, PGameObject performer, float work)
{
	auto c = performer->GetAgent<Creature>();

	auto remove = true;
	if (auto orb = params.world->GetBlock(pos))
	{
		if (auto ore = orb->GetAgent<Ore>())
		{
			remove = false;
			auto ch = performer->GetAgent<Chest>();
			auto cs = ore->DigSome();
			ch->Push(cs.obj, cs.count);

			if (ore->Expire())
				remove = true;
		}
	}

	if (remove)
	{
		params.world->SetBlock(pos, nullptr);
		Done();
	}
}

ext: cpp

max_stars_repo_name: ishellstrike/MinecraftLike

max_issues_repo_name: ishellstrike/MinecraftLike

max_forks_repo_name: ishellstrike/MinecraftLike


text:
#pragma once

#include <badem/crypto_lib/random_pool.hpp>
#include <badem/lib/config.hpp>
#include <badem/lib/diagnosticsconfig.hpp>
#include <badem/lib/logger_mt.hpp>
#include <badem/lib/memory.hpp>
#include <badem/lib/rocksdbconfig.hpp>
#include <badem/secure/common.hpp>
#include <badem/secure/versioning.hpp>

#include <boost/endian/conversion.hpp>
#include <boost/polymorphic_cast.hpp>

#include <stack>

namespace badem
{
/**
 * Encapsulates database specific container
 */
template <typename Val>
class db_val
{
public:
	db_val (Val const & value_a) :
	value (value_a)
	{
	}

	db_val () :
	db_val (0, nullptr)
	{
	}

	db_val (badem::uint128_union const & val_a) :
	db_val (sizeof (val_a), const_cast<badem::uint128_union *> (&val_a))
	{
	}

	db_val (badem::uint256_union const & val_a) :
	db_val (sizeof (val_a), const_cast<badem::uint256_union *> (&val_a))
	{
	}

	db_val (badem::account_info const & val_a) :
	db_val (val_a.db_size (), const_cast<badem::account_info *> (&val_a))
	{
	}

	db_val (badem::account_info_v13 const & val_a) :
	db_val (val_a.db_size (), const_cast<badem::account_info_v13 *> (&val_a))
	{
	}

	db_val (badem::account_info_v14 const & val_a) :
	db_val (val_a.db_size (), const_cast<badem::account_info_v14 *> (&val_a))
	{
	}

	db_val (badem::pending_info const & val_a) :
	db_val (val_a.db_size (), const_cast<badem::pending_info *> (&val_a))
	{
		static_assert (std::is_standard_layout<badem::pending_info>::value, "Standard layout is required");
	}

	db_val (badem::pending_info_v14 const & val_a) :
	db_val (val_a.db_size (), const_cast<badem::pending_info_v14 *> (&val_a))
	{
		static_assert (std::is_standard_layout<badem::pending_info_v14>::value, "Standard layout is required");
	}

	db_val (badem::pending_key const & val_a) :
	db_val (sizeof (val_a), const_cast<badem::pending_key *> (&val_a))
	{
		static_assert (std::is_standard_layout<badem::pending_key>::value, "Standard layout is required");
	}

	db_val (badem::unchecked_info const & val_a) :
	buffer (std::make_shared<std::vector<uint8_t>> ())
	{
		{
			badem::vectorstream stream (*buffer);
			val_a.serialize (stream);
		}
		convert_buffer_to_value ();
	}

	db_val (badem::unchecked_key const & val_a) :
	db_val (sizeof (val_a), const_cast<badem::unchecked_key *> (&val_a))
	{
		static_assert (std::is_standard_layout<badem::unchecked_key>::value, "Standard layout is required");
	}

	db_val (badem::block_info const & val_a) :
	db_val (sizeof (val_a), const_cast<badem::block_info *> (&val_a))
	{
		static_assert (std::is_standard_layout<badem::block_info>::value, "Standard layout is required");
	}

	db_val (badem::endpoint_key const & val_a) :
	db_val (sizeof (val_a), const_cast<badem::endpoint_key *> (&val_a))
	{
		static_assert (std::is_standard_layout<badem::endpoint_key>::value, "Standard layout is required");
	}

	db_val (std::shared_ptr<badem::block> const & val_a) :
	buffer (std::make_shared<std::vector<uint8_t>> ())
	{
		{
			badem::vectorstream stream (*buffer);
			badem::serialize_block (stream, *val_a);
		}
		convert_buffer_to_value ();
	}

	db_val (uint64_t val_a) :
	buffer (std::make_shared<std::vector<uint8_t>> ())
	{
		{
			boost::endian::native_to_big_inplace (val_a);
			badem::vectorstream stream (*buffer);
			badem::write (stream, val_a);
		}
		convert_buffer_to_value ();
	}

	explicit operator badem::account_info () const
	{
		badem::account_info result;
		assert (size () == result.db_size ());
		std::copy (reinterpret_cast<uint8_t const *> (data ()), reinterpret_cast<uint8_t const *> (data ()) + result.db_size (), reinterpret_cast<uint8_t *> (&result));
		return result;
	}

	explicit operator badem::account_info_v13 () const
	{
		badem::account_info_v13 result;
		assert (size () == result.db_size ());
		std::copy (reinterpret_cast<uint8_t const *> (data ()), reinterpret_cast<uint8_t const *> (data ()) + result.db_size (), reinterpret_cast<uint8_t *> (&result));
		return result;
	}

	explicit operator badem::account_info_v14 () const
	{
		badem::account_info_v14 result;
		assert (size () == result.db_size ());
		std::copy (reinterpret_cast<uint8_t const *> (data ()), reinterpret_cast<uint8_t const *> (data ()) + result.db_size (), reinterpret_cast<uint8_t *> (&result));
		return result;
	}

	explicit operator badem::block_info () const
	{
		badem::block_info result;
		assert (size () == sizeof (result));
		static_assert (sizeof (badem::block_info::account) + sizeof (badem::block_info::balance) == sizeof (result), "Packed class");
		std::copy (reinterpret_cast<uint8_t const *> (data ()), reinterpret_cast<uint8_t const *> (data ()) + sizeof (result), reinterpret_cast<uint8_t *> (&result));
		return result;
	}

	explicit operator badem::pending_info_v14 () const
	{
		badem::pending_info_v14 result;
		assert (size () == result.db_size ());
		std::copy (reinterpret_cast<uint8_t const *> (data ()), reinterpret_cast<uint8_t const *> (data ()) + result.db_size (), reinterpret_cast<uint8_t *> (&result));
		return result;
	}

	explicit operator badem::pending_info () const
	{
		badem::pending_info result;
		assert (size () == result.db_size ());
		std::copy (reinterpret_cast<uint8_t const *> (data ()), reinterpret_cast<uint8_t const *> (data ()) + result.db_size (), reinterpret_cast<uint8_t *> (&result));
		return result;
	}

	explicit operator badem::pending_key () const
	{
		badem::pending_key result;
		assert (size () == sizeof (result));
		static_assert (sizeof (badem::pending_key::account) + sizeof (badem::pending_key::hash) == sizeof (result), "Packed class");
		std::copy (reinterpret_cast<uint8_t const *> (data ()), reinterpret_cast<uint8_t const *> (data ()) + sizeof (result), reinterpret_cast<uint8_t *> (&result));
		return result;
	}

	explicit operator badem::unchecked_info () const
	{
		badem::bufferstream stream (reinterpret_cast<uint8_t const *> (data ()), size ());
		badem::unchecked_info result;
		bool error (result.deserialize (stream));
		(void)error;
		assert (!error);
		return result;
	}

	explicit operator badem::unchecked_key () const
	{
		badem::unchecked_key result;
		assert (size () == sizeof (result));
		static_assert (sizeof (badem::unchecked_key::previous) + sizeof (badem::pending_key::hash) == sizeof (result), "Packed class");
		std::copy (reinterpret_cast<uint8_t const *> (data ()), reinterpret_cast<uint8_t const *> (data ()) + sizeof (result), reinterpret_cast<uint8_t *> (&result));
		return result;
	}

	explicit operator badem::uint128_union () const
	{
		return convert<badem::uint128_union> ();
	}

	explicit operator badem::amount () const
	{
		return convert<badem::amount> ();
	}

	explicit operator badem::block_hash () const
	{
		return convert<badem::block_hash> ();
	}

	explicit operator badem::public_key () const
	{
		return convert<badem::public_key> ();
	}

	explicit operator badem::uint256_union () const
	{
		return convert<badem::uint256_union> ();
	}

	explicit operator std::array<char, 64> () const
	{
		badem::bufferstream stream (reinterpret_cast<uint8_t const *> (data ()), size ());
		std::array<char, 64> result;
		auto error = badem::try_read (stream, result);
		(void)error;
		assert (!error);
		return result;
	}

	explicit operator badem::endpoint_key () const
	{
		badem::endpoint_key result;
		std::copy (reinterpret_cast<uint8_t const *> (data ()), reinterpret_cast<uint8_t const *> (data ()) + sizeof (result), reinterpret_cast<uint8_t *> (&result));
		return result;
	}

	explicit operator badem::state_block_w_sideband_v14 () const
	{
		badem::bufferstream stream (reinterpret_cast<uint8_t const *> (data ()), size ());
		auto error (false);
		badem::state_block_w_sideband_v14 state_block_w_sideband_v14;
		state_block_w_sideband_v14.state_block = std::make_shared<badem::state_block> (error, stream);
		assert (!error);

		state_block_w_sideband_v14.sideband.type = badem::block_type::state;
		error = state_block_w_sideband_v14.sideband.deserialize (stream);
		assert (!error);

		return state_block_w_sideband_v14;
	}

	explicit operator badem::no_value () const
	{
		return no_value::dummy;
	}

	explicit operator std::shared_ptr<badem::block> () const
	{
		badem::bufferstream stream (reinterpret_cast<uint8_t const *> (data ()), size ());
		std::shared_ptr<badem::block> result (badem::deserialize_block (stream));
		return result;
	}

	template <typename Block>
	std::shared_ptr<Block> convert_to_block () const
	{
		badem::bufferstream stream (reinterpret_cast<uint8_t const *> (data ()), size ());
		auto error (false);
		auto result (std::make_shared<Block> (error, stream));
		assert (!error);
		return result;
	}

	explicit operator std::shared_ptr<badem::send_block> () const
	{
		return convert_to_block<badem::send_block> ();
	}

	explicit operator std::shared_ptr<badem::receive_block> () const
	{
		return convert_to_block<badem::receive_block> ();
	}

	explicit operator std::shared_ptr<badem::open_block> () const
	{
		return convert_to_block<badem::open_block> ();
	}

	explicit operator std::shared_ptr<badem::change_block> () const
	{
		return convert_to_block<badem::change_block> ();
	}

	explicit operator std::shared_ptr<badem::state_block> () const
	{
		return convert_to_block<badem::state_block> ();
	}

	explicit operator std::shared_ptr<badem::vote> () const
	{
		badem::bufferstream stream (reinterpret_cast<uint8_t const *> (data ()), size ());
		auto error (false);
		auto result (badem::make_shared<badem::vote> (error, stream));
		assert (!error);
		return result;
	}

	explicit operator uint64_t () const
	{
		uint64_t result;
		badem::bufferstream stream (reinterpret_cast<uint8_t const *> (data ()), size ());
		auto error (badem::try_read (stream, result));
		(void)error;
		assert (!error);
		boost::endian::big_to_native_inplace (result);
		return result;
	}

	operator Val * () const
	{
		// Allow passing a temporary to a non-c++ function which doesn't have constness
		return const_cast<Val *> (&value);
	}

	operator Val const & () const
	{
		return value;
	}

	// Must be specialized
	void * data () const;
	size_t size () const;
	db_val (size_t size_a, void * data_a);
	void convert_buffer_to_value ();

	Val value;
	std::shared_ptr<std::vector<uint8_t>> buffer;

private:
	template <typename T>
	T convert () const
	{
		T result;
		assert (size () == sizeof (result));
		std::copy (reinterpret_cast<uint8_t const *> (data ()), reinterpret_cast<uint8_t const *> (data ()) + sizeof (result), result.bytes.data ());
		return result;
	}
};

class block_sideband final
{
public:
	block_sideband () = default;
	block_sideband (badem::block_type, badem::account const &, badem::block_hash const &, badem::amount const &, uint64_t, uint64_t, badem::epoch);
	void serialize (badem::stream &) const;
	bool deserialize (badem::stream &);
	static size_t size (badem::block_type);
	badem::block_type type{ badem::block_type::invalid };
	badem::block_hash successor{ 0 };
	badem::account account{ 0 };
	badem::amount balance{ 0 };
	uint64_t height{ 0 };
	uint64_t timestamp{ 0 };
	badem::epoch epoch{ badem::epoch::epoch_0 };
};
class transaction;
class block_store;

/**
 * Summation visitor for blocks, supporting amount and balance computations. These
 * computations are mutually dependant. The natural solution is to use mutual recursion
 * between balance and amount visitors, but this leads to very deep stacks. Hence, the
 * summation visitor uses an iterative approach.
 */
class summation_visitor final : public badem::block_visitor
{
	enum summation_type
	{
		invalid = 0,
		balance = 1,
		amount = 2
	};

	/** Represents an invocation frame */
	class frame final
	{
	public:
		frame (summation_type type_a, badem::block_hash balance_hash_a, badem::block_hash amount_hash_a) :
		type (type_a), balance_hash (balance_hash_a), amount_hash (amount_hash_a)
		{
		}

		/** The summation type guides the block visitor handlers */
		summation_type type{ invalid };
		/** Accumulated balance or amount */
		badem::uint128_t sum{ 0 };
		/** The current balance hash */
		badem::block_hash balance_hash{ 0 };
		/** The current amount hash */
		badem::block_hash amount_hash{ 0 };
		/** If true, this frame is awaiting an invocation result */
		bool awaiting_result{ false };
		/** Set by the invoked frame, representing the return value */
		badem::uint128_t incoming_result{ 0 };
	};

public:
	summation_visitor (badem::transaction const &, badem::block_store const &, bool is_v14_upgrade = false);
	virtual ~summation_visitor () = default;
	/** Computes the balance as of \p block_hash */
	badem::uint128_t compute_balance (badem::block_hash const & block_hash);
	/** Computes the amount delta between \p block_hash and its predecessor */
	badem::uint128_t compute_amount (badem::block_hash const & block_hash);

protected:
	badem::transaction const & transaction;
	badem::block_store const & store;
	badem::network_params network_params;

	/** The final result */
	badem::uint128_t result{ 0 };
	/** The current invocation frame */
	frame * current{ nullptr };
	/** Invocation frames */
	std::stack<frame> frames;
	/** Push a copy of \p hash of the given summation \p type */
	badem::summation_visitor::frame push (badem::summation_visitor::summation_type type, badem::block_hash const & hash);
	void sum_add (badem::uint128_t addend_a);
	void sum_set (badem::uint128_t value_a);
	/** The epilogue yields the result to previous frame, if any */
	void epilogue ();

	badem::uint128_t compute_internal (badem::summation_visitor::summation_type type, badem::block_hash const &);
	void send_block (badem::send_block const &) override;
	void receive_block (badem::receive_block const &) override;
	void open_block (badem::open_block const &) override;
	void change_block (badem::change_block const &) override;
	void state_block (badem::state_block const &) override;

private:
	bool is_v14_upgrade;
	std::shared_ptr<badem::block> block_get (badem::transaction const &, badem::block_hash const &) const;
};

/**
 * Determine the representative for this block
 */
class representative_visitor final : public badem::block_visitor
{
public:
	representative_visitor (badem::transaction const & transaction_a, badem::block_store & store_a);
	~representative_visitor () = default;
	void compute (badem::block_hash const & hash_a);
	void send_block (badem::send_block const & block_a) override;
	void receive_block (badem::receive_block const & block_a) override;
	void open_block (badem::open_block const & block_a) override;
	void change_block (badem::change_block const & block_a) override;
	void state_block (badem::state_block const & block_a) override;
	badem::transaction const & transaction;
	badem::block_store & store;
	badem::block_hash current;
	badem::block_hash result;
};
template <typename T, typename U>
class store_iterator_impl
{
public:
	virtual ~store_iterator_impl () = default;
	virtual badem::store_iterator_impl<T, U> & operator++ () = 0;
	virtual bool operator== (badem::store_iterator_impl<T, U> const & other_a) const = 0;
	virtual bool is_end_sentinal () const = 0;
	virtual void fill (std::pair<T, U> &) const = 0;
	badem::store_iterator_impl<T, U> & operator= (badem::store_iterator_impl<T, U> const &) = delete;
	bool operator== (badem::store_iterator_impl<T, U> const * other_a) const
	{
		return (other_a != nullptr && *this == *other_a) || (other_a == nullptr && is_end_sentinal ());
	}
	bool operator!= (badem::store_iterator_impl<T, U> const & other_a) const
	{
		return !(*this == other_a);
	}
};
/**
 * Iterates the key/value pairs of a transaction
 */
template <typename T, typename U>
class store_iterator final
{
public:
	store_iterator (std::nullptr_t)
	{
	}
	store_iterator (std::unique_ptr<badem::store_iterator_impl<T, U>> impl_a) :
	impl (std::move (impl_a))
	{
		impl->fill (current);
	}
	store_iterator (badem::store_iterator<T, U> && other_a) :
	current (std::move (other_a.current)),
	impl (std::move (other_a.impl))
	{
	}
	badem::store_iterator<T, U> & operator++ ()
	{
		++*impl;
		impl->fill (current);
		return *this;
	}
	badem::store_iterator<T, U> & operator= (badem::store_iterator<T, U> && other_a)
	{
		impl = std::move (other_a.impl);
		current = std::move (other_a.current);
		return *this;
	}
	badem::store_iterator<T, U> & operator= (badem::store_iterator<T, U> const &) = delete;
	std::pair<T, U> * operator-> ()
	{
		return &current;
	}
	bool operator== (badem::store_iterator<T, U> const & other_a) const
	{
		return (impl == nullptr && other_a.impl == nullptr) || (impl != nullptr && *impl == other_a.impl.get ()) || (other_a.impl != nullptr && *other_a.impl == impl.get ());
	}
	bool operator!= (badem::store_iterator<T, U> const & other_a) const
	{
		return !(*this == other_a);
	}

private:
	std::pair<T, U> current;
	std::unique_ptr<badem::store_iterator_impl<T, U>> impl;
};

// Keep this in alphabetical order
enum class tables
{
	accounts,
	blocks_info, // LMDB only
	cached_counts, // RocksDB only
	change_blocks,
	confirmation_height,
	frontiers,
	meta,
	online_weight,
	open_blocks,
	peers,
	pending,
	receive_blocks,
	representation,
	send_blocks,
	state_blocks,
	unchecked,
	vote
};

class transaction_impl
{
public:
	virtual ~transaction_impl () = default;
	virtual void * get_handle () const = 0;
};

class read_transaction_impl : public transaction_impl
{
public:
	virtual void reset () = 0;
	virtual void renew () = 0;
};

class write_transaction_impl : public transaction_impl
{
public:
	virtual void commit () const = 0;
	virtual void renew () = 0;
	virtual bool contains (badem::tables table_a) const = 0;
};

class transaction
{
public:
	virtual ~transaction () = default;
	virtual void * get_handle () const = 0;
};

/**
 * RAII wrapper of a read MDB_txn where the constructor starts the transaction
 * and the destructor aborts it.
 */
class read_transaction final : public transaction
{
public:
	explicit read_transaction (std::unique_ptr<badem::read_transaction_impl> read_transaction_impl);
	void * get_handle () const override;
	void reset () const;
	void renew () const;
	void refresh () const;

private:
	std::unique_ptr<badem::read_transaction_impl> impl;
};

/**
 * RAII wrapper of a read-write MDB_txn where the constructor starts the transaction
 * and the destructor commits it.
 */
class write_transaction final : public transaction
{
public:
	explicit write_transaction (std::unique_ptr<badem::write_transaction_impl> write_transaction_impl);
	void * get_handle () const override;
	void commit () const;
	void renew ();
	bool contains (badem::tables table_a) const;

private:
	std::unique_ptr<badem::write_transaction_impl> impl;
};

class rep_weights;

/**
 * Manages block storage and iteration
 */
class block_store
{
public:
	virtual ~block_store () = default;
	virtual void initialize (badem::write_transaction const &, badem::genesis const &, badem::rep_weights &, std::atomic<uint64_t> &, std::atomic<uint64_t> &) = 0;
	virtual void block_put (badem::write_transaction const &, badem::block_hash const &, badem::block const &, badem::block_sideband const &) = 0;
	virtual badem::block_hash block_successor (badem::transaction const &, badem::block_hash const &) const = 0;
	virtual void block_successor_clear (badem::write_transaction const &, badem::block_hash const &) = 0;
	virtual std::shared_ptr<badem::block> block_get (badem::transaction const &, badem::block_hash const &, badem::block_sideband * = nullptr) const = 0;
	virtual std::shared_ptr<badem::block> block_get_v14 (badem::transaction const &, badem::block_hash const &, badem::block_sideband_v14 * = nullptr, bool * = nullptr) const = 0;
	virtual std::shared_ptr<badem::block> block_random (badem::transaction const &) = 0;
	virtual void block_del (badem::write_transaction const &, badem::block_hash const &) = 0;
	virtual bool block_exists (badem::transaction const &, badem::block_hash const &) = 0;
	virtual bool block_exists (badem::transaction const &, badem::block_type, badem::block_hash const &) = 0;
	virtual badem::block_counts block_count (badem::transaction const &) = 0;
	virtual bool root_exists (badem::transaction const &, badem::root const &) = 0;
	virtual bool source_exists (badem::transaction const &, badem::block_hash const &) = 0;
	virtual badem::account block_account (badem::transaction const &, badem::block_hash const &) const = 0;

	virtual void frontier_put (badem::write_transaction const &, badem::block_hash const &, badem::account const &) = 0;
	virtual badem::account frontier_get (badem::transaction const &, badem::block_hash const &) const = 0;
	virtual void frontier_del (badem::write_transaction const &, badem::block_hash const &) = 0;

	virtual void account_put (badem::write_transaction const &, badem::account const &, badem::account_info const &) = 0;
	virtual bool account_get (badem::transaction const &, badem::account const &, badem::account_info &) = 0;
	virtual void account_del (badem::write_transaction const &, badem::account const &) = 0;
	virtual bool account_exists (badem::transaction const &, badem::account const &) = 0;
	virtual size_t account_count (badem::transaction const &) = 0;
	virtual void confirmation_height_clear (badem::write_transaction const &, badem::account const & account, uint64_t existing_confirmation_height) = 0;
	virtual void confirmation_height_clear (badem::write_transaction const &) = 0;
	virtual badem::store_iterator<badem::account, badem::account_info> latest_begin (badem::transaction const &, badem::account const &) = 0;
	virtual badem::store_iterator<badem::account, badem::account_info> latest_begin (badem::transaction const &) = 0;
	virtual badem::store_iterator<badem::account, badem::account_info> latest_end () = 0;

	virtual void pending_put (badem::write_transaction const &, badem::pending_key const &, badem::pending_info const &) = 0;
	virtual void pending_del (badem::write_transaction const &, badem::pending_key const &) = 0;
	virtual bool pending_get (badem::transaction const &, badem::pending_key const &, badem::pending_info &) = 0;
	virtual bool pending_exists (badem::transaction const &, badem::pending_key const &) = 0;
	virtual badem::store_iterator<badem::pending_key, badem::pending_info> pending_begin (badem::transaction const &, badem::pending_key const &) = 0;
	virtual badem::store_iterator<badem::pending_key, badem::pending_info> pending_begin (badem::transaction const &) = 0;
	virtual badem::store_iterator<badem::pending_key, badem::pending_info> pending_end () = 0;

	virtual bool block_info_get (badem::transaction const &, badem::block_hash const &, badem::block_info &) const = 0;
	virtual badem::uint128_t block_balance (badem::transaction const &, badem::block_hash const &) = 0;
	virtual badem::uint128_t block_balance_calculated (std::shared_ptr<badem::block>, badem::block_sideband const &) const = 0;
	virtual badem::epoch block_version (badem::transaction const &, badem::block_hash const &) = 0;

	virtual void unchecked_clear (badem::write_transaction const &) = 0;
	virtual void unchecked_put (badem::write_transaction const &, badem::unchecked_key const &, badem::unchecked_info const &) = 0;
	virtual void unchecked_put (badem::write_transaction const &, badem::block_hash const &, std::shared_ptr<badem::block> const &) = 0;
	virtual std::vector<badem::unchecked_info> unchecked_get (badem::transaction const &, badem::block_hash const &) = 0;
	virtual void unchecked_del (badem::write_transaction const &, badem::unchecked_key const &) = 0;
	virtual badem::store_iterator<badem::unchecked_key, badem::unchecked_info> unchecked_begin (badem::transaction const &) = 0;
	virtual badem::store_iterator<badem::unchecked_key, badem::unchecked_info> unchecked_begin (badem::transaction const &, badem::unchecked_key const &) = 0;
	virtual badem::store_iterator<badem::unchecked_key, badem::unchecked_info> unchecked_end () = 0;
	virtual size_t unchecked_count (badem::transaction const &) = 0;

	// Return latest vote for an account from store
	virtual std::shared_ptr<badem::vote> vote_get (badem::transaction const &, badem::account const &) = 0;
	// Populate vote with the next sequence number
	virtual std::shared_ptr<badem::vote> vote_generate (badem::transaction const &, badem::account const &, badem::raw_key const &, std::shared_ptr<badem::block>) = 0;
	virtual std::shared_ptr<badem::vote> vote_generate (badem::transaction const &, badem::account const &, badem::raw_key const &, std::vector<badem::block_hash>) = 0;
	// Return either vote or the stored vote with a higher sequence number
	virtual std::shared_ptr<badem::vote> vote_max (badem::transaction const &, std::shared_ptr<badem::vote>) = 0;
	// Return latest vote for an account considering the vote cache
	virtual std::shared_ptr<badem::vote> vote_current (badem::transaction const &, badem::account const &) = 0;
	virtual void flush (badem::write_transaction const &) = 0;
	virtual badem::store_iterator<badem::account, std::shared_ptr<badem::vote>> vote_begin (badem::transaction const &) = 0;
	virtual badem::store_iterator<badem::account, std::shared_ptr<badem::vote>> vote_end () = 0;

	virtual void online_weight_put (badem::write_transaction const &, uint64_t, badem::amount const &) = 0;
	virtual void online_weight_del (badem::write_transaction const &, uint64_t) = 0;
	virtual badem::store_iterator<uint64_t, badem::amount> online_weight_begin (badem::transaction const &) const = 0;
	virtual badem::store_iterator<uint64_t, badem::amount> online_weight_end () const = 0;
	virtual size_t online_weight_count (badem::transaction const &) const = 0;
	virtual void online_weight_clear (badem::write_transaction const &) = 0;

	virtual void version_put (badem::write_transaction const &, int) = 0;
	virtual int version_get (badem::transaction const &) const = 0;

	virtual void peer_put (badem::write_transaction const & transaction_a, badem::endpoint_key const & endpoint_a) = 0;
	virtual void peer_del (badem::write_transaction const & transaction_a, badem::endpoint_key const & endpoint_a) = 0;
	virtual bool peer_exists (badem::transaction const & transaction_a, badem::endpoint_key const & endpoint_a) const = 0;
	virtual size_t peer_count (badem::transaction const & transaction_a) const = 0;
	virtual void peer_clear (badem::write_transaction const & transaction_a) = 0;
	virtual badem::store_iterator<badem::endpoint_key, badem::no_value> peers_begin (badem::transaction const & transaction_a) const = 0;
	virtual badem::store_iterator<badem::endpoint_key, badem::no_value> peers_end () const = 0;

	virtual void confirmation_height_put (badem::write_transaction const & transaction_a, badem::account const & account_a, uint64_t confirmation_height_a) = 0;
	virtual bool confirmation_height_get (badem::transaction const & transaction_a, badem::account const & account_a, uint64_t & confirmation_height_a) = 0;
	virtual bool confirmation_height_exists (badem::transaction const & transaction_a, badem::account const & account_a) const = 0;
	virtual void confirmation_height_del (badem::write_transaction const & transaction_a, badem::account const & account_a) = 0;
	virtual uint64_t confirmation_height_count (badem::transaction const & transaction_a) = 0;
	virtual badem::store_iterator<badem::account, uint64_t> confirmation_height_begin (badem::transaction const & transaction_a, badem::account const & account_a) = 0;
	virtual badem::store_iterator<badem::account, uint64_t> confirmation_height_begin (badem::transaction const & transaction_a) = 0;
	virtual badem::store_iterator<badem::account, uint64_t> confirmation_height_end () = 0;

	virtual uint64_t block_account_height (badem::transaction const & transaction_a, badem::block_hash const & hash_a) const = 0;
	virtual std::mutex & get_cache_mutex () = 0;

	virtual bool copy_db (boost::filesystem::path const & destination) = 0;

	/** Not applicable to all sub-classes */
	virtual void serialize_mdb_tracker (boost::property_tree::ptree &, std::chrono::milliseconds, std::chrono::milliseconds) = 0;

	virtual bool init_error () const = 0;

	/** Start read-write transaction */
	virtual badem::write_transaction tx_begin_write (std::vector<badem::tables> const & tables_to_lock = {}, std::vector<badem::tables> const & tables_no_lock = {}) = 0;

	/** Start read-only transaction */
	virtual badem::read_transaction tx_begin_read () = 0;
};

std::unique_ptr<badem::block_store> make_store (badem::logger_mt & logger, boost::filesystem::path const & path, bool open_read_only = false, bool add_db_postfix = false, badem::rocksdb_config const & rocksdb_config = badem::rocksdb_config{}, badem::txn_tracking_config const & txn_tracking_config_a = badem::txn_tracking_config{}, std::chrono::milliseconds block_processor_batch_max_time_a = std::chrono::milliseconds (5000), int lmdb_max_dbs = 128, size_t batch_size = 512, bool backup_before_upgrade = false, bool rocksdb_backend = false);
}

namespace std
{
template <>
struct hash<::badem::tables>
{
	size_t operator() (::badem::tables const & table_a) const
	{
		return static_cast<size_t> (table_a);
	}
};
}

max_stars_repo_name: bademcurrency/badem-node

max_issues_repo_name: bademcurrency/badem-node

max_forks_repo_name: bademcurrency/badem-node


text:
#ifndef SUPERGENIUS_CRDT_KEYPAIR_FILE_STORAGE_HPP
#define SUPERGENIUS_CRDT_KEYPAIR_FILE_STORAGE_HPP

#include <outcome/outcome.hpp>
#include <base/logger.hpp>
#include <boost/filesystem/path.hpp>
#include <libp2p/crypto/key.hpp>

namespace sgns::crdt
{
class KeyPairFileStorage
{
public:
    KeyPairFileStorage(const boost::filesystem::path& keyPath);

    outcome::result<libp2p::crypto::KeyPair> GetKeyPair() const;

private:
    boost::filesystem::path m_keyPath;
    sgns::base::Logger m_logger = sgns::base::createLogger("KeyPairFileStorage");
};
}

#endif // SUPERGENIUS_CRDT_KEYPAIR_FILE_STORAGE_HPP

max_stars_repo_name: GeniusVentures/SuperGenius

max_issues_repo_name: GeniusVentures/SuperGenius

max_forks_repo_name: GeniusVentures/SuperGenius


text:
//=======================================================================
// Copyright 2001 University of Notre Dame.
// Author: Lie-Quan Lee
//
// This file is part of the Boost Graph Library
//
// You should have received a copy of the License Agreement for the
// Boost Graph Library along with the software; see the file LICENSE.
// If not, contact Office of Research, University of Notre Dame, Notre
// Dame, IN 46556.
//
// Permission to modify the code and to distribute modified code is
// granted, provided the text of this NOTICE is retained, a notice that
// the code was modified is included with the above COPYRIGHT NOTICE and
// with the COPYRIGHT NOTICE in the LICENSE file, and that the LICENSE
// file is distributed with the modified code.
//
// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.
// By way of example, but not limitation, Licensor MAKES NO
// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY
// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS
// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS
// OR OTHER RIGHTS.
//=======================================================================
#ifndef BOOST_GRAPHVIZ_HPP
#define BOOST_GRAPHVIZ_HPP

#include <boost/config.hpp>
#include <string>
#include <map>
#include <iostream>
#include <fstream>
#include <stdio.h> // for FILE
#include <boost/property_map.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/properties.hpp>
#include <boost/graph/subgraph.hpp>
#include <boost/graph/adjacency_list.hpp>

namespace boost {

  template <typename directed_category>
  struct graphviz_io_traits {
    static std::string name() {
      return "digraph";
    }
    static std::string delimiter() {
      return "->";
    }  };

  template <>
  struct graphviz_io_traits <boost::undirected_tag> {
    static std::string name() {
      return "graph";
    }
    static std::string delimiter() {
      return "--";
    }
  };

  struct default_writer {
    void operator()(std::ostream&) const {
    }
    template <class VorE>
    void operator()(std::ostream&, const VorE&) const {
    }
  };

  template <class Name>
  class label_writer {
  public:
    label_writer(Name _name) : name(_name) {}
    template <class VertexOrEdge>
    void operator()(std::ostream& out, const VertexOrEdge& v) const {
      out << "[label=\"" << name[v] << "\"]";
    }
  private:
    Name name;
  };
  template <class Name>
  inline label_writer<Name>
  make_label_writer(Name n) {
    return label_writer<Name>(n);
  }

  enum edge_attribute_t        { edge_attribute        = 1111 };
  enum vertex_attribute_t      { vertex_attribute      = 2222 };
  enum graph_graph_attribute_t { graph_graph_attribute = 3333 };
  enum graph_vertex_attribute_t  { graph_vertex_attribute  = 4444 };
  enum graph_edge_attribute_t  { graph_edge_attribute  = 5555 };

  BOOST_INSTALL_PROPERTY(edge, attribute);
  BOOST_INSTALL_PROPERTY(vertex, attribute);
  BOOST_INSTALL_PROPERTY(graph, graph_attribute);
  BOOST_INSTALL_PROPERTY(graph, vertex_attribute);
  BOOST_INSTALL_PROPERTY(graph, edge_attribute);

  template <class Attribute>
  inline void write_attributes(const Attribute& attr, std::ostream& out) {
    typename Attribute::const_iterator i, iend;
    i    = attr.begin();
    iend = attr.end();

    while ( i != iend ) {
      out << i->first << "=\"" << i->second << "\"";
      ++i;
      if ( i != iend )
        out << ", ";
    }
  }

  template<typename Attributes>
  inline void write_all_attributes(Attributes attributes,
                                   const std::string& name,
                                   std::ostream& out)
  {
    typename Attributes::const_iterator i = attributes.begin(),
                                        end = attributes.end();
    if (i != end) {
      out << name << " [\n";
      write_attributes(attributes, out);
      out << "];\n";
    }
  }

  inline void write_all_attributes(detail::error_property_not_found,
                                   const std::string&,
                                   std::ostream&)
  {
    // Do nothing - no attributes exist
  }

  template <typename GraphGraphAttributes,
            typename GraphNodeAttributes,
            typename GraphEdgeAttributes>
  struct graph_attributes_writer
  {
    graph_attributes_writer(GraphGraphAttributes gg,
                            GraphNodeAttributes gn,
                            GraphEdgeAttributes ge)
      : g_attributes(gg), n_attributes(gn), e_attributes(ge) { }

    void operator()(std::ostream& out) const {
      write_all_attributes(g_attributes, "graph", out);
      write_all_attributes(n_attributes, "node", out);
      write_all_attributes(e_attributes, "edge", out);
    }
    GraphGraphAttributes g_attributes;
    GraphNodeAttributes n_attributes;
    GraphEdgeAttributes e_attributes;
  };

  template <typename GAttrMap, typename NAttrMap, typename EAttrMap>
  graph_attributes_writer<GAttrMap, NAttrMap, EAttrMap>
  make_graph_attributes_writer(const GAttrMap& g_attr, const NAttrMap& n_attr,
                              const EAttrMap& e_attr) {
    return graph_attributes_writer<GAttrMap, NAttrMap, EAttrMap>
      (g_attr, n_attr, e_attr);
  }

  template <typename Graph>
  graph_attributes_writer
    <typename graph_property<Graph, graph_graph_attribute_t>::type,
     typename graph_property<Graph, graph_vertex_attribute_t>::type,
     typename graph_property<Graph, graph_edge_attribute_t>::type>
  make_graph_attributes_writer(const Graph& g)
  {
    typedef typename graph_property<Graph, graph_graph_attribute_t>::type
      GAttrMap;
    typedef typename graph_property<Graph, graph_vertex_attribute_t>::type
      NAttrMap;
    typedef typename graph_property<Graph, graph_edge_attribute_t>::type
      EAttrMap;
    GAttrMap gam = get_property(g, graph_graph_attribute);
    NAttrMap nam = get_property(g, graph_vertex_attribute);
    EAttrMap eam = get_property(g, graph_edge_attribute);
    graph_attributes_writer<GAttrMap, NAttrMap, EAttrMap> writer(gam, nam, eam);
    return writer;
  }

  template <typename AttributeMap>
  struct attributes_writer {
    attributes_writer(AttributeMap attr)
      : attributes(attr) { }

    template <class VorE>
    void operator()(std::ostream& out, const VorE& e) const {
      this->write_attribute(out, attributes[e]);
    }

    private:
      template<typename AttributeSequence>
      void write_attribute(std::ostream& out,
                           const AttributeSequence& seq) const
      {
        if (!seq.empty()) {
          out << "[";
          write_attributes(seq, out);
          out << "]";
        }
      }

      void write_attribute(std::ostream&,
                           detail::error_property_not_found) const
      {
      }
    AttributeMap attributes;
  };

  template <typename Graph>
  attributes_writer
    <typename property_map<Graph, edge_attribute_t>::const_type>
  make_edge_attributes_writer(const Graph& g)
  {
    typedef typename property_map<Graph, edge_attribute_t>::const_type
      EdgeAttributeMap;
    return attributes_writer<EdgeAttributeMap>(get(edge_attribute, g));
  }

  template <typename Graph>
  attributes_writer
    <typename property_map<Graph, vertex_attribute_t>::const_type>
  make_vertex_attributes_writer(const Graph& g)
  {
    typedef typename property_map<Graph, vertex_attribute_t>::const_type
      VertexAttributeMap;
    return attributes_writer<VertexAttributeMap>(get(vertex_attribute, g));
  }

  template <typename Graph, typename VertexPropertiesWriter,
            typename EdgePropertiesWriter, typename GraphPropertiesWriter>

  inline void write_graphviz(std::ostream& out, const Graph& g,
                             VertexPropertiesWriter vpw,
                             EdgePropertiesWriter epw,
                             GraphPropertiesWriter gpw) {

    typedef typename boost::graph_traits<Graph>::directed_category cat_type;
    typedef graphviz_io_traits<cat_type> Traits;
    std::string name = "G";
    out << Traits::name() << " " << name << " {" << std::endl;

    gpw(out); //print graph properties

    typename boost::graph_traits<Graph>::vertex_iterator i, end;

    for(boost::tie(i,end) = boost::vertices(g); i != end; ++i) {
      out << *i;
      vpw(out, *i); //print vertex attributes
      out << ";" << std::endl;
    }
    typename boost::graph_traits<Graph>::edge_iterator ei, edge_end;
    for(boost::tie(ei, edge_end) = boost::edges(g); ei != edge_end; ++ei) {
      out << source(*ei, g) << Traits::delimiter() << target(*ei, g) << " ";
      epw(out, *ei); //print edge attributes
      out << ";" << std::endl;
    }
    out << "}" << std::endl;
  }

#if !defined(BOOST_MSVC) || BOOST_MSVC > 1300
  // ambiguous overload problem with VC++
  template <typename Graph>
  inline void
  write_graphviz(std::ostream& out, const Graph& g) {
    default_writer dw;
    default_writer gw;
    write_graphviz(out, g, dw, dw, gw);
  }
#endif

  template <typename Graph, typename VertexWriter>
  inline void
  write_graphviz(std::ostream& out, const Graph& g, VertexWriter vw) {
    default_writer dw;
    default_writer gw;
    write_graphviz(out, g, vw, dw, gw);
  }

  template <typename Graph, typename VertexWriter, typename EdgeWriter>
  inline void
  write_graphviz(std::ostream& out, const Graph& g,
                 VertexWriter vw, EdgeWriter ew) {
    default_writer gw;
    write_graphviz(out, g, vw, ew, gw);
  }

  namespace detail {

    template <class Graph_, class RandomAccessIterator>
    void write_graphviz_subgraph (std::ostream& out,
                                  const subgraph<Graph_>& g,
                                  RandomAccessIterator vertex_marker,
                                  RandomAccessIterator edge_marker)
    {
      typedef subgraph<Graph_> Graph;
      typedef typename boost::graph_traits<Graph>::vertex_descriptor Vertex;
      typedef typename boost::graph_traits<Graph>::directed_category cat_type;
      typedef graphviz_io_traits<cat_type> Traits;

      typedef typename graph_property<Graph, graph_name_t>::type NameType;
      const NameType& g_name = get_property(g, graph_name);

      if ( g.is_root() )
        out << Traits::name() ;
      else
        out << "subgraph";

      out << " " << g_name << " {" << std::endl;

      typename Graph::const_children_iterator i_child, j_child;

      //print graph/node/edge attributes
#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300
      typedef typename graph_property<Graph, graph_graph_attribute_t>::type
        GAttrMap;
      typedef typename graph_property<Graph, graph_vertex_attribute_t>::type
        NAttrMap;
      typedef typename graph_property<Graph, graph_edge_attribute_t>::type
        EAttrMap;
      GAttrMap gam = get_property(g, graph_graph_attribute);
      NAttrMap nam = get_property(g, graph_vertex_attribute);
      EAttrMap eam = get_property(g, graph_edge_attribute);
      graph_attributes_writer<GAttrMap, NAttrMap, EAttrMap> writer(gam, nam, eam);
      writer(out);
#else
      make_graph_attributes_writer(g)(out);
#endif

      //print subgraph
      for ( boost::tie(i_child,j_child) = g.children();
            i_child != j_child; ++i_child )
        write_graphviz_subgraph(out, *i_child, vertex_marker, edge_marker);

      // Print out vertices and edges not in the subgraphs.

      typename boost::graph_traits<Graph>::vertex_iterator i, end;
      typename boost::graph_traits<Graph>::edge_iterator ei, edge_end;

      typename property_map<Graph, vertex_index_t>::const_type
        indexmap = get(vertex_index, g.root());

      for(boost::tie(i,end) = boost::vertices(g); i != end; ++i) {
        Vertex v = g.local_to_global(*i);
        int pos = get(indexmap, v);
        if ( vertex_marker[pos] ) {
          vertex_marker[pos] = false;
          out << v;
#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300
          typedef typename property_map<Graph, vertex_attribute_t>::const_type
            VertexAttributeMap;
          attributes_writer<VertexAttributeMap> vawriter(get(vertex_attribute,
                                                             g.root()));
          vawriter(out, v);
#else
          make_vertex_attributes_writer(g.root())(out, v);
#endif
          out << ";" << std::endl;
        }
      }

      for (boost::tie(ei, edge_end) = edges(g); ei != edge_end; ++ei) {
        Vertex u = g.local_to_global(source(*ei,g)),
          v = g.local_to_global(target(*ei, g));
        int pos = get(get(edge_index, g.root()), g.local_to_global(*ei));
        if ( edge_marker[pos] ) {
          edge_marker[pos] = false;
          out << u << " " << Traits::delimiter() << " " << v;
#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300
          typedef typename property_map<Graph, edge_attribute_t>::const_type
            EdgeAttributeMap;
          attributes_writer<EdgeAttributeMap> eawriter(get(edge_attribute, g));
          eawriter(out, *ei);
#else
          make_edge_attributes_writer(g)(out, *ei); //print edge properties
#endif
          out << ";" << std::endl;
        }
      }
      out << "}" << std::endl;
    }
  } // namespace detail

  // requires graph_name graph property
  template <typename Graph>
  void write_graphviz(std::ostream& out, const subgraph<Graph>& g) {
    std::vector<bool> edge_marker(num_edges(g), true);
    std::vector<bool> vertex_marker(num_vertices(g), true);

    detail::write_graphviz_subgraph(out, g,
                                    vertex_marker.begin(),
                                    edge_marker.begin());
  }

  template <typename Graph>
  void write_graphviz(const std::string& filename, const subgraph<Graph>& g) {
    std::ofstream out(filename.c_str());
    std::vector<bool> edge_marker(num_edges(g), true);
    std::vector<bool> vertex_marker(num_vertices(g), true);

    detail::write_graphviz_subgraph(out, g,
                                    vertex_marker.begin(),
                                    edge_marker.begin());
  }

  typedef std::map<std::string, std::string> GraphvizAttrList;

  typedef property<boost::vertex_attribute_t, GraphvizAttrList>
          GraphvizVertexProperty;

  typedef property<boost::edge_attribute_t, GraphvizAttrList,
                   property<boost::edge_index_t, int> >
          GraphvizEdgeProperty;

  typedef property<boost::graph_graph_attribute_t, GraphvizAttrList,
                   property<boost::graph_vertex_attribute_t, GraphvizAttrList,
                   property<boost::graph_edge_attribute_t, GraphvizAttrList,
                   property<boost::graph_name_t, std::string> > > >
          GraphvizGraphProperty;

  typedef subgraph<adjacency_list<boost::vecS,
                   boost::vecS, boost::directedS,
                   GraphvizVertexProperty,
                   GraphvizEdgeProperty,
                   GraphvizGraphProperty> >
          GraphvizDigraph;

  typedef subgraph<adjacency_list<boost::vecS,
                   boost::vecS, boost::undirectedS,
                   GraphvizVertexProperty,
                   GraphvizEdgeProperty,
                   GraphvizGraphProperty> >
          GraphvizGraph;

  // These four require linking the BGL-Graphviz library: libbgl-viz.a
  // from the /src directory.
  extern void read_graphviz(const std::string& file, GraphvizDigraph& g);
  extern void read_graphviz(FILE* file, GraphvizDigraph& g);

  extern void read_graphviz(const std::string& file, GraphvizGraph& g);
  extern void read_graphviz(FILE* file, GraphvizGraph& g);

} // namespace boost

#endif // BOOST_GRAPHVIZ_HPP


text:
#ifndef NWNCHAR_H
#define NWNCHAR_H

#include <Nwn/base.hpp>

#include <array>
#include <vector>
#include <string>
#include <memory>
#include <unordered_map>

#include <boost/serialization/nvp.hpp>
#include <boost/serialization/unique_ptr.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/string.hpp>
#include <boost/serialization/unordered_map.hpp>

namespace Nwn {

class AblBlock;

/// Feat choices per level
using FeatChoiceContainer = std::unordered_map< int, std::unique_ptr< std::vector< int > > >;

class Character
{
public:
    explicit Character();
    ~Character() noexcept;

    void setName( const std::string n ) { name = n; }
    const std::string& getName() const { return name; }

    void setDescription( const std::string d ) { description = d; }
    const std::string& getDescription() const { return description; }

    void setAlignment( const Alignment a ) { alignment = a; }
    Alignment getAlignment() const { return alignment; }

    /* Rules */
    std::string getRules() const { return rules; }
    void setRules( const std::string& r ) { rules = r; }

    /* Abilities */
    AblBlock& getAbls() { return *abls; }
    const AblBlock& getAbls() const { return *abls; }

    int getPointsRemain() const { return ablPointsRemain; }
    void decAbl( AblScore );
    void incAbl( AblScore );

    AblScore getAblInc( int n ) const;
    void setAblInc( int n, AblScore abl );

    /* Race */
    std::string getRace() const { return race; }
    void setRace( const std::string& r ) { race = r; }

    /* Serialization */
    void save( const char* fileName ) const;
    void restore( const char* fileName );

    /* Levels */
    constexpr static const int maxLevel = 30;

    int getNumLevels() const { return static_cast<int>( levels.size() ); }
    void pushLevel( const std::string& chclass );
    void popLevel();
    const std::string& getLevel( int lvl ) const;
    void setLevel( int lvl, const std::string& chclass );

    std::map< std::string, int > getChClassCountsAtLvl( int lvl ) const;

    /* Feats */
    const std::vector<int>& getFeatChoicesAtLvl( int lvl ) const;
    void setFeatChoiceAtLvl( int lvl, int index, int featId );

private:
    friend class boost::serialization::access;

    template<class Archive>
    void serialize( Archive & ar, const unsigned int /* file_version */ )
    {
        ar & boost::serialization::make_nvp( "rules", rules )
           & boost::serialization::make_nvp( "name", name )
           & boost::serialization::make_nvp( "description", description )
           & boost::serialization::make_nvp( "race", race )
           & boost::serialization::make_nvp( "alignment", alignment )
           & boost::serialization::make_nvp( "ablPointsRemain", ablPointsRemain )
           & boost::serialization::make_nvp( "abls", abls )
           & boost::serialization::make_nvp( "levels", levels )
           & boost::serialization::make_nvp( "ablIncs", ablIncs )
           & boost::serialization::make_nvp( "featChoices", featChoices );
    }

    int incCost( int curScore ) const;

    constexpr static const int ablPointBuy = 32;
    constexpr static const int minAblScore = 8;
    constexpr static const int maxAblScore = 18;

    std::string rules;
    std::string name;
    std::string description;
    std::string race;
    Alignment alignment = Alignment::LawfulGood;
    int ablPointsRemain = ablPointBuy;
    std::unique_ptr< AblBlock > abls;
    std::vector< std::string > levels;
    std::array< AblScore, 7 > ablIncs = { AblScore::Str,  AblScore::Str, AblScore::Str, AblScore::Str, AblScore::Str, AblScore::Str, AblScore::Str };
    FeatChoiceContainer featChoices;
};

} // namespace Nwn

#endif // NWNCHAR_H

max_stars_repo_name: rkibria/NwnCharGen

max_issues_repo_name: rkibria/NwnCharGen

max_forks_repo_name: rkibria/NwnCharGen


text:
/*
 * Copyright 2015 David A. Boyuka II
 *
 * 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.
 */

/*
 * test-mpi-gather-stream.cpp
 *
 *  Created on: Sep 29, 2014
 *      Author: David A. Boyuka II
 */

#include <vector>

#include <boost/iterator/counting_iterator.hpp>

#include <mpi.h>

#include "pique/parallel/util/mpi-stream.hpp"

int main(int argc, char **argv) {
	char *tempdir_cstr = std::getenv("testworkdir");
	std::string tempdir = (tempdir_cstr ? tempdir_cstr : "test.work.dir");
	std::string filename = tempdir + "/dataset";

	MPI_Init(&argc, &argv);

	int rank, size;
	MPI_Comm_rank(MPI_COMM_WORLD, &rank);
	MPI_Comm_size(MPI_COMM_WORLD, &size);

	assert(size <= 256);

	MPIGatherBufferedStream stream;
	stream.open(MPI_COMM_WORLD, 123, 0);

	if (rank == 0) {
		std::vector<char> inbuf(0, size * (size - 1) / 2);
		auto in_it = inbuf.begin();

		std::streamsize readsize;
		while (stream.read(&*in_it, size) && (readsize = stream.gcount()) > 0)
			in_it += readsize;

		assert(in_it == inbuf.end());

		in_it = inbuf.begin();
		while (in_it != inbuf.end()) {
			char first = *in_it++;
			for (int i = 0; i < first - 1; ++i)
				assert(*in_it++ == first);
		}
	} else {
		std::vector<char> outbuf(rank, (rank % 256));
		stream.write(&outbuf.front(), outbuf.size());
	}

	MPI_Finalize();
}

max_stars_repo_name: daboyuka/PIQUE

max_issues_repo_name: daboyuka/PIQUE

max_forks_repo_name: daboyuka/PIQUE


text:
#include <catch2/catch.hpp>

#include "faasm_fixtures.h"
#include "fixtures.h"
#include "utils.h"

#include <storage/FileLoader.h>

#include <faabric/util/bytes.h>
#include <faabric/util/config.h>
#include <faabric/util/files.h>
#include <faabric/util/func.h>

#include <boost/filesystem.hpp>

namespace tests {

class SharedFilesExecTestFixture
  : public S3TestFixture
  , public FunctionExecTestFixture
{
  public:
    SharedFilesExecTestFixture()
      : loader(storage::getFileLoader())
    {
        storage::SharedFiles::clear();
    }

    ~SharedFilesExecTestFixture() { storage::SharedFiles::clear(); }

  protected:
    storage::FileLoader& loader;
};

TEST_CASE_METHOD(SharedFilesExecTestFixture,
                 "Test accessing shared files from wasm",
                 "[faaslet]")
{
    // Make sure file is deleted locally first
    std::string relativePath = "some_dir/test_file.txt";
    std::string fullPath = loader.getSharedFileFile(relativePath);
    boost::filesystem::remove(fullPath);

    // Execute the function
    auto req = setUpContext("demo", "shared_file");
    SECTION("WAVM") { execFunction(req); }

    // 11/04/2022 - WAMR shared files implementation seems to be broken, so we
    // comment out for now
    // SECTION("WAMR") { execWamrFunction(req->mutable_messages()->at(0)); }

    // Check file has been synced locally
    REQUIRE(boost::filesystem::exists(fullPath));

    // Check contents locally
    std::string expected = "This is some dummy content";
    std::string actual = faabric::util::readFileToString(fullPath);
    REQUIRE(actual == expected);

    // Check contents from S3
    REQUIRE(s3.listKeys(conf.s3Bucket).size() == 1);
    std::string s3Actual = s3.getKeyStr(conf.s3Bucket, relativePath);
    REQUIRE(s3Actual == expected);
}
}

max_stars_repo_name: BieVic/faasm

max_issues_repo_name: BieVic/faasm

max_forks_repo_name: BieVic/faasm


text:
// Copyright Jason Rice 2020
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)

#include <boost/hana/define_struct.hpp>
#include <boost/hana/equal.hpp>
#include <boost/hana/members.hpp>
#include <boost/hana/not_equal.hpp>
namespace hana = boost::hana;

struct SomeStruct {
    BOOST_HANA_DEFINE_STRUCT(SomeStruct, (int, x));

    constexpr bool operator==(SomeStruct const& other) {
        return hana::equal(hana::members(*this), hana::members(other));
    }

    constexpr bool operator!=(SomeStruct const& other) {
        return hana::not_equal(hana::members(*this), hana::members(other));
    }
};

int main() {
    static_assert(SomeStruct{5} == SomeStruct{5}, "");
    static_assert(hana::equal(SomeStruct{5}, SomeStruct{5}), "");
}