hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
753d41de299f72c849f912ea5ebee821f3ac6529
785
cpp
C++
src/LedDisplay.cpp
JorgeMaker/GRBLPedant
3f61c9ed0098293fec473ac6fae1aaff9d018df6
[ "MIT" ]
2
2021-05-04T02:27:44.000Z
2021-05-05T02:35:14.000Z
src/LedDisplay.cpp
JorgeMaker/GRBLPedant
3f61c9ed0098293fec473ac6fae1aaff9d018df6
[ "MIT" ]
1
2022-03-09T07:51:36.000Z
2022-03-09T07:51:36.000Z
src/LedDisplay.cpp
JorgeMaker/GRBLPedant
3f61c9ed0098293fec473ac6fae1aaff9d018df6
[ "MIT" ]
2
2021-05-05T02:35:17.000Z
2021-08-09T02:00:33.000Z
#include "Definitions.h" #include <Arduino.h> /*************************** * Led Display * *************************/ LedDisplay::LedDisplay(uint8_t xPIN, uint8_t yPIN, uint8_t zPIN) { ledXPIN = xPIN; ledYPIN = yPIN; ledZPIN = zPIN; pinMode(ledXPIN, OUTPUT); pinMode(ledYPIN, OUTPUT); pinMode(ledZPIN, OUTPUT); } void LedDisplay::showSelectedAxis(AxisSelection selection) { if (selection == X) { digitalWrite(ledXPIN, HIGH); digitalWrite(ledYPIN, LOW); digitalWrite(ledZPIN, LOW); } else if (selection == Y) { digitalWrite(ledXPIN, LOW); digitalWrite(ledYPIN, HIGH); digitalWrite(ledZPIN, LOW); } else if (selection == Z) { digitalWrite(ledXPIN, LOW); digitalWrite(ledYPIN, LOW); digitalWrite(ledZPIN, HIGH); } }
22.428571
66
0.620382
JorgeMaker
7541490b64a6cf68377a93f033b9d87b0eca4f84
3,617
cpp
C++
minecraft/minecraft/src/window/window.cpp
llGuy/gamedev
16aa203934fd767926c58558e021630288556399
[ "MIT" ]
null
null
null
minecraft/minecraft/src/window/window.cpp
llGuy/gamedev
16aa203934fd767926c58558e021630288556399
[ "MIT" ]
4
2018-12-24T11:16:53.000Z
2018-12-24T11:20:29.000Z
minecraft/minecraft/src/window/window.cpp
llGuy/gamedev
16aa203934fd767926c58558e021630288556399
[ "MIT" ]
null
null
null
#include <GL/glew.h> #include <GLFW/glfw3.h> #include <chrono> #include <thread> #include "callbacks/callbacks.h" #include "window.h" #include "../log.h" Window::Window(uint32_t width, uint32_t height, const char* title) : m_width(width), m_height(height), m_title(title), m_engine() { // all initializations GLFWInit(); WindowInit(); GLEWInit(); AfterGLEWInit(); } void Window::Destroy(void) { m_engine.HEAPDelete(); } void Window::Draw(void) { m_engine.Render(); } void Window::Update(void) { glViewport(0, 0, m_width, m_height); glfwSwapBuffers(m_glfwWindow); glfwPollEvents(); PollKeys(); PollMouseMovement(); //PollMouseInput(); } void Window::MouseCallback(uint32_t b) { switch (b) { case GLFW_MOUSE_BUTTON_1: m_engine.RecieveMouseInput(minecraft::Engine::mbutton_t::MOUSEL); return; case GLFW_MOUSE_BUTTON_2: m_engine.RecieveMouseInput(minecraft::Engine::mbutton_t::MOUSER); return; } } const bool Window::WindowOpen(void) { return !glfwWindowShouldClose(m_glfwWindow) && !(glfwGetKey(m_glfwWindow, GLFW_KEY_ESCAPE)); } void Window::WindowInit(void) { m_glfwWindow = glfwCreateWindow(m_width, m_height, m_title, NULL, NULL); glfwMakeContextCurrent(m_glfwWindow); if (!m_glfwWindow) { Error("failed to initialize window"); glfwTerminate(); std::cin.get(); exit(1); } glfwSetInputMode(m_glfwWindow, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glfwSetWindowUserPointer(m_glfwWindow, this); glfwSetMouseButtonCallback(m_glfwWindow, CursorEnterCallback); glfwSetKeyCallback(m_glfwWindow, KeyboardEnterCallback); } void Window::GLFWInit(void) { if (!glfwInit()) { Error("failed to initialize GLFW"); glfwTerminate(); std::cin.get(); exit(1); } } void Window::GLEWInit(void) { GLenum err = glewInit(); if (err != GLEW_OK) { Error("failed to initialize GLEW"); glfwTerminate(); std::cin.get(); exit(1); } } void Window::AfterGLEWInit(void) { glEnable(GL_DEPTH_TEST); double x, y; glfwGetCursorPos(m_glfwWindow, &x, &y); m_engine.AfterGLEWInit(m_width, m_height, glm::vec2(x, y), m_glfwWindow); } void Window::PollKeys(void) { if (glfwGetKey(m_glfwWindow, GLFW_KEY_W)) m_engine.RecieveKeyInput(minecraft::Engine::key_t::W); if (glfwGetKey(m_glfwWindow, GLFW_KEY_A)) m_engine.RecieveKeyInput(minecraft::Engine::key_t::A); if (glfwGetKey(m_glfwWindow, GLFW_KEY_S)) m_engine.RecieveKeyInput(minecraft::Engine::key_t::S); if (glfwGetKey(m_glfwWindow, GLFW_KEY_D)) m_engine.RecieveKeyInput(minecraft::Engine::key_t::D); if (glfwGetKey(m_glfwWindow, GLFW_KEY_SPACE)) m_engine.RecieveKeyInput(minecraft::Engine::key_t::SPACE); if (glfwGetKey(m_glfwWindow, GLFW_KEY_LEFT_SHIFT)) m_engine.RecieveKeyInput(minecraft::Engine::key_t::LSHIFT); if (glfwGetKey(m_glfwWindow, GLFW_KEY_R)) m_engine.RecieveKeyInput(minecraft::Engine::key_t::R); if(glfwGetKey(m_glfwWindow, GLFW_KEY_F)) m_engine.RecieveKeyInput(minecraft::Engine::key_t::F); } void Window::PollMouseMovement(void) { double x, y; glfwGetCursorPos(m_glfwWindow, &x, &y); m_engine.RecieveMouseMovement( glm::vec2(static_cast<float>(x), static_cast<float>(y))); } void Window::PollMouseInput(void) { if (glfwGetMouseButton(m_glfwWindow, GLFW_MOUSE_BUTTON_1)) m_engine.RecieveMouseInput(minecraft::Engine::mbutton_t::MOUSEL); } void Window::KeyboardCallback(uint32_t k) { minecraft::Engine::key_t key = static_cast<minecraft::Engine::key_t>((k - GLFW_KEY_1) + static_cast<int32_t>(minecraft::Engine::key_t::ONE)); m_engine.RecieveKeyInput(key); }
28.936
112
0.72104
llGuy
75496c98f4152f5d98503b0bece1d4cd2217c2aa
699
hpp
C++
neovm_cpp/include/vmimpl/crypto.hpp
zoowii/neo-vm-cpp
8debcc334e5b3c6afceef0bfb0ff300e0989d0a7
[ "MIT" ]
null
null
null
neovm_cpp/include/vmimpl/crypto.hpp
zoowii/neo-vm-cpp
8debcc334e5b3c6afceef0bfb0ff300e0989d0a7
[ "MIT" ]
null
null
null
neovm_cpp/include/vmimpl/crypto.hpp
zoowii/neo-vm-cpp
8debcc334e5b3c6afceef0bfb0ff300e0989d0a7
[ "MIT" ]
null
null
null
#ifndef NEOVM_CRYPTO_HPP #define NEOVM_CRYPTO_HPP #include "neovm/icrypto.hpp" namespace neo { namespace vm { namespace impl { class DemoCrypto : public ICrypto { public: virtual std::vector<char> Hash160(std::vector<char> message) { std::vector<char> data(10); memcpy(data.data(), "hashed160", 10); return data; } virtual std::vector<char> Hash256(std::vector<char> message) { std::vector<char> data(10); memcpy(data.data(), "hashed256", 10); return data; } virtual bool VerifySignature(std::vector<char> message, std::vector<char> signature, std::vector<char> pubkey) { return true; } }; } } } #endif
18.394737
114
0.629471
zoowii
754af97f2f81ebb524750f1395e4090d3e228534
1,246
cpp
C++
3-Stacks-And-Queues/StackMin.cpp
sonugiri1043/Cracking-The-Coding-Interview
102cdbc3199d04ab89f5d6894f0489fde352b0d7
[ "MIT" ]
8
2020-05-17T13:48:19.000Z
2022-02-20T06:42:38.000Z
3-Stacks-And-Queues/StackMin.cpp
sonugiri1043/Cracking-The-Coding-Interview
102cdbc3199d04ab89f5d6894f0489fde352b0d7
[ "MIT" ]
null
null
null
3-Stacks-And-Queues/StackMin.cpp
sonugiri1043/Cracking-The-Coding-Interview
102cdbc3199d04ab89f5d6894f0489fde352b0d7
[ "MIT" ]
6
2021-04-09T21:34:15.000Z
2021-12-13T05:40:42.000Z
/* How would you design a stack which, in addition to push and pop, has a function min which returns the minimum element? Push, pop and min should all operate in 0(1) time. */ #include <iostream> #include <stack> using namespace std; class Node{ private: int data_; int min_; public: Node( int _data ) : data_( _data ) {} int data() { return data_; } void dataIs( int _data ) { data_=_data; } void minIs( int _min ) { min_ = _min; } int min() { return min_; } }; class StackWithMinOp{ private: stack< Node* > s; public: Node * top() { return s.top(); } void pop() { s.pop(); } void push( int n ) { Node * node = new Node( n ); int currMin = n; if( not s.empty() ) { currMin = s.top()->min(); if( n < currMin ) { currMin = n; } } node->minIs( currMin ); s.push( node ); } int min() { return s.top()->min(); } }; int main() { StackWithMinOp s; s.push( 5 ); cout<< " Min " << s.min() << endl; s.push( 6 ); cout<< " Min " << s.min() << endl; s.push( 3 ); cout<< " Min " << s.min() << endl; s.push( 7 ); cout<< " Min " << s.min() << endl; s.pop(); cout<< " Min " << s.min() << endl; s.pop(); cout<< " Min " << s.min() << endl; return 0; }
19.777778
87
0.535313
sonugiri1043
754bc528e22224f92c2c6cd6536fbc7f5ea56c6d
948
cpp
C++
core/src/misc/QRCodeDataCall.cpp
azuki-monster/megamol
f5d75ae5630f9a71a7fbf81624bfd4f6b253c655
[ "BSD-3-Clause" ]
2
2020-10-16T10:15:37.000Z
2021-01-21T13:06:00.000Z
core/src/misc/QRCodeDataCall.cpp
azuki-monster/megamol
f5d75ae5630f9a71a7fbf81624bfd4f6b253c655
[ "BSD-3-Clause" ]
null
null
null
core/src/misc/QRCodeDataCall.cpp
azuki-monster/megamol
f5d75ae5630f9a71a7fbf81624bfd4f6b253c655
[ "BSD-3-Clause" ]
1
2021-01-28T01:19:54.000Z
2021-01-28T01:19:54.000Z
#include "stdafx.h" #include "mmcore/misc/QRCodeDataCall.h" using namespace megamol::core; /* * QRCodeDataCall::CallForGetText */ const unsigned int misc::QRCodeDataCall::CallForGetText = 0; /* * QRCodeDataCall::CallForSetText */ const unsigned int misc::QRCodeDataCall::CallForSetText = 1; /* * QRCodeDataCall::CallForGetPointer */ const unsigned int misc::QRCodeDataCall::CallForGetPointAt = 2; /* * QRCodeDataCall::CallForSetPointer */ const unsigned int misc::QRCodeDataCall::CallForSetPointAt = 3; /* * QRCodeDataCall::CallForGetBoundingBox */ const unsigned int misc::QRCodeDataCall::CallForGetBoundingBox = 4; /* * QRCodeDataCall::CallForSetBoundingBox */ const unsigned int misc::QRCodeDataCall::CallForSetBoundingBox = 5; misc::QRCodeDataCall::QRCodeDataCall(void) : qr_text(NULL), qr_pointer(NULL), bbox(NULL) { } misc::QRCodeDataCall::~QRCodeDataCall(void) { qr_text = NULL; qr_pointer = NULL; bbox = NULL; }
19.346939
88
0.75
azuki-monster
754bc6dceb78fe15bab3cb3861497f90e422ef04
1,907
cpp
C++
EmyRenderingEngine/src/Asset/AssetManager.cpp
TheJemy191/EmyGameEngine
cbefe9bc8e59533e4de96623a5916835846af8cd
[ "MIT" ]
null
null
null
EmyRenderingEngine/src/Asset/AssetManager.cpp
TheJemy191/EmyGameEngine
cbefe9bc8e59533e4de96623a5916835846af8cd
[ "MIT" ]
null
null
null
EmyRenderingEngine/src/Asset/AssetManager.cpp
TheJemy191/EmyGameEngine
cbefe9bc8e59533e4de96623a5916835846af8cd
[ "MIT" ]
1
2019-09-03T16:49:50.000Z
2019-09-03T16:49:50.000Z
#include "AssetManager.h" #include "Helper/Log.h" #include "Rendering/UI/ImguiBase.h" #include "Asset/MeshAsset.h" #include <filesystem> #include "Game/Setting.h" uint64_t AssetManager::IDCounter = 0; std::unordered_map<uint64_t, std::shared_ptr<Asset>> AssetManager::assetList; bool AssetManager::assetManagerWindowOpen = true; std::string AssetManager::assetToLoad; void AssetManager::Init() { IDCounter = Setting::Get("IDCounter", 0); } uint64_t AssetManager::GetIDCounter() { return IDCounter; } void AssetManager::IncrementIDCounter() { IDCounter++; Setting::Add("IDCounter", IDCounter); } std::shared_ptr<Asset> AssetManager::Get(uint64_t ID) { return assetList[ID]; } void AssetManager::Register(std::shared_ptr<Asset> asset) { assetList.emplace(asset->GetID(), asset); } void AssetManager::GUI() { if (assetManagerWindowOpen) { ImGui::SetNextWindowSize(ImVec2(600, 300), ImGuiCond_FirstUseEver); if (ImGui::Begin("Asset manager", &assetManagerWindowOpen)) { ImGui::PushItemWidth(ImGui::GetFontSize() * -12); ImGui::Text(("Asset count: " + std::to_string(assetList.size())).c_str()); ImGui::InputText("", &assetToLoad); ImGui::SameLine(); if (std::filesystem::exists("Assets/TempAssetFolder/" + assetToLoad + ".json")) { if (ImGui::Button("Load")) { if (auto loadingAsset = Asset::LoadByType(assetToLoad)) { Register(loadingAsset); } } } else ImGui::Text("File don't exist"); if (ImGui::Button("Create MeshAsset")) Register(Asset::Create<MeshAsset>()); for (auto assetPair : assetList) { Asset* asset = assetPair.second.get(); if (ImGui::TreeNode((asset->name + "|" + asset->GetType() + "###" + std::to_string(asset->GetID())).c_str())) { asset->GUI(); ImGui::TreePop(); } } } ImGui::End(); } } AssetManager::AssetManager() { } AssetManager::~AssetManager() { }
20.728261
113
0.668589
TheJemy191
755097ac4b94cf9e900d33b0ea431a14bfa3c2f2
5,575
cpp
C++
main.cpp
baskeboler/restdbxx
2723c61e154f732e7a0ec114a9654561ee22d467
[ "MIT" ]
6
2017-12-16T14:02:51.000Z
2020-02-24T22:09:42.000Z
main.cpp
baskeboler/restdbxx
2723c61e154f732e7a0ec114a9654561ee22d467
[ "MIT" ]
null
null
null
main.cpp
baskeboler/restdbxx
2723c61e154f732e7a0ec114a9654561ee22d467
[ "MIT" ]
5
2018-05-18T18:57:48.000Z
2022-03-01T16:49:28.000Z
#include <unistd.h> #include <string> #include <iostream> #include <folly/init/Init.h> #include <gflags/gflags.h> #include <glog/logging.h> #include <folly/io/async/EventBaseManager.h> #include <proxygen/httpserver/HTTPServer.h> #include <folly/executors/GlobalExecutor.h> #include <folly/executors/CPUThreadPoolExecutor.h> #include "includes.h" #include "EndpointControllerFactory.h" #include "FiltersFactory.h" #include "AuthenticationRequestHandler.h" #include "FileServerRequestHandler.h" #include "GiphySearchRequestHandler.h" #include "XkcdRequestHandler.h" using proxygen::HTTPServer; using folly::EventBase; using folly::EventBaseManager; using folly::SocketAddress; using Protocol = HTTPServer::Protocol; DEFINE_int32(http_port, 11000, "Port to listen on with HTTP protocol"); DEFINE_int32(https_port, 11043, "Port to listen on with HTTPS protocol"); DEFINE_int32(spdy_port, 11001, "Port to listen on with SPDY protocol"); DEFINE_int32(h2_port, 11002, "Port to listen on with HTTP/2 protocol"); DEFINE_string(ip, "localhost", "IP/Hostname to bind to"); DEFINE_int32(threads, 0, "Number of threads to listen on. Numbers <= 0 " "will use the number of cores on this machine."); DEFINE_string(db_path, "/tmp/restdb", "Path to the database"); DEFINE_string(ssl_cert, "cert.pem", "SSL certificate file"); DEFINE_string(ssl_key, "key.pem", "SSL key file"); DEFINE_string(giphy_api_key, "GIPHY-API-KEY", "Giphy API key"); using google::GLOG_INFO; void initConfiguration(); void init_services(); int main(int argc, char **argv) { using namespace proxygen; folly::init(&argc, &argv, false); gflags::ParseCommandLineFlags(&argc, &argv, false); google::InstallFailureSignalHandler(); initConfiguration(); auto conf = restdbxx::RestDbConfiguration::get_instance(); std::vector<HTTPServer::IPConfig> IPs = {{SocketAddress(FLAGS_ip, conf->getHttps_port(), true), Protocol::HTTP}, {SocketAddress(FLAGS_ip, conf->getHttp_port(), true), Protocol::HTTP}, {SocketAddress(FLAGS_ip, conf->getSpdy_port(), true), Protocol::SPDY}, {SocketAddress(FLAGS_ip, conf->getH2_port(), true), Protocol::HTTP2}, }; wangle::SSLContextConfig sslConfig; sslConfig.certificates = { wangle::SSLContextConfig::CertificateInfo(FLAGS_ssl_cert, FLAGS_ssl_key, "") }; sslConfig.isDefault = true; IPs.front().sslConfigs = {std::move(sslConfig)}; sslConfig.isLocalPrivateKey = true; VLOG(GLOG_INFO) << "Starting restdbxx"; VLOG(GLOG_INFO) << "HTTP PORT: " << FLAGS_http_port; VLOG(GLOG_INFO) << "HTTPS PORT: " << FLAGS_https_port; VLOG(GLOG_INFO) << "SPDY PORT: " << FLAGS_spdy_port; VLOG(GLOG_INFO) << "H2 PORT: " << FLAGS_h2_port; if (FLAGS_threads <= 0) { FLAGS_threads = sysconf(_SC_NPROCESSORS_ONLN); CHECK(FLAGS_threads > 0); } auto handlerChain = std::make_shared<RequestHandlerChain>(); handlerChain->addThen<restdbxx::FiltersFactory>() .addThen<restdbxx::AuthenticationRequestHandlerFactory>() .addThen<restdbxx::EndpointControllerFactory>(); if (conf->is_file_server_enabled()) { std::string path = conf->getFile_server_path(); std::string root = conf->getFile_server_root(); handlerChain->addThen<restdbxx::FileServerRequestHandlerFactory>(std::move(path), std::move(root)); } handlerChain ->addThen<restdbxx::UserRequestHandlerFactory>() .addThen<restdbxx::GiphySearchRequestHandlerFactory>( conf->get_giphy_mount_path(), conf->get_giphy_api_key()) .addThen<restdbxx::XkcdRequestHandlerFactory>("/xkcd") .addThen<restdbxx::RestDbRequestHandlerFactory>(); proxygen::HTTPServerOptions options; options.threads = static_cast<size_t>(FLAGS_threads); options.idleTimeout = std::chrono::milliseconds(600); options.shutdownOn = {SIGINT, SIGTERM}; options.enableContentCompression = false; options.handlerFactories = handlerChain->build(); options.h2cEnabled = false; auto diskIOThreadPool = std::make_shared<folly::CPUThreadPoolExecutor>( FLAGS_threads, std::make_shared<folly::NamedThreadFactory>("StaticDiskIOThread")); folly::setCPUExecutor(diskIOThreadPool); std::shared_ptr<proxygen::HTTPServer> server = std::make_shared<proxygen::HTTPServer>(std::move(options)); server->bind(IPs); init_services(); // Start HTTPServer mainloop in a separate thread std::thread t([&]() { folly::setThreadName("Server main thread"); server->start(); }); t.join(); return 0; } const string &DEFAULT_ADMIN_PASSWORD() { static const std::string value = "admin"; return value; } void init_services() { // force db init auto db = restdbxx::DbManager::get_instance(); auto user_manager = restdbxx::UserManager::get_instance(); if (!user_manager->user_exists("admin")) { VLOG(google::GLOG_INFO) << "admin user does not exist, creating"; user_manager->create_user("admin", DEFAULT_ADMIN_PASSWORD()); VLOG(google::GLOG_INFO) << "admin user created"; } else { VLOG(google::GLOG_INFO) << "admin user exists"; } } void initConfiguration() { std::shared_ptr<restdbxx::RestDbConfiguration> config = restdbxx::RestDbConfiguration::get_instance(); config->setHttp_port(FLAGS_http_port); config->setSpdy_port(FLAGS_spdy_port); config->setHttps_port(FLAGS_https_port); config->setDb_path(FLAGS_db_path); config->setH2_port(FLAGS_h2_port); config->setIp(FLAGS_ip); config->setThreads(FLAGS_threads); config->loadConfiguration("config.json"); }
36.677632
114
0.717848
baskeboler
7556dee6ce519bb584b351a187fb2a86872ec83d
1,765
cpp
C++
src/perf/dataperf.cpp
arntanguy/libqi
7f3e1394cb26126b26fa7ff54d2de1371a1c9f96
[ "BSD-3-Clause" ]
61
2015-01-08T08:05:28.000Z
2022-01-07T16:47:47.000Z
src/perf/dataperf.cpp
arntanguy/libqi
7f3e1394cb26126b26fa7ff54d2de1371a1c9f96
[ "BSD-3-Clause" ]
30
2015-04-06T21:41:18.000Z
2021-08-18T13:24:51.000Z
src/perf/dataperf.cpp
arntanguy/libqi
7f3e1394cb26126b26fa7ff54d2de1371a1c9f96
[ "BSD-3-Clause" ]
64
2015-02-23T20:01:11.000Z
2022-03-14T13:31:20.000Z
/* ** Author(s): ** - Nicolas Cornu <ncornu@aldebaran-robotics.com> ** ** Copyright (C) 2012-2013 Aldebaran Robotics */ #include "dataperf_p.hpp" namespace qi { DataPerfPrivate::DataPerfPrivate() : benchmarkName(""), wallClockElapsed(0), cpuElapsed(0), fLoopCount(0), fMsgSize(0), variable("") { } DataPerf::DataPerf() : _p(new DataPerfPrivate) { } DataPerf::~DataPerf() { delete _p; } void DataPerf::start(const std::string& benchmarkName, unsigned long loopCount, unsigned long msgSize, const std::string& variable) { _p->benchmarkName = benchmarkName; _p->fLoopCount = loopCount; _p->fMsgSize = msgSize; _p->variable = variable; _p->cpuTime.restart(); _p->fStartTime = qi::SteadyClock::now(); } void DataPerf::stop() { _p->cpuElapsed = _p->cpuTime.elapsed(); using second = boost::chrono::duration<double, boost::ratio<1,1>>; _p->wallClockElapsed = qi::durationSince<second>(_p->fStartTime).count(); } std::string DataPerf::getBenchmarkName() const { return _p->benchmarkName; } std::string DataPerf::getVariable() const { return _p->variable; } unsigned long DataPerf::getMsgSize() const { return _p->fMsgSize; } double DataPerf::getPeriod() const { return (double)(_p->wallClockElapsed) * 1000.0 * 1000.0 / (_p->fLoopCount); } double DataPerf::getCpu() const { return (double)(_p->cpuElapsed) / (double)(_p->wallClockElapsed) * 100; } double DataPerf::getMsgPerSecond() const { return 1.0 / ((_p->wallClockElapsed) / (1.0 * (_p->fLoopCount))); } double DataPerf::getMegaBytePerSecond() const { if (_p->fMsgSize > 0) return (getMsgPerSecond() * _p->fMsgSize) / (1024.0 * 1024.0); return -1; } }
22.341772
133
0.646459
arntanguy
755b1fc43f7190141b409820bdf18cbf6ec8904d
3,488
hpp
C++
CF++/include/CF++/CFPP-Error.hpp
macmade/CFPP
e924ca7d33103ab2cf86de292141bdd9d2aa1e4c
[ "MIT" ]
49
2015-02-16T23:04:38.000Z
2022-03-24T13:08:54.000Z
CF++/include/CF++/CFPP-Error.hpp
DigiDNA/CFPP
e093a7ff8e8f1402aac81f2c5f7dde2a529c2805
[ "MIT" ]
34
2015-04-16T18:52:39.000Z
2021-09-08T13:56:51.000Z
CF++/include/CF++/CFPP-Error.hpp
macmade/CFPP
e924ca7d33103ab2cf86de292141bdd9d2aa1e4c
[ "MIT" ]
13
2015-04-15T07:13:13.000Z
2022-03-24T13:08:58.000Z
/******************************************************************************* * The MIT License (MIT) * * Copyright (c) 2014 Jean-David Gadina - www.xs-labs.com / www.digidna.net * * 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. ******************************************************************************/ /*! * @header CFPP-Error.h * @copyright (c) 2014 - Jean-David Gadina - www.xs-labs.com / www.digidna.net * @abstract CoreFoundation++ CFErrorRef wrapper */ #ifndef CFPP_ERROR_H #define CFPP_ERROR_H namespace CF { class CFPP_EXPORT Error: public Type { public: Error( void ); Error( const Error & value ); Error( const AutoPointer & value ); Error( CFTypeRef value ); Error( CFErrorRef value ); Error( std::nullptr_t ); Error( const String & domain, const Number & code ); Error( const String & domain, const Number & code, const Dictionary & userInfo ); Error( CFStringRef domain, CFIndex code ); Error( CFStringRef domain, CFIndex code, CFDictionaryRef userInfo ); Error( const std::string & domain, CFIndex code ); Error( const std::string & domain, CFIndex code, const Dictionary & userInfo ); Error( const char * domain, CFIndex code ); Error( const char * domain, CFIndex code, const Dictionary & userInfo ); Error( Error && value ) noexcept; virtual ~Error( void ); Error & operator = ( Error value ); Error & operator = ( const AutoPointer & value ); Error & operator = ( CFTypeRef value ); Error & operator = ( CFErrorRef value ); Error & operator = ( std::nullptr_t ); virtual CFTypeID GetTypeID( void ) const; virtual CFTypeRef GetCFObject( void ) const; String GetDomain( void ) const; Number GetCode( void ) const; Dictionary GetUserInfo( void ) const; String GetDescription( void ) const; String GetFailureReason( void ) const; String GetRecoverySuggestion( void ) const; friend void swap( Error & v1, Error & v2 ) noexcept; private: CFErrorRef _cfObject; }; } #endif /* CFPP_ERROR_H */
42.024096
93
0.59117
macmade
755cc05208f8724488df609b01c234a137674592
10,191
cpp
C++
3rdParty/oculus/Samples/OculusRoomTiny/Win32_RoomTiny_Main.cpp
Internet-of-People/ApertusVR
3bb954ef02beb8a5a54ac7c062a55b7a0cf402bf
[ "MIT" ]
null
null
null
3rdParty/oculus/Samples/OculusRoomTiny/Win32_RoomTiny_Main.cpp
Internet-of-People/ApertusVR
3bb954ef02beb8a5a54ac7c062a55b7a0cf402bf
[ "MIT" ]
null
null
null
3rdParty/oculus/Samples/OculusRoomTiny/Win32_RoomTiny_Main.cpp
Internet-of-People/ApertusVR
3bb954ef02beb8a5a54ac7c062a55b7a0cf402bf
[ "MIT" ]
null
null
null
/************************************************************************************ Filename : Win32_RoomTiny_Main.cpp Content : First-person view test application for Oculus Rift Created : October 4, 2012 Authors : Tom Heath, Michael Antonov, Andrew Reisse, Volga Aksoy Copyright : Copyright 2012 Oculus, 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. *************************************************************************************/ // This app renders a simple room, with right handed coord system : Y->Up, Z->Back, X->Right // 'W','A','S','D' and arrow keys to navigate. (Other keys in Win32_RoomTiny_ExamplesFeatures.h) // 1. SDK-rendered is the simplest path (this file) // 2. APP-rendered involves other functions, in Win32_RoomTiny_AppRendered.h // 3. Further options are illustrated in Win32_RoomTiny_ExampleFeatures.h // 4. Supporting D3D11 and utility code is in Win32_DX11AppUtil.h // Choose whether the SDK performs rendering/distortion, or the application. #define SDK_RENDER 1 #include "Win32_DX11AppUtil.h" // Include Non-SDK supporting utilities #include "OVR_CAPI.h" // Include the OculusVR SDK ovrHmd HMD; // The handle of the headset ovrEyeRenderDesc EyeRenderDesc[2]; // Description of the VR. ovrRecti EyeRenderViewport[2]; // Useful to remember when varying resolution ImageBuffer * pEyeRenderTexture[2]; // Where the eye buffers will be rendered ImageBuffer * pEyeDepthBuffer[2]; // For the eye buffers to use when rendered ovrPosef EyeRenderPose[2]; // Useful to remember where the rendered eye originated float YawAtRender[2]; // Useful to remember where the rendered eye originated float Yaw(3.141592f); // Horizontal rotation of the player Vector3f Pos(0.0f,1.6f,-5.0f); // Position of player #include "Win32_RoomTiny_ExampleFeatures.h" // Include extra options to show some simple operations #if SDK_RENDER #define OVR_D3D_VERSION 11 #include "OVR_CAPI_D3D.h" // Include SDK-rendered code for the D3D version #else #include "Win32_RoomTiny_AppRender.h" // Include non-SDK-rendered specific code #endif //------------------------------------------------------------------------------------- int WINAPI WinMain(HINSTANCE hinst, HINSTANCE, LPSTR, int) { // Initializes LibOVR, and the Rift ovr_Initialize(); HMD = ovrHmd_Create(0); if (!HMD) { MessageBoxA(NULL,"Oculus Rift not detected.","", MB_OK); return(0); } if (HMD->ProductName[0] == '\0') MessageBoxA(NULL,"Rift detected, display not enabled.", "", MB_OK); // Setup Window and Graphics - use window frame if relying on Oculus driver bool windowed = (HMD->HmdCaps & ovrHmdCap_ExtendDesktop) ? false : true; if (!DX11.InitWindowAndDevice(hinst, Recti(HMD->WindowsPos, HMD->Resolution), windowed)) return(0); DX11.SetMaxFrameLatency(1); ovrHmd_AttachToWindow(HMD, DX11.Window, NULL, NULL); ovrHmd_SetEnabledCaps(HMD, ovrHmdCap_LowPersistence | ovrHmdCap_DynamicPrediction); // Start the sensor which informs of the Rift's pose and motion ovrHmd_ConfigureTracking(HMD, ovrTrackingCap_Orientation | ovrTrackingCap_MagYawCorrection | ovrTrackingCap_Position, 0); // Make the eye render buffers (caution if actual size < requested due to HW limits). for (int eye=0; eye<2; eye++) { Sizei idealSize = ovrHmd_GetFovTextureSize(HMD, (ovrEyeType)eye, HMD->DefaultEyeFov[eye], 1.0f); pEyeRenderTexture[eye] = new ImageBuffer(true, false, idealSize); pEyeDepthBuffer[eye] = new ImageBuffer(true, true, pEyeRenderTexture[eye]->Size); EyeRenderViewport[eye].Pos = Vector2i(0, 0); EyeRenderViewport[eye].Size = pEyeRenderTexture[eye]->Size; } // Setup VR components #if SDK_RENDER ovrD3D11Config d3d11cfg; d3d11cfg.D3D11.Header.API = ovrRenderAPI_D3D11; d3d11cfg.D3D11.Header.BackBufferSize = Sizei(HMD->Resolution.w, HMD->Resolution.h); d3d11cfg.D3D11.Header.Multisample = 1; d3d11cfg.D3D11.pDevice = DX11.Device; d3d11cfg.D3D11.pDeviceContext = DX11.Context; d3d11cfg.D3D11.pBackBufferRT = DX11.BackBufferRT; d3d11cfg.D3D11.pSwapChain = DX11.SwapChain; if (!ovrHmd_ConfigureRendering(HMD, &d3d11cfg.Config, ovrDistortionCap_Chromatic | ovrDistortionCap_Vignette | ovrDistortionCap_TimeWarp | ovrDistortionCap_Overdrive, HMD->DefaultEyeFov, EyeRenderDesc)) return(1); #else APP_RENDER_SetupGeometryAndShaders(); #endif // Create the room model Scene roomScene(false); // Can simplify scene further with parameter if required. // MAIN LOOP // ========= while (!(DX11.Key['Q'] && DX11.Key[VK_CONTROL]) && !DX11.Key[VK_ESCAPE]) { DX11.HandleMessages(); float speed = 1.0f; // Can adjust the movement speed. int timesToRenderScene = 1; // Can adjust the render burden on the app. ovrVector3f useHmdToEyeViewOffset[2] = {EyeRenderDesc[0].HmdToEyeViewOffset, EyeRenderDesc[1].HmdToEyeViewOffset}; // Start timing #if SDK_RENDER ovrHmd_BeginFrame(HMD, 0); #else ovrHmd_BeginFrameTiming(HMD, 0); #endif // Handle key toggles for re-centering, meshes, FOV, etc. ExampleFeatures1(&speed, &timesToRenderScene, useHmdToEyeViewOffset); // Keyboard inputs to adjust player orientation if (DX11.Key[VK_LEFT]) Yaw += 0.02f; if (DX11.Key[VK_RIGHT]) Yaw -= 0.02f; // Keyboard inputs to adjust player position if (DX11.Key['W']||DX11.Key[VK_UP]) Pos+=Matrix4f::RotationY(Yaw).Transform(Vector3f(0,0,-speed*0.05f)); if (DX11.Key['S']||DX11.Key[VK_DOWN]) Pos+=Matrix4f::RotationY(Yaw).Transform(Vector3f(0,0,+speed*0.05f)); if (DX11.Key['D']) Pos+=Matrix4f::RotationY(Yaw).Transform(Vector3f(+speed*0.05f,0,0)); if (DX11.Key['A']) Pos+=Matrix4f::RotationY(Yaw).Transform(Vector3f(-speed*0.05f,0,0)); Pos.y = ovrHmd_GetFloat(HMD, OVR_KEY_EYE_HEIGHT, Pos.y); // Animate the cube if (speed) roomScene.Models[0]->Pos = Vector3f(9*sin(0.01f*clock),3,9*cos(0.01f*clock)); // Get both eye poses simultaneously, with IPD offset already included. ovrPosef temp_EyeRenderPose[2]; ovrHmd_GetEyePoses(HMD, 0, useHmdToEyeViewOffset, temp_EyeRenderPose, NULL); // Render the two undistorted eye views into their render buffers. for (int eye = 0; eye < 2; eye++) { ImageBuffer * useBuffer = pEyeRenderTexture[eye]; ovrPosef * useEyePose = &EyeRenderPose[eye]; float * useYaw = &YawAtRender[eye]; bool clearEyeImage = true; bool updateEyeImage = true; // Handle key toggles for half-frame rendering, buffer resolution, etc. ExampleFeatures2(eye, &useBuffer, &useEyePose, &useYaw, &clearEyeImage, &updateEyeImage); if (clearEyeImage) DX11.ClearAndSetRenderTarget(useBuffer->TexRtv, pEyeDepthBuffer[eye], Recti(EyeRenderViewport[eye])); if (updateEyeImage) { // Write in values actually used (becomes significant in Example features) *useEyePose = temp_EyeRenderPose[eye]; *useYaw = Yaw; // Get view and projection matrices (note near Z to reduce eye strain) Matrix4f rollPitchYaw = Matrix4f::RotationY(Yaw); Matrix4f finalRollPitchYaw = rollPitchYaw * Matrix4f(useEyePose->Orientation); Vector3f finalUp = finalRollPitchYaw.Transform(Vector3f(0, 1, 0)); Vector3f finalForward = finalRollPitchYaw.Transform(Vector3f(0, 0, -1)); Vector3f shiftedEyePos = Pos + rollPitchYaw.Transform(useEyePose->Position); Matrix4f view = Matrix4f::LookAtRH(shiftedEyePos, shiftedEyePos + finalForward, finalUp); Matrix4f proj = ovrMatrix4f_Projection(EyeRenderDesc[eye].Fov, 0.2f, 1000.0f, true); // Render the scene for (int t=0; t<timesToRenderScene; t++) roomScene.Render(view, proj.Transposed()); } } // Do distortion rendering, Present and flush/sync #if SDK_RENDER ovrD3D11Texture eyeTexture[2]; // Gather data for eye textures for (int eye = 0; eye<2; eye++) { eyeTexture[eye].D3D11.Header.API = ovrRenderAPI_D3D11; eyeTexture[eye].D3D11.Header.TextureSize = pEyeRenderTexture[eye]->Size; eyeTexture[eye].D3D11.Header.RenderViewport = EyeRenderViewport[eye]; eyeTexture[eye].D3D11.pTexture = pEyeRenderTexture[eye]->Tex; eyeTexture[eye].D3D11.pSRView = pEyeRenderTexture[eye]->TexSv; } ovrHmd_EndFrame(HMD, EyeRenderPose, &eyeTexture[0].Texture); #else APP_RENDER_DistortAndPresent(); #endif } // Release and close down ovrHmd_Destroy(HMD); ovr_Shutdown(); DX11.ReleaseWindow(hinst); return(0); }
48.070755
114
0.619272
Internet-of-People
756bd42b2b6d39ce41f140c7984188e52775bf54
12,120
cpp
C++
modules/skottie/src/effects/LevelsEffect.cpp
muhleder/skia
a368ea077550d7b3c5607d616ff5fdfbd67eca0e
[ "BSD-3-Clause" ]
19
2018-05-28T15:21:28.000Z
2022-03-13T09:00:08.000Z
modules/skottie/src/effects/LevelsEffect.cpp
muhleder/skia
a368ea077550d7b3c5607d616ff5fdfbd67eca0e
[ "BSD-3-Clause" ]
3
2017-04-28T13:58:09.000Z
2020-09-03T09:23:39.000Z
modules/skottie/src/effects/LevelsEffect.cpp
muhleder/skia
a368ea077550d7b3c5607d616ff5fdfbd67eca0e
[ "BSD-3-Clause" ]
10
2017-08-04T08:46:49.000Z
2021-12-27T03:41:41.000Z
/* * Copyright 2019 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "modules/skottie/src/effects/Effects.h" #include "include/effects/SkTableColorFilter.h" #include "modules/skottie/src/Adapter.h" #include "modules/skottie/src/SkottieValue.h" #include "modules/sksg/include/SkSGColorFilter.h" #include "src/utils/SkJSON.h" #include <array> #include <cmath> namespace skottie { namespace internal { namespace { struct ClipInfo { ScalarValue fClipBlack = 1, // 1: clip, 2/3: don't clip fClipWhite = 1; // ^ }; struct ChannelMapper { ScalarValue fInBlack = 0, fInWhite = 1, fOutBlack = 0, fOutWhite = 1, fGamma = 1; const uint8_t* build_lut(std::array<uint8_t, 256>& lut_storage, const ClipInfo& clip_info) const { auto in_0 = fInBlack, in_1 = fInWhite, out_0 = fOutBlack, out_1 = fOutWhite, g = sk_ieee_float_divide(1, std::max(fGamma, 0.0f)); float clip[] = {0, 1}; const auto kLottieDoClip = 1; if (SkScalarTruncToInt(clip_info.fClipBlack) == kLottieDoClip) { const auto idx = fOutBlack <= fOutWhite ? 0 : 1; clip[idx] = SkTPin(out_0, 0.0f, 1.0f); } if (SkScalarTruncToInt(clip_info.fClipWhite) == kLottieDoClip) { const auto idx = fOutBlack <= fOutWhite ? 1 : 0; clip[idx] = SkTPin(out_1, 0.0f, 1.0f); } SkASSERT(clip[0] <= clip[1]); if (SkScalarNearlyEqual(in_0, out_0) && SkScalarNearlyEqual(in_1, out_1) && SkScalarNearlyEqual(g, 1)) { // no-op return nullptr; } auto dIn = in_1 - in_0, dOut = out_1 - out_0; if (SkScalarNearlyZero(dIn)) { // Degenerate dIn == 0 makes the arithmetic below explode. // // We could specialize the builder to deal with that case, or we could just // nudge by epsilon to make it all work. The latter approach is simpler // and doesn't have any noticeable downsides. // // Also nudge in_0 towards 0.5, in case it was sqashed against an extremity. // This allows for some abrupt transition when the output interval is not // collapsed, and produces results closer to AE. static constexpr auto kEpsilon = 2 * SK_ScalarNearlyZero; dIn += std::copysign(kEpsilon, dIn); in_0 += std::copysign(kEpsilon, .5f - in_0); SkASSERT(!SkScalarNearlyZero(dIn)); } auto t = -in_0 / dIn, dT = 1 / 255.0f / dIn; for (size_t i = 0; i < 256; ++i) { const auto out = out_0 + dOut * std::pow(std::max(t, 0.0f), g); SkASSERT(!SkScalarIsNaN(out)); lut_storage[i] = static_cast<uint8_t>(std::round(SkTPin(out, clip[0], clip[1]) * 255)); t += dT; } return lut_storage.data(); } }; // ADBE Easy Levels2 color correction effect. // // Maps the selected channel(s) from [inBlack...inWhite] to [outBlack, outWhite], // based on a gamma exponent. // // For [i0..i1] -> [o0..o1]: // // c' = o0 + (o1 - o0) * ((c - i0) / (i1 - i0)) ^ G // // The output is optionally clipped to the output range. // // In/out intervals are clampped to [0..1]. Inversion is allowed. class EasyLevelsEffectAdapter final : public DiscardableAdapterBase<EasyLevelsEffectAdapter, sksg::ExternalColorFilter> { public: EasyLevelsEffectAdapter(const skjson::ArrayValue& jprops, sk_sp<sksg::RenderNode> layer, const AnimationBuilder* abuilder) : INHERITED(sksg::ExternalColorFilter::Make(std::move(layer))) { enum : size_t { kChannel_Index = 0, // kHist_Index = 1, kInBlack_Index = 2, kInWhite_Index = 3, kGamma_Index = 4, kOutBlack_Index = 5, kOutWhite_Index = 6, kClipToOutBlack_Index = 7, kClipToOutWhite_Index = 8, }; EffectBinder(jprops, *abuilder, this) .bind( kChannel_Index, fChannel ) .bind( kInBlack_Index, fMapper.fInBlack ) .bind( kInWhite_Index, fMapper.fInWhite ) .bind( kGamma_Index, fMapper.fGamma ) .bind( kOutBlack_Index, fMapper.fOutBlack) .bind( kOutWhite_Index, fMapper.fOutWhite) .bind(kClipToOutBlack_Index, fClip.fClipBlack ) .bind(kClipToOutWhite_Index, fClip.fClipWhite ); } private: void onSync() override { enum LottieChannel { kRGB_Channel = 1, kR_Channel = 2, kG_Channel = 3, kB_Channel = 4, kA_Channel = 5, }; const auto channel = SkScalarTruncToInt(fChannel); std::array<uint8_t, 256> lut; if (channel < kRGB_Channel || channel > kA_Channel || !fMapper.build_lut(lut, fClip)) { this->node()->setColorFilter(nullptr); return; } this->node()->setColorFilter(SkTableColorFilter::MakeARGB( channel == kA_Channel ? lut.data() : nullptr, channel == kR_Channel || channel == kRGB_Channel ? lut.data() : nullptr, channel == kG_Channel || channel == kRGB_Channel ? lut.data() : nullptr, channel == kB_Channel || channel == kRGB_Channel ? lut.data() : nullptr )); } ChannelMapper fMapper; ClipInfo fClip; ScalarValue fChannel = 1; // 1: RGB, 2: R, 3: G, 4: B, 5: A using INHERITED = DiscardableAdapterBase<EasyLevelsEffectAdapter, sksg::ExternalColorFilter>; }; // ADBE Pro Levels2 color correction effect. // // Similar to ADBE Easy Levels2, but offers separate controls for each channel. class ProLevelsEffectAdapter final : public DiscardableAdapterBase<ProLevelsEffectAdapter, sksg::ExternalColorFilter> { public: ProLevelsEffectAdapter(const skjson::ArrayValue& jprops, sk_sp<sksg::RenderNode> layer, const AnimationBuilder* abuilder) : INHERITED(sksg::ExternalColorFilter::Make(std::move(layer))) { enum : size_t { // kHistChan_Index = 0, // kHist_Index = 1, // kRGBBegin_Index = 2, kRGBInBlack_Index = 3, kRGBInWhite_Index = 4, kRGBGamma_Index = 5, kRGBOutBlack_Index = 6, kRGBOutWhite_Index = 7, // kRGBEnd_Index = 8, // kRBegin_Index = 9, kRInBlack_Index = 10, kRInWhite_Index = 11, kRGamma_Index = 12, kROutBlack_Index = 13, kROutWhite_Index = 14, // kREnd_Index = 15, // kGBegin_Index = 16, kGInBlack_Index = 17, kGInWhite_Index = 18, kGGamma_Index = 19, kGOutBlack_Index = 20, kGOutWhite_Index = 21, // kGEnd_Index = 22, // kBBegin_Index = 23, kBInBlack_Index = 24, kBInWhite_Index = 25, kBGamma_Index = 26, kBOutBlack_Index = 27, kBOutWhite_Index = 28, // kBEnd_Index = 29, // kABegin_Index = 30, kAInBlack_Index = 31, kAInWhite_Index = 32, kAGamma_Index = 33, kAOutBlack_Index = 34, kAOutWhite_Index = 35, // kAEnd_Index = 36, kClipToOutBlack_Index = 37, kClipToOutWhite_Index = 38, }; EffectBinder(jprops, *abuilder, this) .bind( kRGBInBlack_Index, fRGBMapper.fInBlack ) .bind( kRGBInWhite_Index, fRGBMapper.fInWhite ) .bind( kRGBGamma_Index, fRGBMapper.fGamma ) .bind(kRGBOutBlack_Index, fRGBMapper.fOutBlack) .bind(kRGBOutWhite_Index, fRGBMapper.fOutWhite) .bind( kRInBlack_Index, fRMapper.fInBlack ) .bind( kRInWhite_Index, fRMapper.fInWhite ) .bind( kRGamma_Index, fRMapper.fGamma ) .bind(kROutBlack_Index, fRMapper.fOutBlack) .bind(kROutWhite_Index, fRMapper.fOutWhite) .bind( kGInBlack_Index, fGMapper.fInBlack ) .bind( kGInWhite_Index, fGMapper.fInWhite ) .bind( kGGamma_Index, fGMapper.fGamma ) .bind(kGOutBlack_Index, fGMapper.fOutBlack) .bind(kGOutWhite_Index, fGMapper.fOutWhite) .bind( kBInBlack_Index, fBMapper.fInBlack ) .bind( kBInWhite_Index, fBMapper.fInWhite ) .bind( kBGamma_Index, fBMapper.fGamma ) .bind(kBOutBlack_Index, fBMapper.fOutBlack) .bind(kBOutWhite_Index, fBMapper.fOutWhite) .bind( kAInBlack_Index, fAMapper.fInBlack ) .bind( kAInWhite_Index, fAMapper.fInWhite ) .bind( kAGamma_Index, fAMapper.fGamma ) .bind(kAOutBlack_Index, fAMapper.fOutBlack) .bind(kAOutWhite_Index, fAMapper.fOutWhite); } private: void onSync() override { std::array<uint8_t, 256> a_lut_storage, r_lut_storage, g_lut_storage, b_lut_storage; auto cf = SkTableColorFilter::MakeARGB(fAMapper.build_lut(a_lut_storage, fClip), fRMapper.build_lut(r_lut_storage, fClip), fGMapper.build_lut(g_lut_storage, fClip), fBMapper.build_lut(b_lut_storage, fClip)); // The RGB mapper composes outside individual channel mappers. if (const auto* rgb_lut = fRGBMapper.build_lut(a_lut_storage, fClip)) { cf = SkColorFilters::Compose(SkTableColorFilter::MakeARGB(nullptr, rgb_lut, rgb_lut, rgb_lut), std::move(cf)); } this->node()->setColorFilter(std::move(cf)); } ChannelMapper fRGBMapper, fRMapper, fGMapper, fBMapper, fAMapper; ClipInfo fClip; using INHERITED = DiscardableAdapterBase<ProLevelsEffectAdapter, sksg::ExternalColorFilter>; }; } // anonymous ns sk_sp<sksg::RenderNode> EffectBuilder::attachEasyLevelsEffect(const skjson::ArrayValue& jprops, sk_sp<sksg::RenderNode> layer) const { return fBuilder->attachDiscardableAdapter<EasyLevelsEffectAdapter>(jprops, std::move(layer), fBuilder); } sk_sp<sksg::RenderNode> EffectBuilder::attachProLevelsEffect(const skjson::ArrayValue& jprops, sk_sp<sksg::RenderNode> layer) const { return fBuilder->attachDiscardableAdapter<ProLevelsEffectAdapter>(jprops, std::move(layer), fBuilder); } } // namespace internal } // namespace skottie
38.971061
100
0.525
muhleder
756ee85ac8d78795348431f6872c6a274845749f
5,643
hxx
C++
code/LibUtilsQt/ProjectionParameters.hxx
mareikethies/EpipolarConsistency
63d7ca2fd705911a6c93ca4247486fc66a9d31c7
[ "Apache-2.0" ]
2
2020-03-21T16:33:51.000Z
2021-09-12T03:03:00.000Z
code/LibUtilsQt/ProjectionParameters.hxx
mareikethies/EpipolarConsistency
63d7ca2fd705911a6c93ca4247486fc66a9d31c7
[ "Apache-2.0" ]
1
2018-06-14T07:48:55.000Z
2018-06-14T07:48:55.000Z
code/LibUtilsQt/ProjectionParameters.hxx
mareikethies/EpipolarConsistency
63d7ca2fd705911a6c93ca4247486fc66a9d31c7
[ "Apache-2.0" ]
6
2018-05-15T21:38:35.000Z
2022-01-06T07:20:47.000Z
#ifndef __projection_parameters_hxx #define __projection_parameters_hxx #include <GetSet/GetSetObjects.h> #include <LibProjectiveGeometry/CameraOpenGL.hxx> namespace UtilsQt { /// A user-defined ProjectionMatrix, which can be changed by mouse interaction struct ProjectionParameters : public GetSetGui::Configurable { double fov; //< Field of View double viewing_distance; //< Distance to center Eigen::Vector4d angle; //< Viewing angles X/Y and additional rotation of the object X/Y Eigen::Vector3d center; //< Center (which camera is looking at) Eigen::Vector2d image_size; //< Size of image in pixels ProjectionParameters() : fov(20) , viewing_distance(2500) , angle(0.785,0.785,0,0) , center(0,0,0) , image_size(800,600) {} virtual Geometry::ProjectionMatrix getProjectionMatrix(double w, double h) { image_size=Eigen::Vector2d(w,h); return getProjectionMatrix(); } virtual ProjectionParameters& setFOV (double _fov ) {fov =_fov ; return *this;} virtual ProjectionParameters& setViewingDistance (double _viewing_distance ) {viewing_distance=_viewing_distance; return *this;} virtual ProjectionParameters& setAngle (const Eigen::Vector4d& _angle ) {angle =_angle ; return *this;} virtual ProjectionParameters& setCenter (const Eigen::Vector3d& _center ) {center =_center ; return *this;} virtual void mouse(int dx, int dy, bool left_button) { if (left_button) { angle[1]-=0.005*dx; angle[0]-=0.005*dy; if (angle[0]<-3.14*0.5) angle[0]=-3.14*0.5; if (angle[0]> 3.14*0.5) angle[0]=3.14*0.5; } else { angle[2]+=0.005*dx; angle[3]+=0.005*dy; } } virtual void wheel(int dy) { viewing_distance-=0.25*dy; if (viewing_distance<0) viewing_distance=0; } virtual Geometry::ProjectionMatrix getProjectionMatrix() { Eigen::Vector3d eye=viewing_distance*Eigen::Vector3d(cos(angle[1])*cos(angle[0]), sin(angle[0]), sin(angle[1])*cos(angle[0])); auto K =Geometry::cameraPerspective(fov/180*Geometry::Pi, image_size[0], image_size[1]); auto Rx =Geometry::RotationX(angle[2]); auto Rz =Geometry::RotationZ(angle[3]); return Geometry::cameraLookAt(K, eye, center)*Rx*Rz; } virtual void gui_declare_section (const GetSetGui::Section& section) { GetSet<double> ("Field of View" ,section,fov ).setDescription("The field of view in degrees."); GetSet<double> ("Distance to Center",section,viewing_distance).setDescription("Distance of camera center to focus point."); GetSet<Eigen::Vector4d>("Rotation" ,section,angle ).setDescription("Rotation of camera. Viewing angles X/Y and additional rotation of the object X/Y."); GetSet<Eigen::Vector3d>("Center" ,section,center ).setDescription("Center (which camera is looking at)."); GetSet<Eigen::Vector2d>("Image Size" ,section,image_size ).setDescription("Size of image in pixels."); } virtual void gui_retreive_section(const GetSetGui::Section& section) { fov =GetSet<double> ("Field of View" ,section); viewing_distance=GetSet<double> ("Distance to Center",section); angle =GetSet<Eigen::Vector4d>("Rotation" ,section); center =GetSet<Eigen::Vector3d>("Center" ,section); image_size =GetSet<Eigen::Vector2d>("Image Size" ,section); } }; /// A user-defined ProjectionMatrix, which can be changed by mouse interaction class ProjectionParametersGui : public ProjectionParameters, public GetSetGui::Object { public: ProjectionParametersGui(GetSetInternal::Section& section, GetSetGui::ProgressInterface* app) : ProjectionParameters() , GetSetGui::Object(section, app) {gui_declare_section(gui_section());} virtual ProjectionParameters& setFOV (double _fov ) {GetSet<double> ("Field of View" ,gui_section())=_fov ; return *this;} virtual ProjectionParameters& setViewing_distance (double _viewing_distance ) {GetSet<double> ("Distance to Center",gui_section())=_viewing_distance; return *this;} virtual ProjectionParameters& setAngle (const Eigen::Vector4d& _angle ) {GetSet<Eigen::Vector4d>("Rotation" ,gui_section())=_angle ; return *this;} virtual ProjectionParameters& setCenter (const Eigen::Vector3d& _center ) {GetSet<Eigen::Vector3d>("Center" ,gui_section())=_center ; return *this;} virtual void mouse(int dx, int dy, bool left_button) { ProjectionParameters::mouse(dx,dy,left_button); GetSet<Eigen::Vector4d>("Rotation",gui_section())=angle; } void gui_notify(const std::string& section, const GetSetInternal::Node& node) { } virtual void wheel(int dy) { ProjectionParameters::wheel(dy); GetSet<double>("Distance to Center",gui_section())=viewing_distance; } virtual Geometry::ProjectionMatrix getProjectionMatrix(double w, double h) { if (image_size!=Eigen::Vector2d(w,h)) GetSet<Eigen::Vector2d>("Image Size",gui_section())=image_size=Eigen::Vector2d(w,h); return getProjectionMatrix(); } virtual Geometry::ProjectionMatrix getProjectionMatrix() { gui_retreive_section(gui_section()); return ProjectionParameters::getProjectionMatrix(); } }; } // namespace UtilsQt #endif // __projection_parameters_hxx
41.8
190
0.658692
mareikethies
75782cad9f69f7ad7013bcf69dde118dbab6d0be
3,493
cc
C++
resonance_audio/utils/lockless_task_queue.cc
seba10000/resonance-audio
e1923fe6fe733ae4d3c8460ff883c87e2ad05d6b
[ "Apache-2.0" ]
8
2020-10-04T22:32:40.000Z
2021-11-15T05:17:00.000Z
resonance_audio/utils/lockless_task_queue.cc
seba10000/resonance-audio
e1923fe6fe733ae4d3c8460ff883c87e2ad05d6b
[ "Apache-2.0" ]
null
null
null
resonance_audio/utils/lockless_task_queue.cc
seba10000/resonance-audio
e1923fe6fe733ae4d3c8460ff883c87e2ad05d6b
[ "Apache-2.0" ]
1
2022-02-11T20:00:58.000Z
2022-02-11T20:00:58.000Z
/* Copyright 2018 Google 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. */ #include "utils/lockless_task_queue.h" #include "base/logging.h" namespace vraudio { LocklessTaskQueue::LocklessTaskQueue(size_t max_tasks) { CHECK_GT(max_tasks, 0U); Init(max_tasks); } LocklessTaskQueue::~LocklessTaskQueue() { Clear(); } void LocklessTaskQueue::Post(Task&& task) { Node* const free_node = PopNodeFromList(&free_list_head_); if (free_node == nullptr) { LOG(WARNING) << "Queue capacity reached - dropping task"; return; } free_node->task = std::move(task); PushNodeToList(&task_list_head_, free_node); } void LocklessTaskQueue::Execute() { Node* const old_task_list_head_ptr = task_list_head_.exchange(nullptr); ProcessTaskList(old_task_list_head_ptr, true /*execute_tasks*/); } void LocklessTaskQueue::Clear() { Node* const old_task_list_head_ptr = task_list_head_.exchange(nullptr); ProcessTaskList(old_task_list_head_ptr, false /*execute_tasks*/); } void LocklessTaskQueue::PushNodeToList(std::atomic<Node*>* list_head, Node* node) { DCHECK(list_head); DCHECK(node); Node* list_head_ptr; do { list_head_ptr = list_head->load(); node->next = list_head_ptr; } while (!std::atomic_compare_exchange_strong_explicit( list_head, &list_head_ptr, node, std::memory_order_release, std::memory_order_relaxed)); } LocklessTaskQueue::Node* LocklessTaskQueue::PopNodeFromList( std::atomic<Node*>* list_head) { DCHECK(list_head); Node* list_head_ptr; Node* list_head_next_ptr; do { list_head_ptr = list_head->load(); if (list_head_ptr == nullptr) { // End of list reached. return nullptr; } list_head_next_ptr = list_head_ptr->next.load(); } while (!std::atomic_compare_exchange_strong_explicit( list_head, &list_head_ptr, list_head_next_ptr, std::memory_order_relaxed, std::memory_order_relaxed)); return list_head_ptr; } void LocklessTaskQueue::ProcessTaskList(Node* list_head, bool execute) { Node* node_itr = list_head; while (node_itr != nullptr) { Node* next_node_ptr = node_itr->next; temp_tasks_.emplace_back(std::move(node_itr->task)); node_itr->task = nullptr; PushNodeToList(&free_list_head_, node_itr); node_itr = next_node_ptr; } if (execute) { // Execute tasks in reverse order. for (std::vector<Task>::reverse_iterator task_itr = temp_tasks_.rbegin(); task_itr != temp_tasks_.rend(); ++task_itr) { if (*task_itr != nullptr) { (*task_itr)(); } } } temp_tasks_.clear(); } void LocklessTaskQueue::Init(size_t num_nodes) { nodes_.resize(num_nodes); temp_tasks_.reserve(num_nodes); // Initialize free list. free_list_head_ = &nodes_[0]; for (size_t i = 0; i < num_nodes - 1; ++i) { nodes_[i].next = &nodes_[i + 1]; } nodes_[num_nodes - 1].next = nullptr; // Initialize task list. task_list_head_ = nullptr; } } // namespace vraudio
29.352941
79
0.708846
seba10000
757936eedd2c555cb8a8476e20c56f829d58cbd3
2,731
hpp
C++
ProjectMajestic/App.Impl.hpp
Edgaru089/ProjectMajestic
16cda6f86fd5ad02baedc9481609d6140cdda62a
[ "MIT" ]
1
2018-08-29T06:36:23.000Z
2018-08-29T06:36:23.000Z
ProjectMajestic/App.Impl.hpp
Edgaru089/ProjectMajestic
16cda6f86fd5ad02baedc9481609d6140cdda62a
[ "MIT" ]
null
null
null
ProjectMajestic/App.Impl.hpp
Edgaru089/ProjectMajestic
16cda6f86fd5ad02baedc9481609d6140cdda62a
[ "MIT" ]
null
null
null
#include "App.hpp" #include "LogSystem.hpp" #include "Scene.hpp" #include "GameScene.hpp" #include "TestScene.hpp" #include "IO.hpp" #include "TextSystem.hpp" //////////////////////////////////////// void App::initalaizePreWindow() { Uuid::seed(random_device()()); sceneMapper["GameScene"] = new GameScene(); sceneMapper["TestScene"] = new TestScene(); for (pair<const string, Scene*>& i : sceneMapper) i.second->preWindowInitalaize(); currentScene = sceneMapper["TestScene"]; text.loadFromFile("lang.list"); hasLog = false; } //////////////////////////////////////// void App::initalaizePostWindow(RenderWindow& win) { for (pair<const string, Scene*>& i : sceneMapper) i.second->postWindowInitalaize(win); } //////////////////////////////////////// void App::start(RenderWindow& win) { currentScene->start(win); logicDeltaClock.restart(); } //////////////////////////////////////// void App::onRender(RenderWindow& win) { currentScene->onRender(win); } //////////////////////////////////////// void App::runImGui() { //////////////////// Log Window //////////////////// if (hasLog) { ImGui::SetNextWindowSize(ImVec2(500, 400), ImGuiCond_FirstUseEver); if (imgui::Begin("Logs", NULL, ImGuiWindowFlags_MenuBar)) { //////// Menu Bar //////// static bool follow = true; if (imgui::BeginMenuBar()) { if (imgui::BeginMenu("Controls")) { if (imgui::MenuItem("Clear")) dlog.clearBuffer(); imgui::Separator(); imgui::MenuItem("Follow the end of log ", NULL, &follow); imgui::EndMenu(); } imgui::EndMenuBar(); } //////// Text Area //////// imgui::BeginChild("DigitLogScroll", Vector2i(0, 0), true); static float size; string total; for (const string& i : dlog.getBuffers()) total += (i + '\n'); imgui::TextUnformatted(total.c_str()); if (size != imgui::GetScrollMaxY() && follow) imgui::SetScrollY(imgui::GetScrollMaxY()); size = imgui::GetScrollMaxY(); imgui::EndChild(); } imgui::End(); } currentScene->runImGui(); } //////////////////////////////////////// void App::updateLogic(RenderWindow& win) { logicIO.deltaTime = logicDeltaClock.restart(); logicIO.renderSize = Vector2i(win.getSize()); logicIO.hasFocus = win.hasFocus(); // Keystate and mouse position handled by game scene for pausing game issues currentScene->updateLogic(win); Scene::updateScene(win); } //////////////////////////////////////// void App::handleEvent(RenderWindow& win, Event& e) { currentScene->handleEvent(win, e); } //////////////////////////////////////// void App::onViewportChange(RenderWindow& win) { } //////////////////////////////////////// void App::onStop() { currentScene->stop(); }
21.335938
77
0.565361
Edgaru089
7579af03644f352a181da3c58d3d992736bccbdc
7,922
cpp
C++
test/combine/pubsub_2d_test.cpp
llamerada-jp/colonio
8594d3131249eda59980faa281c353988469481a
[ "Apache-2.0" ]
5
2021-12-12T23:35:21.000Z
2022-01-09T22:01:53.000Z
test/combine/pubsub_2d_test.cpp
llamerada-jp/colonio
8594d3131249eda59980faa281c353988469481a
[ "Apache-2.0" ]
null
null
null
test/combine/pubsub_2d_test.cpp
llamerada-jp/colonio
8594d3131249eda59980faa281c353988469481a
[ "Apache-2.0" ]
1
2020-07-07T13:17:19.000Z
2020-07-07T13:17:19.000Z
/* * Copyright 2017 Yuji Ito <llamerada.jp@gmail.com> * * 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 <gmock/gmock.h> #include <gtest/gtest.h> #include <cmath> #include <tuple> #include "colonio/colonio.hpp" #include "test_utils/all.hpp" using namespace colonio; using ::testing::MatchesRegex; double d2r(double d) { return M_PI * d / 180.0; } TEST(Pubsub2DTest, pubsub_async) { const std::string URL = "http://localhost:8080/test"; const std::string TOKEN = ""; const std::string PUBSUB_2D_NAME = "ps2"; AsyncHelper helper; TestSeed seed; seed.set_coord_system_sphere(); seed.add_module_pubsub_2d(PUBSUB_2D_NAME, 256); seed.run(); std::unique_ptr<Colonio> node1(Colonio::new_instance(log_receiver("node1"))); std::unique_ptr<Colonio> node2(Colonio::new_instance(log_receiver("node2"))); printf("connect node1\n"); node1->connect( URL, TOKEN, [&URL, &TOKEN, &node2, &helper](Colonio& _) { printf("connect node2\n"); node2->connect( URL, TOKEN, [&helper](Colonio& _) { helper.pass_signal("connect"); }, [](Colonio&, const Error& err) { std::cout << err.message << std::endl; ADD_FAILURE(); }); }, [](Colonio&, const Error& err) { std::cout << err.message << std::endl; ADD_FAILURE(); }); printf("wait connecting\n"); helper.wait_signal("connect"); Pubsub2D& ps1 = node1->access_pubsub_2d(PUBSUB_2D_NAME); Pubsub2D& ps2 = node2->access_pubsub_2d(PUBSUB_2D_NAME); ps1.on("key", [&helper](Pubsub2D&, const Value& v) { helper.mark("1" + v.get<std::string>()); helper.pass_signal("on1"); }); ps2.on("key", [&helper](Pubsub2D&, const Value& v) { helper.mark("2" + v.get<std::string>()); helper.pass_signal("on2"); }); { double x, y; printf("set position node1\n"); std::tie(x, y) = node1->set_position(d2r(50), d2r(50)); EXPECT_FLOAT_EQ(d2r(50), x); EXPECT_FLOAT_EQ(d2r(50), y); } { double x, y; printf("set position node2\n"); std::tie(x, y) = node2->set_position(d2r(50), d2r(50)); EXPECT_FLOAT_EQ(d2r(50), x); EXPECT_FLOAT_EQ(d2r(50), y); } printf("wait publishing\n"); helper.wait_signal("on1", [&ps2] { printf("publish position node2\n"); ps2.publish( "key", d2r(50), d2r(50), 10, Value("b"), 0, [](Pubsub2D& _) {}, [](Pubsub2D& _, const Error& err) { std::cout << err.message << std::endl; ADD_FAILURE(); }); }); helper.wait_signal("on2", [&ps1] { printf("publish position node1\n"); ps1.publish( "key", d2r(50), d2r(50), 10, Value("a"), 0, [](Pubsub2D& _) {}, [](Pubsub2D& _, const Error& err) { std::cout << err.message << std::endl; ADD_FAILURE(); }); }); printf("disconnect\n"); node1->disconnect(); node2->disconnect(); EXPECT_THAT(helper.get_route(), MatchesRegex("^1b2a|2a1b$")); } TEST(Pubsub2DTest, multi_node) { const std::string URL = "http://localhost:8080/test"; const std::string TOKEN = ""; const std::string PUBSUB_2D_NAME = "ps2"; AsyncHelper helper; TestSeed seed; seed.set_coord_system_sphere(); seed.add_module_pubsub_2d(PUBSUB_2D_NAME, 256); seed.run(); std::unique_ptr<Colonio> node1(Colonio::new_instance(log_receiver("node1"))); std::unique_ptr<Colonio> node2(Colonio::new_instance(log_receiver("node2"))); try { // connect node1; printf("connect node1\n"); node1->connect(URL, TOKEN); Pubsub2D& ps1 = node1->access_pubsub_2d(PUBSUB_2D_NAME); ps1.on("key1", [&helper](Pubsub2D&, const Value& v) { helper.mark("11"); helper.mark(v.get<std::string>()); helper.pass_signal("on11"); }); ps1.on("key2", [&helper](Pubsub2D&, const Value& v) { helper.mark("12"); helper.mark(v.get<std::string>()); helper.pass_signal("on12"); }); // connect node2; printf("connect node2\n"); node2->connect(URL, TOKEN); Pubsub2D& ps2 = node2->access_pubsub_2d(PUBSUB_2D_NAME); ps2.on("key1", [&helper](Pubsub2D&, const Value& v) { helper.mark("21"); helper.mark(v.get<std::string>()); helper.pass_signal("on21"); }); ps2.on("key2", [&helper](Pubsub2D&, const Value& v) { helper.mark("22"); helper.mark(v.get<std::string>()); helper.pass_signal("on22"); }); printf("set position 1 and 2\n"); node1->set_position(d2r(100), d2r(50)); node2->set_position(d2r(50), d2r(50)); helper.wait_signal("on21", [&ps1] { printf("publish a\n"); ps1.publish("key1", d2r(50), d2r(50), 10, Value("a")); // 21a }); printf("publish b\n"); ps2.publish("key2", d2r(50), d2r(50), 10, Value("b")); // none helper.clear_signal(); printf("set position 2\n"); node2->set_position(d2r(-20), d2r(10)); printf("publish c\n"); ps1.publish("key1", d2r(50), d2r(50), 10, Value("c")); // none helper.wait_signal("on21", [&ps1] { printf("publish d\n"); ps1.publish("key1", d2r(-20), d2r(10), 10, Value("d")); // 21d }); helper.wait_signal("on22", [&ps1] { printf("publish e\n"); ps1.publish("key2", d2r(-20), d2r(10), 10, Value("e")); // 22e }); } catch (colonio::Error& err) { printf("exception code:%u: %s\n", static_cast<uint32_t>(err.code), err.message.c_str()); ADD_FAILURE(); } // disconnect printf("disconnect\n"); node1->disconnect(); node2->disconnect(); EXPECT_THAT(helper.get_route(), MatchesRegex("^21a21d22e$")); } TEST(Pubsub2DTest, pubsub_plane) { const std::string URL = "http://localhost:8080/test"; const std::string TOKEN = ""; const std::string PUBSUB_2D_NAME = "ps2"; printf("setup seed\n"); AsyncHelper helper; TestSeed seed; seed.set_coord_system_plane(); seed.add_module_pubsub_2d(PUBSUB_2D_NAME, 256); seed.run(); printf("create instance1\n"); std::unique_ptr<Colonio> node1(Colonio::new_instance(log_receiver("node1"))); printf("create instance2\n"); std::unique_ptr<Colonio> node2(Colonio::new_instance(log_receiver("node2"))); // connect node1; printf("connect node1\n"); node1->connect(URL, TOKEN); printf("connect node1 fin\n"); Pubsub2D& ps1 = node1->access_pubsub_2d(PUBSUB_2D_NAME); ps1.on("key1", [&helper](Pubsub2D&, const Value& v) { helper.mark("11"); helper.mark(v.get<std::string>()); }); ps1.on("key2", [&helper](Pubsub2D&, const Value& v) { helper.mark("12"); helper.mark(v.get<std::string>()); }); // connect node2; printf("connect node2\n"); node2->connect(URL, TOKEN); printf("connect node2 fin\n"); Pubsub2D& ps2 = node2->access_pubsub_2d(PUBSUB_2D_NAME); ps2.on("key1", [&helper](Pubsub2D&, const Value& v) { helper.mark("21"); helper.mark(v.get<std::string>()); }); ps2.on("key2", [&helper](Pubsub2D&, const Value& v) { helper.mark("22"); helper.mark(v.get<std::string>()); }); double x1, y1; std::tie(x1, y1) = node1->set_position(-0.5, 0.5); EXPECT_FLOAT_EQ(x1, -0.5); EXPECT_FLOAT_EQ(y1, 0.5); double x2, y2; std::tie(x2, y2) = node2->set_position(0.5, -0.5); EXPECT_FLOAT_EQ(x2, 0.5); EXPECT_FLOAT_EQ(y2, -0.5); // disconnect printf("disconnect\n"); node1->disconnect(); node2->disconnect(); }
29.670412
92
0.611083
llamerada-jp
757bb370aff8cec66cf79dcffe9589f88ec313c1
9,950
cc
C++
src/lib/remote_rom/backend/nic_ip/server.cc
cproc/genode-world
c3b9d920027b6edbd873e4ff8f58005f2456a9ed
[ "MIT" ]
43
2015-12-16T15:29:25.000Z
2022-02-06T12:40:35.000Z
src/lib/remote_rom/backend/nic_ip/server.cc
cproc/genode-world
c3b9d920027b6edbd873e4ff8f58005f2456a9ed
[ "MIT" ]
267
2015-12-17T15:09:32.000Z
2022-03-30T11:36:27.000Z
src/lib/remote_rom/backend/nic_ip/server.cc
cproc/genode-world
c3b9d920027b6edbd873e4ff8f58005f2456a9ed
[ "MIT" ]
37
2015-12-16T15:40:08.000Z
2021-04-27T14:08:50.000Z
/* * \brief Server implementation * \author Johannes Schlatow * \author Edgard Schmidt * \date 2018-11-06 */ #include <base.h> #include <backend_base.h> namespace Remote_rom { using Genode::Cstring; using Genode::Microseconds; class Content_sender; class Backend_server; }; class Remote_rom::Content_sender { private: enum { MAX_PAYLOAD_SIZE = DataPacket::MAX_PAYLOAD_SIZE, MAX_WINDOW_SIZE = 900, TIMEOUT_ACK_US = 1000000 /* 1000ms */ }; /* total data size */ size_t _data_size { 0 }; /* current window length */ size_t _window_length { MAX_WINDOW_SIZE }; /* current window id */ size_t _window_id { 0 }; /* data offset of current window */ size_t _offset { 0 }; /* current packed id */ size_t _packet_id { 0 }; size_t _errors { 0 }; /* timeouts and general object management*/ Timer::One_shot_timeout<Content_sender> _timeout; Backend_server &_backend; Rom_forwarder_base *_frontend { nullptr }; void timeout_handler(Genode::Duration) { Genode::warning("no ACK received for window ", _window_id); /* only handle */ if (_errors == 0) { /* go back to beginning of window */ go_back(0); transmit(false); } else { reset(); _frontend->finish_transmission(); Genode::warning("transmission cancelled"); } _errors++; } /* Noncopyable */ Content_sender(Content_sender const &); Content_sender &operator=(Content_sender const &); static size_t _calculate_window_size(size_t size) { size_t const mod = size % MAX_PAYLOAD_SIZE; size_t const packets = size / MAX_PAYLOAD_SIZE + (mod ? 1 : 0); return Genode::min((size_t)MAX_WINDOW_SIZE, packets); } /** * Go to next packet. Returns false if window is complete. */ inline bool _next_packet() { return ++_packet_id < _window_length; } inline bool _window_complete() const { return _packet_id == _window_length; } inline bool _transmission_complete() const { return _offset >= _data_size; } /** * Return absolute data offset of current packet. */ inline size_t _data_offset() const { return _offset + _packet_id * MAX_PAYLOAD_SIZE; } /** * Go to next window. Returns false if end of data was reached. * TODO we may adapt the window size if retransmission occurred */ bool _next_window() { /* advance offset by data transmitted in the last window */ _offset += _window_length * MAX_PAYLOAD_SIZE; if (_transmission_complete()) return false; _window_id++; _window_length = _calculate_window_size(_data_size-_offset); _packet_id = 0; return true; } public: Content_sender(Timer::Connection &timer, Backend_server &backend) : _timeout(timer, *this, &Content_sender::timeout_handler), _backend(backend) { } void register_forwarder(Rom_forwarder_base *forwarder) { _frontend = forwarder; } void reset() { _offset = 0; _packet_id = 0; _window_id = 0; _data_size = 0; _window_length = 0; _errors = 0; } bool transmitting() { return _packet_id > 0; } /********************** * frontend accessors * **********************/ unsigned content_hash() const { return _frontend ? _frontend->content_hash() : 0; } size_t content_size() const { return _frontend ? _frontend->content_size() : 0; } char const *module_name() const { return _frontend ? _frontend->module_name() : ""; } size_t transfer_content(char* dst, size_t max_size) const { if (!_frontend) return 0; return _frontend->transfer_content(dst, max_size, _data_offset()); } /************************ * transmission control * ************************/ bool transmit(bool restart); void go_back(size_t packet_id) { _packet_id = packet_id; } /************************************* * accessors for packet construction * *************************************/ /** * Return payload size of current packet. */ size_t payload_size() const { return Genode::min(_data_size-_data_offset(), (size_t)MAX_PAYLOAD_SIZE); } size_t window_id() const { return _window_id; } size_t window_length() const { return _window_length; } size_t packet_id() const { return _packet_id; } }; class Remote_rom::Backend_server : public Backend_server_base, public Backend_base { private: friend class Content_sender; Content_sender _content_sender { _timer, *this }; Backend_server(Backend_server &); Backend_server &operator= (Backend_server &); void send_packet(Content_sender const &sender); void receive(Packet &packet, Size_guard &) override; public: Backend_server(Genode::Env &env, Genode::Allocator &alloc, Genode::Xml_node config, Genode::Xml_node policy) : Backend_base(env, alloc, config, policy) { } void register_forwarder(Rom_forwarder_base *forwarder) override { _content_sender.register_forwarder(forwarder); } void send_update() override { if (!_content_sender.content_size()) return; if (_verbose) Genode::log("sending SIGNAL(", _content_sender.module_name(), ")"); /* TODO re-send SIGNAL packet after a timeout */ transmit_notification(Packet::SIGNAL, _content_sender); } }; namespace Remote_rom { using Genode::Env; using Genode::Allocator; using Genode::Xml_node; Backend_server_base &backend_init_server(Env &env, Allocator &alloc, Xml_node config) { static Backend_server backend(env, alloc, config, config.sub_node("remote_rom")); return backend; } }; void Remote_rom::Backend_server::send_packet(Content_sender const &sender) { /* create and transmit packet via NIC session */ size_t const max_payload = sender.payload_size(); size_t const max_size = sizeof(Ethernet_frame) + sizeof(Ipv4_packet) + sizeof(Udp_packet) + sizeof(Packet) + sizeof(DataPacket) + max_payload; Nic::Packet_descriptor pd = alloc_tx_packet(max_size); Size_guard size_guard(pd.size()); char* const content = _nic.tx()->packet_content(pd); Ethernet_frame &eth = prepare_eth(content, size_guard); size_t const ip_off = size_guard.head_size(); Ipv4_packet &ip = prepare_ipv4(eth, size_guard); size_t const udp_off = size_guard.head_size(); Udp_packet &udp = prepare_udp(ip, size_guard); Packet &pak = udp.construct_at_data<Packet>(size_guard); pak.type(Packet::DATA); pak.module_name(sender.module_name()); pak.content_hash(sender.content_hash()); DataPacket &data = pak.construct_at_data<DataPacket>(size_guard); data.window_id(sender.window_id()); data.window_length(sender.window_length()); data.packet_id(sender.packet_id()); size_guard.consume_head(max_payload); data.payload_size(sender.transfer_content((char*)data.addr(), max_payload)); /* fill in header values that need the packet to be complete already */ udp.length(size_guard.head_size() - udp_off); if (!_chksum_offload) udp.update_checksum(ip.src(), ip.dst()); ip.total_length(size_guard.head_size() - ip_off); ip.update_checksum(); submit_tx_packet(pd); } void Remote_rom::Backend_server::receive(Packet &packet, Size_guard &size_guard) { switch (packet.type()) { case Packet::UPDATE: if (_verbose) Genode::log("receiving UPDATE (", Cstring(packet.module_name()), ") packet"); /* check module name */ if (Genode::strcmp(packet.module_name(), _content_sender.module_name())) return; /* compare content hash */ if (packet.content_hash() != _content_sender.content_hash()) { if (_verbose) Genode::log("ignoring UPDATE with invalid hash"); return; } if (_verbose) { Genode::log("Sending data of size ", _content_sender.content_size()); } _content_sender.transmit(true); break; case Packet::SIGNAL: if (_verbose) Genode::log("ignoring SIGNAL"); break; case Packet::DATA: if (_verbose) Genode::log("ignoring DATA"); break; case Packet::ACK: { if (!_content_sender.transmitting()) return; if (Genode::strcmp(packet.module_name(), _content_sender.module_name())) return; if (packet.content_hash() != _content_sender.content_hash()) { if (_verbose) Genode::warning("ignoring ACK with wrong hash"); return; } AckPacket const &ack = packet.data<AckPacket>(size_guard); if (ack.window_id() != _content_sender.window_id()) { if (_verbose) Genode::warning("ignoring ACK with wrong window id"); return; } if (ack.ack_until() < _content_sender.packet_id()) { if (_verbose) Genode::warning("Go back to packet id ", ack.ack_until()); _content_sender.go_back(ack.ack_until()); } _content_sender.transmit(false); break; } default: break; } } bool Remote_rom::Content_sender::transmit(bool restart) { if (!_frontend) return false; if (_timeout.scheduled()) _timeout.discard(); _errors = 0; if (restart) { /* do not start if we are still transmitting */ if (!_transmission_complete()) return false; _frontend->start_transmission(); reset(); _data_size = _frontend->content_size(); _window_length = _calculate_window_size(_data_size); } else if (_window_complete()) { if (!_next_window()) { _frontend->finish_transmission(); if (transmitting()) { reset(); return true; } else return false; } } do { _backend.send_packet(*this); } while (_next_packet()); /* set ACK timeout */ _timeout.schedule(Microseconds(TIMEOUT_ACK_US)); return false; }
24.507389
75
0.642312
cproc
757c485b28a10b331ba2b5458a3c07cac5d7d9b5
2,829
cpp
C++
toonz/sources/common/tcolor/tcolorfunctions.cpp
rozhuk-im/opentoonz
ad5b632512746b97fd526aa79660fbaedf934fad
[ "BSD-3-Clause" ]
3,710
2016-03-26T00:40:48.000Z
2022-03-31T21:35:12.000Z
toonz/sources/common/tcolor/tcolorfunctions.cpp
rozhuk-im/opentoonz
ad5b632512746b97fd526aa79660fbaedf934fad
[ "BSD-3-Clause" ]
4,246
2016-03-26T01:21:45.000Z
2022-03-31T23:10:47.000Z
toonz/sources/common/tcolor/tcolorfunctions.cpp
rozhuk-im/opentoonz
ad5b632512746b97fd526aa79660fbaedf934fad
[ "BSD-3-Clause" ]
633
2016-03-26T00:42:25.000Z
2022-03-17T02:55:13.000Z
#include <cstring> #include "tcolorfunctions.h" #include "tpixelutils.h" TPixel32 TColorFader::operator()(const TPixel32 &color) const { TPixel32 ret = blend(color, m_color, m_fade); return ret; } bool TColorFader::getParameters(Parameters &p) const { p.m_mR = p.m_mG = p.m_mB = p.m_mM = (1 - m_fade); p.m_cR = m_fade * m_color.r; p.m_cG = m_fade * m_color.g; p.m_cB = m_fade * m_color.b; p.m_cM = m_fade * m_color.m; return true; } //--------------------------------------- TGenericColorFunction::TGenericColorFunction(const double m[4], const double c[4]) { memcpy(m_m, m, 4 * sizeof(double)); memcpy(m_c, c, 4 * sizeof(double)); } //--------------------------------------- TPixel32 TGenericColorFunction::operator()(const TPixel32 &color) const { return TPixel32(tcrop(m_m[0] * color.r + m_c[0], 0.0, 255.0), tcrop(m_m[1] * color.g + m_c[1], 0.0, 255.0), tcrop(m_m[2] * color.b + m_c[2], 0.0, 255.0), tcrop(m_m[3] * color.m + m_c[3], 0.0, 255.0)); } //--------------------------------------- bool TGenericColorFunction::getParameters(Parameters &p) const { p.m_mR = m_m[0], p.m_mG = m_m[1], p.m_mB = m_m[2], p.m_mM = m_m[3]; p.m_cR = m_c[0], p.m_cG = m_c[1], p.m_cB = m_c[2], p.m_cM = m_c[3]; return true; } //--------------------------------------- TPixel32 TTranspFader::operator()(const TPixel32 &color) const { return TPixel32(color.r, color.g, color.b, m_transp * color.m); } //--------------------------------------- bool TTranspFader::getParameters(Parameters &p) const { assert(false); return true; } //---------------------------------- TPixel32 TOnionFader::operator()(const TPixel32 &color) const { if (color.m == 0) return color; TPixel32 blendColor = blend(color, m_color, m_fade); blendColor.m = 180; return blendColor; } bool TOnionFader::getParameters(Parameters &p) const { p.m_mR = p.m_mG = p.m_mB = (1 - m_fade); p.m_mM = 1; p.m_cR = m_fade * m_color.r; p.m_cG = m_fade * m_color.g; p.m_cB = m_fade * m_color.b; p.m_cM = m_color.m; return true; } //--------------------------------------- TPixel32 TColumnColorFilterFunction::operator()(const TPixel32 &color) const { int r = 255 - (255 - color.r) * (255 - m_colorScale.r) / 255; int g = 255 - (255 - color.g) * (255 - m_colorScale.g) / 255; int b = 255 - (255 - color.b) * (255 - m_colorScale.b) / 255; return TPixel32(r, g, b, color.m * m_colorScale.m / 255); } bool TColumnColorFilterFunction::getParameters(Parameters &p) const { assert(false); return true; }
30.75
78
0.521386
rozhuk-im
757caad7267e37f6c9b4817c2b9d7e4fa4bbe42a
4,707
cpp
C++
editor/terrain/voxel_terrain_editor_plugin.cpp
PhilipWee/godot_voxel
117802c80766d040ae4d549319d90636512e3d8e
[ "MIT" ]
1
2020-11-28T06:44:32.000Z
2020-11-28T06:44:32.000Z
editor/terrain/voxel_terrain_editor_plugin.cpp
PhilipWee/godot_voxel
117802c80766d040ae4d549319d90636512e3d8e
[ "MIT" ]
null
null
null
editor/terrain/voxel_terrain_editor_plugin.cpp
PhilipWee/godot_voxel
117802c80766d040ae4d549319d90636512e3d8e
[ "MIT" ]
null
null
null
#include "voxel_terrain_editor_plugin.h" #include "../../generators/voxel_generator.h" #include "../../terrain/voxel_lod_terrain.h" #include "../../terrain/voxel_terrain.h" #include "../graph/voxel_graph_node_inspector_wrapper.h" VoxelTerrainEditorPlugin::VoxelTerrainEditorPlugin(EditorNode *p_node) { _restart_stream_button = memnew(Button); _restart_stream_button->set_text(TTR("Re-generate")); _restart_stream_button->connect("pressed", this, "_on_restart_stream_button_pressed"); _restart_stream_button->hide(); add_control_to_container(CONTAINER_SPATIAL_EDITOR_MENU, _restart_stream_button); } static Node *get_as_terrain(Object *p_object) { VoxelTerrain *terrain = Object::cast_to<VoxelTerrain>(p_object); if (terrain != nullptr) { return terrain; } VoxelLodTerrain *terrain2 = Object::cast_to<VoxelLodTerrain>(p_object); if (terrain2 != nullptr) { return terrain2; } return nullptr; } // Things the plugin doesn't directly work on, but still handles to keep things visible. // This is basically a hack because it's not easy to express that with EditorPlugin API. // The use case being, as long as we edit an object NESTED within a voxel terrain, we should keep things visible. static bool is_side_handled(Object *p_object) { // Handle stream too so we can leave some controls visible while we edit a stream or generator VoxelGenerator *generator = Object::cast_to<VoxelGenerator>(p_object); if (generator != nullptr) { return true; } // And have to account for this hack as well VoxelGraphNodeInspectorWrapper *wrapper = Object::cast_to<VoxelGraphNodeInspectorWrapper>(p_object); if (wrapper != nullptr) { return true; } return false; } bool VoxelTerrainEditorPlugin::handles(Object *p_object) const { if (get_as_terrain(p_object) != nullptr) { return true; } if (_node != nullptr) { return is_side_handled(p_object); } return false; } void VoxelTerrainEditorPlugin::edit(Object *p_object) { Node *node = get_as_terrain(p_object); if (node != nullptr) { set_node(node); } else { if (!is_side_handled(p_object)) { set_node(nullptr); } } } void VoxelTerrainEditorPlugin::set_node(Node *node) { if (_node != nullptr) { // Using this to know when the node becomes really invalid, because ObjectID is unreliable in Godot 3.x, // and we may want to keep access to the node when we select some different kinds of objects. // Also moving the node around in the tree triggers exit/enter so have to listen for both. _node->disconnect("tree_entered", this, "_on_terrain_tree_entered"); _node->disconnect("tree_exited", this, "_on_terrain_tree_exited"); VoxelLodTerrain *vlt = Object::cast_to<VoxelLodTerrain>(_node); if (vlt != nullptr) { vlt->set_show_gizmos(false); } } _node = node; if (_node != nullptr) { _node->connect("tree_entered", this, "_on_terrain_tree_entered", varray(_node)); _node->connect("tree_exited", this, "_on_terrain_tree_exited", varray(_node)); VoxelLodTerrain *vlt = Object::cast_to<VoxelLodTerrain>(_node); if (vlt != nullptr) { vlt->set_show_gizmos(true); } } } void VoxelTerrainEditorPlugin::make_visible(bool visible) { _restart_stream_button->set_visible(visible); if (_node != nullptr) { VoxelLodTerrain *vlt = Object::cast_to<VoxelLodTerrain>(_node); if (vlt != nullptr) { vlt->set_show_gizmos(visible); } } // TODO There are deselection problems I cannot fix cleanly! // Can't use `make_visible(false)` to reset our reference to the node or reset gizmos, // because of https://github.com/godotengine/godot/issues/40166 // So we'll need to check if _node is null all over the place } void VoxelTerrainEditorPlugin::_on_restart_stream_button_pressed() { ERR_FAIL_COND(_node == nullptr); VoxelTerrain *terrain = Object::cast_to<VoxelTerrain>(_node); if (terrain != nullptr) { terrain->restart_stream(); return; } VoxelLodTerrain *terrain2 = Object::cast_to<VoxelLodTerrain>(_node); ERR_FAIL_COND(terrain2 == nullptr); terrain2->restart_stream(); } void VoxelTerrainEditorPlugin::_on_terrain_tree_entered(Node *node) { _node = node; } void VoxelTerrainEditorPlugin::_on_terrain_tree_exited(Node *node) { // If the node exited the tree because it was deleted, signals we connected should automatically disconnect. _node = nullptr; } void VoxelTerrainEditorPlugin::_bind_methods() { ClassDB::bind_method(D_METHOD("_on_restart_stream_button_pressed"), &VoxelTerrainEditorPlugin::_on_restart_stream_button_pressed); ClassDB::bind_method(D_METHOD("_on_terrain_tree_entered"), &VoxelTerrainEditorPlugin::_on_terrain_tree_entered); ClassDB::bind_method(D_METHOD("_on_terrain_tree_exited"), &VoxelTerrainEditorPlugin::_on_terrain_tree_exited); }
34.610294
113
0.756533
PhilipWee
757cace84ded8c41e9ff450a96b4cfb16ab7e6d4
172
cpp
C++
DaedalicTestAutomationPlugin/Source/DaedalicTestAutomationPlugin/Private/DaeTestPerformanceBudgetResultData.cpp
DeadMonkeyEntertaiment/ue4-test-automation
d5ba1e22c52bdabdd331766f9272dfc1d4b20962
[ "MIT" ]
128
2020-04-22T12:51:08.000Z
2022-03-30T07:21:27.000Z
DaedalicTestAutomationPlugin/Source/DaedalicTestAutomationPlugin/Private/DaeTestPerformanceBudgetResultData.cpp
DeadMonkeyEntertaiment/ue4-test-automation
d5ba1e22c52bdabdd331766f9272dfc1d4b20962
[ "MIT" ]
23
2020-05-13T11:15:33.000Z
2022-03-30T19:24:26.000Z
DaedalicTestAutomationPlugin/Source/DaedalicTestAutomationPlugin/Private/DaeTestPerformanceBudgetResultData.cpp
DeadMonkeyEntertaiment/ue4-test-automation
d5ba1e22c52bdabdd331766f9272dfc1d4b20962
[ "MIT" ]
46
2020-04-23T14:33:29.000Z
2022-03-24T08:44:56.000Z
#include "DaeTestPerformanceBudgetResultData.h" FName FDaeTestPerformanceBudgetResultData::GetDataType() const { return TEXT("FDaeTestPerformanceBudgetResultData"); }
24.571429
62
0.831395
DeadMonkeyEntertaiment
758082f5c8f5ed3f6386881eeb2d77cd54d18561
2,374
cpp
C++
Sources/Rosetta/Battlegrounds/Triggers/Trigger.cpp
Hearthstonepp/Hearthstonepp
ee17ae6de1ee0078dab29d75c0fbe727a14e850e
[ "MIT" ]
62
2017-08-21T14:11:00.000Z
2018-04-23T16:09:02.000Z
Sources/Rosetta/Battlegrounds/Triggers/Trigger.cpp
Hearthstonepp/Hearthstonepp
ee17ae6de1ee0078dab29d75c0fbe727a14e850e
[ "MIT" ]
37
2017-08-21T11:13:07.000Z
2018-04-30T08:58:41.000Z
Sources/Rosetta/Battlegrounds/Triggers/Trigger.cpp
Hearthstonepp/Hearthstonepp
ee17ae6de1ee0078dab29d75c0fbe727a14e850e
[ "MIT" ]
10
2017-08-21T03:44:12.000Z
2018-01-10T22:29:10.000Z
// This code is based on Sabberstone project. // Copyright (c) 2017-2021 SabberStone Team, darkfriend77 & rnilva // RosettaStone is hearthstone simulator using C++ with reinforcement learning. // Copyright (c) 2017-2021 Chris Ohk #include <Rosetta/Battlegrounds/Models/Minion.hpp> #include <Rosetta/Battlegrounds/Models/Player.hpp> #include <Rosetta/Battlegrounds/Triggers/Trigger.hpp> namespace RosettaStone::Battlegrounds { Trigger::Trigger(TriggerType type) : m_triggerType(type) { // Do nothing } TriggerType Trigger::GetTriggerType() const { return m_triggerType; } TriggerSource Trigger::GetTriggerSource() const { return m_triggerSource; } void Trigger::SetTriggerSource(TriggerSource val) { m_triggerSource = val; } void Trigger::SetTasks(std::vector<TaskType>&& tasks) { m_tasks = tasks; } void Trigger::SetCondition(SelfCondition&& condition) { m_condition = condition; } void Trigger::Validate(Minion& owner, Minion& source) { Player& ownerPlayer = owner.getPlayerCallback(); Player& sourcePlayer = source.getPlayerCallback(); switch (m_triggerSource) { case TriggerSource::NONE: break; case TriggerSource::MINIONS_EXCEPT_SELF: if (ownerPlayer.idx != sourcePlayer.idx || owner.GetIndex() == source.GetIndex()) { return; } break; case TriggerSource::FRIENDLY: if (ownerPlayer.idx != sourcePlayer.idx) { return; } break; default: break; } switch (m_triggerType) { case TriggerType::SUMMON: if (owner.GetIndex() == source.GetIndex()) { return; } break; default: break; } if (m_condition.has_value()) { if (!m_condition.value().Evaluate(source)) { return; } } m_isValidated = true; } void Trigger::Run(Minion& owner, Minion& source) { Validate(owner, source); if (!m_isValidated) { return; } for (auto& task : m_tasks) { std::visit( [&](auto&& _task) { _task.Run(owner.getPlayerCallback(), owner); }, task); } m_isValidated = false; } } // namespace RosettaStone::Battlegrounds
21.581818
79
0.596883
Hearthstonepp
7583028bb868e9a44275687f2db8718c678511da
805
cc
C++
test/main.cc
blsim/residue-cpp
2f052a6fab6798fc700a55ea29febf3189236226
[ "Apache-2.0" ]
2
2018-12-11T05:11:08.000Z
2019-05-24T06:02:35.000Z
test/main.cc
blsim/residue-cpp
2f052a6fab6798fc700a55ea29febf3189236226
[ "Apache-2.0" ]
null
null
null
test/main.cc
blsim/residue-cpp
2f052a6fab6798fc700a55ea29febf3189236226
[ "Apache-2.0" ]
2
2018-12-11T05:11:11.000Z
2019-05-24T06:02:35.000Z
// // Residue.h // // Official C++ client library for Residue logging server // // Copyright (C) 2017-present Amrayn Web Services // Copyright (C) 2017-present @abumusamq // // https://muflihun.com/ // https://amrayn.com // https://github.com/amrayn/residue-cpp/ // // See https://github.com/amrayn/residue-cpp/blob/master/LICENSE // for licensing information // #include "test.h" #include "../include/residue.h" INITIALIZE_EASYLOGGINGPP int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); std::cout << "Default log file: " << ELPP_DEFAULT_LOG_FILE << std::endl; std::cout << "Residue SO version " << Residue::version() << std::endl; el::Loggers::addFlag(el::LoggingFlag::ColoredTerminalOutput); return ::testing::UnitTest::GetInstance()->Run(); }
25.15625
76
0.67205
blsim
7585d7bbefd3316fdaa8be8e2910cab34bf65f3a
25,493
cpp
C++
tools/pb2frigg/src/main.cpp
kITerE/managarm
e6d1229a0bed68cb672a9cad300345a9006d78c1
[ "MIT" ]
935
2018-05-23T14:56:18.000Z
2022-03-29T07:27:20.000Z
tools/pb2frigg/src/main.cpp
kITerE/managarm
e6d1229a0bed68cb672a9cad300345a9006d78c1
[ "MIT" ]
314
2018-05-04T15:58:06.000Z
2022-03-30T16:24:17.000Z
tools/pb2frigg/src/main.cpp
kITerE/managarm
e6d1229a0bed68cb672a9cad300345a9006d78c1
[ "MIT" ]
65
2019-04-21T14:26:51.000Z
2022-03-12T03:16:41.000Z
#include <cassert> #include <iostream> #include <sstream> #include <google/protobuf/descriptor.h> #include <google/protobuf/compiler/plugin.h> #include <google/protobuf/compiler/code_generator.h> #include <google/protobuf/io/zero_copy_stream.h> #include <google/protobuf/io/printer.h> namespace pb = google::protobuf; // -------------------------------------------------------- // scalar specific functions // -------------------------------------------------------- void printScalarInitialize(pb::io::Printer &printer, const pb::FieldDescriptor *field) { if(field->is_optional() || field->is_required()) { printer.Print("m_$name${0}, p_$name${false}", "name", field->name()); }else if(field->is_repeated()) { printer.Print("m_$name${allocator}", "name", field->name()); }else{ assert(!"Unexpected field configuration"); } } void printScalarAccessors(pb::io::Printer &printer, const pb::FieldDescriptor *field) { const char *out_type; switch(field->type()) { case pb::FieldDescriptor::TYPE_INT32: out_type = "int32_t"; break; case pb::FieldDescriptor::TYPE_UINT32: out_type = "uint32_t"; break; case pb::FieldDescriptor::TYPE_INT64: out_type = "int64_t"; break; case pb::FieldDescriptor::TYPE_UINT64: out_type = "uint64_t"; break; case pb::FieldDescriptor::TYPE_ENUM: out_type = "int64_t"; break; default: assert(!"Unexpected scalar type"); } if(field->is_optional() || field->is_required()) { printer.Print("inline $out_type$ $name$() const {\n" " return m_$name$;\n" "}\n", "name", field->name(), "out_type", out_type); printer.Print("inline void set_$name$($out_type$ value) {\n" " m_$name$ = value;\n" " p_$name$ = true;\n" "}\n", "name", field->name(), "out_type", out_type); }else if(field->is_repeated()) { printer.Print("inline void add_$name$($out_type$ value) {\n" " m_$name$.push(value);\n" "}\n", "name", field->name(), "out_type", out_type); printer.Print("inline size_t $name$_size() const {\n" " return m_$name$.size();\n" "}\n", "name", field->name()); printer.Print("inline $out_type$ $name$(size_t i) const {\n" " return m_$name$[i];\n" "}\n", "name", field->name(), "out_type", out_type); }else{ assert(!"Unexpected field configuration"); } } void printScalarSize(pb::io::Printer &printer, const pb::FieldDescriptor *field) { if(field->is_optional() || field->is_required()) { printer.Print("if(p_$name$) {\n" " cachedSize_ += pb2frigg::varintSize($number$ << 3);\n" " cachedSize_ += pb2frigg::varintSize(m_$name$);\n" "}\n", "number", std::to_string(field->number()), "name", field->name()); }else if(field->is_repeated()) { printer.Print("cachedSize_ += m_$name$.size()" " * pb2frigg::varintSize($number$ << 3);\n" "for(size_t i = 0; i < m_$name$.size(); i++)\n" " cachedSize_ += pb2frigg::varintSize(m_$name$[i]);\n", "number", std::to_string(field->number()), "name", field->name()); }else{ assert(!"Unexpected field configuration"); } } void printScalarSerialize(pb::io::Printer &printer, const pb::FieldDescriptor *field) { const char *emit_function; switch(field->type()) { case pb::FieldDescriptor::TYPE_INT32: emit_function = "pb2frigg::emitInt32"; break; case pb::FieldDescriptor::TYPE_UINT32: emit_function = "pb2frigg::emitUInt32"; break; case pb::FieldDescriptor::TYPE_INT64: emit_function = "pb2frigg::emitInt64"; break; case pb::FieldDescriptor::TYPE_UINT64: emit_function = "pb2frigg::emitUInt64"; break; case pb::FieldDescriptor::TYPE_ENUM: emit_function = "pb2frigg::emitInt64"; break; default: assert(!"Unexpected scalar type"); } if(field->is_optional() || field->is_required()) { printer.Print("if(p_$name$)\n" " $emit_function$(writer, $number$, m_$name$);\n", "emit_function", emit_function, "number", std::to_string(field->number()), "name", field->name()); }else if(field->is_repeated()) { printer.Print("for(size_t i = 0; i < m_$name$.size(); i++)\n", "name", field->name()); printer.Indent(); printer.Print("$emit_function$(writer, $number$, m_$name$[i]);\n", "emit_function", emit_function, "number", std::to_string(field->number()), "name", field->name()); printer.Outdent(); }else{ assert(!"Unexpected field configuration"); } } void printScalarParse(pb::io::Printer &printer, const pb::FieldDescriptor *field) { const char *fetch_function, *wire_constant; switch(field->type()) { case pb::FieldDescriptor::TYPE_INT32: fetch_function = "fetchInt32"; wire_constant = "pb2frigg::wireVarint"; break; case pb::FieldDescriptor::TYPE_UINT32: fetch_function = "fetchUInt32"; wire_constant = "pb2frigg::wireVarint"; break; case pb::FieldDescriptor::TYPE_INT64: fetch_function = "fetchInt64"; wire_constant = "pb2frigg::wireVarint"; break; case pb::FieldDescriptor::TYPE_UINT64: fetch_function = "fetchUInt64"; wire_constant = "pb2frigg::wireVarint"; break; case pb::FieldDescriptor::TYPE_ENUM: fetch_function = "fetchInt64"; wire_constant = "pb2frigg::wireVarint"; break; default: assert(!"Unexpected scalar type"); } if(field->is_optional() || field->is_required()) { printer.Print("case $number$:\n" " FRG_ASSERT(header.wire == $wire_constant$);\n", "wire_constant", wire_constant, "number", std::to_string(field->number())); printer.Print(" m_$name$ = $fetch_function$(reader);\n" " p_$name$ = true;\n" " break;\n", "name", field->name(), "fetch_function", fetch_function); }else if(field->is_repeated()) { printer.Print("case $number$:\n", "number", std::to_string(field->number())); printer.Indent(); printer.Print("FRG_ASSERT(header.wire == $wire_constant$);\n" "m_$name$.push($fetch_function$(reader));\n" "break;\n", "wire_constant", wire_constant, "fetch_function", fetch_function, "name", field->name()); printer.Outdent(); }else{ assert(!"Unexpected field configuration"); } } void printScalarMember(pb::io::Printer &printer, const pb::FieldDescriptor *field) { const char *out_type; switch(field->type()) { case pb::FieldDescriptor::TYPE_INT32: out_type = "int32_t"; break; case pb::FieldDescriptor::TYPE_UINT32: out_type = "uint32_t"; break; case pb::FieldDescriptor::TYPE_INT64: out_type = "int64_t"; break; case pb::FieldDescriptor::TYPE_UINT64: out_type = "uint64_t"; break; case pb::FieldDescriptor::TYPE_ENUM: out_type = "int64_t"; break; default: assert(!"Unexpected scalar type"); } if(field->is_optional() || field->is_required()) { printer.Print("$out_type$ m_$name$;\n" "bool p_$name$;\n", "out_type", out_type, "name", field->name()); }else if(field->is_repeated()) { printer.Print("frg::vector<$out_type$, Allocator> m_$name$;\n", "out_type", out_type, "name", field->name()); }else{ assert(!"Unexpected field configuration"); } } // -------------------------------------------------------- // string specific functions // -------------------------------------------------------- void printStringInitialize(pb::io::Printer &printer, const pb::FieldDescriptor *field) { if(field->is_optional() || field->is_required()) { printer.Print("m_$name${allocator}, p_$name${false}", "name", field->name()); }else{ assert(!"Unexpected field configuration"); } } void printStringAccessors(pb::io::Printer &printer, const pb::FieldDescriptor *field) { if(field->is_optional() || field->is_required()) { printer.Print("inline const frg::string<Allocator> &$name$() const {\n" " return m_$name$;\n" "}\n", "name", field->name()); printer.Print("inline void set_$name$(frg::string<Allocator> value) {\n" " m_$name$ = std::move(value);\n" " p_$name$ = true;\n" "}\n", "name", field->name()); }else{ assert(!"Unexpected field configuration"); } } void printStringSize(pb::io::Printer &printer, const pb::FieldDescriptor *field) { if(field->is_optional() || field->is_required()) { printer.Print("if(p_$name$) {\n" " cachedSize_ += pb2frigg::varintSize($number$ << 3);\n" " size_t $name$_length = m_$name$.size();\n" " cachedSize_ += pb2frigg::varintSize($name$_length);\n" " cachedSize_ += $name$_length;\n" "}\n", "number", std::to_string(field->number()), "name", field->name()); }else{ assert(!"Unexpected field configuration"); } } void printStringSerialize(pb::io::Printer &printer, const pb::FieldDescriptor *field) { if(field->is_optional() || field->is_required()) { printer.Print("if(p_$name$)\n" " pb2frigg::emitString(writer, $number$," " m_$name$.data(), m_$name$.size());\n", "number", std::to_string(field->number()), "name", field->name()); }else{ assert(!"Unexpected field configuration"); } } void printStringParse(pb::io::Printer &printer, const pb::FieldDescriptor *field) { if(field->is_optional() || field->is_required()) { printer.Print("case $number$: {\n", "number", std::to_string(field->number())); printer.Indent(); printer.Print("FRG_ASSERT(header.wire == pb2frigg::wireDelimited);\n" "size_t $name$_length = peekVarint(reader);\n" "m_$name$.resize($name$_length);\n" "reader.peek(m_$name$.data(), $name$_length);\n" "p_$name$ = true;\n", "name", field->name()); printer.Outdent(); printer.Print("} break;\n"); }else{ assert(!"Unexpected field configuration"); } } void printStringMember(pb::io::Printer &printer, const pb::FieldDescriptor *field) { if(field->is_optional() || field->is_required()) { printer.Print("frg::string<Allocator> m_$name$;\n" "bool p_$name$;\n", "name", field->name()); }else{ assert(!"Unexpected field configuration"); } } // -------------------------------------------------------- // embedded message specific functions // -------------------------------------------------------- void printEmbeddedInitialize(pb::io::Printer &printer, const pb::FieldDescriptor *field) { if(field->is_optional()) { printer.Print("m_$name${allocator}, p_$name${false}", "name", field->name()); }else if(field->is_repeated()) { printer.Print("m_$name${allocator}", "name", field->name()); }else{ assert(!"Unexpected field configuration"); } } void printEmbeddedAccessors(pb::io::Printer &printer, const pb::FieldDescriptor *field) { const pb::Descriptor *descriptor = field->message_type(); std::string qualified, part; std::istringstream stream(descriptor->full_name()); while(std::getline(stream, part, '.')) qualified += "::" + part; if(field->is_optional()) { printer.Print("inline const $msg_type$<Allocator> &$name$() const {\n" " return m_$name$;\n" "}\n", "name", field->name(), "msg_type", qualified); printer.Print("inline $msg_type$<Allocator> &mutable_$name$() {\n" " p_$name$ = true;\n" " return m_$name$;\n" "}\n", "name", field->name(), "msg_type", qualified); }else if(field->is_repeated()) { printer.Print("inline void add_$name$($msg_type$<Allocator> message) {\n" " m_$name$.push(std::move(message));\n" "}\n", "name", field->name(), "msg_type", qualified); printer.Print("inline size_t $name$_size() const {\n" " return m_$name$.size();\n" "}\n", "name", field->name()); printer.Print("inline const $msg_type$<Allocator> &$name$(size_t i) const {\n" " return m_$name$[i];\n" "}\n", "name", field->name(), "msg_type", qualified); }else{ assert(!"Unexpected field configuration"); } } void printEmbeddedSize(pb::io::Printer &printer, const pb::FieldDescriptor *field) { if(field->is_optional()) { printer.Print("if(p_$name$) {\n" " cachedSize_ += pb2frigg::varintSize($number$ << 3);\n" " size_t $name$_length = m_$name$.ByteSize();\n" " cachedSize_ += pb2frigg::varintSize($name$_length);\n" " cachedSize_ += $name$_length;\n" "}\n", "number", std::to_string(field->number()), "name", field->name()); }else if(field->is_repeated()) { printer.Print("cachedSize_ += m_$name$.size()" " * pb2frigg::varintSize($number$ << 3);\n" "for(size_t i = 0; i < m_$name$.size(); i++) {\n" " size_t $name$_length = m_$name$[i].ByteSize();\n" " cachedSize_ += pb2frigg::varintSize($name$_length);\n" " cachedSize_ += $name$_length;\n" "}\n", "number", std::to_string(field->number()), "name", field->name()); }else{ assert(!"Unexpected field configuration"); } } void printEmbeddedSerialize(pb::io::Printer &printer, const pb::FieldDescriptor *field) { if(field->is_optional()) { printer.Print("if(p_$name$) {\n" " pokeHeader(writer, pb2frigg::Header{$number$," " pb2frigg::wireDelimited});\n" " pokeVarint(writer, m_$name$.GetCachedSize());\n" " m_$name$.SerializeWithCachedSizesToArray((uint8_t *)array" " + writer.offset(), m_$name$.GetCachedSize());\n" " writer.advance(m_$name$.GetCachedSize());\n" "}\n", "number", std::to_string(field->number()), "name", field->name()); }else if(field->is_repeated()) { printer.Print("for(size_t i = 0; i < m_$name$.size(); i++) {\n" " pokeHeader(writer, pb2frigg::Header{$number$," " pb2frigg::wireDelimited});\n" " pokeVarint(writer, m_$name$[i].GetCachedSize());\n" " m_$name$[i].SerializeWithCachedSizesToArray((uint8_t *)array" " + writer.offset(), m_$name$[i].GetCachedSize());\n" " writer.advance(m_$name$[i].GetCachedSize());\n" "}\n", "number", std::to_string(field->number()), "name", field->name()); }else{ assert(!"Unexpected field configuration"); } } void printEmbeddedParse(pb::io::Printer &printer, const pb::FieldDescriptor *field) { const pb::Descriptor *descriptor = field->message_type(); std::string qualified, part; std::istringstream stream(descriptor->full_name()); while(std::getline(stream, part, '.')) qualified += "::" + part; if(field->is_optional()) { printer.Print("case $number$: {\n", "number", std::to_string(field->number())); printer.Indent(); printer.Print("FRG_ASSERT(header.wire == pb2frigg::wireDelimited);\n" "size_t $name$_length = peekVarint(reader);\n" "m_$name$.ParseFromArray((uint8_t *)array + reader.offset(), $name$_length);\n" "reader.advance($name$_length);\n" "p_$name$ = true;\n", "msg_type", qualified, "name", field->name()); printer.Outdent(); printer.Print("} break;\n"); }else if(field->is_repeated()) { printer.Print("case $number$: {\n", "number", std::to_string(field->number())); printer.Indent(); printer.Print("FRG_ASSERT(header.wire == pb2frigg::wireDelimited);\n" "size_t $name$_length = peekVarint(reader);\n" "$msg_type$<Allocator> element(*allocator_);\n" "element.ParseFromArray((uint8_t *)array + reader.offset(), $name$_length);\n" "m_$name$.push(std::move(element));\n" "reader.advance($name$_length);\n", "msg_type", qualified, "name", field->name()); printer.Outdent(); printer.Print("} break;\n"); }else{ assert(!"Unexpected field configuration"); } } void printEmbeddedMember(pb::io::Printer &printer, const pb::FieldDescriptor *field) { const pb::Descriptor *descriptor = field->message_type(); std::string qualified, part; std::istringstream stream(descriptor->full_name()); while(std::getline(stream, part, '.')) qualified += "::" + part; if(field->is_optional()) { printer.Print("$msg_type$<Allocator> m_$name$;\n" "bool p_$name$;\n", "msg_type", qualified, "name", field->name()); }else if(field->is_repeated()) { printer.Print("frg::vector<$msg_type$<Allocator>, Allocator> m_$name$;\n", "msg_type", qualified, "name", field->name()); }else{ assert(!"Unexpected field configuration"); } } // -------------------------------------------------------- // container generation functions // -------------------------------------------------------- void generateEnum(pb::io::Printer &printer, const pb::EnumDescriptor *enumeration) { printer.Print("struct $name$ {\n", "name", enumeration->name()); printer.Indent(); printer.Print("enum {\n"); printer.Indent(); for(int i = 0; i < enumeration->value_count(); i++) { const pb::EnumValueDescriptor *value = enumeration->value(i); printer.Print("$name$ = $number$", "name", value->name(), "number", std::to_string(value->number())); if(i + 1 < enumeration->value_count()) printer.Print(","); printer.Print("\n"); } printer.Outdent(); printer.Print("};\n"); printer.Outdent(); printer.Print("};\n"); } void generateMessage(pb::io::Printer &printer, const pb::Descriptor *descriptor) { // generate a containing class for each message printer.Print("template<typename Allocator>\n" "class $name$ {\n" "public:\n", "name", descriptor->name()); printer.Indent(); for(int i = 0; i < descriptor->enum_type_count(); i++) { printer.Print("\n"); generateEnum(printer, descriptor->enum_type(i)); } // generate the default constructor printer.Print("\n"); printer.Print("$name$(Allocator &allocator)\n" ": allocator_{&allocator}, cachedSize_{0}", "name", descriptor->name()); for(int i = 0; i < descriptor->field_count(); i++) { const pb::FieldDescriptor *field = descriptor->field(i); printer.Print(",\n" " "); switch(field->type()) { case pb::FieldDescriptor::TYPE_INT32: case pb::FieldDescriptor::TYPE_UINT32: case pb::FieldDescriptor::TYPE_INT64: case pb::FieldDescriptor::TYPE_UINT64: case pb::FieldDescriptor::TYPE_ENUM: printScalarInitialize(printer, field); break; case pb::FieldDescriptor::TYPE_STRING: case pb::FieldDescriptor::TYPE_BYTES: printStringInitialize(printer, field); break; case pb::FieldDescriptor::TYPE_MESSAGE: printEmbeddedInitialize(printer, field); break; default: assert(!"Unexpected field type"); } } printer.Print(" { }\n"); // generate the accessor functions for(int i = 0; i < descriptor->field_count(); i++) { const pb::FieldDescriptor *field = descriptor->field(i); printer.Print("\n"); switch(field->type()) { case pb::FieldDescriptor::TYPE_INT32: case pb::FieldDescriptor::TYPE_UINT32: case pb::FieldDescriptor::TYPE_INT64: case pb::FieldDescriptor::TYPE_UINT64: case pb::FieldDescriptor::TYPE_ENUM: printScalarAccessors(printer, field); break; case pb::FieldDescriptor::TYPE_STRING: case pb::FieldDescriptor::TYPE_BYTES: printStringAccessors(printer, field); break; case pb::FieldDescriptor::TYPE_MESSAGE: printEmbeddedAccessors(printer, field); break; default: assert(!"Unexpected field type"); } } // generate the size computation function printer.Print("\n" "size_t ByteSize() {\n"); printer.Indent(); printer.Print("cachedSize_ = 0;\n"); for(int i = 0; i < descriptor->field_count(); i++) { const pb::FieldDescriptor *field = descriptor->field(i); switch(field->type()) { case pb::FieldDescriptor::TYPE_INT32: case pb::FieldDescriptor::TYPE_UINT32: case pb::FieldDescriptor::TYPE_INT64: case pb::FieldDescriptor::TYPE_UINT64: case pb::FieldDescriptor::TYPE_ENUM: printScalarSize(printer, field); break; case pb::FieldDescriptor::TYPE_STRING: case pb::FieldDescriptor::TYPE_BYTES: printStringSize(printer, field); break; case pb::FieldDescriptor::TYPE_MESSAGE: printEmbeddedSize(printer, field); break; default: assert(!"Unexpected field type"); } } printer.Print("return cachedSize_;\n"); printer.Outdent(); printer.Print("}\n" "size_t GetCachedSize() {\n" " return cachedSize_;\n" "}\n"); // generate the serialization function printer.Print("\n" "void SerializeWithCachedSizesToArray(void *array, size_t length) {\n"); printer.Indent(); printer.Print("pb2frigg::BufferWriter writer((uint8_t *)array, length);\n"); for(int i = 0; i < descriptor->field_count(); i++) { const pb::FieldDescriptor *field = descriptor->field(i); switch(field->type()) { case pb::FieldDescriptor::TYPE_INT32: case pb::FieldDescriptor::TYPE_UINT32: case pb::FieldDescriptor::TYPE_INT64: case pb::FieldDescriptor::TYPE_UINT64: case pb::FieldDescriptor::TYPE_ENUM: printScalarSerialize(printer, field); break; case pb::FieldDescriptor::TYPE_STRING: case pb::FieldDescriptor::TYPE_BYTES: printStringSerialize(printer, field); break; case pb::FieldDescriptor::TYPE_MESSAGE: printEmbeddedSerialize(printer, field); break; default: assert(!"Unexpected field type"); } } printer.Print("FRG_ASSERT(writer.offset() == length);\n"); printer.Outdent(); printer.Print("}\n" "void SerializeToString(frg::string<Allocator> *string) {\n" " string->resize(ByteSize());\n" " SerializeWithCachedSizesToArray(string->data(), string->size());\n" "}\n"); // generate the deserialization function printer.Print("\n" "void ParseFromArray(const void *buffer, size_t buffer_size) {\n"); printer.Indent(); printer.Print("const uint8_t *array = static_cast<const uint8_t *>(buffer);\n" "pb2frigg::BufferReader reader(array, buffer_size);\n" "while(!reader.atEnd()) {\n"); printer.Indent(); printer.Print("auto header = fetchHeader(reader);\n" "switch(header.field) {\n"); for(int i = 0; i < descriptor->field_count(); i++) { const pb::FieldDescriptor *field = descriptor->field(i); switch(field->type()) { case pb::FieldDescriptor::TYPE_INT32: case pb::FieldDescriptor::TYPE_UINT32: case pb::FieldDescriptor::TYPE_INT64: case pb::FieldDescriptor::TYPE_UINT64: case pb::FieldDescriptor::TYPE_ENUM: printScalarParse(printer, field); break; case pb::FieldDescriptor::TYPE_STRING: case pb::FieldDescriptor::TYPE_BYTES: printStringParse(printer, field); break; case pb::FieldDescriptor::TYPE_MESSAGE: printEmbeddedParse(printer, field); break; default: assert(!"Unexpected field type"); } } printer.Print("default:\n"); printer.Indent(); printer.Print("FRG_ASSERT(!\"Unexpected field number\");\n"); printer.Outdent(); printer.Print("}\n"); printer.Outdent(); printer.Print("}\n"); printer.Outdent(); printer.Print("}\n"); // generate the fields that hold the actual data printer.Print("\n"); printer.Outdent(); printer.Print("private:\n"); printer.Indent(); printer.Print("Allocator *allocator_;\n"); printer.Print("size_t cachedSize_;\n"); for(int i = 0; i < descriptor->field_count(); i++) { const pb::FieldDescriptor *field = descriptor->field(i); switch(field->type()) { case pb::FieldDescriptor::TYPE_INT32: case pb::FieldDescriptor::TYPE_UINT32: case pb::FieldDescriptor::TYPE_INT64: case pb::FieldDescriptor::TYPE_UINT64: case pb::FieldDescriptor::TYPE_ENUM: printScalarMember(printer, field); break; case pb::FieldDescriptor::TYPE_STRING: case pb::FieldDescriptor::TYPE_BYTES: printStringMember(printer, field); break; case pb::FieldDescriptor::TYPE_MESSAGE: printEmbeddedMember(printer, field); break; default: assert(!"Unexpected field type"); } } // generate a method that reads a message // close the containing class printer.Outdent(); printer.Print("};\n"); } class FriggGenerator : public pb::compiler::CodeGenerator { public: virtual bool Generate(const pb::FileDescriptor *file, const std::string &parameter, pb::compiler::GeneratorContext *context, std::string *error) const; }; bool FriggGenerator::Generate(const pb::FileDescriptor *file, const std::string &parameter, pb::compiler::GeneratorContext *context, std::string *error) const { std::string path = file->name(); size_t file_dot = path.rfind('.'); if(file_dot != std::string::npos) path.erase(path.begin() + file_dot, path.end()); path += ".frigg_pb.hpp"; pb::io::ZeroCopyOutputStream *output = context->Open(path); { // limit the lifetime of printer pb::io::Printer printer(output, '$'); printer.Print("// This file is auto-generated from $file$\n", "file", file->name()); printer.Print("// Do not try to edit it manually!\n"); printer.Print("#include <utility>\n"); // For std::move. printer.Print("#include <frg/string.hpp>\n"); printer.Print("#include <frg/string.hpp>\n"); printer.Print("#include <frg/vector.hpp>\n"); printer.Print("#include <pb2frigg-internals.hpp>\n"); // print the namespace opening braces int num_namespaces = 0; std::string pkg_full, pkg_part; std::istringstream pkg_stream(file->package()); printer.Print("\n"); while(std::getline(pkg_stream, pkg_part, '.')) { printer.Print("namespace $pkg_part$ {\n", "pkg_part", pkg_part); pkg_full += (num_namespaces == 0 ? "" : "::") + pkg_part; num_namespaces++; } // Generate message forward declarations. for(int i = 0; i < file->message_type_count(); i++) { printer.Print("\n"); printer.Print("template<typename Allocator>\n" "class $msg_type$;\n", "msg_type", file->message_type(i)->name()); } // generate all enums for(int i = 0; i < file->enum_type_count(); i++) { printer.Print("\n"); generateEnum(printer, file->enum_type(i)); } // generate all messages for(int i = 0; i < file->message_type_count(); i++) { printer.Print("\n"); generateMessage(printer, file->message_type(i)); } // print the closing braces for the namespace printer.Print("\n"); for(int i = 0; i < num_namespaces; i++) printer.Print("} "); if(num_namespaces > 0) printer.Print("// namespace $pkg_full$\n", "pkg_full", pkg_full); } // printer is destructed here delete output; return true; } int main(int argc, char* argv[]) { FriggGenerator generator; return pb::compiler::PluginMain(argc, argv, &generator); }
33.19401
91
0.653709
kITerE
7587d125dfbda3caf4c566764e312314f1c3a834
559
cpp
C++
libraries/LinearHallSensor/LinearHallSensor.cpp
llebron/arduino
0350e8ad50aaf41a743a09ae437dc687f58337c8
[ "BSD-2-Clause" ]
null
null
null
libraries/LinearHallSensor/LinearHallSensor.cpp
llebron/arduino
0350e8ad50aaf41a743a09ae437dc687f58337c8
[ "BSD-2-Clause" ]
null
null
null
libraries/LinearHallSensor/LinearHallSensor.cpp
llebron/arduino
0350e8ad50aaf41a743a09ae437dc687f58337c8
[ "BSD-2-Clause" ]
null
null
null
#include "LinearHallSensor.h" LinearHallSensor::LinearHallSensor(int sensorPin) { pin = sensorPin; north = false; south = false; } bool LinearHallSensor::atNorth() { return north; } bool LinearHallSensor::atSouth() { return south; } void LinearHallSensor::update() { //read the sensor, and set north or south if it's detecting one of those fields int val = analogRead(pin); if (val <= MAX_SOUTH) { south = true; north = false; } else if (val >= MIN_NORTH) { north = true; south = false; } else { north = false; south = false; } }
17.46875
80
0.67263
llebron
75886f65f1a2f8180d1ae2f72f1a60b07bd446bc
2,279
cxx
C++
src/path_guiding_tree.cxx
DaWelter/NaiveTrace
a904785a0e13c394b2c221bc918cddb41bc8b175
[ "FSFAP" ]
16
2018-04-25T08:14:14.000Z
2022-01-29T06:19:16.000Z
src/path_guiding_tree.cxx
DaWelter/NaiveTrace
a904785a0e13c394b2c221bc918cddb41bc8b175
[ "FSFAP" ]
null
null
null
src/path_guiding_tree.cxx
DaWelter/NaiveTrace
a904785a0e13c394b2c221bc918cddb41bc8b175
[ "FSFAP" ]
null
null
null
#include "path_guiding_tree.hxx" #ifdef HAVE_JSON #include "json.hxx" #include "rapidjson/document.h" #endif namespace guiding { namespace kdtree { void LeafIterator::DecentToNextLeaf() noexcept { const Double3 o = ray.org; const Double3 d = ray.dir; while (true) { auto [node, tnear, tfar] = stack.back(); if (node.is_leaf) { break; } stack.pop_back(); auto [axis, pos] = tree->Split(node); auto [left, right] = tree->Children(node); const double tentative_t = (pos - o[axis]) / d[axis]; const double t = d[axis]==0. ? std::numeric_limits<double>::infinity() : tentative_t; if (unlikely(d[axis] == 0.)) { if (o[axis] <= pos) { stack.push_back({left, tnear, tfar}); } else { stack.push_back({right, tnear, tfar}); } } else { if (d[axis] < 0.) std::swap(left, right); if (tfar > t) { stack.push_back({right, std::max(t, tnear), tfar}); } if (tnear < t) { stack.push_back({left, tnear, std::min(t, tfar)}); } } } } #ifdef HAVE_JSON namespace dump_rj_tree { using namespace rapidjson_util; using Alloc = rj::Document::AllocatorType; rj::Value Build(const Tree &tree, Handle node, Alloc &alloc) { if (node.is_leaf) { rj::Value v(rj::kObjectType); v.AddMember("kind", "leaf", alloc); v.AddMember("id", node.idx, alloc); return v; } else { auto [left, right] = tree.Children(node); auto [axis, pos] = tree.Split(node); rj::Value v_left = Build(tree, left, alloc); rj::Value v_right = Build(tree, right, alloc); rj::Value v{ rj::kObjectType }; v.AddMember("id", node.idx, alloc); v.AddMember("kind", "branch", alloc); v.AddMember("split_axis", axis, alloc); v.AddMember("split_pos", pos, alloc); v.AddMember("left", v_left.Move(), alloc); v.AddMember("right", v_right.Move(), alloc); return v; } } } void Tree::DumpTo(rapidjson::Document &doc, rapidjson::Value & parent) const { using namespace rapidjson_util; auto &alloc = doc.GetAllocator(); parent.AddMember("tree", dump_rj_tree::Build(*this, this->root, alloc), alloc); } #endif } // namespace kdtree } // namespace guiding
19.313559
89
0.593681
DaWelter
7589cd35603a100a94f29140d3802f21a8962293
2,516
hpp
C++
include/gridtools/stencil_composition/icosahedral_grids/accessor.hpp
jdahm/gridtools
5961932cd2ccf336d3d73b4bc967243828e55cc5
[ "BSD-3-Clause" ]
null
null
null
include/gridtools/stencil_composition/icosahedral_grids/accessor.hpp
jdahm/gridtools
5961932cd2ccf336d3d73b4bc967243828e55cc5
[ "BSD-3-Clause" ]
null
null
null
include/gridtools/stencil_composition/icosahedral_grids/accessor.hpp
jdahm/gridtools
5961932cd2ccf336d3d73b4bc967243828e55cc5
[ "BSD-3-Clause" ]
null
null
null
/* * GridTools * * Copyright (c) 2014-2019, ETH Zurich * All rights reserved. * * Please, refer to the LICENSE file in the root directory. * SPDX-License-Identifier: BSD-3-Clause */ #pragma once #include <type_traits> #include "../../common/defs.hpp" #include "../../common/host_device.hpp" #include "../../meta/always.hpp" #include "../accessor_base.hpp" #include "../accessor_intent.hpp" #include "../extent.hpp" #include "../is_accessor.hpp" #include "../location_type.hpp" namespace gridtools { /** * This is the type of the accessors accessed by a stencil functor. */ template <uint_t Id, intent Intent, class LocationType, class Extent = extent<>, uint_t FieldDimensions = 4> class accessor : public accessor_base<Id, Intent, Extent, FieldDimensions> { using base_t = typename accessor::accessor_base; public: GT_STATIC_ASSERT(is_location_type<LocationType>::value, GT_INTERNAL_ERROR); using location_t = LocationType; GT_DECLARE_DEFAULT_EMPTY_CTOR(accessor); accessor(accessor const &) = default; accessor(accessor &&) = default; GT_FUNCTION GT_CONSTEXPR accessor(array<int_t, FieldDimensions> src) : base_t(wstd::move(src)) {} template <uint_t J, uint_t... Js> GT_FUNCTION GT_CONSTEXPR accessor(dimension<J> src, dimension<Js>... srcs) : base_t(src, srcs...) {} }; template <uint_t ID, intent Intent, typename LocationType, typename Extent, uint_t FieldDimensions> meta::repeat_c<FieldDimensions, int_t> tuple_to_types( accessor<ID, Intent, LocationType, Extent, FieldDimensions> const &); template <uint_t ID, intent Intent, typename LocationType, typename Extent, uint_t FieldDimensions> meta::always<accessor<ID, Intent, LocationType, Extent, FieldDimensions>> tuple_from_types( accessor<ID, Intent, LocationType, Extent, FieldDimensions> const &); template <uint_t ID, typename LocationType, typename Extent = extent<>, uint_t FieldDimensions = 4> using in_accessor = accessor<ID, intent::in, LocationType, Extent, FieldDimensions>; template <uint_t ID, typename LocationType, uint_t FieldDimensions = 4> using inout_accessor = accessor<ID, intent::inout, LocationType, extent<>, FieldDimensions>; template <uint_t ID, intent Intent, typename LocationType, typename Extent, uint_t FieldDimensions> struct is_accessor<accessor<ID, Intent, LocationType, Extent, FieldDimensions>> : std::true_type {}; } // namespace gridtools
40.580645
112
0.713434
jdahm
758cefa6b5f61b54a3267a25604dcaefaaba1d79
865
cpp
C++
hackerRank/interview prep kit/basic/countingValleys.cpp
mateuslatrova/competitive-programming
96f24df172e14d2c52c4682aeaad132710a09dc7
[ "MIT" ]
null
null
null
hackerRank/interview prep kit/basic/countingValleys.cpp
mateuslatrova/competitive-programming
96f24df172e14d2c52c4682aeaad132710a09dc7
[ "MIT" ]
null
null
null
hackerRank/interview prep kit/basic/countingValleys.cpp
mateuslatrova/competitive-programming
96f24df172e14d2c52c4682aeaad132710a09dc7
[ "MIT" ]
null
null
null
// Problem: https://www.hackerrank.com/challenges/counting-valleys/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup&h_r=next-challenge&h_v=zen #include <bits/stdc++.h> using namespace std; /* * Complete the 'countingValleys' function below. * * The function is expected to return an INTEGER. * The function accepts following parameters: * 1. INTEGER steps * 2. STRING path */ // Solution: int countingValleys(int steps, string path) { map<char,int> UD; UD.insert({'U',1}); UD.insert({'D',-1}); int h = 0; // current height bool iv = false; // inside valley int n = 0; // number of valleys for (char c: path) { h += UD[c]; if (!iv && h < 0) iv = true; else if (iv && h >= 0) { iv = false; n++; } } return n; }
23.378378
190
0.601156
mateuslatrova
759187034ad95b99b6743f8ee2d0989b34a124ed
487
hpp
C++
src/mseq/some.hpp
lisqlql/constregex
77087bf07d1f402898c848216491c583962089e3
[ "MIT" ]
1
2017-10-06T12:24:25.000Z
2017-10-06T12:24:25.000Z
src/mseq/some.hpp
lisqlql/constregex
77087bf07d1f402898c848216491c583962089e3
[ "MIT" ]
null
null
null
src/mseq/some.hpp
lisqlql/constregex
77087bf07d1f402898c848216491c583962089e3
[ "MIT" ]
null
null
null
#ifndef MSEQ_SOME_HPP__ #define MSEQ_SOME_HPP__ #include "seq.hpp" namespace mseq { template <typename Tseq, template <typename> class Tfunctor> struct some { enum { value = Tfunctor<typename Tseq::hd>::value || some<typename Tseq::tl, Tfunctor>::value }; }; template <template <class> class Tfunctor> struct some<empty, Tfunctor> { enum { value = false }; }; } #endif
18.037037
64
0.554415
lisqlql
7595f432b6f8cadd555870b9015fa1c6eee04da7
1,297
cpp
C++
Game/Player.cpp
maxPrakken/Intake
42f861292887a14bd1bb8c5aa8b5fdd5deee8e9e
[ "MIT" ]
null
null
null
Game/Player.cpp
maxPrakken/Intake
42f861292887a14bd1bb8c5aa8b5fdd5deee8e9e
[ "MIT" ]
null
null
null
Game/Player.cpp
maxPrakken/Intake
42f861292887a14bd1bb8c5aa8b5fdd5deee8e9e
[ "MIT" ]
null
null
null
#include "Player.h" Player::Player() { texturePath = "assets/Player.png"; size = Vector2(50, 50); health = 5; maxHealth = health; speed = 200; bulletSpeed = -10; hasShot = false; velocity = Vector2(0, 0); defaultRPM = 250; RPM = defaultRPM; RPMTimer = 0; } Player::~Player() { } void Player::update(double deltatime) { Entity::update(deltatime); RPMTimer += deltatime; movement(deltatime); if (health > maxHealth) { health = maxHealth; } } void Player::movement(double deltatime) { if (Input::getInstance()->getKey(SDLK_w) && pos.y > 0) { pos -= Vector2(0, speed) * deltatime; } if (Input::getInstance()->getKey(SDLK_a) && pos.x > 0) { pos -= Vector2(speed, 0) * deltatime; } if (Input::getInstance()->getKey(SDLK_s) && pos.y < (canvasSize.y - size.y)) { pos += Vector2(0, speed) * deltatime; } if (Input::getInstance()->getKey(SDLK_d) && pos.x < (canvasSize.x - size.x)) { pos += Vector2(speed, 0) * deltatime; } if (Input::getInstance()->getKey(SDLK_SPACE)) { double xValue = RPM / 60; double fireTime = 1 / xValue; if (RPMTimer > fireTime) { hasShot = true; RPMTimer = 0; Audio::getInstance()->playAudio("pewSound.wav", 0, 1); } } pos += velocity * deltatime; } float Player::getBulletSpeed() { return bulletSpeed; }
17.065789
79
0.629915
maxPrakken
75a4da904dd26a809aae83e5382ceaca830d496f
2,264
cpp
C++
chtho/net/http/HTTPContext.cpp
WineChord/chtho
f43c56a1c2faf83e5f48361ca1b06366ce061aab
[ "MIT" ]
null
null
null
chtho/net/http/HTTPContext.cpp
WineChord/chtho
f43c56a1c2faf83e5f48361ca1b06366ce061aab
[ "MIT" ]
null
null
null
chtho/net/http/HTTPContext.cpp
WineChord/chtho
f43c56a1c2faf83e5f48361ca1b06366ce061aab
[ "MIT" ]
null
null
null
// Copyright (c) 2021 Qizhou Guo // // This software is released under the MIT License. // https://opensource.org/licenses/MIT #include "HTTPContext.h" #include "net/Buffer.h" namespace chtho { namespace net { /* request structure GET /hello.txt HTTP/1.1 User-Agent: curl/7.16.3 libcurl/7.16.3 OpenSSL/0.9.7l zlib/1.2.3 Host: www.example.com Accept-Language: en, mi */ bool HTTPContext::parse(Buffer* buf, Timestamp rcvTime) { bool ok = true, more = true; while(more) { if(state_ == ExpReq) { const char* crlf = buf->findCRLF(); if(crlf) { ok = procReq(buf->peek(), crlf); if(ok) { request_.setRcvTime(rcvTime); buf->retrieveUntil(crlf+2); state_ = ExpHeader; } else more = false; } else more = false; } else if(state_ == ExpHeader) // retrieve headers { const char* crlf = buf->findCRLF(); if(crlf) { const char* colon = std::find(buf->peek(), crlf, ':'); if(colon != crlf) request_.addHeader(buf->peek(), colon, crlf); else // no more headers { state_ = Done; more = false; } buf->retrieveUntil(crlf+2); } else more = false; } } return ok; } /* request line, something like GET /hello HTTP/1.1 */ bool HTTPContext::procReq(const char* begin, const char* end) { const char* space = std::find(begin, end, ' '); if(space == end) return false; if(!request_.setMethod(begin, space)) return false; begin = space + 1; // move to something like '/hello' space = std::find(begin, end, ' '); if(space == end) return false; const char* question = std::find(begin, space, '?'); if(question != space) { request_.setPath(begin, question); request_.setQuery(question, space); } else { request_.setPath(begin, space); } begin = space + 1; // should be either 'HTTP/1.0' or 'HTTP/1.1' if(end - begin != 8) return false; if(!std::equal(begin, end-1, "HTTP/1.")) return false; if(*(end-1) == '1') request_.setVersion(HTTPRequest::HTTP11); else if(*(end-1) == '0') request_.setVersion(HTTPRequest::HTTP10); else return false; return true; } } // namespace net } // namespace chtho
24.879121
71
0.590548
WineChord
b5add455d862a552f5c022684076c0f78dd05a50
415
cpp
C++
Tut 29 Constructor/Constructor.cpp
anuragpathak0/C-Plus-Plus
5e79e3c354b3544f385c77dfbc3fb0a9cef04f64
[ "MIT" ]
null
null
null
Tut 29 Constructor/Constructor.cpp
anuragpathak0/C-Plus-Plus
5e79e3c354b3544f385c77dfbc3fb0a9cef04f64
[ "MIT" ]
null
null
null
Tut 29 Constructor/Constructor.cpp
anuragpathak0/C-Plus-Plus
5e79e3c354b3544f385c77dfbc3fb0a9cef04f64
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> using namespace std; class crdin { int x, y; friend float dist(crdin a, crdin b); public: crdin() { cin >> x >> y; } }; float dist(crdin a, crdin b) { return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y)); } int main() { crdin a, b; cout << "The distance between the two points is " << dist(a, b) << endl; return 0; }
15.37037
76
0.520482
anuragpathak0
b5b1b182a1bee91af559ed0bc29cd27428e0c834
1,829
cpp
C++
1-Array-And-String/OneAway.cpp
sonugiri1043/Cracking-The-Coding-Interview
102cdbc3199d04ab89f5d6894f0489fde352b0d7
[ "MIT" ]
8
2020-05-17T13:48:19.000Z
2022-02-20T06:42:38.000Z
1-Array-And-String/OneAway.cpp
sonugiri1043/Cracking-The-Coding-Interview
102cdbc3199d04ab89f5d6894f0489fde352b0d7
[ "MIT" ]
null
null
null
1-Array-And-String/OneAway.cpp
sonugiri1043/Cracking-The-Coding-Interview
102cdbc3199d04ab89f5d6894f0489fde352b0d7
[ "MIT" ]
6
2021-04-09T21:34:15.000Z
2021-12-13T05:40:42.000Z
/* There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. Given two strings, write a function to check if they are one edit (or zero edits) away. EXAMPLE pale, ple -> true pales, pale -> true pale, bale -> true pale, bake -> false */ #include <iostream> using namespace std; bool checkReplacement( string s1, string s2 ) { bool diffFound = false; for( int i = 0; i < s1.length(); i++ ) { if( s1[ i ] != s2[ i ] ) { if( diffFound ) { return false; } diffFound = true; } } return true; } bool checkRemove( string &s1, string &s2 ) { bool diffFound = false; int j = 0; // index in string s2 for( int i = 0; i < s1.length(); i++, j++ ) { if( s1[ i ] != s2[ j ] ) { i++; if( diffFound ) return false; diffFound = true; } } return true; } bool isStringOneEditAway( string &s1, string &s2 ) { // If string s1 and s2 are of equal length then check for replaceement // else check for remove( removing 1 char from larger string should // give smaller string ). // Insert is opposite of remove. if( s1.length() == s2.length() ) { return checkReplacement( s1, s2 ); } else { if( s1.length() - 1 == s2.length() ) return checkRemove( s1, s2 ); if( s2.length() - 1 == s1.length() ) return checkRemove( s2, s1 ); } return false; } int main() { string a1 = "pale"; string a2 = "ple"; cout<< isStringOneEditAway( a1, a2 ) << endl; string b1 = "pales"; string b2 = "pale"; cout<< isStringOneEditAway( b1, b2 ) << endl; string c1 = "pale"; string c2 = "bale"; cout<< isStringOneEditAway( c1, c2 ) << endl; string d1 = "pale"; string d2 = "bake"; cout<< isStringOneEditAway( d1, d2 ) << endl; return 0; }
23.448718
86
0.593767
sonugiri1043
b5b3ef1c717a5b2b3eb67fb3024aeba7bc276175
3,446
cpp
C++
project/OFEC_sc2/instance/algorithm/realworld/DVRP/LKH/SolveKCenterSubproblems.cpp
BaiChunhui-9803/bch_sc2_OFEC
d50211b27df5a51a953a2475b6c292d00cbfeff6
[ "MIT" ]
null
null
null
project/OFEC_sc2/instance/algorithm/realworld/DVRP/LKH/SolveKCenterSubproblems.cpp
BaiChunhui-9803/bch_sc2_OFEC
d50211b27df5a51a953a2475b6c292d00cbfeff6
[ "MIT" ]
null
null
null
project/OFEC_sc2/instance/algorithm/realworld/DVRP/LKH/SolveKCenterSubproblems.cpp
BaiChunhui-9803/bch_sc2_OFEC
d50211b27df5a51a953a2475b6c292d00cbfeff6
[ "MIT" ]
null
null
null
#include "./INCLUDE/LKH.h" /* * The SolveKCenterSubproblems function attempts to improve a given tour * by means of a partitioning scheme based on approximate K-center clustering. * * The overall region containing the nodes is subdivided into K clusters, * where K = ceil(Dimension/SubproblemSize). Each cluster together with * the given tour induces a subproblem consisting of all nodes in the * cluster and with edges fixed between nodes that are connected by tour * segments whose interior points do not belong to the cluster. * * If an improvement is found, the new tour is written to TourFile. * The original tour is given by the SubproblemSuc references of the nodes. */ namespace LKH { static void KCenterClustering(int K, LKHAlg *Alg); void LKHAlg::SolveKCenterSubproblems() { Node *N; GainType GlobalBestCost, OldGlobalBestCost; double EntryTime = GetTime(); int CurrentSubproblem, Subproblems; AllocateStructures(); ReadPenalties(); /* Compute upper bound for the original problem */ GlobalBestCost = 0; N = FirstNode; do { if (!Fixed(N, N->SubproblemSuc)) GlobalBestCost += (this->*(this->Distance))(N, N->SubproblemSuc); N->Subproblem = 0; } while ((N = N->SubproblemSuc) != FirstNode); if (TraceLevel >= 1) { if (TraceLevel >= 2) printff("\n"); printff("*** K-center partitioning *** [Cost = " GainFormat "]\n", GlobalBestCost); } Subproblems = (int)ceil((double)Dimension / SubproblemSize); KCenterClustering(Subproblems, this); for (CurrentSubproblem = 1; CurrentSubproblem <= Subproblems; CurrentSubproblem++) { OldGlobalBestCost = GlobalBestCost; SolveSubproblem(CurrentSubproblem, Subproblems, &GlobalBestCost); if (SubproblemsCompressed && GlobalBestCost == OldGlobalBestCost) SolveCompressedSubproblem(CurrentSubproblem, Subproblems, &GlobalBestCost); } printff("\nCost = " GainFormat, GlobalBestCost); if (Optimum != MINUS_INFINITY && Optimum != 0) printff(", Gap = %0.4f%%", 100.0 * (GlobalBestCost - Optimum) / Optimum); printff(", Time = %0.2f sec. %s\n", fabs(GetTime() - EntryTime), GlobalBestCost < Optimum ? "<" : GlobalBestCost == Optimum ? "=" : ""); if (SubproblemBorders && Subproblems > 1) SolveSubproblemBorderProblems(Subproblems, &GlobalBestCost); } /* * The KCenterClustering function performs K-center clustering. Each node * is given a unique cluster number in its Subproblem field. */ static void KCenterClustering(int K, LKHAlg *Alg) { LKHAlg::Node **Center, *N; int d, dMax, i; assert(Center = (LKHAlg::Node **) calloc((K + 1), sizeof(LKHAlg::Node *))); /* Pick first cluster arbitrarily */ Center[1] = &Alg->NodeSet[Alg->Random() % Alg->Dimension + 1]; /* Assign all cities to cluster1 */ N = Alg->FirstNode; do { N->Subproblem = 1; N->Cost = (Alg->*(Alg->Distance))(N, Center[1]); } while ((N = N->Suc) != Alg->FirstNode); for (i = 2; i <= K; i++) { /* Take as the cluster center Center[i] a city furthest from * Center[1..i-1]. */ dMax = INT_MIN; N = Alg->FirstNode; do { if ((d = N->Cost) > dMax) { Center[i] = N; dMax = d; } } while ((N = N->Suc) != Alg->FirstNode); do { if ((d = (Alg->*(Alg->Distance))(N, Center[i])) < N->Cost) { N->Cost = d; N->Subproblem = i; } } while ((N = N->Suc) != Alg->FirstNode); } Alg->AdjustClusters(K, Center); free(Center); } }
32.509434
79
0.657864
BaiChunhui-9803
b5b78a0899df08805f07dd001d8cb02d05bee6a3
4,950
cpp
C++
sxaccelerate/src/io/SxParser.cpp
ashtonmv/sphinx_vdw
5896fee0d92c06e883b72725cb859d732b8b801f
[ "Apache-2.0" ]
1
2020-02-29T03:26:32.000Z
2020-02-29T03:26:32.000Z
sxaccelerate/src/io/SxParser.cpp
ashtonmv/sphinx_vdw
5896fee0d92c06e883b72725cb859d732b8b801f
[ "Apache-2.0" ]
null
null
null
sxaccelerate/src/io/SxParser.cpp
ashtonmv/sphinx_vdw
5896fee0d92c06e883b72725cb859d732b8b801f
[ "Apache-2.0" ]
null
null
null
// --------------------------------------------------------------------------- // // The general purpose cross platform C/C++ framework // // S x A c c e l e r a t e // // Home: https://www.sxlib.de // License: Apache 2 // Authors: see src/AUTHORS // // --------------------------------------------------------------------------- #include <SxParser.h> // should become <SxFileParser.h> #include <SxUtil.h> #include <SxException.h> #include <SxDir.h> #ifdef WIN32 # include <windows.h> # ifndef _MAX_PATH # define _MAX_PATH 10240 # endif /* _MAX_PATH */ #endif /* WIN32 */ void initParser () { SxParser_init (); } SxParser::SxParser () : freeFormat(false) { // empty } SxParser::~SxParser () { // empty } void SxParser::setSearchPath (const SxString &path_) { searchPath = path_; } SxConstPtr<SxSymbolTable> SxParser::read (const SxString &file, const SxString &validator_) { SX_TRACE (); SxParser_nestedFiles.removeAll (); SxString path = searchPath; if (searchPath == "") path = getDefaultSearchPath(); SxSymbolTable *&symTab = SxSymbolTable::getGlobalPtr (); if (symTab) delete symTab; SxPtr<SxSymbolTable> table; table = SxPtr<SxSymbolTable>::create (); symTab = &(*table); SxParser_filename = file; SxParser_init (); SxParser_parseFile (SxParser_findInPath(file, path)(0), path, excludeGroups); try { if (table->contains ("handleExceptions")) { if (table->get("handleExceptions")->toAttribute() == false) { SxException::causeSegFault (); sxprintf ("Exceptions will cause segmentation faults!\n"); } } } catch (SxException) { // empty } if (!freeFormat) { try { SxSymbolTable valTable; symTab = &valTable; SxString validator; // --- user provided validator has higher priority if (table->contains("validator")) { validator = table->get("validator")->toString(); } else { if (validator_ != "") validator = validator_; else { sxprintf ("\n"); sxprintf ("Error: No format statement found in file %s.\n", file.ascii()); sxprintf (" Please provide the format validator in the\n"); sxprintf (" input file, e.g.\n"); sxprintf (" format myGrammar;\n"); sxprintf (" This statement would refer to the validator\n"); sxprintf (" $SPHINX/std/myGrammar.std\n"); SX_QUIT; } } SxParser_filename = SxParser_findInPath(validator, path)(0); SxParser_init (); SxString origBuffer = SxParser_buffer; // save original buffer SxParser_parseFile (SxParser_filename, path, excludeGroups); if (!valTable.contains("ignoreValidation")) { table->validateTable (valTable); } SxParser_buffer = origBuffer; // restore original buffer } catch (SxException e) { e.print (); SX_EXIT; } } symTab = NULL; // checkParams (getParam(), __lics); return table; } SxList<SxFile> SxParser::getNestedFiles () const { return SxParser_nestedFiles; } SxFile SxParser::locateFile (const SxSymbol *symbol) const { return (symbol) ? symbol->parserFilename : SxFile(); } SxFile SxParser::locateFile (const SxSymbolTable *symbol) const { return (symbol) ? symbol->parserFilename : SxFile(); } int SxParser::locateLine (const SxSymbol *symbol) const { return (symbol) ? symbol->parserLineNumber : 0; } int SxParser::locateLine (const SxSymbolTable *symbol) const { return (symbol) ? symbol->parserLineNumber : 0; } void SxParser::setVerbose (bool verbose) { SxParser_verbose = verbose; } SxString SxParser::getDefaultSearchPath () { SxString userPath = getenv ("SX_INCLUDE_PATH"); # ifdef WIN32 SxString sep = ";"; # else SxString sep = ":"; # endif /* WIN32 */ if (!userPath) { // --- try to figure out top directory of package try { SxString installPath = SxDir::getInstallPath(); userPath = installPath + "/share/sphinx"; userPath += sep + installPath + "/share" + sep; } catch (SxException e) { #ifndef SX_NOINSTALLPATH e.print (); SX_EXIT; #endif } userPath += SxString(getenv ("HOME")) + "/SPHInX"; } return userPath; } SxString SxParser::getSearchPath () const { if (searchPath != "") return searchPath; else return getDefaultSearchPath (); } void SxParser::setValidation (bool state) { freeFormat = !state; } void SxParser::excludeGroup (const SxString &name) { excludeGroups << name.tokenize (','); }
24.50495
81
0.565859
ashtonmv
b5bf40b9a49616c5a17bd2692bbb89d2f27793f0
1,562
cpp
C++
.LHP/.Lop11/.HSG/.T.Van/QG09/MAZE/MAZE/MAZE.cpp
sxweetlollipop2912/MaCode
661d77a2096e4d772fda2b6a7f80c84113b2cde9
[ "MIT" ]
null
null
null
.LHP/.Lop11/.HSG/.T.Van/QG09/MAZE/MAZE/MAZE.cpp
sxweetlollipop2912/MaCode
661d77a2096e4d772fda2b6a7f80c84113b2cde9
[ "MIT" ]
null
null
null
.LHP/.Lop11/.HSG/.T.Van/QG09/MAZE/MAZE/MAZE.cpp
sxweetlollipop2912/MaCode
661d77a2096e4d772fda2b6a7f80c84113b2cde9
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <cstdio> #include <queue> #define maxN 2501 #define maxH 51 #define row(x) ((x) / n) #define col(x) ((x) % n) #define idx(x, y) ((x) * m + (y)) #define floor first #define pos second typedef int maxn; typedef std::pair <maxn, maxn> co_t; maxn H, m, n, step[maxH][maxN], f[4][2] = { {-1, 0},{0,-1},{0,1},{1,0} }; co_t st, en; std::queue <co_t> bfs; void Prepare() { std::cin >> H >> m >> n; for (maxn h = 0; h < H; h++) for (maxn i = 0; i < m; i++) for (maxn j = 0; j < n; j++) { char c; std::cin >> c; if (c == 'o') step[h][idx(i, j)] = -1; else if (c == '1') st = co_t(h, idx(i, j)); else if (c == '2') en = co_t(h, idx(i, j)); } } maxn BFS(const co_t st, const co_t en) { bfs.push(st); step[st.floor][st.pos] = 1; while (!bfs.empty()) { co_t u = bfs.front(); bfs.pop(); if (u == en) return step[u.floor][u.pos] - 1; for (int i = 0; i < 4; i++) { maxn vx = row(u.pos) + f[i][0], vy = col(u.pos) + f[i][1], v = idx(vx, vy); if (vx < 0 || vx >= m || vy < 0 || vy >= n || step[u.floor][v]) continue; step[u.floor][v] = step[u.floor][u.pos] + 1; bfs.push(co_t(u.floor, v)); } if (u.floor != H - 1 && !step[u.floor + 1][u.pos]) { step[u.floor + 1][u.pos] = step[u.floor][u.pos] + 1; bfs.push(co_t(u.floor + 1, u.pos)); } } return 0; } void Process() { std::cout << BFS(st, en) * 5; } int main() { //freopen("maze.inp", "r", stdin); //freopen("maze.out", "w", stdout); std::ios_base::sync_with_stdio(0); std::cin.tie(0); Prepare(); Process(); }
20.826667
89
0.520487
sxweetlollipop2912
b5c1e556e8aec70f620ee4bda4281bdfc04d8efe
185
cpp
C++
code/nCr.cpp
wewark/ACM-Library
e4cf72d0d11086d284fe0be3b1d322a5f6df3a6e
[ "MIT" ]
1
2019-10-29T22:17:40.000Z
2019-10-29T22:17:40.000Z
code/nCr.cpp
Keyboard2018/ACM-Library
2ab2bf6424345c79a83f0de642bacf4de3e0d676
[ "MIT" ]
null
null
null
code/nCr.cpp
Keyboard2018/ACM-Library
2ab2bf6424345c79a83f0de642bacf4de3e0d676
[ "MIT" ]
1
2019-01-20T14:58:54.000Z
2019-01-20T14:58:54.000Z
ll C[2705][2705]; void initC() { for (int i = 1; i < 2705; i++) { C[i][0] = C[i][i] = 1; for (int j = 1; j < i; j++) { C[i][j] = (C[i - 1][j] + C[i - 1][j - 1]) % MOD; } } }
18.5
51
0.362162
wewark
b5c79c3c6f8e2ade54e21aaa3370a25c3d4f8fd4
234
cpp
C++
A. Vasya and Socks.cpp
Samim-Arefin/Codeforce-Problem-Solution
7219ee6173faaa9e06231d4cd3e9ba292ae27ce3
[ "MIT" ]
null
null
null
A. Vasya and Socks.cpp
Samim-Arefin/Codeforce-Problem-Solution
7219ee6173faaa9e06231d4cd3e9ba292ae27ce3
[ "MIT" ]
null
null
null
A. Vasya and Socks.cpp
Samim-Arefin/Codeforce-Problem-Solution
7219ee6173faaa9e06231d4cd3e9ba292ae27ce3
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main() { int n, m; while (cin >> n >> m) { int sum = 0; for (int i = 1; i <= n; i++) { sum += 1; if (sum % m == 0) { sum += 1; } } cout << sum << '\n'; } }
12.315789
30
0.410256
Samim-Arefin
b5da2ecd1db3090c21511430835c7356410fa16f
10,038
cpp
C++
Options.cpp
sergrt/FileProtect
ee255fb850cedb8cdd4774a469124f4ad8ca62f0
[ "Apache-2.0" ]
null
null
null
Options.cpp
sergrt/FileProtect
ee255fb850cedb8cdd4774a469124f4ad8ca62f0
[ "Apache-2.0" ]
null
null
null
Options.cpp
sergrt/FileProtect
ee255fb850cedb8cdd4774a469124f4ad8ca62f0
[ "Apache-2.0" ]
null
null
null
#include "Options.h" #include <QSettings> #include "../cryptopp/aes.h" #include "../cryptopp/modes.h" #include "../cryptopp/filters.h" #include "CryptoppUtils.h" // Key and IV for options encryption // keyStr should be 64 symbols (to be converted to 32 bytes) and ivStr should be 32 symbols const std::string keyStr = "fa3ead1c0618de10a203a43aef0b19cc" "269a666774eb61d7895fbe10e1496dd7"; const std::string ivStr = "663e27b75f0795b66af1e58961a4f309"; namespace OptionsText { const std::string iniName = "settings.ini"; namespace Groups { const QString general = "General"; } namespace KeyStorage { const QString keyStorage = "KeyStorage"; const std::string keyboard = "keyboard"; const std::string file = "file"; } const QString keyFile = "KeyFile"; namespace WipeMethod { const QString wipeMethod = "WipeMethod"; const std::string regular = "regular"; const std::string external = "external"; } const QString wipeProgram = "WipeProgram"; namespace DecryptionPlace { const QString decryptionPlace = "DecryptionPlace"; const std::string inplace = "inplace"; const std::string specified = "specified"; } const QString decryptionFolder = "DecryptionFolder"; const QString rootPath = "RootPath"; } Options::Options() { // Some defaults m_keyStorage = KeyStorage::Keyboard; m_wipeMethod = WipeMethod::Regular; m_decryptionPlace = DecryptionPlace::Inplace; //m_keyFile = "keyfile.key"; load(); } void Options::updateKeys() { if (key.size() != CryptoPP::AES::MAX_KEYLENGTH && iv.size() != CryptoPP::AES::BLOCKSIZE) { key.resize(CryptoPP::AES::MAX_KEYLENGTH); iv.resize(CryptoPP::AES::BLOCKSIZE); } memcpy(key.BytePtr(), CryptoPPUtils::HexDecodeString(keyStr).BytePtr(), CryptoPP::AES::MAX_KEYLENGTH); memcpy(iv.BytePtr(), CryptoPPUtils::HexDecodeString(ivStr).BytePtr(), CryptoPP::AES::BLOCKSIZE); } std::string Options::encryptString(const std::wstring& src) { CryptoPP::AES::Encryption aesEncryption(key, key.size()); CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption(aesEncryption, iv); std::string ciphertext; CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink(ciphertext)); //stfEncryptor.Put(reinterpret_cast<const unsigned char*>(src.c_str()), src.length() + 1); const int sz = std::wcstombs(nullptr, &src[0], src.size()); std::unique_ptr<char[]> c; if (sz != -1) { c.reset(new char[sz]); std::wcstombs(c.get(), &src[0], src.size()); } else { throw std::runtime_error("Error converting string"); } stfEncryptor.Put(reinterpret_cast<const unsigned char*>(c.get()), sz); stfEncryptor.MessageEnd(); return CryptoPPUtils::HexEncodeString(ciphertext); } std::wstring arrToWstr(const std::string& in) { std::wstring res; const int sz = std::mbstowcs(nullptr, in.c_str(), in.size()); if (sz != -1) { std::unique_ptr<wchar_t[]> t(new wchar_t[sz]); std::mbstowcs(t.get(), in.c_str(), in.size()); res = std::wstring(t.get(), sz); } else { throw std::runtime_error("Error converting string"); } return res; } std::wstring Options::decryptString(const std::string& src) { CryptoPP::SecByteBlock tmp = CryptoPPUtils::HexDecodeString(src); std::string srcDecoded(reinterpret_cast<char*>(tmp.BytePtr()), tmp.size()); CryptoPP::AES::Decryption aesDecryption(key, key.size()); CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption(aesDecryption, iv); std::string decryptedtext; CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink(decryptedtext)); stfDecryptor.Put(reinterpret_cast<const unsigned char*>(srcDecoded.c_str()), srcDecoded.size()); stfDecryptor.MessageEnd(); return arrToWstr(decryptedtext); } bool Options::load() { bool res = true; try { updateKeys(); QSettings s(OptionsText::iniName.c_str(), QSettings::IniFormat); s.beginGroup(OptionsText::Groups::general); KeyStorage k; if (!fromString(k, s.value(OptionsText::KeyStorage::keyStorage, "").toString().toStdString())) throw std::runtime_error("Error converting options to string"); setKeyStorage(k); const std::string keyFile = s.value(OptionsText::keyFile, "").toString().toStdString(); setKeyFile(decryptString(keyFile)); WipeMethod w; if (!fromString(w, s.value(OptionsText::WipeMethod::wipeMethod, "").toString().toStdString())) throw std::runtime_error("Error converting options to string"); setWipeMethod(w); const std::string wipeProgram = s.value(OptionsText::wipeProgram, "").toString().toStdString(); setWipeProgram(decryptString(wipeProgram)); DecryptionPlace d; if (!fromString(d, s.value(OptionsText::DecryptionPlace::decryptionPlace, "").toString().toStdString())) throw std::runtime_error("Error converting options to string"); setDecryptionPlace(d); const std::string decryptionFolder = s.value(OptionsText::decryptionFolder, "").toString().toStdString(); setDecryptionFolder(decryptString(decryptionFolder)); const std::string rootPath = s.value(OptionsText::rootPath, "").toString().toStdString(); setRootPath(decryptString(rootPath)); } catch (std::exception&) { res = false; } return res; } bool Options::save() { bool res = true; try { updateKeys(); QSettings s(OptionsText::iniName.c_str(), QSettings::IniFormat); s.beginGroup(OptionsText::Groups::general); s.setValue(OptionsText::KeyStorage::keyStorage, toString(keyStorage()).c_str()); const std::string keyFileEncrypted = encryptString(keyFile()); s.setValue(OptionsText::keyFile, keyFileEncrypted.c_str()); s.setValue(OptionsText::WipeMethod::wipeMethod, toString(wipeMethod()).c_str()); const std::string wipeProgramEncrypted = encryptString(wipeProgram()); s.setValue(OptionsText::wipeProgram, wipeProgramEncrypted.c_str()); s.setValue(OptionsText::DecryptionPlace::decryptionPlace, toString(decryptionPlace()).c_str()); const std::string decryptionFolderEncrypted = encryptString(decryptionFolder()); s.setValue(OptionsText::decryptionFolder, decryptionFolderEncrypted.c_str()); const std::string rootPathEncrypted = encryptString(rootPath()); s.setValue(OptionsText::rootPath, rootPathEncrypted.c_str()); } catch (std::exception&) { res = false; } return res; } Options::KeyStorage Options::keyStorage() const { return m_keyStorage; } Options::WipeMethod Options::wipeMethod() const { return m_wipeMethod; } Options::DecryptionPlace Options::decryptionPlace() const { return m_decryptionPlace; } std::wstring Options::keyFile() const { return m_keyFile; } std::wstring Options::wipeProgram() const { return m_wipeProgram; } std::wstring Options::decryptionFolder() const { return m_decryptionFolder; } std::wstring Options::rootPath() const { return m_rootPath; } void Options::setKeyStorage(KeyStorage k) { m_keyStorage = k; } void Options::setWipeMethod(WipeMethod w) { m_wipeMethod = w; } void Options::setDecryptionPlace(DecryptionPlace d) { m_decryptionPlace = d; } void Options::setKeyFile(const std::wstring& f) { m_keyFile = f; } void Options::setWipeProgram(const std::wstring& p) { m_wipeProgram = p; } void Options::setDecryptionFolder(const std::wstring& f) { m_decryptionFolder = f; } void Options::setRootPath(const std::wstring& p) { m_rootPath = p; } std::string Options::toString(KeyStorage k) { std::string res; switch (k) { case KeyStorage::Keyboard: res = OptionsText::KeyStorage::keyboard; break; case KeyStorage::File: res = OptionsText::KeyStorage::file; break; default: throw std::runtime_error("Not all KeyStorage values covered"); break; } return res; } bool Options::fromString(KeyStorage& k, const std::string& s) { bool res = false; if (s == OptionsText::KeyStorage::keyboard) { k = KeyStorage::Keyboard; res = true; } else if (s == OptionsText::KeyStorage::file) { k = KeyStorage::File; res = true; } return res; } std::string Options::toString(WipeMethod w) { std::string res; switch (w) { case WipeMethod::Regular: res = OptionsText::WipeMethod::regular; break; case WipeMethod::External: res = OptionsText::WipeMethod::external; break; default: throw std::runtime_error("Not all WipeMethod values covered"); break; } return res; } bool Options::fromString(WipeMethod& w, const std::string& s) { bool res = false; if (s == OptionsText::WipeMethod::regular) { w = WipeMethod::Regular; res = true; } else if (s == OptionsText::WipeMethod::external) { w = WipeMethod::External; res = true; } return res; } std::string Options::toString(DecryptionPlace d) { std::string res; switch (d) { case DecryptionPlace::Inplace: res = OptionsText::DecryptionPlace::inplace; break; case DecryptionPlace::Specified: res = OptionsText::DecryptionPlace::specified; break; default: throw std::runtime_error("Not all DecryptionPlace values covered"); break; } return res; } bool Options::fromString(DecryptionPlace& d, const std::string& s) { bool res = false; if (s == OptionsText::DecryptionPlace::inplace) { d = DecryptionPlace::Inplace; res = true; } else if (s == OptionsText::DecryptionPlace::specified) { d = DecryptionPlace::Specified; res = true; } return res; }
32.803922
113
0.662483
sergrt
b5dc3e3a769ea079bb7ef79422c3bf309f899cf9
2,917
cpp
C++
private/tst/avb_streamhandler/src/IasTestAvbPacket.cpp
tnishiok/AVBStreamHandler
7621daf8c9238361e030fe35188b921ee8ea2466
[ "BSL-1.0", "BSD-3-Clause" ]
13
2018-09-26T13:32:35.000Z
2021-05-20T10:01:12.000Z
private/tst/avb_streamhandler/src/IasTestAvbPacket.cpp
keerockl/AVBStreamHandler
c0c9aa92656ae0acd0f57492d4f325eee2f7d13b
[ "BSD-3-Clause" ]
23
2018-10-03T22:45:21.000Z
2020-03-05T23:40:12.000Z
private/tst/avb_streamhandler/src/IasTestAvbPacket.cpp
keerockl/AVBStreamHandler
c0c9aa92656ae0acd0f57492d4f325eee2f7d13b
[ "BSD-3-Clause" ]
22
2018-09-14T03:55:34.000Z
2021-12-07T01:13:27.000Z
/* * Copyright (C) 2018 Intel Corporation. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ /** * @file IasTestAvbPacket.cpp * @date 2018 */ #include "gtest/gtest.h" #define private public #define protected public #include "avb_streamhandler/IasAvbPacket.hpp" #include "avb_streamhandler/IasAvbPacketPool.hpp" #undef protected #undef private using namespace IasMediaTransportAvb; class IasTestAvbPacket : public ::testing::Test { protected: IasTestAvbPacket(): mAvbPacket(NULL), mDltContext(NULL) { } virtual ~IasTestAvbPacket() {} // Sets up the test fixture. virtual void SetUp() { mAvbPacket = new IasAvbPacket(); mDltContext = new DltContext(); } virtual void TearDown() { delete mAvbPacket; mAvbPacket = NULL; delete mDltContext; mDltContext = NULL; } IasAvbPacket* mAvbPacket; DltContext * mDltContext; }; TEST_F(IasTestAvbPacket, CTor_DTor) { ASSERT_TRUE(NULL != mAvbPacket); } TEST_F(IasTestAvbPacket, assign_op) { unsigned char source[1024] = { 1 }; // rest will be zeroed source[(sizeof source) - 1] = 255; unsigned char dest[sizeof source] = {}; // all zero ASSERT_TRUE(NULL != mAvbPacket); mAvbPacket->vaddr = source; mAvbPacket->len = sizeof source; std::unique_ptr<IasAvbPacket> packet(new IasAvbPacket()); ASSERT_TRUE(NULL != packet); packet->vaddr = dest; *packet = *mAvbPacket; ASSERT_EQ(source[0], dest[0]); ASSERT_EQ(source[1023], dest[1023]); ASSERT_EQ(packet->len, sizeof source); } TEST_F(IasTestAvbPacket, getHomePool) { ASSERT_TRUE(NULL != mAvbPacket); (void)mAvbPacket->getHomePool(); } TEST_F(IasTestAvbPacket, setHomePool) { ASSERT_TRUE(NULL != mAvbPacket); mAvbPacket->setHomePool(NULL); IasAvbPacketPool * homePool = new IasAvbPacketPool(*mDltContext); mAvbPacket->setHomePool(homePool); mAvbPacket->setHomePool(homePool); delete homePool; } TEST_F(IasTestAvbPacket, getPayloadOffset) { ASSERT_TRUE(NULL != mAvbPacket); (void)mAvbPacket->getPayloadOffset(); } TEST_F(IasTestAvbPacket, setPayloadOffset) { unsigned char buf[256]; const size_t offset = (sizeof buf) / 2; ASSERT_TRUE(NULL != mAvbPacket); mAvbPacket->vaddr = buf; mAvbPacket->setPayloadOffset(offset); ASSERT_EQ(mAvbPacket->getPayloadOffset(), offset); ASSERT_EQ(mAvbPacket->getPayloadPointer(), &buf[offset]); } TEST_F(IasTestAvbPacket, isValid) { ASSERT_TRUE(NULL != mAvbPacket); mAvbPacket->mMagic = 0u; ASSERT_FALSE(mAvbPacket->isValid()); DltContext dltCtx; IasAvbPacketPool * pool = new IasAvbPacketPool(dltCtx); mAvbPacket->mHome = pool; ASSERT_FALSE(mAvbPacket->isValid()); delete pool; } TEST_F(IasTestAvbPacket, dummyPacket) { ASSERT_TRUE(NULL != mAvbPacket); mAvbPacket->mDummyFlag = false; ASSERT_FALSE(mAvbPacket->isDummyPacket()); mAvbPacket->makeDummyPacket(); ASSERT_TRUE(mAvbPacket->isDummyPacket()); }
20.985612
67
0.716147
tnishiok
b5dd0218897ef7f655251362975027c41ae5710d
787
cpp
C++
11401.cpp
gcjjyy/acmicpc
763e7a3ec5aabdab6935b9e9970561baafb07729
[ "MIT" ]
null
null
null
11401.cpp
gcjjyy/acmicpc
763e7a3ec5aabdab6935b9e9970561baafb07729
[ "MIT" ]
null
null
null
11401.cpp
gcjjyy/acmicpc
763e7a3ec5aabdab6935b9e9970561baafb07729
[ "MIT" ]
null
null
null
#include <stdio.h> #define MOD 1000000007 typedef unsigned long long ull; ull factorial(ull n) { ull ret = 1; while(n) { ret = (ret * n) % MOD; n--; } return ret; } ull pow(ull m, ull n) { if(n == 0) return 1; if(n == 1) return m; if(n&1 == 1) { return ((pow(m, n / 2) % MOD) * (pow(m, n / 2 + 1) % MOD)) % MOD; } else { return ((pow(m, n / 2) % MOD) * (pow(m, n / 2) % MOD)) % MOD; } } ull modInv(ull k) { return pow(k, MOD - 2); } int main() { int N, K; scanf("%d%d", &N, &K); // (N!) / (K!(N-K)!) ull nfact = factorial(N); ull kfact = factorial(K); ull nkfact = factorial(N-K); printf("%lld\n", (nfact * modInv((kfact * nkfact) % MOD)) % MOD); return 0; }
18.302326
73
0.457433
gcjjyy
b5f770f98e2a7b87145cf6999b76432afce9762b
2,286
cpp
C++
Source/src/Components/ComponentPointLight.cpp
Erick9Thor/Engine3D
32d78f79723fb7c319f79d5e26cdc26481d5cb35
[ "MIT" ]
1
2021-11-17T19:20:07.000Z
2021-11-17T19:20:07.000Z
Source/src/Components/ComponentPointLight.cpp
Erick9Thor/Engine3D
32d78f79723fb7c319f79d5e26cdc26481d5cb35
[ "MIT" ]
null
null
null
Source/src/Components/ComponentPointLight.cpp
Erick9Thor/Engine3D
32d78f79723fb7c319f79d5e26cdc26481d5cb35
[ "MIT" ]
null
null
null
#include "ComponentPointLight.h" #include "../UI/ImGuiUtils.h" #include "ComponentTransform.h" #include "../Scene.h" #include "debugdraw.h" #include <IconsFontAwesome5.h> #include "imgui.h" #include <algorithm> ComponentPointLight::ComponentPointLight(GameObject* conatiner) : Component(Component::Type::POINTLIGHT, conatiner) { if (game_object->scene_owner) game_object->scene_owner->point_lights.push_back((ComponentPointLight*) this); } ComponentPointLight::~ComponentPointLight() { if (game_object->scene_owner) { auto& lights = game_object->scene_owner->point_lights; lights.erase(std::remove(lights.begin(), lights.end(), this), lights.end()); } } void ComponentPointLight::DebugDraw() { if (draw_sphere) { ComponentTransform* transform = game_object->GetComponent<ComponentTransform>(); if (transform) { dd::sphere(transform->GetPosition(), dd::colors::Blue, radius); } } } float3 ComponentPointLight::GetPosition() { ComponentTransform* transform = game_object->GetComponent<ComponentTransform>(); return transform->GetPosition(); } void ComponentPointLight::Save(JsonFormaterValue j_component) const { j_component["LightType"] = (int) Component::Type::POINTLIGHT; JsonFormaterValue j_color = j_component["Color"]; j_color[0] = color.x; j_color[1] = color.y; j_color[2] = color.z; j_color[3] = color.w; j_component["intensity"] = intensity; j_component["radius"] = radius; j_component["active"] = active; j_component["drawSphere"] = draw_sphere; } void ComponentPointLight::Load(JsonFormaterValue j_component) { JsonFormaterValue j_color = j_component["Color"]; color = float4(j_color[0], j_color[1], j_color[2], j_color[3]); intensity = j_component["intensity"]; radius = j_component["radius"]; active = j_component["active"]; draw_sphere = j_component["drawSphere"]; } void ComponentPointLight::DrawGui() { ImGui::PushID(this); if (ImGuiUtils::CollapsingHeader(game_object, this, "Point Light")) { ImGui::Checkbox("P.Active", &active); ImGui::Checkbox("Draw Sphere", &draw_sphere); ImGui::PushItemWidth(100.0f); ImGui::InputFloat("P.Intensity", &intensity); ImGui::InputFloat("P.Radius", &radius); ImGui::PopItemWidth(); ImGuiUtils::CompactColorPicker("Point Color", &color[0]); } ImGui::PopID(); }
25.120879
82
0.731409
Erick9Thor
b5f7b5594697847aa2c9981af2f8f17b8c9c768e
3,649
cpp
C++
BitSet128.cpp
RPG-18/highloadcup2018
b7816d861581d8d8ffc64b66f9e46e2f8341702d
[ "MIT" ]
null
null
null
BitSet128.cpp
RPG-18/highloadcup2018
b7816d861581d8d8ffc64b66f9e46e2f8341702d
[ "MIT" ]
1
2019-07-22T08:57:03.000Z
2019-07-22T08:57:03.000Z
BitSet128.cpp
RPG-18/highloadcup2018
b7816d861581d8d8ffc64b66f9e46e2f8341702d
[ "MIT" ]
null
null
null
#define RAPIDJSON_PARSE_DEFAULT_FLAGS kParseNoFlags #include "Logger.h" #include "BitSet128.h" #include "rapidjson/reader.h" #include "rapidjson/writer.h" extern "C" { #include <fmgr.h> #include <utils/array.h> PG_FUNCTION_INFO_V1(bit128_in); Datum bit128_in(PG_FUNCTION_ARGS); PG_FUNCTION_INFO_V1(bit128_out); Datum bit128_out(PG_FUNCTION_ARGS); PG_FUNCTION_INFO_V1(bit128_equal); Datum bit128_equal(PG_FUNCTION_ARGS); PG_FUNCTION_INFO_V1(bit128_intersection); Datum bit128_intersection(PG_FUNCTION_ARGS); PG_FUNCTION_INFO_V1(bit128_containts); Datum bit128_containts(PG_FUNCTION_ARGS); PG_FUNCTION_INFO_V1(to_array); Datum to_array(PG_FUNCTION_ARGS); extern Datum array_in(PG_FUNCTION_ARGS); } namespace { struct Handler : public rapidjson::BaseReaderHandler<rapidjson::UTF8<>, Handler> { bool Uint(unsigned u) { uint128 v = 0x1; value = value | (v << u); return true; } uint128 value = 0; }; } bool BitSet128::haveIntersection(const BitSet128& b) const noexcept { return (m_bits & b.m_bits) != 0; } bool BitSet128::contains(const BitSet128& b) const noexcept { return (m_bits & b.m_bits) == b.m_bits; } bool BitSet128::operator==(const BitSet128& b) const noexcept { return m_bits == b.m_bits; } bool BitSet128::operator<(const BitSet128& b) const noexcept { return m_bits < b.m_bits; } bool BitSet128::operator>(const BitSet128& b) const noexcept { return m_bits > b.m_bits; } bool BitSet128::fromCString(char* str) noexcept { using namespace rapidjson; Handler h; Reader reader; StringStream ss(str); reader.Parse(ss, h); m_bits = h.value; return true; } char* BitSet128::toCString() const noexcept { using namespace rapidjson; StringBuffer s; Writer<StringBuffer> writer(s); writer.StartArray(); auto c = m_bits; int indx = 0; while (c != 0) { if ((c & 0x01) != 0) { writer.Int(indx); } c = c >> 1; ++indx; } writer.EndArray(); const auto size = s.GetSize() + 1; auto mem = static_cast<char*>(palloc(s.GetSize() + 1)); if (mem == nullptr) { return nullptr; } memcpy(mem, s.GetString(), size); return mem; } std::vector<uint8_t> BitSet128::keys() const { std::vector<uint8_t> out; out.reserve(10); auto c = m_bits; int indx = 0; while (c != 0) { if ((c & 0x01) != 0) { out.push_back(indx); } c = c >> 1; ++indx; } return out; } Datum bit128_in(PG_FUNCTION_ARGS) { char* str = PG_GETARG_CSTRING(0); auto v = new(std::nothrow) BitSet128; if (!v->fromCString(str)) { ereport(ERROR, (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION), errmsg( "invalid input syntax for bit128: \"%s\"", str ))); } PG_RETURN_POINTER(v); } Datum bit128_out(PG_FUNCTION_ARGS) { auto b = GETARG_BIT128(0); PG_RETURN_CSTRING(b->toCString()); } Datum bit128_equal(PG_FUNCTION_ARGS) { const auto a = GETARG_BIT128(0); const auto b = GETARG_BIT128(1); PG_RETURN_BOOL(*a == *b); } Datum bit128_intersection(PG_FUNCTION_ARGS) { //LOGGER->info("call bit128_intersection"); const auto a = GETARG_BIT128(0); const auto b = GETARG_BIT128(1); PG_RETURN_BOOL(a->haveIntersection(*b)); } //containts Datum bit128_containts(PG_FUNCTION_ARGS) { //LOGGER->info("call bit128_containts"); const auto a = GETARG_BIT128(0); const auto b = GETARG_BIT128(1); PG_RETURN_BOOL(a->contains(*b)); }
18.906736
80
0.636613
RPG-18
b5f97458198659b3fec48be1e48a0a29ae49515d
1,851
cc
C++
engine/interior/lightUpdateGrouper.cc
ClayHanson/B4v21-Public-Repo
c812aa7bf2ecb267e02969c85f0c9c2a29be0d28
[ "MIT" ]
1
2020-08-18T19:45:34.000Z
2020-08-18T19:45:34.000Z
engine/interior/lightUpdateGrouper.cc
ClayHanson/B4v21-Launcher-Public-Repo
c812aa7bf2ecb267e02969c85f0c9c2a29be0d28
[ "MIT" ]
null
null
null
engine/interior/lightUpdateGrouper.cc
ClayHanson/B4v21-Launcher-Public-Repo
c812aa7bf2ecb267e02969c85f0c9c2a29be0d28
[ "MIT" ]
null
null
null
//----------------------------------------------------------------------------- // Torque Game Engine // Copyright (C) GarageGames.com, Inc. //----------------------------------------------------------------------------- #include "interior/lightUpdateGrouper.h" LightUpdateGrouper::LightUpdateGrouper(const U32 bitStart, const U32 bitEnd) { AssertFatal(bitEnd >= bitStart, "Error, bitend must be greater than bit start"); AssertFatal(bitEnd < 32, "Error, bitend too large. must be in the range 0..31"); mBitStart = bitStart; mBitEnd = bitEnd; } LightUpdateGrouper::~LightUpdateGrouper() { mBitStart = 0xFFFFFFFF; mBitEnd = 0xFFFFFFFF; } void LightUpdateGrouper::addKey(const U32 key) { #ifdef TORQUE_DEBUG for (U32 i = 0; i < mKeys.size(); i++) AssertFatal(mKeys[i] != key, "Error, key already in the array!"); #endif mKeys.push_back(key); } U32 LightUpdateGrouper::getKeyMask(const U32 key) const { U32 numBits = mBitEnd - mBitStart + 1; for (U32 i = 0; i < mKeys.size(); i++) { if (mKeys[i] == key) { U32 idx = i % numBits; return (1 << (idx + mBitStart)); } } AssertFatal(false, "Error, key not in the array!"); return 0; } LightUpdateGrouper::BitIterator LightUpdateGrouper::begin() { BitIterator itr; itr.mGrouper = this; itr.mCurrBit = mBitStart; itr.resetKeyArray(); return itr; } void LightUpdateGrouper::BitIterator::resetKeyArray() { mKeyArray.clear(); if (valid() == false) return; // Ok, we need to select out every (mBitEnd - mBitStart - 1)th key, // starting at mCurrBit. U32 numBits = mGrouper->mBitEnd - mGrouper->mBitStart + 1; U32 numKeys = mGrouper->mKeys.size(); for (U32 i = mCurrBit - mGrouper->mBitStart; i < numKeys; i += numBits) { mKeyArray.push_back(mGrouper->mKeys[i]); } }
24.355263
84
0.596434
ClayHanson
b5fbb209691fb0173786a0380ec989f5586636d0
2,635
cpp
C++
Plugins/ObjectDeliverer/Source/ObjectDeliverer/Private/Tests/ProtocolLogWriterReaderTest.cpp
ayumax/CommNet
02846b9b7533e548e61a81cd76780456362cc069
[ "MIT" ]
110
2019-02-19T18:50:23.000Z
2022-03-26T10:45:36.000Z
Plugins/ObjectDeliverer/Source/ObjectDeliverer/Private/Tests/ProtocolLogWriterReaderTest.cpp
dlvrydryvr/ObjectDeliverer
e52a88412d4f5c363c612d0a3ac172d4bc8cd74a
[ "MIT" ]
36
2019-01-22T15:08:36.000Z
2021-12-13T13:43:08.000Z
Plugins/ObjectDeliverer/Source/ObjectDeliverer/Private/Tests/ProtocolLogWriterReaderTest.cpp
ayumax/CommNet
02846b9b7533e548e61a81cd76780456362cc069
[ "MIT" ]
25
2019-02-19T15:42:07.000Z
2022-03-17T09:41:50.000Z
// Copyright 2019 ayumax. All Rights Reserved. #include "CoreMinimal.h" #include "Misc/AutomationTest.h" #include "Tests/AutomationCommon.h" #include "Protocol/ProtocolLogReader.h" #include "Protocol/ProtocolLogWriter.h" #include "PacketRule/PacketRuleSizeBody.h" #include "PacketRule/PacketRuleFactory.h" #include "Protocol/ProtocolFactory.h" #include "ObjectDelivererManager.h" #include "DeliveryBox/Utf8StringDeliveryBox.h" #include "Tests/ObjectDelivererManagerTestHelper.h" #if WITH_DEV_AUTOMATION_TESTS IMPLEMENT_SIMPLE_AUTOMATION_TEST(FProtocolLogWrierReaderTest, "ObjectDeliverer.ProtocolTest.ProtocolLogWrierReaderTest1", EAutomationTestFlags::EditorContext | EAutomationTestFlags::EngineFilter) bool FProtocolLogWrierReaderTest::RunTest(const FString& Parameters) { auto deliveryBox = NewObject<UUtf8StringDeliveryBox>(); auto ObjectDelivererWriter = NewObject<UObjectDelivererManager>(); ObjectDelivererWriter->Start(UProtocolFactory::CreateProtocolLogWriter("log.bin", false), UPacketRuleFactory::CreatePacketRuleSizeBody(), deliveryBox); auto deliveryBoxReceive = NewObject<UUtf8StringDeliveryBox>(); auto serverHelper = NewObject<UObjectDelivererManagerTestHelper>(); auto ObjectDelivererReader = NewObject<UObjectDelivererManager>(); deliveryBoxReceive->Received.AddDynamic(serverHelper, &UObjectDelivererManagerTestHelper::OnReceiveString); ADD_LATENT_AUTOMATION_COMMAND(FFunctionLatentCommand([=]() { deliveryBox->Send("AAA"); return true; })); ADD_LATENT_AUTOMATION_COMMAND(FEngineWaitLatentCommand(0.3f)); ADD_LATENT_AUTOMATION_COMMAND(FFunctionLatentCommand([=]() { deliveryBox->Send("BBB"); return true; })); ADD_LATENT_AUTOMATION_COMMAND(FEngineWaitLatentCommand(0.7f)); ADD_LATENT_AUTOMATION_COMMAND(FFunctionLatentCommand([=]() { deliveryBox->Send("CCC"); ObjectDelivererWriter->Close(); ObjectDelivererReader->Start(UProtocolFactory::CreateProtocolLogReader("log.bin", false, true), UPacketRuleFactory::CreatePacketRuleSizeBody(), deliveryBoxReceive); return true; })); ADD_LATENT_AUTOMATION_COMMAND(FEngineWaitLatentCommand(1.5f)); ADD_LATENT_AUTOMATION_COMMAND(FFunctionLatentCommand([=]() { ObjectDelivererReader->Close(); TestEqual("check received count", serverHelper->ReceiveStrings.Num(), 3); if (serverHelper->ReceiveStrings.Num() == 3) { TestEqual("check received data", serverHelper->ReceiveStrings[0], TEXT("AAA")); TestEqual("check received data", serverHelper->ReceiveStrings[1], TEXT("BBB")); TestEqual("check received data", serverHelper->ReceiveStrings[2], TEXT("CCC")); } return true; })); return true; } #endif
34.220779
195
0.795446
ayumax
b5fbdcbede07c27b1513b3d035ae92bbce9251ae
1,193
cpp
C++
zadania-tj/TJ13.cpp
Xeoth/projekty-liceum
b2547d2b6aa7de89b5a13a8e34b724a56779762f
[ "MIT" ]
null
null
null
zadania-tj/TJ13.cpp
Xeoth/projekty-liceum
b2547d2b6aa7de89b5a13a8e34b724a56779762f
[ "MIT" ]
null
null
null
zadania-tj/TJ13.cpp
Xeoth/projekty-liceum
b2547d2b6aa7de89b5a13a8e34b724a56779762f
[ "MIT" ]
null
null
null
// Działa od C++11! #include <iostream> #include <random> // Zamiast cstdlib i ctime użyję tu random using namespace std; int main() { // Seed do generatora random_device rd; // random_device podobno zwraca prawdziwie losowe liczby, nie pseudolosowe mt19937 eng(rd()); // tu dokładnie wrzucamy seed do generatora uniform_int_distribution<> distr(0, 100); // generujemy pseudolosowe liczby zgodnie z seedem // Więcej do zapamiętania, ale ciekawie // Wypełnianie tabeli oraz jej wyświetlanie int array[20]; for (int i = 0; i < 20; i++) { array[i] = distr(eng); cout << array[i] << ' '; } // Wykonywanie polecenia int biggestSum = 0, x, y; for (int j = 0; j < 19; j++) { // Sumujemy ze sobą liczby array[j] oraz array[j+1], aż dojdziemy do j+1=20 int localSum = array[j] + array[j+1]; if (localSum > biggestSum) { biggestSum = localSum; x = array[j], y = array[j+1]; } } // Wyświetlanie wyników cout << endl << "Najwieksza suma elementow: " << biggestSum << endl; cout << "Jest to suma elementow " << x << " i " << y << endl; return 0; }
27.113636
96
0.590947
Xeoth
bd01cbec4b807337be636b609778a876208bfc3a
1,968
cpp
C++
src/system/component/operating_system/operating_system_monitor.cpp
Kinupo/c_cpp_htop
e3fd8c66a299fae800c91ff770876703ba25404a
[ "MIT" ]
null
null
null
src/system/component/operating_system/operating_system_monitor.cpp
Kinupo/c_cpp_htop
e3fd8c66a299fae800c91ff770876703ba25404a
[ "MIT" ]
null
null
null
src/system/component/operating_system/operating_system_monitor.cpp
Kinupo/c_cpp_htop
e3fd8c66a299fae800c91ff770876703ba25404a
[ "MIT" ]
null
null
null
#include "system/component/operating_system/operating_system_monitor.h" OperatingSystemMonitor::OperatingSystemMonitor(){} std::shared_ptr<ComponentStatus> OperatingSystemMonitor::Status(){ return Status(nullptr); } std::string OperatingSystemMonitor::FindVersion(){ std::string version; auto unparsed_version = FileReader::ReadAllLines(kVersionFilename); if((*unparsed_version).size() > 0){ auto parsed_version = DelimitedParser::ParseLine((*unparsed_version).at(0), ' '); if((*parsed_version).size() > 3) version = (*parsed_version).at(2); } return version; } std::string RemoveQuotes(std::string &quoted_string){ auto first_quote = quoted_string.find_first_of("\""); auto second_quote = quoted_string.find_last_of("\""); std::string updated_string = quoted_string; if(first_quote != std::string::npos && second_quote != std::string::npos) updated_string = quoted_string.substr(first_quote, second_quote); return updated_string; } std::string OperatingSystemMonitor::FindOsName(){ std::string pretty_name; auto os_properties = FileReader::ReadLines(kOsPath, os_keys); auto unparsed_os = (*os_properties).find("PRETTY_NAME"); if(unparsed_os != (*os_properties).end()){ auto parsed_os = DelimitedParser::ParseLine(unparsed_os->second, '='); if((*parsed_os).size() > 1) pretty_name = (*parsed_os).at(1); if(pretty_name.length() > 2)//remove quotes pretty_name = pretty_name.substr(1, pretty_name.length() -2); } return pretty_name; } std::shared_ptr<ComponentStatus> OperatingSystemMonitor::Status( std::shared_ptr<ComponentStatus> prior_status){ std::string version = FindVersion(); std::string pretty_name = FindOsName(); return std::make_shared<OperatingSystemStatus>(pretty_name, version); } ComponentType OperatingSystemMonitor::ComponentMonitored(){return component_type_;}
35.781818
89
0.704268
Kinupo
bd01eed443e0fe35655db2bf97e8447b3a8beaff
78
cpp
C++
Source/BroForce/Private/CustomUtils.cpp
solidajenjo/BroForceLikeGame
37666bbab04f0a6a8cf8a364197f10389271b67f
[ "MIT" ]
null
null
null
Source/BroForce/Private/CustomUtils.cpp
solidajenjo/BroForceLikeGame
37666bbab04f0a6a8cf8a364197f10389271b67f
[ "MIT" ]
null
null
null
Source/BroForce/Private/CustomUtils.cpp
solidajenjo/BroForceLikeGame
37666bbab04f0a6a8cf8a364197f10389271b67f
[ "MIT" ]
null
null
null
#include "CustomUtils.h" namespace CustomUtils { } // namespace CustomUtils
11.142857
26
0.75641
solidajenjo
bd02dbc4a3ec0749daa7aca2b397f805b47f6eae
1,359
hpp
C++
src/workspaces.hpp
StardustXR/magnetar
65a08f3878710d3c70c9e93edf416d1dd2eaf0de
[ "MIT" ]
null
null
null
src/workspaces.hpp
StardustXR/magnetar
65a08f3878710d3c70c9e93edf416d1dd2eaf0de
[ "MIT" ]
null
null
null
src/workspaces.hpp
StardustXR/magnetar
65a08f3878710d3c70c9e93edf416d1dd2eaf0de
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include <vector> #include <stardustxr/fusion/values/glm.hpp> #include <stardustxr/fusion/types/drawable/model.hpp> #include <stardustxr/fusion/types/fields/cylinderfield.hpp> #include <stardustxr/fusion/types/input/datamap.hpp> #include <stardustxr/fusion/types/input/types/handinput.hpp> #include <stardustxr/fusion/types/input/inputactionhandler.hpp> #include <stardustxr/fusion/types/input/actions/singleactor.hpp> #include <stardustxr/fusion/util/tween.hpp> #include "workspacecell.hpp" class Workspaces : public StardustXRFusion::Spatial { public: Workspaces(StardustXRFusion::Spatial *parent, StardustXRFusion::Vec3 pos, uint cellCount, float radius); void update(double delta); protected: StardustXRFusion::CylinderField field; StardustXRFusion::InputActionHandler input; std::vector<std::unique_ptr<WorkspaceCell>> cells; uint cellCount; // bool handInput(const std::string uuid, const StardustXRFusion::HandInput &hand, const StardustXRFusion::Datamap &datamap); // bool pointerInput(const StardustXRFusion::PointerInput &hand, const StardustXRFusion::Datamap &datamap); StardustXRFusion::SingleActorAction inRangeAction; StardustXRFusion::SingleActorAction grabAction; float radius; float yPos; float snapStart; float snapTarget; StardustXRFusion::Tween<float> snapTween; float oldInputY; };
32.357143
125
0.802796
StardustXR
bd055633d7aa16c3771299981191ca376d0c68fe
2,173
hpp
C++
cpp/dynlb.hpp
parmes/solfec-2.0
3329d3e1e4d58fefaf976c04bab19284aef45bc2
[ "MIT" ]
1
2020-06-21T23:52:25.000Z
2020-06-21T23:52:25.000Z
cpp/dynlb.hpp
parmes/solfec-2.0
3329d3e1e4d58fefaf976c04bab19284aef45bc2
[ "MIT" ]
1
2020-05-01T14:44:01.000Z
2020-05-01T23:50:36.000Z
cpp/dynlb.hpp
parmes/solfec-2.0
3329d3e1e4d58fefaf976c04bab19284aef45bc2
[ "MIT" ]
2
2020-06-21T23:59:21.000Z
2021-12-09T09:49:50.000Z
/* The MIT License (MIT) Copyright (c) 2016 EDF Energy Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "part_ispc.h" #include "ga.hpp" #ifndef __dynlb__ #define __dynlb__ struct dynlb /* load balancer interface */ { int64_t cutoff; /* partitioning tree cutoff; 0 means use default selection */ REAL epsilon; /* imbalance epsilon; rebalance when imbalance > 1.0 + epsilon */ ispc::partitioning *ptree; /* partitioning tree; used internally */ int ptree_size; /* partitioning tree size; used internally */ REAL imbalance; /* current imbalance */ /* default constructor */ dynlb(): cutoff(0), epsilon(0.), ptree(NULL), ptree_size(0), imbalance(1.) { } /* create local load balancer */ void local_create (uint64_t n, REAL *point[3], int64_t cutoff = 0, REAL epsilon = 0.1); /* assign an MPI rank to a point; return this rank */ int point_assign (REAL point[]); /* assign MPI ranks to a box spanned between lo and hi points; return the number of ranks assigned */ int box_assign (REAL lo[], REAL hi[], int ranks[]); /* update local load balancer */ void local_update (uint64_t n, REAL *point[3]); /* destroy load balancer */ ~dynlb(); }; #endif
36.830508
103
0.741832
parmes
bd05e1c0b1a52dfb1a4b306e1df6fcc7e12179e9
383
cpp
C++
src/Logger.cpp
advpl/advpl-language-server-cxx
7c654c92934ed3e705c6823cbff9687dd8304d06
[ "MIT" ]
4
2018-01-19T07:11:18.000Z
2020-05-15T19:45:53.000Z
src/Logger.cpp
ragssoftwares/advpl-language-server-cxx
7c654c92934ed3e705c6823cbff9687dd8304d06
[ "MIT" ]
3
2018-01-19T22:17:19.000Z
2018-01-25T13:57:31.000Z
src/Logger.cpp
ragssoftwares/advpl-language-server-cxx
7c654c92934ed3e705c6823cbff9687dd8304d06
[ "MIT" ]
2
2018-01-19T07:11:19.000Z
2018-08-21T18:42:07.000Z
#include "Logger.hpp" using namespace advpl_ls; EmptyLogger &EmptyLogger::getInstance() { static EmptyLogger Logger; return Logger; } void EmptyLogger::log(const std::string Message) {} FileLogger &FileLogger::getInstance() { static FileLogger Logger; return Logger; } void FileLogger::log(const std::string Message) { log_info(Message); }
21.277778
53
0.686684
advpl
bd077fa76cb30e3b1b2859db95cf20445f70df64
2,177
cpp
C++
Nanoforge/rfg/xtbl/nodes/SelectionXtblNode.cpp
Moneyl/RF-Viewer
fd5a53c0d7ed94d9c5c9264e3ed11f2037c2f49a
[ "MIT" ]
3
2020-08-26T17:53:47.000Z
2020-09-13T07:48:40.000Z
Nanoforge/rfg/xtbl/nodes/SelectionXtblNode.cpp
Moneyl/RF-Viewer
fd5a53c0d7ed94d9c5c9264e3ed11f2037c2f49a
[ "MIT" ]
2
2020-09-01T06:08:28.000Z
2020-11-14T02:14:41.000Z
Nanoforge/rfg/xtbl/nodes/SelectionXtblNode.cpp
Moneyl/RF-Viewer
fd5a53c0d7ed94d9c5c9264e3ed11f2037c2f49a
[ "MIT" ]
null
null
null
#include "XtblNodes.h" #include "rfg/xtbl/XtblDescription.h" #include "render/imgui/imgui_ext.h" #include "common/string/String.h" #include <tinyxml2/tinyxml2.h> #include <imgui.h> #pragma warning(disable:4100) //Disable warning about unused argument. Can't remove the arg since some implementations of this function use it. bool SelectionXtblNode::DrawEditor(GuiState* guiState, Handle<XtblFile> xtbl, IXtblNode* parent, const char* nameOverride) { CalculateEditorValues(xtbl, nameOverride); bool editedThisFrame = false; //Used for document unsaved change tracking //Select the first choice if one hasn't been selected string& nodeValue = std::get<string>(Value); if (nodeValue == "") nodeValue = desc_->Choices[0]; //Draw combo with all possible choices if (ImGui::BeginCombo(name_.value().c_str(), std::get<string>(Value).c_str())) { ImGui::InputText("Search", searchTerm_); ImGui::Separator(); for (auto& choice : desc_->Choices) { //Check if choice matches seach term if (searchTerm_ != "" && !String::Contains(String::ToLower(choice), String::ToLower(searchTerm_))) continue; bool selected = choice == nodeValue; if (ImGui::Selectable(choice.c_str(), &selected)) { Value = choice; Edited = true; editedThisFrame = true; } } ImGui::EndCombo(); } return editedThisFrame; } #pragma warning(default:4100) void SelectionXtblNode::InitDefault() { Value = ""; } bool SelectionXtblNode::WriteModinfoEdits(tinyxml2::XMLElement* xml) { return WriteXml(xml, false); } bool SelectionXtblNode::WriteXml(tinyxml2::XMLElement* xml, bool writeNanoforgeMetadata) { auto* selectionXml = xml->InsertNewChildElement(Name.c_str()); selectionXml->SetText(std::get<string>(Value).c_str()); //Store edited state if metadata is enabled if (writeNanoforgeMetadata) { selectionXml->SetAttribute("__NanoforgeEdited", Edited); selectionXml->SetAttribute("__NanoforgeNewEntry", NewEntry); } return true; }
31.550725
143
0.658245
Moneyl
bd099af05deb56ef3f6e798eae176ba79c3b4dae
3,024
cpp
C++
raven/io/FileSystem.cpp
nielsuiterwijk/vulkan
b2d5c7d23f7a16d9fdb9ba2796051da4d9e66e05
[ "MIT" ]
2
2019-11-28T12:42:44.000Z
2021-07-02T12:50:20.000Z
raven/io/FileSystem.cpp
nielsuiterwijk/vulkan
b2d5c7d23f7a16d9fdb9ba2796051da4d9e66e05
[ "MIT" ]
null
null
null
raven/io/FileSystem.cpp
nielsuiterwijk/vulkan
b2d5c7d23f7a16d9fdb9ba2796051da4d9e66e05
[ "MIT" ]
null
null
null
#include "FileSystem.h" #include "threading/ThreadPool.h" bool FileSystem::stop = false; bool FileSystem::threadStarted = false; std::thread FileSystem::fileLoadingThread; std::queue<FileSystem::AsyncFileLoad> FileSystem::tasks; Mutex FileSystem::queue_mutex; std::condition_variable_any FileSystem::condition; ThreadPool* FileSystem::threadPool = nullptr; void FileSystem::Start() { ASSERT( !threadStarted ); std::cout << "[FileSystem] starting thread.." << std::endl; threadPool = new ThreadPool( std::min( Utility::AvailableHardwareThreads(), 3 ) ); fileLoadingThread = std::thread( LoadAsync ); } void FileSystem::Exit() { std::cout << "[FileSystem] stopping thread.." << std::endl; stop = true; queue_mutex.lock(); condition.notify_one(); queue_mutex.unlock(); fileLoadingThread.join(); delete threadPool; threadPool = nullptr; } std::vector<char> FileSystem::ReadFile( const std::string& filename ) { std::vector<char> buffer; std::ifstream file( "../assets/" + filename, std::ios::binary | std::ios::ate); if ( !file.is_open() ) { std::cout << "[FileSystem] Failed loading " << filename.c_str() << std::endl; ASSERT_FAIL( "failed to open file!" ); return buffer; } file.seekg(0, file.end); size_t fileSize = file.tellg(); buffer.resize(fileSize); file.seekg(0, file.beg); file.read( buffer.data(), fileSize ); file.close(); std::cout << "[FileSystem] Loaded " << filename.c_str() << " size: " << fileSize << std::endl; #if DEBUG //Sleep(100); #endif return buffer; } //TODO: This callback should probably expect some sort of `Result` object which will either contain the data or an error void FileSystem::LoadFileAsync( const std::string& fileName, std::function<void( std::vector<char> )> callback ) { ASSERT( threadStarted ); ASSERT( fileName.length() != 0 ); std::cout << "[FileSystem] Queuing loading " << fileName.c_str() << std::endl; queue_mutex.lock(); tasks.push( AsyncFileLoad( fileName, callback ) ); queue_mutex.unlock(); condition.notify_one(); } void FileSystem::LoadAsync() { threadStarted = true; stop = false; std::cout << "[FileSystem] thread started" << std::endl; while ( !stop ) { AsyncFileLoad loadTask; { std::unique_lock<Mutex> lock( queue_mutex ); //The condition will take the lock and will wait for to be notified and will continue //only if were stopping (stop == true) or if there are tasks to do, else it will keep waiting. condition.wait( lock, [] { return stop || !tasks.empty(); } ); //Once we passed the condition we have the lock, and as soon we leave the scope, the lock will be given up if ( stop ) { std::cout << "[FileSystem] thread stopped" << std::endl; threadStarted = false; return; } loadTask = tasks.front(); tasks.pop(); } std::vector<char> fileData = ReadFile( loadTask.fileName ); threadPool->Enqueue( [=]() { std::cout << "[FileSystem] callback -> " << loadTask.fileName << std::endl; loadTask.callback( fileData ); } ); } }
23.44186
120
0.676257
nielsuiterwijk
bd0d2e1174542899a4840006d3306ee3fe497936
4,114
hpp
C++
include/otf2xx/event/marker.hpp
dhinf/otf2xx
78d3c0eb0b201010b7436bbb235ebdbdabec17d2
[ "BSD-3-Clause" ]
8
2016-11-11T09:33:59.000Z
2022-03-11T12:34:01.000Z
include/otf2xx/event/marker.hpp
dhinf/otf2xx
78d3c0eb0b201010b7436bbb235ebdbdabec17d2
[ "BSD-3-Clause" ]
38
2016-12-12T09:21:07.000Z
2022-03-11T12:18:36.000Z
include/otf2xx/event/marker.hpp
dhinf/otf2xx
78d3c0eb0b201010b7436bbb235ebdbdabec17d2
[ "BSD-3-Clause" ]
5
2017-06-01T12:01:03.000Z
2022-03-11T11:00:00.000Z
/* * This file is part of otf2xx (https://github.com/tud-zih-energy/otf2xx) * otf2xx - A wrapper for the Open Trace Format 2 library * * Copyright (c) 2013-2016, Technische Universität Dresden, Germany * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef INCLUDE_OTF2XX_EVENT_MARKER_HPP #define INCLUDE_OTF2XX_EVENT_MARKER_HPP #include <otf2xx/definition/fwd.hpp> #include <otf2xx/definition/marker.hpp> #include <otf2xx/event/base.hpp> #include <otf2xx/chrono/chrono.hpp> namespace otf2 { namespace event { class marker : public base<event::marker> { public: using scope_type = otf2::common::marker_scope_type; // construct with values marker(otf2::chrono::time_point timestamp, otf2::chrono::duration duration, const otf2::definition::marker& def_marker, scope_type scope, std::uint64_t scope_ref, std::string text) : base<event::marker>(timestamp), duration_(duration), def_marker_(def_marker), scope_(scope), scope_ref_(scope_ref), text_(text) { } marker(OTF2_AttributeList* al, otf2::chrono::time_point timestamp, otf2::chrono::duration duration, const otf2::definition::marker& def_marker, scope_type scope, std::uint64_t scope_ref, std::string text) : base<event::marker>(al, timestamp), duration_(duration), def_marker_(def_marker), scope_(scope), scope_ref_(scope_ref), text_(text) { } // copy constructor with new timestamp marker(const otf2::event::marker& other, otf2::chrono::time_point timestamp) : base<event::marker>(other, timestamp), duration_(other.duration()), def_marker_(other.def_marker()), scope_(other.scope()), scope_ref_(other.scope_ref()), text_(other.text()) { } public: otf2::chrono::duration duration() const { return duration_; } otf2::definition::marker def_marker() const { return def_marker_; } scope_type scope() const { return scope_; } std::uint64_t scope_ref() const { return scope_ref_; } std::string text() const { return text_; } private: otf2::chrono::duration duration_; otf2::definition::detail::weak_ref<otf2::definition::marker> def_marker_; scope_type scope_; std::uint64_t scope_ref_; std::string text_; }; } // namespace event } // namespace otf2 #endif // INCLUDE_OTF2XX_EVENT_MARKER_HPP
35.465517
96
0.679387
dhinf
bd0fd8caf24d1c1e5754117a22ff1a0bb32e73a9
21,692
hpp
C++
src/core/Strings.hpp
ShamylZakariya/KesslerSyndrome
dce00108304fe2c1b528515dafc29c15011d4679
[ "MIT" ]
null
null
null
src/core/Strings.hpp
ShamylZakariya/KesslerSyndrome
dce00108304fe2c1b528515dafc29c15011d4679
[ "MIT" ]
null
null
null
src/core/Strings.hpp
ShamylZakariya/KesslerSyndrome
dce00108304fe2c1b528515dafc29c15011d4679
[ "MIT" ]
null
null
null
// // StringUtils.h // Milestone6 // // Created by Shamyl Zakariya on 2/11/17. // // #ifndef Strings_h #define Strings_h #include <ctype.h> #include <fstream> #include <set> #include <sstream> #include <stdarg.h> #include <string> #include <vector> #include "core/MathHelpers.hpp" /** @file strings.h Basic string operations, like split(), join(), etc etc. */ /** @defgroup stringutil String Utilities */ /** @namespace core::strings @brief core::util::strings is a toolbox of convenient string-related functions */ namespace core { using std::size_t; using std::string; using std::stringstream; /** @brief Convert @a v to a string @return the input parameter as a string. */ template<class T> string str(T v) { stringstream ss; ss << v; return ss.str(); } /** @brief Convert @a v to a string @return the input parameter as a string with real precision @a prec */ template<class T> string str(T v, int prec) { stringstream ss; ss << std::setprecision(prec) << std::fixed << v; return ss.str(); } /** @brief Convert pointer value @a v to a string */ template<class T> string str(T *v) { stringstream ss; ss << "0x" << std::hex << v; return ss.str(); } /** @brief Convert a boolean to string @return "true" or "false" according to @a v */ inline string str(bool v) { return v ? "true" : "false"; } /** @brief Convert a const chararacter pointer to a string */ inline string str(const char *s) { return string(s); } /** @brief Convert a non-const chararacter pointer to a string */ inline string str(char *s) { return string(s); } /** @brief identity function string->string */ inline string str(const string &s) { return s; } namespace strings { typedef std::vector<string> stringvec; typedef std::vector<char> charvec; typedef std::set<string> stringset; typedef std::set<char> charset; enum numeric_base { Binary, Octal, Decimal, Hexadecimal }; /** @brief generate a lowercase version of a string @ingroup stringutil @return a lowercased version of @a str */ inline string lowercase(const string &str) { using namespace std; string out; size_t l = str.length(); for (int i = 0; i < l; i++) out.push_back(tolower(str[i])); return out; } /** @brief generate an uppercase version of a string @ingroup stringutil @return an uppercased version of @a str */ inline string uppercase(const string &str) { using namespace std; string out; size_t l = str.length(); for (int i = 0; i < l; i++) out.push_back(toupper(str[i])); return out; } /** @brief Variant of sprintf for string @ingroup stringutil works like sprintf, but is reasonably "safe" @note You're better off using stringstream and overloaded insertion operators. */ inline string format(const char *format, ...) { using namespace std; char *buffer = NULL; va_list ap; va_start(ap, format); vasprintf(&buffer, format, ap); va_end(ap); string str(buffer); free(buffer); return str; } /** @brief multi replace for string @ingroup stringutil replaces all instances of @a token in @a src with @a with */ inline string replaceAll(const string &src, const string &token, const string &with) { using namespace std; string out = src; while (true) { string::size_type position = out.find(token); if (position == string::npos) break; //if we're here there's a hash to remove out.replace(position, token.length(), with); } return out; } /** @brief case-insensitive multi replace for string @ingroup stringutil replaces all instances of @a token in @a src with @a with, case insensitive */ inline string iReplaceAll(const string &src, const string &token, const string &with) { using namespace std; string lSrc = lowercase(src); string lToken = lowercase(token); string ret = src; while (true) { string::size_type position = lSrc.find(lToken); if (position == string::npos) break; ret.replace(position, token.length(), with); lSrc.replace(position, token.length(), with); } return ret; } /** @brief string tokenizer @ingroup stringutil splits @a str by @a delimeter. @return the tokens between the delimeter, minus the delimeter. */ inline stringvec split(const string &str, const string &delimeter) { using namespace std; stringvec tokens; size_t start = 0, next = string::npos; while (true) { bool done = false; string ss; //substring next = str.find(delimeter, start); if (next != string::npos) { ss = str.substr(start, next - start); } else { ss = str.substr(start, (str.length() - start)); done = true; } tokens.push_back(ss); if (done) break; start = next + delimeter.length(); } return tokens; } /** @brief string tokenizer @ingroup stringutil @return the tokens between the delimeter, minus the delimeter. */ inline stringvec split(const string &str, char delimeter) { using namespace std; stringvec tokens; size_t start = 0, next = string::npos; while (true) { bool done = false; string ss; //substring next = str.find(delimeter, start); if (next != string::npos) { ss = str.substr(start, next - start); } else { ss = str.substr(start, (str.length() - start)); done = true; } tokens.push_back(ss); if (done) break; start = next + 1; } return tokens; } /** @brief string tokenizer @ingroup stringutil @param str The string to tokenize @param delimeters the character delimeters you're splitting against @param includeDelimeters if true, the returned vector will include the delimeters between tokens @returns the tokens between the delimeter chars, separated by delimeters if @a includeDelimeters is true */ inline stringvec split(const string &str, const charset &delimeters, bool includeDelimeters = true) { using namespace std; string currentToken; stringvec tokens; charset::const_iterator notFound(delimeters.end()); for (string::const_iterator it(str.begin()), end(str.end()); it != end; ++it) { char c(*it); if (delimeters.find(c) == notFound) { currentToken.append(1u, c); } else { tokens.push_back(currentToken); if (includeDelimeters) tokens.push_back(string(1u, c)); currentToken.clear(); } } /* Append whatever's lingering around */ if (!currentToken.empty()) tokens.push_back(currentToken); return tokens; } /** @brief string tokenizer @ingroup stringutil @returns the tokens and delimeters ina vector If your input string is "The Quick Brown Fox Jumped Over The Lazy Dog" and your delimeters are {" ", "The" } the result vector would be: { "The", " ", "Quick", " ", "Brown", " ", "Fox", " ", "Jumped", " ", "Over", " ", "The", " ", "Lazy", " ", "Dog" } */ inline stringvec split(const string &str, const stringset &delimeters) { using namespace std; stringvec tokens; string nonDelimeter; size_t start = 0, next = string::npos; while (true) { string delim; for (stringset::const_iterator it = delimeters.begin(), end(delimeters.end()); it != end; ++it) { next = str.find(*it, start); if (next == start) { delim = *it; break; //get out } } //if we found a delimeter if (delim.length()) { start += delim.length(); if (nonDelimeter.length()) { tokens.push_back(nonDelimeter); nonDelimeter.clear(); } tokens.push_back(delim); } else { nonDelimeter.push_back(str[start]); start++; if (start >= str.length()) break; } } return tokens; } /** @brief string concatenation @ingroup stringutil @return each string in @a tokens with the string @a delimeter in between as one string */ inline string join(const stringvec &tokens, const string &delimeter) { using namespace std; string joined; for (stringvec::const_iterator it = tokens.begin(); it != tokens.end(); ++it) { joined += *it; stringvec::const_iterator next = it; ++next; if (next != tokens.end()) joined += delimeter; } return joined; } template<typename T> string join(const std::vector<T> &tokens, const string &delimeter) { using namespace std; string joined; for (auto it = tokens.begin(); it != tokens.end(); ++it) { joined += str(*it); auto next = it; ++next; if (next != tokens.end()) joined += delimeter; } return joined; } /** @brief Strip whitespace from left side of string @ingroup stringutil @return @a str with whitespace stripped from the left side */ inline string lStrip(const string &str) { using namespace std; //now, cut out trailing whitespace size_t start = 0; while (isspace(str[start])) { start++; } //copy back into line return str.substr(start, str.size() - start); } /** @brief Strip whitespace from right side of string @ingroup stringutil @return @a str with whitespace stripped from the right side */ inline string rStrip(const string &str) { using namespace std; //now, cut out trailing whitespace size_t end = str.size() - 1; while (isspace(str[end])) { end--; } //copy back into line return str.substr(0, end + 1); } /** @brief Strip whitespace from both sides of string @ingroup stringutil @return @a str with whitespace stripped from both sides */ inline string strip(const string &str) { return rStrip(lStrip(str)); } /** @brief determine if a string contains a character @ingroup stringutil @return true if @a str contains @a c */ inline bool contains(const string &str, char c) { for (int i = 0; i < (int) str.length(); i++) if (str[i] == c) return true; return false; } /** @brief determine if a string contains a string @ingroup stringutil @return true if @a str contains @a substr */ inline bool contains(const string &str, const string &substr) { return (str.find(substr) != string::npos); } /** @brief Determine if a string begins with a particular string @ingroup stringutil @return true if @a str begins with @a substr */ inline bool startsWith(const string &str, const string &substr) { return (str.find(substr) == 0); } /** @brief Determine if a string ends with a particular string @ingroup stringutil @return true if @a str ends with @a substr */ inline bool endsWith(const string &str, const string &substr) { return (str.find(substr) == str.length() - substr.length()); } /** @brief find a "closing symbol" in a string. @ingroup stringutil Finds corresponding closing paren for a paren at a given position. @return -1 if there isn't one. Will still work if @a openPos is after the opening paren, but before any other opening parens. given parenthetized string "( 1 + ( 3 / 4 ))" @verbatim openPos: 0 return: 15 openPos: 1,2,3,4,5 return: 15 openPos: 6 return: 14 openPos: 7,8,9,10,11,12,13 return: 14 openPos: 15 return: -1 @endverbatim @a openSymbol is the open delimeter. Function knows that for: @verbatim open: '(' close is: ')' open: '[' close is: ']' open: '{' close is: '}' open: '<' close is: '>' open: '"' close is: '"' open: ' close is: ' @endverbatim */ inline int findClosingSymbol(const string &str, int openPos, char openSymbol = '(') { using namespace std; char closeSymbol = '0'; switch (openSymbol) { case '(': closeSymbol = ')'; break; case '[': closeSymbol = ']'; break; case '{': closeSymbol = '}'; break; case '<': closeSymbol = '>'; break; case '"': closeSymbol = '"'; default: return -1; } int sum, i; i = -1; sum = 0; for (i = openPos; i < (int) str.length(); i++) { if (str[i] == openSymbol) { sum++; continue; } if (str[i] == closeSymbol) sum--; //now where are we? if (sum == 0) break; } return i; } /** @brief find a "closing symbol" in a stringvec. Finds corresponding closing paren for a paren at a given position. @return -1 if there isn't one. Will still work if @a openPos is after the opening paren, but before any other opening parens. given parenthetized string "( 1 + ( 3 / 4 ))" @verbatim openPos: 0 return: 15 openPos: 1,2,3,4,5 return: 15 openPos: 6 return: 14 openPos: 7,8,9,10,11,12,13 return: 14 openPos: 15 return: -1 @endverbatim @a openSymbol is the open delimeter. Function knows that for: @verbatim open: '(' close is: ')' open: '[' close is: ']' open: '{' close is: '}' open: '<' close is: '>' open: '"' close is: '"' open: ' close is: ' @endverbatim */ inline int findClosingSymbol(const stringvec &strlist, int openPos, const string &openSymbol = "(") { using namespace std; string closeSymbol = "0"; int sum = 0, i = -1; if (openSymbol == "(") closeSymbol = ")"; else if (openSymbol == "[") closeSymbol = "]"; else if (openSymbol == "{") closeSymbol = "}"; else if (openSymbol == "<") closeSymbol = ">"; else if (openSymbol == "\"") closeSymbol = "\""; else if (openSymbol == "'") closeSymbol = "'"; else { return -1; } for (i = openPos; i < (int) strlist.size(); i++) { if (strlist[i] == openSymbol) { sum++; continue; } else if (strlist[i] == closeSymbol) sum--; //now where are we? if (sum == 0) break; } return i; } /** @brief remove all characters in an input string from another string @ingroup stringutil @return a string made up of @a str, but with all chars in @a set cut out. */ inline string removeSet(const string &str, const string &set) { using namespace std; string out; size_t l = str.length(); for (int i = 0; i < l; i++) { if (set.find(str[i]) == string::npos) out.push_back(str[i]); } return out; } /** @brief remove a subset of a string @ingroup stringutil @return str with the substring starting at @a startingAt @a charCount long cut out */ inline string remove(const string &str, int startingAt, int charCount) { using namespace std; string out; for (int i = 0; i < startingAt; i++) out.push_back(str[i]); for (int i = startingAt + charCount; i < (int) str.length(); i++) out.push_back(str[i]); return out; } /** @brief insert a subset of a string into another string @ingroup stringutil */ inline void moveInto(string &src, string &dest, int startingAt, int charCount) { using namespace std; for (int i = startingAt; i < startingAt + charCount; i++) { if (i < (int) src.length()) dest.push_back(src[i]); } src = remove(src, startingAt, charCount); } /** @brief convert a canonical four-byte int code to a string. @ingroup stringutil Converts a canonical int-code to string; such that: @code const unsigned int foobar = 'APPL'; cout << intToString( foobar ) << endl; @endcode Would print APPL. */ inline string intCodeToString(unsigned int code) { char buf[5]; buf[0] = (char) ((code & 0xFF000000) >> 24); buf[1] = (char) ((code & 0x00FF0000) >> 16); buf[2] = (char) ((code & 0x0000FF00) >> 8); buf[3] = (char) (code & 0x000000FF); buf[4] = '\0'; return string(buf); } /** @brief calculate a hash code for a string. @ingroup stringutil @return a hash-code for a string @a s. @note the hash algorithm is adapted from java.lang.String */ inline size_t hash(const string &s) { size_t n = s.length(), h = 0; for (size_t i = 0; i < n; i++) { h += s[i] * static_cast<size_t>(powi(31, static_cast<int>(n - 1 - i))); } h += s[n - 1]; return h; } inline string readFile(const string &filename) { using namespace std; fstream file(filename.c_str(), ios::in | ios::binary | ios::ate); long size = file.tellg(); file.seekg(0, ios::beg); if (size <= 0) { return string(); } char *buf = new char[size]; file.read(buf, size); file.close(); string text(buf, size); delete[] buf; return text; } inline stringvec readFileIntoLines(const string &filename) { string buf = readFile(filename); if (buf.size() == 0) return stringvec(); stringvec lines = split(buf, '\n'); for (stringvec::iterator line(lines.begin()), end(lines.end()); line != end; ++line) { *line = strip(*line); } return lines; } } } // end namespace core::strings #endif /* Strings_h */
28.02584
113
0.480361
ShamylZakariya
bd16d949e77a55ae0d8569c0c43a82664de9e1ed
1,071
hpp
C++
include/models/mesh.hpp
h4k1m0u/video
4739f8b1b6c837c41fdb53fc7dea97a47b285d0b
[ "MIT" ]
5
2021-11-11T23:59:38.000Z
2022-03-24T02:10:40.000Z
include/models/mesh.hpp
h4k1m0u/video
4739f8b1b6c837c41fdb53fc7dea97a47b285d0b
[ "MIT" ]
null
null
null
include/models/mesh.hpp
h4k1m0u/video
4739f8b1b6c837c41fdb53fc7dea97a47b285d0b
[ "MIT" ]
1
2022-01-15T13:31:10.000Z
2022-01-15T13:31:10.000Z
#ifndef MESH_HPP #define MESH_HPP #include <vector> #include <glm/glm.hpp> #include <assimp/mesh.h> #include "texture_2d.hpp" /** * Wrapper around Assimp::aiMesh used to get vertexes & faces for given mesh * Used by `models::Model` to parse meshes within current scene * Accessed publicly from `renderer::ModelRenderer` through `models::Model` * Namespace to avoid confusion between `models/Model` & `entities/Model` */ namespace AssimpUtil { struct Mesh { std::vector<float> vertexes; std::vector<unsigned int> indices; /* used to calculate bounding box for 3d model (for collision detection) */ std::vector<glm::vec3> positions; unsigned int material; glm::vec3 color; Texture2D texture_diffuse; Texture2D texture_normal; /* differentiates meshes with color instead of diffuse texture (e.g. tree) in frag. shader */ bool has_texture_diffuse; bool has_texture_normal; Mesh(); Mesh(aiMesh* mesh); private: aiMesh* m_mesh; void set_vertexes(); void set_indices(); }; } #endif // MESH_HPP
24.340909
97
0.701214
h4k1m0u
bd1d52a503533cac7676b4f148ee7d7aa3e701cf
1,766
hpp
C++
openscenario/openscenario_interpreter/include/openscenario_interpreter/utility/circular_check.hpp
autocore-ai/scenario_simulator_v2
bb9569043e20649f0e4390e9225b6bb7b4de10b6
[ "Apache-2.0" ]
45
2021-04-12T22:43:25.000Z
2022-02-27T23:57:53.000Z
openscenario/openscenario_interpreter/include/openscenario_interpreter/utility/circular_check.hpp
autocore-ai/scenario_simulator_v2
bb9569043e20649f0e4390e9225b6bb7b4de10b6
[ "Apache-2.0" ]
140
2021-04-13T04:28:19.000Z
2022-03-30T12:44:32.000Z
openscenario/openscenario_interpreter/include/openscenario_interpreter/utility/circular_check.hpp
autocore-ai/scenario_simulator_v2
bb9569043e20649f0e4390e9225b6bb7b4de10b6
[ "Apache-2.0" ]
13
2021-05-22T02:24:49.000Z
2022-03-25T05:16:31.000Z
// 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 OPENSCENARIO_INTERPRETER__UTILITY__CIRCULAR_CHECK_HPP_ #define OPENSCENARIO_INTERPRETER__UTILITY__CIRCULAR_CHECK_HPP_ #include <unordered_map> #include <utility> namespace openscenario_interpreter { inline namespace utility { namespace detail { template <class Node, class NodeToChildren, class NodeToBool> bool circular_check(const Node & node, NodeToChildren && node_to_children, NodeToBool & visit_flag) { if (visit_flag[node]) { return true; } visit_flag[node] = true; for (auto && child : node_to_children(node)) { if (child == node) continue; if (circular_check(child, node_to_children, visit_flag)) { return true; } visit_flag[child] = false; } return false; } } // namespace detail template <class Node, class NodeToChildren, class Hash = std::hash<Node>> bool circular_check(const Node & init, NodeToChildren && node_to_children) { std::unordered_map<Node, bool, Hash> visit_flag; return detail::circular_check(init, node_to_children, visit_flag); } } // namespace utility } // namespace openscenario_interpreter #endif // OPENSCENARIO_INTERPRETER__UTILITY__CIRCULAR_CHECK_HPP_
29.932203
99
0.754247
autocore-ai
bd2038e6b72ff5d764263e8a301f076f803e5352
1,008
hpp
C++
src/providers/twitch/pubsubmessages/ChatModeratorAction.hpp
1xelerate/chatterino2
57783c7478a955f5224e5025653c0f8549df12fc
[ "MIT" ]
200
2017-01-24T11:23:03.000Z
2019-05-15T19:31:18.000Z
src/providers/twitch/pubsubmessages/ChatModeratorAction.hpp
1xelerate/chatterino2
57783c7478a955f5224e5025653c0f8549df12fc
[ "MIT" ]
878
2017-02-06T13:25:24.000Z
2019-05-18T16:15:21.000Z
src/providers/twitch/pubsubmessages/ChatModeratorAction.hpp
1xelerate/chatterino2
57783c7478a955f5224e5025653c0f8549df12fc
[ "MIT" ]
138
2017-02-07T18:01:49.000Z
2019-05-18T19:00:03.000Z
#pragma once #include <QJsonObject> #include <QString> #include <magic_enum.hpp> namespace chatterino { struct PubSubChatModeratorActionMessage { enum class Type { ModerationAction, ChannelTermsAction, INVALID, }; QString typeString; Type type = Type::INVALID; QJsonObject data; PubSubChatModeratorActionMessage(const QJsonObject &root); }; } // namespace chatterino template <> constexpr magic_enum::customize::customize_t magic_enum::customize::enum_name< chatterino::PubSubChatModeratorActionMessage::Type>( chatterino::PubSubChatModeratorActionMessage::Type value) noexcept { switch (value) { case chatterino::PubSubChatModeratorActionMessage::Type:: ModerationAction: return "moderation_action"; case chatterino::PubSubChatModeratorActionMessage::Type:: ChannelTermsAction: return "channel_terms_action"; default: return default_tag; } }
21.446809
78
0.6875
1xelerate
bd222b9ee234b224c567238d94f4b6edd1fa24e9
405
cpp
C++
src/duke/image/ImageUtils.cpp
hradec/duke
efacf7139cd1d7c2cd2f5127079721bd263dda50
[ "MIT" ]
51
2015-01-07T18:36:39.000Z
2021-11-30T15:24:44.000Z
src/duke/image/ImageUtils.cpp
virneo/duke
efacf7139cd1d7c2cd2f5127079721bd263dda50
[ "MIT" ]
1
2015-01-08T10:48:43.000Z
2015-02-11T19:32:14.000Z
src/duke/image/ImageUtils.cpp
virneo/duke
efacf7139cd1d7c2cd2f5127079721bd263dda50
[ "MIT" ]
18
2015-05-11T12:43:37.000Z
2019-11-29T11:15:41.000Z
#include "duke/image/ImageUtils.hpp" #include "duke/base/Check.hpp" size_t getChannelsByteSize(const Channels& channels) { size_t bits = 0; for (const auto& channel : channels) bits += channel.bits; CHECK(bits % 8 == 0); return bits / 8; } size_t getImageSize(const ImageDescription& description) { return description.width * description.height * getChannelsByteSize(description.channels); }
27
92
0.740741
hradec
bd225d165bbba76e11d2b1a29d6ea7b1efc0110b
18,892
cpp
C++
CodeForces-Solution/1621I.cpp
Tech-Intellegent/CodeForces-Solution
2f291a38b80b8ff2a2595b2e526716468ff26bf8
[ "MIT" ]
1
2022-01-23T07:18:07.000Z
2022-01-23T07:18:07.000Z
CodeForces-Solution/1621I.cpp
Tech-Intellegent/CodeForces-Solution
2f291a38b80b8ff2a2595b2e526716468ff26bf8
[ "MIT" ]
null
null
null
CodeForces-Solution/1621I.cpp
Tech-Intellegent/CodeForces-Solution
2f291a38b80b8ff2a2595b2e526716468ff26bf8
[ "MIT" ]
1
2022-02-05T11:53:04.000Z
2022-02-05T11:53:04.000Z
#include <bits/stdc++.h> using namespace std; using ll = long long; using db = long double; // or double, if TL is tight using str = string; // yay python! // pairs using pi = pair<int,int>; using pl = pair<ll,ll>; using pd = pair<db,db>; #define mp make_pair #define f first #define s second #define tcT template<class T #define tcTU tcT, class U // ^ lol this makes everything look weird but I'll try it tcT> using V = vector<T>; tcT, size_t SZ> using AR = array<T,SZ>; using vi = V<int>; using vb = V<bool>; using vl = V<ll>; using vd = V<db>; using vs = V<str>; using vpi = V<pi>; using vpl = V<pl>; using vpd = V<pd>; // vectors // oops size(x), rbegin(x), rend(x) need C++17 #define sz(x) int((x).size()) #define bg(x) begin(x) #define all(x) bg(x), end(x) #define rall(x) x.rbegin(), x.rend() #define sor(x) sort(all(x)) #define rsz resize #define ins insert #define pb push_back #define eb emplace_back #define ft front() #define bk back() #define lb lower_bound #define ub upper_bound tcT> int lwb(V<T>& a, const T& b) { return int(lb(all(a),b)-bg(a)); } tcT> int upb(V<T>& a, const T& b) { return int(ub(all(a),b)-bg(a)); } // loops #define FOR(i,a,b) for (int i = (a); i < (b); ++i) #define F0R(i,a) FOR(i,0,a) #define ROF(i,a,b) for (int i = (b)-1; i >= (a); --i) #define R0F(i,a) ROF(i,0,a) #define rep(a) F0R(_,a) #define each(a,x) for (auto& a: x) const int MOD = 1e9+7; // 998244353; const int MX = 2e5+5; const ll BIG = 1e18; // not too close to LLONG_MAX const db PI = acos((db)-1); const int dx[4]{1,0,-1,0}, dy[4]{0,1,0,-1}; // for every grid problem!! mt19937 rng((uint32_t)chrono::steady_clock::now().time_since_epoch().count()); template<class T> using pqg = priority_queue<T,vector<T>,greater<T>>; // bitwise ops // also see https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html constexpr int pct(int x) { return __builtin_popcount(x); } // # of bits set constexpr int bits(int x) { // assert(x >= 0); // make C++11 compatible until USACO updates ... return x == 0 ? 0 : 31-__builtin_clz(x); } // floor(log2(x)) constexpr int p2(int x) { return 1<<x; } constexpr int msk2(int x) { return p2(x)-1; } ll cdiv(ll a, ll b) { return a/b+((a^b)>0&&a%b); } // divide a by b rounded up ll fdiv(ll a, ll b) { return a/b-((a^b)<0&&a%b); } // divide a by b rounded down tcT> bool ckmin(T& a, const T& b) { return b < a ? a = b, 1 : 0; } // set a = min(a,b) tcT> bool ckmax(T& a, const T& b) { return a < b ? a = b, 1 : 0; } // set a = max(a,b) tcTU> T fstTrue(T lo, T hi, U f) { ++hi; assert(lo <= hi); // assuming f is increasing while (lo < hi) { // find first index such that f is true T mid = lo+(hi-lo)/2; f(mid) ? hi = mid : lo = mid+1; } return lo; } tcTU> T lstTrue(T lo, T hi, U f) { --lo; assert(lo <= hi); // assuming f is decreasing while (lo < hi) { // find first index such that f is true T mid = lo+(hi-lo+1)/2; f(mid) ? lo = mid : hi = mid-1; } return lo; } tcT> void remDup(vector<T>& v) { // sort and remove duplicates sort(all(v)); v.erase(unique(all(v)),end(v)); } tcTU> void erase(T& t, const U& u) { // don't erase auto it = t.find(u); assert(it != end(t)); t.erase(it); } // element that doesn't exist from (multi)set #define tcTUU tcT, class ...U inline namespace Helpers { //////////// is_iterable // https://stackoverflow.com/questions/13830158/check-if-a-variable-type-is-iterable // this gets used only when we can call begin() and end() on that type tcT, class = void> struct is_iterable : false_type {}; tcT> struct is_iterable<T, void_t<decltype(begin(declval<T>())), decltype(end(declval<T>())) > > : true_type {}; tcT> constexpr bool is_iterable_v = is_iterable<T>::value; //////////// is_readable tcT, class = void> struct is_readable : false_type {}; tcT> struct is_readable<T, typename std::enable_if_t< is_same_v<decltype(cin >> declval<T&>()), istream&> > > : true_type {}; tcT> constexpr bool is_readable_v = is_readable<T>::value; //////////// is_printable // // https://nafe.es/posts/2020-02-29-is-printable/ tcT, class = void> struct is_printable : false_type {}; tcT> struct is_printable<T, typename std::enable_if_t< is_same_v<decltype(cout << declval<T>()), ostream&> > > : true_type {}; tcT> constexpr bool is_printable_v = is_printable<T>::value; } inline namespace Input { tcT> constexpr bool needs_input_v = !is_readable_v<T> && is_iterable_v<T>; tcTUU> void re(T& t, U&... u); tcTU> void re(pair<T,U>& p); // pairs // re: read tcT> typename enable_if<is_readable_v<T>,void>::type re(T& x) { cin >> x; } // default tcT> void re(complex<T>& c) { T a,b; re(a,b); c = {a,b}; } // complex tcT> typename enable_if<needs_input_v<T>,void>::type re(T& i); // ex. vectors, arrays tcTU> void re(pair<T,U>& p) { re(p.f,p.s); } tcT> typename enable_if<needs_input_v<T>,void>::type re(T& i) { each(x,i) re(x); } tcTUU> void re(T& t, U&... u) { re(t); re(u...); } // read multiple // rv: resize and read vectors void rv(size_t) {} tcTUU> void rv(size_t N, V<T>& t, U&... u); template<class...U> void rv(size_t, size_t N2, U&... u); tcTUU> void rv(size_t N, V<T>& t, U&... u) { t.rsz(N); re(t); rv(N,u...); } template<class...U> void rv(size_t, size_t N2, U&... u) { rv(N2,u...); } // dumb shortcuts to read in ints void decrement() {} // subtract one from each tcTUU> void decrement(T& t, U&... u) { --t; decrement(u...); } #define ints(...) int __VA_ARGS__; re(__VA_ARGS__); #define int1(...) ints(__VA_ARGS__); decrement(__VA_ARGS__); } inline namespace ToString { tcT> constexpr bool needs_output_v = !is_printable_v<T> && is_iterable_v<T>; // ts: string representation to print tcT> typename enable_if<is_printable_v<T>,str>::type ts(T v) { stringstream ss; ss << fixed << setprecision(15) << v; return ss.str(); } // default tcT> str bit_vec(T t) { // bit vector to string str res = "{"; F0R(i,sz(t)) res += ts(t[i]); res += "}"; return res; } str ts(V<bool> v) { return bit_vec(v); } template<size_t SZ> str ts(bitset<SZ> b) { return bit_vec(b); } // bit vector tcTU> str ts(pair<T,U> p); // pairs tcT> typename enable_if<needs_output_v<T>,str>::type ts(T v); // vectors, arrays tcTU> str ts(pair<T,U> p) { return "("+ts(p.f)+", "+ts(p.s)+")"; } tcT> typename enable_if<is_iterable_v<T>,str>::type ts_sep(T v, str sep) { // convert container to string w/ separator sep bool fst = 1; str res = ""; for (const auto& x: v) { if (!fst) res += sep; fst = 0; res += ts(x); } return res; } tcT> typename enable_if<needs_output_v<T>,str>::type ts(T v) { return "{"+ts_sep(v,", ")+"}"; } // for nested DS template<int, class T> typename enable_if<!needs_output_v<T>,vs>::type ts_lev(const T& v) { return {ts(v)}; } template<int lev, class T> typename enable_if<needs_output_v<T>,vs>::type ts_lev(const T& v) { if (lev == 0 || !sz(v)) return {ts(v)}; vs res; for (const auto& t: v) { if (sz(res)) res.bk += ","; vs tmp = ts_lev<lev-1>(t); res.ins(end(res),all(tmp)); } F0R(i,sz(res)) { str bef = " "; if (i == 0) bef = "{"; res[i] = bef+res[i]; } res.bk += "}"; return res; } } inline namespace Output { template<class T> void pr_sep(ostream& os, str, const T& t) { os << ts(t); } template<class T, class... U> void pr_sep(ostream& os, str sep, const T& t, const U&... u) { pr_sep(os,sep,t); os << sep; pr_sep(os,sep,u...); } // print w/ no spaces template<class ...T> void pr(const T&... t) { pr_sep(cout,"",t...); } // print w/ spaces, end with newline void ps() { cout << "\n"; } template<class ...T> void ps(const T&... t) { pr_sep(cout," ",t...); ps(); } // debug to cerr template<class ...T> void dbg_out(const T&... t) { pr_sep(cerr," | ",t...); cerr << endl; } void loc_info(int line, str names) { cerr << "Line(" << line << ") -> [" << names << "]: "; } template<int lev, class T> void dbgl_out(const T& t) { cerr << "\n\n" << ts_sep(ts_lev<lev>(t),"\n") << "\n" << endl; } #ifdef LOCAL #define dbg(...) loc_info(__LINE__,#__VA_ARGS__), dbg_out(__VA_ARGS__) #define dbgl(lev,x) loc_info(__LINE__,#x), dbgl_out<lev>(x) #else // don't actually submit with this #define dbg(...) 0 #define dbgl(lev,x) 0 #endif const clock_t beg = clock(); #define dbg_time() dbg((db)(clock()-beg)/CLOCKS_PER_SEC) } inline namespace FileIO { void setIn(str s) { freopen(s.c_str(),"r",stdin); } void setOut(str s) { freopen(s.c_str(),"w",stdout); } void setIO(str s = "") { cin.tie(0)->sync_with_stdio(0); // unsync C / C++ I/O streams // cin.exceptions(cin.failbit); // throws exception when do smth illegal // ex. try to read letter into int if (sz(s)) setIn(s+".in"), setOut(s+".out"); // for old USACO } } /** * Description: 1D range minimum query. Can also do queries * for any associative operation in $O(1)$ with D\&C * Source: KACTL * Verification: * https://cses.fi/problemset/stats/1647/ * http://wcipeg.com/problem/ioi1223 * https://pastebin.com/ChpniVZL * Memory: O(N\log N) * Time: O(1) */ tcT> struct RMQ { int level(int x) { return 31-__builtin_clz(x); } V<T> v; V<vi> jmp; int cmb(int a, int b) { return v[a]==v[b]?min(a,b):(v[a]<v[b]?a:b); } void init(const V<T>& _v) { v = _v; jmp = {vi(sz(v))}; iota(all(jmp[0]),0); for (int j = 1; 1<<j <= sz(v); ++j) { jmp.pb(vi(sz(v)-(1<<j)+1)); F0R(i,sz(jmp[j])) jmp[j][i] = cmb(jmp[j-1][i], jmp[j-1][i+(1<<(j-1))]); } } int index(int l, int r) { assert(l <= r); int d = level(r-l+1); return cmb(jmp[d][l],jmp[d][r-(1<<d)+1]); } T query(int l, int r) { return v[index(l,r)]; } }; /** * Description: Sort suffixes. First element of \texttt{sa} is \texttt{sz(S)}, * \texttt{isa} is the inverse of \texttt{sa}, and \texttt{lcp} stores * the longest common prefix between every two consecutive elements of \texttt{sa}. * Time: O(N\log N) * Source: SuprDewd, KACTL, majk, ekzhang (http://ekzlib.herokuapp.com) * Verification: * https://open.kattis.com/problems/suffixsorting * https://judge.yosupo.jp/problem/suffixarray */ // #include "RMQ.h" template<class Char> struct SuffixArray { V<Char> S; int N; vi sa, isa, lcp; void init(V<Char> _S) { N = sz(S = _S)+1; genSa(); genLcp(); } void genSa() { // sa has size sz(S)+1, starts with sz(S) sa = isa = vi(N); sa[0] = N-1; iota(1+all(sa),0); sort(1+all(sa),[&](int a, int b) { return S[a] < S[b]; }); FOR(i,1,N) { int a = sa[i-1], b = sa[i]; isa[b] = i > 1 && S[a] == S[b] ? isa[a] : i; } for (int len = 1; len < N; len *= 2) { // currently sorted // by first len chars vi s(sa), is(isa), pos(N); iota(all(pos),0); each(t,s) {int T=t-len;if (T>=0) sa[pos[isa[T]]++] = T;} FOR(i,1,N) { int a = sa[i-1], b = sa[i]; /// verify that nothing goes out of bounds isa[b] = is[a]==is[b]&&is[a+len]==is[b+len]?isa[a]:i; } } } void genLcp() { // Kasai's Algo lcp = vi(N-1); int h = 0; F0R(b,N-1) { int a = sa[isa[b]-1]; while (a+h < sz(S) && S[a+h] == S[b+h]) ++h; lcp[isa[b]-1] = h; if (h) h--; } R.init(lcp); /// if we cut off first chars of two strings /// with lcp h then remaining portions still have lcp h-1 } RMQ<int> R; int getLCP(int a, int b) { // lcp of suffixes starting at a,b if (a == b) return sz(S)-a; int l = isa[a], r = isa[b]; if (l > r) swap(l,r); return R.query(l,r-1); } }; int N; vi prefix_answers(SuffixArray<int>& SA, V<int> A) { set<int> positions; V<vpi> to_kill(N+1); vi ans; F0R(i,N) { auto deal = [&](set<int>::iterator il, set<int>::iterator ir) { int l = *il, r = *ir; assert(l < r); to_kill.at(r+SA.getLCP(l,r)).pb({l,r}); }; auto del = [&](set<int>::iterator it) { if (it != begin(positions) && next(it) != end(positions)) deal(prev(it),next(it)); positions.erase(it); }; { auto it = positions.ins(i).f; if (i) deal(prev(it),it); } while (sz(to_kill[i])) { pi p = to_kill[i].bk; to_kill[i].pop_back(); auto it = positions.find(p.f); if (it == end(positions) || next(it) == end(positions) || *next(it) != p.s) continue; if (SA.isa[p.f] > SA.isa[p.s]) del(it); else del(next(it)); } ans.pb(*positions.rbegin()); } return ans; } /** * Description: Polynomial hash for substrings with two bases. * Source: * KACTL * https://codeforces.com/contest/1207/submission/59309672 * Verification: * USACO Dec 17 Plat 1 (LCP :o) * CF Check Transcription */ using H = AR<int,1>; // bases not too close to ends H makeH(int c) { return {c}; } uniform_int_distribution<int> BDIST(0.1*MOD,0.9*MOD); // const H base{BDIST(rng)}; const H base{10}; /// const T ibase = {(int)inv(mi(base[0])),(int)inv(mi(base[1]))}; H operator+(H l, H r) { F0R(i,1) if ((l[i] += r[i]) >= MOD) l[i] -= MOD; return l; } H operator-(H l, H r) { F0R(i,1) if ((l[i] -= r[i]) < 0) l[i] += MOD; return l; } H operator*(H l, H r) { F0R(i,1) l[i] = (ll)l[i]*r[i]%MOD; return l; } /// H& operator+=(H& l, H r) { return l = l+r; } /// H& operator-=(H& l, H r) { return l = l-r; } /// H& operator*=(H& l, H r) { return l = l*r; } V<H> pows{{1}}; struct HashRange { vi S; V<H> cum{{}}; void add(int c) { S.pb(c); cum.pb(base*cum.bk+makeH(c)); } void add(vi s) { reverse(all(s)); each(c,s) add(c); } void extend(int len) { while (sz(pows) <= len) pows.pb(base*pows.bk); } H hash(int l, int r) { tie(l,r) = mp(N-1-r,N-1-l); int len = r+1-l; extend(len); return cum[r+1]-pows[len]*cum[l]; } /**int lcp(HashRange& b) { return first_true([&](int x) { return cum[x] != b.cum[x]; },0,min(sz(S),sz(b.S)))-1; }*/ }; /// HashRange HR; HR.add("ababab"); F0R(i,6) FOR(j,i,6) ps(i,j,HR.hash(i,j)); /** * Description: 1D point update, range query where \texttt{cmb} is * any associative operation. If $N=2^p$ then \texttt{seg[1]==query(0,N-1)}. * Time: O(\log N) * Source: * http://codeforces.com/blog/entry/18051 * KACTL * Verification: SPOJ Fenwick */ HashRange HR; struct HH { int l,r; ll len; H val; HH(): l(0), r(-1), len(0), val({0}) {} HH(int l_, int r_): l(l_), r(r_) { len = r-l+1; val = HR.hash(l,r); } HH(int len_, H val_): len(len_), val(val_) {} HH get_prefix(int p) { assert(1 <= p && p <= len); return HH(l,l+p-1); } }; HH operator+(HH l, const HH& r) { assert(l.len < N); HR.extend(l.len); l.val = l.val+r.val*pows.at(l.len); l.len += r.len; return l; } H hash_prefix(pi p, int partial_len) { assert(p.s-p.f+1 >= partial_len); return HR.hash(p.f,p.f+partial_len-1); } H hash_at(pi p, int pos) { assert(p.s-p.f+1 > pos); return HR.hash(p.f+pos,p.f+pos); } tcT> struct NotSegTree { vl lens{0}; V<H> hashes{H{}}; deque<pi> intervals; void push_front(int l, int r) { dbg("PUSH FRONT",l,r); const int len = r-l+1; lens.pb(len+lens.bk); HR.extend(len); hashes.pb(HR.hash(l,r)+pows.at(len)*hashes.bk); intervals.pb({l,r}); } vi get_all_indices() { vi res; R0F(i,sz(intervals)) { auto p = intervals[i]; FOR(j,p.f,p.s+1) res.pb(j); } return res; } vi get_indices() { reverse(all(intervals)); vi ans; each(p,intervals) { FOR(i,p.f,p.s+1) { ans.pb(i); if (sz(ans) == N) break; } if (sz(ans) == N) break; } assert(sz(ans) == N); return ans; } HH get_prefix_ok(int len) { const int ori_len = len; HR.extend(N); HH H{}; R0F(i,sz(intervals)) { // const int cur_len = intervals[i].s-intervals[i].f+1; FOR(j,intervals[i].f,intervals[i].s+1) { if (len) { // dbg("BEFORE",H.len,HR.hash(j,j)); H = H+HH(j,j); // dbg("AFTER",j,H.val); --len; } } } assert(H.len == ori_len); // dbg("END GET PREFIX",H.len,H.val); return H; } HH get_prefix(int len) { // dbg("STARTING",len); // HH wut = get_prefix_ok(len); // dbg("MODEL",wut.len) HR.extend(N); int i = fstTrue(0,sz(lens)-1,[&](int x) { return lens.bk-lens[x] <= len; }); const int partial_len = lens.bk-lens.at(i); H h = hashes.bk-hashes.at(i)*pows.at(partial_len); // dbg(hashes,hashes.at(i)); // dbg(partial_len); // dbg(i); // dbg(h); // dbg("----"); if (partial_len < len) { h = h+pows.at(partial_len)*hash_prefix(intervals.at(i-1),len-partial_len); } // dbg("FINAL",len); // dbg(h); // dbg(wut.val); // assert(wut.len == len && h == wut.val); return HH{len,h}; } H hash_at(int pos) { // R0F(i,sz(intervals)) { // const int len = intervals[i].s-intervals[i].f+1; // if (pos < len) return ::hash_at(intervals.at(i),pos); // pos -= len; // } // assert(false); int i = fstTrue(0,sz(lens)-1,[&](int x) { return lens.bk-lens[x] <= pos; }); const int partial_len = lens.bk-lens.at(i); return ::hash_at(intervals.at(i-1),pos-partial_len); } }; vi tran(vi A) { SuffixArray<int> SA; SA.init(A); HR = HashRange(); HR.add(A); // dbg(A); // F0R(i,N) dbg("HA",i,HR.hash(i,i)); // dbg(base,HR.hash(0,1)); // exit(0); // dbg("POWS",sz(pows)) vi p = prefix_answers(SA,A); vi q(N); F0R(i,N) { const int len = i+1-p[i]; int lo = 1, hi = (i+1)/len; q[i] = lstTrue(lo,hi,[&](int x) { return SA.getLCP(i+1-len*x,i+1-len*(x-1)) >= len*(x-1); }); q[i] = i+1-len*q[i]; assert(q[i] >= 0); } NotSegTree<HH> ST; R0F(i,N) { // best out of 0 .. i-1 // dbg("DOING",i); // F0R(j,i+1) pr(A[j],' '); // each(x,ST.get_all_indices()) pr(A.at(x),' '); // ps(); const int len = N-i; int smarter = p.at(i); auto hash_bounds = [&](int l, int r) { assert(l <= i); HH ans = HH(l,min(r,i)); l = i+1; if (l <= r) { ans = ans+ST.get_prefix(r-l+1); } return ans.val; }; auto hash_start = [&](int l, int len) { return hash_bounds(l,l+len-1); }; auto hash_at = [&](int l) { if (l <= i) return HR.hash(l,l); return ST.hash_at(l-i-1); }; if (p[i] != q[i] && q[i]+len-1 > i) { // dbg("TRYING",p[i],q[i],len); int lcp = lstTrue(1,len,[&](int x) { return hash_start(p[i],x) == hash_start(q[i],x); }); // dbg("GOT LCP",lcp); // dbg(hash_start(p[i],4),hash_start(q[i],4)); // exit(0); if (lcp < len && hash_at(q[i]+lcp) < hash_at(p[i]+lcp)) { smarter = q[i]; } if (lcp < len) { dbg("WHOOPS",q[i]+lcp,p[i]+lcp,hash_at(q[i]+lcp),hash_at(p[i]+lcp)); } } int l = smarter, r = min(smarter+len,i+1); ST.push_front(l,r-1); } vi inds = ST.get_indices(); vi ans; each(i,inds) ans.pb(A.at(i)); return ans; } int main() { setIO(); re(N); vi A(N); re(A); V<vi> seq{A}; while (1) { vi new_bk = tran(seq.bk); if (new_bk == seq.bk) break; seq.pb(new_bk); } dbg(sz(seq)); ints(q); rep(q) { ints(a,b); ckmin(a,sz(seq)-1); cout << seq.at(a).at(b-1) << "\n"; } // you should actually read the stuff at the bottom } /* stuff you should look for * int overflow, array bounds * special cases (n=1?) * do smth instead of nothing and stay organized * WRITE STUFF DOWN * DON'T GET STUCK ON ONE APPROACH */
29.611285
95
0.578287
Tech-Intellegent
bd2342dfae1f5018f3a324c18c4b02b82c78d6fc
1,891
cpp
C++
src/features/DebugOverlayPass.cpp
bferan/lucent
b19163df12739ffc513110d927e92f98c0b54321
[ "MIT" ]
1
2021-11-12T08:42:43.000Z
2021-11-12T08:42:43.000Z
src/features/DebugOverlayPass.cpp
bferan/lucent
b19163df12739ffc513110d927e92f98c0b54321
[ "MIT" ]
null
null
null
src/features/DebugOverlayPass.cpp
bferan/lucent
b19163df12739ffc513110d927e92f98c0b54321
[ "MIT" ]
null
null
null
#include "DebugOverlayPass.hpp" #include "rendering/Engine.hpp" namespace lucent { void AddDebugOverlayPass(Renderer& renderer, DebugConsole* console, Texture* output) { auto& settings = renderer.GetSettings(); console->SetScreenSize(settings.viewportWidth, settings.viewportHeight); auto overlayFramebuffer = renderer.AddFramebuffer(FramebufferSettings{ .colorTextures = { output } }); auto debugTextShader = renderer.AddPipeline(PipelineSettings{ .shaderName = "DebugFont.shader", .framebuffer = overlayFramebuffer, .depthTestEnable = false, .depthWriteEnable = false }); auto debugShapeShader = renderer.AddPipeline(PipelineSettings{ .shaderName = "DebugShape.shader", .framebuffer = overlayFramebuffer, . depthTestEnable = false, .depthWriteEnable = false }); auto debugShapes = (DebugShapeBuffer*)renderer.GetDebugShapesBuffer()->Map(); auto sphere = settings.sphereMesh.get(); renderer.AddPass("Debug overlay", [=](Context& ctx, View& view) { ctx.GetDevice()->WaitIdle(); ctx.BeginRenderPass(overlayFramebuffer); ctx.BindPipeline(debugShapeShader); for (int i = 0; i < debugShapes->numShapes; ++i) { auto& shape = debugShapes->shapes[i]; auto mvp = view.GetViewProjectionMatrix() * Matrix4::Translation(Vector3(shape.srcPos)) * Matrix4::Scale(shape.radius, shape.radius, shape.radius); ctx.Uniform("u_MVP"_id, mvp); ctx.Uniform("u_Color"_id, shape.color); ctx.BindBuffer(sphere->vertexBuffer); ctx.BindBuffer(sphere->indexBuffer); ctx.Draw(sphere->numIndices); } ctx.BindPipeline(debugTextShader); console->RenderText(ctx); ctx.EndRenderPass(); debugShapes->numShapes = 0; }); } }
30.5
84
0.651507
bferan
bd24ea138e40e37ba1c17fae2842dca3ce54d21e
310
hpp
C++
Test/CalculatorPluginAPI/src/AddIntent.hpp
PiotrMoscicki/PolyPlugin-1
32fd9baf63541f1c240d7435a48c56ad6bce62ee
[ "MIT" ]
null
null
null
Test/CalculatorPluginAPI/src/AddIntent.hpp
PiotrMoscicki/PolyPlugin-1
32fd9baf63541f1c240d7435a48c56ad6bce62ee
[ "MIT" ]
9
2020-04-01T14:45:10.000Z
2020-05-11T07:29:26.000Z
Test/CalculatorPluginAPI/src/AddIntent.hpp
PiotrMoscicki/PolyPlugin-1
32fd9baf63541f1c240d7435a48c56ad6bce62ee
[ "MIT" ]
2
2020-04-01T17:58:13.000Z
2020-05-07T15:21:20.000Z
#pragma once #include <pp/Info.hpp> //------------------------------------------------------------------------------------------------------------------------------------------ class AddIntent { public: using Result = int; static inline pp::IntentInfo Info = { "AddIntent", 3 }; int a = 0; int b = 0; };
22.142857
140
0.348387
PiotrMoscicki
bd2ae0f3fbc874deedff2707882158011aad415b
2,625
cc
C++
simlib/src/object.cc
MichalCab/IMS
d45dd8e7c0f794b4ee7f2ce1ccbc45edeaaa106e
[ "MIT" ]
null
null
null
simlib/src/object.cc
MichalCab/IMS
d45dd8e7c0f794b4ee7f2ce1ccbc45edeaaa106e
[ "MIT" ]
null
null
null
simlib/src/object.cc
MichalCab/IMS
d45dd8e7c0f794b4ee7f2ce1ccbc45edeaaa106e
[ "MIT" ]
null
null
null
///////////////////////////////////////////////////////////////////////////// //! \file object.cc Root of SIMLIB/C++ class hierarchy // // Copyright (c) 1991-2004 Petr Peringer // // This library is licensed under GNU Library GPL. See the file COPYING. // // // this module contains implementation of base class SimObject // #include "simlib.h" #include "internal.h" //////////////////////////////////////////////////////////////////////////// namespace simlib3 { SIMLIB_IMPLEMENTATION; //////////////////////////////////////////////////////////////////////////// // static flag for IsAllocated() static bool SimObject_allocated = false; //////////////////////////////////////////////////////////////////////////// //! allocate memory for object void *SimObject::operator new(size_t size) { // try { void *ptr = ::new char[size]; // global operator new // Dprintf(("SimObject::operator new(%u) = %p ", size, ptr)); // }catch(...) { SIMLIB_error(MemoryError); } // if(!ptr) SIMLIB_error(MemoryError); // for old compilers SimObject_allocated = true; // update flag return ptr; } //////////////////////////////////////////////////////////////////////////// //! free memory // //TODO: this can create trouble if called from e.g. Behavior() // void SimObject::operator delete(void *ptr) { // Dprintf(("SimObject::operator delete(%p) ", ptr)); SimObject *sp = static_cast<SimObject*>(ptr); if (sp->isAllocated()) { sp->_flags = 0; // clear all flags ::operator delete[](ptr); // free memory } } //////////////////////////////////////////////////////////////////////////// //! constructor // SimObject::SimObject() : _name(0), _flags(0) { // Dprintf(("SimObject::SimObject() this=%p ", this)); if(SimObject_allocated) { SimObject_allocated = false; _flags |= (1<<_ALLOCATED_FLAG); } } //////////////////////////////////////////////////////////////////////////// //! virtual destructor // SimObject::~SimObject() { // Dprintf(("SimObject::~SimObject() this=%p ", this)); } //////////////////////////////////////////////////////////////////////////// //! set the name of object // void SimObject::SetName(const char *name) { _name = name; } //////////////////////////////////////////////////////////////////////////// //! get the name of object // const char *SimObject::Name() const { if(_name==0) return ""; // no name return _name; } //////////////////////////////////////////////////////////////////////////// //! print object's info // void SimObject::Output() const { Print("SimObject: this=%p, name=%s\n", this, Name()); // default } } // namespace
25.735294
77
0.459048
MichalCab
bd2e8c3a24a4cfd373e86cb1064b39a0e1db56e3
1,916
cpp
C++
EterPack API/EterPack API/src/EterUtils.cpp
christian-roggia/metin2-eternexus
99d239e33733ae777822e0ea86ab5b437e010b64
[ "MIT" ]
13
2017-01-23T01:55:12.000Z
2020-09-10T12:13:59.000Z
EterPack API/EterPack API/src/EterUtils.cpp
Christian-Roggia/metin2-eternexus
99d239e33733ae777822e0ea86ab5b437e010b64
[ "MIT" ]
1
2020-09-13T19:42:31.000Z
2020-09-17T21:22:02.000Z
EterPack API/EterPack API/src/EterUtils.cpp
Christian-Roggia/metin2-eternexus
99d239e33733ae777822e0ea86ab5b437e010b64
[ "MIT" ]
28
2017-02-25T18:50:58.000Z
2022-02-17T12:19:38.000Z
#include "EterUtils.h" void XTEA_DECRYPT(UINT32 *v, UINT32 *k) { UINT32 sum = 0xC6EF3720, delta = 0x61C88647; UINT32 v0 = v[0], v1 = v[1]; for (int i = 0; i < 32; i++) { v1 -= (v0 + (16 * v0 ^ (v0 >> 5))) ^ (sum + k[(sum >> 11) & 3]); sum += delta; v0 -= (v1 + (16 * v1 ^ (v1 >> 5))) ^ (sum + k[sum & 3]); } v[0] = v0; v[1] = v1; } void XTEA_ENCRYPT(UINT32 *v, UINT32 *k) { UINT32 sum = 0, delta = 0x61C88647; UINT32 v0 = v[0], v1 = v[1]; for (int i = 0; i < 32; i++) { v0 += (v1 + (16 * v1 ^ (v1 >> 5))) ^ (sum + k[sum & 3]); sum -= delta; v1 += (v0 + (16 * v0 ^ (v0 >> 5))) ^ (sum + k[(sum >> 11) & 3]); } v[0] = v0; v[1] = v1; } int EterPackDecrypt(UINT32 *aRawData, UINT32 *vKey, UINT32 iSize) { if(aRawData == NULL || vKey == NULL || iSize == 0) return -1; if(iSize % 8) iSize = iSize - (iSize % 8); for(UINT32 i = 0; i < iSize / 8; i++) XTEA_DECRYPT(&aRawData[i * 2], vKey); return 0; } int EterPackEncrypt(UINT32 *aRawData, UINT32 *vKey, UINT32 iSize) { if(aRawData == NULL || vKey == NULL || iSize == 0) return -1; if(iSize % 8) iSize = iSize - (iSize % 8) + 8; for(UINT32 i = 0; i < iSize / 8; i++) XTEA_ENCRYPT(&aRawData[i * 2], vKey); return 0; } int EterPackCompress(UINT8 *pRawData, UINT32 iRawSize, UINT8 **pCompressedData, UINT32 *iCompressedSize) { if(pRawData == NULL || iRawSize == 0) return ETER_PACK_COMPRESS_EMPTY_DATA_ERROR; void *pWorkMemory = (lzo_voidp)calloc(LZO1X_999_MEM_COMPRESS, 1); *pCompressedData = (unsigned char *)calloc(COMP_BUF_CAL(iRawSize), 1); lzo_init(); lzo1x_999_compress(pRawData, iRawSize, *pCompressedData, (lzo_uint *)iCompressedSize, pWorkMemory); if(*iCompressedSize <= 0) return -2; if(*pCompressedData == NULL) return -3; if(pWorkMemory) free(pWorkMemory); return 0; }
26.985915
104
0.556367
christian-roggia
bd2ed96624bd9e1588fe04eb9c7b602a9ccd0eb4
1,260
hpp
C++
Source/TitaniumKit/examples/NativeTiExample.hpp
garymathews/titanium_mobile_windows
ff2a02d096984c6cad08f498e1227adf496f84df
[ "Apache-2.0" ]
20
2015-04-02T06:55:30.000Z
2022-03-29T04:27:30.000Z
Source/TitaniumKit/examples/NativeTiExample.hpp
garymathews/titanium_mobile_windows
ff2a02d096984c6cad08f498e1227adf496f84df
[ "Apache-2.0" ]
692
2015-04-01T21:05:49.000Z
2020-03-10T10:11:57.000Z
Source/TitaniumKit/examples/NativeTiExample.hpp
garymathews/titanium_mobile_windows
ff2a02d096984c6cad08f498e1227adf496f84df
[ "Apache-2.0" ]
22
2015-04-01T20:57:51.000Z
2022-01-18T17:33:15.000Z
/** * Copyright (c) 2014 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License. * Please see the LICENSE included with this distribution for details. */ #ifndef _TITANIUM_EXAMPLES_NATIVETIEXAMPLE_HPP_ #define _TITANIUM_EXAMPLES_NATIVETIEXAMPLE_HPP_ #include "Titanium/TiModule.hpp" using namespace HAL; /*! @class @discussion This is an example of how to implement Titanium::Titanium for a native Titanium. */ class NativeTiExample final : public Titanium::TiModule, public JSExport<NativeTiExample> { public: NativeTiExample(const JSContext&) TITANIUM_NOEXCEPT; virtual ~NativeTiExample() = default; NativeTiExample(const NativeTiExample&) = default; NativeTiExample& operator=(const NativeTiExample&) = default; #ifdef TITANIUM_MOVE_CTOR_AND_ASSIGN_DEFAULT_ENABLE NativeTiExample(NativeTiExample&&) = default; NativeTiExample& operator=(NativeTiExample&&) = default; #endif static void JSExportInitialize(); protected: virtual std::string version() const TITANIUM_NOEXCEPT override final; virtual std::string buildDate() const TITANIUM_NOEXCEPT override final; virtual std::string buildHash() const TITANIUM_NOEXCEPT override final; }; #endif // _TITANIUM_EXAMPLES_NATIVETIEXAMPLE_HPP_
30.731707
89
0.799206
garymathews
bd2f44c27af90404e4437989e2dba1e31e11aea0
495
cpp
C++
fms_sequence_equal.t.cpp
keithalewis/fms_sequence
f2afc2c302e7f9619bbdd22634428dcad92cb65b
[ "MIT" ]
null
null
null
fms_sequence_equal.t.cpp
keithalewis/fms_sequence
f2afc2c302e7f9619bbdd22634428dcad92cb65b
[ "MIT" ]
null
null
null
fms_sequence_equal.t.cpp
keithalewis/fms_sequence
f2afc2c302e7f9619bbdd22634428dcad92cb65b
[ "MIT" ]
null
null
null
// fms_sequence_equal.t.cpp - Test equality of sequences #include <cassert> #include "fms_sequence_equal.h" #include "fms_sequence_iota.h" #include "fms_sequence_pointer.h" #include "fms_sequence_take.h" using namespace fms::sequence; int test_sequence_equal() { { int s[] = { 1, 2, 3 }; pointer sp(3, s); assert(equal(sp, take(3, iota(1)))); assert(equal(take(0, sp), take(0, sp))); } return 0; } int test_sequence_equal_ = test_sequence_equal();
22.5
56
0.656566
keithalewis
bd33fe5aef4c7952f6cb109cb1bc7f5f0bf52751
513
hpp
C++
include/glCompact/AttributeLayout_.hpp
PixelOfDeath/glCompact
68334cc9c3aa20255e8986ad1ee5fa8e23df354d
[ "MIT" ]
null
null
null
include/glCompact/AttributeLayout_.hpp
PixelOfDeath/glCompact
68334cc9c3aa20255e8986ad1ee5fa8e23df354d
[ "MIT" ]
null
null
null
include/glCompact/AttributeLayout_.hpp
PixelOfDeath/glCompact
68334cc9c3aa20255e8986ad1ee5fa8e23df354d
[ "MIT" ]
null
null
null
#pragma once #include <glCompact/AttributeLayout.hpp> namespace glCompact { class AttributeLayout_ : public AttributeLayout { friend class PipelineRasterization; enum class GpuType : uint8_t { unused, f32, i32, //used for all integers and bool f64 }; GpuType gpuType[config::MAX_ATTRIBUTES] = {}; bool operator==(const AttributeLayout_& rhs) const; bool operator!=(const AttributeLayout_& rhs) const; }; }
25.65
59
0.614035
PixelOfDeath
bd35db98bb3868f5009ce9bd3770d7d994178824
3,383
cxx
C++
vigranumpy/src/core/eccentricity.cxx
ThomasWalter/vigra
e92c892aae38c3977dc3f6400f46377b0cb61799
[ "MIT" ]
null
null
null
vigranumpy/src/core/eccentricity.cxx
ThomasWalter/vigra
e92c892aae38c3977dc3f6400f46377b0cb61799
[ "MIT" ]
null
null
null
vigranumpy/src/core/eccentricity.cxx
ThomasWalter/vigra
e92c892aae38c3977dc3f6400f46377b0cb61799
[ "MIT" ]
null
null
null
#define PY_ARRAY_UNIQUE_SYMBOL vigranumpygraphs_PyArray_API #define NO_IMPORT_ARRAY /*boost python before anything else*/ #include <boost/python.hpp> #include <vigra/numpy_array.hxx> #include <vigra/numpy_array_converters.hxx> #include <vigra/eccentricitytransform.hxx> namespace python = boost::python; /* BROKEN! REFACTOR ME */ namespace vigra { template< int N, class T, class S > NumpyAnyArray pythonEccentricityTransformOnLabels( const NumpyArray< N, T > & src, NumpyArray< N, S > dest ){ dest.reshapeIfEmpty(src.taggedShape(), "eccentricityTransformOnLabels(): Output image has wrong dimensions"); eccentricityTransformOnLabels(src, dest); return dest; } template< int N, class T > NumpyAnyArray pythonEccentricityCenters( const NumpyArray< N, T > & src, NumpyArray< 2, MultiArrayIndex > centers ){ T maxLabel = *std::max_element(src.begin(), src.end()); centers.reshapeIfEmpty(Shape2(maxLabel, N), "eccentricityCenters(): Output has wrong dimensions"); eccentricityCenters(src, centers); return centers; } template< int N, class T, class S > python::tuple pythonEccentricityTransformWithCenters( const NumpyArray< N, T > & src, NumpyArray< N, S > dest, NumpyArray< 2, MultiArrayIndex > centers ){ dest.reshapeIfEmpty(src.taggedShape(), "eccentricityTransformWithCenters(): Output (dest) has wrong dimensions"); T maxLabel = *std::max_element(src.begin(), src.end()); centers.reshapeIfEmpty(Shape2(maxLabel, N), "eccentricityTransformWithCenters(): Output (centers) has wrong dimensions"); eccentricityTransformOnLabels(src, dest, centers); return python::make_tuple(dest, centers); } template< int N, class T, class S > void defineEcc() { python::def("_eccentricityTransform",registerConverters(&pythonEccentricityTransformOnLabels< N, T, S >), ( python::arg("labels"), python::arg("out")=python::object() ) ); } template< int N, class T > void defineCenters() { python::def("_eccentricityCenters",registerConverters(&pythonEccentricityCenters< N, T >), ( python::arg("labels"), python::arg("out")=python::object() ) ); } template< int N, class T, class S > void defineEccWithCenters() { python::def("_eccentricityTransformWithCenters",registerConverters(&pythonEccentricityTransformWithCenters<N, T, S >), ( python::arg("labels"), python::arg("ecc")=python::object(), python::arg("centers")=python::object() ) ); } void defineEccentricity() { defineEcc< 2, UInt32, float >(); defineEcc< 3, UInt32, float >(); defineCenters< 2, UInt32 >(); defineCenters< 3, UInt32 >(); defineEccWithCenters< 2, UInt32, float >(); defineEccWithCenters< 3, UInt32, float >(); } }
32.219048
126
0.571682
ThomasWalter
bd36889f2b15e64b3c62da7129b2cbdddbc88e03
3,268
cpp
C++
lib/util/src/Extension_Argv.cpp
ta0kira/zeolite
a81fdcd92c489fccbb3dd7b1c4dae50c00af6b96
[ "Apache-2.0" ]
15
2019-04-10T13:06:10.000Z
2021-11-12T14:11:30.000Z
lib/util/src/Extension_Argv.cpp
ta0kira/zeolite
a81fdcd92c489fccbb3dd7b1c4dae50c00af6b96
[ "Apache-2.0" ]
196
2020-01-24T14:09:31.000Z
2022-02-25T21:43:44.000Z
lib/util/src/Extension_Argv.cpp
ta0kira/zeolite
a81fdcd92c489fccbb3dd7b1c4dae50c00af6b96
[ "Apache-2.0" ]
null
null
null
/* ----------------------------------------------------------------------------- Copyright 2020-2021 Kevin P. Barry 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. ----------------------------------------------------------------------------- */ // Author: Kevin P. Barry [ta0kira@gmail.com] #include "category-source.hpp" #include "Streamlined_Argv.hpp" #include "Category_Formatted.hpp" #include "Category_String.hpp" #ifdef ZEOLITE_PUBLIC_NAMESPACE namespace ZEOLITE_PUBLIC_NAMESPACE { #endif // ZEOLITE_PUBLIC_NAMESPACE namespace { extern const BoxedValue Var_global; } // namespace struct ExtCategory_Argv : public Category_Argv { }; struct ExtType_Argv : public Type_Argv { inline ExtType_Argv(Category_Argv& p, Params<0>::Type params) : Type_Argv(p, params) {} ReturnTuple Call_global(const S<TypeInstance>& Param_self, const ParamTuple& params, const ValueTuple& args) final { TRACE_FUNCTION("Argv.global") return ReturnTuple(Var_global); } }; struct ExtValue_Argv : public Value_Argv { inline ExtValue_Argv(S<Type_Argv> p, int st, int sz) : Value_Argv(p), start(st), size(sz) {} ReturnTuple Call_readAt(const ParamTuple& params, const ValueTuple& args) final { TRACE_FUNCTION("Argv.readAt") const PrimInt Var_arg1 = (args.At(0)).AsInt(); return ReturnTuple(Box_String(Argv::GetArgAt(start + Var_arg1))); } ReturnTuple Call_size(const ParamTuple& params, const ValueTuple& args) final { TRACE_FUNCTION("Argv.size") return ReturnTuple(Box_Int(GetSize())); } ReturnTuple Call_subSequence(const ParamTuple& params, const ValueTuple& args) final { TRACE_FUNCTION("Argv.subSequence") const PrimInt Var_arg1 = (args.At(0)).AsInt(); const PrimInt Var_arg2 = (args.At(1)).AsInt(); if (Var_arg1 < 0 || (Var_arg1 > 0 && Var_arg1 >= GetSize())) { FAIL() << "index " << Var_arg1 << " is out of bounds"; } if (Var_arg2 < 0 || Var_arg1 + Var_arg2 > GetSize()) { FAIL() << "size " << Var_arg2 << " is invalid"; } return ReturnTuple(BoxedValue::New<ExtValue_Argv>(parent, start + Var_arg1, Var_arg2)); } inline int GetSize() const { return size < 0 ? Argv::ArgCount() : size; } const int start; const int size; }; namespace { const BoxedValue Var_global = BoxedValue::New<ExtValue_Argv>(CreateType_Argv(Params<0>::Type()), 0, -1); } // namespace Category_Argv& CreateCategory_Argv() { static auto& category = *new ExtCategory_Argv(); return category; } S<Type_Argv> CreateType_Argv(Params<0>::Type params) { static const auto cached = S_get(new ExtType_Argv(CreateCategory_Argv(), Params<0>::Type())); return cached; } #ifdef ZEOLITE_PUBLIC_NAMESPACE } // namespace ZEOLITE_PUBLIC_NAMESPACE using namespace ZEOLITE_PUBLIC_NAMESPACE; #endif // ZEOLITE_PUBLIC_NAMESPACE
34.041667
118
0.692166
ta0kira
bd3ed83cc5a0b41bc6924504580b0c69b076fabb
4,329
hpp
C++
Source/AllProjects/SecureUtils/CIDCrypto/CIDCrypto_SHA256.hpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
216
2019-03-09T06:41:28.000Z
2022-02-25T16:27:19.000Z
Source/AllProjects/SecureUtils/CIDCrypto/CIDCrypto_SHA256.hpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
9
2020-09-27T08:00:52.000Z
2021-07-02T14:27:31.000Z
Source/AllProjects/SecureUtils/CIDCrypto/CIDCrypto_SHA256.hpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
29
2019-03-09T10:12:24.000Z
2021-03-03T22:25:29.000Z
// // FILE NAME: CIDCrypto_SHA256.hpp // // AUTHOR: Dean Roddey // // CREATED: 12/19/2009 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2019 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This is the header for the CIDCrypto_SHA256.cpp file. This file implements // the SHA-1 message digest function. It returns an TSHA256Hash object that // holds a message hash for the data hashed. // // LOG: // // $_CIDLib_Log_$ // #pragma once #pragma CIDLIB_PACK(CIDLIBPACK) // --------------------------------------------------------------------------- // CLASS: TSHA256Hasher // PREFIX: mdig // --------------------------------------------------------------------------- class CIDCRYPTEXP TSHA256Hasher : public THashDigest { public : // ------------------------------------------------------------------- // Constructors and Destructor // ------------------------------------------------------------------- TSHA256Hasher(); TSHA256Hasher(const TSHA256Hasher&) = delete; ~TSHA256Hasher(); // ------------------------------------------------------------------- // Public operators // ------------------------------------------------------------------- TSHA256Hasher& operator=(const TSHA256Hasher&) = delete; // ------------------------------------------------------------------- // Public, inherited methods // ------------------------------------------------------------------- tCIDLib::TVoid Complete ( TMsgHash& mhashToFill ) override; tCIDLib::TVoid DigestRaw ( const tCIDLib::TCard1* const pc1ToDigest , const tCIDLib::TCard4 c4Bytes ) override; tCIDLib::TVoid DigestSrc ( TBinInStream& strmSrc , const tCIDLib::TCard4 c4Bytes ) override; tCIDLib::TVoid StartNew() override; private : // ------------------------------------------------------------------- // Private constants // ------------------------------------------------------------------- static constexpr tCIDLib::TCard4 c4BufCnt = 8; // ------------------------------------------------------------------- // Private, non-virtual methods // ------------------------------------------------------------------- tCIDLib::TVoid InitContext(); tCIDLib::TVoid PadMsg(); tCIDLib::TVoid ProcessMsgBlock ( const tCIDLib::TCard1* const pc1Block ); tCIDLib::TVoid ScrubContext(); // ------------------------------------------------------------------- // Private data members // // m_ac1Partial // A single block of input, which is twice the size of the hash. This is // used both as a temporary and it holds partial blocks across digest // calls so that we can pick up again where we left off. m_c4PartialCnt // indicates how many bytes are in here. // // m_ac4H // Storage for our digest buffers // // m_c4ByteCnt // The total count of input bytes so far added to the actual hash. Doesn't // include any partial block not yet added. // // m_c4PartialCnt // Used to track partial buffers so that we can pick up where we left // off next time, and to pad the final block if it is not complete. // ------------------------------------------------------------------- tCIDLib::TCard1 m_ac1Partial[kCIDCrypto::c4SHA256HashBytes * 2]; tCIDLib::TCard4 m_ac4H[c4BufCnt]; tCIDLib::TCard4 m_c4ByteCnt; tCIDLib::TCard4 m_c4PartialCnt; // ------------------------------------------------------------------- // Do any needed magic macros // ------------------------------------------------------------------- RTTIDefs(TSHA256Hasher,TObject) }; #pragma CIDLIB_POPPACK
32.30597
87
0.419496
MarkStega
bd427a1a90fc124044d6c35efec7a6d5416a4e20
805
cpp
C++
leetcode/roman-to-integer/main.cpp
Yash-Singh1/competitive-programming
3b9d278ed8138ab614e2a3d748627db8f4a2cdbd
[ "MIT" ]
null
null
null
leetcode/roman-to-integer/main.cpp
Yash-Singh1/competitive-programming
3b9d278ed8138ab614e2a3d748627db8f4a2cdbd
[ "MIT" ]
null
null
null
leetcode/roman-to-integer/main.cpp
Yash-Singh1/competitive-programming
3b9d278ed8138ab614e2a3d748627db8f4a2cdbd
[ "MIT" ]
null
null
null
class Solution { public: int romanToInt(string s) { int place{1}; reverse(s.begin(), s.end()); int val {0}; for (int i{0}; i < s.size(); ++i) { int shownPlace{1}; if (s[i] == 'M') { shownPlace = 1000; } else if (s[i] == 'D') { shownPlace = 500; } else if (s[i] == 'C') { shownPlace = 100; } else if (s[i] == 'L') { shownPlace = 50; } else if (s[i] == 'X') { shownPlace = 10; } else if (s[i] == 'V') { shownPlace = 5; } if (shownPlace < place) { val -= shownPlace; } else { val += shownPlace; place = shownPlace; } } return val; } };
25.15625
43
0.368944
Yash-Singh1
bd446ae6e5ee5210e9894da8821f10a8106bbb9b
423
cpp
C++
week6/w6d2/removeString.cpp
ash20012003/IPMPRepo
3d288e8ab1c1a25113c45e983da7f7e780ff66d4
[ "MIT" ]
2
2021-11-13T05:41:49.000Z
2022-02-06T16:12:56.000Z
week6/w6d2/removeString.cpp
ash20012003/IPMPRepo
3d288e8ab1c1a25113c45e983da7f7e780ff66d4
[ "MIT" ]
null
null
null
week6/w6d2/removeString.cpp
ash20012003/IPMPRepo
3d288e8ab1c1a25113c45e983da7f7e780ff66d4
[ "MIT" ]
null
null
null
class Solution { public: string removeChars(string string1, string string2) { // code here int flag = 0; string string3; for(int i=0;i<string1.size();i++){ flag = 0; for(int j=0;j<string2.size();j++){ if(string1[i] == string2[j]) flag = 1; } if(flag==0) string3+=string1[i]; } return string3; } };
24.882353
57
0.463357
ash20012003
bd47963431bdd10645f75ad56ef875d27e928666
1,000
cpp
C++
solver/src/solver/interface/Model.cpp
ferdinand-wood/kino_dynamic_opt
ba6bef170819c55d1d26e40af835a744d1ae663f
[ "BSD-3-Clause" ]
26
2019-11-18T17:39:43.000Z
2021-12-18T00:38:22.000Z
solver/src/solver/interface/Model.cpp
ferdinand-wood/kino_dynamic_opt
ba6bef170819c55d1d26e40af835a744d1ae663f
[ "BSD-3-Clause" ]
25
2019-11-11T19:54:51.000Z
2021-04-07T13:41:47.000Z
solver/src/solver/interface/Model.cpp
ferdinand-wood/kino_dynamic_opt
ba6bef170819c55d1d26e40af835a744d1ae663f
[ "BSD-3-Clause" ]
10
2019-12-15T14:36:51.000Z
2021-09-29T10:42:19.000Z
/** * @file Model.cpp * @author Brahayam Ponton (brahayam.ponton@tuebingen.mpg.de) * @license License BSD-3-Clause * @copyright Copyright (c) 2019, New York University and Max Planck Gesellschaft. * @date 2019-10-06 */ #include <iomanip> #include <iostream> #include <solver/interface/Model.hpp> namespace solver { ExitCode Model::optimize() { ExitCode exit_code = ExitCode::Indeterminate; if (this->getProblem().numBinaryVariables()>0 && (this->getProblem().numTrustRegions()>0 || this->getProblem().numSoftConstraints()>0)) { ncvx_bnb_solver_.initialize(this->getProblem()); exit_code = ncvx_bnb_solver_.optimize(); for (int var_id=0; var_id<(int)this->getProblem().problemVariables().size(); var_id++) this->getProblem().problemVariables()[var_id]->set(SolverDoubleParam_X, this->getProblem().getSolver().optimalVector().x()[var_id]); } else { exit_code = this->getProblem().optimize(); } return exit_code; } }
30.30303
142
0.677
ferdinand-wood
bd494540a54743e4b703bfba2f0ce9b138a16f79
202
cpp
C++
src/core/i_listen_child_death_component.cpp
MrPepperoni/Reaping2-1
4ffef3cca1145ddc06ca87d2968c7b0ffd3ba3fd
[ "MIT" ]
3
2015-02-22T20:34:28.000Z
2020-03-04T08:55:25.000Z
src/core/i_listen_child_death_component.cpp
MrPepperoni/Reaping2-1
4ffef3cca1145ddc06ca87d2968c7b0ffd3ba3fd
[ "MIT" ]
22
2015-12-13T16:29:40.000Z
2017-03-04T15:45:44.000Z
src/core/i_listen_child_death_component.cpp
Reaping2/Reaping2
0d4c988c99413e50cc474f6206cf64176eeec95d
[ "MIT" ]
14
2015-11-23T21:25:09.000Z
2020-07-17T17:03:23.000Z
#include "i_listen_child_death_component.h" #include <portable_iarchive.hpp> #include <portable_oarchive.hpp> REAPING2_CLASS_EXPORT_IMPLEMENT( IListenChildDeathComponent, IListenChildDeathComponent );
33.666667
90
0.866337
MrPepperoni
bd4c1fbe51a52d6f20a15fd402f70515471d6aa1
534
cpp
C++
src/main_cpu.cpp
aamatevosyan/ispras_cpp_cpu
6a7c828a355d3ab479bafcb5a60c955cb4250209
[ "MIT" ]
null
null
null
src/main_cpu.cpp
aamatevosyan/ispras_cpp_cpu
6a7c828a355d3ab479bafcb5a60c955cb4250209
[ "MIT" ]
null
null
null
src/main_cpu.cpp
aamatevosyan/ispras_cpp_cpu
6a7c828a355d3ab479bafcb5a60c955cb4250209
[ "MIT" ]
null
null
null
// // Created by armen on 1/26/21. // #include <iostream> #include "lib/cpu.h" static void showHelpMessage() { std::cout << "Usage: cpu [input]\n" "Runs binary code\n" "\n" "Example:\n" "\tcpu code.dasm\n"; } int main(int argc, char *argv[]) { if (argc != 2) { std::cerr << "Incorrect number of arguments.\n"; showHelpMessage(); return -1; } std::string inputFilePath(argv[1]); cpu cpu; cpu.execute(inputFilePath); return 0; }
17.225806
56
0.526217
aamatevosyan
bd53069a214545a71da0cca83d827ba16a3f03a6
917
cpp
C++
eigen_interface/eigen_lbl_driver.cpp
BenChung/nasoq
dcd38830f839941eec2688bdc8a35967d177c627
[ "MIT" ]
null
null
null
eigen_interface/eigen_lbl_driver.cpp
BenChung/nasoq
dcd38830f839941eec2688bdc8a35967d177c627
[ "MIT" ]
null
null
null
eigen_interface/eigen_lbl_driver.cpp
BenChung/nasoq
dcd38830f839941eec2688bdc8a35967d177c627
[ "MIT" ]
null
null
null
// // Created by kazem on 2020-05-18. // #include <unsupported/Eigen/SparseExtra> #include <Util.h> #include "lbl_eigen.h" using namespace nasoq; int main(int argc, const char *argv[]){ std::map<std::string,std::string> qp_args; parse_args(argc, argv, qp_args); /// Reading input matrices. Eigen::SparseMatrix<double,Eigen::ColMajor,int> H; Eigen::VectorXd q; std::string message = "Could not load "; if( !Eigen::loadMarket( H, qp_args["H"] ) ){ std::cout<<message<<"H"; return 1; } if( !Eigen::loadMarketVector( q, qp_args["q"] ) ){ std::cout<<message<<"q"; return 1; } // WARNINGL for now, if there is a zero diagonal in H, // the row/col indices of zero diagonal should be there. //TODO: getting more parameters here and replace qs /// output vectors Eigen::VectorXd x; /// call the wrapper. int ret = nasoq::linear_solve(H,q,x); //print_vec("sol:\n", 0, H.rows(), x.data()); return ret; }
26.970588
88
0.671756
BenChung
32e3c13c9c138af34e6857e801a739ec5482476e
399
cpp
C++
BrickEngine/src/BrickEngine/Renderer/Material.cpp
HomelikeBrick42/GameEngineTest1
3771c65fcd910d360e19b3820b5f4d758cb83997
[ "Apache-2.0" ]
null
null
null
BrickEngine/src/BrickEngine/Renderer/Material.cpp
HomelikeBrick42/GameEngineTest1
3771c65fcd910d360e19b3820b5f4d758cb83997
[ "Apache-2.0" ]
null
null
null
BrickEngine/src/BrickEngine/Renderer/Material.cpp
HomelikeBrick42/GameEngineTest1
3771c65fcd910d360e19b3820b5f4d758cb83997
[ "Apache-2.0" ]
null
null
null
#include "brickpch.hpp" #include "BrickEngine/Renderer/Material.hpp" namespace BrickEngine { void Material::Bind(uint32_t slot) { m_Shader->Bind(); m_Shader->SetFloat4("u_Color", m_Color); if (m_Texture) { m_Texture->Bind(slot); m_Shader->SetInt("u_Texture", slot); } } void Material::UnBind() { m_Shader->SetFloat4("u_Color", glm::vec4(1.0f)); m_Shader->UnBind(); } }
16.625
50
0.669173
HomelikeBrick42
32e6533de5b346bd81e03b49cd9b3eb218db796c
75,592
cpp
C++
Javelin/Tools/jasm/arm64/Encoder.cpp
jthlim/JavelinPattern
8add264f88ac620de109ddf797f7431779bbd9ea
[ "BSD-3-Clause" ]
10
2016-04-06T01:24:00.000Z
2021-11-16T10:16:51.000Z
Javelin/Tools/jasm/arm64/Encoder.cpp
jthlim/JavelinPattern
8add264f88ac620de109ddf797f7431779bbd9ea
[ "BSD-3-Clause" ]
1
2016-05-06T05:38:58.000Z
2016-05-09T16:42:43.000Z
Javelin/Tools/jasm/arm64/Encoder.cpp
jthlim/JavelinPattern
8add264f88ac620de109ddf797f7431779bbd9ea
[ "BSD-3-Clause" ]
null
null
null
//============================================================================ #include "Javelin/Tools/jasm/arm64/Encoder.h" #include "Javelin/Assembler/arm64/ActionType.h" #include "Javelin/Assembler/BitUtility.h" #include "Javelin/Tools/jasm/arm64/Action.h" #include "Javelin/Tools/jasm/arm64/Assembler.h" #include "Javelin/Tools/jasm/arm64/Register.h" #include "Javelin/Tools/jasm/AssemblerException.h" #include "Javelin/Tools/jasm/Log.h" #include <assert.h> #include <inttypes.h> #include <string.h> //============================================================================ using namespace Javelin::Assembler; using namespace Javelin::Assembler::arm64; using namespace Javelin::arm64Assembler; //============================================================================ static bool ImmsModifierDependendsOnImmr(int modifier) { switch(modifier) { case 4: case 5: case 6: return true; default: return false; } } static int ImmModifier(int modifier, int x, int immr, int imms) { switch(modifier) { case 0: return x; case 1: return x-1; case 2: return -x & 0x1f; case 3: return -x & 0x3f; case 4: return x + immr - 1; case 5: return 31 - immr; case 6: return 63 - immr; case 7: return 64 - x; default: assert(!"Internal error"); return x; } } static std::string ImmModifierExpression(int modifier, const ImmediateOperand *x, const ImmediateOperand *immr, const ImmediateOperand *imms, const Assembler &assembler) { switch(modifier) { case 0: assert(x->IsExpression()); return assembler.GetExpression(x->expressionIndex); case 1: assert(x->IsExpression()); return "(" + assembler.GetExpression(x->expressionIndex) + ")-1"; case 2: assert(x->IsExpression()); return "-(" + assembler.GetExpression(x->expressionIndex) + ") & 0x1f"; case 3: assert(x->IsExpression()); return "-(" + assembler.GetExpression(x->expressionIndex) + ") & 0x3f"; case 4: { std::string result; if(x->IsExpression()) result = "(" + assembler.GetExpression(x->expressionIndex) + ")"; else result = "(" + std::to_string(x->value) + ")"; if(immr->IsExpression()) result += "+(" + assembler.GetExpression(immr->expressionIndex) + ")"; else result += "+(" + std::to_string(immr->value) + ")"; result += "-1"; return result; } case 5: assert(immr->IsExpression()); return "31-(" + assembler.GetExpression(x->expressionIndex) + ")"; case 6: assert(immr->IsExpression()); return "63-(" + assembler.GetExpression(x->expressionIndex) + ")"; case 7: assert(x->IsExpression()); return "64-(" + assembler.GetExpression(x->expressionIndex) + ")"; default: assert(!"Internal error"); return ""; } } namespace Javelin::Assembler::arm64::Encoders { // Bits 0:3: modifier for imms // Bits 4:7: modifier for immr // // Modifiers: // f(0,x,immr,imms) = x # unchanged // f(1,x,immr,imms) = x-1 // f(2,x,immr,imms) = -x mod 32 // f(3,x,immr,imms) = -x mod 64 // f(4,x,immr,imms) = x+immr-1 // f(5,x,immr,imms) = 31-immr // f(6,x,immr,imms) = 63-immr // f(7,x,immr,imms) = 64-x static void RdRnImmrImms(Assembler &assembler, ListAction& listAction, const Instruction& instruction, const EncodingVariant &encodingVariant, const Operand *const *operands) { assert(operands[0] == nullptr || operands[0]->type == Operand::Type::Register); assert(operands[1] == nullptr || operands[1]->type == Operand::Type::Register); assert(operands[2] == nullptr || operands[2]->type == Operand::Type::Immediate); assert(operands[3] == nullptr || operands[3]->type == Operand::Type::Immediate); const RegisterOperand *rd = (const RegisterOperand*) operands[0]; const RegisterOperand *rn = (const RegisterOperand*) operands[1]; const ImmediateOperand *immr = (const ImmediateOperand*) operands[2]; const ImmediateOperand *imms = (const ImmediateOperand*) operands[3]; uint32_t opcode = encodingVariant.opcode; if(rd && !rd->IsExpression()) opcode |= rd->index; if(rn && !rn->IsExpression()) opcode |= rn->index << 5; int immr_value = immr ? int(immr->value) : 0; int imms_value = imms ? int(imms->value) : 0; if(immr && !immr->IsExpression()) { if(!(0 <= immr->value && immr->value < 64)) throw AssemblerException("immr value %" PRId64 " not in [0,63]", immr->value); int v = ImmModifier((encodingVariant.data >> 4) & 0xf, int(immr->value), immr_value, imms_value); opcode |= v << 16; } if(imms && !imms->IsExpression()) { if(!ImmsModifierDependendsOnImmr(encodingVariant.data & 0xf) || (!immr || !immr->IsExpression())) { if(!(0 <= imms->value && imms->value < 64)) throw AssemblerException("imms value %" PRId64 " not in [0,63]", imms->value);; int v = ImmModifier(encodingVariant.data & 0xf, int(imms->value), immr_value, imms_value); opcode |= v << 10; } } listAction.AppendOpcode(opcode); if(rd && rd->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 0, 0, rd->expressionIndex, assembler)); } if(rn && rn->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 5, 0, rn->expressionIndex, assembler)); } if(immr && immr->IsExpression()) { std::string expr = ImmModifierExpression((encodingVariant.data >> 4) & 0xf, immr, immr, imms, assembler); int expressionIndex = assembler.AddExpression(expr, 8, assembler.GetExpressionSourceLine(immr->expressionIndex), assembler.GetExpressionFileIndex(immr->expressionIndex)); listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 6, 16, 0, expressionIndex, assembler)); } if((imms && imms->IsExpression()) || (ImmsModifierDependendsOnImmr(encodingVariant.data & 0xf) && immr && immr->IsExpression())) { std::string expr = ImmModifierExpression(encodingVariant.data & 0xf, imms, immr, imms, assembler); int expressionIndex = assembler.AddExpression(expr, 8, assembler.GetExpressionSourceLine(imms->IsExpression() ? imms->expressionIndex : immr->expressionIndex), assembler.GetExpressionFileIndex(imms->IsExpression() ? imms->expressionIndex : immr->expressionIndex)); listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 6, 10, 0, expressionIndex, assembler)); } } static void LogicalImmediate(Assembler &assembler, ListAction& listAction, const Instruction& instruction, const EncodingVariant &encodingVariant, const Operand *const *operands) { assert(operands[0] == nullptr || operands[0]->type == Operand::Type::Register); assert(operands[1] == nullptr || operands[1]->type == Operand::Type::Register); assert(operands[2] == nullptr || operands[2]->type == Operand::Type::Immediate); const RegisterOperand *rd = (const RegisterOperand*) operands[0]; const RegisterOperand *rn = (const RegisterOperand*) operands[1]; const ImmediateOperand *imm = (const ImmediateOperand*) operands[2]; uint32_t opcode = encodingVariant.opcode; if(rd && !rd->IsExpression()) opcode |= rd->index; if(rn && !rn->IsExpression()) opcode |= rn->index << 5; if(imm && !imm->IsExpression()) { uint64_t value = imm->value; if(encodingVariant.data == 32) value |= value << 32; BitMaskEncodeResult result = EncodeBitMask(value); if(result.size == 0) throw AssemblerException("Unable to encode logical immediate %" PRId64, imm->value); opcode |= result.rotate << 16; if(result.size == 64) opcode |= 1 << 22; uint32_t imms = ((0x1e << __builtin_ctz(result.size)) + result.length - 1) & 0x3f; opcode |= imms << 10; } uint8_t opcodeBytes[4]; memcpy(opcodeBytes, &opcode, 4); listAction.Append(new LiteralAction({opcodeBytes, opcodeBytes+4})); if(rd && rd->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 0, 0, rd->expressionIndex, assembler)); } if(rn && rn->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 5, 0, rn->expressionIndex, assembler)); } if(imm && imm->IsExpression()) { listAction.Append(new PatchLogicalImmediateOpcodeAction(encodingVariant.data, imm->expressionIndex, assembler)); } } static void RtRnImm9(Assembler &assembler, ListAction& listAction, const Instruction& instruction, const EncodingVariant &encodingVariant, const Operand *const *operands) { assert(operands[0] == nullptr || operands[0]->type == Operand::Type::Register); assert(operands[1] == nullptr || operands[1]->type == Operand::Type::Register); assert(operands[2] == nullptr || operands[2]->type == Operand::Type::Immediate); const RegisterOperand *rt = (const RegisterOperand*) operands[0]; const RegisterOperand *rn = (const RegisterOperand*) operands[1]; const ImmediateOperand *imm = (const ImmediateOperand*) operands[2]; uint32_t opcode = encodingVariant.opcode; if(rt && !rt->IsExpression()) opcode |= rt->index; if(rn && !rn->IsExpression()) opcode |= rn->index << 5; if(imm && !imm->IsExpression()) { int offset = (int) imm->value; int scale = encodingVariant.data; if(offset % scale != 0) throw AssemblerException("Offset must be multiple of %d", scale); int32_t imm9Value = offset / scale; if((imm9Value >> 9) != 0 && (imm9Value >> 9) != -1) throw AssemblerException("Constant %d out of imm9 range", offset); imm9Value &= 0x1ff; opcode |= imm9Value << 12; } listAction.AppendOpcode(opcode); if(rt && rt->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 0, 0, rt->expressionIndex, assembler)); } if(rn && rn->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 5, 0, rn->expressionIndex, assembler)); } if(imm && imm->IsExpression()) { int valueShift = __builtin_ctz(encodingVariant.data); listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Signed, 9, 12, valueShift, imm->expressionIndex, assembler)); } } static void Rel26(Assembler &assembler, ListAction& listAction, const Instruction& instruction, const EncodingVariant &encodingVariant, const Operand *const *operands) { assert(operands[0]->type == Operand::Type::Label || (operands[0]->type == Operand::Type::Number && operands[0]->IsExpression())); uint32_t opcode = encodingVariant.opcode; switch(operands[0]->type) { case Operand::Type::Label: { const LabelOperand *label = (const LabelOperand*) operands[0]; int displacement = int32_t(label->displacement ? label->displacement->value : 0); int32_t rel = displacement / 4; opcode |= rel & 0x3ffffff; listAction.AppendOpcode(opcode); listAction.Append(label->CreatePatchAction(RelEncoding::Rel26, 4)); if(label->displacement && label->displacement->IsExpression()) { assert(!"Not implemented yet"); } } break; case Operand::Type::Number: { const ImmediateOperand* imm = (const ImmediateOperand*) operands[0]; listAction.AppendOpcode(opcode); listAction.Append(new PatchExpressionAction(RelEncoding::Rel26, 4, imm->expressionIndex, assembler)); } break; default: assert(!"Internal error"); break; } } static void RtRel19(Assembler &assembler, ListAction& listAction, const Instruction& instruction, const EncodingVariant &encodingVariant, const Operand *const *operands) { assert(operands[0] == nullptr || operands[0]->type == Operand::Type::Register); assert(operands[1]->type == Operand::Type::Label || (operands[1]->type == Operand::Type::Number && operands[1]->IsExpression())); const RegisterOperand *rt = (const RegisterOperand*) operands[0]; uint32_t opcode = encodingVariant.opcode; if(rt) opcode |= rt->index; switch(operands[1]->type) { case Operand::Type::Label: { const LabelOperand *label = (const LabelOperand*) operands[1]; int displacement = int32_t(label->displacement ? label->displacement->value : 0); int32_t rel = displacement / 4; opcode |= (rel << 5) & 0x7ffff; listAction.AppendOpcode(opcode); listAction.Append(label->CreatePatchAction(RelEncoding::Rel19Offset5, 4)); if(label->displacement && label->displacement->IsExpression()) { throw AssemblerException("Displacement expressions not implemented yet"); } } break; case Operand::Type::Number: { const ImmediateOperand* imm = (const ImmediateOperand*) operands[1]; listAction.AppendOpcode(opcode); listAction.Append(new PatchExpressionAction(RelEncoding::Rel19Offset5, 4, imm->expressionIndex, assembler)); } break; default: assert(!"Internal error"); break; } if(rt && rt->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 0, 0, rt->expressionIndex, assembler)); } } static void RtImmRel14(Assembler &assembler, ListAction& listAction, const Instruction& instruction, const EncodingVariant &encodingVariant, const Operand *const *operands) { assert(operands[0] == nullptr || operands[0]->type == Operand::Type::Register); assert(operands[1] == nullptr || operands[1]->type == Operand::Type::Immediate); assert(operands[2]->type == Operand::Type::Label || (operands[2]->type == Operand::Type::Number && operands[2]->IsExpression())); const RegisterOperand *rt = (const RegisterOperand*) operands[0]; const ImmediateOperand *imm = (const ImmediateOperand*) operands[1]; uint32_t opcode = encodingVariant.opcode; if(rt) opcode |= rt->index; if(imm && !imm->IsExpression()) { if(imm->value & 32) opcode |= 0x80000000; opcode |= (imm->value & 0x1f) << 19; } switch(operands[2]->type) { case Operand::Type::Label: { const LabelOperand *label = (const LabelOperand*) operands[2]; int displacement = int32_t(label->displacement ? label->displacement->value : 0); int32_t rel = displacement / 4; opcode |= (rel << 5) & 0x3fff; listAction.AppendOpcode(opcode); listAction.Append(label->CreatePatchAction(RelEncoding::Rel14Offset5, 4)); if(label->displacement && label->displacement->IsExpression()) { throw AssemblerException("Displacement expressions not implemented yet"); } } break; case Operand::Type::Number: { const ImmediateOperand* imm = (const ImmediateOperand*) operands[2]; listAction.AppendOpcode(opcode); listAction.Append(new PatchExpressionAction(RelEncoding::Rel14Offset5, 4, imm->expressionIndex, assembler)); } break; default: assert(!"Internal error"); break; } if(rt && rt->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 0, 0, rt->expressionIndex, assembler)); } if(imm && imm->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Masked, 5, 19, 0, imm->expressionIndex, assembler)); if(rt->matchBitfield & MatchReg64) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Masked, 1, 31, 5, imm->expressionIndex, assembler)); } } } /** * encodingVariant.Data * 0: ADR * 1: ADRP */ static void RdRel21HiLo(Assembler &assembler, ListAction& listAction, const Instruction& instruction, const EncodingVariant &encodingVariant, const Operand *const *operands) { assert(operands[0] == nullptr || operands[0]->type == Operand::Type::Register); assert(operands[1]->type == Operand::Type::Label || (operands[1]->type == Operand::Type::Number && operands[1]->IsExpression())); const RegisterOperand *rd = (const RegisterOperand*) operands[0]; uint32_t opcode = encodingVariant.opcode; if(rd) opcode |= rd->index; RelEncoding relEncoding = (encodingVariant.data == 1) ? RelEncoding::Adrp : RelEncoding::Rel21HiLo; switch(operands[1]->type) { case Operand::Type::Label: { const LabelOperand *label = (const LabelOperand*) operands[1]; int displacement = int32_t(label->displacement ? label->displacement->value : 0); int32_t rel = displacement; if(encodingVariant.data == 1) { if(rel != 0) { throw AssemblerException("ADRP does not support displacement offsets"); } } else { opcode |= (rel & 3) << 29; opcode |= (rel & 0x1ffffc) << 3; } listAction.AppendOpcode(opcode); listAction.Append(label->CreatePatchAction(relEncoding, 4)); if(label->displacement && label->displacement->IsExpression()) { throw AssemblerException("Displacement expressions not implemented yet"); } } break; case Operand::Type::Number: { const ImmediateOperand* imm = (const ImmediateOperand*) operands[1]; listAction.AppendOpcode(opcode); listAction.Append(new PatchExpressionAction(relEncoding, 4, imm->expressionIndex, assembler)); } break; default: assert(!"Internal error"); break; } if(rd && rd->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 0, 0, rd->expressionIndex, assembler)); } } static void RtRnUImm12(Assembler &assembler, ListAction& listAction, const Instruction& instruction, const EncodingVariant &encodingVariant, const Operand *const *operands) { assert(operands[0] == nullptr || operands[0]->type == Operand::Type::Register); assert(operands[1] == nullptr || operands[1]->type == Operand::Type::Register); assert(operands[2] == nullptr || operands[2]->type == Operand::Type::Immediate); const RegisterOperand *rt = (const RegisterOperand*) operands[0]; const RegisterOperand *rn = (const RegisterOperand*) operands[1]; const ImmediateOperand *imm = (const ImmediateOperand*) operands[2]; uint32_t opcode = encodingVariant.opcode; if(rt && !rt->IsExpression()) opcode |= rt->index; if(rn && !rn->IsExpression()) opcode |= rn->index << 5; if(imm && !imm->IsExpression()) { int offset = (int) imm->value; int scale = encodingVariant.data; if(offset % scale != 0) throw AssemblerException("Offset must be multiple of %d", scale); uint32_t uimm12Value = offset / scale; if((uimm12Value >> 12) != 0) throw AssemblerException("Constant %d out of uimm12 range", offset); uimm12Value &= 0xfff; opcode |= uimm12Value << 10; } listAction.AppendOpcode(opcode); if(rt && rt->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 0, 0, rt->expressionIndex, assembler)); } if(rn && rn->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 5, 0, rn->expressionIndex, assembler)); } if(imm && imm->IsExpression()) { int valueShift = __builtin_ctz(encodingVariant.data); listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 12, 10, valueShift, imm->expressionIndex, assembler)); } } static void RdRnRmImm6(Assembler &assembler, ListAction& listAction, const Instruction& instruction, const EncodingVariant &encodingVariant, const Operand *const *operands) { assert(operands[0] == nullptr || operands[0]->type == Operand::Type::Register); assert(operands[1] == nullptr || operands[1]->type == Operand::Type::Register); assert(operands[2] == nullptr || operands[2]->type == Operand::Type::Register); assert(operands[3] == nullptr || operands[3]->type == Operand::Type::Immediate); const RegisterOperand *rd = (const RegisterOperand*) operands[0]; const RegisterOperand *rn = (const RegisterOperand*) operands[1]; const RegisterOperand *rm = (const RegisterOperand*) operands[2]; const ImmediateOperand *imm = (const ImmediateOperand*) operands[3]; uint32_t opcode = encodingVariant.opcode; if(rd && !rd->IsExpression()) opcode |= rd->index; if(rn && !rn->IsExpression()) opcode |= rn->index << 5; if(rm && !rm->IsExpression()) opcode |= rm->index << 16; if(imm && !imm->IsExpression()) { assert(0 <= imm->value && imm->value < 64); opcode |= imm->value << 10; } listAction.AppendOpcode(opcode); if(rd && rd->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 0, 0, rd->expressionIndex, assembler)); } if(rn && rn->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 5, 0, rn->expressionIndex, assembler)); } if(rm && rm->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 16, 0, rm->expressionIndex, assembler)); } if(imm && imm->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 6, 10, 0, imm->expressionIndex, assembler)); } } static void RnImmNzcvCond(Assembler &assembler, ListAction& listAction, const Instruction& instruction, const EncodingVariant &encodingVariant, const Operand *const *operands) { assert(operands[0] == nullptr || operands[0]->type == Operand::Type::Register); assert(operands[1] == nullptr || operands[1]->type == Operand::Type::Immediate); assert(operands[2] == nullptr || operands[2]->type == Operand::Type::Immediate); assert(operands[3] == nullptr || operands[3]->type == Operand::Type::Condition); const RegisterOperand *rn = (const RegisterOperand*) operands[0]; const ImmediateOperand *imm = (const ImmediateOperand*) operands[1]; const ImmediateOperand *nzcv = (const ImmediateOperand*) operands[2]; const Operand *cond = operands[3]; uint32_t opcode = encodingVariant.opcode; if(rn && !rn->IsExpression()) opcode |= rn->index << 5; if(imm && !imm->IsExpression()) { assert(0 <= imm->value && imm->value < 32); opcode |= imm->value << 16; } if(nzcv && !nzcv->IsExpression()) { assert(0 <= nzcv->value && nzcv->value < 16); opcode |= nzcv->value; } if(cond) { assert(!cond->IsExpression()); int c = int(cond->condition); if(encodingVariant.data & 0x100) c ^= 1; opcode |= c << 12; } listAction.AppendOpcode(opcode); if(rn && rn->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 5, 0, rn->expressionIndex, assembler)); } if(imm && imm->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 16, 0, imm->expressionIndex, assembler)); } if(nzcv && nzcv->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 4, 0, 0, nzcv->expressionIndex, assembler)); } } /** * RegisterData is taken from Op7 * encodingVariant.data bits: * 8: Opcode[22:23] = (registerData >> 4) & 3 */ static void RnRmNzcvCond(Assembler &assembler, ListAction& listAction, const Instruction& instruction, const EncodingVariant &encodingVariant, const Operand *const *operands) { assert(operands[0] == nullptr || operands[0]->type == Operand::Type::Register); assert(operands[1] == nullptr || operands[1]->type == Operand::Type::Register); assert(operands[2] == nullptr || operands[2]->type == Operand::Type::Immediate); assert(operands[3] == nullptr || operands[3]->type == Operand::Type::Condition); const RegisterOperand *rn = (const RegisterOperand*) operands[0]; const RegisterOperand *rm = (const RegisterOperand*) operands[1]; const ImmediateOperand *nzcv = (const ImmediateOperand*) operands[2]; const Operand *cond = operands[3]; uint32_t opcode = encodingVariant.opcode; if(rn && !rn->IsExpression()) opcode |= rn->index << 5; if(rm && !rm->IsExpression()) opcode |= rm->index << 16; if(nzcv && !nzcv->IsExpression()) { assert(0 <= nzcv->value && nzcv->value < 16); opcode |= nzcv->value; } if(cond) { assert(!cond->IsExpression()); int c = int(cond->condition); if(encodingVariant.data & 0x100) c ^= 1; opcode |= c << 12; } const RegisterOperand *enc = (const RegisterOperand*) operands[7]; if(encodingVariant.data & 8) { assert(enc); opcode |= ((enc->registerData >> 4) & 3) << 22; } listAction.AppendOpcode(opcode); if(rn && rn->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 5, 0, rn->expressionIndex, assembler)); } if(rm && rm->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 16, 0, rm->expressionIndex, assembler)); } if(nzcv && nzcv->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 4, 0, 0, nzcv->expressionIndex, assembler)); } } static void RdRnRmCond(Assembler &assembler, ListAction& listAction, const Instruction& instruction, const EncodingVariant &encodingVariant, const Operand *const *operands) { assert(operands[0] == nullptr || operands[0]->type == Operand::Type::Register); assert(operands[1] == nullptr || operands[1]->type == Operand::Type::Register); assert(operands[2] == nullptr || operands[2]->type == Operand::Type::Register); assert(operands[3] == nullptr || operands[3]->type == Operand::Type::Condition); const RegisterOperand *rd = (const RegisterOperand*) operands[0]; const RegisterOperand *rn = (const RegisterOperand*) operands[1]; const RegisterOperand *rm = (const RegisterOperand*) operands[2]; const Operand *cond = operands[3]; uint32_t opcode = encodingVariant.opcode; if(rd && !rd->IsExpression()) opcode |= rd->index; if(rn && !rn->IsExpression()) opcode |= rn->index << 5; if(rm && !rm->IsExpression()) opcode |= rm->index << 16; if(cond) { assert(!cond->IsExpression()); int c = int(cond->condition); if(encodingVariant.data & 0x100) c ^= 1; opcode |= c << 12; } listAction.AppendOpcode(opcode); if(rd && rd->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 0, 0, rd->expressionIndex, assembler)); } if(rn && rn->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 5, 0, rn->expressionIndex, assembler)); } if(rm && rm->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 16, 0, rm->expressionIndex, assembler)); } } static void RdRnRmRa(Assembler &assembler, ListAction& listAction, const Instruction& instruction, const EncodingVariant &encodingVariant, const Operand *const *operands) { assert(operands[0] == nullptr || operands[0]->type == Operand::Type::Register); assert(operands[1] == nullptr || operands[1]->type == Operand::Type::Register); assert(operands[2] == nullptr || operands[2]->type == Operand::Type::Register); assert(operands[3] == nullptr || operands[3]->type == Operand::Type::Register); const RegisterOperand *rd = (const RegisterOperand*) operands[0]; const RegisterOperand *rn = (const RegisterOperand*) operands[1]; const RegisterOperand *rm = (const RegisterOperand*) operands[2]; const RegisterOperand *ra = (const RegisterOperand*) operands[3]; uint32_t opcode = encodingVariant.opcode; if(rd && !rd->IsExpression()) opcode |= rd->index; if(rn && !rn->IsExpression()) opcode |= rn->index << 5; if(rm && !rm->IsExpression()) opcode |= rm->index << 16; if(ra && !ra->IsExpression()) opcode |= ra->index << 10; listAction.AppendOpcode(opcode); if(rd && rd->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 0, 0, rd->expressionIndex, assembler)); } if(rn && rn->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 5, 0, rn->expressionIndex, assembler)); } if(rm && rm->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 16, 0, rm->expressionIndex, assembler)); } if(ra && ra->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 10, 0, ra->expressionIndex, assembler)); } } static void RdHwImm16(Assembler &assembler, ListAction& listAction, const Instruction& instruction, const EncodingVariant &encodingVariant, const Operand *const *operands) { assert(operands[0] == nullptr || operands[0]->type == Operand::Type::Register); assert(operands[1] && operands[1]->type == Operand::Type::Immediate); const RegisterOperand *rd = (const RegisterOperand*) operands[0]; const ImmediateOperand *imm = (const ImmediateOperand*) operands[1]; assert((imm->value & 0xffffffffffff0000) == 0 || (imm->value & 0xffffffff0000ffff) == 0 || (imm->value & 0xffff0000ffffffff) == 0 || (imm->value & 0x0000ffffffffffff) == 0); uint32_t opcode = encodingVariant.opcode; if(rd) opcode |= rd->index; uint64_t v = imm->value; uint8_t hw = 0; while((v >> 16) != 0) { ++hw; v >>= 16; } opcode |= v << 5; opcode |= hw << 21; listAction.AppendOpcode(opcode); if(rd && rd->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 0, 0, rd->expressionIndex, assembler)); } if(imm->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 16, 5, 0, imm->expressionIndex, assembler)); } } static void RdExpressionImm(Assembler &assembler, ListAction& listAction, const Instruction& instruction, const EncodingVariant &encodingVariant, const Operand *const *operands) { assert(operands[0]->type == Operand::Type::Register); assert(operands[1] && operands[1]->type == Operand::Type::Immediate && operands[1]->IsExpression()); const RegisterOperand *rd = (const RegisterOperand*) operands[0]; const ImmediateOperand *imm = (const ImmediateOperand*) operands[1]; assert(encodingVariant.data == 32 || encodingVariant.data == 64); listAction.Append(new MovExpressionImmediateAction(encodingVariant.data, rd->index, imm->expressionIndex, assembler)); if(rd->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 0, 0, rd->expressionIndex, assembler)); } } // operands[0] = destination // operands[1] = imm // operands[2] = shift static void RdImm16Shift(Assembler &assembler, ListAction& listAction, const Instruction& instruction, const EncodingVariant &encodingVariant, const Operand *const *operands) { assert(operands[0] == nullptr || operands[0]->type == Operand::Type::Register); assert(operands[1] == nullptr || operands[1]->type == Operand::Type::Immediate); assert(operands[2] == nullptr || operands[2]->type == Operand::Type::Immediate); const RegisterOperand *rd = (const RegisterOperand*) operands[0]; const ImmediateOperand *imm = (const ImmediateOperand*) operands[1]; const ImmediateOperand *shiftImm = (const ImmediateOperand*) operands[2]; uint32_t opcode = encodingVariant.opcode; if(rd) opcode |= rd->index; if(imm) opcode |= imm->value << 5; if(shiftImm) { switch(shiftImm->value) { case 0: break; case 16: opcode |= 1 << 21; break; case 32: opcode |= 2 << 21; break; case 48: opcode |= 3 << 21; break; default: throw AssemblerException("Invalid shift value : %" PRId64, shiftImm->value); } } listAction.AppendOpcode(opcode); if(rd && rd->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 0, 0, rd->expressionIndex, assembler)); } if(imm && imm->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 16, 5, 0, imm->expressionIndex, assembler)); } if(shiftImm && shiftImm->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 2, 21, 4, shiftImm->expressionIndex, assembler)); } } static void RdNot32HwImm16(Assembler &assembler, ListAction& listAction, const Instruction& instruction, const EncodingVariant &encodingVariant, const Operand *const *operands) { assert(operands[0] && operands[0]->type == Operand::Type::Register); assert(operands[1] && operands[1]->type == Operand::Type::Immediate); const RegisterOperand *rd = (const RegisterOperand*) operands[0]; const ImmediateOperand *imm = (const ImmediateOperand*) operands[1]; assert(int32_t(imm->value | 0xffff) == -1 || int32_t(imm->value | 0xffff0000) == -1); uint32_t opcode = encodingVariant.opcode; if(rd) opcode |= rd->index; if(imm->IsExpression()) { throw AssemblerException("Unsupported expression"); } uint32_t v = ~uint32_t(imm->value); uint8_t hw = 0; while((v >> 16) != 0) { ++hw; v >>= 16; } opcode |= v << 5; opcode |= hw << 21; listAction.AppendOpcode(opcode); if(rd && rd->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 0, 0, rd->expressionIndex, assembler)); } } static void RdNot64HwImm16(Assembler &assembler, ListAction& listAction, const Instruction& instruction, const EncodingVariant &encodingVariant, const Operand *const *operands) { assert(operands[0] && operands[0]->type == Operand::Type::Register); assert(operands[1] && operands[1]->type == Operand::Type::Immediate); const RegisterOperand *rd = (const RegisterOperand*) operands[0]; const ImmediateOperand *imm = (const ImmediateOperand*) operands[1]; assert((imm->value | 0xffff) == -1 || (imm->value | 0xffff0000) == -1 || (imm->value | 0xffff00000000) == -1 || (imm->value | 0xffff000000000000) == -1); uint32_t opcode = encodingVariant.opcode; if(rd) opcode |= rd->index; if(imm->IsExpression()) { throw AssemblerException("Unsupported expression"); } uint64_t v = ~imm->value; uint8_t hw = 0; while((v >> 16) != 0) { ++hw; v >>= 16; } opcode |= v << 5; opcode |= hw << 21; listAction.AppendOpcode(opcode); if(rd && rd->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 0, 0, rd->expressionIndex, assembler)); } } // operands[0] = load/store register // operands[1] = base register // operands[2] = offset register // operands[3] = extend // operands[4] = shift immediate static void LoadStoreOffsetRegister(Assembler &assembler, ListAction& listAction, const Instruction& instruction, const EncodingVariant &encodingVariant, const Operand *const *operands) { assert(operands[0]->type == Operand::Type::Register); assert(operands[1]->type == Operand::Type::Register); assert(operands[2]->type == Operand::Type::Register); assert(operands[3] == nullptr || operands[3]->type == Operand::Type::Extend || (operands[3]->type == Operand::Type::Shift && operands[3]->shift == Operand::Shift::LSL)); assert(operands[4] == nullptr || operands[4]->type == Operand::Type::Immediate); const RegisterOperand *rt = (const RegisterOperand*) operands[0]; const RegisterOperand *rn = (const RegisterOperand*) operands[1]; const RegisterOperand *rm = (const RegisterOperand*) operands[2]; const Operand *extend = operands[3]; const ImmediateOperand *imm = (const ImmediateOperand*) operands[4]; uint32_t opcode = encodingVariant.opcode; opcode |= rt->index; opcode |= rn->index << 5; opcode |= rm->index << 16; if(extend) { int option = 0; switch(extend->type) { case Operand::Type::Extend: option = (int) extend->extend; break; case Operand::Type::Shift: assert(extend->shift == Operand::Shift::LSL); option = 3; break; default: assert(!"Unknown extend command"); break; } opcode |= option << 13; if(imm) { if(imm->IsExpression()) { throw AssemblerException("Shift expression not permitted for LoadStore"); } int shift = 0; if(imm->value == encodingVariant.data) shift = 1; else if(imm->value == 0) shift = 0; else throw AssemblerException("Invalid shift %" PRId64 ". Must be 0 or %d", imm->value, encodingVariant.data); opcode |= shift << 12; } } listAction.AppendOpcode(opcode); if(rt->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 0, 0, rt->expressionIndex, assembler)); } if(rn->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 5, 0, rn->expressionIndex, assembler)); } if(rm->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 16, 0, rm->expressionIndex, assembler)); } } // operands[0] = load/store reg1 // operands[1] = load/store reg2 // operands[2] = base register // operands[3] = offset immediate static void LoadStorePair(Assembler &assembler, ListAction& listAction, const Instruction& instruction, const EncodingVariant &encodingVariant, const Operand *const *operands) { assert(operands[0]->type == Operand::Type::Register); assert(operands[1]->type == Operand::Type::Register); assert(operands[2]->type == Operand::Type::Register); assert(operands[3] == nullptr || operands[3]->type == Operand::Type::Immediate); const RegisterOperand *rt1 = (const RegisterOperand*) operands[0]; const RegisterOperand *rt2 = (const RegisterOperand*) operands[1]; const RegisterOperand *rn = (const RegisterOperand*) operands[2]; const ImmediateOperand *imm = (const ImmediateOperand*) operands[3]; uint32_t opcode = encodingVariant.opcode; opcode |= rt1->index; opcode |= rt2->index << 10; opcode |= rn->index << 5; if(imm) { assert(imm->value % encodingVariant.data == 0); int immValue = int(imm->value / encodingVariant.data); assert(BitUtility::IsValidSignedImmediate(immValue, 7)); immValue &= 0x7f; opcode |= immValue << 15; } listAction.AppendOpcode(opcode); if(rt1->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 0, 0, rt1->expressionIndex, assembler)); } if(rt2->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 10, 0, rt2->expressionIndex, assembler)); } if(rn && rn->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 5, 0, rn->expressionIndex, assembler)); } if(imm && imm->IsExpression()) { int valueShift = __builtin_ctz(encodingVariant.data); listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Signed, 7, 15, valueShift, imm->expressionIndex, assembler)); } } // operands[0] = destination // operands[1] = opA // operands[2] = opB // operands[3] = extend // operands[4] = shift immediate static void ArithmeticExtendedRegister(Assembler &assembler, ListAction& listAction, const Instruction& instruction, const EncodingVariant &encodingVariant, const Operand *const *operands) { assert(operands[0] == nullptr || operands[0]->type == Operand::Type::Register); assert(operands[1] == nullptr || operands[1]->type == Operand::Type::Register); assert(operands[2] == nullptr || operands[2]->type == Operand::Type::Register); assert(operands[3] == nullptr || operands[3]->type == Operand::Type::Extend || (operands[3]->type == Operand::Type::Shift && operands[3]->shift == Operand::Shift::LSL)); assert(operands[4] == nullptr || operands[4]->type == Operand::Type::Immediate); const RegisterOperand *rd = (const RegisterOperand*) operands[0]; const RegisterOperand *rn = (const RegisterOperand*) operands[1]; const RegisterOperand *rm = (const RegisterOperand*) operands[2]; const Operand *extend = operands[3]; const ImmediateOperand *imm = (const ImmediateOperand*) operands[4]; uint32_t opcode = encodingVariant.opcode; if(rd) opcode |= rd->index; if(rn) opcode |= rn->index << 5; if(rm) opcode |= rm->index << 16; if(extend) { int option = 0; switch(extend->type) { case Operand::Type::Extend: option = (int) extend->extend; break; case Operand::Type::Shift: assert(extend->shift == Operand::Shift::LSL); option = (encodingVariant.operandMatchMasks[0] & MatchReg32) ? 2 : 3; break; default: assert(!"Unknown extend command"); break; } opcode |= option << 13; if(imm) { assert(0 <= imm->value && imm->value <= 4); opcode |= imm->value << 10; } } listAction.AppendOpcode(opcode); if(rd && rd->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 0, 0, rd->expressionIndex, assembler)); } if(rn && rn->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 5, 0, rn->expressionIndex, assembler)); } if(rm && rm->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 16, 0, rm->expressionIndex, assembler)); } if(imm && imm->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 6, 10, 0, imm->expressionIndex, assembler)); } } // operands[0] = destination // operands[1] = opA // operands[2] = immediate // operands[3] = shift immediate static void ArithmeticImmediate(Assembler &assembler, ListAction& listAction, const Instruction& instruction, const EncodingVariant &encodingVariant, const Operand *const *operands) { assert(operands[0] == nullptr || operands[0]->type == Operand::Type::Register); assert(operands[1] == nullptr || operands[1]->type == Operand::Type::Register); assert(operands[2]->type == Operand::Type::Immediate); assert(operands[3] == nullptr || operands[3]->type == Operand::Type::Immediate); const RegisterOperand *rd = (const RegisterOperand*) operands[0]; const RegisterOperand *rn = (const RegisterOperand*) operands[1]; const ImmediateOperand *imm = (const ImmediateOperand*) operands[2]; const ImmediateOperand *shiftImm = (const ImmediateOperand*) operands[3]; uint32_t opcode = encodingVariant.opcode; if(rd) opcode |= rd->index; if(rn) opcode |= rn->index << 5; if((imm->value & ~0xfff000ull) != 0 && (imm->value & ~0xfffull) != 0) { throw AssemblerException("Value %" PRId64 " not permissible for instruction", imm->value); } if((imm->value >> 12) != 0) { opcode |= imm->value >> 2; opcode |= (1 << 22); } else { opcode |= imm->value << 10; } if(shiftImm) { if(shiftImm->IsExpression()) { throw AssemblerException("Shift expressions not supported"); } if(shiftImm->value != 0 && shiftImm->value != 12) { throw AssemblerException("Shift (%" PRId64 ") must be #0 or #12", shiftImm->value); } if(shiftImm->value == 12) opcode |= 1 << 22; } listAction.AppendOpcode(opcode); if(rd && rd->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 0, 0, rd->expressionIndex, assembler)); } if(rn && rn->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 5, 0, rn->expressionIndex, assembler)); } if(imm && imm->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 12, 10, 0, imm->expressionIndex, assembler)); } } // operands[0] = destination // operands[1] = opA // operands[2] = opB // operands[3] = shift // operands[4] = immediate static void ArithmeticShiftedRegister(Assembler &assembler, ListAction& listAction, const Instruction& instruction, const EncodingVariant &encodingVariant, const Operand *const *operands) { assert(operands[0] == nullptr || operands[0]->type == Operand::Type::Register); assert(operands[1] == nullptr || operands[1]->type == Operand::Type::Register); assert(operands[2] == nullptr || operands[2]->type == Operand::Type::Register); assert(operands[3] == nullptr || operands[3]->type == Operand::Type::Shift); assert(operands[4] == nullptr || operands[4]->type == Operand::Type::Immediate); const RegisterOperand *rd = (const RegisterOperand*) operands[0]; const RegisterOperand *rn = (const RegisterOperand*) operands[1]; const RegisterOperand *rm = (const RegisterOperand*) operands[2]; const Operand *shift = operands[3]; const ImmediateOperand *imm = (const ImmediateOperand*) operands[4]; uint32_t opcode = encodingVariant.opcode; if(rd) opcode |= rd->index; if(rn) opcode |= rn->index << 5; if(rm) opcode |= rm->index << 16; if(shift) { int option = (int) shift->shift; opcode |= option << 22; if(imm) { if(0 <= imm->value && imm->value <= 63) { opcode |= imm->value << 10; } else { throw AssemblerException("Invalid shift value: %" PRId64, imm->value); } } } listAction.AppendOpcode(opcode); if(rd && rd->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 0, 0, rd->expressionIndex, assembler)); } if(rn && rn->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 5, 0, rn->expressionIndex, assembler)); } if(rm && rm->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 16, 0, rm->expressionIndex, assembler)); } if(imm && imm->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 6, 10, 0, imm->expressionIndex, assembler)); } } /** * RegisterData is taken from Op7 * encodingVariant.data bits: * 1: Opcode[23:22] = registerData & 3 * 2: Opcode[30] = (registerData & 4) != 0 * 4: Opcode[22] = (registerData >> 4) & 1 * 8: Opcode[23:22] = (registerData >> 4) & 3 * 0x10: Opcode[11:10] = registerData & 3 * 0x20: Immediate must be count << (registerData & 3). For LD#R instructions * 0x40: Opcode[30, 15:14, 12:10] encoded as required for LD/STn (single structure) * 0x80: Immediate must be n * registerSize. For LD#R instructions * 0x100: Immediate is encoded in Opcode[14:11], used for EXT instruction * 0x200: Immediate is used to encode Opcode[22:16], used for right shift instructions (SRSHR, SRSRA, SSHR, etc) * 0x400: Immediate is used to encode Opcode[22:16], used for left shift instructions (SHL, SHLL, SSHL, etc) * 0x800: Rm is verified to be 0..15, and index is encoded in Opcode[11,21:20] * 0x1000: Immediate is encoded in Opcode[15:10] as 64-imm. Used for SCVTF, UCVTF */ static void FpRdRnRmRa(Assembler &assembler, ListAction& listAction, const Instruction& instruction, const EncodingVariant &encodingVariant, const Operand *const *operands) { assert(operands[0] == nullptr || operands[0]->type == Operand::Type::Register); assert(operands[1] == nullptr || operands[1]->type == Operand::Type::Register); assert(operands[2] == nullptr || operands[2]->type == Operand::Type::Register); assert(operands[3] == nullptr || operands[3]->type == Operand::Type::Register); assert(operands[4] == nullptr || operands[4]->type == Operand::Type::Immediate || operands[4]->type == Operand::Type::Number); assert(operands[5] == nullptr || operands[5]->type == Operand::Type::Number); const RegisterOperand *rd = (const RegisterOperand*) operands[0]; const RegisterOperand *rn = (const RegisterOperand*) operands[1]; const RegisterOperand *rm = (const RegisterOperand*) operands[2]; const RegisterOperand *ra = (const RegisterOperand*) operands[3]; const ImmediateOperand *imm = (const ImmediateOperand*) operands[4]; const ImmediateOperand *index = (const ImmediateOperand*) operands[5]; uint32_t opcode = encodingVariant.opcode; const RegisterOperand *enc = (const RegisterOperand*) operands[7]; if(encodingVariant.data & 1) { assert(enc); opcode |= ((enc->registerData & 3) << 22); } if(encodingVariant.data & 2) { assert(enc); opcode |= (enc->registerData & 4) << 28; } if(encodingVariant.data & 4) { assert(enc); opcode |= ((enc->registerData >> 4) & 1) << 22; } if(encodingVariant.data & 8) { assert(enc); opcode |= ((enc->registerData >> 4) & 3) << 22; } if(encodingVariant.data & 0x10) { assert(enc); opcode |= ((enc->registerData & 3) << 10); } if(encodingVariant.data & 0x20) { assert(enc); if(!imm) throw AssemblerException("Internal error: Immediate expected for encodingVariant.data & 0x20"); if(imm->IsExpression()) throw AssemblerException("Expressions not available for fixed-immediate post indexing"); int count = encodingVariant.GetNP1Count() + 1; int validImmediate = count << (enc->registerData & 3); if(imm->value != validImmediate) throw AssemblerException("Specified post index %" PRId64 " cannot be encoded. Must be %d.", imm->value, validImmediate); opcode |= 0x1f0000; } if(encodingVariant.data & 0x40) { assert(enc); if(!index) throw AssemblerException("Internal error: Index expected for encodingVariant.data & 0x40"); int registerSize = (enc->registerData & 3); // 0 = B, 1 = H, 2 = S, 3 = D switch(registerSize) { case 0: break; case 1: opcode |= 0x4000; break; case 2: opcode |= 0x8000; break; case 3: opcode |= 0x8400; break; } int i = int(index->value) << registerSize; if(i >= 16) throw AssemblerException("Index %" PRId64 " out of range", index->value); if(i & 8) opcode |= 1 << 30; opcode |= (i & 7) << 10; } if(encodingVariant.data & 0x80) { assert(enc); if(!imm) throw AssemblerException("Internal error: Immediate expected for encodingVariant.data & 0x80"); if(imm->IsExpression()) throw AssemblerException("Expressions not available for fixed-immediate post indexing"); int count = encodingVariant.GetNP1Count() + 1; int registerSize = (enc->registerData & 4) ? 16 : 8; int validImmediate = count * registerSize; if(imm->value != validImmediate) throw AssemblerException("Specified post index %" PRId64 " cannot be encoded. Must be %d.", imm->value, validImmediate); opcode |= 0x1f0000; } if(encodingVariant.data & 0x100) { assert(enc); int Q = (enc->registerData >> 2) & 1; if(!imm) throw AssemblerException("Internal error: Immediate expected for encodingVariant.data & 0x100"); if(imm->value < 1 || imm->value > 8*Q + 7) throw AssemblerException("Shift %" PRId64 " out of range 1..%d", imm->value, 8*Q + 7); opcode |= imm->value << 11; } if(encodingVariant.data & 0x200) { assert(enc); int size = enc->registerData & 3; if(!imm) throw AssemblerException("Internal error: Immediate expected for encodingVariant.data & 0x200"); if(imm->value < 0 || imm->value >= (8 << size)) throw AssemblerException("Index %" PRId64 " out of range 0..%d", imm->value, (8 << size) - 1); opcode |= ((16 << size) - imm->value) << 16; } if(encodingVariant.data & 0x400) { assert(enc); int size = enc->registerData & 3; if(!imm) throw AssemblerException("Internal error: Immediate expected for encodingVariant.data & 0x400"); if(imm->value < 0 || imm->value >= (8 << size)) throw AssemblerException("Index %" PRId64 " out of range 0..%d", imm->value, (8 << size) - 1); opcode |= ((8 << size) + imm->value) << 16; } if(encodingVariant.data & 0x800) { assert(enc); if(rm && rm->index > 15) throw AssemblerException("Element vector must be in range 0..15"); int registerSize = (enc->registerData & 3); // 0 = B, 1 = H, 2 = S, 3 = D assert(registerSize != 0); int i = int(index->value) << (registerSize-1); if(i >= 16) throw AssemblerException("Index %" PRId64 " out of range", index->value); opcode |= (i & 4) << 9; opcode |= (i & 3) << 20; } if(encodingVariant.data & 0x1000) { if(!imm) throw AssemblerException("Internal error: Immediate expected for encodingVariant.data & 0x1000"); if(imm->value < 1 || imm->value > 64) throw AssemblerException("Fixed point %" PRId64 " out of range 1..64", imm->value); opcode |= (64 - imm->value) << 10; } if(rd && !rd->IsExpression()) opcode |= rd->index; if(rn && !rn->IsExpression()) opcode |= rn->index << 5; if(rm && !rm->IsExpression()) opcode |= rm->index << 16; if(ra && !ra->IsExpression()) opcode |= rm->index << 10; listAction.AppendOpcode(opcode); if(rd && rd->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 0, 0, rd->expressionIndex, assembler)); } if(rn && rn->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 5, 0, rn->expressionIndex, assembler)); } if(rm && rm->IsExpression()) { if(encodingVariant.data & 0x800) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 4, 16, 0, rm->expressionIndex, assembler)); } else { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 16, 0, rm->expressionIndex, assembler)); } } if(ra && ra->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 10, 0, rm->expressionIndex, assembler)); } if(imm && imm->IsExpression()) { if(encodingVariant.data & 0x100) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 4, 1, 0, imm->expressionIndex, assembler)); } if(encodingVariant.data & 0x200) { throw AssemblerException("Dynamic encoding of vector shift immediate not supported"); } if(encodingVariant.data & 0x400) { throw AssemblerException("Dynamic encoding of vector shift immediate not supported"); } if(encodingVariant.data & 0x1000) { throw AssemblerException("Dynamic encoding of fixed point bits not supported"); } } if(index && index->IsExpression()) { if(encodingVariant.data & 0x40) { int registerSize = (enc->registerData & 3); // 0 = B, 1 = H, 2 = S, 3 = D int extraShift = registerSize; if(extraShift < 3) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Masked, 3-extraShift, 10+extraShift, 0, index->expressionIndex, assembler)); } listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Masked, 1, 30, 3-extraShift, index->expressionIndex, assembler)); } if(encodingVariant.data & 0x800) { int registerSize = (enc->registerData & 3); // 0 = B, 1 = H, 2 = S, 3 = D int extraShift = registerSize-1; if(extraShift < 2) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Masked, 2-extraShift, 20+extraShift, 0, index->expressionIndex, assembler)); } listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Masked, 1, 11, 2-extraShift, index->expressionIndex, assembler)); } } } /** * encodingVariant.data bits: * 1: Shift is encoded in immh:immb * 2: Shift is encoded in scale * 4: Opcode[30] = (rn->registerData & 4) != 0 * 8: Opcode[23:22] = = (rn->registerData >> 4) * 0x10: Opcode[31] = rd->matchBitfield & MatchReg64 */ static void FpRdRnFixedPointShift(Assembler &assembler, ListAction& listAction, const Instruction& instruction, const EncodingVariant &encodingVariant, const Operand *const *operands) { assert(operands[0] && operands[0]->type == Operand::Type::Register); assert(operands[1] && operands[1]->type == Operand::Type::Register); assert(operands[2] && operands[2]->type == Operand::Type::Immediate); const RegisterOperand *rd = (const RegisterOperand*) operands[0]; const RegisterOperand *rn = (const RegisterOperand*) operands[1]; const ImmediateOperand *imm = (const ImmediateOperand*) operands[2]; uint32_t opcode = encodingVariant.opcode; if(encodingVariant.data & 1) { opcode |= (rn->registerData & 4) << 28; } opcode |= rd->index; opcode |= rn->index << 5; if(encodingVariant.data & 1) { // fpSize: 0 = 16 bit, 1 = 32 bit, 2 = 64 bit int fpSize = (rn->registerData & 3) - 1; // Sets operand width bit. opcode |= (1 << 20) << fpSize; if(!imm->IsExpression()) { int maxShift = 16 << ((rn->registerData >> 4) & 3); if(imm->value <= 0 || imm->value > maxShift) throw AssemblerException("Fixed point shift must be between #1 and #%d", maxShift); int mask = (16 << fpSize) - 1; int immValue = (uint32_t) (-imm->value & mask); opcode |= immValue << 16; } } if(encodingVariant.data & 2) { if(!imm->IsExpression()) { int immValue = int(64 - imm->value); opcode |= immValue << 10; } } if(encodingVariant.data & 4) { // Opcode[30] = (rn->registerData & 4) != 0 opcode |= (rn->registerData & 4) << 28; } if(encodingVariant.data & 8) { int fpType = (rn->registerData >> 4) & 3; opcode |= fpType << 22; } if(encodingVariant.data & 0x10) { if(rd->matchBitfield & MatchReg64) { opcode |= 0x80000000; } } listAction.AppendOpcode(opcode); if(rd->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 0, 0, rd->expressionIndex, assembler)); } if(rn->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 5, 0, rn->expressionIndex, assembler)); } if(imm->IsExpression()) { if(encodingVariant.data & 1) { // fpSize: 0 = 16 bit, 1 = 32 bit, 2 = 64 bit int fpSize = (rn->registerData & 3) - 1; char buffer[16]; sprintf(buffer, "%d-(", 16 << fpSize); std::string expr = buffer + assembler.GetExpression(imm->expressionIndex) + ")"; int expressionIndex = assembler.AddExpression(expr, 8, assembler.GetExpressionSourceLine(imm->expressionIndex), assembler.GetExpressionFileIndex(imm->expressionIndex)); listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 4+fpSize, 16, 0, expressionIndex, assembler)); } if(encodingVariant.data & 2) { std::string expr = "64-(" + assembler.GetExpression(imm->expressionIndex) + ")"; int expressionIndex = assembler.AddExpression(expr, 8, assembler.GetExpressionSourceLine(imm->expressionIndex), assembler.GetExpressionFileIndex(imm->expressionIndex)); listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 6, 10, 0, expressionIndex, assembler)); } } } static void FpRdRnIndex1Index2(Assembler &assembler, ListAction& listAction, const Instruction& instruction, const EncodingVariant &encodingVariant, const Operand *const *operands) { assert(operands[0] == nullptr || operands[0]->type == Operand::Type::Register); assert(operands[1] == nullptr || operands[1]->type == Operand::Type::Register); assert(operands[2] == nullptr || operands[2]->type == Operand::Type::Number); assert(operands[3] == nullptr || operands[3]->type == Operand::Type::Number); const RegisterOperand *rd = (const RegisterOperand*) operands[0]; const RegisterOperand *rn = (const RegisterOperand*) operands[1]; const ImmediateOperand *index1 = (const ImmediateOperand*) operands[2]; const ImmediateOperand *index2 = (const ImmediateOperand*) operands[3]; uint32_t opcode = encodingVariant.opcode; const RegisterOperand *enc = (const RegisterOperand*) operands[7]; assert(enc); if(encodingVariant.data & 2) opcode |= (enc->registerData & 4) << 28; int size = enc->registerData & 3; if(!index1) throw AssemblerException("Internal error: Immediate expected for encodingVariant.data & 0x200"); if(index1->value < 0 || index1->value > (15 >> size)) throw AssemblerException("Index %" PRId64 " out of range 0..%d", index1->value, 15 >> size); opcode |= ((2*index1->value + 1) << size) << 16; if(index2) { int i2 = int(index2->value << size); if(i2 < 0 || i2 > 15) throw AssemblerException("Index %" PRId64 " out of range 0..%d", index2->value, 15 >> size); opcode |= i2 << 11; } if(rd && !rd->IsExpression()) opcode |= rd->index; if(rn && !rn->IsExpression()) opcode |= rn->index << 5; listAction.AppendOpcode(opcode); if(rd && rd->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 0, 0, rd->expressionIndex, assembler)); } if(rn && rn->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 5, 0, rn->expressionIndex, assembler)); } if(index1 && index1->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5-size, 17+size, 0, index1->expressionIndex, assembler)); } if(index2 && index2->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 4-size, 11+size, 0, index2->expressionIndex, assembler)); } } static uint8_t EncodeFloat(const ImmediateOperand *imm) { long double ld = (imm->immediateType == ImmediateOperand::ImmediateType::Integer) ? (long double) imm->value : imm->realValue; double d = ld; static_assert(sizeof(d) == 8, "Expect double to be 4 bytes"); uint64_t u; memcpy(&u, &d, 8); uint8_t result = 0; if(u & 0x8000000000000000) result |= 0x80; int64_t exp = (u >> 52) & 0x7ff; int64_t unbiasedExp = exp - 1023; if(unbiasedExp <= -4 || unbiasedExp > 4) throw AssemblerException("Cannot encode %f accurately (exponent %d out of range)", d, (int) unbiasedExp); result |= (exp & 7) << 4; uint64_t frac = u & 0xfffffffffffff; if(frac & 0xffffffffffff) throw AssemblerException("Cannot encode %f accurately (fraction bits truncated)", d); result |= frac >> 48; return result; } /** * RegisterData is taken from Op7 * RegisterData2 is taken from Op6 * encodingVariant.data bits: * 1: Opcode[23:22] = registerData & 3 * 2: Opcode[30] = (registerData & 4) != 0 * 4: Opcode[29] = (registerData >> 4) & 1 * 8: Opcode[31] = (registerData2.matchBitField & MatchReg64) != 0 * 0x10: Opcode[20:13] = EncodeFloat(imm->value) * 0x20: Opcode[18:16, 9:5] = EncodeFloat(imm->value) * 0x40: Opcode[19] = index */ static void Fmov(Assembler &assembler, ListAction& listAction, const Instruction& instruction, const EncodingVariant &encodingVariant, const Operand *const *operands) { assert(operands[0] == nullptr || operands[0]->type == Operand::Type::Register); assert(operands[1] == nullptr || operands[1]->type == Operand::Type::Immediate); assert(operands[2] == nullptr || operands[2]->type == Operand::Type::Register); assert(operands[3] == nullptr || operands[3]->type == Operand::Type::Number); const RegisterOperand *rd = (const RegisterOperand*) operands[0]; const ImmediateOperand *imm = (const ImmediateOperand*) operands[1]; const RegisterOperand *rn = (const RegisterOperand*) operands[2]; const ImmediateOperand *index = (const ImmediateOperand*) operands[3]; uint32_t opcode = encodingVariant.opcode; const RegisterOperand *enc = (const RegisterOperand*) operands[7]; const RegisterOperand *enc2 = (const RegisterOperand*) operands[6]; if(encodingVariant.data & 1) { assert(enc); opcode |= ((enc->registerData >> 4) & 3) << 22; } if(encodingVariant.data & 2) { assert(enc); opcode |= (enc->registerData & 4) << 28; } if(encodingVariant.data & 4) { assert(enc); opcode |= ((enc->registerData >> 4) & 1) << 29; } if(encodingVariant.data & 8) { assert(enc2); if(enc2->matchBitfield & MatchReg64) opcode |= 0x80000000; } if(encodingVariant.data & 0x10) { opcode |= EncodeFloat(imm) << 13; } if(encodingVariant.data & 0x20) { uint8_t f = EncodeFloat(imm); opcode |= (f & 0x1f) << 5; opcode |= (f & 0xe0) << 11; } if(encodingVariant.data & 0x40) { assert(index); if(index->value != 1) throw AssemblerException("Index %" PRId64 " must be 1", index->value); opcode |= 1 << 19; } if(rd && !rd->IsExpression()) opcode |= rd->index; if(rn && !rn->IsExpression()) opcode |= rn->index << 5; listAction.AppendOpcode(opcode); if(rd && rd->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 0, 0, rd->expressionIndex, assembler)); } if(imm && imm->IsExpression()) { throw AssemblerException("Floating point constants not yet supported"); } if(rn && rn->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 5, 0, rn->expressionIndex, assembler)); } } // Label, Number and immediate expressions supported // encodingValue.data & 0xff = lowest bit of opcode // encodingValue.data & 0xff00 = number of bits of opcode. static void RdRnImmSubfield(Assembler &assembler, ListAction& listAction, const Instruction& instruction, const EncodingVariant &encodingVariant, const Operand *const *operands) { assert(operands[0] == nullptr || operands[0]->type == Operand::Type::Register); assert(operands[1] == nullptr || operands[1]->type == Operand::Type::Register); assert(operands[2]->type == Operand::Type::Label || (operands[2]->type == Operand::Type::Number && operands[2]->IsExpression()) || (operands[2]->type == Operand::Type::Immediate && operands[2]->IsExpression())); assert(operands[3] != nullptr && operands[3]->type == Operand::Type::Number); assert(operands[4] != nullptr && operands[4]->type == Operand::Type::Number); assert(operands[5] == nullptr || operands[5]->type == Operand::Type::Immediate); const RegisterOperand *rd = (const RegisterOperand*) operands[0]; const RegisterOperand *rn = (const RegisterOperand*) operands[1]; const Operand *target = operands[2]; const ImmediateOperand *highBitIndex = (const ImmediateOperand*) operands[3]; const ImmediateOperand *lowBitIndex = (const ImmediateOperand*) operands[4]; const ImmediateOperand *hwShift = (const ImmediateOperand*) operands[5]; uint32_t opcode = encodingVariant.opcode; if(rd) opcode |= rd->index; if(rn) opcode |= rn->index << 5; if(hwShift) { if(hwShift->IsExpression()) throw AssemblerException("Shift expression not supported"); switch(hwShift->value) { case 0: case 16: case 32: case 48: opcode |= (hwShift->value / 16) << 21; break; default: throw AssemblerException("Invalid shift value (%" PRId64 ")", hwShift->value); } } switch(target->type) { case Operand::Type::Label: { const LabelOperand *label = (const LabelOperand*) target; int displacement = int32_t(label->displacement ? label->displacement->value : 0); if(displacement != 0) { throw AssemblerException("Label displacements are not supported when subfields are specified"); } if(lowBitIndex->value != 0 || highBitIndex->value != 11) { throw AssemblerException("Only bitrange [11:0] is supported for label targets"); } listAction.AppendOpcode(opcode); listAction.Append(label->CreatePatchAction(RelEncoding::Imm12, 4)); if(label->displacement && label->displacement->IsExpression()) { throw AssemblerException("Label displacements are not supported when subfields are specified"); } } break; case Operand::Type::Number: { if(lowBitIndex->value != 0 || highBitIndex->value != 11) { throw AssemblerException("Only bitrange [11:0] is supported for absolute targets"); } listAction.AppendOpcode(opcode); listAction.Append(new PatchExpressionAction(RelEncoding::Imm12, 4, target->expressionIndex, assembler)); } break; case Operand::Type::Immediate: { listAction.AppendOpcode(opcode); if(lowBitIndex->value >= highBitIndex->value) { throw AssemblerException("HighBitIndex (%" PRId64 ") must be greater than LowBitIndex (%" PRId64 ")", highBitIndex->value, lowBitIndex->value); } int numberOfBits = int(highBitIndex->value - lowBitIndex->value + 1); if(numberOfBits != (encodingVariant.data >> 8)) { throw AssemblerException("Bit range [%" PRId64 ":%" PRId64 "] expected to be width %d", highBitIndex->value, lowBitIndex->value, encodingVariant.data >> 8); } listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Masked, numberOfBits, encodingVariant.data & 0xff, lowBitIndex->value, target->expressionIndex, assembler)); } break; default: assert(!"Internal error"); break; } if(rd && rd->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 0, 0, rd->expressionIndex, assembler)); } if(rn && rn->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 5, 0, rn->expressionIndex, assembler)); } } /** * data: 0 = Encoding for BIC, ORR, MOVI (non-64 bit) * 1 = MOVI MSL * 2 = MOVI 64-bit. */ static void VectorImmediate(Assembler &assembler, ListAction& listAction, const Instruction& instruction, const EncodingVariant &encodingVariant, const Operand *const *operands) { assert(operands[0] != nullptr && operands[0]->type == Operand::Type::Register); assert(operands[1] != nullptr && operands[1]->type == Operand::Type::Immediate); assert(operands[2] == nullptr || operands[2]->type == Operand::Type::Label || (operands[2]->type == Operand::Type::Shift && operands[2]->shift == Operand::Shift::LSL)); assert(operands[3] == nullptr || operands[3]->type == Operand::Type::Immediate); const RegisterOperand *rd = (const RegisterOperand*) operands[0]; const ImmediateOperand *imm = (const ImmediateOperand*) operands[1]; const ImmediateOperand *amountImm = (const ImmediateOperand*) operands[3]; int64_t shiftAmount = amountImm ? amountImm->value : 0; uint32_t opcode = encodingVariant.opcode; if(rd->registerData & 4) opcode |= 0x40000000; int64_t value = imm->value; if(rd && !rd->IsExpression()) opcode |= rd->index; switch(encodingVariant.data) { case 0: // LSL switch(rd->registerData & 3) { case 0: if(shiftAmount != 0) throw AssemblerException("ShiftAmount must be #0"); opcode |= 0xe000; break; case 1: switch(shiftAmount) { case 0: opcode |= 0x8000; break; case 8: opcode |= 0xa000; break; default: throw AssemblerException("ShiftAmount must be #0 or #8"); } break; case 2: switch(shiftAmount) { case 0: break; case 8: opcode |= 0x2000; break; case 16: opcode |= 0x4000; break; case 24: opcode |= 0x6000; break; default: throw AssemblerException("ShiftAmount must be #0, #8, #16 or #24"); } break; case 3: opcode |= 0x2000e000; break; } break; case 1: // MSL if((rd->registerData & 3) != 2) { // not 32-bit throw AssemblerException("MSL shifts can only be used with 32-bit destinations."); } if(operands[2]->type != Operand::Type::Label || ((LabelOperand*) operands[2])->labelName != "msl") { throw AssemblerException("Only lsl or msl are allowed"); } switch(shiftAmount) { case 8: break; case 16: opcode |= 0x1000; break; default: throw AssemblerException("ShiftAmount must be #8 or #16"); } break; case 2: // 64-bit { int result = 0; for(int i = 0; i < 8; ++i) { int byte = (value >> (i*8)) & 0xff; switch(byte) { case 0: break; case 0xff: result |= 1 << i; break; default: throw AssemblerException("Invalid 64-bit immediate (%" PRId64 ")", value); } } value = result; } break; } if((value >> 8) != 0) { throw AssemblerException("VectorImmediate must be 8 bits wide"); } int lower5Bits = int(value & 0x1f); int upper3Bits = int(value >> 5); opcode |= lower5Bits << 5; opcode |= upper3Bits << 16; listAction.AppendOpcode(opcode); if(rd && rd->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 0, 0, rd->expressionIndex, assembler)); } if(imm && imm->IsExpression()) { switch(encodingVariant.data) { case 0: case 1: listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Masked, 5, 5, 0, imm->expressionIndex, assembler)); listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Masked, 3, 16, 5, imm->expressionIndex, assembler)); break; default: throw AssemblerException("Expressions for 64-bit immediates Not yet supported"); } } } static void RdRnRmImm2(Assembler &assembler, ListAction& listAction, const Instruction& instruction, const EncodingVariant &encodingVariant, const Operand *const *operands) { assert(operands[0] == nullptr || operands[0]->type == Operand::Type::Register); assert(operands[1] == nullptr || operands[1]->type == Operand::Type::Register); assert(operands[2] == nullptr || operands[2]->type == Operand::Type::Register); assert(operands[3] == nullptr || operands[3]->type == Operand::Type::Number); const RegisterOperand *rd = (const RegisterOperand*) operands[0]; const RegisterOperand *rn = (const RegisterOperand*) operands[1]; const RegisterOperand *rm = (const RegisterOperand*) operands[2]; const ImmediateOperand *imm = (const ImmediateOperand*) operands[3]; uint32_t opcode = encodingVariant.opcode; if(rd && !rd->IsExpression()) opcode |= rd->index; if(rn && !rn->IsExpression()) opcode |= rn->index << 5; if(rm && !rm->IsExpression()) opcode |= rm->index << 16; if(imm && !imm->IsExpression()) { assert(0 <= imm->value && imm->value < 4); opcode |= imm->value << 12; } listAction.AppendOpcode(opcode); if(rd && rd->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 0, 0, rd->expressionIndex, assembler)); } if(rn && rn->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 5, 0, rn->expressionIndex, assembler)); } if(rm && rm->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 5, 16, 0, rm->expressionIndex, assembler)); } if(imm && imm->IsExpression()) { listAction.Append(new PatchOpcodeAction(PatchOpcodeAction::Unsigned, 2, 12, 0, imm->expressionIndex, assembler)); } } static void Fixed(Assembler &assembler, ListAction& listAction, const Instruction& instruction, const EncodingVariant &encodingVariant, const Operand *const *operands) { listAction.AppendOpcode(encodingVariant.opcode); } //============================================================================ } // namespace Encoders //============================================================================ InstructionEncoder* Encoder::GetFunction() const { static InstructionEncoder *const ENCODERS[] = { #define TAG(x) &Encoders::x, #include "EncoderTags.h" #undef TAG }; return ENCODERS[value]; } //============================================================================
33.746429
161
0.653574
jthlim
32ea483ee5cc63a7130af76c05a3432674468358
348
cc
C++
util/time_point.cc
jpanikulam/experiments
be36319a89f8baee54d7fa7618b885edb7025478
[ "MIT" ]
1
2019-04-14T11:40:28.000Z
2019-04-14T11:40:28.000Z
util/time_point.cc
jpanikulam/experiments
be36319a89f8baee54d7fa7618b885edb7025478
[ "MIT" ]
5
2018-04-18T13:54:29.000Z
2019-08-22T20:04:17.000Z
util/time_point.cc
jpanikulam/experiments
be36319a89f8baee54d7fa7618b885edb7025478
[ "MIT" ]
1
2018-12-24T03:45:47.000Z
2018-12-24T03:45:47.000Z
#include "util/time_point.hh" std::ostream& operator<<(std::ostream& os, const jcc::TimePoint& t) { os << std::chrono::duration_cast<std::chrono::microseconds>(t.time_since_epoch()) .count(); return os; } std::ostream& operator<<(std::ostream& os, const jcc::TimeDuration& dt) { os << jcc::to_seconds(dt) << "s"; return os; }
26.769231
83
0.643678
jpanikulam
32f72d43c549a54747deab36fa9995af8861e5d1
10,461
cpp
C++
tests/Engine/Shader/ShaderUtils.cpp
jayrulez/NazaraEngine
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
tests/Engine/Shader/ShaderUtils.cpp
jayrulez/NazaraEngine
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
tests/Engine/Shader/ShaderUtils.cpp
jayrulez/NazaraEngine
e0310cd141f3cc11dbe8abfd5bfedf6b61de1a99
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
#include <Engine/Shader/ShaderUtils.hpp> #include <Nazara/Core/StringExt.hpp> #include <Nazara/Shader/GlslWriter.hpp> #include <Nazara/Shader/LangWriter.hpp> #include <Nazara/Shader/ShaderLangParser.hpp> #include <Nazara/Shader/SpirvPrinter.hpp> #include <Nazara/Shader/SpirvWriter.hpp> #include <Nazara/Shader/Ast/AstReflect.hpp> #include <Nazara/Shader/Ast/SanitizeVisitor.hpp> #include <catch2/catch.hpp> #include <glslang/Public/ShaderLang.h> #include <spirv-tools/libspirv.hpp> namespace { // Use OpenGL default minimal values (from https://www.khronos.org/registry/OpenGL-Refpages/es3.0/html/glGet.xhtml, https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glGet.xhtml and https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/) const TBuiltInResource s_minResources = { 8, //< maxLights 6, //< maxClipPlanes 32, //< maxTextureUnits 32, //< maxTextureCoords 16, //< maxVertexAttribs 1024, //< maxVertexUniformComponents 60, //< maxVaryingFloats 16, //< maxVertexTextureImageUnits 32, //< maxCombinedTextureImageUnits 16, //< maxTextureImageUnits 896, //< maxFragmentUniformComponents 4, //< maxDrawBuffers 256, //< maxVertexUniformVectors 15, //< maxVaryingVectors 224, //< maxFragmentUniformVectors 256, //< maxVertexOutputVectors 224, //< maxFragmentInputVectors -8, //< minProgramTexelOffset 7, //< maxProgramTexelOffset 8, //< maxClipDistances 0xFFFF, //< maxComputeWorkGroupCountX 0xFFFF, //< maxComputeWorkGroupCountY 0xFFFF, //< maxComputeWorkGroupCountZ 1024, //< maxComputeWorkGroupSizeX 1024, //< maxComputeWorkGroupSizeY 64, //< maxComputeWorkGroupSizeZ 1024, //< maxComputeUniformComponents 16, //< maxComputeTextureImageUnits 8, //< maxComputeImageUniforms 8, //< maxComputeAtomicCounters 1, //< maxComputeAtomicCounterBuffers 60, //< maxVaryingComponents 64, //< maxVertexOutputComponents 64, //< maxGeometryInputComponents 128, //< maxGeometryOutputComponents 128, //< maxFragmentInputComponents 8, //< maxImageUnits 8, //< maxCombinedImageUnitsAndFragmentOutputs 8, //< maxCombinedShaderOutputResources 0, //< maxImageSamples 0, //< maxVertexImageUniforms 0, //< maxTessControlImageUniforms 0, //< maxTessEvaluationImageUniforms 0, //< maxGeometryImageUniforms 8, //< maxFragmentImageUniforms 8, //< maxCombinedImageUniforms 16, //< maxGeometryTextureImageUnits 256, //< maxGeometryOutputVertices 1024, //< maxGeometryTotalOutputComponents 1024, //< maxGeometryUniformComponents 64, //< maxGeometryVaryingComponents 128, //< maxTessControlInputComponents 128, //< maxTessControlOutputComponents 16, //< maxTessControlTextureImageUnits 1024, //< maxTessControlUniformComponents 4096, //< maxTessControlTotalOutputComponents 128, //< maxTessEvaluationInputComponents 128, //< maxTessEvaluationOutputComponents 16, //< maxTessEvaluationTextureImageUnits 1024, //< maxTessEvaluationUniformComponents 120, //< maxTessPatchComponents 32, //< maxPatchVertices 64, //< maxTessGenLevel 16, //< maxViewports 0, //< maxVertexAtomicCounters 0, //< maxTessControlAtomicCounters 0, //< maxTessEvaluationAtomicCounters 0, //< maxGeometryAtomicCounters 8, //< maxFragmentAtomicCounters 8, //< maxCombinedAtomicCounters 1, //< maxAtomicCounterBindings 0, //< maxVertexAtomicCounterBuffers 0, //< maxTessControlAtomicCounterBuffers 0, //< maxTessEvaluationAtomicCounterBuffers 0, //< maxGeometryAtomicCounterBuffers 1, //< maxFragmentAtomicCounterBuffers 1, //< maxCombinedAtomicCounterBuffers 16384, //< maxAtomicCounterBufferSize 4, //< maxTransformFeedbackBuffers 64, //< maxTransformFeedbackInterleavedComponents 8, //< maxCullDistances 8, //< maxCombinedClipAndCullDistances 4, //< maxSamples 256, //< maxMeshOutputVerticesNV 512, //< maxMeshOutputPrimitivesNV 32, //< maxMeshWorkGroupSizeX_NV 1, //< maxMeshWorkGroupSizeY_NV 1, //< maxMeshWorkGroupSizeZ_NV 32, //< maxTaskWorkGroupSizeX_NV 1, //< maxTaskWorkGroupSizeY_NV 1, //< maxTaskWorkGroupSizeZ_NV 4, //< maxMeshViewCountNV 1, //< maxDualSourceDrawBuffersEXT { //< limits true, //< nonInductiveForLoops true, //< whileLoops true, //< doWhileLoops true, //< generalUniformIndexing true, //< generalAttributeMatrixVectorIndexing true, //< generalVaryingIndexing true, //< generalSamplerIndexing true, //< generalVariableIndexing true, //< generalConstantMatrixVectorIndexing } }; } void ExpectGLSL(const Nz::ShaderAst::Module& shaderModule, std::string_view expectedOutput) { expectedOutput = Nz::Trim(expectedOutput); SECTION("Generating GLSL") { Nz::ShaderAst::ModulePtr sanitizedModule; WHEN("Sanitizing a second time") { CHECK_NOTHROW(sanitizedModule = Nz::ShaderAst::Sanitize(shaderModule)); } const Nz::ShaderAst::Module& targetModule = (sanitizedModule) ? *sanitizedModule : shaderModule; // Retrieve entry-point to get shader type std::optional<Nz::ShaderStageType> entryShaderStage; Nz::ShaderAst::AstReflect::Callbacks callbacks; callbacks.onEntryPointDeclaration = [&](Nz::ShaderStageType stageType, const std::string& functionName) { INFO("multiple entry points found! (" << functionName << ")"); REQUIRE((!entryShaderStage.has_value() || stageType == entryShaderStage)); entryShaderStage = stageType; }; Nz::ShaderAst::AstReflect reflectVisitor; reflectVisitor.Reflect(*targetModule.rootNode, callbacks); { INFO("no entry point found"); REQUIRE(entryShaderStage.has_value()); } Nz::GlslWriter writer; std::string output = writer.Generate(entryShaderStage, targetModule); WHEN("Validating expected code") { INFO("full GLSL output:\n" << output << "\nexcepted output:\n" << expectedOutput); REQUIRE(output.find(expectedOutput) != std::string::npos); } WHEN("Validating full GLSL code (using glslang)") { EShLanguage stage = EShLangVertex; switch (*entryShaderStage) { case Nz::ShaderStageType::Fragment: stage = EShLangFragment; break; case Nz::ShaderStageType::Vertex: stage = EShLangVertex; break; } glslang::TShader glslangShader(stage); glslangShader.setEnvInput(glslang::EShSourceGlsl, stage, glslang::EShClientOpenGL, 300); glslangShader.setEnvClient(glslang::EShClientOpenGL, glslang::EShTargetOpenGL_450); glslangShader.setEnvTarget(glslang::EShTargetNone, static_cast<glslang::EShTargetLanguageVersion>(0)); glslangShader.setEntryPoint("main"); const char* source = output.c_str(); glslangShader.setStrings(&source, 1); if (!glslangShader.parse(&s_minResources, 100, false, static_cast<EShMessages>(EShMsgDefault | EShMsgKeepUncalled))) { INFO("full GLSL output:\n" << output << "\nerror:\n" << glslangShader.getInfoLog()); REQUIRE(false); } } } } void ExpectNZSL(const Nz::ShaderAst::Module& shaderModule, std::string_view expectedOutput) { expectedOutput = Nz::Trim(expectedOutput); SECTION("Generating NZSL") { Nz::ShaderAst::ModulePtr sanitizedModule; WHEN("Sanitizing a second time") { CHECK_NOTHROW(sanitizedModule = Nz::ShaderAst::Sanitize(shaderModule)); } const Nz::ShaderAst::Module& targetModule = (sanitizedModule) ? *sanitizedModule : shaderModule; Nz::LangWriter writer; std::string output = writer.Generate(targetModule); WHEN("Validating expected code") { INFO("full NZSL output:\n" << output << "\nexcepted output:\n" << expectedOutput); REQUIRE(output.find(expectedOutput) != std::string::npos); } WHEN("Validating full NZSL code (by recompiling it)") { // validate NZSL by recompiling it REQUIRE_NOTHROW(Nz::ShaderLang::Parse(output)); } } } void ExpectSPIRV(const Nz::ShaderAst::Module& shaderModule, std::string_view expectedOutput, bool outputParameter) { expectedOutput = Nz::Trim(expectedOutput); SECTION("Generating SPIRV") { Nz::ShaderAst::ModulePtr sanitizedModule; WHEN("Sanitizing a second time") { CHECK_NOTHROW(sanitizedModule = Nz::ShaderAst::Sanitize(shaderModule)); } const Nz::ShaderAst::Module& targetModule = (sanitizedModule) ? *sanitizedModule : shaderModule; Nz::SpirvWriter writer; Nz::SpirvPrinter printer; Nz::SpirvPrinter::Settings settings; settings.printHeader = false; settings.printParameters = outputParameter; auto spirv = writer.Generate(targetModule); std::string output = printer.Print(spirv.data(), spirv.size(), settings); WHEN("Validating expected code") { INFO("full SPIRV output:\n" << output << "\nexcepted output:\n" << expectedOutput); REQUIRE(output.find(expectedOutput) != std::string::npos); } WHEN("Validating full SPIRV code (using libspirv)") { // validate SPIRV with libspirv spvtools::SpirvTools spirvTools(spv_target_env::SPV_ENV_VULKAN_1_0); spirvTools.SetMessageConsumer([&](spv_message_level_t /*level*/, const char* /*source*/, const spv_position_t& /*position*/, const char* message) { std::string fullSpirv; if (!spirvTools.Disassemble(spirv, &fullSpirv)) fullSpirv = "<failed to disassemble SPIRV>"; UNSCOPED_INFO(fullSpirv + "\n" + message); }); REQUIRE(spirvTools.Validate(spirv)); } } } Nz::ShaderAst::ModulePtr SanitizeModule(const Nz::ShaderAst::Module& module) { Nz::ShaderAst::SanitizeVisitor::Options defaultOptions; return SanitizeModule(module, defaultOptions); } Nz::ShaderAst::ModulePtr SanitizeModule(const Nz::ShaderAst::Module& module, const Nz::ShaderAst::SanitizeVisitor::Options& options) { Nz::ShaderAst::ModulePtr shaderModule; WHEN("We sanitize the shader") { REQUIRE_NOTHROW(shaderModule = Nz::ShaderAst::Sanitize(module, options)); } WHEN("We output NZSL and try to parse it again") { Nz::LangWriter langWriter; std::string outputCode = langWriter.Generate((shaderModule) ? *shaderModule : module); REQUIRE_NOTHROW(shaderModule = Nz::ShaderAst::Sanitize(*Nz::ShaderLang::Parse(outputCode), options)); } // Ensure sanitization if (!shaderModule) REQUIRE_NOTHROW(shaderModule = Nz::ShaderAst::Sanitize(module, options)); return shaderModule; }
34.524752
247
0.710735
jayrulez
32f838592e804be4485b0ae416168a3d980f31ce
398
cpp
C++
test/snippet/alphabet/aminoacid/aa27_construction.cpp
marehr/nomchop
a88bfb6f5d4a291a71b6b3192eeac81fdc450d43
[ "CC-BY-4.0", "CC0-1.0" ]
1
2021-03-01T11:12:56.000Z
2021-03-01T11:12:56.000Z
test/snippet/alphabet/aminoacid/aa27_construction.cpp
simonsasse/seqan3
0ff2e117952743f081735df9956be4c512f4ccba
[ "CC0-1.0", "CC-BY-4.0" ]
2
2017-05-17T07:16:19.000Z
2020-02-13T16:10:10.000Z
test/snippet/alphabet/aminoacid/aa27_construction.cpp
simonsasse/seqan3
0ff2e117952743f081735df9956be4c512f4ccba
[ "CC0-1.0", "CC-BY-4.0" ]
null
null
null
#include <seqan3/alphabet/aminoacid/aa27.hpp> #include <seqan3/core/debug_stream.hpp> int main() { using seqan3::operator""_aa27; seqan3::aa27 my_letter{'A'_aa27}; my_letter.assign_char('C'); my_letter.assign_char('?'); // all unknown characters are converted to 'X'_aa27 implicitly if (my_letter.to_char() == 'X') seqan3::debug_stream << "yeah\n"; // "yeah"; }
24.875
94
0.658291
marehr
32fbbdfc86159f46f80658a55926618bca353a72
7,591
cpp
C++
Hydro-Engine/PanelConfig.cpp
PerezEnric/Hydro-Engine
16b99dc6092889cf2b15cf33aaa9567242eaf6fd
[ "MIT" ]
4
2019-10-15T19:58:57.000Z
2020-12-02T20:15:13.000Z
Hydro-Engine/PanelConfig.cpp
PerezEnric/Hydro-Engine
16b99dc6092889cf2b15cf33aaa9567242eaf6fd
[ "MIT" ]
null
null
null
Hydro-Engine/PanelConfig.cpp
PerezEnric/Hydro-Engine
16b99dc6092889cf2b15cf33aaa9567242eaf6fd
[ "MIT" ]
null
null
null
#include "PanelConfig.h" #include "Application.h" #include "ModuleWindow.h" #include "ModuleRenderer3D.h" #include "ImGui/imconfig.h" #include "ImGui/imgui.h" #include "ImGui/imgui_impl_sdl.h" #include "ImGui/imgui_impl_opengl3.h" #include "Glew/include/glew.h" #include "SDL/include/SDL.h" #include "SDL/include/SDL_opengl.h" #include "mmgr/mmgr.h" #pragma comment (lib, "Glew/lib/glew32.lib") PanelConfig::PanelConfig(): Panel() { std::ifstream file("Config.json"); if (!file) { LOG("Could not open config_file"); } else { LOG("Config_file succesfully loaded"); file >> j; } } PanelConfig::~PanelConfig() { } void PanelConfig::ConfigApplication() { ImGui::Text("App Name: "); ImGui::SameLine(); engine_name = j["Config"]["App"]["Name"].get<std::string>(); ImGui::Text(engine_name.c_str()); ImGui::Text("Organization: "); ImGui::SameLine(); organization = j["Config"]["App"]["Organization"].get<std::string>(); ImGui::Text(organization.c_str()); //FPS and Ms Historigrams sMStats stats = m_getMemoryStatistics(); FillFPSVector(); FillMsVector(); FillMemVector(); char title[25]; sprintf_s(title, 25, "Framerate %.1f", fps_log[fps_log.size() - 1]); ImGui::PlotHistogram("##framerate", &fps_log[0], fps_log.size(), 0, title, 0.0f, 100.0f, ImVec2(310, 100)); sprintf_s(title, 25, "Milliseconds %0.1f", ms_log[ms_log.size() - 1]); ImGui::PlotHistogram("##milliseconds", &ms_log[0], ms_log.size(), 0, title, 0.0f, 100.0f, ImVec2(310, 100)); sprintf_s(title, 25, "Memory Consumption"); ImGui::PlotHistogram("##memory", &mem_log[0], mem_log.size(), 0, title, 0.0f, (float)stats.peakReportedMemory * 1.2f, ImVec2(310, 100)); ImGui::Text("Total Reported Mem: %u", stats.totalReportedMemory); ImGui::Text("Total Actual Mem: %u", stats.totalActualMemory); ImGui::Text("Peak Reported Mem: %u", stats.peakReportedMemory); ImGui::Text("Peak Actual Mem: %u", stats.peakActualMemory); ImGui::Text("Accumulated Reported Mem: %u", stats.accumulatedReportedMemory); ImGui::Text("Accumulated Actual Mem: %u", stats.accumulatedActualMemory); ImGui::Text("Accumulated Alloc Unit Count: %u", stats.accumulatedAllocUnitCount); ImGui::Text("Total Alloc Unit Count: %u", stats.totalAllocUnitCount); ImGui::Text("Peak Alloc Unit Count: %u", stats.peakAllocUnitCount); } void PanelConfig::WindowSettings() { ImGui::SliderFloat("Brightness", &App->window->brightness, 0, 1); SDL_SetWindowBrightness(App->window->window, App->window->brightness); ImGui::SliderInt("Width", &App->window->width, 640, 1920); ImGui::SliderInt("Height", &App->window->height, 480, 1080); SDL_SetWindowSize(App->window->window, App->window->width, App->window->height); if (ImGui::Checkbox("Fullscreen", &App->window->is_fullscreen)) App->window->WindowSettings(SDL_WINDOW_FULLSCREEN, App->window->is_fullscreen); ImGui::SameLine(); if (ImGui::Checkbox("Resizable", &App->window->is_resizable)) App->window->WindowSettings(SDL_WINDOW_RESIZABLE, App->window->is_resizable); if (ImGui::Checkbox("Borderless", &App->window->is_borderless)) App->window->WindowSettings(SDL_WINDOW_BORDERLESS, App->window->is_borderless); ImGui::SameLine(); if (ImGui::Checkbox("Fullscreen Desktop", &App->window->is_full_desktop)) App->window->WindowSettings(SDL_WINDOW_FULLSCREEN_DESKTOP, App->window->is_full_desktop); } void PanelConfig::RenderSettings() { if (ImGui::Checkbox("Depth Test", &App->renderer3D->gl_depth_test)) App->renderer3D->EnableRenderSettings(GL_DEPTH_TEST, App->renderer3D->gl_depth_test); if (ImGui::Checkbox("Cull Face", &App->renderer3D->gl_cull_face)) App->renderer3D->EnableRenderSettings(GL_CULL_FACE, App->renderer3D->gl_cull_face); if (ImGui::Checkbox("Lighting", &App->renderer3D->gl_lighting)) App->renderer3D->EnableRenderSettings(GL_LIGHTING, App->renderer3D->gl_lighting); if (ImGui::Checkbox("Color Material", &App->renderer3D->gl_color_material)) App->renderer3D->EnableRenderSettings(GL_COLOR_MATERIAL, App->renderer3D->gl_color_material); if (ImGui::Checkbox("Texture 2D", &App->renderer3D->gl_texture_2D)) App->renderer3D->EnableRenderSettings(GL_TEXTURE_2D, App->renderer3D->gl_texture_2D); if (ImGui::Checkbox("Blend", &App->renderer3D->gl_blend)) App->renderer3D->EnableRenderSettings(GL_BLEND, App->renderer3D->gl_blend); if (ImGui::Checkbox("Wireframe", &App->renderer3D->is_wireframe)) { if (App->renderer3D->is_wireframe) glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); else glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } } void PanelConfig::HardwareInfo() { ImGui::Text("SDL version: %i.%i.%i", App->system_info.sdl_version.major, App->system_info.sdl_version.minor, App->system_info.sdl_version.patch); ImGui::Separator(); ImGui::Text("System Ram: %.2f GB", App->system_info.ram); ImGui::Text("CPUs: %i (Cache: %i KB)", App->system_info.cpus, App->system_info.cpu_cache); ImGui::Text("Caps:"); ImGui::SameLine(); if (App->system_info.has_AVX) ImGui::Text("AVX"); ImGui::SameLine(); if (App->system_info.has_AVX2) ImGui::Text("AVX2"); ImGui::SameLine(); if (App->system_info.has_AltiVec) ImGui::Text("AltiVec"); ImGui::SameLine(); if (App->system_info.has_MMX) ImGui::Text("MMX"); ImGui::SameLine(); if (App->system_info.has_RDSTC) ImGui::Text("RDSTC"); ImGui::SameLine(); if (App->system_info.has_3DNow) ImGui::Text("3DNow"); ImGui::SameLine(); if (App->system_info.has_SSE) ImGui::Text("SSE"); ImGui::SameLine(); if (App->system_info.has_AVX) ImGui::Text("SSE2"); ImGui::SameLine(); if (App->system_info.has_AVX) ImGui::Text("SSE3"); ImGui::SameLine(); if (App->system_info.has_AVX) ImGui::Text("SSE41"); ImGui::SameLine(); if (App->system_info.has_AVX) ImGui::Text("SSE42"); ImGui::Separator(); ImGui::Text("GPU vendor: %s", App->system_info.vendor); ImGui::Text("GPU brand: %s", App->system_info.renderer); ImGui::Text("GPU version: %s", App->system_info.version); } void PanelConfig::InputInfo() { ImGui::Text("Mouse position:"); ImGui::Text("x: %d", App->input->GetMouseX()); ImGui::SameLine(); ImGui::Text("y: %d", App->input->GetMouseY()); ImGui::Text("Mouse motion:"); ImGui::Text("x: %d", App->input->GetMouseXMotion()); ImGui::SameLine(); ImGui::Text("y: %d", App->input->GetMouseYMotion()); } void PanelConfig::FillFPSVector() { if (fps_log.size() < 100) { for (uint i = 0; fps_log.size() < 100; i++) { fps_log.push_back(App->GetFPS()); } } else fps_log.erase(fps_log.begin()); } void PanelConfig::FillMsVector() { if (ms_log.size() < 100) { for (uint i = 0; ms_log.size() < 100; i++) { ms_log.push_back(App->GetMs()); } } else ms_log.erase(ms_log.begin()); } void PanelConfig::FillMemVector() { sMStats stats = m_getMemoryStatistics(); if (mem_log.size() < 100) { for (uint i = 0; mem_log.size() < 100; i++) { mem_log.push_back((float)stats.totalReportedMemory); } } else mem_log.erase(mem_log.begin()); } bool PanelConfig::Update() { bool ret = true; if (ImGui::Begin("Configuration", &is_active)) { ImGui::SetWindowPos(ImVec2{ 600, 20 }, ImGuiCond_FirstUseEver); ImGui::SetWindowSize(ImVec2{ 600, 600 }, ImGuiCond_FirstUseEver); if (ImGui::CollapsingHeader("Application")) { ConfigApplication(); } if (ImGui::CollapsingHeader("Window Settings")) { WindowSettings(); } if (ImGui::CollapsingHeader("Render Settings")) { RenderSettings(); } if (ImGui::CollapsingHeader("Input Information")) { InputInfo(); } if (ImGui::CollapsingHeader("Hardware")) { HardwareInfo(); } ImGui::End(); } return ret; }
27.305755
146
0.697932
PerezEnric
32fc1e6782acb2bac7b3b46e36f6e3b84bff48ee
84
cpp
C++
EglCpp/Sources/SceneSystem/GameObject.cpp
Egliss/EglCppBase
94d24b6e5e91da880833237a879138760ae9c669
[ "MIT" ]
null
null
null
EglCpp/Sources/SceneSystem/GameObject.cpp
Egliss/EglCppBase
94d24b6e5e91da880833237a879138760ae9c669
[ "MIT" ]
2
2020-08-04T18:14:51.000Z
2020-08-06T19:19:11.000Z
EglCpp/Sources/SceneSystem/GameObject.cpp
Egliss/EglCppBase
94d24b6e5e91da880833237a879138760ae9c669
[ "MIT" ]
null
null
null
#include "pch.h" #include "GameObject.hpp" void Egliss::GameObject::Update() { }
10.5
33
0.678571
Egliss
32fce4fc22ef67c72a91ff6d7e5b8fde23521314
9,852
cpp
C++
source/perm_group_disjoint_decomp.cpp
goens/TUD_computational_group_theory
3f4703cae1ac049089db23eafc321e8daca2d99d
[ "MIT" ]
2
2018-09-10T09:31:17.000Z
2018-10-14T15:19:20.000Z
source/perm_group_disjoint_decomp.cpp
goens/TUD_computational_group_theory
3f4703cae1ac049089db23eafc321e8daca2d99d
[ "MIT" ]
7
2020-06-11T07:25:08.000Z
2020-12-19T09:07:50.000Z
source/perm_group_disjoint_decomp.cpp
goens/TUD_computational_group_theory
3f4703cae1ac049089db23eafc321e8daca2d99d
[ "MIT" ]
2
2020-09-10T19:31:57.000Z
2020-12-09T13:17:50.000Z
#include <algorithm> #include <cassert> #include <iterator> #include <memory> #include <unordered_set> #include <utility> #include <vector> #include "dbg.hpp" #include "orbit.hpp" #include "perm.hpp" #include "perm_group.hpp" #include "perm_set.hpp" #include "timer.hpp" namespace mpsym { namespace internal { std::vector<PermGroup> PermGroup::disjoint_decomposition( bool complete, bool disjoint_orbit_optimization) const { return complete ? disjoint_decomp_complete(disjoint_orbit_optimization) : disjoint_decomp_incomplete(); } bool PermGroup::disjoint_decomp_orbits_dependent( Orbit const &orbit1, Orbit const &orbit2) const { std::unordered_set<Perm> restricted_stabilizers, restricted_elements; for (Perm const &perm : *this) { Perm restricted_perm(perm.restricted(orbit1.begin(), orbit1.end())); if (restricted_perm.id()) continue; if (perm.stabilizes(orbit2.begin(), orbit2.end())) restricted_stabilizers.insert(restricted_perm); restricted_elements.insert(restricted_perm); } return restricted_stabilizers.size() < restricted_elements.size(); } void PermGroup::disjoint_decomp_generate_dependency_classes( OrbitPartition &orbits) const { unsigned num_dependency_classes = 0u; std::vector<int> processed(orbits.num_partitions(), 0); unsigned num_processed = 0u; for (unsigned i = 0u; i < orbits.num_partitions(); ++i) { if (processed[i]) continue; // determine which orbits to merge std::unordered_set<unsigned> merge{i}; for (unsigned j = i + 1u; j < orbits.num_partitions(); ++j) { if (processed[j]) continue; if (disjoint_decomp_orbits_dependent(orbits[i], orbits[j])) { merge.insert(j); processed[j] = 1; ++num_processed; } } // merge orbits for (unsigned x = 0u; x < degree(); ++x) { if (merge.find(orbits.partition_index(x)) != merge.end()) orbits.change_partition(x, num_dependency_classes); } ++num_dependency_classes; // check if we're done processed[i] = 1; if (++num_processed == orbits.num_partitions()) break; } } bool PermGroup::disjoint_decomp_restricted_subgroups( OrbitPartition const &orbit_split, PermGroup const &perm_group, std::pair<PermGroup, PermGroup> &restricted_subgroups) { auto split1(orbit_split[0]); auto split2(orbit_split[1]); PermSet restricted_generators1; PermSet restricted_generators2; for (Perm const &gen : perm_group.generators()) { Perm restricted_generator1(gen.restricted(split1.begin(), split1.end())); Perm restricted_generator2(gen.restricted(split2.begin(), split2.end())); if (!perm_group.contains_element(restricted_generator1) || !perm_group.contains_element(restricted_generator2)) { DBG(TRACE) << "Restricted groups are not a disjoint subgroup decomposition"; return false; } restricted_generators1.insert(restricted_generator1); restricted_generators2.insert(restricted_generator2); } restricted_subgroups.first = PermGroup(perm_group.degree(), restricted_generators1); restricted_subgroups.second = PermGroup(perm_group.degree(), restricted_generators2); DBG(TRACE) << "Found disjoint subgroup decomposition:"; DBG(TRACE) << restricted_subgroups.first; DBG(TRACE) << restricted_subgroups.second; return true; } std::vector<PermGroup> PermGroup::disjoint_decomp_join_results( std::vector<PermGroup> const &res1, std::vector<PermGroup> const &res2) { auto res(res1); res.insert(res.end(), res2.begin(), res2.end()); return res; } std::vector<PermGroup> PermGroup::disjoint_decomp_complete_recursive( OrbitPartition const &orbits, PermGroup const &perm_group) { // iterate over all possible partitions of the set of all orbits into two sets assert(orbits.num_partitions() < 8 * sizeof(unsigned long long)); for (auto part = 1ULL; !(part & (1ULL << (orbits.num_partitions() - 1u))); ++part) { OrbitPartition orbit_split(perm_group.degree()); for (unsigned x = 0u; x < perm_group.degree(); ++x) { if (orbits.partition_index(x) == -1) continue; if ((1ULL << orbits.partition_index(x)) & part) orbit_split.change_partition(x, 1); else orbit_split.change_partition(x, 0); } DBG(TRACE) << "Considering orbit split:"; DBG(TRACE) << orbit_split; // try to find restricted subgroup decomposition std::pair<PermGroup, PermGroup> restricted_subgroups; if (!disjoint_decomp_restricted_subgroups( orbit_split, perm_group, restricted_subgroups)) continue; DBG(TRACE) << "Restricted groups are a disjoint subgroup decomposition"; // recurse for both orbit partition elements and return combined result auto orbits_recurse(orbits.split(orbit_split)); DBG(TRACE) << "Recursing with orbit partitions:"; DBG(TRACE) << orbits_recurse[0]; DBG(TRACE) << orbits_recurse[1]; return disjoint_decomp_join_results( disjoint_decomp_complete_recursive(orbits_recurse[0], restricted_subgroups.first), disjoint_decomp_complete_recursive(orbits_recurse[1], restricted_subgroups.second)); } DBG(TRACE) << "No further decomposition possible, returning group"; return {perm_group}; } std::vector<PermGroup> PermGroup::disjoint_decomp_complete( bool disjoint_orbit_optimization) const { DBG(DEBUG) << "Finding (complete) disjoint subgroup decomposition for:"; DBG(DEBUG) << *this; OrbitPartition orbits(degree(), generators()); DBG(TRACE) << "Orbit decomposition:"; DBG(TRACE) << orbits; if (disjoint_orbit_optimization) { DBG(TRACE) << "Using dependent orbit optimization"; disjoint_decomp_generate_dependency_classes(orbits); DBG(TRACE) << "=> Grouped dependency class unions:"; DBG(TRACE) << orbits; } auto decomp(disjoint_decomp_complete_recursive(orbits, *this)); DBG(DEBUG) << "Found disjoint subgroup decomposition:"; for (PermGroup const &pg : decomp) DBG(DEBUG) << pg; return decomp; } void PermGroup::MovedSet::init(Perm const &perm) { clear(); for (unsigned i = 0u; i < perm.degree(); ++i) { if (perm[i] != i) push_back(i); } } bool PermGroup::MovedSet::equivalent(MovedSet const &other) const { MovedSet::size_type i1 = 0u, i2 = 0u; while ((*this)[i1] != other[i2]) { if ((*this)[i1] < other[i2]) { if (++i1 == this->size()) return false; } else { if (++i2 == other.size()) return false; } } return true; } void PermGroup::MovedSet::extend(MovedSet const &other) { MovedSet tmp; std::set_union( begin(), end(), other.begin(), other.end(), std::back_inserter(tmp)); *this = tmp; } std::vector<PermGroup::EquivalenceClass> PermGroup::disjoint_decomp_find_equivalence_classes() const { TIMER_START("disjoint decomp find equiv classes"); std::vector<EquivalenceClass> equivalence_classes; MovedSet moved; for (Perm const &perm : generators()) { moved.init(perm); if (equivalence_classes.empty()) { equivalence_classes.emplace_back(perm, moved); DBG(TRACE) << "Initial equivalence class: {" << perm << "}"; DBG(TRACE) << "'moved' set is: " << moved; continue; } bool new_class = true; for (auto &ec : equivalence_classes) { if (!moved.equivalent(ec.moved)) continue; ec.generators.insert(perm); DBG(TRACE) << "Updated Equivalence class to " << ec.generators; ec.moved.extend(moved); DBG(TRACE) << "Updated 'moved' set to " << ec.moved; new_class = false; break; } if (new_class) { equivalence_classes.emplace_back(perm, moved); DBG(TRACE) << "New equivalence class: {" << perm << "}"; DBG(TRACE) << "'moved' set is: " << moved; } } TIMER_STOP("disjoint decomp find equiv classes"); return equivalence_classes; } void PermGroup::disjoint_decomp_merge_equivalence_classes( std::vector<EquivalenceClass> &equivalence_classes) const { TIMER_START("disjoint decomp merge equiv classes"); unsigned moved_total = 0u; for (auto i = 0u; i < equivalence_classes.size(); ++i) { EquivalenceClass &ec1 = equivalence_classes[i]; if (ec1.merged) continue; for (auto j = i + 1u; j < equivalence_classes.size(); ++j) { EquivalenceClass &ec2 = equivalence_classes[j]; if (ec1.moved.equivalent(ec2.moved)) { DBG(TRACE) << "Merging equivalence class " << ec2.generators << " into " << ec1.generators; ec1.generators.insert(ec2.generators.begin(), ec2.generators.end()); ec1.moved.extend(ec2.moved); ec2.merged = true; } } if ((moved_total += ec1.moved.size()) == degree()) break; } TIMER_STOP("disjoint decomp merge equiv classes"); } std::vector<PermGroup> PermGroup::disjoint_decomp_incomplete() const { DBG(DEBUG) << "Finding (incomplete) disjoint subgroup decomposition for:"; DBG(DEBUG) << *this; auto equivalence_classes(disjoint_decomp_find_equivalence_classes()); disjoint_decomp_merge_equivalence_classes(equivalence_classes); TIMER_START("disjoint decomp construct groups"); std::vector<PermGroup> decomp; for (auto j = 0u; j < equivalence_classes.size(); ++j) { if (equivalence_classes[j].merged) continue; decomp.emplace_back(degree(), equivalence_classes[j].generators); } TIMER_STOP("disjoint decomp construct groups"); DBG(DEBUG) << "Disjoint subgroup generators are:"; #ifndef NDEBUG for (PermGroup const &pg : decomp) DBG(DEBUG) << pg.generators(); #endif return decomp; } } // namespace internal } // namespace mpsym
26.063492
86
0.671133
goens
fd058a4c024c9d1a7782bcd708fa00491f5f2403
1,550
cpp
C++
EU4toV3Tests/MapperTests/NationMergeMapperTests/NationMergeMapperTests.cpp
ParadoxGameConverters/EU4toVic3
e055d5fbaadc21e37f4bce5b3a4f4c1e415598fa
[ "MIT" ]
5
2021-05-22T20:10:05.000Z
2021-05-28T08:07:05.000Z
EU4toV3Tests/MapperTests/NationMergeMapperTests/NationMergeMapperTests.cpp
klorpa/EU4toVic3
36b53a76402c715f618dd88f0caf962072bda8cf
[ "MIT" ]
13
2021-05-25T08:26:11.000Z
2022-01-13T18:24:12.000Z
EU4toV3Tests/MapperTests/NationMergeMapperTests/NationMergeMapperTests.cpp
Zemurin/EU4toVic3
532b9a11e0e452be54d89e12cff5fb1f84ac3d11
[ "MIT" ]
5
2021-05-22T13:45:43.000Z
2021-12-25T00:00:04.000Z
#include "NationMergeMapper/NationMergeMapper.h" #include "gtest/gtest.h" #include <gmock/gmock-matchers.h> using testing::UnorderedElementsAre; TEST(Mappers_NationMergeMapperTests, primitivesDefaultToDefaults) { std::stringstream input; mappers::NationMergeMapper mapper; mapper.loadNationMerge(input); EXPECT_FALSE(mapper.getMergeDaimyos()); EXPECT_TRUE(mapper.getMergeBlocks().empty()); } TEST(Mappers_NationMergeMapperTests, mergeDaimyosCanBeSet) { std::stringstream input; input << "merge_daimyos = yes\n"; mappers::NationMergeMapper mapper; mapper.loadNationMerge(input); EXPECT_TRUE(mapper.getMergeDaimyos()); } TEST(Mappers_NationMergeMapperTests, mergeBlocksCanBeLoaded) { std::stringstream input; input << "france = {\n"; input << " master = FRA\n"; input << " slave = ALE\n"; input << " slave = ALS\n"; input << " merge = yes\n"; input << "}\n"; input << "ireland = {\n"; input << " master = IRE\n"; input << " slave = ULS\n"; input << " slave = TYR\n"; input << " merge = no\n"; input << "}\n"; mappers::NationMergeMapper mapper; mapper.loadNationMerge(input); ASSERT_EQ(2, mapper.getMergeBlocks().size()); const auto& france = mapper.getMergeBlocks()[0]; const auto& ireland = mapper.getMergeBlocks()[1]; EXPECT_EQ("FRA", france.getMaster()); EXPECT_THAT(france.getSlaves(), UnorderedElementsAre("ALE", "ALS")); EXPECT_TRUE(france.shouldMerge()); EXPECT_EQ("IRE", ireland.getMaster()); EXPECT_THAT(ireland.getSlaves(), UnorderedElementsAre("ULS", "TYR")); EXPECT_FALSE(ireland.shouldMerge()); }
27.678571
70
0.719355
ParadoxGameConverters
fd061de7a51cf338dc6761060f1d72226ec2164b
397
hpp
C++
test/test_utility.hpp
MasterMann/argparse
e6a8802551d54fbd5a9eefb543239776dc763e96
[ "MIT" ]
1,101
2019-04-02T13:59:40.000Z
2022-03-31T23:14:00.000Z
test/test_utility.hpp
MasterMann/argparse
e6a8802551d54fbd5a9eefb543239776dc763e96
[ "MIT" ]
108
2019-04-08T23:46:13.000Z
2022-03-31T15:13:58.000Z
test/test_utility.hpp
MasterMann/argparse
e6a8802551d54fbd5a9eefb543239776dc763e96
[ "MIT" ]
144
2019-04-09T22:06:47.000Z
2022-03-31T13:09:43.000Z
#ifndef ARGPARSE_TEST_UTILITY_HPP #define ARGPARSE_TEST_UTILITY_HPP namespace testutility { // Get value at index from std::list template <typename T> T get_from_list(const std::list<T>& aList, size_t aIndex) { if (aList.size() > aIndex) { auto tIterator = aList.begin(); std::advance(tIterator, aIndex); return *tIterator; } return T(); } } #endif //ARGPARSE_TEST_UTILITY_HPP
22.055556
59
0.720403
MasterMann
fd069a7ad27de3e9edbf15ba67acec45a71612f8
362
cpp
C++
Code/Testing Tools/Boost and Google test/Google test/exception_g/1.cpp
souvik3333/Testing-and-Debugging-Tools
1fb7ddd8efa91a6e7ac6519705761961a7e52c66
[ "MIT" ]
null
null
null
Code/Testing Tools/Boost and Google test/Google test/exception_g/1.cpp
souvik3333/Testing-and-Debugging-Tools
1fb7ddd8efa91a6e7ac6519705761961a7e52c66
[ "MIT" ]
null
null
null
Code/Testing Tools/Boost and Google test/Google test/exception_g/1.cpp
souvik3333/Testing-and-Debugging-Tools
1fb7ddd8efa91a6e7ac6519705761961a7e52c66
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> #include<gtest/gtest.h> using namespace std; TEST(mytest,test1){ stack <int> st; st.push(1); EXPECT_ANY_THROW(st.pop()); // EXPECT_NO_THROW(st.pop()); // EXPECT_THROW(st.pop(),out_of_range); cout<<"continued"; } int main(int argc,char **argv){ testing::InitGoogleTest(&argc,argv); return RUN_ALL_TESTS(); }
24.133333
43
0.651934
souvik3333
fd0aab3e7553d6c6c75f1e6ecc49557fe088fe38
1,194
hpp
C++
include/YourGame/Scenes/ExampleScene.hpp
iPruch/X-GS
ac43b91735a048216f60c49a9b43d6edd6d5e35e
[ "Zlib" ]
1
2015-01-04T22:17:25.000Z
2015-01-04T22:17:25.000Z
include/YourGame/Scenes/ExampleScene.hpp
iPruch/X-GS
ac43b91735a048216f60c49a9b43d6edd6d5e35e
[ "Zlib" ]
null
null
null
include/YourGame/Scenes/ExampleScene.hpp
iPruch/X-GS
ac43b91735a048216f60c49a9b43d6edd6d5e35e
[ "Zlib" ]
null
null
null
#ifndef YOURGAME_EXAMPLESCENE_HPP #define YOURGAME_EXAMPLESCENE_HPP #include <X-GS/Scene.hpp> #include <X-GS/SceneManager.hpp> #include <X-GS/ResourceManager.hpp> #include <SFML/Graphics/RectangleShape.hpp> #include <SFML/Graphics/Font.hpp> #include <SFML/Graphics/Text.hpp> #include "ResourcePath.hpp" #include "ResourceIdentifiers.hpp" #include "ExampleBallEntity.hpp" //#include <iostream> class ExampleScene : public xgs::Scene { // Typedefs and enumerations private: enum TransitionState { none, in, inFinished, out, outFinished }; // Methods public: explicit ExampleScene(sf::RenderWindow& window, xgs::SceneManager& sceneManager); ~ExampleScene(); void update(const xgs::HiResDuration& dt) override; void render() override; void handleEvent(const sf::Event& event) override; private: void buildScene() override; void loadResources() override; // Variables (member / properties) private: TransitionState mTransitionState; xgs::HiResDuration mTransitionTime; xgs::HiResDuration mTransitionDuration; sf::RectangleShape mFadingRectangle; sf::Text mText; FontManager mFontManager; }; #endif // YOURGAME_EXAMPLESCENE_HPP
21.321429
83
0.748744
iPruch
fd13f6bb77a76bf39822fe1fb1addc2ada9b61ae
158
hpp
C++
Empty.hpp
cptkidd62/minesweeper
0ac18dc94d4bca0b5e687cbce64c5e47bde58a26
[ "MIT" ]
null
null
null
Empty.hpp
cptkidd62/minesweeper
0ac18dc94d4bca0b5e687cbce64c5e47bde58a26
[ "MIT" ]
null
null
null
Empty.hpp
cptkidd62/minesweeper
0ac18dc94d4bca0b5e687cbce64c5e47bde58a26
[ "MIT" ]
null
null
null
#ifndef EMPTY_HPP #define EMPTY_HPP #include "Tile.hpp" class Empty : public Tile { public: Empty(int x, int y); int revert(); private: }; #endif
9.875
25
0.658228
cptkidd62
fd1695a2aaed2d58054740379a1436c03f312626
2,026
cpp
C++
libWmfToSvgCpp/SvgRectRegion.cpp
shouhirobumi/wmfToSvgLib
fdd5b9a5517c150e50e111cd0f1bf486fea6e5d1
[ "MIT" ]
null
null
null
libWmfToSvgCpp/SvgRectRegion.cpp
shouhirobumi/wmfToSvgLib
fdd5b9a5517c150e50e111cd0f1bf486fea6e5d1
[ "MIT" ]
null
null
null
libWmfToSvgCpp/SvgRectRegion.cpp
shouhirobumi/wmfToSvgLib
fdd5b9a5517c150e50e111cd0f1bf486fea6e5d1
[ "MIT" ]
null
null
null
#include "SvgRectRegion.h" //#include "SvgRegion.h" #include "SvgGdi.h" #include "SvgDc.h" //#include "tinyxml2.h" //#include "tool.h" namespace WMFConverter{ SvgRectRegion::SvgRectRegion(SvgGdi *gdi, int left, int top, int right, int bottom) : SvgRegion(gdi) { _left = left; _top = top; _right = right; _bottom = bottom; } /// Left value. int SvgRectRegion::Left() { return _left; } /// Top value. int SvgRectRegion::Top() { return _top; } /// Right value. int SvgRectRegion::Right() { return _right; } /// Bottom value. int SvgRectRegion::Bottom() { return _bottom; } /// Create rect element. tinyxml2::XMLElement* SvgRectRegion::CreateElement() { tinyxml2::XMLElement *elem = GDI()->Document()->NewElement("rect"); elem->SetAttribute("x", intToString((int)(GDI()->DC()->ToAbsoluteX(this->Left()))).c_str()); elem->SetAttribute("y", intToString((int)GDI()->DC()->ToAbsoluteY(Top())).c_str()); elem->SetAttribute("width", intToString((int)GDI()->DC()->ToRelativeX(Right() - Left())).c_str()); elem->SetAttribute("height", intToString((int)GDI()->DC()->ToRelativeY(Bottom() - Top())).c_str()); return (elem); } /// Serves as the default hash function. int SvgRectRegion::GetHashCode() { int prime = 31; int result = 1; result = prime * result + _bottom; result = prime * result + _left; result = prime * result + _right; result = prime * result + _top; return result; } /// Determines whether the specified object is equal to the current object. bool SvgRectRegion::Equals(void *obj) { if (this == obj) return true; if (obj == NULL) return false; SvgRectRegion *other = (SvgRectRegion*)obj; if (_bottom != other->Bottom()) return false; if (_left != other->Left()) return false; if (_right != other->Right()) return false; if (_top != other->Top()) return false; return true; } }
22.764045
103
0.60464
shouhirobumi
fd1788dcc29506e736a4c8874803405df4d028d4
4,636
cpp
C++
export/windows/obj/src/openfl/_internal/renderer/opengl/GLTextField.cpp
seanbashaw/frozenlight
47c540d30d63e946ea2dc787b4bb602cc9347d21
[ "MIT" ]
null
null
null
export/windows/obj/src/openfl/_internal/renderer/opengl/GLTextField.cpp
seanbashaw/frozenlight
47c540d30d63e946ea2dc787b4bb602cc9347d21
[ "MIT" ]
null
null
null
export/windows/obj/src/openfl/_internal/renderer/opengl/GLTextField.cpp
seanbashaw/frozenlight
47c540d30d63e946ea2dc787b4bb602cc9347d21
[ "MIT" ]
null
null
null
// Generated by Haxe 3.4.7 #include <hxcpp.h> #ifndef INCLUDED_openfl__internal_renderer_cairo_CairoTextField #include <openfl/_internal/renderer/cairo/CairoTextField.h> #endif #ifndef INCLUDED_openfl__internal_renderer_opengl_GLTextField #include <openfl/_internal/renderer/opengl/GLTextField.h> #endif #ifndef INCLUDED_openfl_display_CairoRenderer #include <openfl/display/CairoRenderer.h> #endif #ifndef INCLUDED_openfl_display_DisplayObject #include <openfl/display/DisplayObject.h> #endif #ifndef INCLUDED_openfl_display_DisplayObjectRenderer #include <openfl/display/DisplayObjectRenderer.h> #endif #ifndef INCLUDED_openfl_display_IBitmapDrawable #include <openfl/display/IBitmapDrawable.h> #endif #ifndef INCLUDED_openfl_display_InteractiveObject #include <openfl/display/InteractiveObject.h> #endif #ifndef INCLUDED_openfl_display_OpenGLRenderer #include <openfl/display/OpenGLRenderer.h> #endif #ifndef INCLUDED_openfl_events_EventDispatcher #include <openfl/events/EventDispatcher.h> #endif #ifndef INCLUDED_openfl_events_IEventDispatcher #include <openfl/events/IEventDispatcher.h> #endif #ifndef INCLUDED_openfl_geom_Matrix #include <openfl/geom/Matrix.h> #endif #ifndef INCLUDED_openfl_text_TextField #include <openfl/text/TextField.h> #endif HX_LOCAL_STACK_FRAME(_hx_pos_a3c009369abbec2d_28_render,"openfl._internal.renderer.opengl.GLTextField","render",0x31a77300,"openfl._internal.renderer.opengl.GLTextField.render","openfl/_internal/renderer/opengl/GLTextField.hx",28,0x30c8ae9c) namespace openfl{ namespace _internal{ namespace renderer{ namespace opengl{ void GLTextField_obj::__construct() { } Dynamic GLTextField_obj::__CreateEmpty() { return new GLTextField_obj; } void *GLTextField_obj::_hx_vtable = 0; Dynamic GLTextField_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< GLTextField_obj > _hx_result = new GLTextField_obj(); _hx_result->__construct(); return _hx_result; } bool GLTextField_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x7b08b0ea; } void GLTextField_obj::render( ::openfl::text::TextField textField, ::openfl::display::OpenGLRenderer renderer, ::openfl::geom::Matrix transform){ HX_STACKFRAME(&_hx_pos_a3c009369abbec2d_28_render) HXDLIN( 28) ::openfl::_internal::renderer::cairo::CairoTextField_obj::render(textField,( ( ::openfl::display::CairoRenderer)(renderer->_hx___softwareRenderer) ),transform); } STATIC_HX_DEFINE_DYNAMIC_FUNC3(GLTextField_obj,render,(void)) GLTextField_obj::GLTextField_obj() { } bool GLTextField_obj::__GetStatic(const ::String &inName, Dynamic &outValue, hx::PropertyAccess inCallProp) { switch(inName.length) { case 6: if (HX_FIELD_EQ(inName,"render") ) { outValue = render_dyn(); return true; } } return false; } #if HXCPP_SCRIPTABLE static hx::StorageInfo *GLTextField_obj_sMemberStorageInfo = 0; static hx::StaticInfo *GLTextField_obj_sStaticStorageInfo = 0; #endif static void GLTextField_obj_sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(GLTextField_obj::__mClass,"__mClass"); }; #ifdef HXCPP_VISIT_ALLOCS static void GLTextField_obj_sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(GLTextField_obj::__mClass,"__mClass"); }; #endif hx::Class GLTextField_obj::__mClass; static ::String GLTextField_obj_sStaticFields[] = { HX_HCSTRING("render","\x56","\x6b","\x29","\x05"), ::String(null()) }; void GLTextField_obj::__register() { hx::Object *dummy = new GLTextField_obj; GLTextField_obj::_hx_vtable = *(void **)dummy; hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_HCSTRING("openfl._internal.renderer.opengl.GLTextField","\x84","\x07","\x5f","\x25"); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &GLTextField_obj::__GetStatic; __mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField; __mClass->mMarkFunc = GLTextField_obj_sMarkStatics; __mClass->mStatics = hx::Class_obj::dupFunctions(GLTextField_obj_sStaticFields); __mClass->mMembers = hx::Class_obj::dupFunctions(0 /* sMemberFields */); __mClass->mCanCast = hx::TCanCast< GLTextField_obj >; #ifdef HXCPP_VISIT_ALLOCS __mClass->mVisitFunc = GLTextField_obj_sVisitStatics; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = GLTextField_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = GLTextField_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace openfl } // end namespace _internal } // end namespace renderer } // end namespace opengl
33.114286
241
0.799827
seanbashaw
fd19e414273b79c162a8ac3d4ef1b479dc393540
2,527
cpp
C++
samples/snippets/cpp/VS_Snippets_CLR_System/system.Byte.ToString/CPP/newbytemembers2.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
421
2018-04-01T01:57:50.000Z
2022-03-28T15:24:42.000Z
samples/snippets/cpp/VS_Snippets_CLR_System/system.Byte.ToString/CPP/newbytemembers2.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
5,797
2018-04-02T21:12:23.000Z
2022-03-31T23:54:38.000Z
samples/snippets/cpp/VS_Snippets_CLR_System/system.Byte.ToString/CPP/newbytemembers2.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
1,482
2018-03-31T11:26:20.000Z
2022-03-30T22:36:45.000Z
// Byte.ToString2.cpp : main project file. using namespace System; using namespace System::Globalization; // Byte.ToString() void Byte1() { // <Snippet2> array<Byte>^ bytes = gcnew array<Byte> {0, 1, 14, 168, 255}; for each (Byte byteValue in bytes) Console::WriteLine(byteValue); // The example displays the following output to the console if the current // culture is en-US: // 0 // 1 // 14 // 168 // 255 // </Snippet2> } // Byte.ToString(String) void Byte2() { // <Snippet4> array<String^>^ formats = gcnew array<String^> {"C3", "D4", "e1", "E2", "F1", "G", "N1", "P0", "X4", "0000.0000"}; Byte number = 240; for each (String^ format in formats) Console::WriteLine("'{0}' format specifier: {1}", format, number.ToString(format)); // The example displays the following output to the console if the // current culture is en-us: // 'C3' format specifier: $240.000 // 'D4' format specifier: 0240 // 'e1' format specifier: 2.4e+002 // 'E2' format specifier: 2.40E+002 // 'F1' format specifier: 240.0 // 'G' format specifier: 240 // 'N1' format specifier: 240.0 // 'P0' format specifier: 24,000 % // 'X4' format specifier: 00F0 // '0000.0000' format specifier: 0240.0000 // </Snippet4> } // ToString(String, IFormatProvider) void Byte3() { // <Snippet5> Byte byteValue = 250; array<CultureInfo^>^ providers = gcnew array<CultureInfo^> { gcnew CultureInfo("en-us"), gcnew CultureInfo("fr-fr"), gcnew CultureInfo("es-es"), gcnew CultureInfo("de-de")}; for each (CultureInfo^ provider in providers) Console::WriteLine("{0} ({1})", byteValue.ToString("N2", provider), provider->Name); // The example displays the following output to the console: // 250.00 (en-US) // 250,00 (fr-FR) // 250,00 (es-ES) // 250,00 (de-DE) // </Snippet5> } void main() { Byte1(); Console::WriteLine(); Byte2(); Console::WriteLine(); Byte3(); Console::WriteLine(); Console::ReadLine(); }
31.5875
94
0.496636
hamarb123
fd1bc1167a9149ce4ce2ac37b6b879283b24c251
2,007
cpp
C++
arm/system/sdram.cpp
mborik/speccy2010-dividised
414978cdaf3e27852d47e9f3d5211503b17c6a2f
[ "MIT" ]
26
2018-09-20T08:49:37.000Z
2022-02-22T14:50:40.000Z
arm/system/sdram.cpp
andykarpov/speccy2010
a8a3d53835a3bd5cbf7a4f96e30729ebf244dcd4
[ "MIT" ]
4
2019-04-18T11:04:08.000Z
2020-09-05T21:12:36.000Z
arm/system/sdram.cpp
andykarpov/speccy2010
a8a3d53835a3bd5cbf7a4f96e30729ebf244dcd4
[ "MIT" ]
6
2018-10-19T21:10:03.000Z
2021-04-30T22:42:08.000Z
#include "sdram.h" #include "../system.h" dword sdramHeapPtr = VIDEO_PAGE_PTR + SDRAM_PAGE_SIZE; //--------------------------------------------------------------------------------------- dword Malloc(word recordCount, word recordSize) { dword size = recordSize; if ((size & 1) != 0) size++; size *= recordCount; if (sdramHeapPtr + 4 + size > SDRAM_PAGES * SDRAM_PAGE_SIZE) return 0; dword result = sdramHeapPtr; sdramHeapPtr += 4 + size; dword addr = 0x800000 | (result >> 1); SystemBus_Write(addr++, recordSize); SystemBus_Write(addr++, recordCount); return result; } //--------------------------------------------------------------------------------------- void Free(dword sdramPtr) { if (sdramPtr != 0) sdramHeapPtr = sdramPtr; } //--------------------------------------------------------------------------------------- bool Read(void *rec, dword sdramPtr, word pos) { if (sdramPtr == 0) return false; dword addr = 0x800000 | (sdramPtr >> 1); word recordSize = SystemBus_Read(addr++); word recordCount = SystemBus_Read(addr++); if (pos >= recordCount) return false; addr += ((recordSize + 1) >> 1) * pos; byte *ptr = (byte *) rec; while (recordSize > 0) { word data = SystemBus_Read(addr++); *ptr++ = (byte) data; recordSize--; if (recordSize > 0) { *ptr++ = (byte)(data >> 8); recordSize--; } } return true; } //--------------------------------------------------------------------------------------- bool Write(void *rec, dword sdramPtr, word pos) { if (sdramPtr == 0) return false; dword addr = 0x800000 | (sdramPtr >> 1); word recordSize = SystemBus_Read(addr++); word recordCount = SystemBus_Read(addr++); if (pos >= recordCount) return false; addr += ((recordSize + 1) >> 1) * pos; byte *ptr = (byte *) rec; for (word i = 0; i < recordSize; i += 2) { SystemBus_Write(addr++, ptr[0] | (ptr[1] << 8)); ptr += 2; } return true; } //---------------------------------------------------------------------------------------
23.611765
89
0.491779
mborik
fd206f4180a12a60374ad3f469418b51ac9fa89e
11,798
cc
C++
packages/spatial/Linear_MLS_Function.cc
brbass/ibex
5a4cc5b4d6d46430d9667970f8a34f37177953d4
[ "MIT" ]
2
2020-04-13T20:06:41.000Z
2021-02-12T17:55:54.000Z
packages/spatial/Linear_MLS_Function.cc
brbass/ibex
5a4cc5b4d6d46430d9667970f8a34f37177953d4
[ "MIT" ]
1
2018-10-22T21:03:35.000Z
2018-10-22T21:03:35.000Z
packages/spatial/Linear_MLS_Function.cc
brbass/ibex
5a4cc5b4d6d46430d9667970f8a34f37177953d4
[ "MIT" ]
3
2019-04-03T02:15:37.000Z
2022-01-04T05:50:23.000Z
#include "Linear_MLS_Function.hh" #include "Linear_Algebra.hh" #include "Linear_MLS_Normalization.hh" #include "Matrix_Functions.hh" #include "Vector_Functions.hh" #include "XML_Node.hh" namespace la = Linear_Algebra; namespace mf = Matrix_Functions; namespace vf = Vector_Functions; using std::make_shared; using std::shared_ptr; using std::vector; Linear_MLS_Function:: Linear_MLS_Function(vector<shared_ptr<Meshless_Function> > neighbor_functions): index_(neighbor_functions[0]->index()), dimension_(neighbor_functions[0]->dimension()), number_of_functions_(neighbor_functions.size()), position_(neighbor_functions[0]->position()), function_(neighbor_functions[0]), neighbor_functions_(neighbor_functions) { number_of_polynomials_ = dimension_ + 1; radius_ = function_->radius(); normalization_ = make_shared<Linear_MLS_Normalization>(dimension_); check_class_invariants(); } double Linear_MLS_Function:: value(vector<double> const &r) const { if (!function_->inside_radius(r)) { return 0.; } // Get A vector<double> a_mat(number_of_polynomials_ * number_of_polynomials_); get_a(r, a_mat); // Get B vector<double> b_vec(number_of_polynomials_); get_b(r, b_vec); // Get x = A^-1 B vector<double> x_vec(number_of_polynomials_); la::linear_solve(a_mat, b_vec, x_vec); // Get p vector<double> p_vec(number_of_polynomials_); get_polynomial(r, p_vec); // Return result return vf::dot(p_vec, x_vec); } double Linear_MLS_Function:: d_value(int dim, vector<double> const &r) const { // Check if value is inside basis radius if (!function_->inside_radius(r)) { return 0.; } // Get A vector<double> a_mat(number_of_polynomials_ * number_of_polynomials_); vector<double> d_a_mat(number_of_polynomials_ * number_of_polynomials_); get_d_a(dim, r, a_mat, d_a_mat); // Get A inverse vector<double> a_inv_mat(number_of_polynomials_ * number_of_polynomials_); la::direct_inverse(a_mat, a_inv_mat); vector<double> d_a_inv_mat(number_of_polynomials_ * number_of_polynomials_); d_a_inv_mat = mf::square_matrix_matrix_product(number_of_polynomials_, d_a_mat, a_inv_mat); d_a_inv_mat = mf::square_matrix_matrix_product(number_of_polynomials_, a_inv_mat, d_a_inv_mat); d_a_inv_mat = vf::multiply(d_a_inv_mat, -1.); // Get B vector<double> b_vec(number_of_polynomials_); vector<double> d_b_vec(number_of_polynomials_); get_d_b(dim, r, b_vec, d_b_vec); // Get p vector<double> p_vec(number_of_polynomials_); get_polynomial(r, p_vec); vector<double> d_p_vec(number_of_polynomials_); get_d_polynomial(dim, r, d_p_vec); // Calculate terms double t1 = vf::dot(d_p_vec, mf::square_matrix_vector_product(number_of_polynomials_, a_inv_mat, b_vec)); double t2 = vf::dot(p_vec, mf::square_matrix_vector_product(number_of_polynomials_, d_a_inv_mat, b_vec)); double t3 = vf::dot(p_vec, mf::square_matrix_vector_product(number_of_polynomials_, a_inv_mat, d_b_vec)); return t1 + t2 + t3; } double Linear_MLS_Function:: dd_value(int dim, vector<double> const &r) const { AssertMsg(false, "dd_value not available for Linear_MLS"); return -1.; } vector<double> Linear_MLS_Function:: gradient_value(vector<double> const &r) const { // Check if value is inside basis radius if (!function_->inside_radius(r)) { return vector<double>(dimension_, 0.); } // Get dimensional derivatives separately vector<double> result(dimension_); for (int d = 0; d < dimension_; ++d) { result[d] = d_value(d, r); } return result; } double Linear_MLS_Function:: laplacian_value(vector<double> const &r) const { AssertMsg(false, "laplacian not available for Linear_MLS"); return -1.; } void Linear_MLS_Function:: values(vector<double> const &position, vector<int> &indices, vector<double> &vals) const { // Check if position is inside weight function radius Assert(function_->inside_radius(position)); // Resize indices and values indices.resize(number_of_functions_); vals.resize(number_of_functions_); // Get indices of basis functions for (int i = 0; i < number_of_functions_; ++i) { indices[i] = neighbor_functions_[i]->index(); } // Get meshless function values vector<double> base_values(number_of_functions_); for (int i = 0; i < number_of_functions_; ++i) { base_values[i] = neighbor_functions_[i]->value(position); } // Get center positions vector<vector<double> > center_positions(number_of_functions_); for (int i = 0; i < number_of_functions_; ++i) { center_positions[i] = neighbor_functions_[i]->position(); } // Get values normalization_->get_values(position, center_positions, base_values, vals); } void Linear_MLS_Function:: gradient_values(vector<double> const &position, vector<int> &indices, vector<double> &vals, vector<vector<double> > &grad_vals) const { // Check if position is inside weight function radius Assert(function_->inside_radius(position)); // Resize indices and values indices.resize(number_of_functions_); vals.resize(number_of_functions_); grad_vals.assign(number_of_functions_, vector<double>(dimension_)); // Get indices of basis functions for (int i = 0; i < number_of_functions_; ++i) { indices[i] = neighbor_functions_[i]->index(); } // Get meshless function values vector<double> base_values(number_of_functions_); vector<vector<double> > grad_base_values(number_of_functions_, vector<double>(dimension_)); for (int i = 0; i < number_of_functions_; ++i) { base_values[i] = neighbor_functions_[i]->value(position); grad_base_values[i] = neighbor_functions_[i]->gradient_value(position); } // Get center positions vector<vector<double> > center_positions(number_of_functions_); for (int i = 0; i < number_of_functions_; ++i) { center_positions[i] = neighbor_functions_[i]->position(); } // Get values normalization_->get_gradient_values(position, center_positions, base_values, grad_base_values, vals, grad_vals); } void Linear_MLS_Function:: output(XML_Node output_node) const { output_node.set_attribute("linear_mls", "type"); function_->output(output_node); } void Linear_MLS_Function:: check_class_invariants() const { Assert(dimension_ >= 1); Assert(number_of_functions_ >= 3); // number of functions must be greater than number of polynomials (2 for linear) Assert(function_); for (shared_ptr<Meshless_Function> func : neighbor_functions_) { AssertMsg(func, "basis for mls function not initialized"); } } void Linear_MLS_Function:: get_polynomial(vector<double> const &position, vector<double> &poly) const { poly.resize(dimension_ + 1); poly[0] = 1.; for (int d = 0; d < dimension_; ++d) { poly[d+1] = position[d]; } } void Linear_MLS_Function:: get_d_polynomial(int dim, vector<double> const &position, vector<double> &d_poly) const { d_poly.assign(dimension_ + 1, 0); d_poly[dim + 1] = 1.; } void Linear_MLS_Function:: get_a(vector<double> const &position, vector<double> &a) const { a .assign(number_of_polynomials_ * number_of_polynomials_, 0); for (shared_ptr<Meshless_Function> func : neighbor_functions_) { if (func->inside_radius(position)) { vector<double> poly; get_polynomial(func->position(), poly); double weight = func->value(position); for (int j = 0; j < number_of_polynomials_; ++j) { for (int k = 0; k < number_of_polynomials_; ++k) { int l = j + number_of_polynomials_ * k; double polyprod = poly[j] * poly[k]; a[l] += weight * polyprod; } } } } } void Linear_MLS_Function:: get_d_a(int dim, vector<double> const &position, vector<double> &a, vector<double> &d_a) const { a.assign(number_of_polynomials_ * number_of_polynomials_, 0); d_a.assign(number_of_polynomials_ * number_of_polynomials_, 0); for (shared_ptr<Meshless_Function> func : neighbor_functions_) { if (func->inside_radius(position)) { vector<double> poly; get_polynomial(func->position(), poly); double weight = func->value(position); double d_weight = func->d_value(dim, position); for (int j = 0; j < number_of_polynomials_; ++j) { for (int k = 0; k < number_of_polynomials_; ++k) { int l = j + number_of_polynomials_ * k; double polyprod = poly[j] * poly[k]; a[l] += weight * polyprod; d_a[l] += d_weight * polyprod; } } } } } void Linear_MLS_Function:: get_b(vector<double> const &position, vector<double> &b) const { b.resize(number_of_polynomials_); vector<double> poly; get_polynomial(function_->position(), poly); double weight = function_->value(position); for (int i = 0; i < number_of_polynomials_; ++i) { b[i] = poly[i] * weight; } } void Linear_MLS_Function:: get_d_b(int dim, vector<double> const &position, vector<double> &b, vector<double> &d_b) const { b.resize(number_of_polynomials_); d_b.resize(number_of_polynomials_); vector<double> poly; get_polynomial(function_->position(), poly); double weight = function_->value(position); double d_weight = function_->d_value(dim, position); for (int i = 0; i < number_of_polynomials_; ++i) { b[i] = poly[i] * weight; d_b[i] = poly[i] * d_weight; } } shared_ptr<Meshless_Normalization> Linear_MLS_Function:: normalization() const { return normalization_; }
29.348259
119
0.569164
brbass
fd25f3ead434bab5bb747324e20797792ae12451
5,861
cpp
C++
core/src/engine/Manifoldmath.cpp
SpiritSuperUser/spirit
fbe69c2a9b7a73e8f47d302c619303aea2a22ace
[ "MIT" ]
2
2020-11-12T13:54:22.000Z
2021-11-05T09:10:27.000Z
core/src/engine/Manifoldmath.cpp
SpiritSuperUser/spirit
fbe69c2a9b7a73e8f47d302c619303aea2a22ace
[ "MIT" ]
null
null
null
core/src/engine/Manifoldmath.cpp
SpiritSuperUser/spirit
fbe69c2a9b7a73e8f47d302c619303aea2a22ace
[ "MIT" ]
null
null
null
#ifndef USE_CUDA #include <engine/Vectormath.hpp> #include <engine/Manifoldmath.hpp> #include <utility/Logging.hpp> #include <utility/Exception.hpp> #include <Eigen/Dense> #include <array> namespace Engine { namespace Manifoldmath { scalar norm(const vectorfield & vf) { scalar x = Vectormath::dot(vf, vf); return std::sqrt(x); } void normalize(vectorfield & vf) { scalar x = 1.0/norm(vf); #pragma omp parallel for for (unsigned int i = 0; i < vf.size(); ++i) vf[i] *= x; } void project_parallel(vectorfield & vf1, const vectorfield & vf2) { vectorfield vf3 = vf1; project_orthogonal(vf3, vf2); // TODO: replace the loop with Vectormath Kernel #pragma omp parallel for for (unsigned int i = 0; i < vf1.size(); ++i) vf1[i] -= vf3[i]; } void project_orthogonal(vectorfield & vf1, const vectorfield & vf2) { scalar x = Vectormath::dot(vf1, vf2); // TODO: replace the loop with Vectormath Kernel #pragma omp parallel for for (unsigned int i=0; i<vf1.size(); ++i) vf1[i] -= x*vf2[i]; } void invert_parallel(vectorfield & vf1, const vectorfield & vf2) { scalar x = Vectormath::dot(vf1, vf2); // TODO: replace the loop with Vectormath Kernel #pragma omp parallel for for (unsigned int i=0; i<vf1.size(); ++i) vf1[i] -= 2*x*vf2[i]; } void invert_orthogonal(vectorfield & vf1, const vectorfield & vf2) { vectorfield vf3 = vf1; project_orthogonal(vf3, vf2); // TODO: replace the loop with Vectormath Kernel #pragma omp parallel for for (unsigned int i = 0; i < vf1.size(); ++i) vf1[i] -= 2 * vf3[i]; } void project_tangential(vectorfield & vf1, const vectorfield & vf2) { #pragma omp parallel for for (unsigned int i = 0; i < vf1.size(); ++i) vf1[i] -= vf1[i].dot(vf2[i]) * vf2[i]; } scalar dist_greatcircle(const Vector3 & v1, const Vector3 & v2) { scalar r = v1.dot(v2); // Prevent NaNs from occurring r = std::fmax(-1.0, std::fmin(1.0, r)); // Greatcircle distance return std::acos(r); } scalar dist_geodesic(const vectorfield & v1, const vectorfield & v2) { scalar dist = 0; #pragma omp parallel for reduction(+:dist) for (unsigned int i = 0; i < v1.size(); ++i) dist += pow(dist_greatcircle(v1[i], v2[i]), 2); return sqrt(dist); } /* Calculates the 'tangent' vectors, i.e.in crudest approximation the difference between an image and the neighbouring */ void Tangents(std::vector<std::shared_ptr<vectorfield>> configurations, const std::vector<scalar> & energies, std::vector<vectorfield> & tangents) { int noi = configurations.size(); int nos = (*configurations[0]).size(); for (int idx_img = 0; idx_img < noi; ++idx_img) { auto& image = *configurations[idx_img]; // First Image if (idx_img == 0) { auto& image_plus = *configurations[idx_img + 1]; Vectormath::set_c_a( 1, image_plus, tangents[idx_img]); Vectormath::add_c_a(-1, image, tangents[idx_img]); } // Last Image else if (idx_img == noi - 1) { auto& image_minus = *configurations[idx_img - 1]; Vectormath::set_c_a( 1, image, tangents[idx_img]); Vectormath::add_c_a(-1, image_minus, tangents[idx_img]); } // Images Inbetween else { auto& image_plus = *configurations[idx_img + 1]; auto& image_minus = *configurations[idx_img - 1]; // Energies scalar E_mid = 0, E_plus = 0, E_minus = 0; E_mid = energies[idx_img]; E_plus = energies[idx_img + 1]; E_minus = energies[idx_img - 1]; // Vectors to neighbouring images vectorfield t_plus(nos), t_minus(nos); Vectormath::set_c_a( 1, image_plus, t_plus); Vectormath::add_c_a(-1, image, t_plus); Vectormath::set_c_a( 1, image, t_minus); Vectormath::add_c_a(-1, image_minus, t_minus); // Near maximum or minimum if ((E_plus < E_mid && E_mid > E_minus) || (E_plus > E_mid && E_mid < E_minus)) { // Get a smooth transition between forward and backward tangent scalar E_max = std::max(std::abs(E_plus - E_mid), std::abs(E_minus - E_mid)); scalar E_min = std::min(std::abs(E_plus - E_mid), std::abs(E_minus - E_mid)); if (E_plus > E_minus) { Vectormath::set_c_a(E_max, t_plus, tangents[idx_img]); Vectormath::add_c_a(E_min, t_minus, tangents[idx_img]); } else { Vectormath::set_c_a(E_min, t_plus, tangents[idx_img]); Vectormath::add_c_a(E_max, t_minus, tangents[idx_img]); } } // Rising slope else if (E_plus > E_mid && E_mid > E_minus) { Vectormath::set_c_a(1, t_plus, tangents[idx_img]); } // Falling slope else if (E_plus < E_mid && E_mid < E_minus) { Vectormath::set_c_a(1, t_minus, tangents[idx_img]); //tangents = t_minus; for (int i = 0; i < nos; ++i) { tangents[idx_img][i] = t_minus[i]; } } // No slope(constant energy) else { Vectormath::set_c_a(1, t_plus, tangents[idx_img]); Vectormath::add_c_a(1, t_minus, tangents[idx_img]); } } // Project tangents into tangent planes of spin vectors to make them actual tangents project_tangential(tangents[idx_img], image); // Normalise in 3N - dimensional space Manifoldmath::normalize(tangents[idx_img]); }// end for idx_img }// end Tangents } } #endif
29.903061
148
0.579423
SpiritSuperUser
fd26c1dc458dfb7ba1601c898f7d0b88c44e9f21
4,639
hpp
C++
uActor/include/actor_runtime/managed_actor.hpp
uActor/uActor
1180db98f48ad447639a3d625573307d87b28902
[ "MIT" ]
1
2021-09-15T12:41:37.000Z
2021-09-15T12:41:37.000Z
uActor/include/actor_runtime/managed_actor.hpp
uActor/uActor
1180db98f48ad447639a3d625573307d87b28902
[ "MIT" ]
null
null
null
uActor/include/actor_runtime/managed_actor.hpp
uActor/uActor
1180db98f48ad447639a3d625573307d87b28902
[ "MIT" ]
null
null
null
#pragma once #ifdef ESP_IDF #include <sdkconfig.h> #endif #include <cstdint> #include <deque> #include <functional> #include <set> #include <string> #include <utility> #include "executor_api.hpp" #include "pubsub/filter.hpp" #include "pubsub/publication.hpp" #include "pubsub/router.hpp" #include "runtime_allocator_configuration.hpp" #include "support/tracking_allocator.hpp" namespace uActor::ActorRuntime { class ManagedActor { public: enum class RuntimeReturnValue { NONE = 0, OK, NOT_READY, RUNTIME_ERROR, INITIALIZATION_ERROR }; template <typename U> using Allocator = RuntimeAllocatorConfiguration::Allocator<U>; using allocator_type = Allocator<ManagedActor>; template <typename U> constexpr static auto make_allocator = RuntimeAllocatorConfiguration::make_allocator<U>; using AString = std::basic_string<char, std::char_traits<char>, Allocator<char>>; struct ReceiveResult { ReceiveResult(bool exit, uint32_t next_timeout) : exit(exit), next_timeout(next_timeout) {} bool exit; uint32_t next_timeout; }; ManagedActor(const ManagedActor&) = delete; template <typename PAllocator = allocator_type> ManagedActor(ExecutorApi* api, uint32_t unique_id, std::string_view node_id, std::string_view actor_type, std::string_view actor_version, std::string_view instance_id, PAllocator allocator = make_allocator<ManagedActor>()) : _id(unique_id), _node_id(node_id, allocator), _actor_type(actor_type, allocator), _actor_version(actor_version, allocator), _instance_id(instance_id, allocator), message_queue(allocator), subscriptions(allocator), api(api) { add_default_subscription(); publish_creation_message(); } ~ManagedActor() { for (uint32_t sub_id : subscriptions) { api->remove_subscription(_id, sub_id); } #if CONFIG_UACTOR_ENABLE_TELEMETRY total_queue_size -= queue_size(); #endif } virtual RuntimeReturnValue receive(PubSub::Publication&& p) = 0; virtual std::string actor_runtime_type() = 0; std::pair<RuntimeReturnValue, uint32_t> early_initialize(); RuntimeReturnValue late_initialize(std::string&& code); bool hibernate() { if (hibernate_internal()) { _initialized = false; return true; } return false; } RuntimeReturnValue wakeup() { auto ret = wakeup_internal(); if (ret == RuntimeReturnValue::OK) { _initialized = true; } return ret; } ReceiveResult receive_next_internal(); bool enqueue(PubSub::Publication&& message); void trigger_timeout(bool user_defined, std::string_view wakeup_id); [[nodiscard]] uint32_t id() const { return _id; } // Code is returned as part of a publication void trigger_code_fetch(); [[nodiscard]] const char* node_id() const { return _node_id.c_str(); } [[nodiscard]] const char* actor_type() const { return _actor_type.c_str(); } [[nodiscard]] const char* instance_id() const { return _instance_id.c_str(); } [[nodiscard]] const char* actor_version() const { return _actor_version.c_str(); } [[nodiscard]] bool initialized() const { return _initialized; } #if CONFIG_UACTOR_ENABLE_TELEMETRY static std::atomic<int> total_queue_size; #endif protected: virtual RuntimeReturnValue early_internal_initialize() = 0; virtual RuntimeReturnValue late_internal_initialize(std::string&& code) = 0; virtual bool hibernate_internal() = 0; virtual RuntimeReturnValue wakeup_internal() = 0; uint32_t subscribe(PubSub::Filter&& f, uint8_t priority = 0); void unsubscribe(uint32_t sub_id); void publish(PubSub::Publication&& p); void republish(PubSub::Publication&& p); void delayed_publish(PubSub::Publication&& p, uint32_t delay); void enqueue_wakeup(uint32_t delay, std::string_view wakeup_id); void deffered_block_for(PubSub::Filter&& filter, uint32_t timeout); uint32_t queue_size(); private: uint32_t _id; bool waiting = false; PubSub::Filter pattern; uint32_t _timeout = UINT32_MAX; AString _node_id; AString _actor_type; AString _actor_version; AString _instance_id; std::deque<PubSub::Publication, Allocator<PubSub::Publication>> message_queue; std::set<uint32_t, std::less<uint32_t>, Allocator<uint32_t>> subscriptions; ExecutorApi* api; bool _initialized = false; uint32_t code_fetch_retries = 0; bool waiting_for_code = false; void publish_exit_message(std::string exit_reason); void publish_creation_message(); void add_default_subscription(); }; } // namespace uActor::ActorRuntime
26.357955
80
0.718258
uActor
fd2eb9f60b1eabf606bb8c786ed72dc03f981561
4,072
hpp
C++
Simpfer/data.hpp
amgt-d1/Simpfer
01697c574c7d1b99d8add87c0f105c4607bc29f5
[ "MIT" ]
5
2021-11-19T16:19:52.000Z
2022-03-17T15:59:26.000Z
Simpfer/data.hpp
amgt-d1/Simpfer
01697c574c7d1b99d8add87c0f105c4607bc29f5
[ "MIT" ]
null
null
null
Simpfer/data.hpp
amgt-d1/Simpfer
01697c574c7d1b99d8add87c0f105c4607bc29f5
[ "MIT" ]
1
2022-03-20T04:10:57.000Z
2022-03-20T04:10:57.000Z
#include "file_input.hpp" #include <vector> #include <functional> #include <algorithm> #include <map> #include <cfloat> // definition of data class data { public: unsigned int identifier = 0; std::vector<float> vec; float norm = 0; std::map<float, unsigned int, std::greater<float>> topk; float threshold = 0; std::vector<float> lowerbound_array; unsigned int block_id = 0; // constructor data() { } // norm computation void norm_computation() { for (unsigned int i = 0; i < vec.size(); ++i) norm += vec[i] * vec[i]; norm = sqrt(norm); } // k-MIPS update void update_topk(const float ip, const unsigned int id, const unsigned int k_) { if (ip > threshold) topk.insert({ip,id}); if (topk.size() > k_) { auto it = topk.end(); --it; topk.erase(it); } if (topk.size() == k_) { auto it = topk.end(); --it; threshold = it->first; } } // make lower-bound array void make_lb_array() { auto it = topk.begin(); while(it != topk.end()) { lowerbound_array.push_back(it->first); ++it; } } // init void init() { // clear top-k in pre-processing topk.clear(); // clear threshold in pre-processing threshold = 0; } bool operator <(const data &d) const { return norm < d.norm; } bool operator >(const data &d) const { return norm > d.norm; } }; // set of query & item vectors std::vector<data> query_set, item_set; // definition of block class block{ public: unsigned int identifier = 0; std::vector<data*> member; std::vector<float> lowerbound_array; // constructor block() { lowerbound_array.resize(k_max); for (unsigned int i = 0; i < k_max; ++i) lowerbound_array[i] = FLT_MAX; } // init void init() { // increment identifier ++identifier; // clear member member.clear(); // init array for (unsigned int i = 0; i < k_max; ++i) lowerbound_array[i] = FLT_MAX; } // make lower-bound array void update_lowerbound_array() { for (unsigned int i = 0; i < k_max; ++i) { for (unsigned int j = 0; j < member.size(); ++j) { if (lowerbound_array[i] > member[j]->lowerbound_array[i]) lowerbound_array[i] = member[j]->lowerbound_array[i]; } } } }; // set of blocks std::vector<block> block_set; // input matrix void input_matrix() { // file-name std::string f_name; data query, item; std::mt19937_64 mt(1); std::uniform_real_distribution<> uni_rnd(0,1); if (dataset_id == 0 || dataset_id == 1 || dataset_id == 2 || dataset_id == 3) { if (dataset_id == 0) f_name = "dataset/movielens_mf-50.txt"; if (dataset_id == 1) f_name = "dataset/netflix_mf-50.txt"; if (dataset_id == 2) f_name = "dataset/yahoosong_mf-50.txt"; if (dataset_id == 3) f_name = "dataset/amazon_mf-50.txt"; // file input std::ifstream ifs_file(f_name); std::string full_data; // error detection if (ifs_file.fail()) { std::cout << " file does not exist." << std::endl; std::exit(0); } while (std::getline(ifs_file, full_data)) { std::string meta_info; std::istringstream stream(full_data); std::string type = ""; std::string flag = ""; std::vector<float> vector_query, vector_item; for (unsigned int i = 0; i < dimensionality + 3; ++i) { std::getline(stream, meta_info, ' '); std::istringstream stream_(meta_info); double val = 0; switch (i) { case 0: // obtain user or item type = meta_info; break; case 1: // obtain T or F flag = meta_info; break; default: // obtain value if (meta_info != "") { val = std::stof(meta_info); if (type[0] == 'p') vector_query.push_back(val); if (type[0] == 'q') vector_item.push_back(val); } break; } if (flag == "F") break; } // store vector if (flag == "T") { if (type[0] == 'p') { if (uni_rnd(mt) <= sampling_rate) { query.vec = vector_query; query_set.push_back(query); ++query.identifier; } } if (type[0] == 'q') { item.vec = vector_item; item_set.push_back(item); ++item.identifier; } } } } }
18.425339
115
0.606336
amgt-d1
fd34a6a5226121bc4da851ab3005d0ca3d714c47
749
cpp
C++
other-small-sources/nooby_mistakes.cpp
Nickeron-dev/Basics-Of-CPP
84e2cd50c9bd466830054715a1cd708f87311e7b
[ "Apache-2.0" ]
1
2021-09-15T15:11:39.000Z
2021-09-15T15:11:39.000Z
other-small-sources/nooby_mistakes.cpp
Nickeron-dev/Basics-Of-CPP
84e2cd50c9bd466830054715a1cd708f87311e7b
[ "Apache-2.0" ]
null
null
null
other-small-sources/nooby_mistakes.cpp
Nickeron-dev/Basics-Of-CPP
84e2cd50c9bd466830054715a1cd708f87311e7b
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <string> int main() { // variables are not initialised(only defined) // so undefined behaviour will be there(values cannot be predicted) int x; int *x2 = new int; // OK. initial value 0 is guaranteed int y {}; int *y1 = new int{}; int *y2 = new int(); int z(); // The same works with structs and classes struct S { int n, m; std::string s; }; // int values - undefined behavious, // but std::string is defined to "" (empty string) S instance; S *instance1 = new S; // int values - initialized to 0 // but std::string is defined to "" (empty string) S s1 {}; S *s2 = new S{}; S *s3 = new S(); delete x2; delete y1; delete y2; delete instance1; delete s2; delete s3; return 0; }
16.282609
68
0.631509
Nickeron-dev
fd3a18b424c5449d31d34ae7ffdd756b86f1b175
1,691
hpp
C++
rmf_traffic_ros2/include/rmf_traffic_ros2/StandardNames.hpp
Yadunund/rmf_core
90e9871ce595c53dfbc0f4f16dc00192f7a9fbcf
[ "Apache-2.0" ]
null
null
null
rmf_traffic_ros2/include/rmf_traffic_ros2/StandardNames.hpp
Yadunund/rmf_core
90e9871ce595c53dfbc0f4f16dc00192f7a9fbcf
[ "Apache-2.0" ]
1
2020-06-12T08:57:11.000Z
2020-06-17T11:29:33.000Z
rmf_traffic_ros2/include/rmf_traffic_ros2/StandardNames.hpp
Yadunund/rmf_core
90e9871ce595c53dfbc0f4f16dc00192f7a9fbcf
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2019 Open Source Robotics Foundation * * 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 RMF_TRAFFIC_ROS2__STANDARDNAMES_HPP #define RMF_TRAFFIC_ROS2__STANDARDNAMES_HPP #include <string> namespace rmf_traffic_ros2 { const std::string Prefix = "rmf_traffic/"; const std::string SubmitTrajectoriesSrvName = Prefix + "submit_trajectories"; const std::string ReplaceTrajectoriesSrvName = Prefix + "replace_trajectories"; const std::string DelayTrajectoriesSrvName = Prefix + "delay_trajectories"; const std::string EraseTrajectoriesSrvName = Prefix + "erase_trajectories"; const std::string ResolveConflictsSrvName = Prefix + "resolve_conflicts"; const std::string RegisterQueryServiceName = Prefix + "register_query"; const std::string UnregisterQueryServiceName = Prefix + "unregister_query"; const std::string MirrorUpdateServiceName = Prefix + "mirror_update"; const std::string MirrorWakeupTopicName = Prefix + "mirror_wakeup"; const std::string ScheduleConflictTopicName = Prefix + "schedule_conflict"; const std::string EmergencyTopicName = "fire_alarm_trigger"; } // namespace rmf_traffic_ros2 #endif // RMF_TRAFFIC_ROS2__STANDARDNAMES_HPP
40.261905
79
0.786517
Yadunund
fd3c6821607f3a9ab94f431531e10da9c2fa4072
3,590
hpp
C++
src/core/constant_buffers.hpp
SleepKiller/shaderpatch
4bda848df0273993c96f1d20a2cf79161088a77d
[ "MIT" ]
13
2019-03-25T09:40:12.000Z
2022-03-13T16:12:39.000Z
src/core/constant_buffers.hpp
SleepKiller/shaderpatch
4bda848df0273993c96f1d20a2cf79161088a77d
[ "MIT" ]
110
2018-10-16T09:05:43.000Z
2022-03-16T23:32:28.000Z
src/core/constant_buffers.hpp
SleepKiller/shaderpatch
4bda848df0273993c96f1d20a2cf79161088a77d
[ "MIT" ]
1
2020-02-06T20:32:50.000Z
2020-02-06T20:32:50.000Z
#pragma once #include <array> #include <cstddef> #include <cstdint> #include <glm/glm.hpp> namespace sp::core::cb { // Evil macro. Takes the type of the constant buffer and the first non-game // constant in the type and returns the number of game constants in the buffer. #define CB_MAX_GAME_CONSTANTS(Type, first_patch_constant) \ (sizeof(Type) - (sizeof(Type) - offsetof(Type, first_patch_constant))) / \ sizeof(glm::vec4); struct Scene_tag { }; struct Draw_tag { }; struct Fixedfunction_tag { }; struct Skin_tag { }; struct Draw_ps_tag { }; static constexpr Scene_tag scene{}; static constexpr Draw_tag draw{}; static constexpr Fixedfunction_tag fixedfunction{}; static constexpr Skin_tag skin{}; static constexpr Draw_ps_tag draw_ps{}; struct alignas(16) Scene { std::array<glm::vec4, 4> projection_matrix; glm::vec3 vs_view_positionWS; float _padding0; glm::vec4 fog_info; float near_scene_fade_scale; float near_scene_fade_offset; float vs_lighting_scale; std::uint32_t _padding1{}; std::array<glm::vec4, 3> shadow_map_transform; glm::vec2 pixel_offset; std::uint32_t input_color_srgb; float time; std::uint32_t particle_texture_scale; float prev_near_scene_fade_scale; float prev_near_scene_fade_offset; std::uint32_t _padding2{}; }; constexpr auto scene_game_count = CB_MAX_GAME_CONSTANTS(Scene, pixel_offset); static_assert(sizeof(Scene) == 192); static_assert(scene_game_count == 10); struct alignas(16) Draw { glm::vec4 normaltex_decompress; glm::vec4 position_decompress_min; glm::vec4 position_decompress_max; glm::vec4 color_state; std::array<glm::vec4, 3> world_matrix; glm::vec4 light_ambient_color_top; glm::vec4 light_ambient_color_bottom; glm::vec4 light_directional_0_color; glm::vec4 light_directional_0_dir; glm::vec4 light_directional_1_color; glm::vec4 light_directional_1_dir; glm::vec4 light_point_0_color; glm::vec4 light_point_0_pos; glm::vec4 light_point_1_color; glm::vec4 light_point_1_pos; glm::vec4 overlapping_lights[4]; glm::vec4 light_proj_color; glm::vec4 light_proj_selector; std::array<glm::vec4, 4> light_proj_matrix; glm::vec4 material_diffuse_color; glm::vec4 custom_constants[9]; }; constexpr auto draw_game_count = sizeof(Draw) / 16; static_assert(sizeof(Draw) == 592); static_assert(draw_game_count == 37); struct alignas(16) Fixedfunction { glm::vec4 texture_factor; glm::vec2 inv_resolution; std::array<float, 2> _buffer_padding; }; static_assert(sizeof(Fixedfunction) == 32); struct alignas(16) Skin { std::array<std::array<glm::vec4, 3>, 15> bone_matrices; }; constexpr auto skin_game_count = sizeof(Skin) / 16; static_assert(sizeof(Skin) == 720); static_assert(skin_game_count == 45); struct alignas(16) Draw_ps { std::array<glm::vec4, 5> ps_custom_constants; glm::vec3 ps_view_positionWS; float ps_lighting_scale; glm::vec4 rt_resolution; // x = width, y = height, z = 1 / width, w = 1 / height glm::vec3 fog_color; std::uint32_t light_active = 0; std::uint32_t light_active_point_count = 0; std::uint32_t light_active_spot = 0; std::uint32_t additive_blending; std::uint32_t cube_projtex; std::uint32_t fog_enabled; std::uint32_t limit_normal_shader_bright_lights; std::uint32_t input_color_srgb; float time_seconds; }; constexpr auto draw_ps_game_count = CB_MAX_GAME_CONSTANTS(Draw_ps, ps_view_positionWS); static_assert(sizeof(Draw_ps) == 160); static_assert(draw_ps_game_count == 5); #undef CB_MAX_GAME_CONSTANTS }
27.829457
87
0.741504
SleepKiller
fd3f817910eab22d6cd2b608d523b875b07a4110
395
hpp
C++
include/modules/waterAdditionControl/actionCreators/messages/AddionalWaterTankEmptyingTimeout.hpp
thebartekbanach/simple-aqua-controller
338331072155b9f98fb07b6a1e31e6d3c1f650fa
[ "MIT" ]
1
2019-11-18T13:22:57.000Z
2019-11-18T13:22:57.000Z
include/modules/waterAdditionControl/actionCreators/messages/AddionalWaterTankEmptyingTimeout.hpp
thebartekbanach/simple-aqua-controller
338331072155b9f98fb07b6a1e31e6d3c1f650fa
[ "MIT" ]
null
null
null
include/modules/waterAdditionControl/actionCreators/messages/AddionalWaterTankEmptyingTimeout.hpp
thebartekbanach/simple-aqua-controller
338331072155b9f98fb07b6a1e31e6d3c1f650fa
[ "MIT" ]
null
null
null
#pragma once #include "../../../../utils/informationBanner/InformationBannerActionCreator.hpp" InformationBannerActionCreator* addionalWaterTankEmptyingTimeoutMessage(ActionCreator* target = nullptr) { return new InformationBannerActionCreator(target, 0, true, " Uwaga: timeout", " oproznienia wody w", "zbiorniku rezerwowym", " Sprawdz zawory" ); }
32.916667
106
0.701266
thebartekbanach
fd41be035b030017b44edf23576823b680b00e14
1,472
cpp
C++
FWCoreLibrary/TPMLogger.cpp
terilenard/dias-firewall
b836f1180ef187e6f1bb597f8666165f9f4fa082
[ "MIT" ]
null
null
null
FWCoreLibrary/TPMLogger.cpp
terilenard/dias-firewall
b836f1180ef187e6f1bb597f8666165f9f4fa082
[ "MIT" ]
null
null
null
FWCoreLibrary/TPMLogger.cpp
terilenard/dias-firewall
b836f1180ef187e6f1bb597f8666165f9f4fa082
[ "MIT" ]
null
null
null
#include "TPMLogger.h" #include "Config.h" #ifndef WIN32 #include <sys/types.h> #include <sys/stat.h> #include <sys/errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #endif TPMLogger::TPMLogger(const char* pszCfgFile): m_fd(-1), m_sCfgFile(pszCfgFile) { } TPMLogger::~TPMLogger() { #ifndef WIN32 if (m_fd != -1) { close(m_fd); } #endif } bool TPMLogger::initialize(void) { #ifndef WIN32 const char* fifo; fifo = getParameter(m_sCfgFile.c_str(),"tpmPipe"); if (!fifo) { printf("Error while reading pipe path from config file\n"); return false; } printf("Found TPM named pipe: %s\n", fifo); // Create the named pipe, read and write rights only for the owner int result = mkfifo(fifo, S_IFIFO | S_IRUSR | S_IWUSR); if (-1 == result && EEXIST != errno) { perror("The creation of the named pipe failed!\n"); return false; } m_fd = open(fifo, O_WRONLY); if (-1 == m_fd) { perror("Unable to open the fifo for writing!\n"); return false; } #endif return true; } bool TPMLogger::logMessage(const string& msg) { #ifndef WIN32 if (-1 == m_fd) { return false; } if (write(m_fd, msg.c_str(), msg.size() + 1) < 0) { perror("Unable to write log message!"); return false; } printf("Message '%s' was sent to TPM for logging!\n", msg.c_str()); #endif return true; }
18.632911
71
0.600543
terilenard