text:
// This file is part of Miscellaneous Container Templates.
//
//             https://launchpad.net/libmct/
//
// Copyright (c) 2012, 2013 Paul Pogonyshev.
//
// 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.

#ifndef MCT_TESTS_SERIALIZATION_COMMON_HPP
#define MCT_TESTS_SERIALIZATION_COMMON_HPP

#include <sstream>

#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>

// This header is supposed to be included directly in '.cpp' files.
namespace
{

  template <typename type>
  void
  test_serialization (const type& object)
  {
    // Hardly worth it to make yet another template for this.

    {
      std::stringstream  buffer;

      {
        boost::archive::xml_oarchive  out (buffer);
        out << boost::serialization::make_nvp ("object", object);
      }

      {
        boost::archive::xml_iarchive  in (buffer);
        type                          object2;

        in >> boost::serialization::make_nvp ("object", object2);
        BOOST_CHECK_EQUAL (object, object2);
      }
    }

    {
      std::stringstream  buffer;

      {
        boost::archive::text_oarchive  out (buffer);
        out << boost::serialization::make_nvp ("object", object);
      }

      {
        boost::archive::text_iarchive  in (buffer);
        type                           object2;

        in >> boost::serialization::make_nvp ("object", object2);
        BOOST_CHECK_EQUAL (object, object2);
      }
    }

    {
      std::stringstream  buffer;

      {
        boost::archive::binary_oarchive  out (buffer);
        out << boost::serialization::make_nvp ("object", object);
      }

      {
        boost::archive::binary_iarchive  in (buffer);
        type                             object2;

        in >> boost::serialization::make_nvp ("object", object2);
        BOOST_CHECK_EQUAL (object, object2);
      }
    }
  }

}

#endif  // Multi-inclusion guard.

// Local variables:
// mode: c++
// c-basic-offset: 2
// indent-tabs-mode: nil
// fill-column: 90
// End:

ext: hpp

max_stars_repo_name: seiriosPlus/libmct

max_issues_repo_name: seiriosPlus/libmct

max_forks_repo_name: seiriosPlus/libmct


