text:
//Copyright (c) 2008-2016 Emil Dotchevski and Reverge Studios, Inc.

//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 <boost/qvm/vec_traits_array.hpp>
#include <boost/qvm/vec_operations.hpp>
#include <boost/detail/lightweight_test.hpp>

template <class T,class U>
struct same_type;

template <class T>
struct
same_type<T,T>
    {
    };

template <class T,class P>
void
test_ref_cast( T & v, P * ptr )
    {
    using namespace boost::qvm;
    BOOST_QVM_STATIC_ASSERT(is_vec<T>::value);
    BOOST_QVM_STATIC_ASSERT(vec_traits<T>::dim==3);
    BOOST_TEST(vec_traits<T>::template read_element<0>(v)==ptr[0]);
    BOOST_TEST(vec_traits<T>::template read_element<1>(v)==ptr[1]);
    BOOST_TEST(vec_traits<T>::template read_element<2>(v)==ptr[2]);
    BOOST_TEST(&vec_traits<T>::template write_element<0>(v)==&ptr[0]);
    BOOST_TEST(&vec_traits<T>::template write_element<1>(v)==&ptr[1]);
    BOOST_TEST(&vec_traits<T>::template write_element<2>(v)==&ptr[2]);
    BOOST_TEST(&v[0]==&ptr[0]);
    BOOST_TEST(&v[1]==&ptr[1]);
    BOOST_TEST(&v[2]==&ptr[2]);
    }

int
main()
    {
    using namespace boost::qvm;
        {
        BOOST_QVM_STATIC_ASSERT(is_vec<int[3]>::value);
        BOOST_QVM_STATIC_ASSERT(!is_vec<int[3][3]>::value);
        BOOST_QVM_STATIC_ASSERT(!is_vec<int[3][3][3]>::value);
        BOOST_QVM_STATIC_ASSERT((vec_traits<int[3]>::dim==3));
        same_type<vec_traits<int[3]>::scalar_type,int>();
        same_type< vec<int,3>, deduce_vec<int[3]>::type >();
        same_type< vec<int,3>, deduce_vec<int const[3]>::type >();
        int arr[3] = {0,1,2};
        BOOST_TEST((vec_traits<int[3]>::read_element<0>(arr)==0));
        BOOST_TEST((vec_traits<int[3]>::read_element<1>(arr)==1));
        BOOST_TEST((vec_traits<int[3]>::read_element<2>(arr)==2));
        BOOST_TEST((vec_traits<int const[3]>::read_element<0>(arr)==0));
        BOOST_TEST((vec_traits<int const[3]>::read_element<1>(arr)==1));
        BOOST_TEST((vec_traits<int const[3]>::read_element<2>(arr)==2));
        BOOST_TEST((vec_traits<int[3]>::read_element_idx(0,arr)==0));
        BOOST_TEST((vec_traits<int[3]>::read_element_idx(1,arr)==1));
        BOOST_TEST((vec_traits<int[3]>::read_element_idx(2,arr)==2));
        BOOST_TEST((vec_traits<int const[3]>::read_element_idx(0,arr)==0));
        BOOST_TEST((vec_traits<int const[3]>::read_element_idx(1,arr)==1));
        BOOST_TEST((vec_traits<int const[3]>::read_element_idx(2,arr)==2));
        BOOST_TEST((&vec_traits<int[3]>::write_element<0>(arr)==&arr[0]));
        BOOST_TEST((&vec_traits<int[3]>::write_element<1>(arr)==&arr[1]));
        BOOST_TEST((&vec_traits<int[3]>::write_element<2>(arr)==&arr[2]));
        BOOST_TEST((&vec_traits<int[3]>::write_element_idx(0,arr)==&arr[0]));
        BOOST_TEST((&vec_traits<int[3]>::write_element_idx(1,arr)==&arr[1]));
        BOOST_TEST((&vec_traits<int[3]>::write_element_idx(2,arr)==&arr[2]));
        }
        {
        int arr[42] = {0};
        int * ptr=arr+5;
        ptr[0]=42;
        ptr[1]=43;
        ptr[2]=44;
        test_ref_cast(ptr_vref<3>(ptr),ptr);
        int v[3] = {1,1,1};
        ptr_vref<3>(ptr) += vref(v);
        BOOST_TEST(ptr[0]==43);
        BOOST_TEST(ptr[1]==44);
        BOOST_TEST(ptr[2]==45);
        }
    return boost::report_errors();
    }

max_issues_repo_name: lipper/arangodb

max_forks_repo_name: lipper/arangodb


text:
// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <boost/thread.hpp>
#include <memory>
#include <string>
#include <vector>

#include "SurgSim/DataStructures/DataGroup.h"
#include "SurgSim/DataStructures/Image.h"
#include "SurgSim/Devices/OpenNI/OpenNIDevice.h"
#include "SurgSim/Framework/LockedContainer.h"
#include "SurgSim/Input/DeviceInterface.h"
#include "SurgSim/Math/Vector.h"
#include "SurgSim/Testing/VisualTestCommon/GlutRenderer.h"

using SurgSim::Devices::OpenNIDevice;
using SurgSim::Input::DeviceInterface;
using SurgSim::Math::Vector3d;

class ImageGlutWindow : public SurgSim::Input::InputConsumerInterface
{
public:
	explicit ImageGlutWindow(const std::vector<std::string>& imageNames)
	{
		const size_t numImages = imageNames.size();
		const SurgSim::Math::Vector2d yRange(-1.0, 1.0);
		SurgSim::Math::Vector2d xRange;
		for (size_t i = 0; i < numImages; i++)
		{
			xRange = SurgSim::Math::Vector2d(i - numImages, i - numImages + 1) / numImages;
			auto view = std::make_shared<GlutImage>(Eigen::AlignedBox<double, 2>(xRange, yRange));
			GlutRenderer::addObject(view);
			m_views.insert(std::make_pair(imageNames[i], view));
		}
		m_renderThread = boost::thread(boost::ref(GlutRenderer::run));
	}

	~ImageGlutWindow()
	{
		if (m_renderThread.joinable())
		{
			m_renderThread.join();
		}
	}

	void initializeInput(const std::string& device, const SurgSim::DataStructures::DataGroup& inputData) override
	{
		for (auto view : m_views)
		{
			SURGSIM_ASSERT(inputData.images().hasEntry(view.first))
				<< "No image named '" << view.first << "' provided by the device: " << device;
		}
	}

	void handleInput(const std::string& device, const SurgSim::DataStructures::DataGroup& inputData) override
	{
		SurgSim::DataStructures::DataGroup::ImageType data;
		for (auto view : m_views)
		{
			if(inputData.images().get(view.first, &data))
			{
				view.second->image.set(std::move(data));
			}
		}
	}

private:
	boost::thread m_renderThread;
	std::unordered_map<std::string, std::shared_ptr<GlutImage>> m_views;
};

int main(int argc, char** argv)
{
	std::shared_ptr<DeviceInterface> device = std::make_shared<OpenNIDevice>("OpenNIDevice");
	if (!device->initialize())
	{
		std::cout << std::endl << "Could not initialize device: " << device->getName()
			<< std::endl << "--- Press Enter to quit the application! ---" << std::endl;
		getc(stdin);
		return 1;
	}

	std::vector<std::string> imagesToDraw;
	imagesToDraw.push_back("color");
	imagesToDraw.push_back("depth");
	std::shared_ptr<ImageGlutWindow> imageWindow = std::make_shared<ImageGlutWindow>(imagesToDraw);
	device->addInputConsumer(imageWindow);

	std::cout << std::endl << "**********************************************************************" << std::endl
		<< "OpenNI Visual Test" << std::endl << std::endl
		<< "When done, press Enter to quit the application." << std::endl
		<< "**********************************************************************" << std::endl;
	getc(stdin);

	std::cout << "Exiting..." << std::endl;
	device->removeInputConsumer(imageWindow);
	device.reset();
	exit(0);
}

ext: cpp

max_stars_repo_name: dbungert/opensurgsim

max_issues_repo_name: dbungert/opensurgsim

max_forks_repo_name: dbungert/opensurgsim


text:
// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt
/*

    This example illustrates the use of the HTTP extension to the server object
    from the dlib C++ Library.
    It creates a server that always responds with a simple HTML form.

    To view the page this program displays you should go to http://localhost:5000

*/

#include <iostream>
#include <sstream>
#include <string>
#include <dlib/server.h>

using namespace dlib;
using namespace std;

class web_server : public server_http
{
    const std::string on_request (
        const incoming_things& incoming,
        outgoing_things& outgoing
    )
    {
        ostringstream sout;
        // We are going to send back a page that contains an HTML form with two text input fields.
        // One field called name.  The HTML form uses the post method but could also use the get
        // method (just change method='post' to method='get').
        sout << "   "
            << "<form action='/form_handler' method='post'> "
            << "User Name: <input name='user' type='text'>
  "
            << "User password: <input name='pass' type='text'> <input type='submit'> "
            << " </form>";

        // Write out some of the inputs to this request so that they show up on the
        // resulting web page.
        sout << "
  path = "         << incoming.path << endl;
        sout << "
  request_type = " << incoming.request_type << endl;
        sout << "
  content_type = " << incoming.content_type << endl;
        sout << "
  protocol = "     << incoming.protocol << endl;
        sout << "
  foreign_ip = "   << incoming.foreign_ip << endl;
        sout << "
  foreign_port = " << incoming.foreign_port << endl;
        sout << "
  local_ip = "     << incoming.local_ip << endl;
        sout << "
  local_port = "   << incoming.local_port << endl;
        sout << "
  body = \""       << incoming.body << "\"" << endl;

        // If this request is the result of the user submitting the form then echo back
        // the submission.
        if (incoming.path == "/form_handler")
        {
            sout << "
 Stuff from the query string
" << endl;
            sout << "
  user = " << incoming.queries["user"] << endl;
            sout << "
  pass = " << incoming.queries["pass"] << endl;

            // save these form submissions as cookies.
            outgoing.cookies["user"] = incoming.queries["user"];
            outgoing.cookies["pass"] = incoming.queries["pass"];
        }

        // Echo any cookies back to the client browser
        sout << "
Cookies the web browser sent to the server
";
        for ( key_value_map::const_iterator ci = incoming.cookies.begin(); ci != incoming.cookies.end(); ++ci )
        {
            sout << "
" << ci->first << " = " << ci->second << endl;
        }

        sout << "

";

        sout << "
HTTP Headers the web browser sent to the server
";
        // Echo out all the HTTP headers we received from the client web browser
        for ( key_value_map_ci::const_iterator ci = incoming.headers.begin(); ci != incoming.headers.end(); ++ci )
        {
            sout << "
" << ci->first << ": " << ci->second << endl;
        }

        sout << " ";

        return sout.str();
    }

};

