text:
#define BOOST_AUTO_TEST_MAIN
#include <boost/test/included/unit_test_framework.hpp>
#include <boost/test/auto_unit_test.hpp>

ext: cpp


text:
/*
Original Author: Andrew Fox
E-Mail: mailto:foxostro@gmail.com

Copyright (c) 2003,2007,2009,2010 Game Creation Society
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the Game Creation Society nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE Game Creation Society ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE Game Creation Society BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <boost/lexical_cast.hpp>
#include <iostream>
#include <ctime>
#include <string>

using std::string;

// Returns a formatted timestamp for the current time.
static string Timestamp(void)
{
	time_t curTime = std::time(NULL);
	char timestamp[32];
	std::strftime(timestamp,
	              sizeof(timestamp),
				  "%Y%m%dT%H%M%S",
				  localtime(&curTime));
	return string(timestamp);
}

namespace Engine {

void Log(const string & msg, const string & fun, const string & fil, int ln)
{
	static FILE * log = NULL;

	string ts = Timestamp();

	if(!log) {
		/* XXX: Not thread-safe! Since we aren't using threads during
		 * initialization, that's probably OK for now.
		 */
		string f = string("arbarlith2_") + ts + string(".log");
		log = fopen(f.c_str(), "w");
	}

	fprintf(log, "%s\t%s:%d\t%s\t%s\n", ts.c_str(), fil.c_str(), ln,
	        fun.c_str(), msg.c_str());
}

} // namespace Engine


text:
/**
 * @file
 * @author  Mamadou Babaei <info@babaei.net>
 * @version 0.1.0
 *
 * @section LICENSE
 *
 * (The MIT License)
 *
 * Copyright (c) 2018 - 2019 Mamadou Babaei
 * Copyright (c) 2018 - 2019 Seditious Games Studio
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 * @section DESCRIPTION
 *
 * Provides a low-level implementation for an abstraction layer on top of the
 * cryptography API.
 */

#include "GCryptoImpl/GCryptoImpl.h"

#include <algorithm>
#include <vector>

#include <cstdlib>

#include <Containers/StringConv.h>

#include <GHacks/GUndef_check.h>
THIRD_PARTY_INCLUDES_START
#include <boost/algorithm/string.hpp>
THIRD_PARTY_INCLUDES_END
#include <GHacks/GRestore_check.h>

THIRD_PARTY_INCLUDES_START
#include <cryptopp/base64.h>
#include <cryptopp/filters.h>
#include <cryptopp/hex.h>
#include <cryptopp/hmac.h>
#include <cryptopp/sha.h>
THIRD_PARTY_INCLUDES_END

THIRD_PARTY_INCLUDES_START
#include <fmt/format.h>
#include <fmt/ostream.h>
THIRD_PARTY_INCLUDES_END

#include <GHacks/GInclude_Windows.h>

#define     GCRYPTO_ERROR_DIALOG_TITLE          "Cryptography Error"
#define     GCRYPTO_UNKNOWN_ERROR_MESSAGE       "GCrypto: unknown error!"

struct GCryptoImpl::Impl
{
public:
    GCryptoByte* SignKey;
    uint64 SignKeySize;

public:
    Impl();
    ~Impl();
};

void GCryptoImpl::ByteArrayToString(const GCryptoByte* Array,
                                    const uint64 Length,
                                    FString& Out_String)
{
    try
    {
        Out_String = FString();

        fmt::memory_buffer MemoryBuffer;

        for (size_t Index = 0; Index < Length; ++Index)
        {
            fmt::format_to(MemoryBuffer, "{i}", fmt::arg("i", Array[Index]));
        }

        Out_String = StringCast<WIDECHAR>(
                    fmt::to_string(MemoryBuffer).c_str()).Get();
    }

    catch (const fmt::v5::format_error& Exception)
    {
#if defined ( _WIN32 ) || defined ( _WIN64 )
        MessageBoxA(0, Exception.what(), GCRYPTO_ERROR_DIALOG_TITLE, MB_OK);
#endif  /* defined ( _WIN32 ) || defined ( _WIN64 ) */
        checkf(false, TEXT("%s"),
               StringCast<WIDECHAR>(Exception.what()).Get());
    }

    catch (const std::exception& Exception)
    {
#if defined ( _WIN32 ) || defined ( _WIN64 )
        MessageBoxA(0, Exception.what(), GCRYPTO_ERROR_DIALOG_TITLE, MB_OK);
#endif  /* defined ( _WIN32 ) || defined ( _WIN64 ) */
        checkf(false, TEXT("%s"),
               StringCast<WIDECHAR>(Exception.what()).Get());
    }

    catch (...)
    {
#if defined ( _WIN32 ) || defined ( _WIN64 )
        MessageBoxA(0, GCRYPTO_UNKNOWN_ERROR_MESSAGE,
                    GCRYPTO_ERROR_DIALOG_TITLE, MB_OK);
#endif  /* defined ( _WIN32 ) || defined ( _WIN64 ) */
        checkf(false, TEXT("%s"),
               StringCast<WIDECHAR>(GCRYPTO_UNKNOWN_ERROR_MESSAGE).Get());
    }
}

FString GCryptoImpl::ByteArrayToString(const GCryptoByte* Array,
                                       const uint64 Length)
{
    FString Result;
    GCryptoImpl::ByteArrayToString(Array, Length, Result);
    return Result;
}

void GCryptoImpl::HexStringToString(const FString& HexString,
                                    FString& Out_String)
{
    try {
        Out_String = FString();

        std::vector<std::string> Bytes;
        std::string HexString_(StringCast<ANSICHAR>(*HexString).Get());

        boost::algorithm::iter_split(
                    Bytes, HexString_,
                    boost::algorithm::first_finder(":"));

        fmt::memory_buffer MemoryBuffer;

        for (std::vector<std::string>::iterator Iterator = Bytes.begin();
             Iterator != Bytes.end(); ++Iterator)
        {
            fmt::format_to(MemoryBuffer, "{c}",
                           fmt::arg("c",
                                    static_cast<char>(
                                        std::strtol(
                                            Iterator->c_str(),
                                            nullptr, 16))));
        }

        Out_String = StringCast<WIDECHAR>(
                    fmt::to_string(MemoryBuffer).c_str()).Get();
    }

    catch (const fmt::v5::format_error& Exception)
    {
#if defined ( _WIN32 ) || defined ( _WIN64 )
        MessageBoxA(0, Exception.what(), GCRYPTO_ERROR_DIALOG_TITLE, MB_OK);
#endif  /* defined ( _WIN32 ) || defined ( _WIN64 ) */
        checkf(false, TEXT("%s"),
               StringCast<WIDECHAR>(Exception.what()).Get());
    }

    catch (const std::exception& Exception)
    {
#if defined ( _WIN32 ) || defined ( _WIN64 )
        MessageBoxA(0, Exception.what(), GCRYPTO_ERROR_DIALOG_TITLE, MB_OK);
#endif  /* defined ( _WIN32 ) || defined ( _WIN64 ) */
        checkf(false, TEXT("%s"),
               StringCast<WIDECHAR>(Exception.what()).Get());
    }

    catch (...)
    {
#if defined ( _WIN32 ) || defined ( _WIN64 )
        MessageBoxA(0, GCRYPTO_UNKNOWN_ERROR_MESSAGE,
                    GCRYPTO_ERROR_DIALOG_TITLE, MB_OK);
#endif  /* defined ( _WIN32 ) || defined ( _WIN64 ) */
        checkf(false, TEXT("%s"),
               StringCast<WIDECHAR>(GCRYPTO_UNKNOWN_ERROR_MESSAGE).Get());
    }
}

