text:
//==================================================================================================
/*!
  @file

  @copyright 2016 NumScale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_CONJ_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_CONJ_HPP_INCLUDED

#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{

 /*!

    @ingroup group-arithmetic
    Function object implementing conj capabilities

    Computes the complex conjugate of its parameter

    @par semantic:
    For any given value @c x of type @c T:

    @code
    T r = conj(x);
    @endcode

    for a real parameter, this is equivalent to:

    @code
    T r = x
    @endcode

    This function is the restriction to real numbers of the complex conj(ugation).

  **/
  Value conj(Value const & v0);
} }
#endif

#include <boost/simd/function/scalar/conj.hpp>

#include <boost/simd/function/simd/conj.hpp>

#endif

max_stars_repo_name: xmar/pythran

max_issues_repo_name: xmar/pythran

max_forks_repo_name: xmar/pythran


text:
//==============================================================================
//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI
//         Copyright 2012 - 2014 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_REDUCTION_FUNCTIONS_SCALAR_IS_SIMD_LOGICAL_HPP_INCLUDED
#define BOOST_SIMD_REDUCTION_FUNCTIONS_SCALAR_IS_SIMD_LOGICAL_HPP_INCLUDED

#include <boost/simd/reduction/functions/is_simd_logical.hpp>
#include <boost/simd/sdk/meta/as_logical.hpp>
#include <boost/simd/include/functions/scalar/genmask.hpp>
#include <boost/dispatch/attributes.hpp>

namespace boost { namespace simd { namespace ext
{
  BOOST_DISPATCH_IMPLEMENT          ( is_simd_logical_
                                    , tag::cpu_
                                    , (A0)
                                    , (scalar_<arithmetic_<A0> >)
                                    )
  {
    typedef typename meta::as_logical<A0>::type result_type;

    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL(1)
    {
      return a0 == genmask(a0);
    }
  };

  BOOST_DISPATCH_IMPLEMENT          ( is_simd_logical_
                                    , tag::cpu_
                                    , (A0)
                                    , (scalar_<logical_<A0> >)
                                    )
  {
    typedef typename meta::as_logical<A0>::type result_type;

    BOOST_FORCEINLINE result_type operator()(A0 const&) const
    {
      return true;
    }
  };
} } }

#endif

ext: hpp


text:
// Copyright (c) 2018 The Bitcoin Core developers
// Copyright (c) 2011-2021 The Freicoin Developers
//
// This program is free software: you can redistribute it and/or modify it under
// the terms of version 3 of the GNU Affero General Public License as published
// by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
// details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

#include <memory>

#include <boost/test/unit_test.hpp>

#include <fs.h>
#include <test/test_freicoin.h>
#include <wallet/db.h>

BOOST_FIXTURE_TEST_SUITE(db_tests, BasicTestingSetup)

BOOST_AUTO_TEST_CASE(getwalletenv_file)
{
    std::string test_name = "test_name.dat";
    fs::path datadir = SetDataDir("tempdir");
    fs::path file_path = datadir / test_name;
    std::ofstream f(file_path.BOOST_FILESYSTEM_C_STR);
    f.close();

    std::string filename;
    std::shared_ptr<BerkeleyEnvironment> env = GetWalletEnv(file_path, filename);
    BOOST_CHECK(filename == test_name);
    BOOST_CHECK(env->Directory() == datadir);
}

BOOST_AUTO_TEST_CASE(getwalletenv_directory)
{
    std::string expected_name = "wallet.dat";
    fs::path datadir = SetDataDir("tempdir");

    std::string filename;
    std::shared_ptr<BerkeleyEnvironment> env = GetWalletEnv(datadir, filename);
    BOOST_CHECK(filename == expected_name);
    BOOST_CHECK(env->Directory() == datadir);
}

BOOST_AUTO_TEST_CASE(getwalletenv_g_dbenvs_multiple)
{
    fs::path datadir = SetDataDir("tempdir");
    fs::path datadir_2 = SetDataDir("tempdir_2");
    std::string filename;

    std::shared_ptr<BerkeleyEnvironment> env_1 = GetWalletEnv(datadir, filename);
    std::shared_ptr<BerkeleyEnvironment> env_2 = GetWalletEnv(datadir, filename);
    std::shared_ptr<BerkeleyEnvironment> env_3 = GetWalletEnv(datadir_2, filename);

    BOOST_CHECK(env_1 == env_2);
    BOOST_CHECK(env_2 != env_3);
}

BOOST_AUTO_TEST_CASE(getwalletenv_g_dbenvs_free_instance)
{
    fs::path datadir = SetDataDir("tempdir");
    fs::path datadir_2 = SetDataDir("tempdir_2");
    std::string filename;

    std::shared_ptr <BerkeleyEnvironment> env_1_a = GetWalletEnv(datadir, filename);
    std::shared_ptr <BerkeleyEnvironment> env_2_a = GetWalletEnv(datadir_2, filename);
    env_1_a.reset();

    std::shared_ptr<BerkeleyEnvironment> env_1_b = GetWalletEnv(datadir, filename);
    std::shared_ptr<BerkeleyEnvironment> env_2_b = GetWalletEnv(datadir_2, filename);

    BOOST_CHECK(env_1_a != env_1_b);
    BOOST_CHECK(env_2_a == env_2_b);
}

BOOST_AUTO_TEST_SUITE_END()

ext: cpp

max_stars_repo_name: tradecraftio/tradecraft

max_issues_repo_name: tradecraftio/tradecraft

max_forks_repo_name: tradecraftio/tradecraft


text: #include <boost/thread/ostream_buffer.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include "stdafx.h"
#include "PipeMessage.h"
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/json_parser/detail/wide_encoding.hpp>
#include <boost/iostreams/stream.hpp>

using namespace boost::property_tree;
using namespace std;

PipeMessage::PipeMessage()
	: mMsgType(TRACER_INIT) {
}

PipeMessage::~PipeMessage() {
}

shared_ptr<string> PipeMessage::getSerializedData() const {
	assert(mSerializedData->length() != 0);
	return this->mSerializedData;
}

size_t PipeMessage::getSerializedSize() const {
	return this->mSerializedData->length();
}

PipeMessage::MessageType PipeMessage::getMessageType() const {
	return this->mMsgType;
}

JsonStringMap PipeMessage::getDeserializedData() const {
	return this->mDeserializedData;
}

void PipeMessage::deserialize(const string &serializedData) {
	/*
	Pipe message use a very simple format:

	{
		"type": string,
		"data": {
			"key1": value (string),
			"key2": value (string),
			etc ...
		}
	}
	*/

	// https://stackoverflow.com/a/37712933/7973038
	boost::iostreams::stream<boost::iostreams::array_source> stream(serializedData.c_str(), serializedData.size());
	ptree tree;
	read_json(stream, tree);

	this->mMsgType = static_cast<MessageType>(stoi(tree.get_child("type").data()));

	for (const auto& itm : tree.get_child("data"))
		this->mDeserializedData[itm.first] = itm.second.data();
}

void PipeMessage::serialize(const MessageType &type, const JsonStringMap &map) {
	ptree tree;

	tree.put("type", to_string(type));
	tree.put("data", "");

	for (const auto &entry : map)
		tree.put("data." + entry.first, entry.second);

	ostringstream outBuf;
	write_json(outBuf, tree, false);
	this->mSerializedData = make_shared<string>(outBuf.str().c_str());
}

max_stars_repo_name: FenixDan/NETTrace

max_issues_repo_name: ubbelol/NETTrace

max_forks_repo_name: ubbelol/NETTrace


text:
#if !defined(BOOST_PP_IS_ITERATING)

///// header body

#ifndef BOOST_MPL_UNPACK_ARGS_HPP_INCLUDED
#define BOOST_MPL_UNPACK_ARGS_HPP_INCLUDED

// Copyright Aleksey Gurtovoy 2002-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.

// $Source: /CVSROOT/boost/boost/mpl/unpack_args.hpp,v $
// $Date: 2007/10/29 07:32:40 $
// $Revision: 1.1.1.1 $

#if !defined(BOOST_MPL_PREPROCESSING_MODE)
#   include <boost/mpl/apply.hpp>
#   include <boost/mpl/at.hpp>
#   include <boost/mpl/size.hpp>
#   include <boost/mpl/aux_/nttp_decl.hpp>
#   include <boost/mpl/aux_/lambda_spec.hpp>
#endif

#include <boost/mpl/aux_/config/use_preprocessed.hpp>

#if !defined(BOOST_MPL_CFG_NO_PREPROCESSED_HEADERS) \
    && !defined(BOOST_MPL_PREPROCESSING_MODE)

#   define BOOST_MPL_PREPROCESSED_HEADER unpack_args.hpp
#   include <boost/mpl/aux_/include_preprocessed.hpp>

#else

#   include <boost/mpl/limits/arity.hpp>
#   include <boost/mpl/aux_/preprocessor/repeat.hpp>
#   include <boost/mpl/aux_/config/ctps.hpp>
#   include <boost/mpl/aux_/config/forwarding.hpp>
#   include <boost/preprocessor/iterate.hpp>
#   include <boost/preprocessor/cat.hpp>

