text:
#include <miopen/conv/invokers/impl_gemm.hpp>

#include <miopen/conv/data_invoke_params.hpp>
#include <miopen/algorithm.hpp>
#include <miopen/handle.hpp>
#include <miopen/tensor_ops.hpp>

#include <boost/any.hpp>

namespace miopen {
namespace conv {

InvokerFactory MakeImplGemmDataInvokerFactory(const ConvolutionContext& ctx)
{
    if(ctx.direction.IsForward())
    {
        return [](const std::vector<Kernel>& kernels) {
            return [=](Handle& handle, const boost::any& primitive_parameters) {
                const auto data_ctx = boost::any_cast<conv::DataInvokeParams>(primitive_parameters);
                const auto& tensors = data_ctx.tensors;
                handle.Run(kernels[0])(tensors.in, tensors.w, tensors.out);
            };
        };
    }
    else
    {
        const auto& conv       = ctx.conv_problem.GetConv();
        const auto& lowp_quant = conv.lowp_quant;

        return [conv, lowp_quant](const std::vector<Kernel>& kernels) {
            return [=](Handle& handle, const boost::any& primitive_parameters) {
                const auto data_ctx = boost::any_cast<conv::DataInvokeParams>(primitive_parameters);
                const auto& tensors = data_ctx.tensors;
                const auto& workSpace = data_ctx.workSpace;

                // Miminum checks. Only check what is required to select
                // proper invocation procedure & workspace sanity.
                auto kernel = handle.Run(kernels[0]);

                float elapsed = 0;
                // clang-format off
                if((tensors.outDesc.GetType() == miopenHalf ||
                    tensors.outDesc.GetType() == miopenBFloat16) &&
                   (kernel.GetName() == "gridwise_convolution_backward_data_implicit_gemm_v1r1_xdlops_nchw_kcyx_nkhw" ||
                    kernel.GetName() == "gridwise_convolution_backward_data_implicit_gemm_v1r1_xdlops_gnchw_gkcyx_gnkhw" ||
                    kernel.GetName() == "gridwise_convolution_backward_data_implicit_gemm_v1r1_nchw_kcyx_nkhw" ||
                    kernel.GetName() == "gridwise_convolution_backward_data_implicit_gemm_v1r1_ncdhw_kczyx_nkdhw"))
                // clang-format on
                {
                    float zero = 0.f;
                    TensorDescriptor workspaceDesc(
                        miopenFloat, tensors.outDesc.GetLengths(), tensors.outDesc.GetStrides());
                    SetTensor(handle, workspaceDesc, workSpace, &zero);
                    if(handle.IsProfilingEnabled())
                        elapsed += handle.GetKernelTime();

                    kernel(tensors.in, tensors.w, workSpace);
                    if(handle.IsProfilingEnabled())
                        elapsed += handle.GetKernelTime();

                    CastTensor(handle,
                               &lowp_quant,
                               workspaceDesc,
                               workSpace,
                               tensors.outDesc,
                               tensors.out,
                               0,
                               0);
                    if(handle.IsProfilingEnabled())
                        elapsed += handle.GetKernelTime();
                }
                // clang-format off
                else if((kernel.GetName() == "gridwise_convolution_implicit_gemm_v4_nchw_kc1x1_nkhw_lds_double_buffer") ||
                        (kernel.GetName() == "gridwise_convolution_implicit_gemm_v4r4_xdlops_nchw_kc1x1_nkhw_lds_double_buffer"))
                // clang-format on
                {
                    bool hasStride =
                        (tensors.inDesc.GetLengths()[2] != tensors.outDesc.GetLengths()[2]) ||
                        (tensors.inDesc.GetLengths()[3] != tensors.outDesc.GetLengths()[3]);
                    /// \todo set zero within implicitGEMM kernel
                    if(hasStride)
                    {
                        MIOPEN_LOG_I2("hasStride, call SetTensor with zero");
                        float zero = 0.f;
                        SetTensor(handle, tensors.outDesc, tensors.out, &zero);

                        if(handle.IsProfilingEnabled())
                            elapsed += handle.GetKernelTime();
                    }

                    kernel(tensors.in, tensors.w, tensors.out);

                    if(handle.IsProfilingEnabled())
                        elapsed += handle.GetKernelTime();
                }
                // clang-format off
                else if(kernel.GetName() == "gridwise_convolution_backward_data_implicit_gemm_v1r1_xdlops_nchw_kcyx_nkhw" ||
                        kernel.GetName() == "gridwise_convolution_backward_data_implicit_gemm_v1r1_xdlops_gnchw_gkcyx_gnkhw")
                // clang-format on
                {
                    float zero = 0.f;
                    SetTensor(handle, tensors.outDesc, tensors.out, &zero);
                    if(handle.IsProfilingEnabled())
                        elapsed += handle.GetKernelTime();

                    kernel(tensors.in, tensors.w, tensors.out);
                    if(handle.IsProfilingEnabled())
                        elapsed += handle.GetKernelTime();
                }
                // clang-format off
                else if(
                    kernel.GetName() == "gridwise_convolution_backward_data_implicit_gemm_v1r1_nchw_kcyx_nkhw" ||
                    kernel.GetName() == "gridwise_convolution_backward_data_implicit_gemm_v1r1_ncdhw_kczyx_nkdhw")
                // clang-format on
                {
                    // this kernel accumulate results into input tensor, therefore need to set zero
                    bool is_1x1_s1 = false;
                    if(miopen::all_of(conv.GetConvPads(), [](auto v) { return v == 0; }) &&
                       miopen::all_of(conv.GetConvStrides(), [](auto v) { return v == 1; }))
                    {
                        if(tensors.wDesc.GetLengths()[2] == 1 && tensors.wDesc.GetLengths()[3] == 1)
                        { // filter = 1
                            if(tensors.wDesc.GetSize() == 4 ||
                               (tensors.wDesc.GetSize() == 5 && tensors.wDesc.GetLengths()[4] == 1))
                            {
                                is_1x1_s1 = true;
                            }
                        }
                    }

                    if(!is_1x1_s1)
                    {
                        float zero = 0.f;
                        SetTensor(handle, tensors.outDesc, tensors.out, &zero);
                        if(handle.IsProfilingEnabled())
                            elapsed += handle.GetKernelTime();
                    }

                    kernel(tensors.in, tensors.w, tensors.out);
                    if(handle.IsProfilingEnabled())
                        elapsed += handle.GetKernelTime();
                }
                // clang-format off
                else if(
                    kernel.GetName() == "gridwise_convolution_backward_data_implicit_gemm_v4r1_nchw_kcyx_nkhw" ||
                    kernel.GetName() == "gridwise_convolution_backward_data_implicit_gemm_v4r1_ncdhw_kczyx_nkdhw")
                // clang-format on
                {
                    // \todo this kernel doesn't always need to set-zero
                    bool filterGeStride = false;
                    if(miopen::all_of(conv.GetConvPads(), [](auto v) { return v == 0; }))
                    {
                        if(tensors.wDesc.GetSize() == 4)
                        { // 2d
                            if(tensors.wDesc.GetLengths()[2] >= conv.GetConvStrides()[0] &&
                               tensors.wDesc.GetLengths()[3] >= conv.GetConvStrides()[1])
                            {
                                filterGeStride = true;
                            }
                        }
                        else
                        { // 3d
                            if(tensors.wDesc.GetLengths()[2] >= conv.GetConvStrides()[0] &&
                               tensors.wDesc.GetLengths()[3] >= conv.GetConvStrides()[1] &&
                               tensors.wDesc.GetLengths()[4] >= conv.GetConvStrides()[2])
                            {
                                filterGeStride = true;
                            }
                        }
                    }

                    if(!filterGeStride)
                    {
                        float zero = 0.f;
                        SetTensor(handle, tensors.outDesc, tensors.out, &zero);

                        if(handle.IsProfilingEnabled())
                            elapsed += handle.GetKernelTime();
                    }

                    // a group kernels (compiled from same source code) will be launched
                    for(const auto& k : kernels)
                    {
                        handle.Run(k)(tensors.in, tensors.w, tensors.out);
                        elapsed += handle.GetKernelTime();
                    }
                }
                else
                {
                    MIOPEN_THROW(
                        "Error running implicit GEMM backward data convolution (none workspace?)");
                }

                if(handle.IsProfilingEnabled())
                {
                    handle.ResetKernelTime();
                    handle.AccumKernelTime(elapsed);
                }
            };
        };
    }
}

} // namespace conv
} // namespace miopen

max_stars_repo_name: nelsonc-amd/MIOpen

max_issues_repo_name: nelsonc-amd/MIOpen

max_forks_repo_name: nelsonc-amd/MIOpen


text:
/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include "FinalInlineV2.h"

#include <boost/variant.hpp>
#include <unordered_set>
#include <vector>

#include "ConstantPropagationAnalysis.h"
#include "ConstantPropagationTransform.h"
#include "Debug.h"
#include "DexAccess.h"
#include "DexClass.h"
#include "DexUtil.h"
#include "IPConstantPropagationAnalysis.h"
#include "IRCode.h"
#include "LocalDce.h"
#include "Resolver.h"
#include "Walkers.h"

/*
 * dx-generated class initializers often use verbose bytecode sequences to
 * initialize static fields, instead of relying on the more compact
 * encoded_value formats. This pass determines the values of the static
 * fields after the <clinit> has finished running, which it uses to generate
 * their encoded_value equivalents. This applies to both final statics and
 * non-final statics.
 *
 * Additionally, for static final fields, this pass inlines sgets to them where
 * possible, replacing them with const / const-wide / const-string opcodes.
 */

namespace cp = constant_propagation;

namespace {

class StringAnalyzer
    : public InstructionAnalyzerBase<StringAnalyzer, ConstantEnvironment> {
 public:
  static bool analyze_const_string(const IRInstruction* insn,
                                   ConstantEnvironment* env) {
    env->set(RESULT_REGISTER, StringDomain(insn->get_string()));
    return true;
  }
};

/*
 * Foo.<clinit> may read some static fields from class Bar, in which case
 * Bar.<clinit> will be executed first by the VM to determine the values of
 * those fields.
 *
 * Similarly, to ensure that our analysis of Foo.<clinit> knows as much about
 * Bar's static fields as possible, we want to analyze Bar.<clinit> before
 * Foo.<clinit>, since Foo.<clinit> depends on it. As such, we do a topological
 * sort of the classes here based on these dependencies.
 *
 * Note that the class initialization graph is *not* guaranteed to be acyclic.
 * (JLS SE7 12.4.1 indicates that cycles are indeed allowed.) In that case,
 * this pass cannot safely optimize the static final constants.
 */
Scope reverse_tsort_by_clinit_deps(const Scope& scope) {
  std::unordered_set<const DexClass*> scope_set(scope.begin(), scope.end());
  Scope result;
  std::unordered_set<const DexClass*> visiting;
  std::unordered_set<const DexClass*> visited;
  std::function<void(DexClass*)> visit = [&](DexClass* cls) {
    if (visited.count(cls) != 0 || scope_set.count(cls) == 0) {
      return;
    }
    if (visiting.count(cls)) {
      throw final_inline::class_initialization_cycle(cls);
    }
    visiting.emplace(cls);
    auto clinit = cls->get_clinit();
    if (clinit != nullptr && clinit->get_code() != nullptr) {
      for (auto& mie : InstructionIterable(clinit->get_code())) {
        auto insn = mie.insn;
        if (is_sget(insn->opcode())) {
          auto dependee_cls = type_class(insn->get_field()->get_class());
          if (dependee_cls == nullptr || dependee_cls == cls) {
            continue;
          }
          visit(dependee_cls);
        }
      }
    }
    visiting.erase(cls);
    result.emplace_back(cls);
    visited.emplace(cls);
  };
  for (DexClass* cls : scope) {
    visit(cls);
  }
  return result;
}

using CombinedAnalyzer =
    InstructionAnalyzerCombiner<cp::ClinitFieldAnalyzer,
                                cp::WholeProgramAwareAnalyzer,
                                StringAnalyzer,
                                cp::PrimitiveAnalyzer>;

// A trivial clinit should only contain a return-void instruction.
bool is_trivial_clinit(const DexMethod* method) {
  auto ii = InstructionIterable(method->get_code());
  return std::none_of(ii.begin(), ii.end(), [](const MethodItemEntry& mie) {
    return mie.insn->opcode() != OPCODE_RETURN_VOID;
  });
}

/*
 * Converts a ConstantValue into its equivalent encoded_value. Returns null if
 * no such encoding is known.
 */
class encoding_visitor : public boost::static_visitor<DexEncodedValue*> {
 public:
  encoding_visitor(const DexField* field) : m_field(field) {}

  DexEncodedValue* operator()(const SignedConstantDomain& dom) const {
    auto cst = dom.get_constant();
    if (!cst) {
      return nullptr;
    }
    auto ev = DexEncodedValue::zero_for_type(m_field->get_type());
    ev->value(static_cast<uint64_t>(*cst));
    return ev;
  }

