text:
//==============================================================================
//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI
//         Copyright 2012 - 2014 MetaScale SAS
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_SIMD_ARITHMETIC_FUNCTIONS_GENERIC_MOD_HPP_INCLUDED
#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_GENERIC_MOD_HPP_INCLUDED
#include <boost/simd/arithmetic/functions/mod.hpp>
#include <boost/simd/include/functions/simd/selsub.hpp>
#include <boost/simd/include/functions/simd/is_nez.hpp>
#include <boost/simd/include/functions/simd/divfloor.hpp>
#include <boost/simd/include/functions/simd/idivfloor.hpp>
#include <boost/simd/include/functions/simd/multiplies.hpp>
#include <boost/dispatch/attributes.hpp>

namespace boost { namespace simd { namespace ext
{
  BOOST_DISPATCH_IMPLEMENT          ( mod_, tag::cpu_
                                    , (A0)
                                    , (generic_<floating_<A0> >)
                                      (generic_<floating_<A0> >)
                                    )
  {
    typedef A0 result_type;
    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)
    {
      return selsub(boost::simd::is_nez(a1),a0,
                    divfloor(a0,a1)*a1
                   );
    }
  };

  BOOST_DISPATCH_IMPLEMENT          ( mod_, tag::cpu_
                                    , (A0)
                                    , (generic_<arithmetic_<A0> >)
                                      (generic_<arithmetic_<A0> >)
                                    )
  {
    typedef A0 result_type;
    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL_REPEAT(2)
    {
      return selsub(is_nez(a1),a0,
                    boost::simd::multiplies(idivfloor(a0,a1), a1)
                   );

    }
  };

} } }

#endif


text:
#include "extractor/guidance/turn_lane_data.hpp"
#include "util/guidance/turn_lanes.hpp"

#include <boost/numeric/conversion/cast.hpp>

#include <algorithm>
#include <cstddef>
#include <string>
#include <unordered_map>
#include <utility>

namespace osrm
{
namespace extractor
{
namespace guidance
{
namespace lanes
{

bool TurnLaneData::operator<(const TurnLaneData &other) const
{
    if (from < other.from)
        return true;
    if (from > other.from)
        return false;

    if (to < other.to)
        return true;
    if (to > other.to)
        return false;

    // the suppress-assignment flag is ignored, since it does not influence the order
    const constexpr TurnLaneType::Mask tag_by_modifier[] = {TurnLaneType::sharp_right,
                                                            TurnLaneType::right,
                                                            TurnLaneType::slight_right,
                                                            TurnLaneType::straight,
                                                            TurnLaneType::slight_left,
                                                            TurnLaneType::left,
                                                            TurnLaneType::sharp_left,
                                                            TurnLaneType::uturn};
    // U-Turns are supposed to be on the outside. So if the first lane is 0 and we are looking at a
    // u-turn, it has to be on the very left. If it is equal to the number of lanes, it has to be on
    // the right. These sorting function assume reverse to be on the outside always. Might need to
    // be reconsidered if there are situations that offer a reverse from some middle lane (seems
    // improbable)

    if (tag == TurnLaneType::uturn)
    {
        if (from == 0)
            return true;
        else
            return false;
    }

    if (other.tag == TurnLaneType::uturn)
    {
        if (other.from == 0)
            return false;
        else
            return true;
    }

    return std::find(tag_by_modifier, tag_by_modifier + 8, this->tag) <
           std::find(tag_by_modifier, tag_by_modifier + 8, other.tag);
}

LaneDataVector laneDataFromDescription(TurnLaneDescription turn_lane_description)
{
    typedef std::unordered_map<TurnLaneType::Mask, std::pair<LaneID, LaneID>> LaneMap;
    // TODO need to handle cases that have none-in between two identical values
    const auto num_lanes = boost::numeric_cast<LaneID>(turn_lane_description.size());

    const auto setLaneData = [&](
        LaneMap &map, TurnLaneType::Mask full_mask, const LaneID current_lane) {
        const auto isSet = [&](const TurnLaneType::Mask test_mask) -> bool {
            return (test_mask & full_mask) == test_mask;
        };

        for (std::size_t shift = 0; shift < TurnLaneType::detail::num_supported_lane_types; ++shift)
        {
            TurnLaneType::Mask mask = 1 << shift;
            if (isSet(mask))
            {
                auto map_iterator = map.find(mask);
                if (map_iterator == map.end())
                    map[mask] = std::make_pair(current_lane, current_lane);
                else
                {
                    map_iterator->second.first = current_lane;
                }
            }
        }
    };

    LaneMap lane_map;
    LaneID lane_nr = num_lanes - 1;
    if (turn_lane_description.empty())
        return {};

    for (auto full_mask : turn_lane_description)
    {
        setLaneData(lane_map, full_mask, lane_nr);
        --lane_nr;
    }

    // transform the map into the lane data vector
    LaneDataVector lane_data;
    for (const auto tag : lane_map)
        lane_data.push_back({tag.first, tag.second.first, tag.second.second, false});

    std::sort(lane_data.begin(), lane_data.end());

    // check whether a given turn lane string resulted in valid lane data
    const auto hasValidOverlaps = [](const LaneDataVector &lane_data) {
        // Allow an overlap of at most one. Larger overlaps would result in crossing another turn,
        // which is invalid
        for (std::size_t index = 1; index < lane_data.size(); ++index)
        {
            // u-turn located somewhere in the middle
            // Right now we can only handle u-turns at the sides. If we find a u-turn somewhere in
            // the middle of the tags, we abort the handling right here.
            if (index + 1 < lane_data.size() &&
                ((lane_data[index].tag & TurnLaneType::uturn) != TurnLaneType::empty))
                return false;

            if (lane_data[index - 1].to > lane_data[index].from)
                return false;
        }
        return true;
    };

    if (!hasValidOverlaps(lane_data))
        lane_data.clear();

    return lane_data;
}

LaneDataVector::iterator findTag(const TurnLaneType::Mask tag, LaneDataVector &data)
{
    return std::find_if(data.begin(), data.end(), [&](const TurnLaneData &lane_data) {
        return (tag & lane_data.tag) != TurnLaneType::empty;
    });
}
LaneDataVector::const_iterator findTag(const TurnLaneType::Mask tag, const LaneDataVector &data)
{
    return std::find_if(data.cbegin(), data.cend(), [&](const TurnLaneData &lane_data) {
        return (tag & lane_data.tag) != TurnLaneType::empty;
    });
}

bool hasTag(const TurnLaneType::Mask tag, const LaneDataVector &data)
{
    return findTag(tag, data) != data.cend();
}

} // namespace lanes
} // namespace guidance
} // namespace extractor
} // namespace osrm

ext: cpp

max_stars_repo_name: shiyuan/osrm

max_issues_repo_name: zummach/osrm

max_forks_repo_name: dingchunda/osrm-backend


text:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <fstream>
#include "utils.h"
#include "cray_iop.h"
#include <boost/filesystem.hpp>
#include "cray_mainframe.h"

