text:
/**
 * Copyright Soramitsu Co., Ltd. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

#include "integration/acceptance/acceptance_fixture.hpp"

#include <boost/algorithm/string.hpp>
#include "backend/protobuf/transaction.hpp"
#include "cryptography/crypto_provider/crypto_defaults.hpp"
#include "datetime/time.hpp"
#include "framework/integration_framework/integration_test_framework.hpp"
#include "interfaces/permissions.hpp"
#include "module/shared_model/builders/protobuf/test_transaction_builder.hpp"

using namespace shared_model;
using namespace shared_model::crypto;
using namespace integration_framework;

struct HexKeys : public AcceptanceFixture {
  IntegrationTestFramework itf;
  HexKeys() : itf(1), kNow(iroha::time::now()) {}

  void SetUp() override {
    using Role = interface::permissions::Role;
    const interface::RolePermissionSet permissions = {Role::kAddSignatory,
                                                      Role::kRemoveSignatory,
                                                      Role::kAddPeer,
                                                      Role::kCreateAccount,
                                                      Role::kAppendRole};

    itf.setInitialState(common_constants::kAdminKeypair)
        .sendTxAwait(AcceptanceFixture::makeUserWithPerms(permissions),
                     CHECK_TXS_QUANTITY(1));
  }

  auto addSignatory(
      std::string key,
      interface::types::TimestampType time,
      interface::types::AccountIdType user_id = common_constants::kUserId) {
    return AcceptanceFixture::baseTx().createdTime(time).addSignatoryRaw(
        user_id, key);
  }

  auto removeSignatory(
      std::string key,
      interface::types::TimestampType time,
      interface::types::AccountIdType user_id = common_constants::kUserId) {
    return AcceptanceFixture::baseTx().createdTime(time).removeSignatoryRaw(
        user_id, key);
  }

  auto createAccount(std::string key, interface::types::TimestampType time) {
    return AcceptanceFixture::baseTx().createdTime(time).createAccountRaw(
        common_constants::kAnotherUser, common_constants::kDomain, key);
  }

  auto addPeer(std::string key, interface::types::TimestampType time) {
    const auto imaginary_address = "192.168.23.149:50051";
    return AcceptanceFixture::baseTx().createdTime(time).addPeerRaw(
        imaginary_address, key);
  }

  auto composeKeypairFromHex(std::string public_key, std::string private_key) {
    return crypto::Keypair(
        crypto::PublicKey(crypto::Blob::fromHexString(public_key)),
        crypto::PrivateKey(crypto::Blob::fromHexString(private_key)));
  }

  Keypair keypair = DefaultCryptoAlgorithmType::generateKeypair();
  Keypair anotherKeypair = DefaultCryptoAlgorithmType::generateKeypair();

  const std::string kLowercasedPublicKey = [this]() {
    std::string result = keypair.publicKey().hex();
    std::transform(result.begin(), result.end(), result.begin(), [](char c) {
      return std::tolower(c);
    });

    return result;
  }();

  const std::string kUppercasedPublicKey = [this]() {
    std::string result = keypair.publicKey().hex();
    std::transform(result.begin(), result.end(), result.begin(), [](char c) {
      return std::toupper(c);
    });

    return result;
  }();

  const std::string kPrivateKey = keypair.privateKey().hex();

  const std::string kAnotherPublicKey = anotherKeypair.publicKey().hex();
  const std::string kAnotherPrivateKey = anotherKeypair.privateKey().hex();

  const interface::types::TimestampType kNow;
};

/**
 * @given an account with kAddSignatory permission
 * @when the same public key is used twice but written in different case
 * @then only first attempt to add the key succeeds
 */
TEST_F(HexKeys, AddSignatory) {
  auto tx1 = complete(addSignatory(kLowercasedPublicKey, kNow));
  auto tx2 = complete(addSignatory(kUppercasedPublicKey, kNow + 1));
  auto hash1 = tx1.hash();
  auto hash2 = tx2.hash();

  itf.sendTx(tx1)
      .checkStatus(hash1, CHECK_STATELESS_VALID)
      .checkStatus(hash1, CHECK_ENOUGH_SIGNATURES)
      .checkStatus(hash1, CHECK_STATEFUL_VALID)
      .checkStatus(hash1, CHECK_COMMITTED)
      .sendTx(tx2)
      .checkStatus(hash2, CHECK_STATELESS_VALID)
      .checkStatus(hash2, CHECK_ENOUGH_SIGNATURES)
      .checkStatus(hash2, CHECK_STATEFUL_INVALID)
      .checkStatus(hash2, CHECK_REJECTED);
}

/**
 * The same as the previous test, but the keys are swapped.
 * Thus we ensure that there is no difference what case of the key is used
 * first.
 *
 * @given an account with kAddSignatory permission
 * @when the same public key is used twice but written in different case
 * @then only first attempt to add the key succeeds
 */
TEST_F(HexKeys, AddSignatoryReverse) {
  auto tx1 = complete(addSignatory(kUppercasedPublicKey, kNow));
  auto tx2 = complete(addSignatory(kLowercasedPublicKey, kNow + 1));
  auto hash1 = tx1.hash();
  auto hash2 = tx2.hash();

  itf.sendTx(tx1)
      .checkStatus(hash1, CHECK_STATELESS_VALID)
      .checkStatus(hash1, CHECK_ENOUGH_SIGNATURES)
      .checkStatus(hash1, CHECK_STATEFUL_VALID)
      .checkStatus(hash1, CHECK_COMMITTED)
      .sendTx(tx2)
      .checkStatus(hash2, CHECK_STATELESS_VALID)
      .checkStatus(hash2, CHECK_ENOUGH_SIGNATURES)
      .checkStatus(hash2, CHECK_STATEFUL_INVALID)
      .checkStatus(hash2, CHECK_REJECTED);
}

/**
 * @given a user with kAddSignatory and kRemoveSignatory permissions
 * @when a user adds a signatory using uppercased key string
 * @then the signatory can be removed using lowercased key string
 */
TEST_F(HexKeys, RemoveSignatoryUl) {
  auto tx1 = complete(addSignatory(kUppercasedPublicKey, kNow));
  auto tx2 = complete(removeSignatory(kLowercasedPublicKey, kNow + 1));
  auto hash2 = tx2.hash();

  itf.sendTxAwait(tx1, CHECK_TXS_QUANTITY(1))
      .sendTx(tx2)
      .checkStatus(hash2, CHECK_STATELESS_VALID)
      .checkStatus(hash2, CHECK_ENOUGH_SIGNATURES)
      .checkStatus(hash2, CHECK_STATEFUL_VALID)
      .checkStatus(hash2, CHECK_COMMITTED);
}

/**
 * @given a user with kAddSignatory and kRemoveSignatory permissions
 * @when a user adds a signatory using lowercased key string
 * @then the signatory can be removed using uppercased key string
 */
TEST_F(HexKeys, RemoveSignatorylU) {
  auto tx1 = complete(addSignatory(kLowercasedPublicKey, kNow));
  auto tx2 = complete(removeSignatory(kUppercasedPublicKey, kNow + 1));
  auto hash2 = tx2.hash();

  itf.sendTxAwait(tx1, CHECK_TXS_QUANTITY(1))
      .sendTx(tx2)
      .checkStatus(hash2, CHECK_STATELESS_VALID)
      .checkStatus(hash2, CHECK_ENOUGH_SIGNATURES)
      .checkStatus(hash2, CHECK_STATEFUL_VALID)
      .checkStatus(hash2, CHECK_COMMITTED);
}

/**
 * @given a user created with uppercased public key
 * @when some additional key is added to the user
 * @then the first key can be removed even when it passed in lower case to a
 * command
 */
TEST_F(HexKeys, CreateAccountUl) {
  auto user = common_constants::kSameDomainUserId;
  auto keypair = composeKeypairFromHex(kLowercasedPublicKey, kPrivateKey);

  // kUserId creates kSameDomainUserId and appends the role with test
  // permissions
  auto tx1 = complete(createAccount(kUppercasedPublicKey, kNow)
                          .appendRole(user, common_constants::kRole));

  // kSameDomainUserId adds one more key to own account
  auto tx2 = complete(
      addSignatory(kAnotherPublicKey, kNow + 1, user).creatorAccountId(user),
      keypair);

  // kSameDomainUserId removes the initial key specifing it in other font case
  auto tx3 = complete(removeSignatory(kLowercasedPublicKey, kNow + 2, user)
                          .creatorAccountId(user),
                      keypair);

  itf.sendTxAwait(tx1, CHECK_TXS_QUANTITY(1))
      .sendTxAwait(tx2, CHECK_TXS_QUANTITY(1))
      .sendTxAwait(tx3, CHECK_TXS_QUANTITY(1));
}

/**
 * The same as the previous test, but the keys are swapped.
 * Thus we ensure that there is no difference what case of the key is used
 * first.
 *
 * @given a user created with uppercased public key
 * @when some additional key is added to the user
 * @then the first key can be removed even when it passed in lower case to a
 * command
 */
TEST_F(HexKeys, CreateAccountlU) {
  auto user = common_constants::kSameDomainUserId;
  auto keypair = composeKeypairFromHex(kUppercasedPublicKey, kPrivateKey);

  // kUserId creates kSameDomainUserId and appends the role with test
  // permissions
  auto tx1 = complete(createAccount(kLowercasedPublicKey, kNow)
                          .appendRole(user, common_constants::kRole));

  // kSameDomainUserId adds one more key to own account
  auto tx2 = complete(
      addSignatory(kAnotherPublicKey, kNow + 1, user).creatorAccountId(user),
      keypair);

  // kSameDomainUserId removes the initial key specifing it in other font
  // case
  auto tx3 = complete(removeSignatory(kUppercasedPublicKey, kNow + 2, user)
                          .creatorAccountId(user),
                      keypair);

  itf.sendTxAwait(tx1, CHECK_TXS_QUANTITY(1))
      .sendTxAwait(tx2, CHECK_TXS_QUANTITY(1))
      .sendTxAwait(tx3, CHECK_TXS_QUANTITY(1));
}

/**
 * @given an initialized peer
 * @when a user tries to add another peer with the same key as the first peer
 * has, but written in a different font case
 * @then the transaction is considered as stateful invalid
 */
TEST_F(HexKeys, AddPeerSameKeyDifferentCase) {
  std::string original_key = common_constants::kAdminKeypair.publicKey().hex();
  std::string same_key_uppercased = original_key;
  boost::to_upper(same_key_uppercased);
  ASSERT_NE(original_key, same_key_uppercased);
  auto tx = complete(addPeer(same_key_uppercased, kNow));
  auto hash = tx.hash();

  itf.sendTx(tx)
      .checkStatus(hash, CHECK_STATELESS_VALID)
      .checkStatus(hash, CHECK_ENOUGH_SIGNATURES)
      .checkStatus(hash, CHECK_STATEFUL_INVALID)
      .checkStatus(hash, CHECK_REJECTED);
}


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

#include <nt2/core/utility/of_size.hpp>
#include <nt2/sdk/meta/safe_at.hpp>
#include <nt2/sdk/meta/tribool.hpp>
#include <boost/type_traits/is_same.hpp>

namespace nt2 { namespace details
{
  template<class Seq>
  struct is_col_vector
  {
    static const std::size_t n = Seq::static_size;
    static const bool is_not = n < 1 || (n > 1 && meta::mpl_safe_at_c<typename Seq::values_type, 1, boost::mpl::long_<1> >::type::value != -1);
    typedef typename meta::indeterminate_false<!is_not>::type type;
  };

  template<std::ptrdiff_t N>
  struct is_col_vector< nt2::of_size_<N> >
       : meta::true_
  {
  };

  template<class Seq>
  struct is_row_vector
  {
    static const std::size_t n = Seq::static_size;
    static const bool is_not = n < 2 || (n > 2 && meta::mpl_safe_at_c<typename Seq::values_type, 2, boost::mpl::long_<1> >::type::value != -1);
    typedef typename meta::indeterminate_false<!is_not>::type type;
  };

  template<std::ptrdiff_t N>
  struct is_row_vector< nt2::of_size_<1, N> >
       : meta::true_
  {
  };

  template<class Seq>
  struct is_vector : meta::or_< is_col_vector<Seq>, is_row_vector<Seq> > {};

  template<class Seq>
  struct is_definitely_not_vector : boost::is_same<typename is_vector<Seq>::type, meta::false_> {};

  template<class Seq>
  struct is_definitely_vector : boost::is_same<typename is_vector<Seq>::type, meta::true_> {};

  template<class Seq>
  struct is_definitely_col_vector : boost::is_same<typename is_col_vector<Seq>::type, meta::true_> {};