FString GCryptoImpl::HexStringToString(const FString& HexString)
{
    FString Result;
    GCryptoImpl::HexStringToString(HexString, Result);
    return Result;
}

void GCryptoImpl::Base64Decode(const GCryptoByte* EncodedBuffer,
                               const uint64 EncodedBufferSize,
                               std::string& Out_Decoded)
{
    try
    {
        Out_Decoded.clear();

        CryptoPP::StringSource StringSource(
                    EncodedBuffer, static_cast<std::size_t>(EncodedBufferSize),
                    true,
                    new CryptoPP::Base64Decoder(
                        new CryptoPP::StringSink(Out_Decoded)
                        )
                    );
        (void)StringSource;
    }

    catch (const CryptoPP::Exception& Exception)
    {
#if defined ( _WIN32 ) || defined ( _WIN64 )
        MessageBoxA(0, Exception.what(), GCRYPTO_ERROR_DIALOG_TITLE, MB_OK);
#endif  /* defined ( _WIN32 ) || defined ( _WIN64 ) */
        checkf(false, TEXT("%s"),
               StringCast<WIDECHAR>(Exception.what()).Get());
    }

    catch (const std::exception& Exception)
    {
#if defined ( _WIN32 ) || defined ( _WIN64 )
        MessageBoxA(0, Exception.what(), GCRYPTO_ERROR_DIALOG_TITLE, MB_OK);
#endif  /* defined ( _WIN32 ) || defined ( _WIN64 ) */
        checkf(false, TEXT("%s"),
               StringCast<WIDECHAR>(Exception.what()).Get());
    }

    catch (...)
    {
#if defined ( _WIN32 ) || defined ( _WIN64 )
        MessageBoxA(0, GCRYPTO_UNKNOWN_ERROR_MESSAGE,
                    GCRYPTO_ERROR_DIALOG_TITLE, MB_OK);
#endif  /* defined ( _WIN32 ) || defined ( _WIN64 ) */
        checkf(false, TEXT("%s"),
               StringCast<WIDECHAR>(GCRYPTO_UNKNOWN_ERROR_MESSAGE).Get());
    }
}

void GCryptoImpl::Base64Decode(const GCryptoByte* EncodedBuffer,
                               const uint64 EncodedBufferSize,
                               GCryptoBuffer& Out_Decoded)
{
    Out_Decoded.clear();
    std::string Decoded;

    GCryptoImpl::Base64Decode(
                &EncodedBuffer[0], EncodedBufferSize, Decoded);

    Out_Decoded.assign(Decoded.begin(), Decoded.end());
}

void GCryptoImpl::Base64Decode(const GCryptoByte* EncodedBuffer,
                               const uint64 EncodedBufferSize,
                               FString& Out_Decoded)
{
    Out_Decoded = TEXT("");
    std::string Decoded;

    GCryptoImpl::Base64Decode(
                &EncodedBuffer[0], EncodedBufferSize, Decoded);

    Out_Decoded.Append(StringCast<WIDECHAR>(Decoded.c_str()).Get(),
                       Decoded.size());
    Out_Decoded.TrimToNullTerminator();
}

void GCryptoImpl::Base64Decode(const GCryptoBuffer& EncodedBuffer,
                               FString& Out_Decoded)
{
    Out_Decoded = TEXT("");
    std::string Decoded;

    GCryptoImpl::Base64Decode(&EncodedBuffer[0],
            static_cast<uint64>(EncodedBuffer.size()), Decoded);

    Out_Decoded.Append(StringCast<WIDECHAR>(Decoded.c_str()).Get(),
                       Decoded.size());
    Out_Decoded.TrimToNullTerminator();
}

void GCryptoImpl::Base64Decode(const FString& EncodedBuffer,
                               FString& Out_Decoded)
{
    Out_Decoded = TEXT("");
    std::string Decoded;

    GCryptoImpl::Base64Decode(
                reinterpret_cast<const GCryptoByte*>(
                    StringCast<ANSICHAR>(*EncodedBuffer).Get()),
                EncodedBuffer.Len(), Decoded);

    Out_Decoded.Append(StringCast<WIDECHAR>(Decoded.c_str()).Get(),
                       Decoded.size());
    Out_Decoded.TrimToNullTerminator();
}

void GCryptoImpl::Base64Encode(const GCryptoByte* RawBuffer,
                               const uint64 RawBufferSize,
                               FString& Out_Encoded)
{
    try
    {
        Out_Encoded = TEXT("");

        std::string Encoded;

        CryptoPP::StringSource StringSource(
                    RawBuffer, static_cast<std::size_t>(RawBufferSize), true,
                    new CryptoPP::Base64Encoder(
                        new CryptoPP::StringSink(Encoded)));
        (void)StringSource;

        Out_Encoded.Append(StringCast<WIDECHAR>(
                               Encoded.c_str()).Get(), Encoded.size());
        Out_Encoded.TrimToNullTerminator();
    }

    catch (const CryptoPP::Exception& Exception)
    {
#if defined ( _WIN32 ) || defined ( _WIN64 )
        MessageBoxA(0, Exception.what(), GCRYPTO_ERROR_DIALOG_TITLE, MB_OK);
#endif  /* defined ( _WIN32 ) || defined ( _WIN64 ) */
        checkf(false, TEXT("%s"),
               StringCast<WIDECHAR>(Exception.what()).Get());
    }

    catch (const std::exception& Exception)
    {
#if defined ( _WIN32 ) || defined ( _WIN64 )
        MessageBoxA(0, Exception.what(), GCRYPTO_ERROR_DIALOG_TITLE, MB_OK);
#endif  /* defined ( _WIN32 ) || defined ( _WIN64 ) */
        checkf(false, TEXT("%s"),
               StringCast<WIDECHAR>(Exception.what()).Get());
    }

    catch (...)
    {
#if defined ( _WIN32 ) || defined ( _WIN64 )
        MessageBoxA(0, GCRYPTO_UNKNOWN_ERROR_MESSAGE,
                    GCRYPTO_ERROR_DIALOG_TITLE, MB_OK);
#endif  /* defined ( _WIN32 ) || defined ( _WIN64 ) */
        checkf(false, TEXT("%s"),
               StringCast<WIDECHAR>(GCRYPTO_UNKNOWN_ERROR_MESSAGE).Get());
    }
}

void GCryptoImpl::Base64Encode(const GCryptoBuffer& RawBuffer,
                               FString& Out_Encoded)
{
    return GCryptoImpl::Base64Encode(
                &RawBuffer[0],
            static_cast<uint64>(RawBuffer.size()),
            Out_Encoded);
}

void GCryptoImpl::Base64Encode(const std::string& RawBuffer,
                               FString& Out_Encoded)
{
    return GCryptoImpl::Base64Encode(
                reinterpret_cast<const GCryptoByte*>(RawBuffer.c_str()),
                static_cast<uint64>(RawBuffer.size()),
                Out_Encoded);
}