int main(int argc, char* argv[])
{
	if (argc != 3) {
		std::cout << "Usage: " << argv[0] << " <image file> <iop type>" << std::endl;
		return 1;
	}
	bool DoSwapBytes = true;
	uint64_t FileSize = boost::filesystem::file_size(argv[1])/sizeof(IopInt_t);
	const size_t MaxFileSize = 65536*2;
	if (FileSize > MaxFileSize) {
		std::cout << "Can't use files larger than " << MaxFileSize/1024 << "kB" << std::endl;
		return 1;
	}
	std::vector<uint8_t> File((size_t)FileSize*2);
	std::ifstream Input(argv[1], std::ios::in | std::ios::binary);
	if (Input.bad()) {
		std::cout << "Can't open input file: " << argv[1] << std::endl;
		return 1;
	}
	Input.read((char*)&File[0],File.size());
	if (Input.bad()) {
		std::cout << "Can't read file." << std::endl;
		return 1;
	}
	Input.close();
	if (DoSwapBytes) {
		for(size_t i=0;i<FileSize;++i) {
			*(uint16_t*)(&File[i*2]) = SwapBytes(*(uint16_t*)(&File[i*2]));
		}
	}

	size_t Offset = 0;
	IopTypes_e IopType;
	if (strcmp(argv[2],"MIOP") == 0) {
		IopType = IopType_MIOP;
	} else if (strcmp(argv[2],"BIOP") == 0) {
		IopType = IopType_BIOP;
	} else if (strcmp(argv[2],"DIOP") == 0) {
		IopType = IopType_DIOP;
	} else if (strcmp(argv[2],"XIOP") == 0) {
		IopType = IopType_XIOP;
	} else {
		std::cout << "invalid IOP type. Valid values are: MIOP, BIOP, DIOP or XIOP" << std::endl;
		return 1;
	}
	IopCpu_c Iop(IopType, 0,File, nullptr);
	while (Offset < FileSize) {
		std::stringstream Disassembly;
		std::stringstream Explanation;
		std::stringstream InstFields;
		IopInt_t Increment;
		Increment = Iop.Disassemble(IopInt_t(Offset),Disassembly,Explanation,InstFields);
		std::cout << HexPrinter(Offset,4) << " (" << HexPrinter(Offset*2,6) << ") " << InstFields.str() << " | " << std::left << std::setw(30) << Disassembly.str() << std::setw(0);
		if (Explanation.str().length() > 0) std::cout << " | " << Explanation.str();
		std::cout << std::endl;
		Offset += Increment;
	}
	return 0;
}


text:
#include "work_queue.h"

#include <boost/thread.hpp>

std::vector<std::pair<std::string, BOT>> work_queue;
boost::mutex work_queue_lock;

void add_to_queue(const std::string& filename, BOT bot) {
    work_queue_lock.lock();
    work_queue.emplace_back(filename, bot);
    work_queue_lock.unlock();
}

void add_to_queue(const std::string& filename) {
    add_to_queue(filename, bot_from_string(""));
}

void add_to_queue(const std::vector<std::pair<std::string, BOT>>& jobs) {
    work_queue_lock.lock();
    work_queue.reserve(jobs.size() + work_queue.size());
    work_queue.insert(work_queue.end(), jobs.begin(), jobs.end());
    work_queue_lock.unlock();
}

void add_to_queue(const std::vector<std::string>& filenames) {
    std::vector<std::pair<std::string, BOT>> jobs;
    jobs.reserve(filenames.size());
    for (const auto& filename : filenames) {
        jobs.emplace_back(filename, bot_from_string(""));
    }
    add_to_queue(jobs);
}

std::vector<std::pair<std::string, BOT>> queue_copy() {
    std::vector<std::pair<std::string, BOT>> out;
    out.reserve(work_queue.size());
    work_queue_lock.lock();
    out.insert(out.begin(), work_queue.begin(), work_queue.end());
    work_queue_lock.unlock();
    return out;
}

std::optional<std::pair<std::string, BOT>> get_job() {
    if (work_queue.empty()) return std::nullopt;

    work_queue_lock.lock();
    auto job = work_queue[0];
    work_queue.erase(work_queue.begin());
    work_queue_lock.unlock();

    return std::make_optional(job);
}

BOT bot_from_string(const std::string& bot_name) {
    if (bot_name == "leela_zero") {
        return BOT::LEELA_ZERO;
    } else {
        return BOT::LEELA;
    }
}

std::string string_from_bot(BOT bot) {
    switch (bot) {
        case BOT::LEELA_ZERO: return "leela_zero";
        default: return "leela";
    }
}

max_stars_repo_name: mkkelley/autogrp

max_issues_repo_name: mkkelley/autogrp

max_forks_repo_name: mkkelley/autogrp


text:
///////////////////////////////////////////////////////////////////
//  Copyright Eduardo Quintana 2021
//  Copyright Janek Kozicki 2021
//  Copyright Christopher Kormanyos 2021
//  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)

// Example using custom allocators
#include <boost/math/fft/bsl_backend.hpp>
#include <array>
#include <numeric>

#if __cplusplus >= 201700L
#include <memory>
#include <memory_resource>
#endif

using namespace boost::math::fft;

int main()
{
#if __cplusplus >= 201700L
  const std::size_t N = 100;
  std::array<char,30000> buf;
  std::pmr::monotonic_buffer_resource
    pool{buf.data(),buf.size(),std::pmr::null_memory_resource()};

  using Real = double;
  using Complex = std::complex<Real>;
  using allocator_type = std::pmr::polymorphic_allocator<Complex>;

  std::vector<Complex,allocator_type> A(N,Complex(),&pool);
  std::vector<Complex,allocator_type> B(N,Complex(),&pool);
  // ...
  bsl_dft<Complex,allocator_type> plan(N,&pool);
  plan.forward(A.begin(),A.end(),B.begin());
#endif
  return 0;
}


text:
/*
 * libasiotap - A portable TAP adapter extension for Boost::ASIO.
 * Copyright (C) 2010-2011 Julien KAUFFMANN <julien.kauffmann@freelan.org>
 *
 * This file is part of libasiotap.
 *
 * libasiotap is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of
 * the License, or (at your option) any later version.
 *
 * libasiotap is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 *
 * In addition, as a special exception, the copyright holders give
 * permission to link the code of portions of this program with the
 * OpenSSL library under certain conditions as described in each
 * individual source file, and distribute linked combinations
 * including the two.
 * You must obey the GNU General Public License in all respects
 * for all of the code used other than OpenSSL.  If you modify
 * file(s) with this exception, you may extend this exception to your
 * version of the file(s), but you are not obligated to do so.  If you
 * do not wish to do so, delete this exception statement from your
 * version.  If you delete this exception statement from all source
 * files in the program, then also delete it here.
 *
 * If you intend to use libasiotap in a commercial software, please
 * contact me : we may arrange this for a small fee or no fee at all,
 * depending on the nature of your project.
 */