namespace boost { namespace mpl {

// local macros, #undef-ined at the end of the header

#   define AUX778076_UNPACK(unused, i, Args) \
    , typename at_c<Args,i>::type \
    /**/

#   define AUX778076_UNPACKED_ARGS(n, Args) \
    BOOST_MPL_PP_REPEAT(n, AUX778076_UNPACK, Args) \
    /**/

namespace aux {

#if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)
template< int size, typename F, typename Args >
struct unpack_args_impl;
#else
template< BOOST_MPL_AUX_NTTP_DECL(int, size) > struct unpack_args_impl
{
    template< typename F, typename Args > struct apply;
};
#endif

#define BOOST_PP_ITERATION_PARAMS_1 \
    (3,(0, BOOST_MPL_LIMIT_METAFUNCTION_ARITY, <boost/mpl/unpack_args.hpp>))
#include BOOST_PP_ITERATE()

}

template<
      typename F
    >
struct unpack_args
{
    template< typename Args > struct apply
#if !defined(BOOST_MPL_CFG_NO_NESTED_FORWARDING)
#   if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)
        : aux::unpack_args_impl< size<Args>::value,F,Args >
#   else
        : aux::unpack_args_impl< size<Args>::value >
            ::template apply< F,Args >
#   endif
    {
#else // BOOST_MPL_CFG_NO_NESTED_FORWARDING
    {
        typedef typename aux::unpack_args_impl<
              size<Args>::value
            , F
            , Args
            >::type type;
#endif
    };
};

BOOST_MPL_AUX_PASS_THROUGH_LAMBDA_SPEC(1, unpack_args)

#   undef AUX778076_UNPACK
#   undef AUX778076_UNPACKED_ARGS

}}

#endif // BOOST_MPL_CFG_USE_PREPROCESSED_HEADERS
#endif // BOOST_MPL_UNPACK_ARGS_HPP_INCLUDED

///// iteration, depth == 1

#elif BOOST_PP_ITERATION_DEPTH() == 1

#   define i_ BOOST_PP_FRAME_ITERATION(1)

#if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)

template< typename F, typename Args >
struct unpack_args_impl<i_,F,Args>
    : BOOST_PP_CAT(apply,i_)<
          F
        AUX778076_UNPACKED_ARGS(i_, Args)
        >
{
};

#else

template<> struct unpack_args_impl<i_>
{
    template< typename F, typename Args > struct apply
        : BOOST_PP_CAT(apply,i_)<
              F
            AUX778076_UNPACKED_ARGS(i_, Args)
            >
    {
    };
};

#endif

#   undef i_

#endif // BOOST_PP_IS_ITERATING

max_stars_repo_name: hackerlank/SourceCode

max_issues_repo_name: shacojx/SourceCodeGameTLBB

max_forks_repo_name: shacojx/SourceCodeGameTLBB


text:
/* CirKit: A circuit toolkit
 * Copyright (C) 2009-2015  University of Bremen
 * Copyright (C) 2015-2017  EPFL
 *
 * 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 "circuit.hpp"

#include <iostream>
#include <string>

#include <boost/format.hpp>
#include <boost/range/adaptors.hpp>

#include "gate.hpp"

#include "functions/copy_circuit.hpp"

namespace cirkit
{
  using boost::adaptors::indirected;
  using boost::adaptors::transformed;

  struct num_gates_visitor : public boost::static_visitor<unsigned>
  {
    unsigned operator()( const standard_circuit& circ ) const
    {
      return circ.gates.size();
    }

    unsigned operator()( const subcircuit& circ ) const
    {
      return circ.to - circ.from;
    }
  };

  struct lines_setter : public boost::static_visitor<>
  {
    explicit lines_setter( unsigned _lines ) : lines( _lines ) {}

    void operator()( standard_circuit& circ ) const
    {
      circ.inputs.resize( lines );
      circ.outputs.resize( lines );
      for ( unsigned i = circ.lines; i < lines; ++i )
      {
          circ.inputs[i] = boost::str( boost::format( "i%d" ) % i );
          circ.outputs[i] = boost::str( boost::format( "o%d" ) % i );
      }
      circ.constants.resize( lines, constant() );
      circ.garbage.resize( lines, false );
      circ.lines = lines;
    }

    void operator()( subcircuit& circ ) const
    {
      // NOTE expand the sub-circuit and therewith automatically the base circuit (in future version)
      assert( false );
    }

  private:
    unsigned lines;
  };

  struct lines_visitor : public boost::static_visitor<unsigned>
  {
    unsigned operator()( const standard_circuit& circ ) const
    {
      return circ.lines;
    }

    unsigned operator()( const subcircuit& circ ) const
    {
      return circ.base->lines;
    }
  };

  struct const_begin_visitor : public boost::static_visitor<circuit::const_iterator>
  {
    circuit::const_iterator operator()( const standard_circuit& circ ) const
    {
      return boost::make_indirect_iterator( circ.gates.begin() );
    }

    circuit::const_iterator operator()( const subcircuit& circ ) const
    {
      return boost::make_indirect_iterator( circ.base->gates.begin() + circ.from );
    }
  };

  struct const_end_visitor : public boost::static_visitor<circuit::const_iterator>
  {
    circuit::const_iterator operator()( const standard_circuit& circ ) const
    {
      return boost::make_indirect_iterator( circ.gates.end() );
    }

    circuit::const_iterator operator()( const subcircuit& circ ) const
    {
      return boost::make_indirect_iterator( circ.base->gates.begin() + circ.to );
    }
  };

  struct begin_visitor : public boost::static_visitor<circuit::iterator>
  {
    circuit::iterator operator()( standard_circuit& circ ) const
    {
      return boost::make_indirect_iterator( circ.gates.begin() );
    }

    circuit::iterator operator()( subcircuit& circ ) const
    {
      return boost::make_indirect_iterator( circ.base->gates.begin() + circ.from );
    }
  };

  struct end_visitor : public boost::static_visitor<circuit::iterator>
  {
    circuit::iterator operator()( standard_circuit& circ ) const
    {
      return boost::make_indirect_iterator( circ.gates.end() );
    }

    circuit::iterator operator()( subcircuit& circ ) const
    {
      return boost::make_indirect_iterator( circ.base->gates.begin() + circ.to );
    }
  };

  struct const_rbegin_visitor : public boost::static_visitor<circuit::const_reverse_iterator>
  {
    circuit::const_reverse_iterator operator()( const standard_circuit& circ ) const
    {
      return boost::make_indirect_iterator( circ.gates.rbegin() );
    }

    circuit::const_reverse_iterator operator()( const subcircuit& circ ) const
    {
      return boost::make_indirect_iterator( circ.base->gates.rbegin() + ( circ.base->gates.size() - circ.to ) );
    }
  };

  struct const_rend_visitor : public boost::static_visitor<circuit::const_reverse_iterator>
  {
    circuit::const_reverse_iterator operator()( const standard_circuit& circ ) const
    {
      return boost::make_indirect_iterator( circ.gates.rend() );
    }

    circuit::const_reverse_iterator operator()( const subcircuit& circ ) const
    {
      return boost::make_indirect_iterator( circ.base->gates.rbegin() + ( circ.base->gates.size() - circ.from ) );
    }
  };

  struct rbegin_visitor : public boost::static_visitor<circuit::reverse_iterator>
  {
    circuit::reverse_iterator operator()( standard_circuit& circ ) const
    {
      return boost::make_indirect_iterator( circ.gates.rbegin() );
    }

    circuit::reverse_iterator operator()( subcircuit& circ ) const
    {
      return boost::make_indirect_iterator( circ.base->gates.rbegin() + ( circ.base->gates.size() - circ.to ) );
    }
  };

  struct rend_visitor : public boost::static_visitor<circuit::reverse_iterator>
  {
    circuit::reverse_iterator operator()( standard_circuit& circ ) const
    {
      return boost::make_indirect_iterator( circ.gates.rend() );
    }

    circuit::reverse_iterator operator()( subcircuit& circ ) const
    {
      return boost::make_indirect_iterator( circ.base->gates.rbegin() + ( circ.base->gates.size() - circ.from ) );
    }
  };

  struct append_gate_visitor/* : public boost::static_visitor<gate&>*/
  {
    gate& operator()( standard_circuit& circ ) const
    {
      circ.gates.push_back( std::make_shared<gate>() );
      return *circ.gates.back();
    }

    gate& operator()( subcircuit& circ ) const
    {
      circ.base->gates.insert( circ.base->gates.begin() + circ.to, std::make_shared<gate>() );
      ++circ.to;

      gate& g = **( circ.base->gates.begin() + circ.to - 1 );
      return g;
    }
  };

  struct prepend_gate_visitor/* : public boost::static_visitor<gate&>*/
  {
    gate& operator()( standard_circuit& circ ) const
    {
      circ.gates.insert( circ.gates.begin(), std::make_shared<gate>() );
      return *circ.gates.front();
    }

    gate& operator()( subcircuit& circ ) const
    {
      circ.base->gates.insert( circ.base->gates.begin() + circ.from, std::make_shared<gate>() );
      ++circ.to;

      gate& g = **( circ.base->gates.begin() + circ.from );
      return g;
    }
  };

  struct insert_gate_visitor/* : public boost::static_visitor<gate&>*/
  {
    explicit insert_gate_visitor( unsigned _pos ) : pos( _pos ) {}

    gate& operator()( standard_circuit& circ ) const
    {
      circ.gates.insert( circ.gates.begin() + pos, std::make_shared<gate>() );
      return *circ.gates.at( pos );
    }

    gate& operator()( subcircuit& circ ) const
    {
      circ.base->gates.insert( circ.base->gates.begin() + circ.from + pos, std::make_shared<gate>() );
      ++circ.to;

      gate& g = **( circ.base->gates.begin() + circ.from + pos );
      return g;
    }

  private:
    unsigned pos;
  };

  struct remove_gate_at_visitor/* : public boost::static_visitor<>*/
  {
    explicit remove_gate_at_visitor( unsigned _pos ) : pos( _pos ) {}

    void operator()( standard_circuit& circ ) const
    {
      if ( pos < circ.gates.size() )
      {
        circ.gates.erase( circ.gates.begin() + pos );
      }
    }

    void operator()( subcircuit& circ ) const
    {
      if ( pos < circ.to )
      {
        circ.base->gates.erase( circ.base->gates.begin() + circ.from + pos );
        --circ.to;
      }
    }

  private:
    unsigned pos;
  };

  struct inputs_setter/* : public boost::static_visitor<>*/
  {
    explicit inputs_setter( const std::vector<std::string>& _inputs ) : inputs( _inputs ) {}

    void operator()( standard_circuit& circ ) const
    {
      circ.inputs.clear();
      std::copy( inputs.begin(), inputs.end(), std::back_inserter( circ.inputs ) );
      circ.inputs.resize( circ.lines, "i" );
    }

    void operator()( subcircuit& circ ) const
    {
      circ.base->inputs.clear();
      std::copy( inputs.begin(), inputs.end(), std::back_inserter( circ.base->inputs ) );
      circ.base->inputs.resize( circ.base->lines, "i" );
    }

  private:
    const std::vector<std::string>& inputs;
  };

  struct inputs_visitor/* : public boost::static_visitor<const std::vector<std::string>& >*/
  {
    const std::vector<std::string>& operator()( const standard_circuit& circ ) const
    {
      return circ.inputs;
    }

    const std::vector<std::string>& operator()( const subcircuit& circ ) const
    {
      return circ.base->inputs;
    }
  };

  struct outputs_setter/* : public boost::static_visitor<>*/
  {
    explicit outputs_setter( const std::vector<std::string>& _outputs ) : outputs( _outputs ) {}

    void operator()( standard_circuit& circ ) const
    {
      circ.outputs.clear();
      std::copy( outputs.begin(), outputs.end(), std::back_inserter( circ.outputs ) );
      circ.outputs.resize( circ.lines, "o" );
    }

    void operator()( subcircuit& circ ) const
    {
      circ.base->outputs.clear();
      std::copy( outputs.begin(), outputs.end(), std::back_inserter( circ.base->outputs ) );
      circ.base->outputs.resize( circ.base->lines, "o" );
    }

  private:
    const std::vector<std::string>& outputs;
  };

  struct outputs_visitor/* : public boost::static_visitor<const std::vector<std::string>& >*/
  {
    const std::vector<std::string>& operator()( const standard_circuit& circ ) const
    {
      return circ.outputs;
    }

    const std::vector<std::string>& operator()( const subcircuit& circ ) const
    {
      return circ.base->outputs;
    }
  };

  struct constants_setter/* : public boost::static_visitor<>*/
  {
    explicit constants_setter( const std::vector<constant>& _constants ) : constants( _constants ) {}

    void operator()( standard_circuit& circ ) const
    {
      circ.constants.clear();
      std::copy( constants.begin(), constants.end(), std::back_inserter( circ.constants ) );
      circ.constants.resize( circ.lines, constant() );
    }

    void operator()( subcircuit& circ ) const
    {
      circ.base->constants.clear();
      std::copy( constants.begin(), constants.end(), std::back_inserter( circ.base->constants ) );
      circ.base->constants.resize( circ.base->lines, constant() );
    }

  private:
    const std::vector<constant>& constants;
  };

  struct constants_visitor/* : public boost::static_visitor<const std::vector<constant>& >*/
  {
    const std::vector<constant>& operator()( const standard_circuit& circ ) const
    {
      return circ.constants;
    }

    const std::vector<constant>& operator()( const subcircuit& circ ) const
    {
      return circ.base->constants;
    }
  };

  struct garbage_setter/* : public boost::static_visitor<>*/
  {
    explicit garbage_setter( const std::vector<bool>& _garbage ) : garbage( _garbage ) {}

    void operator()( standard_circuit& circ ) const
    {
      circ.garbage.clear();
      std::copy( garbage.begin(), garbage.end(), std::back_inserter( circ.garbage ) );
      circ.garbage.resize( circ.lines, false );
    }

    void operator()( subcircuit& circ ) const
    {
      circ.base->garbage.clear();
      std::copy( garbage.begin(), garbage.end(), std::back_inserter( circ.base->garbage ) );
      circ.base->garbage.resize( circ.base->lines, false );
    }

  private:
    const std::vector<bool>& garbage;
  };

  struct garbage_visitor/* : public boost::static_visitor<const std::vector<bool>& >*/
  {
    const std::vector<bool>& operator()( const standard_circuit& circ ) const
    {
      return circ.garbage;
    }