void GCryptoImpl::Base64Encode(const FString& RawBuffer,
                               FString& Out_Encoded)
{
    return GCryptoImpl::Base64Encode(
                reinterpret_cast<const GCryptoByte*>(
                    StringCast<ANSICHAR>(*RawBuffer).Get()),
                RawBuffer.Len(),
                Out_Encoded);
}

void GCryptoImpl::Sign(const GCryptoByte* Key, const uint64 KeySize,
                       const GCryptoByte* PlainBuffer, uint64 PlainBufferSize,
                       FString& Out_MAC)
{
    try
    {
        Out_MAC = FString();

        CryptoPP::HMAC<CryptoPP::SHA512> HMAC(Key, KeySize);

        std::string MAC;
        CryptoPP::StringSource(
                    PlainBuffer, static_cast<std::size_t>(PlainBufferSize),
                    true, new CryptoPP::HashFilter(
                        HMAC, new CryptoPP::StringSink(MAC)));

        std::string Encoded;
        CryptoPP::StringSource(MAC, true, new CryptoPP::Base64Encoder(
                                   new CryptoPP::StringSink(Encoded)));

        Out_MAC = StringCast<WIDECHAR>(Encoded.c_str()).Get();
    }

    catch (const CryptoPP::Exception& Exception)
    {
#if defined ( _WIN32 ) || defined ( _WIN64 )
        MessageBoxA(0, Exception.what(), GCRYPTO_ERROR_DIALOG_TITLE, MB_OK);
#endif  /* defined ( _WIN32 ) || defined ( _WIN64 ) */
        checkf(false, TEXT("%s"),
               StringCast<WIDECHAR>(Exception.what()).Get());
    }

    catch (const std::exception& Exception)
    {
#if defined ( _WIN32 ) || defined ( _WIN64 )
        MessageBoxA(0, Exception.what(), GCRYPTO_ERROR_DIALOG_TITLE, MB_OK);
#endif  /* defined ( _WIN32 ) || defined ( _WIN64 ) */
        checkf(false, TEXT("%s"),
               StringCast<WIDECHAR>(Exception.what()).Get());
    }

    catch (...)
    {
#if defined ( _WIN32 ) || defined ( _WIN64 )
        MessageBoxA(0, GCRYPTO_UNKNOWN_ERROR_MESSAGE, GCRYPTO_ERROR_DIALOG_TITLE, MB_OK);
#endif  /* defined ( _WIN32 ) || defined ( _WIN64 ) */
        checkf(false, TEXT("%s"),
               StringCast<WIDECHAR>(GCRYPTO_UNKNOWN_ERROR_MESSAGE).Get());
    }
}

void GCryptoImpl::Sign(const GCryptoByte* Key, const uint64 KeySize,
                       const GCryptoBuffer& PlainBuffer, FString& Out_MAC)
{
    GCryptoImpl::Sign(
                Key, KeySize,
                &PlainBuffer[0], static_cast<uint64>(PlainBuffer.size()),
            Out_MAC);
}

void GCryptoImpl::Sign(const GCryptoByte* Key, const uint64 KeySize,
                       const std::string& PlainString, FString& Out_MAC)
{
    GCryptoImpl::Sign(
                Key, KeySize,
                reinterpret_cast<const GCryptoByte*>(PlainString.c_str()),
                static_cast<uint64>(PlainString.size()),
                Out_MAC);
}

void GCryptoImpl::Sign(const GCryptoByte* Key, const uint64 KeySize,
                       const FString& PlainString, FString& Out_MAC)
{
    GCryptoImpl::Sign(
                Key, KeySize,
                reinterpret_cast<const GCryptoByte*>(
                    StringCast<ANSICHAR>(*PlainString).Get()),
                static_cast<uint64>(PlainString.Len()),
                Out_MAC);
}

GCryptoImpl::GCryptoImpl(const GCryptoByte* SignKey, const uint64 SignKeySize)
    : Pimpl(std::make_unique<GCryptoImpl::Impl>())
{
    Pimpl->SignKey = new GCryptoByte[SignKeySize];
    Pimpl->SignKeySize = SignKeySize;
    std::copy(SignKey, SignKey + SignKeySize, Pimpl->SignKey);
}

GCryptoImpl::GCryptoImpl(const GCryptoBuffer& SignKey)
    : GCryptoImpl(&SignKey[0], static_cast<uint64>(SignKey.size()))
{

}

GCryptoImpl::~GCryptoImpl() = default;

void GCryptoImpl::Sign(const GCryptoByte* PlainBuffer,
                       const uint64 PlainBufferSize,
                       FString& Out_MAC) const
{
    return GCryptoImpl::Sign(Pimpl->SignKey, Pimpl->SignKeySize,
                             PlainBuffer, PlainBufferSize, Out_MAC);
}

void GCryptoImpl::Sign(const GCryptoBuffer& PlainBuffer,
                       FString& Out_MAC) const
{
    return GCryptoImpl::Sign(Pimpl->SignKey, Pimpl->SignKeySize,
                             PlainBuffer, Out_MAC);
}

void GCryptoImpl::Sign(const std::string& PlainString, FString& Out_MAC) const
{
    return GCryptoImpl::Sign(Pimpl->SignKey, Pimpl->SignKeySize,
                             PlainString, Out_MAC);
}

void GCryptoImpl::Sign(const FString& PlainString, FString& Out_MAC) const
{
    GCryptoImpl::Sign(Pimpl->SignKey, Pimpl->SignKeySize,
                      PlainString, Out_MAC);
}

GCryptoImpl::Impl::Impl()
{

}

GCryptoImpl::Impl::~Impl()
{
    delete SignKey;
    SignKey = nullptr;
}

max_stars_repo_name: SeditiousGames/GodsOfDeceit

max_issues_repo_name: SeditiousGames/GodsOfDeceit

max_forks_repo_name: SeditiousGames/GodsOfDeceit


text:
/*    This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
 *    See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
 *    Author(s):       Pawel Dlotko
 *
 *    Copyright (C) 2016 Inria
 *
 *    Modification(s):
 *      - YYYY/MM Author: Description of the modification
 */

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE "Persistence_intervals_with_distances_test"
#include <boost/test/unit_test.hpp>
#include <gudhi/reader_utils.h>
#include <gudhi/Persistence_intervals_with_distances.h>
#include <gudhi/common_persistence_representations.h>
#include <gudhi/Unitary_tests_utils.h>

#include <iostream>

using namespace Gudhi;
using namespace Gudhi::Persistence_representations;

BOOST_AUTO_TEST_CASE(check_bottleneck_distances_computation) {
  Persistence_intervals_with_distances p("data/file_with_diagram");
  Persistence_intervals_with_distances q("data/file_with_diagram_1");

  double dist = p.distance(q);

  GUDHI_TEST_FLOAT_EQUALITY_CHECK(dist, 0.389043, Gudhi::Persistence_representations::epsi);
}

BOOST_AUTO_TEST_CASE(check_default_parameters_in_distance) {
  Persistence_intervals_with_distances p("data/file_with_diagram");
  Persistence_intervals_with_distances q("data/file_with_diagram_1");

  double default_parameter_distance = p.distance(q);
  double max_parameter_distance = p.distance(q, std::numeric_limits<double>::max());
  double inf_parameter_distance = p.distance(q, std::numeric_limits<double>::infinity());

  GUDHI_TEST_FLOAT_EQUALITY_CHECK(default_parameter_distance, max_parameter_distance);
  GUDHI_TEST_FLOAT_EQUALITY_CHECK(inf_parameter_distance, max_parameter_distance);
  GUDHI_TEST_FLOAT_EQUALITY_CHECK(inf_parameter_distance, max_parameter_distance);
}