text:
/*
  Copyright (c) 2014-2016 DataStax

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

#include <algorithm>

#include <boost/test/unit_test.hpp>
#include <boost/test/debug.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/cstdint.hpp>
#include <boost/format.hpp>
#include <boost/thread.hpp>
#include <boost/chrono.hpp>

#include "cassandra.h"
#include "test_utils.hpp"

const CassPrepared* prepare_statement(CassSession* session, std::string query) {
  test_utils::CassFuturePtr prepared_future(cass_session_prepare_n(session,
                                                                   query.data(), query.size()));
  test_utils::wait_and_check_error(prepared_future.get());
  return cass_future_get_prepared(prepared_future.get());
}

void check_result(CassSession* session) {
  test_utils::CassResultPtr result;
  test_utils::execute_query(session, "SELECT * FROM test", &result);
  BOOST_REQUIRE(cass_result_column_count(result.get()) == 5);
  BOOST_REQUIRE(cass_result_row_count(result.get()) > 0);

  const CassRow* row = cass_result_first_row(result.get());

  cass_int32_t key;
  BOOST_REQUIRE(cass_value_get_int32(cass_row_get_column(row, 0), &key) == CASS_OK);

  cass_int32_t v1;
  BOOST_REQUIRE(cass_value_get_int32(cass_row_get_column(row, 1), &v1) == CASS_OK);

  CassString v2;
  BOOST_REQUIRE(cass_value_get_string(cass_row_get_column(row, 2), &v2.data, &v2.length) == CASS_OK);

  test_utils::CassIteratorPtr v3(cass_iterator_from_collection(cass_row_get_column(row, 3)));

  cass_int32_t i = 0;
  while (cass_iterator_next(v3.get())) {
    const CassValue* value =  cass_iterator_get_value(v3.get());
    BOOST_REQUIRE(cass_value_type(value) == CASS_VALUE_TYPE_INT);

    cass_int32_t output;
    cass_value_get_int32(value, &output);
    BOOST_REQUIRE(i == output);
    i++;
  }

  test_utils::CassIteratorPtr v4(cass_iterator_from_collection(cass_row_get_column(row, 4)));

  cass_int32_t j = 0;
  while (cass_iterator_next(v4.get())) {
    const CassValue* value =  cass_iterator_get_value(v4.get());
    BOOST_REQUIRE(cass_value_type(value) == CASS_VALUE_TYPE_VARCHAR);

    CassString output;
    cass_value_get_string(value, &output.data, &output.length);
    BOOST_REQUIRE(output.length == 1 && output.data[0] == 'd' + j);
    j++;
  }
}

struct Version1Tests : public test_utils::SingleSessionTest {
  Version1Tests() : SingleSessionTest(1, 0, 1) { // v1
    test_utils::execute_query(session, str(boost::format(test_utils::CREATE_KEYSPACE_SIMPLE_FORMAT)
                                           % test_utils::SIMPLE_KEYSPACE % "1"));
    test_utils::execute_query(session, str(boost::format("USE %s") % test_utils::SIMPLE_KEYSPACE));
  }

  ~Version1Tests() {
    // Drop the keyspace (ignore any and all errors)
    test_utils::execute_query_with_error(session,
      str(boost::format(test_utils::DROP_KEYSPACE_FORMAT)
      % test_utils::SIMPLE_KEYSPACE));
  }
};

BOOST_AUTO_TEST_SUITE(version1)

BOOST_AUTO_TEST_CASE(query)
{
  // Handle deprecated and removed protocol versions [CASSANDRA-10146]
  // https://issues.apache.org/jira/browse/CASSANDRA-10146
  CCM::CassVersion version = test_utils::get_version();
  if (version < "3.0.0") {
    Version1Tests tester;
    test_utils::execute_query(tester.session, "CREATE TABLE test (key int PRIMARY KEY, v1 int, v2 text, v3 list<int>, v4 set<text>);");
    test_utils::execute_query(tester.session, "INSERT INTO test (key, v1, v2, v3, v4) VALUES (0, 99, 'abc', [ 0, 1, 2 ], { 'd', 'e', 'f' });");
    check_result(tester.session);
   } else {
    std::cout << "Invalid Test for Cassandra v" << version.to_string() << ": Protocol v1 and v2 were dropped in v3.0.0" << std::endl;
    BOOST_REQUIRE(true);
  }
}

BOOST_AUTO_TEST_CASE(prepared)
{
  // Handle deprecated and removed protocol versions [CASSANDRA-10146]
  // https://issues.apache.org/jira/browse/CASSANDRA-10146
  CCM::CassVersion version = test_utils::get_version();
  if (version < "3.0.0") {
    Version1Tests tester;
    test_utils::execute_query(tester.session, "CREATE TABLE test (key int PRIMARY KEY, v1 int, v2 text, v3 list<int>, v4 set<text>);");
    test_utils::CassPreparedPtr prepared(prepare_statement(tester.session, "INSERT INTO test (key, v1, v2, v3, v4) VALUES (?, ?, ?, ?, ?)"));
    test_utils::CassStatementPtr statement(cass_prepared_bind(prepared.get()));

    cass_statement_bind_int32(statement.get(), 0, 0);
    cass_statement_bind_int32(statement.get(), 1, 99);
    cass_statement_bind_string(statement.get(), 2, "abc");

    test_utils::CassCollectionPtr list(cass_collection_new(CASS_COLLECTION_TYPE_LIST, 3));
    cass_collection_append_int32(list.get(), 0);
    cass_collection_append_int32(list.get(), 1);
    cass_collection_append_int32(list.get(), 2);
    cass_statement_bind_collection(statement.get(), 3, list.get());

    test_utils::CassCollectionPtr set(cass_collection_new(CASS_COLLECTION_TYPE_SET, 3));
    cass_collection_append_string(set.get(), "d");
    cass_collection_append_string(set.get(), "e");
    cass_collection_append_string(set.get(), "f");
    cass_statement_bind_collection(statement.get(), 4, set.get());

    test_utils::CassFuturePtr future(cass_session_execute(tester.session, statement.get()));
    test_utils::wait_and_check_error(future.get());

    check_result(tester.session);
  } else {
    std::cout << "Invalid Test for Cassandra v" << version.to_string() << ": Protocol v1 and v2 were dropped in v3.0.0" << std::endl;
    BOOST_REQUIRE(true);
  }
}

BOOST_AUTO_TEST_CASE(batch_error)
{
  // Handle deprecated and removed protocol versions [CASSANDRA-10146]
  // https://issues.apache.org/jira/browse/CASSANDRA-10146
  CCM::CassVersion version = test_utils::get_version();
  if (version < "3.0.0") {
    Version1Tests tester;
    test_utils::execute_query(tester.session, "CREATE TABLE test (key int PRIMARY KEY, value int);");
    test_utils::CassBatchPtr batch(cass_batch_new(CASS_BATCH_TYPE_LOGGED));

    for (int x = 0; x < 4; x++) {
      std::string insert_query = str(boost::format("INSERT INTO test (key, value) VALUES(%d, %d);") % x % x);
      test_utils::CassStatementPtr insert_statement(cass_statement_new(insert_query.c_str(), 0));
      cass_batch_add_statement(batch.get(), insert_statement.get());
    }

    test_utils::CassFuturePtr future(cass_session_execute_batch(tester.session, batch.get()));

    CassError code = cass_future_error_code(future.get());
    CassString message;
    cass_future_error_message(future.get(), &message.data, &message.length);
    BOOST_REQUIRE(code == CASS_ERROR_LIB_MESSAGE_ENCODE);
    BOOST_REQUIRE(std::string(message.data, message.length).find("Operation unsupported by this protocol version") != std::string::npos);
  } else {
    std::cout << "Invalid Test for Cassandra v" << version.to_string() << ": Protocol v1 and v2 were dropped in v3.0.0" << std::endl;
    BOOST_REQUIRE(true);
  }
}

BOOST_AUTO_TEST_CASE(query_param_error)
{
  // Handle deprecated and removed protocol versions [CASSANDRA-10146]
  // https://issues.apache.org/jira/browse/CASSANDRA-10146
  CCM::CassVersion version = test_utils::get_version();
  if (version < "3.0.0") {
    Version1Tests tester;
    test_utils::execute_query(tester.session, "CREATE TABLE test (key int PRIMARY KEY, value int);");
    const char* insert_query = "INSERT INTO test (key, value) VALUES(?, ?);";
    test_utils::CassStatementPtr statement(cass_statement_new(insert_query, 2));

    cass_statement_bind_int32(statement.get(), 0, 11);
    cass_statement_bind_int32(statement.get(), 1, 99);

    test_utils::CassFuturePtr future(cass_session_execute(tester.session, statement.get()));

    CassError code = cass_future_error_code(future.get());
    CassString message;
    cass_future_error_message(future.get(), &message.data, &message.length);
    BOOST_REQUIRE(code == CASS_ERROR_SERVER_INVALID_QUERY);
    if (version.major_version == 1) {
      BOOST_REQUIRE(std::string(message.data, message.length).find("Cannot execute query with bind variables") != std::string::npos);
    } else {
      BOOST_REQUIRE(std::string(message.data, message.length).find("Invalid amount of bind variables") != std::string::npos);
    }
  } else {
    std::cout << "Invalid Test for Cassandra v" << version.to_string() << ": Protocol v1 and v2 were dropped in v3.0.0" << std::endl;
    BOOST_REQUIRE(true);
  }
}

BOOST_AUTO_TEST_SUITE_END()

ext: cpp

max_stars_repo_name: tcpcloud/debian-cassandra-cpp-driver

max_issues_repo_name: tcpcloud/debian-cassandra-cpp-driver

max_forks_repo_name: tcpcloud/debian-cassandra-cpp-driver


text:
//==================================================================================================
/**
  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_ARCH_X86_AVX_SIMD_FUNCTION_SHUFFLE_SSE_HPP_INCLUDED
#define BOOST_SIMD_ARCH_X86_AVX_SIMD_FUNCTION_SHUFFLE_SSE_HPP_INCLUDED

#include <boost/simd/detail/shuffle.hpp>
#include <boost/simd/detail/dispatch/meta/as_floating.hpp>
#include <type_traits>

namespace boost { namespace simd { namespace detail
{
 namespace bd = boost::dispatch;

 // ---------------------------------------------------------------------------------------------
  // AVX shuffling for SSE register
  struct  avx_128_shuffle : ssse3_shuffle
  {
    // -------------------------------------------------------------------------------------------
    // Reuse SSSE3 as back-up
    using ssse3_shuffle::process;

    // -------------------------------------------------------------------------------------------
    // Check if permutaton its into mm_permute_p*
    template<int I0, int I1>
    struct permute2 : brigand::bool_<(I0!=-1) && (I1!=-1)> {};

    template<int I0, int I1, int I2, int I3>
    struct permute4 : brigand::bool_<(I0!=-1) && (I1!=-1) && (I2!=-1) && (I3!=-1)> {};

    // -------------------------------------------------------------------------------------------
    // Unary process for 2x64 registers
    template<typename T,int P0, int P1>
    static BOOST_FORCEINLINE T process(T const& a0, pattern_<P0,P1> const& p)
    {
      return do_(a0, p, typename permute2<P0,P1>::type{}, typename perform_zeroing<P0,P1>::type{});
    }

    template<typename T,int P0, int P1>
    static BOOST_FORCEINLINE T do_( T const& a0, pattern_<P0,P1> const&
                                  , std::true_type const&, std::false_type const&
                                  )
    {
      bd::as_floating_t<T> tmp =  _mm_permute_pd( bitwise_cast<bd::as_floating_t<T>>(a0)
                                                , (P0&1)|((P1&1)<<1)
                                                );
      return bitwise_cast<T>( tmp );
    }

    // -------------------------------------------------------------------------------------------
    // Unary process for 4x32 registers
    template<typename T,int P0, int P1, int P2, int P3>
    static BOOST_FORCEINLINE T process(T const& a0, pattern_<P0,P1,P2,P3> const& p)
    {
      return do_( a0, p
                , typename permute4<P0,P1,P2,P3>::type{}
                , typename perform_zeroing<P0,P1,P2,P3>::type{}
                );
    }

    template<typename T, int P0, int P1, int P2, int P3>
    static BOOST_FORCEINLINE T do_( T const& a0, pattern_<P0,P1,P2,P3> const&
                                  , std::true_type const&, std::false_type const&
                                  )
    {
      bd::as_floating_t<T> tmp = _mm_permute_ps( bitwise_cast<bd::as_floating_t<T>>(a0)
                                               , (P0&3)|((P1&3)<<2)|((P2&3)<<4)|((P3&3)<<6)
                                               );
      return bitwise_cast<T>( tmp );
    }

    // -------------------------------------------------------------------------------------------
    // Common case when everything crumbles
    template<typename T, int... Ps, typename PR, typename PZ>
    static BOOST_FORCEINLINE T do_( T const& a0, pattern_<Ps...> const& p
                                  , PR const&, PZ const&
                                  )
    {
      return ssse3_shuffle::process(a0,p);
    }
  };
} } }

#endif

max_stars_repo_name: nickporubsky/boost-simd-clone


text:
// Boost.Range library
//
//  Copyright Neil Groves 2009. 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/libs/range/
//
#include <boost/range/algorithm/partial_sort.hpp>

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

#include <boost/assign.hpp>
#include <boost/bind.hpp>
#include <algorithm>
#include <functional>
#include <list>
#include <numeric>
#include <deque>
#include <vector>

namespace boost
{
    namespace
    {
        struct partial_sort_policy
        {
            template<class Container, class Iterator>
            void test_partial_sort(Container& cont, Iterator mid)
            {
                const Container old_cont(cont);

                boost::partial_sort(cont, mid);

                const std::size_t index = std::distance(cont.begin(), mid);
                Container cont2(old_cont);
                Iterator mid2(cont2.begin());
                std::advance(mid2, index);
                boost::partial_sort(cont2, mid2);

                BOOST_CHECK_EQUAL_COLLECTIONS( cont.begin(), cont.end(),
                                               cont2.begin(), cont2.end() );
            }

            template<class Container, class Iterator>
            void reference_partial_sort(Container& cont, Iterator mid)
            {
                std::partial_sort(cont.begin(), mid, cont.end());
            }
        };

        template<class BinaryPredicate>
        struct partial_sort_pred_policy
        {
            template<class Container, class Iterator>
            void test_partial_sort(Container& cont, Iterator mid)
            {
                const Container old_cont(cont);

                boost::partial_sort(cont, mid, BinaryPredicate());

                const std::size_t index = std::distance(cont.begin(), mid);
                Container cont2(old_cont);
                Iterator mid2(cont2.begin());
                std::advance(mid2, index);
                boost::partial_sort(cont2, mid2, BinaryPredicate());

                BOOST_CHECK_EQUAL_COLLECTIONS( cont.begin(), cont.end(),
                                               cont2.begin(), cont2.end() );
            }

            template<class Container, class Iterator>
            void reference_partial_sort(Container& cont, Iterator mid)
            {
                std::partial_sort(cont.begin(), mid, cont.end(), BinaryPredicate());
            }
        };

        template<class Container, class TestPolicy>
        void test_partial_sort_tp_impl(Container& cont, TestPolicy policy)
        {
            Container reference(cont);
            Container test(cont);

            typedef BOOST_DEDUCED_TYPENAME range_iterator<Container>::type iterator_t;

            BOOST_CHECK_EQUAL( reference.size(), test.size() );
            if (reference.size() != test.size())
                return;

            iterator_t reference_mid = reference.begin();
            iterator_t test_mid = test.begin();

            bool complete = false;
            while (!complete)
            {
                if (reference_mid == reference.end())
                    complete = true;

                policy.test_partial_sort(test, test_mid);
                policy.reference_partial_sort(reference, reference_mid);

                BOOST_CHECK_EQUAL_COLLECTIONS(
                    reference.begin(), reference.end(),
                    test.begin(), test.end()
                    );

                if (reference_mid != reference.end())
                {
                    ++reference_mid;
                    ++test_mid;
                }
            }
        }

        template<class Container>
        void test_partial_sort_impl(Container& cont)
        {
            test_partial_sort_tp_impl(cont, partial_sort_policy());
        }

        template<class Container, class BinaryPredicate>
        void test_partial_sort_impl(Container& cont, BinaryPredicate pred)
        {
            test_partial_sort_tp_impl(cont, partial_sort_pred_policy<BinaryPredicate>());
        }

        template<class Container>
        void test_partial_sort_impl()
        {
            using namespace boost::assign;

            Container cont;
            test_partial_sort_impl(cont);
            test_partial_sort_impl(cont, std::less<int>());
            test_partial_sort_impl(cont, std::greater<int>());

            cont.clear();
            cont += 1;
            test_partial_sort_impl(cont);
            test_partial_sort_impl(cont, std::less<int>());
            test_partial_sort_impl(cont, std::greater<int>());

            cont.clear();
            cont += 1,2,3,4,5,6,7,8,9;
            test_partial_sort_impl(cont);
            test_partial_sort_impl(cont, std::less<int>());
            test_partial_sort_impl(cont, std::greater<int>());
        }

        void test_partial_sort()
        {
            test_partial_sort_impl< std::vector<int> >();
            test_partial_sort_impl< std::deque<int> >();
        }
    }
}

boost::unit_test::test_suite*
init_unit_test_suite(int argc, char* argv[])
{
    boost::unit_test::test_suite* test
        = BOOST_TEST_SUITE( "RangeTestSuite.algorithm.partial_sort" );

    test->add( BOOST_TEST_CASE( &boost::test_partial_sort ) );

    return test;
}

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2000, 2001, 2002, 2003 RiskMap srl
 Copyright (C) 2003, 2004, 2005, 2006, 2007 StatPro Italia srl
 Copyright (C) 2006, 2008 Ferdinando Ametrano

 This file is part of QuantLib, a free-software/open-source library
 for financial quantitative analysts and developers - http://quantlib.org/

 QuantLib is free software: you can redistribute it and/or modify it
 under the terms of the QuantLib license.  You should have received a
 copy of the license along with this program; if not, please email
 <quantlib-dev@lists.sf.net>. The license is also available online at
 <http://quantlib.org/license.shtml>.

 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 license for more details.
*/

