text:
// Copyright (C) 2019 David Harmon and Artificial Necessity
// This code distributed under zlib, see LICENSE.txt for terms.

#include "triangle_energies.hpp"

#include <Eigen/Dense>
#include <Eigen/SVD>

TriangleOrthoStrain::TriangleOrthoStrain(const Eigen::Vector3i& idxs,
                                         const std::vector<Eigen::Vector3d>& x,
                                         double ksx, double ksy,
                                         bool ignore_compression)
    : idxs_(idxs), ignore_compression_(ignore_compression)  {

    Matrix3x2 Ds;
    Ds.col(0) = x[1] - x[0];
    Ds.col(1) = x[2] - x[0];

    // Take n1 as just the first edge, n2 as the orthogonal vector closest to second edge
    Eigen::Vector3d n1 = Ds.col(0).normalized();
    Eigen::Vector3d n2 = (Ds.col(1) - Ds.col(1).dot(n1) * n1).normalized();

    Matrix3x2 Dm;
    Dm.col(0) = n1;
    Dm.col(1) = n2;

    Eigen::Matrix2d F = Dm.transpose() * Ds;
    rest_ = F.inverse();

    A_ = F.determinant() * 0.5;

    ksx = std::sqrt(ksx * A_);
    ksy = std::sqrt(ksy * A_);

    weights_ = Eigen::VectorXd(6);
    weights_ << ksx, ksx, ksx, ksy, ksy, ksy;

    S_.setZero();
    S_(0,0) = -1; S_(0,1) = -1;
    S_(1,0) =  1; S_(2,1) =  1;
}

void TriangleOrthoStrain::get_reduction(std::vector<Eigen::Triplet<double>> &triplets) const {
    const int cols[3] = { 3*idxs_[0], 3*idxs_[1], 3*idxs_[2] };

    Matrix3x2 D = S_ * rest_;
    for (int i=0; i<3; ++i) {
        for (int j=0; j<3; ++j) {
            triplets.emplace_back(i, cols[j]+i, D(j,0));
            triplets.emplace_back(3+i, cols[j]+i, D(j,1));
        }
    }
}

Eigen::VectorXd TriangleOrthoStrain::reduce(const Eigen::VectorXd& x) const {
    const int cols[3] = { 3*idxs_[0], 3*idxs_[1], 3*idxs_[2] };

    Vector6d z = Vector6d::Zero();

    Matrix3x2 D = S_ * rest_;
    for (int i=0; i<3; ++i ) {
        for (int j=0; j<3; j++) {
            z[i]   += D(j,0) * x[cols[j]+i];
            z[3+i] += D(j,1) * x[cols[j]+i];
        }
    }

    return z;
}

void TriangleOrthoStrain::project(Eigen::VectorXd& zi) const {
    Eigen::JacobiSVD<Matrix3x2>
        svd(Eigen::Map<Matrix3x2>(zi.data()), Eigen::ComputeThinU | Eigen::ComputeThinV);

    //Eigen::Vector2d S = Eigen::Vector2d::Ones();
    //if (ignore_compression_) {
    //    for (int i=0; i<2; i++) {
    //        S[i] = std::min(S[i], svd.singularValues()[i]);
    //    }
    //}

    //Matrix3x2 P = svd.matrixU().leftCols(2) * S.asDiagonal() * svd.matrixV().transpose();

    Matrix3x2 P = svd.matrixU().leftCols(2) * svd.matrixV().transpose();
    zi = 0.5 * (Eigen::Map<Vector6d>(P.data()) + zi);
}


text:
/* Copyright 2006-2018 Joaquin M Lopez Munoz.
 * Distributed under the Boost Software License, Version 1.0.
 * (See accompanying file LICENSE_1_0.txt or copy at
 * http://www.boost.org/LICENSE_1_0.txt)
 *
 * See http://www.boost.org/libs/flyweight for library home page.
 */

#ifndef BOOST_FLYWEIGHT_DETAIL_NOT_PLACEHOLDER_EXPR_HPP
#define BOOST_FLYWEIGHT_DETAIL_NOT_PLACEHOLDER_EXPR_HPP

#if defined(_MSC_VER)
#pragma once
#endif

/* BOOST_FLYWEIGHT_NOT_A_PLACEHOLDER_EXPRESSION can be inserted at the end
 * of a class template parameter declaration:
 *   template<
 *     typename X0,...,typename Xn
 *     BOOST_FLYWEIGHT_NOT_A_PLACEHOLDER_EXPRESSION
 *   >
 *   struct foo...
 * to prevent instantiations from being treated as MPL placeholder
 * expressions in the presence of placeholder arguments; this is useful
 * to avoid masking of a metafunction class nested ::apply during
 * MPL invocation.
 */

#include <boost/config.hpp> /* keep it first to prevent nasty warns in MSVC */
#include <boost/detail/workaround.hpp>

#if BOOST_WORKAROUND(__GNUC__, <4)||\
    BOOST_WORKAROUND(__GNUC__,==4)&&(__GNUC_MINOR__<2)||\
    BOOST_WORKAROUND(__GNUC__, ==7)&&( __cplusplus>=201703L)||\
    BOOST_WORKAROUND(__GNUC__, >=8)&&( __cplusplus>=201103L)
/* The default trick on which the macro is based, namely adding a int=0
 * defaulted template parameter, does not work in GCC prior to 4.2 due to
 * an unfortunate compiler non-standard extension, as explained in
 *   http://lists.boost.org/boost-users/2007/07/29866.php
 * As it happens, GCC 7 in C++17 mode and GCC 8 (and presumably later) in
 * C++11 mode (and presumably later) go back to this old behavior, anticipating
 * the resolution of CWG DR 150 (see P0522R0).
 * In these cases we resort to an uglier technique, adding defaulted template
 * parameters so as to exceed BOOST_MPL_LIMIT_METAFUNCTION_ARITY.
 */

#include <boost/mpl/limits/arity.hpp>
#include <boost/preprocessor/facilities/intercept.hpp>
#include <boost/preprocessor/repetition/enum_trailing_params.hpp>

#define BOOST_FLYWEIGHT_NOT_A_PLACEHOLDER_EXPRESSION                  \
BOOST_PP_ENUM_TRAILING_PARAMS(                                        \
  BOOST_MPL_LIMIT_METAFUNCTION_ARITY,typename=int BOOST_PP_INTERCEPT)
#define BOOST_FLYWEIGHT_NOT_A_PLACEHOLDER_EXPRESSION_DEF              \
BOOST_PP_ENUM_TRAILING_PARAMS(                                        \
  BOOST_MPL_LIMIT_METAFUNCTION_ARITY,typename BOOST_PP_INTERCEPT)

#else
#define BOOST_FLYWEIGHT_NOT_A_PLACEHOLDER_EXPRESSION  ,int=0
#define BOOST_FLYWEIGHT_NOT_A_PLACEHOLDER_EXPRESSION_DEF  ,int
#endif