max_stars_repo_name: jmarino/gudhi-devel

max_issues_repo_name: jmarino/gudhi-devel

max_forks_repo_name: jmarino/gudhi-devel


text:
#pragma once

////////////////////////////////////////////////////////////////////////////////
#include <polyfem/Common.hpp>
#include <polyfem/LinearSolver.hpp>
#include <Eigen/Dense>
#include <Eigen/Sparse>
#include <memory>
////////////////////////////////////////////////////////////////////////////////

namespace polyfem {

///
/// @brief         { Solve a linear system Ax = b with Dirichlet boundary
///                conditions. For each Dirichlet node i, we want to ensure that
///                x[i] = b[i]. The implementation follows
///                http://www.math.colostate.edu/~bangerth/videos.676.21.65.html
///
///                For memory efficiency, this function updates in place the
///                matrix of the linear system. We also return the modified rhs
///                to the user }
///
/// @param[in]     solver           { Linear solver class to use for solving the
///                                 system }
/// @param[in,out] A                { Matrix of the linear system without
///                                 boundary conditions. Output: modified
///                                 matrix. }
/// @param[in,out] b                { Right-hand side of the linear system.
///                                 Output: modified rhs for the equivalent
///                                 system. }
/// @param[in]     dirichlet_nodes  { List of ids of Dirichlet nodes }
/// @param[in,out] x                { Unknown vector }
///
Eigen::Vector4d dirichlet_solve(LinearSolver &solver, StiffnessMatrix &A,
	Eigen::VectorXd &b, const std::vector<int> &dirichlet_nodes, Eigen::VectorXd &x, const std::string &save_path = "",
	bool compute_spectrum = false);

} // namespace polyfem

ext: hpp

max_stars_repo_name: ldXiao/polyfem

max_issues_repo_name: ldXiao/polyfem

max_forks_repo_name: ldXiao/polyfem


text:
/* boost random/poisson_distribution.hpp header file
 *
 * Copyright Jens Maurer 2002
 * Copyright Steven Watanabe 2010
 * Distributed under the Boost Software License, Version 1.0. (See
 * accompanying file LICENSE_1_0.txt or copy at
 * http://www.boost.org/LICENSE_1_0.txt)
 *
 * See http://www.boost.org for most recent version including documentation.
 *
 * $Id$
 *
 */

#ifndef BOOST_RANDOM_POISSON_DISTRIBUTION_HPP
#define BOOST_RANDOM_POISSON_DISTRIBUTION_HPP

#include <boost/config/no_tr1/cmath.hpp>
#include <cstdlib>
#include <iosfwd>
#include <boost/assert.hpp>
#include <boost/limits.hpp>
#include <boost/random/uniform_01.hpp>
#include <boost/random/detail/config.hpp>

#include <boost/random/detail/disable_warnings.hpp>

namespace lslboost {
namespace random {

namespace detail {

template<class RealType>
struct poisson_table {
    static RealType value[10];
};

template<class RealType>
RealType poisson_table<RealType>::value[10] = {
    0.0,
    0.0,
    0.69314718055994529,
    1.7917594692280550,
    3.1780538303479458,
    4.7874917427820458,
    6.5792512120101012,
    8.5251613610654147,
    10.604602902745251,
    12.801827480081469
};

}

/**
 * An instantiation of the class template @c poisson_distribution is a
 * model of \random_distribution.  The poisson distribution has
 * \f$p(i) = \frac{e^{-\lambda}\lambda^i}{i!}\f$
 *
 * This implementation is based on the PTRD algorithm described
 *
 *  @blockquote
 *  "The transformed rejection method for generating Poisson random variables",
 *  Wolfgang Hormann, Insurance: Mathematics and Economics
 *  Volume 12, Issue 1, February 1993, Pages 39-45
 *  @endblockquote
 */
template<class IntType = int, class RealType = double>
class poisson_distribution {
public:
    typedef IntType result_type;
    typedef RealType input_type;

    class param_type {
    public:
        typedef poisson_distribution distribution_type;
        /**
         * Construct a param_type object with the parameter "mean"
         *
         * Requires: mean > 0
         */
        explicit param_type(RealType mean_arg = RealType(1))
          : _mean(mean_arg)
        {
            BOOST_ASSERT(_mean > 0);
        }
        /* Returns the "mean" parameter of the distribution. */
        RealType mean() const { return _mean; }
#ifndef BOOST_RANDOM_NO_STREAM_OPERATORS
        /** Writes the parameters of the distribution to a @c std::ostream. */
        template<class CharT, class Traits>
        friend std::basic_ostream<CharT, Traits>&
        operator<<(std::basic_ostream<CharT, Traits>& os,
                   const param_type& parm)
        {
            os << parm._mean;
            return os;
        }

        /** Reads the parameters of the distribution from a @c std::istream. */
        template<class CharT, class Traits>
        friend std::basic_istream<CharT, Traits>&
        operator>>(std::basic_istream<CharT, Traits>& is, param_type& parm)
        {
            is >> parm._mean;
            return is;
        }
#endif
        /** Returns true if the parameters have the same values. */
        friend bool operator==(const param_type& lhs, const param_type& rhs)
        {
            return lhs._mean == rhs._mean;
        }
        /** Returns true if the parameters have different values. */
        friend bool operator!=(const param_type& lhs, const param_type& rhs)
        {
            return !(lhs == rhs);
        }
    private:
        RealType _mean;
    };

    /**
     * Constructs a @c poisson_distribution with the parameter @c mean.
     *
     * Requires: mean > 0
     */
    explicit poisson_distribution(RealType mean_arg = RealType(1))
      : _mean(mean_arg)
    {
        BOOST_ASSERT(_mean > 0);
        init();
    }

    /**
     * Construct an @c poisson_distribution object from the
     * parameters.
     */
    explicit poisson_distribution(const param_type& parm)
      : _mean(parm.mean())
    {
        init();
    }

    /**
     * Returns a random variate distributed according to the
     * poisson distribution.
     */
    template<class URNG>
    IntType operator()(URNG& urng) const
    {
        if(use_inversion()) {
            return invert(urng);
        } else {
            return generate(urng);
        }
    }

    /**
     * Returns a random variate distributed according to the
     * poisson distribution with parameters specified by param.
     */
    template<class URNG>
    IntType operator()(URNG& urng, const param_type& parm) const
    {
        return poisson_distribution(parm)(urng);
    }

    /** Returns the "mean" parameter of the distribution. */
    RealType mean() const { return _mean; }

    /** Returns the smallest value that the distribution can produce. */
    IntType min BOOST_PREVENT_MACRO_SUBSTITUTION() const { return 0; }
    /** Returns the largest value that the distribution can produce. */
    IntType max BOOST_PREVENT_MACRO_SUBSTITUTION() const
    { return (std::numeric_limits<IntType>::max)(); }

    /** Returns the parameters of the distribution. */
    param_type param() const { return param_type(_mean); }
    /** Sets parameters of the distribution. */
    void param(const param_type& parm)
    {
        _mean = parm.mean();
        init();
    }

