text:
/***********************************************************************

Copyright (c) 2014, Carnegie Mellon University
All rights reserved.

Authors: Jennifer King <jeking04@gmail.com>

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.

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
HOLDER 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.

*************************************************************************/

#include <vector>
#include <Eigen/Geometry>
#include <ompl/util/RandomNumbers.h>
#include <or_ompl/TSR.h>

using namespace or_ompl;

TSR::TSR()
    : _initialized(false)
{
}

TSR::TSR(
        const Eigen::Affine3d &T0_w,
        const Eigen::Affine3d &Tw_e,
        const Eigen::Matrix<double, 6, 2> &Bw)
    : _T0_w(T0_w)
    , _Tw_e(Tw_e)
    , _Bw(Bw)
    , _manipulator_index(-1)
    , _relative_body_name("NULL")
    , _relative_link_name("")
    , _initialized(true)
{
    _T0_w_inv = _T0_w.inverse();
    _Tw_e_inv = _Tw_e.inverse();
}

bool TSR::deserialize(std::stringstream &ss)
{
    return deserialize(static_cast<std::istream &>(ss));
}

bool TSR::deserialize(std::istream &ss)
{
    // Set _initialized to false in case an error occurs.
    _initialized = false;

    ss >> _manipulator_index
       >> _relative_body_name;

    if(_relative_body_name != "NULL")
        ss >> _relative_link_name;

    // Read in the T0_w matrix
    for(unsigned int c=0; c < 3; c++)
    for(unsigned int r=0; r < 3; r++)
        ss >> _T0_w.matrix()(r,c);

    for(unsigned int idx=0; idx < 3; idx++)
        ss >> _T0_w.translation()(idx);

    // Read in the Tw_e matrix
    for(unsigned int c=0; c < 3; c++)
    for(unsigned int r=0; r < 3; r++)
        ss >> _Tw_e.matrix()(r,c);

    for(unsigned int idx=0; idx < 3; idx++)
        ss >> _Tw_e.translation()(idx);

    // Read in the Bw matrix
    for(unsigned int r=0; r < 6; r++)
    for(unsigned int c=0; c < 2; c++)
        ss >> _Bw(r,c);

    // Check for an error.
    if (!ss)
        return false;

    _T0_w_inv = _T0_w.inverse();
    _Tw_e_inv = _Tw_e.inverse();
    _initialized = true;

    return true;
}

void TSR::serialize(std::ostream& ss)
{
    if (!_initialized)
        throw std::runtime_error("TSR is not initialized.");

    ss << _manipulator_index
       << ' ' << _relative_body_name;

    if(_relative_body_name != "NULL")
        ss << ' ' << _relative_link_name;

    // T0_w matrix
    for(unsigned int c=0; c < 3; c++)
    for(unsigned int r=0; r < 3; r++)
        ss << ' ' << _T0_w.matrix()(r, c);

    for(unsigned int idx=0; idx < 3; idx++)
        ss << ' ' << _T0_w.translation()(idx);

    // Tw_e matrix
    for(unsigned int c=0; c < 3; c++)
    for(unsigned int r=0; r < 3; r++)
        ss << ' ' << _Tw_e.matrix()(r, c);

    for(unsigned int idx=0; idx < 3; idx++)
        ss << ' ' << _Tw_e.translation()(idx);

    // Read in the Bw matrix
    for(unsigned int r=0; r < 6; r++)
    for(unsigned int c=0; c < 2; c++)
        ss << ' ' << _Bw(r, c);
}

Eigen::Matrix<double, 6, 1> TSR::distance(const Eigen::Affine3d &ee_pose) const {
    Eigen::Matrix<double, 6, 1> dist = Eigen::Matrix<double, 6, 1>::Zero();

    // First compute the pose of the w frame in world coordinates, given the ee_pose
    Eigen::Affine3d w_in_world = ee_pose * _Tw_e_inv;

    // Next compute the pose of the w frame relative to its original pose (as specified by T0_w)
    Eigen::Affine3d w_offset = _T0_w_inv * w_in_world;

    // Now compute the elements of the distance matrix
    dist(0,0) = w_offset.translation()(0);
    dist(1,0) = w_offset.translation()(1);
    dist(2,0) = w_offset.translation()(2);
    dist(3,0) = atan2(w_offset.rotation()(2,1), w_offset.rotation()(2,2));
    dist(4,0) = -asin(w_offset.rotation()(2,0));
    dist(5,0) = atan2(w_offset.rotation()(1,0), w_offset.rotation()(0,0));

    return dist;
}