/*! \file vanillaswap.hpp
    \brief Simple fixed-rate vs Libor swap
*/

#ifndef quantlib_vanilla_swap_hpp
#define quantlib_vanilla_swap_hpp

#include <ql/instruments/swap.hpp>
#include <ql/time/daycounter.hpp>
#include <ql/time/schedule.hpp>
#include <boost/optional.hpp>

namespace QuantLib {

    class IborIndex;

    //! Plain-vanilla swap: fix vs floating leg
    /*! \ingroup instruments

        If no payment convention is passed, the convention of the
        floating-rate schedule is used.

        \warning if <tt>Settings::includeReferenceDateCashFlows()</tt>
                 is set to <tt>true</tt>, payments occurring at the
                 settlement date of the swap might be included in the
                 NPV and therefore affect the fair-rate and
                 fair-spread calculation. This might not be what you
                 want.

        \test
        - the correctness of the returned value is tested by checking
          that the price of a swap paying the fair fixed rate is null.
        - the correctness of the returned value is tested by checking
          that the price of a swap receiving the fair floating-rate
          spread is null.
        - the correctness of the returned value is tested by checking
          that the price of a swap decreases with the paid fixed rate.
        - the correctness of the returned value is tested by checking
          that the price of a swap increases with the received
          floating-rate spread.
        - the correctness of the returned value is tested by checking
          it against a known good value.
    */
    class VanillaSwap : public Swap {
      public:
        class arguments;
        class results;
        class engine;
        VanillaSwap(Type type,
                    Real nominal,
                    Schedule fixedSchedule,
                    Rate fixedRate,
                    DayCounter fixedDayCount,
                    Schedule floatSchedule,
                    ext::shared_ptr<IborIndex> iborIndex,
                    Spread spread,
                    DayCounter floatingDayCount,
                    boost::optional<BusinessDayConvention> paymentConvention = boost::none,
                    boost::optional<bool> useIndexedCoupons = boost::none);
        //! \name Inspectors
        //@{
        Type type() const;
        Real nominal() const;