/**
 * \file posix_tap_adapter.hpp
 * \author Julien KAUFFMANN <julien.kauffmann@freelan.org>
 * \brief The POSIX tap adapter class.
 */

#ifndef ASIOTAP_WINDOWS_REGISTRY_HPP
#define ASIOTAP_WINDOWS_REGISTRY_HPP

#include <windows.h>

#include <boost/system/system_error.hpp>
#include <boost/optional.hpp>
#include <boost/array.hpp>
#include <boost/filesystem.hpp>

#include <string>
#include <iterator>

#include "../error.hpp"

namespace asiotap
{
	class registry_key
	{
		public:

			registry_key() :
				m_key(),
				m_name()
			{
			}

			registry_key(HKEY hKey, const std::string& name, REGSAM samDesired = KEY_READ) :
				m_key(),
				m_name(name)
			{
				HKEY key;

				const LONG status = ::RegOpenKeyExA(hKey, m_name.c_str(), 0, samDesired, &key);

				if (status != ERROR_SUCCESS)
				{
					throw boost::system::system_error(status, boost::system::system_category());
				}

				m_key = key;
			}

			registry_key(const registry_key& parent, const std::string& name, REGSAM samDesired = KEY_READ) :
				registry_key(parent.native_handle(), name, samDesired)
			{
			}

			~registry_key()
			{
				if (m_key)
				{
					::RegCloseKey(*m_key);
				}
			}

			registry_key(const registry_key&) = delete;
			registry_key& operator=(const registry_key&) = delete;

			registry_key(registry_key&& other) throw() :
				m_key(other.m_key),
				m_name(other.m_name)
			{
				other.m_key.reset();
				other.m_name.clear();
			}

			registry_key& operator=(registry_key&& other) throw()
			{
				using std::swap;

				swap(m_key, other.m_key);

				return *this;
			}

			bool is_open() const
			{
				return static_cast<bool>(m_key);
			}

			HKEY native_handle() const
			{
				return *m_key;
			}

			const std::string& name() const
			{
				return m_name;
			}

			void query_value(const std::string& value_name, DWORD& type, void* buf, size_t& buflen, boost::system::error_code& ec) const
			{
				DWORD data_len = static_cast<DWORD>(buflen);

				const LONG status = ::RegQueryValueExA(native_handle(), value_name.c_str(), NULL, &type, static_cast<LPBYTE>(buf), &data_len);

				buflen = static_cast<size_t>(data_len);

				if (status != ERROR_SUCCESS)
				{
					ec = boost::system::error_code(status, boost::system::system_category());

					return;
				}
			}

			std::string query_string(const std::string& value_name, boost::system::error_code& ec) const
			{
				boost::array<char, 256> value;

				DWORD type = REG_NONE;

				size_t value_size = value.size();

				query_value(value_name, type, value.data(), value_size, ec);

				if (ec)
				{
					return std::string();
				}

				if (type != REG_SZ)
				{
					ec = make_error_code(asiotap_error::invalid_type);
				}

				return std::string(value.begin(), value.begin() + value_size - 1);
			}

			std::string query_string(const std::string& value_name) const
			{
				boost::system::error_code ec;

				const std::string result = query_string(value_name, ec);

				if (ec)
				{
					throw boost::system::system_error(ec);
				}

				return result;
			}

			boost::filesystem::path query_path(const std::string& value_name, boost::system::error_code& ec) const
			{
				boost::array<char, 4096> value;

				DWORD type = REG_NONE;

				size_t value_size = value.size();

				query_value(value_name, type, value.data(), value_size, ec);

				if (ec)
				{
					return std::string();
				}

				if (type != REG_SZ)
				{
					ec = make_error_code(asiotap_error::invalid_type);
				}

				return boost::filesystem::path(value.begin(), value.begin() + value_size - 1);
			}

			boost::filesystem::path query_path(const std::string& value_name) const
			{
				boost::system::error_code ec;

				const boost::filesystem::path result = query_path(value_name, ec);

				if (ec)
				{
					throw boost::system::system_error(ec);
				}

				return result;
			}

			registry_key operator[](size_t index) const
			{
				boost::array<char, 256> name;
				DWORD name_size = static_cast<DWORD>(name.size());

				const LONG status = ::RegEnumKeyExA(native_handle(), static_cast<DWORD>(index), name.data(), &name_size, NULL, NULL, NULL, NULL);

				switch (status)
				{
					case ERROR_SUCCESS:
					{
						try
						{
							return registry_key(*this, std::string(name.begin(), name.begin() + name_size));
						}
						catch (const boost::system::system_error&)
						{
							return registry_key();
						}
					}
					case ERROR_NO_MORE_ITEMS:
					{
						return registry_key();
					}
					default:
					{
						throw boost::system::system_error(status, boost::system::system_category());
					}
				}
			}

			size_t size() const
			{
				DWORD count = 0;

				const LONG status = ::RegQueryInfoKey(native_handle(), NULL, NULL, NULL, &count, NULL, NULL, NULL, NULL, NULL, NULL, NULL);

				if (status != ERROR_SUCCESS)
				{
					throw boost::system::system_error(status, boost::system::system_category());
				}

				return static_cast<size_t>(count);
			}

			class const_iterator : public std::iterator<std::forward_iterator_tag, registry_key>
			{
				public:

					const_iterator operator++(int)
					{
						const const_iterator result = *this;

						++m_index;

						return result;
					}

					const_iterator& operator++()
					{
						m_index++;

						return *this;
					}

					value_type operator*() const
					{
						return m_key[m_index];
					}

				private:

					const_iterator(const registry_key& key, size_t index) :
						m_key(key),
						m_index(index)
					{
					}

					friend bool operator<(const const_iterator& lhs, const const_iterator& rhs)
					{
						assert(&lhs.m_key == &rhs.m_key);

						return (lhs.m_index < rhs.m_index);
					}

					friend bool operator==(const const_iterator& lhs, const const_iterator& rhs)
					{
						assert(&lhs.m_key == &rhs.m_key);

						return (lhs.m_index == rhs.m_index);
					}

					friend bool operator!=(const const_iterator& lhs, const const_iterator& rhs)
					{
						assert(&lhs.m_key == &rhs.m_key);

						return (lhs.m_index != rhs.m_index);
					}

					const registry_key& m_key;
					size_t m_index;

					friend class registry_key;
			};

			class available_keys_range
			{
				public:

					const_iterator begin() const
					{
						return const_iterator(m_key, 0);
					}

					const_iterator end() const
					{
						return const_iterator(m_key, m_key.size());
					}

				private:

					available_keys_range(const registry_key& key) :
						m_key(key)
					{}

					const registry_key& m_key;

					friend class registry_key;
			};

			available_keys_range available_keys() const
			{
				return available_keys_range(*this);
			}

		private:

			boost::optional<HKEY> m_key;
			std::string m_name;
	};
}

#endif /* ASIOTAP_WINDOWS_REGISTRY_HPP */

ext: hpp

max_stars_repo_name: krattai/AEBL

max_issues_repo_name: krattai/AEBL