#if defined(BUILD_MONOLITHIC)
#define main(cnt, arr)      dlib_server_http_ex_main(cnt, arr)
#endif

int main(int argc, const char** argv)
{
    try
    {
        // create an instance of our web server
        web_server our_web_server;

        // make it listen on port 5000
        our_web_server.set_listening_port(5000);
        // Tell the server to begin accepting connections.
        our_web_server.start_async();

        cout << "Press enter to end this program" << endl;
        cin.get();
    }
    catch (exception& e)
    {
        cout << e.what() << endl;
    }
}

max_stars_repo_name: GerHobbelt/dlib

max_issues_repo_name: GerHobbelt/dlib

max_forks_repo_name: GerHobbelt/dlib


text:
#include <deip/protocol/config.hpp>
#include <deip/chain/database/database.hpp>
#include <deip/chain/operation_notification.hpp>
#include <deip/chain/services/dbs_research.hpp>
#include <deip/investments_history/investments_history_api.hpp>
#include <deip/investments_history/investments_history_plugin.hpp>
#include <deip/investments_history/account_revenue_income_history_object.hpp>

#include <fc/smart_ref_impl.hpp>
#include <fc/thread/thread.hpp>

#include <boost/algorithm/string.hpp>

namespace deip {
namespace investments_history {

using namespace deip::protocol;
using namespace deip::chain;

namespace detail {

class investments_history_plugin_impl
{
public:
    investments_history_plugin_impl(investments_history_plugin& _plugin)
        : _self(_plugin)
    {
    }

    virtual ~investments_history_plugin_impl()
    {
    }

    deip::chain::database& database()
    {
        return _self.database();
    }

    void pre_operation(const operation_notification& op_obj);
    void post_operation(const operation_notification& op_obj);

    investments_history_plugin& _self;
};

struct post_operation_visitor
{
    investments_history_plugin& _plugin;

    post_operation_visitor(investments_history_plugin& plugin)
        : _plugin(plugin)
    {
    }

    typedef void result_type;

    template <typename T> void operator()(const T&) const
    {
    }

    void operator()(const account_revenue_income_history_operation& op) const
    {
        _plugin.database().create<account_revenue_income_history_object>([&](account_revenue_income_history_object& hist_o) {
               hist_o.account = op.account;
               hist_o.security_token_symbol = op.security_token.symbol;
               hist_o.security_token = op.security_token;
               hist_o.revenue = op.revenue;
               hist_o.timestamp = op.timestamp;
        });
    }

};

void investments_history_plugin_impl::pre_operation(const operation_notification& note)
{
}

void investments_history_plugin_impl::post_operation(const operation_notification& note)
{
    note.op.visit(post_operation_visitor(_self));
}

} // end namespace detail

investments_history_plugin::investments_history_plugin(application* app)
    : plugin(app)
    , my(new detail::investments_history_plugin_impl(*this))
{
    ilog("Loading Investments history plugin");
}

investments_history_plugin::~investments_history_plugin()
{
}

std::string investments_history_plugin::plugin_name() const
{
    return INVESTMENTS_HISTORY_PLUGIN_NAME;
}

void investments_history_plugin::plugin_set_program_options(boost::program_options::options_description& cli, boost::program_options::options_description& cfg)
{

}

void investments_history_plugin::plugin_initialize(const boost::program_options::variables_map& options)
{
    ilog("Intializing Investemnts history plugin");

    chain::database& db = database();

    db.add_plugin_index<account_revenue_income_history_index>();

    db.pre_apply_operation.connect([&](const operation_notification& note) { my->pre_operation(note); });
    db.post_apply_operation.connect([&](const operation_notification& note) { my->post_operation(note); });
}

void investments_history_plugin::plugin_startup()
{
    ilog("investments_history plugin: plugin_startup() begin");
    app().register_api_factory<investments_history_api>("investments_history_api");
    ilog("investments_history plugin: plugin_startup() end");
}

} // namespace investments_history
} // namespace deip

DEIP_DEFINE_PLUGIN(investments_history, deip::investments_history::investments_history_plugin)

max_stars_repo_name: DEIPworld/deip-chain

max_issues_repo_name: DEIPworld/deip-chain

max_forks_repo_name: DEIPworld/deip-chain


text:
/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <iterator>
#include <string>
#include <utility>

#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/filesystem.hpp>

#include <thrift/compiler/ast/t_service.h>
#include <thrift/compiler/generate/common.h>
#include <thrift/compiler/generate/t_mstch_generator.h>
#include <thrift/compiler/generate/t_mstch_objects.h>
#include <thrift/compiler/lib/cpp2/util.h>
#include <thrift/compiler/lib/py3/util.h>

namespace apache {
namespace thrift {
namespace compiler {

namespace {

std::vector<std::string> get_py3_namespace(const t_program* prog) {
  return split_namespace(prog->get_namespace("py3"));
}

std::string get_py3_namespace_with_name_and_prefix(
    const t_program* prog, const std::string& prefix) {
  std::ostringstream ss;
  if (!prefix.empty()) {
    ss << prefix << ".";
  }
  for (const auto& name : split_namespace(prog->get_namespace("py3"))) {
    ss << name << ".";
  }
  ss << prog->name();
  return ss.str();
}

bool is_type_iobuf(const std::string& name) {
  return name == "folly::IOBuf" || name == "std::unique_ptr<folly::IOBuf>";
}

bool is_func_supported(const t_function* func) {
  return !func->returns_stream() && !func->returns_sink() &&
      !func->get_returntype()->is_service();
}

class mstch_py3lite_type : public mstch_type {
 public:
  mstch_py3lite_type(
      const t_type* type,
      std::shared_ptr<const mstch_generators> generators,
      std::shared_ptr<mstch_cache> cache,
      ELEMENT_POSITION pos,
      const t_program* prog)
      : mstch_type(type, std::move(generators), std::move(cache), pos),
        prog_{prog} {
    register_methods(
        this,
        {
            {"type:module_path", &mstch_py3lite_type::module_path},
            {"type:py3_namespace", &mstch_py3lite_type::py3_namespace},
            {"type:need_module_path?", &mstch_py3lite_type::need_module_path},
            {"type:external_program?",
             &mstch_py3lite_type::is_external_program},
            {"type:integer?", &mstch_py3lite_type::is_integer},
            {"type:iobuf?", &mstch_py3lite_type::is_iobuf},
        });
  }

  mstch::node module_path() {
    return get_py3_namespace_with_name_and_prefix(
               get_type_program(), get_option("root_module_prefix")) +
        ".lite_types";
  }

  mstch::node py3_namespace() {
    std::ostringstream ss;
    for (const auto& path : get_py3_namespace(get_type_program())) {
      ss << path << ".";
    }
    return ss.str();
  }

  mstch::node need_module_path() {
    if (!has_option("is_types_file")) {
      return true;
    }
    if (const t_program* prog = type_->program()) {
      if (prog != prog_) {
        return true;
      }
    }
    return false;
  }

  mstch::node is_external_program() {
    auto p = type_->program();
    return p && p != prog_;
  }

  mstch::node is_integer() { return type_->is_any_int() || type_->is_byte(); }

  // Supporting legacy py3 cpp.type iobuf declaration here
  mstch::node is_iobuf() {
    return type_->has_annotation("py3.iobuf") ||
        is_type_iobuf(type_->get_annotation("cpp2.type")) ||
        is_type_iobuf(type_->get_annotation("cpp.type"));
  }

 protected:
  const t_program* get_type_program() const {
    if (const t_program* p = type_->program()) {
      return p;
    }
    return prog_;
  }

  const t_program* prog_;
};

class mstch_py3lite_const_value : public mstch_const_value {
 public:
  mstch_py3lite_const_value(
      t_const_value const* const_value,
      t_const const* current_const,
      t_type const* expected_type,
      std::shared_ptr<mstch_generators const> generators,
      std::shared_ptr<mstch_cache> cache,
      ELEMENT_POSITION pos,
      int32_t index)
      : mstch_const_value(
            const_value,
            current_const,
            expected_type,
            std::move(generators),
            std::move(cache),
            pos,
            index) {
    register_methods(
        this,
        {
            {"value:py3_string_value",
             &mstch_py3lite_const_value::string_value},
            {"value:py3_string?", &mstch_py3lite_const_value::is_string},
            {"value:py3_binary?", &mstch_py3lite_const_value::is_binary},
            {"value:const_enum_type",
             &mstch_py3lite_const_value::const_enum_type},
            {"value:value_for_bool?",
             &mstch_py3lite_const_value::value_for_bool},
            {"value:value_for_floating_point?",
             &mstch_py3lite_const_value::value_for_floating_point},
            {"value:list_elem_type",
             &mstch_py3lite_const_value::list_elem_type},
            {"value:value_for_set?", &mstch_py3lite_const_value::value_for_set},
            {"value:map_key_type", &mstch_py3lite_const_value::map_key_type},
            {"value:map_val_type", &mstch_py3lite_const_value::map_val_type},
        });
  }
  mstch::node is_string() {
    auto& ttype = const_value_->ttype();
    return type_ == cv::CV_STRING && ttype &&
        ttype->deref().get_true_type()->is_string();
  }