Eigen::Matrix<double, 6, 1> TSR::displacement(const Eigen::Affine3d &ee_pose) const {

    Eigen::Matrix<double, 6, 1> dist = distance(ee_pose);
    Eigen::Matrix<double, 6, 1> disp = Eigen::Matrix<double, 6, 1>::Zero();

    for(unsigned int idx=0; idx < 6; idx++){
        if(dist(idx,0) < _Bw(idx,0)){
            disp(idx,0) = dist(idx,0) - _Bw(idx,0);
        }else if(dist(idx,0) > _Bw(idx,1)){
            disp(idx,0) = dist(idx,0) - _Bw(idx,1);
        }
    }

    return disp;
}

Eigen::Affine3d TSR::sampleDisplacementTransform(void) const {

    // First sample uniformly betwee each of the bounds of Bw
    std::vector<double> d_sample(6);

    ompl::RNG rng;
    for(unsigned int idx=0; idx < d_sample.size(); idx++){
        if(_Bw(idx,1) > _Bw(idx,0)){
            d_sample[idx] = rng.uniformReal(_Bw(idx,0), _Bw(idx,1));
        }
    }

    Eigen::Affine3d return_tf;
    return_tf.translation() << d_sample[0], d_sample[1], d_sample[2];

    // Convert to a transform matrix
    double roll = d_sample[3];
    double pitch = d_sample[4];
    double yaw = d_sample[5];

    double A = cos(yaw);
    double B = sin(yaw);
    double C = cos(pitch);
    double D = sin(pitch);
    double E = cos(roll);
    double F = sin(roll);
    return_tf.linear() << A*C, A*D*F - B*E, B*F + A*D*E,
        B*C, A*E + B*D*F, B*D*E - A*F,
        -D, C*F, C*E;

    return return_tf;
}

Eigen::Affine3d TSR::sample() const {

    Eigen::Affine3d tf = sampleDisplacementTransform();

    return _T0_w * tf * _Tw_e;
}

ext: cpp


text:
#include "winbox_session.hpp"

#include "winbox_message.hpp"
#include "md5.hpp"

#include <iostream>
#include <iomanip>
#include <cstring>
#include <stdexcept>
#include <boost/lambda/bind.hpp>
#include <boost/lambda/lambda.hpp>

namespace
{
    /*!
     * Validates the first four bytes of the header. The first byte is the size of this chunk. The
     * second byte indicates if there are more packets in this series. The third and fourth bytes
     * are the total length.
     *
     * \return 0 if failure and the length we need to read otherwise
     */
    boost::uint32_t parse_header(const std::string& p_header)
    {
        if (p_header.size() != 4)
        {
            return 0;
        }

        boost::uint8_t short_length = p_header[0];
        boost::uint16_t long_length = ntohs(*reinterpret_cast<const boost::uint16_t*>(&p_header[2]));

        if (short_length == 0xff)
        {
            return long_length;
        }

        if ((short_length - 2) != long_length)
        {
            std::cerr <<  std::hex << "Length mismatch. " << (short_length -2) << " != " << long_length << std::endl;
            return 0;
        }

        return long_length;
    }
}

Winbox_Session::Winbox_Session(const std::string& p_ip, const std::string& p_port) :
    Session(p_ip, p_port),
    m_io_service(),
    m_socket(m_io_service),
    m_deadline(m_io_service)
{
    m_deadline.expires_at(boost::posix_time::pos_infin);
    check_deadline();
}

Winbox_Session::~Winbox_Session()
{
    try
    {
        m_socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both);
        m_socket.close();
    }
    catch (...)
    {
    }
}

bool Winbox_Session::connect()
{
    try
    {
        boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string(m_ip), atoi(m_port.c_str()));

        // set a 2 second deadline for the connection
        boost::system::error_code ec = boost::asio::error::would_block;
        m_deadline.expires_from_now(boost::posix_time::seconds(2));
        m_socket.async_connect(endpoint, boost::lambda::var(ec) = boost::lambda::_1);

        do
        {
            m_io_service.run_one();
        }
        while (ec == boost::asio::error::would_block);

        if (ec || !m_socket.is_open())
        {
           return false;
        }
    }
    catch(const std::exception& e)
    {
        return false;
    }
    return true;
}