max_forks_repo_name: krattai/AEBL


text: #include <boost/spirit/home/qi/string/symbols.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#ifndef PRIMAL_SOLVER_HPP_
#define PRIMAL_SOLVER_HPP_

#include "Tool_impl.hpp"
#include <algorithm>

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

namespace sdm{

class PrimalSolver {
public:
  virtual ~PrimalSolver(void) {}
  virtual int get_valid_l(void) = 0;
  virtual int get_valid_n(void) = 0;
  virtual Eigen::VectorXd train_warm_start(const Eigen::VectorXd &w) = 0;

  // virtual Eigen::VectorXd train_warm_start_inexact(const Eigen::VectorXd &w,
  //                                                  const double
  //                                                  inexact_level,
  //                                                  double &ub_validerr,
  //                                                  double &lb_validerr) = 0;

};

}
#endif //PrimalSolver_hpp_

max_stars_repo_name: takeuchi-lab/rpcvelb

max_issues_repo_name: takeuchi-lab/rpcvelb

max_forks_repo_name: takeuchi-lab/rpcvelb


text:
#include <iostream>
#include <fstream>
#include <sstream>
#include <map>
#include <list>
#include <string>
#include <set>
#include <vector>
#include <utility>
#include <boost/algorithm/string.hpp>

using namespace std;
using namespace boost;

struct Ing {
    __int64 quantity;
    string name;
};
typedef list<Ing> IngList;
struct RecipeElement {
    __int64 makes;
    IngList ings;
    RecipeElement() : makes(0) {}
};
typedef map<string, RecipeElement> Recipe;
typedef map<string, __int64> Stash;

Ing Parse(string s)
{
    Ing r;
    stringstream ss(s);
    ss >> r.quantity;
    ss >> r.name;
    trim(r.name);

    return r;
}

Recipe Load()
{
    Recipe r;
    ifstream f("Data.txt");

    while (!f.eof()) {
        string s;
        getline(f, s);

        vector<string> parts;
        split(parts, s, is_any_of("=>"), token_compress_on);
        vector<string> ings;
        split(ings, parts[0], is_any_of(","), token_compress_on);

        Ing result = Parse(parts[1]);
        auto& re = r[result.name];
        re.makes = result.quantity;

        for (const string& ing : ings) {
            Ing src = Parse(ing);
            re.ings.push_back(src);
        }
    }

    return r;
}

__int64 GetRequiredOre(const Recipe& r, const string& type, __int64 num, Stash& stash)
{
    __int64 ore = 0;
    __int64 in_stash = stash[type];

    //cout << "Need " << num << " " << type << "> ";

    // Check if we have enough in stash
    if (in_stash > num) {
        stash[type] -= num;
        //cout << "In stash" << endl;
        return 0;
    }

    // Exhaust stash first
    //cout << stash[type] << " from stash, ";
    num -= stash[type];
    stash.erase(type);

    // Get recipe
    auto it = r.find(type);
    if (it == r.end()) throw std::exception("No recipe!");
    auto& re = it->second;

    // Recipe makes X lots per batch, so need to make
    __int64 to_make = (__int64)ceil(1.0 * num / re.makes);
    //cout << "Making " << to_make * re.makes << "< ";
    //for (auto ing : re.ings) cout << ing.name << ": " << ing.quantity * to_make << " ";
    //cout << endl;

    for (auto ing : re.ings) {
        if (ing.name == "ORE"s) {
            ore += ing.quantity * to_make;
        }
        else {
            ore += GetRequiredOre(r, ing.name, ing.quantity * to_make, stash);
        }
    }

    stash[type] += (to_make * re.makes - num);
    return ore;
}

int main()
{
    Recipe r = Load();
    Stash stash;
    __int64 needs = GetRequiredOre(r, "FUEL", 1, stash);
    cout << "FUEL requires " << needs << " ORE" << endl;
    cout << "Left over:" << endl;
    for (auto x : stash) {
        if (x.second > 0) {
            cout << "  " << x.first << " = " << x.second << endl;
        }
    }

    // Part 2 - for 1e12 ore, how much fuel.  Search!
    __int64 target = 1000000000000i64;
    __int64 guess = target / needs + 1;
    __int64 step = 16777216;
    while (true) {
        stash.clear();
        needs = GetRequiredOre(r, "FUEL", guess, stash);
        cout << "Guess " << guess << " gives " << needs << endl;
        if (needs > target) {
            guess -= step;
        }
        else if (step > 1) {
            step /= 2;
            guess += step;
        }
        else {
            break;
        }
    }
    cout << guess << " FUEL from " << needs << " ORE" << endl;

    return 0;
}