    const std::vector<bool>& operator()( const subcircuit& circ ) const
    {
      return circ.base->garbage;
    }
  };

  struct circuit_name_setter/* : public boost::static_visitor<>*/
  {
    explicit circuit_name_setter( const std::string& _name ) : name( _name ) {}

    void operator()( standard_circuit& circ ) const
    {
      circ.name = name;
    }

    void operator()( subcircuit& circ ) const
    {
      circ.base->name = name;
    }

  private:
    const std::string& name;
  };

  struct circuit_name_visitor/* : public boost::static_visitor<const std::string&>*/
  {
    const std::string& operator()( const standard_circuit& circ ) const
    {
      return circ.name;
    }

    const std::string& operator()( const subcircuit& circ ) const
    {
      return circ.base->name;
    }
  };

  struct const_inputbuses_visitor/* : public boost::static_visitor<const bus_collection&>*/
  {
    const bus_collection& operator()( const standard_circuit& circ ) const
    {
      return circ.inputbuses;
    }

    const bus_collection& operator()( const subcircuit& circ ) const
    {
      return circ.base->inputbuses;
    }
  };

  struct inputbuses_visitor/* : public boost::static_visitor<bus_collection&>*/
  {
    bus_collection& operator()( standard_circuit& circ ) const
    {
      return circ.inputbuses;
    }

    bus_collection& operator()( subcircuit& circ ) const
    {
      return circ.base->inputbuses;
    }
  };

  struct const_outputbuses_visitor/* : public boost::static_visitor<const bus_collection&>*/
  {
    const bus_collection& operator()( const standard_circuit& circ ) const
    {
      return circ.outputbuses;
    }

    const bus_collection& operator()( const subcircuit& circ ) const
    {
      return circ.base->outputbuses;
    }
  };

  struct outputbuses_visitor/* : public boost::static_visitor<bus_collection&>*/
  {
    bus_collection& operator()( standard_circuit& circ ) const
    {
      return circ.outputbuses;
    }

    bus_collection& operator()( subcircuit& circ ) const
    {
      return circ.base->outputbuses;
    }
  };

  struct const_statesignals_visitor/* : public boost::static_visitor<const bus_collection&>*/
  {
    const bus_collection& operator()( const standard_circuit& circ ) const
    {
      return circ.statesignals;
    }

    const bus_collection& operator()( const subcircuit& circ ) const
    {
      return circ.base->statesignals;
    }
  };

  struct statesignals_visitor/* : public boost::static_visitor<bus_collection&>*/
  {
    bus_collection& operator()( standard_circuit& circ ) const
    {
      return circ.statesignals;
    }

    bus_collection& operator()( subcircuit& circ ) const
    {
      return circ.base->statesignals;
    }
  };

  struct is_subcircuit_visitor/* : public boost::static_visitor<bool>*/
  {
    bool operator()( const standard_circuit& circ ) const
    {
      return false;
    }

    bool operator()( const subcircuit& circ ) const
    {
      return true;
    }
  };

  struct offset_visitor/* : public boost::static_visitor<unsigned>*/
  {
    unsigned operator()( const standard_circuit& circ ) const
    {
      return 0u;
    }

    unsigned operator()( const subcircuit& circ ) const
    {
      return circ.from;
    }
  };

  struct annotation_visitor/* : public boost::static_visitor<const std::string&>*/
  {
    annotation_visitor( const gate& g, const std::string& key, const std::string& default_value )
      : g( g ), key( key ), default_value( default_value )
    {
    }

    const std::string& operator()( const standard_circuit& circ ) const
    {
      std::map<const gate*, std::map<std::string, std::string> >::const_iterator it = circ.annotations.find( &g );
      if ( it != circ.annotations.end() )
      {
        std::map<std::string, std::string>::const_iterator it2 = it->second.find( key );
        if ( it2 != it->second.end() )
        {
          return it2->second;
        }
        else
        {
          return default_value;
        }
      }
      else
      {
        return default_value;
      }
    }

    const std::string& operator()( const subcircuit& circ ) const
    {
      return operator()( *circ.base );
    }

  private:
    const gate& g;
    const std::string& key;
    const std::string& default_value;
  };

  struct annotations_visitor/* : public boost::static_visitor<boost::optional<const std::map<std::string, std::string>& > >*/
  {
    explicit annotations_visitor( const gate& g ) : g( g ) {}

    boost::optional<const std::map<std::string, std::string>& > operator()( const standard_circuit& circ ) const
    {
      std::map<const gate*, std::map<std::string, std::string> >::const_iterator it = circ.annotations.find( &g );
      if ( it != circ.annotations.end() )
      {
        return boost::optional<const std::map<std::string, std::string>& >( it->second );
      }
      else
      {
        return boost::optional<const std::map<std::string, std::string>& >();
      }
    }

    boost::optional<const std::map<std::string, std::string>& > operator()( const subcircuit& circ ) const
    {
      return operator()( *circ.base );
    }

  private:
    const gate& g;
  };

  struct annotate_visitor/* : public boost::static_visitor<>*/
  {
    annotate_visitor( const gate& g, const std::string& key, const std::string& value )
      : g( g ), key( key ), value( value )
    {
    }

    void operator()( standard_circuit& circ ) const
    {
      circ.annotations[&g][key] = value;
    }

    void operator()( subcircuit& circ ) const
    {
      operator()( *circ.base );
    }

  private:
    const gate& g;
    const std::string& key;
    const std::string& value;
  };

  unsigned circuit::num_gates() const
  {
    return boost::apply_visitor( num_gates_visitor(), circ );
  }

  void circuit::set_lines( unsigned lines )
  {
    boost::apply_visitor( lines_setter( lines ), circ );
  }

  unsigned circuit::lines() const
  {
    return boost::apply_visitor( lines_visitor(), circ );
  }

  circuit::const_iterator circuit::begin() const
  {
    return boost::apply_visitor( const_begin_visitor(), circ );
  }

  circuit::const_iterator circuit::end() const
  {
    return boost::apply_visitor( const_end_visitor(), circ );
  }

  circuit::iterator circuit::begin()
  {
    return boost::apply_visitor( begin_visitor(), circ );
  }

  circuit::iterator circuit::end()
  {
    return boost::apply_visitor( end_visitor(), circ );
  }

  circuit::const_reverse_iterator circuit::rbegin() const
  {
    return boost::apply_visitor( const_rbegin_visitor(), circ );
  }

  circuit::const_reverse_iterator circuit::rend() const
  {
    return boost::apply_visitor( const_rend_visitor(), circ );
  }

  circuit::reverse_iterator circuit::rbegin()
  {
    return boost::apply_visitor( rbegin_visitor(), circ );
  }

  circuit::reverse_iterator circuit::rend()
  {
    return boost::apply_visitor( rend_visitor(), circ );
  }

  const gate& circuit::operator[]( unsigned index ) const
  {
    return *( begin() + index );
  }

  gate& circuit::operator[]( unsigned index )
  {
    return *( begin() + index );
  }

  gate& circuit::append_gate()
  {
    return boost::apply_visitor( append_gate_visitor(), circ );
  }

  gate& circuit::prepend_gate()
  {
    return boost::apply_visitor( prepend_gate_visitor(), circ );
  }

  gate& circuit::insert_gate( unsigned pos )
  {
    return boost::apply_visitor( insert_gate_visitor( pos ), circ );
  }

  void circuit::remove_gate_at( unsigned pos )
  {
    boost::apply_visitor( remove_gate_at_visitor( pos ), circ );
  }

  void circuit::set_inputs( const std::vector<std::string>& inputs )
  {
    boost::apply_visitor( inputs_setter( inputs ), circ );
  }

  const std::vector<std::string>& circuit::inputs() const
  {
    return boost::apply_visitor( inputs_visitor(), circ );
  }

  void circuit::set_outputs( const std::vector<std::string>& outputs )
  {
    boost::apply_visitor( outputs_setter( outputs ), circ );
  }

  const std::vector<std::string>& circuit::outputs() const
  {
    return boost::apply_visitor( outputs_visitor(), circ );
  }

  void circuit::set_constants( const std::vector<constant>& constants )
  {
    boost::apply_visitor( constants_setter( constants ), circ );
  }

  const std::vector<constant>& circuit::constants() const
  {
    return boost::apply_visitor( constants_visitor(), circ );
  }

  void circuit::set_garbage( const std::vector<bool>& garbage )
  {
    boost::apply_visitor( garbage_setter( garbage ), circ );
  }

  const std::vector<bool>& circuit::garbage() const
  {
    return boost::apply_visitor( garbage_visitor(), circ );
  }

  void circuit::set_circuit_name( const std::string& name )
  {
    boost::apply_visitor( circuit_name_setter( name ), circ );
  }

  const std::string& circuit::circuit_name() const
  {
    return boost::apply_visitor( circuit_name_visitor(), circ );
  }

  const bus_collection& circuit::inputbuses() const
  {
    return boost::apply_visitor( const_inputbuses_visitor(), circ );
  }

  bus_collection& circuit::inputbuses()
  {
    return boost::apply_visitor( inputbuses_visitor(), circ );
  }

  const bus_collection& circuit::outputbuses() const
  {
    return boost::apply_visitor( const_outputbuses_visitor(), circ );
  }

  bus_collection& circuit::outputbuses()
  {
    return boost::apply_visitor( outputbuses_visitor(), circ );
  }

  const bus_collection& circuit::statesignals() const
  {
    return boost::apply_visitor( const_statesignals_visitor(), circ );
  }

  bus_collection& circuit::statesignals()
  {
    return boost::apply_visitor( statesignals_visitor(), circ );
  }

  bool circuit::is_subcircuit() const
  {
    return boost::apply_visitor( is_subcircuit_visitor(), circ );
  }

  unsigned circuit::offset() const
  {
    return boost::apply_visitor( offset_visitor(), circ );
  }

  void circuit::add_module( const std::string& name, const std::shared_ptr<circuit>& module )
  {
    _modules.insert( std::make_pair( name, module ) );
  }

  void circuit::add_module( const std::string& name, const circuit& module )
  {
    circuit* copy = new circuit();
    copy_circuit( module, *copy );
    add_module( name, std::shared_ptr<circuit>( copy ) );
  }

  const std::map<std::string, std::shared_ptr<circuit> >& circuit::modules() const
  {
    return _modules;
  }

  const std::string& circuit::annotation( const gate& g, const std::string& key, const std::string& default_value ) const
  {
    return boost::apply_visitor( annotation_visitor( g, key, default_value ), circ );
  }

  boost::optional<const std::map<std::string, std::string>& > circuit::annotations( const gate& g ) const
  {
    return boost::apply_visitor( annotations_visitor( g ), circ );
  }

  void circuit::annotate( const gate& g, const std::string& key, const std::string& value )
  {
    boost::apply_visitor( annotate_visitor( g, key, value ), circ );
  }

}

// Local Variables:
// c-basic-offset: 2
// eval: (c-set-offset 'substatement-open 0)
// eval: (c-set-offset 'innamespace 0)
// End:

max_stars_repo_name: eletesta/cirkit

max_issues_repo_name: eletesta/cirkit

max_forks_repo_name: eletesta/cirkit


text:
// Function library

// Copyright (C) 2001-2003 Douglas Gregor

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

#include <boost/function.hpp>
#include <boost/detail/lightweight_test.hpp>
#include <iostream>
#include <functional>

struct X {
  int foo(int);
  std::ostream& foo2(std::ostream&) const;
};
int X::foo(int x) { return -x; }
std::ostream& X::foo2(std::ostream& x) const { return x; }

int main()
{
    boost::function2<int, X*, int> f;
    boost::function2<std::ostream&, X*, std::ostream&> f2;

    f = &X::foo;
    f2 = &X::foo2;

    X x;
    BOOST_TEST(f(&x, 5) == -5);
    BOOST_TEST(f2(&x, boost::ref(std::cout)) == std::cout);

    return ::boost::report_errors();
}