#endif

ext: hpp


text:
/*
  +----------------------------------------------------------------------+
  | Yasd                                                                 |
  +----------------------------------------------------------------------+
  | This source file is subject to version 2.0 of the Apache license,    |
  | that is bundled with this package in the file LICENSE, and is        |
  | available through the world-wide-web at the following url:           |
  | http://www.apache.org/licenses/LICENSE-2.0.html                      |
  | If you did not receive a copy of the Apache2.0 license and are unable|
  | to obtain it through the world-wide-web, please send a note to       |
  | license@swoole.com so we can mail you a copy immediately.            |
  +----------------------------------------------------------------------+
  | Author: codinghuang  <codinghuang@qq.com>                            |
  +----------------------------------------------------------------------+
*/
#include <iostream>

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

#include "include/common.h"
#include "include/context.h"
#include "include/cmder_debugger.h"
#include "include/util.h"
#include "include/global.h"
#include "include/source_reader.h"

namespace yasd {

CmderDebugger::CmderDebugger() {}

void CmderDebugger::init() {
    int status;
    std::string cmd;

    show_welcome_info();

    reload_cache_breakpoint();
    register_cmd_handler();

    do {
        cmd = get_next_cmd();
        if (cmd == "") {
            yasd::Util::printfln_info(yasd::Color::YASD_ECHO_RED, "please input cmd!");
            continue;
        }
        status = execute_cmd();
    } while (status != yasd::DebuggerModeBase::status::NEXT_OPLINE);
}

void CmderDebugger::handle_request(const char *filename, int lineno) {
    int status;
    std::string cmd;
    yasd::SourceReader reader(filename);
    std::vector<std::string> exploded_cmd;

    boost::split(exploded_cmd, last_cmd, boost::is_any_of(" "), boost::token_compress_on);

    if (get_full_name(exploded_cmd[0]) == "run" || get_full_name(exploded_cmd[0]) == "continue") {
        yasd::Util::printf_info(yasd::Color::YASD_ECHO_MAGENTA, "stop because of breakpoint ");
    } else {
        yasd::Util::printf_info(
            yasd::Color::YASD_ECHO_MAGENTA, "stop because of %s ", get_full_name(exploded_cmd[0]).c_str());
    }

    reader.show_contents(lineno, get_listsize(), true, true);

    do {
        global->do_next = false;
        global->do_step = false;
        global->do_finish = false;

        cmd = get_next_cmd();
        if (cmd == "") {
            yasd::Util::printfln_info(yasd::Color::YASD_ECHO_RED, "please input cmd!");
            continue;
        }
        status = execute_cmd();
    } while (status != yasd::DebuggerModeBase::status::NEXT_OPLINE);
}

void CmderDebugger::handle_stop() {}

CmderDebugger::~CmderDebugger() {}

std::string CmderDebugger::get_next_cmd() {
    std::string tmp;

    std::cout << "> ";
    getline(std::cin, tmp);
    boost::algorithm::trim(tmp);
    if (tmp == "") {
        return last_cmd;
    }
    last_cmd = tmp;
    return last_cmd;
}

int CmderDebugger::parse_run_cmd() {
    global->is_running = true;

    return NEXT_OPLINE;
}

int CmderDebugger::parse_breakpoint_cmd() {
    int lineno;
    std::string filename;
    std::vector<std::string> exploded_cmd;

    boost::split(exploded_cmd, last_cmd, boost::is_any_of(" "), boost::token_compress_on);

    // breakpoint in current file with lineno
    if (exploded_cmd.size() == 2) {
        filename = yasd::Util::get_executed_filename();
        if (filename == "") {
            filename = global->entry_file;
        }
        lineno = atoi(exploded_cmd[1].c_str());
    } else if (exploded_cmd.size() == 3) {
        filename = exploded_cmd[1];
        lineno = atoi(exploded_cmd[2].c_str());
    } else {
        yasd::Util::printfln_info(YASD_ECHO_RED, "use set breakpoint cmd error!");
        return RECV_CMD_AGAIN;
    }

    auto iter = global->breakpoints->find(filename);

    if (iter != global->breakpoints->end()) {
        iter->second.insert(lineno);
    } else {
        std::set<int> lineno_set;
        lineno_set.insert(lineno);
        global->breakpoints->insert(std::make_pair(filename, lineno_set));
    }

    yasd::Util::cache_breakpoint(filename, lineno);

    yasd::Util::printfln_info(yasd::Color::YASD_ECHO_GREEN, "set breakpoint at %s:%d", filename.c_str(), lineno);

    return RECV_CMD_AGAIN;
}

int CmderDebugger::parse_delete_breakpoint_cmd() {
    int lineno;
    std::string filename;
    std::vector<std::string> exploded_cmd;

    boost::split(exploded_cmd, last_cmd, boost::is_any_of(" "), boost::token_compress_on);

    if (exploded_cmd.size() == 2) {
        filename = yasd::Util::get_executed_filename();
        if (filename == "") {
            filename = global->entry_file;
        }
        lineno = atoi(exploded_cmd[1].c_str());
    } else if (exploded_cmd.size() == 3) {
        filename = exploded_cmd[1];
        lineno = atoi(exploded_cmd[2].c_str());
    } else {
        yasd::Util::printfln_info(YASD_ECHO_RED, "use delete breakpoint cmd error!");
        return RECV_CMD_AGAIN;
    }

    auto iter = global->breakpoints->find(filename);

    if (iter != global->breakpoints->end()) {
        iter->second.erase(lineno);
        if (iter->second.empty()) {
            global->breakpoints->erase(iter->first);
        }
        yasd::Util::printfln_info(yasd::Color::YASD_ECHO_GREEN, "delete breakpoint at %s:%d", filename.c_str(), lineno);
    } else {
        yasd::Util::printfln_info(YASD_ECHO_RED, "breakpoint at %s:%d is not existed!", filename.c_str(), lineno);
    }

    return RECV_CMD_AGAIN;
}

int CmderDebugger::parse_info_cmd() {
    if (global->breakpoints->empty()) {
        yasd::Util::printfln_info(YASD_ECHO_RED, "no found breakpoints!");
    }
    for (auto i = global->breakpoints->begin(); i != global->breakpoints->end(); i++) {
        for (auto j = i->second.begin(); j != i->second.end(); j++) {
            yasd::Util::printfln_info(yasd::Color::YASD_ECHO_GREEN, "filename: %s:%d", i->first.c_str(), *j);
        }
    }

    return RECV_CMD_AGAIN;
}

int CmderDebugger::parse_level_cmd() {
    yasd::Context *context = global->get_current_context();

    std::cout << "in coroutine: " << context->cid << "next coroutine: " << global->next_cid
              << ", level: " << context->level << ", next level: " << context->next_level << std::endl;

    return RECV_CMD_AGAIN;
}

int CmderDebugger::parse_backtrace_cmd() {
    yasd::Context *context = global->get_current_context();

    yasd::Util::printfln_info(
        YASD_ECHO_GREEN, "%s:%d", yasd::Util::get_executed_filename(), yasd::Util::get_executed_file_lineno());

    for (auto iter = context->strace->rbegin(); iter != context->strace->rend(); ++iter) {
        yasd::Util::printfln_info(YASD_ECHO_GREEN, "%s:%d", (*iter)->filename.c_str(), (*iter)->lineno);
    }

    return RECV_CMD_AGAIN;
}

int CmderDebugger::parse_continue_cmd() {
    return NEXT_OPLINE;
}

int CmderDebugger::parse_quit_cmd() {
    yasd::Util::printfln_info(YASD_ECHO_RED, "quit!");
    exit(255);

    return FAILED;
}

int CmderDebugger::parse_print_cmd() {
    std::vector<std::string> exploded_cmd;

    boost::split(exploded_cmd, last_cmd, boost::is_any_of(" "), boost::token_compress_on);

    yasd::Util::print_var(exploded_cmd[1]);
    global->do_next = true;

    return RECV_CMD_AGAIN;
}

int CmderDebugger::parse_list_cmd() {
    int lineno = last_list_lineno;
    const char *filename = yasd::Util::get_executed_filename();
    yasd::SourceReader reader(filename);
    std::vector<std::string> exploded_cmd;

    boost::split(exploded_cmd, last_cmd, boost::is_any_of(" "), boost::token_compress_on);

    // list lineno or list -
    if (exploded_cmd.size() == 2) {
        if (exploded_cmd[1] == "-") {
            lineno = last_list_lineno - listsize;
        } else {
            lineno = atoi(exploded_cmd[1].c_str());
            lineno = last_list_lineno + listsize;
        }
        last_list_lineno = lineno;
    } else {
        // list
        lineno = last_list_lineno;
        last_list_lineno = lineno + listsize;
    }

    reader.show_contents(lineno, get_listsize());
    return RECV_CMD_AGAIN;
}

int CmderDebugger::parse_set_cmd() {
    std::vector<std::string> exploded_cmd;

    boost::split(exploded_cmd, last_cmd, boost::is_any_of(" "), boost::token_compress_on);

    if (exploded_cmd[1] == "listsize") {
        listsize = atoi(exploded_cmd[2].c_str());
    }
    return RECV_CMD_AGAIN;
}

int CmderDebugger::parse_watch_cmd() {
    zend_function *func = EG(current_execute_data)->func;
    std::string var_name;
    yasd::WatchPointElement element;
    std::vector<std::string> exploded_cmd;

    boost::split(exploded_cmd, last_cmd, boost::is_any_of(" "), boost::token_compress_on);
    if (exploded_cmd.size() < 2) {
        yasd::Util::printfln_info(yasd::Color::YASD_ECHO_RED, "you should set watch point");
        return RECV_CMD_AGAIN;
    } else if (exploded_cmd.size() == 2) {
        element.type = yasd::WatchPointElement::t::VARIABLE_CHANGE;
        var_name = exploded_cmd[1];

        zval *old_var = yasd::Util::find_variable(var_name);

        if (!old_var) {
            zval tmp;
            old_var = &tmp;
            ZVAL_UNDEF(old_var);
        }

        element.old_var = *old_var;
    } else {
        // w a < 1
        element.type = yasd::WatchPointElement::t::CONDITION;
        var_name = exploded_cmd[1];
        element.operation = exploded_cmd[2];

        if (yasd::Util::is_integer(exploded_cmd[3])) {
            ZVAL_LONG(&element.old_var, atoi(exploded_cmd[3].c_str()));
        } else {
            ZVAL_NEW_STR(&element.old_var, zend_string_init(exploded_cmd[3].c_str(), exploded_cmd[3].length(), 0));
        }
    }

    auto iter = global->watchPoints.var_watchpoint.find(func);
    if (iter == global->watchPoints.var_watchpoint.end()) {
        WATCHPOINT *watchpoint = new WATCHPOINT();
        watchpoint->insert(std::make_pair(var_name, element));
        global->watchPoints.var_watchpoint.insert(std::make_pair(func, watchpoint));
    } else {
        iter->second->insert(std::make_pair(var_name, element));
    }

    yasd::Util::printfln_info(yasd::Color::YASD_ECHO_GREEN, "watching variable $%s", var_name.c_str());

    return RECV_CMD_AGAIN;
}

int CmderDebugger::parse_unwatch_cmd() {
    zend_function *func = EG(current_execute_data)->func;
    std::vector<std::string> exploded_cmd;

    boost::split(exploded_cmd, last_cmd, boost::is_any_of(" "), boost::token_compress_on);
    if (exploded_cmd.size() < 2) {
        yasd::Util::printfln_info(yasd::Color::YASD_ECHO_RED, "you should set watch point");
        return RECV_CMD_AGAIN;
    }
    std::string var_name = exploded_cmd[1];

    auto iter = global->watchPoints.var_watchpoint.find(func);
    if (iter == global->watchPoints.var_watchpoint.end()) {
        yasd::Util::printfln_info(yasd::Color::YASD_ECHO_GREEN, "not found watch point $%s", var_name.c_str());
    } else {
        auto zval_iter = iter->second->find(var_name);
        if (zval_iter == iter->second->end()) {
            yasd::Util::printfln_info(yasd::Color::YASD_ECHO_GREEN, "not found watch point $%s", var_name.c_str());
        } else {
            zval_dtor(&zval_iter->second.old_var);
            iter->second->erase(var_name);
            yasd::Util::printfln_info(yasd::Color::YASD_ECHO_GREEN, "unwatch variable $%s", var_name.c_str());
        }
    }

    return RECV_CMD_AGAIN;
}

bool CmderDebugger::is_disable_cmd(std::string cmd) {
    // the command in the condition is allowed to execute in non-run state
    if (get_full_name(cmd) != "run" && get_full_name(cmd) != "b" && get_full_name(cmd) != "quit" &&
        get_full_name(cmd) != "info" && get_full_name(cmd) != "delete" && get_full_name(cmd) != "list" &&
        get_full_name(cmd) != "set") {
        return true;
    }

    return false;
}

std::string CmderDebugger::get_full_name(std::string sub_cmd) {
    for (auto &&kv : handlers) {
        if (yasd::Util::is_match(sub_cmd, kv.first)) {
            return kv.first;
        }
    }
    return "unknown cmd";
}

void CmderDebugger::show_welcome_info() {
    yasd::Util::printfln_info(YASD_ECHO_GREEN, "[Welcome to yasd, the Swoole debugger]");
    yasd::Util::printfln_info(YASD_ECHO_GREEN, "[You can set breakpoint now]");
}

void CmderDebugger::reload_cache_breakpoint() {
    std::string content;
    std::string cache_filename_path = yasd::Util::get_breakpoint_cache_filename();

    if (cache_filename_path == "") {
        return;
    }

    std::fstream file(cache_filename_path);
    std::string filename;
    int lineno;

    while (getline(file, content)) {
        std::vector<std::string> exploded_content;

        boost::split(exploded_content, content, boost::is_any_of(":"), boost::token_compress_on);
        if (exploded_content.size() != 2) {
            continue;
        }

        filename = exploded_content[0];
        lineno = atoi(exploded_content[1].c_str());

        auto iter = global->breakpoints->find(filename);

        yasd::Util::printfln_info(yasd::Color::YASD_ECHO_GREEN, "reload breakpoint at %s:%d", filename.c_str(), lineno);

        if (iter != global->breakpoints->end()) {
            iter->second.insert(lineno);
        } else {
            std::set<int> lineno_set;
            lineno_set.insert(lineno);
            global->breakpoints->insert(std::make_pair(filename, lineno_set));
        }
    }
}

int CmderDebugger::execute_cmd() {
    std::vector<std::string> exploded_cmd;

    boost::split(exploded_cmd, last_cmd, boost::is_any_of(" "), boost::token_compress_on);

    if (!global->is_running) {
        if (is_disable_cmd(exploded_cmd[0])) {
            yasd::Util::printfln_info(YASD_ECHO_RED, "program is not running!");
            return RECV_CMD_AGAIN;
        }
    }

    auto handler = find_cmd_handler(exploded_cmd[0]);
    if (!handler) {
        return FAILED;
    }

    return handler();
}

void CmderDebugger::register_cmd_handler() {
    handlers.emplace_back(std::make_pair("run", std::bind(&CmderDebugger::parse_run_cmd, this)));
    handlers.emplace_back(std::make_pair("b", std::bind(&CmderDebugger::parse_breakpoint_cmd, this)));
    handlers.emplace_back(std::make_pair("bt", std::bind(&CmderDebugger::parse_backtrace_cmd, this)));
    handlers.emplace_back(std::make_pair("delete", std::bind(&CmderDebugger::parse_delete_breakpoint_cmd, this)));
    handlers.emplace_back(std::make_pair("info", std::bind(&CmderDebugger::parse_info_cmd, this)));
    handlers.emplace_back(std::make_pair("step", std::bind(&CmderDebugger::parse_step_into_cmd, this)));
    handlers.emplace_back(std::make_pair("list", std::bind(&CmderDebugger::parse_list_cmd, this)));
    handlers.emplace_back(std::make_pair("next", std::bind(&CmderDebugger::parse_step_over_cmd, this)));
    handlers.emplace_back(std::make_pair("continue", std::bind(&CmderDebugger::parse_continue_cmd, this)));
    handlers.emplace_back(std::make_pair("quit", std::bind(&CmderDebugger::parse_quit_cmd, this)));
    handlers.emplace_back(std::make_pair("print", std::bind(&CmderDebugger::parse_print_cmd, this)));
    handlers.emplace_back(std::make_pair("finish", std::bind(&CmderDebugger::parse_step_out_cmd, this)));
    handlers.emplace_back(std::make_pair("set", std::bind(&CmderDebugger::parse_set_cmd, this)));
    handlers.emplace_back(std::make_pair("level", std::bind(&CmderDebugger::parse_level_cmd, this)));
    handlers.emplace_back(std::make_pair("watch", std::bind(&CmderDebugger::parse_watch_cmd, this)));
    handlers.emplace_back(std::make_pair("unwatch", std::bind(&CmderDebugger::parse_unwatch_cmd, this)));
}

std::function<int()> CmderDebugger::find_cmd_handler(std::string cmd) {
    for (auto &&kv : handlers) {
        if (kv.first == get_full_name(cmd)) {
            return kv.second;
        }
    }
    return nullptr;
}
}  // namespace yasd