bool Winbox_Session::login(const std::string& p_username, const std::string& p_password, boost::uint32_t& p_session_id)
{
    WinboxMessage msg;

    // request the challenge
    msg.set_to(13, 4);
    msg.set_command(4);
    msg.set_request_id(2);
    msg.set_session_id(p_session_id);
    msg.set_reply_expected(true);
    if (!send(msg))
    {
        return false;
    }

    msg.reset();
    if (!receive(msg) || msg.has_error())
    {
        std::cerr << msg.get_error_string() << std::endl;
        return false;
    }

    std::string salt(msg.get_raw(0x9));
    if (salt.size() != 16)
    {
        msg.reset();
        if (!receive(msg) || msg.has_error())
        {
            std::cerr << msg.get_error_string() << std::endl;
            return false;
        }
        salt.assign(msg.get_raw(0x9));
    }

    // generate the challenge response
    std::string one;
    one.push_back(0);

    MD5 md5;
    md5.update(one.data(), one.length());
    md5.update(p_password.data(), p_password.length());
    md5.update(salt.data(), salt.length());
    md5.finalize();

    std::string hashed(md5.getDigest());
    hashed.insert(0, "\x0", 1);

    msg.reset();
    msg.set_to(13, 4);
    msg.set_command(1);
    msg.set_request_id(3);
    msg.set_session_id(p_session_id);
    msg.set_reply_expected(true);
    msg.add_string(1, p_username);
    msg.add_raw(9, salt);
    msg.add_raw(10, hashed);
    if (!send(msg))
    {
        return false;
    }

    msg.reset();
    if (!receive(msg))
    {
        std::cerr << "Error receiving a response." << std::endl;
        return false;
    }

    if (msg.has_error())
    {
        std::cerr << msg.get_error_string() << std::endl;
        return false;
    }

    p_session_id = msg.get_session_id();

    return true;
}

bool Winbox_Session::send(const WinboxMessage& p_msg)
{
    std::string serialized(p_msg.serialize_to_binary());

    // each message starts with M2 (message format 2) identifier
    std::string message("M2");
    message.append(serialized.data(), serialized.size());

    if (message.length() > 0xffff)
    {
        std::cerr << "Winbox message oversized" << std::endl;
        return false;
    }

    boost::uint8_t msg_size[] =
    {
        static_cast<boost::uint8_t>(message.length() >> 8),     // 0: upper byte
        static_cast<boost::uint8_t>(message.length() & 0xff)    // 1: lower byte
    };

    boost::asio::streambuf request;
    std::ostream request_stream(&request);

    if (message.length() < 0xfe)
    {
        request_stream << static_cast<boost::uint8_t>(msg_size[1] + 2);
        request_stream << '\x01';
        request_stream << msg_size[0] << msg_size[1];
        request_stream << message;
    }
    else
    {
        request_stream << '\xff' << '\x01';
        request_stream << msg_size[0] << msg_size[1];
        request_stream << message.substr(0, 0xfd);              // 0xff-2, because we write 2 bytes above
        for(size_t i = 0xfd; i < message.length(); i+=0xff)
        {
            boost::uint8_t remain;
            if (message.length() - i > 0xff) remain = 0xff;
            else remain = message.length() - i;
            request_stream << remain << '\xff';
            request_stream << message.substr(i, 0xff);
        }
    }

    try
    {
        // convert to async with timer
        boost::asio::write(m_socket, request);
    }
    catch(const std::exception&)
    {
        return false;
    }

    return true;
}

bool Winbox_Session::receive(WinboxMessage& p_msg)
{
    boost::system::error_code ec = boost::asio::error::would_block;
    m_deadline.expires_from_now(boost::posix_time::seconds(2));

    // read in the the header
    boost::asio::streambuf response;
    boost::asio::async_read(m_socket, response, boost::asio::transfer_exactly(4), boost::lambda::var(ec) = boost::lambda::_1);
    do
    {
        m_io_service.run_one();
    }
    while (ec == boost::asio::error::would_block);

    if (ec)
    {
        return false;
    }

    std::string header;
    header.assign(std::istreambuf_iterator<char>(&response), std::istreambuf_iterator<char>());
    response.consume(4);

    // parse the header
    boost::uint32_t to_read = parse_header(header);
    if (to_read == 0)
    {
        //std::cerr << "Failed header parsing" << std::endl;
        return false;
    }

    std::string message;
    for (int i = 0; to_read > 0xff; i++)
    {
        boost::uint32_t step = 0xff;
        if (i == 0)
        {
            // in the first iteration we already read in the first 3 bytes
            step = 0x100 - 3;
        }

        boost::asio::read(m_socket, response, boost::asio::transfer_exactly(step));
        message.append(std::istreambuf_iterator<char>(&response), std::istreambuf_iterator<char>());
        response.consume(step);
        to_read -= step;

        // should be two bytes of 0xff here
        std::string step_chars;
        boost::asio::read(m_socket, response, boost::asio::transfer_exactly(2));
        step_chars.assign(std::istreambuf_iterator<char>(&response), std::istreambuf_iterator<char>());
        response.consume(2);

        // ensure pad bytes are there
        if (static_cast<unsigned char>(step_chars[1]) != 0xff)
        {
            //std::cerr << "Padding error." << std::endl;
            return false;
        }
    }

    // read the last bit of data
    boost::asio::read(m_socket, response, boost::asio::transfer_exactly(to_read));
    message.append(std::istreambuf_iterator<char>(&response), std::istreambuf_iterator<char>());
    response.consume(to_read);

    // remove the M2 header and load into a message obj
    message.erase(0, 2);
    p_msg.parse_binary(message);

    return true;
}