        const Schedule& fixedSchedule() const;
        Rate fixedRate() const;
        const DayCounter& fixedDayCount() const;

        const Schedule& floatingSchedule() const;
        const ext::shared_ptr<IborIndex>& iborIndex() const;
        Spread spread() const;
        const DayCounter& floatingDayCount() const;

        BusinessDayConvention paymentConvention() const;

        const Leg& fixedLeg() const;
        const Leg& floatingLeg() const;
        //@}

        //! \name Results
        //@{
        Real fixedLegBPS() const;
        Real fixedLegNPV() const;
        Rate fairRate() const;

        Real floatingLegBPS() const;
        Real floatingLegNPV() const;
        Spread fairSpread() const;
        //@}
        // other
        void setupArguments(PricingEngine::arguments* args) const override;
        void fetchResults(const PricingEngine::results*) const override;

      private:
        void setupExpired() const override;
        Type type_;
        Real nominal_;
        Schedule fixedSchedule_;
        Rate fixedRate_;
        DayCounter fixedDayCount_;
        Schedule floatingSchedule_;
        ext::shared_ptr<IborIndex> iborIndex_;
        Spread spread_;
        DayCounter floatingDayCount_;
        BusinessDayConvention paymentConvention_;
        // results
        mutable Rate fairRate_;
        mutable Spread fairSpread_;
    };