ext: cc

max_stars_repo_name: Hetystars/yasd

max_issues_repo_name: Hetystars/yasd

max_forks_repo_name: Hetystars/yasd


text:
/*
 * AMZ-Driverless
 * Copyright (c) 2018 Authors:
 *   - Juraj Kabzan <kabzanj@gmail.com>
 *
 * 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.
 */

#ifndef FSSIM_GAZEBO_GAZEBOUTILLS_H
#define FSSIM_GAZEBO_GAZEBOUTILLS_H

// STD Includes
#include <string>

// Eigen Include
#include <Eigen/Dense>

namespace gazebo {

template<class Joint, class Model>
void getJoint(Joint &joint, Model &model, const std::string &name) {
    joint = model->GetJoint(name);
    if (!joint) {
        gzerr << "could not find " << name << " joint" << std::endl;
    }
}

template<class Link, class Model>
void getLink(Link &link, Model &model, const std::string &name) {
    link = model->GetLink(name);
    if (!link) {
        gzerr << "could not find " << name << " link" << std::endl;
    }
}

template<class type>
type getParam(sdf::ElementPtr &sdf, std::string paramName, type paramDefault) {
    type para;
    if (sdf->HasElement(paramName)) {
        para = sdf->Get<type>(paramName);
    } else {
        gzwarn << "Setting default value for: " << paramName << ":" << paramDefault << std::endl;
        para = paramDefault;
    }
    return para;
}

template<class type>
type getParam(sdf::ElementPtr &sdf, std::string paramName) {
    type para;
    if (sdf->HasElement(paramName)) {
        para = sdf->Get<type>(paramName);
    } else {
        para = type();
    }
    return para;
}

} // namespace gazebo