void Winbox_Session::check_deadline()
{
    if (m_deadline.expires_at() <= boost::asio::deadline_timer::traits_type::now())
    {
      boost::system::error_code ignored_ec;
      m_socket.close(ignored_ec);
      m_deadline.expires_at(boost::posix_time::pos_infin);
    }

    // Put the actor back to sleep.
    m_deadline.async_wait(boost::lambda::bind(&Winbox_Session::check_deadline, this));
}

max_stars_repo_name: fengjixuchui/routeros

max_issues_repo_name: fengjixuchui/routeros

max_forks_repo_name: fengjixuchui/routeros


text:
/**
 * SPDX-FileCopyrightText: 2020-2021 EasyCoding Team and contributors
 *
 * SPDX-License-Identifier: MIT
*/

#include <iostream>
#include <fstream>
#include <memory>
#include <stdexcept>

#ifndef FILESYSTEM_LEGACY
#include <filesystem>
namespace fs = std::filesystem;
#else
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
#endif

#include <boost/program_options.hpp>
#include <fmt/format.h>

#include "application/application.hpp"
#include "cwrappers/cwrappers.hpp"
#include "zswapobject/zswapobject.hpp"
#include "zswapdebug/zswapdebug.hpp"
#include "ksysinfo/ksysinfo.hpp"

void Application::PrintDebugInfo()
{
    std::unique_ptr<ZSwapDebug> ZSwapDebugger = std::make_unique<ZSwapDebug>();
    std::cout << fmt::format("Duplicate entries count: {0}.\n"
                             "Pool limit hit: {1}.\n"
                             "Pool total size: {2}.\n"
                             "Reject allocation failures: {3}.\n"
                             "Reject compression poor: {4}.\n"
                             "Reject Kmemcache failures: {5}.\n"
                             "Reject reclaim failures: {6}.\n"
                             "Same filled pages count: {7}.\n"
                             "Stored pages count: {8}.\n"
                             "Written back pages count: {9}.",
                             ZSwapDebugger -> GetDuplicateEntry(),
                             ZSwapDebugger -> GetPoolLimitHit(),
                             ZSwapDebugger -> GetPoolTotalSize(),
                             ZSwapDebugger -> GetRejectAllocFail(),
                             ZSwapDebugger -> GetRejectCompressPoor(),
                             ZSwapDebugger -> GetRejectKmemCacheFail(),
                             ZSwapDebugger -> GetRejectReclaimFail(),
                             ZSwapDebugger -> GetSameFilledPages(),
                             ZSwapDebugger -> GetSameFilledPages(),
                             ZSwapDebugger -> GetStoredPages(),
                             ZSwapDebugger -> GetWrittenBackPages())
              << std::endl;
}

void Application::PrintSettings()
{
    std::cout << fmt::format("ZSwap enabled: {0}.\n"
                             "Same filled pages enabled: {1}.\n"
                             "Maximum pool percentage: {2}.\n"
                             "Compression algorithm: {3}.\n"
                             "Kernel's zpool type: {4}.\n"
                             "Accept threshold percentage: {5}.",
                             ZSwap -> GetZSwapEnabled(),
                             ZSwap -> GetZSwapSameFilledPages(),
                             ZSwap -> GetZSwapMaxPoolPercent(),
                             ZSwap -> GetZSwapCompressor(),
                             ZSwap -> GetZSwapZpool(),
                             ZSwap -> GetZSwapAcceptThresholdPercent())
              << std::endl;
}