  DexEncodedValue* operator()(const StringDomain& dom) const {
    auto cst = dom.get_constant();
    if (!cst) {
      return nullptr;
    }
    return new DexEncodedValueString(const_cast<DexString*>(*cst));
  }

  template <typename Domain>
  DexEncodedValue* operator()(const Domain&) const {
    return nullptr;
  }

 private:
  const DexField* m_field;
};

void encode_values(DexClass* cls, StaticFieldEnvironment field_env) {
  for (auto* field : cls->get_sfields()) {
    auto value = field_env.get(field);
    auto encoded_value =
        ConstantValue::apply_visitor(encoding_visitor(field), value);
    if (encoded_value == nullptr) {
      continue;
    }
    field->make_concrete(field->get_access(), encoded_value);
    TRACE(FINALINLINE,
          2,
          "Found encodable field: %s %s\n",
          SHOW(field),
          SHOW(value));
  }
}

} // namespace

namespace final_inline {

/*
 * This method determines the values of the static fields after the <clinit>
 * has finished running and generates their encoded_value equivalents.
 *
 * Additionally, for static final fields, this method collects and returns them
 * as part of the WholeProgramState object.
 */
cp::WholeProgramState analyze_and_simplify_clinits(const Scope& scope) {
  cp::WholeProgramState wps;
  for (DexClass* cls : reverse_tsort_by_clinit_deps(scope)) {
    ConstantEnvironment env;
    cp::set_encoded_values(cls, &env);
    auto clinit = cls->get_clinit();
    if (clinit != nullptr && clinit->get_code() != nullptr) {
      auto* code = clinit->get_code();
      code->build_cfg();
      auto& cfg = code->cfg();
      cfg.calculate_exit_block();
      cp::intraprocedural::FixpointIterator intra_cp(
          cfg, CombinedAnalyzer(cls->get_type(), &wps, nullptr, nullptr));
      intra_cp.run(env);
      env = intra_cp.get_exit_state_at(cfg.exit_block());

      // Generate the encoded_values and re-run the analysis.
      encode_values(cls, env.get_field_environment());
      auto fresh_env = ConstantEnvironment();
      cp::set_encoded_values(cls, &fresh_env);
      intra_cp.run(fresh_env);

      // Detect any field writes made redundant by the new encoded_values and
      // remove those sputs.
      cp::Transform::Config transform_config;
      transform_config.class_under_init = cls->get_type();
      cp::Transform(transform_config).apply(intra_cp, wps, code);
      // Delete the instructions rendered dead by the removal of those sputs.
      LocalDcePass::run(code);
      // If the clinit is empty now, delete it.
      if (is_trivial_clinit(clinit)) {
        cls->remove_method(clinit);
      }
    }
    wps.collect_static_finals(cls, env.get_field_environment());
  }
  return wps;
}

} // namespace final_inline

namespace {

size_t inline_static_final_gets(
    const Scope& scope,
    const cp::WholeProgramState& wps,
    const std::unordered_set<const DexType*>& black_list_types) {
  size_t inlined_count{0};
  walk::code(scope, [&](const DexMethod* method, IRCode& code) {
    if (is_clinit(method)) {
      return;
    }
    std::vector<std::pair<IRInstruction*, std::vector<IRInstruction*>>>
        replacements;
    for (auto& mie : InstructionIterable(code)) {
      auto it = code.iterator_to(mie);
      auto insn = mie.insn;
      auto op = insn->opcode();
      if (is_sget(op)) {
        auto field = resolve_field(insn->get_field(), FieldSearch::Static);
        if (field == nullptr || black_list_types.count(field->get_class())) {
          continue;
        }
        auto replacement = ConstantValue::apply_visitor(
            cp::value_to_instruction_visitor(
                ir_list::move_result_pseudo_of(it)),
            wps.get_field_value(field));
        if (replacement.size() == 0) {
          continue;
        }
        replacements.emplace_back(insn, replacement);
      }
    }
    for (auto const& p : replacements) {
      code.replace_opcode(p.first, p.second);
    }
    inlined_count += replacements.size();
  });
  return inlined_count;
}

// XXX(jezng): In principle, we should avoid deleting a field if
// can_delete(field) is false, even if can_delete(containing class) is true.
// However, the previous implementation of FinalInline did this more aggressive
// deletion -- deleting as long as either can_delete(field) or can_delete(cls)
// is true -- and I'm following it so as not to cause a regression. The right
// long-term fix is to clean up the proguard keep rules -- then we can just rely
// on RMU to delete these fields.
void aggressively_delete_static_finals(const Scope& scope) {
  std::unordered_set<const DexField*> referenced_fields;
  walk::opcodes(scope, [&](const DexMethod*, const IRInstruction* insn) {
    if (!insn->has_field()) {
      return;
    }
    auto field = resolve_field(insn->get_field(), FieldSearch::Static);
    referenced_fields.emplace(field);
  });
  for (auto* cls : scope) {
    auto& sfields = cls->get_sfields();
    sfields.erase(
        std::remove_if(sfields.begin(),
                       sfields.end(),
                       [&](DexField* field) {
                         return is_final(field) && !field->is_external() &&
                                referenced_fields.count(field) == 0 &&
                                (can_delete(cls) || can_delete(field));
                       }),
        sfields.end());
  }
}

} // namespace

size_t FinalInlinePassV2::run(const Scope& scope, Config config) {
  try {
    auto wps = final_inline::analyze_and_simplify_clinits(scope);
    return inline_static_final_gets(scope, wps, config.black_list_types);
  } catch (final_inline::class_initialization_cycle& e) {
    std::cerr << e.what();
    return 0;
  }
}

void FinalInlinePassV2::run_pass(DexStoresVector& stores,
                                 ConfigFiles& cfg,
                                 PassManager& mgr) {
  if (mgr.no_proguard_rules()) {
    TRACE(FINALINLINE,
          1,
          "FinalInlinePassV2 not run because no ProGuard configuration was "
          "provided.");
    return;
  }
  auto scope = build_class_scope(stores);
  auto inlined_count = run(scope, m_config);

  if (m_config.aggressively_delete) {
    aggressively_delete_static_finals(scope);
  }

  mgr.incr_metric("num_finals_inlined", inlined_count);
}

static FinalInlinePassV2 s_pass;

ext: cpp

max_stars_repo_name: gdawg/redex

max_issues_repo_name: gdawg/redex

max_forks_repo_name: gdawg/redex


text:
#ifndef BUFFER_HPP_INCLUDE_GUARD_7711062925
#define BUFFER_HPP_INCLUDE_GUARD_7711062925
#include <queue>
#include <vector>

#include <boost/utility.hpp>

#include "socket/Base.hpp"
#include "socket/SwitchEndian.hpp"
#include "Types.hpp"
#include "Exceptions.hpp"
#include "Tag.hpp"

namespace dicom
{

	//!Buffer for data going between the library and the network.
	/*!
		RATIONALE:
			Because data is send to us across the wire in the form of a series
			of PDVs (See Part 8, Annex E), it doesn't seem to be  practical to read data
			directly from a socket onto a dataset.  An intermediatry 'holding stage' needs
			to be introduced to pull together data from a series of PDVs and make it
			ready to be fed onto a dataset.  (An alternative solution might involve something
			clever with callbacks, but I'm not really sure how.)

			This functionality is provided by the Buffer class.  I haven't spent much time
			fine - tuning this class, I suspect that there is scope for considerable improvement
			in terms of both speed and interface.

		Note that this class also has a responsibility to perform endian corrections as data
		is fed onto and off of it.  (This means that it's duplicating functionality provided
		by class Socket.  Is there a way of abstracting this out into one place?)
			-This abstraction has now mostly been done in socket/SwitchEndian.hpp

		Lots of scope for optimization in this class - in fact, I suspect that
		this is the biggest bottleneck in the library.

		Should look at the interaction between this class and Socket - it might
		be that we CAN do in-place endian switches, because once the data
		has been written to the socket we don't care about it any more, so
		corruption isn't an issue.

		We tried using std::deque to implement this, but took a big performance hit.
		vector is the only guaranteed contiguous container, which means we can
		directly pass data to socket and file functions.
    */

	class Buffer : public std::vector<BYTE>, boost::noncopyable
	{

	private:

		/*!
			We keep track of position using this variable rather than
			an iterator, because vector iterators can get invalidated
			by insertions. I'm not very happy about this.
        */
		size_type I_;

	public:
		const int ExternalByteOrder_;

		Buffer(int ExternalByteOrder):I_(0),ExternalByteOrder_(ExternalByteOrder){}

		iterator position();
		void Increment(size_type i);

        Buffer& operator << (std::string data);

		template <typename T>
		Buffer& operator << (T data)
		{
			BOOST_STATIC_ASSERT(::boost::is_fundamental<T>::value);//because we're treating it as a byte stream.

			if(ExternalByteOrder_!=__BYTE_ORDER && sizeof(T)!=1)
			{
				data=SwitchEndian<T>(data);
			}
			BYTE* pdata=reinterpret_cast<BYTE*> (&data);
			for(BYTE* p=pdata;p<pdata+sizeof(T);p++)
			{
				push_back(*p);
			}
			return *this;
		}

		Buffer& operator << (Tag tag);

		template<typename T>
		Buffer& operator >> (T& data)
		{
			BOOST_STATIC_ASSERT(!(::boost::is_const<T>::value));//because we're writing to it.
			BOOST_STATIC_ASSERT(::boost::is_fundamental<T>::value);//because we're treating it as a byte stream.
			BYTE* pdata=reinterpret_cast<BYTE*> (&data);

			if(int(sizeof(T))>(end()-position()))
				throw dicom::exception("Attempting to read beyond end of buffer");
				for(BYTE* p=pdata;p<pdata+sizeof(T);p++)//this is tedious to have to check.
			{
				//can we do this with a copy?
				*p=*position();
				I_++;
			}

			if(ExternalByteOrder_!=__BYTE_ORDER && sizeof(T)!=1)
				data=SwitchEndian<T>(data);

			return *this;
		}

		Buffer& operator >>(std::vector<UINT16>& data);
		Buffer& operator >>(std::vector<BYTE>& data);
		Buffer& operator >>(std::string& data);

		Buffer& operator >>(Tag& tag);

		//!Override this to make sure we keep I_ nice.
		void clear();

		/*!
			This has now been optimized.  We could probably combine the
			two functions into a templated one if we really wanted to.
        */

		void AddVector(const std::vector<BYTE>& data)
		{
			insert(this->end(),data.begin(),data.end());
		}
		void AddVector(const std::vector<UINT16>& data);

    };
}

#endif //BUFFER_HPP_INCLUDE_GUARD_7711062925

ext: hpp

max_stars_repo_name: marcosivni/dicomlib

max_issues_repo_name: marcosivni/dicomlib

max_forks_repo_name: marcosivni/dicomlib


text:
#ifdef HAVE_ARMA
#include <armadillo>                     // arma::imat/imat22
#endif
#include <iostream>                      // std::cout/endl/boolalpha
#include <memory>                        // std::shared_ptr/unique_ptr

using namespace std;

#if defined(__cpp_concepts)

#if __cpp_concepts < 201811

#include <experimental/ranges/concepts>  // concepts defined in ranges
using namespace experimental::ranges;

#else

#include <concepts>                      // standard concepts

template <typename T>
concept readable = indirectly_readable<T>;
template <typename T, typename U>
concept writable = indirectly_writable<T, U>;

#endif

#else // defined(__cpp_concepts)

#error "No support for concepts!"

#endif

#define TEST_CONCEPT(Concept,      \
                     Type)         \
  cout << #Concept << '<' << #Type \
       << ">: "                    \
       << Concept<Type> << endl

#define TEST_CONCEPT2(             \
  Concept, Type1, Type2)           \
  cout << #Concept << '<'          \
       << #Type1 << ", " << #Type2 \
       << ">: "                    \
       << Concept<Type1,           \
                  Type2> << endl

int main()
{
    cout << boolalpha;
    cout << "__cpp_concepts is " << __cpp_concepts << endl;
    TEST_CONCEPT(regular, int);
    TEST_CONCEPT(regular, char);
    TEST_CONCEPT(integral, int);
    TEST_CONCEPT(integral, char);
    TEST_CONCEPT(readable, int);
    TEST_CONCEPT(readable, unique_ptr<int>);
    TEST_CONCEPT2(writable, unique_ptr<int>, int);
    TEST_CONCEPT2(writable, unique_ptr<int>, double);
    TEST_CONCEPT2(writable, unique_ptr<int>, int*);
    TEST_CONCEPT(semiregular, unique_ptr<int>);
    TEST_CONCEPT(semiregular, shared_ptr<int>);
    TEST_CONCEPT(equality_comparable, unique_ptr<int>);
#ifdef HAVE_ARMA
    TEST_CONCEPT(semiregular, arma::imat);
    TEST_CONCEPT2(assignable_from, arma::imat&, arma::imat&);
    TEST_CONCEPT(semiregular, arma::imat22);
    TEST_CONCEPT2(assignable_from, arma::imat22&, arma::imat22&);
#endif
}