inline Eigen::Vector3d toVector(const boost::shared_ptr<gazebo::physics::Entity> &v) {
    return {v->GetWorldPose().pos.x, v->GetWorldPose().pos.y, 0.0};
}

#endif //FSSIM_GAZEBO_GAZEBOUTILLS_H

max_stars_repo_name: AhmedOsamaAgha/fssim

max_issues_repo_name: AhmedOsamaAgha/fssim

max_forks_repo_name: AhmedOsamaAgha/fssim


text:
#ifndef INCLUDED_STDDEFX
#include "stddefx.h"
#define INCLUDED_STDDEFX
#endif

#ifndef INCLUDED_CALC_XMLSCRIPTCLIENTINTERFACE
#include "calc_xmlscriptclientinterface.h"
#define INCLUDED_CALC_XMLSCRIPTCLIENTINTERFACE
#endif

// Library headers.
#ifndef INCLUDED_BOOST_FOREACH
#include <boost/foreach.hpp>
#define INCLUDED_BOOST_FOREACH
#endif
#ifndef INCLUDED_BOOST_NONCOPYABLE
#include <boost/noncopyable.hpp>
#define INCLUDED_BOOST_NONCOPYABLE
#endif
// PCRaster library headers.
#ifndef INCLUDED_PCRASTERXSD
#include "PCRasterXSD.h"
#define INCLUDED_PCRASTERXSD
#endif
#ifndef INCLUDED_PCRXSD_DOMINPUT
#include "pcrxsd_dominput.h"
#define INCLUDED_PCRXSD_DOMINPUT
#endif
// Module headers.
#ifndef INCLUDED_CALC_STRINGPARSER
#include "calc_stringparser.h"
#define INCLUDED_CALC_STRINGPARSER
#endif
#ifndef INCLUDED_CALC_ASTNODELIST
#include "calc_astnodelist.h"
#define INCLUDED_CALC_ASTNODELIST
#endif
#ifndef INCLUDED_CALC_ASTSCRIPT
#include "calc_astscript.h"
#define INCLUDED_CALC_ASTSCRIPT
#endif
#ifndef INCLUDED_CALC_ASTSYMBOLTABLE
#include "calc_astsymboltable.h"
#define INCLUDED_CALC_ASTSYMBOLTABLE
#endif
#ifndef INCLUDED_CALC_STATTABLE
#include "calc_stattable.h"
#define INCLUDED_CALC_STATTABLE
#endif
#ifndef INCLUDED_CALC_ASTPAR
#include "calc_astpar.h"
#define INCLUDED_CALC_ASTPAR
#endif
#ifndef INCLUDED_CALC_CODE
#include "calc_code.h"
#define INCLUDED_CALC_CODE
#endif
#ifndef INCLUDED_CALC_DATATYPECLASH
#include "calc_datatypeclash.h"
#define INCLUDED_CALC_DATATYPECLASH
#endif
#ifndef INCLUDED_CALC_POSITIONNAME
#include "calc_positionname.h"
#define INCLUDED_CALC_POSITIONNAME
#endif