    //! %Arguments for simple swap calculation
    class VanillaSwap::arguments : public Swap::arguments {
      public:
        arguments() : nominal(Null<Real>()) {}
        Type type = Receiver;
        Real nominal;

        std::vector<Date> fixedResetDates;
        std::vector<Date> fixedPayDates;
        std::vector<Time> floatingAccrualTimes;
        std::vector<Date> floatingResetDates;
        std::vector<Date> floatingFixingDates;
        std::vector<Date> floatingPayDates;

        std::vector<Real> fixedCoupons;
        std::vector<Spread> floatingSpreads;
        std::vector<Real> floatingCoupons;
        void validate() const override;
    };

    //! %Results from simple swap calculation
    class VanillaSwap::results : public Swap::results {
      public:
        Rate fairRate;
        Spread fairSpread;
        void reset() override;
    };

    class VanillaSwap::engine : public GenericEngine<VanillaSwap::arguments,
                                                     VanillaSwap::results> {};

    // inline definitions

    inline Swap::Type VanillaSwap::type() const {
        return type_;
    }

    inline Real VanillaSwap::nominal() const {
        return nominal_;
    }

    inline const Schedule& VanillaSwap::fixedSchedule() const {
        return fixedSchedule_;
    }

    inline Rate VanillaSwap::fixedRate() const {
        return fixedRate_;
    }