text:
#ifndef DCS_ALGORITHM_SLICE_HPP
#define DCS_ALGORITHM_SLICE_HPP

#include <boost/core/enable_if.hpp>
#include <boost/mpl/and.hpp>
#include <boost/mpl/not.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/tti/has_member_function.hpp>
#include <boost/tti/has_type.hpp>
#include <vector>

namespace dcs { namespace algorithm {

namespace detail {

//BOOST_TTI_HAS_TYPE(value_type)
BOOST_TTI_HAS_TYPE(key_type)
BOOST_TTI_HAS_TYPE(mapped_type)
BOOST_TTI_HAS_MEMBER_FUNCTION(at)

template <typename T>
struct is_not_associative_with_at
{
	typedef typename boost::mpl::and_< boost::mpl::not_<typename has_type_key_type<T>::type>,
									   typename has_member_function_at<T,typename T::reference,boost::mpl::vector<typename T::size_type> >::type>::type type;
};

template <typename T>
struct is_associative_not_map
{
	typedef typename boost::mpl::and_< typename has_type_key_type<T>::type,
									   boost::mpl::not_<typename has_type_mapped_type<T>::type> >::type type;
};

template <typename T>
struct is_associative_map
{
	typedef typename has_type_mapped_type<T>::type type;
};

/*
template <typename T>
struct is_associative
{
	typedef typename has_type_key_type<T>::type type;
};

template <typename T>
struct is_associative_not_map
{
	typedef typename boost::mpl::and_< typename has_type_key_type<T>::type,
									   boost::mpl::not_<typename has_type_mapped_type<T>::type> >::type type;
};
*/

} // Namespace detail

template <typename ContainerT, typename IterT>
typename boost::enable_if< typename detail::is_not_associative_with_at<ContainerT>::type,
							std::vector<typename ContainerT::value_type> >::type
slice(ContainerT const& c, IterT first, IterT last)
{
	std::vector<typename ContainerT::value_type> res;

	while (first != last)
	{
		res.push_back(c.at(*first));
		++first;
	}

	return res;
}

template <typename ContainerT, typename IterT>
typename boost::enable_if< typename detail::is_associative_not_map<ContainerT>::type,
							std::vector<typename ContainerT::value_type> >::type
slice(ContainerT const& c, IterT first, IterT last)
{
	std::vector<typename ContainerT::value_type> res;

	while (first != last)
	{
		res.push_back(*(c.find(*first)));
		++first;
	}

	return res;
}

template <typename ContainerT, typename IterT>
typename boost::enable_if< typename detail::is_associative_map<ContainerT>::type,
						   std::vector<typename ContainerT::mapped_type> >::type
slice(ContainerT const& c, IterT first, IterT last)
{
	std::vector<typename ContainerT::mapped_type> res;

	while (first != last)
	{
		res.push_back(c.at(*first));
		++first;
	}

	return res;
}

/*
template <typename ContainerT>
typename boost::enable_if<typename detail::is_map<ContainerT>::value,
						  std::vector<typename ContainerT::value_type> >::type slice(ContainerT const& c)
{
	return std::vector<typename ContainerT::value_type>();
}

template <typename ContainerT>
typename boost::enable_if<typename detail::is_associative_not_map<ContainerT>::value,
						  std::vector<typename ContainerT::value_type> >::type slice(ContainerT const& c)
{
	return std::vector<typename ContainerT::value_type>();
}
*/

}} // Namespace dcs::algorithm

#endif // DCS_ALGORITHM_SLICE_HPP

max_stars_repo_name: sguazt/fog-gt

max_issues_repo_name: sguazt/fog-gt

max_forks_repo_name: sguazt/fog-gt


text:
/*
 * plik ma na celu prezentację podstawowych zagadnień z programowania w języku C++
 * prezentuje:
 *  - tworzenie programów wielowątkowych
 *  - korzystanie z mutexów
 *  - korzystanie z asynchronicznego io jako timera
 *  - korzystanie z kolejki C++
 *  - podatwy obsługi czasu ...
 *
 * kompilacja: g++ -lboost_date_time -lboost_system -lboost_thread -lpthread watki.cpp
 *
 * (wymagane pakiety: libboost-date-time-dev libboost-system-dev libboost-thread-dev)
 */

#include <queue>

#include <boost/thread/mutex.hpp>
#include <boost/thread/thread.hpp>

#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

#include <string>
#include <iostream>

std::queue<std::string> kolejka;

boost::mutex mutex;

int globalna=13;

class Watki {
public:
	int parametr_watku;
	void operator()() {
		std::cout << "to wątek z parametrem " << parametr_watku;
		std::cout << " globalna = " << globalna << std::endl;
		boost::this_thread::sleep(boost::posix_time::seconds(5));
		std::cout << "a teraz (nadal) z parametrem " << parametr_watku;
		std::cout << " globalna = " << globalna << std::endl;

		for (int i=0; i<6; i++) {
			boost::this_thread::sleep(boost::posix_time::millisec(700));
			boost::mutex::scoped_lock scoped_lock(mutex);
			// powyższy mutex blokuje od teraz do końca bloku
			// warto też wspomnieć o muteksach odpornych na blokowanie
			// już zablokowanego przez nas samych - boost::recursive_mutex

			if (!kolejka.empty()) {
				std::cout << i << ") odebrałem z kolejki " << kolejka.front() << std::endl;
				kolejka.pop();
			}
		}

	}
};

void zdarzenie(const boost::system::error_code&) {
	std::cout << "budzik start" << std::endl;
	boost::this_thread::sleep(boost::posix_time::seconds(5));
	std::cout << "budzik stop" << std::endl;
}

int main() {
	Watki funktor_watek1;

	funktor_watek1.parametr_watku=56;
	boost::thread watek1(funktor_watek1);
	boost::this_thread::sleep(boost::posix_time::seconds(2));
	funktor_watek1.parametr_watku=78;
	globalna=58;

	boost::this_thread::sleep(boost::posix_time::seconds(2));

	mutex.lock();
	kolejka.push("Ala ma kota");
	kolejka.push("Kot ma Ale");
	mutex.unlock();

	std::cout << "2 pierwsze elementy są w kolejce" << std::endl;
	boost::this_thread::sleep(boost::posix_time::seconds(2));

	mutex.lock();
	kolejka.push("Abecadlo");
	kolejka.push("z pieca spadło");
	mutex.unlock();

	std::cout << "2 kolejne elementy są w kolejce" << std::endl;

	// asynchroniczne IO jako alarm
	boost::asio::io_service ios;
	boost::asio::deadline_timer budzik(ios, boost::posix_time::seconds(2));
	budzik.async_wait(zdarzenie);
	std::cout << "czekamy na budzik" << std::endl;
	ios.run(); // uruchomienie pętli obsługi
	std::cout << "po budziku" << std::endl;
}


text:
/****************************************************************************
 *  hipipe library
 *  Copyright (c) 2018, Iterait a.s.
 *  Author(s) Adam Blazek
 *
 *  This file is distributed under the MIT License.
 *  See the accompanying file LICENSE.txt for the complete license agreement.
 ****************************************************************************/

#include <hipipe/core/python/initialize.hpp>

#include <boost/python.hpp>
#include <opencv2/core/core.hpp>

// check c++ -> python
cv::Point2f point()
{
    cv::Point2f pt = cv::Point2f(4.2, 42);
    return pt;
}

// check python -> c++
bool check_point(cv::Point2f pt)
{
    return std::abs(pt.x - 4.2) < 0.0001 && std::abs(pt.y - 42.0) < 0.0001;
}

BOOST_PYTHON_MODULE(pyboost_cv_point_converter_py_cpp)
{
    // initialize hipipe OpenCV converters, exceptions, etc.
    hipipe::python::initialize();

    // expose the functions
    namespace py = boost::python;
    py::def("point", point);
    py::def("check_point", check_point);
}

max_stars_repo_name: iterait/hipipe

max_issues_repo_name: iterait/hipipe

max_forks_repo_name: iterait/hipipe


text:
// Boost.Bimap
//
// Copyright (c) 2006-2007 Matias Capeletto
//
// 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)

/// \file container_adaptor/vector_map_adaptor.hpp
/// \brief Container adaptor.

#ifndef BOOST_BIMAP_CONTAINER_ADAPTOR_VECTOR_MAP_ADAPTOR_HPP
#define BOOST_BIMAP_CONTAINER_ADAPTOR_VECTOR_MAP_ADAPTOR_HPP

#if defined(_MSC_VER) && (_MSC_VER>=1200)
#pragma once
#endif

#include <boost/config.hpp>

#include <boost/mpl/list.hpp>
#include <boost/mpl/push_front.hpp>
#include <boost/mpl/aux_/na.hpp>
#include <boost/bimap/container_adaptor/vector_adaptor.hpp>
#include <boost/bimap/container_adaptor/detail/identity_converters.hpp>
#include <boost/mpl/vector.hpp>

namespace boost {
namespace bimaps {
namespace container_adaptor {

/// \brief Container adaptor.

template
<
    class Base,

    class Iterator,
    class ConstIterator,
    class ReverseIterator,
    class ConstReverseIterator,

    class IteratorToBaseConverter          = ::boost::mpl::na,
    class IteratorFromBaseConverter        = ::boost::mpl::na,
    class ReverseIteratorFromBaseConverter = ::boost::mpl::na,
    class ValueToBaseConverter             = ::boost::mpl::na,
    class ValueFromBaseConverter           = ::boost::mpl::na,

    class FunctorsFromDerivedClasses = mpl::vector<>
>
class vector_map_adaptor :

    public vector_adaptor
    <
        Base,
        Iterator, ConstIterator, ReverseIterator, ConstReverseIterator,
        IteratorToBaseConverter, IteratorFromBaseConverter,
        ReverseIteratorFromBaseConverter,
        ValueToBaseConverter, ValueFromBaseConverter,
        FunctorsFromDerivedClasses
    >
{
    typedef vector_adaptor
    <
        Base,
        Iterator, ConstIterator, ReverseIterator, ConstReverseIterator,
        IteratorToBaseConverter, IteratorFromBaseConverter,
        ReverseIteratorFromBaseConverter,
        ValueToBaseConverter, ValueFromBaseConverter,
        FunctorsFromDerivedClasses

    > base_;

    // MetaData -------------------------------------------------------------

    public:

    typedef BOOST_DEDUCED_TYPENAME Iterator::value_type::first_type  key_type;
    typedef BOOST_DEDUCED_TYPENAME Iterator::value_type::second_type data_type;

    // Access -----------------------------------------------------------------

    public:

    vector_map_adaptor() {}

    explicit vector_map_adaptor(Base & c) :
        base_(c) {}

    protected:

    typedef vector_map_adaptor vector_map_adaptor_;

};

} // namespace container_adaptor
} // namespace bimaps
} // namespace boost

#endif // BOOST_BIMAP_CONTAINER_ADAPTOR_VECTOR_MAP_ADAPTOR_HPP

max_stars_repo_name: dyzmapl/BumpTop

max_issues_repo_name: foxostro/CheeseTesseract

max_forks_repo_name: foxostro/CheeseTesseract


text:
//
// Copyright Copyright 2009-2022, AMT – The Association For Manufacturing Technology (“AMT”)
// All rights reserved.
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
//

#pragma once

#include "boost/asio/io_context.hpp"
#include <boost/dll/alias.hpp>

#include "configuration/agent_config.hpp"
#include "entity/json_printer.hpp"
#include "printer/printer.hpp"
#include "printer/xml_printer_helper.hpp"
#include "sink/sink.hpp"
#include "utilities.hpp"

using namespace std;
using namespace mtconnect::entity;

namespace mtconnect {
  class XmlPrinter;

  namespace sink {
    namespace mqtt_sink {
      class MqttService : public sink::Sink
      {
        // dynamic loading of sink

      public:
        MqttService(boost::asio::io_context &context, sink::SinkContractPtr &&contract,
                    const ConfigOptions &options, const boost::property_tree::ptree &config);

        ~MqttService() = default;

        // Sink Methods
        void start() override;

        void stop() override;

        uint64_t publish(observation::ObservationPtr &observation) override;

        bool publish(asset::AssetPtr asset) override;

        static void registerFactory(SinkFactory &factory);

      protected:
        boost::asio::io_context &m_context;
        ConfigOptions m_options;
        std::unique_ptr<JsonPrinter> m_jsonPrinter;
      };

    }  // namespace mqtt_sink
  }    // namespace sink
}  // namespace mtconnect

max_stars_repo_name: bburns/cppagent

max_issues_repo_name: bburns/cppagent

max_forks_repo_name: bburns/cppagent


text:
#include <cstdint>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <list>
#include <boost/core/demangle.hpp>
#include <typeinfo>
#include <iostream>

#include <nop/serializer.h>
#include <nop/structure.h>
#include <nop/utility/stream_writer.h>
#include <nop/utility/stream_reader.h>

namespace example {

struct Person {
  std::string name;
  std::uint32_t age_years;
  std::uint8_t height_inches;
  std::uint16_t weight_pounds;
  NOP_STRUCTURE(Person, name, age_years, height_inches, weight_pounds);
};

}  // namespace example