  template<class Seq>
  struct is_definitely_row_vector : boost::is_same<typename is_row_vector<Seq>::type, meta::true_> {};
} }

#endif

ext: hpp


text:
//==============================================================================
//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          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_ARITHMETIC_FUNCTIONS_SCALAR_ADDS_HPP_INCLUDED
#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_SCALAR_ADDS_HPP_INCLUDED
#include <boost/simd/arithmetic/functions/adds.hpp>
#include <boost/simd/include/functions/scalar/saturate.hpp>
#include <boost/simd/include/functions/scalar/is_gtz.hpp>
#include <boost/simd/include/functions/scalar/is_greater.hpp>
#include <boost/simd/include/functions/scalar/is_less.hpp>
#include <boost/simd/include/functions/scalar/min.hpp>
#include <boost/simd/include/functions/scalar/max.hpp>
#include <boost/simd/include/constants/valmin.hpp>
#include <boost/simd/include/constants/valmax.hpp>
#include <boost/dispatch/meta/upgrade.hpp>
#include <boost/dispatch/meta/as_unsigned.hpp>

namespace boost { namespace simd { namespace ext
{
  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::adds_, tag::cpu_
                            , (A0)
                            , (scalar_< integer_<A0> >)(scalar_< integer_<A0> >)
                            )
  {
    typedef A0 result_type;
    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)
    {
      typedef typename dispatch::meta::upgrade<A0>::type utype;
      return static_cast<A0>(boost::simd::saturate<A0>(utype(a0)+utype(a1)));
    }
  };

  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::adds_, tag::cpu_
                            , (A0)
                            , (scalar_< unsigned_<A0> >)(scalar_< unsigned_<A0> >)
                            )
  {
    typedef A0 result_type;
    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)
    {
      typedef typename dispatch::meta::upgrade<A0>::type utype;
      return static_cast<A0>(boost::simd::min(utype(boost::simd::Valmax<A0>()), utype(a0+a1)));
    }
  };

  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::adds_, tag::cpu_
                            , (A0)
                            , (scalar_< int64_<A0> >)(scalar_< int64_<A0> >)
                            )
  {
    typedef A0 result_type;
    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)
    {
      typedef typename dispatch::meta::as_unsigned<A0>::type utype;

      bool gtza0 = is_gtz(a0);
      bool gtza1 = is_gtz(a1);
      A0 a0pa1 = A0(utype(a0)+utype(a1));
      if (gtza0 && gtza1 && (lt(a0pa1, a0)))
      {
        return Valmax<A0>();
      }
      else if (!gtza0 && !gtza1 && (is_gtz(a0pa1) || (gt(a0pa1, boost::simd::min(a0, a1)))))
      {
        return Valmin<A0>();
      }
      else
      {
        return a0pa1;
      }
    }
  };

  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::adds_, tag::cpu_
                            , (A0)
                            , (scalar_< uint64_<A0> >)(scalar_< uint64_<A0> >)
                            )
  {
    typedef A0 result_type;
    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)
    {
      A0 a0pa1 = a0+a1;
      if (lt(a0pa1, boost::simd::max(a0, a1)))
      {
        return Valmax<A0>();
      }
      else
      {
        return a0pa1;
      }
    }
  };

  BOOST_SIMD_FUNCTOR_IMPLEMENTATION( boost::simd::tag::adds_, tag::cpu_
                            , (A0)
                            , (scalar_< uint32_<A0> >)(scalar_< uint32_<A0> >)
                            )
  {
    typedef A0 result_type;
    BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)
    {
      A0 a0pa1 = a0+a1;
      if (lt(a0pa1, boost::simd::max(a0, a1)))
      {
        return Valmax<A0>();
      }
      else
      {
        return a0pa1;
      }
    }
  };
} } }

#endif


text:
#include "IPC/Managed/detail/Throw.h"
#include "Exception.h"

#pragma managed(push, off)
#include "IPC/Exception.h"
#include <boost/interprocess/exceptions.hpp>
#include <stdexcept>
#pragma managed(pop)

namespace IPC
{
namespace Managed
{
    namespace detail
    {
#pragma managed(push, off)
        namespace
        {
            [[noreturn]] void RethrowException(std::exception_ptr error)
            {
                std::rethrow_exception(error);
            }
        }
#pragma managed(pop)

        void ThrowManagedException(std::exception_ptr error)
        {
            try
            {
                RethrowException(error);  // TODO: Support nested exceptions.
            }
            catch (const IPC::Exception& e)
            {
                throw gcnew Managed::Exception{ e };
            }
            catch (const boost::interprocess::bad_alloc& e)
            {
                throw gcnew System::OutOfMemoryException{ gcnew System::String{ e.what() } };
            }
            catch (const boost::interprocess::interprocess_exception& e)
            {
                throw gcnew Managed::Exception{ e };
            }
            catch (const std::invalid_argument& e)
            {
                throw gcnew System::ArgumentException{ gcnew System::String{ e.what() } };
            }
            catch (const std::out_of_range& e)
            {
                throw gcnew System::ArgumentOutOfRangeException{ gcnew System::String{ e.what() } };
            }
            catch (const std::bad_cast& e)
            {
                throw gcnew System::InvalidCastException{ gcnew System::String{ e.what() } };
            }
            catch (const std::bad_alloc& e)
            {
                throw gcnew System::OutOfMemoryException{ gcnew System::String{ e.what() } };
            }
            catch (const std::exception& e)
            {
                throw gcnew System::Exception{ gcnew System::String{ e.what() } };
            }
        }

    } // detail

} // Managed
} // IPC

ext: cpp


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

using namespace std;
using namespace boost;

enum class Color {red, green, blue};
enum class Size {small, medium, large};

struct Product
{
    string name;
    Color color;
    Size size;
};

/*
    Product를 필터링 하기 위한 클래스이지만,
    필요한 요구 사항들이 점점 늘어나고 복잡해질수록
    작성해야 되는 코드양이 많아 지고, 내부 구조 또한 복잡해지게 된다.

    예를 들어 지금은 Product가 3개의 멤버 밖에 없어서
    ByColor, BySize 등등의 함수 밖에 나타나지 않을 수 있지만
    Product의 멤버 변수가 점점 늘어나게 되면
    ProductFilter도 그에 따라 클래스의 크기가 방대해지게 된다.
*/
struct ProductFilter
{
    vector<Product*> ByColor(vector<Product*> items, Color color)
    {
        vector<Product*> result;
        for(auto& i : items)
        {
            if(i->color == color){
                result.emplace_back(i);
            }
        }
        return result;
    }

    vector<Product*> BySize(vector<Product*> items, Size size)
    {
        vector<Product*> result;
        for(auto& i : items)
        {
            if(i->size == size){
                result.emplace_back(i);
            }
        }
        return result;
    }
};

/*
    이러한 문제는 인터페이스를 통해 해결할 수 있다.
    필터링을 위한 인터페이스를 구성하고, 필터에 사용될
    함수 또한 인터페이스로 두는 것이다.
*/

template <typename T> struct AndSpecification;

template <typename T> struct Specification
{
    virtual bool IsSatisfied(T* item) = 0;

    // AndSpecification을 구현이 되있으므로 && 연산자를 통한 추가가 가능합니다.
    AndSpecification<T> operator&&(Specification<T>&& other)
    {
        return AndSpecification<T>(*this, other);
    }
};

template <typename T> struct Filter
{
    virtual vector<T*> Filtered(vector<T*> items, Specification<T>& spec)=0;
};

struct BetterFilter : Filter<Product>
{
    vector<Product*> Filtered(vector<Product*> items, Specification<Product>& spec)
    {
        vector<Product*> result;

        for(auto& item : items)
        {
            if(spec.IsSatisfied(item))
            {
                result.emplace_back(item);
            }
        }
        return result;
    }
};

struct ColorSpecification : Specification<Product>
{
    Color color;
    explicit ColorSpecification(Color color) : color(color){}

    bool IsSatisfied(Product *item) override{
        return item->color == color;
    }
};

struct SizeSpecification : Specification<Product>
{
    Size size;
    explicit SizeSpecification(Size size) : size(size){}

    bool IsSatisfied(Product *item) override{
        return item->size == size;
    }
};

/*
    복수의 조건을 가진 데이터를 필터링 해야 될 때는 어떻게 해야될까?

*/
template <typename T> struct AndSpecification : Specification<T>
{
    Specification<T>& first;
    Specification<T>& second;

    AndSpecification(Specification<T> &first, Specification<T> &second) : first(first), second(second){}

    bool IsSatisfied(T *item) override{
        return first.IsSatisfied(item) && second.IsSatisfied(item);
    }
};

int main()
{
    Product apple{"Apple", Color::green, Size::small};
    Product tree{"Tree", Color::green, Size::large};
    Product house{"House", Color::blue, Size::large};

    vector<Product*> items {&apple, &tree, &house};

    // 좋지 않는 방법

    /*
    ProductFilter pf;
    auto green_things = pf.ByColor(items, Color::green);
    for(auto& item : green_things)
    {
        cout<<item->name<<endl;
    }
    */

    // 좋은 방법
    BetterFilter betterFilter;
    ColorSpecification greenSpec(Color::green);
    for(auto& item : betterFilter.Filtered(items, greenSpec))
    {
        cout<<item->name<<endl;
    }

    // 복수의 멤버를 필터링 하는 방법
    SizeSpecification largeSpec(Size::large);
    AndSpecification<Product> largeAndGreenSpec(greenSpec, largeSpec);
    for(auto& item : betterFilter.Filtered(items, largeAndGreenSpec))
    {
        cout<<item->name<<endl;
    }

    auto spec = ColorSpecification(Color::green) && SizeSpecification(Size::large);
    for(auto& item : betterFilter.Filtered(items, spec))
    {
        cout<<item->name<<endl;
    }
}

max_stars_repo_name: homveloper/DesignPattern-CPP

max_issues_repo_name: homveloper/DesignPattern-CPP

max_forks_repo_name: homveloper/DesignPattern-CPP


text:
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra. Eigen itself is part of the KDE project.
//
// Copyright (C) 2008 Gael Guennebaud <g.gael@free.fr>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#define EIGEN_NO_ASSERTION_CHECKING
#include "main.h"
#include <Eigen/Cholesky>
#include <Eigen/LU>

#ifdef HAS_GSL
#include "gsl_helper.h"
#endif

template<typename MatrixType> void cholesky(const MatrixType& m)
{
  /* this test covers the following files:
     LLT.h LDLT.h
  */
  int rows = m.rows();
  int cols = m.cols();

  typedef typename MatrixType::Scalar Scalar;
  typedef typename NumTraits<Scalar>::Real RealScalar;
  typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime> SquareMatrixType;
  typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, 1> VectorType;

  MatrixType a0 = MatrixType::Random(rows,cols);
  VectorType vecB = VectorType::Random(rows), vecX(rows);
  MatrixType matB = MatrixType::Random(rows,cols), matX(rows,cols);
  SquareMatrixType symm =  a0 * a0.adjoint();
  // let's make sure the matrix is not singular or near singular
  MatrixType a1 = MatrixType::Random(rows,cols);
  symm += a1 * a1.adjoint();

  #ifdef HAS_GSL
  if (ei_is_same_type<RealScalar,double>::ret)
  {
    typedef GslTraits<Scalar> Gsl;
    typename Gsl::Matrix gMatA=0, gSymm=0;
    typename Gsl::Vector gVecB=0, gVecX=0;
    convert<MatrixType>(symm, gSymm);
    convert<MatrixType>(symm, gMatA);
    convert<VectorType>(vecB, gVecB);
    convert<VectorType>(vecB, gVecX);
    Gsl::cholesky(gMatA);
    Gsl::cholesky_solve(gMatA, gVecB, gVecX);
    VectorType vecX(rows), _vecX, _vecB;
    convert(gVecX, _vecX);
    symm.llt().solve(vecB, &vecX);
    Gsl::prod(gSymm, gVecX, gVecB);
    convert(gVecB, _vecB);
    // test gsl itself !
    VERIFY_IS_APPROX(vecB, _vecB);
    VERIFY_IS_APPROX(vecX, _vecX);

    Gsl::free(gMatA);
    Gsl::free(gSymm);
    Gsl::free(gVecB);
    Gsl::free(gVecX);
  }
  #endif

  {
    LDLT<SquareMatrixType> ldlt(symm);
    VERIFY(ldlt.isPositiveDefinite());
    // in eigen3, LDLT is pivoting
    //VERIFY_IS_APPROX(symm, ldlt.matrixL() * ldlt.vectorD().asDiagonal() * ldlt.matrixL().adjoint());
    ldlt.solve(vecB, &vecX);
    VERIFY_IS_APPROX(symm * vecX, vecB);
    ldlt.solve(matB, &matX);
    VERIFY_IS_APPROX(symm * matX, matB);
  }

  {
    LLT<SquareMatrixType> chol(symm);
    VERIFY(chol.isPositiveDefinite());
    VERIFY_IS_APPROX(symm, chol.matrixL() * chol.matrixL().adjoint());
    chol.solve(vecB, &vecX);
    VERIFY_IS_APPROX(symm * vecX, vecB);
    chol.solve(matB, &matX);
    VERIFY_IS_APPROX(symm * matX, matB);
  }

#if 0 // cholesky is not rank-revealing anyway
  // test isPositiveDefinite on non definite matrix
  if (rows>4)
  {
    SquareMatrixType symm =  a0.block(0,0,rows,cols-4) * a0.block(0,0,rows,cols-4).adjoint();
    LLT<SquareMatrixType> chol(symm);
    VERIFY(!chol.isPositiveDefinite());
    LDLT<SquareMatrixType> cholnosqrt(symm);
    VERIFY(!cholnosqrt.isPositiveDefinite());
  }
#endif
}