    /**
     * Effects: Subsequent uses of the distribution do not depend
     * on values produced by any engine prior to invoking reset.
     */
    void reset() { }

#ifndef BOOST_RANDOM_NO_STREAM_OPERATORS
    /** Writes the parameters of the distribution to a @c std::ostream. */
    template<class CharT, class Traits>
    friend std::basic_ostream<CharT,Traits>&
    operator<<(std::basic_ostream<CharT,Traits>& os,
               const poisson_distribution& pd)
    {
        os << pd.param();
        return os;
    }

    /** Reads the parameters of the distribution from a @c std::istream. */
    template<class CharT, class Traits>
    friend std::basic_istream<CharT,Traits>&
    operator>>(std::basic_istream<CharT,Traits>& is, poisson_distribution& pd)
    {
        pd.read(is);
        return is;
    }
#endif

    /** Returns true if the two distributions will produce the same
        sequence of values, given equal generators. */
    friend bool operator==(const poisson_distribution& lhs,
                           const poisson_distribution& rhs)
    {
        return lhs._mean == rhs._mean;
    }
    /** Returns true if the two distributions could produce different
        sequences of values, given equal generators. */
    friend bool operator!=(const poisson_distribution& lhs,
                           const poisson_distribution& rhs)
    {
        return !(lhs == rhs);
    }

private:

    /// @cond show_private

    template<class CharT, class Traits>
    void read(std::basic_istream<CharT, Traits>& is) {
        param_type parm;
        if(is >> parm) {
            param(parm);
        }
    }

    bool use_inversion() const
    {
        return _mean < 10;
    }

    static RealType log_factorial(IntType k)
    {
        BOOST_ASSERT(k >= 0);
        BOOST_ASSERT(k < 10);
        return detail::poisson_table<RealType>::value[k];
    }

    void init()
    {
        using std::sqrt;
        using std::exp;

        if(use_inversion()) {
            _u._exp_mean = exp(-_mean);
        } else {
            _u._ptrd.smu = sqrt(_mean);
            _u._ptrd.b = 0.931 + 2.53 * _u._ptrd.smu;
            _u._ptrd.a = -0.059 + 0.02483 * _u._ptrd.b;
            _u._ptrd.inv_alpha = 1.1239 + 1.1328 / (_u._ptrd.b - 3.4);
            _u._ptrd.v_r = 0.9277 - 3.6224 / (_u._ptrd.b - 2);
        }
    }

    template<class URNG>
    IntType generate(URNG& urng) const
    {
        using std::floor;
        using std::abs;
        using std::log;

        while(true) {
            RealType u;
            RealType v = uniform_01<RealType>()(urng);
            if(v <= 0.86 * _u._ptrd.v_r) {
                u = v / _u._ptrd.v_r - 0.43;
                return static_cast<IntType>(floor(
                    (2*_u._ptrd.a/(0.5-abs(u)) + _u._ptrd.b)*u + _mean + 0.445));
            }

            if(v >= _u._ptrd.v_r) {
                u = uniform_01<RealType>()(urng) - 0.5;
            } else {
                u = v/_u._ptrd.v_r - 0.93;
                u = ((u < 0)? -0.5 : 0.5) - u;
                v = uniform_01<RealType>()(urng) * _u._ptrd.v_r;
            }

            RealType us = 0.5 - abs(u);
            if(us < 0.013 && v > us) {
                continue;
            }

            RealType k = floor((2*_u._ptrd.a/us + _u._ptrd.b)*u+_mean+0.445);
            v = v*_u._ptrd.inv_alpha/(_u._ptrd.a/(us*us) + _u._ptrd.b);

            RealType log_sqrt_2pi = 0.91893853320467267;

            if(k >= 10) {
                if(log(v*_u._ptrd.smu) <= (k + 0.5)*log(_mean/k)
                               - _mean
                               - log_sqrt_2pi
                               + k
                               - (1/12. - (1/360. - 1/(1260.*k*k))/(k*k))/k) {
                    return static_cast<IntType>(k);
                }
            } else if(k >= 0) {
                if(log(v) <= k*log(_mean)
                           - _mean
                           - log_factorial(static_cast<IntType>(k))) {
                    return static_cast<IntType>(k);
                }
            }
        }
    }

    template<class URNG>
    IntType invert(URNG& urng) const
    {
        RealType p = _u._exp_mean;
        IntType x = 0;
        RealType u = uniform_01<RealType>()(urng);
        while(u > p) {
            u = u - p;
            ++x;
            p = _mean * p / x;
        }
        return x;
    }

    RealType _mean;

    union {
        // for ptrd
        struct {
            RealType v_r;
            RealType a;
            RealType b;
            RealType smu;
            RealType inv_alpha;
        } _ptrd;
        // for inversion
        RealType _exp_mean;
    } _u;

    /// @endcond
};

} // namespace random

using random::poisson_distribution;

} // namespace lslboost

#include <boost/random/detail/enable_warnings.hpp>

#endif // BOOST_RANDOM_POISSON_DISTRIBUTION_HPP

max_stars_repo_name: samuelpowell/liblsl

max_issues_repo_name: samuelpowell/liblsl

max_forks_repo_name: samuelpowell/liblsl


text:
////////////////////////////////////////////////////////////////////////////////
// Name:      ctags.cpp
// Purpose:   Implementation of class wex::ctags
//            https://github.com/universal-ctags/ctags
// Author:    Anton van Wezenbeek
// Copyright: (c) 2021 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////

#include <algorithm>
#include <vector>

#include <boost/algorithm/string.hpp>
#include <readtags.h>

#include <wex/config.h>
#include <wex/ctags.h>
#include <wex/ex.h>
#include <wex/factory/stc.h>
#include <wex/frame.h>
#include <wex/frd.h>
#include <wex/log.h>
#include <wex/path.h>
#include <wx/app.h>
#include <wx/choicdlg.h>

namespace wex
{
auto* get_frame()
{
  return dynamic_cast<frame*>(wxTheApp->GetTopWindow());
}

const std::string tag_name(const path& p)
{
  return config(_("stc.vi tag fullpath")).get(false) ? p.string() :
                                                       p.filename();
};

// Support class.
class ctags_info
{
public:
  // Constructor.
  explicit ctags_info(const tagEntry& entry)
    : m_line_number(entry.address.lineNumber)
    , m_path(entry.file)
    , m_pattern(
        [](const tagEntry& entry)
        {
          std::string pattern(
            entry.address.pattern != nullptr ?
              // prepend colon to force ex command
              ":" + std::string(entry.address.pattern) :
              std::string());
          // the pattern generated by
          // ctags mixes regex with non regex....
          boost::algorithm::replace_all(pattern, "*", "\\*");
          boost::algorithm::replace_all(pattern, "(", "\\(");
          boost::algorithm::replace_all(pattern, ")", "\\)");
          return pattern;
        }(entry))
  {
  }

  // Returns name, being fullpath or path name depending on
  // config settings.
  const std::string name() const { return tag_name(m_path); }

  // Opens file in specified frame.
  auto open_file(factory::frame* frame) const
  {
    return frame->open_file(
      m_path,
      data::control().line(m_line_number).command(m_pattern));
  }

private:
  const path        m_path;
  const int         m_line_number;
  const std::string m_pattern;
};
}; // namespace wex