namespace ado
{

template <typename X>
class list
{
public:
  list(const std::string& name) {
    /* create list object */
  }

  void push_back(const X& item) {
    _serializer.Write("op::push_back");
    _serializer.Write(item);
    /* send to mcas */
  }
private:
  using Writer = nop::StreamWriter<std::stringstream>;
  nop::Serializer<Writer> _serializer;
};

}

class ADO
{
public:
  template <typename T>
  void invoke(const std::string& name, T arg)
  {
    _serializer.Write(arg);
  }

  template <typename T, typename... Args>
  void invoke(const std::string& name, T arg, Args... args) {
    invoke(name, arg);
    invoke(name, args...);
  }

private:

  using Writer = nop::StreamWriter<std::stringstream>;
  nop::Serializer<Writer> _serializer;
};

template <typename T>
void create_ADO(const T& arg)
{
  using Writer = nop::StreamWriter<std::stringstream>;
  nop::Serializer<Writer> serializer;
  serializer.Write(arg);
}

int main(int argc, char** argv) {
  using nop::Deserializer;
  using nop::ErrorStatus;
  using nop::Serializer;
  using nop::Status;
  using nop::StreamReader;
  using nop::StreamWriter;
  using namespace nop;

  create_ADO(std::vector<std::vector<int>>{});

  auto name = typeid(std::vector<std::vector<int>>).name();
  printf("type:%s\n", name);
  std::cout << boost::core::demangle( name ) << std::endl; // prints X<int>
  {
    ADO ado;
    int x=0;
    unsigned long y = 123;
    std::vector<int> z{1,2,3};
    ado.invoke("my_op", x,y,z);
  }

  {
    ado::list<std::vector<int>> list("myList");
    list.push_back(std::vector<int>{1,2,3});
  }

  using Writer = nop::StreamWriter<std::stringstream>;

  nop::Serializer<Writer> serializer;

  int x = 666;
  serializer.Write(std::vector<int>{1,3,7,11});
  serializer.Write(x);

  const std::string data = serializer.writer().stream().str();
  std::cout << "Wrote " << data.size() << " bytes. " << std::endl;

  nop::Deserializer<nop::StreamReader<std::stringstream>> deserializer{std::move(serializer.writer().stream())};

  std::vector<int> p;
  auto return_status = deserializer.Read(&p);

  for(auto& i : p)
    printf("i=%d\n", i);

  int xx;
  return_status = deserializer.Read(&xx);
  printf("xx=%d\n",xx);

  return 0;
}


text:
#include <StdInc.h>
#include <Hooking.h>

#include <CoreConsole.h>

#include <RageParser.h>

#include <gameSkeleton.h>
#include <ICoreGameInit.h>

#include <atArray.h>
#include <MinHook.h>

#include <CustomText.h>

#include <concurrent_queue.h>

#include <array>
#include <unordered_set>

#include <CrossBuildRuntime.h>

#include <GameInput.h>
#include <InputHook.h>

namespace rage
{
	struct ioInputSource
	{
		uint32_t source;
		uint32_t parameter;
		int unk;

		inline ioInputSource()
			: source(0), parameter(0), unk(-1)
		{

		}

		inline ioInputSource(uint32_t source, uint32_t parameter, int unk)
			: source(source), parameter(parameter), unk(unk)
		{

		}
	};

	class ioValue
	{
	public:
		using ReadOptions = uint64_t;

		ioValue()
		{
			memset(pad, 0, sizeof(pad));

			*(float*)(&pad[0]) = 1.0f;
			*(uint64_t*)(&pad[16]) = -1;
			*(int32_t*)(&pad[24]) = -3;
			*(uint64_t*)(&pad[28]) = -1;
			*(int32_t*)(&pad[36]) = -3;
			*(int32_t*)(&pad[40]) = -1;
			*(int32_t*)(&pad[44]) = -1;
			*(int32_t*)(&pad[48]) = -3;
			*(int32_t*)(&pad[52]) = -1;
			*(int8_t*)(&pad[58]) = 1;
		}

		void Update(uint8_t preFrameCounter, uint32_t time);

		void SetCurrentValue(float value, rage::ioInputSource& source);

		bool IsDown(float threshold, const ReadOptions& readOptions);

		static ReadOptions NO_DEAD_ZONE;

	private:
		char pad[9 * 8];
	};

	ioValue::ReadOptions ioValue::NO_DEAD_ZONE = 0x100000000;

	class ioMapper
	{
	public:
		uint32_t Map(uint32_t mapperSource, uint32_t key, ioValue& value, int a4);

		void UpdateMap(int max_k, const ioInputSource& info, ioValue& value);

		void RemoveDeviceMappings(ioValue& value, int a3);
	};
}

static hook::cdecl_stub<void(rage::ioValue* self, float value, rage::ioInputSource& source)> _ioValue_SetCurrentValue([]()
{
	return hook::get_pattern("8A 41 3A 4C 8B C9 A8 01");
});

void rage::ioValue::SetCurrentValue(float value, rage::ioInputSource& source)
{
	_ioValue_SetCurrentValue(this, value, source);
}

static hook::cdecl_stub<bool(rage::ioValue* self, float value, const rage::ioValue::ReadOptions&)> _ioValue_IsDown([]()
{
	return hook::get_pattern("0F 29 74 24 20 48 8B F9 48 8B D3 0F 28 F1 E8", -0xD);
});

bool rage::ioValue::IsDown(float threshold, const ReadOptions& readOptions)
{
	return _ioValue_IsDown(this, threshold, readOptions);
}

static hook::cdecl_stub<uint32_t(rage::ioMapper*, uint32_t, uint32_t, rage::ioValue&, int)> _ioMapper_Map([]()
{
	return hook::get_pattern("89 54 81 24 48 63", -0x30);
});

uint32_t rage::ioMapper::Map(uint32_t mapperSource, uint32_t key, ioValue& value, int a4)
{
	return _ioMapper_Map(this, mapperSource, key, value, a4);
}

static hook::cdecl_stub<void(rage::ioMapper*, int, const rage::ioInputSource&, rage::ioValue&)> _ioMapper_UpdateMap([]()
{
	return hook::get_pattern("33 C0 4D  8B D0 44 8B D8 8B D8 48", -0x0D);
});

void rage::ioMapper::UpdateMap(int max_k, const rage::ioInputSource& info, rage::ioValue& value)
{
	return _ioMapper_UpdateMap(this, max_k, info, value);
}

static hook::cdecl_stub<void(rage::ioMapper*, rage::ioValue&, int)> _ioMapper_RemoveDeviceMappings([]()
{
	return hook::get_pattern("45 33 E4 45 33 ED 89 94 24 80 00 00 00 39 11", -0x34);
});

void rage::ioMapper::RemoveDeviceMappings(rage::ioValue& value, int a3)
{
	return _ioMapper_RemoveDeviceMappings(this, value, a3);
}

static hook::cdecl_stub<void(rage::ioValue*, uint8_t, uint32_t)> _ioValue_Update([]()
{
	return hook::get_pattern("41 22 C3 74 06 F6 41 3A 02 74 6F", -0x18);
});

void rage::ioValue::Update(uint8_t preFrameCounter, uint32_t time)
{
	_ioValue_Update(this, preFrameCounter, time);
}

static hook::cdecl_stub<uint32_t(uint32_t)> _controlSourceToMapperSource([]()
{
	return hook::get_pattern("85 C9 78 20 83 F9 04");
});

uint32_t ControlSourceToMapperSource(uint32_t source)
{
	return _controlSourceToMapperSource(source);
}

static hook::cdecl_stub<uint32_t(uint32_t, uint32_t)> _getParameterIndex([]()
{
	return hook::get_pattern("83 F9 01 74 2C 0F 8E E8 00 00 00", -0xF);
});

//
// Given a source/parameter, gets the parameter to use when serializing a control.
//
uint32_t GetParameterIndex(uint32_t source, uint32_t parameter)
{
	return _getParameterIndex(source, parameter);
}

static hook::cdecl_stub<uint32_t(uint32_t, uint32_t)> _ungetParameterIndex([]()
{
	return hook::get_pattern("74 28 7E 36 83 F9", -0x12);
});

//
// Given a source/serialized parameter, gets the native parameter to use.
//
uint32_t UngetParameterIndex(uint32_t source, uint32_t parameter)
{
	return _ungetParameterIndex(source, parameter);
}

class Button
{
public:
	Button(const std::string& name);

	void UpdateIoValues(float value, rage::ioInputSource& source);

	void UpdateOnControl();

	void SetFromControl(void* control, int keyIndex);

private:
	std::string m_name;

	std::unique_ptr<ConsoleCommand> m_downCommand;
	std::unique_ptr<ConsoleCommand> m_upCommand;

	rage::ioValue m_ioValue;

	std::array<rage::ioValue*, 4> m_ioValueCopies;
};

Button::Button(const std::string& name)
	: m_name(name)
{
	for (auto& copy : m_ioValueCopies)
	{
		copy = nullptr;
	}

	m_downCommand = std::make_unique<ConsoleCommand>("+" + name, [this]()
	{
		rage::ioInputSource source{ 0, 1, -4 }; // keyboard?
		UpdateIoValues(1.0f, source);
	});

	m_upCommand = std::make_unique<ConsoleCommand>("-" + name, [this]()
	{
		rage::ioInputSource source{ 0, 1, -4 }; // keyboard?
		UpdateIoValues(0.0f, source);
	});
}

void Button::UpdateIoValues(float value, rage::ioInputSource& source)
{
	m_ioValue.SetCurrentValue(value, source);
}

void Button::UpdateOnControl()
{
	if (m_ioValue.IsDown(0.5f, rage::ioValue::NO_DEAD_ZONE))
	{
		for (auto copy : m_ioValueCopies)
		{
			if (copy)
			{
				rage::ioInputSource source{ 0, 1, -4 }; // keyboard?

				if (!copy->IsDown(0.5f, rage::ioValue::NO_DEAD_ZONE))
				{
					copy->SetCurrentValue(1.0f, source);
				}
			}
		}
	}
}

void Button::SetFromControl(void* control, int keyIndex)
{
	auto controlPtr = (uint8_t*)control;

	rage::ioValue* value = (rage::ioValue*) & controlPtr[33704 + (keyIndex * 72)];

	for (auto& copy : m_ioValueCopies)
	{
		if (copy == nullptr)
		{
			copy = value;
			break;
		}
	}
}

class Binding
{
public:
	Binding(const std::string& command);

	~Binding();

	void Update(rage::ioMapper* mapper);

	void UpdateMap(rage::ioMapper* mapper)
	{
		rage::ioInputSource src;
		GetBinding(src);
		mapper->UpdateMap(0, src, m_value);

		m_mappers.insert(mapper);
	}

	rage::ioValue& GetValue()
	{
		return m_value;
	}

	inline void SetBinding(std::tuple<int, int> binding)
	{
		m_binding = binding;
	}

	inline const auto& GetCommand() const
	{
		return m_command;
	}

	inline const auto& GetTag() const
	{
		return m_tag;
	}

	inline void SetTag(const std::string& tag)
	{
		m_tag = tag;
	}

	inline void GetBinding(rage::ioInputSource& source) const
	{
		source.source = std::get<0>(m_binding);
		source.parameter = std::get<1>(m_binding);
		source.unk = -1;
	}

private:
	rage::ioValue m_value;

	bool m_wasDown;

	std::string m_command;

	std::string m_tag;

	std::tuple<int, int> m_binding;

	std::set<rage::ioMapper*> m_mappers;
};

Binding::Binding(const std::string& command)
	: m_command(command), m_wasDown(false)
{

}

Binding::~Binding()
{
	for (rage::ioMapper* mapper : m_mappers)
	{
		mapper->RemoveDeviceMappings(m_value, -4);
	}
}

static void* g_control;
static uint32_t g_mapperOffset;

static hook::cdecl_stub<bool(int)> _isMenuActive([]
{
	return hook::get_call(hook::get_pattern("33 C9 E8 ? ? ? ? 84 C0 74 04 84 DB 75 21", 2));
});

static hook::cdecl_stub<bool()> _isTextInputBoxActive([]
{
	return hook::get_call(hook::get_pattern("E8 ? ? ? ? 40 84 FF 74 15 E8", 10));
});

bool IsTagActive(const std::string& tag);