void Application::PrintSummary()
{
    std::unique_ptr<ZSwapDebug> ZSwapDebugger = std::make_unique<ZSwapDebug>();
    std::unique_ptr<KSysInfo> SysInfo = std::make_unique<KSysInfo>();

    if (ZSwapDebugger -> GetPoolTotalSize() == 0)
    {
        std::cout << "ZSwap is not working. The pool is empty." << std::endl;
        return;
    }

    constexpr const long Power = 1024 << 10;
    const float PoolSizeMB = static_cast<float>(ZSwapDebugger -> GetPoolTotalSize()) / Power;
    const float MemTotalPercent = static_cast<float>(ZSwapDebugger -> GetPoolTotalSize()) / static_cast<float>(SysInfo -> GetTotalRam()) * 100.f;
    const float StoredPagesMB = static_cast<float>(ZSwapDebugger -> GetStoredPages() * CWrappers::GetSCPageSize()) / Power;
    const float SwapUsedPercent = static_cast<float>(ZSwapDebugger -> GetStoredPages() * CWrappers::GetSCPageSize()) / static_cast<float>(SysInfo -> GetTotalSwap() - SysInfo -> GetFreeSwap()) * 100.f;
    const float CompressionRatio = StoredPagesMB / PoolSizeMB;

    std::cout << fmt::format("Pool: {0:.2f} MiB ({1:.1f}% of MemTotal).\n"
                             "Stored: {2:.2f} MiB ({3:.1f}% of SwapUsed).\n"
                             "Compression ratio: {4:.2f}.",
                             PoolSizeMB,
                             MemTotalPercent,
                             StoredPagesMB,
                             SwapUsedPercent,
                             CompressionRatio)
              << std::endl;
}

void Application::PrintCombined()
{
    std::cout << "ZSWAP KERNEL MODULE SETTINGS:" << std::endl;
    PrintSettings();
    std::cout << std::endl;
    std::cout << "ZSWAP KERNEL MODULE USAGE SUMMARY:" << std::endl;
    PrintSummary();
    std::cout << std::endl;
    std::cout << "ZSWAP KERNEL MODULE DEBUG INFO:" << std::endl;
    PrintDebugInfo();
}

int Application::PrintStats(const int Value)
{
    switch (Value)
    {
        case 0:
            PrintCombined();
            break;
        case 1:
            PrintSettings();
            break;
        case 2:
            PrintSummary();
            break;
        case 3:
            PrintDebugInfo();
            break;
        default:
            throw std::invalid_argument("Incorrect value of --stats command-line option was specified.");
    }
    return 0;
}

int Application::PrintHelp()
{
    CmdLineOptions -> print(std::cout);
    return 0;
}

int Application::ExecuteEnv()
{
    const std::string ZSwapEnabledEnv = CWrappers::GetEnv("ZSWAP_ENABLED_VALUE");
    const std::string ZSwapSameFilledPagesEnv = CWrappers::GetEnv("ZSWAP_SAME_FILLED_PAGES_ENABLED_VALUE");
    const std::string ZSwapMaxPoolPercentEnv = CWrappers::GetEnv("ZSWAP_MAX_POOL_PERCENT_VALUE");
    const std::string ZSwapCompressorEnv = CWrappers::GetEnv("ZSWAP_COMPRESSOR_VALUE");
    const std::string ZSwapZpoolEnv = CWrappers::GetEnv("ZSWAP_ZPOOL_VALUE");
    const std::string ZSwapAcceptThresholdPercentEnv = CWrappers::GetEnv("ZSWAP_ACCEPT_THRESHOLD_PERCENT_VALUE");

    if (!ZSwapEnabledEnv.empty()) ZSwap -> SetZSwapEnabled(ZSwapEnabledEnv);
    if (!ZSwapSameFilledPagesEnv.empty()) ZSwap -> SetZSwapSameFilledPages(ZSwapSameFilledPagesEnv);
    if (!ZSwapMaxPoolPercentEnv.empty()) ZSwap -> SetZSwapMaxPoolPercent(ZSwapMaxPoolPercentEnv);
    if (!ZSwapCompressorEnv.empty()) ZSwap -> SetZSwapCompressor(ZSwapCompressorEnv);
    if (!ZSwapZpoolEnv.empty()) ZSwap -> SetZSwapZpool(ZSwapZpoolEnv);
    if (!ZSwapAcceptThresholdPercentEnv.empty()) ZSwap -> SetZSwapAcceptThresholdPercent(ZSwapAcceptThresholdPercentEnv);
    return 0;
}