std::map<std::string, wex::ctags_info>           wex::ctags::m_matches;
std::map<std::string, wex::ctags_info>::iterator wex::ctags::m_iterator;

wex::ctags::ctags(wex::ex* ex, bool open_file)
  : m_ex(ex)
{
  if (open_file)
  {
    open();
  }
}

const std::string
wex::ctags::auto_complete(const std::string& text, const ctags_entry& filter)
{
  if (m_file == nullptr)
  {
    return std::string();
  }

  ctags_entry entry(filter);

  if (text.empty())
  {
    if (tagsFirst(m_file, &entry.entry()) == TagFailure)
    {
      return std::string();
    }
  }
  else if (
    tagsFind(
      m_file,
      &entry.entry(),
      text.c_str(),
      TAG_PARTIALMATCH | TAG_OBSERVECASE) == TagFailure)
  {
    return std::string();
  }

  if (!m_is_prepared)
  {
    auto_complete_prepare();
  }

  std::string s, prev_tag;

  const int min_size{3}, max{100};
  int       count{0};
  tagResult result = TagSuccess;

  do
  {
    if (const auto& tag(entry.entry_string(min_size));
        !tag.empty() && tag != prev_tag)
    {
      s.append(tag);
      s.push_back(m_separator);
      count++;
      prev_tag = tag;
    }

    result =
      (text.empty() ? tagsNext(m_file, &entry.entry()) :
                      tagsFindNext(m_file, &entry.entry()));
  } while (result == TagSuccess && count < max);

  log::trace("ctags::auto_complete count") << count;

  return s;
}

void wex::ctags::auto_complete_prepare()
{
  m_ex->get_stc()->AutoCompSetIgnoreCase(false);
  m_ex->get_stc()->AutoCompSetAutoHide(false);

  ctags_entry::register_image(m_ex->get_stc());

  m_is_prepared = true;
}

bool wex::ctags::close()
{
  if (m_file == nullptr || tagsClose(m_file) == TagFailure)
  {
    return false;
  }

  m_file = nullptr;

  return true;
}

bool wex::ctags::do_open(const std::string& path)
{
  if (tagFileInfo info; (m_file = tagsOpen(path.c_str(), &info)) != nullptr)
  {
    log::trace("ctags file") << path;
    return true;
  }

  return false;
}

bool wex::ctags::find(const std::string& tag, ex* ex)
{
  if (m_file == nullptr)
  {
    return false;
  }

  if (tag.empty())
  {
    log::trace("ctags::find empty tag") << m_matches.size();
    return next();
  }

  ctags_entry entry;

  if (
    tagsFind(m_file, &entry.entry(), tag.c_str(), TAG_FULLMATCH) == TagFailure)
  {
    log::status("Tag not found") << tag;
    return false;
  }

  m_matches.clear();

  do
  {
    if (const ctags_info ct(entry.entry());
        ex == nullptr || (ct.name() != tag_name(ex->get_stc()->path())))
    {
      m_matches.insert({ct.name(), ct});
    }
  } while (tagsFindNext(m_file, &entry.entry()) == TagSuccess);

  m_iterator = m_matches.begin();

  log::trace("ctags::find matches") << m_matches.size();

  switch (m_matches.size())
  {
    case 0:
      if (ex != nullptr)
      {
        ex->get_stc()->find(tag);
      }
      break;

    case 1:
      m_matches.begin()->second.open_file(get_frame());
      break;

    default:
    {
      wxArrayString as;

      for (const auto& it : m_matches)
        as.Add(it.second.name());

      wxMultiChoiceDialog dialog(
        get_frame(),
        _("Input") + ":",
        _("Select File"),
        as);

      if (dialog.ShowModal() != wxID_OK)
        return false;

      for (const auto& sel : dialog.GetSelections())
      {
        m_iterator = m_matches.find(as[sel]);
        m_iterator->second.open_file(get_frame());
      }
    }
  }

  find_replace_data::get()->set_find_string(tag);

  return true;
}

bool wex::ctags::find(const std::string& tag, wex::ctags_entry& filter)
{
  if (m_file == nullptr)
  {
    return false;
  }

  ctags_entry entry;

  // Find first entry. This entry determines which kind of
  // filter will be set.
  if (
    tagsFind(m_file, &entry.entry(), tag.c_str(), TAG_FULLMATCH) == TagFailure)
  {
    return false;
  }

  filter.clear();

  do
  {
    if (entry.is_master())
    {
      filter.filter(entry);
      return true;
    }
  } while (!entry.is_master() &&
           tagsFindNext(m_file, &entry.entry()) == TagSuccess);

  return false;
}

bool wex::ctags::next()
{
  if (m_matches.size() <= 1)
  {
    log::trace("ctags::next no next match") << m_matches.size();
    return false;
  }

  if (++m_iterator == m_matches.end())
  {
    m_iterator = m_matches.begin();
  }

  m_iterator->second.open_file(get_frame());

  return true;
}

void wex::ctags::open(const std::string& filename)
{
  if (m_file != nullptr)
  {
    return;
  }

  m_iterator = m_matches.begin();

  if (filename != DEFAULT_TAGFILE)
  {
    do_open(filename);
  }
  else if (const std::vector<std::string> v{"./", config::dir().string() + "/"};
           !std::any_of(
             v.begin(),
             v.end(),
             [filename](const auto& p)
             {
               return do_open(p + filename);
             }))
  {
    if (filename != DEFAULT_TAGFILE && m_file == nullptr)
    {
      log("could not locate ctags file") << filename;
    }
  }
}

bool wex::ctags::previous()
{
  if (m_matches.size() <= 1)
  {
    log::trace("ctags::previous no previous match") << m_matches.size();
    return false;
  }

  if (m_iterator == m_matches.begin())
  {
    m_iterator = m_matches.end();
  }

  --m_iterator;

  m_iterator->second.open_file(get_frame());

  return true;
}

max_stars_repo_name: antonvw/wex

max_issues_repo_name: antonvw/wex

max_forks_repo_name: antonvw/wex


text:
/* -*- C++ -*-; c-basic-offset: 4; indent-tabs-mode: nil */
/*
 * Copyright (c) 2017 Cisco Systems, Inc. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */

#include <boost/optional.hpp>

#include <opflexagent/Agent.h>

#include "VppRuntime.hpp"

namespace VOM
{
class gbp_endpoint_group;
class gbp_bridge_domain;
class gbp_route_domain;
class bridge_domain;
class route_domain;
class vxlan_tunnel;
};

namespace VPP
{
class EndPointGroupManager
{
  public:
    struct ForwardInfo
    {
        ForwardInfo();
        ~ForwardInfo() = default;

        uint16_t sclass;
        uint32_t vnid;
        uint32_t rdId;
        uint32_t bdId;
        boost::optional<opflex::modb::URI> rdURI;
        boost::optional<opflex::modb::URI> bdURI;
    };
    struct NoFowardInfoException
    {
        NoFowardInfoException(std::string s)
            : reason(s)
        {
        }

        std::string reason;
    };

    EndPointGroupManager(Runtime &runtime);

    static ForwardInfo
    get_fwd_info(Runtime &r,
                 const opflex::modb::URI &uri) throw(NoFowardInfoException);
    static ForwardInfo get_fwd_info_ext_itf(
        Runtime &r, const opflex::modb::URI &uri) throw(NoFowardInfoException);