text:
/*!
 * Author: mocibb mocibb@163.com
 * Group:  CarrotSLAM https://github.com/mocibb/CarrotSLAM
 * Name:   covisible_keyframe.cpp
 * Date:   2015.10.11
 * Func:
 *
 *
 * The MIT License (MIT)
 * Copyright (c) 2015 CarrotSLAM Group
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
#include <Eigen/Core>
#include <sophus/se3.hpp>
#include "core/carrot_slam.h"
#include "types/pinhole_camera.h"
#include "types/covisible_keyframe.h"
#include <set>

namespace carrotslam {

void CovisibleKeyFrame::add(const CovisibleKeyFramePtr& frame, float weight) {
  CovisibleEdge edge;
  edge.vertex = frame;
  edge.weight = weight;
  edges_.insert(edge);
}

void CovisibleKeyFrame::remove(const CovisibleKeyFramePtr& frame) {
  for (auto e : edges_) {
    if (e.vertex->id_ == frame->id_) {
      edges_.erase(e);
      break;
    }
  }
}

std::vector<CovisibleKeyFramePtr> CovisibleKeyFrame::getCovisibleKeyFrames() {
  std::vector<CovisibleKeyFramePtr> frames;

  for (auto e : edges_) {
    frames.push_back(e.vertex);
  }

  return frames;
}

std::vector<CovisibleKeyFramePtr> CovisibleKeyFrame::getBestCovisibilityKeyFrames(const int &N){
  std::vector<CovisibleKeyFramePtr> frames;

  for (auto e : edges_) {
    frames.push_back(e.vertex);
    if (frames.size() >= N)
      break;
  }

  return frames;
}
}  // namespace carrotslam

max_stars_repo_name: mocibb/CarrotSLAM

max_issues_repo_name: ayumizll/CarrotSLAM

max_forks_repo_name: ayumizll/CarrotSLAM


text:
#include "miningpage.h"
#include "ui_miningpage.h"

#include "dynode-sync.h"
#include "guiutil.h"
#include "miner.h"
#include "net.h"
#include "util.h"
#include "utiltime.h"
#include "validation.h"
#include "walletmodel.h"

#include <boost/thread.hpp>
#include <stdio.h>

MiningPage::MiningPage(const PlatformStyle *platformStyle, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MiningPage),
    hasMiningprivkey(false)
{
    ui->setupUi(this);

    int nMaxUseThreads = GUIUtil::MaxThreads();

    std::string PrivAddress = GetArg("-miningprivkey", "");
    if (!PrivAddress.empty())
    {
        CDynamicSecret Secret;
        Secret.SetString(PrivAddress);
        if (Secret.IsValid())
        {
            CDynamicAddress Address;
            Address.Set(Secret.GetKey().GetPubKey().GetID());
            ui->labelAddress->setText(QString("All mined coins will go to %1").arg(Address.ToString().c_str()));
            hasMiningprivkey = true;
        }
    }

    ui->sliderCores->setMinimum(0);
    ui->sliderCores->setMaximum(nMaxUseThreads);
    ui->sliderCores->setValue(nMaxUseThreads);
    ui->labelNCores->setText(QString("%1").arg(nMaxUseThreads));
    ui->sliderGraphSampleTime->setMaximum(0);
    ui->sliderGraphSampleTime->setMaximum(6);

    ui->sliderCores->setToolTip(tr("Use the slider to select the amount of CPU threads to use"));
    ui->labelNetHashRate->setToolTip(tr("This shows the overall hashrate of the Dynamic network"));
    ui->labelMinerHashRate->setToolTip(tr("This shows the hashrate of your CPU whilst mining"));
    ui->labelNextBlock->setToolTip(tr("This shows the average time between the blocks you have mined"));

    connect(ui->sliderCores, SIGNAL(valueChanged(int)), this, SLOT(changeNumberOfCores(int)));
    connect(ui->sliderGraphSampleTime, SIGNAL(valueChanged(int)), this, SLOT(changeSampleTime(int)));
    connect(ui->pushSwitchMining, SIGNAL(clicked()), this, SLOT(switchMining()));
    connect(ui->pushButtonClearData, SIGNAL(clicked()), this, SLOT(clearHashRateData()));
    connect(ui->checkBoxShowGraph, SIGNAL(stateChanged(int)), this, SLOT(showHashRate(int)));
    //
    ui->minerHashRateWidget->graphType = HashRateGraphWidget::GraphType::MINER_HASHRATE;
    ui->minerHashRateWidget->UpdateSampleTime(HashRateGraphWidget::SampleTime::FIVE_MINUTES);

    showHashMeterControls(false);
    updateUI();
    startTimer(3511);
}

MiningPage::~MiningPage()
{
    delete ui;
}

void MiningPage::setModel(WalletModel *model)
{
    this->model = model;
}

void MiningPage::updateUI()
{
    qint64 NetworkHashrate = GUIUtil::GetNetworkHashPS(120, -1);
    qint64 Hashrate = GUIUtil::GetHashRate();

    ui->labelNetHashRate->setText(GUIUtil::FormatHashRate(NetworkHashrate));
    ui->labelMinerHashRate->setText(GUIUtil::FormatHashRate(Hashrate));

    QString NextBlockTime;
    if (Hashrate == 0)
        NextBlockTime = QChar(L'∞');
    else
    {
        arith_uint256 Target;
        Target.SetCompact(chainActive.Tip()->nBits);
        arith_uint256 ExpectedTime = (arith_uint256(1) << 256)/(Target*Hashrate);
        NextBlockTime = GUIUtil::FormatTimeInterval(ExpectedTime);
    }

    ui->labelNextBlock->setText(NextBlockTime);

    if (!dynodeSync.IsSynced() || !dynodeSync.IsBlockchainSynced()) {
        ui->pushSwitchMining->setToolTip(tr("Blockchain/Dynodes are not synced, please wait until fully synced before mining!"));
        ui->pushSwitchMining->setText(tr("Disabled"));
        ui->pushSwitchMining->setEnabled(false);
    }
    else if (dynodeSync.IsSynced() && dynodeSync.IsBlockchainSynced() && GUIUtil::GetHashRate() == 0) {
        ui->pushSwitchMining->setToolTip(tr("Click 'Start mining' to begin mining!"));
        ui->pushSwitchMining->setText(tr("Start mining"));
        ui->pushSwitchMining->setEnabled(true);
     }
     else {
        ui->pushSwitchMining->setToolTip(tr("Click 'Stop mining' to finish mining!"));
        ui->pushSwitchMining->setText(tr("Stop mining"));
        ui->pushSwitchMining->setEnabled(true);
    }
}

void MiningPage::StartMiner()
{
    int nThreads = (int)ui->sliderCores->value();
    GenerateDynamics(true, nThreads, Params(), *g_connman);
    updateUI();
}

void MiningPage::StopMiner()
{
    GenerateDynamics(false, 0, Params(), *g_connman);
    updateUI();
}

void MiningPage::changeNumberOfCores(int i)
{
    ui->labelNCores->setText(QString("%1").arg(i));
    if (i == 0) {
        StopMiner();
    }
    else if (i > 0 && GUIUtil::GetHashRate() > 0) {
        StartMiner();
    }
}

void MiningPage::switchMining()
{
    int64_t hashRate = GUIUtil::GetHashRate();
    int nThreads = (int)ui->sliderCores->value();

    if (hashRate > 0) {
        ui->pushSwitchMining->setText(tr("Stopping"));
        StopMiner();
    }
    else if (nThreads == 0 && hashRate == 0){
        ui->sliderCores->setValue(1);
        ui->pushSwitchMining->setText(tr("Starting"));
        StartMiner();
    }
    else {
        ui->pushSwitchMining->setText(tr("Starting"));
        StartMiner();
    }
}

void MiningPage::timerEvent(QTimerEvent *)
{
    updateUI();
}

void MiningPage::showHashRate(int i)
{
    if (i == 0) {
        ui->minerHashRateWidget->StopHashMeter();
        showHashMeterControls(false);
    }
    else {
        ui->minerHashRateWidget->StartHashMeter();
        showHashMeterControls(true);
    }
}

void MiningPage::showHashMeterControls(bool show)
{
    if (show == false) {
        ui->sliderGraphSampleTime->setVisible(false);
        ui->labelGraphSampleSize->setVisible(false);
        ui->pushButtonClearData->setVisible(false);
    }
    else {
        ui->sliderGraphSampleTime->setVisible(true);
        ui->labelGraphSampleSize->setVisible(true);
        ui->pushButtonClearData->setVisible(true);
    }
}

void MiningPage::changeSampleTime(int i)
{
    if (i == 0) {
        ui->minerHashRateWidget->UpdateSampleTime(HashRateGraphWidget::SampleTime::FIVE_MINUTES);
        ui->labelGraphSampleSize->setText(QString("5 minutes"));
    }
    else if (i == 1) {
        ui->minerHashRateWidget->UpdateSampleTime(HashRateGraphWidget::SampleTime::TEN_MINUTES);
        ui->labelGraphSampleSize->setText(QString("10 minutes"));
    }
    else if (i == 2) {
        ui->minerHashRateWidget->UpdateSampleTime(HashRateGraphWidget::SampleTime::THIRTY_MINUTES);
        ui->labelGraphSampleSize->setText(QString("30 minutes"));
    }
    else if (i == 3) {
        ui->minerHashRateWidget->UpdateSampleTime(HashRateGraphWidget::SampleTime::ONE_HOUR);
        ui->labelGraphSampleSize->setText(QString("1 hour"));
    }
    else if (i == 4) {
        ui->minerHashRateWidget->UpdateSampleTime(HashRateGraphWidget::SampleTime::EIGHT_HOURS);
        ui->labelGraphSampleSize->setText(QString("8 hours"));
    }
    else if (i == 5) {
        ui->minerHashRateWidget->UpdateSampleTime(HashRateGraphWidget::SampleTime::TWELVE_HOURS);
        ui->labelGraphSampleSize->setText(QString("12 hours"));
    }
    else if (i == 6) {
        ui->minerHashRateWidget->UpdateSampleTime(HashRateGraphWidget::SampleTime::ONE_DAY);
        ui->labelGraphSampleSize->setText(QString("1 day"));
    }
    else {
        ui->minerHashRateWidget->UpdateSampleTime(HashRateGraphWidget::SampleTime::ONE_DAY);
        ui->labelGraphSampleSize->setText(QString("1 day"));
    }
}

void MiningPage::clearHashRateData()
{
    ui->minerHashRateWidget->clear();
}

max_stars_repo_name: Ethernodes-org/Dynamic


text:
/*********************************************************************
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2012, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *********************************************************************/