text:
/*
Part of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)
Copyright 2017-2019 University of Huddersfield.
Licensed under the BSD-3 License.
See license.md file in the project root for full license information.
This project has received funding from the European Research Council (ERC)
under the European Union’s Horizon 2020 research and innovation programme
(grant agreement No 725899).
*/

#pragma once

#include "FluidEigenMappings.hpp"
#include "../../data/FluidIndex.hpp"
#include "../../data/FluidTensor.hpp"
#include <Eigen/Core>
#include <limits>

namespace fluid {
namespace algorithm {

class OutlierDetection
{

  using ArrayXd = Eigen::ArrayXd;
  using ArrayXi = Eigen::ArrayXi;

public:
  void process(Eigen::Ref<const ArrayXd> input, Eigen::Ref<Eigen::ArrayXi> mask,
               double k)
  {
    index   length = input.size();
    ArrayXidx perm = ArrayXidx::LinSpaced(length, 0, length - 1);
    std::sort(perm.data(), perm.data() + length,
              [&](index i, index j) { return input(i) < input(j); });
    index  q1 = lrint(0.25 * (length - 1));
    index  q3 = lrint(0.75 * (length - 1));
    double margin = k * (input(perm(q3)) - input(perm(q1)));
    double lowerBound = input(perm(q1)) - margin;
    double upperBound = input(perm(q3)) + margin;
    for (index i = 0; input(perm(i)) < lowerBound && i <= q1; i++)
    { mask(perm(i)) = 0; }
    for (index i = length - 1; input(perm(i)) > upperBound && i >= q3; i--)
    { mask(perm(i)) = 0; }
  }
};
} // namespace algorithm
} // namespace fluid


text:
// Copyright (c) 2017-2018 The Bitcoin Green developers
// Copyright (c) 2018 The Insifa developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "init.h"
#include "main.h"

#include "activemasternode.h"
#include "addrman.h"
#include "masternode-vote.h"
#include "masternode-sync.h"
#include "masternode-helpers.h"
#include "masternodeconfig.h"
#include "masternode.h"
#include "masternodeman.h"
#include "util.h"
#include "wallet.h"

#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>

CCommunityVoteManager communityVote;
CCriticalSection cs_communityvote;

std::map<uint256, int64_t> askedForSourceProposalOrVote;
std::vector<CCommunityProposalBroadcast> vecCommunityProposals;

bool IsCommunityCollateralValid(uint256 nTxCollateralHash, uint256 nExpectedHash, std::string& strError, int64_t& nTime, int& nConf)
{
    CTransaction txCollateral;
    uint256 nBlockHash;
    if (!GetTransaction(nTxCollateralHash, txCollateral, nBlockHash, true)) {
        strError = strprintf("Can't find collateral tx %s", txCollateral.ToString());
        LogPrint("masternode", "::IsCommunityCollateralValid - %s\n", strError);
        return false;
    }

    if (txCollateral.vout.size() < 1) return false;
    if (txCollateral.nLockTime != 0) return false;

    CScript findScript;
    findScript << OP_RETURN << ToByteVector(nExpectedHash);

    bool foundOpReturn = false;
    for (const CTxOut o : txCollateral.vout) {
        if (!o.scriptPubKey.IsNormalPaymentScript() && !o.scriptPubKey.IsUnspendable()) {
            strError = strprintf("Invalid Script %s", txCollateral.ToString());
            LogPrint("masternode", "::IsCommunityCollateralValid - %s\n", strError);
            return false;
        }
        if (o.scriptPubKey == findScript && o.nValue >= COMMUNITY_VOTE_FEE_TX) foundOpReturn = true;
    }

    if (!foundOpReturn) {
        strError = strprintf("Couldn't find opReturn %s in %s", nExpectedHash.ToString(), txCollateral.ToString());
        LogPrint("masternode", "::IsCommunityCollateralValid - %s\n", strError);
        return false;
    }

    // RETRIEVE CONFIRMATIONS AND NTIME
    /*
        - nTime starts as zero and is passed-by-reference out of this function and stored in the external proposal
        - nTime is never validated via the hashing mechanism and comes from a full-validated source (the blockchain)
    */

    int conf = GetIXConfirmations(nTxCollateralHash);
    if (nBlockHash != uint256(0)) {
        BlockMap::iterator mi = mapBlockIndex.find(nBlockHash);
        if (mi != mapBlockIndex.end() && (*mi).second) {
            CBlockIndex* pindex = (*mi).second;
            if (chainActive.Contains(pindex)) {
                conf += chainActive.Height() - pindex->nHeight + 1;
                nTime = pindex->nTime;
            }
        }
    }

    nConf = conf;

    // if we're syncing we won't have swiftTX information, so accept 1 confirmation
    if (conf >= Params().Budget_Fee_Confirmations()) {
        return true;
    } else {
        strError = strprintf("Collateral requires at least %d confirmations - %d confirmations", Params().Budget_Fee_Confirmations(), conf);
        LogPrint("masternode", "::IsCommunityCollateralValid - %s\n", strError);
        return false;
    }
}

void CCommunityVoteManager::CheckOrphanVotes()
{
    LOCK(cs);

    std::string strError = "";
    std::map<uint256, CCommunityVote>::iterator it1 = mapOrphanMasternodeCommunityVotes.begin();
    while (it1 != mapOrphanMasternodeCommunityVotes.end()) {
        if (communityVote.UpdateProposal(((*it1).second), NULL, strError)) {
            LogPrint("masternode", "CCommunityVoteManager::CheckOrphanVotes - Proposal/CommunityVote is known, activating and removing orphan vote\n");
            mapOrphanMasternodeCommunityVotes.erase(it1++);
        } else {
            ++it1;
        }
    }

    LogPrint("masternode", "CCommunityVoteManager::CheckOrphanVotes - Done\n");
}

//
// CCommunityDB
//

CCommunityDB::CCommunityDB()
{
    pathDB = GetDataDir() / "communityvote.dat";
    strMagicMessage = "MasternodeCommunityVote";
}

bool CCommunityDB::Write(const CCommunityVoteManager& objToSave)
{
    LOCK(objToSave.cs);

    int64_t nStart = GetTimeMillis();

    // serialize, checksum data up to that point, then append checksum
    CDataStream ssObj(SER_DISK, CLIENT_VERSION);
    ssObj << strMagicMessage;                   // masternode cache file specific magic message
    ssObj << FLATDATA(Params().MessageStart()); // network specific magic number
    ssObj << objToSave;
    uint256 hash = Hash(ssObj.begin(), ssObj.end());
    ssObj << hash;

    // open output file, and associate with CAutoFile
    FILE* file = fopen(pathDB.string().c_str(), "wb");
    CAutoFile fileout(file, SER_DISK, CLIENT_VERSION);
    if (fileout.IsNull())
        return error("%s : Failed to open file %s", __func__, pathDB.string());

    // Write and commit header, data
    try {
        fileout << ssObj;
    } catch (std::exception& e) {
        return error("%s : Serialize or I/O error - %s", __func__, e.what());
    }
    fileout.fclose();

    LogPrint("masternode", "Written info to communityvote.dat  %dms\n", GetTimeMillis() - nStart);

    return true;
}

CCommunityDB::ReadResult CCommunityDB::Read(CCommunityVoteManager& objToLoad, bool fDryRun)
{
    LOCK(objToLoad.cs);

    int64_t nStart = GetTimeMillis();
    // open input file, and associate with CAutoFile
    FILE* file = fopen(pathDB.string().c_str(), "rb");
    CAutoFile filein(file, SER_DISK, CLIENT_VERSION);
    if (filein.IsNull()) {
        error("%s : Failed to open file %s", __func__, pathDB.string());
        return FileError;
    }

    // use file size to size memory buffer
    int fileSize = boost::filesystem::file_size(pathDB);
    int dataSize = fileSize - sizeof(uint256);
    // Don't try to resize to a negative number if file is small
    if (dataSize < 0)
        dataSize = 0;
    vector<unsigned char> vchData;
    vchData.resize(dataSize);
    uint256 hashIn;

    // read data and checksum from file
    try {
        filein.read((char*)&vchData[0], dataSize);
        filein >> hashIn;
    } catch (std::exception& e) {
        error("%s : Deserialize or I/O error - %s", __func__, e.what());
        return HashReadError;
    }
    filein.fclose();

    CDataStream ssObj(vchData, SER_DISK, CLIENT_VERSION);

    // verify stored checksum matches input data
    uint256 hashTmp = Hash(ssObj.begin(), ssObj.end());
    if (hashIn != hashTmp) {
        error("%s : Checksum mismatch, data corrupted", __func__);
        return IncorrectHash;
    }

    unsigned char pchMsgTmp[4];
    std::string strMagicMessageTmp;
    try {
        // de-serialize file header (masternode cache file specific magic message) and ..
        ssObj >> strMagicMessageTmp;

        // ... verify the message matches predefined one
        if (strMagicMessage != strMagicMessageTmp) {
            error("%s : Invalid masternode cache magic message", __func__);
            return IncorrectMagicMessage;
        }

        // de-serialize file header (network specific magic number) and ..
        ssObj >> FLATDATA(pchMsgTmp);

        // ... verify the network matches ours
        if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp))) {
            error("%s : Invalid network magic number", __func__);
            return IncorrectMagicNumber;
        }

        // de-serialize data into CCommunityVoteManager object
        ssObj >> objToLoad;
    } catch (std::exception& e) {
        objToLoad.Clear();
        error("%s : Deserialize or I/O error - %s", __func__, e.what());
        return IncorrectFormat;
    }

    LogPrint("masternode", "Loaded info from communityvote.dat  %dms\n", GetTimeMillis() - nStart);
    LogPrint("masternode", "  %s\n", objToLoad.ToString());
    if (!fDryRun) {
        LogPrint("masternode", "Community vote manager - cleaning....\n");
        objToLoad.CheckAndRemove();
        LogPrint("masternode", "Community vote manager - result:\n");
        LogPrint("masternode", "  %s\n", objToLoad.ToString());
    }

    return Ok;
}

void DumpCommunityVotes()
{
    int64_t nStart = GetTimeMillis();

    CCommunityDB votedb;
    CCommunityVoteManager tempCommunityVote;

    LogPrint("masternode", "Verifying communityvote.dat format...\n");
    CCommunityDB::ReadResult readResult = votedb.Read(tempCommunityVote, true);
    // there was an error and it was not an error on file opening => do not proceed
    if (readResult == CCommunityDB::FileError)
        LogPrint("masternode", "Missing communityvote file - communityvote.dat, will try to recreate\n");
    else if (readResult != CCommunityDB::Ok) {
        LogPrint("masternode", "Error reading communityvote.dat: ");
        if (readResult == CCommunityDB::IncorrectFormat)
            LogPrint("masternode", "magic is ok but data has invalid format, will try to recreate\n");
        else {
            LogPrint("masternode", "file format is unknown or invalid, please fix it manually\n");
            return;
        }
    }
    LogPrint("masternode", "Writting info to communityvote.dat...\n");
    votedb.Write(communityVote);

    LogPrint("masternode", "Community vote dump finished  %dms\n", GetTimeMillis() - nStart);
}

bool CCommunityVoteManager::AddProposal(CCommunityProposal& voteProposal)
{
    LOCK(cs);
    std::string strError = "";
    if (!voteProposal.IsValid(strError)) {
        LogPrint("masternode", "CCommunityVoteManager::AddProposal - invalid vote proposal - %s\n", strError);
        return false;
    }

    if (mapProposals.count(voteProposal.GetHash())) {
        return false;
    }

    mapProposals.insert(make_pair(voteProposal.GetHash(), voteProposal));
    LogPrint("masternode", "CCommunityVoteManager::AddProposal - proposal %s added\n", voteProposal.GetName().c_str());
    return true;
}