void Binding::Update(rage::ioMapper* mapper)
{
	if (!IsTagActive(m_tag))
	{
		return;
	}

	if (Instance<ICoreGameInit>::Get()->GetGameLoaded() && mapper == (rage::ioMapper*)((char*)g_control + g_mapperOffset) && !_isMenuActive(1))
	{
		UpdateMap(mapper);
	}

	bool down = m_value.IsDown(0.5f, rage::ioValue::NO_DEAD_ZONE);

	// text input should count as up
	if (Instance<ICoreGameInit>::Get()->GetGameLoaded() && _isTextInputBoxActive())
	{
		down = false;
	}

	bool isDownEvent = (!m_wasDown && down);
	bool isUpEvent = (m_wasDown && !down);

	m_wasDown = down;

	if (isDownEvent || isUpEvent)
	{
		const auto& commandString = m_command;

		// split the string by ';' (so button bindings get handled separately)
		int i = 0;
		std::stringstream thisCmd;

		bool hadButtonEvent = false;

		while (true)
		{
			if (i == commandString.length() || commandString[i] == ';')
			{
				std::string thisString = thisCmd.str();
				thisCmd.str("");

				// suppress any missing commands (requested via https://forum.cfx.re/t/1859314/3)
				bool ignore = false;

				if (!m_tag.empty())
				{
					auto parsed = console::Tokenize(thisString);

					if (parsed.Count() > 0 && !console::GetDefaultContext()->GetCommandManager()->HasCommand(parsed[0]))
					{
						ignore = true;
					}
				}

				if (!ignore)
				{
					// if this is a button binding
					if (thisString[0] == '+')
					{
						if (isDownEvent)
						{
							// TODO: add key code arguments
							console::GetDefaultContext()->AddToBuffer(thisString + "\n");
						}
						else
						{
							// up event is -[button cmd]
							// TODO: add key code arguments
							console::GetDefaultContext()->AddToBuffer("-" + thisString.substr(1) + "\n");
						}

						hadButtonEvent = true;
					}
					else
					{
						// if not, just execute the command on down
						if (isDownEvent || hadButtonEvent)
						{
							console::GetDefaultContext()->AddToBuffer(thisString + "\n");
						}
					}
				}
			}

			if (i == commandString.length())
			{
				break;
			}

			thisCmd << commandString[i];

			i++;
		}
	}
}

class BindingManager
{
public:
	void Initialize();

	void OnGameInit();

	void CreateButtons();

	void UpdateButtons();

	void Update(rage::ioMapper* mapper, uint32_t time);

	std::shared_ptr<Binding> Bind(int source, int parameter, const std::string& command);

	inline auto& GetBindings()
	{
		return m_bindings;
	}

	inline void QueueOnFrame(const std::function<void()>& func)
	{
		m_queue.push(func);
	}

private:
	std::unique_ptr<ConsoleCommand> m_bindCommand;
	std::unique_ptr<ConsoleCommand> m_rbindCommand;
	std::unique_ptr<ConsoleCommand> m_unbindCommand;
	std::unique_ptr<ConsoleCommand> m_unbindAllCommand;
	std::unique_ptr<ConsoleCommand> m_listBindsCommand;

	std::multimap<std::tuple<int, int>, std::shared_ptr<Binding>> m_bindings;

	std::list<std::unique_ptr<Button>> m_buttons;

	concurrency::concurrent_queue<std::function<void()>> m_queue;
};

static std::map<std::string, int, console::IgnoreCaseLess> ioSourceMap;
static std::map<std::string, int, console::IgnoreCaseLess> ioParameterMap;

void BindingManager::Initialize()
{
	m_listBindsCommand = std::make_unique<ConsoleCommand>("bind", [this]()
	{
		for (auto& binding : m_bindings)
		{
			rage::ioInputSource source;
			binding.second->GetBinding(source);

			auto parameterIndex = _getParameterIndex(source.source, source.parameter);

			std::string ioSource = "";
			std::string ioParameter = "";

			for (auto& entry : ioSourceMap)
			{
				if (entry.second == source.source)
				{
					ioSource = entry.first;
				}
			}

			for (auto& entry : ioParameterMap)
			{
				if (entry.second == parameterIndex)
				{
					ioParameter = entry.first;
				}
			}

			auto sourceString = fmt::sprintf("%s %s", ioSource, ioParameter);

			console::Printf("IO", "%s %s -> %s\n", sourceString, binding.second->GetTag(), binding.second->GetCommand());
		}
	});

	auto bind = [=](const std::string& ioSourceName, const std::string& ioParameterName, const std::string& commandString, const std::string& tag)
	{
		int ioSource;

		{
			auto it = ioSourceMap.find(ioSourceName);

			if (it == ioSourceMap.end())
			{
				console::Printf("IO", "Invalid I/O source %s\n", ioSourceName);
				return;
			}

			ioSource = it->second;
		}

		int ioParameter;

		{
			auto it = ioParameterMap.find(ioParameterName);

			if (it == ioParameterMap.end())
			{
				console::Printf("IO", "Invalid key name %s\n", ioParameterName.c_str());
				return;
			}

			ioParameter = _ungetParameterIndex(ioSource, it->second);
		}

		auto binding = std::make_shared<Binding>(commandString);
		binding->SetBinding({ ioSource, ioParameter });
		binding->SetTag(tag);

		m_bindings.insert({ { ioSource, ioParameter }, binding });

		// TODO: implement when saving is added
		console::GetDefaultContext()->SetVariableModifiedFlags(ConVar_Archive);
	};

	m_bindCommand = std::make_unique<ConsoleCommand>("bind", [=](const std::string& ioSourceName, const std::string& ioParameterName, const std::string& commandString)
	{
		bind(ioSourceName, ioParameterName, commandString, "");
	});

	m_rbindCommand = std::make_unique<ConsoleCommand>("rbind", [=](const std::string& tag, const std::string& ioSourceName, const std::string& ioParameterName, const std::string& commandString)
	{
		bind(ioSourceName, ioParameterName, commandString, tag);
	});

	m_unbindCommand = std::make_unique<ConsoleCommand>("unbind", [=](const std::string& ioSourceName, const std::string& ioParameterName)
	{
		int ioSource;

		{
			auto it = ioSourceMap.find(ioSourceName);

			if (it == ioSourceMap.end())
			{
				console::Printf("IO", "Invalid I/O source %s\n", ioSourceName);
				return;
			}

			ioSource = it->second;
		}

		int ioParameter;

		{
			auto it = ioParameterMap.find(ioParameterName);

			if (it == ioParameterMap.end())
			{
				console::Printf("IO", "Invalid key name %s\n", ioParameterName.c_str());
				return;
			}

			ioParameter = _ungetParameterIndex(ioSource, it->second);
		}

		m_bindings.erase({ ioSource, ioParameter });

		console::GetDefaultContext()->SetVariableModifiedFlags(ConVar_Archive);
	});

	m_unbindAllCommand = std::make_unique<ConsoleCommand>("unbindall", [=]()
	{
		m_bindings.clear();
	});
}

std::shared_ptr<Binding> BindingManager::Bind(int ioSource, int ioParameter, const std::string& commandString)
{
	for (auto& binding : m_bindings)
	{
		if (binding.second->GetCommand() == commandString && IsTagActive(binding.second->GetTag()))
		{
			m_bindings.erase(binding.first);
			break;
		}
	}

	//m_bindings.erase({ ioSource, ioParameter });

	auto binding = std::make_shared<Binding>(commandString);
	binding->SetBinding({ ioSource, ioParameter });

	m_bindings.insert({ { ioSource, ioParameter }, binding });

	console::GetDefaultContext()->SetVariableModifiedFlags(ConVar_Archive);

	return binding;
}

void BindingManager::Update(rage::ioMapper* mapper, uint32_t time)
{
	static uint8_t counter = 0;
	counter++;

	for (auto& bindingPair : m_bindings)
	{
		auto [source, binding] = bindingPair;

		binding->Update(mapper);
	}

	std::function<void()> func;

	while (m_queue.try_pop(func))
	{
		func();
	}
}

void BindingManager::OnGameInit()
{
	{
		auto structureField = rage::GetStructureDefinition("rage__InputCalibration__Data");

		auto enumeration = structureField->m_members[0]->m_definition->enumData;
		auto name = enumeration->names;

		for (auto field = enumeration->fields; field->index != -1 || field->hash != 0; field++)
		{
			std::string_view thisName = *name;

			if (thisName.find("KEY_") == 0)
			{
				thisName = thisName.substr(thisName.find_first_of('_') + 1);
			}

			ioParameterMap[std::string(thisName)] = field->index;

			name++;
		}
	}

	{
		auto structureField = rage::GetStructureDefinition("rage__ControlInput__Mapping");

		auto enumeration = structureField->m_members[1]->m_definition->enumData;
		auto name = enumeration->names;

		for (auto field = enumeration->fields; field->index != -1 || field->hash != 0; field++)
		{
			std::string_view thisName = *name;
			thisName = thisName.substr(thisName.find_first_of('_') + 1);

			ioSourceMap[std::string(thisName)] = field->index;

			name++;
		}
	}
}

void BindingManager::CreateButtons()
{
	{
		auto structureField = rage::GetStructureDefinition("rage__ControlInput__Mapping");

		auto enumeration = structureField->m_members[0]->m_definition->enumData;
		auto name = enumeration->names;

		for (auto field = enumeration->fields; field->index != -1 || field->hash != 0; field++)
		{
			std::string_view thisName = *name;
			thisName = thisName.substr(thisName.find_first_of('_') + 1);

			std::string thisNameStr(thisName);
			std::transform(thisNameStr.begin(), thisNameStr.end(), thisNameStr.begin(), ToLower);

			auto button = std::make_unique<Button>(thisNameStr);
			button->SetFromControl(g_control, field->index);

			if (!xbr::IsGameBuildOrGreater<2060>())
			{
				button->SetFromControl((char*)g_control + 0x21A98, field->index); // 1604
			}
			else
			{
				button->SetFromControl((char*)g_control + 0x21B78, field->index); // 2198
			}

			m_buttons.push_back(std::move(button));

			name++;
		}
	}
}

void BindingManager::UpdateButtons()
{
	for (auto& button : m_buttons)
	{
		button->UpdateOnControl();
	}
}

static size_t g_controlSize;
static BindingManager bindingManager;

static std::unordered_set<std::string> g_activeTags;

bool IsTagActive(const std::string& tag)
{
	return (tag.empty() || g_activeTags.find(tag) != g_activeTags.end());
}

static void(*ioMapper_Update)(void*, uint32_t, bool);
void UpdateButtonPlumbing();

static void ioMapper_UpdateStub(rage::ioMapper* mapper, uint32_t time, bool a3)
{
	bindingManager.Update(mapper, time);

	ioMapper_Update(mapper, time, a3);

	bindingManager.UpdateButtons();

	UpdateButtonPlumbing();
}

void ProfileSettingsInit();

static void* (*origGetFunc)();
static void* GetFunc()
{
	bindingManager.OnGameInit();
	ProfileSettingsInit();

	return origGetFunc();
}

static std::map<std::string, std::tuple<std::string, std::string>> g_registeredBindings;

namespace game
{
	void SetBindingTagActive(const std::string& tag, bool active)
	{
		if (active)
		{
			g_activeTags.insert(tag);
		}
		else
		{
			for (auto it = g_registeredBindings.begin(); it != g_registeredBindings.end();)
			{
				if (std::get<0>(it->second) == tag)
				{
					it = g_registeredBindings.erase(it);
				}
				else
				{
					it++;
				}
			}

			g_activeTags.erase(tag);
		}
	}

	void RegisterBindingForTag(const std::string& tag, const std::string& command, const std::string& languageDesc, const std::string& ioms, const std::string& ioParam)
	{
		g_registeredBindings.insert({ command, { tag, languageDesc } });

		if (!ioms.empty() && !ioParam.empty())
		{
			int ioSource;

			{
				auto it = ioSourceMap.find(ioms);

				if (it == ioSourceMap.end())
				{
					console::Printf("IO", "Invalid I/O source %s\n", ioms);
					return;
				}

				ioSource = it->second;
			}

			int ioParameter;

			{
				auto it = ioParameterMap.find(ioParam);

				if (it == ioParameterMap.end())
				{
					console::Printf("IO", "Invalid key name %s\n", ioParam);
					return;
				}

				ioParameter = _ungetParameterIndex(ioSource, it->second);
			}

			for (auto& binding : bindingManager.GetBindings())
			{
				if (binding.second->GetCommand() == command && IsTagActive(binding.second->GetTag()))
				{
					return;
				}
			}

			bindingManager.Bind(ioSource, ioParameter, command)->SetTag(tag);
		}
	}
}

static uint32_t HashBinding(const std::string& key)
{
	return HashString(key.c_str()) | 0x80000000;
}

static auto GetRegisteredBindingByHash(uint32_t hash)
{
	for (auto& b : g_registeredBindings)
	{
		if (HashBinding(b.first) == hash)
		{
			return b;
		}
	}

	return std::pair<const std::string, std::tuple<std::string, std::string>>{};
}

static void(*g_origGetMappingCategories)(atArray<uint32_t>& mappingCategories);

static void GetMappingCategories(atArray<uint32_t>& mappingCategories)
{
	g_origGetMappingCategories(mappingCategories);

	mappingCategories.Set(mappingCategories.GetCount(), HashString("PM_PANE_CFX"));
}

static void(*g_origGetMappingCategoryInputs)(uint32_t* categoryId, atArray<uint32_t>& controlIds);