    inline const DayCounter& VanillaSwap::fixedDayCount() const {
        return fixedDayCount_;
    }

    inline const Schedule& VanillaSwap::floatingSchedule() const {
        return floatingSchedule_;
    }

    inline const ext::shared_ptr<IborIndex>& VanillaSwap::iborIndex() const {
        return iborIndex_;
    }

    inline Spread VanillaSwap::spread() const {
        return spread_;
    }

    inline const DayCounter& VanillaSwap::floatingDayCount() const {
        return floatingDayCount_;
    }

    inline BusinessDayConvention VanillaSwap::paymentConvention() const {
        return paymentConvention_;
    }

    inline const Leg& VanillaSwap::fixedLeg() const {
        return legs_[0];
    }

    inline const Leg& VanillaSwap::floatingLeg() const {
        return legs_[1];
    }

}

#endif

max_stars_repo_name: jiangjiali/QuantLib

max_issues_repo_name: jiangjiali/QuantLib

max_forks_repo_name: jiangjiali/QuantLib


text: #include <boost/geometry/multi/algorithms/transform.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
//---------------------------------------------------------------------------//
// Copyright (c) 2018-2020 Mikhail Komarov <nemo@nil.foundation>
//
// MIT License
//
// 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.
//---------------------------------------------------------------------------//