/*!
  \file
  This file contains the implementation of the XMLScriptClientInterface class.
*/

namespace calc {
 namespace detail {
  typedef std::pair<std::string, StatTable *> NameStatTablePair;
  typedef std::map<std::string, StatTable *> NameStatTableMap;

  /*! parse the model parts
   */
  class ParseModelParts {
   private:
     Code* d_code;
     NameStatTableMap d_nameStatTableMap;
   public:
     ParseModelParts():
       d_code(new Code(new ASTNodeList()))
     { }
     ~ParseModelParts() {
      delete d_code;
     }

     void parseTextModel(std::string const& textModel) {
      // Code, initial/dynamic only, timer, bindings are
      //  simply ignored
      delete d_code;
      d_code = StringParser::createCode(pcrxsd::toString<>(textModel));
     }

     void parseTextStatistics(pcrxml::TextStatistics const& s ) {

       std::string name(pcrxsd::toString(s.name()));
       if (d_nameStatTableMap.count(name)) {
          std::ostringstream is;
          is << "redefinition of textStatistics with name '"<<
                name << "'" << std::endl;
          throw com::Exception(is.str());
       }

       std::vector<StatTable::InputMap> maps;
       BOOST_FOREACH(pcrxml::TextStatisticsSubject const& i,
                    s.textStatisticsSubject())
       {
          StatTable::InputMap in;
          in.d_name = pcrxsd::toString(i.fieldRef());
          in.d_field= new ASTPar(pcrxsd::toString(i.fieldRef()));
          if (i.intervalRef())
            in.d_intervals=new ASTPar(pcrxsd::toString(i.intervalRef()));
          maps.push_back(in);
       }
       if (maps.size()==1) {
          maps.push_back(StatTable::InputMap());
       }
       StatTable *st = new StatTable(name, maps[0],maps[1]);
       d_code->transferPushBack(st);
       d_nameStatTableMap.insert(std::make_pair(name,st));
     }

     Code* releaseCode() {
      Code* c=d_code;
      d_code=0;
      return c;
     }

     NameStatTableMap const& nameStatTableMap() const {
      return d_nameStatTableMap;
     }
  };

  //! update ASTSymbolTable for definitions
  class XMLUpdateSymbolTable:
    public boost::noncopyable
  {
  private:
    ASTSymbolTable& d_table;
    NameStatTableMap const& d_nameStatTableMap;
  public:
    XMLUpdateSymbolTable(ASTSymbolTable& table,
                         NameStatTableMap const& nameStatTableMap):
      d_table(table),
      d_nameStatTableMap(nameStatTableMap)
    {
      BOOST_FOREACH(NameStatTablePair i, d_nameStatTableMap)
      {
        std::string name(i.first);
        if (d_table.count(name)) {
          // force a type error on existing
          ASTSymbolInfo& sym(d_table[i.second->id()]);
          try {
           sym.dataType().restrict(VS_STATISTICS);
          } catch(const VSClash& v) {
           // PRINT_VAR(name);
           std::string msg= sym.vsClashError(v,"set");
           sym.throwSym(PositionName("xml"),msg);
          }
        } else {
          // insert as string
         d_table[i.second->id()].dataType()=DataType(VS_STATISTICS);
        }
      }
    }

    //! only update the symbol if found in the model
    void updateUsedSymbols(pcrxml::Definition const& d) {
      ASTSymbolTable::iterator si=d_table.find(d.name());
      if (si == d_table.end())
        return; // not found

      ASTSymbolInfo& i(si->second);
      i.setDefinition(d);

      NameStatTableMap::const_iterator s = d_nameStatTableMap.find(d.name());
      if (s != d_nameStatTableMap.end()) {
        // TODO now always report that is not conform scriptOutput meaning
        s->second->setIdBinding(i);
      }

    }
   };
  }

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

//------------------------------------------------------------------------------
// DEFINITION OF STATIC XMLSCRIPTCLIENTINTERFACE MEMBERS
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// DEFINITION OF XMLSCRIPTCLIENTINTERFACE MEMBERS
//------------------------------------------------------------------------------

XMLScriptClientInterface::XMLScriptClientInterface(
    const std::string& scriptFileOrContents,
    bool asFile):
     ClientInterface(scriptFileOrContents,asFile)
{
}

/* NOT IMPLEMENTED
//! Copy constructor.
XMLScriptClientInterface::XMLScriptClientInterface(
         XMLScriptClientInterface const& rhs)

  : Base(rhs)

{
}
*/

XMLScriptClientInterface::~XMLScriptClientInterface()
{
}

/* NOT IMPLEMENTED
//! Assignment operator.
XMLScriptClientInterface& XMLScriptClientInterface::operator=(
         XMLScriptClientInterface const& rhs)
{
  if(this != &rhs) {
  }

  return *this;
}
*/

void XMLScriptClientInterface::parse()
{
  pcrxsd::DOMInput d(pcrxsd::DOMInput::CompiledIn);
  d.setValidate(true);
  if (d_asFile) {
    d.setFile(d_scriptFileOrContents);
  } else {
    d.setString(d_scriptFileOrContents);
  }
  d_xml.reset(pcrxml::script(*d.document()).release());
}

ASTScript* XMLScriptClientInterface::createScriptAndAnalyzeNoContext()
{
  std::auto_ptr<ASTScript> script(new ASTScript());
  script->setReportOnlyForXMLScriptOutput(true);

  try {
    parse();
  } catch (pcrxsd::Exception const& e) {
    std::ostringstream is;
    is << e.msg() << std::endl;
    throw com::Exception(is.str());
  } catch (xml_schema::exception const& e) {
    std::ostringstream is;
    is << e << std::endl;
    throw com::Exception(is.str());
  }

  detail::ParseModelParts pmp;

  if (d_xml->model()) {
     pmp.parseTextModel(pcrxsd::toString<>(d_xml->model()->textModel()));
  }
  BOOST_FOREACH(pcrxml::TextStatistics const& s, d_xml->textStatistics())
  {
     pmp.parseTextStatistics(s);
  }

  // fixed PCRaster Bugzilla #77
  // setSettingsFromXML must be done before transferCode
  // because symbol used for areaMap must be found
  script->setSettingsFromXML(*d_xml);

  // ASTNodeList *p(new ASTNodeList());
  // p->transferPushBack(pmp.releaseCode());
  // script->transferCode(p);

  script->transferCode(pmp.releaseCode());

  if (d_xml->timer()) {
   Timer t;
   t.setStartInt(d_xml->timer()->integer().start());
   if (d_xml->timer()->integer().end().present())
      t.setLastInt(d_xml->timer()->integer().end().get());
   script->setExternalTimer(t);
  }

  // pick up the symbols used
  script->analyzeNoContext();

  // annotate the symbols used
  detail::XMLUpdateSymbolTable ust(script->symbols(), pmp.nameStatTableMap());
  BOOST_FOREACH(pcrxml::Definition const& d, d_xml->definition())
  {
    ust.updateUsedSymbols(d);
  }

  return script.release();
}

//------------------------------------------------------------------------------
// DEFINITION OF FREE OPERATORS
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// DEFINITION OF FREE FUNCTIONS
//------------------------------------------------------------------------------

} // namespace calc