  mstch::node is_binary() {
    auto& ttype = const_value_->ttype();
    return type_ == cv::CV_STRING && ttype &&
        ttype->deref().get_true_type()->is_binary();
  }

  mstch::node const_enum_type() {
    if (!const_value_->ttype() || type_ != cv::CV_INTEGER ||
        !const_value_->is_enum()) {
      return {};
    }
    const auto* type = const_value_->ttype()->deref().get_true_type();
    if (type->is_enum()) {
      return generators_->type_generator_->generate(type, generators_, cache_);
    }
    return {};
  }

  mstch::node value_for_bool() {
    if (auto ttype = const_value_->ttype()) {
      return ttype->deref().get_true_type()->is_bool();
    }
    return false;
  }

  mstch::node value_for_floating_point() {
    if (auto ttype = const_value_->ttype()) {
      return ttype->deref().get_true_type()->is_floating_point();
    }
    return false;
  }

  mstch::node string_value() {
    if (type_ != cv::CV_STRING) {
      return mstch::node();
    }
    std::string string_val = const_value_->get_string();
    if (string_val.find('\n') == std::string::npos) {
      if (string_val.find('"') == std::string::npos) {
        return "\"" + string_val + "\"";
      }
      if (string_val.find('\'') == std::string::npos) {
        return "'" + string_val + "'";
      }
    }
    const auto& front = string_val.front();
    const auto& back = string_val.back();

    if (front != '"' && back != '"') {
      return "\"\"\"" + string_val + "\"\"\"";
    }
    if (front != '\'' && back != '\'') {
      return "'''" + string_val + "'''";
    }
    if (front == '"') { // and back = '\''
      string_val.pop_back(); // remove the last '\''
      return "'''" + string_val + "'''\"'\"";
    }
    // the only possible case left: back = '"' and front = '\''
    string_val.pop_back(); // remove the last '"'
    return "\"\"\"" + string_val + "\"\"\"'\"'";
  }

  mstch::node list_elem_type() {
    if (auto ttype = const_value_->ttype()) {
      const auto* type = ttype->deref().get_true_type();
      const t_type* elem_type = nullptr;
      if (type->is_list()) {
        elem_type = dynamic_cast<const t_list*>(type)->get_elem_type();
      } else if (type->is_set()) {
        elem_type = dynamic_cast<const t_set*>(type)->get_elem_type();
      } else {
        return {};
      }
      return generators_->type_generator_->generate(
          elem_type, generators_, cache_, pos_);
    }
    return {};
  }

  mstch::node value_for_set() {
    if (auto ttype = const_value_->ttype()) {
      return ttype->deref().get_true_type()->is_set();
    }
    return false;
  }

  mstch::node map_key_type() {
    if (auto ttype = const_value_->ttype()) {
      const auto* type = ttype->deref().get_true_type();
      if (type->is_map()) {
        return generators_->type_generator_->generate(
            dynamic_cast<const t_map*>(type)->get_key_type(),
            generators_,
            cache_,
            pos_);
      }
    }
    return {};
  }

  mstch::node map_val_type() {
    if (auto ttype = const_value_->ttype()) {
      const auto* type = ttype->deref().get_true_type();
      if (type->is_map()) {
        return generators_->type_generator_->generate(
            dynamic_cast<const t_map*>(type)->get_val_type(),
            generators_,
            cache_,
            pos_);
      }
    }
    return {};
  }
};

class type_py3lite_generator : public type_generator {
 public:
  explicit type_py3lite_generator(const t_program* prog) : prog_{prog} {}
  std::shared_ptr<mstch_base> generate(
      const t_type* type,
      std::shared_ptr<const mstch_generators> generators,
      std::shared_ptr<mstch_cache> cache,
      ELEMENT_POSITION pos,
      int32_t /*index*/) const override {
    auto true_type = type->get_true_type();
    return std::make_shared<mstch_py3lite_type>(
        true_type, generators, cache, pos, prog_);
  }

 protected:
  const t_program* prog_;
};

class mstch_py3lite_program : public mstch_program {
 public:
  mstch_py3lite_program(
      const t_program* program,
      std::shared_ptr<const mstch_generators> generators,
      std::shared_ptr<mstch_cache> cache,
      ELEMENT_POSITION pos)
      : mstch_program{program, std::move(generators), std::move(cache), pos} {
    register_methods(
        this,
        {
            {"program:module_path", &mstch_py3lite_program::module_path},
            {"program:is_types_file?", &mstch_py3lite_program::is_types_file},
            {"program:include_namespaces",
             &mstch_py3lite_program::include_namespaces},
            {"program:base_library_package",
             &mstch_py3lite_program::base_library_package},
        });
    gather_included_program_namespaces();
    visit_types_for_services_and_interactions();
    visit_types_for_objects();
    visit_types_for_constants();
    visit_types_for_typedefs();
    visit_types_for_mixin_fields();
  }

  mstch::node is_types_file() { return has_option("is_types_file"); }

  mstch::node include_namespaces() {
    mstch::array a;
    for (auto& it : include_namespaces_) {
      a.push_back(mstch::map{
          {"included_module_path", it.second.ns},
          {"has_services?", it.second.has_services},
          {"has_types?", it.second.has_types}});
    }
    return a;
  }

  mstch::node module_path() {
    return get_py3_namespace_with_name_and_prefix(
        program_, get_option("root_module_prefix"));
  }

  mstch::node base_library_package() {
    auto option = get_option("base_library_package");
    return option.empty() ? "thrift.py3lite" : option;
  }

 protected:
  struct Namespace {
    std::string ns;
    bool has_services;
    bool has_types;
  };

  void gather_included_program_namespaces() {
    for (const t_program* included_program :
         program_->get_included_programs()) {
      bool has_types =
          !(included_program->objects().empty() &&
            included_program->enums().empty() &&
            included_program->typedefs().empty() &&
            included_program->consts().empty());
      include_namespaces_[included_program->path()] = Namespace{
          get_py3_namespace_with_name_and_prefix(
              included_program, get_option("root_module_prefix")),
          !included_program->services().empty(),
          has_types,
      };
    }
  }

  void add_typedef_namespace(const t_type* type) {
    auto prog = type->program();
    if (prog && prog != program_) {
      const auto& path = prog->path();
      if (include_namespaces_.find(path) != include_namespaces_.end()) {
        return;
      }
      auto ns = Namespace();
      ns.ns = get_py3_namespace_with_name_and_prefix(
          prog, get_option("root_module_prefix"));
      ns.has_services = false;
      ns.has_types = true;
      include_namespaces_[path] = std::move(ns);
    }
  }

  void visit_type_single_service(const t_service* service) {
    for (const auto& function : service->functions()) {
      for (const auto& field : function.get_paramlist()->fields()) {
        visit_type(field.get_type());
      }
      for (const auto& field : function.get_stream_xceptions()->fields()) {
        visit_type(field.get_type());
      }
      visit_type(function.get_returntype());
    }
  }

  void visit_types_for_services_and_interactions() {
    for (const auto* service : program_->services()) {
      visit_type_single_service(service);
    }
    for (const auto* interaction : program_->interactions()) {
      visit_type_single_service(interaction);
    }
  }

  void visit_types_for_objects() {
    for (const auto& object : program_->objects()) {
      for (auto&& field : object->fields()) {
        visit_type(field.get_type());
      }
    }
  }

  void visit_types_for_constants() {
    for (const auto& constant : program_->consts()) {
      visit_type(constant->get_type());
    }
  }

  void visit_types_for_typedefs() {
    for (const auto typedef_def : program_->typedefs()) {
      visit_type(typedef_def->get_type());
    }
  }

  void visit_types_for_mixin_fields() {
    for (const auto& strct : program_->structs()) {
      for (const auto& m : cpp2::get_mixins_and_members(*strct)) {
        visit_type(m.member->get_type());
      }
    }
  }
  enum TypeDef { NoTypedef, HasTypedef };

  void visit_type(const t_type* orig_type) {
    return visit_type_with_typedef(orig_type, TypeDef::NoTypedef);
  }

  void visit_type_with_typedef(const t_type* orig_type, TypeDef is_typedef) {
    auto true_type = orig_type->get_true_type();
    if (!seen_types_.insert(true_type).second) {
      return;
    }
    is_typedef = is_typedef == TypeDef::HasTypedef || orig_type->is_typedef()
        ? TypeDef::HasTypedef
        : TypeDef::NoTypedef;
    if (is_typedef == TypeDef::HasTypedef) {
      add_typedef_namespace(true_type);
    }
    if (true_type->is_list()) {
      visit_type_with_typedef(
          dynamic_cast<const t_list&>(*true_type).get_elem_type(), is_typedef);
    } else if (true_type->is_set()) {
      visit_type_with_typedef(
          dynamic_cast<const t_set&>(*true_type).get_elem_type(), is_typedef);
    } else if (true_type->is_map()) {
      visit_type_with_typedef(
          dynamic_cast<const t_map&>(*true_type).get_key_type(), is_typedef);
      visit_type_with_typedef(
          dynamic_cast<const t_map&>(*true_type).get_val_type(), is_typedef);
    } else if (true_type->is_streamresponse()) {
      const t_type* resp_type =
          dynamic_cast<const t_stream_response&>(*true_type)
              .get_first_response_type();
      const t_type* elem_type =
          dynamic_cast<const t_stream_response&>(*true_type).get_elem_type();
      if (resp_type) {
        visit_type_with_typedef(resp_type, is_typedef);
      }
      visit_type_with_typedef(elem_type, is_typedef);
    }
  }