int Application::ExecuteConfig(const std::string& ConfigFile)
{
    std::unique_ptr<boost::program_options::variables_map> Config = std::make_unique<boost::program_options::variables_map>();
    std::unique_ptr<boost::program_options::options_description> ConfigOptions = std::make_unique<boost::program_options::options_description>("Configuration file options.");
    ConfigOptions -> add_options()
        ("zswap.enabled", boost::program_options::value<std::string>(), "Enable or disable ZSwap kernel module.")
        ("zswap.same_filled_pages_enabled", boost::program_options::value<std::string>(), "Enable or disable memory pages deduplication.")
        ("zswap.max_pool_percent", boost::program_options::value<std::string>(), "The maximum percentage of memory that the compressed pool can occupy.")
        ("zswap.compressor", boost::program_options::value<std::string>(), "The default compression algorithm.")
        ("zswap.zpool", boost::program_options::value<std::string>(), "The kernel's zpool type.")
        ("zswap.accept_threshold_percent", boost::program_options::value<std::string>(), "The threshold at which ZSwap would start accepting pages again after it became full.")
        ;

    if (!fs::exists(ConfigFile)) throw std::invalid_argument("Configuration file does not exist!");
    std::ifstream ConfigFileFs(ConfigFile);
    boost::program_options::store(boost::program_options::parse_config_file(ConfigFileFs, *ConfigOptions), *Config);
    Config -> notify();
    ConfigFileFs.close();

    if (Config -> count("zswap.enabled")) ZSwap -> SetZSwapEnabled(Config -> at("zswap.enabled").as<std::string>());
    if (Config -> count("zswap.same_filled_pages_enabled")) ZSwap -> SetZSwapSameFilledPages(Config -> at("zswap.same_filled_pages_enabled").as<std::string>());
    if (Config -> count("zswap.max_pool_percent")) ZSwap -> SetZSwapMaxPoolPercent(Config -> at("zswap.max_pool_percent").as<std::string>());
    if (Config -> count("zswap.compressor")) ZSwap -> SetZSwapCompressor(Config -> at("zswap.compressor").as<std::string>());
    if (Config -> count("zswap.zpool")) ZSwap -> SetZSwapZpool(Config -> at("zswap.zpool").as<std::string>());
    if (Config -> count("zswap.accept_threshold_percent")) ZSwap -> SetZSwapAcceptThresholdPercent(Config -> at("zswap.accept_threshold_percent").as<std::string>());
    return 0;
}

int Application::ExecuteCmdLine()
{
    if (CmdLine -> count("enabled")) ZSwap -> SetZSwapEnabled(CmdLine -> at("enabled").as<std::string>());
    if (CmdLine -> count("same_filled_pages_enabled")) ZSwap -> SetZSwapSameFilledPages(CmdLine -> at("same_filled_pages_enabled").as<std::string>());
    if (CmdLine -> count("max_pool_percent")) ZSwap -> SetZSwapMaxPoolPercent(CmdLine -> at("max_pool_percent").as<std::string>());
    if (CmdLine -> count("compressor")) ZSwap -> SetZSwapCompressor(CmdLine -> at("compressor").as<std::string>());
    if (CmdLine -> count("zpool")) ZSwap -> SetZSwapZpool(CmdLine -> at("zpool").as<std::string>());
    if (CmdLine -> count("accept_threshold_percent")) ZSwap -> SetZSwapAcceptThresholdPercent(CmdLine -> at("accept_threshold_percent").as<std::string>());
    return 0;
}

int Application::Run()
{
    if (CmdLine -> empty() || CmdLine -> count("help")) return PrintHelp();
    if (CmdLine -> count("stats")) return PrintStats(CmdLine -> at("stats").as<int>());
    if (CmdLine -> count("config")) return ExecuteConfig(CmdLine -> at("config").as<std::string>());
    if (CmdLine -> count("env")) return ExecuteEnv();
    return ExecuteCmdLine();
}

void Application::CheckIfRunningBySuperUser()
{
    if (CWrappers::CheckRoot())
    {
        throw std::runtime_error("This program must be run by the super-user. Terminating.");
    }
}

void Application::InitClassMembers()
{
    CmdLineOptions = std::make_unique<boost::program_options::options_description>("Command-line tool to control ZSwap Linux kernel module");
    CmdLine = std::make_unique<boost::program_options::variables_map>();
    ZSwap = std::make_unique<ZSwapObject>();
}