/* Author: Ioan Sucan, Dave Coleman */

#include <moveit/kinematics_plugin_loader/kinematics_plugin_loader.h>
#include <moveit/rdf_loader/rdf_loader.h>
#include <pluginlib/class_loader.hpp>
#include <boost/thread/mutex.hpp>
#include <sstream>
#include <vector>
#include <map>
#include <memory>
#include "rclcpp/rclcpp.hpp"
#include <moveit/profiler/profiler.h>

namespace kinematics_plugin_loader
{
rclcpp::Logger LOGGER = rclcpp::get_logger("kinematics_plugin_loader");

class KinematicsPluginLoader::KinematicsLoaderImpl
{
public:
  /**
   * \brief Pimpl Implementation of KinematicsLoader
   * \param robot_description
   * \param possible_kinematics_solvers
   * \param search_res
   * \param iksolver_to_tip_links - a map between each ik solver and a vector of custom-specified tip link(s)
   */
  KinematicsLoaderImpl(const rclcpp::Node::SharedPtr& node, const std::string& robot_description,
                       const std::map<std::string, std::vector<std::string>>& possible_kinematics_solvers,
                       const std::map<std::string, std::vector<double>>& search_res,
                       const std::map<std::string, std::vector<std::string>>& iksolver_to_tip_links)
    : node_(node)
    , robot_description_(robot_description)
    , possible_kinematics_solvers_(possible_kinematics_solvers)
    , search_res_(search_res)
    , iksolver_to_tip_links_(iksolver_to_tip_links)
  {
    try
    {
      kinematics_loader_.reset(new pluginlib::ClassLoader<kinematics::KinematicsBase>("moveit_core", "kinematics::"
                                                                                "KinematicsBase"));
    }
    catch (pluginlib::PluginlibException& e)
    {
      RCLCPP_ERROR(LOGGER, "Unable to construct kinematics loader. Error: %s", e.what());
    }
  }

  /**
   * \brief Helper function to decide which, and how many, tip frames a planning group has
   * \param jmg - joint model group pointer
   * \return tips - list of valid links in a planning group to plan for
   */
  std::vector<std::string> chooseTipFrames(const robot_model::JointModelGroup* jmg)
  {
    std::vector<std::string> tips;
    std::map<std::string, std::vector<std::string>>::const_iterator ik_it = iksolver_to_tip_links_.find(jmg->getName());

    // Check if tips were loaded onto the rosparam server previously
    if (ik_it != iksolver_to_tip_links_.end())
    {
      // the tip is being chosen based on a corresponding rosparam ik link
      RCLCPP_DEBUG(LOGGER, "Choosing tip frame of kinematic solver for group %s"
                           "based on values in rosparam server.",
                   jmg->getName().c_str());
      tips = ik_it->second;
    }
    else
    {
      // get the last link in the chain
      RCLCPP_DEBUG(LOGGER, "Choosing tip frame of kinematic solver for group %s"
                           "based on last link in chain",
                   jmg->getName().c_str());

      tips.push_back(jmg->getLinkModels().back()->getName());
    }

    // Error check
    if (tips.empty())
    {
      RCLCPP_ERROR(LOGGER, "Error choosing kinematic solver tip frame(s).");
    }

    // Debug tip choices
    std::stringstream tip_debug;
    tip_debug << "Planning group '" << jmg->getName() << "' has tip(s): ";
    for (std::size_t i = 0; i < tips.size(); ++i)
      tip_debug << tips[i] << ", ";
    RCLCPP_DEBUG(LOGGER, tip_debug.str());

    return tips;
  }

  kinematics::KinematicsBasePtr allocKinematicsSolver(const robot_model::JointModelGroup* jmg)
  {
    kinematics::KinematicsBasePtr result;
    if (!kinematics_loader_)
    {
      RCLCPP_ERROR(LOGGER, "Invalid kinematics loader.");
      return result;
    }
    if (!jmg)
    {
      RCLCPP_ERROR(LOGGER, "Specified group is NULL. Cannot allocate kinematics solver.");
      return result;
    }
    const std::vector<const robot_model::LinkModel*>& links = jmg->getLinkModels();
    if (links.empty())
    {
      RCLCPP_ERROR(LOGGER, "No links specified for group '%s'. Cannot allocate kinematics solver.",
                   jmg->getName().c_str());
      return result;
    }

    RCLCPP_DEBUG(LOGGER, "Trying to allocate kinematics solver for group '%s'", jmg->getName().c_str());

    std::map<std::string, std::vector<std::string>>::const_iterator it =
        possible_kinematics_solvers_.find(jmg->getName());
    if (it == possible_kinematics_solvers_.end())
    {
      RCLCPP_DEBUG(LOGGER, "No kinematics solver available for this group");
      return result;
    }

    const std::string& base = links.front()->getParentJointModel()->getParentLinkModel() ?
                                  links.front()->getParentJointModel()->getParentLinkModel()->getName() :
                                  jmg->getParentModel().getModelFrame();

    // just to be sure, do not call the same pluginlib instance allocation function in parallel
    boost::mutex::scoped_lock slock(lock_);
    for (std::size_t i = 0; !result && i < it->second.size(); ++i)
    {
      try
      {
        result = kinematics_loader_->createUniqueInstance(it->second[i]);
        if (result)
        {
          // choose the tip of the IK solver
          const std::vector<std::string> tips = chooseTipFrames(jmg);

          // choose search resolution
          double search_res = search_res_.find(jmg->getName())->second[i];  // we know this exists, by construction

          if (!result->initialize(node_, jmg->getParentModel(), jmg->getName(),
                                  (base.empty() || base[0] != '/') ? base : base.substr(1), tips, search_res) &&
              // on failure: fallback to old method (TODO: remove in future)
              !result->initialize(robot_description_, jmg->getName(),
                                  (base.empty() || base[0] != '/') ? base : base.substr(1), tips, search_res))
          {
            RCLCPP_ERROR(LOGGER, "Kinematics solver of type '%s' could not be initialized for group '%s'",
                         it->second[i].c_str(), jmg->getName().c_str());
            result.reset();
            continue;
          }

          result->setDefaultTimeout(jmg->getDefaultIKTimeout());
          RCLCPP_DEBUG(LOGGER, "Successfully allocated and initialized a kinematics solver of type '%s' with search "
                               "resolution %lf for group '%s' at address %p",
                       it->second[i].c_str(), search_res, jmg->getName().c_str(), result.get());
          break;
        }
      }
      catch (pluginlib::PluginlibException& e)
      {
        RCLCPP_ERROR(LOGGER, "The kinematics plugin (%s) failed to load. Error: %s", it->first.c_str(), e.what());
      }
    }

    if (!result)
    {
      RCLCPP_DEBUG(LOGGER, "No usable kinematics solver was found for this group.\n"
                           "Did you load kinematics.yaml into your node's namespace?");
    }
    return result;
  }