void test_eigen2_cholesky()
{
  for(int i = 0; i < g_repeat; i++) {
    CALL_SUBTEST_1( cholesky(Matrix<double,1,1>()) );
    CALL_SUBTEST_2( cholesky(Matrix2d()) );
    CALL_SUBTEST_3( cholesky(Matrix3f()) );
    CALL_SUBTEST_4( cholesky(Matrix4d()) );
    CALL_SUBTEST_5( cholesky(MatrixXcd(7,7)) );
    CALL_SUBTEST_6( cholesky(MatrixXf(17,17)) );
    CALL_SUBTEST_7( cholesky(MatrixXd(33,33)) );
  }
}


text:
//
//  common.hpp
//  ezWebSockify
//
//  Created by Franck  on 22/07/2020.
//  Copyright © 2020 Frachop. All rights reserved.
//

#pragma once
#include "../include/ezWebSockifyLib/ezWebSockifyLib.hpp"

namespace ezWebSockify
{

	//- /////////////////////////////////////////////////////////////////////////////////

	namespace net = boost::asio;            // from <boost/asio.hpp>
	using tcp = net::ip::tcp;               // from <boost/asio/ip/tcp.hpp>

	//- /////////////////////////////////////////////////////////////////////////////////

	constexpr std::size_t MAX_FRAME_SIZE{ 512 * 1024 };
	constexpr auto TIMER_TIMEOUT{ std::chrono::milliseconds(5) };

	//- /////////////////////////////////////////////////////////////////////////////////

	class Frame
	{
	private:
		static std::list<Frame*> _all;

	public:
		constexpr static size_t MAX_FRAME_SIZE { ezWebSockify::MAX_FRAME_SIZE };

		enum class Status {
			released= 0,
			readyToRead,
			readed,
			waitToWrite
		};

	public:
		Frame() : _size{ 0 }, _data{}, _status{ Status::released } { _all.push_back(this); }
		void clear() { _size = 0; }
		std::size_t size() const { return _size; }
		void resize(std::size_t sz) {
			if ( sz > MAX_FRAME_SIZE )
				throw std::range_error("frame size out of range");
			_size = sz;
		}
		uint8_t * data() { return _data.data(); }
		uint8_t const * cdata() const { return _data.data(); }

		Status status() const { return _status; }
		void setStatus(Status s) { _status= s; }

		static void dumpAll() {
			std::array<std::size_t, 4> histogram{0};
			std::for_each( std::begin(_all), std::end(_all),
				[&histogram](Frame const * f){
					histogram[ static_cast<int>(f->_status) ]++;
				}
			);
			LOGD("Frames {}", _all.size());
			LOGD("  released    [{}]", histogram[0]);
			LOGD("  readyToRead [{}]", histogram[1]);
			LOGD("  readed      [{}]", histogram[2]);
			LOGD("  waitToWrite [{}]", histogram[3]);
		}

	private:
		std::size_t _size;
		std::array<uint8_t, MAX_FRAME_SIZE> _data;
		Status _status;
	};

	using frame_queue_t= std::deque<Frame*> ;

	// - ///////////////////////////////////////////////////////////////////////////////////////////////////////

	class Context
	{
	public:
		void wait() {
			std::unique_lock<std::mutex> lock(_m);
			_mustQuit.wait(lock);
		}

		void stop(){
			std::unique_lock<std::mutex> lock(_m);
			_mustQuit.notify_all();
		}

	private:
		std::mutex _m{};
		std::condition_variable _mustQuit{};
	};

}

// - ///////////////////////////////////////////////////////////////////////////////////////////////////////

#include "pool.hpp"
#include "tcpClient.hpp"

#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>

namespace ezWebSockify{
	namespace beast = boost::beast;         // from <boost/beast.hpp>
	namespace websocket = beast::websocket; // from <boost/beast/websocket.hpp>
}

#include "wsServer.hpp"

max_stars_repo_name: frachop/ezWebSockify

max_issues_repo_name: frachop/ezWebSockify

max_forks_repo_name: frachop/ezWebSockify


text:
/*
 * This file is part of the DUDS project. It is subject to the BSD-style
 * license terms in the LICENSE file found in the top-level directory of this
 * distribution and at https://github.com/jjackowski/duds/blob/master/LICENSE.
 * No part of DUDS, including this file, may be copied, modified, propagated,
 * or distributed except according to the terms contained in the LICENSE file.
 *
 * Copyright (C) 2017  Jeff Jackowski
 */
#ifndef PLANETARY_HPP
#define PLANETARY_HPP

#include <duds/time/planetary/LeapSeconds.hpp>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <duds/data/GenericValue.hpp>

namespace duds {

/**
 * Items that deal with time, a surprisingly difficult and annoying subject.
 * So difficult and annoying, I opted against an implementation close to
 * exitsing ones because those implementations and their conventions seem
 * to be part of the problem. Seconds will not be redefined, solar days
 * do not have a constant length, and a one second point in time will not
 * occur twice. The system here lives within that reality.
 * @author  Jeff Jackowski
 */
namespace time {

namespace planetary {

using std::unique_ptr;
/*
class PlanetaryTime {
	LeapSeconds leaps;
	int days;
};
*/

// move to earth.hpp
/**
 * Terran time stuffs.
 */
class Earth {
	LeapBounds<> bound;
public:
	Earth();
	LeapSeconds leaps;
	static const boost::gregorian::date &dateZero();
	static const boost::posix_time::ptime &timeZero();
	/**
	 * Makes the Earth planetary time object using the given zoneinfo file for
	 * data on leap seconds.
	 */
	static void make(const std::string &path = "/usr/share/zoneinfo-leaps/UTC");
	typedef duds::time::interstellar::Femtoseconds duration;
	typedef duration::rep rep;
	typedef duration::period period;
	typedef std::chrono::time_point<Earth, duration> time_point;
	static constexpr bool is_steady = false;
	time_point now() noexcept {
		// wrong
		return time_point(std::chrono::duration_cast<duration, rep, period>(
			std::chrono::system_clock::now().time_since_epoch()));
	}
	/**
	 * Converts from IST to UTC and provides a date result.
	 */
	boost::gregorian::date date(
		const duds::time::interstellar::SecondTime &t
	) const;
	template <class ISTime>
	/**
	 * Converts from IST to UTC and provides a date result.
	 */
	boost::gregorian::date date(const ISTime &t) const {
		return date(interstellar::SecondTime(
			std::chrono::duration_cast<interstellar::Seconds>(
				t.time_since_epoch()
			)
		));
	}
	/**
	 * Converts from IST to UTC and provides a std::time_t result.
	 */
	std::time_t timeUtc(
		const duds::time::interstellar::SecondTime &t
	) const;
	template <class ISTime>
	/**
	 * Converts from IST to UTC and provides a std::time_t result.
	 */
	std::time_t timeUtc(const ISTime &t) const {
		return timeUtc(interstellar::SecondTime(
			std::chrono::duration_cast<interstellar::Seconds>(
				t.time_since_epoch()
			)
		));
	}

	/**
	 * Converts from UTC to TAI and provides a date result.
	 */
	boost::gregorian::date dateUtcToTai(
		const duds::time::interstellar::SecondTime &t
		) const;
	template <class ISTime>
	/**
	 * Converts from IST to UTC and provides a date result.
	 */
	boost::gregorian::date dateUtcToTai(const ISTime &t) const {
		return dateUtcToTai(interstellar::SecondTime(
			std::chrono::duration_cast<interstellar::Seconds>(
				t.time_since_epoch()
			)
		));
	}
	/**
	 * Converts from IST to UTC and provides a ptime result.
	 */
	boost::posix_time::ptime posix(
		const duds::time::interstellar::MilliTime &t
	) const;
	template <class ISTime>
	/**
	 * Converts from IST to UTC and provides a ptime result.
	 */
	boost::posix_time::ptime posix(const ISTime &t) const {
		return posix(duds::time::interstellar::MilliTime(
			std::chrono::duration_cast<duds::time::interstellar::Milliseconds>(
				t.time_since_epoch()
			)
		));
	}
	/**
	 * Converts from UTC to TAI and provides a ptime result.
	 */
	boost::posix_time::ptime posixUtcToTai(
		const duds::time::interstellar::MilliTime &t
	) const;
	template <class ISTime>
	/**
	 * Converts from UTC to TAI and provides a ptime result.
	 */
	boost::posix_time::ptime posixUtcToTai(const ISTime &t) const {
		return posixUtcToTai(duds::time::interstellar::MilliTime(
			std::chrono::duration_cast<duds::time::interstellar::Milliseconds>(
				t.time_since_epoch()
			)
		));
	}
	// UTC

	/**
	 * Adds leap seconds to the given time in UTC, resulting in TAI.
	 * @param time  The time that needs leap seconds.
	 */
	template <class Clock, class Duration>
	void addLeapSeconds(
		duds::time::interstellar::TimePoint<Clock, Duration> &time
	) {
		//duds::time::interstellar::SecondTime comp = time;
		if (!bound.within(time)) {
			bound = leaps.getLeapBounds(time);
		}
		assert(bound.within(time));
		time += bound.leaps;
	}

	/**
	 * Converts a Gregorian calendar date into one of the time formats defined
	 * inside the duds::time::interstellar namespace.
	 */
	template <class ISTime>
	void date(ISTime &dest, const boost::gregorian::date &src) {
		dest = duds::time::interstellar::SecondTime(
			duds::time::interstellar::Seconds((src - dateZero()).days() * 86400)
		);
		duds::time::interstellar::Seconds ls = leaps.leapSeconds(dest);
		dest += ls;
	}
	/**
	 * Converts a POSIX time into one of the time formats defined
	 * inside the duds::time::interstellar namespace.
	 */
	template <class ISTime>
	void time(ISTime &dest, const boost::posix_time::ptime &src) {
		dest = duds::time::interstellar::MilliTime(
			duds::time::interstellar::Milliseconds(
				(src - timeZero()).total_milliseconds()
			)
		);
		duds::time::interstellar::Seconds ls = leaps.leapSeconds(dest);
		dest += ls;
	}
};

extern unique_ptr<Earth> earth;

/**
 * Converts without applying any modification to the time, so if the input
 * is in TAI, the result will be, too. Not a member of Earth to emphasize that
 * this is just a type conversion that does no adjustment of the time.
 */
template <class ISTime>
inline boost::gregorian::date ToDate(const ISTime &t) {
	return Earth::dateZero() + boost::gregorian::days(
		std::chrono::duration_cast<duds::time::interstellar::Seconds>(
			t.time_since_epoch()
		).count()
	);
}

/**
 * Converts without applying any modification to the time, so if the input
 * is in TAI, the result will be, too. Not a member of Earth to emphasize that
 * this is just a type conversion that does no adjustment of the time.
 */
template <class ISTime>
inline boost::posix_time::ptime ToPosix(const ISTime &t) {
	return Earth::timeZero() + boost::posix_time::milliseconds(
		std::chrono::duration_cast<duds::time::interstellar::Milliseconds>(
			t.time_since_epoch()
		).count()
	);
}

} } }

#endif        //  #ifndef PLANETARY_HPP

max_stars_repo_name: jjackowski/duds

max_issues_repo_name: jjackowski/duds

max_forks_repo_name: jjackowski/duds


text:
/*
 * Copyright (C) Alex Nekipelov (alex@nekipelov.net)
 * License: MIT
 */

#include <fstream>
#include <iostream>

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

#include <hserv/httpserver.h>
#include <hserv/request.h>
#include <hserv/response.h>

#ifdef _MSC_VER
#define strcasecmp stricmp
#endif