void CCommunityVoteManager::CheckAndRemove()
{
    LogPrint("mncommunityvote", "CCommunityVoteManager::CheckAndRemove\n");

    std::string strError = "";

    LogPrint("mncommunityvote", "CCommunityVoteManager::CheckAndRemove - mapProposals cleanup - size before: %d\n", mapProposals.size());
    std::map<uint256, CCommunityProposal>::iterator it2 = mapProposals.begin();
    while (it2 != mapProposals.end()) {
        CCommunityProposal* pcommunityProposal = &((*it2).second);
        pcommunityProposal->fValid = pcommunityProposal->IsValid(strError);
        if (!strError.empty()) {
            LogPrint("masternode", "CCommunityVoteManager::CheckAndRemove - Invalid vote proposal - %s\n", strError);
            strError = "";
        } else {
             LogPrint("masternode", "CCommunityVoteManager::CheckAndRemove - Found valid vote proposal: %s %s\n",
                      pcommunityProposal->strProposalName.c_str(), pcommunityProposal->nFeeTXHash.ToString().c_str());
        }

        ++it2;
    }

    LogPrint("masternode", "CCommunityVoteManager::CheckAndRemove - PASSED\n");
}

CCommunityProposal* CCommunityVoteManager::FindProposal(const std::string& strProposalName)
{
    //find the prop with the highest yes count

    int nYesCount = -99999;
    CCommunityProposal* pcommunityProposal = NULL;

    std::map<uint256, CCommunityProposal>::iterator it = mapProposals.begin();
    while (it != mapProposals.end()) {
        if ((*it).second.strProposalName == strProposalName && (*it).second.GetYeas() > nYesCount) {
            pcommunityProposal = &((*it).second);
            nYesCount = pcommunityProposal->GetYeas();
        }
        ++it;
    }

    if (nYesCount == -99999) return NULL;

    return pcommunityProposal;
}

CCommunityProposal* CCommunityVoteManager::FindProposal(uint256 nHash)
{
    LOCK(cs);

    if (mapProposals.count(nHash))
        return &mapProposals[nHash];

    return NULL;
}

std::vector<CCommunityProposal*> CCommunityVoteManager::GetAllProposals()
{
    LOCK(cs);

    std::vector<CCommunityProposal*> vVoteProposalRet;

    std::map<uint256, CCommunityProposal>::iterator it = mapProposals.begin();
    while (it != mapProposals.end()) {
        (*it).second.CleanAndRemove(false);

        CCommunityProposal* pcommunityProposal = &((*it).second);
        vVoteProposalRet.push_back(pcommunityProposal);

        ++it;
    }

    return vVoteProposalRet;
}

//
// Sort by votes, if there's a tie sort by their feeHash TX
//
struct sortCommunityProposalsByVotes {
    bool operator()(const std::pair<CCommunityProposal*, int>& left, const std::pair<CCommunityProposal*, int>& right)
    {
        if (left.second != right.second)
            return (left.second > right.second);
        return (left.first->nFeeTXHash > right.first->nFeeTXHash);
    }
};

void CCommunityVoteManager::NewBlock()
{
    TRY_LOCK(cs, fVoteNewBlock);
    if (!fVoteNewBlock) return;

    if (masternodeSync.RequestedMasternodeAssets <= MASTERNODE_SYNC_COMMUNITYVOTE) return;

    // incremental sync with our peers
    if (masternodeSync.IsSynced()) {
        LogPrint("masternode", "CCommunityVoteManager::NewBlock - incremental sync started\n");
        if (chainActive.Height() % 1440 == rand() % 1440) {
            ClearSeen();
            ResetSync();
        }

        LOCK(cs_vNodes);
        BOOST_FOREACH (CNode* pnode, vNodes)
            if (pnode->nVersion >= ActiveProtocol())
                Sync(pnode, 0, true);

        MarkSynced();
    }

    CheckAndRemove();

    //remove invalid votes once in a while (we have to check the signatures and validity of every vote, somewhat CPU intensive)
    LogPrint("masternode", "CCommunityVoteManager::NewBlock - askedForSourceProposalOrVote cleanup - size: %d\n", askedForSourceProposalOrVote.size());
    std::map<uint256, int64_t>::iterator it = askedForSourceProposalOrVote.begin();
    while (it != askedForSourceProposalOrVote.end()) {
        if ((*it).second > GetTime() - (60 * 60 * 24)) {
            ++it;
        } else {
            askedForSourceProposalOrVote.erase(it++);
        }
    }

    LogPrint("masternode", "CCommunityVoteManager::NewBlock - mapProposals cleanup - size: %d\n", mapProposals.size());
    std::map<uint256, CCommunityProposal>::iterator it2 = mapProposals.begin();
    while (it2 != mapProposals.end()) {
        (*it2).second.CleanAndRemove(false);
        ++it2;
    }

    LogPrint("masternode", "CCommunityVoteManager::NewBlock - vecCommunityProposals cleanup - size: %d\n", vecCommunityProposals.size());
    std::vector<CCommunityProposalBroadcast>::iterator it4 = vecCommunityProposals.begin();
    while (it4 != vecCommunityProposals.end()) {
        std::string strError = "";
        int nConf = 0;
        if (!IsCommunityCollateralValid((*it4).nFeeTXHash, (*it4).GetHash(), strError, (*it4).nTime, nConf)) {
            ++it4;
            continue;
        }

        if (!(*it4).IsValid(strError)) {
            LogPrint("masternode", "mcprop - invalid community vote proposal - %s\n", strError);
            it4 = vecCommunityProposals.erase(it4);
            continue;
        }

        CCommunityProposal communityProposal((*it4));
        if (AddProposal(communityProposal)) {
            (*it4).Relay();
        }

        LogPrint("masternode", "mcprop - new community vote - %s\n", (*it4).GetHash().ToString());
        it4 = vecCommunityProposals.erase(it4);
    }

    LogPrint("masternode", "CCommunityVoteManager::NewBlock - PASSED\n");
}

void CCommunityVoteManager::ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv)
{
    // lite mode is not supported
    if (fLiteMode) return;
    if (!masternodeSync.IsBlockchainSynced()) return;

    LOCK(cs_communityvote);

    if (strCommand == "mncvs") { // Masternode community vote sync
        uint256 nProp;
        vRecv >> nProp;

        if (Params().NetworkID() == CBaseChainParams::MAIN) {
            if (nProp == 0) {
                if (pfrom->HasFulfilledRequest("mncvs")) {
                    LogPrint("masternode", "mncvs - peer already asked me for the list\n");
                    Misbehaving(pfrom->GetId(), 20);
                    return;
                }
                pfrom->FulfilledRequest("mncvs");
            }
        }

        Sync(pfrom, nProp);
        LogPrint("mncommunityvote", "mncvs - Sent Masternode community votes to peer %i\n", pfrom->GetId());
    }

    if (strCommand == "mcprop") { // Masternode Community Proposal
        CCommunityProposalBroadcast communityProposalBroadcast;
        vRecv >> communityProposalBroadcast;

        if (mapSeenMasternodeCommunityProposals.count(communityProposalBroadcast.GetHash())) {
            masternodeSync.AddedCommunityItem(communityProposalBroadcast.GetHash());
            return;
        }

        std::string strError = "";
        int nConf = 0;
        if (!IsCommunityCollateralValid(communityProposalBroadcast.nFeeTXHash, communityProposalBroadcast.GetHash(), strError, communityProposalBroadcast.nTime, nConf)) {
            LogPrint("masternode", "Community Proposal FeeTX is not valid - %s - %s\n", communityProposalBroadcast.nFeeTXHash.ToString(), strError);
            if (nConf >= 1) vecCommunityProposals.push_back(communityProposalBroadcast);
            return;
        }

        mapSeenMasternodeCommunityProposals.insert(make_pair(communityProposalBroadcast.GetHash(), communityProposalBroadcast));

        if (!communityProposalBroadcast.IsValid(strError)) {
            LogPrint("masternode", "mcprop - invalid community proposal - %s\n", strError);
            return;
        }

        CCommunityProposal communityProposal(communityProposalBroadcast);
        if (AddProposal(communityProposal)) {
            communityProposalBroadcast.Relay();
        }
        masternodeSync.AddedCommunityItem(communityProposalBroadcast.GetHash());

        LogPrint("masternode", "mcprop - new community - %s\n", communityProposalBroadcast.GetHash().ToString());

        // We might have active votes for this proposal that are valid now
        CheckOrphanVotes();
    }

    if (strCommand == "mcvote") { // Masternode Community Vote
        CCommunityVote vote;
        vRecv >> vote;
        vote.fValid = true;

        if (mapSeenMasternodeCommunityVotes.count(vote.GetHash())) {
            masternodeSync.AddedCommunityItem(vote.GetHash());
            return;
        }

        CMasternode* pmn = mnodeman.Find(vote.vin);
        if (pmn == NULL) {
            LogPrint("masternode", "mcvote - unknown masternode - vin: %s\n", vote.vin.prevout.hash.ToString());
            mnodeman.AskForMN(pfrom, vote.vin);
            return;
        }

        mapSeenMasternodeCommunityVotes.insert(make_pair(vote.GetHash(), vote));
        if (!vote.SignatureValid(true)) {
            LogPrint("masternode", "mcvote - signature invalid\n");
            if (masternodeSync.IsSynced())
                Misbehaving(pfrom->GetId(), 20);
            // it could just be a non-synced masternode
            mnodeman.AskForMN(pfrom, vote.vin);
            return;
        }

        std::string strError = "";
        if (UpdateProposal(vote, pfrom, strError)) {
            vote.Relay();
            masternodeSync.AddedCommunityItem(vote.GetHash());
        }

        LogPrint("masternode", "mcvote - new vote for community vote %s - %s\n", vote.nProposalHash.ToString(),  vote.GetHash().ToString());
    }
}

bool CCommunityVoteManager::PropExists(uint256 nHash)
{
    if (mapProposals.count(nHash)) return true;
    return false;
}

// mark that a full sync is needed
void CCommunityVoteManager::ResetSync()
{
    LOCK(cs);

    std::map<uint256, CCommunityProposalBroadcast>::iterator it1 = mapSeenMasternodeCommunityProposals.begin();
    while (it1 != mapSeenMasternodeCommunityProposals.end()) {
        CCommunityProposal* pcommunityProposal = FindProposal((*it1).first);
        if (pcommunityProposal && pcommunityProposal->fValid) {
            // mark votes
            std::map<uint256, CCommunityVote>::iterator it2 = pcommunityProposal->mapVotes.begin();
            while (it2 != pcommunityProposal->mapVotes.end()) {
                (*it2).second.fSynced = false;
                ++it2;
            }
        }
        ++it1;
    }
}

void CCommunityVoteManager::MarkSynced()
{
    LOCK(cs);

    /*
        Mark that we've sent all valid items
    */

    std::map<uint256, CCommunityProposalBroadcast>::iterator it1 = mapSeenMasternodeCommunityProposals.begin();
    while (it1 != mapSeenMasternodeCommunityProposals.end()) {
        CCommunityProposal* pcommunityProposal = FindProposal((*it1).first);
        if (pcommunityProposal && pcommunityProposal->fValid) {
            //mark votes
            std::map<uint256, CCommunityVote>::iterator it2 = pcommunityProposal->mapVotes.begin();
            while (it2 != pcommunityProposal->mapVotes.end()) {
                if ((*it2).second.fValid)
                    (*it2).second.fSynced = true;
                ++it2;
            }
        }
        ++it1;
    }
}