  std::map<std::string, Namespace> include_namespaces_;
  std::unordered_set<const t_type*> seen_types_;
};

class mstch_py3lite_field : public mstch_field {
 public:
  mstch_py3lite_field(
      const t_field* field,
      std::shared_ptr<const mstch_generators> generators,
      std::shared_ptr<mstch_cache> cache,
      ELEMENT_POSITION pos,
      int32_t index,
      field_generator_context const* field_context)
      : mstch_field(
            field,
            std::move(generators),
            std::move(cache),
            pos,
            index,
            field_context),
        py_name_{py3::get_py3_name(*field)} {
    register_methods(
        this,
        {
            {"field:py_name", &mstch_py3lite_field::py_name},
        });
  }

  mstch::node py_name() { return py_name_; }

 private:
  const std::string py_name_;
};

class mstch_py3lite_struct : public mstch_struct {
 public:
  mstch_py3lite_struct(
      const t_struct* strct,
      std::shared_ptr<const mstch_generators> generators,
      std::shared_ptr<mstch_cache> cache,
      ELEMENT_POSITION pos)
      : mstch_struct(strct, std::move(generators), std::move(cache), pos) {
    register_methods(
        this,
        {
            {"struct:fields_and_mixin_fields",
             &mstch_py3lite_struct::fields_and_mixin_fields},
            {"struct:exception_message?",
             &mstch_py3lite_struct::has_exception_message},
            {"struct:exception_message",
             &mstch_py3lite_struct::exception_message},
        });
  }

  mstch::node fields_and_mixin_fields() {
    std::vector<t_field const*> fields = strct_->fields().copy();
    for (auto m : cpp2::get_mixins_and_members(*strct_)) {
      fields.push_back(m.member);
    }
    return generate_fields(fields);
  }

  mstch::node has_exception_message() {
    return strct_->has_annotation("message");
  }
  mstch::node exception_message() { return strct_->get_annotation("message"); }
};

class mstch_py3lite_enum : public mstch_enum {
 public:
  mstch_py3lite_enum(
      const t_enum* enm,
      std::shared_ptr<const mstch_generators> generators,
      std::shared_ptr<mstch_cache> cache,
      ELEMENT_POSITION pos)
      : mstch_enum(enm, std::move(generators), std::move(cache), pos) {
    register_methods(
        this,
        {
            {"enum:flags?", &mstch_py3lite_enum::has_flags},
        });
  }

  mstch::node has_flags() { return enm_->has_annotation("py3.flags"); }
};

class mstch_py3lite_enum_value : public mstch_enum_value {
 public:
  mstch_py3lite_enum_value(
      const t_enum_value* enm_value,
      std::shared_ptr<const mstch_generators> generators,
      std::shared_ptr<mstch_cache> cache,
      ELEMENT_POSITION pos)
      : mstch_enum_value(
            enm_value, std::move(generators), std::move(cache), pos) {
    register_methods(
        this,
        {
            {"enum_value:py_name", &mstch_py3lite_enum_value::py_name},
        });
  }

  mstch::node py_name() { return py3::get_py3_name(*enm_value_); }
};

class program_py3lite_generator : public program_generator {
 public:
  std::shared_ptr<mstch_base> generate(
      const t_program* program,
      std::shared_ptr<const mstch_generators> generators,
      std::shared_ptr<mstch_cache> cache,
      ELEMENT_POSITION pos,
      int32_t /*index*/) const override {
    const std::string& id = program->path();
    auto it = cache->programs_.find(id);
    if (it != cache->programs_.end()) {
      return it->second;
    }
    auto r = cache->programs_.emplace(
        id,
        std::make_shared<mstch_py3lite_program>(
            program, generators, cache, pos));
    return r.first->second;
  }
};

class struct_py3lite_generator : public struct_generator {
 public:
  std::shared_ptr<mstch_base> generate(
      const t_struct* strct,
      std::shared_ptr<const mstch_generators> generators,
      std::shared_ptr<mstch_cache> cache,
      ELEMENT_POSITION pos,
      int32_t /*index*/) const override {
    return std::make_shared<mstch_py3lite_struct>(
        strct, generators, cache, pos);
  }
};

class mstch_py3lite_function : public mstch_function {
 public:
  mstch_py3lite_function(
      t_function const* function,
      std::shared_ptr<mstch_generators const> generators,
      std::shared_ptr<mstch_cache> cache,
      ELEMENT_POSITION const pos)
      : mstch_function(function, generators, cache, pos) {
    register_methods(
        this,
        {
            {"function:args?", &mstch_py3lite_function::has_args},
        });
  }

  mstch::node has_args() {
    return !function_->get_paramlist()->get_members().empty();
  }

 protected:
  const std::string cppName_;
};

class function_py3lite_generator : public function_generator {
 public:
  function_py3lite_generator() = default;
  ~function_py3lite_generator() override = default;
  std::shared_ptr<mstch_base> generate(
      t_function const* function,
      std::shared_ptr<mstch_generators const> generators,
      std::shared_ptr<mstch_cache> cache,
      ELEMENT_POSITION pos,
      int32_t /*index*/) const override {
    return std::make_shared<mstch_py3lite_function>(
        function, generators, cache, pos);
  }
};

class mstch_py3lite_service : public mstch_service {
 public:
  mstch_py3lite_service(
      const t_service* service,
      std::shared_ptr<const mstch_generators> generators,
      std::shared_ptr<mstch_cache> cache,
      ELEMENT_POSITION const pos,
      const t_program* prog)
      : mstch_service(service, generators, cache, pos), prog_{prog} {
    register_methods(
        this,
        {
            {"service:module_path", &mstch_py3lite_service::module_path},
            {"service:program_name", &mstch_py3lite_service::program_name},
            {"service:parent_service_name",
             &mstch_py3lite_service::parent_service_name},
            {"service:supported_functions",
             &mstch_py3lite_service::supported_functions},
            {"service:supported_functions?",
             &mstch_py3lite_service::has_supported_functions},
            {"service:external_program?",
             &mstch_py3lite_service::is_external_program},
        });
  }

  mstch::node module_path() {
    return get_py3_namespace_with_name_and_prefix(
        service_->program(), get_option("root_module_prefix"));
  }

  mstch::node program_name() { return service_->program()->name(); }

  mstch::node parent_service_name() {
    return cache_->parsed_options_.at("parent_service_name");
  }

  std::vector<t_function*> get_supported_functions() {
    std::vector<t_function*> funcs;
    for (auto func : service_->get_functions()) {
      if (is_func_supported(func)) {
        funcs.push_back(func);
      }
    }
    return funcs;
  }

  mstch::node supported_functions() {
    return generate_functions(get_supported_functions());
  }

  mstch::node has_supported_functions() {
    return !get_supported_functions().empty();
  }

  mstch::node is_external_program() { return prog_ != service_->program(); }

 protected:
  const t_program* prog_;
};

class service_py3lite_generator : public service_generator {
 public:
  explicit service_py3lite_generator(const t_program* prog) : prog_{prog} {}
  std::shared_ptr<mstch_base> generate(
      const t_service* service,
      std::shared_ptr<const mstch_generators> generators,
      std::shared_ptr<mstch_cache> cache,
      ELEMENT_POSITION pos,
      int32_t /*index*/) const override {
    return std::make_shared<mstch_py3lite_service>(
        service, generators, cache, pos, prog_);
  }

 protected:
  const t_program* prog_;
};

class field_py3lite_generator : public field_generator {
 public:
  std::shared_ptr<mstch_base> generate(
      const t_field* field,
      std::shared_ptr<const mstch_generators> generators,
      std::shared_ptr<mstch_cache> cache,
      ELEMENT_POSITION pos,
      int32_t index,
      field_generator_context const* field_context) const override {
    return std::make_shared<mstch_py3lite_field>(
        field, generators, cache, pos, index, field_context);
  }
};

class enum_py3lite_generator : public enum_generator {
 public:
  std::shared_ptr<mstch_base> generate(
      const t_enum* enm,
      std::shared_ptr<const mstch_generators> generators,
      std::shared_ptr<mstch_cache> cache,
      ELEMENT_POSITION pos,
      int32_t /*index*/) const override {
    return std::make_shared<mstch_py3lite_enum>(enm, generators, cache, pos);
  }
};

class enum_value_py3lite_generator : public enum_value_generator {
 public:
  std::shared_ptr<mstch_base> generate(
      const t_enum_value* enm_value,
      std::shared_ptr<const mstch_generators> generators,
      std::shared_ptr<mstch_cache> cache,
      ELEMENT_POSITION pos,
      int32_t /*index*/) const override {
    return std::make_shared<mstch_py3lite_enum_value>(
        enm_value, generators, cache, pos);
  }
};

class const_value_py3lite_generator : public const_value_generator {
 public:
  const_value_py3lite_generator() = default;
  ~const_value_py3lite_generator() override = default;
  std::shared_ptr<mstch_base> generate(
      t_const_value const* const_value,
      std::shared_ptr<mstch_generators const> generators,
      std::shared_ptr<mstch_cache> cache,
      ELEMENT_POSITION pos,
      int32_t index,
      t_const const* current_const,
      t_type const* expected_type) const override {
    return std::make_shared<mstch_py3lite_const_value>(
        const_value,
        current_const,
        expected_type,
        generators,
        cache,
        pos,
        index);
  }
};

/**
 * Generator-specific validator that enforces that reserved key is
 * not used as namespace field name.
 */
class no_reserved_key_in_namespace_validator : virtual public validator {
 public:
  using validator::visit;

  bool visit(t_program* const prog) override {
    set_program(prog);
    validate(prog);
    return true;
  }