using namespace hserv;
namespace fs = boost::filesystem;

std::string detectMimeType(const std::string &fileName);
void handler(const boost::shared_ptr<Context> &context);
void handleNextChunk(const boost::shared_ptr<Context> &context, boost::shared_ptr<std::ifstream> in);

int main(int, char**)
{
    int port = 3000;
    std::string address = "0.0.0.0";
    boost::asio::io_service ioService;

    try
    {
        std::cout << "--> Test HTTP Server started on "
                  << "http://" << address << ":" << port
                  << std::endl;

        HttpServer server(ioService, address, port, handler);

        server.run();
        ioService.run();
    }
    catch (std::exception &e)
    {
        std::cerr << "exception: " << e.what() << "\n";
    }

    return 0;
}

void handler(const boost::shared_ptr<Context> &context)
{

    std::cout << context->request().method() << " "
              << context->request().uri() << std::endl;

    std::string fileName;
    const std::string &uri = context->request().uri();

    if( uri.size() < 2 ) { // if url == '/' || url.empty()
        fileName = "index.html";
    }
    else {
        fileName.assign( uri.begin() + 1, uri.end() );

        if( fileName[ fileName.size() - 1 ] == '/'  )
            fileName += "index.html";
        else if( fs::is_directory(fileName) )
            fileName += "/index.html";
    }

    boost::shared_ptr<std::ifstream>
            in(new std::ifstream(fileName.c_str(), std::ios::in | std::ios::binary));

    if( in->good() ) {
        size_t size = fs::file_size(fileName);
        const std::string &s = boost::lexical_cast<std::string>(size);

        context->response().setStatus(Response::Ok);
        context->response().addHeader("Content-Type", detectMimeType(fileName));
        context->response().addHeader("Content-Length", s);

        handleNextChunk(context, in);
    }
    else {
        context->response() = Response::makeResponse(Response::NotFound);
        context->asyncDone();
    }
}

void handleNextChunk(const boost::shared_ptr<Context> &context, boost::shared_ptr<std::ifstream> in)
{
    char buff[4096];

    if( in->read(buff, sizeof(buff)).gcount() > 0 ) {
        context->response().setContent(buff, in->gcount());
        context->asyncPartialSend(boost::bind(handleNextChunk, boost::ref(context), in));
    }
    else {
        context->asyncDone();
    }
}

struct ContentMap {
    const char *ext;
    const char *mime;
    const char *encoding;
    const char *encoding11;
};

ContentMap contentMap[] = {
    { ".html",      "text/html",                    "",             "" },
    { ".htm",       "text/html",                    "",             "" },
    { ".js",        "text/javascript",              "",             "" },
    { ".gif",       "image/gif",                    "",             "" },
    { ".jpeg",      "image/jpeg",                   "",             "" },
    { ".jpg",       "image/jpeg",                   "",             "" },
    { ".jpe",       "image/jpeg",                   "",             "" },
    { ".png",       "image/png",                    "",             "" },
    { ".mp3",       "audio/mpeg",                   "",             "" },
    { ".css",       "text/css",                     "",             "" },
    { ".txt",       "text/plain",                   "",             "" },
    { ".swf",       "application/x-shockwave-flash","",             "" },
    { ".dcr",       "application/x-director",       "",             "" },
    { ".pac",       "application/x-ns-proxy-autoconfig", "",        "" },
    { ".pa",        "application/x-ns-proxy-autoconfig", "",        "" },
    { ".tar",       "multipart/x-tar",              "",             "" },
    { ".gtar",      "multipart/x-gtar",             "",             "" },
    { ".tar.Z",     "multipart/x-tar",              "x-compress",   "compress" },
    { ".tar.gz",    "multipart/x-tar",              "x-gzip",       "gzip" },
    { ".taz",       "multipart/x-tar",              "x-gzip",       "gzip" },
    { ".tgz",       "multipart/x-tar",              "x-gzip",       "gzip" },
    { ".tar.z",     "multipart/x-tar",              "x-pack",       "x-pack" },
    { ".Z",         "application/x-compress",       "x-compress",   "compress" },
    { ".gz",        "application/x-gzip",           "x-gzip",       "gzip" },
    { ".z",         "unknown",                      "x-pack",       "x-pack" },
    { ".bz2",       "application/x-bzip2",          "x-bzip2",      "x-bzip2" },
    { ".ogg",       "application/x-ogg",            "",             "" },
    { ".xbel",      "text/xml",                     "",             "" },
    { ".xml",       "text/xml",                     "",             "" },
    { ".xsl",       "text/xml",                     "",             "" },
    { ".hqx",       "application/mac-binhex40",     "",             "" },
    { ".cpt",       "application/mac-compactpro",   "",             "" },
    { ".doc",       "application/msword",           "",             "" },
    { ".bin",       "application/octet-stream",     "",             "" },
    { ".dms",       "application/octet-stream",     "",             "" },
    { ".lha",       "application/octet-stream",     "",             "" },
    { ".lzh",       "application/octet-stream",     "",             "" },
    { ".exe",       "application/octet-stream",     "",             "" },
    { ".class",     "application/octet-stream",     "",             "" },
    { ".oda",       "application/oda",              "",             "" },
    { ".pdf",       "application/pdf",              "",             "" },
    { ".ai",        "application/postscript",       "",             "" },
    { ".eps",       "application/postscript",       "",             "" },
    { ".ps",        "application/postscript",       "",             "" },
    { ".ppt",       "application/powerpoint",       "",             "" },
    { ".rtf",       "application/rtf",              "",             "" },
    { ".bcpio",     "application/x-bcpio",          "",             "" },
    { ".torrent",   "application/x-bittorrent",     "",             "" },
    { ".vcd",       "application/x-cdlink",         "",             "" },
    { ".cpio",      "application/x-cpio",           "",             "" },
    { ".csh",       "application/x-csh",            "",             "" },
    { ".dir",       "application/x-director",       "",             "" },
    { ".dxr",       "application/x-director",       "",             "" },
    { ".dvi",       "application/x-dvi",            "",             "" },
    { ".hdf",       "application/x-hdf",            "",             "" },
    { ".cgi",       "application/x-httpd-cgi",      "",             "" },
    { ".skp",       "application/x-koan",           "",             "" },
    { ".skd",       "application/x-koan",           "",             "" },
    { ".skt",       "application/x-koan",           "",             "" },
    { ".skm",       "application/x-koan",           "",             "" },
    { ".latex",     "application/x-latex",          "",             "" },
    { ".mif",       "application/x-mif",            "",             "" },
    { ".nc",        "application/x-netcdf",         "",             "" },
    { ".cdf",       "application/x-netcdf",         "",             "" },
    { ".patch",     "application/x-patch",          "",             "" },
    { ".sh",        "application/x-sh",             "",             "" },
    { ".shar",      "application/x-shar",           "",             "" },
    { ".sit",       "application/x-stuffit",        "",             "" },
    { ".sv4cpio",   "application/x-sv4cpio",        "",             "" },
    { ".sv4crc",    "application/x-sv4crc",         "",             "" },
    { ".tar",       "application/x-tar",            "",             "" },
    { ".tcl",       "application/x-tcl",            "",             "" },
    { ".tex",       "application/x-tex",            "",             "" },
    { ".texinfo",   "application/x-texinfo",        "",             "" },
    { ".texi",      "application/x-texinfo",        "",             "" },
    { ".t",         "application/x-troff",          "",             "" },
    { ".tr",        "application/x-troff",          "",             "" },
    { ".roff",      "application/x-troff",          "",             "" },
    { ".man",       "application/x-troff-man",      "",             "" },
    { ".me",        "application/x-troff-me",       "",             "" },
    { ".ms",        "application/x-troff-ms",       "",             "" },
    { ".ustar",     "application/x-ustar",          "",             "" },
    { ".src",       "application/x-wais-source",    "",             "" },
    { ".zip",       "application/zip",              "",             "" },
    { ".au",        "audio/basic",                  "",             "" },
    { ".snd",       "audio/basic",                  "",             "" },
    { ".mpga",      "audio/mpeg",                   "",             "" },
    { ".mp2",       "audio/mpeg",                   "",             "" },
    { ".aif",       "audio/x-aiff",                 "",             "" },
    { ".aiff",      "audio/x-aiff",                 "",             "" },
    { ".aifc",      "audio/x-aiff",                 "",             "" },
    { ".ram",       "audio/x-pn-realaudio",         "",             "" },
    { ".rpm",       "audio/x-pn-realaudio-plugin",  "",             "" },
    { ".ra",        "audio/x-realaudio",            "",             "" },
    { ".wav",       "audio/x-wav",                  "",             "" },
    { ".pdb",       "chemical/x-pdb",               "",             "" },
    { ".xyz",       "chemical/x-pdb",               "",             "" },
    { ".ief",       "image/ief",                    "",             "" },
    { ".tiff",      "image/tiff",                   "",             "" },
    { ".tif",       "image/tiff",                   "",             "" },
    { ".ras",       "image/x-cmu-raster",           "",             "" },
    { ".pnm",       "image/x-portable-anymap",      "",             "" },
    { ".pbm",       "image/x-portable-bitmap",      "",             "" },
    { ".pgm",       "image/x-portable-graymap",     "",             "" },
    { ".ppm",       "image/x-portable-pixmap",      "",             "" },
    { ".rgb",       "image/x-rgb",                  "",             "" },
    { ".xbm",       "image/x-xbitmap",              "",             "" },
    { ".xpm",       "image/x-xpixmap",              "",             "" },
    { ".xwd",       "image/x-xwindowdump",          "",             "" },
    { ".ico",       "image/x-icon",					"",             "" },
    { ".rtx",       "text/richtext",                "",             "" },
    { ".tsv",       "text/tab-separated-values",    "",             "" },
    { ".etx",       "text/x-setext",                "",             "" },
    { ".sgml",      "text/x-sgml",                  "",             "" },
    { ".sgm",       "text/x-sgml",                  "",             "" },
    { ".mpeg",      "video/mpeg",                   "",             "" },
    { ".mpg",       "video/mpeg",                   "",             "" },
    { ".mpe",       "video/mpeg",                   "",             "" },
    { ".qt",        "video/quicktime",              "",             "" },
    { ".mov",       "video/quicktime",              "",             "" },
    { ".avi",       "video/x-msvideo",              "",             "" },
    { ".movie",     "video/x-sgi-movie",            "",             "" },
    { ".ice",       "x-conference/x-cooltalk",      "",             "" },
    { ".wrl",       "x-world/x-vrml",               "",             "" },
    { ".vrml",      "x-world/x-vrml",               "",             "" },
};

std::string detectMimeType(const std::string &fileName)
{
    std::size_t lastSlashPos = fileName.rfind('/');
    std::size_t lastDotPos = fileName.rfind('.');
    std::string extension;

    if (lastDotPos != std::string::npos && (lastDotPos > lastSlashPos || lastSlashPos == std::string::npos) )
    {
        extension = fileName.substr(lastDotPos);

        ContentMap *it = &contentMap[0], *end = &contentMap[sizeof(contentMap) / sizeof(ContentMap)];

        for(; it != end; ++it)
        {
            if( strcasecmp(extension.c_str(), it->ext) == 0 )
                return it->mime;
        }
    }

    static std::string defaultMimeType = "application/octet-stream";
    return defaultMimeType;
}

max_stars_repo_name: nekipelov/hserv

max_issues_repo_name: nekipelov/hserv

max_forks_repo_name: nekipelov/hserv


text:
/**
 * io.cpp
 *
 * 2021 Gabriel Moreira
 *
 * https://github.com/gabmoreira/maks
 *
 * This software and the related documents  are provided as  is,  with no express
 * or implied  warranties,  other  than those  that are  expressly stated  in the
 * License.
 *
 * Copyright © 2021 Gabriel Moreira. All rights reserved.
 */

#include <iostream>
#include <string>
#include <vector>
#include <fstream>

#include <Eigen/Geometry>

#include "io.hpp"

using std::vector;
using std::string;
using std::stod;
using std::stoi;

using Eigen::Quaterniond;
using Eigen::Vector3d;
using Eigen::VectorXi;
using Eigen::Matrix3d;
using Eigen::MatrixXd;
using Eigen::Ref;

#define G2O_PRECISION 15

/**
 * Splits a string based on a delimiter.
 *
 * @param str Input string to be split.
 * @param delim Input string delimiter.
 * @return vector of tokens.
 */
vector<string> strSplit(const string& str, const string& delim) {
    vector<string> tokens;
    size_t prev = 0, pos = 0;
    do {
        pos = str.find(delim, prev);
        if (pos == string::npos)
            pos = str.length();
        string token = str.substr(prev, pos-prev);
        if (!token.empty())
            tokens.push_back(token);
        prev = pos + delim.length();
    } while (pos < str.length() && prev < str.length());

    return tokens;
};