void Application::InitCmdLineOptions()
{
    CmdLineOptions -> add_options()
        ("help", "Print this help message and exit.")
        ("config", boost::program_options::value<std::string>(), "Get options from the configuration file instead of the cmdline.")
        ("env", "Get options from the environment variables instead of the cmdline.")
        ("stats", boost::program_options::value<int>() -> implicit_value(0), "Get statistics and current settings of ZSwap kernel module.")
        ("enabled,e", boost::program_options::value<std::string>(), "Enable or disable ZSwap kernel module.")
        ("same_filled_pages_enabled,s", boost::program_options::value<std::string>(), "Enable or disable memory pages deduplication.")
        ("max_pool_percent,p", boost::program_options::value<std::string>(), "The maximum percentage of memory that the compressed pool can occupy.")
        ("compressor,c", boost::program_options::value<std::string>(), "The default compression algorithm.")
        ("zpool,z", boost::program_options::value<std::string>(), "The kernel's zpool type.")
        ("accept_threshold_percent,a", boost::program_options::value<std::string>(), "The threshold at which ZSwap would start accepting pages again after it became full.")
        ;
}

void Application::ParseCmdLine(int argc, char** argv)
{
    boost::program_options::store(boost::program_options::parse_command_line(argc, argv, *CmdLineOptions), *CmdLine);
    CmdLine -> notify();
}

Application::Application(int argc, char** argv)
{
    CheckIfRunningBySuperUser();
    InitClassMembers();
    InitCmdLineOptions();
    ParseCmdLine(argc, argv);
}

max_stars_repo_name: nmmanx/zswap-cli

max_issues_repo_name: nmmanx/zswap-cli

max_forks_repo_name: nmmanx/zswap-cli


text:
/*
Part of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)
Copyright 2017-2019 University of Huddersfield.
Licensed under the BSD-3 License.
See license.md file in the project root for full license information.
This project has received funding from the European Research Council (ERC)
under the European Union’s Horizon 2020 research and innovation programme
(grant agreement No 725899).
*/

#pragma once

#include "../util/FluidEigenMappings.hpp"
#include "../util/Novelty.hpp"
#include "../../data/FluidIndex.hpp"
#include "../../data/TensorTypes.hpp"
#include <Eigen/Core>

namespace fluid {
namespace algorithm {

class NoveltyFeature
{

public:
  using ArrayXd = Eigen::ArrayXd;

  NoveltyFeature(index maxKernelSize, index maxFilterSize)
      : mFilterBufferStorage(maxFilterSize), mNovelty(maxKernelSize)
  {}

  void init(index kernelSize, index filterSize, index nDims)
  {
    assert(kernelSize % 2);
    mNovelty.init(kernelSize, nDims);
    mFilterBuffer = mFilterBufferStorage.segment(0, filterSize);
    mFilterBuffer.setZero();
  }

  double processFrame(const RealVectorView input)
  {
    double novelty = mNovelty.processFrame(_impl::asEigen<Eigen::Array>(input));
    index  filterSize = mFilterBuffer.size();

    if (filterSize > 1)
    {
      mFilterBuffer.segment(0, filterSize - 1) =
          mFilterBuffer.segment(1, filterSize - 1);
    }

    mFilterBuffer(filterSize - 1) = novelty;

    return mFilterBuffer.mean();
  }

private:
  ArrayXd mFilterBuffer;
  ArrayXd mFilterBufferStorage;
  Novelty mNovelty;
};
} // namespace algorithm
} // namespace fluid

ext: hpp


text:
#include "SPlisHSPlasH/Common.h"
#include <Eigen/Dense>
#include <iostream>
#include "Utilities/Timing.h"
#include "Utilities/PartioReaderWriter.h"
#include "Utilities/OBJLoader.h"
#include "SPlisHSPlasH/Utilities/PoissonDiskSampling.h"
#include "Utilities/FileSystem.h"
#include "Utilities/StringTools.h"
#include "Utilities/Version.h"
#include "SPlisHSPlasH/TriangleMesh.h"
#include "extern/cxxopts/cxxopts.hpp"

// Enable memory leak detection
#ifdef _DEBUG
#ifndef EIGEN_ALIGN
	#define new DEBUG_NEW
#endif
#endif

INIT_TIMING
INIT_LOGGING

using namespace SPH;
using namespace Eigen;
using namespace std;
using namespace Utilities;

void loadObj(const std::string &filename, TriangleMesh &mesh, const Vector3r &scale);