void CCommunityVoteManager::Sync(CNode* pfrom, uint256 nProp, bool fPartial)
{
    LOCK(cs);

    /*
        Sync with a client on the network

        --

        This code checks each of the hash maps for all known community proposals, then checks them against the
        community vote object to see if they're OK. If all checks pass, we'll send it to the peer.

    */

    int nInvCount = 0;

    std::map<uint256, CCommunityProposalBroadcast>::iterator it1 = mapSeenMasternodeCommunityProposals.begin();
    while (it1 != mapSeenMasternodeCommunityProposals.end()) {
        CCommunityProposal* pcommunityProposal = FindProposal((*it1).first);
        if (pcommunityProposal && pcommunityProposal->fValid && (nProp == 0 || (*it1).first == nProp)) {
            pfrom->PushInventory(CInv(MSG_COMMUNITY_PROPOSAL, (*it1).second.GetHash()));
            nInvCount++;

            // send votes
            std::map<uint256, CCommunityVote>::iterator it2 = pcommunityProposal->mapVotes.begin();
            while (it2 != pcommunityProposal->mapVotes.end()) {
                if ((*it2).second.fValid) {
                    if ((fPartial && !(*it2).second.fSynced) || !fPartial) {
                        pfrom->PushInventory(CInv(MSG_COMMUNITY_VOTE, (*it2).second.GetHash()));
                        nInvCount++;
                    }
                }
                ++it2;
            }
        }
        ++it1;
    }

    pfrom->PushMessage("ssc", MASTERNODE_SYNC_COMMUNITYVOTE_PROP, nInvCount);
    LogPrint("mncommunityvote", "CCommunityVoteManager::Sync - sent %d items\n", nInvCount);
}

bool CCommunityVoteManager::UpdateProposal(CCommunityVote& vote, CNode* pfrom, std::string& strError)
{
    LOCK(cs);

    if (!mapProposals.count(vote.nProposalHash)) {
        if (pfrom) {
            // only ask for missing items after our syncing process is complete --
            //   otherwise we'll think a full sync succeeded when they return a result
            if (!masternodeSync.IsSynced()) return false;

            LogPrint("masternode", "CCommunityVoteManager::UpdateProposal - Unknown proposal %d, asking for source proposal\n", vote.nProposalHash.ToString());
            mapOrphanMasternodeCommunityVotes[vote.nProposalHash] = vote;

            if (!askedForSourceProposalOrVote.count(vote.nProposalHash)) {
                pfrom->PushMessage("mncvs", vote.nProposalHash);
                askedForSourceProposalOrVote[vote.nProposalHash] = GetTime();
            }
        }

        strError = "Proposal not found!";
        return false;
    }

    return mapProposals[vote.nProposalHash].AddOrUpdateVote(vote, strError);
}

CCommunityProposal::CCommunityProposal()
{
    strProposalName = "unknown";
    strProposalDescription = "unknown";
    nBlockEnd = 0;
    nTime = 0;
    fValid = true;
}

CCommunityProposal::CCommunityProposal(std::string strProposalNameIn, std::string strProposalDescriptionIn, int nBlockEndIn, uint256 nFeeTXHashIn)
{
    strProposalName = strProposalNameIn;
    strProposalDescription = strProposalDescriptionIn;
    nBlockEnd = nBlockEndIn;
    nFeeTXHash = nFeeTXHashIn;
    fValid = true;
}

CCommunityProposal::CCommunityProposal(const CCommunityProposal& other)
{
    strProposalName = other.strProposalName;
    strProposalDescription = other.strProposalDescription;
    nBlockEnd = other.nBlockEnd;
    nTime = other.nTime;
    nFeeTXHash = other.nFeeTXHash;
    mapVotes = other.mapVotes;
    fValid = true;
}

bool CCommunityProposal::IsValid(std::string& strError, bool fCheckCollateral)
{
    if (GetNays() - GetYeas() > mnodeman.CountEnabled(ActiveProtocol()) / 10) {
        strError = "Proposal " + strProposalName + ": Active removal";
        return false;
    }

    if (fCheckCollateral) {
        int nConf = 0;
        if (!IsCommunityCollateralValid(nFeeTXHash, GetHash(), strError, nTime, nConf)) {
            strError = "Proposal " + strProposalName + ": Invalid collateral";
            return false;
        }
    }

    return true;
}

bool CCommunityProposal::AddOrUpdateVote(CCommunityVote& vote, std::string& strError)
{
    std::string strAction = "New vote inserted:";
    LOCK(cs);

    uint256 hash = vote.vin.prevout.GetHash();

    if (mapVotes.count(hash)) {
        if (mapVotes[hash].nTime > vote.nTime) {
            strError = strprintf("new vote older than existing vote - %s\n", vote.GetHash().ToString());
            LogPrint("mncommunityvote", "CCommunityProposal::AddOrUpdateVote - %s\n", strError);
            return false;
        }
        if (vote.nTime - mapVotes[hash].nTime < COMMUNITY_VOTE_UPDATE_MIN) {
            strError = strprintf("time between votes is too soon - %s - %lli sec < %lli sec\n", vote.GetHash().ToString(), vote.nTime - mapVotes[hash].nTime, COMMUNITY_VOTE_UPDATE_MIN);
            LogPrint("mncommunityvote", "CCommunityProposal::AddOrUpdateVote - %s\n", strError);
            return false;
        }
        strAction = "Existing vote updated:";
    }

    if (vote.nTime > GetTime() + (60 * 60)) {
        strError = strprintf("new vote is too far ahead of current time - %s - nTime %lli - Max Time %lli\n", vote.GetHash().ToString(), vote.nTime, GetTime() + (60 * 60));
        LogPrint("mncommunityvote", "CCommunityProposal::AddOrUpdateVote - %s\n", strError);
        return false;
    }

    mapVotes[hash] = vote;
    LogPrint("mncommunityvote", "CCommunityProposal::AddOrUpdateVote - %s %s\n", strAction.c_str(), vote.GetHash().ToString().c_str());

    return true;
}

// If masternode voted for a proposal, but is now invalid -- remove the vote
void CCommunityProposal::CleanAndRemove(bool fSignatureCheck)
{
    std::map<uint256, CCommunityVote>::iterator it = mapVotes.begin();

    while (it != mapVotes.end()) {
        (*it).second.fValid = (*it).second.SignatureValid(fSignatureCheck);
        ++it;
    }
}

double CCommunityProposal::GetRatio()
{
    int yeas = 0;
    int nays = 0;

    std::map<uint256, CCommunityVote>::iterator it = mapVotes.begin();

    while (it != mapVotes.end()) {
        if ((*it).second.nVote == VOTE_YES) yeas++;
        if ((*it).second.nVote == VOTE_NO) nays++;
        ++it;
    }

    if (yeas + nays == 0) return 0.0f;

    return ((double)(yeas) / (double)(yeas + nays));
}

int CCommunityProposal::GetYeas()
{
    int ret = 0;

    std::map<uint256, CCommunityVote>::iterator it = mapVotes.begin();
    while (it != mapVotes.end()) {
        if ((*it).second.nVote == VOTE_YES && (*it).second.fValid) ret++;
        ++it;
    }

    return ret;
}

int CCommunityProposal::GetNays()
{
    int ret = 0;

    std::map<uint256, CCommunityVote>::iterator it = mapVotes.begin();
    while (it != mapVotes.end()) {
        if ((*it).second.nVote == VOTE_NO && (*it).second.fValid) ret++;
        ++it;
    }

    return ret;
}

int CCommunityProposal::GetAbstains()
{
    int ret = 0;

    std::map<uint256, CCommunityVote>::iterator it = mapVotes.begin();
    while (it != mapVotes.end()) {
        if ((*it).second.nVote == VOTE_ABSTAIN && (*it).second.fValid) ret++;
        ++it;
    }

    return ret;
}

CCommunityProposalBroadcast::CCommunityProposalBroadcast(std::string strProposalNameIn, std::string strProposalDescriptionIn, int nBlockEndIn, uint256 nFeeTXHashIn)
{
    strProposalName = strProposalNameIn;
    strProposalDescription = strProposalDescriptionIn;
    nBlockEnd = nBlockEndIn;
    nFeeTXHash = nFeeTXHashIn;
}

void CCommunityProposalBroadcast::Relay()
{
    CInv inv(MSG_COMMUNITY_PROPOSAL, GetHash());
    RelayInv(inv);
}

CCommunityVote::CCommunityVote()
{
    vin = CTxIn();
    nProposalHash = 0;
    nVote = VOTE_ABSTAIN;
    nTime = 0;
    fValid = true;
    fSynced = false;
}

CCommunityVote::CCommunityVote(CTxIn vinIn, uint256 nProposalHashIn, int nVoteIn)
{
    vin = vinIn;
    nProposalHash = nProposalHashIn;
    nVote = nVoteIn;
    nTime = GetAdjustedTime();
    fValid = true;
    fSynced = false;
}

void CCommunityVote::Relay()
{
    CInv inv(MSG_COMMUNITY_VOTE, GetHash());
    RelayInv(inv);
}

bool CCommunityVote::Sign(CKey& keyMasternode, CPubKey& pubKeyMasternode)
{
    // Choose coins to use
    CPubKey pubKeyCollateralAddress;
    CKey keyCollateralAddress;

    std::string errorMessage;
    std::string strMessage = vin.prevout.ToStringShort() + nProposalHash.ToString() + boost::lexical_cast<std::string>(nVote) + boost::lexical_cast<std::string>(nTime);

    if (!masternodeSigner.SignMessage(strMessage, errorMessage, vchSig, keyMasternode)) {
        LogPrint("masternode", "CCommunityVote::Sign - Error upon calling SignMessage");
        return false;
    }

    if (!masternodeSigner.VerifyMessage(pubKeyMasternode, vchSig, strMessage, errorMessage)) {
        LogPrint("masternode", "CCommunityVote::Sign - Error upon calling VerifyMessage");
        return false;
    }

    return true;
}

bool CCommunityVote::SignatureValid(bool fSignatureCheck)
{
    std::string errorMessage;
    std::string strMessage = vin.prevout.ToStringShort() + nProposalHash.ToString() + boost::lexical_cast<std::string>(nVote) + boost::lexical_cast<std::string>(nTime);

    CMasternode* pmn = mnodeman.Find(vin);

    if (pmn == NULL) {
        LogPrint("masternode", "CCommunityVote::SignatureValid() - Unknown Masternode - %s\n", vin.prevout.hash.ToString());
        return false;
    }

    if (!fSignatureCheck) return true;

    if (!masternodeSigner.VerifyMessage(pmn->pubKeyMasternode, vchSig, strMessage, errorMessage)) {
        LogPrint("masternode", "CCommunityVote::SignatureValid() - Verify message failed\n");
        return false;
    }

    return true;
}

std::string CCommunityVoteManager::ToString() const
{
    std::ostringstream info;

    info << "Proposals: " << (int)mapProposals.size() << ", Seen Community Proposals: " << (int)mapSeenMasternodeCommunityProposals.size() << ", Seen Community Votes: " << (int)mapSeenMasternodeCommunityVotes.size();

    return info.str();
}

max_stars_repo_name: Insifa/insifa

max_issues_repo_name: Insifa/insifa

max_forks_repo_name: Insifa/insifa


text:
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <boost/filesystem.hpp>

using std::vector;
using std::string;
using std::to_string;
using std::cin;
using std::cout;
using std::endl;
using std::ofstream;
using std::ifstream;

void write_org_header(const string &title, unsigned no, ofstream &ofs)
{
  string description = "Introduction to Algorithms Chapter-" + to_string(no);
  string header = "#+BEGIN_COMMENT\n.. title: "
    + title
    + "\n.. slug: "
    + title
    + "\n.. date: 2018-04-25 13:30:12 UTC+08:00\n.. tags: C++,CLRS\n.. category: CLRS\n.. link:\n.. description: "
    + description
    + "\n.. type: text\n#+END_COMMENT\n\n#+OPTIONS: ^:{}";
  ofs << header << "\n\n";
}

bool is_utilities_file(const string &file_name)
{
  if(file_name.find("utilities") != string::npos)
    return true;
  else
    return false;
}