 private:
  void validate(t_program* const prog) {
    const auto& py3_namespace = prog->get_namespace("py3");
    if (py3_namespace.empty()) {
      return;
    }

    std::vector<std::string> namespace_tokens = split_namespace(py3_namespace);
    for (const auto& field_name : namespace_tokens) {
      if (field_name == "include") {
        std::ostringstream ss;
        ss << "Namespace '" << py3_namespace
           << "' contains reserved keyword 'include'";
        add_error(boost::none, ss.str());
      }
    }

    std::string filepath_delimiters("\\/.");
    std::vector<std::string> fields;
    boost::split(fields, prog->path(), boost::is_any_of(filepath_delimiters));
    for (const auto& field : fields) {
      if (field == "include") {
        std::ostringstream ss;
        ss << "Path '" << prog->path()
           << "' contains reserved keyword 'include'";
        add_error(boost::none, ss.str());
      }
    }
  }
};

/**
 * Generator-specific validator that enforces "name" and "value" is not used
 * as enum member or union field names (thrift-py3)
 */
class enum_member_union_field_names_validator : virtual public validator {
 public:
  using validator::visit;

  bool visit(t_enum* enm) override {
    for (const t_enum_value* ev : enm->get_enum_values()) {
      validate(ev, ev->get_name());
    }
    return true;
  }

  bool visit(t_struct* s) override {
    if (!s->is_union()) {
      return false;
    }
    for (const t_field& f : s->fields()) {
      validate(&f, f.name());
    }
    return true;
  }

 private:
  void validate(const t_named* node, const std::string& name) {
    const auto& pyname = node->get_annotation("py3.name", &name);
    if (pyname == "name" || pyname == "value") {
      std::ostringstream ss;
      ss << "'" << pyname
         << "' should not be used as an enum/union field name in thrift-py3. "
         << "Use a different name or annotate the field with `(py3.name=\"<new_py_name>\")`";
      add_error(node->get_lineno(), ss.str());
    }
  }
};

class t_mstch_py3lite_generator : public t_mstch_generator {
 public:
  t_mstch_py3lite_generator(
      t_program* program,
      t_generation_context context,
      const std::map<std::string, std::string>& parsed_options,
      const std::string& /* option_string unused */)
      : t_mstch_generator(
            program, std::move(context), "py3lite", parsed_options),
        generate_root_path_{package_to_path()} {
    out_dir_base_ = "gen-py3lite";
    auto include_prefix = get_option("include_prefix");
    if (!include_prefix.empty()) {
      program->set_include_prefix(std::move(include_prefix));
    }
  }

  void generate_program() override {
    set_mstch_generators();
    generate_types();
    generate_clients();
    generate_services();
  }

  void fill_validator_list(validator_list& vl) const override {
    vl.add<no_reserved_key_in_namespace_validator>();
    vl.add<enum_member_union_field_names_validator>();
  }

  enum TypesFile { IsTypesFile, NotTypesFile };

 protected:
  bool should_resolve_typedefs() const override { return true; }
  void set_mstch_generators();
  void generate_file(
      const std::string& file,
      TypesFile is_types_file,
      const boost::filesystem::path& base);
  void set_types_file(bool val);
  void generate_types();
  void generate_clients();
  void generate_services();
  boost::filesystem::path package_to_path();

  const boost::filesystem::path generate_root_path_;
};

} // namespace

void t_mstch_py3lite_generator::set_mstch_generators() {
  generators_->set_program_generator(
      std::make_unique<program_py3lite_generator>());
  generators_->set_struct_generator(
      std::make_unique<struct_py3lite_generator>());
  generators_->set_function_generator(
      std::make_unique<function_py3lite_generator>());
  generators_->set_service_generator(
      std::make_unique<service_py3lite_generator>(get_program()));
  generators_->set_field_generator(std::make_unique<field_py3lite_generator>());
  generators_->set_enum_generator(std::make_unique<enum_py3lite_generator>());
  generators_->set_enum_value_generator(
      std::make_unique<enum_value_py3lite_generator>());
  generators_->set_const_value_generator(
      std::make_unique<const_value_py3lite_generator>());
  generators_->set_type_generator(
      std::make_unique<type_py3lite_generator>(get_program()));
}

boost::filesystem::path t_mstch_py3lite_generator::package_to_path() {
  auto package = get_program()->get_namespace("py3");
  return boost::algorithm::replace_all_copy(package, ".", "/");
}

void t_mstch_py3lite_generator::generate_file(
    const std::string& file,
    TypesFile is_types_file,
    const boost::filesystem::path& base = {}) {
  auto program = get_program();
  const auto& name = program->name();
  if (is_types_file == IsTypesFile) {
    cache_->parsed_options_["is_types_file"] = "";
  } else {
    cache_->parsed_options_.erase("is_types_file");
  }
  auto node_ptr =
      generators_->program_generator_->generate(program, generators_, cache_);
  render_to_file(node_ptr, file, base / name / file);
}

void t_mstch_py3lite_generator::generate_types() {
  generate_file("lite_types.py", IsTypesFile, generate_root_path_);
  generate_file("lite_types.pyi", IsTypesFile, generate_root_path_);
}

void t_mstch_py3lite_generator::generate_clients() {
  if (get_program()->services().empty()) {
    // There is no need to generate empty / broken code for non existent
    // services.
    return;
  }

  generate_file("lite_clients.py", NotTypesFile, generate_root_path_);
}

void t_mstch_py3lite_generator::generate_services() {
  if (get_program()->services().empty()) {
    // There is no need to generate empty / broken code for non existent
    // services.
    return;
  }
  generate_file("lite_services.py", NotTypesFile, generate_root_path_);
}

THRIFT_REGISTER_GENERATOR(
    mstch_py3lite,
    "Py3 Lite",
    "    include_prefix:  Use full include paths in generated files.\n");

} // namespace compiler
} // namespace thrift
} // namespace apache

ext: cc

max_stars_repo_name: ahornby/fbthrift

max_issues_repo_name: ahornby/fbthrift

max_forks_repo_name: ahornby/fbthrift


text:
#include "WSServerManager.hpp" // IWYU pragma: associated

#include "GameClient.hpp"
#include "WSServerManager.hpp"
#include "algo/DispatchQueue.hpp"
#include "algo/TickManager.hpp"
#include "config/ServerConfig.hpp"
#include "log/Logger.hpp"
#include "net/NetworkManagerBase.hpp"
#include "net/ws/WsNetworkOperation.hpp"
#include "net/ws/client/ClientSessionManager.hpp"
#include "net/ws/client/ClientInputCallbacks.hpp"
#include "net/wrtc/SessionManager.hpp"
#include "net/ws/SessionGUID.hpp"
#include "net/SessionPair.hpp"
#include "storage/path.hpp"
#include <algorithm>
#include <api/peerconnectioninterface.h>
#include <boost/asio.hpp>
#include <boost/assert.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/core/ignore_unused.hpp>
#include <boost/system/error_code.hpp>
#include <chrono>
#include <cinttypes>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <enum.h>

#ifndef __has_include
  static_assert(false, "__has_include not supported");
#else
#  if __has_include(<filesystem>)
#    include <filesystem>
     namespace fs = std::filesystem;
#  elif __has_include(<experimental/filesystem>)
#    include <experimental/filesystem>
     namespace fs = std::experimental::filesystem;
#  elif __has_include(<boost/filesystem.hpp>)
#    include <boost/filesystem.hpp>
     namespace fs = boost::filesystem;
#  endif
#endif

#include <functional>
#include <iostream>
#include <map>
#include <new>
#include <rapidjson/document.h>
#include <rapidjson/error/error.h>
#include <stdexcept>
#include <string>
#include <thread>
#include <type_traits>
#include <utility>
#include <vector>

using namespace std::chrono_literals;

using namespace ::gloer::net::ws;
using namespace ::gloer::algo;

using namespace ::gameclient;