    void handle_update(const opflex::modb::URI &epgURI);

    static std::shared_ptr<VOM::gbp_endpoint_group>
    mk_group(Runtime &r,
             const std::string &key,
             const opflex::modb::URI &uri,
             bool is_ext = false);

    static std::shared_ptr<VOM::gbp_route_domain>
    mk_gbp_rd(Runtime &r,
              const std::string &key,
              const VOM::route_domain &rd,
              uint32_t vnid);

    static std::shared_ptr<vxlan_tunnel>
    mk_mcast_tunnel(Runtime &r,
                    const std::string &key,
                    uint32_t vni,
                    const std::string &maddr);

    static std::shared_ptr<VOM::interface>
    mk_bvi(Runtime &r,
           const std::string &key,
           const VOM::bridge_domain &bd,
           const VOM::route_domain &rd,
           const boost::optional<mac_address_t> &mac = boost::none);

  private:
    /**
     * Referene to runtime data.
     */
    Runtime &m_runtime;
};
};

/*
 * Local Variables:
 * eval: (c-set-style "llvm.org")
 * End:
 */

max_stars_repo_name: opflex-vpp/vpp-renderer

max_issues_repo_name: nranns/vpp-renderer

max_forks_repo_name: nranns/vpp-renderer


text:
//--------------------------------------------------------------------------------------
// File: validator.cpp
//
// Handles command line argument parsing invoking the disassembly routine.
//
// Copyright (c) Oberoi Security Solutions. All rights reserved.
// Licensed under the Apache 2.0 License.
//--------------------------------------------------------------------------------------

#include <iostream>
#include <boost/algorithm/string.hpp>
#include <boost/program_options.hpp>
#include <boost/filesystem/fstream.hpp>
#include <loadimage.hh>
#include <sleigh.hh>
using namespace std;

// This is a tiny LoadImage class which feeds the executable bytes to the translator
// Taken straight from sleighexample.cc
class MyLoadImage : public LoadImage {
  uintb baseaddr;
  int4 length;
  uint1 *data;
public:
  MyLoadImage(uintb ad,uint1 *ptr,int4 sz) : LoadImage("nofile") { baseaddr = ad; data = ptr; length = sz; }
  virtual void loadFill(uint1 *ptr,int4 size,const Address &addr);
  virtual string getArchType(void) const { return "myload"; }
  virtual void adjustVma(long adjust) { }
};

// This is the only important method for the LoadImage. It returns bytes from the static array
// depending on the address range requested
void MyLoadImage::loadFill(uint1 *ptr,int4 size,const Address &addr)

{
  uintb start = addr.getOffset();
  uintb max = baseaddr + (length-1);
  for(int4 i=0;i<size;++i) {	// For every byte requestes
    uintb curoff = start + i; // Calculate offset of byte
    if ((curoff < baseaddr)||(curoff>max)) {	// If byte does not fall in window
      ptr[i] = 0;		// return 0
      continue;
    }
    uintb diff = curoff - baseaddr;
    ptr[i] = data[(int4)diff];	// Otherwise return data from our window
  }
}

// Here is a simple class for emitting assembly.  In this case, we send the strings straight
// to standard out.
class AssemblyRaw : public AssemblyEmit {
public:
  virtual void dump(const Address &addr,const string &mnem,const string &body) {
        disassembly = mnem + " " + body;
        boost::trim(disassembly);
  }
  string disassembly;
};

// converts unsigned char to two byte hex value
#define CHAR2HEX( x ) setw(2) << setfill('0') << uppercase << hex << (unsigned int)x

int parseInputAndDisassemble(string& inputFilename, string& outputFilename, string& slaFilename);
int convertOpcodeToBinary(string& opcode, vector<unsigned char>& opcodeBytes);
int convertHexNibbletoInteger(unsigned char x);
int sleighDisassemble(string& slaFilename, vector<unsigned char>& opcodeBytes, string& disassembly);

int main(int argc, char *argv[])
{
    boost::program_options::options_description desc{"Ghidra Processor Module Generator Validator"};
    boost::program_options::variables_map args;
    string inputFilename;
    string outputFilename;
    string slaFilename;
    int result = 0;

    cout << "Ghidra Processor Module Generator (GPMG) Validator" << endl;

    //
    // command line arg parsing
    //

    try
    {
        desc.add_options()
            ("input-file,i", boost::program_options::value<string>(&inputFilename), "Path to a newline delimited text file containing all opcodes and instructions for the processor module. Required.")
            ("output-file,o",boost::program_options::value<string>(&outputFilename)->default_value("output.txt"), "Output file. Defaults to output.txt if not specified.")
            ("sla-file,s",boost::program_options::value<string>(&slaFilename), "Path to the compiled processor .sla.")
            ("help,h", "Help screen");

        store(parse_command_line(argc, argv, desc), args);
        notify(args);

        if(args.count("help") || argc == 1)
        {
            cout << desc << endl;
            return 0;
        }

        if(args.count("input-file") == 0)
        {
            cout << "Input file name is required!!" << endl;
            return -1;
        }

        if(args.count("sla-file") == 0)
        {
            cout << "Sla file name is required!!" << endl;
            return -1;
        }
    }
    catch (const boost::program_options::error &ex)
    {
        cout << "[-] Error parsing command line: " << ex.what() << endl;
        return -1;
    }

    cout << "[*] Input file: " << inputFilename << endl;
    cout << "[*] Compiled SLA file: " << slaFilename << endl;
    cout << "[*] Outputting (might take a while) to: " << outputFilename << endl;

    result = parseInputAndDisassemble(inputFilename, outputFilename, slaFilename);
    if(result != 0)
    {
        return result;
    }

    cout << "[*] Successfully created output disassembly file. Diff input and output files to find errors in the SLA." << endl;
    return 0;
}

// Parses the input file for addresses and passes it to the SLEIGH disassembler for output
int parseInputAndDisassemble(string& inputFilename, string& outputFilename, string& slaFilename)
{
    unsigned int lineNum = 0;
    int result = 0;
    std::string line;

    // open the input file for parsing
    boost::filesystem::path infile{inputFilename};
    boost::filesystem::ifstream ifs{infile};

    boost::filesystem::path outfile{outputFilename};
    boost::filesystem::ofstream ofs{outfile};

    if(!ifs)
    {
        cout << "[-] Failed to open input file!!" << endl;
        return -1;
    }

    if(!ofs)
    {
        cout << "[-] Failed to open output file!!" << endl;
        return -1;
    }

    //
    // parse the input file line by line
    //
    while (std::getline(ifs, line))
    {
        vector<string> lineSplit;
        vector<unsigned char> opcodeBytes;
        string disassembly;

        lineNum++;

        // split the line into components
        boost::split(lineSplit, line, boost::algorithm::is_space(), boost::token_compress_on);

        if(lineSplit.size() < 1)
        {
            continue;
        }

        result = convertOpcodeToBinary(lineSplit[0], opcodeBytes);
        if(result != 0)
        {
            cout << "Failed to covert opcode!!" << endl;
            goto exit;
        }

        result = sleighDisassemble(slaFilename, opcodeBytes, disassembly);
        if(result != 0)
        {
            goto exit;
        }

        ofs << "0x";
        for (auto& x: opcodeBytes)
        {
            ofs << CHAR2HEX(x);
        }
        ofs << " " << disassembly;
        ofs << endl;
    }

    result = 0;

exit:
    ifs.close();
    ofs.close();
    return result;
}