max_stars_repo_name: quanpands/wflow

max_issues_repo_name: quanpands/wflow

max_forks_repo_name: quanpands/wflow


text:
//
// Created by everettjf on 2019-06-22.
//

#include "networkhandler.h"
#include "syslog.h"

#include "networkhandler.h"
#include <thread>
#include "./dep/bifrost/server/bifrost_server.hpp"
#include "./dep/bifrost/server/bifrost_file_server.hpp"
#include "./dep/logic/json.hpp"
#include <boost/algorithm/string/predicate.hpp>
#include <boost/lexical_cast.hpp>
#include <iostream>
#include "native-lib.h"

namespace rekb {

    void sendMessage(bifrost::chat_session_handler *session, const std::string & command, const std::string & content) {
        if (!session){
            return;
        }

        session->send(bifrost::chat_message(rekb::construct_message(command,content)));
    }

    struct NetworkHandler::Impl {
        std::shared_ptr<bifrost::server> server;
        std::thread thread;
    };

    NetworkHandler::NetworkHandler(): _imp(std::make_shared<Impl>()){

    }

    NetworkHandler::~NetworkHandler(){

    }

    void NetworkHandler::start() {
        stop();

        // port
        bifrost::config::value().chat_server_listen_port = 6999;
        bifrost::config::value().chat_client_connect_port = 6999;

        _imp->server = std::make_shared<bifrost::server>();

        // config user defined message
        configMessage();

        // run server
        if (_imp->thread.joinable()) {
            _imp->thread.join();
        }
        _imp->thread = std::thread([this]() {
            std::string error_info;
            if(!_imp->server->run(error_info)){
                LOGD("--------------------------RKB Error------------------------------");
                std::string error_str = "server start failed : " +  error_info;
                LOGD("%s",error_str.c_str());
                LOGD("---------------------------------------------------------------------");
                return;
            }

            LOGD("server running");

            _imp->server->wait();

            LOGD("server stopped");
        });

        LOGD("server started");
    }

    void NetworkHandler::stop() {
        if (_imp->server) {
            _imp->server->close();
        }

        if (_imp->thread.joinable()) {
            _imp->thread.join();
        }
    }

    void NetworkHandler::configMessage() {
        _imp->server->on_session_created =  [this](bifrost::chat_session_handler *session) {
            session->send(bifrost::chat_message(rekb::construct_message("hello", "")));
            postSocketNotification("status", "connected", "");
        };
        _imp->server->on_session_closed =  [this](bifrost::chat_session_handler *session) {
            postSocketNotification("status", "disconnected", "");
        };

        _imp->server->on_receive_message = [this](const bifrost::chat_message& msg, bifrost::chat_session_handler *session) {
            std::string message = msg.get_string();

            LOGD("receive:%s", message.c_str());

            std::string command;
            std::string content;
            if(! rekb::deconstruct_message(message, command, content)) {
                LOGD("failed to deconstruct message");
                return;
            }

            LOGD("command : %s", command.c_str());
            LOGD("content : %s", content.c_str());

            processMessage(session,command,content);

        };
    }

    void NetworkHandler::processMessage(void * handler,const std::string & command, const std::string & content)
    {
        bifrost::chat_session_handler *session = static_cast<bifrost::chat_session_handler *>(handler);

        if (command == "hello"){
            LOGD("connected to desktop");
            session->send(bifrost::chat_message(rekb::construct_message("device-info", _device_info.to_json())));
            postSocketNotification("message", "connected", "");
        } else if (command == "ping") {
            session->send(bifrost::chat_message(rekb::construct_message("pong", "")));
        } else {
            postSocketNotification("message", command.c_str(), content.c_str());
        }
    }

}

ext: cpp

max_stars_repo_name: remoboard/remoboard-source

max_issues_repo_name: remoboard/remoboard-source

max_forks_repo_name: remoboard/remoboard-source


text:
#ifndef STAN_LANG_GENERATOR_GENERATE_MEMBER_VAR_INITS_HPP
#define STAN_LANG_GENERATOR_GENERATE_MEMBER_VAR_INITS_HPP

#include <stan/lang/ast.hpp>
#include <stan/lang/generator/constants.hpp>
#include <stan/lang/generator/dump_member_var_visgen.hpp>
#include <stan/lang/generator/generate_indent.hpp>
#include <boost/variant/apply_visitor.hpp>
#include <ostream>
#include <vector>

namespace stan {
  namespace lang {

    /**
     * Generate initializations for member variables by reading from
     * constructor variable context.
     * Generated initializations are preceeded by stmt updating global variable
     * `current_statement_begin__` to src file line number where
     * variable is declared.
     *
     * @param[in] vs member variable declarations
     * @param[in] indent indentation level
     * @param[in,out] o stream for generating
     */
    void generate_member_var_inits(const std::vector<var_decl>& vs,
                                   int indent, std::ostream& o) {
      dump_member_var_visgen vis(indent, o);
      for (size_t i = 0; i < vs.size(); ++i) {
        generate_indent(indent, o);
        o << "current_statement_begin__ = " <<  vs[i].begin_line_ << ";"
          << EOL;
        boost::apply_visitor(vis, vs[i].decl_);
      }
    }

  }
}
#endif