namespace gameclient {

/**
 * Type field stores uint32_t -> [0-4294967295] -> max 10 digits
 **/
constexpr unsigned long UINT32_FIELD_MAX_LEN = 10;

WSServerManager::WSServerManager(std::weak_ptr<GameClient> game) : ServerManagerBase(game) {
  LOG(WARNING) << "WSServerManager::WSServerManager";
  if (!receivedMessagesQueue_ || !receivedMessagesQueue_.get()) {
    LOG(WARNING) << "WSServerManager::WSServerManager: invalid receivedMessagesQueue_";
  }
  /*receivedMessagesQueue_ =
      std::make_shared<DispatchQueue>(std::string{"WebSockets Server Dispatch Queue"}, 0);*/
}

/**
 * Add message to queue for further processing
 * Returs true if message can be processed
 **/
bool WSServerManager::handleIncomingJSON(const gloer::net::ws::SessionGUID& sessId, const std::string& message) {
  if (message.empty()) {
    LOG(WARNING) << "WS::handleIncomingJSON: invalid message";
    return false;
  }

  if (!receivedMessagesQueue_ || !receivedMessagesQueue_.get()) {
    LOG(WARNING) << "WS::handleIncomingJSON: invalid receivedMessagesQueue_ ";
    return false;
  }

  // parse incoming message
  rapidjson::Document message_object;
  rapidjson::ParseResult result = message_object.Parse(message.c_str());
  // LOG(INFO) << "incomingStr: " << message->c_str();
  if (!result || !message_object.IsObject() || !message_object.HasMember("type")) {
    LOG(WARNING) << "WsSession::handleIncomingJSON: ignored invalid message without type "
                 << message;
    return false;
  }
  // Probably should do some error checking on the JSON object.
  std::string typeStr = message_object["type"].GetString();
  if (typeStr.empty() || typeStr.length() > UINT32_FIELD_MAX_LEN) {
    LOG(WARNING) << "WsSession::handleIncomingJSON: ignored invalid message with invalid "
                    "type field";
  }

  /// TODO: nm <<<<
  const auto& callbacks = game_.lock()->ws_nm->operationCallbacks().getCallbacks();
  const gloer::net::ws::WsNetworkOperation NetworkOperation{
      static_cast<WS_OPCODE>(Opcodes::wsOpcodeFromStr(typeStr))};
  const auto itFound = callbacks.find(NetworkOperation);
  // if a callback is registered for event, add it to queue
  if (itFound != callbacks.end()) {
    gloer::net::ws::ClientNetworkOperationCallback callback = itFound->second;
    auto sessPtr = game_.lock()->ws_nm->sessionManager().getSessById(sessId);
    if (!sessPtr || !sessPtr.get()) {
      LOG(WARNING) << "WsSession::handleIncomingJSON: ignored invalid session";
      return false;
    }
    // WsSession* sess = sessPtr.get();
    DispatchQueue::dispatch_callback callbackBind = std::bind(
        callback, sessPtr, game_.lock()->ws_nm.get(), std::make_shared<std::string>(message));
    receivedMessagesQueue_->dispatch(callbackBind);

    /*LOG(WARNING) << "WsSession::handleIncomingJSON: receivedMessagesQueue_->sizeGuess() "
                 << receivedMessagesQueue_->sizeGuess();*/
  } else {
    LOG(WARNING) << "WsSession::handleIncomingJSON: ignored invalid message with type " << typeStr;
    return false;
  }

  return true;
}

void WSServerManager::handleClose(const gloer::net::ws::SessionGUID& sessId) {}

void WSServerManager::processIncomingMessages() {
  if (game_.lock()->ws_nm->sessionManager().getSessionsCount()) {
    LOG(INFO) << "WSServer::handleIncomingMessages getSessionsCount "
              << game_.lock()->ws_nm->sessionManager().getSessionsCount();
    const std::unordered_map<gloer::net::ws::SessionGUID, std::shared_ptr<gloer::net::SessionPair>>& sessions =
        game_.lock()->ws_nm->sessionManager().getSessions();
    /*std::string msg = "WS SESSIONS:[";
    for (auto& it : sessions) {
      std::shared_ptr<WsSession> wss = it.second;
    if (!session || !session.get()) {
      LOG(WARNING) << "WsServer::handleAllPlayerMessages: trying to "
                      "use non-existing session";
      // NOTE: unregisterSession must be automatic!
      game_.lock()->ws_nm->getRunner()->unregisterSession(sessId);
      return;
    }

      msg += it.first;
      msg += "=";
      if (!wss || !wss.get()) {
        msg += "EMPTY";
      } else {
        msg += wrtcSessId;
      }
    }
    msg += "]SESSIONS";
    LOG(INFO) << msg;*/
  }
  game_.lock()->ws_nm->sessionManager().doToAllSessions([&](const gloer::net::ws::SessionGUID& sessId,
                                                 std::shared_ptr<gloer::net::SessionPair> session) {
    if (!session || !session.get()) {
      LOG(WARNING) << "WsServer::handleAllPlayerMessages: trying to "
                      "use non-existing session";
      // NOTE: unregisterSession must be automatic!
      game_.lock()->ws_nm->sessionManager().unregisterSession(sessId);
      return;
    }

    auto wsSessId = session->getId(); // remember id before session deletion

    /*if (!session->isOpen() && session->fullyCreated()) {
      LOG(WARNING) << "WsServer::handleAllPlayerMessages: !session->isOpen()";
      // NOTE: unregisterSession must be automatic!
      unregisterSession(wrtcSessId);
      return;
    }*/

    /*if (session->isExpired()) {
      LOG(WARNING) << "WsServer::handleAllPlayerMessages: session timer expired";
      game_.lock()->ws_nm->getRunner()->unregisterSession(wrtcSessId);
      return;
    }*/

    // LOG(INFO) << "doToAllSessions for " << wrtcSessId;
    if (!receivedMessagesQueue_ || !receivedMessagesQueue_.get()) {
      LOG(WARNING) << "WsServer::handleAllPlayerMessages: invalid session->getReceivedMessages()";
      return;
    }
    receivedMessagesQueue_->DispatchQueued();
  });
}

} // namespace gameclient

max_stars_repo_name: lineCode/webrtc-datachannels

max_issues_repo_name: lineCode/webrtc-datachannels

max_forks_repo_name: lineCode/webrtc-datachannels


text:
//          Copyright Oliver Kowalke 2009.
// 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)

// this file is based on config.hpp of boost.thread

#ifndef BOOST_FIBERS_DETAIL_CONFIG_H
#define BOOST_FIBERS_DETAIL_CONFIG_H

#include <boost/config.hpp>
#include <boost/detail/workaround.hpp>

# if BOOST_WORKAROUND(__BORLANDC__, < 0x600)
#   pragma warn -8008 // Condition always true/false
#   pragma warn -8080 // Identifier declared but never used
#   pragma warn -8057 // Parameter never used
#   pragma warn -8066 // Unreachable code
# endif

# if defined(BOOST_ALL_DYN_LINK) || defined(BOOST_FIBER_DYN_LINK)
#   undef  BOOST_FIBER_USE_LIB
#   define BOOST_FIBER_USE_DLL
# endif

# if defined(BOOST_WINDOWS_API) && defined(BOOST_POSIX_API)
#   error "Both BOOST_WINDOWS_API and BOOST_POSIX_API are defined!"
# elif ! defined(BOOST_WINDOWS_API ) && ! defined(BOOST_POSIX_API)
#   if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) || defined(__CYGWIN__)
#     define BOOST_WINDOWS_API
#   else
#     define BOOST_POSIX_API
#   endif
# endif

# if defined(BOOST_FIBER_BUILD_DLL)   //Build dll
# elif defined(BOOST_FIBER_BUILD_LIB) //Build lib
# elif defined(BOOST_FIBER_USE_DLL)   //Use dll
# elif defined(BOOST_FIBER_USE_LIB)   //Use lib
# else //Use default
#   if defined(BOOST_FIBER_PLATFORM_WIN32)
#      if defined(BOOST_MSVC) || defined(BOOST_INTEL_WIN)
            //For compilers supporting auto-tss cleanup
            //with Boost.Threads lib, use Boost.Threads lib
#         define BOOST_FIBER_USE_LIB
#      else
            //For compilers not yet supporting auto-tss cleanup
            //with Boost.Threads lib, use Boost.Threads dll
#         define BOOST_FIBER_USE_DLL
#      endif
#   else
#      define BOOST_FIBER_USE_LIB
#   endif
# endif

# if defined(BOOST_HAS_DECLSPEC)
#   if defined(BOOST_FIBER_BUILD_DLL) //Build dll
#      define BOOST_FIBER_DECL __declspec(dllexport)
#   elif defined(BOOST_FIBER_USE_DLL) //Use dll
#      define BOOST_FIBER_DECL __declspec(dllimport)
#   else
#      define BOOST_FIBER_DECL
#   endif
# else
#   define BOOST_FIBER_DECL
# endif

// Automatically link to the correct build variant where possible.
# if ! defined(BOOST_ALL_NO_LIB) && ! defined(BOOST_FIBER_NO_LIB) && ! defined(BOOST_FIBER_BUILD_DLL) && ! defined(BOOST_FIBER_BUILD_LIB)

// Tell the autolink to link dynamically, this will get undef'ed by auto_link.hpp
# if defined(BOOST_FIBER_USE_DLL)
#   define BOOST_DYN_LINK
# endif

// Set the name of our library, this will get undef'ed by auto_link.hpp
# if defined(BOOST_FIBER_LIB_NAME)
#   define BOOST_LIB_NAME BOOST_FIBER_LIB_NAME
# else
#   define BOOST_LIB_NAME boost_fiber
# endif

// If we're importing code from a dll, then tell auto_link.hpp about it
// And include the header that does the work
#include <boost/config/auto_link.hpp>
# endif  // auto-linking disabled

#endif // BOOST_FIBERS_DETAIL_CONFIG_H

ext: hpp

max_stars_repo_name: ghisguth/tasks

max_issues_repo_name: ghisguth/tasks

max_forks_repo_name: ghisguth/tasks


text: #include <boost/spirit/home/classic/utility/loops.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


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

#ifndef TRAFFIC_SIMULATOR__ENTITY__PEDESTRIAN_PARAMETER_HPP_
#define TRAFFIC_SIMULATOR__ENTITY__PEDESTRIAN_PARAMETER_HPP_

// headers in pugixml
#include <boost/foreach.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <geometry_msgs/msg/vector3.hpp>
#include <openscenario_msgs/msg/pedestrian_parameters.hpp>
#include <pugixml.hpp>
#include <rclcpp/rclcpp.hpp>
#include <sstream>
#include <string>
#include <traffic_simulator/entity/vehicle_parameter.hpp>

namespace traffic_simulator
{
namespace entity
{
struct PedestrianParameters
{
  explicit PedestrianParameters(const pugi::xml_node & xml)
  : name(xml.child("Pedestrian").attribute("name").as_string()),
    pedestrian_category(xml.child("Pedestrian").attribute("pedestrianCategory").as_string()),
    bounding_box(xml.child("Pedestrian"))
  {
  }
  PedestrianParameters(std::string name, std::string pedestrian_category, BoundingBox bounding_box)
  : name(name), pedestrian_category(pedestrian_category), bounding_box(bounding_box)
  {
  }
  const std::string name;
  const std::string pedestrian_category;
  const BoundingBox bounding_box;

  std::string toXml() const
  {
    using boost::property_tree::ptree;
    ptree pt;
    ptree & pedestrian_tree = pt.add("Pedestrian", "");
    pedestrian_tree.put("<xmlattr>.name", name);
    pedestrian_tree.put("<xmlattr>.PedestrianCategory", pedestrian_category);
    ptree & center_tree = pedestrian_tree.add("BoundingBox.Center", "");
    center_tree.put("<xmlattr>.x", bounding_box.center.x);
    center_tree.put("<xmlattr>.y", bounding_box.center.y);
    center_tree.put("<xmlattr>.z", bounding_box.center.z);
    ptree & dimensions_tree = pedestrian_tree.add("BoundingBox.Dimensions", "");
    dimensions_tree.put("<xmlattr>.width", bounding_box.dimensions.width);
    dimensions_tree.put("<xmlattr>.length", bounding_box.dimensions.length);
    dimensions_tree.put("<xmlattr>.height", bounding_box.dimensions.height);
    std::stringstream ss;
    boost::property_tree::write_xml(ss, pt);
    return ss.str();
  }