/**
 * Reads g2o file.
 *
 * @param path (input) char*  - g2o file name.
 * @param node_i (output) Eigen::VectorXi - node indices.
 * @param node_r (output) Eigen::MatrixXd - SO(3) node rotations.
 * @param node_t (output) Eigen::MatrixXd - node translations.
 * @param edge_i (output) Eigen::VectorXi - edge indices (from).
 * @param edge_j (output) Eigen::VectorXi - edge indices (to).
 * @param edge_r (output) Eigen::MatrixXd - SO(3) edge rotations.
 * @param edge_t (output) Eigen::MatrixXd - edge translations.
 * @param num_nodes (output) int - number of nodes loaded.
 * @param num_edges (output) int - number of edges loaded.
 */
void readG2O(const char*   path,
             Ref<VectorXi> node_i,
             Ref<MatrixXd> node_r,
             Ref<MatrixXd> node_t,
             Ref<VectorXi> edge_i,
             Ref<VectorXi> edge_j,
             Ref<MatrixXd> edge_r,
             Ref<MatrixXd> edge_t,
             int&          num_nodes,
             int&          num_edges) {

    std::ifstream infile(path);
    if(!infile)
        return;

    string edge_tag = "EDGE_SE3:QUAT";
    string node_tag = "VERTEX_SE3:QUAT";

    num_nodes = 0;
    num_edges = 0;

    string line;
    while (std::getline(infile, line)) {
        vector<string> tokens = strSplit(line, " ");
        string tag = tokens[0];

        if (0 == tag.compare(edge_tag)) {
            int edge_i_id = stoi(tokens[1]);
            int edge_j_id = stoi(tokens[2]);

            // Edge translation
            Vector3d t( stod(tokens[3]), stod(tokens[4]), stod(tokens[5]) );

            // Edge quaternion
            Quaterniond q( stod(tokens[9]), stod(tokens[6]), stod(tokens[7]), stod(tokens[8]) );

            edge_i(num_edges) += edge_i_id;
            edge_j(num_edges) += edge_j_id;
            edge_r.block<3,3>(0,num_edges*3) += q.normalized().toRotationMatrix();
            edge_t.block<3,1>(0,num_edges) += t;
            num_edges++;

        } else if (0 == tag.compare(node_tag)) {
            int node_id = stoi(tokens[1]);

            // Node translation
            Vector3d t( stod(tokens[2]), stod(tokens[3]), stod(tokens[4]) );

            // Node quaternion
            Quaterniond q( stod(tokens[8]), stod(tokens[5]), stod(tokens[6]), stod(tokens[7]) );

            node_i(num_nodes) += node_id;
            node_r.block<3,3>(0,num_nodes*3) += q.normalized().toRotationMatrix();
            node_t.block<3,1>(0,num_nodes) += t;
            num_nodes++;
        };
    };
};

/**
 * Reads edge rotations from g2o file.
 *
 * @param path (input) char*  - g2o file name.
 * @param edge_i (output) Eigen::VectorXi - edge id (from).
 * @param edge_j (output) Eigen::VectorXi - edge id (to).
 * @param edge_r (output) Eigen::MatrixXd - Row block matrix containing SO(3) rotations.
 * @param num_edges (output) int - number of edges.
 */
void readG2O(const char*          path,
             Eigen::Ref<VectorXi> edge_i,
             Eigen::Ref<VectorXi> edge_j,
             Eigen::Ref<MatrixXd> edge_r,
             int&                 num_edges) {

    std::ifstream infile(path);
    if(!infile)
        return;

    string edge_tag = "EDGE_SE3:QUAT";

    num_edges = 0;

    string line;
    while (std::getline(infile, line)) {
        vector<string> tokens = strSplit(line, " ");
        string tag = tokens[0];

        if (0 == tag.compare(edge_tag)) {
            int edge_i_id = stoi(tokens[1]);
            int edge_j_id = stoi(tokens[2]);

            /* Edge quaternion */
            Quaterniond q( stod(tokens[9]), stod(tokens[6]), stod(tokens[7]), stod(tokens[8]) );

            edge_i(num_edges) += edge_i_id;
            edge_j(num_edges) += edge_j_id;
            edge_r.block<3,3>(0,num_edges*3) += q.normalized().toRotationMatrix();
            num_edges++;
        };
    };
};

void writeG2O(const char* filename,
              const vector<int>&         node_i,
              const vector<Quaterniond>& node_q,
              const vector<Vector3d>&    node_t,
              const vector<int>&         edge_i,
              const vector<int>&         edge_j,
              const vector<Quaterniond>& edge_q,
              const vector<Vector3d>&    edge_t) {

    int num_nodes = (int) node_i.size();
    int num_edges = (int) edge_i.size();

    string filepath = string(filename) + ".g2o";

    std::ostringstream buffer;
    buffer.clear();

    /* Write node data */
    for (int i = 0; i < num_nodes; ++i) {
        /* Write tag */
        buffer << "VERTEX_SE3:QUAT";

        /* Write node id */
        buffer << " " << std::to_string(node_i[i]);

        /* Write node translation */
        buffer << " " << std::fixed << std::setprecision(G2O_PRECISION) << node_t[i](0); // x
        buffer << " " << std::fixed << std::setprecision(G2O_PRECISION) << node_t[i](1); // y
        buffer << " " << std::fixed << std::setprecision(G2O_PRECISION) << node_t[i](2); // z

        /* Write node quaternion */
        buffer << " " << std::fixed << std::setprecision(G2O_PRECISION) << node_q[i].x();           // qx
        buffer << " " << std::fixed << std::setprecision(G2O_PRECISION) << node_q[i].y();           // qy
        buffer << " " << std::fixed << std::setprecision(G2O_PRECISION) << node_q[i].z();           // qz
        buffer << " " << std::fixed << std::setprecision(G2O_PRECISION) << node_q[i].w() << "\n";   // qw
    };

    /* Write edge data */
    for (int i = 0; i < num_edges; ++i) {
        /* Write tag */
        buffer << "EDGE_SE3:QUAT";

        /* Write edge ids */
        buffer << " " << std::to_string(edge_i[i]);
        buffer << " " << std::to_string(edge_j[i]);

        /* Write node translation */
        buffer << " " << std::fixed << std::setprecision(G2O_PRECISION) << edge_t[i](0); // x
        buffer << " " << std::fixed << std::setprecision(G2O_PRECISION) << edge_t[i](1); // y
        buffer << " " << std::fixed << std::setprecision(G2O_PRECISION) << edge_t[i](2); // z

        /* Write node quaternion */
        buffer << " " << std::fixed << std::setprecision(G2O_PRECISION) << edge_q[i].x();           // qx
        buffer << " " << std::fixed << std::setprecision(G2O_PRECISION) << edge_q[i].y();           // qy
        buffer << " " << std::fixed << std::setprecision(G2O_PRECISION) << edge_q[i].z();           // qz
        buffer << " " << std::fixed << std::setprecision(G2O_PRECISION) << edge_q[i].w() << "\n";   // qw
    };

    std::ofstream outfile;
    outfile.open(filepath);
    if(!outfile) {
        return;
    };

    outfile << buffer.str();
    outfile.close();
    printf("Pose graph saved to %s\n", filepath.c_str());
};

max_stars_repo_name: rjanvier/maks

max_issues_repo_name: rjanvier/maks

max_forks_repo_name: rjanvier/maks


text:
#pragma once

#include <boost/lexical_cast.hpp>

#include <optional>
#include <type_traits>

#include "all_type_variant.hpp"
#include "null_value.hpp"
#include "resolve_type.hpp"

/**
 * This file defines the following casting functions that guarantee **lossless** conversion between data types and
 * return std::nullopt if no lossless conversion was possible.
 *      Target lossless_cast<Target>(Source source)
 *      Target lossless_variant_cast<Target>(AllTypeVariant source)
 *      AllTypeVariant lossless_variant_cast(Source source, DataType target)
 *
 * "Lossless" means just that: No information must be lost duri<ng casting. Typical lossful operations would be
 *      - float-to-int casts with the float having a non-zero fractional part
 *      - long-to-int casts where the long is not inside [MIN_INT, MAX_INT]
 *      - string-to-int where the string contained no number, or a number > MAX_INT.
 *      - double-to-float where the significand of the double has bits set that cannot be represented in float
 *
 * Whenever possible you should use these casts over "comfortable" casts such as static_cast or boost::lexical_cast.
 * Those might incur information loss and might thus introduce bugs. See #1306, #1525.
 */

namespace opossum {

// Identity
template <typename Target, typename Source>
std::enable_if_t<std::is_same_v<Target, std::decay_t<Source>>, std::optional<Target>> lossless_cast(Source&& source) {
  return std::forward<Source>(source);
}

// int64_t to int32_t
template <typename Target, typename Source>
std::enable_if_t<std::is_same_v<int64_t, Source> && std::is_same_v<int32_t, Target>, std::optional<Target>>
lossless_cast(const Source& source) {
  if (source < std::numeric_limits<int32_t>::min() || source > std::numeric_limits<int32_t>::max()) {
    return std::nullopt;
  } else {
    return static_cast<Target>(source);
  }
}

// int32_t to int64_t
template <typename Target, typename Source>
std::enable_if_t<std::is_same_v<int32_t, Source> && std::is_same_v<int64_t, Target>, std::optional<Target>>
lossless_cast(const Source& source) {
  return static_cast<Target>(source);
}

// NULL to anything but NULL
template <typename Target, typename Source>
std::enable_if_t<std::is_same_v<NullValue, Source> && !std::is_same_v<NullValue, Target>, std::optional<Target>>
lossless_cast(const Source& source) {
  return std::nullopt;
}

// Anything but NULL to NULL
template <typename Target, typename Source>
std::enable_if_t<!std::is_same_v<NullValue, Source> && std::is_same_v<NullValue, Target>, std::optional<Target>>
lossless_cast(const Source& source) {
  return std::nullopt;
}

// String to integral
template <typename Target, typename Source>
std::enable_if_t<std::is_same_v<pmr_string, Source> && std::is_integral_v<Target>, std::optional<Target>> lossless_cast(
    const Source& source) {
  static_assert(std::is_same_v<int32_t, Target> || std::is_same_v<int64_t, Target>, "Expected int32_t or int64_t");

  Target result{};

  // try_lexical_convert() covers, e.g., string with integrals > INT_MAX.
  if (boost::conversion::detail::try_lexical_convert(source, result)) {
    return result;
  } else {
    return std::nullopt;
  }
}

// String to floating point
// NOT SUPPORTED: Some strings (e.g., "5.5") have lossless float representations, others (e.g., "5.3") do not. Allowing
//                string to floating point conversion just sets up confusion why one string was convertible and another
//                was not.
template <typename Target, typename Source>
std::enable_if_t<std::is_same_v<pmr_string, Source> && std::is_floating_point_v<Target>, std::optional<Target>>
lossless_cast(const Source& source) {
  return std::nullopt;
}

// integral to string
template <typename Target, typename Source>
std::enable_if_t<std::is_integral_v<Source> && std::is_same_v<pmr_string, Target>, std::optional<Target>> lossless_cast(
    const Source& source) {
  return pmr_string{std::to_string(source)};
}

// Floating point to string
// NOT SUPPORTED: Lossless floating point to string conversion is too obscure and rarely needed to justify supporting
//                it.
//                Lossless floating point to string conversion might be possible in theory, but standard library
//                functions do not openly support such a conversion
template <typename Target, typename Source>
std::enable_if_t<std::is_floating_point_v<Source> && std::is_same_v<pmr_string, Target>, std::optional<Target>>
lossless_cast(const Source& source) {
  return std::nullopt;
}

// integral to floating point
template <typename Target, typename Source>
std::enable_if_t<std::is_integral_v<Source> && std::is_floating_point_v<Target>, std::optional<Target>> lossless_cast(
    const Source& source) {
  auto floating_point = static_cast<Target>(source);
  auto integral = static_cast<Source>(floating_point);
  if (source == integral) {
    return floating_point;
  } else {
    return std::nullopt;
  }
}

// floating point type to 32/64 bit integral type
template <typename Target, typename Source>
std::enable_if_t<std::is_floating_point_v<Source> &&
                     (std::is_same_v<Target, int32_t> || std::is_same_v<Target, int64_t>),
                 std::optional<Target>>
lossless_cast(const Source& source) {
  static_assert(std::numeric_limits<float>::is_iec559, "IEEE 754 floating point representation expected.");

  auto integral_part = Source{};

  // No lossless float-to-int conversion possible if the source float has a fractional part
  if (std::modf(source, &integral_part) != 0.0) {
    return std::nullopt;
  }

  // Check the floating point value against explicitly defined boundary values. The boundary values are the
  // the closest-to-zero floating point values that are NOT representable in the given integral type.
  // (Note: We evaluated multiple approaches to identify whether a float/double is representable as a int32/64. None
  //        of them was really portable/readable/"clean". The bounding values approach at least makes intuitive sense.)
  if constexpr (std::is_same_v<Source, float> && std::is_same_v<Target, int32_t>) {
    if (source >= 2'147'483'648.0f || source <= -2'147'483'904.0f) return std::nullopt;
  } else if constexpr (std::is_same_v<Source, double> && std::is_same_v<Target, int32_t>) {
    if (source >= 2'147'483'648.0 || source <= -2'147'483'649.0) return std::nullopt;
  } else if constexpr (std::is_same_v<Source, float> && std::is_same_v<Target, int64_t>) {
    if (source >= 9'223'372'036'854'775'808.0f || source <= -9'223'373'136'366'403'584.0f) return std::nullopt;
  } else if constexpr (std::is_same_v<Source, double> && std::is_same_v<Target, int64_t>) {
    if (source >= 9'223'372'036'854'775'808.0 || source <= -9'223'372'036'854'777'856.0) return std::nullopt;
  }

  return static_cast<Target>(source);
}

// float to double
template <typename Target, typename Source>
std::enable_if_t<std::is_same_v<float, Source> && std::is_same_v<double, Target>, std::optional<Target>> lossless_cast(
    const Source& source) {
  return static_cast<Target>(source);
}

// double to float
template <typename Target, typename Source>
std::enable_if_t<std::is_same_v<double, Source> && std::is_same_v<float, Target>, std::optional<Target>> lossless_cast(
    const Source& source) {
  static_assert(std::numeric_limits<float>::is_iec559, "IEEE 754 floating point representation expected.");

  // Check the source double against the highest and lowest double that can still be converted to a float
  // Casting any double greater/less than the respective bound to float is UB according to UBSan
  if (source > 340282346638528859811704183484516925440.0 || source < -340282346638528859811704183484516925440.0) {
    return std::nullopt;
  } else {
    if (static_cast<float>(source) == source) {
      return static_cast<float>(source);
    } else {
      return std::nullopt;
    }
  }
}

template <typename Target>
std::optional<Target> lossless_variant_cast(const AllTypeVariant& variant) {
  std::optional<Target> result;

  const auto source_data_type = data_type_from_all_type_variant(variant);

  // Safe casting from NULL to NULL is always NULL. (Cannot be handled below as resolve_data_type()
  // doesn't resolve NULL)
  if constexpr (std::is_same_v<Target, NullValue>) {
    if (source_data_type == DataType::Null) {
      return NullValue{};
    }
  }

  // Safe casting between NULL and non-NULL type is not possible. (Cannot be handled below as resolve_data_type()
  // doesn't resolve NULL)
  if ((source_data_type == DataType::Null) != std::is_same_v<Target, NullValue>) {
    return std::nullopt;
  }

  resolve_data_type(data_type_from_all_type_variant(variant), [&](auto source_data_type_t) {
    using SourceDataType = typename decltype(source_data_type_t)::type;
    result = lossless_cast<Target>(boost::get<SourceDataType>(variant));
  });

  return result;
}

std::optional<AllTypeVariant> lossless_variant_cast(const AllTypeVariant& variant, DataType target_data_type);

}  // namespace opossum