void write_utilities_file(const string &file_path, ofstream &ofs)
{
  static const string git_repo =
    "https://github.com/zero4drift/CLRS_Cpp_Implementations/tree/master/";
  auto index = file_path.find("include");
  ofs << "* utilities\n\n  " << git_repo << file_path.substr(index) << "\n\n";
}

bool is_include_using_ifndef_line(const string &line)
{
  return (line.find("#include <") != string::npos)
    || (line.find("using std") != string::npos)
    || (line.find("#ifndef") != string::npos)
    || (line.find("#define") != string::npos)
    || (line.find("#endif") != string::npos);
}

void handle_cpp_file(ifstream &ifs, ofstream &ofs)
{
  string line;
  ofs << "#+begin_src c++\n";
  while(ifs)
    {
      getline(ifs, line);
      if(!line.size() || is_include_using_ifndef_line(line)) continue;
      ofs << "  " << line << "\n";
    }
  ofs << "#+end_src\n\n";
}

vector<string> handle_cpp_files(const string &project_root, unsigned chapter_no, ofstream &ofs)
{
  vector<string> vs;
  ifstream ifs;
  string file_name, file_path;
  string chapter_path = project_root + "/chapter-" + to_string(chapter_no);
  for(boost::filesystem::recursive_directory_iterator end, dir(chapter_path);
      dir != end; ++dir)
    {
      file_name = dir->path().filename().native();
      file_path = dir->path().native();
      if(boost::filesystem::is_directory(dir->path()))
	{
	  ofs << "* " + file_name + "\n\n";
	  vs.push_back(file_name);
	}
      else if(is_utilities_file(file_name))
	write_utilities_file(file_path, ofs);
      else
	{
	  ifs.open(file_path);
	  handle_cpp_file(ifs, ofs);
	  ifs.close();
	}
    }
  return vs;
}

int main()
{
  string title;
  string project_root;
  cout << "Specify project root path: ";
  cin >> project_root;
  unsigned first, last;
  cout << "Specify first chpater and last chapter number: " << endl;
  cin >> first >> last;
  string chapter_path;
  string output_path;
  ofstream ofs;
  while(first <= last)
    {
      string title = "CLRS-Cpp-Implementations-Chapter-" + to_string(first);
      output_path = project_root + title + ".org";
      ofs.open(output_path, ofstream::app);
      write_org_header(title, first, ofs);
      auto vs = handle_cpp_files(project_root, first, ofs);
      for(const auto &s : vs)
	ofs << s << " ";
      ++first;
      ofs.close();
    }
}


text:
#include <boost/type_index.hpp>
#include <cstdlib>
#include <iostream>

using namespace std;

//显示参数类型，这里不研究boost库
template <typename T>
void myFunction01(T& tem) {
    using boost::typeindex::type_id_with_cvr;
    cout << "T type=" << type_id_with_cvr<T>().pretty_name() << endl;                //显示T类型
    cout << "tem type=" << type_id_with_cvr<decltype(tem)>().pretty_name() << endl;  //显示tem类型
}

int main(void) {
    // c++98支持的初始化方式
    int number01 = 10;
    int number02(23);
    // c++11支持的初始化方式
    int number03 = {23};
    int number04{234};
    //替换为auto可以吗？？

    auto number05 = 23;    // int
    auto number06(23);     // int
    auto number07 = {23};  // class std::initializer_list<int>  auto遇见={}推导规则不一样
    auto number08{23};     // int
    using boost::typeindex::type_id_with_cvr;
    cout << "number07 type=" << type_id_with_cvr<decltype(number07)>().pretty_name() << endl;  //显示T类型
    cout << "number08 type=" << type_id_with_cvr<decltype(number08)>().pretty_name() << endl;  //显示T类型
    /*
     *  std::initializer_list<int> C++11引入的新类型（类模板）
     */

    auto number09 = {23, 345};  //所有的类型要一致，需要进行二次推导，先推导auto=int,再推导出类模板类型

    system("pause");
    return 0;
}
/*
 * (1)auto类型std::initializer_list的特殊推断
 *	class std::initializer_list<T> c++中引入的类模板，表示某种特定的值的数组
 * (2)auto还可以放在函数返回值类型，以后讲。
 */

max_stars_repo_name: xuesongzh/cpp-basis

max_issues_repo_name: xuesongzh/cpp-basis

max_forks_repo_name: xuesongzh/cpp-basis


text:
#define BOOST_TEST_MODULE InterpreterLockGuard
#define BOOST_TEST_DYN_LINK

#include <Python.h>
#include <boost/test/unit_test.hpp>
#include "../InterpreterLockGuard.hpp"

BOOST_AUTO_TEST_SUITE(test_InterpreterLockGuard)