  const openscenario_msgs::msg::PedestrianParameters toRosMsg() const
  {
    openscenario_msgs::msg::PedestrianParameters msg;
    msg.bounding_box = bounding_box.toRosMsg();
    msg.name = name;
    msg.pedestrian_category = pedestrian_category;
    return msg;
  }
};
}  // namespace entity
}  // namespace traffic_simulator

#endif  // TRAFFIC_SIMULATOR__ENTITY__PEDESTRIAN_PARAMETER_HPP_


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

#include "gui/pl_account_entry_list_ctrl.hpp"
#include "account.hpp"
#include "entry.hpp"
#include "gui/locale.hpp"
#include "gui/filtered_entry_list_ctrl.hpp"
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/optional.hpp>
#include <jewel/assert.hpp>
#include <jewel/decimal.hpp>
#include <jewel/optional.hpp>
#include <sqloxx/handle.hpp>

using boost::optional;
using jewel::Decimal;
using jewel::value;
using sqloxx::Handle;

namespace gregorian = boost::gregorian;

namespace dcm
{
namespace gui
{

namespace
{
    int comment_col_num()
    {
        return 1;
    }
    int amount_col_num()
    {
        return 2;
    }
    int anon_num_columns()
    {
        return 3;
    }

}  // end anonymous namespace

PLAccountEntryListCtrl::PLAccountEntryListCtrl
(   wxWindow* p_parent,
    wxSize const& p_size,
    Handle<Account> const& p_account,
    optional<gregorian::date> const& p_maybe_min_date,
    optional<gregorian::date> const& p_maybe_max_date
):
    FilteredEntryListCtrl
    (   p_parent,
        p_size,
        p_account,
        p_maybe_min_date,
        p_maybe_max_date
    ),
    m_reverse_signs(p_account->account_type() == AccountType::revenue)
{
}

PLAccountEntryListCtrl::~PLAccountEntryListCtrl()
{
}

void
PLAccountEntryListCtrl::do_set_non_date_columns
(   long p_row,
    Handle<Entry> const& p_entry
)
{
    SetItem(p_row, comment_col_num(), p_entry->comment());
    SetItem
    (   p_row,
        amount_col_num(),
        finformat_wx
        (   friendly_amount(p_entry),
            locale(),
            DecimalFormatFlags().clear(string_flags::dash_for_zero)
        )
    );
    JEWEL_ASSERT (num_columns() == 3);
    return;
}

wxString
PLAccountEntryListCtrl::verb() const
{
    switch (account()->account_type())
    {
    case AccountType::revenue:
        return wxString("earned");
    case AccountType::expense:
        return wxString("spent");
    default:
        JEWEL_HARD_ASSERT (false);
    }
}

void
PLAccountEntryListCtrl::do_insert_non_date_columns()
{
    InsertColumn
    (   comment_col_num(),
        wxString("Memo"),
        wxLIST_FORMAT_LEFT
    );
    InsertColumn
    (   amount_col_num(),
        wxString("Amount ") + verb(),
        wxLIST_FORMAT_RIGHT
    );
    JEWEL_ASSERT (num_columns() == 3);
    return;
}

int
PLAccountEntryListCtrl::do_get_comment_col_num() const
{
    return comment_col_num();
}

int
PLAccountEntryListCtrl::do_get_num_columns() const
{
    return anon_num_columns();
}

jewel::Decimal
PLAccountEntryListCtrl::friendly_amount(Handle<Entry> const& p_entry) const
{
    return m_reverse_signs? -p_entry->amount(): p_entry->amount();
}

}  // namespace gui
}  // namespace dcm

max_stars_repo_name: skybaboon/dailycashmanager

max_issues_repo_name: skybaboon/dailycashmanager

max_forks_repo_name: skybaboon/dailycashmanager


text:
#ifndef BOOST_MPL_AUX_RANGE_C_ITERATOR_HPP_INCLUDED
#define BOOST_MPL_AUX_RANGE_C_ITERATOR_HPP_INCLUDED

// Copyright Aleksey Gurtovoy 2000-2004
//
// 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/mpl for documentation.

// $Id$
// $Date$
// $Revision$

#include <boost/mpl/iterator_tags.hpp>
#include <boost/mpl/advance_fwd.hpp>
#include <boost/mpl/distance_fwd.hpp>
#include <boost/mpl/next_prior.hpp>
#include <boost/mpl/deref.hpp>
#include <boost/mpl/plus.hpp>
#include <boost/mpl/minus.hpp>
#include <boost/mpl/aux_/value_wknd.hpp>
#include <boost/mpl/aux_/config/ctps.hpp>

namespace boost { namespace mpl {

// theoretically will work on any discrete numeric type
template< typename N > struct r_iter
{
    typedef aux::r_iter_tag tag;
    typedef random_access_iterator_tag category;
    typedef N type;

};

template<
      typename N
    >
struct next< r_iter<N> >
{
    typedef r_iter< typename mpl::next<N>::type > type;
};

template<
      typename N
    >
struct prior< r_iter<N> >
{
    typedef r_iter< typename mpl::prior<N>::type > type;
};

template<> struct advance_impl<aux::r_iter_tag>
{
    template< typename Iter, typename Dist > struct apply
    {
        typedef typename deref<Iter>::type n_;
        typedef typename plus<n_,Dist>::type m_;
        // agurt, 10/nov/04: to be generic, the code have to do something along
        // the lines below...
        //
        // typedef typename apply_wrap1<
        //       numeric_cast< typename m_::tag, typename n_::tag >
        //     , m_
        //     >::type result_;
        //
        // ... meanwhile:

        typedef integral_c<
              typename aux::value_type_wknd<n_>::type
            , BOOST_MPL_AUX_VALUE_WKND(m_)::value
            > result_;

        typedef r_iter<result_> type;
    };
};

template<> struct distance_impl<aux::r_iter_tag>
{
    template< typename Iter1, typename Iter2 > struct apply
        : minus<
              typename Iter2::type
            , typename Iter1::type
            >
    {
    };
};

}}

#endif // BOOST_MPL_AUX_RANGE_C_ITERATOR_HPP_INCLUDED

max_stars_repo_name: ballisticwhisper/boost

max_issues_repo_name: ballisticwhisper/boost

max_forks_repo_name: ballisticwhisper/boost


text:
#include <burst/iterator/merge_iterator.hpp>
#include <burst/range/make_range_vector.hpp>

#include <doctest/doctest.h>

#include <boost/range/iterator_range.hpp>

#include <functional>
#include <iterator>

TEST_SUITE("merge_iterator")
{
    TEST_CASE("Конец итератора сляния создаётся из его начала с помощью специальной "
        "метки-индикатора")
    {
        auto  first = {500, 100};
        auto second = {600, 200};
        auto ranges = burst::make_range_vector(first, second);

        auto merged_begin = burst::make_merge_iterator(ranges, std::greater<>{});
        auto merged_end = burst::make_merge_iterator(burst::iterator::end_tag, merged_begin);

        auto expected_collection = {600, 500, 200, 100};
        CHECK(boost::make_iterator_range(merged_begin, merged_end) == expected_collection);
    }
}

max_stars_repo_name: izvolov/thrust

max_issues_repo_name: izvolov/burst

max_forks_repo_name: izvolov/thrust


text:
//
// TestTransitiveDependencies.cpp
// Copyright (c) Charles Baker. All rights reserved.
//

#include "stdafx.hpp"
#include <forge/Forge.hpp>
#include <forge/ForgeEventSink.hpp>
#include <error/ErrorPolicy.hpp>
#include <luaxx/luaxx_unit/LuaUnitTest.hpp>
#include <assert/assert.hpp>
#include <UnitTest++/UnitTest++.h>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
#include <string>

using std::string;
using namespace sweet;
using namespace sweet::forge;
using namespace luaxx;
using namespace boost::filesystem;

SUITE( dependencies )
{
    struct LuaTest : public forge::ForgeEventSink
    {
        error::ErrorPolicy* error_policy_;
        forge::Forge* forge_;
        luaxx::LuaUnitTest* lua_unit_test_;

        LuaTest()
        {
            path path = boost::filesystem::path( string(TEST_DIRECTORY) );
            error_policy_ = new error::ErrorPolicy;
            forge_ = new forge::Forge( path.string(), *error_policy_, this );
            lua_unit_test_ = new LuaUnitTest( forge_->lua_state(), error_policy_ );
            forge_->set_root_directory( path.generic_string() );
            forge_->set_stack_trace_enabled( true );
            forge_->set_package_path(
                forge_->root("../lua/?.lua").generic_string() + ";" +
                forge_->root("../lua/?/init.lua").generic_string()
            );
        }

        ~LuaTest()
        {
            delete lua_unit_test_;
            delete forge_;
            delete error_policy_;
        }

        void forge_output( Forge* /*forge*/, const char* message )
        {
            SWEET_ASSERT( message );
            fputs( message, stdout );
            fputs( "\n", stdout );
            fflush( stdout );
        }

        void forge_warning( Forge* /*forge*/, const char* message )
        {
            SWEET_ASSERT( message );
            fputs( "forge_test: ", stderr );
            fputs( message, stderr );
            fputs( ".\n", stderr );
            fflush( stderr );
        }

        void forge_error( Forge* /*forge*/, const char* message )
        {
            SWEET_ASSERT( message );
            fputs( "forge_test: ", stderr );
            fputs( message, stderr );
            fputs( ".\n", stderr );
            fflush( stderr );
        }
    };

    TEST_FIXTURE( LuaTest, transitive_dependencies )
    {
        forge_->file( "transitive_dependencies.lua" );
    }
}

max_stars_repo_name: willmbaker/forge

max_issues_repo_name: willmbaker/forge