// disassembles opcode bytes using the passed in SLA file
int sleighDisassemble(string& slaFilename, vector<unsigned char>& opcodeBytes, string& disassembly)
{
    unsigned char buffer[4096] = {0};

    // initialize instruction to disassemble
    for(unsigned int i = 0; i < opcodeBytes.size(); i++)
    {
        buffer[i] = opcodeBytes[i];
    }

    // instantiate sleigh
    try
    {
        MyLoadImage loader(0, (uint1*)buffer, sizeof(buffer));

        // Set up the context object
        ContextInternal context;

        // Set up the disassembler
        Sleigh trans(&loader, &context);

        // Read sleigh file into DOM
        DocumentStorage docstorage;
        Element *sleighroot = docstorage.openDocument(slaFilename)->getRoot();
        docstorage.registerTag(sleighroot);
        trans.initialize(docstorage); // Initialize the translator

        AssemblyRaw assememit;	// Set up the disassembly dumper
        Address addr(trans.getDefaultCodeSpace(), 0); // First disassembly address

        // dump the disassembly now
        trans.printAssembly(assememit, addr);
        disassembly = assememit.disassembly;
    }
    catch(XmlError e)
    {
        cout << "Failed to instantiate SLEIGH. Is processor SLA invalid?" << endl;
        return -1;
    }
    catch(BadDataError e)
    {
        // disassembly error, just report it as a success so it appears in the output
        disassembly = "Error";
        return 0;
    }
    catch(...)
    {
        cout << "Unknown error during disassembly!!\n";
        return -3;
    }

    return 0;
}

// converts an opcode in the of 0xaabb... or 0b0011... to a an array of raw bytes
int convertOpcodeToBinary(string& opcode, vector<unsigned char>& opcodeBytes)
{
    int opcodeLength = 0;

    // opcode must begin with 0x or 0b
    if(opcode[0] != '0')
    {
        cout << "Opcode must begin with 0x or 0b!!" << endl;
        return -1;
    }

    if(opcode[1] == 'x' || opcode[1] == 'X')
    {
        opcodeLength = opcode.length() - 2;
        if((opcodeLength % 2) != 0)
        {
            cout << "Hex opcode length must be divisble by 2!!" << endl;
            return -2;
        }

         // loop through the hex string, converting each byte
        for(unsigned int i = 2; i < opcode.length(); i += 2)
        {
            unsigned char value;
            unsigned char high;
            unsigned char low;

            // convert the hex string to a byte
            high = convertHexNibbletoInteger(opcode[i]);
            low = convertHexNibbletoInteger(opcode[i+1]);

            value = (high << 4) | low;

            opcodeBytes.push_back(value);
        }

        return 0;
    }
    else if(opcode[1] == 'b' || opcode[1] == 'B')
    {
        opcodeLength = opcode.length() - 2;
        if((opcodeLength % 8) != 0)
        {
            cout << "Binary opcode length must be divisble by 8!!" << endl;
            return -2;
        }

        // loop through the bit string, converting each byte
        for(unsigned int i = 2; i < opcode.length(); i += 8)
        {
            unsigned char value = 0;

            for(unsigned int j = 0; j < 8; j++)
            {
                value = value << 1;
                if(opcode[i + j] == '1')
                {
                    value = value | 1;
                }
            }
            opcodeBytes.push_back(value);
        }

        return 0;
    }
    else
    {
        cout << "Opcode must begin with 0x or 0b!!" << endl;
        return -1;
    }

    return 0;
}

// simple utility to convert an ascii hex char to decimal
int convertHexNibbletoInteger(unsigned char x)
{
    if(x >= '0' && x <= '9')
    {
        return x - '0';
    }

    if(x >= 'A' && x <= 'F')
    {
        return x - 'A' + 0xa;
    }

    if(x >= 'a' && x <= 'f')
    {
        return x - 'a' + 0xa;
    }

    return 0;
}


text:
#include "optimization_task_result.h"

#include <string>
#include <stdexcept>

#ifdef BUILD_WITH_MPI

#include <boost/mpi.hpp>
#include <boost/bind.hpp>
#include <k52/parallel/mpi/constants.h>
#include <k52/parallel/mpi/identifyable_objects_manager.h>

using ::k52::parallel::mpi::AsyncCallChain;

#endif

namespace k52
{
namespace optimization
{

OptimizationTaskResult::OptimizationTaskResult(const IParameters* optimal_parameters)

#ifdef BUILD_WITH_MPI
    : communicator_(), source_(0)
#endif

{
    optimal_parameters_ = IParameters::shared_ptr( optimal_parameters->Clone() );
}

IParameters::shared_ptr OptimizationTaskResult::get_optimal_parameters() const
{
    return optimal_parameters_;
}

#ifdef BUILD_WITH_MPI

AsyncCallChain::shared_ptr OptimizationTaskResult::ReceiveAsync(boost::mpi::communicator* communicator, int source)
{
    //TODO fix partial copypaste from CountObjectiveFunctionTask::Receive
    communicator_ = communicator;
    source_ = source;

    AsyncCallChain::shared_ptr call_chain = AsyncCallChain::CreateAsyncCallChain(
        boost::bind(&OptimizationTaskResult::ReceiveParametersIdAsyncCall, this)
    );
    call_chain->Add(boost::bind(&OptimizationTaskResult::ReceiveParametersAsyncCall, this));
    return call_chain;
}

void OptimizationTaskResult::Send(boost::mpi::communicator* communicator)
{
    //TODO fix copypaste from CountObjectiveFunctionTask::Send
    communicator->send(k52::parallel::mpi::constants::kServerRank,
                       k52::parallel::mpi::constants::kCommonTag,
                       k52::parallel::mpi::IdentifyableObjectsManager::GetId(*optimal_parameters_));
    optimal_parameters_->Send(communicator, k52::parallel::mpi::constants::kServerRank);
}

boost::mpi::request OptimizationTaskResult::ReceiveParametersIdAsyncCall()
{
    return communicator_->irecv(source_, k52::parallel::mpi::constants::kCommonTag, parameters_id_);
}

boost::optional<boost::mpi::request> OptimizationTaskResult::ReceiveParametersAsyncCall()
{
    const IParameters* parameters = dynamic_cast<const IParameters*>( k52::parallel::mpi::IdentifyableObjectsManager::Instance().GetObject(parameters_id_) );
    if (!parameters)
    {
        throw std::runtime_error("Unexpected parameters object received");
    }
    optimal_parameters_ = IParameters::shared_ptr( parameters->Clone() );

    //TODO implement ReceiveAsync for even more effectivness
    optimal_parameters_->Receive(communicator_, source_);

    return boost::optional<boost::mpi::request>();
}
#endif

}/* namespace optimization */
}/* namespace k52 */


text:
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>

int main()
{
  using namespace boost::numeric::ublas;

  matrix<double> m(3,3);

  for(int i=0; i!=m.size1(); ++i)
    for(int j=0; j!=m.size2(); ++j)
      m(i,j)=3*i+j;

  std::cout << trans(m) << std::endl;
}

max_stars_repo_name: ethansaxenian/RosettaDecode

max_issues_repo_name: ethansaxenian/RosettaDecode

max_forks_repo_name: ethansaxenian/RosettaDecode