BOOST_AUTO_TEST_CASE(test1)
{
    {
        // test building a guard without Python threads initialized
        // this isn't a common thing to do, but we do support it "just in case"
        pccl::python::InterpreterLockGuard guard1;
    }

    {
        Py_InitializeEx(false);
        pccl::python::InterpreterLockGuard guard2;
        pccl::python::InterpreterLockGuard guard3; // should do nothing
        pccl::python::InterpreterLockAcquirer releaser1; // re-acquires the lock
        pccl::python::InterpreterLockAcquirer releaser2; // should do nothing
    }
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: jzwinck/pccl

max_issues_repo_name: jzwinck/pccl

max_forks_repo_name: jzwinck/pccl


text:
#ifndef ___INANITY_NET_ASIO_HPP___
#define ___INANITY_NET_ASIO_HPP___

#include "net.hpp"

#ifdef ___INANITY_PLATFORM_WINDOWS
#define WIN32_LEAN_AND_MEAN
#include "../platform/windows.hpp"
#endif

#define BOOST_ASIO_SEPARATE_COMPILATION
#include <boost/asio.hpp>
#include <boost/system/system_error.hpp>

#endif

max_stars_repo_name: quyse/inanity

max_issues_repo_name: quyse/inanity

max_forks_repo_name: quyse/inanity


text:
/* Copyright © 2017 Apple Inc. All rights reserved.
 *
 * Use of this source code is governed by a BSD-3-clause license that can
 * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
 */
#ifndef TURI_ML_DATA_ROW_REFERENCE_H_
#define TURI_ML_DATA_ROW_REFERENCE_H_

#include <core/logging/assertions.hpp>
#include <toolkits/ml_data_2/data_storage/ml_data_row_translation.hpp>
#include <toolkits/ml_data_2/data_storage/ml_data_block_manager.hpp>
#include <toolkits/ml_data_2/ml_data.hpp>
#include <toolkits/ml_data_2/side_features.hpp>
#include <core/util/code_optimization.hpp>

#include <Eigen/SparseCore>
#include <Eigen/Core>

#include <array>

namespace turi { namespace v2 {

typedef Eigen::Matrix<double, Eigen::Dynamic,1>  DenseVector;
typedef Eigen::SparseVector<double> SparseVector;

/**
 *  A class containing a reference to the row of an ml_data instance.
 *  The row can then be used to fill any sort of data row that an
 *  iterator can be used to fill.
 *
 *  In other words,
 *
 *     it.fill_observation(x);
 *
 *  Can be replaced with
 *
 *     auto row_ref = it.get_reference();
 *
 *     // do stuff ...
 *     row_ref.fill(x);
 *
 *  The data block pointed to by this reference is kept alive as long
 *  as this reference class exists.
 *
 *
 *  Another example of how it is used is below:
 *
 *     sframe X = make_integer_testing_sframe( {"C1", "C2"}, { {0, 0}, {1, 1}, {2, 2}, {3, 3}, {4, 4} } );
 *
 *     v2::ml_data data;
 *
 *     data.fill(X);
 *
 *     // Get row references
 *
 *     std::vector<v2::ml_data_row_reference> rows(data.num_rows());
 *
 *     for(auto it = data.get_iterator(); !it.done(); ++it) {
 *       rows[it.row_index()] = it.get_reference();
 *     }
 *
 *     // Now go through and make sure that each of these hold the
 *     // correct answers.
 *
 *     std::vector<v2::ml_data_entry> x;
 *
 *     for(size_t i = 0; i < rows.size(); ++i) {
 *
 *       // The metadata for the row is the same as that in the data.
 *       ASSERT_TRUE(rows[i].metadata().get() == data.metadata().get());
 *
 *       rows[i].fill(x);
 *
 *       ASSERT_EQ(x.size(), 2);
 *
 *       ASSERT_EQ(x[0].column_index, 0);
 *       ASSERT_EQ(x[0].index, 0);
 *       ASSERT_EQ(x[0].value, i);
 *
 *       ASSERT_EQ(x[1].column_index, 1);
 *       ASSERT_EQ(x[1].index, 0);
 *       ASSERT_EQ(x[1].value, i);
 *     }
 *   }
 *
 */
class ml_data_row_reference {
 public:

  /**
   * Fill an observation vector, represented as an ml_data_entry
   * struct.  (column_index, index, value) pairs, from this row
   * reference.  For each column:
   *
   * Categotical: Returns (col_id, v, 1)
   * Numeric    : Returns (col_id, 0, v)
   * Vector     : Returns (col_id, i, v) for each (i,v) in vector.
   *
   * Example use is given by the following code:
   *
   *   std::vector<ml_data_entry> x;
   *
   *   row_ref.fill(x);
   *   double y = row_ref.target_value();
   *   ...
   */
  template <typename Entry>
  GL_HOT_INLINE
  inline void fill(std::vector<Entry>& x) const {

    x.clear();

    if(!data_block->metadata->has_translated_columns())
      return;

    ml_data_internal::copy_raw_into_ml_data_entry_row(
        x, data_block->rm, current_data_iter(),
        side_features);
  }

  /**
   * Fill an observation vector with the untranslated columns, if any
   * have been specified at setup time.  These columns are simply
   * mapped back to their sarray counterparts.
   */
  inline void fill_untranslated_values(std::vector<flexible_type>& x) const GL_HOT_INLINE_FLATTEN {

    if(!data_block->metadata->has_untranslated_columns()) {
      x.clear();
      return;
    }

    x.resize(data_block->untranslated_columns.size());

    for(size_t i = 0; i < data_block->untranslated_columns.size(); ++i) {
      x[i] = data_block->untranslated_columns[i][current_in_block_index];
    }

    DASSERT_TRUE(x.size() >= 1);
  }

  /**
   * Fill an observation vector, represented as an Eigen Sparse Vector, from
   * the current location in the iteration.
   *
   * \note A reference category is used in this version of the function.
   * \note For performance reasons, this function does not check for new
   * categories during predict time.  That must be checked externally.
   *
   * This function returns a flattened version of the vector provided by the
   * std::pair version of fill.
   *
   * Example
   * ---------------------------------------------
   *
   * \warning This only works when the SFrame is "mapped" to integer keys.
   *
   * For a dataset with a 3 column SFrame
   *
   * Row 1: 1.0  0(categorical) <9.1, 2.4>
   * Row 2: 2.0  1(categorical) <1.0, 4.5>
   *
   * with index = {1,2,2}
   *
   * the SparseVector format would return
   *
   * Row 1: < (0, 1.0), (1, 1) ,(3, 9.1) ,(4, 2.4)>
   * Row 2: < (0, 2.0), (2, 1) ,(3, 1.0) ,(4, 4.5)>
   *
   * \note The '0'th category is used as reference.
   *
   * \param[in,out] x   Data containing everything!
   *
   */
  inline void fill(SparseVector& x) const GL_HOT_INLINE_FLATTEN {

    x.setZero();

    if(!data_block->metadata->has_translated_columns())
      return;

    ml_data_internal::copy_raw_into_eigen_array(
        x,
        data_block->rm, current_data_iter(),
        side_features,
        use_reference_encoding);
  }

  /**
   * Fill an observation vector, represented as an Eigen Dense Vector, from
   * the current location in the iteration.
   *
   * \note The 0th category is used as a reference category.
   *
   * \note For performance reasons, this function does not check for new
   * categories during predict time.  That must be checked externally.
   *
   * This function returns a flattened version of the vector provided by the
   * std::pair version of fill.
   *
   * Example
   * ---------------------------------------------
   *
   * \warning This only works when the SFrame is "mapped" to intger keys.
   *
   * For a dataset with a 3 column SFrame
   *
   * Row 1: 1.0  0(categorical) <9.1, 2.4>
   * Row 2: 2.0  1(categorical) <1.0, 4.5>
   *
   * with index = {1,2,2}
   *
   * the DenseVector format would return
   *
   * Row 1: <1.0, 0, 1, 9.1, 2.4>
   * Row 2: <2.0, 1, 0, 1.0, 4.5>
   *
   * \param[in,out] x   Data containing everything!
   *
   */
  inline void fill(DenseVector& x) const  GL_HOT_INLINE_FLATTEN {

    x.setZero();

    if(!data_block->metadata->has_translated_columns())
      return;

    ml_data_internal::copy_raw_into_eigen_array(
        x,
        data_block->rm, current_data_iter(),
        side_features,
        use_reference_encoding);
  }

  /**
   * Fill a row of an Eigen Dense Vector, from
   * the current location in the iteration.
   *
   * \note The 0th category is used as a reference category.
   *
   *
   * Example:
   *
   *   Eigen::MatrixXd X;
   *
   *   ...
   *
   *   it.fill_eigen_row(X.row(row_idx));
   *
   * ---------------------------------------------
   *
   * \param[in,out] x   An eigen row expression.
   *
   */
  template <typename DenseRowXpr>
  GL_HOT_INLINE_FLATTEN
  inline void fill_eigen_row(DenseRowXpr&& x) const {

    x.setZero();

    ml_data_internal::copy_raw_into_eigen_array(
        x,
        data_block->rm, current_data_iter(),
        side_features,
        use_reference_encoding);
  }

  /** Returns the current target value, if present, or 1 if not
   *  present.  If the target column is supposed to be a categorical
   *  value, then use categorical_target_index().
   */
  double target_value() const GL_HOT_INLINE_FLATTEN {
    return get_target_value(data_block->rm, current_data_iter());
  }

  /** Returns the current categorical target index, if present, or 0
   *  if not present.
   */
  size_t target_index() const GL_HOT_INLINE_FLATTEN {
    return get_target_index(data_block->rm, current_data_iter());
  }

  /** Returns a pointer to the metadata class that describes the data
   *  that this row reference refers to.
   */
  const std::shared_ptr<ml_metadata>& metadata() const {
    return data_block->metadata;
  }

 private:
  friend class ml_data_iterator_base;

  std::shared_ptr<ml_data_internal::ml_data_block> data_block;
  std::shared_ptr<ml_data_side_features> side_features;
  size_t current_in_block_index = size_t(-1);
  bool use_reference_encoding = false;

  /** Return a pointer to the current location in the data.
   */
  inline ml_data_internal::entry_value_iterator current_data_iter() const GL_HOT_INLINE_FLATTEN {

    DASSERT_LT(current_in_block_index, data_block->translated_rows.entry_data.size());

    return &(data_block->translated_rows.entry_data[current_in_block_index]);
  }

};

}}

#endif /* TURI_ML_DATA_ROW_REFERENCE_H_ */


text:
/*
 Copyright (c) 2013, The Cinder Project (http://libcinder.org)
 All rights reserved.

 Redistribution and use in source and binary forms, with or without modification, are permitted provided that
 the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and
	the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
	the following disclaimer in the documentation and/or other materials provided with the distribution.

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

#include "cinder/ConvexHull.h"

#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/polygon.hpp>

namespace cinder {

typedef boost::geometry::model::polygon<boost::geometry::model::d2::point_xy<double> > polygon;

namespace {

PolyLine2f toPolyLine( const polygon &p )
{
	PolyLine2f result;

	for( auto pt = p.outer().begin(); pt != p.outer().end(); ++pt )
		result.push_back( vec2( boost::geometry::get<0>(*pt), boost::geometry::get<1>(*pt) ) );

	return result;
}

boost::geometry::model::d2::point_xy<double> makePoint( const vec2 &p )
{
	return boost::geometry::make<boost::geometry::model::d2::point_xy<double> >( p.x, p.y );
}

void includePathExtremeties( const Path2d &p, polygon *output )
{
	size_t firstPoint = 0;
	for( size_t s = 0; s < p.getSegments().size(); ++s ) {
		switch( p.getSegments()[s] ) {
			case Path2d::CUBICTO: {
				float monotoneT[4];
				int monotoneCnt = Path2d::calcCubicBezierMonotoneRegions( &(p.getPoints()[firstPoint]), monotoneT );
				for( int monotoneIdx = 0; monotoneIdx < monotoneCnt; ++monotoneIdx )
					output->outer().push_back( makePoint( Path2d::calcCubicBezierPos( &(p.getPoints()[firstPoint]), monotoneT[monotoneIdx] ) ) );

				output->outer().push_back( makePoint( p.getPoints()[firstPoint+0] ) );
				output->outer().push_back( makePoint( p.getPoints()[firstPoint+1] ) );
				output->outer().push_back( makePoint( p.getPoints()[firstPoint+2] ) );
			}
			break;
			case Path2d::QUADTO: {
				float monotoneT[2];
				int monotoneCnt = Path2d::calcCubicBezierMonotoneRegions( &(p.getPoints()[firstPoint]), monotoneT );
				for( int monotoneIdx = 0; monotoneIdx < monotoneCnt; ++monotoneIdx )
					output->outer().push_back( makePoint( Path2d::calcQuadraticBezierPos( &(p.getPoints()[firstPoint]), monotoneT[monotoneIdx] ) ) );
				output->outer().push_back( makePoint( p.getPoints()[firstPoint+0] ) );
				output->outer().push_back( makePoint( p.getPoints()[firstPoint+1] ) );
			}
			break;
			case Path2d::LINETO:
				output->outer().push_back( makePoint( p.getPoints()[firstPoint+0] ) );
			break;
			case Path2d::CLOSE:
				output->outer().push_back( makePoint( p.getPoints()[firstPoint+0] ) );
			break;
			default:
				throw Path2dExc();
		}

		firstPoint += Path2d::sSegmentTypePointCounts[p.getSegments()[s]];
	}
}

} // anonymous namespace

PolyLine2f calcConvexHull( const std::vector<vec2> &points )
{
	if( points.empty() )
		return PolyLine2f();
	else
		return calcConvexHull( points.data(), points.size() );
}

PolyLine2f calcConvexHull( const vec2 *points, size_t numPoints )
{
	polygon poly;
	for( size_t p = 0; p < numPoints; ++p )
		poly.outer().push_back( boost::geometry::make<boost::geometry::model::d2::point_xy<double> >( points[p].x, points[p].y ) );

	polygon result;
	boost::geometry::convex_hull( poly, result );

	return toPolyLine( result );
}

PolyLine2f calcConvexHull( const Shape2d &shape )
{
	polygon poly;
	for( auto contourIt = shape.getContours().begin(); contourIt != shape.getContours().end(); ++contourIt )
		includePathExtremeties( *contourIt, &poly );

	polygon result;
	boost::geometry::convex_hull( poly, result );

	return toPolyLine( result );
}

PolyLine2f calcConvexHull( const Path2d &path )
{
	polygon poly;
	includePathExtremeties( path, &poly );

	polygon result;
	boost::geometry::convex_hull( poly, result );

	return toPolyLine( result );
}

PolyLine2f calcConvexHull( const PolyLine2f &polyLine )
{
	polygon poly;
	for( auto ptIt = polyLine.begin(); ptIt != polyLine.end(); ++ptIt )
		poly.outer().push_back( boost::geometry::make<boost::geometry::model::d2::point_xy<double> >( ptIt->x, ptIt->y ) );

	polygon result;
	boost::geometry::convex_hull( poly, result );

	return toPolyLine( result );
}

} // namespace cinder

max_stars_repo_name: rsh/Cinder-Emscripten

max_issues_repo_name: rsh/Cinder-Emscripten

max_forks_repo_name: rsh/Cinder-Emscripten


text:
/*
// Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a
// component of the Texas A&M University System.

// All rights reserved.

// The information and source code contained herein is the exclusive
// property of TEES and may not be disclosed, examined or reproduced
// in whole or in part without explicit written authorization from TEES.
*/

#define STAPL_RUNTIME_TEST_MODULE aligned_storage
#include "utility.h"
#include <stapl/runtime/type_traits/aligned_storage.hpp>
#include <boost/mpl/range_c.hpp>
#include <boost/mpl/for_each.hpp>

// Returns the size of an object aligned to the word size.
#define THIS_ALIGNMENT \
  STAPL_RUNTIME_DEFAULT_ALIGNMENT
#define ALIGNED_SIZEOF(type) \
  (sizeof(type)+THIS_ALIGNMENT-((sizeof(type)-1)%THIS_ALIGNMENT + 1))
#define ALIGNED_SIZE(num) \
  ((num)+THIS_ALIGNMENT-(((num)-1)%THIS_ALIGNMENT + 1))

template<std::size_t Size>
struct array
{
  char data[Size];
};

template<>
struct array<0>
{ };

using stapl::runtime::aligned_storage_t;
using stapl::runtime::aligned_size;

struct test_wrapper
{
  template<typename T>
  void operator()(T&) const
  {
    typedef array<T::value>                       array_type;
    typedef aligned_storage_t<sizeof(array_type)> aligned_type;

    const std::size_t size = T::value;
    BOOST_CHECK_EQUAL( size, sizeof(array_type) );

    // test aligned_storage<T>
    const std::size_t aligned_type_size = sizeof(aligned_type);
    BOOST_CHECK_EQUAL( (aligned_type_size%THIS_ALIGNMENT), std::size_t(0) );
    BOOST_CHECK( aligned_type_size>=sizeof(array_type) );
    BOOST_CHECK_EQUAL( aligned_type_size, (ALIGNED_SIZE(sizeof(array_type))) );
    BOOST_CHECK_EQUAL( aligned_type_size, (ALIGNED_SIZEOF(array_type)) );
    if (size%THIS_ALIGNMENT==std::size_t(0)) {
      BOOST_CHECK_EQUAL( aligned_type_size, size );
    }

    // test aligned_size()
    const std::size_t fsz = aligned_size(sizeof(array_type));
    BOOST_CHECK_EQUAL( (fsz%THIS_ALIGNMENT), std::size_t(0) );
    BOOST_CHECK( fsz>=sizeof(array_type) );
    BOOST_CHECK_EQUAL( fsz, (ALIGNED_SIZE(sizeof(array_type))) );
    BOOST_CHECK_EQUAL( fsz, (ALIGNED_SIZEOF(array_type)) );
    if (size%THIS_ALIGNMENT==0) {
      BOOST_CHECK_EQUAL( fsz, size );
    }

    // compare aligned_storage_t with aligned_size()
    BOOST_CHECK_EQUAL(sizeof(aligned_type), aligned_size(sizeof(array_type)));
  }
};

BOOST_AUTO_TEST_CASE( test_aligned_storage )
{
  using namespace boost::mpl;

  typedef range_c<std::size_t, 1, 129> range;
  for_each<range>( test_wrapper() );
}

BOOST_AUTO_TEST_CASE( test_aligned_storage_size_t )
{
  typedef std::size_t T;

  BOOST_CHECK( sizeof(T)<=sizeof(aligned_storage_t<sizeof(T)>) );
}

BOOST_AUTO_TEST_CASE( test_aligned_storage_ptr )
{
  typedef void* T;

  BOOST_CHECK( sizeof(T)<=sizeof(aligned_storage_t<sizeof(T)>) );
}

ext: cc