  // cache solver between two consecutive calls
  // first call in RobotModelLoader::loadKinematicsSolvers() is just to check suitability for jmg
  // second call in JointModelGroup::setSolverAllocators() is to actually retrieve the instance for use
  kinematics::KinematicsBasePtr allocKinematicsSolverWithCache(const robot_model::JointModelGroup* jmg)
  {
    boost::mutex::scoped_lock slock(cache_lock_);
    kinematics::KinematicsBasePtr& cached = instances_[jmg];
    if (cached.unique())
      return std::move(cached);  // pass on unique instance

    // create a new instance and store in instances_
    cached = allocKinematicsSolver(jmg);
    return cached;
  }

  void status() const
  {
    for (std::map<std::string, std::vector<std::string>>::const_iterator it = possible_kinematics_solvers_.begin();
         it != possible_kinematics_solvers_.end(); ++it)
    {
      for (std::size_t i = 0; i < it->second.size(); ++i)
      {
        RCLCPP_INFO(LOGGER, "Solver for group '%s': '%s' (search resolution = %lf)", it->first.c_str(),
                    it->second[i].c_str(), search_res_.at(it->first)[i]);
      }
    }
  }

private:
  const rclcpp::Node::SharedPtr node_;
  std::string robot_description_;
  std::map<std::string, std::vector<std::string>> possible_kinematics_solvers_;
  std::map<std::string, std::vector<double>> search_res_;
  std::map<std::string, std::vector<std::string>> iksolver_to_tip_links_;  // a map between each ik solver and a vector
                                                                           // of custom-specified tip link(s)
  std::shared_ptr<pluginlib::ClassLoader<kinematics::KinematicsBase>> kinematics_loader_;
  std::map<const robot_model::JointModelGroup*, kinematics::KinematicsBasePtr> instances_;
  boost::mutex lock_;
  boost::mutex cache_lock_;
};

void KinematicsPluginLoader::status() const
{
  if (loader_)
    loader_->status();
  else
    RCLCPP_INFO(LOGGER, "Loader function was never required");
}

robot_model::SolverAllocatorFn KinematicsPluginLoader::getLoaderFunction()
{
  moveit::tools::Profiler::ScopedStart prof_start;
  moveit::tools::Profiler::ScopedBlock prof_block("KinematicsPluginLoader::getLoaderFunction");

  if (loader_)
    return boost::bind(&KinematicsLoaderImpl::allocKinematicsSolverWithCache, loader_.get(), _1);

  rdf_loader::RDFLoader rml(node_, robot_description_);
  robot_description_ = rml.getRobotDescription();
  return getLoaderFunction(rml.getSRDF());
}

robot_model::SolverAllocatorFn KinematicsPluginLoader::getLoaderFunction(const srdf::ModelSharedPtr& srdf_model)
{
  moveit::tools::Profiler::ScopedStart prof_start;
  moveit::tools::Profiler::ScopedBlock prof_block("KinematicsPluginLoader::getLoaderFunction(SRDF)");

  if (!loader_)
  {
    RCLCPP_DEBUG(LOGGER, "Configuring kinematics solvers");
    groups_.clear();

    std::map<std::string, std::vector<std::string>> possible_kinematics_solvers;
    std::map<std::string, std::vector<double>> search_res;
    std::map<std::string, std::vector<std::string>> iksolver_to_tip_links;

    if (srdf_model)
    {
      const std::vector<srdf::Model::Group>& known_groups = srdf_model->getGroups();
      if (default_search_resolution_ <= std::numeric_limits<double>::epsilon())
        default_search_resolution_ = kinematics::KinematicsBase::DEFAULT_SEARCH_DISCRETIZATION;

      if (default_solver_plugin_.empty())
      {
        RCLCPP_DEBUG(LOGGER, "Loading settings for kinematics solvers from the ROS param server ...");

        // TODO(JafarAbdi): revise parameter lookup
        // read the list of plugin names for possible kinematics solvers
        for (const srdf::Model::Group& known_group : known_groups)
        {
          std::string base_param_name = known_group.name_;
          std::string ksolver_param_name = base_param_name + ".kinematics_solver";
          RCLCPP_DEBUG(LOGGER, "Looking for param %s ", ksolver_param_name.c_str());
          bool found = node_->has_parameter(ksolver_param_name);
          if (!found)
          {
            base_param_name = robot_description_ + "_kinematics." + known_group.name_;
            ksolver_param_name = base_param_name + ".kinematics_solver";
            RCLCPP_DEBUG(LOGGER, "Looking for param %s ", ksolver_param_name.c_str());
            found = node_->has_parameter(ksolver_param_name);
          }
          if (found)
          {
            RCLCPP_DEBUG(LOGGER, "Found param %s", ksolver_param_name.c_str());

            std::string ksolver = node_->get_parameter(ksolver_param_name).as_string();
            std::stringstream ss(ksolver);
            bool first = true;
            while (ss.good() && !ss.eof())
            {
              if (first)
              {
                first = false;
                groups_.push_back(known_group.name_);
              }
              std::string solver;
              ss >> solver >> std::ws;
              possible_kinematics_solvers[known_group.name_].push_back(solver);
              RCLCPP_DEBUG(LOGGER, "Using kinematics solver '%s' for group '%s'.", solver.c_str(),
                           known_group.name_.c_str());
            }
          }

          std::string ksolver_timeout_param_name = base_param_name + "/kinematics_solver_timeout";
          if (node_->has_parameter(ksolver_timeout_param_name))
          {
            double ksolver_timeout;
            rclcpp::Parameter parameter = node_->get_parameter(ksolver_timeout_param_name);
            if (parameter.get_type() == rclcpp::ParameterType::PARAMETER_DOUBLE)
            {
              ksolver_timeout = node_->get_parameter(ksolver_timeout_param_name).as_double();
              ik_timeout_[known_group.name_] = ksolver_timeout;
            }
            else if (parameter.get_type() == rclcpp::ParameterType::PARAMETER_INTEGER)
            {  // just in case this is an int
              ksolver_timeout = node_->get_parameter(ksolver_timeout_param_name).as_int();
              ik_timeout_[known_group.name_] = ksolver_timeout;
            }
          }

          std::string ksolver_res_param_name = base_param_name + "/kinematics_solver_search_resolution";
          if (node_->has_parameter(ksolver_res_param_name))
          {
            rclcpp::Parameter ksolver_res_param = node_->get_parameter(ksolver_res_param_name);
            if (ksolver_res_param.get_type() == rclcpp::ParameterType::PARAMETER_STRING)
            {
              std::string ksolver_res = ksolver_res_param.as_string();
              std::stringstream ss(ksolver_res);
              while (ss.good() && !ss.eof())
              {
                double res;
                ss >> res >> std::ws;
                search_res[known_group.name_].push_back(res);
              }
            }
            // handle the case this param is just one value and parsed as a double
            else if (ksolver_res_param.get_type() == rclcpp::ParameterType::PARAMETER_DOUBLE)
            {
              double res = node_->get_parameter(ksolver_res_param_name).as_double();
              search_res[known_group.name_].push_back(res);
            }
            else if (ksolver_res_param.get_type() == rclcpp::ParameterType::PARAMETER_INTEGER)
            {
              int res = node_->get_parameter(ksolver_res_param_name).as_int();
              search_res[known_group.name_].push_back(res);
            }
          }

          // Allow a kinematic solver's tip links to be specified on the rosparam server as an array
          std::string ksolver_ik_links_param_name = base_param_name + "/kinematics_solver_ik_links";
          if (node_->has_parameter(ksolver_ik_links_param_name))
          {
            rclcpp::Parameter ksolver_ik_links_param = node_->get_parameter(ksolver_ik_links_param_name);
            if (ksolver_ik_links_param.get_type() == rclcpp::ParameterType::PARAMETER_STRING_ARRAY)
            {
              std::vector<std::string> ksolver_ik_links = ksolver_ik_links_param.as_string_array();
              for (size_t j = 0; j < ksolver_ik_links.size(); ++j)
              {
                RCLCPP_DEBUG(LOGGER, "found tip %s for group %s", ksolver_ik_links[j].c_str(),
                             known_group.name_.c_str());
                iksolver_to_tip_links[known_group.name_].push_back(ksolver_ik_links[j]);
              }
            }
            else
            {
              RCLCPP_WARN(LOGGER, "the parameter '%s' needs to be of type 'STRING_ARRAY'",
                          ksolver_ik_links_param_name.c_str());
            }
          }

          // make sure there is a default resolution at least specified for every solver (in case it was not specified
          // on the param server)
          while (search_res[known_group.name_].size() < possible_kinematics_solvers[known_group.name_].size())
            search_res[known_group.name_].push_back(default_search_resolution_);
        }
      }
      else
      {
        RCLCPP_DEBUG(LOGGER, "Using specified default settings for kinematics solvers ...");
        for (const srdf::Model::Group& known_group : known_groups)
        {
          possible_kinematics_solvers[known_group.name_].resize(1, default_solver_plugin_);
          search_res[known_group.name_].resize(1, default_search_resolution_);
          ik_timeout_[known_group.name_] = default_solver_timeout_;
          groups_.push_back(known_group.name_);
        }
      }
    }

    loader_.reset(new KinematicsLoaderImpl(node_, robot_description_, possible_kinematics_solvers, search_res,
                                           iksolver_to_tip_links));
  }

  return boost::bind(&KinematicsPluginLoader::KinematicsLoaderImpl::allocKinematicsSolverWithCache, loader_.get(), _1);
}
}  // namespace kinematics_plugin_loader