#ifndef CRYPTO3_RANDOM_CHACHA_HPP
#define CRYPTO3_RANDOM_CHACHA_HPP

#include <string>

#include <boost/config.hpp>
#include <boost/noncopyable.hpp>
#include <boost/random/detail/auto_link.hpp>
#include <boost/system/config.hpp>    // force autolink to find Boost.System

#include <nil/crypto3/hash/algorithm/hash.hpp>
#include <nil/crypto3/hash/sha2.hpp>

#include <nil/crypto3/mac/algorithm/compute.hpp>
#include <nil/crypto3/mac/hmac.hpp>

#include <nil/crypto3/stream/algorithm/encrypt.hpp>
#include <nil/crypto3/stream/chacha.hpp>

namespace nil {
    namespace crypto3 {
        namespace random {

            /*!
             * @brief
             * @tparam StreamCipher
             * @tparam MessageAuthenticationCode
             *
             * ChaCha_RNG is a very fast but completely ad-hoc RNG created by
             * creating a 256-bit random value and using it as a key for ChaCha20.
             *
             * The RNG maintains two 256-bit keys, one for HMAC_SHA256 (HK) and the
             * other for ChaCha20 (CK). To compute a new key in response to
             * reseeding request or add_entropy calls, ChaCha_RNG computes
             *   CK' = HMAC_SHA256(HK, input_material)
             * Then a new HK' is computed by running ChaCha20 with the new key to
             * output 32 bytes:
             *   HK' = ChaCha20(CK')
             *
             * Now output can be produced by continuing to produce output with ChaCha20
             * under CK'
             *
             * The first HK (before seeding occurs) is taken as the all zero value.
             *
             * @warning This RNG construction is probably fine but is non-standard.
             * The primary reason to use it is in cases where the other RNGs are
             * not fast enough.
             */
            template<typename StreamCipher = stream::chacha<64, 128, 20>,
                     typename MessageAuthenticationCode = mac::hmac<hashes::sha2<256>>>
            struct chacha : private boost::noncopyable {
                typedef StreamCipher stream_cipher_type;
                typedef MessageAuthenticationCode mac_type;
                typedef typename mac_type::key_type key_type;