max_stars_repo_name: hyrise-mp/hyrise

max_issues_repo_name: hyrise-mp/hyrise

max_forks_repo_name: hyrise-mp/hyrise


text:
#include "get_floor_fHf.h"
#include "ransac_floor_fHf.h"
#include "ransac_data.h"
#include "randperm.h"
#include <Eigen/Geometry>
#include <vector>

using namespace Eigen;

RansacData ransac_floor_fHf(MatrixXd &p1, MatrixXd &p2, Matrix3d &R1, Matrix3d &R2, int nbr_iter, double thresh)
{
    // Init RANSAC loop
    PoseData best_posedata;
    int best_nbr_inliers = 0;
    VectorXi best_inliers;
    best_inliers.setZero();
    int nbr_pts = p1.cols();

    MatrixXd reproj1(2, nbr_pts);
    MatrixXd reproj2(2, nbr_pts);
    MatrixXd reproj(4, nbr_pts);
    VectorXd reproj_mean(nbr_pts);
    MatrixXd H(3,3);
    VectorXi inliers(nbr_pts);
    int nbr_inliers;
    VectorXi history(nbr_iter);

    int nbr_pts_minimal = 3;

    for (int i = 0; i < nbr_iter; i++) {
        std::vector<int> rands = randperm(nbr_pts_minimal, nbr_pts);
        MatrixXd x1(3, nbr_pts_minimal);
        MatrixXd x2(3, nbr_pts_minimal);
        for (int j = 0; j < nbr_pts_minimal; j++) {
            x1.col(j) << p1.col(rands[j]);
            x2.col(j) << p2.col(rands[j]);
        }

        // Get pose
        MatrixXd x1h(2,3);
        MatrixXd x2h(2,3);
        x1h << x1.colwise().hnormalized();
        x2h << x2.colwise().hnormalized();

        PoseData posedata = get_floor_fHf(x1h, x2h, R1, R2);

        // Compute reprojection error, and compare to other solutions.
        H = posedata.homography;
        reproj1 = p2.colwise().hnormalized() - (H * p1).colwise().hnormalized();
        reproj2 = p1.colwise().hnormalized() - (H.lu().solve(p2)).colwise().hnormalized();
        reproj << reproj1.cwiseAbs(), reproj2.cwiseAbs();
        reproj_mean = reproj.colwise().mean().array();

        inliers = (reproj_mean.array() < thresh).cast<int>();
        nbr_inliers = inliers.sum();

        if (best_nbr_inliers < nbr_inliers) {
            best_posedata = posedata;
            best_nbr_inliers = nbr_inliers;
            best_inliers = inliers;
        }
        history(i) = best_nbr_inliers;

    }

    RansacData ransac_data;
    ransac_data.posedata = best_posedata;
    ransac_data.inliers = best_inliers;
    ransac_data.history = history;

    return ransac_data;
}

// ---------------- //
// MATLAB interface //
// ---------------- //
#ifdef MATLAB_MEX_FILE
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    if (nrhs != 6) {
        mexErrMsgIdAndTxt("ransac_floor_fHf:nrhs", "Six input arguments are required.");
    }
    if (nlhs != 4) {
        mexErrMsgIdAndTxt("ransac_floor_fHf:nlhs", "Four output arguments are required.");
    }
    if (!mxIsDouble(prhs[0]) || mxIsComplex(prhs[0])) {
        mexErrMsgIdAndTxt("ransac_floor_fHf:notDouble", "Input data must be type double.");
    }
    if(mxGetNumberOfElements(prhs[0]) % 3 != 0
       && mxGetNumberOfElements(prhs[0]) != mxGetNumberOfElements(prhs[1])
       && mxGetNumberOfElements(prhs[2]) != 9 && mxGetNumberOfElements(prhs[3]) != 9
       && mxGetNumberOfElements(prhs[4]) != 1 && mxGetNumberOfElements(prhs[5]) != 1)
    {
        mexErrMsgIdAndTxt("ransac_floor_fHf:incorrectSize", "Input dimensions incorrect.");
    }
    // Convert to expected input
    int nbr_pts = mxGetNumberOfElements(prhs[0]) / 3;
    VectorXd x1_tmp = Map<VectorXd>(mxGetPr(prhs[0]), mxGetNumberOfElements(prhs[0]));
    VectorXd x2_tmp = Map<VectorXd>(mxGetPr(prhs[1]), mxGetNumberOfElements(prhs[1]));
    MatrixXd x1 = Map<MatrixXd>(x1_tmp.data(), 3, nbr_pts);
    MatrixXd x2 = Map<MatrixXd>(x2_tmp.data(), 3, nbr_pts);

    VectorXd R1_tmp = Map<VectorXd>(mxGetPr(prhs[2]), 9);
    VectorXd R2_tmp = Map<VectorXd>(mxGetPr(prhs[3]), 9);
    Matrix3d R1 = Map<Matrix3d>(R1_tmp.data(), 3, 3);
    Matrix3d R2 = Map<Matrix3d>(R2_tmp.data(), 3, 3);

    double *nbr_iter_p = mxGetPr(prhs[4]);
    double *thresh = mxGetPr(prhs[5]);
    int nbr_iter = (int) nbr_iter_p[0];

    // Compute output
    RansacData ransac_data = ransac_floor_fHf(x1, x2, R1, R2, nbr_iter, thresh[0]);
    PoseData posedata = ransac_data.posedata;

    // Wrap it up to Matlab compatible output
    plhs[0] = mxCreateDoubleMatrix(3, 3, mxREAL);
    double* zr = mxGetPr(plhs[0]);
    for (Index i = 0; i < posedata.homography.size(); i++) {
        zr[i] = posedata.homography(i);
    }
    plhs[1] = mxCreateDoubleMatrix(1, 1, mxREAL);
    zr = mxGetPr(plhs[1]);
    zr[0] = posedata.focal_length;

    plhs[2] = mxCreateDoubleMatrix(nbr_pts, 1, mxREAL);
    zr = mxGetPr(plhs[2]);
    for (Index i = 0; i < nbr_pts; i++) {
        zr[i] = ransac_data.inliers(i);
    }

    plhs[3] = mxCreateDoubleMatrix(nbr_iter, 1, mxREAL);
    zr = mxGetPr(plhs[3]);
    for (Index i = 0; i < nbr_iter; i++) {
        zr[i] = ransac_data.history(i);
    }
}
#endif


text:
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
//    names, trademarks, service marks, or product names of the Licensor
//    and its affiliates, except as required to comply with Section 4(c) of
//    the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#include "pxr/base/work/loops.h"
#include "pxr/base/work/threadLimits.h"
#include "pxr/base/tf/diagnostic.h"
#include "pxr/base/tf/envSetting.h"
#include "pxr/base/tf/staticData.h"

#include <boost/bind.hpp>

#include <iostream>
#include <mutex>
#include <pthread.h>
#include <set>
#include <stdio.h>

extern TfEnvSetting<int> PXR_WORK_THREAD_LIMIT;

static TfStaticData< std::set<pthread_t> > _uniqueThreads;
static TfStaticData< std::mutex > _uniqueThreadsMutex;

static void
_CountThreads(size_t begin, size_t end)
{
    // Do something to take up some time
    for (size_t i = begin; i < end; ++i) {
        int *a = new int[i];
        delete [] a;
    }
    std::lock_guard<std::mutex> lock(*_uniqueThreadsMutex);
    _uniqueThreads->insert(pthread_self());
}

static void
_TestThreadLimit(size_t n)
{
    const size_t numSamples = 1000000;
    std::cout << "   maximum " << n << " threads\n";

    _uniqueThreads->clear();

    WorkParallelForN(numSamples, boost::bind(&_CountThreads, _1, _2));

    std::cout << "   TBB used " << _uniqueThreads->size() << '\n';

    if (_uniqueThreads->size() > n) {
        TF_FATAL_ERROR("TBB expected less than or equal to %zu threads, got %zu",
                       n, _uniqueThreads->size());
    }

}

static void
_TestArguments()
{
    size_t numCores = WorkGetMaximumConcurrencyLimit();

    // These tests assume we have at least 4 cores.
    TF_AXIOM(numCores >= 4);

    // n = 0, means full threading
    WorkSetConcurrencyLimitArgument(0);
    TF_AXIOM(WorkGetConcurrencyLimit() == numCores);

    // n = 1 means no threading
    WorkSetConcurrencyLimitArgument(1);
    TF_AXIOM(WorkGetConcurrencyLimit() == 1);

    // n = 3 means 3
    WorkSetConcurrencyLimitArgument(3);
    TF_AXIOM(WorkGetConcurrencyLimit() == 3);

    // n = numCores means numCores
    WorkSetConcurrencyLimitArgument(numCores);
    TF_AXIOM(WorkGetConcurrencyLimit() == numCores);

    // n = 1000 means max
    WorkSetConcurrencyLimitArgument(1000);
    TF_AXIOM(WorkGetConcurrencyLimit() == numCores);

    // n = -1 means numCores - 1
    WorkSetConcurrencyLimitArgument(-1);
    TF_AXIOM(WorkGetConcurrencyLimit() == numCores-1);

    // n = -3 means numCores - 3
    WorkSetConcurrencyLimitArgument(-3);
    TF_AXIOM(WorkGetConcurrencyLimit() == numCores-3);

    // n = -numCores means 1 (no threading)
    WorkSetConcurrencyLimitArgument(-numCores);
    TF_AXIOM(WorkGetConcurrencyLimit() == 1);

    // n = -numCores*10 means 1 (no threading)
    WorkSetConcurrencyLimitArgument(-numCores*10);
    TF_AXIOM(WorkGetConcurrencyLimit() == 1);
}