string inputFile = "";
string outputFile = "";
Real particleRadius = 0.025;
Vector3r scale = Vector3r::Ones();

std::istream& operator >> (std::istream& istream, Vector3r& v)
{
	return istream >> std::skipws >> v[0] >> v[1] >> v[2];
}

// main
int main( int argc, char **argv )
{
	REPORT_MEMORY_LEAKS;

	std::cout << "Git refspec: " << GIT_REFSPEC << std::endl;
	std::cout << "Git SHA1: " << GIT_SHA1 << std::endl;
	std::cout << "Git status: " << GIT_LOCAL_STATUS << std::endl;

	try
	{
		cxxopts::Options options(argv[0], "SurfaceSampling - Sample a surface geometry given by an OBJ file.");

		options.add_options()
			("h,help", "Print help")
			("i,input", "Input file (obj)", cxxopts::value<std::string>())
			("o,output", "Output file (bgeo)", cxxopts::value<std::string>())
			("r,radius", "Particle radius", cxxopts::value<Real>()->default_value("0.025"))
			("s,scale", "Scaling of input geometry (e.g. --scale \"1 2 3\")", cxxopts::value<Vector3r>())
			;

		auto result = options.parse(argc, argv);

		if (result.count("help"))
		{
			std::cout << options.help({ "", "Group" }) << std::endl;
			exit(0);
		}

		if (result.count("input") && result.count("output"))
		{
			inputFile = result["input"].as<std::string>();
			std::cout << "Input = " << inputFile << std::endl;
			outputFile = result["output"].as<std::string>();
			std::cout << "Output = " << outputFile << std::endl;
		}
		else
		{
			std::cout << "Input or output missing!" << std::endl;
			std::cout << options.help({ "", "Group" }) << std::endl;
			exit(1);
		}

		if (result.count("radius"))
			particleRadius = result["radius"].as<Real>();
		cout << "Radius: " << particleRadius << endl;

		if (result.count("scale"))
			scale = result["scale"].as<Vector3r>();
		cout << "Scale: " << scale << endl;
	}
	catch (const cxxopts::OptionException& e)
	{
		std::cout << "error parsing options: " << e.what() << std::endl;
		exit(1);
	}

	TriangleMesh mesh;
	loadObj(inputFile, mesh, scale);

	std::cout << "Surface sampling of " << inputFile << "\n";
	START_TIMING("Poisson disk sampling");
	PoissonDiskSampling sampling;
	std::vector<Vector3r> samplePoints;
	sampling.sampleMesh(mesh.numVertices(), mesh.getVertices().data(), mesh.numFaces(), mesh.getFaces().data(), particleRadius, 10, 1, samplePoints);
	STOP_TIMING_AVG;
	std::cout << "Number of sample points: " << samplePoints.size() << "\n";

	PartioReaderWriter::writeParticles(outputFile, (unsigned int) samplePoints.size(), samplePoints.data(), NULL, particleRadius);

	Timing::printAverageTimes();
	Timing::printTimeSums();

	return 0;
}

void loadObj(const std::string &filename, TriangleMesh &mesh, const Vector3r &scale)
{
	std::vector<OBJLoader::Vec3f> x;
	std::vector<OBJLoader::Vec3f> normals;
	std::vector<MeshFaceIndices> faces;
	OBJLoader::Vec3f s = { (float)scale[0], (float)scale[1], (float)scale[2] };
	OBJLoader::loadObj(filename, &x, &faces, &normals, nullptr, s);

	mesh.release();
	const unsigned int nPoints = (unsigned int)x.size();
	const unsigned int nFaces = (unsigned int)faces.size();
	mesh.initMesh(nPoints, nFaces);
	for (unsigned int i = 0; i < nPoints; i++)
	{
		mesh.addVertex(Vector3r(x[i][0], x[i][1], x[i][2]));
	}
	for (unsigned int i = 0; i < nFaces; i++)
	{
		// Reduce the indices by one
		int posIndices[3];
		for (int j = 0; j < 3; j++)
		{
			posIndices[j] = faces[i].posIndices[j] - 1;
		}

		mesh.addFace(&posIndices[0]);
	}

	LOG_INFO << "Number of triangles: " << nFaces;
	LOG_INFO << "Number of vertices: " << nPoints;
}

max_stars_repo_name: gnastacast/SPlisHSPlasH

max_issues_repo_name: gnastacast/SPlisHSPlasH

max_forks_repo_name: gnastacast/SPlisHSPlasH