max_stars_repo_name: yizhang-cae/torsten

max_issues_repo_name: yizhang-cae/torsten

max_forks_repo_name: yizhang-cae/torsten


text:
#include <fmt/format.h>

#include <boost/convert.hpp>
#include <boost/convert/lexical_cast.hpp>
#include <boost/convert/printf.hpp>
#include <boost/convert/spirit.hpp>
#include <boost/convert/stream.hpp>
#include <boost/convert/strtol.hpp>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/locale.hpp>
#include <boost/spirit/home/x3.hpp>
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/qi.hpp>

struct
{
  template <typename T = double>
  std::string operator()(std::string_view lhs, std::string_view rhs, int /*precision*/) const
  {
    const auto l = boost::lexical_cast<T>(lhs);
    const auto r = boost::lexical_cast<T>(rhs);
    return boost::lexical_cast<std::string>(l + r);
  }
} lexical_cast;

struct
{
  template <typename T = double>
  std::string operator()(std::string_view lhs, std::string_view rhs, int precision) const
  {
    const auto l = boost::lexical_cast<T>(lhs);
    const auto r = boost::lexical_cast<T>(rhs);
    return (boost::format("%.17f") % (l + r)).str();
  }
} boost_format;

struct
{
  template <typename Num>
  struct precision_policy : boost::spirit::karma::real_policies<Num>
  {
    precision_policy(int precision) : precision_{precision} {}
    unsigned precision(Num /*n*/) const { return precision_; }
    int precision_;
  };

  template <typename T = double>
  std::string operator()(std::string_view lhs, std::string_view rhs, int precision) const
  {
    const auto parse_double = [](std::string_view str, double &d)
    {
      namespace qi = boost::spirit::qi;

      using qi::double_;

      const auto action = [&d](double v)
      { d = v; };
      qi::parse(str.begin(), str.end(), double_[action]);
    };

    double l, r;
    parse_double(lhs, l);
    parse_double(rhs, r);

    namespace karma = boost::spirit::karma;
    using karma::double_;
    using precision_double_ =
        karma::real_generator<double, precision_policy<T>>;

    std::string res;
    karma::generate(std::back_inserter(res), precision_double_{precision}, l + r);
    return res;
  }
} qi_karma;

struct
{
  template <typename Num>
  struct precision_policy : boost::spirit::karma::real_policies<Num>
  {
    precision_policy(int precision) : precision_{precision} {}
    unsigned precision(Num /*n*/) const { return precision_; }
    int precision_;
  };

  template <typename T = double>
  std::string operator()(std::string_view lhs, std::string_view rhs, int precision) const
  {
    const auto parse_double = [](std::string_view str, double &d)
    {
      namespace x3 = boost::spirit::x3;

      using x3::double_;
      using x3::_attr;

      const auto action = [&d](auto &ctx)
      { d = _attr(ctx); };
      x3::parse(str.begin(), str.end(), double_[action]);
    };

    double l, r;
    parse_double(lhs, l);
    parse_double(rhs, r);

    namespace karma = boost::spirit::karma;
    using karma::double_;
    using precision_double_ =
        karma::real_generator<double, precision_policy<T>>;

    std::string res;
    karma::generate(std::back_inserter(res), precision_double_{precision}, l + r);
    return res;
  }
} x3_karma;

template <typename Converter>
struct convert_
{
  template <typename T = double>
  std::string operator()(std::string_view lhs, std::string_view rhs,
                         int precision)
  {
    Converter ccnv;
    namespace arg = boost::cnv::parameter;

    // https://github.com/boostorg/convert/issues/53
    using T_ = std::conditional_t<std::is_same_v<Converter, boost::cnv::printf>, float, double>;

    const auto l = boost::convert<T_>(lhs, ccnv).value();
    const auto r = boost::convert<T_>(rhs, ccnv).value();
    if constexpr (std::is_invocable_v<Converter, decltype(arg::precision)>)
    {
      return boost::convert<std::string>(l + r,
                                         ccnv(arg::precision = precision))
          .value();
    }
    else
    {
      return boost::convert<std::string>(l + r, ccnv).value();
    }
  }
};

template <typename Converter>
convert_<Converter> convert;

int main()
{
  static const int DEFAULT_PRECISION =
      std::numeric_limits<double>::max_digits10 + 1;

  auto test =
      [lhs = fmt::format("{:.{}f}", std::numbers::pi - 0.2, DEFAULT_PRECISION),
       rhs = fmt::format("{:.{}f}", 0.2, DEFAULT_PRECISION)](
          const std::string_view name, auto method)
  {
    fmt::print("{:25}", name);
    if constexpr (std::is_invocable_v<decltype(method), const char *,
                                      const char *, char *, int>)
    {
      constexpr int n = 1 /*'-'*/ +
                        (std::numeric_limits<double>::max_exponent10 +
                         1) /*exponent+1 digits*/
                        + 1 /*'.'*/ + DEFAULT_PRECISION /* precision*/ +
                        1 /*terminating null*/;
      char buf[n];
      method(lhs.c_str(), rhs.c_str(), buf, DEFAULT_PRECISION);
      fmt::print("{}\n", buf);
    }
    else
    {
      fmt::print("{}\n", method(lhs, rhs, DEFAULT_PRECISION));
    }
  };

  fmt::print("{:25}{:.{}f}\n", "π", std::numbers::pi, DEFAULT_PRECISION);
  test("lexical_cast", lexical_cast);
  test("boost_format", boost_format);
  test("qi_karma", qi_karma);
  test("x3_karma", x3_karma);
  test("convert<cstream>", convert<boost::cnv::cstream>);
  test("convert<strtol>", convert<boost::cnv::strtol>);
  test("convert<lexical_cast>", convert<boost::cnv::lexical_cast>);
  test("convert<printf>", convert<boost::cnv::printf>);
  test("convert<spirit>", convert<boost::cnv::spirit>);
}

max_stars_repo_name: dvirtz/slides

max_issues_repo_name: dvirtz/slides

max_forks_repo_name: dvirtz/slides


text:
#include <opencv2/core.hpp>
//#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/dnn.hpp>
#include <iostream>
#include <string>
#include <thread>
#include <array>

#include "Detector.hpp"
#include "Settings.hpp"
#include "PlayerTracker.hpp"

#include "websocket/server.hpp"

#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
namespace beast = boost::beast;         // from <boost/beast.hpp>
namespace http = beast::http;           // from <boost/beast/http.hpp>
namespace websocket = beast::websocket; // from <boost/beast/websocket.hpp>
using tcp = boost::asio::ip::tcp;       // from <boost/asio/ip/tcp.hpp>