static void GetMappingCategoryInputs(uint32_t* categoryId, atArray<uint32_t>& controlIds)
{
	g_origGetMappingCategoryInputs(categoryId, controlIds);

	if (*categoryId == HashString("PM_PANE_CFX"))
	{
		std::vector<std::pair<std::string, std::tuple<std::string, std::string>>> sortedBindings(g_registeredBindings.begin(), g_registeredBindings.end());
		std::sort(sortedBindings.begin(), sortedBindings.end(), [](const auto& left, const auto& right)
		{
			// #TODO: Unicode-aware comparison
			return std::get<1>(left.second) < std::get<1>(right.second);
		});

		for (auto& binding : sortedBindings)
		{
			controlIds.Set(controlIds.GetCount(), HashBinding(binding.first));
		}
	}
}

static void*(*g_origGetBindingForControl)(void* control, rage::ioInputSource* outBinding, uint32_t controlId, int source, uint8_t subIdx, bool unk);

static void* GetBindingForControl(void* control, rage::ioInputSource* outBinding, uint32_t controlId, int source, uint8_t subIdx, bool unk)
{
	if (controlId & 0x80000000)
	{
		outBinding->parameter = -1;
		outBinding->source = -1;
		outBinding->unk = -1;

		if (subIdx == 0)
		{
			auto controlRef = GetRegisteredBindingByHash(controlId);

			for (auto& bindingSet : bindingManager.GetBindings())
			{
				if (bindingSet.second->GetCommand() == controlRef.first && IsTagActive(bindingSet.second->GetTag()))
				{
					bindingSet.second->GetBinding(*outBinding);
					outBinding->unk = source;
					break;
				}
			}
		}

		return outBinding;
	}

	return g_origGetBindingForControl(control, outBinding, controlId, source, subIdx, unk);
}

static const char*(*g_origGetNameForControl)(uint32_t controlIdx);

static const char* GetNameForControl(uint32_t controlId)
{
	if (controlId & 0x80000000)
	{
		auto pair = GetRegisteredBindingByHash(controlId);

		static std::string str;
		str = fmt::sprintf("INPUT_%08X", HashString(pair.first.c_str()));

		// lame hack
		game::AddCustomText(HashString(str.c_str()), fmt::sprintf("%s (%s)", std::get<1>(pair.second), std::get<0>(pair.second)));

		return str.c_str();
	}

	return g_origGetNameForControl(controlId);
}

static uint32_t(*g_origGetControlForName)(const char* controlName);

static uint32_t GetControlForName(const char* controlName)
{
	auto control = g_origGetControlForName(controlName);

	if (control == -1)
	{
		for (auto& pair : g_registeredBindings)
		{
			auto str = fmt::sprintf("INPUT_%08X", HashString(pair.first.c_str()));

			if (str == controlName)
			{
				control = HashBinding(pair.first);
				break;
			}
		}
	}

	return control;
}

static void(*g_origMapControlInternal)(void* control, uint32_t controlIdx, int sourceIdx, rage::ioInputSource* input, uint32_t subIdx, bool persist);

static void MapControlInternal(void* control, uint32_t controlId, int sourceIdx, rage::ioInputSource* input, uint32_t subIdx, bool persist)
{
	if (controlId & 0x80000000)
	{
		auto pair = GetRegisteredBindingByHash(controlId);

		if (!pair.first.empty())
		{
			auto ioSource = input->source;
			auto ioParameter = input->parameter;

			bindingManager.QueueOnFrame([ioSource, ioParameter, pair]()
			{
				auto binding = bindingManager.Bind(ioSource, ioParameter, pair.first);

				if (binding)
				{
					auto tag = std::get<0>(pair.second);

					binding->SetTag(tag);
				}
			});
		}

		return;
	}

	return g_origMapControlInternal(control, controlId, sourceIdx, input, subIdx, persist);
}

static bool(*g_origHandleMappingConflicts)(void* control, uint32_t idx, rage::ioInputSource* input, void* a4, void* a5);

static bool HandleMappingConflicts(void* control, uint32_t idx, rage::ioInputSource* input, void* a4, void* a5)
{
	if (idx & 0x80000000)
	{
		return false;
	}

	return g_origHandleMappingConflicts(control, idx, input, a4, a5);
}

static void(*g_origMapFunc)(void*, uint32_t, void*, void*);

static void MapFuncHook(void* a1, uint32_t controlIdx, void* a3, void* a4)
{
	if (controlIdx < 512)
	{
		g_origMapFunc(a1, controlIdx, a3, a4);
	}
}

static hook::thiscall_stub<rage::ioInputSource*(void* control, rage::ioInputSource* outParam, int controlIdx, int unkN1, bool secondaryBinding, bool)> _control_getBinding([]()
{
	return hook::get_call(hook::get_pattern("40 88 6C 24 28 40 88 6C 24 20 E8 ? ? ? ? 41 8D", 10));
});

void UpdateButtonPlumbing()
{
	rage::ioInputSource controlDatas[2];
	_control_getBinding(g_control, &controlDatas[0], 249 /* INPUT_PUSH_TO_TALK */, -1, false, false);
	_control_getBinding(g_control, &controlDatas[1], 249 /* INPUT_PUSH_TO_TALK */, -1, true, false);

	auto mapBypass = [](rage::ioInputSource& controlData)
	{
		InputHook::ControlBypass bypass = { 0 };

		if (controlData.source == 0 /* IOMS_KEYBOARD */ || controlData.source == 7 /* IOMS_MOUSE_BUTTON */)
		{
			bypass.isMouse = controlData.source == 7;
			bypass.ctrlIdx = controlData.parameter;
		}

		return bypass;
	};

	InputHook::SetControlBypasses({ mapBypass(controlDatas[0]), mapBypass(controlDatas[1]) });
}

#include <boost/algorithm/string.hpp>

static HookFunction hookFunction([]()
{
	if (Is372())
	{
		return;
	}

	console::GetDefaultContext()->OnSaveConfiguration.Connect([](const std::function<void(const std::string&)>& writeLine)
	{
		writeLine("unbindall");

		for (auto& binding : bindingManager.GetBindings())
		{
			auto commandString = binding.second->GetCommand();
			boost::algorithm::replace_all(commandString, "\\", "\\\\");
			boost::algorithm::replace_all(commandString, "\"", "\\\"");

			rage::ioInputSource source;
			binding.second->GetBinding(source);

			auto parameterIndex = _getParameterIndex(source.source, source.parameter);

			std::string ioSource = "";
			std::string ioParameter = "";

			for (auto& entry : ioSourceMap)
			{
				if (entry.second == source.source)
				{
					ioSource = entry.first;
				}
			}

			for (auto& entry : ioParameterMap)
			{
				if (entry.second == parameterIndex)
				{
					ioParameter = entry.first;
				}
			}

			auto sourceString = fmt::sprintf("%s %s", ioSource, ioParameter);

			if (binding.second->GetTag().empty())
			{
				writeLine(fmt::sprintf("bind %s \"%s\"", sourceString, commandString));
			}
			else
			{
				writeLine(fmt::sprintf("rbind %s %s \"%s\"", binding.second->GetTag(), sourceString, commandString));
			}
		}
	});

	game::AddCustomText("PM_PANE_CFX", "FiveM");

	bindingManager.Initialize();

	rage::OnInitFunctionEnd.Connect([](rage::InitFunctionType type)
	{
		if (type == rage::INIT_CORE)
		{
			bindingManager.CreateButtons();
		}
	});

	{
		auto location = hook::get_pattern("45 33 C0 48 8B CF E8 ? ? ? ? 48 81 C7", 6);
		hook::set_call(&ioMapper_Update, location);
		hook::call(location, ioMapper_UpdateStub);
	}

	// coincidental call after first parser init
	{
		auto location = hook::get_pattern("48 8D 55 40 45 8A C6 89 45 44 E8 ? ? ? ? E8", 15);
		hook::set_call(&origGetFunc, location);
		hook::call(location, GetFunc);
	}

	// pause menu hooks
	MH_Initialize();
	MH_CreateHook(hook::get_pattern("74 2A 48 63 CB 8D 56 10 48", -0x23), GetMappingCategories, (void**)&g_origGetMappingCategories);
	MH_CreateHook(hook::get_pattern("45 33 ED 4C 8B E2 41 8B C5 45 85 C0 0F 84", -0x24), GetMappingCategoryInputs, (void**)&g_origGetMappingCategoryInputs);
	MH_CreateHook(hook::get_call(hook::get_pattern("41 B9 FE FF FF FF C6 44 24 28 01 44 88 64 24 20 E8", 16)), GetBindingForControl, (void**)&g_origGetBindingForControl);
	MH_CreateHook(hook::get_call(hook::get_pattern("48 8B F9 45 8A E1 8B CE 45 8B F8 E8", 11)), GetNameForControl, (void**)&g_origGetNameForControl);
	MH_CreateHook(hook::get_pattern("4D 8B F9 45 8B E0 48 8B F9 83 FE FF 0F", -0x22), MapControlInternal, (void**)&g_origMapControlInternal);
	MH_CreateHook(hook::get_call(hook::get_pattern("48 8B DA E8 ? ? ? ? 83 F8 FF 74 27", 3)), GetControlForName, (void**)&g_origGetControlForName);
	MH_CreateHook(hook::get_pattern("33 DB 4C 8B D1 48 89 5E 50", -0x27), HandleMappingConflicts, (void**)&g_origHandleMappingConflicts);
	MH_EnableHook(MH_ALL_HOOKS);

	g_mapperOffset = *hook::get_pattern<uint32_t>("48 63 04 B0 4C 8D 89 ? ? 00 00 B9 BF", 7);

	// hacks for unknown array
	{
		auto location = hook::get_pattern<char>("44 38 34 08 0F 84");
		hook::nop(location, 4 + 6);
	}

	{
		auto location = hook::get_pattern<char>("49 8B D1 8A 1C 0E", 3);
		hook::nop(location, 3);
		hook::put<uint16_t>(location, 0x01B3);
	}

	{
		auto location = hook::get_pattern<char>("42 80 3C 08 00 74");
		hook::put<uint8_t>(location - 12, 0xEB);
		hook::nop(location, 7);
		//hook::put<uint8_t>(location + 5, 0xEB);
	}

	{
		auto location = hook::get_pattern("8A 9C 33 ? 1F 00 00 48 8D");
		hook::nop(location, 7);
		hook::put<uint16_t>(location, 0x01B3);
	}

	{
		auto location = hook::get_pattern<char>("80 BC 33 ? 1F 00 00 00 74 05");
		hook::nop(location, 10);
		//hook::put<uint8_t>(location + 8, 0xEB);
	}

	{
		auto location = hook::get_pattern("83 3C 81 06 77 25");
		hook::nop(location, 10);
		hook::put<uint16_t>(location, 0xC033);
	}

	// fix for ioValue pointer that will be out of bounds if a custom mapping exists
	{
		auto location = hook::get_pattern("48 C1 FA 02 48 8B C2 48 C1 E8 3F 48 03 D0 E8", 14);
		hook::set_call(&g_origMapFunc, location);
		hook::call(location, MapFuncHook);
	}

	// control
	g_control = hook::get_address<void*>(hook::get_pattern("74 09 48 8D 05 ? ? ? ? EB 07 48 8D 05", 5));
	g_controlSize = *hook::get_pattern<int>("E8 ? ? ? ? 48 81 C3 ? ? ? ? 48 FF CF 75 EA", 8);
});

max_stars_repo_name: ISFASI/fivem

max_issues_repo_name: less-x/fivem

max_forks_repo_name: less-x/fivem


text:
//==================================================================================================
/**
  Copyright 2016 Numscale SAS

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

#include <boost/simd/detail/overload.hpp>
#include <boost/simd/function/gammaln.hpp>

namespace boost { namespace simd { namespace ext
{
  namespace bd =  boost::dispatch;
  BOOST_DISPATCH_OVERLOAD ( gammaln_
                          , (typename A0)
                          , bs::sse2_
                          , bs::pack_<bd::double_<A0>, bs::sse_>
                         )
  {
    BOOST_FORCEINLINE A0 operator() ( const A0 & a0 ) const BOOST_NOEXCEPT
    {
      return {bs::gammaln(a0[0]), bs::gammaln(a0[1])};

    }
  };

} } }

#endif

max_stars_repo_name: SylvainCorlay/pythran

max_issues_repo_name: SylvainCorlay/pythran

max_forks_repo_name: SylvainCorlay/pythran


text:
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>

using namespace std;

using boost::asio::ip::tcp;

class Connection : public boost::enable_shared_from_this<Connection>
{
  private:
    tcp::socket sock;
    enum
    {
        BUF_SIZE = 1410
    };
    char buf[BUF_SIZE];
    string msg_;
    char *msg_buff = (char *)malloc(1400 * sizeof(char));
    char *msg_receive=(char *)malloc(1400 * sizeof(char));

    void handle_Read(const boost::system::error_code &error, std::size_t bytes_transferred);
    void handle_Write(const boost::system::error_code &error);
    string make_daytime_string();

  public:
    Connection(boost::asio::io_context &service);
    tcp::socket &getSocket()
    {
        return sock;
    }
    void start();
};

typedef boost::shared_ptr<Connection> ConnectionPtr;

class Server
{
  private:
    tcp::acceptor acceptor;
    void start();
    void handle_Accept(ConnectionPtr con, const boost::system::error_code &error);

  public:
    Server(boost::asio::io_context &service);
};

Connection::Connection(boost::asio::io_context &service) : sock(service)
{
}

void Connection::start()
{
    memset(msg_buff, 0, BUF_SIZE);
    boost::asio::async_read(sock, boost::asio::buffer(msg_buff, BUF_SIZE),
                            boost::asio::transfer_at_least(1), boost::bind(&Connection::handle_Read, // ＃1
                                                                           shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
}

void Connection::handle_Read(const boost::system::error_code &error, std::size_t bytes_transferred)
{
    if (!error)
    {
        cout << "recv from: " << sock.remote_endpoint().address() << ":" << sock.remote_endpoint().port() << endl;
        cout << "接受到的数据：" << endl;
         memcpy(msg_receive,msg_buff,BUF_SIZE);
            //cout << strlen(msg_buff) <<endl;
        printf("%d %s\n", *(short *)msg_receive, msg_receive + 2); //打印发送的数据包
                                                                 /*TODO 数据包验证函数*/
        memset(msg_receive,0,BUF_SIZE);
        msg_ = make_daytime_string();
        cout << "将要发送的数据" << endl;
        cout << msg_ << endl;

        sock.async_write_some(boost::asio::buffer(msg_),
                              boost::bind(
                                  &Connection::handle_Write, // ＃2
                                  shared_from_this(),
                                  boost::asio::placeholders::error));
    }
}