                typedef std::vector<std::uint8_t> result_type;

                BOOST_STATIC_CONSTANT(std::size_t, reseed_interval = 256);

                BOOST_STATIC_CONSTANT(bool, has_fixed_range = false);

                /** Returns the smallest value that the \random_device can produce. */
                static BOOST_CONSTEXPR std::size_t min BOOST_PREVENT_MACRO_SUBSTITUTION() {
                    return 0;
                }
                /** Returns the largest value that the \random_device can produce. */
                static BOOST_CONSTEXPR std::size_t max BOOST_PREVENT_MACRO_SUBSTITUTION() {
                    return ~0u;
                }

                /** Constructs a @c random_device, optionally using the default device. */
                BOOST_RANDOM_DECL chacha() : cnt(0) {
                    mac_key.fill(0);
                }
                /**
                 * Constructs a @c random_device, optionally using the given token as an
                 * access specification (for example, a URL) to some implementation-defined
                 * service for monitoring a stochastic process.
                 */
                template<typename SeedSinglePassRange>
                BOOST_RANDOM_DECL explicit chacha(const SeedSinglePassRange &token) : cnt(0) {
                    mac_key.fill(0);
                }

                BOOST_RANDOM_DECL ~chacha() {
                    mac_key.fill(0);
                    mac_key.clear();
                }

                /** default seeds the underlying generator. */
                void seed() {
                    cnt = 0;
                }

                /** Seeds the underlying generator with first and last. */
                template<typename InputIterator>
                void seed(InputIterator &first, InputIterator last) {
                    update(first, last);

                    if (CHAR_BIT * std::distance(first, last) *
                            sizeof(typename std::iterator_traits<InputIterator>::value_type) >=
                        reseed_interval) {
                        cnt = 0;
                    }
                }

                /**
                 * Returns: An entropy estimate for the random numbers returned by
                 * operator(), in the range min() to log2( max()+1). A deterministic
                 * random number generator (e.g. a pseudo-random number engine)
                 * has entropy 0.
                 *
                 * Throws: Nothing.
                 */
                BOOST_RANDOM_DECL double entropy() const {
                }
                /** Returns a random value in the range [min, max]. */
                BOOST_RANDOM_DECL result_type operator()() {
                    return accumulators::extract::stream<StreamCipher>(acc);
                }

                /** Fills a range with random values. */
                template<class Iter>
                void generate(Iter begin, Iter end) {
                    detail::pack(accumulators::extract::stream<StreamCipher>(acc), begin, end);
                }

            protected:
                template<typename InputIterator>
                void update(InputIterator first, InputIterator last) {
                    mac_key = encrypt<StreamCipher>({0}, mac::compute<mac_type>(first, last, mac_key), acc);
                }

                std::size_t cnt;
                key_type mac_key;
                accumulator_set<StreamCipher> acc;
            };
        }    // namespace random
    }        // namespace crypto3
}    // namespace nil

#endif /* BOOST_RANDOM_RANDOM_DEVICE_HPP */