void ChainDetector::Detector(ThreadStatus& threadStatus, cv::Mat& qtPreview, CaptureSettings& captureSettings)
{
    // Toggle thread status
    threadStatus.detectorClosed = false;

    cv::VideoCapture cap;
    cap.open(captureSettings.deviceID, captureSettings.mode);
    cap.set(cv::CAP_PROP_FRAME_HEIGHT, 270);
    cap.set(cv::CAP_PROP_FRAME_WIDTH, 480);

    if (!cap.isOpened())
    {
        std::cerr << "Couldn't open the capture feed.\n";
        threadStatus.captureFailed = true;
        threadStatus.detectorClosed = true;
        threadStatus.runDetector = false;
        return;
    }

    // Load MLP
    cv::dnn::Net net = cv::dnn::readNetFromONNX("puyo-mlp-gpu.onnx");

    // Set up player data. The Chain Detector writes to it; the websocket threads read from it
    PlayerTracker p0{ 0, net, captureSettings };
    PlayerTracker p1{ 1, net, captureSettings };
    std::array<BrowserSource::DataFields, 2> playerData;
    playerData.at(0) = BrowserSource::DataFields{ &(p0.m_lengthField), &(p0.m_popColors), &(p0.m_puyoField) };
    playerData.at(1) = BrowserSource::DataFields{ &(p1.m_lengthField), &(p1.m_popColors), &(p1.m_puyoField) };

    // Spawn a websocket service in another thread
    std::thread websocketThread = std::thread(&BrowserSource::waitForConnection, std::ref(threadStatus), std::ref(playerData) );

    // Initialize the mats the analysis will need
    cv::Mat frame;

    // Detection loop
    std::cout << "Beginning Detection loop...." << std::endl;
    while (threadStatus.runDetector)
    {
        // Receive current frame from capture device and resize it.
        cap >> frame;
        cv::resize(frame, frame, cv::Size(480, 270), 0, 0, cv::INTER_LINEAR);

        p0.update(frame);
        p1.update(frame);

        // Preview to show in the Qt App
        if (captureSettings.enablePreview)
        {
            frame.copyTo(qtPreview);
        }

        if (frame.empty())
        {
            std::cout << "Input data stream was empty. Aborting.\n";
            threadStatus.runDetector = false;
            break;
        }

        if (threadStatus.runDetector == false || threadStatus.runWebsocket == false)
        {
            break;
        }
    }
    // Don't need to run websockets anymore if detection loop is finished.
    threadStatus.runWebsocket = false;

    // Make a dummy connection to the websocket server just to get the acceptor to unblock lol.
    // I don't feel like figuring out async right now...
    // https://github1s.com/boostorg/beast/blob/HEAD/example/websocket/client/sync/websocket_client_sync.cpp
    std::string host = "127.0.0.1";
    std::string port = "2424";
    boost::asio::io_context ioc;
    tcp::resolver resolver{ ioc };
    websocket::stream<tcp::socket> ws{ ioc };
    auto const results = resolver.resolve(host, port);
    auto ep = boost::asio::connect(ws.next_layer(), results);
    host += ':' + std::to_string(ep.port());
    ws.set_option(websocket::stream_base::decorator(
        [](websocket::request_type& req)
        {
            req.set(http::field::user_agent,
                std::string(BOOST_BEAST_VERSION_STRING) +
                    " puyo-chain-detector");
        }));
    ws.handshake(host, "/");

    // Block until the websocket server is closed.
    websocketThread.join();

    std::cout << "Chain Detector closed." << std::endl;
    threadStatus.detectorClosed = true;
    return;
}

max_stars_repo_name: puyogg/puyo-chain-detector

max_issues_repo_name: puyogg/puyo-chain-detector

max_forks_repo_name: puyogg/puyo-chain-detector


text:
//          Copyright Carl Philipp Reh 2009 - 2016.
// 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)

#include <fcppt/make_ref.hpp>
#include <fcppt/make_unique_ptr.hpp>
#include <fcppt/reference_impl.hpp>
#include <fcppt/unique_ptr.hpp>
#include <fcppt/optional/maybe_void.hpp>
#include <fcppt/optional/object.hpp>
#include <fcppt/optional/output.hpp>
#include <fcppt/optional/reference.hpp>
#include <fcppt/preprocessor/disable_gcc_warning.hpp>
#include <fcppt/preprocessor/pop_warning.hpp>
#include <fcppt/preprocessor/push_warning.hpp>
#include <fcppt/config/external_begin.hpp>
#include <boost/test/unit_test.hpp>
#include <fcppt/config/external_end.hpp>

FCPPT_PP_PUSH_WARNING
FCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)

BOOST_AUTO_TEST_CASE(
	maybe_void
)
{
FCPPT_PP_POP_WARNING

	typedef
	fcppt::optional::object<
		int
	>
	optional_int;

	int result{
		0
	};

	fcppt::optional::maybe_void(
		optional_int(
			10
		),
		[
			&result
		](
			int const _val
		)
		{
			result =
				_val;
		}
	);

	BOOST_CHECK_EQUAL(
		result,
		10
	);

	fcppt::optional::maybe_void(
		optional_int(),
		[
			&result
		](
			int const _val
		)
		{
			result =
				_val;
		}
	);

	BOOST_CHECK_EQUAL(
		result,
		10
	);

	optional_int temp(
		0
	);

	fcppt::optional::maybe_void(
		temp,
		[](
			int &_val
		)
		{
			_val = 30;
		}
	);

	BOOST_CHECK_EQUAL(
		temp,
		optional_int(
			30
		)
	);
}

FCPPT_PP_PUSH_WARNING
FCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)

BOOST_AUTO_TEST_CASE(
	maybe_void_ref
)
{
FCPPT_PP_POP_WARNING

	int result{
		0
	};

	typedef
	fcppt::optional::reference<
		int
	>
	optional_int_ref;

	fcppt::optional::maybe_void(
		optional_int_ref{
			fcppt::make_ref(
				result
			)
		},
		[](
			fcppt::reference<
				int
			> const _val
		)
		{
			_val.get() = 42;
		}
	);

	BOOST_CHECK_EQUAL(
		result,
		42
	);
}

FCPPT_PP_PUSH_WARNING
FCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)

BOOST_AUTO_TEST_CASE(
	maybe_void_move
)
{
FCPPT_PP_POP_WARNING

	typedef
	fcppt::unique_ptr<
		int
	>
	int_unique_ptr;

	typedef
	fcppt::optional::object<
		int_unique_ptr
	>
	optional_int_unique_ptr;

	fcppt::optional::maybe_void(
		optional_int_unique_ptr(
			fcppt::make_unique_ptr<
				int
			>(
				42
			)
		),
		[](
			int_unique_ptr &&_ptr
		)
		{
			BOOST_CHECK_EQUAL(
				*_ptr,
				42
			);
		}
	);
}

max_stars_repo_name: vinzenz/fcppt

max_issues_repo_name: vinzenz/fcppt

max_forks_repo_name: vinzenz/fcppt