void Connection::handle_Write(const boost::system::error_code &error)
{
    if (!error)
    {
        memset(msg_buff, 0, BUF_SIZE); // 注意：重置buff
        sock.async_read_some(boost::asio::buffer(msg_buff, BUF_SIZE), boost::bind(
                                                                          &Connection::handle_Read, // ＃3
                                                                          shared_from_this(), boost::asio::placeholders::error,
                                                                          boost::asio::placeholders::bytes_transferred));
    }
}

string Connection::make_daytime_string() //生成字符串的日期信息
{
      time_t now = time(0);
    return ctime(&now);
}

Server::Server(boost::asio::io_context &service) : acceptor(service, tcp::endpoint(tcp::v4(), 9972))
{
    start();
}

void Server::start()
{
    ConnectionPtr conn(new Connection(acceptor.get_io_context()));
    acceptor.async_accept(conn->getSocket(), boost::bind(
                                                 &Server::handle_Accept, this, conn,
                                                 boost::asio::placeholders::error));
}

void Server::handle_Accept(ConnectionPtr con, const boost::system::error_code &error)
{
    if (!error)
    {
        con->start();
        start();
    }
}


text:
//Boost reading
#include <boost/iostreams/device/mapped_file.hpp> // for mmap
#include <boost/iostreams/stream.hpp> //for stream
#include <boost/algorithm/string/join.hpp> //for join
#include <algorithm>  // for std::find
#include <cstring>
#include <assert.h>
#include <boost/regex.hpp>

// === RELEASE ===
#include <set>
#include <vector>
#include <map>
#include <iostream>
#include <chrono>

using namespace std::chrono;
using namespace std;

string anagramSolver(string filename, string anagram)
{
	using boost::iostreams::mapped_file_source;
	using boost::iostreams::stream;
	mapped_file_source mmap(filename);
	stream<mapped_file_source> is(mmap, std::ios::binary);
	std::string line;
	set<string>dict;
	istream_iterator<string> eof;
	istream_iterator<string> iit(is);
	copy(iit, eof, inserter(dict, dict.begin()));
	vector<string> anagrams;
	sort(anagram.begin(), anagram.end());
	do {
		if (dict.find(anagram) != dict.end()) {
			anagrams.push_back(anagram);
		}
	} while (next_permutation(anagram.begin(), anagram.end()));
	if (anagrams.size() == 0)
		return nullptr;
	return  boost::algorithm::join(anagrams, ", ");

}

//argv[0] - string app name
//argv[1] - string dictionary path
//argv[2] - string word
int main(int argc, char *argv[])
{
	assert(argc >= 3);
	auto st = std::chrono::high_resolution_clock::now();
	string resultstr = anagramSolver(argv[1], argv[2]);
	auto et = std::chrono::high_resolution_clock::now() - st;
	cout << std::to_string(std::chrono::duration_cast<std::chrono::microseconds>(et).count()) + ", " + resultstr << '\n';
}

max_stars_repo_name: kapstahillar/anagramSolver

max_issues_repo_name: kapstahillar/anagramSolver

max_forks_repo_name: kapstahillar/anagramSolver


text:
#include "FWCore/PluginManager/interface/PluginManager.h"
#include "FWCore/PluginManager/interface/standard.h"
#include "RecoLuminosity/LumiProducer/interface/DataPipe.h"
#include "RecoLuminosity/LumiProducer/interface/DataPipeFactory.h"
#include "RecoLuminosity/LumiProducer/interface/Exception.h"
#include "RecoLuminosity/LumiProducer/interface/RevisionDML.h"
#include "RecoLuminosity/LumiProducer/interface/DBConfig.h"
#include "RecoLuminosity/LumiProducer/interface/Exception.h"
#include "RelationalAccess/ConnectionService.h"
#include "RelationalAccess/ISessionProxy.h"
#include "RelationalAccess/ITransaction.h"
#include "RelationalAccess/ITypeConverter.h"
#include "RelationalAccess/ISchema.h"
#include "CoralBase/Exception.h"
#include <fstream>
#include <stdexcept>
#include <sstream>
#include <iostream>
#include <time.h>
#include <unistd.h>
#include <cstdio>

#include <boost/program_options.hpp>