struct _RawTBBCounter
{
    void operator()(const tbb::blocked_range<size_t> &r) const {
        _CountThreads(r.begin(), r.end());
    }
};

int
main(int argc, char **argv)
{
    // Read the env setting used to limit threading
    size_t limit = TfGetEnvSetting(PXR_WORK_THREAD_LIMIT);
    std::cout << "PXR_WORK_THREAD_LIMIT = " << limit << '\n';

    // Test to make sure that a call to tbb that happens before any of the
    // libWork API is touched is unrestricted.  We need to do this for now to
    // make sure that we don't break existing tbb code just by having libWork
    // linked in.
    //
    // Note that if we test this, we can't run the rest of the test because once
    // tbb is initialized by default (by just using its API) then there doesn't
    // seem to be a way to limit it again.  That's why we test this
    // functionality by itself.
    if ((argc == 2) and (strcmp(argv[1], "--rawtbb") == 0)) {
        TF_AXIOM(WorkGetMaximumConcurrencyLimit() >= 4);

        std::cout << "Testing that libWork automatically limits tbb "
            "threading when PXR_WORK_THREAD_LIMIT is set...\n";
        _uniqueThreads->clear();
        tbb::parallel_for(
            tbb::blocked_range<size_t>(0, 100000), _RawTBBCounter());
        std::cout << "   default TBB used " << _uniqueThreads->size()
                  << " threads\n";

        if (limit == 0) {
            if (_uniqueThreads->size() < 2) {
                TF_FATAL_ERROR("tbb only used %zu threads when it should be "
                               "unlimited\n", _uniqueThreads->size());
            }
        }
        else if (_uniqueThreads->size() > limit) {
            TF_FATAL_ERROR("tbb used %zu threads, which is greater than "
                           "PXR_WORK_THREAD_LIMIT=%zu.", _uniqueThreads->size(),
                           limit);
        }

        // Stop the test, now that we've initialized tbb, there's no going
        // back.
        return 0;
    }

    // 0 means all cores.
    if (limit == 0) {
        WorkSetMaximumConcurrencyLimit();
        limit = WorkGetConcurrencyLimit();
    }

    TF_AXIOM(limit > 0 and limit <= WorkGetMaximumConcurrencyLimit());

    // Make sure that we get the default thread limit
    std::cout << "Testing that the thread limit defaults to "
        " PXR_WORK_THREAD_LIMIT by default...\n";
    _TestThreadLimit(limit);

    // Now that we've invoked libWork, make sure that raw TBB API also defaults
    // to PXR_WORK_THREAD_LIMIT.
    std::cout << "Testing that raw tbb code is now also unlimited "
        " after first invocation of libWork API...\n";

    _uniqueThreads->clear();
    tbb::parallel_for(tbb::blocked_range<size_t>(0, 100000), _RawTBBCounter());
    std::cout << "   raw tbb used " << _uniqueThreads->size() << " threads\n";
    if (_uniqueThreads->size() > limit) {
        TF_FATAL_ERROR("it appears as though libWork hasn't been initialized "
                       "with PXR_WORK_THREAD_LIMIT.");
    }

    // Test with full concurrency.
    std::cout << "Testing full concurrency...\n";
    WorkSetMaximumConcurrencyLimit();
    _TestThreadLimit(WorkGetMaximumConcurrencyLimit());

    // Test with no concurrency.
    std::cout << "Testing turning off concurrency...\n";
    WorkSetConcurrencyLimit(1);
    _TestThreadLimit(1);

    // Test with 4 threads.
    std::cout << "Testing with 4 threads...\n";
    WorkSetConcurrencyLimit(4);
    _TestThreadLimit(4);

    // Test argument parsing
    std::cout << "Testing argument parsing...\n";
    _TestArguments();
    return 0;
}


text:
#include "NoiseCovariancePlottingGadget.h"

#include "GtPLplot.h"

#include "fstream"

#ifndef _WIN32
#include <sys/types.h>
#include <sys/stat.h>
#endif // _WIN32

#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/split.hpp>

#include "mri_core_def.h"
#include "io/primitives.h"

namespace Gadgetron{

NoiseCovariancePlottingGadget::NoiseCovariancePlottingGadget()
    : noise_decorrelation_calculated_(false)
    , noise_dwell_time_us_(-1.0f)
    , noiseCovarianceLoaded_(false)
{
    noise_dependency_prefix_ = "GadgetronNoiseCovarianceMatrix";
    measurement_id_.clear();
    measurement_id_of_noise_dependency_.clear();
}

NoiseCovariancePlottingGadget::~NoiseCovariancePlottingGadget()
{

}

int NoiseCovariancePlottingGadget::process_config(ACE_Message_Block* mb)
{
    if (!workingDirectory.value().empty())
    {
        noise_dependency_folder_ = workingDirectory.value();
    }
    else
    {
#ifdef _WIN32
        noise_dependency_folder_ = std::string("c:\\temp\\gadgetron\\");
#else
        noise_dependency_folder_ =  std::string("/tmp/gadgetron/");
#endif // _WIN32
    }

    GDEBUG("Folder to store noise dependencies is %s\n", noise_dependency_folder_.c_str());

    if (!noise_dependency_prefix.value().empty()) noise_dependency_prefix_ = noise_dependency_prefix.value();

    ISMRMRD::deserialize(mb->rd_ptr(), current_ismrmrd_header_);

    // find the measurementID of this scan
    if (current_ismrmrd_header_.measurementInformation)
    {
        if (current_ismrmrd_header_.measurementInformation->measurementID)
        {
            measurement_id_ = *current_ismrmrd_header_.measurementInformation->measurementID;
            GDEBUG("Measurement ID is %s\n", measurement_id_.c_str());
        }

        // find the noise dependencies if any
        if (current_ismrmrd_header_.measurementInformation->measurementDependency.size() > 0)
        {
            measurement_id_of_noise_dependency_.clear();

            std::vector<ISMRMRD::MeasurementDependency>::const_iterator iter = current_ismrmrd_header_.measurementInformation->measurementDependency.begin();
            for (; iter != current_ismrmrd_header_.measurementInformation->measurementDependency.end(); iter++)
            {
                std::string dependencyType = iter->dependencyType;
                std::string dependencyID = iter->measurementID;

                GDEBUG("Found dependency measurement : %s with ID %s\n", dependencyType.c_str(), dependencyID.c_str());

                if (dependencyType == "Noise" || dependencyType == "noise") {
                    measurement_id_of_noise_dependency_ = dependencyID;
                }
            }

            if (!measurement_id_of_noise_dependency_.empty())
            {
                GDEBUG("Measurement ID of noise dependency is %s\n", measurement_id_of_noise_dependency_.c_str());

                full_name_stored_noise_dependency_ = this->generateNoiseDependencyFilename(generateMeasurementIdOfNoiseDependency(measurement_id_of_noise_dependency_));
                GDEBUG("Stored noise dependency is %s\n", full_name_stored_noise_dependency_.c_str());
            }
        }
        else
        {
            full_name_stored_noise_dependency_ = this->generateNoiseDependencyFilename(measurement_id_);
            GDEBUG("Stored noise dependency is %s\n", full_name_stored_noise_dependency_.c_str());
        }
    }

    return GADGET_OK;
}

std::string NoiseCovariancePlottingGadget::generateMeasurementIdOfNoiseDependency(const std::string& noise_id)
{
    //TODO: Remove this hack. This hack addresses a problem with mislabeled noise dependency IDs generated by the converter.
    //We will keep this for a transition period while preserving backwards compatibility
    if (noise_id.find("_") == std::string::npos) {
        // find the scan prefix
        std::string measurementStr = measurement_id_;
        size_t ind  = measurement_id_.find_last_of ("_");
        if ( ind != std::string::npos ) {
            measurementStr = measurement_id_.substr(0, ind);
            measurementStr.append("_");
            measurementStr.append(noise_id);
        }

        return measurementStr;
    }

    return noise_id;
}

std::string NoiseCovariancePlottingGadget::generateNoiseDependencyFilename(const std::string& measurement_id)
{
    std::string full_name_stored_noise_dependency;

    full_name_stored_noise_dependency = noise_dependency_folder_;
    full_name_stored_noise_dependency.append("/");
    full_name_stored_noise_dependency.append(noise_dependency_prefix_);
    full_name_stored_noise_dependency.append("_");
    full_name_stored_noise_dependency.append(measurement_id);

    return full_name_stored_noise_dependency;
}

bool NoiseCovariancePlottingGadget::loadNoiseCovariance()
{
    std::ifstream infile;
    infile.open(full_name_stored_noise_dependency_.c_str(), std::ios::in | std::ios::binary);

    if (infile.good())
    {
        //Read the XML header of the noise scan
        uint32_t xml_length;
        infile.read(reinterpret_cast<char*>(&xml_length), 4);
        std::string xml_str(xml_length, '\0');
        infile.read(const_cast<char*>(xml_str.c_str()), xml_length);
        ISMRMRD::deserialize(xml_str.c_str(), noise_ismrmrd_header_);

        infile.read(reinterpret_cast<char*>(&noise_dwell_time_us_), sizeof(float));

        size_t len;
        infile.read(reinterpret_cast<char*>(&len), sizeof(size_t));

        auto buf = std::vector<char>(len);

        infile.read(buf.data(), len);

        noise_covariance_matrixf_ = Core::IO::read<hoNDArray<std::complex<float>>>(infile);
        infile.close();
    }
    else
    {
        return false;
    }

    return true;
}

int NoiseCovariancePlottingGadget::process(GadgetContainerMessage<ISMRMRD::ImageHeader>* m1, GadgetContainerMessage< hoNDArray< std::complex<float> > >* m2)
{
    curr_image_header_ = *m1->getObjectPtr();

    if (this->next()->putq(m1) == -1)
    {
        m1->release();
        GDEBUG("NoiseCovariancePlottingGadget, Unable to put image on next gadgets queue");
        return GADGET_FAIL;
    }

    return GADGET_OK;
}

int NoiseCovariancePlottingGadget::close(unsigned long flags)
{
    if (BaseClass::close(flags) != GADGET_OK) return GADGET_FAIL;

    // try to load the precomputed noise prewhitener
    if (flags == 0) return GADGET_OK;

    if (!full_name_stored_noise_dependency_.empty())
    {
        if (this->loadNoiseCovariance())
        {
            GDEBUG("Stored noise dependency is found : %s\n", full_name_stored_noise_dependency_.c_str());

            if (noise_ismrmrd_header_.acquisitionSystemInformation.is_present())
            {
                hoNDArray<float> plotIm;

                bool trueColor = false;
                size_t CHA = noise_covariance_matrixf_.get_size(0);

                std::vector<std::string> coilStrings(CHA, "Unknown");
                for (size_t n = 0; n < CHA; n++)
                {
                    int coilNum = noise_ismrmrd_header_.acquisitionSystemInformation.get().coilLabel[n].coilNumber;
                    if (coilNum >= 0 && coilNum < CHA)
                    {
                        coilStrings[coilNum] = noise_ismrmrd_header_.acquisitionSystemInformation.get().coilLabel[n].coilName;
                    }
                }

                Gadgetron::plotNoiseStandardDeviation(noise_covariance_matrixf_, coilStrings, xlabel.value(), ylabel.value(), title.value(), xsize.value(), ysize.value(), trueColor, plotIm);

                // send out the noise variance plot
                Gadgetron::GadgetContainerMessage<ISMRMRD::ImageHeader>* cm1 = new Gadgetron::GadgetContainerMessage<ISMRMRD::ImageHeader>();
                Gadgetron::GadgetContainerMessage<ISMRMRD::MetaContainer>* cm3 = new Gadgetron::GadgetContainerMessage<ISMRMRD::MetaContainer>();

                *cm1->getObjectPtr() = curr_image_header_;

                cm1->getObjectPtr()->flags = 0;
                cm1->getObjectPtr()->data_type = ISMRMRD::ISMRMRD_CXFLOAT;
                cm1->getObjectPtr()->image_type = ISMRMRD::ISMRMRD_IMTYPE_MAGNITUDE;

                cm1->getObjectPtr()->image_index = 1;
                cm1->getObjectPtr()->image_series_index = series_num.value();

                Gadgetron::GadgetContainerMessage< Gadgetron::hoNDArray< std::complex<float> > >* cm2 = new Gadgetron::GadgetContainerMessage< Gadgetron::hoNDArray< std::complex<float> > >();
                cm1->cont(cm2);
                cm2->cont(cm3);

                std::vector<size_t> img_dims(2);
                img_dims[0] = plotIm.get_size(0);
                img_dims[1] = plotIm.get_size(1);

                // set the image attributes
                cm3->getObjectPtr()->set(GADGETRON_IMAGECOMMENT, "Noise SD");
                cm3->getObjectPtr()->set(GADGETRON_SEQUENCEDESCRIPTION, "_GT_Noise_SD_Plot");
                cm3->getObjectPtr()->set(GADGETRON_IMAGEPROCESSINGHISTORY, "GT");
                cm3->getObjectPtr()->set(GADGETRON_DATA_ROLE, GADGETRON_IMAGE_RECON_FIGURE);

                cm3->getObjectPtr()->set(GADGETRON_IMAGE_SCALE_RATIO, (double)(1));
                cm3->getObjectPtr()->set(GADGETRON_IMAGE_WINDOWCENTER, (long)(200));
                cm3->getObjectPtr()->set(GADGETRON_IMAGE_WINDOWWIDTH, (long)(400));

                cm1->getObjectPtr()->matrix_size[0] = (uint16_t)plotIm.get_size(0);
                cm1->getObjectPtr()->matrix_size[1] = (uint16_t)plotIm.get_size(1);
                cm1->getObjectPtr()->matrix_size[2] = 1;
                cm1->getObjectPtr()->channels = 1;

                // make sure pixel is squared in size
                float dx = cm1->getObjectPtr()->field_of_view[0] / cm1->getObjectPtr()->matrix_size[0];
                cm1->getObjectPtr()->field_of_view[1] = dx * cm1->getObjectPtr()->matrix_size[1];

                try
                {
                    cm2->getObjectPtr()->create(img_dims);
                }
                catch (...)
                {
                    GDEBUG("Unable to allocate new image\n");
                    cm1->release();
                    return false;
                }

                Gadgetron::real_to_complex(plotIm, *cm2->getObjectPtr());

                // send out the images
                if (this->next()->putq(cm1) < 0)
                {
                    return false;
                }
            }
        }
        else
        {
            GDEBUG("Stored noise dependency is NOT found : %s\n", full_name_stored_noise_dependency_.c_str());
        }
    }
    else
    {
        GDEBUG("There is no noise stored ... \n");
    }

    return GADGET_OK;
}

GADGET_FACTORY_DECLARE(NoiseCovariancePlottingGadget)

} // namespace Gadgetron