max_forks_repo_name: willmbaker/forge


text:
#ifndef ASSOCIATIVE_ACTION_HPP
#define ASSOCIATIVE_ACTION_HPP

#include <string>
#include <vector>
#include <map>

#include <boost/program_options.hpp>
#include <boost/optional.hpp>

#include "../util/util.hpp"
#include "../util/parameters.hpp"
#include "../util/modules.hpp"
#include "../env/environment.hpp"

#define COMMANDLINE_DECL \
	MODULE_DECL

#define COMMANDLINE_DEF(NAME) \
	MODULE_DEF(NAME, Action, Action)

namespace associative
{

	class Environment;
	class ActionParameters;

	class MainParameters : public Parameters
	{
	private:
		MainParameters(const Parameters& parent, const po::variables_map& options, const std::vector<std::string>& unrecognized);

	public:
		const po::variables_map options;
		const std::vector<std::string> unrecognized;

		boost::optional<ActionParameters> parseFurther();

		static boost::optional<MainParameters> fromCommandLine(const std::vector<std::string>& args);
	};

	class Action : public Module
	{
		friend class ActionParameters;

	protected:
		static ModuleManager<Action>& manager();

		Action(const std::string& name);

		virtual po::options_description* desc() = 0;

	public:
		virtual int perform(const po::variables_map& vm, const std::vector<std::string>& parameters, Environment& env) = 0;
	};

	class ActionParameters
	{
	private:
		ActionParameters(Action* const action, const po::variables_map& options);

	public:
		Action* const action;
		const po::variables_map options;

		int dispatch(Environment& env);

		static boost::optional<ActionParameters> fromCommandLine(std::vector<std::string> args);
	};

}

#endif

max_stars_repo_name: larsrh/associative

max_issues_repo_name: larsrh/associative

max_forks_repo_name: larsrh/associative


text:
#include <iostream>
#include <string>

#include <boost/tokenizer.hpp>

int main()
{
    std::string_view s{"Boost C++ Libraries"};
    boost::char_separator<char> sep{" ", "+", boost::keep_empty_tokens};
    boost::tokenizer tok{s, sep};
    for (const auto& t : tok)
        std::cout << t << '\n';
}

max_stars_repo_name: cvlabmiet/master-programming

max_issues_repo_name: cvlabmiet/master-programming

max_forks_repo_name: cvlabmiet/master-programming


text: #include <boost/mpl/vector/vector40.hpp>


text: #include <boost/mpl/aux_/preprocessed/msvc70/reverse_fold_impl.hpp>


text:
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>

#include <sstream> // stringstream

// evil hack to allow testing of private and protected data
#define private public
#define protected public

#include "niflib.h"
#include "obj/NiNode.h"
#include "obj/NiTriShape.h"
#include "obj/NiTriShapeData.h"

using namespace Niflib;
using namespace std;

BOOST_AUTO_TEST_SUITE(numuvsets_test_suite)

BOOST_AUTO_TEST_CASE(numuvsets_write_test)
{
  stringstream ss;
  stringstream ss2;

  // create a simple nif tree with a trishape
  NiNodeRef root = new NiNode;
  NiTriShapeRef shape = new NiTriShape;
  NiTriShapeDataRef data = new NiTriShapeData;
  // set hierarchy
  shape->SetData(data);
  root->AddChild(DynamicCast<NiAVObject>(shape));
  // set flag
  data->SetTspaceFlag(1);
  // write and read
  NiObjectRef obj;
  BOOST_CHECK_NO_THROW(WriteNifTree(ss, root, NifInfo(VER_20_0_0_5)));
  ss.seekg(0);
  BOOST_CHECK_NO_THROW(obj = ReadNifTree(ss));
  // check flag
  root = DynamicCast<NiNode>(obj);
  BOOST_REQUIRE(root != NULL);
  BOOST_REQUIRE_EQUAL(root->GetChildren().size(), 1);
  shape = DynamicCast<NiTriShape>(root->GetChildren()[0]);
  BOOST_REQUIRE(shape != NULL);
  data = DynamicCast<NiTriShapeData>(shape->GetData());
  BOOST_REQUIRE(data != NULL);
  BOOST_CHECK_EQUAL(data->GetTspaceFlag(), 1);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: BlazesRus/niflib

max_issues_repo_name: BlazesRus/niflib

max_forks_repo_name: BlazesRus/niflib


text:
#include <iostream>
#include <typeinfo> // to enable c++filt in script

#include <boost/numeric/mtl/mtl.hpp>

#include "print_compiler.hpp"
#include "../my_info.hpp"

using namespace std;

struct too_small {};
struct too_large {};

template <typename Vector>
class value_range_vector
{
    using value_type= typename Vector::value_type;
    using size_type=  typename Vector::size_type;
  public:
    value_range_vector(Vector& vref, value_type minv, value_type maxv)
      : vref(vref), minv(minv), maxv(maxv)
    {}

    decltype(auto) operator[](size_type i)
    {
	decltype(auto) value= vref[i];
	if (value < minv) throw too_small{};
	if (value > maxv) throw too_large{};
	return value;
    }
  private:
    Vector&    vref;
    value_type minv, maxv;
};

int main ()
{
    print_compiler();

    using Vec= mtl::vector<double>;
    Vec v= {2.3, 8.1, 9.2};

    value_range_vector<Vec> w(v, 1.0, 10.0);
    decltype(auto) val= w[1];
    cout << "The type of val is " << my_info<decltype(val)>() << endl;
}

max_stars_repo_name: tzaffi/cpp

max_issues_repo_name: tzaffi/cpp

max_forks_repo_name: tzaffi/cpp


text:
// ------------------------------------ //
#include "ScriptComponentHolder.h"

#include "GameWorld.h"
#include "Script/ScriptConversionHelpers.h"
#include "Script/ScriptExecutor.h"

#include <boost/range/adaptor/map.hpp>
using namespace Leviathan;
// ------------------------------------ //

DLLEXPORT ScriptComponentHolder::ScriptComponentHolder(
    const std::string& name, asIScriptFunction* factory, GameWorld* world) :
    ComponentType(name),
    Factory(factory), World(world)
{
    if(!Factory)
        throw InvalidArgument("ScriptComponentHolder not given a factory function");
}

DLLEXPORT ScriptComponentHolder::~ScriptComponentHolder()
{
    // Make sure all are released
    ReleaseAllComponents();

    Factory->Release();

    LEVIATHAN_ASSERT(CreatedObjects.empty(), "ScriptComponentHolder didn't properly clear");
}
// ------------------------------------ //
DLLEXPORT bool ScriptComponentHolder::ReleaseComponent(ObjectID entity)
{
    auto iter = CreatedObjects.find(entity);

    if(iter == CreatedObjects.end())
        return false;

    Removed.push_back(std::make_tuple(iter->second, entity));

    // Remove from added if there //
    for(auto iter = Added.begin(); iter != Added.end(); ++iter) {

        if(std::get<1>(*iter) == entity) {

            std::iter_swap(iter, Added.rbegin());
            Added.pop_back();
            break;
        }
    }

    // TODO: call release on the actual script object to let it do shutdown stuff
    // Release our reference to let the object be destroyed once all references are released
    iter->second->Release();

    CreatedObjects.erase(iter);

    return true;
}

DLLEXPORT void ScriptComponentHolder::ReleaseAllComponents()
{
    for(auto iter = CreatedObjects.begin(); iter != CreatedObjects.end(); ++iter) {

        // TODO: also call release here
        iter->second->Release();
    }

    CreatedObjects.clear();
    Added.clear();
    Removed.clear();
}

DLLEXPORT asIScriptObject* ScriptComponentHolder::Create(ObjectID entity)
{
    // Fail if already exists //
    asIScriptObject* found = Find(entity);
    if(found != nullptr) {

        LOG_WARNING("ScriptComponentHolder: Create: called for existing component, id: " +
                    std::to_string(entity));

        // Must release reference
        found->Release();
        return nullptr;
    }

    ScriptRunningSetup setup;

    auto result = static_cast<ScriptExecutor*>(Factory->GetEngine()->GetUserData())
                      ->RunScript<asIScriptObject*>(Factory, nullptr, setup, World);

    if(result.Result != SCRIPT_RUN_RESULT::Success || result.Value == nullptr) {

        LOG_ERROR("ScriptComponentHolder: Create: failed to run the angelscript factory "
                  "function for this type (" +
                  ComponentType + ")");
        return nullptr;
    }

    Added.push_back(std::make_tuple(result.Value, entity));

    // Remove from removed if there //
    for(auto iter = Removed.begin(); iter != Removed.end(); ++iter) {

        if(std::get<1>(*iter) == entity) {

            std::iter_swap(iter, Removed.rbegin());
            Removed.pop_back();
            break;
        }
    }

    // Remember that we take a reference to it
    result.Value->AddRef();

    CreatedObjects[entity] = result.Value;

    // And we return it so increase refcount for that too //
    result.Value->AddRef();
    return result.Value;
}

DLLEXPORT asIScriptObject* ScriptComponentHolder::Find(ObjectID entity)
{
    auto iter = CreatedObjects.find(entity);

    if(iter == CreatedObjects.end())
        return nullptr;

    iter->second->AddRef();
    return iter->second;
}
// ------------------------------------ //
DLLEXPORT CScriptArray* ScriptComponentHolder::GetIndex() const
{
    asIScriptContext* ctx = asGetActiveContext();

    asIScriptEngine* engine = ctx ? ctx->GetEngine() : ScriptExecutor::Get()->GetASEngine();

    return ConvertIteratorToASArray((CreatedObjects | boost::adaptors::map_keys).begin(),
        (CreatedObjects | boost::adaptors::map_keys).end(), engine, "array<ObjectID>");
}

max_stars_repo_name: hhyyrylainen/Leviathan

max_issues_repo_name: hhyyrylainen/Leviathan

max_forks_repo_name: hhyyrylainen/Leviathan