int main(int argc, char** argv) {
  std::string lumipluginName("Lumi2DB");
  std::string trgpluginName("TRGScalers2DB");
  std::string wbmpluginName("TRGWBM2DB");
  std::string hltpluginName("HLTV32DB");
  std::string hltconfpluginName("HLTConf2DB");
  std::string runsummarypluginName("CMSRunSummary2DB");
  std::string defaultRuninfoConnect("oracle://cms_omds_lb/CMS_RUNINFO");
  std::string defaultTRGConnect("oracle://cms_omds_lb/CMS_GT_MON");
  std::string defaultWBMConnect("oracle://cms_omds_lb/CMS_WBM");
  std::string defaultHLTConfConnect("oracle://cms_omds_lb/CMS_HLT");

  boost::program_options::options_description desc("options");
  boost::program_options::options_description visible("Usage: cmmdLoadLumiDB [options] \n");
  visible.add_options()("runnumber,r", boost::program_options::value<unsigned int>(), "runnumber(required)")(
      "destConnect,c", boost::program_options::value<std::string>(), "destionation connection (required)")(
      "lumipath,L", boost::program_options::value<std::string>(), "path to lumi data file(required)")(
      "authpath,P", boost::program_options::value<std::string>(), "path to authentication xml(default .)")(
      "runinfodb,R", boost::program_options::value<std::string>(), "connect to runinfodb")(
      "confdb,C", boost::program_options::value<std::string>(), "connect to hltconfdb")(
      "trgdb,T", boost::program_options::value<std::string>(), "connect to trgdb")(
      "wbmdb,W", boost::program_options::value<std::string>(), "connect to wbmdb")(
      "configFile,f", boost::program_options::value<std::string>(), "configuration file(optional)")(
      "norm,n", boost::program_options::value<float>(), "norm factor(optional)")(
      "patchcomment,a", boost::program_options::value<std::string>(), "patchcomment(optional)")(
      "without-lumi", "exclude lumi loading")("without-trg", "exclude trg loading")(
      "without-hlt", "exclude hlt loading")("without-runsummary", "exclude runsummary loading")(
      "without-hconf", "exclude hltconf loading")("use-wbm", "use wbmdb for trigger info")(
      "collision-only", "load collision/physics run only")("schemav2-only", "load only to schemav2")(
      "nocheckingstablebeam", "do not require any presence of stable beam")("novalidate", "do not validate lumi data")(
      "dryrun", "dryrun print parameter only")("debug", "switch on debug mode")("help,h", "help message");
  desc.add(visible);
  std::string configuration_filename;
  unsigned int runnumber;
  std::string authpath(".");
  std::string destconnect;
  std::string lumipath;
  std::string runinfodb = defaultRuninfoConnect;
  std::string trgdb = defaultTRGConnect;
  std::string wbmdb = defaultWBMConnect;
  std::string hltconfdb = defaultHLTConfConnect;
  std::string patchcomment("");
  float norm = 0.0;
  bool without_lumi = false;
  bool without_trg = false;
  bool without_hlt = false;
  bool without_runsummary = false;
  bool without_hltconf = false;
  bool use_wbm = false;
  bool debug = false;
  bool novalidate = false;
  bool collision_only = false;
  bool schemav2_only = false;
  bool nocheckingstablebeam = false;
  bool dryrun = false;
  boost::program_options::variables_map vm;
  try {
    boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(desc).run(), vm);
    if (vm.count("help")) {
      std::cout << visible << std::endl;
      ;
      return 0;
    }
    if (vm.count("configFile")) {
      configuration_filename = vm["configFile"].as<std::string>();
      if (!configuration_filename.empty()) {
        std::fstream configuration_file;
        configuration_file.open(configuration_filename.c_str(), std::fstream::in);
        boost::program_options::store(boost::program_options::parse_config_file(configuration_file, desc), vm);
        configuration_file.close();
      }
    }
    if (!vm.count("runnumber")) {
      std::cerr << "[Error] runnumber[r] option given \n";
      std::cerr << " please do " << argv[0] << " --help \n";
      return 1;
    } else {
      runnumber = vm["runnumber"].as<unsigned int>();
    }
    if (!vm.count("destConnect")) {
      std::cerr << "[Error] no destConnect[c] option given \n";
      std::cerr << " please do " << argv[0] << " --help \n";
      return 1;
    } else {
      destconnect = vm["destConnect"].as<std::string>();
    }
    if (vm.count("lumipath")) {
      lumipath = vm["lumipath"].as<std::string>();
    }
    if (vm.count("authpath")) {
      authpath = vm["authpath"].as<std::string>();
    }
    if (vm.count("runinfodb")) {
      runinfodb = vm["runinfodb"].as<std::string>();
    }
    if (vm.count("confdb")) {
      hltconfdb = vm["confdb"].as<std::string>();
    }
    if (vm.count("trgdb")) {
      trgdb = vm["trgdb"].as<std::string>();
    }
    if (vm.count("wbmdb")) {
      wbmdb = vm["wbmdb"].as<std::string>();
    }
    if (vm.count("patchcomment")) {
      patchcomment = vm["patchcomment"].as<std::string>();
    }
    if (vm.count("norm")) {
      norm = vm["norm"].as<float>();
    }
    if (vm.count("without-lumi")) {
      without_lumi = true;
    }
    if (vm.count("without-trg")) {
      without_trg = true;
    }
    if (vm.count("without-hlt")) {
      without_hlt = true;
    }
    if (vm.count("without-runsummary")) {
      without_runsummary = true;
    }
    if (vm.count("without-hconf")) {
      without_hltconf = true;
    }
    if (vm.count("use-wbm")) {
      use_wbm = true;
    }
    if (vm.count("novalidate")) {
      novalidate = true;
    }
    if (vm.count("collision-only")) {
      collision_only = true;
    }
    if (vm.count("schemav2-only")) {
      schemav2_only = true;
    }
    if (vm.count("nocheckingstablebeam")) {
      nocheckingstablebeam = true;
    }
    if (vm.count("dryrun")) {
      dryrun = true;
    }
    if (vm.count("debug")) {
      debug = true;
    }
    if (!without_lumi && lumipath.size() == 0) {
      std::cerr << "[Error] lumipath[L] option is required \n";
      std::cerr << " please do " << argv[0] << " --help \n";
      return 1;
    }
    boost::program_options::notify(vm);
  } catch (const boost::program_options::error& er) {
    std::cerr << er.what() << std::endl;
    return 1;
  }
  if (debug) {
    std::cout << "runnumber " << runnumber << std::endl;
    std::cout << "destConnect " << destconnect << std::endl;
    std::cout << "authpath " << authpath << std::endl;
    std::cout << "lumipath " << lumipath << std::endl;
    std::cout << "runinfodb " << runinfodb << std::endl;
    std::cout << "hltconfdb " << hltconfdb << std::endl;
    std::cout << "trgdb " << trgdb << std::endl;
    std::cout << "wbmdb " << wbmdb << std::endl;
    std::string answer;
    (without_lumi) ? (answer = std::string("No")) : (answer = std::string("Yes"));
    std::cout << "loading lumi? " << answer << std::endl;
    (without_trg) ? (answer = std::string("No")) : (answer = std::string("Yes"));
    std::cout << "loading trg? " << answer << std::endl;
    (without_hlt) ? (answer = std::string("No")) : (answer = std::string("Yes"));
    std::cout << "loading hlt? " << answer << std::endl;
    (without_runsummary) ? (answer = std::string("No")) : (answer = std::string("Yes"));
    std::cout << "loading runsummary? " << answer << std::endl;
    (without_hltconf) ? (answer = std::string("No")) : (answer = std::string("Yes"));
    std::cout << "loading hltconf? " << answer << std::endl;
    (use_wbm) ? (answer = std::string("Yes")) : (answer = std::string("No"));
    std::cout << "using wbm as trigger source? " << answer << std::endl;
    (novalidate) ? (answer = std::string("No")) : (answer = std::string("Yes"));
    std::cout << "validate data? " << answer << std::endl;
    (collision_only) ? (answer = std::string("Yes")) : (answer = std::string("No"));
    std::cout << "collision only ? " << answer << std::endl;
    (schemav2_only) ? (answer = std::string("Yes")) : (answer = std::string("No"));
    std::cout << "schemav2 only ? " << answer << std::endl;
    (nocheckingstablebeam) ? (answer = std::string("No")) : (answer = std::string("Yes"));
    std::cout << "checking stablebeam ? " << answer << std::endl;
    (dryrun) ? (answer = std::string("Yes")) : (answer = std::string("No"));
    std::cout << "dryrun? " << answer << std::endl;
  }
  if (dryrun)
    return 0;
  clock_t startClock, endClock;
  double elapsedTime = 0.0;
  time_t t1, t2;
  edmplugin::PluginManager::Config config;
  edmplugin::PluginManager::configure(edmplugin::standard::config());
  std::cout << "==========" << std::endl;
  unsigned int lumidataid = 0;
  unsigned int trgdataid = 0;
  unsigned int hltdataid = 0;
  if (!without_lumi) {
    std::cout << "Loading lumi from " << lumipath << " to " << destconnect << " run " << runnumber << " with "
              << lumipluginName << std::endl;
    try {
      std::unique_ptr<lumi::DataPipe> lumiptr(lumi::DataPipeFactory::get()->create(lumipluginName, destconnect));
      lumiptr->setAuthPath(authpath);
      lumiptr->setSource(lumipath);
      if (novalidate) {
        lumiptr->setNoValidate();
      }
      if (nocheckingstablebeam) {
        lumiptr->setNoCheckingStableBeam();
      }
      if (norm != 0.0) {
        std::cout << "applying norm " << norm << std::endl;
        lumiptr->setNorm(norm);
      }
      //lumiptr->setMode("beamintensity_only");
      if (!schemav2_only) {
        lumiptr->setMode("loadoldschema");
      }
      startClock = clock();
      time(&t1);
      lumidataid = lumiptr->retrieveData(runnumber);
      time(&t2);
      endClock = clock();
      lumiptr.release();
    } catch (const lumi::invalidDataException& er) {
      //if (novalidate){
      //	std::cout<<"\t [WARNING]lumi data for this run is not valid, load anyway\n";
      //	std::cout<<"\t"<<er.what()<<std::endl;
      //}else{
      std::cout << "\t [ERROR]lumi data for this run is not valid, stop loading immediately";
      std::cout << "\t" << er.what() << std::endl;
      return 1;
      //}
    } catch (const lumi::noStableBeamException& er) {
      std::cout << "\t [ERROR]lumi data for this run has no stable beam, stop loading immediately";
      std::cout << "\t" << er.what() << std::endl;
      return 1;
    } catch (const coral::Exception& er) {
      std::cout << "\t Database error " << er.what() << std::endl;
      throw;
    } catch (...) {
      std::cout << "\tproblem in loading lumi  " << runnumber << " SKIP " << std::endl;
      throw;
    }
    printf("\tElaspsed time %fs\n", difftime(t2, t1));
    elapsedTime = ((double)(endClock - startClock)) / CLOCKS_PER_SEC;
    std::cout << "\tCPU Time taken in seconds : " << elapsedTime << std::endl;
  }
  if (!without_runsummary) {
    std::cout << "Loading runsummary from " << runinfodb << " to " << destconnect << " run " << runnumber << " with "
              << runsummarypluginName << std::endl;
    try {
      std::unique_ptr<lumi::DataPipe> runptr(lumi::DataPipeFactory::get()->create(runsummarypluginName, destconnect));
      runptr->setSource(runinfodb);
      runptr->setAuthPath(authpath);
      if (!collision_only) {
        runptr->setNoValidate();
      }
      startClock = clock();
      time(&t1);
      runptr->retrieveData(runnumber);
      time(&t2);
      endClock = clock();
      runptr.release();
    } catch (const lumi::invalidDataException& er) {
      std::cout << "\t [ERROR], run is not collision run, stop loading immediately";
      std::cout << "\t" << er.what() << std::endl;
      return 1;
    } catch (const coral::Exception& er) {
      std::cout << "\t Database error " << er.what() << std::endl;
      throw;
    } catch (...) {
      std::cout << "\tproblem in loading runsummary " << runnumber << " SKIP " << std::endl;
      throw;
    }
    printf("\tElaspsed time %fs\n", difftime(t2, t1));
    elapsedTime = ((double)(endClock - startClock)) / CLOCKS_PER_SEC;
    std::cout << "\tCPU Time taken in seconds : " << elapsedTime << std::endl;
  }
  if (!without_hltconf) {
    try {
      std::cout << "Loading hlt conf from " << hltconfdb << " to " << destconnect << " run " << runnumber << " with "
                << hltconfpluginName << std::endl;
      std::unique_ptr<lumi::DataPipe> confptr(lumi::DataPipeFactory::get()->create(hltconfpluginName, destconnect));
      confptr->setSource(hltconfdb);
      confptr->setAuthPath(authpath);
      startClock = clock();
      time(&t1);
      confptr->retrieveData(runnumber);
      time(&t2);
      endClock = clock();
      confptr.release();
    } catch (const coral::Exception& er) {
      std::cout << "\t Database error " << er.what() << std::endl;
      throw;
    } catch (...) {
      std::cout << "\tproblem in loading hltconf " << runnumber << " SKIP " << std::endl;
      throw;
    }
    printf("\tElaspsed time %fs\n", difftime(t2, t1));
    elapsedTime = ((double)(endClock - startClock)) / CLOCKS_PER_SEC;
    std::cout << "\tCPU Time taken in seconds : " << elapsedTime << std::endl;
  }
  if (!without_trg) {
    try {
      if (!use_wbm) {
        std::cout << "Loading trg from GT " << trgdb << " to " << destconnect << " run " << runnumber << " with "
                  << trgpluginName << std::endl;
        std::unique_ptr<lumi::DataPipe> trgptr(lumi::DataPipeFactory::get()->create(trgpluginName, destconnect));
        trgptr->setAuthPath(authpath);
        trgptr->setSource(trgdb);
        if (!schemav2_only) {
          trgptr->setMode("loadoldschema");
        }
        startClock = clock();
        time(&t1);
        trgdataid = trgptr->retrieveData(runnumber);
        time(&t2);
        endClock = clock();
        trgptr.release();
      } else {
        std::cout << "Loading trg from WBM " << wbmdb << " to " << destconnect << " run " << runnumber << " with "
                  << wbmpluginName << std::endl;
        std::unique_ptr<lumi::DataPipe> trgptr(lumi::DataPipeFactory::get()->create(wbmpluginName, destconnect));
        trgptr->setAuthPath(authpath);
        trgptr->setSource(wbmdb);
        startClock = clock();
        time(&t1);
        trgdataid = trgptr->retrieveData(runnumber);
        time(&t2);
        endClock = clock();
        trgptr.release();
      }
    } catch (const coral::Exception& er) {
      std::cout << "\t Database error " << er.what() << std::endl;
      throw;
    } catch (...) {
      std::cout << "\tproblem in loading trigger " << runnumber << " SKIP " << std::endl;
      throw;
    }
    printf("\tElaspsed time %fs\n", difftime(t2, t1));
    elapsedTime = ((double)(endClock - startClock)) / CLOCKS_PER_SEC;
    std::cout << "\tCPU Time taken in seconds : " << elapsedTime << std::endl;
  }
  if (!without_hlt) {
    std::cout << "Loading hlt from Runinfo " << runinfodb << " to " << destconnect << " run " << runnumber << " with "
              << hltpluginName << std::endl;
    try {
      std::unique_ptr<lumi::DataPipe> hltptr(lumi::DataPipeFactory::get()->create(hltpluginName, destconnect));
      hltptr->setSource(runinfodb);
      hltptr->setAuthPath(authpath);
      if (!schemav2_only) {
        hltptr->setMode("loadoldschema");
      }
      startClock = clock();
      time(&t1);
      hltdataid = hltptr->retrieveData(runnumber);
      time(&t2);
      endClock = clock();
      hltptr.release();
    } catch (const coral::Exception& er) {
      std::cout << "\t Database error " << er.what() << std::endl;
      throw;
    } catch (...) {
      std::cout << "\tproblem in loading hlt " << runnumber << " SKIP " << std::endl;
      throw;
    }
    printf("\tElaspsed time %fs\n", difftime(t2, t1));
    std::cout << "\tCPU Time taken in seconds : " << elapsedTime << std::endl;
  }

  //
  //register ids and patchcomment
  //
  coral::ConnectionService* svc = new coral::ConnectionService;
  lumi::DBConfig dbconf(*svc);
  if (!authpath.empty()) {
    dbconf.setAuthentication(authpath);
  }
  coral::ISessionProxy* session = svc->connect(destconnect, coral::Update);
  coral::ITypeConverter& lumitpc = session->typeConverter();
  lumitpc.setCppTypeForSqlType("unsigned int", "NUMBER(7)");
  lumitpc.setCppTypeForSqlType("unsigned int", "NUMBER(10)");
  lumitpc.setCppTypeForSqlType("unsigned long long", "NUMBER(20)");
  coral::ITransaction& transaction = session->transaction();
  transaction.start(false);
  lumi::RevisionDML revisionDML;
  unsigned long long currenttagiid = 0;
  try {
    currenttagiid = revisionDML.addRunToCurrentHFDataTag(
        session->nominalSchema(), runnumber, lumidataid, trgdataid, hltdataid, patchcomment);
  } catch (const lumi::duplicateRunInDataTagException&) {
    std::cout << "\t[ERROR] run already registered in the current tag, create a new tag for the patches" << std::endl;
    transaction.rollback();
    delete session;
    return 0;
  } catch (const coral::Exception& er) {
    std::cout << "\t[ERROR] Database error " << er.what() << std::endl;
    throw;
  } catch (...) {
    std::cout << "\t[ERROR] problem in registering run to tag " << runnumber << " SKIP " << std::endl;
    throw;
  }
  transaction.commit();
  std::cout << "register run to current data tag id=" << currenttagiid << " run " << runnumber
            << " dataid: " << lumidataid << "-" << trgdataid << "-" << hltdataid << " " << patchcomment << std::endl;
  delete session;
  return 0;
}

max_stars_repo_name: ckamtsikis/cmssw

max_issues_repo_name: ckamtsikis/cmssw

max_forks_repo_name: ckamtsikis/cmssw


text:
// Copyright (C) 2020 T. Zachary Laine
//
// 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)
// Copyright (C) 2019 T. Zachary Laine
//
// 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)
#ifndef BOOST_TEXT_ILL_FORMED_HPP
#define BOOST_TEXT_ILL_FORMED_HPP

#include <boost/text/detail/algorithm.hpp>

template<template<class...> class Template, typename... Args>
using ill_formed =
    std::integral_constant<bool, !boost::is_detected_v<Template, Args...>>;

template<template<class...> class Template, typename... Args>
using well_formed =
    std::integral_constant<bool, boost::is_detected_v<Template, Args...>>;

#endif

max_stars_repo_name: Ryan-rsm-McKenzie/text

max_issues_repo_name: Ryan-rsm-McKenzie/text

max_forks_repo_name: Ryan-rsm-McKenzie/text


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

    Distributed under the Boost Software License, Version 1.0. (See accompanying
    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#if !defined(FUSION_CONVERT_ITERATOR_05062005_1218)
#define FUSION_CONVERT_ITERATOR_05062005_1218

#include <boost/fusion/support/is_iterator.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/bool.hpp>

namespace boost { namespace fusion
{
    template <typename Iterator>
    struct mpl_iterator; // forward declaration

    //  Test T. If it is a fusion iterator, return a reference to it.
    //  else, assume it is an mpl iterator.

    template <typename T>
    struct convert_iterator
    {
        typedef typename
            mpl::if_<
                is_fusion_iterator<T>
              , T
              , mpl_iterator<T>
            >::type
        type;

        static T const&
        call(T const& x, mpl::true_)
        {
            return x;
        }

        static mpl_iterator<T>
        call(T const& /*x*/, mpl::false_)
        {
            return mpl_iterator<T>();
        }

        static typename
            mpl::if_<
                is_fusion_iterator<T>
              , T const&
              , mpl_iterator<T>
            >::type
        call(T const& x)
        {
            return call(x, is_fusion_iterator<T>());
        }
    };
}}

#endif

max_issues_repo_name: dyzmapl/BumpTop

max_forks_repo_name: dyzmapl/BumpTop