max_stars_repo_name: roopchansinghv/gadgetron


text:
#include "TArrow.h"
#include "TCanvas.h"
#include "TGraph.h"
#include "TH1.h"
#include "TH2.h"
#include "TH2Poly.h"
#include "TLatex.h"
#include "TStyle.h"

#include <fmt/printf.h>
#include <fstream>
#include <memory>
#include <boost/tokenizer.hpp>
#include <boost/range/adaptor/indexed.hpp>

#include "FWCore/ParameterSet/interface/FileInPath.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "CalibTracker/StandaloneTrackerTopology/interface/StandaloneTrackerTopology.h"
#include "DQM/TrackerRemapper/interface/Phase1PixelSummaryMap.h"

// set option, but only if not already set
//============================================================================
void Phase1PixelSummaryMap::resetOption(const char* option) {
  if (m_option != nullptr && !m_option[0]) {
    m_option = option;
  } else {
    edm::LogError("Phase1PixelSummaryMap")
        << "Option has already been set to " << m_option << ". It's not possible to reset it.";
  }
}

//============================================================================
void Phase1PixelSummaryMap::createTrackerBaseMap() {
  m_BaseTrackerMap = std::make_shared<TH2Poly>("Summary", "", -10, 160, -70, 70);
  m_BaseTrackerMap->SetFloat(true);
  m_BaseTrackerMap->GetXaxis()->SetTitle("");
  m_BaseTrackerMap->GetYaxis()->SetTitle("");
  m_BaseTrackerMap->GetZaxis()->SetTitle(m_zAxisTitle.c_str());
  m_BaseTrackerMap->GetZaxis()->CenterTitle();
  m_BaseTrackerMap->GetZaxis()->SetTitleOffset(1.2);
  m_BaseTrackerMap->SetOption("COLZ L");
  m_BaseTrackerMap->SetStats(false);

  //BARREL FIRST
  for (unsigned int i = 0; i < maxPxBarrel; i++) {
    LOGINFO("Phase1PixelSummaryMap") << "barrel, shift: " << i << " corner: " << i << std::endl;
    LOGINFO("Phase1PixelSummaryMap") << "translate x: " << 0 << std::endl;
    LOGINFO("Phase1PixelSummaryMap") << "translate y: " << barrelLadderShift[i] << std::endl;

    int currBarrelTranslateX = 0;
    int currBarrelTranslateY = barrelLadderShift[i];
    addNamedBins(m_cornersBPIX[i], currBarrelTranslateX, currBarrelTranslateY, 1, 1, true);
  }

  //MINUS FORWARD
  for (int j : {-3, -2, -1}) {
    LOGINFO("Phase1PixelSummaryMap") << "negative fwd, shift: " << -j - 1 << " corner: " << maxPxForward + j
                                     << std::endl;
    LOGINFO("Phase1PixelSummaryMap") << "translate x: " << forwardDiskXShift[-j - 1] << std::endl;
    LOGINFO("Phase1PixelSummaryMap") << "translate y: " << -forwardDiskYShift << std::endl;

    int currForwardTranslateX = forwardDiskXShift[-j - 1];
    int currForwardTranslateY = -forwardDiskYShift;
    addNamedBins(m_cornersFPIX[maxPxForward + j], currForwardTranslateX, currForwardTranslateY, 1, 1);
  }

  //PLUS FORWARD
  for (int k : {1, 2, 3}) {
    LOGINFO("Phase1PixelSummaryMap") << "positive fwd, shift: " << k << " corner: " << maxPxForward + k - 1
                                     << std::endl;
    LOGINFO("Phase1PixelSummaryMap") << "translate x: " << forwardDiskXShift[k - 1] << std::endl;
    LOGINFO("Phase1PixelSummaryMap") << "translate y: " << forwardDiskYShift << std::endl;

    int currForwardTranslateX = forwardDiskXShift[k - 1];
    int currForwardTranslateY = forwardDiskYShift;
    addNamedBins(m_cornersFPIX[maxPxForward + k - 1], currForwardTranslateX, currForwardTranslateY, 1, 1);
  }

  edm::LogPrint("Phase1PixelSummaryMap") << "Base Tracker Map: constructed" << std::endl;
  return;
}

//============================================================================
void Phase1PixelSummaryMap::printTrackerMap(TCanvas& canvas) {
  //canvas = TCanvas("c1","c1",plotWidth,plotHeight);
  canvas.cd();
  canvas.SetTopMargin(0.02);
  canvas.SetBottomMargin(0.02);
  canvas.SetLeftMargin(0.02);
  canvas.SetRightMargin(0.14);
  m_BaseTrackerMap->Draw("AL");
  m_BaseTrackerMap->Draw("AC COLZ0 L SAME");

  //### z arrow
  arrow = TArrow(0.05, 27.0, 0.05, -30.0, 0.02, "|>");
  arrow.SetLineWidth(4);
  arrow.Draw();
  arrow.SetAngle(30);
  //### phi arrow
  phiArrow = TArrow(0.0, 27.0, 30.0, 27.0, 0.02, "|>");
  phiArrow.SetLineWidth(4);
  phiArrow.Draw();
  phiArrow.SetAngle(30);
  //### x arrow
  xArrow = TArrow(25.0, 44.5, 50.0, 44.5, 0.02, "|>");
  xArrow.SetLineWidth(4);
  xArrow.Draw();
  xArrow.SetAngle(30);
  //### y arrow
  yArrow = TArrow(25.0, 44.5, 25.0, 69.5, 0.02, "|>");
  yArrow.SetLineWidth(4);
  yArrow.Draw();
  yArrow.SetAngle(30);

  //###################################################
  //# add some captions
  auto txt = TLatex();
  txt.SetNDC();
  txt.SetTextFont(1);
  txt.SetTextColor(1);
  txt.SetTextAlign(22);
  txt.SetTextAngle(0);

  //# draw new-style title
  txt.SetTextSize(0.05);
  txt.DrawLatex(0.5, 0.95, (fmt::sprintf("Pixel Tracker Map: %s", m_title)).c_str());
  txt.SetTextSize(0.03);

  txt.DrawLatex(0.55, 0.125, "-DISK");
  txt.DrawLatex(0.55, 0.875, "+DISK");

  txt.DrawLatex(0.08, 0.28, "+z");
  txt.DrawLatex(0.25, 0.70, "+phi");
  txt.DrawLatex(0.31, 0.78, "+x");
  txt.DrawLatex(0.21, 0.96, "+y");

  txt.SetTextAngle(90);
  txt.DrawLatex(0.04, 0.5, "BARREL");

  edm::LogPrint("Phase1PixelSummaryMap") << "Base Tracker Map: printed" << std::endl;
}

//============================================================================
bool Phase1PixelSummaryMap::fillTrackerMap(unsigned int id, double value) {
  auto detid = DetId(id);
  if (detid.subdetId() != PixelSubdetector::PixelBarrel && detid.subdetId() != PixelSubdetector::PixelEndcap) {
    edm::LogError("Phase1PixelSummaryMap")
        << __func__ << " The following detid " << id << " is not Pixel!" << std::endl;
    return false;
  } else {
    m_BaseTrackerMap->Fill(TString::Format("%u", id), value);
    return true;
  }
}

//============================================================================
void Phase1PixelSummaryMap::addNamedBins(
    edm::FileInPath geoFile, int tX, int tY, int sX, int sY, bool applyModuleRotation) {
  auto cornerFileName = geoFile.fullPath();
  std::ifstream cornerFile(cornerFileName.c_str());
  if (!cornerFile.good()) {
    throw cms::Exception("FileError") << "Problem opening corner file: " << cornerFileName;
  }
  std::string line;
  while (std::getline(cornerFile, line)) {
    if (!line.empty()) {
      std::istringstream iss(line);

      auto tokens = Ph1PMapSummaryHelper::tokenize(line, '"');
      // Printing the token vector
      for (unsigned int i = 0; i < tokens.size(); i++)
        LOGDEBUG("Phase1PixelSummaryMap") << tokens[i] << '\n';

      auto detInfo = Ph1PMapSummaryHelper::tokenize(tokens[0], ' ');
      unsigned int detId = stoi(detInfo[0]);
      std::string detIdName = detInfo[1];
      auto xy = Ph1PMapSummaryHelper::tokenize(tokens[1], ' ');
      unsigned int verNum = 1;
      std::vector<float> xP, yP;
      for (const auto& coord : xy) {
        auto coordSpl = Ph1PMapSummaryHelper::tokenize(coord, ',');
        if (applyModuleRotation) {
          xP.push_back(-(std::stof(coordSpl[0]) * sX + tX));
          yP.push_back(((std::stof(coordSpl[1]) * sY + tY)));
        } else {
          xP.push_back(std::stof(coordSpl[0]) * sX + tX);
          yP.push_back(std::stof(coordSpl[1]) * sY + tY);
        }
        verNum++;
      }
      //close the polygon
      xP.push_back(xP[0]);
      yP.push_back(yP[0]);

      LOGDEBUG("Phase1PixelSummaryMap") << detId << "[";
      for (const auto& p : xP) {
        LOGDEBUG("Phase1PixelSummaryMap") << p << ",";
      }
      LOGDEBUG("Phase1PixelSummaryMap") << "] [ ";
      for (const auto& q : yP) {
        LOGDEBUG("Phase1PixelSummaryMap") << q << ",";
      }
      LOGDEBUG("Phase1PixelSummaryMap") << "]" << std::endl;

      const unsigned int N = verNum;
      if (applyModuleRotation) {
        bins[detId] = std::make_shared<TGraph>(N, &yP[0], &xP[0]);
      } else {
        bins[detId] = std::make_shared<TGraph>(N, &xP[0], &yP[0]);
        //bins[detId] = std::make_shared<TGraph>(N, &yP[0], &xP[0]); // rotation by 90 deg (so that it had the same layout as for the strips)
      }

      bins[detId]->SetName(detInfo[0].c_str());
      m_BaseTrackerMap->AddBin(bins[detId]->Clone());
    }
  }
  return;
}

ext: cc

max_stars_repo_name: malbouis/cmssw

max_issues_repo_name: malbouis/cmssw

max_forks_repo_name: malbouis/cmssw