text:
#pragma once

#include <map>
#include <ostream>
#include <boost/test/unit_test.hpp>

#include "api/Packet.hh"
#include "oxm/field_set.hh"
#include "maple/Backend.hh"
#include "maple/Flow.hh"

namespace runos {

class MockSwitch : public maple::Backend {
    using Flow = maple::Flow;
    using FlowPtr = maple::FlowPtr;

    struct Classifier {
        unsigned prio;
        oxm::field_set match;

        friend bool operator== (const Classifier& lhs, const Classifier& rhs)
        { return lhs.prio == rhs.prio && lhs.match == rhs.match; }

        friend bool operator< (const Classifier& lhs, const Classifier& rhs)
        { return lhs.prio > rhs.prio; }

        friend std::ostream& operator<< (std::ostream& out, const Classifier& c)
        { return out << "prio=" << c.prio << ", " << c.match; }
    };

    typedef std::map< Classifier, FlowPtr >
        FlowTable;

    FlowPtr miss;
    FlowTable flow_table;

public:
    explicit MockSwitch(FlowPtr miss)
        : miss(miss)
    { }

    virtual void install(unsigned priority,
                         oxm::field_set const& fs,
                         FlowPtr flow) override
    {
        Classifier classifier {priority, fs};
        BOOST_TEST_MESSAGE("Installing flow " << classifier);
        BOOST_REQUIRE_MESSAGE(flow_table.emplace(classifier, flow).second,
                              "Overlapping flow " << classifier);
    }

    virtual void remove(FlowPtr flow) override
    {
        BOOST_TEST_MESSAGE("Removing flow " << flow);
        for (auto it = flow_table.begin(); it != flow_table.end(); ++it) {
            if (it->second == flow)
                flow_table.erase(it);
        }
    }

    virtual void remove(unsigned priority,
                        oxm::field_set const& match) override
    {
        Classifier key{ priority, std::move(match) };
        BOOST_TEST_MESSAGE("Removing flow " << key);
        for (auto it = flow_table.begin(); it != flow_table.end(); ++it) {
            if (it->first == key)
                flow_table.erase(it);
        }
    }

    virtual void remove(oxm::field_set const& match) override
    {
        BOOST_TEST_MESSAGE("Removing flow " << match);
        for (auto it = flow_table.begin(); it != flow_table.end(); ++it) {
            if (it->first.match == match)
                flow_table.erase(it);
        }
    }

    FlowPtr operator()(const Packet& pkt) const
    {
        auto it = flow_table.cbegin();
        auto match = flow_table.cend();

        for (; it != flow_table.cend(); ++it) {
            if (it->first.match & pkt) {
                match = it;
                break;
            }
        }

        if (it != flow_table.cend())
            ++it;

        for (; it != flow_table.cend() &&
               it->first.prio == match->first.prio;
               ++it)
        {
            BOOST_REQUIRE( not (it->first.match & pkt) );
        }

        if (match != flow_table.cend())
            return match->second;
        else
            return miss;
    }
};

}

ext: hh

max_stars_repo_name: Alexey-Ershov/runos

max_issues_repo_name: Alexey-Ershov/runos

max_forks_repo_name: Alexey-Ershov/runos