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
9a39d79751778014da3e9ac19d7e7ca4a3feed88
8,704
cpp
C++
tool-dfxcli/src/ConfigCommand.cpp
nuralogix/dfx-api-client-cpp
6b45307ddf4b0036c107eebd7e8915f6c501c3b0
[ "MIT" ]
null
null
null
tool-dfxcli/src/ConfigCommand.cpp
nuralogix/dfx-api-client-cpp
6b45307ddf4b0036c107eebd7e8915f6c501c3b0
[ "MIT" ]
null
null
null
tool-dfxcli/src/ConfigCommand.cpp
nuralogix/dfx-api-client-cpp
6b45307ddf4b0036c107eebd7e8915f6c501c3b0
[ "MIT" ]
null
null
null
// Copyright (c) Nuralogix. All rights reserved. Licensed under the MIT license. // See LICENSE.txt in the project root for license information. #include "dfx/api/cli/ConfigCommand.hpp" #include "nlohmann/json.hpp" using nlohmann::json; ConfigViewCommand::ConfigViewCommand(CLI::App* config, std::shared_ptr<Options> options, DFXExitCode& result) : DFXAppCommand(std::move(options)), full(false) { cmd = config->add_subcommand("view", "Display current configuration"); cmd->alias("show"); cmd->add_flag("-f,--full", full, "Show full details without obfuscation")->capture_default_str(); cmd->callback([&]() { result = DFXAppCommand::execute(loadConfig()); }); } DFXExitCode ConfigViewCommand::execute() { json response = {{"context", config.contextID}, {"transport-type", config.transportType}, {"host", config.serverHost}, {"port", config.serverPort}, {"secure", config.secure}, {"skip-verify", config.skipVerify}}; if (!config.authEmail.empty()) { response["auth-email"] = config.authEmail; } if (!config.authPassword.empty()) { response["auth-password"] = (full ? config.authPassword : "OBFUSCATED"); } if (!config.authOrg.empty()) { response["auth-org"] = config.authOrg; } if (!config.license.empty()) { response["license"] = (full ? config.license : "OBFUSCATED"); } if (!config.studyID.empty()) { response["study-id"] = config.studyID; } if (!config.authToken.empty()) { response["auth-token"] = (full ? config.authToken : "OBFUSCATED"); } if (!config.deviceToken.empty()) { response["device-token"] = (full ? config.deviceToken : "OBFUSCATED"); } if (!config.rootCA.empty()) { response["root-ca"] = config.rootCA; } response["list-limit"] = config.listLimit; response["timeout"] = config.timeoutMillis; outputResponse(response); return DFXExitCode::SUCCESS; } ConfigListCommand::ConfigListCommand(CLI::App* config, std::shared_ptr<Options> options, DFXExitCode& result) : DFXAppCommand(std::move(options)) { cmd = config->add_subcommand("list", "List available config contexts"); cmd->alias("ls"); cmd->callback([&]() { result = execute(); }); } DFXExitCode ConfigListCommand::execute() { std::string defaultContext; std::vector<std::string> contextNames; auto status = dfx::api::getAvailableContexts(options->configFilePath, defaultContext, contextNames); if (!status.OK()) { outputError(status); return DFXExitCode::FAILURE; } // If user is overloading on the command line, mark that context as the default CLI::App* app = cmd; while (app && app->get_parent()) { app = app->get_parent(); } auto contextOpt = app->get_option_no_throw("--context"); if (contextOpt != nullptr && contextOpt->count() > 0) { defaultContext = options->context; } json response = json::array(); for (auto& name : contextNames) { json context = {{"context", name}}; context["default"] = name.compare(defaultContext) == 0; response.push_back(context); } outputResponse(response); return DFXExitCode::SUCCESS; } ConfigSampleCommand::ConfigSampleCommand(CLI::App* config, std::shared_ptr<Options> options, DFXExitCode& result) : DFXAppCommand(std::move(options)), advanced(false) { cmd = config->add_subcommand("sample", "Write sample YAML config to stdout"); cmd->add_flag("-a,--advanced", advanced, "Show an advanced sample format with multiple contexts"); cmd->callback([&]() { result = execute(); }); } DFXExitCode ConfigSampleCommand::execute() { if (!advanced) { // Basic example format std::cout << "# DFX Sample YAML Configuration File (basic)\n" << "# Save this default to: ~/.dfxcloud.yaml\n" << "\n" << "# This file contains only one configuration, to use multiple look at\n" << "# the advanced configuration layout example.\n" << "\n" << "host: api.deepaffex.ai\n" << "\n" << "auth-email: your-email-id\n" << "auth-password: your-password\n" << "auth-org: your-org-identifier\n" << "license: your-license\n" << "study-id: study-id # (Optional) Used for operations requiring\n" << "\n" << "# If the below tokens are present, you do not require email, password, org, license\n" << "#auth-token: your-auth-token # (Optional) Reusable from ./dfxcli login\n" << "#device-token: your-device-token # (Optional) Reusable from ./dfxcli register\n" << std::endl; } else { std::cout << "# DFX Sample YAML Configuration File (advanced)\n" << "# Save this default to: ~/.dfxcloud.yaml\n" << "\n" << "# This file can contain multiple contexts and this provides the default context\n" << "# name to use when loading. Context can be overridden on command line with --context.\n" << "context: rest # default context name to use\n" << "\n" << "# Place defaults here which apply to all services or contexts and\n" << "# explicitly override as needed for individual services or contexts\n" << "verbose: 2\n" << "timeout: 3000 # 3 seconds\n" << "list-limit: 25 # Maximum number of records returned for list calls. Default: 25\n" << "auth-email: your-email-id # defining below is optional if here\n" << "\n" << "# Services define the end-point hosts and can be cloud instances or\n" << "# standalone devices. They are used by contexts to provide host/port details.\n" << "services:\n" << " - name: v2-rest\n" << " host: api.deepaffex.ai\n" << " transport-type: REST\n" << " - name: v2-websocket\n" << " host: api.deepaffex.ai\n" << " #skip-verify: true # If TLS/SSL handshake can skip verification. Default: false\n" << " transport-type: WEBSOCKET\n" << " - name: v3-grpc\n" << " host: local-server.deepaffex.ai\n" << " port: 8443\n" << " transport-type: GRPC\n" << "\n" << "# Contexts provide the authentication details and link to the service hosts\n" << "contexts:\n" << " - name: rest\n" << " service: v2-rest # links to service host/port name above\n" << " auth-email: your-email-id\n" << " auth-password: your-secret-password\n" << " auth-org: your-org-identifier\n" << " license: your-license\n" << " study-id: study-id # (Optional) Used for operations requiring\n" << "\n" << " # Tokens can be cached in config to avoid login/register/unregister/logout on every request\n" << " # if provided, auth-email, auth-password, auth-org, license are optional\n" << " #auth-token: your-auth-token # (Optional) Reusable from ./dfxcli login\n" << " #device-token: your-device-token # (Optional) Reusable from ./dfxcli register\n" << "\n" << " - name: websocket\n" << " service: v2-websocket\n" << " auth-email: your-email-id\n" << " auth-password: your-secret-password\n" << " auth-org: your-org-identifier\n" << " license: your-license\n" << " study-id: study-id\n" << "\n" << " - name: grpc\n" << " service: v3-grpc\n" << " auth-email: your-email-id\n" << " auth-password: your-secret-password\n" << " auth-org: your-org-identifier\n" << " license: your-license\n" << " study-id: study-id\n"; } return DFXExitCode::SUCCESS; }
46.05291
120
0.534352
nuralogix
9a429a6662ec32856578f6b9347a6c613aa54248
5,250
cc
C++
src/remote_adapter/remote_adapter_client/hmi_adapter/lua_lib/hmi_adapter_client_lua_wrapper.cc
LuxoftSDL/sdl_atf
454487dafdc422db724cceb02827a6738e93203b
[ "BSD-3-Clause" ]
6
2016-03-04T20:27:37.000Z
2021-11-06T08:05:00.000Z
src/remote_adapter/remote_adapter_client/hmi_adapter/lua_lib/hmi_adapter_client_lua_wrapper.cc
smartdevicelink/sdl_atf
08354ae6633169513639a3d9257acd1229a5caa2
[ "BSD-3-Clause" ]
122
2016-03-09T20:03:50.000Z
2022-01-31T14:26:36.000Z
src/remote_adapter/remote_adapter_client/hmi_adapter/lua_lib/hmi_adapter_client_lua_wrapper.cc
smartdevicelink/sdl_atf
08354ae6633169513639a3d9257acd1229a5caa2
[ "BSD-3-Clause" ]
41
2016-03-10T09:34:00.000Z
2020-12-01T09:08:24.000Z
#include "hmi_adapter/lua_lib/hmi_adapter_client_lua_wrapper.h" #include <iostream> #include "common/constants.h" #include "hmi_adapter/hmi_adapter_client.h" #include "rpc/detail/log.h" namespace lua_lib { RPCLIB_CREATE_LOG_CHANNEL(HmiAdapterClientLuaWrapper) int HmiAdapterClientLuaWrapper::create_SDLRemoteTestAdapter(lua_State *L) { LOG_INFO("{0}", __func__); luaL_checktype(L, 1, LUA_TTABLE); // Index -1(top) - table shm_params_array // Index -2 - table out_params // Index -3 - table in_params // Index -4 - RemoteClient instance // index -5 - Library table auto tcp_params = build_TCPParams(L); lua_pop(L, 1); // Remove value from the top of the stack // Index -1(top) - table in_params // Index -2 - RemoteClient instance // Index -3 - Library table RemoteClient **user_data = reinterpret_cast<RemoteClient **>(luaL_checkudata(L, 2, "RemoteClient")); if (nullptr == user_data) { std::cout << "RemoteClient was not found" << std::endl; return 0; } RemoteClient *client = *user_data; lua_pop(L, 1); // Remove value from the top of the stack // Index -1(top) - Library table try { HmiAdapterClient *qt_client = new HmiAdapterClient(client, tcp_params); // Allocate memory for a pointer to client object HmiAdapterClient **s = (HmiAdapterClient **)lua_newuserdata(L, sizeof(HmiAdapterClient *)); // Index -1(top) - instance userdata // Index -2 - Library table *s = qt_client; } catch (std::exception &e) { std::cout << "Exception occurred: " << e.what() << std::endl; lua_pushnil(L); // Index -1(top) - nil // Index -2 - Library table return 1; } HmiAdapterClientLuaWrapper::registerSDLRemoteTestAdapter(L); // Index -1 (top) - registered SDLRemoteTestAdapter metatable // Index -2 - instance userdata // Index -3 - Library table lua_setmetatable(L, -2); // Set class table as metatable for instance userdata // Index -1(top) - instance table // Index -2 - Library table return 1; } int HmiAdapterClientLuaWrapper::destroy_SDLRemoteTestAdapter(lua_State *L) { LOG_INFO("{0}", __func__); auto instance = get_instance(L); delete instance; return 0; } void HmiAdapterClientLuaWrapper::registerSDLRemoteTestAdapter(lua_State *L) { LOG_INFO("{0}", __func__); static const luaL_Reg SDLRemoteTestAdapterFunctions[] = { {"connect", HmiAdapterClientLuaWrapper::lua_connect}, {"write", HmiAdapterClientLuaWrapper::lua_write}, {NULL, NULL}}; luaL_newmetatable(L, "HmiAdapterClient"); // Index -1(top) - SDLRemoteTestAdapter metatable lua_newtable(L); // Index -1(top) - created table // Index -2 : SDLRemoteTestAdapter metatable luaL_setfuncs(L, SDLRemoteTestAdapterFunctions, 0); // Index -1(top) - table with SDLRemoteTestAdapterFunctions // Index -2 : SDLRemoteTestAdapter metatable lua_setfield(L, -2, "__index"); // Setup created table as index lookup for metatable // Index -1(top) - SDLRemoteTestAdapter metatable lua_pushcfunction(L, HmiAdapterClientLuaWrapper::destroy_SDLRemoteTestAdapter); // Index -1(top) - destroy_SDLRemoteTestAdapter function pointer // Index -2 - SDLRemoteTestAdapter metatable lua_setfield(L, -2, "__gc"); // Set garbage collector function to metatable // Index -1(top) - SDLRemoteTestAdapter metatable } HmiAdapterClient *HmiAdapterClientLuaWrapper::get_instance(lua_State *L) { LOG_INFO("{0}", __func__); // Index 1 - lua instance HmiAdapterClient **user_data = reinterpret_cast<HmiAdapterClient **>( luaL_checkudata(L, 1, "HmiAdapterClient")); if (nullptr == user_data) { return nullptr; } return *user_data; //*((HmiAdapterClient**)ud); } std::vector<parameter_type> HmiAdapterClientLuaWrapper::build_TCPParams(lua_State *L) { LOG_INFO("{0}", __func__); // Index -1(top) - table params lua_getfield(L, -1, "host"); // Pushes onto the stack the value params[host] // Index -1(top) - string host // Index -2 - table params const char *host = lua_tostring(L, -1); lua_pop(L, 1); // remove value from the top of the stack // Index -1(top) - table params lua_getfield(L, -1, "port"); // Pushes onto the stack the value params[port] // Index -1(top) - number port // Index -2 - table params const int port = lua_tointeger(L, -1); lua_pop(L, 1); // Remove value from the top of the stack // Index -1(top) - table params std::vector<parameter_type> TCPParams; TCPParams.push_back( std::make_pair(std::string(host), constants::param_types::STRING)); TCPParams.push_back( std::make_pair(std::to_string(port), constants::param_types::INT)); return TCPParams; } int HmiAdapterClientLuaWrapper::lua_connect(lua_State *L) { LOG_INFO("{0}", __func__); // Index -1(top) - table instance auto instance = get_instance(L); instance->connect(); return 0; } int HmiAdapterClientLuaWrapper::lua_write(lua_State *L) { LOG_INFO("{0}", __func__); // Index -1(top) - string data // Index -2 - table instance auto instance = get_instance(L); auto data = lua_tostring(L, -1); int result = instance->send(data); lua_pushinteger(L, result); return 1; } } // namespace lua_lib
29.829545
80
0.689714
LuxoftSDL
9a4c545f7d7970ebd62784026561a3524d260312
1,288
cpp
C++
src/Cyril/Ops/CyrilPaletteItem.cpp
danhett/cyril
38702d3334bdce56b2a4fcabcf4fd43dd08d6f95
[ "MIT" ]
87
2016-05-14T22:43:32.000Z
2021-12-19T04:33:20.000Z
src/Cyril/Ops/CyrilPaletteItem.cpp
danhett/cyril
38702d3334bdce56b2a4fcabcf4fd43dd08d6f95
[ "MIT" ]
15
2016-05-10T12:49:13.000Z
2020-04-15T12:21:52.000Z
src/Cyril/Ops/CyrilPaletteItem.cpp
danhett/cyril
38702d3334bdce56b2a4fcabcf4fd43dd08d6f95
[ "MIT" ]
12
2016-05-16T22:56:19.000Z
2022-01-06T22:45:06.000Z
// // CyrilPaletteItem.cpp // cyril2 // // Created by Darren Mothersele on 06/11/2013. // // #include "CyrilPaletteItem.h" CyrilPaletteItem::CyrilPaletteItem(float _f, Cyril* _e) : d(_f), e(_e) { /* string converter(_s); stringstream sr(converter.substr(0,2)); stringstream sg(converter.substr(2,2)); stringstream sb(converter.substr(4,2)); int ir, ig, ib; sr >> hex >> ir; sg >> hex >> ig; sb >> hex >> ib; r = ir; g = ig; b = ib; */ int sz = _e->size(); if (!(sz == 3)) { yyerror("Palette item requires 3 arguments"); valid = false; } paletteCalc = false; } CyrilPaletteItem::CyrilPaletteItem (const CyrilPaletteItem &other) { d = other.d; r = other.r; g = other.g; b = other.b; } CyrilPaletteItem::~CyrilPaletteItem () { } void CyrilPaletteItem::print() { cout << "PaletteItem" << endl; } Cyril * CyrilPaletteItem::clone () { return new CyrilPaletteItem (*this); } int CyrilPaletteItem::size() { return 4; } void CyrilPaletteItem::eval(CyrilState &_s) { if (!paletteCalc) { e->eval(_s); b = _s.stk->top(); _s.stk->pop(); g = _s.stk->top(); _s.stk->pop(); r = _s.stk->top(); _s.stk->pop(); paletteCalc = true; } _s.stk->push(r); _s.stk->push(g); _s.stk->push(b); _s.stk->push(d); }
18.666667
72
0.599379
danhett
9a532ceacb03eda34f93e2483ea1039b1af28261
1,879
cpp
C++
src/entity_systems/ffi_layer.cpp
mokoi/luxengine
965532784c4e6112141313997d040beda4b56d07
[ "MIT" ]
11
2015-03-02T07:43:00.000Z
2021-12-04T04:53:02.000Z
src/entity_systems/ffi_layer.cpp
mokoi/luxengine
965532784c4e6112141313997d040beda4b56d07
[ "MIT" ]
1
2015-03-28T17:17:13.000Z
2016-10-10T05:49:07.000Z
src/entity_systems/ffi_layer.cpp
mokoi/luxengine
965532784c4e6112141313997d040beda4b56d07
[ "MIT" ]
3
2016-11-04T01:14:31.000Z
2020-05-07T23:42:27.000Z
/**************************** Copyright © 2014 Luke Salisbury This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ****************************/ #include "ffi_layer.h" #include "ffi_functions.h" #include "display/display.h" #include "elix/elix_endian.hpp" /** * @brief Lux_FFI_Layer_Rotation * @param layer * @param roll * @param pitch * @param yaw */ void Lux_FFI_Layer_Rotation( int8_t layer, int16_t roll, int16_t pitch, int16_t yaw ) { lux::display->ChangeLayerRotation( layer, roll, pitch, yaw ); } /** * @brief Lux_FFI_Layer_Offset * @param layer * @param x * @param y */ void Lux_FFI_Layer_Offset( int8_t layer, int32_t fixed_x, int32_t fixed_y ) { if ( layer == -1) lux::display->SetCameraView( (fixed)fixed_x, (fixed)fixed_y ); else lux::display->SetCameraView( layer, (fixed)fixed_x, (fixed)fixed_y ); } /** * @brief Lux_FFI_Layer_Colour * @param layer * @param colour */ void Lux_FFI_Layer_Colour( int8_t layer, uint32_t colour) { cell_colour temp_colour; temp_colour.hex = elix::endian::host32( colour ); if ( layer >= 0 ) lux::display->SetLayerColour( layer, temp_colour.rgba ); }
33.553571
243
0.728579
mokoi
9a54d2abbb11bce9c69996a17f854e121989a061
828
hpp
C++
detail/itoa.hpp
isadchenko/brig
3e65a44fa4b8690cdfa8bdaca08d560591afcc38
[ "MIT" ]
null
null
null
detail/itoa.hpp
isadchenko/brig
3e65a44fa4b8690cdfa8bdaca08d560591afcc38
[ "MIT" ]
null
null
null
detail/itoa.hpp
isadchenko/brig
3e65a44fa4b8690cdfa8bdaca08d560591afcc38
[ "MIT" ]
null
null
null
// Andrew Naplavkov // http://stackoverflow.com/questions/6713420/c-convert-integer-to-string-at-compile-time #ifndef BRIG_DETAIL_ITOA_HPP #define BRIG_DETAIL_ITOA_HPP #include <boost/mpl/string.hpp> #include <string> namespace brig { namespace detail { template <bool Top, size_t N> struct itoa_impl { typedef typename ::boost::mpl::push_back<typename itoa_impl<false, N / 10>::type, ::boost::mpl::char_<'0' + N % 10>>::type type; }; template <> struct itoa_impl<false, 0> { typedef ::boost::mpl::string<> type; }; template <> struct itoa_impl<true, 0> { typedef ::boost::mpl::string<'0'> type; }; template <size_t N> struct itoa { typedef typename ::boost::mpl::c_str<typename itoa_impl<true, N>::type>::type type; }; } } // brig::detail #endif // BRIG_DETAIL_ITOA_HPP
20.7
131
0.672705
isadchenko
9a591b4a1748d455b834f77cb6f9839b65a2b4a1
6,382
cc
C++
lib/correspondence.cc
dbs4261/smvs
5a4ff04d7642a354c543ffadbead14c4be73918e
[ "BSD-3-Clause" ]
null
null
null
lib/correspondence.cc
dbs4261/smvs
5a4ff04d7642a354c543ffadbead14c4be73918e
[ "BSD-3-Clause" ]
null
null
null
lib/correspondence.cc
dbs4261/smvs
5a4ff04d7642a354c543ffadbead14c4be73918e
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2017, Fabian Langguth * TU Darmstadt - Graphics, Capture and Massively Parallel Computing * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD 3-Clause license. See the LICENSE.txt file for details. */ #include "correspondence.h" namespace smvs { Correspondence::Correspondence (mve::math::Matrix3d const& M, mve::math::Vec3d const& t, double u, double v, double w, double w_dx, double w_dy) { this->update(M, t, u, v, w, w_dx, w_dy); } void Correspondence::update (mve::math::Matrix3d const& M, mve::math::Vec3d const& t, double u, double v, double w, double w_dx, double w_dy) { this->t = t; this->w = w; this->p_prime[0] = M(0,0); this->p_prime[1] = M(0,1); this->q_prime[0] = M(1,0); this->q_prime[1] = M(1,1); this->r_prime[0] = M(2,0); this->r_prime[1] = M(2,1); this->w_prime[0] = w_dx; this->w_prime[1] = w_dy; this->p = M(0,0) * u + M(0,1) * v + M(0,2); this->q = M(1,0) * u + M(1,1) * v + M(1,2); this->r = M(2,0) * u + M(2,1) * v + M(2,2); this->a = w * p + t[0]; this->b = w * q + t[1]; this->d = w * r + t[2]; this->d2 = d * d; } void Correspondence::fill (double * corr) const { corr[0] = a / d; corr[1] = b / d; } void Correspondence::get_derivative ( double const* dn00, double const* dn10, double const* dn01, double const* dn11, mve::math::Vec2d * c_dn00, mve::math::Vec2d * c_dn10, mve::math::Vec2d * c_dn01, mve::math::Vec2d * c_dn11) const { double du_w = (p * d - r * a) / d2; double dv_w = (q * d - r * b) / d2; for (int i = 0; i < 4; ++i) { c_dn00[i] = mve::math::Vec2d(du_w, dv_w) * dn00[i]; c_dn10[i] = mve::math::Vec2d(du_w, dv_w) * dn10[i]; c_dn01[i] = mve::math::Vec2d(du_w, dv_w) * dn01[i]; c_dn11[i] = mve::math::Vec2d(du_w, dv_w) * dn11[i]; } } void Correspondence::fill_derivative (double const* dn, mve::math::Vec2d * c_dn) const { double du_w = (p * d - r * a) / d2; double dv_w = (q * d - r * b) / d2; for (int n = 0; n < 4; ++n) for (int i = 0; i < 4; ++i) { c_dn[n * 4 + i][0] = du_w * dn[n * 24 + i]; c_dn[n * 4 + i][1] = dv_w * dn[n * 24 + i]; } } void Correspondence::fill_jacobian(double * jac) const { jac[0] = (w_prime[0] * p + w * p_prime[0]) / d; jac[2] = (w_prime[1] * p + w * p_prime[1]) / d; jac[0] -= a * (w_prime[0] * r + w * r_prime[0]) / d2; jac[2] -= a * (w_prime[1] * r + w * r_prime[1]) / d2; jac[1] = (w_prime[0] * q + w * q_prime[0]) / d; jac[3] = (w_prime[1] * q + w * q_prime[1]) / d; jac[1] -= b * (w_prime[0] * r + w * r_prime[0]) / d2; jac[3] -= b * (w_prime[1] * r + w * r_prime[1]) / d2; } void Correspondence::fill_jacobian_derivative_grad(double const* grad, double const* dn, mve::math::Vec2d * jac_dn) const { double d4 = d2 * d2; double d_prime = 2.0 * d * r; mve::math::Vec2d du_a_temp; du_a_temp[0] = w * (p_prime[0] * r - p * r_prime[0]); du_a_temp[1] = w * (p_prime[1] * r - p * r_prime[1]); mve::math::Vec2d du_a_prime; du_a_prime[0] = 2.0 * du_a_temp[0]; du_a_prime[1] = 2.0 * du_a_temp[1]; mve::math::Vec2d du_b_prime; du_b_prime[0] = (p_prime[0] * t[2] - r_prime[0] * t[0]); du_b_prime[1] = (p_prime[1] * t[2] - r_prime[1] * t[0]); double du_c_prime = (p * t[2] - r * t[0]); mve::math::Vec2d du_c; du_c[0] = w_prime[0] * du_c_prime; du_c[1] = w_prime[1] * du_c_prime; mve::math::Vec2d dv_a_temp; dv_a_temp[0] = w * (q_prime[0] * r - q * r_prime[0]); dv_a_temp[1] = w * (q_prime[1] * r - q * r_prime[1]); mve::math::Vec2d dv_a_prime; dv_a_prime[0] = 2.0 * dv_a_temp[0]; dv_a_prime[1] = 2.0 * dv_a_temp[1]; mve::math::Vec2d dv_b_prime; dv_b_prime[0] = (q_prime[0] * t[2] - r_prime[0] * t[1]); dv_b_prime[1] = (q_prime[1] * t[2] - r_prime[1] * t[1]); double dv_c_prime = (q * t[2] - r * t[1]); mve::math::Vec2d dv_c; dv_c[0] = w_prime[0] * dv_c_prime; dv_c[1] = w_prime[1] * dv_c_prime; mve::math::Vec2d du_a_b_c; du_a_b_c[0] = w * (du_a_temp[0] + du_b_prime[0]) + du_c[0]; du_a_b_c[1] = w * (du_a_temp[1] + du_b_prime[1]) + du_c[1]; mve::math::Vec2d dv_a_b_c; dv_a_b_c[0] = w * (dv_a_temp[0] + dv_b_prime[0]) + dv_c[0]; dv_a_b_c[1] = w * (dv_a_temp[1] + dv_b_prime[1]) + dv_c[1]; mve::math::Vec2d du_ap_bp_d; du_ap_bp_d[0] = (du_a_prime[0] + du_b_prime[0]) / d2; du_ap_bp_d[1] = (du_a_prime[1] + du_b_prime[1]) / d2; mve::math::Vec2d dv_ap_bp_d; dv_ap_bp_d[0] = (dv_a_prime[0] + dv_b_prime[0]) / d2; dv_ap_bp_d[1] = (dv_a_prime[1] + dv_b_prime[1]) / d2; mve::math::Vec2d du_a_b_c_d_prime; du_a_b_c_d_prime[0] = du_a_b_c[0] * d_prime / d4; du_a_b_c_d_prime[1] = du_a_b_c[1] * d_prime / d4; mve::math::Vec2d dv_a_b_c_d_prime; dv_a_b_c_d_prime[0] = dv_a_b_c[0] * d_prime / d4; dv_a_b_c_d_prime[1] = dv_a_b_c[1] * d_prime / d4; double du_c_prime_d = du_c_prime / d2; double dv_c_prime_d = dv_c_prime / d2; mve::math::Vec2d du_ap_bp_d_du_a_b_c_d_prime; du_ap_bp_d_du_a_b_c_d_prime[0] = du_ap_bp_d[0] - du_a_b_c_d_prime[0]; du_ap_bp_d_du_a_b_c_d_prime[1] = du_ap_bp_d[1] - du_a_b_c_d_prime[1]; mve::math::Vec2d dv_ap_bp_d_dv_a_b_c_d_prime; dv_ap_bp_d_dv_a_b_c_d_prime[0] = dv_ap_bp_d[0] - dv_a_b_c_d_prime[0]; dv_ap_bp_d_dv_a_b_c_d_prime[1] = dv_ap_bp_d[1] - dv_a_b_c_d_prime[1]; mve::math::Vec2d du_dn; mve::math::Vec2d dv_dn; for (int n = 0; n < 4; ++n) for (int i = 0; i < 4; ++i) { int offset = n * 24; du_dn[0] = du_ap_bp_d_du_a_b_c_d_prime[0] * dn[offset + 0 + i]; du_dn[1] = du_ap_bp_d_du_a_b_c_d_prime[1] * dn[offset + 0 + i]; dv_dn[0] = dv_ap_bp_d_dv_a_b_c_d_prime[0] * dn[offset + 0 + i]; dv_dn[1] = dv_ap_bp_d_dv_a_b_c_d_prime[1] * dn[offset + 0 + i]; jac_dn[n * 4 + i][0] = (du_dn[0] + du_c_prime_d * dn[offset + 4 + i]) * grad[0] + (dv_dn[0] + dv_c_prime_d * dn[offset + 4 + i]) * grad[1]; jac_dn[n * 4 + i][1] = (du_dn[1] + du_c_prime_d * dn[offset + 8 + i]) * grad[0] + (dv_dn[1] + dv_c_prime_d * dn[offset + 8 + i]) * grad[1]; } } } // namespace smvs
33.589474
88
0.559072
dbs4261
9a59c458181420730463ff43414fdbdb0d97aaad
801
cpp
C++
KROSS/src/Kross/Renderer/Context.cpp
WillianKoessler/KROSS-ENGINE
0e680b455ffd071565fe8b99343805ad16ca1e91
[ "Apache-2.0" ]
null
null
null
KROSS/src/Kross/Renderer/Context.cpp
WillianKoessler/KROSS-ENGINE
0e680b455ffd071565fe8b99343805ad16ca1e91
[ "Apache-2.0" ]
null
null
null
KROSS/src/Kross/Renderer/Context.cpp
WillianKoessler/KROSS-ENGINE
0e680b455ffd071565fe8b99343805ad16ca1e91
[ "Apache-2.0" ]
null
null
null
#include <Kross_pch.h> #include "Context.h" #include "GFXAPI/OpenGL/GLContext.h" #include "Kross/Renderer/Renderer.h" #include "Kross/Core/Window.h" namespace Kross { Ref<Context> Context::CreateRef(Window* window) { switch (Renderer::GetAPI()) { case RendererAPI::API::None: KROSS_FATAL("Invalid Graphics API"); return nullptr; case RendererAPI::API::OpenGL: return makeRef<OpenGL::Context>(window); } KROSS_FATAL("Unknown Graphics API."); return nullptr; } Scope<Context> Context::CreateScope(Window* window) { switch (Renderer::GetAPI()) { case RendererAPI::API::None: KROSS_FATAL("Invalid Graphics API"); return nullptr; case RendererAPI::API::OpenGL: return makeScope<OpenGL::Context>(window); } KROSS_FATAL("Unknown Graphics API."); return nullptr; } }
28.607143
85
0.715356
WillianKoessler
9a5a0d1e3eefc78619d8c6434e6d9ad05e723465
1,510
cpp
C++
Fasta.cpp
yanlinlin82/crabber
b924e5e4e19e8072303b9b83ec7eb945b42e58b3
[ "Apache-2.0" ]
null
null
null
Fasta.cpp
yanlinlin82/crabber
b924e5e4e19e8072303b9b83ec7eb945b42e58b3
[ "Apache-2.0" ]
null
null
null
Fasta.cpp
yanlinlin82/crabber
b924e5e4e19e8072303b9b83ec7eb945b42e58b3
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <fstream> #include "String.h" #include "Fasta.h" bool Fasta::Load(const std::string& filename, bool verbose) { std::ifstream file(filename, std::ios::in); if (!file.is_open()) { std::cerr << "Error: Can not open file '" << filename << "'!" << std::endl; return false; } if (verbose) { std::cerr << "Loading fasta '" << filename << "'" << std::endl; } std::string chrom; std::string line; while (std::getline(file, line)) { if (line.empty()) continue; if (line[0] == '>') { chrom = TrimLeft(line.substr(1)); std::string::size_type pos = chrom.find_first_of(" \t"); if (pos != std::string::npos) { chrom = chrom.substr(0, pos); } if (verbose) { std::cerr << " loading '" << chrom << "'\r" << std::flush; } } else { seq_[chrom] += Trim(line); } } file.close(); if (verbose) { std::cerr << "Total " << seq_.size() << " sequence(s) loaded" << std::endl; } return true; } bool Fasta::Has(const std::string& chrom) const { return (seq_.find(chrom) != seq_.end()); } size_t Fasta::GetLength(const std::string& chrom) const { auto it = seq_.find(chrom); if (it == seq_.end()) { return 0; } return it->second.size(); } std::string Fasta::GetSeq(const std::string& chrom, size_t pos, size_t size) const { std::string res; auto it = seq_.find(chrom); if (it != seq_.end()) { std::string s = it->second.substr(pos, size); for (size_t i = 0; i < s.size(); ++i) { res += std::toupper(s[i]); } } return res; }
21.884058
82
0.586755
yanlinlin82
9a5a18a89b6ab92e063758607dfe74e5cc84694b
2,385
cpp
C++
Section02/Problem04/Source.cpp
0xdec0de5/cpp-training
afa15c3bd9cbbe1ee7f219f5a5cae563cbe004b8
[ "MIT" ]
null
null
null
Section02/Problem04/Source.cpp
0xdec0de5/cpp-training
afa15c3bd9cbbe1ee7f219f5a5cae563cbe004b8
[ "MIT" ]
null
null
null
Section02/Problem04/Source.cpp
0xdec0de5/cpp-training
afa15c3bd9cbbe1ee7f219f5a5cae563cbe004b8
[ "MIT" ]
null
null
null
#include <iostream> int main() { std::cout << "Enter the character class for your player." << std::endl; std::cout << "(B)arbarian, (M)age, (R)ogue, (D)ruid: "; // TODO - handle user input: (b/B), (m/M), (r/R), or (d/D) char character_class; std::cin >> character_class; // Barbarian Character unsigned short barbarian_strength = 20; unsigned short barbarian_agility = 12; unsigned short barbarian_intelligence = 5; unsigned short barbarian_wisdom = 7; // Mage Character unsigned short mage_strength = 5; unsigned short mage_agility = 10; unsigned short mage_intelligence = 20; unsigned short mage_wisdom = 11; // Rogue Character unsigned short rogue_strength = 9; unsigned short rogue_agility = 20; unsigned short rogue_intelligence = 14; unsigned short rogue_wisdom = 6; // Druid Character unsigned short druid_strength = 14; unsigned short druid_agility = 8; unsigned short druid_intelligence = 5; unsigned short druid_wisdom = 20; // TODO - from the user's selection, print their character's properties to the console. switch(character_class) { case 'b': case 'B': std::cout << "The player is a Barbarian" << std::endl << "\tStrength = " << barbarian_strength << std::endl << "\tAgility = " << barbarian_agility << std::endl << "\tIntelligence = " << barbarian_intelligence << std::endl << "\tWisdom = " << barbarian_wisdom << std::endl; break; case 'm': case 'M': std::cout << "The player is a Mage" << std::endl << "\tStrength = " << mage_strength << std::endl << "\tAgility = " << mage_agility << std::endl << "\tIntelligence = " << mage_intelligence << std::endl << "\tWisdom = " << mage_wisdom << std::endl; break; case 'r': case 'R': std::cout << "The player is a Rogue" << std::endl << "\tStrength = " << rogue_strength << std::endl << "\tAgility = " << rogue_agility << std::endl << "\tIntelligence = " << rogue_intelligence << std::endl << "\tWisdom = " << rogue_wisdom << std::endl; break; case 'd': case 'D': std::cout << "The player is a Druid" << std::endl << "\tStrength = " << druid_strength << std::endl << "\tAgility = " << druid_agility << std::endl << "\tIntelligence = " << druid_intelligence << std::endl << "\tWisdom = " << druid_wisdom << std::endl; break; default: std::cout << "You didn't enter a valid character class."; break; } return 0; }
31.381579
88
0.644025
0xdec0de5
9a6087ab262f30d73951a4ee120da2c7333c789f
162
cpp
C++
src/examples/04_module/08_strings/main.cpp
acc-cosc-1337-summer-2020-classroom/acc-cosc-1337-summer-2020-Gabe-Cpp
f5b7d8610054c975b67ff04a41a7a054325e3c7e
[ "MIT" ]
null
null
null
src/examples/04_module/08_strings/main.cpp
acc-cosc-1337-summer-2020-classroom/acc-cosc-1337-summer-2020-Gabe-Cpp
f5b7d8610054c975b67ff04a41a7a054325e3c7e
[ "MIT" ]
null
null
null
src/examples/04_module/08_strings/main.cpp
acc-cosc-1337-summer-2020-classroom/acc-cosc-1337-summer-2020-Gabe-Cpp
f5b7d8610054c975b67ff04a41a7a054325e3c7e
[ "MIT" ]
null
null
null
#include<string> #include<iostream> #include "strings.h" int main() { std::string str1 = "john"; loop_string_w_index(str1); std::cout << str1; return 0; }
12.461538
27
0.666667
acc-cosc-1337-summer-2020-classroom
9a6bf681d119656a39fe600124d3a3094b65a541
13,720
cc
C++
hackt_docker/hackt/src/Object/sizes-entity.cc
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
hackt_docker/hackt/src/Object/sizes-entity.cc
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
hackt_docker/hackt/src/Object/sizes-entity.cc
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
/** \file "Object/sizes-entity.cc" Just dumps the sizeof for most HAC::entity classes. This file came from "art_persistent_table.cc". $Id: sizes-entity.cc,v 1.3 2010/04/07 00:12:32 fang Exp $ */ #include <iostream> #include "common/sizes-common.hh" #include "util/what.tcc" // use default typeinfo-based mangled names #include "Object/sizes-entity.hh" // include all Object/*.hh header files to evaluate struct sizes. #include "Object/module.hh" #include "Object/global_entry.hh" #include "Object/def/footprint.hh" #include "Object/def/enum_datatype_def.hh" #include "Object/def/process_definition.hh" #include "Object/def/process_definition_alias.hh" #include "Object/def/user_def_chan.hh" #include "Object/def/user_def_datatype.hh" #include "Object/def/datatype_definition_alias.hh" #include "Object/def/channel_definition_alias.hh" #include "Object/def/built_in_datatype_def.hh" #include "Object/def/channel_definition_base.hh" #include "Object/def/param_definition.hh" #include "Object/type/builtin_channel_type_reference.hh" #include "Object/type/canonical_generic_chan_type.hh" #include "Object/type/canonical_type.hh" #include "Object/type/channel_type_reference.hh" #include "Object/type/data_type_reference.hh" #include "Object/type/fundamental_type_reference.hh" #include "Object/type/param_type_reference.hh" #include "Object/type/process_type_reference.hh" #include "Object/type/template_actuals.hh" #include "Object/traits/preal_traits.hh" #include "Object/expr/pbool_const.hh" #include "Object/expr/pint_const.hh" #include "Object/expr/preal_const.hh" #include "Object/expr/bool_logical_expr.hh" #include "Object/expr/bool_negation_expr.hh" #include "Object/expr/int_arith_expr.hh" #include "Object/expr/int_relational_expr.hh" #include "Object/expr/int_negation_expr.hh" // #include "Object/expr/real_arith_expr.hh" // #include "Object/expr/real_relational_expr.hh" // #include "Object/expr/real_negation_expr.hh" #include "Object/expr/const_collection.hh" #include "Object/expr/const_index.hh" #include "Object/expr/const_range.hh" #include "Object/expr/pint_range.hh" #include "Object/expr/const_param_expr_list.hh" #include "Object/expr/dynamic_param_expr_list.hh" #include "Object/expr/const_index_list.hh" #include "Object/expr/dynamic_meta_index_list.hh" #include "Object/expr/const_range_list.hh" #include "Object/expr/dynamic_meta_range_list.hh" #include "Object/expr/pbool_logical_expr.hh" #include "Object/expr/pbool_unary_expr.hh" #include "Object/expr/pint_arith_expr.hh" #include "Object/expr/pint_unary_expr.hh" #include "Object/expr/pint_relational_expr.hh" #include "Object/expr/preal_arith_expr.hh" #include "Object/expr/preal_unary_expr.hh" #include "Object/expr/preal_relational_expr.hh" #include "Object/inst/alias_actuals.hh" #include "Object/inst/alias_empty.hh" #include "Object/inst/alias_printer.hh" #include "Object/inst/alias_visitee.hh" #include "Object/inst/alias_visitor.hh" #include "Object/inst/bool_instance.hh" #include "Object/inst/bool_instance_collection.hh" #include "Object/inst/channel_instance.hh" #include "Object/inst/channel_instance_collection.hh" #include "Object/inst/collection_fwd.hh" #include "Object/inst/datatype_instance_collection.hh" #include "Object/inst/enum_instance.hh" #include "Object/inst/enum_instance_collection.hh" #include "Object/inst/general_collection_type_manager.hh" #include "Object/inst/instance_alias_info.hh" #include "Object/inst/instance_collection.hh" #include "Object/inst/instance_collection_base.hh" #include "Object/inst/instance_array.hh" #include "Object/inst/instance_scalar.hh" #include "Object/inst/port_formal_array.hh" #include "Object/inst/port_actual_collection.hh" #include "Object/inst/instance_fwd.hh" #include "Object/inst/instance_pool.hh" #include "Object/inst/int_collection_type_manager.hh" #include "Object/inst/int_instance.hh" #include "Object/inst/int_instance_collection.hh" #include "Object/inst/internal_aliases_policy.hh" #include "Object/inst/null_collection_type_manager.hh" #include "Object/inst/param_value_collection.hh" #include "Object/inst/parameterless_collection_type_manager.hh" #include "Object/inst/pbool_instance.hh" #include "Object/inst/pbool_value_collection.hh" #include "Object/inst/physical_instance_collection.hh" #include "Object/inst/pint_instance.hh" #include "Object/inst/pint_value_collection.hh" #include "Object/inst/port_alias_tracker.hh" #include "Object/inst/preal_instance.hh" #include "Object/inst/preal_value_collection.hh" #include "Object/inst/process_instance.hh" #include "Object/inst/process_instance_collection.hh" #include "Object/inst/state_instance.hh" #include "Object/inst/struct_instance.hh" #include "Object/inst/struct_instance_collection.hh" #include "Object/inst/subinstance_manager.hh" #include "Object/inst/substructure_alias_base.hh" #include "Object/inst/value_collection.hh" #include "Object/inst/value_scalar.hh" #include "Object/inst/value_array.hh" #include "Object/inst/value_placeholder.hh" #include "Object/inst/instance_placeholder.hh" #include "Object/inst/datatype_instance_placeholder.hh" #include "Object/ref/aggregate_meta_instance_reference.hh" #include "Object/ref/aggregate_meta_value_reference.hh" #include "Object/ref/data_nonmeta_instance_reference.hh" #include "Object/ref/inst_ref_implementation.hh" #include "Object/ref/member_meta_instance_reference.hh" #include "Object/ref/meta_instance_reference_subtypes.hh" #include "Object/ref/meta_reference_union.hh" #include "Object/ref/meta_value_reference.hh" #include "Object/ref/nonmeta_instance_reference_subtypes.hh" #include "Object/ref/references_fwd.hh" #include "Object/ref/simple_meta_instance_reference.hh" #include "Object/ref/simple_meta_value_reference.hh" #include "Object/ref/simple_nonmeta_instance_reference.hh" #include "Object/ref/simple_nonmeta_value_reference.hh" #include "util/multikey_map.hh" #include "util/multikey.hh" #include "util/packed_array.hh" namespace HAC { namespace entity { using std::ostream; using std::cerr; using std::endl; using util::memory::never_ptr; using util::memory::some_ptr; using util::memory::excl_ptr; using util::memory::count_ptr; using util::packed_array; using util::packed_array_generic; //============================================================================= /** Diagnostic for inspecting sizes of classes. Has nothing to do with class persistence. */ ostream& dump_class_sizes(ostream& o) { o << "util library structures:" << endl; __dump_class_size<never_ptr<int> >(o); __dump_class_size<excl_ptr<int> >(o); __dump_class_size<some_ptr<int> >(o); __dump_class_size<count_ptr<int> >(o); // __dump_class_size<packed_array<1, size_t, char*> >(o); // error // TODO: need specialization on coeffs_type here __dump_class_size<packed_array<4, size_t, char*> >(o); __dump_class_size<packed_array_generic<size_t, char*> >(o); o << "HAC::entity general classes:" << endl; __dump_class_size<module>(o); o << "HAC::entity definition classes:" << endl; __dump_class_size<footprint>(o); __dump_class_size<footprint_base<process_tag> >(o); __dump_class_size<footprint_manager>(o); __dump_class_size<definition_base>(o); __dump_class_size<process_definition_base>(o); __dump_class_size<process_definition>(o); __dump_class_size<channel_definition_base>(o); __dump_class_size<user_def_chan>(o); __dump_class_size<datatype_definition_base>(o); __dump_class_size<user_def_datatype>(o); __dump_class_size<enum_datatype_def>(o); __dump_class_size<enum_member>(o); __dump_class_size<built_in_datatype_def>(o); // __dump_class_size<built_in_channel_def>(o); __dump_class_size<template_formals_manager>(o); __dump_class_size<port_formals_manager>(o); __dump_class_size<typedef_base>(o); __dump_class_size<process_definition_alias>(o); __dump_class_size<channel_definition_alias>(o); __dump_class_size<datatype_definition_alias>(o); __dump_class_size<built_in_param_def>(o); o << "HAC::entity expression classes:" << endl; __dump_class_size<data_expr>(o); __dump_class_size<param_expr>(o); __dump_class_size<bool_expr>(o); __dump_class_size<bool_logical_expr>(o); __dump_class_size<bool_negation_expr>(o); __dump_class_size<pbool_expr>(o); __dump_class_size<pbool_logical_expr>(o); __dump_class_size<pbool_const>(o); __dump_class_size<pbool_const_collection>(o); __dump_class_size<int_expr>(o); __dump_class_size<int_arith_expr>(o); __dump_class_size<int_relational_expr>(o); __dump_class_size<int_negation_expr>(o); __dump_class_size<pint_expr>(o); __dump_class_size<pint_unary_expr>(o); __dump_class_size<pint_arith_expr>(o); __dump_class_size<pint_relational_expr>(o); __dump_class_size<pint_const>(o); __dump_class_size<pint_const_collection>(o); __dump_class_size<real_expr>(o); __dump_class_size<preal_expr>(o); __dump_class_size<preal_arith_expr>(o); __dump_class_size<preal_unary_expr>(o); __dump_class_size<preal_relational_expr>(o); __dump_class_size<preal_const>(o); __dump_class_size<preal_const_collection>(o); __dump_class_size<meta_index_expr>(o); __dump_class_size<const_index>(o); __dump_class_size<const_param>(o); __dump_class_size<meta_range_expr>(o); __dump_class_size<const_range>(o); __dump_class_size<pint_range>(o); __dump_class_size<param_expr_list>(o); __dump_class_size<const_param_expr_list>(o); __dump_class_size<dynamic_param_expr_list>(o); __dump_class_size<meta_index_list>(o); __dump_class_size<const_index_list>(o); __dump_class_size<dynamic_meta_index_list>(o); __dump_class_size<meta_range_list>(o); __dump_class_size<const_range_list>(o); __dump_class_size<dynamic_meta_range_list>(o); __dump_class_size<nonmeta_index_expr_base>(o); __dump_class_size<nonmeta_range_expr_base>(o); o << "HAC::entity type classes:" << endl; __dump_class_size<type_reference_base>(o); __dump_class_size<fundamental_type_reference>(o); __dump_class_size<channel_type_reference_base>(o); __dump_class_size<channel_type_reference>(o); __dump_class_size<builtin_channel_type_reference>(o); __dump_class_size<canonical_generic_chan_type>(o); __dump_class_size<canonical_process_type>(o); __dump_class_size<data_type_reference>(o); __dump_class_size<process_type_reference>(o); __dump_class_size<template_actuals>(o); // __dump_class_size<resolved_template_actuals>(o); o << "HAC::entity instance classes:" << endl; __dump_class_size<instance_collection_base>(o); __dump_class_size<physical_instance_collection>(o); __dump_class_size<param_value_collection>(o); __dump_class_size<bool_instance_collection>(o); __dump_class_size<int_instance_collection>(o); __dump_class_size<channel_instance_collection>(o); __dump_class_size<substructure_alias_base<true> >(o); __dump_class_size<substructure_alias_base<false> >(o); __dump_class_size<subinstance_manager>(o); __dump_class_size<bool_instance_collection>(o); __dump_class_size<port_actual_collection<bool_tag> >(o); __dump_class_size<bool_instance>(o); __dump_class_size<instance_alias_info<bool_tag> >(o); __dump_class_size<bool_scalar>(o); __dump_class_size<bool_array_1D>(o); __dump_class_size<bool_array_4D>(o); __dump_class_size<bool_port_formal_array>(o); __dump_class_size<process_instance_collection>(o); __dump_class_size<port_actual_collection<process_tag> >(o); __dump_class_size<process_instance>(o); __dump_class_size<instance_alias_info<process_tag> >(o); __dump_class_size<process_scalar>(o); __dump_class_size<process_array_1D>(o); __dump_class_size<process_array_4D>(o); __dump_class_size<process_port_formal_array>(o); __dump_class_size<pint_instance_collection>(o); __dump_class_size<pint_instance>(o); __dump_class_size<pint_scalar>(o); __dump_class_size<pint_array_1D>(o); __dump_class_size<pint_array_4D>(o); __dump_class_size<pbool_instance_collection>(o); __dump_class_size<pbool_instance>(o); __dump_class_size<pbool_scalar>(o); __dump_class_size<pbool_array_1D>(o); __dump_class_size<pbool_array_4D>(o); __dump_class_size<instance_placeholder_base>(o); __dump_class_size<physical_instance_placeholder>(o); __dump_class_size<param_value_placeholder>(o); __dump_class_size<bool_instance_placeholder>(o); __dump_class_size<int_instance_placeholder>(o); __dump_class_size<process_instance_placeholder>(o); __dump_class_size<pbool_value_placeholder>(o); __dump_class_size<pint_value_placeholder>(o); __dump_class_size<preal_value_placeholder>(o); o << "HAC::entity reference classes:" << endl; __dump_class_size<nonmeta_instance_reference_base>(o); __dump_class_size<meta_instance_reference_base>(o); __dump_class_size<simple_meta_indexed_reference_base>(o); __dump_class_size<simple_nonmeta_instance_reference_base>(o); // __dump_class_size<simple_param_meta_value_reference>(o); __dump_class_size<aggregate_meta_value_reference_base>(o); __dump_class_size<aggregate_meta_instance_reference_base>(o); __dump_class_size<bool_meta_instance_reference_base>(o); __dump_class_size<process_meta_instance_reference_base>(o); __dump_class_size<pbool_meta_value_reference_base>(o); __dump_class_size<pint_meta_value_reference_base>(o); __dump_class_size<simple_bool_nonmeta_instance_reference>(o); __dump_class_size<simple_process_nonmeta_instance_reference>(o); __dump_class_size<simple_bool_meta_instance_reference>(o); __dump_class_size<simple_process_meta_instance_reference>(o); __dump_class_size<aggregate_bool_meta_instance_reference>(o); __dump_class_size<aggregate_process_meta_instance_reference>(o); __dump_class_size<bool_member_meta_instance_reference>(o); __dump_class_size<process_member_meta_instance_reference>(o); return o; } //============================================================================= } // end namespace entity } // end namespace HAC
41.829268
79
0.810277
broken-wheel
9a753b1acc734448b049111f8a0bb73bac5f8e00
2,145
cpp
C++
src/fastsynth/smt2_frontend.cpp
kroening/fastsynth
6a8aed3182c7156e3ea4981576e2d29ba4088a3c
[ "BSD-3-Clause" ]
3
2020-06-01T03:07:06.000Z
2021-01-21T12:42:04.000Z
src/fastsynth/smt2_frontend.cpp
kroening/fastsynth
6a8aed3182c7156e3ea4981576e2d29ba4088a3c
[ "BSD-3-Clause" ]
10
2019-09-13T21:18:15.000Z
2020-12-04T01:18:46.000Z
src/fastsynth/smt2_frontend.cpp
kroening/fastsynth
6a8aed3182c7156e3ea4981576e2d29ba4088a3c
[ "BSD-3-Clause" ]
2
2019-09-13T21:15:53.000Z
2019-09-15T04:42:31.000Z
#include <util/cmdline.h> #include <util/cout_message.h> #include <util/namespace.h> #include <util/symbol_table.h> #include <solvers/flattening/boolbv.h> #include <solvers/sat/satcheck.h> #include <solvers/smt2/smt2_parser.h> #include <fstream> #include <iostream> class smt2_frontendt:public smt2_parsert { public: smt2_frontendt( std::ifstream &_in, decision_proceduret &_solver): smt2_parsert(_in), solver(_solver) { } protected: decision_proceduret &solver; void command(const std::string &) override; }; void smt2_frontendt::command(const std::string &c) { if(c=="assert") { exprt e=expression(); solver.set_to_true(e); } else if(c=="check-sat") { switch(solver()) { case decision_proceduret::resultt::D_SATISFIABLE: std::cout << "(sat)\n"; break; case decision_proceduret::resultt::D_UNSATISFIABLE: std::cout << "(unsat)\n"; break; case decision_proceduret::resultt::D_ERROR: std::cout << "(error)\n"; } } else smt2_parsert::command(c); } int smt2_frontend(const cmdlinet &cmdline) { assert(cmdline.args.size()==1); #if 0 register_language(new_ansi_c_language); config.ansi_c.set_32(); #endif console_message_handlert message_handler; messaget message(message_handler); // this is our default verbosity unsigned int v=messaget::M_STATISTICS; if(cmdline.isset("verbosity")) { v=std::stol( cmdline.get_value("verbosity"));; if(v>10) v=10; } message_handler.set_verbosity(v); std::ifstream in(cmdline.args.front()); if(!in) { message.error() << "Failed to open input file" << messaget::eom; return 10; } symbol_tablet symbol_table; namespacet ns(symbol_table); satcheckt satcheck(message_handler); boolbvt solver(ns, satcheck, message_handler); smt2_frontendt smt2(in, solver); try { smt2.parse(); return 0; } catch(const smt2_tokenizert::smt2_errort &error) { message.error() << error.get_line_no() << ": " << error.what() << messaget::eom; return 20; } catch(...) { return 20; } }
18.815789
68
0.652681
kroening
9a77e1eabc656137780911f4cc82bb9207f1f000
6,003
cpp
C++
modules/futures_redis/src/RedisFuture.cpp
chyh1990/futures_cpp
8e60e74af0cffff0a9749682a4caf1768277c04b
[ "MIT" ]
71
2017-12-18T10:35:41.000Z
2021-12-11T19:57:34.000Z
modules/futures_redis/src/RedisFuture.cpp
chyh1990/futures_cpp
8e60e74af0cffff0a9749682a4caf1768277c04b
[ "MIT" ]
1
2017-12-19T09:31:46.000Z
2017-12-20T07:08:01.000Z
modules/futures_redis/src/RedisFuture.cpp
chyh1990/futures_cpp
8e60e74af0cffff0a9749682a4caf1768277c04b
[ "MIT" ]
7
2017-12-20T01:55:44.000Z
2019-12-06T12:25:55.000Z
#include <futures_redis/RedisFuture.h> #include "hiredis/async.h" #include "hiredis/hiredis.h" namespace futures { namespace redis_io { AsyncContext::AsyncContext(EventExecutor *loop, const std::string& addr, uint16_t port) : io::IOObject(loop), c_(nullptr), addr_(addr), port_(port), rev_(loop->getLoop()), wev_(loop->getLoop()) { connected_ = false; // reconnect(); } void AsyncContext::reconnect() { rev_.stop(); wev_.stop(); if (c_) { redisAsyncDisconnect(c_); c_ = nullptr; } FUTURES_DLOG(INFO) << "reconnecting to redis"; c_ = redisAsyncConnect(addr_.c_str(), port_); if (!c_) throw RedisException("redisAsyncContext"); if (c_->err) { std::string err(c_->errstr); redisAsyncFree(c_); throw RedisException(err); } c_->ev.addRead = redisAddRead; c_->ev.delRead = redisDelRead; c_->ev.addWrite = redisAddWrite; c_->ev.delWrite = redisDelWrite; c_->ev.cleanup = redisCleanup; c_->ev.data = this; c_->data = this; reading_ = false; writing_ = false; connected_ = false; rev_.set<AsyncContext, &AsyncContext::redisReadEvent>(this); rev_.set(c_->c.fd, ev::READ); wev_.set<AsyncContext, &AsyncContext::redisWriteEvent>(this); wev_.set(c_->c.fd, ev::WRITE); redisAsyncSetConnectCallback(c_, redisConnect); redisAsyncSetDisconnectCallback(c_, redisDisconnect); } AsyncContext::~AsyncContext() { FUTURES_DLOG(INFO) << "AsyncContext destroy: " << c_; rev_.stop(); wev_.stop(); if (c_) redisAsyncFree(c_); } void AsyncContext::redisReadEvent(ev::io &watcher, int revent) { if (revent & ev::ERROR) throw RedisException("failed to read"); redisAsyncHandleRead(c_); } void AsyncContext::redisWriteEvent(ev::io &watcher, int revent) { if (revent & ev::ERROR) throw RedisException("failed to write"); redisAsyncHandleWrite(c_); } void AsyncContext::redisAddRead(void *data) { AsyncContext *self = static_cast<AsyncContext*>(data); if (!self->reading_) { self->reading_ = true; self->rev_.start(); } } void AsyncContext::redisDelRead(void *data) { AsyncContext *self = static_cast<AsyncContext*>(data); if (self->reading_) { self->reading_ = false; self->rev_.stop(); } } void AsyncContext::redisAddWrite(void *data) { AsyncContext *self = static_cast<AsyncContext*>(data); if (!self->writing_) { self->writing_ = true; self->wev_.start(); } } void AsyncContext::redisDelWrite(void *data) { AsyncContext *self = static_cast<AsyncContext*>(data); if (self->writing_) { self->writing_ = false; self->wev_.stop(); } } void AsyncContext::redisCleanup(void *data) { AsyncContext *self = static_cast<AsyncContext*>(data); FUTURES_DLOG(INFO) << "redisCleanup"; if (self) { redisDelRead(self); redisDelWrite(self); } } void AsyncContext::redisConnect(const redisAsyncContext *c, int status) { AsyncContext *self = static_cast<AsyncContext*>(c->data); FUTURES_DLOG(INFO) << "redis connect: " << status; if (status != REDIS_OK) { self->c_ = nullptr; } else { self->connected_ = true; } } void AsyncContext::redisDisconnect(const redisAsyncContext *c, int status) { AsyncContext *self = static_cast<AsyncContext*>(c->data); FUTURES_DLOG(INFO) << "redis disconnect: " << status; self->c_ = nullptr; self->connected_ = false; // pending should be empty } io::intrusive_ptr<AsyncContext::CompletionToken> AsyncContext::asyncFormattedCommand(const char *cmd, size_t len, bool subscribe) { reconnectIfNeeded(); assert(c_); io::intrusive_ptr<CompletionToken> p(new CompletionToken(subscribe)); int status = redisAsyncFormattedCommand(c_, redisCallback, p.get(), cmd, len); if (status) { p->reply_ = Try<Reply>(RedisException(c_->errstr)); p->notifyDone(); } else { p->attach(this); p->addRef(); } return p; } void AsyncContext::redisCallback(struct redisAsyncContext* ctx, void *r, void *p) { AsyncContext *self = static_cast<AsyncContext*>(ctx->data); (void)self; auto handler = static_cast<CompletionToken*>(p); auto reply = static_cast<redisReply*>(r); if (!handler->subscribe_) { if (reply) { handler->reply_ = Try<Reply>(Reply(reply)); } else { handler->reply_ = Try<Reply>(FutureCancelledException()); } handler->notifyDone(); handler->decRef(); } else { if (reply) { // TODO unsubscribe handler->stream_.push_back(Try<Reply>(Reply(reply))); handler->notify(); } else { handler->stream_.push_back(Try<Reply>(FutureCancelledException())); handler->notifyDone(); handler->decRef(); } } } void AsyncContext::onCancel(CancelReason r) { FUTURES_DLOG(INFO) << "canceling all requests"; if (c_) { redisAsyncFree(c_); c_ = nullptr; connected_ = false; } } // RedisCommandFuture RedisCommandFuture::RedisCommandFuture(AsyncContext::Ptr ctx, const char *format, ...) : ctx_(ctx) { va_list ap; int len; char *cmd; va_start(ap,format); len = redisvFormatCommand(&cmd, format, ap); va_end(ap); if (len < 0) throw RedisException("invalid command"); assert(cmd != nullptr); cmd_.assign(cmd, len); } RedisCommandStream::RedisCommandStream(AsyncContext::Ptr ctx, const char *format, ...) : ctx_(ctx) { va_list ap; int len; char *cmd; va_start(ap,format); len = redisvFormatCommand(&cmd, format, ap); va_end(ap); if (len < 0) throw RedisException("invalid command"); assert(cmd != nullptr); cmd_.assign(cmd, len); } } }
27.791667
86
0.617191
chyh1990
9a799309ae4d8f47c9cc005df306f0a5d0e0eb91
1,643
cpp
C++
src/physics_animation.cpp
AleksanderSiwek/Fluide_Engine
12c626105b079a3dd21a3cc95b7d98342d041f5d
[ "MIT" ]
null
null
null
src/physics_animation.cpp
AleksanderSiwek/Fluide_Engine
12c626105b079a3dd21a3cc95b7d98342d041f5d
[ "MIT" ]
null
null
null
src/physics_animation.cpp
AleksanderSiwek/Fluide_Engine
12c626105b079a3dd21a3cc95b7d98342d041f5d
[ "MIT" ]
null
null
null
#include "physics_animation.hpp" PhysicsAnimation::PhysicsAnimation() { Initialize(); } PhysicsAnimation::~PhysicsAnimation() { } void PhysicsAnimation::AdvanceSingleFrame() { Frame f = _currentFrame; Update(++f); } void PhysicsAnimation::SetCurrentFrame(const Frame& frame) { _currentFrame = frame; } void PhysicsAnimation::SetNumberOfSubTimesteps(unsigned int numberOfSubTimesteps) { _numberOfSubTimesteps = numberOfSubTimesteps; } Frame PhysicsAnimation::GetCurrentFrame() const { return _currentFrame; } double PhysicsAnimation::GetCurrentTimeInSeconds() const { return _currentTime; } unsigned int PhysicsAnimation::GetNumberOfSubTimeSteps() const { return _numberOfTimeSteps; } void PhysicsAnimation::OnUpdate(const Frame& frame) { if(frame.GetIndex() > _currentFrame.GetIndex()) { long int numberOfFrames = frame.GetIndex() - _currentFrame.GetIndex(); for (size_t i = 0; i < numberOfFrames; ++i) { AdvanceTimeStep(frame.GetTimeIntervalInSeconds()); } _currentFrame = frame; } } void PhysicsAnimation::AdvanceTimeStep(double timeIntervalInSeconds) { _currentTime = _currentFrame.GetTimeInSeconds(); const double subTimestepInterval = _currentFrame.GetTimeIntervalInSeconds() / NumberOfSubTimeSteps(timeIntervalInSeconds); for(size_t i = 0; i < NumberOfSubTimeSteps(timeIntervalInSeconds); i++) { OnAdvanceTimeStep(subTimestepInterval); _currentTime += subTimestepInterval; } } void PhysicsAnimation::Initialize() { OnInitialize(); } void PhysicsAnimation::OnInitialize() { }
20.283951
126
0.720633
AleksanderSiwek
9a7ea5d5cb03f555ed8b370c08acadaee18ab31c
1,297
hpp
C++
Axis.Echinopsis/application/factories/collectors/HyperworksNodeCollectorFactory.hpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
2
2021-07-23T08:49:54.000Z
2021-07-29T22:07:30.000Z
Axis.Echinopsis/application/factories/collectors/HyperworksNodeCollectorFactory.hpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
null
null
null
Axis.Echinopsis/application/factories/collectors/HyperworksNodeCollectorFactory.hpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
null
null
null
#pragma once #include "application/factories/collectors/CollectorFactory.hpp" #include "application/factories/collectors/GeneralNodeCollectorFactory.hpp" #include "HyperworksNodeCollectorBuilder.hpp" namespace axis { namespace application { namespace factories { namespace collectors { class HyperworksNodeCollectorFactory : public CollectorFactory { public: HyperworksNodeCollectorFactory(void); ~HyperworksNodeCollectorFactory(void); virtual void Destroy( void ) const; virtual axis::services::language::parsing::ParseResult TryParse( const axis::String& formatName, const axis::services::language::iterators::InputIterator& begin, const axis::services::language::iterators::InputIterator& end ); virtual CollectorBuildResult ParseAndBuild( const axis::String& formatName, const axis::services::language::iterators::InputIterator& begin, const axis::services::language::iterators::InputIterator& end, const axis::domain::analyses::NumericalModel& model, axis::application::parsing::core::ParseContext& context ); private: axis::application::factories::collectors::GeneralNodeCollectorFactory *factory_; HyperworksNodeCollectorBuilder builder_; }; } } } } // namespace axis::application::factories::collectors
41.83871
103
0.764842
renato-yuzup
9a846635ec4bc8ee32415cdc76a08ba1d8f16037
2,762
cc
C++
Neptune/Socket.cc
superly1213/Neptune
11e34a6c44bd10161c59560d24cbe6f83580855e
[ "BSD-2-Clause" ]
1
2017-01-30T04:32:27.000Z
2017-01-30T04:32:27.000Z
Neptune/Socket.cc
superly1213/Neptune
11e34a6c44bd10161c59560d24cbe6f83580855e
[ "BSD-2-Clause" ]
null
null
null
Neptune/Socket.cc
superly1213/Neptune
11e34a6c44bd10161c59560d24cbe6f83580855e
[ "BSD-2-Clause" ]
1
2019-03-21T07:09:16.000Z
2019-03-21T07:09:16.000Z
// Copyright (c) 2017 ASMlover. 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 ofconditions 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 materialsprovided with the // distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include <Chaos/Logging/Logging.h> #include <Neptune/Kern/NetOps.h> #include <Neptune/InetAddress.h> #include <Neptune/Socket.h> namespace Neptune { Socket::~Socket(void) { NetOps::socket::close(sockfd_); } void Socket::bind_address(const InetAddress& local_addr) { NetOps::socket::bind(sockfd_, local_addr.get_address()); } void Socket::listen(void) { NetOps::socket::listen(sockfd_); } int Socket::accept(InetAddress& peer_addr) { struct sockaddr_in6 addr6{}; int connfd = NetOps::socket::accept(sockfd_, &addr6); if (connfd >= 0) peer_addr.set_address(addr6); return connfd; } void Socket::shutdown_write(void) { NetOps::socket::shutdown(sockfd_, NetOps::socket::SHUT_WRIT); } void Socket::set_tcp_nodelay(bool nodelay) { NetOps::socket::set_option( sockfd_, IPPROTO_TCP, TCP_NODELAY, nodelay ? 1 : 0); } void Socket::set_reuse_addr(bool reuse) { NetOps::socket::set_option(sockfd_, SOL_SOCKET, SO_REUSEADDR, reuse ? 1 : 0); } void Socket::set_reuse_port(bool reuse) { int r = -1; #if defined(SO_REUSEPORT) r = NetOps::socket::set_option( sockfd_, SOL_SOCKET, SO_REUSEPORT, reuse ? 1 : 0); #endif if (r < 0 && reuse) CHAOSLOG_SYSERR << "Socket::set_reuse_port - failed or not support"; } void Socket::set_keep_alive(bool keep_alive) { NetOps::socket::set_option( sockfd_, SOL_SOCKET, SO_KEEPALIVE, keep_alive ? 1 : 0); } }
33.277108
79
0.736061
superly1213
89412bbd52f4055b39f0530c4515f8abdd6d4ebb
14,199
cc
C++
wrappers/8.1.1/vtkGeoProjectionWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
6
2016-02-03T12:48:36.000Z
2020-09-16T15:07:51.000Z
wrappers/8.1.1/vtkGeoProjectionWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
4
2016-02-13T01:30:43.000Z
2020-03-30T16:59:32.000Z
wrappers/8.1.1/vtkGeoProjectionWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
null
null
null
/* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #define VTK_WRAPPING_CXX #define VTK_STREAMS_FWD_ONLY #include <nan.h> #include "vtkObjectWrap.h" #include "vtkGeoProjectionWrap.h" #include "vtkObjectBaseWrap.h" #include "../../plus/plus.h" using namespace v8; extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap; Nan::Persistent<v8::FunctionTemplate> VtkGeoProjectionWrap::ptpl; VtkGeoProjectionWrap::VtkGeoProjectionWrap() { } VtkGeoProjectionWrap::VtkGeoProjectionWrap(vtkSmartPointer<vtkGeoProjection> _native) { native = _native; } VtkGeoProjectionWrap::~VtkGeoProjectionWrap() { } void VtkGeoProjectionWrap::Init(v8::Local<v8::Object> exports) { Nan::SetAccessor(exports, Nan::New("vtkGeoProjection").ToLocalChecked(), ConstructorGetter); Nan::SetAccessor(exports, Nan::New("GeoProjection").ToLocalChecked(), ConstructorGetter); } void VtkGeoProjectionWrap::ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { InitPtpl(); info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction()); } void VtkGeoProjectionWrap::InitPtpl() { if (!ptpl.IsEmpty()) return; v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); VtkObjectWrap::InitPtpl( ); tpl->Inherit(Nan::New<FunctionTemplate>(VtkObjectWrap::ptpl)); tpl->SetClassName(Nan::New("VtkGeoProjectionWrap").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "ClearOptionalParameters", ClearOptionalParameters); Nan::SetPrototypeMethod(tpl, "clearOptionalParameters", ClearOptionalParameters); Nan::SetPrototypeMethod(tpl, "GetCentralMeridian", GetCentralMeridian); Nan::SetPrototypeMethod(tpl, "getCentralMeridian", GetCentralMeridian); Nan::SetPrototypeMethod(tpl, "GetDescription", GetDescription); Nan::SetPrototypeMethod(tpl, "getDescription", GetDescription); Nan::SetPrototypeMethod(tpl, "GetIndex", GetIndex); Nan::SetPrototypeMethod(tpl, "getIndex", GetIndex); Nan::SetPrototypeMethod(tpl, "GetName", GetName); Nan::SetPrototypeMethod(tpl, "getName", GetName); Nan::SetPrototypeMethod(tpl, "GetNumberOfOptionalParameters", GetNumberOfOptionalParameters); Nan::SetPrototypeMethod(tpl, "getNumberOfOptionalParameters", GetNumberOfOptionalParameters); Nan::SetPrototypeMethod(tpl, "GetNumberOfProjections", GetNumberOfProjections); Nan::SetPrototypeMethod(tpl, "getNumberOfProjections", GetNumberOfProjections); Nan::SetPrototypeMethod(tpl, "GetOptionalParameterKey", GetOptionalParameterKey); Nan::SetPrototypeMethod(tpl, "getOptionalParameterKey", GetOptionalParameterKey); Nan::SetPrototypeMethod(tpl, "GetOptionalParameterValue", GetOptionalParameterValue); Nan::SetPrototypeMethod(tpl, "getOptionalParameterValue", GetOptionalParameterValue); Nan::SetPrototypeMethod(tpl, "GetProjectionDescription", GetProjectionDescription); Nan::SetPrototypeMethod(tpl, "getProjectionDescription", GetProjectionDescription); Nan::SetPrototypeMethod(tpl, "GetProjectionName", GetProjectionName); Nan::SetPrototypeMethod(tpl, "getProjectionName", GetProjectionName); Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "RemoveOptionalParameter", RemoveOptionalParameter); Nan::SetPrototypeMethod(tpl, "removeOptionalParameter", RemoveOptionalParameter); Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "SetCentralMeridian", SetCentralMeridian); Nan::SetPrototypeMethod(tpl, "setCentralMeridian", SetCentralMeridian); Nan::SetPrototypeMethod(tpl, "SetName", SetName); Nan::SetPrototypeMethod(tpl, "setName", SetName); Nan::SetPrototypeMethod(tpl, "SetOptionalParameter", SetOptionalParameter); Nan::SetPrototypeMethod(tpl, "setOptionalParameter", SetOptionalParameter); #ifdef VTK_NODE_PLUS_VTKGEOPROJECTIONWRAP_INITPTPL VTK_NODE_PLUS_VTKGEOPROJECTIONWRAP_INITPTPL #endif ptpl.Reset( tpl ); } void VtkGeoProjectionWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info) { if(!info.IsConstructCall()) { Nan::ThrowError("Constructor not called in a construct call."); return; } if(info.Length() == 0) { vtkSmartPointer<vtkGeoProjection> native = vtkSmartPointer<vtkGeoProjection>::New(); VtkGeoProjectionWrap* obj = new VtkGeoProjectionWrap(native); obj->Wrap(info.This()); } else { if(info[0]->ToObject() != vtkNodeJsNoWrap ) { Nan::ThrowError("Parameter Error"); return; } } info.GetReturnValue().Set(info.This()); } void VtkGeoProjectionWrap::ClearOptionalParameters(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkGeoProjectionWrap *wrapper = ObjectWrap::Unwrap<VtkGeoProjectionWrap>(info.Holder()); vtkGeoProjection *native = (vtkGeoProjection *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->ClearOptionalParameters(); } void VtkGeoProjectionWrap::GetCentralMeridian(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkGeoProjectionWrap *wrapper = ObjectWrap::Unwrap<VtkGeoProjectionWrap>(info.Holder()); vtkGeoProjection *native = (vtkGeoProjection *)wrapper->native.GetPointer(); double r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetCentralMeridian(); info.GetReturnValue().Set(Nan::New(r)); } void VtkGeoProjectionWrap::GetDescription(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkGeoProjectionWrap *wrapper = ObjectWrap::Unwrap<VtkGeoProjectionWrap>(info.Holder()); vtkGeoProjection *native = (vtkGeoProjection *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetDescription(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkGeoProjectionWrap::GetIndex(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkGeoProjectionWrap *wrapper = ObjectWrap::Unwrap<VtkGeoProjectionWrap>(info.Holder()); vtkGeoProjection *native = (vtkGeoProjection *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetIndex(); info.GetReturnValue().Set(Nan::New(r)); } void VtkGeoProjectionWrap::GetName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkGeoProjectionWrap *wrapper = ObjectWrap::Unwrap<VtkGeoProjectionWrap>(info.Holder()); vtkGeoProjection *native = (vtkGeoProjection *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetName(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkGeoProjectionWrap::GetNumberOfOptionalParameters(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkGeoProjectionWrap *wrapper = ObjectWrap::Unwrap<VtkGeoProjectionWrap>(info.Holder()); vtkGeoProjection *native = (vtkGeoProjection *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetNumberOfOptionalParameters(); info.GetReturnValue().Set(Nan::New(r)); } void VtkGeoProjectionWrap::GetNumberOfProjections(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkGeoProjectionWrap *wrapper = ObjectWrap::Unwrap<VtkGeoProjectionWrap>(info.Holder()); vtkGeoProjection *native = (vtkGeoProjection *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetNumberOfProjections(); info.GetReturnValue().Set(Nan::New(r)); } void VtkGeoProjectionWrap::GetOptionalParameterKey(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkGeoProjectionWrap *wrapper = ObjectWrap::Unwrap<VtkGeoProjectionWrap>(info.Holder()); vtkGeoProjection *native = (vtkGeoProjection *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { char const * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->GetOptionalParameterKey( info[0]->Int32Value() ); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); return; } Nan::ThrowError("Parameter mismatch"); } void VtkGeoProjectionWrap::GetOptionalParameterValue(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkGeoProjectionWrap *wrapper = ObjectWrap::Unwrap<VtkGeoProjectionWrap>(info.Holder()); vtkGeoProjection *native = (vtkGeoProjection *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { char const * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->GetOptionalParameterValue( info[0]->Int32Value() ); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); return; } Nan::ThrowError("Parameter mismatch"); } void VtkGeoProjectionWrap::GetProjectionDescription(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkGeoProjectionWrap *wrapper = ObjectWrap::Unwrap<VtkGeoProjectionWrap>(info.Holder()); vtkGeoProjection *native = (vtkGeoProjection *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { char const * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->GetProjectionDescription( info[0]->Int32Value() ); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); return; } Nan::ThrowError("Parameter mismatch"); } void VtkGeoProjectionWrap::GetProjectionName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkGeoProjectionWrap *wrapper = ObjectWrap::Unwrap<VtkGeoProjectionWrap>(info.Holder()); vtkGeoProjection *native = (vtkGeoProjection *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { char const * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->GetProjectionName( info[0]->Int32Value() ); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); return; } Nan::ThrowError("Parameter mismatch"); } void VtkGeoProjectionWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkGeoProjectionWrap *wrapper = ObjectWrap::Unwrap<VtkGeoProjectionWrap>(info.Holder()); vtkGeoProjection *native = (vtkGeoProjection *)wrapper->native.GetPointer(); vtkGeoProjection * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->NewInstance(); VtkGeoProjectionWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkGeoProjectionWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkGeoProjectionWrap *w = new VtkGeoProjectionWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkGeoProjectionWrap::RemoveOptionalParameter(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkGeoProjectionWrap *wrapper = ObjectWrap::Unwrap<VtkGeoProjectionWrap>(info.Holder()); vtkGeoProjection *native = (vtkGeoProjection *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->RemoveOptionalParameter( *a0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkGeoProjectionWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkGeoProjectionWrap *wrapper = ObjectWrap::Unwrap<VtkGeoProjectionWrap>(info.Holder()); vtkGeoProjection *native = (vtkGeoProjection *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectBaseWrap::ptpl))->HasInstance(info[0])) { VtkObjectBaseWrap *a0 = ObjectWrap::Unwrap<VtkObjectBaseWrap>(info[0]->ToObject()); vtkGeoProjection * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->SafeDownCast( (vtkObjectBase *) a0->native.GetPointer() ); VtkGeoProjectionWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkGeoProjectionWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkGeoProjectionWrap *w = new VtkGeoProjectionWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); return; } Nan::ThrowError("Parameter mismatch"); } void VtkGeoProjectionWrap::SetCentralMeridian(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkGeoProjectionWrap *wrapper = ObjectWrap::Unwrap<VtkGeoProjectionWrap>(info.Holder()); vtkGeoProjection *native = (vtkGeoProjection *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsNumber()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetCentralMeridian( info[0]->NumberValue() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkGeoProjectionWrap::SetName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkGeoProjectionWrap *wrapper = ObjectWrap::Unwrap<VtkGeoProjectionWrap>(info.Holder()); vtkGeoProjection *native = (vtkGeoProjection *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetName( *a0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkGeoProjectionWrap::SetOptionalParameter(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkGeoProjectionWrap *wrapper = ObjectWrap::Unwrap<VtkGeoProjectionWrap>(info.Holder()); vtkGeoProjection *native = (vtkGeoProjection *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); if(info.Length() > 1 && info[1]->IsString()) { Nan::Utf8String a1(info[1]); if(info.Length() != 2) { Nan::ThrowError("Too many parameters."); return; } native->SetOptionalParameter( *a0, *a1 ); return; } } Nan::ThrowError("Parameter mismatch"); }
31.48337
106
0.7347
axkibe
89427c5306d3cbf81dfd33f11c25a5c2e9fbb185
1,329
hpp
C++
include/interface_handler.hpp
rdavid/atm
c3a69799b5993cec694a69b0f881603aa092fc32
[ "0BSD" ]
null
null
null
include/interface_handler.hpp
rdavid/atm
c3a69799b5993cec694a69b0f881603aa092fc32
[ "0BSD" ]
null
null
null
include/interface_handler.hpp
rdavid/atm
c3a69799b5993cec694a69b0f881603aa092fc32
[ "0BSD" ]
null
null
null
#pragma once #include <interface.hpp> #include <future> namespace atm { class interface_handler { public: std::future<void> issue_money(unsigned amount) const { return std::async(&interface::issue_money, &m_interface, amount); } std::future<void> display_insufficient_funds() const { return std::async(&interface::display_insufficient_funds, &m_interface); } std::future<void> display_enter_pin() const { return std::async(&interface::display_enter_pin, &m_interface); } std::future<void> display_enter_card() const { return std::async(&interface::display_enter_card, &m_interface); } std::future<void> display_balance(unsigned balance) const { return std::async(&interface::display_balance, &m_interface, balance); } std::future<void> display_withdrawal_options() const { return std::async(&interface::display_withdrawal_options, &m_interface); } std::future<void> display_cancelled() const { return std::async(&interface::display_cancelled, &m_interface); } std::future<void> display_pin_incorrect_message() const { return std::async(&interface::display_pin_incorrect_message, &m_interface); } std::future<void> eject_card() const { return std::async(&interface::eject_card, &m_interface); } private: interface m_interface; }; } // namespace atm
30.906977
79
0.72912
rdavid
8945d2f322c94aad0085b1c9c7e31fbbfcc5e764
542
hpp
C++
libs/console/include/sge/console/callback/function_type.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/console/include/sge/console/callback/function_type.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/console/include/sge/console/callback/function_type.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_CONSOLE_CALLBACK_FUNCTION_TYPE_HPP_INCLUDED #define SGE_CONSOLE_CALLBACK_FUNCTION_TYPE_HPP_INCLUDED #include <sge/console/arg_list.hpp> #include <sge/console/object_ref.hpp> namespace sge::console::callback { using function_type = void(sge::console::arg_list const &, sge::console::object_ref); } #endif
27.1
85
0.756458
cpreh
8947abb1f31cde821893456393d10619c8c882f2
432
cpp
C++
cs162/labs/lab6/square.cpp
franzmk/Oregon-State-Schoolwork
20f8a72e78ec4baa131add2dda8026cd47f36188
[ "MIT" ]
null
null
null
cs162/labs/lab6/square.cpp
franzmk/Oregon-State-Schoolwork
20f8a72e78ec4baa131add2dda8026cd47f36188
[ "MIT" ]
null
null
null
cs162/labs/lab6/square.cpp
franzmk/Oregon-State-Schoolwork
20f8a72e78ec4baa131add2dda8026cd47f36188
[ "MIT" ]
null
null
null
#include "square.h" Square::Square() { //nothing here } Square::Square(float x, string name, string color) : Rectangle(x, x, name, color) { //nothing here } float Square::get_dimensions() { get_height(); } void Square::set_dimensions(float x) { set_height(x); set_width(x); } float Square::get_area() { float area = get_height() * get_width(); return area; } Square::~Square() { cout << "Destructor called" << endl; }
15.428571
83
0.662037
franzmk
894b98f737b3d6f2eeb7c7def093bd7f68529f96
207
cpp
C++
2021.09.13-Homework-1/Task 5/Source.cpp
095238/Personal-Space
4950722f815193030674e7d899f5f07970e9e08f
[ "Apache-2.0" ]
null
null
null
2021.09.13-Homework-1/Task 5/Source.cpp
095238/Personal-Space
4950722f815193030674e7d899f5f07970e9e08f
[ "Apache-2.0" ]
null
null
null
2021.09.13-Homework-1/Task 5/Source.cpp
095238/Personal-Space
4950722f815193030674e7d899f5f07970e9e08f
[ "Apache-2.0" ]
null
null
null
#include<iostream> using namespace std; int main(int argc, char* argv[]) { int x = 0; cin >> x; int a = x % 10; int b = (x % 100) / 10; int c = x / 100; cout << a+b+c << endl; return EXIT_SUCCESS; }
14.785714
32
0.565217
095238
89566a1d7c886db3bfac38c58df9b36a0a639ef4
19,308
cpp
C++
source/games/game_tetris.cpp
Chrscool8/Brick-Game-9999-in-1
5f5aa93729ded47d395f7546308b7ce89f035c17
[ "Zlib" ]
5
2021-04-06T06:18:26.000Z
2021-11-10T02:01:33.000Z
source/games/game_tetris.cpp
Chrscool8/Brick-Game-9999-in-1
5f5aa93729ded47d395f7546308b7ce89f035c17
[ "Zlib" ]
null
null
null
source/games/game_tetris.cpp
Chrscool8/Brick-Game-9999-in-1
5f5aa93729ded47d395f7546308b7ce89f035c17
[ "Zlib" ]
null
null
null
#include <games/game_tetris.h> #include <games/game_race.h> #include <grid_sprites.h> #include <game_tetris_shapes.h> #include <platform/control_layer.h> // Let's the subgame know what main game it belongs to. subgame_tetris::subgame_tetris(BrickGameFramework& _parent) : subgame(_parent) { name = "Tetris"; } // Runs once when the subgame starts (when the transition shade is fully black) void subgame_tetris::subgame_init() { printf("Initting Tetris!!\n"); // Create an instance of a snake object in game 'game' at position 5, 5. objects.push_back(std::make_unique<obj_tetris_rows>(game)); } // Runs every frame of the subgame unless the game is transitioning void subgame_tetris::subgame_step() { if (phase == -1) { // Be Prepared phase = 0; } else if (phase == 0) { // Create Object objects.push_back(std::make_unique<obj_tetromino>(game, grid_width(game.game_grid) / 2 - 1, -2, next_piece)); next_piece = rand() % tetris_shapes.size(); phase = 1; } else if (phase == 1) { // Wait for no more object if (!object_exists("obj_tetromino")) { phase = 2; } } else if (phase == 2) { highlighted_rows.clear(); // Check Rows game_object* rows = get_object_by_name("obj_tetris_rows"); if (rows != NULL) { obj_tetris_rows* row_obj = static_cast<obj_tetris_rows*>(rows); int width = grid_width(row_obj->filled_blocks); int height = grid_height(row_obj->filled_blocks); print_debug(to_string(width) + " " + to_string(height)); for (int i = 0; i < height; i++) { bool filled = true; for (int j = 0; j < width; j++) { if (!grid_get(row_obj->filled_blocks, j, i)) { filled = false; break; } } if (filled) { highlighted_rows.push_back(i); print_debug(to_string(i)); } } } phase = 3; ticker = 0; } else if (phase == 3) { // Animate Rows ticker += 1; game_object* rows = get_object_by_name("obj_tetris_rows"); if (rows != NULL) { obj_tetris_rows* row_obj = static_cast<obj_tetris_rows*>(rows); for (unsigned int i = 0; i < highlighted_rows.size(); i++) { for (int j = 0; j < grid_width(row_obj->filled_blocks); j++) { grid_set(row_obj->filled_blocks, j, highlighted_rows.at(i), (ticker % 50) > 25); } } } if (ticker > 150 || highlighted_rows.empty()) phase = 4; } else if (phase == 4) { // Remove row game_object* rows = get_object_by_name("obj_tetris_rows"); if (rows != NULL) { obj_tetris_rows* row_obj = static_cast<obj_tetris_rows*>(rows); while (!highlighted_rows.empty()) { //print_debug(to_string(highlighted_rows.size() - 1)); row_obj->shift_down(highlighted_rows.at(highlighted_rows.size() - 1)); highlighted_rows.erase(highlighted_rows.begin() + highlighted_rows.size() - 1); game.incrementScore(1); for (unsigned int i = 0; i < highlighted_rows.size(); i++) { highlighted_rows[i] += 1; } } } phase = 0; } } // Runs every frame of the subgame whether it's transitioning or not (to draw behind the shade) void subgame_tetris::subgame_draw() { //printf("Drawing Tetris!!\n"); vector<vector<bool>> spr = get_sprite(next_piece, 0); vector<vector<bool>> small_grid = grid_create(4, 4); place_grid_sprite(small_grid, spr, (grid_width(spr) <= 3), (grid_height(spr) <= 3)); draw_grid(small_grid, 1280 * .75, 720 / 2, 31); } void subgame_tetris::subgame_demo() { vector<vector<bool>> sprite; const int frames = 10; int frame = (game.game_time_in_frames / 30) % frames; switch (frame) { case 0: sprite = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 }, { 0, 0, 0, 0, 1, 1, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 1, 1, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 1, 1, 0, 0, 0, 0, 1, 0 }, { 1, 1, 1, 1, 1, 1, 0, 1, 1, 1 }, { 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; break; case 1: sprite = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 }, { 0, 0, 0, 0, 1, 1, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 1, 1, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 1, 1, 0, 0, 0, 0, 1, 0 }, { 1, 1, 1, 1, 1, 1, 0, 1, 1, 1 }, { 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; break; case 2: sprite = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 }, { 0, 0, 0, 0, 0, 1, 1, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 }, { 0, 1, 1, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 1, 1, 0, 0, 0, 0, 1, 0 }, { 1, 1, 1, 1, 1, 1, 0, 1, 1, 1 }, { 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; break; case 3: sprite = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 1, 1, 1, 0, 0 }, { 0, 1, 1, 0, 0, 0, 1, 0, 0, 0 }, { 0, 0, 1, 1, 0, 0, 0, 0, 1, 0 }, { 1, 1, 1, 1, 1, 1, 0, 1, 1, 1 }, { 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; break; case 4: sprite = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 1, 1, 0, 0, 1, 1, 1, 0, 0 }, { 0, 0, 1, 1, 0, 0, 1, 0, 1, 0 }, { 1, 1, 1, 1, 1, 1, 0, 1, 1, 1 }, { 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; break; case 5: sprite = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 1, 1, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 1, 1, 0, 1, 1, 1, 1, 0 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; break; case 6: sprite = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 1, 1, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 1, 1, 0, 1, 1, 1, 1, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; break; case 7: sprite = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 1, 1, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 1, 1, 0, 1, 1, 1, 1, 0 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, }; break; case 8: sprite = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 1, 1, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 1, 1, 0, 1, 1, 1, 1, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; break; case 9: sprite = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 1, 1, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 1, 1, 0, 1, 1, 1, 1, 0 }, { 1, 1, 1, 1, 0, 1, 1, 1, 1, 1 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }; break; default: sprite = { { 1, 1, 1 }, { 1, 1, 1 }, { 1, 1, 1 } }; } place_grid_sprite(game.game_grid, sprite, 0, 1); //print_debug(to_string(frame)); } // Clean up subgame objects here, runs once when the game is changing to a different // game and the transition shade is fully black void subgame_tetris::subgame_exit() { //printf("Exiting Tetris!!\n"); } std::string subgame_tetris::subgame_controls_text() { return "D-Pad: Move\nA: Clockwise\nY: Counter-C"; } subgame_tetris::obj_tetromino::obj_tetromino(BrickGameFramework& game, int _x, int _y, int _piece_type) : game_object(game, _x, _y) { name = "obj_tetromino"; angle = 0; time_til_drop_move = 60; pause_time_drop = 60; shape_index = _piece_type; } void subgame_tetris::obj_tetromino::change_rotation_by(int amount) { angle = (angle + amount + tetris_shapes.at(shape_index).size()) % tetris_shapes.at(shape_index).size(); } void subgame_tetris::obj_tetromino::check_spots(vector<vector<int>> _potentials, vector<vector<bool>> _sprite, int _direction) { for (unsigned int i = 0; i < _potentials.size(); i++) { int _x = _potentials.at(i)[0]; int _y = -_potentials.at(i)[1]; if (!check_collision(_sprite, x + _x, y + _y)) { change_rotation_by(_direction); x += _x; y += _y; break; } } } void subgame_tetris::obj_tetromino::rotate_piece(bool right) { int iter = (((double)right) - .5) * 2; vector<vector<bool>> new_shape = get_sprite(shape_index, angle + iter); if (!check_collision(new_shape, x, y)) { change_rotation_by(iter); } else { vector<vector<int>> offset_tests; // I piece if (shape_index == 0) { if (angle == 0) { if (iter == 1) { offset_tests = { {0, 0}, {-2, 0}, {1, 0}, {-2, -1}, {1, 2} }; } else { offset_tests = { {0, 0}, {-1, 0}, {2, 0}, {-1, 2}, {2, -1} }; } } else if (angle == 1) { if (iter == 1) { offset_tests = { {0, 0}, {-1, 0}, {2, 0}, {-1, 2}, {2, -1} }; } else { offset_tests = { {0, 0}, {2, 0}, {-1, 0}, {2, 1}, {-1, -2} }; } } else if (angle == 2) { if (iter == 1) { offset_tests = { {0, 0}, {2, 0}, {-1, 0}, {2, 1}, {-1, -2} }; } else { offset_tests = { {0, 0}, {1, 0}, {-2, 0}, {1, -2}, {-2, 1} }; } } else if (angle == 3) { if (iter == 1) { offset_tests = { {0, 0}, {1, 0}, {-2, 0}, {1, -2}, {-2, 1} }; } else { offset_tests = { {0, 0}, {-2, 0}, {1, 0}, {-2, -1}, {1, 2} }; } } } // not I piece else { if (angle == 0) { if (iter == 1) { offset_tests = { {0, 0}, {-1, 0}, {-1, 1}, {0, -2}, {-1, -2} }; } else { offset_tests = { {0, 0}, {1, 0}, {1, 1}, {0, -2}, {1, -2} }; } } else if (angle == 1) { if (iter == 1) { offset_tests = { {0, 0}, {1, 0}, {1, -1}, {0, 2}, {1, 2} }; } else { offset_tests = { {0, 0}, {1, 0}, {1, -1}, {0, 2}, {1, 2} }; } } else if (angle == 2) { if (iter == 1) { offset_tests = { {0, 0}, {1, 0}, {1, +1}, {0, -2}, {1, -2} }; } else { offset_tests = { {0, 0}, {-1, 0}, {-1, 1}, {0, -2}, {-1, -2} }; } } else if (angle == 3) { if (iter == 1) { offset_tests = { {0, 0}, {-1, 0}, {-1, -1}, {0, 2}, {-1, 2} }; } else { offset_tests = { {0, 0}, {-1, 0}, {-1, -1}, {0, 2}, {-1, 2} }; } } } check_spots(offset_tests, new_shape, iter); } } void subgame_tetris::obj_tetromino::step_function() { if (moving) { if (keyboard_check_pressed_left() || keyboard_check_pressed_right() || keyboard_check_pressed_down()) time_til_move = 0; if (keyboard_check_pressed_Y()) rotate_piece(false); if (keyboard_check_pressed_A()) rotate_piece(true); if (keyboard_check_left()) if (time_til_move <= 0) move_left(); if (keyboard_check_right()) if (time_til_move <= 0) move_right(); if (keyboard_check_down()) { if (time_til_move <= 0) { move_down(); time_til_drop_move = pause_time_drop; } } if (keyboard_check_left() || keyboard_check_right() || keyboard_check_down()) { if (time_til_move <= 0) time_til_move = pause_time; else time_til_move -= 1; } if (time_til_drop_move > 0) { time_til_drop_move -= 1; } else { time_til_drop_move = pause_time_drop; move_down(); } } } void subgame_tetris::obj_tetromino::draw_function() { vector<vector<bool>> spr = get_sprite(shape_index, angle); place_grid_sprite(game.game_grid, spr, x, y, true); } void subgame_tetris::obj_tetromino::destroy_function() { } int subgame_tetris::obj_tetromino::check_off_top(vector<vector<bool>> shape, int _x, int _y) { for (int i = 0; i < grid_width(shape); i++) { for (int j = 0; j < grid_height(shape); j++) { if (shape[j][i]) { //print_debug("> "+to_string(_x + i) + " " + to_string(_y + j)); if (_y + j < 0) { return 5; } } } } return 0; } // 0 - No Collision // 1 - Off Board Side Left // 2 - Off Board Side Right // 3 - Off Board Bottom // 4 - Another Piece int subgame_tetris::obj_tetromino::check_collision(vector<vector<bool>> shape, int _x, int _y) { game_object* rows = get_object_by_name("obj_tetris_rows"); for (int i = 0; i < grid_width(shape); i++) { for (int j = 0; j < grid_height(shape); j++) { if (shape[j][i]) { if (_x + i < 0) { return 1; } if (_x + i >= grid_width(game.game_grid)) { return 2; } if (_y + j >= grid_height(game.game_grid)) { return 3; } if (rows != NULL) { obj_tetris_rows* row_obj = static_cast<obj_tetris_rows*>(rows); if (grid_get(row_obj->filled_blocks, _x + i, _y + j)) { return 4; } } } } } return 0; } vector<vector<bool>> get_sprite(int _index, int _rotation) { return tetris_shapes.at(_index).at((_rotation + tetris_shapes.at(_index).size()) % tetris_shapes.at(_index).size()); } void subgame_tetris::obj_tetromino::move_left() { if (!check_collision(get_sprite(shape_index, angle), x - 1, y)) { x -= 1; } } void subgame_tetris::obj_tetromino::move_right() { if (!check_collision(get_sprite(shape_index, angle), x + 1, y)) { x += 1; } } void subgame_tetris::obj_tetromino::lose() { game.running = false; objects.push_back(std::make_unique<obj_explosion>(game, 5, 0)); } void subgame_tetris::obj_tetromino::move_down() { if (!check_collision(get_sprite(shape_index, angle), x, y + 1)) { y += 1; } else { game_object* rows = get_object_by_name("obj_tetris_rows"); if (rows != NULL) { obj_tetris_rows* row_obj = static_cast<obj_tetris_rows*>(rows); vector<vector<bool>> gtp = get_sprite(shape_index, angle); place_grid_sprite(row_obj->filled_blocks, gtp, x, y); //print_debug(to_string(x) + " " + to_string(y)); if (check_off_top(gtp, x, y)) lose(); } instance_destroy(); } } subgame_tetris::obj_tetris_rows::obj_tetris_rows(BrickGameFramework& game) : game_object(game, 0, 0) { filled_blocks = grid_create(grid_width(game.game_grid), grid_height(game.game_grid)); for (int i = 0; i < grid_height(game.game_grid); i++) { for (int j = 0; j < grid_width(game.game_grid); j++) { grid_set(game.game_grid, i, j, 0); } } name = "obj_tetris_rows"; } void subgame_tetris::obj_tetris_rows::step_function() { } void subgame_tetris::obj_tetris_rows::draw_function() { emplace_grid_in_grid(game.game_grid, filled_blocks, x, y, true); } void subgame_tetris::obj_tetris_rows::destroy_function() { } void subgame_tetris::obj_tetris_rows::shift_down(int starting_at) { for (int yy = starting_at; yy > 0; yy--) { for (int xx = 0; xx < grid_width(filled_blocks); xx++) { grid_set(filled_blocks, xx, yy, grid_get(filled_blocks, xx, yy - 1)); } } } void subgame_tetris::obj_tetris_rows::check_rows() { } int subgame_tetris::obj_tetris_rows::lowest_occupied_line(std::vector<std::vector<bool>>& grid) { return 0; }
24.596178
131
0.472757
Chrscool8
895a6c3a827ff05009eac170a1e39c165b2d1f38
30,545
inl
C++
src/fonts/stb_font_arial_28_usascii.inl
stetre/moonfonts
5c8010c02ea62edcf42902e09478b0cd14af56ea
[ "MIT" ]
3
2018-03-13T12:51:57.000Z
2021-10-11T11:32:17.000Z
src/fonts/stb_font_arial_28_usascii.inl
stetre/moonfonts
5c8010c02ea62edcf42902e09478b0cd14af56ea
[ "MIT" ]
null
null
null
src/fonts/stb_font_arial_28_usascii.inl
stetre/moonfonts
5c8010c02ea62edcf42902e09478b0cd14af56ea
[ "MIT" ]
null
null
null
// Font generated by stb_font_inl_generator.c (4/1 bpp) // // Following instructions show how to use the only included font, whatever it is, in // a generic way so you can replace it with any other font by changing the include. // To use multiple fonts, replace STB_SOMEFONT_* below with STB_FONT_arial_28_usascii_*, // and separately install each font. Note that the CREATE function call has a // totally different name; it's just 'stb_font_arial_28_usascii'. // /* // Example usage: static stb_fontchar fontdata[STB_SOMEFONT_NUM_CHARS]; static void init(void) { // optionally replace both STB_SOMEFONT_BITMAP_HEIGHT with STB_SOMEFONT_BITMAP_HEIGHT_POW2 static unsigned char fontpixels[STB_SOMEFONT_BITMAP_HEIGHT][STB_SOMEFONT_BITMAP_WIDTH]; STB_SOMEFONT_CREATE(fontdata, fontpixels, STB_SOMEFONT_BITMAP_HEIGHT); ... create texture ... // for best results rendering 1:1 pixels texels, use nearest-neighbor sampling // if allowed to scale up, use bilerp } // This function positions characters on integer coordinates, and assumes 1:1 texels to pixels // Appropriate if nearest-neighbor sampling is used static void draw_string_integer(int x, int y, char *str) // draw with top-left point x,y { ... use texture ... ... turn on alpha blending and gamma-correct alpha blending ... glBegin(GL_QUADS); while (*str) { int char_codepoint = *str++; stb_fontchar *cd = &fontdata[char_codepoint - STB_SOMEFONT_FIRST_CHAR]; glTexCoord2f(cd->s0, cd->t0); glVertex2i(x + cd->x0, y + cd->y0); glTexCoord2f(cd->s1, cd->t0); glVertex2i(x + cd->x1, y + cd->y0); glTexCoord2f(cd->s1, cd->t1); glVertex2i(x + cd->x1, y + cd->y1); glTexCoord2f(cd->s0, cd->t1); glVertex2i(x + cd->x0, y + cd->y1); // if bilerping, in D3D9 you'll need a half-pixel offset here for 1:1 to behave correct x += cd->advance_int; } glEnd(); } // This function positions characters on float coordinates, and doesn't require 1:1 texels to pixels // Appropriate if bilinear filtering is used static void draw_string_float(float x, float y, char *str) // draw with top-left point x,y { ... use texture ... ... turn on alpha blending and gamma-correct alpha blending ... glBegin(GL_QUADS); while (*str) { int char_codepoint = *str++; stb_fontchar *cd = &fontdata[char_codepoint - STB_SOMEFONT_FIRST_CHAR]; glTexCoord2f(cd->s0f, cd->t0f); glVertex2f(x + cd->x0f, y + cd->y0f); glTexCoord2f(cd->s1f, cd->t0f); glVertex2f(x + cd->x1f, y + cd->y0f); glTexCoord2f(cd->s1f, cd->t1f); glVertex2f(x + cd->x1f, y + cd->y1f); glTexCoord2f(cd->s0f, cd->t1f); glVertex2f(x + cd->x0f, y + cd->y1f); // if bilerping, in D3D9 you'll need a half-pixel offset here for 1:1 to behave correct x += cd->advance; } glEnd(); } */ #ifndef STB_FONTCHAR__TYPEDEF #define STB_FONTCHAR__TYPEDEF typedef struct { // coordinates if using integer positioning float s0,t0,s1,t1; signed short x0,y0,x1,y1; int advance_int; // coordinates if using floating positioning float s0f,t0f,s1f,t1f; float x0f,y0f,x1f,y1f; float advance; } stb_fontchar; #endif #define STB_FONT_arial_28_usascii_BITMAP_WIDTH 256 #define STB_FONT_arial_28_usascii_BITMAP_HEIGHT 102 #define STB_FONT_arial_28_usascii_BITMAP_HEIGHT_POW2 128 #define STB_FONT_arial_28_usascii_FIRST_CHAR 32 #define STB_FONT_arial_28_usascii_NUM_CHARS 95 #define STB_FONT_arial_28_usascii_LINE_SPACING 18 static unsigned int stb__arial_28_usascii_pixels[]={ 0x26000031,0x00988001,0x01310062,0x037d404c,0xfffb80ae,0x9ffff32f, 0x80000600,0x02600009,0x26000026,0x20011000,0x00040009,0x00000000, 0x0fe20011,0x3ffb2600,0x400aceff,0xfd80dffa,0x20bff701,0x06fa80fb, 0x754037a6,0xdff32ffe,0x3f6e207d,0x2001bdff,0xbefffec8,0x517e2001, 0x7f64c05f,0x203ec0ce,0x201dffd8,0xfb5003f9,0x75c0039f,0x75c02dff, 0x6d400bdf,0x404effff,0xfd3000fb,0xffb99bdf,0x7ecc09ff,0x981fd84f, 0x3f883fff,0xeb887930,0x202effff,0x80df32fe,0xffeffffa,0xffa804ff, 0x5ffffeff,0xfc87f500,0xfdfff701,0x00fdc1ff,0x05fd5bfb,0x7fe401f6, 0x4400ffec,0x5ffffffe,0xfffffe98,0xffff902f,0x401dffff,0xdffa804f, 0x3bfee602,0x361be600,0x204fb81f,0xffd8006c,0x02ffedec,0x81be65fd, 0x64c1dff9,0x3fee04ff,0x2ffdcc1e,0x1fa17dc0,0xfd517fd4,0xdf01fccd, 0x1fcc37cc,0xfb07fc40,0x12efd807,0xffe87ff7,0x41ffb88b,0x75cc3ffb, 0x803ee07f,0x22002ffa,0x43fc06fe,0x03fd81fd,0xf98007f3,0x1bf67b1f, 0x06f997f4,0xfa807ff3,0x04ff883f,0x36027fcc,0xfe837c0f,0x3e0ff984, 0x7f89f306,0xbf7007e8,0x7fc06fa8,0x3ee6fc83,0x746fa81f,0x0bfe604f, 0xff882fc4,0x7f440300,0x3f61fe04,0xfb01fd81,0xf737d401,0x0ff99ecb, 0x0df32fe8,0x7e4017fa,0x8037ec1f,0x1ba02ffb,0x0df309f3,0x01f9065c, 0x20fe85f7,0xdf7003fa,0x3e604fc8,0x367f980f,0x23ff106f,0x7ec01ff8, 0x3607fa04,0x7ffe4c2f,0x1fa29f94,0x0fec0ff8,0x2fcc0fec,0x4fc9bea0, 0x3fa008f6,0xff10df32,0x31ff4003,0x7ec003ff,0x3fffff64,0x4fffffff, 0xf50013f2,0x7f89f505,0xff100374,0xf007fea7,0x74df705f,0xf93f603f, 0x004c403f,0x44fa89f7,0xcffceff9,0x407f22fe,0x40fec0fe,0x03fc81fe, 0x4df737d4,0x25fd003d,0x06fa86f9,0xff52fec0,0x326fc800,0xeeeefeee, 0x3f63eeff,0x20179513,0x26f984f8,0x00fea6f9,0x7ffbff70,0x441dfb00, 0x80ffa3fe,0x2fff65fd,0x17e60000,0x1ff443f9,0xfa83fff2,0xfd83fd03, 0xfe81fe81,0xf337d401,0x2007b19f,0x90df32fe,0x6fb800bf,0xf5001bee, 0xfd07ee0f,0x3feebfa0,0x0fd03fff,0x87faf7f6,0xffd0006e,0x7fe4003d, 0x7ec3ffdd,0x44bff106,0x09befffe,0xfd1fe200,0xff884fe8,0xfd82fc47, 0x7fc0fec2,0x5400ff80,0x7fffdc6f,0x32fe800c,0x009fb0df,0xbf90ffa8, 0x81ff8800,0xf82fc0fd,0xffbbffdf,0x701fc83f,0x17d43bfd,0x77ffec00, 0x3ffa2000,0x7fdc0eff,0xc86ffb80,0x1dffffff,0x2fc1ff00,0x3fa01ff3, 0xdf506f85,0x2fdc1fd8,0x7d403fc4,0xffffea86,0x4cbfa01d,0x004fe86f, 0x5fd87fcc,0x40ffc400,0xf827cc6f,0x0ffb84ff,0x20201fcc,0x405edc6e, 0x5ffaefe9,0x6ffdc062,0x742ffeba,0xefd99cff,0xfd95105f,0xff007fff, 0x5fb8fe63,0xbf10ff60,0xfd977dc0,0x301dfb11,0x0df500df,0x17ffff4c, 0x0df32fe8,0xfb800bf9,0x3001bee7,0xb8bf10ff,0x01fff02f,0x0bf07ff1, 0x3fa2fb80,0x6ffc4ffe,0x3f69ff50,0x5c0ffcc5,0x3ffa60ff,0x05facfff, 0x09ffd710,0x45f72fe8,0x0bfa03fd,0x4fd807f5,0x03fe63fb,0x7d4037d4, 0x7f55ec06,0xf32fe80f,0x800df50d,0x01fe66fc,0x7764df50,0xeffeeeff, 0x817fa3ee,0x007d84fd,0x229f337c,0x90ff51fd,0xc85ff5ff,0x20bfe06f, 0x9f72cedb,0x80ff9000,0x7c3f91ff,0x81ff102f,0x3bf201fd,0x3f623fb2, 0x807f980d,0xf1ec06fa,0x265fd07f,0x00ff886f,0x3ff13fa0,0xfb27ec00, 0xffffffff,0x1fec9fff,0x5f70bf90,0xfc8bee00,0x27ecfee1,0xe86fffd8, 0x017f202f,0x07d93fc8,0x2203ff10,0xfd8bea7f,0xfa8df903,0xfb1be605, 0xf885fb83,0x137d400f,0xbf91ec13,0x1be65fd0,0x22d82ffc,0x37ec1ffb, 0xd82ff980,0xc817e20f,0x20ffa05f,0x8df004f8,0x6d3e60fe,0x7ffd104f, 0x7e407fd0,0x7fc03315,0x3e00df71,0x44df301f,0x261bf23f,0x03fe64ff, 0x0fec2fc8,0x0ff407fc,0x2ff9bea0,0xe84fc8f6,0x260df32f,0x77fc43ff, 0xff884ffa,0x82ff4404,0x1027cc6f,0x3ff101ff,0x3ee01ba0,0x9f507f42, 0x3a203fea,0x2fe40eff,0xdf73ff88,0xff89bea0,0x503fd403,0x3e65f89f, 0x37ffea3f,0x7403ffb8,0x740fec1f,0x402fd81f,0xd97f26fa,0x3fa0ffe3, 0x7d40df32,0x3ff220df,0x37fe606f,0x105ffa81,0x402fb89f,0x3f620efd, 0x8803f206,0x2e1fd86f,0x8877fe3f,0x20effffe,0x7e443ff9,0x985ff10f, 0x67fec0ff,0x027fdc41,0x20fd87f9,0xdcfffffb,0x802fffff,0x40fec0fe, 0x03fb81fe,0x7ff537d4,0x407fe4f6,0x80df32fe,0xfeeffffa,0x2602efff, 0xffeeffff,0x90fea05f,0xffe8801f,0x200effdd,0x07ee03fa,0x3fa237ea, 0x3b7ffee0,0x6ffa9eff,0x7ee77fdc,0x77fdc2ff,0xf902ffdc,0xffffdfff, 0x541fe807,0x96fed45f,0x220cefe8,0x6c0ff809,0x981fd81f,0x237d405f, 0xffeeeffc,0x265fd02f,0xfdb9806f,0xffbaceff,0xffb5101e,0xfc8059df, 0xf9003f41,0x8801bfff,0x40df105f,0x982ffffc,0x20cffffe,0xffe983fa, 0xf9501eff,0xda805bff,0x02dffffe,0x3fc837cc,0x077e4000,0x07f607fc, 0x0ff407f6,0xfd70bf70,0x7403dfff,0x000df32f,0x03f91013,0x29800260, 0x188002a8,0xc9815400,0x4015c401,0x10020098,0x00180033,0x6c001310, 0x033fa01f,0x01ffb100,0x1fd81ff1,0x9f302fc8,0xd102fe40,0x25fd001b, 0x800006f9,0x00000000,0x00000000,0x00000000,0x00000000,0x05f88000, 0x055fff4c,0x03dfd510,0x07f61be6,0x0fd813f2,0x2017fee4,0x3fbaa03d, 0x7ddff32f,0x00000000,0x00000000,0x00000000,0x00000000,0x40000000, 0xfd5000fc,0xdb99bfff,0x36607fff,0x81fd84ff,0xf883eff9,0x4027ffc4, 0x3ffee02b,0x9ffff32f,0x00000000,0x00000000,0x00000000,0x00000000, 0x20000000,0xdb8003f8,0xdefffffe,0x37fea00c,0xf701fd80,0x883f20bf, 0x00000009,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x880000c4,0x04c40009,0x09880310,0x00000260,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x01880000, 0x22003100,0x40000000,0x44000001,0x21ff0000,0x000006fa,0x20620000, 0xcccccccb,0x3e00c404,0x0ff9802f,0x04c000c0,0x7c40ff50,0x29fb000f, 0x10df56fa,0x9dfffd95,0x4417e001,0x1dffffdb,0x1ceec980,0x6fffed40, 0x76441fd8,0x3ee01cef,0x21ff0001,0x5c0006fa,0xffeb882f,0x7ffe403e, 0x7fffffc5,0x19f50fff,0xf03bfffd,0x1ff3005f,0x2bfffb50,0x7ff4c0fe, 0x1ff80dff,0x6c00bf70,0x3eadf54f,0x7ffffd46,0x402ffffe,0xfff983f9, 0x04ffffef,0x3fffbff2,0xf9fff502,0x7c43fddf,0x02fffeff,0x3e0003ff, 0x000df50f,0x3e617fd4,0x0effffff,0x23efffa8,0xaaaaaff9,0x3ffbea2a, 0x7c0fffce,0x0ff9802f,0x7f67ffcc,0x3fea0fee,0x42fffddf,0x05fd04fc, 0x3c9a7ec0,0x77fd4df5,0x1ffecc0a,0xff983f90,0x3ff6a0ad,0x2a1ef983, 0x5ffc41ff,0xe87ffee0,0x3ff711df,0x20003ff0,0x00df50ff,0xd0bffea0, 0x37f545bf,0x5fa82fec,0x45dff500,0x17fc6fc8,0xf107fcc0,0x0fffb87f, 0x6c41bff1,0x21fe60ff,0x7ec007f8,0x3e2df504,0x06fc805f,0x09ff31ba, 0x7f40ffe8,0x7e45fb81,0x2a3ff705,0x84fd80ff,0xf83001ff,0x0c4df50f, 0x3ffff220,0x2603fea2,0x81fec1ff,0xff5003fc,0xff8bfa05,0x20ff9802, 0x1ff905fc,0x3e203fee,0x2e17f43f,0x27ec004f,0x1ff96fa8,0x105ff100, 0x00efd89f,0xdf527fcc,0xfe83fe20,0x75c7fe01,0x7e4df705,0xda83ffff, 0x0ff8cfff,0xfffd1df5,0xafff883d,0x817f22fe,0x817f43fe,0xdf5001fd, 0x5ff27dc0,0x6c1ff300,0x21ff102f,0x13f605fd,0x01fe8bf7,0x6faa7ec0, 0x00ffadf5,0x2fa80aa8,0x1a800ffc,0x5fd027e4,0x3fd007fc,0xeb93f600, 0x7cc2eeff,0xffeffcff,0xbdffff50,0x6fcc3fff,0x0d445fd0,0x3ff67fd0, 0x47fc6fff,0xfa83dec9,0xff97ea05,0x20ff9802,0x83fe01ff,0x10ff6008, 0x01be61ff,0xb7d53f60,0x01ff8efa,0x4c1f9000,0x3a0000ff,0x44ff603f, 0x07fa00ff,0x3e0bfe60,0x0bff881f,0x7d43ffee,0x9bf622ef,0x0017f418, 0x3fb23ff3,0x3fe25eef,0x0effffff,0x6fa817ea,0x3e600bfe,0x401ff10f, 0xff3000fe,0x3f27fb03,0x54fd8003,0x3e7beadf,0xdf00000f,0x40007fb8, 0x93f203fe,0x07fe01ff,0x817ff5c4,0x05fc81ff,0x3fea1ff9,0x7405ff02, 0x1bf6002f,0x3fea0bfa,0x6ffda8ae,0x5fb817ea,0x3e600bfe,0xf807fe0f, 0x3ff9800f,0x03febf50,0x7d53f600,0x0df7df56,0x4cccccc4,0x3f21fcc1, 0x17f40005,0x17f49f90,0xf701ff88,0x3fe01bff,0xf102fd81,0xc81bea1f, 0x00bfa04f,0x7f40ffdc,0xf505c982,0xc81bea5f,0x200bfe3f,0x0bfa0ff9, 0x7cc00ff8,0x7d7fc04f,0x29fb0005,0xf9df56fa,0x7fffe40d,0x20fdc7ff, 0x7c0005fc,0xb97ee02f,0x03ff706f,0x0fffaea6,0x07fe07fe,0x0bf50ff8, 0x5fd02fdc,0x207ff700,0xff0002fe,0x7c07feab,0x200bfe2f,0x837dc7f9, 0x3e200ffb,0xfefc805f,0x29fb0002,0xf5df56fa,0x3fff201f,0x43ec7fff, 0x740007fb,0x893f202f,0xff932eff,0x3fee003f,0x3e20ffc0,0x543fa00f, 0x81bea05f,0x7fe402fe,0x000bfa03,0xeffab7e4,0xfd17f662,0x88ff5007, 0x3fea0cff,0x017f600f,0x0007ffcc,0x2df54fd8,0x01ff8efa,0x5f89fea0, 0x1000ff98,0x3603fd81,0x7fffcc3f,0x001ffdff,0x03ff0bfe,0x87fc03ff, 0x17ee05fa,0x3f602fe8,0x017f402f,0xff56fb80,0x1dffbdff,0xfb804fd8, 0xecfffa85,0x3e00ffef,0x13fa000f,0x4ffa0330,0x3adf56fa,0x9fea003f, 0x03ff02fa,0x3fc9bee0,0x3220bf60,0x01ff3dfe,0x3fe2fe40,0xf102fd81, 0xc81bea1f,0x20bfa04f,0xe801ffd8,0x203ed82f,0xd3df55fe,0xf9019fff, 0x209fb00b,0xf8dfffe9,0x00ff100f,0x3e601fe8,0x3ea5fd07,0x3ff2df56, 0x64ff5001,0x00dfd00f,0x05fb93fa,0xff0003fe,0xfe80ff61,0x7dc0ff44, 0x2a1ff705,0x2ff881ff,0xfd10bfa0,0x0bfa001d,0x7fcc1ff2,0x00c4df52, 0xf880bfea,0xf04c403f,0x0132201f,0x7c406f98,0xf51ff80f,0x7fc5bead, 0x3fec401f,0x27fcc0dd,0xf887ff20,0x646fa80f,0x64df502d,0x87ff307f, 0xcff882fe,0x543ffea0,0x3f660eff,0x3617f406,0x3fa000ef,0x4c4ff982, 0x01bea6fd,0x502bff60,0x3e000bfd,0xd100000f,0x3bfd005f,0x7d43ff62, 0x7fd4df56,0x7fdcc1bf,0xa809f15f,0x36a21cff,0x45fc83ff,0x77dc1fe8, 0xf327fc40,0x86fd987f,0x7cc3fffd,0xffefecff,0xbbffdf50,0xfe803fff, 0x266bfea2,0x74099999,0x9fff702f,0x7d41dffd,0xffe88006,0x0effffff, 0x201ff000,0x3f200cc9,0xff5006ff,0x545fffdf,0xf98df56f,0xfffeffff, 0x007ee2ef,0x3fbffff2,0xfd104fff,0x109ffb9d,0xffd9bffd,0xd9fff70b, 0xfd103fff,0xfffb30bf,0x3ea1fd1b,0x0dfffe9c,0x3fe2fe80,0xffffffff, 0x5017f44f,0x81bffffd,0x910006fa,0x19fffffb,0x807fc000,0x3ee00ffa, 0x3ea000ef,0x7d42efff,0x9510df56,0x07bffffd,0x7ed400fb,0x401effff, 0x03dfffd8,0x3bfff6e2,0x3fffaa03,0x800800df,0x00188001,0xfff897f4, 0xffffffff,0x44017f44,0x01bea009,0x000cc400,0xf500ff80,0x0009801f, 0x00002620,0x55002620,0x00666000,0x0c0004c0,0x00066200,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x7e406fc8,0x47fe203f,0xf7001ffc,0x3fffea3f,0xffffffff,0x003ff66f, 0xffff17fa,0x59bdffff,0x7fffffc0,0xfd82deef,0x4bfe2006,0xf9804ff8, 0x013ffe27,0xff8bffd4,0x07fe2001,0x2a1dff50,0x1bea006f,0x9802ff80, 0x3ffee0ff,0xffffffff,0x401ff52f,0x3ea05fff,0x201bfa27,0x3fea3ff9, 0xffffffff,0x3fe26fff,0x2077e405,0xffffffff,0xff04ffff,0xffffffff, 0x0ffd41df,0x3e27fb80,0x3fcc01ff,0x200dfff1,0x3ff17ffd,0x00ffc400, 0x6fa8bff5,0x801bea00,0xff9802ff,0x3ffffee0,0x2fffffff,0x77cc07fe, 0x317f207f,0x6fe807ff,0x64ccccc4,0x099999ef,0xfa81ffd4,0x102ff81f, 0xff09ffb7,0x93333337,0x03ff8bff,0x7fc49fd0,0x9fe600ef,0x401ffff8, 0xff17fff8,0x0ffc4003,0xfa85ffa8,0x01bea006,0xf9802ff8,0x2666620f, 0xffe99999,0x7dc0ff60,0x5fd01feb,0x2e03ff90,0xdf7000ff,0x20ffe400, 0x5ff03ff8,0xff0dfb00,0x21ffb803,0xff8806fc,0x13fffe20,0x3fe27f98, 0x77d404fd,0x003ff17f,0x7d40ffc4,0x00df505f,0xff0037d4,0x01ff3005, 0x5c2ffc80,0xf93fb05f,0x101ff107,0x7ff10dfd,0x0037dc00,0x0bfd1bfa, 0x7d4017fc,0x200ffc0f,0x3fe23ff8,0x222fdc01,0x302ffcff,0x7d7fc4ff, 0xbfdfec06,0x22001ff8,0x2ffd41ff,0x0098df50,0x7fc00df5,0x00ff9802, 0x260ffee0,0xf37f887f,0x540df50d,0x02fec3ff,0x3001bee0,0x03ff29ff, 0xf9802ff8,0x400ffc0f,0x027ec4fe,0x1ff10bfa,0xff301dfb,0x0ff47fc4, 0x17f9ef88,0x7c4003ff,0x017fea1f,0xfffb1df5,0xa86fa87d,0x00bfe2ff, 0x4c003fe6,0x07fe05ff,0x207fcbf5,0x7fe404fc,0x8001ff70,0xfb8006fb, 0x7c01ffbf,0x85fc802f,0x7fcc01ff,0xf303fd42,0xf11ff10f,0x44ff309f, 0x504fc8ff,0x3e2ff37f,0x3fe2001f,0x5009ff51,0xffbdfdff,0x2a37d45f, 0x017fc2ff,0x44007fcc,0x1fec06ff,0x42fd8bf2,0x7f4402fe,0x8002ff8d, 0xfb0006fb,0x5ff007ff,0x0bff6660,0xffb007fe,0x3205ff01,0x50ff884f, 0x27f985ff,0x06f98ff8,0x22ff31fb,0x3e2001ff,0x00fffa9f,0x220fffa8, 0xa9bea6fd,0xcdff82ff,0xdccccccc,0xffe800ff,0x3a27dc00,0xf893ee0f, 0xeffa800f,0xdf70005f,0x1ffe2000,0x7fffffc0,0x04ffffff,0x755559ff, 0x3209ffd9,0x103ff05f,0x077ec1ff,0x87fc4ff3,0x9afc41fe,0x003ff17f, 0x7ffdffc4,0x1ffa804f,0x5bea7fa8,0xfff02ffa,0xffffffff,0xfc801fff, 0x26f9801f,0x53fcc6f8,0x7fe400bf,0xdf70000f,0x3fff2000,0xfffff803, 0x01beffff,0x3ffffffe,0x2603ffff,0x837d40ff,0x3fe20ff8,0xff89fe64, 0x2fb89f90,0x07fe2ff3,0xbffff880,0x7d402ffb,0x7d43fe07,0x3e02ffae, 0xccccccdf,0x200ffdcc,0x3e003ffb,0xff09f70f,0x8800ff21,0x2e0002ff, 0xffa8006f,0x7fc01ffd,0x017fe4c2,0x37bbbbfe,0xfe800abc,0xf881fec2, 0x997fd40f,0x4c3fe27f,0xf987ec6f,0x4003ff17,0x3f63fff8,0x81bea00f, 0xffff51ff,0x017fc05f,0xf9807fcc,0x97e4005f,0xd2fc81fd,0x2ff8003f, 0x01bee000,0x3fa9ff10,0xc817fc06,0x07fe02ff,0x897ee000,0x1ff100ff, 0xff31ffb0,0x3fd07fc4,0x17f997e2,0x7c4003ff,0x037fc43f,0x8ffc0df5, 0x0ffdfffa,0xf3005ff0,0x0dff101f,0x1fe9f500,0x007fa7d4,0x20002ff8, 0x7ec006fb,0xf813fe66,0x07ff602f,0x40000ffc,0x09f70ff8,0x7c407fc4, 0x3e27f9cf,0x7dd3f20f,0x7fc5fe62,0x07fe2001,0x7d413fea,0x7d47fe06, 0x3e0bfd1f,0x0ff9802f,0x8000ffe8,0x105f9ef8,0x000bf3df,0x5c0005ff, 0x3fee006f,0xf817fe41,0x1bfe202f,0x80000ffc,0x403fd3fd,0xff700ff8, 0x07fc4ff7,0x983fadf3,0x003ff17f,0xfc80ffc4,0x206fa82f,0x4cdf51ff, 0x02ff82ff,0x7e40ff98,0x3fa0001f,0x2ffa03fc,0x2ff8002f,0x01bee000, 0xfe81ffcc,0x402ff80f,0x1ff83ffb,0x3bf50000,0x0ff880df,0x89ffff60, 0x7d7f40ff,0xff8bfcc5,0x07fe2001,0x7d40ffe8,0x7d47fe06,0x3e07fdc6, 0x0ff9802f,0x0000ffea,0x6401fff9,0xf8000fff,0x3ee0002f,0x05fe8806, 0x3fe17fe2,0x40ffd802,0x200001ff,0x4403fcfe,0x3fe200ff,0x703fe27f, 0x7f985fff,0x33335ff1,0x7fc43333,0x517fe601,0xa8ffc0df,0x7c5fe86f, 0x0ff9802f,0x3333bff3,0x01333333,0xf301bfea,0x3fe000df,0x1bee0002, 0x7003ff60,0x02ff87ff,0x7fc5ff88,0x3ee00001,0x7fc400ff,0x13ffdc00, 0x7ff981ff,0xfff17f98,0xffffffff,0x2e00ffc4,0x81bea3ff,0x30df51ff, 0x017fc5ff,0xffb87fcc,0xffffffff,0xff104fff,0x009ff009,0x8000bfe0, 0x7fdc06fb,0x43ffb002,0xff7002ff,0x0000ffc7,0x100bff10,0xffb001ff, 0x7f407fc4,0xff17f984,0xffffffff,0x400ffc4f,0x0df51ffe,0x06fa8ffc, 0x0bfe1ff9,0x7dc3fe60,0xffffffff,0x0004ffff,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x7ffc0000, 0xffffffff,0x3ffffe0f,0x7fffffff,0x7ffffffc,0xbf900cee,0x3bbbbbb2, 0xff14eeee,0x79dfffff,0x09ff5000,0x3600dfd0,0x202fec1f,0x0cc00099, 0x00033100,0x02200033,0x80600300,0x40df5008,0x804c00ff,0x3e5755fd, 0xffffffff,0x3ffe0fff,0xffffffff,0x7ffffc7f,0x84ffffff,0xffffd5fc, 0x2bffffff,0xfffffff8,0x2000dfff,0xfe807ffd,0x41ffb806,0xffea85fd, 0x36203fff,0x300dffff,0x03dffffb,0x6fffff4c,0x7ffecc00,0x4e7d40bd, 0x19f52fff,0x261dfffb,0x7d43effe,0x7d43fe06,0x3ffffd8c,0xf5fdafec, 0x3333337f,0x9bff8333,0x99999999,0x4ccdffc1,0x44ffeba9,0x555555fc, 0x27ff7555,0x9999aff8,0x1006ffba,0xe805fbdf,0x7ffcc06f,0x3f21e5c1, 0x4fffdcef,0xecdfff98,0x77fcc1ff,0xa82fffcc,0xfffedfff,0xbbfff101, 0xfdfa8bff,0xdbf51fff,0xf5dffdbf,0x549ffdbf,0x543fe06f,0xffdefedf, 0x7ecf2e3f,0xf0005ff5,0x3fe0005f,0x90ffec01,0x97f600bf,0x3e601ff8, 0xacfb800f,0x037f406f,0x2007fffa,0x7fc81ff8,0x7e40cfe8,0x7ec27e46, 0x3067fc45,0x9fd10dfb,0xf517f441,0xffa8a3df,0x33ffe60f,0x6fa9fee0, 0x7fd43fe0,0x2037ec1e,0x0005ff4c,0x3e0005ff,0x26fd801f,0xffb805fc, 0xf007fe20,0x15fd005f,0x37f403ff,0x03fd7f90,0x3e60bd70,0x403fee0f, 0x20bf62ff,0x037e42c8,0x06fb87ff,0x17fd4bf5,0xfe81ffa8,0xf50ff886, 0xfa87fc0d,0x00ff981f,0x0017fcba,0xf80017fc,0x1ff9801f,0xff880bf9, 0x200ffc42,0x7fcc01ff,0x7ec09fb0,0x3fabf505,0xff880001,0xfd813f60, 0x002fff24,0x5fb80bfa,0xf5001fe4,0x03fea01f,0x8ffc17f2,0x43fe06fa, 0x03fe07fa,0x02ff8764,0x0002ff80,0x3fe003ff,0xfd80bf92,0x201ff884, 0x5fc807fa,0x5fc81fea,0x3fd0ff88,0xedca9800,0x3bfa0fff,0xfeeeeeee, 0x3bfffa25,0x403ff01b,0x017f46fa,0x7d40ff50,0x3e09f907,0x7c0df51f, 0x7c0df50f,0xbff8301f,0x09999999,0xaaaacff8,0x7c0aaaaa,0x27fd001f, 0x3fea05fc,0xaabff880,0x01efdcaa,0x17fc2ff8,0x2fd84fc8,0x754007fa, 0xffceffff,0x3fffffe0,0x446fffff,0x0efffffc,0xf9803fe2,0x5000ffc7, 0x837d40df,0x23ff04fc,0x1ff106fa,0x1ff81bea,0xffffff00,0xff0dffff, 0xffffffff,0x01ff83ff,0x17f2bfb0,0xff105fd8,0xffffffff,0x90ff5005, 0x513ee0df,0x801fe8bf,0x221bdffa,0x00bfe0ff,0xfffd7300,0xf500ffc1, 0x2002fe8b,0x1bea06fa,0x1ff827e4,0x3fe60df5,0x7fc0df50,0x3fe57501, 0xeeeeeeee,0xeeeeff85,0x41eeeeee,0xbfb001ff,0x7fc417f2,0xdddff101, 0x09fffddd,0xff984fd8,0x3e23fb81,0x400ff40f,0x1ff304fe,0x20102ff4, 0x745ff300,0xb13ee02f,0xa866c07f,0x41bea06f,0x23ff04fc,0x1ff707f9, 0x1ff81bea,0x0bfebfb0,0x000bfe00,0xfe800ffc,0x3ee0bf94,0x807fe206, 0xff104ffa,0xff555559,0x7f47f509,0x65c1fe81,0x7dc0bfe3,0x403ff21f, 0x407fe4fe,0x817f23fe,0x837dc2fe,0x81bea7fa,0x09f906fa,0x1ffc47fe, 0x7d43ffea,0x65c7fe06,0x0bfebfb3,0x000bfe00,0xff800ffc,0x3fa0bf93, 0x007fe203,0x3fee0ff7,0xffffffff,0xfb97d40f,0xffaaaaae,0x6cbfb1ac, 0x1fffa85f,0xf9077fe2,0x4c0efb8d,0x33fe20ff,0x103bf660,0x7f4419ff, 0xfa81bea4,0x3e09f906,0x33bff21f,0xf50fedfe,0xfd8ffc0d,0x0005ff05, 0x3e0005ff,0x1ff9801f,0x1ff30bf9,0x200ffc40,0xdfe81ff8,0xfccccccc, 0xfc97cc3f,0xffffffff,0x4cbfb5ff,0xdfecbeff,0x7ffd42fe,0xe81fffcd, 0x4ffecdff,0xfddfffb8,0xfff500ef,0xfa8dffbb,0x641bea06,0xb83ff04f, 0x1fd4ffff,0x1ff81bea,0x0bfe0bfb,0x000bfe00,0x7f400ffc,0x3f217f26, 0x00ffc405,0xff307fe6,0x446fd801,0xddddd70c,0x49ddffdd,0x7fffdc4c, 0xb10bf92f,0x2039dfff,0x2effffd9,0x3bfffa60,0x7ff4c00c,0x37d40cff, 0x3f20df50,0x2203ff04,0xf037d400,0x0bfe003f,0x000bfe00,0x3ee00ffc, 0x3617f22f,0x0ffc404f,0x3f21ff20,0x01ff9805,0x3a07fa00,0x00013302, 0x99880026,0x0004c000,0x00000198,0x00000000,0x05ff0000,0x3337ff00, 0x13333333,0x4cccdffc,0x645ffda9,0x402fe85f,0x9999aff8,0xf84ffc99, 0x49fd002f,0x3fd003cb,0x00000ec8,0x00000000,0x00000000,0x00000000, 0x3fe00000,0xffff8002,0xffffffff,0x3ffffe2f,0x84ffffff,0x01ff85fc, 0x7fffffc4,0xa85fffff,0x3fee007f,0x3a00bfb0,0x00000c1f,0x00000000, 0x00000000,0x00000000,0x7fc00000,0xffff8002,0xffffffff,0x3ffffe2f, 0x901ceeff,0x807f98bf,0xfffffff8,0x9fb01def,0xd9ffc400,0x03fd005f, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x4427fc40,0x000ee4fe,0xff981bee,0xff307fb0,0x640bf505,0x7fffc01e, 0x04ffffff,0x1300e440,0x65404c00,0xcccccccc,0x369fd0cc,0x0449fb4f, 0x88166e54,0x99999912,0x33333265,0xcccccccc,0x0000000c,0x00000000, 0x3f60ffd4,0x0067fe46,0xf900ff88,0x7dc2fdc9,0x203fc84f,0x777402fd, 0x3ffeeeee,0x03ffb500,0x7c003fea,0xfffffc84,0xd1ffffff,0x7ed3fa9f, 0x7e43ff75,0x99cfffff,0xffff13eb,0x3ffea7ff,0xffffffff,0x00000fff, 0x00000000,0x2a6fd800,0x7fecc1ff,0x3fd802df,0x3fc43fd0,0x7fc37fec, 0x000bf600,0x2202ff44,0x00cfffeb,0xf0c07ffb,0x5554c227,0xaaaaaaaa, 0x53fa9fd0,0xe97f25fd,0xffffecdf,0x99913fff,0x00005999,0x00000000, 0x20000000,0x3ff8cff8,0x3bfff220,0x30df500b,0xf83fd0df,0x1be60fee, 0x20005fb0,0x3f2606fd,0x7cc02eff,0x2fbe07fe,0x0004fcce,0xb3fd9ff4, 0x1b1fd89f,0x3fffeb88,0x00000000,0x00000000,0xf9800000,0x2a005fef, 0xf81cfffe,0x641fe41f,0x3f73e64f,0xfb00ff22,0x1df90005,0x39fffd50, 0x3f2bf200,0xfffdb882,0x640002ce,0x3ee5f92f,0x8800d443,0x00000000, 0x00000000,0x40000000,0x8000effc,0x641fffc9,0x4c07fc4f,0x3eebee6f, 0xeeb83fa4,0xeeeeffee,0x07fee01e,0x002fbff2,0x0df37f88,0x4c41ffc8, 0x99999999,0x7d47ee19,0x00003f51,0x00000000,0x00000000,0x30000000, 0x54000bff,0x3fcc1ffd,0x87fc0bf5,0xf16f88fe,0xfffffc8d,0x01ffffff, 0x3f205ff5,0x7dc000cf,0x7dc07fa4,0x3ff21fda,0xffffffff,0x1144511f, 0x00000015,0x00000000,0x00000000,0xffd00000,0x75c4007f,0x5fd03eff, 0xafc80bf6,0x2e3fa6f8,0x4cccc44f,0x01999bfd,0x64407ff3,0xf002dfff, 0xe82fd41f,0x775c9f15,0xeeeeeeee,0x0000001e,0x00000000,0x00000000, 0x40000000,0x01ffaefc,0x16fffe4c,0x3fe33ee0,0x3eb7ea00,0x07f6bf24, 0x2200bf60,0xd71004ff,0x2a017dff,0x100ff85f,0x00000004,0x00000000, 0x00000000,0x00000000,0x23ff5000,0xffd506fc,0x3e20039f,0xff804fbf, 0x3f7ea1fc,0x805fb007,0x50005fe8,0xe83bfffb,0x004fc82f,0x00000000, 0x00000000,0x00000000,0x00000000,0xf88ffe20,0x5f7fe44f,0xfffd8000, 0x47ffd801,0xb004fff8,0x06fe805f,0xfffc9800,0x32209911,0x00000004, 0x00000000,0x00000000,0x00000000,0x1bf60000,0x2dc87fea,0x37fd4000, 0xe85ffb80,0x5fb001ff,0x7777fdc0,0x005eeeee,0x00007ae2,0x00000000, 0x00000000,0x00000000,0x00000000,0x80ffdc00,0x00010efd,0x8801ffc0, 0x07fc83ff,0x7ffdc000,0x7fffffff,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000,0x00000000,0x00000000,0x00000000,0x00000000,0x00000000, 0x00000000, }; static signed short stb__arial_28_usascii_x[95]={ 0,2,1,0,0,1,1,1,1,1,0,1,2,0, 2,0,1,2,0,1,0,1,0,1,1,1,2,2,1,1,1,1,1,-1,1,1,1,1,2,1,2,2,0,1, 1,1,1,1,1,1,1,1,0,1,0,0,0,0,0,1,0,0,0,-1,1,0,1,0,0,0,0,0,1,1, -2,1,1,1,1,0,1,0,1,0,0,1,0,0,0,0,0,0,2,0,1, }; static signed short stb__arial_28_usascii_y[95]={ 22,4,4,3,2,3,3,4,3,3,3,7,19,14, 19,3,3,3,3,3,4,4,3,4,3,3,9,9,7,9,7,3,3,4,4,3,4,4,4,3,4,4,4,4, 4,4,4,3,4,3,4,3,4,4,4,4,4,4,4,4,3,4,3,25,3,8,4,8,4,8,3,8,4,4, 4,4,4,8,8,8,8,8,8,8,4,9,9,9,9,9,9,3,3,3,11, }; static unsigned short stb__arial_28_usascii_w[95]={ 0,3,7,14,13,20,16,3,7,7,9,13,3,8, 3,7,12,8,13,12,13,12,13,12,12,12,3,3,13,13,13,12,24,18,15,17,16,15,13,17,15,3,11,16, 13,18,16,18,15,18,17,15,15,16,17,24,17,17,15,6,7,6,12,16,5,13,12,13,13,13,8,13,12,3, 6,12,3,19,12,14,12,13,8,12,7,12,13,18,13,13,12,8,3,8,13, }; static unsigned short stb__arial_28_usascii_h[95]={ 0,18,7,20,23,20,20,7,25,25,9,13,7,3, 3,20,20,19,19,20,18,19,20,18,20,20,13,17,13,8,13,19,25,18,18,20,18,18,18,20,18,18,19,18, 18,18,18,20,18,21,18,20,18,19,18,18,18,18,18,23,20,23,11,2,5,15,19,15,19,15,19,20,18,18, 24,18,18,14,14,15,19,19,14,15,19,14,13,13,13,19,13,25,25,25,5, }; static unsigned short stb__arial_28_usascii_s[95]={ 254,100,144,137,71,174,195,140,56,1,116, 62,251,172,251,19,45,120,129,72,104,152,152,52,212,225,247,118,89,126,15, 209,9,81,65,27,31,15,1,1,223,48,236,180,166,147,130,118,96,99,78, 238,44,178,112,1,60,26,239,92,166,85,103,181,152,122,107,178,93,136,143, 58,197,248,64,210,252,201,234,163,165,195,192,150,85,221,29,43,1,222,76, 47,43,34,158, }; static unsigned short stb__arial_28_usascii_t[95]={ 1,67,86,1,1,1,1,86,1,1,86, 86,67,86,75,27,27,27,27,27,67,27,1,67,1,1,67,67,86,86,86, 27,1,67,67,27,67,67,67,27,48,67,27,48,48,48,48,1,48,1,48, 1,48,27,48,48,48,48,48,1,1,1,86,86,86,67,27,67,27,67,27, 27,48,27,1,48,27,67,67,67,27,27,67,67,27,67,86,86,86,27,86, 1,1,1,86, }; static unsigned short stb__arial_28_usascii_a[95]={ 111,111,142,223,223,357,267,77, 134,134,156,234,111,134,111,111,223,223,223,223,223,223,223,223, 223,223,111,111,234,234,234,223,407,267,267,290,290,267,245,312, 290,111,201,267,223,334,290,312,267,312,290,267,245,290,267,378, 267,267,245,111,111,111,188,223,134,223,223,201,223,223,111,223, 223,89,89,201,89,334,223,223,223,223,134,201,111,223,201,290, 201,201,201,134,104,134,234, }; // Call this function with // font: NULL or array length // data: NULL or specified size // height: STB_FONT_arial_28_usascii_BITMAP_HEIGHT or STB_FONT_arial_28_usascii_BITMAP_HEIGHT_POW2 // return value: spacing between lines static void stb_font_arial_28_usascii(stb_fontchar font[STB_FONT_arial_28_usascii_NUM_CHARS], unsigned char data[STB_FONT_arial_28_usascii_BITMAP_HEIGHT][STB_FONT_arial_28_usascii_BITMAP_WIDTH], int height) { int i,j; if (data != 0) { unsigned int *bits = stb__arial_28_usascii_pixels; unsigned int bitpack = *bits++, numbits = 32; for (i=0; i < STB_FONT_arial_28_usascii_BITMAP_WIDTH*height; ++i) data[0][i] = 0; // zero entire bitmap for (j=1; j < STB_FONT_arial_28_usascii_BITMAP_HEIGHT-1; ++j) { for (i=1; i < STB_FONT_arial_28_usascii_BITMAP_WIDTH-1; ++i) { unsigned int value; if (numbits==0) bitpack = *bits++, numbits=32; value = bitpack & 1; bitpack >>= 1, --numbits; if (value) { if (numbits < 3) bitpack = *bits++, numbits = 32; data[j][i] = (bitpack & 7) * 0x20 + 0x1f; bitpack >>= 3, numbits -= 3; } else { data[j][i] = 0; } } } } // build font description if (font != 0) { float recip_width = 1.0f / STB_FONT_arial_28_usascii_BITMAP_WIDTH; float recip_height = 1.0f / height; for (i=0; i < STB_FONT_arial_28_usascii_NUM_CHARS; ++i) { // pad characters so they bilerp from empty space around each character font[i].s0 = (stb__arial_28_usascii_s[i]) * recip_width; font[i].t0 = (stb__arial_28_usascii_t[i]) * recip_height; font[i].s1 = (stb__arial_28_usascii_s[i] + stb__arial_28_usascii_w[i]) * recip_width; font[i].t1 = (stb__arial_28_usascii_t[i] + stb__arial_28_usascii_h[i]) * recip_height; font[i].x0 = stb__arial_28_usascii_x[i]; font[i].y0 = stb__arial_28_usascii_y[i]; font[i].x1 = stb__arial_28_usascii_x[i] + stb__arial_28_usascii_w[i]; font[i].y1 = stb__arial_28_usascii_y[i] + stb__arial_28_usascii_h[i]; font[i].advance_int = (stb__arial_28_usascii_a[i]+8)>>4; font[i].s0f = (stb__arial_28_usascii_s[i] - 0.5f) * recip_width; font[i].t0f = (stb__arial_28_usascii_t[i] - 0.5f) * recip_height; font[i].s1f = (stb__arial_28_usascii_s[i] + stb__arial_28_usascii_w[i] + 0.5f) * recip_width; font[i].t1f = (stb__arial_28_usascii_t[i] + stb__arial_28_usascii_h[i] + 0.5f) * recip_height; font[i].x0f = stb__arial_28_usascii_x[i] - 0.5f; font[i].y0f = stb__arial_28_usascii_y[i] - 0.5f; font[i].x1f = stb__arial_28_usascii_x[i] + stb__arial_28_usascii_w[i] + 0.5f; font[i].y1f = stb__arial_28_usascii_y[i] + stb__arial_28_usascii_h[i] + 0.5f; font[i].advance = stb__arial_28_usascii_a[i]/16.0f; } } } #ifndef STB_SOMEFONT_CREATE #define STB_SOMEFONT_CREATE stb_font_arial_28_usascii #define STB_SOMEFONT_BITMAP_WIDTH STB_FONT_arial_28_usascii_BITMAP_WIDTH #define STB_SOMEFONT_BITMAP_HEIGHT STB_FONT_arial_28_usascii_BITMAP_HEIGHT #define STB_SOMEFONT_BITMAP_HEIGHT_POW2 STB_FONT_arial_28_usascii_BITMAP_HEIGHT_POW2 #define STB_SOMEFONT_FIRST_CHAR STB_FONT_arial_28_usascii_FIRST_CHAR #define STB_SOMEFONT_NUM_CHARS STB_FONT_arial_28_usascii_NUM_CHARS #define STB_SOMEFONT_LINE_SPACING STB_FONT_arial_28_usascii_LINE_SPACING #endif
62.979381
117
0.775184
stetre
895cbed539482619f455397ed672789054adedaf
1,801
cpp
C++
ext/types/offer.cpp
Atidot/hs-mesos
7449a31550259a231c4809d9a6fcc626892502b3
[ "MIT" ]
null
null
null
ext/types/offer.cpp
Atidot/hs-mesos
7449a31550259a231c4809d9a6fcc626892502b3
[ "MIT" ]
null
null
null
ext/types/offer.cpp
Atidot/hs-mesos
7449a31550259a231c4809d9a6fcc626892502b3
[ "MIT" ]
null
null
null
#include <iostream> #include "types.h" using namespace mesos; OfferPtr toOffer(OfferIDPtr offerID, FrameworkIDPtr frameworkID, SlaveIDPtr slaveID, char* hostname, int hostnameLen, ResourcePtr* resources, int resourcesLen, AttributePtr* attributes, int attributesLen, ExecutorIDPtr* executorIDs, int idsLen) { OfferPtr offer = new Offer(); *offer->mutable_id() = *offerID; *offer->mutable_framework_id() = *frameworkID; *offer->mutable_slave_id() = *slaveID; offer->set_hostname(hostname, hostnameLen); for (int i = 0; i < resourcesLen; ++i) *offer->add_resources() = *resources[i]; for (int i = 0; i < attributesLen; ++i) *offer->add_attributes() = *attributes[i]; for (int i = 0; i < idsLen; ++i) *offer->add_executor_ids() = *executorIDs[i]; return offer; } void fromOffer(OfferPtr offer, OfferIDPtr* offerID, FrameworkIDPtr* frameworkID, SlaveIDPtr* slaveID, char** hostname, int* hostnameLen, ResourcePtr** resources, int* resourcesLen, AttributePtr** attributes, int* attributesLen, ExecutorIDPtr** executorIDs, int* idsLen) { *offerID = offer->mutable_id(); *frameworkID = offer->mutable_framework_id(); *slaveID = offer->mutable_slave_id(); *hostname = (char*) offer->mutable_hostname()->data(); *hostnameLen = offer->mutable_hostname()->size(); *resources = offer->mutable_resources()->mutable_data(); *resourcesLen = offer->resources_size(); *attributes = offer->mutable_attributes()->mutable_data(); *attributesLen = offer->attributes_size(); *executorIDs = offer->mutable_executor_ids()->mutable_data(); *idsLen = offer->executor_ids_size(); } void destroyOffer(OfferPtr offer) { delete offer; }
22.5125
63
0.667962
Atidot
89678386c71f9f7c8a1dead073b46d650133a148
582
cpp
C++
hw4/src/lib/sema/ContextManager.cpp
idoleat/P-Language-Compiler-CourseProject
57db735b349a0a3a30d78b927953e2d44b7c7d53
[ "MIT" ]
7
2020-09-10T16:54:49.000Z
2022-03-15T12:39:23.000Z
hw4/src/lib/sema/ContextManager.cpp
idoleat/simple-P-compiler
57db735b349a0a3a30d78b927953e2d44b7c7d53
[ "MIT" ]
null
null
null
hw4/src/lib/sema/ContextManager.cpp
idoleat/simple-P-compiler
57db735b349a0a3a30d78b927953e2d44b7c7d53
[ "MIT" ]
null
null
null
#include "sema/SemanticAnalyzer.hpp" std::string SemanticAnalyzer::ContextManager::TrimDimension(const char* typeString, int amount, bool TrimWhiteSpace){ std::string type = std::string(typeString); std::size_t left, right; while(amount != 0){ left = type.find_first_of("["); right = type.find_first_of("]"); type.erase(type.begin() + left, type.begin() + right+1); amount -= 1; } if(TrimWhiteSpace){ while(type.find(" ") != std::string::npos){ type.erase(type.find(" ")); } } return type; }
29.1
117
0.594502
idoleat
8967bedf82ef7802f2c640389d5bcc1ffdc0b67b
1,198
cpp
C++
Source/10.0.18362.0/ucrt/string/strtok.cpp
825126369/UCRT
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
[ "MIT" ]
2
2021-01-27T10:19:30.000Z
2021-02-09T06:24:30.000Z
Source/10.0.18362.0/ucrt/string/strtok.cpp
825126369/UCRT
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
[ "MIT" ]
null
null
null
Source/10.0.18362.0/ucrt/string/strtok.cpp
825126369/UCRT
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
[ "MIT" ]
1
2021-01-27T10:19:36.000Z
2021-01-27T10:19:36.000Z
// // strtok.cpp // // Copyright (c) Microsoft Corporation. All rights reserved. // // Defines strtok(), which tokenizes a string via repeated calls. // // strtok() considers the string to consist of a sequence of zero or more text // tokens separated by spans of one or more control characters. The first call, // with a string specified, returns a pointer to the first character of the // first token, and will write a null character into the string immediately // following the returned token. Subsequent calls with a null string argument // will work through the string until no tokens remain. The control string // may be different from call to call. When no tokens remain in the string, a // null pointer is returned. // #include <corecrt_internal.h> #include <string.h> extern "C" char* __cdecl __acrt_strtok_s_novalidation( _Inout_opt_z_ char* string, _In_z_ char const* control, _Inout_ _Deref_prepost_opt_z_ char** context ); extern "C" char* __cdecl strtok(char* const string, char const* const control) { return __acrt_strtok_s_novalidation(string, control, &__acrt_getptd()->_strtok_token); }
35.235294
90
0.708681
825126369
896a4c73f95f68c47644475ea4886e136439e6b8
1,225
hpp
C++
CRTPFactory/src/AddToRegistry.hpp
DLancer999/FactoryImplementation
a87b595cac1b2c082a39113b5a6cfbc2548bd8ff
[ "MIT" ]
null
null
null
CRTPFactory/src/AddToRegistry.hpp
DLancer999/FactoryImplementation
a87b595cac1b2c082a39113b5a6cfbc2548bd8ff
[ "MIT" ]
null
null
null
CRTPFactory/src/AddToRegistry.hpp
DLancer999/FactoryImplementation
a87b595cac1b2c082a39113b5a6cfbc2548bd8ff
[ "MIT" ]
null
null
null
/*************************************************************************\ License Copyright (c) 2018 Kavvadias Ioannis. This file is part of FactoryImplementation. Licensed under the MIT License. See LICENSE file in the project root for full license information. Class AddToRegistry Description Dummy class to create runTimeSelection tables at global initialization stage \************************************************************************/ #ifndef ADDTOREGISTRY_H #define ADDTOREGISTRY_H //ADDED class has to inherit from PolymorphicInheritance and from HASREGISTRY //HASREGISTRY class has to inherit from PolymorphicBase template <class ADDED, class HASREGISTRY> class AddToRegistry { using ObjectCreator = typename HASREGISTRY::ObjectCreator; public: AddToRegistry() { //track additions std::cout<<"Adding \"" <<ADDED::name <<"\" to RuntimeSelectionTable of " <<HASREGISTRY::name<<'\n'; //needed to define which polymorphicCreate instantiation we need ObjectCreator createFunc = ADDED::polymorphicCreate; //actual addition HASREGISTRY::registry()[ADDED::name] = createFunc; } }; #endif
27.840909
80
0.621224
DLancer999
897172d3ad4713dc6ff9e70ca874f801cc893b2b
747
cpp
C++
String/First Non-repeted char in a string.cpp
Biplob68/Data-Structure-and-Algorithms
2ea7895a87ce1dfb9bd90495c678fc5d1ae133f6
[ "MIT" ]
null
null
null
String/First Non-repeted char in a string.cpp
Biplob68/Data-Structure-and-Algorithms
2ea7895a87ce1dfb9bd90495c678fc5d1ae133f6
[ "MIT" ]
null
null
null
String/First Non-repeted char in a string.cpp
Biplob68/Data-Structure-and-Algorithms
2ea7895a87ce1dfb9bd90495c678fc5d1ae133f6
[ "MIT" ]
null
null
null
#include <stdio.h> #include <string.h> int main(void) { char str[100] ; scanf("%[^\n]%c", str); int len = strlen(str); int i,j,flag; // Two loops to compare each character with other character for(i = 0; i < len; i++) { flag = 0; for(j = 0; j < len; j++) { // If it's equal and indexes is not same if((str[i] == str[j]) && (i != j)) { flag = 1; break; } } if (flag == 0) { printf("First non-repeating character is %c\n",str[i]); break; } } if (flag == 1) { printf("Didn't find any non-repeating character\n"); } return 0; }
18.675
67
0.417671
Biplob68
89780c9bf1eb5779c361a74d2cf56f2d76c3717d
822
cpp
C++
acm/hdu/1873.cpp
xiaohuihuigh/cpp
c28bdb79ecb86f44a92971ac259910546dba29a7
[ "MIT" ]
17
2016-01-01T12:57:25.000Z
2022-02-06T09:55:12.000Z
acm/hdu/1873.cpp
xiaohuihuigh/cpp
c28bdb79ecb86f44a92971ac259910546dba29a7
[ "MIT" ]
null
null
null
acm/hdu/1873.cpp
xiaohuihuigh/cpp
c28bdb79ecb86f44a92971ac259910546dba29a7
[ "MIT" ]
8
2018-12-27T01:31:49.000Z
2022-02-06T09:55:12.000Z
#include<bits/stdc++.h> using namespace std; #define sa(x) scanf("%d",&x) const int maxn = 1005; struct node{ int pri; int id; bool operator < (const node a) const { if(pri == a.pri)return id>a.id; return pri<a.pri; } }g; int main(){ string a; int n; while(cin>>n){ int cnt = 1; priority_queue<node> q[3]; for(int i = 0;i<n;i++){ cin>>a; if(a == "OUT"){ int d; cin>>d; d--; if(q[d].empty()){cout<<"EMPTY"<<endl;} else{ g = q[d].top(); q[d].pop(); cout<<g.id<<endl; } } else{ int d; cin>>d>>g.pri; g.id = cnt++; q[d-1].push(g); } } } }
19.116279
50
0.375912
xiaohuihuigh
897970954c73f23ff6cf5eda1abbf808f5415d5b
7,409
hpp
C++
src/operator/perturbedst2eoperator.hpp
susilehtola/aquarius
9160e73bd7e3e0d8d97b10d00d9a4860aee709d2
[ "BSD-3-Clause" ]
18
2015-02-11T15:02:39.000Z
2021-09-24T13:10:12.000Z
src/operator/perturbedst2eoperator.hpp
susilehtola/aquarius
9160e73bd7e3e0d8d97b10d00d9a4860aee709d2
[ "BSD-3-Clause" ]
21
2015-06-23T13:32:29.000Z
2022-02-15T20:14:42.000Z
src/operator/perturbedst2eoperator.hpp
susilehtola/aquarius
9160e73bd7e3e0d8d97b10d00d9a4860aee709d2
[ "BSD-3-Clause" ]
8
2016-01-09T23:36:21.000Z
2019-11-19T14:22:34.000Z
#ifndef _AQUARIUS_OPERATOR_PERTURBEDST2EOPERATOR_HPP_ #define _AQUARIUS_OPERATOR_PERTURBEDST2EOPERATOR_HPP_ #include "util/global.hpp" #include "2eoperator.hpp" #include "st2eoperator.hpp" namespace aquarius { namespace op { /* * _A -T A T _ A A T _ A * Form X = e X e + [X, T ] = (X e ) + (X T ) , up to two-electron terms * c c */ template <typename U> class PerturbedSTTwoElectronOperator : public STTwoElectronOperator<U> { protected: const STTwoElectronOperator<U>& X; const ExcitationOperator<U,2>& TA; public: template <int N> PerturbedSTTwoElectronOperator(const string& name, const STTwoElectronOperator<U>& X, const OneElectronOperator<U>& XA, const ExcitationOperator<U,N>& T, const ExcitationOperator<U,N>& TA) : STTwoElectronOperator<U>(name, XA, T), X(X), TA(TA) { OneElectronOperator<U> I("I", this->arena, this->occ, this->vrt); tensor::SpinorbitalTensor<U>& IMI = I.getIJ(); tensor::SpinorbitalTensor<U>& IAE = I.getAB(); tensor::SpinorbitalTensor<U>& IME = I.getIA(); IME["me"] = X.getIJAB()["mnef"]*TA(1)["fn"]; IMI["mi"] = X.getIJAK()["nmei"]*TA(1)["en"]; IMI["mi"] += 0.5*X.getIJAB()["mnef"]*TA(2)["efin"]; IAE["ae"] = X.getAIBC()["amef"]*TA(1)["fm"]; IAE["ae"] -= 0.5*X.getIJAB()["mnef"]*TA(2)["afmn"]; this->ia["ia"] += IME["ia"]; this->ij["ij"] += X.getIA()["ie"]*TA(1)["ej"]; this->ij["ij"] += IMI["ij"]; this->ab["ab"] -= X.getIA()["mb"]*TA(1)["am"]; this->ab["ab"] += IAE["ab"]; this->ai["ai"] += X.getAB()["ae"]*TA(1)["ei"]; this->ai["ai"] -= X.getIJ()["mi"]*TA(1)["am"]; this->ai["ai"] += X.getIA()["me"]*TA(2)["aeim"]; this->ai["ai"] -= X.getAIBJ()["amei"]*TA(1)["em"]; this->ai["ai"] -= 0.5*X.getIJAK()["nmei"]*TA(2)["aemn"]; this->ai["ai"] += 0.5*X.getAIBC()["amef"]*TA(2)["efim"]; this->getIJAK()["ijak"] += X.getIJAB()["ijae"]*TA(1)["ek"]; this->getAIBC()["aibc"] -= X.getIJAB()["mibc"]*TA(1)["am"]; this->getIJKL()["ijkl"] += X.getIJAK()["jiek"]*TA(1)["el"]; this->getIJKL()["ijkl"] += 0.5*X.getIJAB()["ijef"]*TA(2)["efkl"]; this->getABCD()["abcd"] -= X.getAIBC()["amcd"]*TA(1)["bm"]; this->getABCD()["abcd"] += 0.5*X.getIJAB()["mncd"]*TA(2)["abmn"]; this->getAIBJ()["aibj"] += X.getAIBC()["aibe"]*TA(1)["ej"]; this->getAIBJ()["aibj"] -= X.getIJAK()["mibj"]*TA(1)["am"]; this->getAIBJ()["aibj"] -= X.getIJAB()["mibe"]*TA(2)["aemj"]; this->getAIJK()["aijk"] += IME["ie"]*T(2)["aejk"]; this->getAIJK()["aijk"] += X.getAIBJ()["aiek"]*TA(1)["ej"]; this->getAIJK()["aijk"] -= X.getIJKL()["mijk"]*TA(1)["am"]; this->getAIJK()["aijk"] += X.getIJAK()["miek"]*TA(2)["aejm"]; this->getAIJK()["aijk"] += 0.5*X.getAIBC()["aief"]*TA(2)["efjk"]; this->getABCI()["abci"] -= IME["mc"]*T(2)["abmi"]; this->getABCI()["abci"] -= X.getAIBJ()["amci"]*TA(1)["bm"]; this->getABCI()["abci"] += X.getABCD()["abce"]*TA(1)["ei"]; this->getABCI()["abci"] += X.getAIBC()["amce"]*TA(2)["beim"]; this->getABCI()["abci"] += 0.5*X.getIJAK()["mnci"]*TA(2)["abmn"]; this->abij["abij"] += IAE["ae"]*T(2)["ebij"]; this->abij["abij"] -= IMI["mi"]*T(2)["abmj"]; this->abij["abij"] += X.getABCI()["abej"]*TA(1)["ei"]; this->abij["abij"] -= X.getAIJK()["bmji"]*TA(1)["am"]; this->abij["abij"] += 0.5*X.getABCD()["abef"]*TA(2)["efij"]; this->abij["abij"] += 0.5*X.getIJKL()["mnij"]*TA(2)["abmn"]; this->abij["abij"] -= X.getAIBJ()["amei"]*TA(2)["ebmj"]; } template <int N> PerturbedSTTwoElectronOperator(const string& name, const STTwoElectronOperator<U>& X, const TwoElectronOperator<U>& XA, const ExcitationOperator<U,N>& T, const ExcitationOperator<U,N>& TA) : STTwoElectronOperator<U>(name, XA, T), X(X), TA(TA) { OneElectronOperator<U> I("I", this->arena, this->occ, this->vrt); tensor::SpinorbitalTensor<U>& IMI = I.getIJ(); tensor::SpinorbitalTensor<U>& IAE = I.getAB(); tensor::SpinorbitalTensor<U>& IME = I.getIA(); IME["me"] = X.getIJAB()["mnef"]*TA(1)["fn"]; IMI["mi"] = X.getIJAK()["nmei"]*TA(1)["en"]; IMI["mi"] += 0.5*X.getIJAB()["mnef"]*TA(2)["efin"]; IAE["ae"] = X.getAIBC()["amef"]*TA(1)["fm"]; IAE["ae"] -= 0.5*X.getIJAB()["mnef"]*TA(2)["afmn"]; this->ia["ia"] += IME["ia"]; this->ij["ij"] += X.getIA()["ie"]*TA(1)["ej"]; this->ij["ij"] += IMI["ij"]; this->ab["ab"] -= X.getIA()["mb"]*TA(1)["am"]; this->ab["ab"] += IAE["ab"]; this->ai["ai"] += X.getAB()["ae"]*TA(1)["ei"]; this->ai["ai"] -= X.getIJ()["mi"]*TA(1)["am"]; this->ai["ai"] += X.getIA()["me"]*TA(2)["aeim"]; this->ai["ai"] -= X.getAIBJ()["amei"]*TA(1)["em"]; this->ai["ai"] -= 0.5*X.getIJAK()["nmei"]*TA(2)["aemn"]; this->ai["ai"] += 0.5*X.getAIBC()["amef"]*TA(2)["efim"]; this->getIJAK()["ijak"] += X.getIJAB()["ijae"]*TA(1)["ek"]; this->getAIBC()["aibc"] -= X.getIJAB()["mibc"]*TA(1)["am"]; this->getIJKL()["ijkl"] += X.getIJAK()["jiek"]*TA(1)["el"]; this->getIJKL()["ijkl"] += 0.5*X.getIJAB()["ijef"]*TA(2)["efkl"]; this->getABCD()["abcd"] -= X.getAIBC()["amcd"]*TA(1)["bm"]; this->getABCD()["abcd"] += 0.5*X.getIJAB()["mncd"]*TA(2)["abmn"]; this->getAIBJ()["aibj"] += X.getAIBC()["aibe"]*TA(1)["ej"]; this->getAIBJ()["aibj"] -= X.getIJAK()["mibj"]*TA(1)["am"]; this->getAIBJ()["aibj"] -= X.getIJAB()["mibe"]*TA(2)["aemj"]; this->getAIJK()["aijk"] += IME["ie"]*T(2)["aejk"]; this->getAIJK()["aijk"] += X.getAIBJ()["aiek"]*TA(1)["ej"]; this->getAIJK()["aijk"] -= X.getIJKL()["mijk"]*TA(1)["am"]; this->getAIJK()["aijk"] += X.getIJAK()["miek"]*TA(2)["aejm"]; this->getAIJK()["aijk"] += 0.5*X.getAIBC()["aief"]*TA(2)["efjk"]; this->getABCI()["abci"] -= IME["mc"]*T(2)["abmi"]; this->getABCI()["abci"] -= X.getAIBJ()["amci"]*TA(1)["bm"]; this->getABCI()["abci"] += X.getABCD()["abce"]*TA(1)["ei"]; this->getABCI()["abci"] += X.getAIBC()["amce"]*TA(2)["beim"]; this->getABCI()["abci"] += 0.5*X.getIJAK()["mnci"]*TA(2)["abmn"]; this->abij["abij"] += IAE["ae"]*T(2)["ebij"]; this->abij["abij"] -= IMI["mi"]*T(2)["abmj"]; this->abij["abij"] += X.getABCI()["abej"]*TA(1)["ei"]; this->abij["abij"] -= X.getAIJK()["bmji"]*TA(1)["am"]; this->abij["abij"] += 0.5*X.getABCD()["abef"]*TA(2)["efij"]; this->abij["abij"] += 0.5*X.getIJKL()["mnij"]*TA(2)["abmn"]; this->abij["abij"] -= X.getAIBJ()["amei"]*TA(2)["ebmj"]; } }; } } #endif
43.582353
127
0.460791
susilehtola
897e903e3cd8d885a3599f107cb5c14b6bf1f674
3,803
cpp
C++
test/test_speed.cpp
barometz/ringbuf
96b49b86d88969a46df56485cfa2d005bd524d9f
[ "MIT" ]
15
2021-12-12T16:58:13.000Z
2022-03-25T09:22:06.000Z
test/test_speed.cpp
barometz/ringbuf
96b49b86d88969a46df56485cfa2d005bd524d9f
[ "MIT" ]
null
null
null
test/test_speed.cpp
barometz/ringbuf
96b49b86d88969a46df56485cfa2d005bd524d9f
[ "MIT" ]
1
2021-12-19T02:03:04.000Z
2021-12-19T02:03:04.000Z
#include "baudvine/deque_ringbuf.h" #include "baudvine/ringbuf.h" #include <gtest/gtest.h> #include <chrono> // Speed comparison between deque and standard. Standard should generally be at // least as fast as deque, but in practice we're not the only process so there's // going to be some noise. namespace std { namespace chrono { std::ostream& operator<<(std::ostream& os, system_clock::duration d) { return os << duration_cast<microseconds>(d).count() << " µs"; } } // namespace chrono } // namespace std namespace { constexpr uint64_t kTestSize = 1 << 25; std::chrono::system_clock::duration TimeIt(const std::function<void()>& fn) { const auto start = std::chrono::system_clock::now(); fn(); return std::chrono::system_clock::now() - start; } } // namespace TEST(Speed, PushBackToFull) { baudvine::RingBuf<uint64_t, kTestSize> standard; baudvine::DequeRingBuf<uint64_t, kTestSize> deque; // Preload everything once so all the memory is definitely allocated for (uint32_t i = 0; i < standard.max_size(); i++) { standard.push_back(0); } standard.clear(); for (uint32_t i = 0; i < deque.max_size(); i++) { deque.push_back(0); } deque.clear(); auto standardDuration = TimeIt([&standard] { for (uint32_t i = 0; i < standard.max_size(); i++) { standard.push_back(0); } }); auto dequeDuration = TimeIt([&deque] { for (uint32_t i = 0; i < deque.max_size(); i++) { deque.push_back(0); } }); EXPECT_LT(standardDuration, dequeDuration); std::cout << "RingBuf: " << standardDuration << std::endl; std::cout << "DequeRingBuf: " << dequeDuration << std::endl; } TEST(Speed, PushBackOverFull) { baudvine::RingBuf<uint64_t, 3> standard; baudvine::DequeRingBuf<uint64_t, 3> deque; auto standardDuration = TimeIt([&standard] { for (uint32_t i = 0; i < kTestSize; i++) { standard.push_back(0); } }); auto dequeDuration = TimeIt([&deque] { for (uint32_t i = 0; i < kTestSize; i++) { deque.push_back(0); } }); EXPECT_LT(standardDuration, dequeDuration); std::cout << "RingBuf: " << standardDuration << std::endl; std::cout << "DequeRingBuf: " << dequeDuration << std::endl; } TEST(Speed, IterateOver) { baudvine::RingBuf<uint64_t, kTestSize> standard; baudvine::DequeRingBuf<uint64_t, kTestSize> deque; for (uint32_t i = 0; i < standard.max_size(); i++) { standard.push_back(i); } for (uint32_t i = 0; i < deque.max_size(); i++) { deque.push_back(i); } // Do a little math so the compiler doesn't optimize the test away in a // release build. uint64_t acc{}; auto standardDuration = TimeIt([&standard, &acc] { for (auto& x : standard) { acc += x; } }); auto dequeDuration = TimeIt([&deque, &acc] { for (auto& x : deque) { acc += x; } }); EXPECT_LT(standardDuration, dequeDuration); std::cout << "RingBuf: " << standardDuration << std::endl; std::cout << "DequeRingBuf: " << dequeDuration << std::endl; } TEST(Speed, Copy) { // baudvine::copy should be faster than std::copy as std::copy doesn't know // that there are at most two contiguous sections. baudvine::RingBuf<int, kTestSize> underTest; std::fill_n(std::back_inserter(underTest), kTestSize, 55); std::vector<int> copy; copy.reserve(kTestSize); std::fill_n(std::back_inserter(copy), kTestSize, 44); auto customTime = TimeIt([&underTest, &copy] { baudvine::copy(underTest.begin(), underTest.end(), copy.begin()); }); auto standardTime = TimeIt([&underTest, &copy] { std::copy(underTest.begin(), underTest.end(), copy.begin()); }); EXPECT_LT(customTime, standardTime); std::cout << "baudvine::copy: " << customTime << std::endl; std::cout << "std::copy: " << standardTime << std::endl; }
27.963235
80
0.645543
barometz
897f32006cf2ae2432b186da04d9755ca44448ab
6,583
cc
C++
src/external_library/libgp/src/cg.cc
ecbaum/ugpm
3ab6ff2dbc59642e0e9739f5f4647a906f19e333
[ "MIT" ]
89
2015-02-28T12:20:07.000Z
2022-02-01T17:15:57.000Z
src/cg.cc
Bellout/libgp
f2bcfe7b5b6f02444ef98caf822717662c13fc88
[ "BSD-3-Clause" ]
212
2018-09-21T10:44:07.000Z
2022-03-22T14:33:05.000Z
src/cg.cc
Bellout/libgp
f2bcfe7b5b6f02444ef98caf822717662c13fc88
[ "BSD-3-Clause" ]
58
2015-03-08T09:22:01.000Z
2021-12-14T10:12:31.000Z
/* * cg.cpp * * Created on: Feb 22, 2013 * Author: Joao Cunha <[email protected]> */ #include "cg.h" #include <iostream> #include <Eigen/Core> using namespace std; namespace libgp { CG::CG() { } CG::~CG() { } void CG::maximize(GaussianProcess* gp, size_t n, bool verbose) { const double INT = 0.1; // don't reevaluate within 0.1 of the limit of the current bracket const double EXT = 3.0; // extrapolate maximum 3 times the current step-size const int MAX = 20; // max 20 function evaluations per line search const double RATIO = 10; // maximum allowed slope ratio const double SIG = 0.1, RHO = SIG/2; /* SIG and RHO are the constants controlling the Wolfe- Powell conditions. SIG is the maximum allowed absolute ratio between previous and new slopes (derivatives in the search direction), thus setting SIG to low (positive) values forces higher precision in the line-searches. RHO is the minimum allowed fraction of the expected (from the slope at the initial point in the linesearch). Constants must satisfy 0 < RHO < SIG < 1. Tuning of SIG (depending on the nature of the function to be optimized) may speed up the minimization; it is probably not worth playing much with RHO. */ /* The code falls naturally into 3 parts, after the initial line search is started in the direction of steepest descent. 1) we first enter a while loop which uses point 1 (p1) and (p2) to compute an extrapolation (p3), until we have extrapolated far enough (Wolfe-Powell conditions). 2) if necessary, we enter the second loop which takes p2, p3 and p4 chooses the subinterval containing a (local) minimum, and interpolates it, unil an acceptable point is found (Wolfe-Powell conditions). Note, that points are always maintained in order p0 <= p1 <= p2 < p3 < p4. 3) compute a new search direction using conjugate gradients (Polack-Ribiere flavour), or revert to steepest if there was a problem in the previous line-search. Return the best value so far, if two consecutive line-searches fail, or whenever we run out of function evaluations or line-searches. During extrapolation, the "f" function may fail either with an error or returning Nan or Inf, and maxmize should handle this gracefully. */ bool ls_failed = false; //prev line-search failed double f0 = -gp->log_likelihood(); //initial negative marginal log likelihood Eigen::VectorXd df0 = -gp->log_likelihood_gradient(); //initial gradient Eigen::VectorXd X = gp->covf().get_loghyper(); //hyper parameters if(verbose) cout << f0 << endl; Eigen::VectorXd s = -df0; //initial search direction double d0 = -s.dot(s); //initial slope double x3 = 1/(1-d0); double f3 = 0; double d3 = 0; Eigen::VectorXd df3 = df0; double x2 = 0, x4 = 0; double f2 = 0, f4 = 0; double d2 = 0, d4 = 0; for (unsigned int i = 0; i < n; ++i) { //copy current values Eigen::VectorXd X0 = X; double F0 = f0; Eigen::VectorXd dF0 = df0; unsigned int M = min(MAX, (int)(n-i)); while(1) //keep extrapolating until necessary { x2 = 0; f2 = f0; d2 = d0; f3 = f0; df3 = df0; double success = false; while( !success && M>0) { M --; i++; gp->covf().set_loghyper(X+s*x3); f3 = -gp->log_likelihood(); df3 = -gp->log_likelihood_gradient(); if(verbose) cout << f3 << endl; bool nanFound = false; //test NaN and Inf's for (int j = 0; j < df3.rows(); ++j) { if(isnan(df3(j))) { nanFound = true; break; } } if(!isnan(f3) && !isinf(f3) && !nanFound) success = true; else { x3 = (x2+x3)/2; // if fail, bissect and try again } } //keep best values if(f3 < F0) { X0 = X+s*x3; F0 = f3; dF0 = df3; } d3 = df3.dot(s); // new slope if( (d3 > SIG*d0) || (f3 > f0+x3*RHO*d0) || M == 0) // are we done extrapolating? { break; } double x1 = x2; double f1 = f2; double d1 = d2; // move point 2 to point 1 x2 = x3; f2 = f3; d2 = d3; // move point 3 to point 2 double A = 6*(f1-f2) + 3*(d2+d1)*(x2-x1); // make cubic extrapolation double B = 3*(f2-f1) - (2*d1+d2)*(x2-x1); x3 = x1-d1*(x2-x1)*(x2-x1)/(B+sqrt(B*B -A*d1*(x2-x1))); if(isnan(x3) || x3 < 0 || x3 > x2*EXT) // num prob | wrong sign | beyond extrapolation limit x3 = EXT*x2; else if(x3 < x2+INT*(x2-x1)) // too close to previous point x3 = x2+INT*(x2-x1); } while( ( (abs(d3) > -SIG*d0) || (f3 > f0+x3*RHO*d0) ) && (M > 0)) // keep interpolating { if( (d3 > 0) || (f3 > f0+x3*RHO*d0) ) // choose subinterval { // move point 3 to point 4 x4 = x3; f4 = f3; d4 = d3; } else { x2 = x3; //move point 3 to point 2 f2 = f3; d2 = d3; } if(f4 > f0) x3 = x2 - (0.5*d2*(x4-x2)*(x4-x2))/(f4-f2-d2*(x4-x2)); // quadratic interpolation else { double A = 6*(f2-f4)/(x4-x2)+3*(d4+d2); double B = 3*(f4-f2)-(2*d2+d4)*(x4-x2); x3 = x2+sqrt(B*B-A*d2*(x4-x2)*(x4-x2) -B)/A; } if(isnan(x3) || isinf(x3)) x3 = (x2+x4)/2; x3 = std::max(std::min(x3, x4-INT*(x4-x2)), x2+INT*(x4-x2)); gp->covf().set_loghyper(X+s*x3); f3 = -gp->log_likelihood(); df3 = -gp->log_likelihood_gradient(); if(f3 < F0) // keep best values { X0 = X+s*x3; F0 = f3; dF0 = df3; } if(verbose) cout << F0 << endl; M--; i++; d3 = df3.dot(s); // new slope } if( (abs(d3) < -SIG*d0) && (f3 < f0+x3*RHO*d0)) { X = X+s*x3; f0 = f3; s = (df3.dot(df3)-df0.dot(df3)) / (df0.dot(df0))*s - df3; // Polack-Ribiere CG direction df0 = df3; // swap derivatives d3 = d0; d0 = df0.dot(s); if(verbose) cout << f0 << endl; if(d0 > 0) // new slope must be negative { // otherwise use steepest direction s = -df0; d0 = -s.dot(s); } x3 = x3 * std::min(RATIO, d3/(d0-std::numeric_limits< double >::min())); // slope ratio but max RATIO ls_failed = false; // this line search did not fail } else { // restore best point so far X = X0; f0 = F0; df0 = dF0; if(verbose) cout << f0 << endl; if(ls_failed || i >= n) // line search failed twice in a row break; // or we ran out of time, so we give up s = -df0; d0 = -s.dot(s); // try steepest x3 = 1/(1-d0); ls_failed = true; // this line search failed } } gp->covf().set_loghyper(X); } }
27.776371
104
0.581346
ecbaum
8982d7c06dcd2f60a1505fc2864abd29f58310be
6,511
hpp
C++
3rdparty/stlsoft/include/acestl/memory/message_block_functions.hpp
wohaaitinciu/zpublic
0e4896b16e774d2f87e1fa80f1b9c5650b85c57e
[ "Unlicense" ]
50
2015-01-07T01:54:54.000Z
2021-01-15T00:41:48.000Z
3rdparty/stlsoft/include/acestl/memory/message_block_functions.hpp
lib1256/zpublic
64c2be9ef1abab878288680bb58122dcc25df81d
[ "Unlicense" ]
2
2016-01-08T19:32:57.000Z
2019-10-11T03:50:34.000Z
3rdparty/stlsoft/include/acestl/memory/message_block_functions.hpp
lib1256/zpublic
64c2be9ef1abab878288680bb58122dcc25df81d
[ "Unlicense" ]
39
2015-01-07T02:03:15.000Z
2021-01-15T00:41:50.000Z
/* ///////////////////////////////////////////////////////////////////////// * File: acestl/memory/message_block_functions.hpp * * Purpose: Helper functions for ACE_Message_Block (and ACE_Data_Block) classes. * * Created: 23rd September 2004 * Updated: 10th August 2009 * * Home: http://stlsoft.org/ * * Copyright (c) 2004-2009, Matthew Wilson and Synesis Software * 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(s) of Matthew Wilson and Synesis Software nor the names of * any contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * ////////////////////////////////////////////////////////////////////// */ /** \file acestl/memory/message_block_functions.hpp * * \brief [C++ only] Helper functions for use with the ACE_Message_Block * and ACE_Data_Block classes * (\ref group__library__memory "Memory" Library). */ #ifndef ACESTL_INCL_ACESTL_MEMORY_HPP_MESSAGE_BLOCK_FUNCTIONS #define ACESTL_INCL_ACESTL_MEMORY_HPP_MESSAGE_BLOCK_FUNCTIONS #ifndef STLSOFT_DOCUMENTATION_SKIP_SECTION # define ACESTL_VER_ACESTL_MEMORY_HPP_MESSAGE_BLOCK_FUNCTIONS_MAJOR 2 # define ACESTL_VER_ACESTL_MEMORY_HPP_MESSAGE_BLOCK_FUNCTIONS_MINOR 0 # define ACESTL_VER_ACESTL_MEMORY_HPP_MESSAGE_BLOCK_FUNCTIONS_REVISION 3 # define ACESTL_VER_ACESTL_MEMORY_HPP_MESSAGE_BLOCK_FUNCTIONS_EDIT 28 #endif /* !STLSOFT_DOCUMENTATION_SKIP_SECTION */ /* ///////////////////////////////////////////////////////////////////////// * Includes */ #ifndef ACESTL_INCL_ACESTL_HPP_ACESTL # include <acestl/acestl.hpp> #endif /* !ACESTL_INCL_ACESTL_HPP_ACESTL */ #ifndef STLSOFT_INCL_ACE_H_MESSAGE_BLOCK # define STLSOFT_INCL_ACE_H_MESSAGE_BLOCK # include <ace/Message_Block.h> // for ACE_Message_Block #endif /* !STLSOFT_INCL_ACE_H_MESSAGE_BLOCK */ #ifndef STLSOFT_INCL_ACE_H_OS_MEMORY # define STLSOFT_INCL_ACE_H_OS_MEMORY # include <ace/OS_Memory.h> // for ACE_bad_alloc, ACE_NEW_THROWS_EXCEPTIONS #endif /* !STLSOFT_INCL_ACE_H_OS_MEMORY */ /* ///////////////////////////////////////////////////////////////////////// * Namespace */ #ifndef _ACESTL_NO_NAMESPACE # if defined(_STLSOFT_NO_NAMESPACE) || \ defined(STLSOFT_DOCUMENTATION_SKIP_SECTION) /* There is no stlsoft namespace, so must define ::acestl */ namespace acestl { # else /* Define stlsoft::acestl_project */ namespace stlsoft { namespace acestl_project { # endif /* _STLSOFT_NO_NAMESPACE */ #endif /* !_ACESTL_NO_NAMESPACE */ /* ///////////////////////////////////////////////////////////////////////// * Functions */ /** \brief Creates a new ACE_Message_Block instance whose contents are * copied from the given memory. * * \ingroup group__library__memory * * \param p Pointer to the memory to copy into the new message block. May be * NULL, in which case the contents are not explicitly initialised. * \param n Number of bytes to copy into the new message block. If * <code>NULL == p</code>, this is the size of the initialised block. * * Usage is simple: just specify the source (pointer and length), and test * for NULL (allocation failure): * \code ACE_Message_Block *newBlock = acestl::make_copied_Message_Block("Contents", 7); if(NULL == newBlock) { std::cerr << "Allocation failed!\n"; } \endcode * * * \exception - In accordance with the non-throwing nature of * ACE, memory allocation failure is reflected by returning NULL. */ inline ACE_Message_Block *make_copied_Message_Block(char const* p, as_size_t n) { #if defined(ACE_NEW_THROWS_EXCEPTIONS) try { #endif /* ACE_NEW_THROWS_EXCEPTIONS */ ACE_Message_Block *pmb = new ACE_Message_Block(n); if(NULL == pmb) { errno = ENOMEM; } else { pmb->wr_ptr(n); if(NULL != p) { ::memcpy(pmb->base(), p, n); } } return pmb; #if defined(ACE_NEW_THROWS_EXCEPTIONS) } catch(ACE_bad_alloc) // TODO: This should be a reference, surely?? { return NULL; } #endif /* ACE_NEW_THROWS_EXCEPTIONS */ } #if defined(STLSOFT_CF_STATIC_ARRAY_SIZE_DETERMINATION_SUPPORT) template <ss_size_t N> inline ACE_Message_Block *make_copied_Message_Block(const char (&ar)[N]) { return make_copied_Message_Block(&ar[0], N); } #endif /* STLSOFT_CF_STATIC_ARRAY_SIZE_DETERMINATION_SUPPORT */ //////////////////////////////////////////////////////////////////////////// // Unit-testing #ifdef STLSOFT_UNITTEST # include "./unittest/message_block_functions_unittest_.h" #endif /* STLSOFT_UNITTEST */ /* ////////////////////////////////////////////////////////////////////// */ #ifndef _ACESTL_NO_NAMESPACE # if defined(_STLSOFT_NO_NAMESPACE) || \ defined(STLSOFT_DOCUMENTATION_SKIP_SECTION) } // namespace acestl # else } // namespace acestl_project } // namespace stlsoft # endif /* _STLSOFT_NO_NAMESPACE */ #endif /* !_ACESTL_NO_NAMESPACE */ /* ////////////////////////////////////////////////////////////////////// */ #endif /* ACESTL_INCL_ACESTL_MEMORY_HPP_MESSAGE_BLOCK_FUNCTIONS */ /* ///////////////////////////// end of file //////////////////////////// */
33.735751
84
0.664107
wohaaitinciu
89830906549049ec94bd68b5850cbaa453031e56
2,782
cpp
C++
src/Fantasma.cpp
rickylh/Medieval-Game
2e818ab09cdd6158b59133c56cfca8e31d1f8f3a
[ "MIT" ]
null
null
null
src/Fantasma.cpp
rickylh/Medieval-Game
2e818ab09cdd6158b59133c56cfca8e31d1f8f3a
[ "MIT" ]
null
null
null
src/Fantasma.cpp
rickylh/Medieval-Game
2e818ab09cdd6158b59133c56cfca8e31d1f8f3a
[ "MIT" ]
null
null
null
#include "Fantasma.hpp" #include "Fase.hpp" const float Fantasma::TEMPO_FANTASMA (0.2f); Fantasma::Fantasma(sf::Vector2f posicao) : Inimigo(2.0f, false, false) , caveira_de_fogo(1, 2, sf::Vector2f(10.0f,10.0f), this) , _tempo_ataque (0.0f) { setIdTipoObjeto(Codigos::FANTASMA); setPosicao(posicao); carregarAnimacoes(); setArea(sf::Vector2f(35, 35)); caveira_de_fogo.setVelocidade(sf::Vector2f(6.0f, 3.0f)); caveira_de_fogo.setPosicao(posicao); caveira_de_fogo.setIdTipoObjeto(Codigos::BOLA_FOGO); surgindo.atualiza(true, _corpo, TEMPO_FANTASMA); setVelocidade(sf::Vector2f(0, 0));\ setEstatico(true); _esta_nascendo = true; esta_atacando = false; } Fantasma::~Fantasma(){ } void Fantasma::mover(){ if (estaVivo() && !esta_atacando && !_esta_nascendo) { if (getJogadorMaisProximo()->getPosicao().x > getPosicao().x) { setEstaParaDireita(false); } else { setEstaParaDireita(true); } parado.atualiza(estaParaDireita(), _corpo); } else if (_esta_nascendo) { if (surgindo.terminou()) { _esta_nascendo = false; } else { surgindo.atualiza(estaParaDireita(), _corpo); } } EntidadeColidivel::mover(); } void Fantasma::carregarAnimacoes(){ soltando_caveira.setConfig("sprites/fantasma-cast.png", 4, TEMPO_FANTASMA); parado.setConfig("sprites/fantasma.png", 7, TEMPO_FANTASMA); surgindo.setConfig("sprites/fantasma-spawn.png", 6, TEMPO_FANTASMA); _morte.setConfig("sprites/fantasma-death.png", 7, TEMPO_FANTASMA); caveira_de_fogo.setAnimador("sprites/caveira-fogo_att.png", 8, 0.15f); } Projetil* Fantasma::atacar() { if (!estaVivo() || (getJogador1() == NULL && getJogador2() == NULL)) { return NULL; } Projetil* atk = NULL; _tempo_ataque += Fase::getCronometro(); if (estaVivo() && !_esta_nascendo && !esta_atacando) { if (caveira_de_fogo.recarregou()) { esta_atacando = true; soltando_caveira.reiniciar(); } } else if (esta_atacando) { if (soltando_caveira.executou(3) && _tempo_ataque > 1.0f) { _tempo_ataque = 0; atk = new Projetil (caveira_de_fogo); atk->setPosicao(getPosicao()); atk->ativar(); sf::Vector2f vel; vel.x = caveira_de_fogo.getVelocidade().x * direcaoNormalizada(getJogadorMaisProximo()).x; vel.y = caveira_de_fogo.getVelocidade().y * direcaoNormalizada(getJogadorMaisProximo()).y; atk->setVelocidade(vel); caveira_de_fogo.setTempoUltimoArtefatoAtaque(0); } if (!soltando_caveira.terminou()) { soltando_caveira.atualiza(estaParaDireita(), _corpo); } else { soltando_caveira.zerar(); parado.atualiza(estaParaDireita(), _corpo); esta_atacando = false; } } return atk; }
28.387755
94
0.668584
rickylh
898400f485fa53dc1690a4de3cf759bc7b9292f9
704
hpp
C++
state/state.hpp
B777B2056/Design-Pattern-Cpp
cb2cb72d745cc7b529ef5957dc787b7094001165
[ "MIT" ]
null
null
null
state/state.hpp
B777B2056/Design-Pattern-Cpp
cb2cb72d745cc7b529ef5957dc787b7094001165
[ "MIT" ]
null
null
null
state/state.hpp
B777B2056/Design-Pattern-Cpp
cb2cb72d745cc7b529ef5957dc787b7094001165
[ "MIT" ]
null
null
null
#ifndef STATE #define STATE #include <string> #include <memory> #include <iostream> class context; class state { public: virtual ~state() {} virtual void handle(context& c) = 0; }; class concrete_state_A : public state { private: std::string _inner_state; public: concrete_state_A(); virtual void handle(context& c) override; }; class concrete_state_B : public state { private: std::string _inner_state; public: concrete_state_B(); virtual void handle(context& c) override; }; class context { friend class concrete_state_A; friend class concrete_state_B; private: std::shared_ptr<state> _s; public: context(state* s); void request(); }; #endif
13.538462
45
0.691761
B777B2056
8985ea1530bd6c49cbf6bc9acdb1f0b71aba2087
3,039
cpp
C++
src/order_book/order_book.cpp
YileZheng/hft-system
9294d751a6906f42c6c2ebc4f180a1415c6ff12f
[ "MIT" ]
1
2022-03-03T16:15:01.000Z
2022-03-03T16:15:01.000Z
src/order_book/order_book.cpp
YileZheng/hft-system
9294d751a6906f42c6c2ebc4f180a1415c6ff12f
[ "MIT" ]
null
null
null
src/order_book/order_book.cpp
YileZheng/hft-system
9294d751a6906f42c6c2ebc4f180a1415c6ff12f
[ "MIT" ]
1
2022-03-08T00:27:51.000Z
2022-03-08T00:27:51.000Z
#include "order_book.hpp" // make sure there should up to only one empty slot each time execute this function void table_refresh( int ystart, int xstart, price_lookup price_table[LEVELS*STOCKS][2] ){ bool last_empty = False; price_lookup slot; for (int i=0; i < LEVELS; i++){ slot = price_table[ystart+i][xstart]; if (last_empty){ price_table[ystart+i][xstart] = slot; last_empty = true }else{ last_empty = slot.orderCnt == 0; } } } // insert a new data in the table and move the following data 1 step backward void table_insert( int &ystart, int &xstart, price_lookup price_table[LEVELS*STOCKS][2], price_lookup price_new, int &insert_pos // relative position to the start point ){ price_lookup bubble = price_new, bubble_tmp; for (int i=0; i < LEVELS; i++){ if (i >= insert_pos && bubble.orderCnt != 0){ // start from the insert_pos and ended at the last valid slot bubble_tmp = price_table[ystart+i][xstart]; price_table[ystart+i][xstart] = bubble; bubble = bubble_tmp; } } } void order_new( sub_order book[LEVELS*STOCKS][2*CAPACITY], price_lookup price_table[LEVELS*STOCKS][2], order order_info, ap_uint<12> bookIndex, bool bid=true ){ int book_frame_ystart = bookIndex*LEVELS; int book_frame_xstart = bid? 0: CAPACITY; int price_table_frame_xstart = bid? 0: 1; static int heap_head=0, heap_tail=0; // search existing level if (bid) { for (int i=0; i < LEVELS; i++){ price_lookup level_socket = price_table[book_frame_ystart+i][price_table_frame_xstart] level_socket.orderCnt == 0 || level_socket.price == order_info.price } } } void order_change(bool bid=true){ } void order_remove(bool bid=true){ } void suborder_book(){ } void order_book_system( stream<decoded_message> &messages_stream, stream<Time> &incoming_time, stream<metadata> &incoming_meta, stream<Time> &outgoing_time, stream<metadata> &outgoing_meta, stream<order> &top_bid, stream<order> &top_ask, orderID_t &top_bid_id, orderID_t &top_ask_id) { static sub_order book[LEVELS*STOCKS][2*CAPACITY]; static price_lookup price_map[LEVELS*STOCKS][2]; static symbol_t symbol_list[STOCKS]; // string of length 6 decoded_message msg_inbound = messages_stream.read(); order order_inbound; order_inbound.price = msg_inbound.price; order_inbound.size = msg_inbound.size; order_inbound.orderID = msg_inbound.orderID; symbol_t symbol_inbound = msg_inbound.symbol; ap_uint<3> operation = msg_inbound.operation; // symbol location searching ap_uint<12> bookIndex; // stock's correponding index in the order book, up to 4096 stocks for (int i=0; i<STOCKS; i++){ if (symbol_inbound == symbol_list[i]) bookIndex = i; } // Order book modification according to the operation type switch (operation) { case 0: // Change ASK break; case 2: // New ASK break; case 4: // Remove ASK break; case 1: // Change BID break; case 3: // New BID break; case 5: // Remove BID break; default: break; } // Order book access from master }
23.55814
115
0.71438
YileZheng
898864ee7acfbd5a1d4a0d68fccc6563d09be1c4
10,227
cc
C++
build/x86/cpu/o3/O3CPU.py.cc
billionshang/gem5
18cc4294f32315595f865d07d1f33434e92b06b2
[ "BSD-3-Clause" ]
null
null
null
build/x86/cpu/o3/O3CPU.py.cc
billionshang/gem5
18cc4294f32315595f865d07d1f33434e92b06b2
[ "BSD-3-Clause" ]
null
null
null
build/x86/cpu/o3/O3CPU.py.cc
billionshang/gem5
18cc4294f32315595f865d07d1f33434e92b06b2
[ "BSD-3-Clause" ]
null
null
null
#include "sim/init.hh" namespace { const uint8_t data_m5_objects_O3CPU[] = { 120,156,181,152,91,87,27,57,18,128,101,67,204,37,36,16, 8,201,228,222,185,59,23,226,92,38,153,36,147,153,9,24, 72,60,67,128,180,205,230,44,47,62,237,150,140,5,237,110, 167,213,77,96,207,236,83,246,109,31,118,30,246,23,236,47, 217,199,121,220,127,180,91,85,106,181,101,200,100,206,158,51, 193,208,180,62,149,74,85,186,148,74,246,89,246,51,4,127, 47,29,198,84,12,47,28,126,11,44,96,172,91,96,155,5, 86,192,114,145,5,69,214,200,222,134,244,219,16,11,134,89, 119,152,109,14,231,50,71,116,205,48,11,74,172,91,98,155, 165,188,102,4,106,142,48,49,204,218,5,198,75,236,111,140, 125,100,236,207,155,163,140,143,176,122,121,20,186,149,255,133, 159,114,1,222,18,44,182,82,25,240,165,112,87,19,124,220, 214,175,35,240,88,240,148,168,174,111,104,48,6,143,181,71, 213,142,240,119,68,156,140,67,105,81,196,114,23,208,250,134, 111,60,28,198,86,232,225,223,225,77,48,116,12,44,219,44, 162,171,155,67,104,24,88,137,86,65,145,236,4,247,178,98, 137,138,195,166,56,194,196,40,219,30,99,224,14,56,242,177, 200,54,199,13,25,97,124,148,200,81,34,19,140,3,28,39, 114,204,34,71,137,28,183,200,4,145,73,139,28,35,50,101, 52,31,103,124,146,200,9,67,166,24,63,65,100,218,144,105, 198,103,136,204,88,122,78,18,57,105,145,89,34,179,22,57, 69,228,148,69,78,19,57,109,245,254,21,145,175,44,153,51, 68,206,88,228,44,145,179,22,57,71,228,156,165,231,60,145, 243,150,204,5,34,23,12,185,200,248,37,34,23,45,25,135, 200,37,75,207,101,34,142,69,174,16,185,108,145,171,68,174, 16,185,202,196,53,92,114,252,26,193,235,150,242,235,68,110, 88,228,6,145,155,150,170,155,68,202,22,41,19,185,101,90, 221,98,252,54,145,219,150,158,59,68,238,152,86,119,25,159, 35,114,215,34,247,136,204,89,147,88,33,114,207,34,247,137, 84,12,121,192,248,67,34,247,137,60,96,226,33,227,143,136, 60,50,50,95,51,254,152,200,215,134,60,97,252,27,34,143, 45,242,148,200,19,67,224,247,25,145,111,12,121,206,248,183, 68,158,90,228,5,145,103,184,5,54,159,51,241,45,227,223, 177,51,124,131,237,148,88,28,14,137,23,108,251,41,250,118, 18,42,67,150,181,19,208,238,37,181,251,206,90,194,243,68, 190,55,100,129,241,42,145,31,44,139,22,137,188,36,50,207, 248,18,227,203,68,22,12,121,197,248,107,34,85,34,139,140, 215,24,255,145,200,146,37,243,19,145,101,75,102,133,200,43, 75,230,13,145,215,150,204,42,145,154,145,89,99,124,157,200, 143,68,126,98,98,133,241,183,76,188,97,219,32,9,225,206, 165,218,53,51,51,217,216,252,192,118,32,212,212,169,110,157, 241,6,6,147,205,183,204,173,151,255,4,129,201,197,232,164, 38,225,225,247,210,74,244,168,194,49,128,221,235,116,124,12, 112,230,175,138,225,11,37,33,100,213,203,69,120,89,77,74, 24,0,101,87,134,91,101,140,114,58,32,98,52,247,3,165, 9,62,84,21,30,149,110,152,84,58,91,109,85,169,119,188, 88,212,59,34,172,108,137,238,227,185,40,150,91,50,156,83, 137,215,10,196,220,195,251,15,30,207,61,155,123,84,81,177, 95,201,204,161,80,122,175,183,159,28,5,61,93,209,141,226, 253,102,55,226,226,22,234,70,67,88,241,211,150,38,12,44, 69,178,170,45,67,214,136,83,65,37,183,100,236,251,99,141, 60,14,122,98,241,62,149,177,104,250,158,223,17,106,238,255, 180,211,29,53,99,249,165,108,60,129,202,210,94,47,138,147, 102,226,237,136,102,180,43,226,7,125,51,37,245,118,12,30, 181,80,38,210,11,28,63,74,195,68,254,138,24,103,161,138, 142,57,235,208,94,73,52,84,205,210,185,231,195,172,56,73, 228,180,69,226,119,28,46,2,111,159,106,92,17,122,221,67, 53,55,80,191,82,169,168,44,237,9,63,77,68,229,93,44, 19,209,242,252,157,79,41,169,70,221,174,76,14,212,200,81, 99,210,50,193,15,146,39,29,249,18,225,217,28,182,210,118, 91,196,142,146,127,17,142,12,157,214,126,34,148,116,80,166, 156,203,188,79,69,42,114,145,174,244,227,104,46,234,41,167, 39,226,185,164,19,11,143,171,83,3,158,112,237,173,182,239, 230,231,93,25,144,61,53,224,203,64,213,108,110,206,193,154, 137,254,248,146,139,191,215,99,172,237,252,84,143,135,170,250, 243,54,80,53,209,119,183,223,101,95,205,111,117,174,167,5, 215,17,53,232,15,216,103,27,168,135,198,31,20,21,90,72, 87,57,101,25,38,34,14,97,21,66,85,2,235,174,182,244, 206,129,101,190,37,110,41,220,109,139,82,245,188,124,242,105, 49,104,77,186,140,129,173,223,155,102,39,113,160,211,208,79, 100,132,122,55,96,149,59,189,40,10,126,111,88,125,237,190, 54,249,226,128,123,177,136,98,8,156,102,177,245,199,48,27, 50,221,49,130,250,251,212,83,102,169,226,38,35,218,136,189, 158,19,120,137,8,253,125,53,221,95,8,22,150,71,80,248, 46,10,75,232,212,94,214,237,8,122,6,35,63,120,49,87, 100,102,26,74,223,67,255,212,237,223,106,0,127,40,127,64, 252,60,6,162,180,219,2,201,168,237,4,145,199,179,205,33, 194,36,150,66,169,11,3,2,42,137,98,49,40,33,233,64, 185,51,32,214,11,60,95,40,28,40,213,145,237,196,241,56, 7,139,69,27,27,251,152,60,171,26,14,77,39,74,3,14, 131,215,19,33,71,151,157,93,25,5,218,46,144,214,146,130, 147,245,104,153,114,110,104,3,148,3,100,59,85,73,86,148, 191,252,103,136,145,202,65,87,42,218,92,25,170,68,153,238, 113,73,65,143,78,47,22,92,250,80,15,38,146,25,45,20, 220,245,2,201,97,252,185,196,44,158,156,95,241,160,31,10, 66,96,138,86,72,65,151,70,86,157,70,63,8,42,145,56, 181,69,187,238,204,128,65,110,182,100,22,104,94,148,196,83, 65,93,27,28,182,206,190,130,137,9,28,220,3,91,192,98, 177,37,21,108,7,117,112,124,141,96,27,220,76,224,68,134, 245,12,109,250,242,116,53,105,204,187,175,150,26,205,90,125, 158,142,105,47,238,210,255,189,167,79,212,165,79,171,243,125, 171,203,171,3,50,56,136,113,74,123,232,192,252,255,27,231, 223,25,16,62,176,61,204,90,194,61,84,127,211,112,250,130, 180,236,209,254,134,142,186,9,109,25,0,129,200,200,84,214, 70,111,144,94,20,72,95,231,6,235,94,156,72,52,71,232, 96,141,66,43,245,183,14,30,148,168,113,157,68,37,71,235, 174,90,245,168,23,166,28,102,60,151,244,98,216,214,232,243, 108,38,87,59,168,70,93,233,215,124,78,129,49,196,93,91, 56,168,225,170,85,245,25,21,52,115,46,28,192,220,141,90, 48,232,39,178,102,89,96,209,202,72,40,76,187,217,24,209, 32,45,196,94,8,35,180,110,214,53,45,205,165,144,150,99, 163,190,230,188,161,92,202,193,92,42,160,204,4,163,246,152, 201,76,254,165,51,19,72,247,206,192,13,17,147,235,127,224, 181,20,175,215,5,188,156,255,21,46,231,73,17,179,240,159, 25,219,30,194,235,40,100,88,112,11,77,142,224,69,20,158, 31,217,48,84,53,75,236,231,2,166,210,40,54,194,182,71, 49,81,197,247,18,107,142,88,85,99,131,85,26,142,179,172, 56,206,194,73,188,205,190,122,13,83,141,119,88,253,213,64, 189,140,1,116,213,197,233,119,113,165,88,247,120,76,158,230, 227,110,99,101,129,174,244,31,162,120,7,67,0,45,21,177, 39,147,181,112,41,142,33,133,65,13,105,15,247,184,33,51, 40,238,197,225,90,24,236,175,133,43,208,72,115,138,107,184, 143,49,6,47,185,238,154,251,220,201,110,254,78,4,178,78, 150,84,65,88,128,217,2,56,239,190,113,96,179,93,166,36, 73,167,116,104,100,153,206,86,76,178,92,140,244,46,238,65, 23,59,77,48,194,47,123,129,18,148,4,210,183,13,126,246, 213,2,10,201,164,229,226,36,82,129,39,45,242,17,178,187, 38,156,37,195,153,91,148,155,107,83,69,208,166,14,190,64, 10,137,131,6,49,60,243,190,218,75,255,137,218,113,177,179, 194,84,97,170,56,89,40,193,103,162,112,14,62,211,67,71, 10,100,21,57,239,98,211,50,122,79,211,210,108,226,9,218, 108,210,2,110,98,98,159,6,88,164,196,120,191,39,136,251, 123,123,205,14,172,107,24,6,156,61,63,240,148,130,189,209, 137,184,139,67,228,226,162,117,199,205,0,210,206,33,229,27, 161,146,91,16,14,168,224,65,168,218,149,137,222,42,148,154, 83,2,75,99,88,221,247,3,161,18,28,44,157,119,53,34, 10,47,139,120,140,19,214,185,209,0,198,204,66,138,15,135, 68,117,150,48,128,177,75,58,49,222,225,169,79,45,169,168, 67,127,29,214,20,93,28,136,189,197,88,74,104,198,234,87, 103,105,90,219,148,233,216,134,51,86,207,54,159,54,122,7, 241,209,220,85,109,82,174,83,167,52,135,117,30,228,102,156, 108,126,52,55,184,175,212,180,135,172,173,111,189,241,42,135, 168,81,98,226,213,136,178,204,75,115,92,44,60,75,240,180, 206,113,35,169,139,56,255,31,90,250,29,103,114,121,99,29, 18,57,106,183,40,218,94,26,36,25,193,202,118,74,175,185, 175,58,132,30,54,11,34,114,223,33,237,128,238,1,203,138, 242,183,126,25,83,180,21,157,161,145,18,61,216,22,68,33, 76,206,160,183,254,76,235,220,203,32,92,192,43,111,151,244, 169,72,165,122,94,66,157,112,76,45,138,30,237,182,58,230, 79,180,61,22,192,23,29,39,142,105,17,170,199,112,165,18, 220,137,148,154,52,33,11,105,194,226,246,226,38,220,101,100, 164,247,194,202,114,189,65,29,99,161,94,175,233,194,136,62, 67,224,152,81,100,36,188,175,67,34,80,11,19,87,108,105, 67,50,180,140,89,6,65,60,32,155,92,143,244,170,174,172, 86,177,134,226,27,217,89,135,56,68,38,134,118,61,29,236, 64,106,185,163,153,8,12,190,33,168,92,117,81,175,73,11, 76,86,128,179,89,79,240,160,36,75,65,136,36,178,195,112, 66,35,24,146,12,96,188,4,55,104,227,233,138,252,192,213, 115,218,77,106,70,246,184,41,247,69,50,125,96,89,38,51, 153,131,190,80,198,244,154,178,228,244,49,156,159,194,164,172, 17,165,49,46,181,48,89,88,39,95,32,102,65,193,197,179, 157,86,120,43,111,68,83,20,10,200,105,224,204,118,47,13, 132,243,63,52,166,211,247,64,215,81,225,47,240,192,240,93, 42,78,14,227,103,186,8,159,2,124,244,19,2,122,254,94, 180,254,155,247,194,108,254,150,201,101,165,177,236,147,183,27, 42,21,166,70,166,250,172,112,224,83,156,160,186,153,194,88, 113,181,60,102,198,166,251,248,30,44,56,25,138,108,141,141, 105,214,195,176,175,104,184,176,20,71,123,251,46,157,58,47, 243,51,182,205,178,175,187,190,208,16,82,231,47,244,25,246, 61,94,21,232,130,58,85,24,135,207,148,254,43,254,15,190, 234,75,146, }; EmbeddedPython embedded_m5_objects_O3CPU( "m5/objects/O3CPU.py", "/mnt/hgfs/ShareShen/gem5-origin-stable-2015-9-3/src/cpu/o3/O3CPU.py", "m5.objects.O3CPU", data_m5_objects_O3CPU, 2563, 6391); } // anonymous namespace
57.455056
74
0.661093
billionshang
898997678197f9d0d9bcaa468b0dc51d11207bb2
488
cpp
C++
70. Climbing Stairs/Solution.cpp
Ainevsia/Leetcode-Rust
c4f16d72f3c0d0524478b6bb90fefae9607d88be
[ "BSD-2-Clause" ]
15
2020-02-07T13:04:05.000Z
2022-03-02T14:33:21.000Z
70. Climbing Stairs/Solution.cpp
Ainevsia/Leetcode-Rust
c4f16d72f3c0d0524478b6bb90fefae9607d88be
[ "BSD-2-Clause" ]
null
null
null
70. Climbing Stairs/Solution.cpp
Ainevsia/Leetcode-Rust
c4f16d72f3c0d0524478b6bb90fefae9607d88be
[ "BSD-2-Clause" ]
3
2020-04-02T15:36:57.000Z
2021-09-14T14:13:44.000Z
#include <string> #include <vector> #include <iostream> #include <sstream> #include <algorithm> #include <tuple> #include <deque> #include <unordered_map> #include <cmath> using namespace std; class Solution { public: int climbStairs(int n) { vector <int> fib (n+1, 1); for (int i=2; i<=n;i++) { fib[i] = fib[i-1] + fib[i-2]; } // for (int i: fib) cout << i; return fib[n]; } }; int main() { Solution a; return 0; }
16.266667
41
0.55123
Ainevsia
899bd53962ea646c9babfee418df07267d68983b
4,397
cpp
C++
projs/sphere_reflect/src/app.cpp
colintan95/gl_projects
ad9bcdeaaa65474f45968b26a9a565cbe34af68e
[ "MIT" ]
null
null
null
projs/sphere_reflect/src/app.cpp
colintan95/gl_projects
ad9bcdeaaa65474f45968b26a9a565cbe34af68e
[ "MIT" ]
null
null
null
projs/sphere_reflect/src/app.cpp
colintan95/gl_projects
ad9bcdeaaa65474f45968b26a9a565cbe34af68e
[ "MIT" ]
null
null
null
#include "app.h" #include <iostream> #include <cstdlib> #include <random> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtx/string_cast.hpp> #include "gfx_utils/primitives.h" // // Significant portion of implementation adapted from: LearnOpenGL // https://learnopengl.com/Advanced-Lighting/SSAO // static const float kPi = 3.14159265358979323846f; static const int kWindowWidth = 1920; static const int kWindowHeight = 1080; static const std::string kReflectPassVertShaderPath = "shaders/reflection.vert"; static const std::string kReflectPassFragShaderPath = "shaders/reflection.frag"; // Format of vertex - {pos_x, pos_y, pos_z, texcoord_u, texcoord_v} static const float kQuadVertices[] = { -1.f, 1.f, 0.f, 0.f, 1.f, -1.f, -1.f, 0.f, 0.f, 0.f, 1.f, 1.f, 0.f, 1.f, 1.f, 1.f, -1.f, 0.f, 1.f, 0.f }; void App::Run() { Startup(); MainLoop(); Cleanup(); } void App::MainLoop() { bool should_quit = false; while (!should_quit) { ReflectPass(); window_.SwapBuffers(); window_.TickMainLoop(); if (window_.ShouldQuit()) { should_quit = true; } } } void App::ReflectPass() { glUseProgram(reflect_pass_program_.GetProgramId()); glViewport(0, 0, kWindowWidth, kWindowHeight); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glBindVertexArray(reflect_pass_vao_); glm::mat4 view_mat = camera_.CalcViewMatrix(); glm::mat4 proj_mat = glm::perspective(glm::radians(30.f), window_.GetAspectRatio(), 0.1f, 1000.f); const auto& entities = scene_.GetEntities(); for (auto entity_ptr : entities) { if (!entity_ptr->HasModel()) { continue; } for (auto& mesh : entity_ptr->GetModel()->GetMeshes()) { glm::mat4 model_mat = entity_ptr->ComputeTransform(); glm::mat4 mv_mat = view_mat * model_mat; glm::mat4 mvp_mat = proj_mat * view_mat * model_mat; glm::mat3 normal_mat = glm::transpose(glm::inverse(glm::mat3(mv_mat))); reflect_pass_program_.GetUniform("mv_mat").Set(mv_mat); reflect_pass_program_.GetUniform("mvp_mat").Set(mvp_mat); reflect_pass_program_.GetUniform("normal_mat").Set(normal_mat); reflect_pass_program_.GetUniform("camera_pos") .Set(camera_.GetCameraLocation()); GLuint cubemap_id = resource_manager_.GetCubemapId("skybox"); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_CUBE_MAP, cubemap_id); reflect_pass_program_.GetUniform("cubemap").Set(1); // Set vertex attributes GLuint pos_vbo_id = resource_manager_.GetMeshVboId(mesh.id, gfx_utils::kVertTypePosition); glBindBuffer(GL_ARRAY_BUFFER, pos_vbo_id); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)0); GLuint normal_vbo_id = resource_manager_.GetMeshVboId(mesh.id, gfx_utils::kVertTypeNormal); glBindBuffer(GL_ARRAY_BUFFER, normal_vbo_id); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, (GLvoid*)0); glDrawArrays(GL_TRIANGLES, 0, mesh.num_verts); } } glBindVertexArray(0); glUseProgram(0); } void App::Startup() { if (!window_.Inititalize(kWindowWidth, kWindowHeight, "Shadow Map")) { std::cerr << "Failed to initialize gfx window" << std::endl; exit(1); } if (!camera_.Initialize(&window_)) { std::cerr << "Failed to initialize camera" << std::endl; exit(1); } scene_.LoadSceneFromJson("scene/scene.json"); resource_manager_.SetScene(&scene_); resource_manager_.CreateGLResources(); glEnable(GL_TEXTURE_2D); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glEnable(GL_CULL_FACE); SetupReflectPass(); } void App::SetupReflectPass() { if (!reflect_pass_program_.CreateFromFiles(kReflectPassVertShaderPath, kReflectPassFragShaderPath)) { std::cerr << "Could not create reflect pass program." << std::endl; exit(1); } glGenVertexArrays(1, &reflect_pass_vao_); } void App::Cleanup() { glDeleteVertexArrays(1, &reflect_pass_vao_); resource_manager_.Cleanup(); window_.Destroy(); }
26.810976
80
0.654992
colintan95
899c0b78a6e02e4b8fb767c9b055e1c7303c4706
1,702
cpp
C++
src/Look.cpp
FellowRoboticists/myRobotScan
f87c73937d1a26a273479c6747bd7d4731bf31e3
[ "MIT" ]
null
null
null
src/Look.cpp
FellowRoboticists/myRobotScan
f87c73937d1a26a273479c6747bd7d4731bf31e3
[ "MIT" ]
null
null
null
src/Look.cpp
FellowRoboticists/myRobotScan
f87c73937d1a26a273479c6747bd7d4731bf31e3
[ "MIT" ]
null
null
null
// Look Arduino library // // Copyright 2013 Dave Sieh // See LICENSE.txt for details. #include <Arduino.h> #include "Look.h" #include "SoftServo.h" #include "IrSensors.h" #include "PingSensor.h" #include "pspc_support.h" Look::Look(SoftServo *sweepServo, IrSensors *sensors, PingSensor *pingSensor) { servo = sweepServo; irSensors = sensors; ping = pingSensor; } void Look::begin() { if (servo) { servo->begin(); } if (irSensors) { irSensors->begin(); } if (ping) { ping->begin(); } } boolean Look::irEdgeDetect(IrSensor sensor) { boolean detected = false; if (irSensors) { detected = irSensors->lowReflectionDetected(sensor); } return detected; } boolean Look::sensesObstacle(ObstacleType obstacle, int minDistance) { switch(obstacle) { case OBST_FRONT_EDGE: return irEdgeDetect(IrLeft) && irEdgeDetect(IrRight); case OBST_LEFT_EDGE: return irEdgeDetect(IrLeft); case OBST_RIGHT_EDGE: return irEdgeDetect(IrRight); case OBST_FRONT: return lookAt(DIR_CENTER) <= minDistance; } return false; } int Look::lookAt(LookDirection direction) { int angle = servoAngles[direction]; // wait for servo to get into position servo->write(angle, servoDelay); int distance = (ping) ? ping->getAverageDistance(4) : 0; // distaceToObstacle(); if (angle != servoAngles[DIR_CENTER]) { #ifdef LOOK_DEBUG // Print only if looking right/left Serial.print(P("looking at dir ")); Serial.print(angle), Serial.print(P(" distance= ")); Serial.println(distance); #endif // Re-center the servo servo->write(servoAngles[DIR_CENTER], servoDelay / 2); } return distance; }
22.394737
82
0.672738
FellowRoboticists
89a64aaf723287c92770b3b3227e323d7298bea2
1,483
cpp
C++
03-Ejemplo basico de Qt/main.cpp
vialrogo/TutorialCPP
f0b44dcc0f58eb54ce5d48a069923f5963eb545f
[ "CC0-1.0" ]
null
null
null
03-Ejemplo basico de Qt/main.cpp
vialrogo/TutorialCPP
f0b44dcc0f58eb54ce5d48a069923f5963eb545f
[ "CC0-1.0" ]
null
null
null
03-Ejemplo basico de Qt/main.cpp
vialrogo/TutorialCPP
f0b44dcc0f58eb54ce5d48a069923f5963eb545f
[ "CC0-1.0" ]
null
null
null
/* +---------------------------------------+ | Ejemplos-Tutorial C++ con Qt | | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | | Creado por: Victor Alberto Romero | | e-mail: [email protected] | +---------------------------------------+ Archivo main de ejemplo de qt básico En esta clase podemos ver como usamos la clase BasicoQT para hacer la suma de unas cadenas. Estas clases usan la clase QString de QT, por lo cual se compilan diferentes. Primero de seclara el objeto miBasicoQT, luego los datos con los que se va a trabajar. Es importante ver que se usa el método cin para el ingreso de caracteres por consola. El método data() de string permite convertir un "string" en un "const char * ". El metodo qPrintable permite convertir un QString en un char* Podemos compilar este ejemplo con: qmake -project qmake -makefile make y podemos correrlo con: ./<nombre de la carpeta donde se encuentra> */ #include <iostream> #include <QString> #include "BasicoQT.h" using namespace std; //Es para poder usar directamente cin, cout y endl. int main() { BasicoQT* miBasicoQT = new BasicoQT(); char* Cabecera = "La cadena sumada fue: "; string parteA; string parteB; cout<<"Introduzca la parte A: "<<endl; cin>>parteA; cout<<"Introduzca la parte B: "<<endl; cin>>parteB; miBasicoQT->calcularCadena(parteA.data(), parteB.data()); QString* cadenaSumada = miBasicoQT->devolverCadena(); cout<<Cabecera<<qPrintable(*cadenaSumada)<<endl; return 0; }
26.482143
119
0.664194
vialrogo
89a6ad9f44e2b3661a8cbab41b0e722e79153c56
842
cpp
C++
code_blocks/check_fft/main.cpp
rafald/xtechnical_analysis
7686c16241e9e53fb5a5548354531b533f983b54
[ "MIT" ]
12
2020-01-20T14:22:18.000Z
2022-01-26T04:41:36.000Z
code_blocks/check_fft/main.cpp
rafald/xtechnical_analysis
7686c16241e9e53fb5a5548354531b533f983b54
[ "MIT" ]
1
2020-05-23T07:35:03.000Z
2020-05-23T07:35:03.000Z
code_blocks/check_fft/main.cpp
rafald/xtechnical_analysis
7686c16241e9e53fb5a5548354531b533f983b54
[ "MIT" ]
9
2019-11-02T19:01:55.000Z
2021-07-08T21:51:44.000Z
#include <iostream> #include "xtechnical_indicators.hpp" using namespace std; int main() { cout << "Hello world!" << endl; xtechnical_indicators::FreqHist<double> iFreqHist(100, xtechnical_dft::RECTANGULAR_WINDOW); const double MATH_PI = 3.14159265358979323846264338327950288; for(size_t i = 0; i < 1000; ++i) { double temp = std::cos(3 * MATH_PI * 2 * (double)i / 100.0); std::vector<double> amplitude; std::vector<double> frequencies; iFreqHist.update(temp, amplitude, frequencies, 100); std::cout << "step: " << i << " temp " << temp << std::endl; for(size_t i = 0; i < frequencies.size(); ++i) { std::cout << "freq " << frequencies[i] << " " << amplitude[i] << std::endl; } std::cout << std::endl << std::endl; } return 0; }
31.185185
87
0.58076
rafald
89a93f9d49fa304f09791a1595ca12b48e44ebdc
1,952
cpp
C++
src/Gen/Builders/DoLoopBuilder.cpp
albeva/LightBASIC
489bcc81bed268798874d6675054e594ffc8eb07
[ "MIT" ]
6
2021-05-24T15:43:58.000Z
2022-03-21T12:50:05.000Z
src/Gen/Builders/DoLoopBuilder.cpp
albeva/LightBASIC
489bcc81bed268798874d6675054e594ffc8eb07
[ "MIT" ]
15
2022-02-23T23:24:36.000Z
2022-03-05T13:44:27.000Z
src/Gen/Builders/DoLoopBuilder.cpp
albeva/LightBASIC
489bcc81bed268798874d6675054e594ffc8eb07
[ "MIT" ]
1
2017-04-13T13:13:29.000Z
2017-04-13T13:13:29.000Z
// // Created by Albert Varaksin on 28/05/2021. // #include "DoLoopBuilder.hpp" #include "Driver/Context.hpp" using namespace lbc; using namespace Gen; DoLoopBuilder::DoLoopBuilder(CodeGen& gen, AstDoLoopStmt& ast) : Builder{ gen, ast }, m_bodyBlock{ llvm::BasicBlock::Create(m_llvmContext, "do_loop.body") }, m_condBlock{ (m_ast.condition == AstDoLoopStmt::Condition::None) ? nullptr : llvm::BasicBlock::Create(m_llvmContext, "do_loop.cond") }, m_exitBlock{ llvm::BasicBlock::Create(m_llvmContext, "do_loop.end") }, m_continueBlock{ m_condBlock } { build(); } void DoLoopBuilder::build() { for (const auto& decl : m_ast.decls) { m_gen.visit(*decl); } // pre makeCondition switch (m_ast.condition) { case AstDoLoopStmt::Condition::None: m_continueBlock = m_bodyBlock; break; case AstDoLoopStmt::Condition::PreUntil: makeCondition(true); break; case AstDoLoopStmt::Condition::PreWhile: makeCondition(false); break; default: break; } // body m_gen.switchBlock(m_bodyBlock); m_gen.getControlStack().push(ControlFlowStatement::Do, { m_continueBlock, m_exitBlock }); m_gen.visit(*m_ast.stmt); m_gen.getControlStack().pop(); // post makeCondition switch (m_ast.condition) { case AstDoLoopStmt::Condition::PostUntil: makeCondition(true); break; case AstDoLoopStmt::Condition::PostWhile: makeCondition(false); break; default: m_gen.terminateBlock(m_continueBlock); break; } // exit m_gen.switchBlock(m_exitBlock); } void DoLoopBuilder::makeCondition(bool isUntil) { m_gen.switchBlock(m_condBlock); auto value = m_gen.visit(*m_ast.expr).load(); if (isUntil) { m_builder.CreateCondBr(value, m_exitBlock, m_bodyBlock); } else { m_builder.CreateCondBr(value, m_bodyBlock, m_exitBlock); } }
27.492958
93
0.659324
albeva
89af705ee09cb1cb533cbad81ee8eaa74e2c01a7
413
hpp
C++
header/Connector.hpp
Sdc97/Rshell
37c0dd264799d199e6c0dc1f13ae1e25f9368620
[ "MIT" ]
1
2020-06-28T20:40:57.000Z
2020-06-28T20:40:57.000Z
header/Connector.hpp
Sdc97/Rshell
37c0dd264799d199e6c0dc1f13ae1e25f9368620
[ "MIT" ]
null
null
null
header/Connector.hpp
Sdc97/Rshell
37c0dd264799d199e6c0dc1f13ae1e25f9368620
[ "MIT" ]
1
2021-04-02T21:47:58.000Z
2021-04-02T21:47:58.000Z
#ifndef CONNECTOR #define CONNECTOR #include "Executable.hpp" #include "Cmnd.hpp" class Connector : public Executable { protected: Executable* left; Executable* right; public: virtual bool run_command() =0; virtual char** get_command() {} virtual void set_left(Executable*) =0; virtual void set_right(Executable*) =0; virtual Executable* get_left() =0; virtual Executable* get_right() =0; }; #endif
18.772727
40
0.731235
Sdc97
89af7544e15c04b34f0c1e40b22d5ca5ef17f78e
1,953
cpp
C++
src/display/display.cpp
passinglink/passinglink
d1bc70cc8bf2c32a9dfea412fc37a44c6dbf09c1
[ "MIT" ]
76
2020-03-09T20:30:59.000Z
2022-03-29T13:39:47.000Z
src/display/display.cpp
Project-Alpaca/passinglink
f259466d2e8aafca6c8511df3b1259156954e907
[ "MIT" ]
24
2020-08-08T23:07:12.000Z
2022-03-31T20:38:07.000Z
src/display/display.cpp
Project-Alpaca/passinglink
f259466d2e8aafca6c8511df3b1259156954e907
[ "MIT" ]
18
2020-07-31T01:23:44.000Z
2022-03-23T01:14:45.000Z
#include "display/display.h" #include <stdio.h> #include "arch.h" #include "display/menu.h" #include "display/ssd1306.h" #include "types.h" #include "util.h" #include <logging/log.h> #define LOG_LEVEL LOG_LEVEL_INF LOG_MODULE_REGISTER(display); static bool status_locked; static bool status_probing; static optional<uint32_t> status_latency; static ProbeType status_probe_type; static void display_draw_status_line() { char buf[DISPLAY_WIDTH + 1]; static_assert(DISPLAY_WIDTH == 21); char* p = buf; memset(buf, ' ', sizeof(buf) - 1); switch (status_probe_type) { case ProbeType::NX: p += copy_text(buf, "Switch"); break; case ProbeType::PS3: p += copy_text(buf, "PS3"); break; case ProbeType::PS4: p += copy_text(buf, "PS4"); break; } if (status_probing) { p[0] = '?'; } if (status_probe_type == ProbeType::NX) { p = buf + 8; if (!status_probing) { ++p; } } else { p = buf + 7; } if (status_locked) { memcpy(p, "LOCKED", strlen("LOCKED")); } if (!status_latency) { snprintf(buf + 15, 7, " ???us"); } else { snprintf(buf + 15, 7, "%4uus", *status_latency); } buf[DISPLAY_WIDTH] = '\0'; display_set_line(DISPLAY_ROWS, buf); } void display_update_latency(uint32_t us) { status_latency.reset(us); display_draw_status_line(); display_blit(); } void display_set_locked(bool locked) { status_locked = locked; display_draw_status_line(); display_blit(); } void display_set_connection_type(bool probing, ProbeType type) { LOG_INF("display_set_connection_type: probing = %d", probing); status_probing = probing; status_probe_type = type; display_draw_status_line(); display_blit(); } void display_init() { status_locked = false; status_probing = true; status_probe_type = ProbeType::NX; ssd1306_init(); menu_init(); display_draw_logo(); display_draw_status_line(); display_blit(); }
19.53
64
0.664107
passinglink
89b786614913a2a02561549873a2de4534c62c9d
10,368
cpp
C++
src/D3dsurf.cpp
rbwsok/3dfx-OpenGL-ICD-update
4e0846d6569bf5d7ec8b22918f33fc7701df6e73
[ "Unlicense" ]
null
null
null
src/D3dsurf.cpp
rbwsok/3dfx-OpenGL-ICD-update
4e0846d6569bf5d7ec8b22918f33fc7701df6e73
[ "Unlicense" ]
null
null
null
src/D3dsurf.cpp
rbwsok/3dfx-OpenGL-ICD-update
4e0846d6569bf5d7ec8b22918f33fc7701df6e73
[ "Unlicense" ]
null
null
null
// // d3dsurf.cpp : You *really* don't want to know // #include "stdafx.h" #define INITGUID #include <Guiddef.h> // {1F2069EB-6D07-4f75-9409-AFEABA279E6A} //DEFINE_GUID(IID_IGXP_D3DSurface8, //0x1f2069eb, 0x6d07, 0x4f75, 0x94, 0x9, 0xaf, 0xea, 0xba, 0x27, 0x9e, 0x6a); #define PRINTF while(0) printf #define IS_2_POW_N(X) (((X)&(X-1)) == 0) void * _fastcall _aligned_malloc(size_t size,size_t alignment) { size_t ptr, r_ptr; size_t *reptr; if (!IS_2_POW_N(alignment)) { return NULL; } alignment = (alignment > sizeof(void *) ? alignment : sizeof(void *)); if ((ptr = (size_t)GlobalAllocPtr(GPTR,size + alignment + sizeof(void *))) == (size_t)NULL) return NULL; r_ptr = (ptr + alignment + sizeof(void *)) & ~(alignment -1); reptr = (size_t *)(r_ptr - sizeof(void *)); *reptr = ptr; return (void *)r_ptr; } void _fastcall _aligned_free(void *memblock) { size_t ptr; if (memblock == NULL) return; ptr = (size_t)memblock; /* ptr points to the pointer to starting of the memory block */ ptr = (ptr & ~(sizeof(void *) -1)) - sizeof(void *); /* ptr is the pointer to the start of memory block*/ ptr = *((size_t *)ptr); GlobalFree((void *)ptr); } int IGXP_D3DSurface8::GetSizeForFormat(D3DFORMAT format) { switch (format) { case D3DFMT_A8R8G8B8: case D3DFMT_X8R8G8B8: return 32; case D3DFMT_R8G8B8: return 24; case D3DFMT_R5G6B5: case D3DFMT_X1R5G5B5: case D3DFMT_A1R5G5B5: case D3DFMT_A4R4G4B4: case D3DFMT_A8R3G3B2: case D3DFMT_X4R4G4B4: case D3DFMT_A8P8: case D3DFMT_A8L8: return 16; case D3DFMT_R3G3B2: case D3DFMT_A8: case D3DFMT_P8: case D3DFMT_L8: case D3DFMT_A4L4: case D3DFMT_DXT2: case D3DFMT_DXT3: case D3DFMT_DXT4: case D3DFMT_DXT5: return 8; case D3DFMT_DXT1: return 4; default: return 0; } } // // operator new // //void *IGXP_D3DSurface8::operator new (size_t s) //{ // PRINTF("void *IGXP_D3DSurface8::operator new (size_t s)\n"); // return CoTaskMemAlloc(s); //} // // operator delete // //void IGXP_D3DSurface8::operator delete (void *b) //{ // PRINTF("void IGXP_D3DSurface8::operator delete (void *b)\n"); // CoTaskMemFree(b); //} // // Constructor // IGXP_D3DSurface8::IGXP_D3DSurface8(D3DFORMAT format, int w, int h, BYTE *_buffer) : m_cRef(1), lock_count(0) { // PRINTF("IGXP_D3DSurface8::IGXP_D3DSurface8(D3DFORMAT format = %i, int w = %i, int h = %i)\n", format, w, h); bpp = GetSizeForFormat(format); // Do these first surf_desc.Format = format; surf_desc.Type = D3DRTYPE_SURFACE; surf_desc.Usage = 0; surf_desc.Pool = D3DPOOL_MANAGED; surf_desc.MultiSampleType = D3DMULTISAMPLE_NONE; surf_desc.Width = w; surf_desc.Height = h; // Now what we need to do is clamp the w and h values if we are using S3TC if (surf_desc.Format >= D3DFMT_DXT1 && surf_desc.Format <= D3DFMT_DXT5) { w = max(w,4); h = max(h,4); } surf_desc.Size = (w * h * bpp) / 8; if (_buffer) { nodel = TRUE; buffer = _buffer; allocated = 0; allocated_size = 0; } else { nodel = FALSE; allocated = buffer = (BYTE*) _aligned_malloc(allocated_size = max(surf_desc.Size,16), 8); } } // // Destructor // IGXP_D3DSurface8::~IGXP_D3DSurface8() { // PRINTF("IGXP_D3DSurface8::~IGXP_D3DSurface8()\n"); if (allocated) _aligned_free(allocated); } // // IUnknown::AddRef implementation // ULONG IGXP_D3DSurface8::AddRef(void) { // PRINTF("ULONG IGXP_D3DSurface8::AddRef(void)\n"); return ++m_cRef; } // // IUnknown::Release implementation // ULONG IGXP_D3DSurface8::Release(void) { // PRINTF("ULONG IGXP_D3DSurface8::Release(void)\n"); --m_cRef; if (!m_cRef) { delete this; return 0; } return m_cRef; } // // IUnknown::QueryInterface implementation // HRESULT IGXP_D3DSurface8::QueryInterface(REFIID riid, void** ppvObj) { // PRINTF("HRESULT IGXP_D3DSurface8::QueryInterface(REFIID riid, void** ppvObj)\n"); if (IsEqualGUID(riid, IID_IUnknown)) { *ppvObj = (IUnknown*)this; return S_OK; } if (IsEqualGUID(riid, IID_IDirect3DSurface8)) { *ppvObj = (IDirect3DSurface8*)this; return S_OK; } if (IsEqualGUID(riid, IID_IGXP_D3DSurface8)) { *ppvObj = (IGXP_D3DSurface8*)this; return S_OK; } *ppvObj = 0; return E_NOINTERFACE; } // // IDirect3DSurface8::GetDevice implementation // HRESULT IGXP_D3DSurface8::GetDevice(IDirect3DDevice8** ppDevice) { // PRINTF("HRESULT IGXP_D3DSurface8::GetDevice(IDirect3DDevice8** ppDevice)\n"); lpD3DDevice->AddRef(); *ppDevice = lpD3DDevice; return D3D_OK; } // // IDirect3DSurface8::SetPrivateData implementation // HRESULT IGXP_D3DSurface8::SetPrivateData(REFGUID refguid,CONST void* pData,DWORD SizeOfData,DWORD Flags) { // PRINTF("HRESULT IGXP_D3DSurface8::SetPrivateData(REFGUID refguid,CONST void* pData,DWORD SizeOfData,DWORD Flags)\n"); return D3DERR_INVALIDCALL; } // // IDirect3DSurface8::GetPrivateData implementation // HRESULT IGXP_D3DSurface8::GetPrivateData(REFGUID refguid,void* pData,DWORD* pSizeOfData) { // PRINTF("HRESULT IGXP_D3DSurface8::GetPrivateData(REFGUID refguid,void* pData,DWORD* pSizeOfData)\n"); return D3DERR_INVALIDCALL; } // // IDirect3DSurface8::FreePrivateData implementation // HRESULT IGXP_D3DSurface8::FreePrivateData(REFGUID refguid) { // PRINTF("HRESULT IGXP_D3DSurface8::FreePrivateData(REFGUID refguid)\n"); return D3DERR_INVALIDCALL; } // // IDirect3DSurface8::GetContainer implementation // HRESULT IGXP_D3DSurface8::GetContainer(REFIID riid,void** ppContainer) { // PRINTF("HRESULT IGXP_D3DSurface8::GetContainer(REFIID riid,void** ppContainer)\n"); return D3DERR_INVALIDCALL; } // // IDirect3DSurface8::GetDesc implementation // HRESULT IGXP_D3DSurface8::GetDesc(D3DSURFACE_DESC *pDesc) { // PRINTF("HRESULT IGXP_D3DSurface8::GetDesc(D3DSURFACE_DESC *pDesc = %X)\n", pDesc); *pDesc = surf_desc; return D3D_OK; } // // IDirect3DSurface8::LockRect implementation // HRESULT IGXP_D3DSurface8::LockRect(D3DLOCKED_RECT* pLockedRect,CONST RECT* pRect,DWORD Flags) { // PRINTF("HRESULT IGXP_D3DSurface8::LockRect(D3DLOCKED_RECT* pLockedRect = %X,CONST RECT* pRect = %X,DWORD Flags = %X)\n", pLockedRect, pRect, Flags); lock_count++; pLockedRect->pBits = buffer; if (surf_desc.Format >= D3DFMT_DXT1 && surf_desc.Format <= D3DFMT_DXT5) { // Pitch will 'screw up' on surfaces smaller than 4 pixels if (surf_desc.Width <= 4) pLockedRect->Pitch = bpp*2; else pLockedRect->Pitch = (surf_desc.Width*bpp)/2; // If we have a rectangle and we are using S3TC, then we must be // aligned to the 4x4 blocks if (pRect) { // Never Valid if ((pRect->left&3) || (pRect->top&3)) return D3DERR_INVALIDCALL; // It's valid to lock non multiples of 4, IF the surface is smaller than 4 pixels if ((pRect->right != (LONG) surf_desc.Width && (pRect->right&3)) || (pRect->bottom != (LONG) surf_desc.Height && (pRect->bottom&3))) { return D3DERR_INVALIDCALL; } int x = pRect->left/4; int y = pRect->top /4; pLockedRect->pBits = buffer + (pLockedRect->Pitch * y) + (x * bpp)/2; } } else { pLockedRect->Pitch = (surf_desc.Width*bpp)/8; if (pRect) pLockedRect->pBits = buffer + (surf_desc.Width*pRect->top+pRect->left)*bpp/8; } return D3D_OK; } // // IDirect3DSurface8::UnlockRect implementation // HRESULT IGXP_D3DSurface8::UnlockRect() { // PRINTF("HRESULT IGXP_D3DSurface8::UnlockRect()\n"); if (lock_count == 0) return D3DERR_INVALIDCALL; lock_count--; return D3D_OK; } // // IGXP_D3DSurface8::CopyFromOpenGL implementation // HRESULT IGXP_D3DSurface8::CopyFromOpenGL (GLenum format, const GLvoid *pixels) { BYTE *dest = buffer; BYTE *end = dest+surf_desc.Size; BYTE *source = (BYTE *)pixels; if (format == GL_RGBA) { if (bpp == 32) while (dest < end) { *(dest+0) = *(source+2); *(dest+1) = *(source+1); *(dest+2) = *(source+0); *(dest+3) = *(source+3); dest+= 4; source+= 4; } else if (bpp == 24) while (dest < end) { *(dest+0) = *(source+2); *(dest+1) = *(source+1); *(dest+2) = *(source+0); dest+= 3; source+= 4; } } else if (format == GL_RGB) { if (bpp == 32) while (dest < end) { *(dest+0) = *(source+2); *(dest+1) = *(source+1); *(dest+2) = *(source+0); *(dest+3) = 0xFF; dest+= 4; source+= 3; } else if (bpp == 24) while (dest < end) { *(dest+0) = *(source+2); *(dest+1) = *(source+1); *(dest+2) = *(source+0); dest+= 3; source+= 3; } } else if (format == GL_BGRA_EXT) { if (bpp == 32) while (dest < end) { *(DWORD*)dest = *(DWORD*)source; dest+= 4; source+= 4; } else if (bpp == 24) while (dest < end) { *(dest+0) = *(source+0); *(dest+1) = *(source+1); *(dest+2) = *(source+2); dest+= 3; source+= 4; } } else if (format == GL_BGR_EXT) { if (bpp == 32) while (dest < end) { *(dest+0) = *(source+0); *(dest+1) = *(source+1); *(dest+2) = *(source+2); *(dest+3) = 0xFF; dest+= 4; source+= 3; } else if (bpp == 24) while (dest < end) { *(dest+0) = *(source+0); *(dest+1) = *(source+1); *(dest+2) = *(source+2); dest+= 3; source+= 3; } } return D3D_OK; } // // IGXP_D3DSurface8::ReallocSurface implementation // HRESULT IGXP_D3DSurface8::ReallocSurface(D3DFORMAT format, int w, int h, BYTE *_buffer) { // PRINTF("IGXP_D3DSurface8::ReallocSurface(D3DFORMAT format = %i, int w = %i, int h = %i)\n", format, w, h); if (lock_count) D3DERR_INVALIDCALL; bpp = GetSizeForFormat(format); // Do these first surf_desc.Format = format; surf_desc.Type = D3DRTYPE_SURFACE; surf_desc.Usage = 0; surf_desc.Pool = D3DPOOL_MANAGED; surf_desc.MultiSampleType = D3DMULTISAMPLE_NONE; surf_desc.Width = w; surf_desc.Height = h; // Now what we need to do is clamp the w and h values if we are using S3TC if (surf_desc.Format >= D3DFMT_DXT1 && surf_desc.Format <= D3DFMT_DXT5) { w = max(w,4); h = max(h,4); } surf_desc.Size = (w * h * bpp) / 8; if (_buffer) { // Don't care about the allocated surface nodel = TRUE; buffer = _buffer; } else { // Only realloc IF real_size is less than the size we want if (allocated_size < surf_desc.Size) { if (allocated) _aligned_free(allocated); allocated = (BYTE*) _aligned_malloc(allocated_size = max(surf_desc.Size,16), 8); } buffer = allocated; nodel = FALSE; } return D3D_OK; }
21.6
151
0.66088
rbwsok
89b8c660bb355f90968b76344c6b893124347574
2,301
cpp
C++
src/omwmm/modmanager.cpp
luluco250/omwmm
ee9cd11e4876515c84ad4f2c97372ba23616ac2b
[ "MIT" ]
null
null
null
src/omwmm/modmanager.cpp
luluco250/omwmm
ee9cd11e4876515c84ad4f2c97372ba23616ac2b
[ "MIT" ]
null
null
null
src/omwmm/modmanager.cpp
luluco250/omwmm
ee9cd11e4876515c84ad4f2c97372ba23616ac2b
[ "MIT" ]
null
null
null
#include <omwmm/modmanager.hpp> #include <filesystem> #include <utility> #include <functional> #include <unordered_set> #include <string> #include <string_view> #include <omwmm/config.hpp> #include <omwmm/exceptions.hpp> #include <7zpp/7zpp.h> using Path = std::filesystem::path; using DirectoryIterator = std::filesystem::directory_iterator; template<class T> using Function = std::function<T>; template<class T> using UnorderedSet = std::unordered_set<T>; using String = std::string; using StringView = std::string_view; namespace omwmm { using namespace exceptions; ModManager::ModManager(const Config& cfg) { config(cfg); } const Config& ModManager::config() const { return _config; } void ModManager::config(const Config& cfg) { if (!cfg.data_files_path || cfg.data_files_path->empty()) throw ModManagerSetupException("Data files path is empty"); if (!cfg.downloaded_mods_path || cfg.downloaded_mods_path->empty()) throw ModManagerSetupException("Downloaded mods path is empty"); if (!cfg.extracted_mods_path || cfg.extracted_mods_path->empty()) throw ModManagerSetupException("Extracted mods path is empty"); _config = cfg; } static const UnorderedSet<StringView> download_exts{ ".7z", ".zip", ".rar" }; void ModManager::query_downloads( const Function<void(StringView)>& func ) { for (auto p : DirectoryIterator(downloaded_mods_path())) if (download_exts.find(p.path().extension().string()) != download_exts.end()) func(p.path().filename().string()); } void ModManager::extract_mod(StringView filename) { auto source = downloaded_mods_path() / filename; auto dest = extracted_mods_path() / source.filename().replace_extension(""); _extractor.extract(source, dest); } #define GET_SET(NAME, PRETTY_NAME) \ Path ModManager::NAME() const { \ return *_config.NAME; \ } \ void ModManager::NAME(const Path& path) { \ if (path.empty()) \ throw InvalidArgumentException(PRETTY_NAME " cannot be empty"); \ \ _config.NAME = path; \ } \ void ModManager::NAME(Path&& path) { \ if (path.empty()) \ throw InvalidArgumentException(PRETTY_NAME " cannot be empty"); \ \ _config.NAME = std::move(path); \ } GET_SET(data_files_path, "Data files path") GET_SET(downloaded_mods_path, "Downloaded mods path") GET_SET(extracted_mods_path, "Extracted mods path") }
26.755814
79
0.734463
luluco250
89bc5aecef0da213a33adbe7fcd3462897651c6d
10,443
cpp
C++
src/libtsduck/dtv/descriptors/tsEventGroupDescriptor.cpp
manuelmann/tsduck-test
13760d34bd6f522c2ff813a996371a7cb30e1835
[ "BSD-2-Clause" ]
null
null
null
src/libtsduck/dtv/descriptors/tsEventGroupDescriptor.cpp
manuelmann/tsduck-test
13760d34bd6f522c2ff813a996371a7cb30e1835
[ "BSD-2-Clause" ]
null
null
null
src/libtsduck/dtv/descriptors/tsEventGroupDescriptor.cpp
manuelmann/tsduck-test
13760d34bd6f522c2ff813a996371a7cb30e1835
[ "BSD-2-Clause" ]
null
null
null
//---------------------------------------------------------------------------- // // TSDuck - The MPEG Transport Stream Toolkit // Copyright (c) 2005-2020, Thierry Lelegard // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // //---------------------------------------------------------------------------- #include "tsEventGroupDescriptor.h" #include "tsDescriptor.h" #include "tsNames.h" #include "tsTablesDisplay.h" #include "tsPSIRepository.h" #include "tsDuckContext.h" #include "tsxmlElement.h" #include "tsMJD.h" TSDUCK_SOURCE; #define MY_XML_NAME u"event_group_descriptor" #define MY_CLASS ts::EventGroupDescriptor #define MY_DID ts::DID_ISDB_EVENT_GROUP #define MY_PDS ts::PDS_ISDB #define MY_STD ts::Standards::ISDB TS_REGISTER_DESCRIPTOR(MY_CLASS, ts::EDID::Private(MY_DID, MY_PDS), MY_XML_NAME, MY_CLASS::DisplayDescriptor); //---------------------------------------------------------------------------- // Constructors //---------------------------------------------------------------------------- ts::EventGroupDescriptor::EventGroupDescriptor() : AbstractDescriptor(MY_DID, MY_XML_NAME, MY_STD, 0), group_type(0), actual_events(), other_events(), private_data() { } ts::EventGroupDescriptor::EventGroupDescriptor(DuckContext& duck, const Descriptor& desc) : EventGroupDescriptor() { deserialize(duck, desc); } void ts::EventGroupDescriptor::clearContent() { group_type = 0; actual_events.clear(); other_events.clear(); private_data.clear(); } ts::EventGroupDescriptor::ActualEvent::ActualEvent() : service_id(0), event_id(0) { } ts::EventGroupDescriptor::OtherEvent::OtherEvent() : original_network_id(0), transport_stream_id(0), service_id(0), event_id(0) { } //---------------------------------------------------------------------------- // Serialization //---------------------------------------------------------------------------- void ts::EventGroupDescriptor::serialize(DuckContext& duck, Descriptor& desc) const { ByteBlockPtr bbp(serializeStart()); bbp->appendUInt8(uint8_t(group_type << 4) | uint8_t(actual_events.size() & 0x0F)); for (auto it = actual_events.begin(); it != actual_events.end(); ++it) { bbp->appendUInt16(it->service_id); bbp->appendUInt16(it->event_id); } if (group_type == 4 || group_type == 5) { for (auto it = other_events.begin(); it != other_events.end(); ++it) { bbp->appendUInt16(it->original_network_id); bbp->appendUInt16(it->transport_stream_id); bbp->appendUInt16(it->service_id); bbp->appendUInt16(it->event_id); } } else { bbp->append(private_data); } serializeEnd(desc, bbp); } //---------------------------------------------------------------------------- // Deserialization //---------------------------------------------------------------------------- void ts::EventGroupDescriptor::deserialize(DuckContext& duck, const Descriptor& desc) { const uint8_t* data = desc.payload(); size_t size = desc.payloadSize(); _is_valid = desc.isValid() && desc.tag() == tag() && size >= 1; actual_events.clear(); other_events.clear(); private_data.clear(); if (_is_valid) { group_type = (data[0] >> 4) & 0x0F; size_t count = data[0] & 0x0F; data++; size--; while (count > 0 && size >= 4) { ActualEvent ev; ev.service_id = GetUInt16(data); ev.event_id = GetUInt16(data + 2); actual_events.push_back(ev); data += 4; size -= 4; count--; } _is_valid = count == 0; if (_is_valid) { if (group_type == 4 || group_type == 5) { while (size >= 8) { OtherEvent ev; ev.original_network_id = GetUInt16(data); ev.transport_stream_id = GetUInt16(data + 2); ev.service_id = GetUInt16(data + 4); ev.event_id = GetUInt16(data + 6); other_events.push_back(ev); data += 8; size -= 8; } _is_valid = size == 0; } else { private_data.copy(data, size); } } } } //---------------------------------------------------------------------------- // Static method to display a descriptor. //---------------------------------------------------------------------------- void ts::EventGroupDescriptor::DisplayDescriptor(TablesDisplay& display, DID did, const uint8_t* data, size_t size, int indent, TID tid, PDS pds) { DuckContext& duck(display.duck()); std::ostream& strm(duck.out()); const std::string margin(indent, ' '); if (size >= 1) { const uint8_t type = (data[0] >> 4) & 0x0F; size_t count = data[0] & 0x0F; data++; size--; strm << margin << "Group type: " << NameFromSection(u"ISDBEventGroupType", type, names::DECIMAL_FIRST) << std::endl; strm << margin << "Actual events:" << (count == 0 ? " none" : "") << std::endl; while (count > 0 && size >= 4) { strm << margin << UString::Format(u"- Service id: 0x%X (%d)", {GetUInt16(data), GetUInt16(data)}) << std::endl << margin << UString::Format(u" Event id: 0x%X (%d)", {GetUInt16(data + 2), GetUInt16(data + 2)}) << std::endl; data += 4; size -= 4; count--; } if (type == 4 || type == 5) { strm << margin << "Other networks events:" << (size < 8 ? " none" : "") << std::endl; while (size >= 8) { strm << margin << UString::Format(u"- Original network id: 0x%X (%d)", {GetUInt16(data), GetUInt16(data)}) << std::endl << margin << UString::Format(u" Transport stream id: 0x%X (%d)", {GetUInt16(data + 2), GetUInt16(data + 2)}) << std::endl << margin << UString::Format(u" Service id: 0x%X (%d)", {GetUInt16(data + 4), GetUInt16(data + 4)}) << std::endl << margin << UString::Format(u" Event id: 0x%X (%d)", {GetUInt16(data + 6), GetUInt16(data + 6)}) << std::endl; data += 8; size -= 8; } display.displayExtraData(data, size, indent); } else { display.displayPrivateData(u"Private data", data, size, indent); } } } //---------------------------------------------------------------------------- // XML serialization //---------------------------------------------------------------------------- void ts::EventGroupDescriptor::buildXML(DuckContext& duck, xml::Element* root) const { root->setIntAttribute(u"group_type", group_type); for (auto it = actual_events.begin(); it != actual_events.end(); ++it) { xml::Element* e = root->addElement(u"actual"); e->setIntAttribute(u"service_id", it->service_id, true); e->setIntAttribute(u"event_id", it->event_id, true); } if (group_type == 4 || group_type == 5) { for (auto it = other_events.begin(); it != other_events.end(); ++it) { xml::Element* e = root->addElement(u"other"); e->setIntAttribute(u"original_network_id", it->original_network_id, true); e->setIntAttribute(u"transport_stream_id", it->transport_stream_id, true); e->setIntAttribute(u"service_id", it->service_id, true); e->setIntAttribute(u"event_id", it->event_id, true); } } else { root->addHexaTextChild(u"private_data", private_data, true); } } //---------------------------------------------------------------------------- // XML deserialization //---------------------------------------------------------------------------- bool ts::EventGroupDescriptor::analyzeXML(DuckContext& duck, const xml::Element* element) { xml::ElementVector xactual; xml::ElementVector xother; bool ok = element->getIntAttribute<uint8_t>(group_type, u"group_type", true, 0, 0, 15) && element->getChildren(xactual, u"actual", 0, 15) && element->getChildren(xother, u"other", 0, group_type == 4 || group_type == 5 ? 31 : 0) && element->getHexaTextChild(private_data, u"private_data", false, 0, group_type == 4 || group_type == 5 ? 0 : 254); for (auto it = xactual.begin(); ok && it != xactual.end(); ++it) { ActualEvent ev; ok = (*it)->getIntAttribute<uint16_t>(ev.service_id, u"service_id", true) && (*it)->getIntAttribute<uint16_t>(ev.event_id, u"event_id", true); actual_events.push_back(ev); } for (auto it = xother.begin(); ok && it != xother.end(); ++it) { OtherEvent ev; ok = (*it)->getIntAttribute<uint16_t>(ev.original_network_id, u"original_network_id", true) && (*it)->getIntAttribute<uint16_t>(ev.transport_stream_id, u"transport_stream_id", true) && (*it)->getIntAttribute<uint16_t>(ev.service_id, u"service_id", true) && (*it)->getIntAttribute<uint16_t>(ev.event_id, u"event_id", true); other_events.push_back(ev); } return ok; }
39.259398
145
0.551566
manuelmann
89c30d095e454b52779a31d7e31efe1f00ba13c0
3,746
cc
C++
storageServer/saveFile_2/src/Loop.cc
HenryKing96/MiniDistributedStorage
7da8b7fb72baca4a04cfde9ce27eec3bb207e056
[ "Apache-2.0" ]
null
null
null
storageServer/saveFile_2/src/Loop.cc
HenryKing96/MiniDistributedStorage
7da8b7fb72baca4a04cfde9ce27eec3bb207e056
[ "Apache-2.0" ]
null
null
null
storageServer/saveFile_2/src/Loop.cc
HenryKing96/MiniDistributedStorage
7da8b7fb72baca4a04cfde9ce27eec3bb207e056
[ "Apache-2.0" ]
null
null
null
#include "Loop.h" #include "EpollEvent.h" #include "EPoller.h" #include <boost/bind.hpp> #include <iostream> #include <assert.h> #include <signal.h> #include <sys/eventfd.h> using namespace Reactor; Loop* t_loopInThisThread = 0; const int kPollTimeMs = 10000; static int createEventfd() { return ::eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); } Loop::Loop() : looping_(false), quit_(false), callFunctors_(false), threadId_(std::this_thread::get_id()), wakeupFd_(createEventfd()), epoller_(new EPoller(this)), wakeupEvent_(new EpollEvent(this, wakeupFd_)) { printf("thread id: %lu created success\n", threadId_); t_loopInThisThread = this; wakeupEvent_->setReadCallback(boost::bind(&Loop::handleRead, this)); wakeupEvent_->enableReading(); } Loop::~Loop() { ::close(wakeupFd_); t_loopInThisThread = NULL; } void Loop::loop() { looping_ = true; quit_ = false; while (!quit_) { activeEvents_.clear(); epoller_->epoll(kPollTimeMs, &activeEvents_); for (EventlList::iterator it = activeEvents_.begin(); it != activeEvents_.end(); ++it) { (*it)->handleEvent(); } doFunctors(); } looping_ = false; } void Loop::quit() { quit_ = true; if (!isInLoopThread()) { wakeup(); } } void Loop::runInLoop(const Functor& cb) { if (isInLoopThread()) { cb(); } else { queueInLoop(cb); } } void Loop::queueInLoop(const Functor& cb) { { std::lock_guard<std::mutex> guard(mutex_); Functors_.push_back(cb); } if (!isInLoopThread() || callFunctors_) { wakeup(); } } void Loop::updateEvent(EpollEvent* epollEvent) { epoller_->updateEvent(epollEvent); } void Loop::removeEvent(EpollEvent* epollEvent) { epoller_->removeEvent(epollEvent); } void Loop::wakeup() { uint64_t one = 1; ::write(wakeupFd_, &one, sizeof one); } void Loop::handleRead() { uint64_t one = 1; ::read(wakeupFd_, &one, sizeof one); } void Loop::doFunctors() { std::vector<Functor> functors; callFunctors_ = true; { std::lock_guard<std::mutex> guard(mutex_); functors.swap(Functors_); } for (size_t i = 0; i < functors.size(); ++i) { functors[i](); } callFunctors_ = false; }
27.955224
1,532
0.381474
HenryKing96
89c37b76a49283607c174aa28f43ff946d88690b
5,710
cpp
C++
test_gcc/test.cpp
KnicKnic/native-powershell
add37eff76c47fc0e782c22a8460bff3f3327dca
[ "Apache-2.0" ]
21
2019-06-27T06:29:11.000Z
2021-12-29T05:08:37.000Z
test_gcc/test.cpp
KnicKnic/native-powershell
add37eff76c47fc0e782c22a8460bff3f3327dca
[ "Apache-2.0" ]
5
2019-08-17T01:34:11.000Z
2019-11-06T21:52:15.000Z
test_gcc/test.cpp
KnicKnic/native-powershell
add37eff76c47fc0e782c22a8460bff3f3327dca
[ "Apache-2.0" ]
1
2021-03-13T20:58:48.000Z
2021-03-13T20:58:48.000Z
// test.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> #include <algorithm> #include <vector> #include "host.h" #include "utils/macros.hpp" #include "utils/zero_resetable.hpp" #include "utils/cpp_wrappers.hpp" using namespace std; using namespace native_powershell; struct SomeContext { std::wstring LoggerContext; std::wstring CommandContext; NativePowerShell_RunspaceHandle runspace; std::optional<NativePowerShell_PowerShellHandle> powershell; }; extern "C" { void Logger(void* context, const wchar_t* s) { auto realContext = (SomeContext*)context; std::wcout << realContext->LoggerContext << std::wstring(s); } void Command(void* context, const wchar_t* s, NativePowerShell_PowerShellObject* input, unsigned long long inputCount, NativePowerShell_JsonReturnValues* returnValues) { input; inputCount; auto realContext = (SomeContext*)context; std::wcout << realContext->CommandContext << std::wstring(s) << L'\n'; for (size_t i = 0; i < inputCount; ++i) { // test nested creation RunScript(realContext->runspace, realContext->powershell, L"[int]11", true); auto& v = input[i]; std::wcout << L"In data processing got " << GetToString(v) << L" of type " << GetType(v) << L'\n'; } // allocate return object holders returnValues->count = 1 + inputCount; returnValues->objects = (NativePowerShell_GenericPowerShellObject*)NativePowerShell_DefaultAlloc(sizeof(*(returnValues->objects)) * returnValues->count); if (returnValues->objects == nullptr) { throw "memory allocation failed for return values in command"; } // allocate and fill out each object auto& object = returnValues->objects[0]; object.releaseObject = char(1); object.type = NativePowerShell_PowerShellObjectTypeString; object.instance.string = MallocCopy(s); for (size_t i = 0; i < inputCount; ++i) { auto& v = returnValues->objects[1 + i]; v.releaseObject = char(0); v.type = NativePowerShell_PowerShellObjectHandle; v.instance.psObject = input[i]; } return; } } int main() { SomeContext context{ L"MyLoggerContext: ", L"MyCommandContext: ", NativePowerShell_InvalidHandleValue, std::nullopt }; NativePowerShell_LogString_Holder logHolder = { 0 }; logHolder.Log = Logger; auto runspace = NativePowerShell_CreateRunspace(&context, Command, &logHolder); context.runspace = runspace; RunScript(runspace, std::nullopt, L"[int12", true); auto powershell = NativePowerShell_CreatePowerShell(runspace); //AddScriptSpecifyScope(powershell, L"c:\\code\\psh_host\\script.ps1", 1); //AddCommand(powershell, L"c:\\code\\go-net\\t3.ps1"); //AddScriptSpecifyScope(powershell, L"write-host $pwd", 0); NativePowerShell_AddScriptSpecifyScope(powershell, L"0;1;$null;dir c:\\", 1); //AddCommandSpecifyScope(powershell, L"..\\..\\go-net\\t3.ps1", 0); //AddScriptSpecifyScope(powershell, L"$a = \"asdf\"", 0); //AddArgument(powershell, L"c:\\ddddddd"); { Invoker invoke(powershell); wcout << L"examining returned objects\n"; for (unsigned int i = 0; i < invoke.count; ++i) { wcout << L"Got type: " << GetType(invoke[i]) << L"with value: " << GetToString(invoke[i]) << L'\n'; } auto powershell2 = NativePowerShell_CreatePowerShell(runspace); // note below will write to output, not return objects NativePowerShell_AddScriptSpecifyScope(powershell2, L"write-host 'about to enumerate directory';" L"write-host $args; $len = $args.length; write-host \"arg count $len\";" L"$args | ft | out-string | write-host;" L"@(1,'asdf',$null,$false) | send-hostcommand -message 'I sent the host a command' | write-host;" L"send-hostcommand -message 'I sent the host a command' | write-host", 0); NativePowerShell_AddArgument(powershell2, L"String to start"); NativePowerShell_AddPSObjectArguments(powershell2, invoke.objects, invoke.count); NativePowerShell_AddArgument(powershell2, L"String to end"); context.powershell = powershell2; Invoker invoke2(powershell2); context.powershell = std::nullopt; } NativePowerShell_DeletePowershell(powershell); powershell = NativePowerShell_CreatePowerShell(runspace); //AddScriptSpecifyScope(powershell, L"c:\\code\\psh_host\\script.ps1", 1); NativePowerShell_AddCommandSpecifyScope(powershell, L"..\\..\\go-net\\t3.ps1", 0); //AddScriptSpecifyScope(powershell, L"write-host $a", 0); //AddCommand(powershell, L"c:\\code\\go-net\\t3.ps1"); //AddArgument(powershell, L"c:\\ddddddd"); { Invoker invoke(powershell); } NativePowerShell_DeletePowershell(powershell); NativePowerShell_DeleteRunspace(runspace); std::cout << "Hello World!\n"; } // Run program: Ctrl + F5 or Debug > Start Without Debugging menu // Debug program: F5 or Debug > Start Debugging menu // Tips for Getting Started: // 1. Use the Solution Explorer window to add/manage files // 2. Use the Team Explorer window to connect to source control // 3. Use the Output window to see build output and other messages // 4. Use the Error List window to view errors // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
41.376812
171
0.670228
KnicKnic
89c562a87b5acce423f54442a803bd258039f8f2
1,036
hpp
C++
codegen.hpp
kwQt/dummyscope
160010342e87fb1578f707b97812af9d34814d76
[ "MIT" ]
1
2020-07-17T05:17:07.000Z
2020-07-17T05:17:07.000Z
codegen.hpp
kwQt/dummyscope
160010342e87fb1578f707b97812af9d34814d76
[ "MIT" ]
null
null
null
codegen.hpp
kwQt/dummyscope
160010342e87fb1578f707b97812af9d34814d76
[ "MIT" ]
null
null
null
#pragma once #include <llvm/IR/IRBuilder.h> #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Module.h> #include <llvm/IR/Value.h> #include <memory> #include "ast.hpp" class ExprAST; class CodeGen { private: std::unique_ptr<llvm::LLVMContext> context; std::unique_ptr<llvm::Module> module; std::unique_ptr<llvm::IRBuilder<>> builder; std::map<std::string, llvm::Value*> named_values; public: CodeGen(); ~CodeGen(){}; bool generate(TranslationUnitAST* ast); llvm::Module* getModule() { return module.get(); } private: llvm::Function* generateFunction(FunctionAST* ast); llvm::Value* generateNumber(NumberAST* ast); llvm::Function* generateProtoType(PrototypeAST* ast); llvm::Value* generateExpr(ExprAST* ast); llvm::Value* generateBinaryExpr(BinaryExprAST* ast); llvm::Value* generateCallExpr(CallExprAST* ast); llvm::Value* generateVariable(VariableAST* ast); void setNamedValue(const std::string& name, llvm::Value* value); void clearNamedValue(); void addBuiltinFunction(); };
21.142857
66
0.718147
kwQt
89c668a24249d00c648bf3d9099505d397572bf2
484
cpp
C++
Sesame/src/Sesame/Core/Log.cpp
yook00627/Sesame-Engine
1adf6227afcfc582697203cb9ccf0e2d56c9d5eb
[ "MIT" ]
3
2020-06-06T23:07:55.000Z
2020-07-31T17:13:29.000Z
Sesame/src/Sesame/Core/Log.cpp
yook00627/Sesame-Engine
1adf6227afcfc582697203cb9ccf0e2d56c9d5eb
[ "MIT" ]
1
2020-08-09T17:43:03.000Z
2021-03-25T02:22:23.000Z
Sesame/src/Sesame/Core/Log.cpp
yook00627/Sesame-Engine
1adf6227afcfc582697203cb9ccf0e2d56c9d5eb
[ "MIT" ]
null
null
null
#include "ssmpch.h" #include "Log.h" namespace Sesame { std::shared_ptr<spdlog::logger> Log::s_CoreLogger; std::shared_ptr<spdlog::logger> Log::s_ClientLogger; void Log::Init() { spdlog::set_pattern("%t-%^[%T] %n: %v%$"); s_CoreLogger = spdlog::stdout_color_mt("SESAME"); s_CoreLogger->set_level(spdlog::level::trace); s_ClientLogger = spdlog::stdout_color_mt("APP"); s_ClientLogger->set_level(spdlog::level::trace); } }
26.888889
57
0.634298
yook00627
89c7c9bdd0b58f4151ed3099002373f24e5497f8
4,337
cpp
C++
apps/Stencil2D_InPlace_ASYN_Tps/Stencil2DKernel.cpp
randres2011/DARTS
d3a0d28926b15796661783f91451dcd313905582
[ "BSD-2-Clause" ]
3
2020-02-21T01:34:36.000Z
2021-11-13T06:24:40.000Z
apps/Stencil2D_InPlace_ASYN_Tps/Stencil2DKernel.cpp
randres2011/DARTS
d3a0d28926b15796661783f91451dcd313905582
[ "BSD-2-Clause" ]
1
2021-01-25T06:57:45.000Z
2022-02-02T11:44:04.000Z
apps/Stencil2D_InPlace_ASYN_Tps/Stencil2DKernel.cpp
randres2011/DARTS
d3a0d28926b15796661783f91451dcd313905582
[ "BSD-2-Clause" ]
4
2016-12-12T05:46:58.000Z
2022-01-01T16:08:56.000Z
#include <stdint.h> #include <stdlib.h> #include "Stencil2DKernel.h" /** * Naive 4pt stencil for 2D array */ void stencil2d_seq(double *dst,double *src,const uint64_t n_rows,const uint64_t n_cols,uint64_t n_tsteps){ typedef double (*Array2D)[n_cols]; Array2D DST = (Array2D) dst, SRC = (Array2D) src; for (size_t ts = 0; ts < n_tsteps; ++ts) { for (size_t i = 1; i < n_rows-1; ++i) { for (size_t j = 1; j < n_cols-1; ++j) { DST[i][j] = (SRC[i-1][j] + SRC[i+1][j] + SRC[i][j-1] + SRC[i][j+1]) / 4; } } SWAP_PTR(&DST,&SRC); } } /* //compute inner blocks for no sub cut void computeInner_stencil2d(uint64_t BlockPosition,double *Initial,double *share,uint64_t BlockM,const uint64_t InitialM, const uint64_t InitialN){ double *upper = new double[InitialN];//upper is used to store current line which can be used for next line computing double *lower = new double[InitialN]; double *current=new double[InitialN]; if(BlockM > InitialM){ std::cout << "Inner error \n"<<std::endl; return; } memcpy(current,share,sizeof(double)*InitialN); memcpy(lower,Initial+BlockPosition-1,sizeof(double)*InitialN); for(uint64_t i=0;i<BlockM;++i){ memcpy(upper,current,sizeof(double)*InitialN); memcpy(current,lower,sizeof(double)*InitialN); //memcpy(lower,Initial+BlockPosition+i*InitialN-1,sizeof(double)*(BlockNPlus2)); double *LOWER = (i==(BlockM-1))? (share+InitialN):(Initial+BlockPosition+(i+1)*InitialN-1); memcpy(lower,LOWER,sizeof(double)*(InitialN)); for(uint64_t j=0;j<InitialN-2;++j){ Initial[BlockPosition+i*InitialN+j]=(upper[j+1]+current[j]+current[j+2]+lower[j+1])/4; } } delete [] upper; delete [] lower; delete [] current; return; } */ //compute inner blocks void computeInner_stencil2d(uint64_t BlockPosition,double *Initial,double *share,uint64_t BlockM,uint64_t BlockN,const uint64_t InitialM, const uint64_t InitialN){ uint64_t BlockNPlus2=BlockN+2; double *upper = new double[BlockNPlus2];//upper is used to store current line which can be used for next line computing double *lower = new double[BlockNPlus2]; double *current=new double[BlockNPlus2]; if(BlockM > InitialM){ std::cout << "Inner error \n"<<std::endl; return; } memcpy(current,share,sizeof(double)*(BlockNPlus2)); memcpy(lower,Initial+BlockPosition-1,sizeof(double)*(BlockNPlus2)); for(uint64_t i=0;i<BlockM;++i){ memcpy(upper,current,sizeof(double)*(BlockNPlus2)); memcpy(current,lower,sizeof(double)*(BlockNPlus2)); //memcpy(lower,Initial+BlockPosition+i*InitialN-1,sizeof(double)*(BlockNPlus2)); double *LOWER = (i==(BlockM-1))? (share+BlockNPlus2):(Initial+BlockPosition+(i+1)*InitialN-1); memcpy(lower,LOWER,sizeof(double)*(BlockNPlus2)); for(uint64_t j=0;j<BlockN;++j){ Initial[BlockPosition+i*InitialN+j]=(upper[j+1]+current[j]+current[j+2]+lower[j+1])/4; } } delete [] upper; delete [] lower; delete [] current; return; } /* // when we compute inner matrix, we first should copy the block to the inner of codelet void copyMatrix_stencil2d(uint64_t BlockPosition, uint64_t BlockM, uint64_t BlockN,double *InitialMatrix,double *CopyMatrix,const uint64_t InitialM, const uint64_t InitialN){ uint64_t i,j,k,l; uint64_t i_begin = BlockPosition/InitialN; uint64_t j_begin = BlockPosition%InitialN; uint64_t i_end = i_begin + BlockM-1; uint64_t j_end = j_begin + BlockN-1; if(i_end > InitialM){ std::cout << "Inner error \n"<<std::endl; return; } for(i=i_begin,k=0;i<=i_end;++i,++k) for(j=j_begin,l=0;j<=j_end;++j,++l){ CopyMatrix[k*BlockN+l]=InitialMatrix[i*InitialN+j]; } return; } */ /* //copy RowDecomposition block share lines (up+lower lines) void copyShareLines_stencil2d(uint64_t BlockPosition,double *InitialMatrix,double *CopyMatrix,uint64_t StepM,const uint64_t InitialM, const uint64_t InitialN){ uint64_t i = BlockPosition/InitialN; if((i+StepM) > InitialM){ std::cout << "Inner error \n"<<std::endl; return; } for(uint64_t j=0;j<InitialN;++j){ CopyMatrix[j]=InitialMatrix[i*InitialN+j]; CopyMatrix[InitialN+j]=InitialMatrix[(i+StepM+1)*InitialN+j]; } return; } */ void copyLine_stencil2d(uint64_t BlockPosition,double *Initial,double *Copy,const uint64_t InitialN){ uint64_t i = BlockPosition/InitialN; memcpy(Copy,Initial+i*InitialN,sizeof(double)*InitialN); return; }
31.889706
174
0.709477
randres2011
89c9c38e01658b9f9f35f37518c62387db41fdf2
11,634
cpp
C++
src/QtComponents/Traditions/nComboBox.cpp
Vladimir-Lin/QtComponents
e7f0a6abcf0504cc9144dcf59f3f14a52d08092c
[ "MIT" ]
null
null
null
src/QtComponents/Traditions/nComboBox.cpp
Vladimir-Lin/QtComponents
e7f0a6abcf0504cc9144dcf59f3f14a52d08092c
[ "MIT" ]
null
null
null
src/QtComponents/Traditions/nComboBox.cpp
Vladimir-Lin/QtComponents
e7f0a6abcf0504cc9144dcf59f3f14a52d08092c
[ "MIT" ]
null
null
null
#include <qtcomponents.h> N::ComboBox:: ComboBox ( QWidget * parent , Plan * p ) : QComboBox ( parent ) , VirtualGui ( this , p ) , Thread ( 0 , false ) { WidgetClass ; Configure ( ) ; } N::ComboBox::~ComboBox(void) { } SUID N::ComboBox::toUuid(void) { return toUuid ( currentIndex ( ) ) ; } SUID N::ComboBox::toUuid(int index) { return itemData ( index ) . toULongLong ( ) ; } void N::ComboBox::Configure(void) { setAttribute ( Qt::WA_InputMethodEnabled ) ; setAcceptDrops ( true ) ; setDropFlag ( DropFont , true ) ; setDropFlag ( DropPen , true ) ; setDropFlag ( DropBrush , true ) ; addConnector ( "AssignName" , this , SIGNAL(assignNames(NAMEs&)) , this , SLOT (appendNames(NAMEs&)) ) ; addConnector ( "Commando" , Commando , SIGNAL ( timeout ( ) ) , this , SLOT ( DropCommands ( ) ) ) ; onlyConnector ( "AssignName" ) ; onlyConnector ( "Commando" ) ; //////////////////////////////////////////////// if ( NotNull ( plan ) ) { Data . Controller = & ( plan->canContinue ) ; } ; } void N::ComboBox::paintEvent(QPaintEvent * event) { nIsolatePainter ( QComboBox ) ; } void N::ComboBox::focusInEvent(QFocusEvent * event) { if (!focusIn (event)) QComboBox::focusInEvent (event) ; } void N::ComboBox::focusOutEvent(QFocusEvent * event) { if (!focusOut(event)) QComboBox::focusOutEvent(event) ; } void N::ComboBox::resizeEvent(QResizeEvent * event) { QComboBox :: resizeEvent ( event ) ; } void N::ComboBox::dragEnterEvent(QDragEnterEvent * event) { if (dragEnter(event)) event->acceptProposedAction() ; else { if (PassDragDrop) QComboBox::dragEnterEvent(event) ; else event->ignore() ; } ; } void N::ComboBox::dragLeaveEvent(QDragLeaveEvent * event) { if (removeDrop()) event->accept() ; else { if (PassDragDrop) QComboBox::dragLeaveEvent(event) ; else event->ignore() ; } ; } void N::ComboBox::dragMoveEvent(QDragMoveEvent * event) { if (dragMove(event)) event->acceptProposedAction() ; else { if (PassDragDrop) QComboBox::dragMoveEvent(event) ; else event->ignore() ; } ; } void N::ComboBox::dropEvent(QDropEvent * event) { if (drop(event)) event->acceptProposedAction() ; else { if (PassDragDrop) QComboBox::dropEvent(event) ; else event->ignore() ; } ; } bool N::ComboBox::acceptDrop(QWidget * source,const QMimeData * mime) { Q_UNUSED ( source ) ; Q_UNUSED ( mime ) ; return false ; } bool N::ComboBox::dropNew(QWidget * source,const QMimeData * mime,QPoint pos) { Q_UNUSED ( source ) ; Q_UNUSED ( mime ) ; Q_UNUSED ( pos ) ; return true ; } bool N::ComboBox::dropMoving(QWidget * source,const QMimeData * mime,QPoint pos) { Q_UNUSED ( source ) ; Q_UNUSED ( mime ) ; Q_UNUSED ( pos ) ; return true ; } bool N::ComboBox::dropAppend(QWidget * source,const QMimeData * mime,QPoint pos) { return dropItems ( source , mime , pos ) ; } bool N::ComboBox::dropFont(QWidget * source,QPointF pos,const SUID font) { Q_UNUSED ( source ) ; Q_UNUSED ( pos ) ; nKickOut ( IsNull(plan) , false ) ; Font f ; GraphicsManager GM ( plan ) ; EnterSQL ( SC , plan->sql ) ; f = GM.GetFont ( SC , font ) ; LeaveSQL ( SC , plan->sql ) ; assignFont ( f ) ; return true ; } bool N::ComboBox::dropPen(QWidget * source,QPointF pos,const SUID pen) { Q_UNUSED ( source ) ; Q_UNUSED ( pos ) ; nKickOut ( IsNull(plan) , false ) ; Pen p ; GraphicsManager GM ( plan ) ; EnterSQL ( SC , plan->sql ) ; p = GM.GetPen ( SC , pen ) ; LeaveSQL ( SC , plan->sql ) ; assignPen ( p ) ; return true ; } bool N::ComboBox::dropBrush(QWidget * source,QPointF pos,const SUID brush) { Q_UNUSED ( source ) ; Q_UNUSED ( pos ) ; nKickOut ( IsNull(plan) , false ) ; Brush b ; GraphicsManager GM ( plan ) ; EnterSQL ( SC , plan->sql ) ; b = GM.GetBrush ( SC , brush ) ; LeaveSQL ( SC , plan->sql ) ; assignBrush ( b ) ; return true ; } void N::ComboBox::DropCommands(void) { LaunchCommands ( ) ; } void N::ComboBox::assignFont(Font & f) { QComboBox::setFont ( f ) ; } void N::ComboBox::assignPen(Pen & p) { Q_UNUSED ( p ) ; } void N::ComboBox::assignBrush(Brush & b) { QBrush B = b ; QPalette P = palette ( ) ; P . setBrush ( QPalette::Base , B ) ; setPalette ( P ) ; } void N::ComboBox::appendNames(NAMEs & names) { N :: AddItems ( ME , names ) ; } void N::ComboBox::appendNames(UUIDs & uuids,NAMEs & names) { SUID u ; foreach ( u , uuids ) { addItem ( names[u] , u ) ; } ; } void N::ComboBox::addItems(SqlConnection & SC,UUIDs & Uuids) { SUID uuid ; foreach (uuid,Uuids) { QString name = SC.getName(PlanTable(Names),"uuid",vLanguageId,uuid) ; addItem ( name , uuid ) ; } ; } void N::ComboBox::addItems(UUIDs Uuids) { SqlConnection SC(plan->sql) ; if (SC.open("ComboBox","addItems")) { addItems ( SC , Uuids ) ; SC.close ( ) ; } ; SC.remove() ; } void N::ComboBox::addItems(QString table,enum Qt::SortOrder sorting) { SqlConnection SC(plan->sql) ; if (SC.open("ComboBox","addItems")) { UUIDs Uuids = SC.Uuids ( table , "uuid" , SC.OrderBy("id",sorting) ) ; addItems ( SC , Uuids ) ; SC.close ( ) ; } ; SC.remove() ; } void N::ComboBox::addGroups ( SUID group , int t1 , int t2 , int relation , enum Qt::SortOrder sorting ) { GroupItems GI ( plan ) ; SqlConnection SC ( plan -> sql ) ; if (SC.open("ComboBox","addGroups")) { UUIDs U ; U = GI . Subordination ( SC , group , t1 , t2 , relation , SC.OrderBy("position",sorting) ) ; addItems ( SC , U ) ; SC.close ( ) ; } ; SC.remove() ; } void N::ComboBox::addDivision(int type,enum Qt::SortOrder sorting) { GroupItems GI ( plan ) ; SqlConnection SC ( plan -> sql ) ; if (SC.open("ComboBox","addDivision")) { UUIDs U ; U = GI . Groups ( SC , (Types::ObjectTypes)type , SC.OrderBy("id",sorting) ) ; addItems ( SC , U ) ; SC.close ( ) ; } ; SC.remove() ; } void N::ComboBox::pendItems(UUIDs U) { VarArgs V ; V << U.count() ; toVariants ( U , V ) ; start ( 10001 , V ) ; } void N::ComboBox::pendItems(QString table,enum Qt::SortOrder sorting) { VarArgs V ; V << table ; V << (int)sorting ; start ( 10002 , V ) ; } void N::ComboBox::pendGroups ( SUID group , int t1 , int t2 , int relation , enum Qt::SortOrder sorting ) { VarArgs V ; V << group ; V << t1 ; V << t2 ; V << relation ; V << (int)sorting ; start ( 10003 , V ) ; } void N::ComboBox::pendDivision(int type,enum Qt::SortOrder sorting) { VarArgs V ; V << type ; V << (int)sorting ; start ( 10004 , V ) ; } void N::ComboBox::run(int Type,ThreadData * data) { UUIDs U ; VarArgs V = data->Arguments ; int t ; switch ( Type ) { case 10001 : startLoading ( ) ; t = V [ 0 ] . toInt ( ) ; for (int i=1;i<=t;i++) { U << V [ i ] . toULongLong ( ) ; } ; addItems ( U ) ; stopLoading ( ) ; break ; case 10002 : startLoading ( ) ; t = V [ 1 ] .toInt() ; addItems ( V [ 0 ] .toString() , (enum Qt::SortOrder)t ) ; stopLoading ( ) ; break ; case 10003 : startLoading ( ) ; t = V [ 4 ] .toInt() ; addGroups ( V [ 0 ] . toULongLong ( ) , V [ 1 ] . toInt ( ) , V [ 2 ] . toInt ( ) , V [ 3 ] . toInt ( ) , (enum Qt::SortOrder)t ) ; stopLoading ( ) ; break ; case 10004 : startLoading ( ) ; t = V [ 1 ] .toInt() ; addDivision ( V[0].toInt() , (enum Qt::SortOrder)t ) ; stopLoading ( ) ; break ; } ; }
32.406685
80
0.381382
Vladimir-Lin
89ce426f74a24b73142fd46265afa8a66c571523
697
cpp
C++
4 course/parallel_programming/lab12/lab12_4/main.cpp
SgAkErRu/labs
9cf71e131513beb3c54ad3599f2a1e085bff6947
[ "BSD-3-Clause" ]
null
null
null
4 course/parallel_programming/lab12/lab12_4/main.cpp
SgAkErRu/labs
9cf71e131513beb3c54ad3599f2a1e085bff6947
[ "BSD-3-Clause" ]
null
null
null
4 course/parallel_programming/lab12/lab12_4/main.cpp
SgAkErRu/labs
9cf71e131513beb3c54ad3599f2a1e085bff6947
[ "BSD-3-Clause" ]
null
null
null
// Программа с пользовательской обработкой сигнала SIGINT. #include <signal.h> #include <iostream> using namespace std; // Функция my_handler - пользовательский обработчик сигнала. void my_handler(int nsig) { if (nsig == SIGINT) { cout << "Receive signal " << nsig << ", CTRL-C pressed" << endl; } else if (nsig == SIGQUIT) { cout << "Receive signal " << nsig << ", CTRL+4 pressed" << endl; } } int main() { // Выставляем реакцию процесса на сигнал SIGINT. signal(SIGINT, my_handler); signal(SIGQUIT, my_handler); // Начиная с этого места, процесс будет печатать сообщение о возникновении сигнала SIGINT. while(1); return 0; }
21.78125
94
0.64132
SgAkErRu
89d190c4b043c886e75f81bca3cfbd3773c2488b
3,867
cpp
C++
posix/subsystem/src/inotify.cpp
avdgrinten/managarm
4c4478cbde21675ca31e65566f10e1846b268bd5
[ "MIT" ]
13
2017-02-13T23:29:44.000Z
2021-09-30T05:41:21.000Z
posix/subsystem/src/inotify.cpp
avdgrinten/managarm
4c4478cbde21675ca31e65566f10e1846b268bd5
[ "MIT" ]
12
2016-12-03T13:06:13.000Z
2018-05-04T15:49:17.000Z
posix/subsystem/src/inotify.cpp
avdgrinten/managarm
4c4478cbde21675ca31e65566f10e1846b268bd5
[ "MIT" ]
1
2021-12-01T19:01:53.000Z
2021-12-01T19:01:53.000Z
#include <string.h> #include <sys/epoll.h> #include <sys/inotify.h> #include <iostream> #include <async/doorbell.hpp> #include <helix/ipc.hpp> #include "fs.hpp" #include "inotify.hpp" #include "process.hpp" #include "vfs.hpp" namespace inotify { namespace { struct OpenFile : File { public: struct Packet { int descriptor; uint32_t events; std::string name; uint32_t cookie; }; struct Watch final : FsObserver { Watch(OpenFile *file_, int descriptor, uint32_t mask) : file{file_}, descriptor{descriptor}, mask{mask} { } void observeNotification(uint32_t events, const std::string &name, uint32_t cookie) override { uint32_t inotifyEvents = 0; if(events & FsObserver::deleteEvent) inotifyEvents |= IN_DELETE; if(!(inotifyEvents & mask)) return; file->_queue.push_back(Packet{descriptor, inotifyEvents & mask, name, cookie}); file->_inSeq = ++file->_currentSeq; file->_statusBell.ring(); } OpenFile *file; int descriptor; uint32_t mask; }; static void serve(smarter::shared_ptr<OpenFile> file) { helix::UniqueLane lane; std::tie(lane, file->_passthrough) = helix::createStream(); async::detach(protocols::fs::servePassthrough(std::move(lane), smarter::shared_ptr<File>{file}, &File::fileOperations)); } OpenFile() : File{StructName::get("inotify")} { } ~OpenFile() { // TODO: Properly keep track of watches. std::cout << "\e[31m" "posix: Destruction of inotify leaks watches" "\e[39m" << std::endl; } expected<size_t> readSome(Process *, void *data, size_t maxLength) override { // TODO: As an optimization, we could return multiple events at the same time. Packet packet = std::move(_queue.front()); _queue.pop_front(); if(maxLength < sizeof(inotify_event) + packet.name.size() + 1) co_return Error::illegalArguments; inotify_event e; memset(&e, 0, sizeof(inotify_event)); e.wd = packet.descriptor; e.mask = packet.events; e.cookie = packet.cookie; e.len = packet.name.size(); memcpy(data, &e, sizeof(inotify_event)); memcpy(reinterpret_cast<char *>(data) + sizeof(inotify_event), packet.name.c_str(), packet.name.size() + 1); co_return sizeof(inotify_event) + packet.name.size() + 1; } expected<PollResult> poll(Process *, uint64_t sequence, async::cancellation_token cancellation) override { // TODO: Return Error::fileClosed as appropriate. assert(sequence <= _currentSeq); while(sequence == _currentSeq && !cancellation.is_cancellation_requested()) co_await _statusBell.async_wait(cancellation); int edges = 0; if(_inSeq > sequence) edges |= EPOLLIN; int events = 0; if(!_queue.empty()) events |= EPOLLIN; co_return PollResult(_currentSeq, edges, events); } helix::BorrowedDescriptor getPassthroughLane() override { return _passthrough; } int addWatch(std::shared_ptr<FsNode> node, uint32_t mask) { // TODO: Coalesce watch descriptors for the same inode. if(mask & ~(IN_DELETE)) std::cout << "posix: inotify mask " << mask << " is partially ignored" << std::endl; auto descriptor = _nextDescriptor++; auto watch = std::make_shared<Watch>(this, descriptor, mask); node->addObserver(watch); return descriptor; } private: helix::UniqueLane _passthrough; std::deque<Packet> _queue; // TODO: Use a proper ID allocator to allocate watch descriptor IDs. int _nextDescriptor = 1; async::doorbell _statusBell; uint64_t _currentSeq = 1; uint64_t _inSeq = 0; }; } // anonymous namespace smarter::shared_ptr<File, FileHandle> createFile() { auto file = smarter::make_shared<OpenFile>(); file->setupWeakFile(file); OpenFile::serve(file); return File::constructHandle(std::move(file)); } int addWatch(File *base, std::shared_ptr<FsNode> node, uint32_t mask) { auto file = static_cast<OpenFile *>(base); return file->addWatch(std::move(node), mask); } } // namespace inotify
27.041958
107
0.703905
avdgrinten
89d71df45db0d567d681e5286bf650ef2dc12542
2,078
cpp
C++
Settings.cpp
mariosbikos/Augmented_Reality_Chess_Game_RGB-D
aa22b722a9f7b6f94891c6015166e39d1570c27c
[ "MIT" ]
6
2016-05-29T01:10:33.000Z
2019-12-04T13:34:05.000Z
Settings.cpp
mariosbikos/Augmented_Reality_Chess_Game_RGB-D
aa22b722a9f7b6f94891c6015166e39d1570c27c
[ "MIT" ]
null
null
null
Settings.cpp
mariosbikos/Augmented_Reality_Chess_Game_RGB-D
aa22b722a9f7b6f94891c6015166e39d1570c27c
[ "MIT" ]
5
2015-11-22T14:36:29.000Z
2021-03-31T06:52:21.000Z
#include "Settings.h" void SetCameraParameters(std::string TheIntrinsicFile) { TheDistCameraParameters.readFromXMLFile(TheIntrinsicFile); TheDistCameraParameters.resize( cv::Size(constants::COLOR_WIDTH,constants::COLOR_HEIGHT) ); TheCameraParameters=TheDistCameraParameters; //The cv::Mat Distortion of TheCameraParameters become all-0 TheCameraParameters.Distorsion.setTo( cv::Scalar::all(0) ); } void SetDictionary(aruco::Dictionary &D) { if (!D.fromFile(TheDictionaryFile)) { cerr<<"Could not open dictionary file"<<endl; exit(1); } } void SetBoardDetectorParameters(BoardConfiguration& TheBoardConfig, CameraParameters& TheCameraParameters,float TheMarkerSize,Dictionary& D) { //Set the properties of aruco-BoardDetector TheBoardDetector.setYPerperdicular(false); TheBoardDetector.setParams(TheBoardConfig,TheCameraParameters,TheMarkerSize); //Set the parameters of the INTERNAL Marker Detector //Threhold parameters //1)Size of a pixel neighborhood that is used to calculate a threshold value for the pixel: 3, 5, 7, and so on. //2)The constant subtracted from the mean or weighted mean TheBoardDetector.getMarkerDetector().setThresholdParams( constants::THRESHOLD_PARAMETER_1,constants::THRESHOLD_PARAMETER_2); // for blue-green markers, the window size has to be larger TheBoardDetector.getMarkerDetector().setMakerDetectorFunction(aruco::HighlyReliableMarkers::detect); TheBoardDetector.getMarkerDetector().setCornerRefinementMethod(aruco::MarkerDetector::LINES); TheBoardDetector.getMarkerDetector().setWarpSize( (D[0].n() + 2) * 8 ); TheBoardDetector.getMarkerDetector().setMinMaxSize(0.005, 0.5); } void SetOffsetValuesBasedOnMarkerSize() { //Set offset for rendering in the lower left corner of chessboard(center of marker 0,0) //3.5 is 3 cells and a half to go to (0,0) marker of chessboard Offset_X_M=(-3.5 * TheMarkerSize - 3.5 * constants::SPACE_BETWEEN_CELLS); Offset_Y_M=(-3.5 * TheMarkerSize - 3.5 * constants::SPACE_BETWEEN_CELLS); Offset_Pieces_M= TheMarkerSize + constants::SPACE_BETWEEN_CELLS; }
42.408163
185
0.786814
mariosbikos
89d8347c92b8a2e321d3484e482702ff32661d41
1,091
ipp
C++
include/External/stlib/packages/numerical/random/gamma/GammaGeneratorMarsagliaTsang.ipp
bxl295/m4extreme
2a4a20ebb5b4e971698f7c981de140d31a5e550c
[ "BSD-3-Clause" ]
null
null
null
include/External/stlib/packages/numerical/random/gamma/GammaGeneratorMarsagliaTsang.ipp
bxl295/m4extreme
2a4a20ebb5b4e971698f7c981de140d31a5e550c
[ "BSD-3-Clause" ]
null
null
null
include/External/stlib/packages/numerical/random/gamma/GammaGeneratorMarsagliaTsang.ipp
bxl295/m4extreme
2a4a20ebb5b4e971698f7c981de140d31a5e550c
[ "BSD-3-Clause" ]
null
null
null
// -*- C++ -*- #if !defined(__numerical_random_GammaGeneratorMarsagliaTsang_ipp__) #error This file is an implementation detail of GammaGeneratorMarsagliaTsang. #endif namespace numerical { template < typename T, class Uniform, template<class> class Normal > inline typename GammaGeneratorMarsagliaTsang<T, Uniform, Normal>::result_type GammaGeneratorMarsagliaTsang<T, Uniform, Normal>:: operator()(const Number a) { #ifdef DEBUG_stlib assert(a >= 1); #endif const Number d = a - 1. / 3.; const Number c = 1 / std::sqrt(9 * d); Number x, v, u; for (;;) { do { x = ((*_normalGenerator)()); v = 1 + c * x; } while (v <= 0); v = v * v * v; u = transformDiscreteDeviateToContinuousDeviateOpen<Number> ((*_normalGenerator->getDiscreteUniformGenerator())()); if (u < 1 - 0.331 * x * x * x * x) { return d * v; } if (std::log(u) < 0.5 * x * x + d *(1 - v + std::log(v))) { return d * v; } } } } // namespace numerical
26.609756
78
0.56187
bxl295
89dbf4bcc8fd03715f0ec2ef881dda474025b745
7,308
cpp
C++
ControlX/wk.cpp
bikashtudu/Interfacing-and-Data-Acquisition-from-Scientific-Instruments
e2da91b2a9a8a7bf19aac75334925ae30b2c10e9
[ "MIT" ]
null
null
null
ControlX/wk.cpp
bikashtudu/Interfacing-and-Data-Acquisition-from-Scientific-Instruments
e2da91b2a9a8a7bf19aac75334925ae30b2c10e9
[ "MIT" ]
null
null
null
ControlX/wk.cpp
bikashtudu/Interfacing-and-Data-Acquisition-from-Scientific-Instruments
e2da91b2a9a8a7bf19aac75334925ae30b2c10e9
[ "MIT" ]
1
2018-08-04T14:12:15.000Z
2018-08-04T14:12:15.000Z
#include "wk.h" #include "ui_wk.h" #include "measureset.h" #include "traceset.h" #include "wkmeter.h" #include "QFile" #include "QTextStream" #include <QDebug> #include "allfun4.h" #include <QPixmap> #define sta sta4 #define sto sto4 #define read read4 #define write write4 #define delay delay1 #include <QTime> #include <wk.h> QString props[12]={"L","C","Q","D","R","X","Z","Y","Angle","B","G","L"}; QString propy[11]={"Inductance","Capacitance","Q-factor","D-factor","Resistance","Reactance","Impedance","Admittance","Angle","Susceptance","Conductance"}; QVector< QString > vec; int j; int pt; qreal mi,Ma; QFile fi("/home/dell/build-CTC100-Desktop_Qt_5_8_0_GCC_64bit-Debug/check.txt"); QTextStream foo(&fi); void delay1( int millisecondsToWait ) { millisecondsToWait*=1000; QTime dieTime = QTime::currentTime().addMSecs( millisecondsToWait ); while( QTime::currentTime() < dieTime ) { QCoreApplication::processEvents( QEventLoop::AllEvents, 100 ); } } void readfile() { QFile file("/home/dell/build-CTC100-Desktop_Qt_5_8_0_GCC_64bit-Debug/wk.txt"); vec.clear(); file.open(QIODevice::ReadOnly); while(!file.atEnd()) { char a[1025]; file.readLine(a,sizeof(a)); if(a[0]=='r' and a[1]=='e') { QString temp; int x=strlen(a); for(int i=18;i<x-2;i++) { temp=temp+a[i]; } vec.push_back(temp); //qDebug()<<temp; } } } void wk::writelog() { sta(); read("ANA:POINTS?"); sto(); readfile(); QFile file1("/home/dell/build-CTC100-Desktop_Qt_5_8_0_GCC_64bit-Debug/Graphs/"+props[j]+"~Freq"+".txt"); QFile file2("/home/dell/build-CTC100-Desktop_Qt_5_8_0_GCC_64bit-Debug/Graphs/"+props[j+1]+"~Freq"+".txt"); file1.open(QFile::WriteOnly |QFile::Text); file2.open(QFile::WriteOnly |QFile::Text); QTextStream out1(&file1); QTextStream out2(&file2); int tot=vec[0].toInt(); //qDebug()<<vec[0]; sta(); for(int i=0;i<tot;i++) { read("ANA:POINT? "+QString::number(i)); } sto(); readfile(); out1<<"Frquency(Hz)"<<" "<<props[j]<<endl<<endl; out2<<"Frquency(Hz)"<<" "<<props[j+1]<<endl<<endl; for(int i=0;i<tot;i++) { QStringList my = vec[i].split(','); out1<<my[0]<<" "<<my[1]<<endl; out2<<my[0]<<" "<<my[2]<<endl; } //delay(ui->spinBox_3->value()); for(int i=0;i<11;i++) {int temp=250; sta(); write("ANA:PROP1 "+props[i]); write("ANA:FIT 3"); sto(); QFile file1("/home/dell/build-CTC100-Desktop_Qt_5_8_0_GCC_64bit-Debug/Graphs/"+props[i]+"~Freq"+".txt"); file1.open(QFile::ReadWrite); QTextStream out(&file1); out<<temp<<" "; sta(); for(int i=0;i<=tot;i++) { read("ANA:POINT? "+QString::number(i)); } sto(); readfile(); for(int i=0;i<11;i++) { QStringList my = vec[i].split(','); out<<my[1]<<" "; } } } bool biasm=0; wk::wk(QWidget *parent) : QMainWindow(parent), ui(new Ui::wk) { ui->setupUi(this); fi.open(QIODevice::ReadOnly); this->setWindowTitle("Analysis Mode"); sta(); read("ANA:BIAS-STAT?"); sto(); readfile(); if(vec[0][0]=="0") { QPixmap pixmap(":/on.jpg"); QIcon ButtonIcon(pixmap); ui->pushButton->setIcon(ButtonIcon); ui->pushButton->setIconSize(QSize(61,31)); biasm=1; } else { QPixmap pixmap(":/on-off.jpg"); QIcon ButtonIcon(pixmap); ui->pushButton->setIcon(ButtonIcon); ui->pushButton->setIconSize(QSize(61,31)); biasm=0; } //Graphs...1 for(int i=0;i<11;i++){ series[i] = new QLineSeries(); chart[i] = new QChart(); axisX[i] = new QValueAxis(); axisY[i] = new QValueAxis(); series[i]->setName(propy[i]+" Vs Temperature"); series[i]->setPointsVisible(true); chart[i]->addSeries(series[i]); chart[i]->addAxis(axisY[i], Qt::AlignLeft); chart[i]->setAxisX(axisX[i], series[i]); series[i]->attachAxis(axisY[i]); //series[i]->attachAxis(axisX[i]); axisX[i]->setTitleText("Temperature"); axisY[i]->setTitleText(propy[i]); axisY[i]->setLabelFormat("%0.4E"); series[i]->setPointsVisible(true); // axisY[i]->setTickCount(10); //axisX[i]->setRange(); //axisY[i]->setRange(0,250); chartView[i] = new QChartView(chart[i]); } ui->gridLayout_4->addWidget(chartView[0]); ui->gridLayout_5->addWidget(chartView[1]); ui->gridLayout_6->addWidget(chartView[2]); ui->gridLayout_7->addWidget(chartView[3]); ui->gridLayout_8->addWidget(chartView[4]); ui->gridLayout_9->addWidget(chartView[5]); ui->gridLayout_10->addWidget(chartView[6]); ui->gridLayout_11->addWidget(chartView[7]); ui->gridLayout_12->addWidget(chartView[8]); ui->gridLayout_13->addWidget(chartView[9]); ui->gridLayout_14->addWidget(chartView[10]); } wk::~wk() { delete ui; } void wk::on_pushButton_2_clicked() { wkmeter* ptr=new wkmeter; ptr->show(); hide(); } void wk::on_meas_setup_clicked() { measureset* ptr; ptr= new measureset; ptr->show(); } void wk::on_trace_setup_clicked() { traceset* ptr; ptr=new traceset; ptr->show(); } void wk::on_pushButton_clicked() { if(biasm==1) { QPixmap pixmap(":/on-off.jpg"); QIcon ButtonIcon(pixmap); ui->pushButton->setIcon(ButtonIcon); ui->pushButton->setIconSize(QSize(61,31)); biasm=0; sta(); write("ANA:BIAS-STAT OFF"); sto(); } else { QPixmap pixmap(":/on.jpg"); QIcon ButtonIcon(pixmap); ui->pushButton->setIcon(ButtonIcon); ui->pushButton->setIconSize(QSize(61,31)); biasm=1; sta(); write("ANA:BIAS-STAT ON"); sto(); } } void wk::on_trig_clicked() { sta(); write("ANA:TRIG"); sto(); delay(50); for( j=0;j<11;j+=2) { sta(); write("ANA:PROP1 "+props[j]); write("ANA:PROP2 "+props[j+1]); write("ANA:FIT 3"); sto(); writelog(); } //writelog(); } /*void wk::on_add_clicked() { // fi.open(QIODevice::ReadOnly); char a[1025]; fi.readLine(a,sizeof(a)); QString cur=a; double yt=cur.toDouble(); fi.readLine(a,sizeof(a)); cur=a; double xt=cur.toDouble(); qreal y=qreal(yt); qreal x=qreal(xt); series[3]->append(x,y); if(pt==0) { if(y>0) {mi=y-y/50; Ma=y+y/50;} else {mi=y+y/50; Ma=y-y/50;} axisX[3]->setRange(x-5,x+5); } else { if(y<mi) mi=y-(mi-y); else if(y>Ma) Ma=y+(y-Ma); axisX[3]->setMax(x+5); } axisY[3]->setRange(mi,Ma); pt++; foo<<y<<" "<<mi<<" "<<Ma<<endl; //series[0]->attachAxis(axisY[0]); }*/
20.132231
155
0.532704
bikashtudu
89e25d3362cd03cd30ac65a747e3a353fea83e1f
7,427
cpp
C++
SDKs/CryCode/3.6.15/CryEngine/CryAction/GameRulesSystem.cpp
amrhead/FireNET
34d439aa0157b0c895b20b2b664fddf4f9b84af1
[ "BSD-2-Clause" ]
4
2017-12-18T20:10:16.000Z
2021-02-07T21:21:24.000Z
SDKs/CryCode/3.8.1/CryEngine/CryAction/GameRulesSystem.cpp
amrhead/FireNET
34d439aa0157b0c895b20b2b664fddf4f9b84af1
[ "BSD-2-Clause" ]
null
null
null
SDKs/CryCode/3.8.1/CryEngine/CryAction/GameRulesSystem.cpp
amrhead/FireNET
34d439aa0157b0c895b20b2b664fddf4f9b84af1
[ "BSD-2-Clause" ]
3
2019-03-11T21:36:15.000Z
2021-02-07T21:21:26.000Z
/************************************************************************* Crytek Source File. Copyright (C), Crytek Studios, 2001-2004. ------------------------------------------------------------------------- $Id$ $DateTime$ Description: ------------------------------------------------------------------------- History: - 15:9:2004 10:30 : Created by Mathieu Pinard *************************************************************************/ #include "StdAfx.h" #include "GameObjects/GameObjectSystem.h" #include "GameObjects/GameObject.h" #include "GameRulesSystem.h" #include "Network/GameServerNub.h" #include <list> #ifdef WIN64 #pragma warning ( disable : 4244 ) #endif #define GAMERULES_GLOBAL_VARIABLE ("g_gameRules") #define GAMERULESID_GLOBAL_VARIABLE ("g_gameRulesId") //------------------------------------------------------------------------ CGameRulesSystem::CGameRulesSystem( ISystem *pSystem, IGameFramework *pGameFW ) : m_pGameFW(pGameFW), m_pGameRules(0), m_currentGameRules(0) { } //------------------------------------------------------------------------ CGameRulesSystem::~CGameRulesSystem() { } //------------------------------------------------------------------------ bool CGameRulesSystem::RegisterGameRules( const char *rulesName, const char *extensionName ) { IEntityClassRegistry::SEntityClassDesc ruleClass; char scriptName[1024]; sprintf(scriptName, "Scripts/GameRules/%s.lua", rulesName); ruleClass.sName = rulesName; ruleClass.sScriptFile = scriptName; ruleClass.pUserProxyCreateFunc = CreateGameObject; ruleClass.pUserProxyData = this; ruleClass.flags |= ECLF_INVISIBLE; if (!gEnv->pEntitySystem->GetClassRegistry()->RegisterStdClass(ruleClass)) { CRY_ASSERT(0); return false; } std::pair<TGameRulesMap::iterator, bool> rit=m_GameRules.insert(TGameRulesMap::value_type(rulesName, SGameRulesDef())); rit.first->second.extension=extensionName; return true; } //------------------------------------------------------------------------ bool CGameRulesSystem::CreateGameRules( const char *rulesName) { const char *name=GetGameRulesName(rulesName); TGameRulesMap::iterator it=m_GameRules.find(name); if (it==m_GameRules.end()) return false; // If a rule is currently being used, ask the entity system to remove it DestroyGameRules(); SEntitySpawnParams params; params.sName = "GameRules"; params.pClass = gEnv->pEntitySystem->GetClassRegistry()->FindClass( name ); params.nFlags |= ENTITY_FLAG_NO_PROXIMITY|ENTITY_FLAG_UNREMOVABLE; params.id = 1; IEntity* pEntity = gEnv->pEntitySystem->SpawnEntity( params ); CRY_ASSERT(pEntity); if (pEntity == NULL) return false; pEntity->Activate(true); if (pEntity->GetScriptTable()) { IScriptSystem *pSS = gEnv->pScriptSystem; pSS->SetGlobalValue(GAMERULES_GLOBAL_VARIABLE, pEntity->GetScriptTable()); pSS->SetGlobalValue(GAMERULESID_GLOBAL_VARIABLE, ScriptHandle((UINT_PTR)m_currentGameRules)); } //since we re-instantiating game rules, let's get rid of everything related to previous match if(IGameplayRecorder *pGameplayRecorder = CCryAction::GetCryAction()->GetIGameplayRecorder()) pGameplayRecorder->Event(pEntity, GameplayEvent(eGE_GameReset)); if(gEnv->bServer) { if (CGameServerNub* pGameServerNub = CCryAction::GetCryAction()->GetGameServerNub()) pGameServerNub->ResetOnHoldChannels(); } return true; } //------------------------------------------------------------------------ bool CGameRulesSystem::DestroyGameRules() { // If a rule is currently being used, ask the entity system to remove it if ( m_currentGameRules ) { IEntity* pEntity = gEnv->pEntitySystem->GetEntity(m_currentGameRules); if (pEntity) pEntity->ClearFlags(ENTITY_FLAG_UNREMOVABLE); gEnv->pEntitySystem->RemoveEntity( m_currentGameRules, true ); SetCurrentGameRules(0); IScriptSystem *pSS = gEnv->pScriptSystem; pSS->SetGlobalToNull(GAMERULES_GLOBAL_VARIABLE); pSS->SetGlobalToNull(GAMERULESID_GLOBAL_VARIABLE); } return true; } //------------------------------------------------------------------------ bool CGameRulesSystem::HaveGameRules( const char *rulesName ) { const char *name=GetGameRulesName(rulesName); if (!name || !gEnv->pEntitySystem->GetClassRegistry()->FindClass( name )) return false; if (m_GameRules.find(name) == m_GameRules.end() ) return false; return true; } //------------------------------------------------------------------------ void CGameRulesSystem::AddGameRulesAlias(const char *gamerules, const char *alias) { if (SGameRulesDef *def=GetGameRulesDef(gamerules)) def->aliases.push_back(alias); } //------------------------------------------------------------------------ void CGameRulesSystem::AddGameRulesLevelLocation(const char *gamerules, const char *mapLocation) { if (SGameRulesDef *def=GetGameRulesDef(gamerules)) def->maplocs.push_back(mapLocation); } //------------------------------------------------------------------------ const char *CGameRulesSystem::GetGameRulesLevelLocation(const char *gamerules, int i) { if (SGameRulesDef *def=GetGameRulesDef(GetGameRulesName(gamerules))) { if (i>=0 && i<def->maplocs.size()) return def->maplocs[i].c_str(); } return 0; } //------------------------------------------------------------------------ void CGameRulesSystem::SetCurrentGameRules(IGameRules *pGameRules) { m_pGameRules = pGameRules; m_currentGameRules = m_pGameRules ? m_pGameRules->GetEntityId() : 0; } //------------------------------------------------------------------------ IGameRules * CGameRulesSystem::GetCurrentGameRules() const { return m_pGameRules; } //------------------------------------------------------------------------ const char *CGameRulesSystem::GetGameRulesName(const char *alias) const { for (TGameRulesMap::const_iterator it=m_GameRules.begin(); it!=m_GameRules.end(); ++it) { if (!stricmp(it->first.c_str(), alias)) return it->first.c_str(); for (std::vector<string>::const_iterator ait=it->second.aliases.begin();ait!=it->second.aliases.end(); ++ait) { if (!stricmp(ait->c_str(), alias)) return it->first.c_str(); } } return 0; } //------------------------------------------------------------------------ /* string& CGameRulesSystem::GetCurrentGameRules() { return } */ CGameRulesSystem::SGameRulesDef *CGameRulesSystem::GetGameRulesDef(const char *name) { TGameRulesMap::iterator it = m_GameRules.find(name); if (it==m_GameRules.end()) return 0; return &it->second; } //------------------------------------------------------------------------ IEntityProxyPtr CGameRulesSystem::CreateGameObject(IEntity *pEntity, SEntitySpawnParams &params, void *pUserData) { CGameRulesSystem *pThis = static_cast<CGameRulesSystem *>(pUserData); CRY_ASSERT(pThis); TGameRulesMap::iterator it = pThis->m_GameRules.find(params.pClass->GetName()); CRY_ASSERT(it != pThis->m_GameRules.end()); CGameObjectPtr pGameObject = ComponentCreateAndRegister_DeleteWithRelease<CGameObject>( IComponent::SComponentInitializer(pEntity), IComponent::EComponentFlags_LazyRegistration ); if (!it->second.extension.empty()) { if (!pGameObject->ActivateExtension(it->second.extension.c_str())) { pEntity->RegisterComponent( pGameObject, false ); pGameObject.reset(); } } return pGameObject; } void CGameRulesSystem::GetMemoryStatistics(ICrySizer * s) { s->Add(*this); s->AddContainer(m_GameRules); }
29.240157
181
0.616534
amrhead
89e644052dd68012cdb4039d8972a40e186d0b90
2,977
cpp
C++
ALight-RayCPU-Reference/mesh.cpp
Asixa/ALight-Renderer-Complex
30b1ac19053ee89f38ee5b10e85387c92309e5bc
[ "FTL" ]
1
2020-07-28T09:25:51.000Z
2020-07-28T09:25:51.000Z
ALight-RayCPU-Reference/mesh.cpp
Asixa/ALight-Renderer-Complex
30b1ac19053ee89f38ee5b10e85387c92309e5bc
[ "FTL" ]
null
null
null
ALight-RayCPU-Reference/mesh.cpp
Asixa/ALight-Renderer-Complex
30b1ac19053ee89f38ee5b10e85387c92309e5bc
[ "FTL" ]
null
null
null
#include "mesh.h" Mesh::Mesh(const char *fileName, Material material) { m_fileName = fileName; m_material = material; if (loadObj() != 0) { std::cerr << "Mesh: Error loading " << m_fileName << std::endl; std::exit(1); } std::cout << "Mesh: " << m_fileName << " has been loaded succesfully." << std::endl; } int Mesh::loadObj() { std::vector<vec3> vertices; std::vector<vec3> normals; std::vector<face> indices; std::ifstream file; std::string line; file.open(m_fileName); if (file.is_open()) { while (file.good()) { std::getline(file, line); if (line.substr(0, 2) == "v ") { std::istringstream s(line.substr(2)); vec3 v; s >> v.x; s >> v.y; s >> v.z; vertices.push_back(v); } else if (line.substr(0, 2) == "vn ") { std::istringstream s(line.substr(2)); vec3 n; s >> n.x; s >> n.y; s >> n.z; normals.push_back(n); } else if (line.substr(0, 2) == "f ") { if (line.find("//") == std::string::npos) { std::istringstream s(line.substr(2)); face f; s >> f.va; s >> f.vb; s >> f.vc; f.va--; f.vb--; f.vc--; indices.push_back(f); } else { std::replace(line.begin(), line.end(), '/', ' '); std::istringstream s(line.substr(2)); face f; s >> f.va; s >> f.na; s >> f.vb; s >> f.nb; s >> f.vc; s >> f.nc; f.va--; f.na--; f.vb--; f.nb--; f.vc--; f.nc--; indices.push_back(f); } } else { continue; } } } else { return 1; } for (size_t i = 0; i < indices.size(); i++) { vec3 v0 = vertices[indices[i].va]; vec3 v1 = vertices[indices[i].vb]; vec3 v2 = vertices[indices[i].vc]; if (normals.size() > 0) { vec3 n0 = normals[indices[i].na]; vec3 n1 = normals[indices[i].nb]; vec3 n2 = normals[indices[i].nc]; m_triangles.push_back(Triangle(v0, v1, v2, n0, n1, n2, m_material)); } else { m_triangles.push_back(Triangle(v0, v1, v2, m_material)); } } return 0; }
25.444444
88
0.356063
Asixa
89eae73ba1a6b81299a89893c8f328a496874954
287
cpp
C++
core/src/cubos/core/io/cursor.cpp
GameDevTecnico/cubos
51f89c9f3afc8afe502d167dadecab7dfe5b1c7b
[ "MIT" ]
2
2021-09-28T14:13:27.000Z
2022-03-26T11:36:48.000Z
core/src/cubos/core/io/cursor.cpp
GameDevTecnico/cubos
51f89c9f3afc8afe502d167dadecab7dfe5b1c7b
[ "MIT" ]
72
2021-09-29T08:55:26.000Z
2022-03-29T21:21:00.000Z
core/src/cubos/core/io/cursor.cpp
GameDevTecnico/cubos
51f89c9f3afc8afe502d167dadecab7dfe5b1c7b
[ "MIT" ]
null
null
null
#include <cubos/core/io/cursor.hpp> using namespace cubos::core; #ifdef WITH_GLFW io::Cursor::Cursor(GLFWcursor* handle) { this->glfwHandle = handle; } #endif io::Cursor::~Cursor() { #ifdef WITH_GLFW if (this->glfwHandle) glfwDestroyCursor(this->glfwHandle); #endif }
15.105263
44
0.69338
GameDevTecnico
8851eb91b640daf6f65521884f718c6b6d402a14
41,327
cpp
C++
belatedly/src/belatedly.cpp
Ahziu/Delayed-Hits
39e062a34ce7d3bb693dceff0a7e68ea1ee6864b
[ "BSD-3-Clause-Clear" ]
15
2020-09-04T18:32:14.000Z
2022-03-31T08:29:05.000Z
belatedly/src/belatedly.cpp
Ahziu/Delayed-Hits
39e062a34ce7d3bb693dceff0a7e68ea1ee6864b
[ "BSD-3-Clause-Clear" ]
1
2021-02-18T08:14:29.000Z
2021-02-18T08:14:29.000Z
belatedly/src/belatedly.cpp
Ahziu/Delayed-Hits
39e062a34ce7d3bb693dceff0a7e68ea1ee6864b
[ "BSD-3-Clause-Clear" ]
4
2020-10-17T21:39:38.000Z
2021-06-04T14:29:27.000Z
// STD headers #include <assert.h> #include <fstream> #include <functional> #include <iomanip> #include <iostream> #include <list> #include <string> #include <thread> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // Boost headers #include <boost/bimap.hpp> #include <boost/program_options.hpp> // Cereal headers #include <cereal/archives/binary.hpp> #include <cereal/types/vector.hpp> // Gurobi headers #include <gurobi_c++.h> // Custom headers #include "flow_dict.hpp" #include "simulator.hpp" #include "utils.hpp" // Typedefs namespace bopt = boost::program_options; typedef std::tuple<std::string, bool, std::string, std::string, double> Edge; // Format: (flow_id, in_cache, src, dst, cost) // Constant hyperparameters constexpr unsigned int kNumThreads = 24; /** * Implements a Multi-Commodity Min-Cost Flow-based * solver for the Delayed Hits caching problem. */ class MCMCFSolver { private: typedef std::vector<size_t> Indices; // Trace and cache parameters const uint z_; const uint c_; const bool is_forced_; const size_t trace_len_; const std::string trace_file_path_; const std::string model_file_prefix_; const std::string packets_file_path_; const std::vector<std::string> trace_; // Housekeeping std::vector<double> solution_; std::unordered_set<size_t> cache_node_idxs_; std::unordered_map<std::string, Indices> indices_; boost::bimap<size_t, std::string> idx_to_nodename_; std::unordered_map<size_t, double> idx_to_miss_cost_; std::unordered_map<std::string, std::string> sink_nodes_; std::unordered_map<std::string, Indices> cache_interval_start_idxs_; // "Split nodes" are used to enforce forced admission, if required. // We detect nodes where the forced admission constraint *might* be // violated (i.e. an object doesn't remain in the cache for atleast // one timestep), and add manually a constraint that enforces this. std::unordered_set<size_t> split_node_idxs_; // Internal helper methods double getMissCostStartingAt(const size_t idx) const; const std::string& cchNodeForMemAt(const size_t idx) const; size_t getNextMemNodeIdx(const size_t idx, const std::string& flow_id, std::unordered_map<std::string, size_t>& next_idxs_map) const; // Thread-safe, concurrent helper methods void populateOutOfCchEdgesConcurrent( const std::list<std::string>& flow_ids, std::list<Edge>& edges, std::unordered_set<size_t>& cache_node_idxs); void populateCchCapacityConstraintsConcurrent( const std::pair<size_t, size_t> range, const belatedly::FlowDict& flows, std::list<GRBLinExpr>& exprs) const; // Setup and checkpointing void setup(); bool loadOptimizedModelSolution(belatedly::FlowDict& flows); void saveOptimizedModelSolution(const belatedly::FlowDict& flows) const; // Model creation void populateOutOfCchEdges(std::list<Edge>& all_edges); void createFlowVariables(GRBModel& model, belatedly::FlowDict& flows, const std::list<Edge>& edges) const; void populateCchCapacityConstraints( GRBModel& model, const belatedly::FlowDict& flows) const; void populateSplitNodeFlowConstraints( GRBModel& model, const belatedly::FlowDict& flows) const; void populateFlowConservationConstraints( GRBModel& model, const belatedly::FlowDict& flows) const; void addMissCostStartingAt(const size_t start_idx, const double coefficient, std::vector<utils::Packet>& packets) const; // Cost computation and validation double getCostLowerBound(const belatedly::FlowDict& flows, const std::list<Edge>& edges) const; double getCostUpperBoundAndValidateSolution( const belatedly::FlowDict& flows, const std::list<Edge>& edges) const; public: MCMCFSolver(const std::string& trace_fp, const std::string& model_fp, const std::string& packets_fp, const bool forced, const uint z, const uint c, const std::vector<std::string>& trace) : z_(z), c_(c), is_forced_(forced), trace_len_(trace.size()), trace_file_path_(trace_fp), model_file_prefix_(model_fp), packets_file_path_(packets_fp), trace_(trace) {} void solve(); }; /** * Given an index, returns the corresponding cache node. * * Thread-safe. */ const std::string& MCMCFSolver::cchNodeForMemAt(const size_t idx) const { return idx_to_nodename_.left.at(idx); } /** * Returns the cost of a cache miss starting at idx. * * Thread-safe. */ double MCMCFSolver::getMissCostStartingAt(const size_t idx) const { const std::string& flow_id = trace_[idx]; double miss_cost = z_; // Iterate over the next z timesteps, and add the // latency cost corresponding to each subsequent // packet of the same flow. for (size_t offset = 1; offset < z_; offset++) { if (idx + offset >= trace_len_) { break; } else if (trace_[idx + offset] == flow_id) { miss_cost += (z_ - offset); } } return miss_cost; } /** * Returns the index of the first mem node corresponding to the given * flow ID occuring after idx. If no reference to this flow is found * in (idx, trace_len_), returns maxval. * * The state for each flow is cached in next_idxs_map. This dict must * be cleared before starting a new operation (that is, when indices * are no longer expected to continue increasing monotonically). * * Thread-safe. */ size_t MCMCFSolver::getNextMemNodeIdx( const size_t idx, const std::string& flow_id, std::unordered_map<std::string, size_t>& next_idxs_map) const { const std::vector<size_t>& indices = indices_.at(flow_id); size_t indices_len = indices.size(); while ((next_idxs_map[flow_id] < indices_len) && (indices[next_idxs_map[flow_id]] <= idx)) { next_idxs_map[flow_id]++; } // If the next index is beyond the idxs list for // this flow, return the corresponding sink node. size_t next_idx = next_idxs_map[flow_id]; if (next_idx == indices_len) { return std::numeric_limits<size_t>::max(); } else { size_t next_mem_idx = indices[next_idx]; assert(trace_[next_mem_idx] == flow_id); return next_mem_idx; } } /** * Attempts to load the optimal solution and the flow mappings * for the given model. Returns true if successful, else false. */ bool MCMCFSolver::loadOptimizedModelSolution(belatedly::FlowDict& flows) { if (model_file_prefix_.empty()) { return false; } std::ifstream solution_ifs(model_file_prefix_ + ".sol"); const std::string flows_fp = model_file_prefix_ + ".flows"; // Either of the required model files is missing, indicating failure if (!solution_ifs.good() || !std::ifstream(flows_fp).good()) { return false; } // Load the solutions vector { cereal::BinaryInputArchive ar(solution_ifs); ar(solution_); } // Load the flow mappings flows.loadFlowMappings(flows_fp); // Sanity check: The number of decision variables should // be equal to the number of entries in the flows map. assert(solution_.size() == flows.numVariables()); return true; } /** * Saves the optimal solution and flow mappings to disk. */ void MCMCFSolver::saveOptimizedModelSolution( const belatedly::FlowDict& flows) const { if (model_file_prefix_.empty()) { return; } std::ofstream solution_ofs(model_file_prefix_ + ".sol"); const std::string flows_fp = model_file_prefix_ + ".flows"; // Save the solutions vector cereal::BinaryOutputArchive oarchive(solution_ofs); oarchive(solution_); // Save the flow mappings flows.saveFlowMappings(flows_fp); } /** * Populate the indices map and internal data structures. */ void MCMCFSolver::setup() { size_t num_nonempty_packets = 0; for (size_t idx = 0; idx < trace_len_; idx++) { const std::string& flow_id = trace_[idx]; // If the packet is non-empty, append the idx to // the corresponding flow's idxs. Also, populate // the miss-costs map. if (!flow_id.empty()) { num_nonempty_packets++; indices_[flow_id].push_back(idx); idx_to_miss_cost_[idx] = getMissCostStartingAt(idx); } // Found a possible violation of forced admission; track this as a split node if (is_forced_ && !flow_id.empty() && (idx > 0) && (idx < trace_len_ - z_) && (flow_id == trace_[idx - 1]) && (flow_id == trace_[idx + z_])) { split_node_idxs_.insert(idx); } // Populate the nodenames map idx_to_nodename_.insert(boost::bimap<size_t, std::string>::value_type( idx, "cch_t" + std::to_string(idx + z_ - 1) + "_" + flow_id)); } // Populate the sink nodes map and // prime the cache intervals map. for (const auto& iter : indices_) { const std::string& flow_id = iter.first; sink_nodes_[flow_id] = ("x_" + flow_id); cache_interval_start_idxs_[flow_id]; } // Debug std::cout << "Finished setup with " << trace_len_ << " packets (" << num_nonempty_packets << " nonempty), " << indices_.size() << " flows." << std::endl; } /** * Helper method. Populates the out-of-cache edges (mem->cch/admittance, * and cch->mem/eviction) for the given flow IDs in a thread-safe manner. * * Important note: This method relies on the fact that separate threads * operate on disjoint sets of flow IDs (and only ever access different * STL containers concurrently), precluding the need for mutexes. * * Thread-safe. */ void MCMCFSolver::populateOutOfCchEdgesConcurrent( const std::list<std::string>& flow_ids, std::list<Edge>& edges, std::unordered_set<size_t>& local_cache_node_idxs) { // Iterate over the given flow IDs to populate the edges list std::unordered_map<std::string, size_t> next_idxs_map; for (const std::string& flow_id : flow_ids) { std::string evicted_reference = std::string(); bool has_flow_started = false; // Iterate over each timestep and fetch the next mem reference for (size_t idx = 0; idx < trace_len_; idx++) { const std::string& trace_flow_id = trace_[idx]; bool is_same_flow = (!trace_flow_id.empty() && (trace_flow_id == flow_id)); if (has_flow_started) { // Fetch the next mem reference corresponding to this flow const size_t next_reference_idx = getNextMemNodeIdx( idx + z_ - 1, flow_id, next_idxs_map); const bool is_dst_sink_node = (next_reference_idx == std::numeric_limits<size_t>::max()); // Fetch the dst node for this out-of-cache edge const std::string& next_reference = is_dst_sink_node ? sink_nodes_.at(flow_id) : cchNodeForMemAt(next_reference_idx); if (is_same_flow) { // In optional admission, unconditionally create an // outedge from this node to the next mem reference. if (!is_forced_) { evicted_reference = next_reference; edges.push_back(std::make_tuple( flow_id, false, cchNodeForMemAt(idx), next_reference, (is_dst_sink_node ? 0.0 : idx_to_miss_cost_.at(next_reference_idx))) ); } // The following node in the trace (mem_t{idx + z}) maps to // this flow, but the previous node in the caching sequence // (cch_t{idx + z - 1}) also maps to it. Thus, this is the // final opportunity to reach mem_t{idx + z}, and we create // an edge to it. else if (split_node_idxs_.find(idx) != split_node_idxs_.end()) { assert(!is_dst_sink_node); edges.push_back(std::make_tuple( flow_id, false, cchNodeForMemAt(idx), next_reference, idx_to_miss_cost_.at(next_reference_idx)) ); } // Discard the next mem reference for this flow else { evicted_reference.clear(); } // Mark this idx as the start of a new interval for this flow local_cache_node_idxs.insert(idx); cache_interval_start_idxs_.at(flow_id).push_back(idx); } // If we did not already created an eviction edge to the // next mem reference for this flow, create one to it. else if (evicted_reference != next_reference) { evicted_reference = next_reference; edges.push_back(std::make_tuple( flow_id, false, cchNodeForMemAt(idx), next_reference, (is_dst_sink_node ? 0.0 : idx_to_miss_cost_.at(next_reference_idx))) ); // Mark this idx as the start of a new interval for this flow local_cache_node_idxs.insert(idx); cache_interval_start_idxs_.at(flow_id).push_back(idx); } } // The flow has not yet started and the packet at this timestep // belongs to this flow, indicating that this is the first ever // request to it. else if (is_same_flow) { has_flow_started = true; // In optional admission, unconditionally create an // outedge from this node to the next mem reference. if (!is_forced_) { // Fetch the next mem reference corresponding to this flow const size_t next_reference_idx = getNextMemNodeIdx( idx + z_ - 1, flow_id, next_idxs_map); const bool is_dst_sink_node = (next_reference_idx == std::numeric_limits<size_t>::max()); // Fetch the dst node for this out-of-cache edge const std::string& next_reference = is_dst_sink_node ? sink_nodes_.at(flow_id) : cchNodeForMemAt(next_reference_idx); evicted_reference = next_reference; edges.push_back(std::make_tuple( flow_id, false, cchNodeForMemAt(idx), next_reference, (is_dst_sink_node ? 0.0 : idx_to_miss_cost_.at(next_reference_idx))) ); } // Mark this idx as the start of a new interval for this flow local_cache_node_idxs.insert(idx); cache_interval_start_idxs_.at(flow_id).push_back(idx); } } } } /** * Populates the out-of-cache (eviction and admittance) edges. */ void MCMCFSolver::populateOutOfCchEdges(std::list<Edge>& all_edges) { size_t num_out_of_cch_edges = 0; size_t num_total_flows = indices_.size(); size_t num_flows_per_thread = int(ceil(num_total_flows / static_cast<double>(kNumThreads))); // Temporary containers for each thread size_t num_flows_allotted = 0; std::array<std::list<Edge>, kNumThreads> edges; std::array<std::list<std::string>, kNumThreads> flow_ids; std::array<std::unordered_set<size_t>, kNumThreads> local_cache_node_idxs; // Partition the entire set of flow IDs into kNumThreads disjoint sets auto iter = indices_.begin(); for (size_t t_idx = 0; t_idx < kNumThreads; t_idx++) { for (size_t i = 0; (i < num_flows_per_thread) && (iter != indices_.end()); i++, iter++) { num_flows_allotted++; flow_ids[t_idx].push_back(iter->first); } } // Sanity check assert(num_flows_allotted == num_total_flows); // Launch kNumThreads on the corresponding sets of flow IDs std::thread workers[kNumThreads]; for (size_t t_idx = 0; t_idx < kNumThreads; t_idx++) { workers[t_idx] = std::thread(&MCMCFSolver::populateOutOfCchEdgesConcurrent, this, std::ref(flow_ids[t_idx]), std::ref(edges[t_idx]), std::ref(local_cache_node_idxs[t_idx])); } // Wait for all the worker threads to finish execution for (size_t t_idx = 0; t_idx < kNumThreads; t_idx++) { workers[t_idx].join(); } // Then, combine their results for (size_t t_idx = 0; t_idx < kNumThreads; t_idx++) { num_out_of_cch_edges += edges[t_idx].size(); all_edges.splice(all_edges.end(), edges[t_idx]); cache_node_idxs_.insert(local_cache_node_idxs[t_idx].begin(), local_cache_node_idxs[t_idx].end()); } // Next, sort the cache intervals for each flow in-place for (auto& iter : cache_interval_start_idxs_) { std::vector<size_t>& start_idxs = iter.second; std::sort(start_idxs.begin(), start_idxs.end()); } // Finally, for the last packet in the trace, unconditionally // create an outedge to the corresponding flow's sink node. size_t idx = (trace_len_ - 1); const std::string& flow_id = trace_[idx]; if (is_forced_ && !flow_id.empty()) { num_out_of_cch_edges++; all_edges.push_back(std::make_tuple(flow_id, false, cchNodeForMemAt(idx), sink_nodes_.at(flow_id), 0.0)); } // Debug std::cout << "Finished populating " << num_out_of_cch_edges << " out-of-cache edges concurrently, using " << kNumThreads << " threads." << std::endl; } /** * Given a list of edges, populates the flow tupledict. */ void MCMCFSolver:: createFlowVariables(GRBModel& model, belatedly::FlowDict& flows, const std::list<Edge>& edges) const { size_t num_total_cache_intervals = 0; // First, create variables representing mem->cch and cch->mem edges for (const Edge& edge : edges) { flows.addVariable(std::get<0>(edge), std::get<1>(edge), std::get<2>(edge), std::get<3>(edge), std::get<4>(edge)); } // Next, for every flow, create decision variables // corresponding to each possible caching interval. for (const auto& iter : cache_interval_start_idxs_) { const std::string& flow_id = iter.first; const std::vector<size_t>& start_idxs = iter.second; const size_t num_intervals = (start_idxs.size() - 1); // Iterate over each interval for (size_t i = 0; i < num_intervals; i++) { size_t idx = start_idxs[i]; size_t next_idx = start_idxs[i + 1]; // Sanity check: Both indices should be in the nodes set assert((cache_node_idxs_.find(idx) != cache_node_idxs_.end()) && (cache_node_idxs_.find(next_idx) != cache_node_idxs_.end())); // Create a decision variable corresponding to cch_{idx}->cch_{next_idx} num_total_cache_intervals++; flows.addVariable(flow_id, true, cchNodeForMemAt(idx), cchNodeForMemAt(next_idx), 0.0); } } // Finally, update the model model.update(); // Debug std::cout << "Finished creating " << flows.numVariables() << " flow variables (for " << edges.size() << " edges, plus " << num_total_cache_intervals << " caching intervals)." << std::endl; } /** * Helper method. Populates the cache capacity constraints for * the given range of trace indices in a thread-safe manner. * * Thread-safe. */ void MCMCFSolver::populateCchCapacityConstraintsConcurrent( const std::pair<size_t, size_t> range, const belatedly:: FlowDict& flows, std::list<GRBLinExpr>& exprs) const { std::unordered_map<std::string, GRBVar> decision_variables; std::unordered_map<std::string, size_t> current_idxs; // Starting index is out-of-bounds, do nothing if (range.first >= trace_len_) { return; } // First, for each flow ID, forward its current iterator idx // to point to the appropriate location in its indices list. for (const auto& iter : cache_interval_start_idxs_) { const std::vector<size_t>& intervals = iter.second; const std::string& flow_id = iter.first; size_t i = 0; while (i < (intervals.size() - 1) && range.first > intervals[i + 1]) { i++; } // Update the current iterator idx current_idxs[flow_id] = i; } // Next, generate a linear-expression corresponding to the sum of // all flow decision variables at every timestep, and impose that // it is LEQ the cache size as a constraint. for (size_t idx = range.first; idx < range.second; idx++) { if (cache_node_idxs_.find(idx) == cache_node_idxs_.end()) { continue; } bool is_split_node = (split_node_idxs_.find(idx) != split_node_idxs_.end()); GRBLinExpr node_capacity_expr; bool is_expr_changed = false; // Update the current decision variable for each // flow and add it to the LHS of the constraints. for (const auto& iter : cache_interval_start_idxs_) { const std::string& flow_id = iter.first; const std::vector<size_t>& intervals = iter.second; bool is_split_node_for_flow = (is_split_node && (trace_[idx] == flow_id)); // If this trace index either precedes the first decision // variable, or is either at or beyond the last decision // variable for this flow, do nothing. size_t i = current_idxs[flow_id]; if (idx < intervals[0] || idx >= intervals.back()) { continue; } // Reached the first interval or the end // of the current interval for this flow. else if ((decision_variables.find(flow_id) == decision_variables.end()) || (idx == intervals[i + 1])) { // If this is the end of the current // interval, update the idx iterator. if (idx == intervals[i + 1]) { current_idxs[flow_id] = ++i; } // Fetch the current interval size_t start_idx = intervals[i]; size_t end_idx = intervals[i + 1]; // This is a regular node GRBVar decision_variable = ( flows.getVariable(flow_id, true, cchNodeForMemAt(start_idx), cchNodeForMemAt(end_idx))); // Update the decision variable for this flow decision_variables[flow_id] = decision_variable; node_capacity_expr += decision_variable; is_expr_changed = true; } // Else, add the current decision variable to the expression else { GRBVar decision_variable = decision_variables.at(flow_id); node_capacity_expr += decision_variable; assert(!is_split_node_for_flow); } } // Finally, add the expression as a cache constraints if (is_expr_changed) { exprs.push_back(node_capacity_expr); } } } /** * Populates the cache capacity constraints for the given flow variables. */ void MCMCFSolver::populateCchCapacityConstraints( GRBModel& model, const belatedly::FlowDict& flows) const { std::array<std::list<GRBLinExpr>, kNumThreads> exprs; std::thread workers[kNumThreads]; size_t num_constraints = 0; // Partition the trace into kNumThreads disjoint sets size_t start_idx = 0; size_t idxs_per_thread = int(ceil(trace_len_ / static_cast<double>(kNumThreads))); // Launch kNumThreads on the corresponding range of indices for (size_t t_idx = 0; t_idx < kNumThreads; t_idx++) { size_t end_idx = std::min(trace_len_, start_idx + idxs_per_thread); workers[t_idx] = std::thread( &MCMCFSolver::populateCchCapacityConstraintsConcurrent, this, std::make_pair(start_idx, end_idx), std::ref(flows), std::ref(exprs[t_idx])); // Update the starting idx start_idx = end_idx; } // Wait for all the worker threads to finish execution for (size_t t_idx = 0; t_idx < kNumThreads; t_idx++) { workers[t_idx].join(); } // Populate the model constraints for (size_t t_idx = 0; t_idx < kNumThreads; t_idx++) { for (auto& expr : exprs[t_idx]) { num_constraints++; model.addConstr(expr, GRB_LESS_EQUAL, c_, ""); } exprs[t_idx].clear(); } // Debug std::cout << "Finished adding " << num_constraints << " arc-capacity" << " constraints for cch->cch edges concurrently, using " << kNumThreads << " threads." << std::endl; } /** * Populates flow constraints for split nodes. These ensure that once * flow enters the cache, it remains there for at least one timestep. */ void MCMCFSolver::populateSplitNodeFlowConstraints( GRBModel& model, const belatedly::FlowDict& flows) const { size_t num_split_node_constraints = 0; for (const size_t idx : split_node_idxs_) { const std::string& flow_id = trace_[idx]; num_split_node_constraints++; // Fetch the decision variable corresponding // to the cch_{idx}->next_mem_node edge. const GRBVar outflow = flows.getVariable( flow_id, false, cchNodeForMemAt(idx), cchNodeForMemAt(idx + z_)); // Fetch the expression corresponding // to the mem_{idx}->cch_{idx} edge. const GRBLinExpr inflow = ( flows.sumAcrossSrcNodes(flow_id, false, cchNodeForMemAt(idx))); // Ensure that the outflow is LEQ (1 - inflow) model.addConstr(outflow + inflow, GRB_LESS_EQUAL, 1, ""); } // Debug std::cout << "Finished populating " << num_split_node_constraints << " flow constraints for split nodes." << std::endl; } /** * Populates the flow conservation constraints for all nodes. */ void MCMCFSolver::populateFlowConservationConstraints( GRBModel& model, const belatedly::FlowDict& flows) const { // Flow-conservation constraints for sink nodes size_t num_sink_node_constraints = 0; for (const auto& iter : indices_) { num_sink_node_constraints++; const std::string& flow_id = iter.first; const std::string& node = sink_nodes_.at(flow_id); model.addConstr(flows.sumAcrossSrcNodes(flow_id, node), GRB_EQUAL, 1, ""); } // Debug std::cout << "Finished adding " << num_sink_node_constraints << " flow-conservation constraints for sink nodes." << std::endl; // Flow-conservation constraints for cache nodes size_t num_cache_node_constraints = 0; for (const auto& iter : cache_interval_start_idxs_) { const std::string& flow_id = iter.first; const std::vector<size_t>& start_idxs = iter.second; for (size_t idx : start_idxs) { num_cache_node_constraints++; const std::string& node = cchNodeForMemAt(idx); assert(cache_node_idxs_.find(idx) != cache_node_idxs_.end()); // This is the source node for this flow if (idx == start_idxs.front()) { model.addConstr(flows.sumAcrossDstNodes(flow_id, node), GRB_EQUAL, 1, ""); } // Else, this is a regular node else { model.addConstr(flows.sumAcrossSrcNodes(flow_id, node), GRB_EQUAL, flows.sumAcrossDstNodes(flow_id, node), ""); } } } // Debug std::cout << "Finished adding " << num_cache_node_constraints << " flow-conservation constraints for cache nodes." << std::endl; } /** * Helper method. Given a start idx and cost coefficient (flow fraction), * updates latencies of subsequent same-flow packets that occur within z * timesteps of start_idx. */ void MCMCFSolver:: addMissCostStartingAt(const size_t start_idx, const double coefficient, std::vector<utils::Packet>& packets) const { if (utils::DoubleApproxEqual(coefficient, 0.)) { return; } // Iterate over the next z timesteps, and add the weighted // latency cost to each subsequent packet of the same flow. const std::string& flow_id = trace_[start_idx]; for (size_t offset = 0; offset < z_; offset++) { const size_t idx = start_idx + offset; if (idx >= trace_len_) { break; } else if (trace_[idx] == flow_id) { packets[idx].addLatency((z_ - offset) * coefficient); } } } /** * Returns a (tight) lower-bound on the cost of the LP solution. */ double MCMCFSolver::getCostLowerBound(const belatedly::FlowDict& flows, const std::list<Edge>& edges) const { // Create packets corresponding to each timestep std::vector<utils::Packet> processed_packets; for (const std::string& flow_id : trace_) { processed_packets.push_back(utils::Packet(flow_id)); } // Update the packet latency corresponding // to the first occurence of each flow. for (const auto& elem : indices_) { const size_t src_idx = elem.second.front(); addMissCostStartingAt(src_idx, 1., processed_packets); } // Next, add the latency cost of flow // routed through out-of-cch edges. for (const auto& edge : edges) { const bool in_cache = std::get<1>(edge); const std::string& src = std::get<2>(edge); const std::string& dst = std::get<3>(edge); const std::string& flow_id = std::get<0>(edge); // This is an out-of-cch edge and dst is not a sink node if (!in_cache && dst != sink_nodes_.at(flow_id)) { double flow_fraction = solution_[ flows.getVariableIdx(flow_id, in_cache, src, dst)]; size_t dst_idx = idx_to_nodename_.right.at(dst); addMissCostStartingAt(dst_idx, flow_fraction, processed_packets); } } // Compute the total latency for this solution double total_latency = 0; for (const utils::Packet& packet : processed_packets) { const std::string& flow_id = packet.getFlowId(); const double latency = packet.getTotalLatency(); if (!flow_id.empty()) { // Sanity check: For non-empty packets, latency should be in [0, z] assert(utils::DoubleApproxGreaterThanOrEqual(latency, 0.) && utils::DoubleApproxGreaterThanOrEqual(z_, latency)); total_latency += latency; } // Else, for empty packets, do nothing else { assert(latency == 0.); } } return total_latency; } /** * Validates the computed LP solution. */ double MCMCFSolver::getCostUpperBoundAndValidateSolution( const belatedly::FlowDict& flows, const std::list<Edge>& edges) const { std::vector<std::tuple<size_t, std::string, double>> evictions; std::vector<std::tuple<size_t, std::string, double>> inductions; // Parse the eviction schedule from the computed LP solution bool is_solution_integral = true; size_t num_fractional_vars = 0; for (const auto& edge : edges) { const bool in_cache = std::get<1>(edge); const std::string& flow_id = std::get<0>(edge); // If this is an out-of-cch edge, fetch the // decision variable corresponding to it. if (!in_cache) { const size_t src_idx = idx_to_nodename_.right.at( std::get<2>(edge)) + z_ - 1; const size_t dst_idx = (std::get<3>(edge) == sink_nodes_.at(flow_id)) ? std::numeric_limits<size_t>::max() : idx_to_nodename_.right.at(std::get<3>(edge)) + z_ - 1; double value = solution_[flows.getVariableIdx( flow_id, in_cache, std::get<2>(edge), std::get<3>(edge))]; // The solution has non-integral variables if (!utils::DoubleApproxEqual(value, 1.) && !utils::DoubleApproxEqual(value, 0.)) { is_solution_integral = false; num_fractional_vars++; } // Perform an eviction at this node if (value > 0.) { evictions.push_back(std::make_tuple(src_idx, flow_id, value)); if (dst_idx != std::numeric_limits<size_t>::max()) { inductions.push_back(std::make_tuple(dst_idx, flow_id, value)); } } } } // Populate the inductions list for source nodes for (const auto& item : indices_) { const std::string& flow_id = item.first; const size_t src_idx = item.second.front() + z_ - 1; inductions.push_back(std::make_tuple(src_idx, flow_id, 1.)); } // Sort the eviction schedule std::sort(evictions.begin(), evictions.end(), []( const std::tuple<size_t, std::string, double>& a, const std::tuple<size_t, std::string, double>& b) { return (std::get<0>(a) < std::get<0>(b)); }); // Sort the induction schedule std::sort(inductions.begin(), inductions.end(), []( const std::tuple<size_t, std::string, double>& a, const std::tuple<size_t, std::string, double>& b) { return (std::get<0>(a) < std::get<0>(b)); }); // Debug std::cout << "Solution is " << (is_solution_integral ? "INTEGRAL." : "FRACTIONAL.") << std::endl; // For fractional solutions, output the fraction of non-integer decision variables if (!is_solution_integral) { double percentage_fractional = (num_fractional_vars * 100.) / flows.numVariables(); std::cout << "Warning: Solution has " << num_fractional_vars << " fractional " << "decision variables (" << flows.numVariables() << " in total => " << std::fixed << std::setprecision(2) << percentage_fractional << "%)." << std::endl; } // Finally, run the cache simulator and validate the computed LP solution belatedly::CacheSimulator simulator(packets_file_path_, is_solution_integral, is_forced_, z_, c_, trace_, evictions, inductions); return simulator.run(); } /** * Solve the MCMCF instance for the given trace. */ void MCMCFSolver::solve() { // Populate the internal structs setup(); std::list<Edge> edges; populateOutOfCchEdges(edges); // Create optimization model GRBEnv env = GRBEnv(); GRBModel model = GRBModel(env); belatedly::FlowDict flows = belatedly::FlowDict(model); // If the solution does not already exist, re-run the optimizer bool is_loaded_from_file = loadOptimizedModelSolution(flows); double opt_cost = std::numeric_limits<double>::max(); if (!is_loaded_from_file) { // Create variables, populate constraints createFlowVariables(model, flows, edges); populateCchCapacityConstraints(model, flows); populateSplitNodeFlowConstraints(model, flows); populateFlowConservationConstraints(model, flows); // Compute the optimal solution model.set(GRB_IntAttr_ModelSense, GRB_MINIMIZE); model.set(GRB_DoubleParam_NodefileStart, 5); model.set(GRB_IntParam_Threads, 1); model.set(GRB_IntParam_Method, 1); model.optimize(); // Populate the solution vector int status = model.get(GRB_IntAttr_Status); assert(status == GRB_OPTIMAL); // Sanity check for (size_t idx = 0; idx < flows.numVariables(); idx++) { solution_.push_back(flows.getVariableAt(idx).get(GRB_DoubleAttr_X)); } // Save the optimal solution saveOptimizedModelSolution(flows); // Fetch the optimal cost opt_cost = model.get(GRB_DoubleAttr_ObjVal); for (const auto& iter : indices_) { size_t first_idx = iter.second.front(); opt_cost += idx_to_miss_cost_.at(first_idx); } // Print the cost corresponding to the optimal solution std::cout << "Optimal cost is: " << std::fixed << std::setprecision(3) << opt_cost << std::endl << std::endl; } // Note: This point onwards, we cannot assume that the Gurobi model parameters are // available (since the solution may have been loaded from file). Instead, we use // the flow mappings and the solutions vector in the remainder of the pipeline. double lower_bound = getCostLowerBound(flows, edges); double upper_bound = getCostUpperBoundAndValidateSolution(flows, edges); double delta_percent = ((upper_bound - lower_bound) / lower_bound) * 100; // Debug std::cout << "Lower-bound (LB) on the total latency cost is: " << std::fixed << std::setprecision(3) << lower_bound << "." << std::endl; std::cout << "Upper-bound (UB) on the total latency cost is: " << std::fixed << std::setprecision(3) << upper_bound << " (" << delta_percent << "% worse than LB)." << std::endl << std::endl; // If the model was solved in this instance, also validate the opt_cost if (!is_loaded_from_file) { assert(utils::DoubleApproxEqual(opt_cost, lower_bound, 1e-2)); } } int main(int argc, char **argv) { // Parameters uint z; double c_scale; std::string trace_fp; std::string model_fp; std::string packets_fp; // Program options bopt::variables_map variables; bopt::options_description desc{"BELATEDLY's MCMCF-based solver for" " the Delayed Hits caching problem"}; try { // Command-line arguments desc.add_options() ("help", "Prints this message") ("trace", bopt::value<std::string>(&trace_fp)->required(), "Input trace file path") ("cscale", bopt::value<double>(&c_scale)->required(), "Parameter: Cache size (%Concurrent Flows)") ("zfactor", bopt::value<uint>(&z)->required(), "Parameter: Z") ("model", bopt::value<std::string>(&model_fp)->default_value(""), "[Optional] Output model file prefix (for checkpointing)") ("packets", bopt::value<std::string>(&packets_fp)->default_value(""), "[Optional] Output packets file path") ("forced,f", "[Optional] Use forced admission"); // Parse model parameters bopt::store(bopt::parse_command_line(argc, argv, desc), variables); // Handle help flag if (variables.count("help")) { std::cout << desc << std::endl; return 0; } bopt::notify(variables); } // Flag argument errors catch(const bopt::required_option& e) { std::cerr << "Error: " << e.what() << std::endl; return 1; } catch(...) { std::cerr << "Unknown Error." << std::endl; return 1; } // Use forced admission? bool is_forced = (variables.count("forced") != 0); // Parse the trace file, and compute the absolute cache size std::vector<std::string> trace = utils::parseTrace(trace_fp); size_t num_cfs = utils::getFlowCounts(trace).num_concurrent_flows; uint c = std::max(1u, static_cast<uint>(round((num_cfs * c_scale) / 100.))); // Debug std::cout << "Optimizing trace: " << trace_fp << " (with " << num_cfs << " concurrent flows) using z = " << z << ", c = " << c << ", and " << (is_forced ? "forced" : "optional") << " admission." << std::endl; // Instantiate the solver and optimize MCMCFSolver solver(trace_fp, model_fp, packets_fp, is_forced, z, c, trace); solver.solve(); }
40.397849
146
0.599753
Ahziu
885723fee25f1b0e86d62aea222192c1febd6e59
36,952
cpp
C++
src/fred2/briefingeditordlg.cpp
ptitSeb/freespace2
500ee249f7033aac9b389436b1737a404277259c
[ "Linux-OpenIB" ]
1
2020-07-14T07:29:18.000Z
2020-07-14T07:29:18.000Z
src/fred2/briefingeditordlg.cpp
ptitSeb/freespace2
500ee249f7033aac9b389436b1737a404277259c
[ "Linux-OpenIB" ]
2
2019-01-01T22:35:56.000Z
2022-03-14T07:34:00.000Z
src/fred2/briefingeditordlg.cpp
ptitSeb/freespace2
500ee249f7033aac9b389436b1737a404277259c
[ "Linux-OpenIB" ]
2
2021-03-07T11:40:42.000Z
2021-12-26T21:40:39.000Z
/* * Copyright (C) Volition, Inc. 1999. All rights reserved. * * All source code herein is the property of Volition, Inc. You may not sell * or otherwise commercially exploit the source or things you created based on * the source. */ /* * $Logfile: /Freespace2/code/Fred2/BriefingEditorDlg.cpp $ * $Revision: 110 $ * $Date: 2002-06-09 06:41:30 +0200 (Sun, 09 Jun 2002) $ * $Author: relnev $ * * Briefing editor dialog box class. * * $Log$ * Revision 1.3 2002/06/09 04:41:16 relnev * added copyright header * * Revision 1.2 2002/05/07 03:16:43 theoddone33 * The Great Newline Fix * * Revision 1.1.1.1 2002/05/03 03:28:08 root * Initial import. * * * 9 7/19/99 3:01p Dave * Fixed icons. Added single transport icon. * * 8 7/18/99 5:19p Dave * Jump node icon. Fixed debris fogging. Framerate warning stuff. * * 7 7/09/99 5:54p Dave * Seperated cruiser types into individual types. Added tons of new * briefing icons. Campaign screen. * * 6 5/20/99 1:46p Andsager * Add briefing view copy and paste between stages * * 5 4/23/99 12:01p Johnson * Added SIF_HUGE_SHIP * * 4 11/30/98 5:32p Dave * Fixed up Fred support for software mode. * * 3 10/16/98 4:28p Andsager * Fix fred dependency * * 2 10/07/98 6:28p Dave * Initial checkin. Renamed all relevant stuff to be Fred2 instead of * Fred. Globalized mission and campaign file extensions. Removed Silent * Threat specific code. * * 1 10/07/98 3:02p Dave * * 1 10/07/98 3:00p Dave * * 63 5/21/98 4:20p Dave * Fixed bug with briefing editor when no current stage selected. * * 62 5/21/98 12:58a Hoffoss * Fixed warnings optimized build turned up. * * 61 5/14/98 4:47p Hoffoss * Made it so when you switch to a new team's debriefing (via menu), it * updates the camera position to what it should be for new briefing * stage. * * 60 4/30/98 8:23p John * Fixed some bugs with Fred caused by my new cfile code. * * 59 4/22/98 9:56a Sandeep * * 58 4/20/98 4:40p Hoffoss * Added a button to 4 editors to play the chosen wave file. * * 57 4/16/98 2:49p Johnson * Fixed initialization for new icons in briefing. * * 56 4/07/98 6:32p Dave * Fixed function I forget to change back. * * 55 4/07/98 6:27p Dave * Implemented a more boiler-plate solution to the multiple team briefing * problem in this editor. * * 54 4/07/98 4:51p Dave * (Hoffoss) Fixed a boat load of bugs caused by the new change to * multiple briefings. Allender's code changed to support this in the * briefing editor wasn't quite correct. * * 53 4/06/98 5:37p Hoffoss * Added sexp tree support to briefings in Fred. * * 52 4/06/98 10:43a John * Fixed bugs with inserting/deleting stages * * 51 4/03/98 12:39p Hoffoss * Changed starting directory for browse buttons in several editors. * * 50 4/03/98 11:34a John * Fixed the stuff I broke in Fred from the new breifing * * 49 3/26/98 6:40p Lawrance * Don't store icon text for briefings * * 48 3/21/98 7:36p Lawrance * Move jump nodes to own lib. * * 47 3/19/98 4:24p Hoffoss * Added remaining support for command brief screen (ANI and WAVE file * playing). * * 46 3/17/98 2:00p Hoffoss * Added ability to make an icon from a jump node in briefing editor. * * 45 2/18/98 6:44p Hoffoss * Added support for lines between icons in briefings for Fred. * * 44 2/09/98 9:25p Allender * team v team support. multiple pools and breifings * * 43 2/04/98 4:31p Allender * support for multiple briefings and debriefings. Changes to mission * type (now a bitfield). Bitfield defs for multiplayer modes * * 42 1/28/98 7:19p Lawrance * Get fading/highlighting animations working * * 41 12/28/97 5:52p Lawrance * Add support for debriefing success/fail music. * * 40 11/04/97 4:33p Hoffoss * Made saving keep the current briefing state intact. * * 39 11/04/97 11:31a Duncan * Made make icon button gray if at max icons already. * * 38 11/03/97 4:07p Jasen * Fixed bug in briefing editor caused by changes in TEAM_* defines in the * past and whoever made these changes failed to update this editor along * with it. * * 37 10/19/97 11:32p Hoffoss * Added support for briefing cuts in Fred. * * 36 10/12/97 11:23p Mike * About ten fixes/changes in the docking system. * Also, renamed SIF_REARM_REPAIR to SIF_SUPPORT. * * 35 9/30/97 5:56p Hoffoss * Added music selection combo boxes to Fred. * * $NoKeywords: $ */ #include "stdafx.h" #include <mmsystem.h> #include "fred.h" #include "briefingeditordlg.h" #include "freddoc.h" #include "missionbriefcommon.h" #include "missionparse.h" #include "fredrender.h" #include "management.h" #include "linklist.h" #include "mainfrm.h" #include "bmpman.h" #include "eventmusic.h" #include "starfield.h" #include "jumpnode.h" #include "cfile.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #define ID_MENU 9000 #define NAVBUOY_NAME "Terran NavBuoy" static int Max_icons_for_lines; ///////////////////////////////////////////////////////////////////////////// // briefing_editor_dlg dialog briefing_editor_dlg::briefing_editor_dlg(CWnd* pParent /*=NULL*/) : CDialog(briefing_editor_dlg::IDD, pParent) { int i, z; // figure out max icons we can have with lines to each other less than max allowed lines. // Basically, # lines = (# icons - 1) factorial Max_icons_for_lines = 0; do { i = ++Max_icons_for_lines + 1; z = 0; while (--i) z += i; } while (z < MAX_BRIEF_STAGE_LINES); //{{AFX_DATA_INIT(briefing_editor_dlg) m_hilight = FALSE; m_icon_image = -1; m_icon_label = _T(""); m_stage_title = _T(""); m_text = _T(""); m_time = _T(""); m_voice = _T(""); m_icon_text = _T(""); m_icon_team = -1; m_ship_type = -1; m_change_local = FALSE; m_id = 0; m_briefing_music = -1; m_cut_next = FALSE; m_cut_prev = FALSE; m_current_briefing = -1; //}}AFX_DATA_INIT m_cur_stage = 0; m_last_stage = m_cur_icon = m_last_icon = -1; m_tree.link_modified(&modified); // provide way to indicate trees are modified in dialog // copy view initialization m_copy_view_set = 0; } void briefing_editor_dlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(briefing_editor_dlg) DDX_Control(pDX, IDC_TREE, m_tree); DDX_Control(pDX, IDC_LINES, m_lines); DDX_Check(pDX, IDC_HILIGHT, m_hilight); DDX_CBIndex(pDX, IDC_ICON_IMAGE, m_icon_image); DDX_Text(pDX, IDC_ICON_LABEL, m_icon_label); DDX_Text(pDX, IDC_STAGE_TITLE, m_stage_title); DDX_Text(pDX, IDC_TEXT, m_text); DDX_Text(pDX, IDC_TIME, m_time); DDX_Text(pDX, IDC_VOICE, m_voice); DDX_Text(pDX, IDC_ICON_TEXT, m_icon_text); DDX_CBIndex(pDX, IDC_TEAM, m_icon_team); DDX_CBIndex(pDX, IDC_SHIP_TYPE, m_ship_type); DDX_Check(pDX, IDC_LOCAL, m_change_local); DDX_Text(pDX, IDC_ID, m_id); DDX_CBIndex(pDX, IDC_BRIEFING_MUSIC, m_briefing_music); DDX_Check(pDX, IDC_CUT_NEXT, m_cut_next); DDX_Check(pDX, IDC_CUT_PREV, m_cut_prev); //}}AFX_DATA_MAP DDV_MaxChars(pDX, m_text, MAX_BRIEF_LEN - 1); DDV_MaxChars(pDX, m_voice, MAX_FILENAME_LEN - 1); DDV_MaxChars(pDX, m_icon_label, MAX_LABEL_LEN - 1); DDV_MaxChars(pDX, m_icon_text, MAX_ICON_TEXT_LEN - 1); } BEGIN_MESSAGE_MAP(briefing_editor_dlg, CDialog) //{{AFX_MSG_MAP(briefing_editor_dlg) ON_WM_CLOSE() ON_BN_CLICKED(IDC_NEXT, OnNext) ON_BN_CLICKED(IDC_PREV, OnPrev) ON_BN_CLICKED(IDC_BROWSE, OnBrowse) ON_BN_CLICKED(IDC_ADD_STAGE, OnAddStage) ON_BN_CLICKED(IDC_DELETE_STAGE, OnDeleteStage) ON_BN_CLICKED(IDC_INSERT_STAGE, OnInsertStage) ON_BN_CLICKED(IDC_MAKE_ICON, OnMakeIcon) ON_BN_CLICKED(IDC_DELETE_ICON, OnDeleteIcon) ON_BN_CLICKED(IDC_GOTO_VIEW, OnGotoView) ON_BN_CLICKED(IDC_SAVE_VIEW, OnSaveView) ON_CBN_SELCHANGE(IDC_ICON_IMAGE, OnSelchangeIconImage) ON_CBN_SELCHANGE(IDC_TEAM, OnSelchangeTeam) ON_BN_CLICKED(IDC_PROPAGATE_ICONS, OnPropagateIcons) ON_WM_INITMENU() ON_BN_CLICKED(IDC_LINES, OnLines) ON_NOTIFY(NM_RCLICK, IDC_TREE, OnRclickTree) ON_NOTIFY(TVN_BEGINLABELEDIT, IDC_TREE, OnBeginlabeleditTree) ON_NOTIFY(TVN_ENDLABELEDIT, IDC_TREE, OnEndlabeleditTree) ON_BN_CLICKED(IDC_PLAY, OnPlay) ON_BN_CLICKED(IDC_COPY_VIEW, OnCopyView) ON_BN_CLICKED(IDC_PASTE_VIEW, OnPasteView) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // briefing_editor_dlg message handlers void briefing_editor_dlg::OnInitMenu(CMenu* pMenu) { int i; CMenu *m; // disable any items we should disable m = pMenu->GetSubMenu(0); // uncheck all menu items for (i=0; i<Num_teams; i++) m->CheckMenuItem(i, MF_BYPOSITION | MF_UNCHECKED); for (i=Num_teams; i<MAX_TEAMS; i++) m->EnableMenuItem(i, MF_BYPOSITION | MF_GRAYED); // put a check next to the currently selected item m->CheckMenuItem(m_current_briefing, MF_BYPOSITION | MF_CHECKED ); CDialog::OnInitMenu(pMenu); } void briefing_editor_dlg::create() { int i; CComboBox *box; CDialog::Create(IDD); theApp.init_window(&Briefing_wnd_data, this); box = (CComboBox *) GetDlgItem(IDC_ICON_IMAGE); for (i=0; i<MAX_BRIEF_ICONS; i++) box->AddString(Icon_names[i]); box = (CComboBox *) GetDlgItem(IDC_TEAM); for (i=0; i<Num_team_names; i++) box->AddString(Team_names[i]); box = (CComboBox *) GetDlgItem(IDC_SHIP_TYPE); for (i=0; i<Num_ship_types; i++) box->AddString(Ship_info[i].name); box = (CComboBox *) GetDlgItem(IDC_BRIEFING_MUSIC); box->AddString("None"); for (i=0; i<Num_music_files; i++) box->AddString(Spooled_music[i].name); m_play_bm.LoadBitmap(IDB_PLAY); ((CButton *) GetDlgItem(IDC_PLAY)) -> SetBitmap(m_play_bm); m_current_briefing = 0; Briefing = &Briefings[m_current_briefing]; m_briefing_music = Mission_music[SCORE_BRIEFING] + 1; UpdateData(FALSE); update_data(); OnGotoView(); update_map_window(); } void briefing_editor_dlg::focus_sexp(int select_sexp_node) { int i, n; n = m_tree.select_sexp_node = select_sexp_node; if (n != -1) { for (i=0; i<Briefing->num_stages; i++) if (query_node_in_sexp(n, Briefing->stages[i].formula)) break; if (i < Briefing->num_stages) { m_cur_stage = i; update_data(); GetDlgItem(IDC_TREE) -> SetFocus(); m_tree.hilite_item(m_tree.select_sexp_node); } } } void briefing_editor_dlg::OnOK() { } void briefing_editor_dlg::OnCancel() { OnClose(); } void briefing_editor_dlg::OnClose() { int bs, i, j, s, t, dup = 0; briefing_editor_dlg *ptr; brief_stage *sp; m_cur_stage = -1; update_data(1); for ( bs = 0; bs < Num_teams; bs++ ) { for (s=0; s<Briefing[bs].num_stages; s++) { sp = &Briefing[bs].stages[s]; t = sp->num_icons; for (i=0; i<t-1; i++) for (j=i+1; j<t; j++) { if ((sp->icons[i].id >= 0) && (sp->icons[i].id == sp->icons[j].id)) dup = 1; } } } if (dup) MessageBox("You have duplicate icons names. You should resolve these.", "Warning"); theApp.record_window_data(&Briefing_wnd_data, this); ptr = Briefing_dialog; Briefing_dialog = NULL; delete ptr; } void briefing_editor_dlg::reset_editor() { m_cur_stage = -1; update_data(0); } // some kind of hackish code to get around the problem if saving (which implicitly loads, // which implicitly clears all mission info) not affecting the editor's state at save. void briefing_editor_dlg::save_editor_state() { stage_saved = m_cur_stage; icon_saved = m_cur_icon; } void briefing_editor_dlg::restore_editor_state() { m_cur_stage = stage_saved; m_cur_icon = icon_saved; } void briefing_editor_dlg::update_data(int update) { char buf[MAX_LABEL_LEN], buf2[MAX_ICON_TEXT_LEN], buf3[MAX_BRIEF_LEN]; int i, j, l, lines, count, enable = TRUE, valid = 0, invalid = 0; object *objp; brief_stage *ptr = NULL; if (update) UpdateData(TRUE); // save off current data before we update over it with new briefing stage/team stuff Briefing = save_briefing; Mission_music[SCORE_BRIEFING] = m_briefing_music - 1; if (m_last_stage >= 0) { ptr = &Briefing->stages[m_last_stage]; deconvert_multiline_string(buf3, m_text, MAX_BRIEF_LEN); if (stricmp(ptr->new_text, buf3)) set_modified(); strcpy(ptr->new_text, buf3); MODIFY(ptr->camera_time, atoi(m_time)); string_copy(ptr->voice, m_voice, MAX_FILENAME_LEN, 1); i = ptr->flags; if (m_cut_prev) i |= BS_BACKWARD_CUT; else i &= ~BS_BACKWARD_CUT; if (m_cut_next) i |= BS_FORWARD_CUT; else i &= ~BS_FORWARD_CUT; MODIFY(ptr->flags, i); ptr->formula = m_tree.save_tree(); switch (m_lines.GetCheck()) { case 1: // add lines between every pair of 2 marked icons if there isn't one already. for (i=0; i<ptr->num_icons - 1; i++) for (j=i+1; j<ptr->num_icons; j++) { if ( icon_marked[i] && icon_marked[j] ) { for (l=0; l<ptr->num_lines; l++) if ( ((ptr->lines[l].start_icon == i) && (ptr->lines[l].end_icon == j)) || ((ptr->lines[l].start_icon == j) && (ptr->lines[l].end_icon == i)) ) break; if ((l == ptr->num_lines) && (l < MAX_BRIEF_STAGE_LINES)) { ptr->lines[l].start_icon = i; ptr->lines[l].end_icon = j; ptr->num_lines++; } } } break; case 0: // remove all existing lines between any 2 marked icons i = ptr->num_lines; while (i--) if ( icon_marked[ptr->lines[i].start_icon] && icon_marked[ptr->lines[i].end_icon] ) { ptr->num_lines--; for (l=i; l<ptr->num_lines; l++) ptr->lines[l] = ptr->lines[l + 1]; } break; } if (m_last_icon >= 0) { valid = (m_id != ptr->icons[m_last_icon].id); if (m_id >= 0) { if (valid && !m_change_local) { for (i=m_last_stage+1; i<Briefing->num_stages; i++) { if (find_icon(m_id, i) >= 0) { char msg[1024]; valid = 0; sprintf(msg, "Icon ID #%d is already used in a later stage. You can only\n" "change to that ID locally. Icon ID has been reset back to %d", m_id, ptr->icons[m_last_icon].id); m_id = ptr->icons[m_last_icon].id; MessageBox(msg); break; } } } for (i=0; i<ptr->num_icons; i++) if ((i != m_last_icon) && (ptr->icons[i].id == m_id)) { char msg[1024]; sprintf(msg, "Icon ID #%d is already used in this stage. Icon ID has been reset back to %d", m_id, ptr->icons[m_last_icon].id); m_id = ptr->icons[m_last_icon].id; MessageBox(msg); break; } if (valid && !m_change_local) { set_modified(); reset_icon_loop(m_last_stage); while (get_next_icon(ptr->icons[m_last_icon].id)) iconp->id = m_id; } } ptr->icons[m_last_icon].id = m_id; string_copy(buf, m_icon_label, MAX_LABEL_LEN); if (stricmp(ptr->icons[m_last_icon].label, buf) && !m_change_local) { set_modified(); reset_icon_loop(m_last_stage); while (get_next_icon(m_id)) strcpy(iconp->label, buf); } strcpy(ptr->icons[m_last_icon].label, buf); if ( m_hilight ) ptr->icons[m_last_icon].flags |= BI_HIGHLIGHT; else ptr->icons[m_last_icon].flags &= ~BI_HIGHLIGHT; if ((ptr->icons[m_last_icon].type != m_icon_image) && !m_change_local) { set_modified(); reset_icon_loop(m_last_stage); while (get_next_icon(m_id)) iconp->type = m_icon_image; } ptr->icons[m_last_icon].type = m_icon_image; if ((ptr->icons[m_last_icon].team != (1 << m_icon_team)) && !m_change_local) { set_modified(); reset_icon_loop(m_last_stage); while (get_next_icon(m_id)) iconp->team = (1 << m_icon_team); } ptr->icons[m_last_icon].team = (1 << m_icon_team); if ((ptr->icons[m_last_icon].ship_class != m_ship_type) && !m_change_local) { set_modified(); reset_icon_loop(m_last_stage); while (get_next_icon(m_id)) iconp->ship_class = m_ship_type; } MODIFY(ptr->icons[m_last_icon].ship_class, m_ship_type); deconvert_multiline_string(buf2, m_icon_text, MAX_ICON_TEXT_LEN); /* if (stricmp(ptr->icons[m_last_icon].text, buf2) && !m_change_local) { set_modified(); reset_icon_loop(m_last_stage); while (get_next_icon(m_id)) strcpy(iconp->text, buf2); } strcpy(ptr->icons[m_last_icon].text, buf2); */ } } if (!::IsWindow(m_hWnd)) return; // set briefing pointer to correct team Briefing = &Briefings[m_current_briefing]; if ((m_cur_stage >= 0) && (m_cur_stage < Briefing->num_stages)) { ptr = &Briefing->stages[m_cur_stage]; m_stage_title.Format("Stage %d of %d", m_cur_stage + 1, Briefing->num_stages); m_text = convert_multiline_string(ptr->new_text); m_time.Format("%d", ptr->camera_time); m_voice = ptr->voice; m_cut_prev = (ptr->flags & BS_BACKWARD_CUT) ? 1 : 0; m_cut_next = (ptr->flags & BS_FORWARD_CUT) ? 1 : 0; m_tree.load_tree(ptr->formula); } else { m_stage_title = _T("No stages"); m_text = _T(""); m_time = _T(""); m_voice = _T(""); m_cut_prev = m_cut_next = 0; m_tree.clear_tree(); enable = FALSE; m_cur_stage = -1; } if (m_cur_stage == Briefing->num_stages - 1) GetDlgItem(IDC_NEXT) -> EnableWindow(FALSE); else GetDlgItem(IDC_NEXT) -> EnableWindow(enable); if (m_cur_stage) GetDlgItem(IDC_PREV) -> EnableWindow(enable); else GetDlgItem(IDC_PREV) -> EnableWindow(FALSE); if (Briefing->num_stages >= MAX_BRIEF_STAGES) GetDlgItem(IDC_ADD_STAGE) -> EnableWindow(FALSE); else GetDlgItem(IDC_ADD_STAGE) -> EnableWindow(TRUE); if (Briefing->num_stages) { GetDlgItem(IDC_DELETE_STAGE) -> EnableWindow(enable); GetDlgItem(IDC_INSERT_STAGE) -> EnableWindow(enable); } else { GetDlgItem(IDC_DELETE_STAGE) -> EnableWindow(FALSE); GetDlgItem(IDC_INSERT_STAGE) -> EnableWindow(FALSE); } GetDlgItem(IDC_TIME) -> EnableWindow(enable); GetDlgItem(IDC_VOICE) -> EnableWindow(enable); GetDlgItem(IDC_BROWSE) -> EnableWindow(enable); GetDlgItem(IDC_TEXT) -> EnableWindow(enable); GetDlgItem(IDC_SAVE_VIEW) -> EnableWindow(enable); GetDlgItem(IDC_GOTO_VIEW) -> EnableWindow(enable); GetDlgItem(IDC_CUT_PREV) -> EnableWindow(enable); GetDlgItem(IDC_CUT_NEXT) -> EnableWindow(enable); GetDlgItem(IDC_TREE) -> EnableWindow(enable); GetDlgItem(IDC_PLAY) -> EnableWindow(enable); if ((m_cur_stage >= 0) && (m_cur_icon >= 0) && (m_cur_icon < ptr->num_icons)) { m_hilight = (ptr->icons[m_cur_icon].flags & BI_HIGHLIGHT)?1:0; m_icon_image = ptr->icons[m_cur_icon].type; m_icon_team = bitmask_2_bitnum(ptr->icons[m_cur_icon].team); m_icon_label = ptr->icons[m_cur_icon].label; m_ship_type = ptr->icons[m_cur_icon].ship_class; // m_icon_text = convert_multiline_string(ptr->icons[m_cur_icon].text); m_id = ptr->icons[m_cur_icon].id; enable = TRUE; } else { m_hilight = FALSE; m_icon_image = -1; m_icon_team = -1; m_ship_type = -1; m_icon_label = _T(""); m_cur_icon = -1; m_id = 0; enable = FALSE; } GetDlgItem(IDC_ICON_TEXT) -> EnableWindow(enable); GetDlgItem(IDC_ICON_LABEL) -> EnableWindow(enable); GetDlgItem(IDC_ICON_IMAGE) -> EnableWindow(enable); GetDlgItem(IDC_SHIP_TYPE) -> EnableWindow(enable); GetDlgItem(IDC_HILIGHT) -> EnableWindow(enable); GetDlgItem(IDC_TEAM) -> EnableWindow(enable); GetDlgItem(IDC_ID) -> EnableWindow(enable); GetDlgItem(IDC_DELETE_ICON) -> EnableWindow(enable); valid = invalid = 0; objp = GET_FIRST(&obj_used_list); while (objp != END_OF_LIST(&obj_used_list)) { if (objp->flags & OF_MARKED) { if ((objp->type == OBJ_SHIP) || (objp->type == OBJ_START) || (objp->type == OBJ_WAYPOINT) || (objp->type == OBJ_JUMP_NODE)) valid = 1; else invalid = 1; } objp = GET_NEXT(objp); } if (m_cur_stage >= 0) ptr = &Briefing->stages[m_cur_stage]; if (valid && !invalid && (m_cur_stage >= 0) && (ptr->num_icons < MAX_STAGE_ICONS)) GetDlgItem(IDC_MAKE_ICON) -> EnableWindow(TRUE); else GetDlgItem(IDC_MAKE_ICON) -> EnableWindow(FALSE); if (m_cur_stage >= 0) for (i=0; i<ptr->num_icons; i++) icon_marked[i] = 0; valid = invalid = 0; objp = GET_FIRST(&obj_used_list); while (objp != END_OF_LIST(&obj_used_list)) { if (objp->flags & OF_MARKED) { if (objp->type == OBJ_POINT) { valid++; icon_marked[objp->instance] = 1; } else invalid++; } objp = GET_NEXT(objp); } if (valid && !invalid && (m_cur_stage >= 0)) GetDlgItem(IDC_PROPAGATE_ICONS) -> EnableWindow(TRUE); else GetDlgItem(IDC_PROPAGATE_ICONS) -> EnableWindow(FALSE); count = 0; lines = 1; // default lines checkbox to checked if (m_cur_stage >= 0) { for (i=0; i<ptr->num_lines; i++) line_marked[i] = 0; // go through and locate all lines between marked icons for (i=0; i<ptr->num_icons - 1; i++) for (j=i+1; j<ptr->num_icons; j++) { if ( icon_marked[i] && icon_marked[j] ) { for (l=0; l<ptr->num_lines; l++) if ( ((ptr->lines[l].start_icon == i) && (ptr->lines[l].end_icon == j)) || ((ptr->lines[l].start_icon == j) && (ptr->lines[l].end_icon == i)) ) { line_marked[l] = 1; count++; // track number of marked lines (lines between 2 icons that are both marked) break; } // at least 1 line missing between 2 marked icons, so use mixed state if (l == ptr->num_lines) lines = 2; } } } // not even 1 line between any 2 marked icons? Set checkbox to unchecked. if (!count) lines = 0; i = 0; if (m_cur_stage >= 0){ i = calc_num_lines_for_icons(valid) + ptr->num_lines - count; } if ((valid > 1) && !invalid && (m_cur_stage >= 0) && (i <= MAX_BRIEF_STAGE_LINES)) GetDlgItem(IDC_LINES) -> EnableWindow(TRUE); else GetDlgItem(IDC_LINES) -> EnableWindow(FALSE); m_lines.SetCheck(lines); UpdateData(FALSE); if ((m_last_stage != m_cur_stage) || (Briefing != save_briefing)) { if (m_last_stage >= 0) { for (i=0; i<save_briefing->stages[m_last_stage].num_icons; i++) { // save positions of all icons, in case they have moved save_briefing->stages[m_last_stage].icons[i].pos = Objects[icon_obj[i]].pos; // release objects being used by last stage obj_delete(icon_obj[i]); } } if (m_cur_stage >= 0) { for (i=0; i<ptr->num_icons; i++) { // create an object for each icon for display/manipulation purposes icon_obj[i] = obj_create(OBJ_POINT, -1, i, NULL, &ptr->icons[i].pos, 0.0f, OF_RENDERS); } obj_merge_created_list(); } m_last_stage = m_cur_stage; } m_last_icon = m_cur_icon; Update_window = 1; save_briefing = Briefing; } // Given a number of icons, figure out how many lines would be required to connect each one // with all of the others. // int briefing_editor_dlg::calc_num_lines_for_icons(int num) { int lines = 0; if (num < 2) return 0; // Basically, this is # lines = (# icons - 1) factorial while (--num) lines += num; return lines; } void briefing_editor_dlg::OnNext() { m_cur_stage++; m_cur_icon = -1; update_data(); OnGotoView(); } void briefing_editor_dlg::OnPrev() { m_cur_stage--; m_cur_icon = -1; update_data(); OnGotoView(); } void briefing_editor_dlg::OnBrowse() { int z; CString name; UpdateData(TRUE); if (The_mission.game_type & MISSION_TYPE_TRAINING) z = cfile_push_chdir(CF_TYPE_VOICE_TRAINING); else z = cfile_push_chdir(CF_TYPE_VOICE_BRIEFINGS); CFileDialog dlg(TRUE, "wav", NULL, OFN_HIDEREADONLY | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR, "Wave Files (*.wav)|*.wav||"); if (dlg.DoModal() == IDOK) { m_voice = dlg.GetFileName(); UpdateData(FALSE); } if (!z) cfile_pop_dir(); } void briefing_editor_dlg::OnAddStage() { int i; if (Briefing->num_stages >= MAX_BRIEF_STAGES) return; m_cur_stage = i = Briefing->num_stages++; copy_stage(i - 1, i); update_data(1); } void briefing_editor_dlg::OnDeleteStage() { int i, z; if (m_cur_stage < 0) return; Assert(Briefing->num_stages); z = m_cur_stage; m_cur_stage = -1; update_data(1); for (i=z+1; i<Briefing->num_stages; i++) { copy_stage(i, i-1); } Briefing->num_stages--; m_cur_stage = z; if (m_cur_stage >= Briefing->num_stages) m_cur_stage = Briefing->num_stages - 1; update_data(0); } void briefing_editor_dlg::draw_icon(object *objp) { if (m_cur_stage < 0) return; brief_render_icon(m_cur_stage, objp->instance, 1.0f/30.0f, objp->flags & OF_MARKED, (float) True_rw / BRIEF_GRID_W, (float) True_rh / BRIEF_GRID_H); } void briefing_editor_dlg::batch_render() { int i, num_lines; if (m_cur_stage < 0) return; num_lines = Briefing->stages[m_cur_stage].num_lines; for (i=0; i<num_lines; i++) brief_render_icon_line(m_cur_stage, i); } void briefing_editor_dlg::icon_select(int num) { m_cur_icon = num; update_data(1); } void briefing_editor_dlg::OnInsertStage() { int i, z; if (Briefing->num_stages >= MAX_BRIEF_STAGES) return; if (!Briefing->num_stages) { OnAddStage(); return; } z = m_cur_stage; m_cur_stage = -1; update_data(1); for (i=Briefing->num_stages; i>z; i--) { copy_stage(i-1, i); } Briefing->num_stages++; copy_stage(z, z + 1); m_cur_stage = z; update_data(0); } void briefing_editor_dlg::copy_stage(int from, int to) { if ((from < 0) || (from >= Briefing->num_stages)) { strcpy(Briefing->stages[to].new_text, "<Text here>"); strcpy(Briefing->stages[to].voice, "none.wav"); Briefing->stages[to].camera_pos = view_pos; Briefing->stages[to].camera_orient = view_orient; Briefing->stages[to].camera_time = 500; Briefing->stages[to].num_icons = 0; Briefing->stages[to].formula = Locked_sexp_true; return; } // Copy all the data in the stage structure. strcpy( Briefing->stages[to].new_text, Briefing->stages[from].new_text ); strcpy( Briefing->stages[to].voice, Briefing->stages[from].voice ); Briefing->stages[to].camera_pos = Briefing->stages[from].camera_pos; Briefing->stages[to].camera_orient = Briefing->stages[from].camera_orient; Briefing->stages[to].camera_time = Briefing->stages[from].camera_time; Briefing->stages[to].flags = Briefing->stages[from].flags; Briefing->stages[to].num_icons = Briefing->stages[from].num_icons; Briefing->stages[to].num_lines = Briefing->stages[from].num_lines; Briefing->stages[to].formula = Briefing->stages[from].formula; memmove( Briefing->stages[to].icons, Briefing->stages[from].icons, sizeof(brief_icon)*MAX_STAGE_ICONS ); memmove( Briefing->stages[to].lines, Briefing->stages[from].lines, sizeof(brief_line)*MAX_BRIEF_STAGE_LINES ); } void briefing_editor_dlg::update_positions() { int i, s, z; vector v1, v2; if (m_cur_stage < 0) return; for (i=0; i<Briefing->stages[m_cur_stage].num_icons; i++) { v1 = Briefing->stages[m_cur_stage].icons[i].pos; v2 = Objects[icon_obj[i]].pos; if ((v1.x != v2.x) || (v1.y != v2.y) || (v1.z != v2.z)) { Briefing->stages[m_cur_stage].icons[i].pos = Objects[icon_obj[i]].pos; if (!m_change_local) // propagate changes through rest of stages.. for (s=m_cur_stage+1; s<Briefing->num_stages; s++) { z = find_icon(Briefing->stages[m_cur_stage].icons[i].id, s); if (z >= 0) Briefing->stages[s].icons[z].pos = Objects[icon_obj[i]].pos; } } } } void briefing_editor_dlg::OnMakeIcon() { char *name; int z, len, team, ship, waypoint, jump_node, count = -1; int cargo = 0, cargo_count = 0, freighter_count = 0; object *ptr; vector min, max, pos; brief_icon *iconp; if (Briefing->stages[m_cur_stage].num_icons >= MAX_STAGE_ICONS) return; m_cur_icon = Briefing->stages[m_cur_stage].num_icons++; iconp = &Briefing->stages[m_cur_stage].icons[m_cur_icon]; ship = waypoint = jump_node = -1; team = TEAM_FRIENDLY; vm_vec_make(&min, 9e19f, 9e19f, 9e19f); vm_vec_make(&max, -9e19f, -9e19f, -9e19f); ptr = GET_FIRST(&obj_used_list); while (ptr != END_OF_LIST(&obj_used_list)) { if (ptr->flags & OF_MARKED) { if (ptr->pos.x < min.x) min.x = ptr->pos.x; if (ptr->pos.x > max.x) max.x = ptr->pos.x; if (ptr->pos.y < min.y) min.y = ptr->pos.y; if (ptr->pos.y > max.y) max.y = ptr->pos.y; if (ptr->pos.z < min.z) min.z = ptr->pos.z; if (ptr->pos.z > max.z) max.z = ptr->pos.z; switch (ptr->type) { case OBJ_SHIP: case OBJ_START: ship = ptr->instance; break; case OBJ_WAYPOINT: waypoint = ptr->instance; break; case OBJ_JUMP_NODE: jump_node = ptr->instance; break; default: Int3(); } if (ship >= 0) { team = Ships[ship].team; z = ship_query_general_type(ship); if (z == SHIP_TYPE_CARGO) cargo_count++; if (z == SHIP_TYPE_FREIGHTER) { z = Ai_info[Ships[ship].ai_index].dock_objnum; if (z) { // docked with anything? if ((Objects[z].flags & OF_MARKED) && (Objects[z].type == OBJ_SHIP)) { if (ship_query_general_type(Objects[z].instance) == SHIP_TYPE_CARGO) freighter_count++; } } } } count++; } ptr = GET_NEXT(ptr); } if (cargo_count && cargo_count == freighter_count) cargo = 1; vm_vec_avg(&pos, &min, &max); if (ship >= 0) name = Ships[ship].ship_name; else if (waypoint >= 0) name = Waypoint_lists[waypoint / 65536].name; else if (jump_node >= 0) name = Jump_nodes[jump_node].name; else return; len = strlen(name); if (len >= MAX_LABEL_LEN - 1) len = MAX_LABEL_LEN - 1; strncpy(iconp->label, name, len); iconp->label[len] = 0; // iconp->text[0] = 0; iconp->type = 0; iconp->team = team; iconp->pos = pos; iconp->flags = 0; iconp->id = Cur_brief_id++; if (ship >= 0) { iconp->ship_class = Ships[ship].ship_info_index; switch (Ship_info[Ships[ship].ship_info_index].flags & SIF_ALL_SHIP_TYPES) { case SIF_KNOSSOS_DEVICE: iconp->type = ICON_KNOSSOS_DEVICE; break; case SIF_CORVETTE: iconp->type = ICON_CORVETTE; break; case SIF_GAS_MINER: iconp->type = ICON_GAS_MINER; break; case SIF_SUPERCAP: iconp->type = ICON_SUPERCAP; break; case SIF_SENTRYGUN: iconp->type = ICON_SENTRYGUN; break; case SIF_AWACS: iconp->type = ICON_AWACS; break; case SIF_CARGO: if (cargo) iconp->type = (count == 1) ? ICON_FREIGHTER_WITH_CARGO : ICON_FREIGHTER_WING_WITH_CARGO; else iconp->type = count ? ICON_CARGO_WING : ICON_CARGO; break; case SIF_SUPPORT: iconp->type = ICON_SUPPORT_SHIP; break; case SIF_FIGHTER: iconp->type = count ? ICON_FIGHTER_WING : ICON_FIGHTER; break; case SIF_BOMBER: iconp->type = count ? ICON_BOMBER_WING : ICON_BOMBER; break; case SIF_FREIGHTER: if (cargo) iconp->type = (count == 1) ? ICON_FREIGHTER_WITH_CARGO : ICON_FREIGHTER_WING_WITH_CARGO; else iconp->type = count ? ICON_FREIGHTER_WING_NO_CARGO : ICON_FREIGHTER_NO_CARGO; break; case SIF_CRUISER: iconp->type = count ? ICON_CRUISER_WING : ICON_CRUISER; break; case SIF_TRANSPORT: iconp->type = count ? ICON_TRANSPORT_WING : ICON_TRANSPORT; break; case SIF_CAPITAL: case SIF_DRYDOCK: iconp->type = ICON_CAPITAL; break; default: if (Ships[ship].ship_info_index == ship_info_lookup(NAVBUOY_NAME)) iconp->type = ICON_WAYPOINT; else iconp->type = ICON_ASTEROID_FIELD; break; } } // jumpnodes else if(jump_node >= 0){ iconp->ship_class = ship_info_lookup(NAVBUOY_NAME); iconp->type = ICON_JUMP_NODE; } // everything else else { iconp->ship_class = ship_info_lookup(NAVBUOY_NAME); iconp->type = ICON_WAYPOINT; } if (!m_change_local){ propagate_icon(m_cur_icon); } icon_obj[m_cur_icon] = obj_create(OBJ_POINT, -1, m_cur_icon, NULL, &pos, 0.0f, OF_RENDERS); Assert(icon_obj[m_cur_icon] >= 0); obj_merge_created_list(); unmark_all(); set_cur_object_index(icon_obj[m_cur_icon]); GetDlgItem(IDC_MAKE_ICON) -> EnableWindow(FALSE); GetDlgItem(IDC_PROPAGATE_ICONS) -> EnableWindow(TRUE); update_data(1); } void briefing_editor_dlg::OnDeleteIcon() { delete_icon(m_cur_icon); } void briefing_editor_dlg::delete_icon(int num) { int i, z; if (num < 0) num = m_cur_icon; if (num < 0) return; Assert(m_cur_stage >= 0); Assert(Briefing->stages[m_cur_stage].num_icons); z = m_cur_icon; if (z == num) z = -1; if (z > num) z--; m_cur_icon = -1; update_data(1); obj_delete(icon_obj[num]); for (i=num+1; i<Briefing->stages[m_cur_stage].num_icons; i++) { Briefing->stages[m_cur_stage].icons[i-1] = Briefing->stages[m_cur_stage].icons[i]; icon_obj[i-1] = icon_obj[i]; Objects[icon_obj[i-1]].instance = i - 1; } Briefing->stages[m_cur_stage].num_icons--; if (z >= 0) { m_cur_icon = z; update_data(0); } } void briefing_editor_dlg::OnGotoView() { if (m_cur_stage < 0) return; view_pos = Briefing->stages[m_cur_stage].camera_pos; view_orient = Briefing->stages[m_cur_stage].camera_orient; Update_window = 1; } void briefing_editor_dlg::OnSaveView() { if (m_cur_stage < 0) return; Briefing->stages[m_cur_stage].camera_pos = view_pos; Briefing->stages[m_cur_stage].camera_orient = view_orient; } void briefing_editor_dlg::OnSelchangeIconImage() { update_data(1); } void briefing_editor_dlg::OnSelchangeTeam() { update_data(1); } int briefing_editor_dlg::check_mouse_hit(int x, int y) { int i; brief_icon *ptr; if (m_cur_stage < 0) return -1; for (i=0; i<Briefing->stages[m_cur_stage].num_icons; i++) { ptr = &Briefing->stages[m_cur_stage].icons[i]; if ((x > ptr->x) && (x < ptr->x + ptr->w) && (y > ptr->y) && (y < ptr->y + ptr->h)) { return icon_obj[i]; } } return -1; } void briefing_editor_dlg::OnPropagateIcons() { object *ptr; ptr = GET_FIRST(&obj_used_list); while (ptr != END_OF_LIST(&obj_used_list)) { if ((ptr->type == OBJ_POINT) && (ptr->flags & OF_MARKED)) { propagate_icon(ptr->instance); } ptr = GET_NEXT(ptr); } } void briefing_editor_dlg::propagate_icon(int num) { int i, s; for (s=m_cur_stage+1; s<Briefing->num_stages; s++) { i = Briefing->stages[s].num_icons; if (i >= MAX_STAGE_ICONS) continue; if (find_icon(Briefing->stages[m_cur_stage].icons[num].id, s) >= 0) continue; // don't change if icon exists here already. Briefing->stages[s].icons[i] = Briefing->stages[m_cur_stage].icons[num]; Briefing->stages[s].num_icons++; } } int briefing_editor_dlg::find_icon(int id, int stage) { int i; if (id >= 0) for (i=0; i<Briefing->stages[stage].num_icons; i++) if (Briefing->stages[stage].icons[i].id == id) return i; return -1; } void briefing_editor_dlg::reset_icon_loop(int stage) { stage_loop = stage + 1; icon_loop = -1; } int briefing_editor_dlg::get_next_icon(int id) { while (1) { icon_loop++; if (icon_loop >= Briefing->stages[stage_loop].num_icons) { stage_loop++; if (stage_loop > Briefing->num_stages) return 0; icon_loop = -1; continue; } iconp = &Briefing->stages[stage_loop].icons[icon_loop]; if ((id >= 0) && (iconp->id == id)) return 1; } } BOOL briefing_editor_dlg::OnCommand(WPARAM wParam, LPARAM lParam) { int id; // deal with figuring out menu stuff id = LOWORD(wParam); if ( (id >= ID_TEAM_1) && (id < ID_TEAM_3) ) { m_current_briefing = id - ID_TEAM_1; // put user back at first stage for this team (or no current stage is there are none). Briefing = &Briefings[m_current_briefing]; if ( Briefing->num_stages > 0 ) m_cur_stage = 0; else m_cur_stage = -1; update_data(1); OnGotoView(); return 1; } return CDialog::OnCommand(wParam, lParam); } void briefing_editor_dlg::OnLines() { if (m_lines.GetCheck() == 1) m_lines.SetCheck(0); else m_lines.SetCheck(1); update_data(1); } void briefing_editor_dlg::OnRclickTree(NMHDR* pNMHDR, LRESULT* pResult) { m_tree.right_clicked(); *pResult = 0; } void briefing_editor_dlg::OnBeginlabeleditTree(NMHDR* pNMHDR, LRESULT* pResult) { TV_DISPINFO* pTVDispInfo = (TV_DISPINFO*)pNMHDR; if (m_tree.edit_label(pTVDispInfo->item.hItem) == 1) { *pResult = 0; modified = 1; } else *pResult = 1; } void briefing_editor_dlg::OnEndlabeleditTree(NMHDR* pNMHDR, LRESULT* pResult) { TV_DISPINFO* pTVDispInfo = (TV_DISPINFO*)pNMHDR; *pResult = m_tree.end_label_edit(pTVDispInfo->item.hItem, pTVDispInfo->item.pszText); } BOOL briefing_editor_dlg::DestroyWindow() { m_play_bm.DeleteObject(); return CDialog::DestroyWindow(); } void briefing_editor_dlg::OnPlay() { char path[MAX_PATH_LEN + 1]; GetDlgItem(IDC_VOICE)->GetWindowText(m_voice); int size, offset; cf_find_file_location((char *) (LPCSTR) m_voice, CF_TYPE_ANY, path, &size, &offset ); PlaySound(path, NULL, SND_ASYNC | SND_FILENAME); } void briefing_editor_dlg::OnCopyView() { // TODO: Add your control notification handler code here m_copy_view_set = 1; m_copy_view_pos = view_pos; m_copy_view_orient = view_orient; } void briefing_editor_dlg::OnPasteView() { // TODO: Add your control notification handler code here if (m_cur_stage < 0) return; if (m_copy_view_set == 0) { MessageBox("No view set", "Unable to copy view"); } else { Briefing->stages[m_cur_stage].camera_pos = m_copy_view_pos; Briefing->stages[m_cur_stage].camera_orient = m_copy_view_orient; update_data(1); OnGotoView(); } }
25.519337
151
0.675227
ptitSeb
885de00c45ededb4aef602920d57ebefdf333fbd
768
hpp
C++
Jackal/Source/RenderDevice/Public/RenderDevice/TextureCubeMap.hpp
CheezBoiger/Jackal
6c87bf19f6c1cd63f53c815820b32fc71b48bf77
[ "MIT" ]
null
null
null
Jackal/Source/RenderDevice/Public/RenderDevice/TextureCubeMap.hpp
CheezBoiger/Jackal
6c87bf19f6c1cd63f53c815820b32fc71b48bf77
[ "MIT" ]
null
null
null
Jackal/Source/RenderDevice/Public/RenderDevice/TextureCubeMap.hpp
CheezBoiger/Jackal
6c87bf19f6c1cd63f53c815820b32fc71b48bf77
[ "MIT" ]
null
null
null
// Copyright (c) 2017 Jackal Engine, MIT License. #pragma once #include "Core/Platform/JTypes.hpp" #include "Core/Structure/JString.hpp" #include "Core/Utility/TextureLoader.hpp" #include "RenderDeviceTypes.hpp" #include "RenderObject.hpp" namespace jackal { // CubeMap Texture object. class CubeMap : public RenderObject { protected: CubeMap() { } public: virtual ~CubeMap() { } TextureT TextureType() { static const TextureT type = TEXTURE_CUBE; return type; } // Load textures into this texture object, for use in the rendering // api. Must load 6 faces, or texture handles. // The order of the handles must be: // virtual void Load(TextureInfoT &info, TextureHandle *textures) = 0; virtual void CleanUp() = 0; }; } // jackal
20.210526
69
0.705729
CheezBoiger
8866263f42cea726dfa486f18f253b776670aa6a
1,278
cpp
C++
daily_challenge/September_LeetCoding_Challenge_2021/minimizeDistanceToGasStation.cpp
archit-1997/LeetCode
7c0f74da0836d3b0855f09bae8960f81a384f3f3
[ "MIT" ]
1
2021-01-27T16:37:36.000Z
2021-01-27T16:37:36.000Z
daily_challenge/September_LeetCoding_Challenge_2021/minimizeDistanceToGasStation.cpp
archit-1997/LeetCode
7c0f74da0836d3b0855f09bae8960f81a384f3f3
[ "MIT" ]
null
null
null
daily_challenge/September_LeetCoding_Challenge_2021/minimizeDistanceToGasStation.cpp
archit-1997/LeetCode
7c0f74da0836d3b0855f09bae8960f81a384f3f3
[ "MIT" ]
null
null
null
/** * @author : archit * @GitHub : archit-1997 * @Email : [email protected] * @file : minimizeDistanceToGasStation.cpp * @created : Saturday Sep 18, 2021 02:17:22 IST */ #include <bits/stdc++.h> using namespace std; #define ll long long #define P pair<int,int> void init(){ freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); } class Solution { public: bool isPossible(vector<int> &nums,int k,double gap){ int count=0,n=nums.size(); for(int i=0;i<n-1;i++){ int val=(int)((nums[i+1]-nums[i])/gap); count+=val; } return count<=k; } double minmaxGasDist(vector<int>& stations, int k) { //we will use binary search to find the smallest possible value of distance int n=stations.size(); double l=0,r=stations[n-1]-stations[0]; //while the distance gap between the adjacent values is < 1e-6 double ans=INT_MAX; while(r-l>1e-6){ double m=l+(r-l)/2; //check if can have k stations with this gap if(isPossible(stations,k,m)){ ans=min(ans,m); r=m; } else l=m; } return ans; } };
23.666667
83
0.536776
archit-1997
88671c98ae280e3f980ab324078c10e768fd8152
304
cpp
C++
codeforces/codeforces_100_days/B/2.cpp
shivanshu-semwal/competitive-programming
b1c7fe1f9d5807fff47890267cc9936c9ff95f58
[ "MIT" ]
1
2021-09-24T03:57:42.000Z
2021-09-24T03:57:42.000Z
codeforces/codeforces_100_days/B/2.cpp
shivanshu-semwal/competitive-programming
b1c7fe1f9d5807fff47890267cc9936c9ff95f58
[ "MIT" ]
null
null
null
codeforces/codeforces_100_days/B/2.cpp
shivanshu-semwal/competitive-programming
b1c7fe1f9d5807fff47890267cc9936c9ff95f58
[ "MIT" ]
null
null
null
// https://codeforces.com/problemset/problem/734/B #include <iostream> using namespace std; int main() { long k2, k3, k5, k6; cin >> k2 >> k3 >> k5 >> k6; long min1 = std::min(k2, min(k5, k6)); long long int ans = min1 * 256 + min(k2 - min1, k3) * 32; cout << ans; return 0; }
20.266667
61
0.565789
shivanshu-semwal
886c4cd447dee614e0df4c02fbf260fdb26218e9
1,201
hpp
C++
include/caffe/util/parallel.hpp
whitenightwu/caffe-quant-TI
df1551f184d9d5e850650af0e7a68206d09cea2d
[ "MIT" ]
2
2019-06-06T13:15:46.000Z
2019-06-20T08:14:45.000Z
include/caffe/util/parallel.hpp
whitenightwu/caffe-quant-TI
df1551f184d9d5e850650af0e7a68206d09cea2d
[ "MIT" ]
null
null
null
include/caffe/util/parallel.hpp
whitenightwu/caffe-quant-TI
df1551f184d9d5e850650af0e7a68206d09cea2d
[ "MIT" ]
1
2020-03-24T02:04:59.000Z
2020-03-24T02:04:59.000Z
/** * TI C++ Reference software for Computer Vision Algorithms (TICV) * TICV is a software module developed to model computer vision * algorithms on TI's various platforms/SOCs. * * Copyright (C) 2016 Texas Instruments Incorporated - http://www.ti.com/ * ALL RIGHTS RESERVED */ /** * @file: parallel.h * @brief: Implements Parallel Thread Processing */ #pragma once #include <functional> namespace caffe { typedef std::function<void(int)> ParalelForExecutorFunc; class ParallelForFunctor: public cv::ParallelLoopBody { public: ParallelForFunctor(ParalelForExecutorFunc func) : execFunc(func) { } void operator()(const cv::Range &range) const { for (int i = range.start; i < range.end; i++) { execFunc(i); } } ParalelForExecutorFunc execFunc; }; static inline void ParallelFor(int start, int endPlus1, ParalelForExecutorFunc func, int nthreads = -1) { if (nthreads == 1) { for (int i = start; i < endPlus1; i++) { func(i); } } else { cv::Range range(start, endPlus1); ParallelForFunctor functor(func); cv::parallel_for_(range, functor, nthreads); } } }
24.510204
105
0.642798
whitenightwu
8872a557b0e6db1a52000ce44d6176f8cd4af1dd
3,055
hpp
C++
include/espadin/comments_group.hpp
mexicowilly/Espadin
f33580d2c77c5efe92c05de0816ec194e87906f0
[ "Apache-2.0" ]
null
null
null
include/espadin/comments_group.hpp
mexicowilly/Espadin
f33580d2c77c5efe92c05de0816ec194e87906f0
[ "Apache-2.0" ]
null
null
null
include/espadin/comments_group.hpp
mexicowilly/Espadin
f33580d2c77c5efe92c05de0816ec194e87906f0
[ "Apache-2.0" ]
null
null
null
#if !defined(ESPADIN_COMMENTS_GROUP_HPP_) #define ESPADIN_COMMENTS_GROUP_HPP_ #include <espadin/comment.hpp> #include <memory> namespace espadin { class ESPADIN_EXPORT comments_group { public: class create_interface { public: virtual ~create_interface() = default; virtual std::unique_ptr<comment> run() = 0; virtual create_interface& anchor(const std::string& str) = 0; virtual create_interface& quoted_file_content(const std::string& str) = 0; }; class delete_interface { public: virtual ~delete_interface() = default; virtual void run() = 0; }; class get_interface { public: virtual ~get_interface() = default; virtual std::unique_ptr<comment> run() = 0; }; class list_interface { public: class reply { public: reply(const cJSON& json); const std::optional<std::vector<comment>>& comments() const; const std::optional<std::string>& kind() const; const std::optional<std::string>& next_page_token() const; private: std::optional<std::string> kind_; std::optional<std::string> next_page_token_; std::optional<std::vector<comment>> comments_; }; virtual ~list_interface() = default; virtual list_interface& include_deleted(bool to_set) = 0; virtual list_interface& page_size(std::size_t num) = 0; virtual list_interface& page_token(const std::string& tok) = 0; virtual std::unique_ptr<reply> run() = 0; virtual list_interface& start_modified_time(const std::chrono::system_clock::time_point& when) = 0; }; class update_interface { public: virtual ~update_interface() = default; virtual std::unique_ptr<comment> run() = 0; }; virtual ~comments_group() = default; virtual std::unique_ptr<create_interface> create(const std::string& content, const std::string& fields) = 0; virtual std::unique_ptr<delete_interface> del(const std::string& comment_id) = 0; virtual std::unique_ptr<get_interface> get(const std::string& comment_id, const std::string& fields) = 0; virtual std::unique_ptr<list_interface> list(const std::string& fields) = 0; virtual std::unique_ptr<update_interface> update(const std::string& comment_id, const std::string& content, const std::string& fields) = 0; }; inline const std::optional<std::vector<comment>>& comments_group::list_interface::reply::comments() const { return comments_; } inline const std::optional<std::string>& comments_group::list_interface::reply::kind() const { return kind_; } inline const std::optional<std::string>& comments_group::list_interface::reply::next_page_token() const { return next_page_token_; } } #endif
29.375
107
0.615712
mexicowilly
887b0e7e8d39ff75c07236fe027d06843ce6b2f3
2,043
cpp
C++
01/solution.cpp
IAmBullsaw/AOC-2017
c320ea275403d261ebc0dbd8f46c8fb62453dc97
[ "MIT" ]
null
null
null
01/solution.cpp
IAmBullsaw/AOC-2017
c320ea275403d261ebc0dbd8f46c8fb62453dc97
[ "MIT" ]
null
null
null
01/solution.cpp
IAmBullsaw/AOC-2017
c320ea275403d261ebc0dbd8f46c8fb62453dc97
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using namespace std; int solveCaptcha(string & captcha) { captcha.push_back(captcha.front()); string::const_iterator it{captcha.begin()}; int sum{0}; while(it != captcha.end()) { char letter{*it}; unsigned n{0}; do { if (letter == *(it+1+n)) { ++n; } else break; } while(n < captcha.size()); sum += static_cast<int>(letter - '0')*n; advance(it,1+n); } return sum; } int solveCaptcha2(string const& captcha) { const long unsigned half{captcha.size()/2}; int opposite{0}; char other{}; int sum{0}; long unsigned i{0}; for (char letter : captcha) { if (i < half) { opposite = half + i; } else { opposite = i - half; } other = captcha.at(opposite); if (letter == other) { sum += static_cast<int>(letter - '0'); } ++i; } return sum; } void test() { string captcha{"1122"}; int sum{solveCaptcha(captcha)}; cout << "Sum of 1122 is: " << sum << endl; captcha = "1111"; sum = solveCaptcha(captcha); cout << "Sum of 1111 is: " << sum << endl; captcha = "1234"; sum = solveCaptcha(captcha); cout << "Sum of 1234 is: " << sum << endl; captcha = "91212129"; sum = solveCaptcha(captcha); cout << "Sum of 91212129 is: " << sum << endl; } void test2() { string captcha{"1212"}; int sum{solveCaptcha2(captcha)}; cout << "Sum of " << captcha << " is: " << sum << endl; captcha = "1221"; sum = solveCaptcha2(captcha); cout << "Sum of " << captcha << " is: " << sum << endl; captcha = "123425"; sum = solveCaptcha2(captcha); cout << "Sum of " << captcha << " is: " << sum << endl; captcha = "123123"; sum = solveCaptcha2(captcha); cout << "Sum of " << captcha << " is: " << sum << endl; captcha = "12131415"; sum = solveCaptcha2(captcha); cout << "Sum of " << captcha << " is: " << sum << endl; } int main() { string captcha{""}; cin >> captcha; int sum{solveCaptcha2(captcha)}; cout << "Sum of " << captcha << " is: " << sum << endl; return 0; }
24.614458
57
0.565835
IAmBullsaw
887f1664c29e830bcfde11052ab662a9c323950c
5,611
cpp
C++
src/slaggy-engine/slaggy-engine/engine/Shader.cpp
SlaggyWolfie/slaggy-engine
846235c93a52a96be85c5274a1372bc09c16f144
[ "MIT" ]
1
2021-09-24T23:13:13.000Z
2021-09-24T23:13:13.000Z
src/slaggy-engine/slaggy-engine/engine/Shader.cpp
SlaggyWolfie/slaggy-engine
846235c93a52a96be85c5274a1372bc09c16f144
[ "MIT" ]
null
null
null
src/slaggy-engine/slaggy-engine/engine/Shader.cpp
SlaggyWolfie/slaggy-engine
846235c93a52a96be85c5274a1372bc09c16f144
[ "MIT" ]
2
2020-06-24T07:10:13.000Z
2022-03-08T17:19:12.000Z
#include "Shader.hpp" #include <fstream> #include <sstream> #include <iostream> #include <glm/gtc/type_ptr.hpp> namespace slaggy { std::map<Shader::ShaderType, Shader::ShaderTypeInfo> Shader::_shaderTypes = { {ShaderType::VERTEX, {"VERTEX", GL_VERTEX_SHADER}}, {ShaderType::FRAGMENT, {"FRAGMENT", GL_FRAGMENT_SHADER}}, {ShaderType::GEOMETRY, {"GEOMETRY", GL_GEOMETRY_SHADER}} }; std::map<unsigned, unsigned> Shader::_idCounter; Shader::Shader(const std::string& vertexPath, const std::string& fragmentPath) { std::string vCode, fCode; read(vertexPath, vCode); read(fragmentPath, fCode); const unsigned int vID = compile(vCode, ShaderType::VERTEX); const unsigned int fID = compile(fCode, ShaderType::FRAGMENT); id = link({ vID, fID }); incrementCounter(); } Shader::Shader(const std::string& vertexPath, const std::string& geometryPath, const std::string& fragmentPath) { std::string vCode, fCode, gCode; read(vertexPath, vCode); read(fragmentPath, fCode); read(geometryPath, gCode); const unsigned int vID = compile(vCode, ShaderType::VERTEX); const unsigned int fID = compile(fCode, ShaderType::FRAGMENT); const unsigned int gID = compile(gCode, ShaderType::GEOMETRY); id = link({ vID, fID, gID }); incrementCounter(); } Shader::Shader(const std::string& path) : Shader ( std::string(path).append(".vert"), std::string(path).append(".frag") ) { } Shader::~Shader() { decrementCounter(); } void Shader::idReassign(const Shader& other) { decrementCounter(); id = other.id; incrementCounter(); } Shader::Shader(const Shader& other) { idReassign(other); } Shader::Shader(Shader&& other) noexcept { idReassign(other); } Shader& Shader::operator=(const Shader& other) { if (this == &other) return *this; idReassign(other); return *this; } Shader& Shader::operator=(Shader&& other) noexcept { idReassign(other); return *this; } void Shader::read(const std::string& path, std::string& code) { std::ifstream file; // > ensure ifstream objects can throw exceptions file.exceptions(std::ifstream::failbit | std::ifstream::badbit); //-----OPEN & READ-----// // Try to open and read the shader files // and place them into memory // ALTERNATIVE METHOD in MGE: read line-by-line and add it to a string try { // opening the files file.open(path); // setting up streams (reading pipelines ?) std::stringstream stream; // > read file's buffer contents into the stream stream << file.rdbuf(); // close file.close(); // place into memory code = stream.str(); } catch (std::ifstream::failure& exception) { std::cout << "ERROR::SHADER::FILE_NOT_SUCCESSFULLY_FOUND_OR_READ\n" << exception.what() << std::endl; // TODO fix shader failure not stopping the rest of the process //return; } } unsigned Shader::compile(const std::string& code, const ShaderType shaderType) { const char* code_c = code.c_str(); const ShaderTypeInfo& info = _shaderTypes[shaderType]; //-----COMPILE & LINK-----// unsigned int id = 0; int success = -1; char log[512]; // Vertex Shader id = glCreateShader(info.glID); glShaderSource(id, 1, &code_c, nullptr); glCompileShader(id); // print compilation errors glGetShaderiv(id, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(id, 512, nullptr, log); std::cout << "ERROR::SHADER::" << info.name << "::COMPILATION_FAILED\n" << log << std::endl; } return id; } unsigned Shader::link(const std::vector<unsigned>& shaderIds) { int success = -1; char log[512]; const unsigned int programID = glCreateProgram(); for (unsigned id : shaderIds) glAttachShader(programID, id); glLinkProgram(programID); glGetProgramiv(programID, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(programID, 512, nullptr, log); std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << log << std::endl; } for (unsigned id : shaderIds) glDeleteShader(id); return programID; } void Shader::use() const { glUseProgram(id); } void Shader::set(const std::string& name, const bool value) const { glUniform1i(location(name), static_cast<int>(value)); } void Shader::set(const std::string& name, const int value) const { glUniform1i(location(name), value); } void Shader::set(const std::string& name, const unsigned int value) const { glUniform1ui(location(name), value); } void Shader::set(const std::string& name, const float value) const { glUniform1f(location(name), value); } void Shader::set(const std::string& name, const glm::vec2& value) const { glUniform2fv(location(name), 1, glm::value_ptr(value)); } void Shader::set(const std::string& name, const glm::vec3& value) const { glUniform3fv(location(name), 1, glm::value_ptr(value)); } void Shader::set(const std::string& name, const glm::vec4& value) const { glUniform4fv(location(name), 1, glm::value_ptr(value)); } void Shader::set(const std::string& name, const glm::mat3& value) const { glUniformMatrix3fv(location(name), 1, GL_FALSE, glm::value_ptr(value)); } void Shader::set(const std::string& name, const glm::mat4& value) const { glUniformMatrix4fv(location(name), 1, GL_FALSE, glm::value_ptr(value)); } unsigned Shader::location(const std::string& name) const { return glGetUniformLocation(id, name.c_str()); } void Shader::incrementCounter() const { _idCounter[id]++; } void Shader::decrementCounter() const { _idCounter[id]--; if (_idCounter[id] == 0) glDeleteProgram(id); } }
22.716599
112
0.679023
SlaggyWolfie
8881516f07cb80f2fe4b38071deddf5a594c62a4
5,164
cpp
C++
2018/0325_ARC093/E.cpp
kazunetakahashi/atcoder
16ce65829ccc180260b19316e276c2fcf6606c53
[ "MIT" ]
7
2019-03-24T14:06:29.000Z
2020-09-17T21:16:36.000Z
2018/0325_ARC093/E.cpp
kazunetakahashi/atcoder
16ce65829ccc180260b19316e276c2fcf6606c53
[ "MIT" ]
null
null
null
2018/0325_ARC093/E.cpp
kazunetakahashi/atcoder
16ce65829ccc180260b19316e276c2fcf6606c53
[ "MIT" ]
1
2020-07-22T17:27:09.000Z
2020-07-22T17:27:09.000Z
/** * File : E.cpp * Author : Kazune Takahashi * Created : 2018-3-25 21:58:58 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <random> // random_device rd; mt19937 mt(rd()); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; #define DEBUG 0 // change 0 -> 1 if we need debug. typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; const int MAX_SIZE = 1000010; const long long MOD = 1000000007; long long inv[MAX_SIZE]; long long fact[MAX_SIZE]; long long factinv[MAX_SIZE]; const int UFSIZE = 100010; int union_find[UFSIZE]; int root(int a) { if (a == union_find[a]) return a; return (union_find[a] = root(union_find[a])); } bool issame(int a, int b) { return root(a) == root(b); } void unite(int a, int b) { union_find[root(a)] = root(b); } bool isroot(int a) { return root(a) == a; } void init() { inv[1] = 1; for (int i=2; i<MAX_SIZE; i++) { inv[i] = ((MOD - inv[MOD%i]) * (MOD/i))%MOD; } fact[0] = factinv[0] = 1; for (int i=1; i<MAX_SIZE; i++) { fact[i] = (i * fact[i-1])%MOD; factinv[i] = (inv[i] * factinv[i-1])%MOD; } for (auto i=0; i<UFSIZE; i++) { union_find[i] = i; } } long long C(int n, int k) { if (n >=0 && k >= 0 && n-k >= 0) { return ((fact[n] * factinv[k])%MOD * factinv[n-k])%MOD; } return 0; } long long power(long long x, long long n) { if (n == 0) { return 1; } else if (n%2 == 1) { return (x * power(x, n-1)) % MOD; } else { long long half = power(x, n/2); return (half * half) % MOD; } } long long gcm(long long a, long long b) { if (a < b) { return gcm(b, a); } if (b == 0) return a; return gcm(b, a%b); } typedef tuple<ll, int, int> edge; typedef tuple<ll, int> path; int N, M; ll X; vector<edge> V; vector<path> T[1010]; vector<edge> W; path parent[10][1010]; int depth[1010]; void dfs(int v, int p, ll cost, int d) { parent[0][v] = path(cost, p); depth[v] = d; for (auto x : T[v]) { if (get<1>(x) != p) { dfs(get<1>(x), v, get<0>(x), d + 1); } } } void init2() { dfs(0, -1, 0, 0); for (auto k = 0; k+1 < 10; k++) { for (auto v = 0; v < N; v++) { if (get<1>(parent[k][v]) < 0) { parent[k + 1][v] = path(0, -1); } else { ll cost = get<0>(parent[k][v]); int u = get<1>(parent[k][v]); int new_u = get<1>(parent[k][u]); ll new_cost = max(cost, get<0>(parent[k][u])); parent[k + 1][v] = path(new_cost, new_u); #if DEBUG == 1 cerr << "parent[" << k + 1 << "][" << v << "] = (" << new_cost << ", " << new_u << ")" << endl; #endif } } } } ll lca(int u, int v) { if (depth[u] > depth[v]) swap(u, v); ll ans = 0; #if DEBUG == 1 cerr << "depth[" << u << "] = " << depth[u] << ", depth[" << v << "] = " << depth[v] << endl; #endif for (auto k = 0; k < 10; k++) { if ((depth[v] - depth[u]) >> k & 1) { ans = max(ans, get<0>(parent[k][v])); v = get<1>(parent[k][v]); } } if (u == v) return ans; for (auto k = 9; k >= 0; k--) { if (get<1>(parent[k][u]) != get<1>(parent[k][v])) { ans = max(ans, get<0>(parent[k][u])); ans = max(ans, get<0>(parent[k][v])); u = get<1>(parent[k][u]); v = get<1>(parent[k][v]); } } ans = max(ans, get<0>(parent[0][v])); ans = max(ans, get<0>(parent[0][u])); return ans; } int main() { init(); cin >> N >> M; cin >> X; for (auto i = 0; i < M; i++) { int u, v; ll w; cin >> u >> v >> w; u--; v--; V.push_back(edge(w, u, v)); } sort(V.begin(), V.end()); ll Y = 0; for (auto e : V) { ll cost = get<0>(e); int u = get<1>(e); int v = get<2>(e); if (!issame(u, v)) { unite(u, v); T[u].push_back(path(cost, v)); T[v].push_back(path(cost, u)); Y += cost; } else { W.push_back(e); } } #if DEBUG == 1 cerr << "X = " << X << ", Y = " << Y << endl; #endif if (X < Y) { cout << 0 << endl; return 0; } ll ans = 0; ll K = N - 1; ll L = W.size(); if (X == Y) { ans = (((power(2, K) + MOD - 2) % MOD) * power(2, L)) % MOD; } #if DEBUG == 1 cerr << "L = " << L << ", ans = " << ans << endl; #endif init2(); ll L1 = 0; ll L2 = 0; for (auto e : W) { ll cost = get<0>(e); int u = get<1>(e); int v = get<2>(e); ll temp = cost - lca(u, v); if (temp < X - Y) L2++; else if (temp == X - Y) L1++; } #if DEBUG == 1 cerr << "L1 = " << L1 << ", L2 = " << L2 << endl; #endif ans += (2 * (power(2, L - L2) + MOD - power(2, L - L2 - L1))) % MOD; ans %= MOD; cout << ans << endl; }
19.785441
103
0.480442
kazunetakahashi
88842f01a273fce974ec20e86b3a43e9eedd4796
1,412
cpp
C++
src/problem79/Solution.cpp
MyYaYa/leetcode
d779c215516ede594267b15abdfba5a47dc879dd
[ "Apache-2.0" ]
1
2016-09-29T14:23:59.000Z
2016-09-29T14:23:59.000Z
src/problem79/Solution.cpp
MyYaYa/leetcode
d779c215516ede594267b15abdfba5a47dc879dd
[ "Apache-2.0" ]
null
null
null
src/problem79/Solution.cpp
MyYaYa/leetcode
d779c215516ede594267b15abdfba5a47dc879dd
[ "Apache-2.0" ]
null
null
null
class Solution { public: bool exist(vector<vector<char>>& board, string word) { len = word.size(); if (len == 0) { return false; } row = board.size(); if (row == 0) return false; col = board[0].size(); if (col == 0) return false; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (backtrack(board, word, 0, i, j)) return true; } } return false; } private: int len; int row; int col; bool backtrack(vector<vector<char>>& board, string& word, int w_start, int b_row, int b_col) { if (w_start == len) return true; if (b_row < 0 || b_row >= row || b_col < 0 || b_col >= col) return false; if (board[b_row][b_col] == word[w_start]) { char t = board[b_row][b_col]; board[b_row][b_col] = '\0'; if (backtrack(board, word, w_start+1, b_row+1, b_col) || \ backtrack(board, word, w_start+1, b_row-1, b_col) || \ backtrack(board, word, w_start+1, b_row, b_col+1) || \ backtrack(board, word, w_start+1, b_row, b_col-1)) { return true; } else { board[b_row][b_col] = t; } } return false; } };
31.377778
98
0.445467
MyYaYa
889048e718aec3cb4029716789daa16ce803a323
1,071
cpp
C++
src/measurecurrent.cpp
WAAM-UFJF/Ensaio-Frequencia
7063eb764872f5039c5ce203c894402d7edaab46
[ "MIT" ]
null
null
null
src/measurecurrent.cpp
WAAM-UFJF/Ensaio-Frequencia
7063eb764872f5039c5ce203c894402d7edaab46
[ "MIT" ]
null
null
null
src/measurecurrent.cpp
WAAM-UFJF/Ensaio-Frequencia
7063eb764872f5039c5ce203c894402d7edaab46
[ "MIT" ]
null
null
null
#include <Arduino.h> #include <Adafruit_INA219.h> // Definição do sensor de corrente e tensão. Adafruit_INA219 ina219_0 (0x40); // Define o valor de amostras para a media movel static const int N = 128; static const float n = 1.0/N; static float mediaMovel[N]; static int contador=0; void inicializaINA(){ while (1){ if(ina219_0.begin()){ break; } Serial.println("Falha ao encontrar o INA219"); delay(20); } ina219_0.setCalibration_16V_400mA(); } void measureCurrent(){ float corrente = 0, correnteFiltrada = 0; contador++; corrente = ina219_0.getCurrent_mA(); mediaMovel[(contador-1)%N] = corrente; if(contador < N){ for(int i=0; i<contador+1;i++){ correnteFiltrada += mediaMovel[i]; } correnteFiltrada = correnteFiltrada/contador; } else{ for(int i=0; i<N; i++){ correnteFiltrada += mediaMovel[i]; } correnteFiltrada = correnteFiltrada*n; } Serial.print(correnteFiltrada); Serial.print(";"); }
22.787234
54
0.612512
WAAM-UFJF
88906223a4d3d9e5c88edaf0266e2134e5a36e9c
9,716
cpp
C++
Sources Age of Enigma/Scene_Island_Dive.cpp
calidrelle/Gamecodeur
4449ea1dce02b8f08e39d258d864546fcc9b2fc6
[ "CC0-1.0" ]
29
2016-05-04T08:22:46.000Z
2022-01-27T10:20:55.000Z
Sources Age of Enigma/Scene_Island_Dive.cpp
calidrelle/Gamecodeur
4449ea1dce02b8f08e39d258d864546fcc9b2fc6
[ "CC0-1.0" ]
1
2018-11-25T14:12:39.000Z
2018-11-25T14:12:39.000Z
Sources Age of Enigma/Scene_Island_Dive.cpp
calidrelle/Gamecodeur
4449ea1dce02b8f08e39d258d864546fcc9b2fc6
[ "CC0-1.0" ]
49
2016-04-29T19:43:42.000Z
2022-02-19T16:13:35.000Z
/* * SceneFondMarin.cpp * * Created by Rockford on 19/04/10. * Copyright 2010 Casual Games France. All rights reserved. * */ #include "EScene.h" #include "Scene_Island_Dive.h" #include "ESceneDirector.h" #include "SoundBank.h" #include "MyGame.h" #include <string> #include "EMiniJeuTemplate.h" #include "GlobalBank.h" SceneFondMarin::SceneFondMarin(ESceneDirector *lpSceneDirector) : EScene(lpSceneDirector) { _bDiveEnd = false; _lpAnimTempoBenitier = new KCounter; _lpAnimApnee = new KCounter; /* Load font */ EMiniJeuTemplate::Preload(); } SceneFondMarin::~SceneFondMarin() { XDELETE(_lpAnimTempoBenitier); XDELETE(_lpAnimApnee); XDELETE(_lpFont); } void SceneFondMarin::Init() { _lpFont = EFontBank::getFont("NITECLUB.TTF",200); // 1ère visite if (!TaskResolved("task_island_dive_visit")) { ResolveTask("task_island_dive_visit"); AddObjective("island","key"); AddHint("island","key","how"); } // Bénitier fermé à l'arrivée if (!TaskResolved("task_island_clamwood")) { AddTask("task_island_clamwood"); _bBenitierOpen = false; SetVisible("benitieropen", false); SetVisible("benitierclose", true); } else { _bBenitierOpen = true; SetVisible("benitieropen", true); SetVisible("woodin", true); SetVisible("benitierclose", false); if (TaskResolved("task_island_getkey")) { SetVisible("dive_pearl", true); } else { SetVisible("dive_key", true); } } SetupItem("island_shovelhead"); // Le baton au sol if (!TestGlobal("woodout")) { SetVisible("woodout", true); } else { SetVisible("woodout", false); } // StartAnimation("sharkanim"); StartAnimation("fishbanc1P2P"); // StartAnimation("wavesanim"); StartAnimation("fish1animrot"); StartAnimation("fish1animp2p"); _lpSndDive = ESoundBank::getSound("island_dive"); _lpSndDive->playSample(); // Animation ouverture / fermeture du bénitier _lpAnimTempoBenitier->startCounter(0, 1, 0, 5000, K_COUNTER_LINEAR); // 30 secondes d'apnée !! _lpAnimApnee->startCounter(30, 0, 0, 30000, K_COUNTER_LINEAR); // Musique apnée _lpSceneDirector->ChangeMusic(DIRECTOR_MUSIC_DIVE30); if (TaskResolved("task_island_getkey") && TaskResolved("island_shovelhead")) { _lpSceneDirector->getSequencer()->Talk(NULL, CHARACTER_POSX, CHARACTER_POSY, KStr("ISLAND_DIVE_MURRAY_DONE") ,"",true); } } void SceneFondMarin::Check() { EScene::Check(); #ifdef SCENE_SHORTCUT if (KInput::isPressed(K_VK_F5)) { _lpSceneDirector->GoToScene("menu"); } #endif } void SceneFondMarin::Logic() { EScene::Logic(); } void SceneFondMarin::Draw() { EScene::Draw(); // Anims // On n'avance que si aucun mini jeu n'est affiché if (_lpSceneDirector->GetCurrentMinigame() == NULL) { double fElapsed = MyGame::getGame()->getKWindow()->getFrameTime(); _lpAnimApnee->move(fElapsed); _lpAnimTempoBenitier->move(fElapsed); } // Si l'anim du bénitier est finie, on inverse l'état du bénitier et on reprend if (!TaskResolved("task_island_clamwood")) { if (_lpAnimTempoBenitier->isCompleted()) { if (_bBenitierOpen ) { _bBenitierOpen = false; SetVisible("benitieropen", false); SetVisible("dive_key", false); SetVisible("dive_pearl", false); SetVisible("benitierclose", true); StopEmitter("bubbles"); } else { _bBenitierOpen = true; SetVisible("benitieropen", true); if (TaskResolved("task_island_getkey")) { SetVisible("dive_pearl", true); } else { SetVisible("dive_key", true); } SetVisible("benitierclose", false); StartEmitter("bubbles"); } _lpAnimTempoBenitier->startCounter(0, 30, 0, 5000, K_COUNTER_LINEAR); } } // Si l'apnée est finit, on sort ! if (_lpAnimApnee->isCompleted() && _bDiveEnd == false) { _bDiveEnd = true; _lpSceneDirector->PlayDirectorSound("diveend"); _lpSceneDirector->GoToScene("island_beach"); } // Affiche le temps restant d'Apnée std::string str; str = itos(int(_lpAnimApnee->getCurrentValue())); if (int(_lpAnimApnee->getCurrentValue()) < 10) { _lpFont->drawStringCentered(str.c_str(), 750, 1024, 20); } else { std::string u = str.substr(1,1); str = str.substr(0,1); float cx = (1024-750)/2 + 750; _lpFont->drawStringFromRight(str.c_str(),cx, 20); _lpFont->drawStringFromLeft(u.c_str(),cx, 20); } } void SceneFondMarin::Close() { _lpSndDive->stopSample(); } bool SceneFondMarin::ObjectClicked(const char *szObjectName, float x, float y) { if (strcmp(szObjectName, "benitieropen") == 0 || strcmp(szObjectName, "benitierclose") == 0) { if (_bBenitierOpen) { // Referme le bénitier _lpAnimTempoBenitier->move(99999); _lpSceneDirector->getSequencer()->Talk(NULL, CHARACTER_POSX, CHARACTER_POSY, KStr("ISLAND_DIVE_MURRAY_WHY"), "", true); return true; } } if (strcmp(szObjectName, "dive_key") == 0) { // Referme le bénitier _lpAnimTempoBenitier->move(99999); // TODO:Animer 2 bouts de baton ? if (TaskResolved("task_island_clamwood")) { _lpSceneDirector->getSequencer()->PlaySound(NULL, "brokenstick"); _lpSceneDirector->getSequencer()->Talk(NULL, CHARACTER_POSX, CHARACTER_POSY, KStr("ISLAND_DIVE_MURRAY_STICKNOT"), "", true); // On annule la tâche ResetTask("task_island_clamwood"); SetVisible("woodin", false); SetVisible("woodout", true); SetGlobal("woodout","0"); // Remet l'objet au sol } else { _lpSceneDirector->getSequencer()->Talk(NULL, CHARACTER_POSX, CHARACTER_POSY, KStr("ISLAND_DIVE_MURRAY_WHY"), "", true); } return true; } if (strcmp(szObjectName, "woodout") == 0) { PickupSimple(szObjectName, "inv_island_wood"); return true; } if (strcmp(szObjectName, "island_shovelhead") == 0) { PickupMultiple(szObjectName, "inv_island_shovelhead",-1); return true; } if (strcmp(szObjectName, "woodin") == 0) { _lpSceneDirector->getSequencer()->Talk(NULL, CHARACTER_POSX, CHARACTER_POSY, KStr("ISLAND_DIVE_MURRAY_STICK"), "", true); return true; } if (strcmp(szObjectName, "dive_pearl") == 0) { _lpSceneDirector->getSequencer()->Talk(NULL, CHARACTER_POSX, CHARACTER_POSY, KStr("ISLAND_DIVE_MURRAY_PEARL"), "", true); return true; } _lpSceneDirector->getSequencer()->Talk(NULL, CHARACTER_POSX, CHARACTER_POSY, KStr("ISLAND_DIVE_MURRAY_BLOUP"), "", true); return false; } bool SceneFondMarin::ObjectOver(char *szObjectName, float x, float y) { return false; } /* Un objet de l'inventaire est utilisé sur un objet de la scène */ bool SceneFondMarin::ItemUsed(const char *szItemName, const char *szObjectName) { // Le joueur utilise la perle dans le bénitier ouvert if ( strcmp(szItemName, "inv_island_pearl") == 0 ) { if (_lpAnimApnee->getCurrentValue() > 3.0f) { if ((strcmp(szObjectName, "dive_key") == 0 || strcmp(szObjectName, "benitieropen") == 0) && TaskResolved("task_island_clamwood")) { // On peut maintenant retirer l'objet de l'inventaire _lpSceneDirector->DropItem("inv_pearl"); // On a obtenu la clé ! ESoundBank::getSound("success")->playSample(); int x, y; GetObjectPosition("dive_key", x, y, false, false); _lpSceneDirector->getSequencer()->ShowImage(NULL,"dive_key", false); _lpSceneDirector->getSequencer()->PickupItem(NULL, "inv_island_key", (float)x, (float)y, 1); _lpSceneDirector->getSequencer()->ShowImage(NULL, "dive_pearl", true); _lpSceneDirector->getSequencer()->Talk(NULL, CHARACTER_POSX, CHARACTER_POSY, KStr("ISLAND_DIVE_MURRAY_SUCCESS") ,"",true); ResolveTask("task_island_getkey"); ResolveObjective("island","key"); _lpSceneDirector->DropItem("inv_island_pearl"); return true; } else if (strcmp(szObjectName, "dive_key") == 0 && !TaskResolved("task_island_clamwood")) { // Referme le bénitier _lpAnimTempoBenitier->move(99999); // TODO:Animer 2 bouts de baton ? _lpSceneDirector->getSequencer()->Talk(NULL, CHARACTER_POSX, CHARACTER_POSY, KStr("ISLAND_DIVE_MURRAY_TOFAST"), "", true); return true; } } else { _lpSceneDirector->getSequencer()->Talk(NULL, CHARACTER_POSX, CHARACTER_POSY, KStr("ISLAND_DIVE_MURRAY_TOOLATE"), "", true); } } // Le joueur utilise le bout de bois sur l'intérieur du bénitier if ( strcmp(szItemName, "inv_island_wood") == 0 ) { if (strcmp(szObjectName, "benitieropen") == 0 || strcmp(szObjectName, "dive_key") == 0) { ESoundBank::getSound("success")->playSample(); ResolveTask("task_island_clamwood"); AddTask("task_island_getkey"); SetVisible("woodin", true); _lpSceneDirector->DropItem("inv_island_wood"); return true; } if (strcmp(szObjectName, "benitierclose") == 0) { _lpSceneDirector->getSequencer()->Talk(NULL, CHARACTER_POSX, CHARACTER_POSY, KStr("ISLAND_DIVE_MURRAY_MISSED") ,"",true); return true; } } return false; } void SceneFondMarin::MiniGameDone(const char *szGameName, bool bIsRevolved) { }
32.066007
138
0.63555
calidrelle
8895a634fb861c4d0f7d42812b8a21a98dce0726
1,557
hpp
C++
Game/Physics.hpp
Zakhar-V/Game32k
1b44efb539c0382500511cb0190f00ccbfbe3243
[ "MIT" ]
null
null
null
Game/Physics.hpp
Zakhar-V/Game32k
1b44efb539c0382500511cb0190f00ccbfbe3243
[ "MIT" ]
null
null
null
Game/Physics.hpp
Zakhar-V/Game32k
1b44efb539c0382500511cb0190f00ccbfbe3243
[ "MIT" ]
null
null
null
#pragma once #include "Scene.hpp" //----------------------------------------------------------------------------// // Defs //----------------------------------------------------------------------------// //----------------------------------------------------------------------------// // PhysicsBody //----------------------------------------------------------------------------// class PhysicsBody : public Object { public: }; //----------------------------------------------------------------------------// // PhysicsShape //----------------------------------------------------------------------------// enum PhysicsShapeType : uint { PST_Empty, PST_Box, PST_Sphere, PST_Capsule, PST_Cyliner, PST_Heightfield, }; class PhysicsShape : public Object { public: }; //----------------------------------------------------------------------------// // PhysicsJoint //----------------------------------------------------------------------------// class PhysicsJoint : public Object { public: }; //----------------------------------------------------------------------------// // PhysicsWorld //----------------------------------------------------------------------------// class PhysicsWorld : public NonCopyable { public: PhysicsWorld(Scene* _scene); ~PhysicsWorld(void); protected: Scene* m_scene; }; //----------------------------------------------------------------------------// // //----------------------------------------------------------------------------//
22.897059
81
0.23571
Zakhar-V
88a0031164db190941245acab3b8bb995ce5c9d2
637
cpp
C++
rt/rt/cameras/perspective.cpp
DasNaCl/old-university-projects
af1c82afec4805ea672e0c353369035b394cb69d
[ "Apache-2.0" ]
null
null
null
rt/rt/cameras/perspective.cpp
DasNaCl/old-university-projects
af1c82afec4805ea672e0c353369035b394cb69d
[ "Apache-2.0" ]
null
null
null
rt/rt/cameras/perspective.cpp
DasNaCl/old-university-projects
af1c82afec4805ea672e0c353369035b394cb69d
[ "Apache-2.0" ]
null
null
null
#include <rt/cameras/perspective.h> #include <rt/ray.h> #include <cmath> #include <iostream> namespace rt { PerspectiveCamera::PerspectiveCamera(const Point& center, const Vector& forward, const Vector& up, float verticalOpeningAngle, float horizontalOpeningAngle) : center(center) , focal(forward.normalize()) , right( cross(forward, up).normalize() * std::tan(horizontalOpeningAngle / 2.f)) , sup( cross(right, forward).normalize() * std::tan(verticalOpeningAngle / 2.f)) { } Ray PerspectiveCamera::getPrimaryRay(float x, float y) const { return Ray(center, (focal + x * right + y * sup).normalize()); } }
23.592593
80
0.704867
DasNaCl
88a1ef50564b78b62b5e7e2bab2b98d5beb9b829
32
cpp
C++
code/source/Octree.cpp
MajiKau/MoosEngine
3fca25f52129a33f438d0b3477a810d1f6c83a3f
[ "MIT" ]
null
null
null
code/source/Octree.cpp
MajiKau/MoosEngine
3fca25f52129a33f438d0b3477a810d1f6c83a3f
[ "MIT" ]
null
null
null
code/source/Octree.cpp
MajiKau/MoosEngine
3fca25f52129a33f438d0b3477a810d1f6c83a3f
[ "MIT" ]
null
null
null
#include "code/headers/Octree.h"
32
32
0.78125
MajiKau
88b4bbed90633e0e94837c47bc3a79716d3bcf98
1,923
hpp
C++
lib/abcresub/abcresub/vec_wrd.hpp
osamamowafy/mockturtle
840ff314e9f5301686790a517c383240f1403588
[ "MIT" ]
98
2018-06-15T09:28:11.000Z
2022-03-31T15:42:48.000Z
lib/abcresub/abcresub/vec_wrd.hpp
osamamowafy/mockturtle
840ff314e9f5301686790a517c383240f1403588
[ "MIT" ]
257
2018-05-09T12:14:28.000Z
2022-03-30T16:12:14.000Z
lib/abcresub/abcresub/vec_wrd.hpp
osamamowafy/mockturtle
840ff314e9f5301686790a517c383240f1403588
[ "MIT" ]
75
2020-11-26T13:05:15.000Z
2021-12-24T00:28:18.000Z
/*! \file vec_wrd.hpp \brief Extracted from ABC https://github.com/berkeley-abc/abc \author Alan Mishchenko (UC Berkeley) */ #pragma once namespace abcresub { typedef struct Vec_Wrd_t_ Vec_Wrd_t; struct Vec_Wrd_t_ { int nCap; int nSize; word * pArray; }; inline Vec_Wrd_t * Vec_WrdAlloc( int nCap ) { Vec_Wrd_t * p; p = ABC_ALLOC( Vec_Wrd_t, 1 ); if ( nCap > 0 && nCap < 16 ) nCap = 16; p->nSize = 0; p->nCap = nCap; p->pArray = p->nCap? ABC_ALLOC( word, p->nCap ) : NULL; return p; } inline void Vec_WrdErase( Vec_Wrd_t * p ) { ABC_FREE( p->pArray ); p->nSize = 0; p->nCap = 0; } inline void Vec_WrdFree( Vec_Wrd_t * p ) { ABC_FREE( p->pArray ); ABC_FREE( p ); } inline word * Vec_WrdArray( Vec_Wrd_t * p ) { return p->pArray; } inline word Vec_WrdEntry( Vec_Wrd_t * p, int i ) { assert( i >= 0 && i < p->nSize ); return p->pArray[i]; } inline word * Vec_WrdEntryP( Vec_Wrd_t * p, int i ) { assert( i >= 0 && i < p->nSize ); return p->pArray + i; } inline void Vec_WrdGrow( Vec_Wrd_t * p, int nCapMin ) { if ( p->nCap >= nCapMin ) return; p->pArray = ABC_REALLOC( word, p->pArray, nCapMin ); assert( p->pArray ); p->nCap = nCapMin; } inline void Vec_WrdFill( Vec_Wrd_t * p, int nSize, word Fill ) { int i; Vec_WrdGrow( p, nSize ); for ( i = 0; i < nSize; i++ ) p->pArray[i] = Fill; p->nSize = nSize; } inline void Vec_WrdClear( Vec_Wrd_t * p ) { p->nSize = 0; } inline void Vec_WrdPush( Vec_Wrd_t * p, word Entry ) { if ( p->nSize == p->nCap ) { if ( p->nCap < 16 ) Vec_WrdGrow( p, 16 ); else Vec_WrdGrow( p, 2 * p->nCap ); } p->pArray[p->nSize++] = Entry; } inline int Vec_WrdSize( Vec_Wrd_t * p ) { return p->nSize; } } /* namespace abcresub */
18.141509
62
0.552782
osamamowafy
88b562af416f747ac467974e3d2d9f316b8cc77c
464
cpp
C++
app/bootloader/default_bd.cpp
HPezz/LekaOS
e4c16f52e2c7bd3d75c9d5aefe94eb67dbf5a694
[ "Apache-2.0" ]
2
2021-10-30T20:51:30.000Z
2022-01-12T11:18:34.000Z
app/bootloader/default_bd.cpp
HPezz/LekaOS
e4c16f52e2c7bd3d75c9d5aefe94eb67dbf5a694
[ "Apache-2.0" ]
343
2021-07-15T12:57:08.000Z
2022-03-29T10:14:06.000Z
app/bootloader/default_bd.cpp
HPezz/LekaOS
e4c16f52e2c7bd3d75c9d5aefe94eb67dbf5a694
[ "Apache-2.0" ]
3
2021-12-30T02:53:24.000Z
2022-01-11T22:08:05.000Z
// Leka - LekaOS // Copyright 2021 APF France handicap // SPDX-License-Identifier: Apache-2.0 #include "QSPIFBlockDevice.h" #include "SlicingBlockDevice.h" auto get_secondary_bd() -> mbed::BlockDevice * { // In this case, our flash is much larger than a single image so // slice it into the size of an image slot static auto _bd = QSPIFBlockDevice {}; static auto sliced_bd = mbed::SlicingBlockDevice {&_bd, 0x0, MCUBOOT_SLOT_SIZE}; return &sliced_bd; }
24.421053
81
0.734914
HPezz
88c1c46e3fb983cd08d102bef22f878a3d7a3b6f
42,925
hpp
C++
include/libopfcpp/OPF.hpp
thierrypin/LibOPFcpp
27614069e6600a1a2cab0d016018103b4eea1ee5
[ "Apache-2.0" ]
4
2019-05-06T14:44:53.000Z
2021-11-07T17:09:44.000Z
include/libopfcpp/OPF.hpp
thierrypin/LibOPFcpp
27614069e6600a1a2cab0d016018103b4eea1ee5
[ "Apache-2.0" ]
null
null
null
include/libopfcpp/OPF.hpp
thierrypin/LibOPFcpp
27614069e6600a1a2cab0d016018103b4eea1ee5
[ "Apache-2.0" ]
null
null
null
/****************************************************** * A C++ program for the OPF classification machine, * * all contained in a single header file. * * * * Author: Thierry Moreira * * * ******************************************************/ // Copyright 2019 Thierry Moreira // // 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 OPF_HPP #define OPF_HPP #include <functional> #include <stdexcept> #include <algorithm> #include <typeinfo> #include <sstream> #include <utility> #include <cstring> #include <string> #include <limits> #include <memory> #include <vector> #include <cmath> #include <map> #include <set> #include <omp.h> namespace opf { using uchar = unsigned char; #define INF std::numeric_limits<float>::infinity() #define NIL -1 // Generic distance function template <class T> using distance_function = std::function<T (const T*, const T*, size_t)>; /*****************************************/ /*************** Binary IO ***************/ /*****************************************/ //////////// // OPF types enum Type : unsigned char { Classifier = 1, Clustering = 2, }; ////////////////////// // Serialization Flags enum SFlags : unsigned char { Sup_SavePrototypes = 1, Unsup_Anomaly = 2, }; /////////////// // IO functions template <class T> void write_bin(std::ostream& output, const T& val) { output.write((char*) &val, sizeof(T)); } template <class T> void write_bin(std::ostream& output, const T* val, int n=1) { output.write((char*) val, sizeof(T) * n); } template <class T> T read_bin(std::istream& input) { T val; input.read((char*) &val, sizeof(T)); return val; } template <class T> void read_bin(std::istream& input, T* val, int n=1) { input.read((char*) val, sizeof(T) * n); } /*****************************************/ /************** Matrix type **************/ /*****************************************/ template <class T=float> class Mat { protected: std::shared_ptr<T> data; public: size_t rows, cols; size_t size; size_t stride; Mat(); Mat(const Mat<T>& other); Mat(size_t rows, size_t cols); Mat(size_t rows, size_t cols, T val0); Mat(std::shared_ptr<T>& data, size_t rows, size_t cols, size_t stride = 0); Mat(T* data, size_t rows, size_t cols, size_t stride=0); virtual T& at(size_t i, size_t j); const virtual T at(size_t i, size_t j) const; virtual T* row(size_t i); const virtual T* row(size_t i) const; virtual T* operator[](size_t i); const virtual T* operator[](size_t i) const; Mat<T>& operator=(const Mat<T>& other); virtual Mat<T> copy(); void release(); }; template <class T> Mat<T>::Mat() { this->rows = this->cols = this->size = this->stride = 0; } template <class T> Mat<T>::Mat(const Mat<T>& other) { this->rows = other.rows; this->cols = other.cols; this->size = other.size; this->data = other.data; this->stride = other.stride; } template <class T> Mat<T>::Mat(size_t rows, size_t cols) { this->rows = rows; this->cols = cols; this->size = rows * cols; this->stride = cols; this->data = std::shared_ptr<T>(new T[this->size], std::default_delete<T[]>()); } template <class T> Mat<T>::Mat(size_t rows, size_t cols, T val) { this->rows = rows; this->cols = cols; this->size = rows * cols; this->stride = cols; this->data = std::shared_ptr<T>(new T[this->size], std::default_delete<T[]>()); for (size_t i = 0; i < rows; i++) { T* row = this->row(i); for (size_t j = 0; j < cols; j++) row[j] = val; } } template <class T> Mat<T>::Mat(std::shared_ptr<T>& data, size_t rows, size_t cols, size_t stride) { this->rows = rows; this->cols = cols; this->size = rows * cols; this->data = data; if (stride) this->stride = stride; else this->stride = cols; } // Receives a pointer to some data, which may not be deleted. template <class T> Mat<T>::Mat(T* data, size_t rows, size_t cols, size_t stride) { this->rows = rows; this->cols = cols; this->size = rows * cols; this->data = std::shared_ptr<T>(data, [](T *p) {}); if (stride) this->stride = stride; else this->stride = cols; } template <class T> T& Mat<T>::at(size_t i, size_t j) { size_t idx = i * this->stride + j; return this->data.get()[idx]; } template <class T> const T Mat<T>::at(size_t i, size_t j) const { size_t idx = i * this->stride + j; return this->data.get()[idx]; } template <class T> T* Mat<T>::row(size_t i) { size_t idx = i * this->stride; return this->data.get() + idx; } template <class T> const T* Mat<T>::row(size_t i) const { size_t idx = i * this->stride; return this->data.get() + idx; } template <class T> T* Mat<T>::operator[](size_t i) { size_t idx = i * this->stride; return this->data.get() + idx; } template <class T> const T* Mat<T>::operator[](size_t i) const { size_t idx = i * this->stride; return this->data.get() + idx; } template <class T> Mat<T>& Mat<T>::operator=(const Mat<T>& other) { if (this != &other) { this->rows = other.rows; this->cols = other.cols; this->size = other.size; this->data = other.data; this->stride = other.stride; } return *this; } template <class T> Mat<T> Mat<T>::copy() { Mat<T> out(this->rows, this->cols); for (size_t i = 0; i < this->rows; i++) { T* row = this->row(i); T* outrow = out.row(i); for (size_t j = 0; j < this->cols; j++) outrow[j] = row[j]; } return std::move(out); } template <class T> void Mat<T>::release() { this->data.reset(); } /*****************************************/ // Default distance function template <class T> T euclidean_distance(const T* a, const T* b, size_t size) { T sum = 0; for (size_t i = 0; i < size; i++) { sum += (a[i]-b[i]) * (a[i]-b[i]); } return (T)sqrt(sum); } template <class T> T magnitude(const T* v, size_t size) { T sum = 0; for (size_t i = 0; i < size; i++) { sum += v[i] * v[i]; } return (T)sqrt(sum); } // One alternate distance function template <class T> T cosine_distance(const T* a, const T* b, size_t size) { T dividend = 0; for (size_t i = 0; i < size; i++) { dividend += a[i] * b[i]; } T divisor = magnitude<T>(a, size) * magnitude<T>(b, size); // 1 - cosine similarity return 1 - (dividend / divisor); } template <class T> Mat<T> compute_train_distances(const Mat<T> &features, distance_function<T> distance=euclidean_distance<T>) { Mat<float> distances(features.rows, features.rows); #pragma omp parallel for shared(features, distances) for (size_t i = 0; i < features.rows - 1; i++) { distances[i][i] = 0; for (size_t j = i + 1; j < features.rows; j++) { distances[i][j] = distances[j][i] = distance(features[i], features[j], features.cols); } } return distances; } /*****************************************/ /********* Distance matrix type **********/ /*****************************************/ // Instead of storing n x n elements, we only store the upper triangle, // which has (n * (n-1))/2 elements (less than half). template <class T> class DistMat: public Mat<T> { private: T diag_vals = static_cast<T>(0); int get_index(int i, int j) const; public: DistMat(){this->rows = this->cols = this->size = 0;}; DistMat(const DistMat& other); DistMat(const Mat<T>& features, distance_function<T> distance=euclidean_distance<T>); virtual T& at(size_t i, size_t j); const virtual T at(size_t i, size_t j) const; }; // The first row has n-1 cols, the second has n-2, and so on until row n has 0 cols. // This way, #define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b))) template <class T> inline int DistMat<T>::get_index(int i, int j) const { if (i > j) SWAP(i, j); return ((((this->rows<<1) - i - 1) * i) >> 1) + (j - i - 1); } template <class T> DistMat<T>::DistMat(const DistMat& other) { this->rows = other.rows; this->cols = other.cols; this->size = other.size; this->data = other.data; } template <class T> DistMat<T>::DistMat(const Mat<T>& features, distance_function<T> distance) { this->rows = features.rows; this->cols = features.rows; this->size = (this->rows * (this->rows - 1)) / 2; this->data = std::shared_ptr<T>(new float[this->size], std::default_delete<float[]>()); for (size_t i = 0; i < this->rows; i++) { for (size_t j = i+1; j < this->rows; j++) this->data.get()[get_index(i, j)] = distance(features[i], features[j], features.cols); } } template <class T> T& DistMat<T>::at(size_t i, size_t j) { if (i == j) return this->diag_vals = static_cast<T>(0); return this->data.get()[this->get_index(i, j)]; } template <class T> const T DistMat<T>::at(size_t i, size_t j) const { if (i == j) return 0; return this->data.get()[this->get_index(i, j)]; } /*****************************************/ /************ Data structures ************/ /*****************************************/ /** * Color codes for Prim's algorithm */ enum Color{ WHITE, // New node GRAY, // On the heap BLACK // Already seen }; /** * Plain class to store node information */ class Node { public: Node() { this->color = WHITE; this->pred = -1; this->cost = INF; this->is_prototype = false; } size_t index; // Index on the list -- makes searches easier * Color color; // Color on the heap. white: never visiter, gray: on the heap, black: removed from the heap * float cost; // Cost to reach the node int true_label; // Ground truth * int label; // Assigned label int pred; // Predecessor node * bool is_prototype; // Whether the node is a prototype * }; /** * Heap data structure to use as a priority queue * */ class Heap { private: std::vector<Node> *nodes; // A reference for the original container vector std::vector<Node*> vec; // A vector of pointers to build the heap upon static bool compare_element(const Node* lhs, const Node* rhs) { return lhs->cost >= rhs->cost; } public: // Size-constructor Heap(std::vector<Node> *nodes, const std::vector<int> &labels) { this->nodes = nodes; size_t n = nodes->size(); this->vec.reserve(n); for (size_t i = 0; i < n; i++) { (*this->nodes)[i].index = i; (*this->nodes)[i].true_label = (*this->nodes)[i].label = labels[i]; } } // Insert new element into heap void push(int item, float cost) { // Update node's cost value (*this->nodes)[item].cost = cost; // Already on the heap if ((*this->nodes)[item].color == GRAY) make_heap(this->vec.begin(), this->vec.end(), compare_element); // Remake the heap // New to the heap else if ((*this->nodes)[item].color == WHITE) { (*this->nodes)[item].color = GRAY; this->vec.push_back(&(*this->nodes)[item]); push_heap(this->vec.begin(), this->vec.end(), compare_element); // Push new item to the heap } // Note that black items can not be inserted into the heap } // Update item's cost without updating the heap void update_cost(int item, float cost) { // Update node's cost value (*this->nodes)[item].cost = cost; if ((*this->nodes)[item].color == WHITE) { (*this->nodes)[item].color = GRAY; this->vec.push_back(&(*this->nodes)[item]); } } // Update the heap. // This is used after multiple calls to update_cost in order to reduce the number of calls to make_heap. void heapify() { make_heap(this->vec.begin(), this->vec.end(), compare_element); // Remake the heap } // Remove and return the first element of the heap int pop() { // Obtain and mark the first element Node *front = this->vec.front(); front->color = BLACK; // Remove it from the heap pop_heap(this->vec.begin(), this->vec.end(), compare_element); this->vec.pop_back(); // And return it return front->index; } bool empty() { return this->vec.size() == 0; } size_t size() { return this->vec.size(); } }; /*****************************************/ /*****************************************/ /****************** OPF ******************/ /*****************************************/ /******** Supervised ********/ template <class T=float> class SupervisedOPF { private: // Model Mat<T> train_data; // Training data (original vectors or distance matrix) std::vector<Node> nodes; // Learned model // List of nodes ordered by cost. Useful for speeding up classification // Its not size_t to reduce memory usage, since ML may handle large data std::vector<unsigned int> ordered_nodes; // Options bool precomputed; distance_function<T> distance; void prim_prototype(const std::vector<int> &labels); public: SupervisedOPF(bool precomputed=false, distance_function<T> distance=euclidean_distance<T>); void fit(const Mat<T> &train_data, const std::vector<int> &labels); std::vector<int> predict(const Mat<T> &test_data); bool get_precomputed() {return this->precomputed;} // Serialization functions std::string serialize(uchar flags=0); static SupervisedOPF<T> unserialize(const std::string& contents); // Training information std::vector<std::vector<float>> get_prototypes(); }; template <class T> SupervisedOPF<T>::SupervisedOPF(bool precomputed, distance_function<T> distance) { this->precomputed = precomputed; this->distance = distance; } /** * - The first step in OPF's training procedure. Finds the prototype nodes using Prim's * Minimum Spanning Tree algorithm. * - Any node with an adjacent node of a different class is taken as a prototype. */ template <class T> void SupervisedOPF<T>::prim_prototype(const std::vector<int> &labels) { this->nodes = std::vector<Node>(this->train_data.rows); Heap h(&this->nodes, labels); // Heap as a priority queue // Arbitrary first node h.push(0, 0); while(!h.empty()) { // Gets the head of the heap and marks it black size_t s = h.pop(); // Prototype definition int pred = this->nodes[s].pred; if (pred != NIL) { // Find points in the border between two classes... if (this->nodes[s].true_label != this->nodes[pred].true_label) { // And set them as prototypes this->nodes[s].is_prototype = true; this->nodes[pred].is_prototype = true; } } // Edge selection #pragma omp parallel for default(shared) for (size_t t = 0; t < this->nodes.size(); t++) { // If nodes are different and t has not been poped out of the heap (marked black) if (s != t && this->nodes[t].color != BLACK) // TODO if s == t, t is black { // Compute weight float weight; if (this->precomputed) weight = this->train_data[s][t]; else weight = this->distance(this->train_data[s], this->train_data[t], this->train_data.cols); // Assign if smaller than current value if (weight < this->nodes[t].cost) { this->nodes[t].pred = static_cast<int>(s); // h.push(t, weight); #pragma omp critical(updateHeap) h.update_cost(t, weight); } } } h.heapify(); } } /** * Trains the model with the given data and labels. * * Inputs: * - train_data: * - original feature vectors [n_samples, n_features] -- if precomputed == false * - distance matrix [n_samples, n_samples] -- if precomputed == true * - labels: * - true label values [n_samples] */ template <class T> void SupervisedOPF<T>::fit(const Mat<T> &train_data, const std::vector<int> &labels) { if ((size_t)train_data.rows != labels.size()) throw std::invalid_argument("[OPF/fit] Error: data size does not match labels size: " + std::to_string(train_data.rows) + " x " + std::to_string(labels.size())); // Store data reference for testing this->train_data = train_data; // Initialize model this->prim_prototype(labels); // Find prototypes Heap h(&this->nodes, labels); // Heap as a priority queue // Initialization for (Node& node: this->nodes) { node.color = WHITE; // Prototypes cost 0, have no predecessor and populate the heap if (node.is_prototype) { node.pred = NIL; node.cost = 0; } else // Other nodes start with cost = INF { node.cost = INF; } // Since all nodes are connected to all the others h.push(node.index, node.cost); } // List of nodes ordered by cost // Useful for speeding up classification this->ordered_nodes.reserve(this->nodes.size()); // Consume the queue while(!h.empty()) { int s = h.pop(); this->ordered_nodes.push_back(s); // Iterate over all neighbors #pragma omp parallel for default(shared) for (int t = 0; t < (int) this->nodes.size(); t++) { if (s != t && this->nodes[s].cost < this->nodes[t].cost) // && this->nodes[t].color != BLACK ?? { // Compute weight float weight; if (precomputed) weight = this->train_data[s][t]; else weight = distance(this->train_data[s], this->train_data[t], this->train_data.cols); float cost = std::max(weight, this->nodes[s].cost); if (cost < this->nodes[t].cost) { this->nodes[t].pred = s; this->nodes[t].label = this->nodes[s].true_label; // h.push(t, cost); #pragma omp critical(updateHeap) h.update_cost(t, cost); } } } h.heapify(); } } /** * Classify a set of samples using a model trained by SupervisedOPF::fit. * * Inputs: * - test_data: * - original feature vectors [n_test_samples, n_features] -- if precomputed == false * - distance matrix [n_test_samples, n_train_samples] -- if precomputed == true * * Returns: * - predictions: * - a vector<int> of size [n_test_samples] with classification outputs. */ template <class T> std::vector<int> SupervisedOPF<T>::predict(const Mat<T> &test_data) { int n_test_samples = (int) test_data.rows; int n_train_samples = (int) this->nodes.size(); // Output predictions std::vector<int> predictions(n_test_samples); #pragma omp parallel for default(shared) for (int i = 0; i < n_test_samples; i++) { int idx = this->ordered_nodes[0]; int min_idx = 0; T min_cost = INF; T weight = 0; // 'ordered_nodes' contains sample indices ordered by cost, so if the current // best connection costs less than the next node, it is useless to keep looking. for (int j = 0; j < n_train_samples && min_cost > this->nodes[idx].cost; j++) { // Get the next node in the ordered list idx = this->ordered_nodes[j]; // Compute its distance to the query point if (precomputed) weight = test_data[i][idx]; else weight = distance(test_data[i], this->train_data[idx], this->train_data.cols); // The cost corresponds to the max between the distance and the reference cost float cost = std::max(weight, this->nodes[idx].cost); if (cost < min_cost) { min_cost = cost; min_idx = idx; } } predictions[i] = this->nodes[min_idx].label; } return predictions; } /*****************************************/ /* Persistence */ /*****************************************/ template <class T> std::string SupervisedOPF<T>::serialize(uchar flags) { if (this->precomputed) throw std::invalid_argument("Serialization for precomputed OPF not implemented yet"); // Open file std::ostringstream output(std::ios::out | std::ios::binary); int n_samples = this->train_data.rows; int n_features = this->train_data.cols; // Header write_bin<char>(output, "OPF", 3); write_bin<uchar>(output, Type::Classifier); write_bin<uchar>(output, flags); write_bin<uchar>(output, static_cast<uchar>(0)); // Reserved flags byte write_bin<int>(output, n_samples); write_bin<int>(output, n_features); // Data for (int i = 0; i < n_samples; i++) { const T* data = this->train_data.row(i); write_bin<T>(output, data, n_features); } // Nodes for (int i = 0; i < n_samples; i++) { write_bin<float>(output, this->nodes[i].cost); write_bin<int>(output, this->nodes[i].label); } // Ordered_nodes write_bin<unsigned int>(output, this->ordered_nodes.data(), n_samples); // Prototypes if (flags & SFlags::Sup_SavePrototypes) { // Find which are prototypes first, because we need the correct amount std::set<int> prots; for (int i = 0; i < n_samples; i++) { if (this->nodes[i].is_prototype) prots.insert(i); } write_bin<int>(output, prots.size()); for (auto it = prots.begin(); it != prots.end(); ++it) write_bin<int>(output, *it); } return output.str(); } template <class T> SupervisedOPF<T> SupervisedOPF<T>::unserialize(const std::string& contents) { // Header int n_samples; int n_features; char header[4]; SupervisedOPF<float> opf; // Open stream std::istringstream ifs(contents); // , std::ios::in | std::ios::binary // Check if stream is an OPF serialization read_bin<char>(ifs, header, 3); header[3] = '\0'; if (strcmp(header, "OPF")) throw std::invalid_argument("Input is not an OPF serialization"); // Get type and flags uchar type = read_bin<uchar>(ifs); uchar flags = read_bin<uchar>(ifs); read_bin<uchar>(ifs); // Reserved byte if (type != Type::Classifier) throw std::invalid_argument("Input is not a Supervised OPF serialization"); n_samples = read_bin<int>(ifs); n_features = read_bin<int>(ifs); // Data int size = n_samples * n_features; opf.train_data = Mat<T>(n_samples, n_features); T* data = opf.train_data.row(0); read_bin<T>(ifs, data, size); // Nodes opf.nodes = std::vector<Node>(n_samples); for (int i = 0; i < n_samples; i++) { opf.nodes[i].cost = read_bin<float>(ifs); opf.nodes[i].label = read_bin<int>(ifs); } // Ordered_nodes opf.ordered_nodes = std::vector<unsigned int>(n_samples); read_bin<unsigned int>(ifs, opf.ordered_nodes.data(), n_samples); if (flags & SFlags::Sup_SavePrototypes) { int prots = read_bin<int>(ifs); for (int i = 0; i < prots; i++) { int idx = read_bin<int>(ifs); opf.nodes[idx].is_prototype = true; } } return std::move(opf); } /*****************************************/ /* Data Access */ /*****************************************/ template <class T> std::vector<std::vector<float>> SupervisedOPF<T>::get_prototypes() { std::set<int> prots; for (size_t i = 0; i < this->train_data.rows; i++) { if (this->nodes[i].is_prototype) prots.insert(i); } std::vector<std::vector<float>> out(prots.size(), std::vector<float>(this->train_data.cols)); int i = 0; for (auto it = prots.begin(); it != prots.end(); ++it, ++i) { for (int j = 0; j < this->train_data.cols; j++) { out[i][j] = this->train_data[*it][j]; } } return out; } /*****************************************/ /******** Unsupervised ********/ // Index + distance to another node using Pdist = std::pair<int, float>; static bool compare_neighbor(const Pdist& lhs, const Pdist& rhs) { return lhs.second < rhs.second; } // Aux class to find the k nearest neighbors from a given node // In the future, this should be replaced by a kdtree class BestK { private: int k; std::vector<Pdist> heap; // idx, dist public: // Empty initializer BestK(int k) : k(k) {this->heap.reserve(k);} // Tries to insert another element to the heap void insert(int idx, float dist) { if (heap.size() < static_cast<unsigned int>(this->k)) { heap.push_back(Pdist(idx, dist)); push_heap(this->heap.begin(), this->heap.end(), compare_neighbor); } else { // If the new point is closer than the farthest neighbor Pdist farthest = this->heap.front(); if (dist < farthest.second) { // Remove one from the heap and add the other pop_heap(this->heap.begin(), this->heap.end(), compare_neighbor); this->heap[this->k-1] = Pdist(idx, dist); push_heap(this->heap.begin(), this->heap.end(), compare_neighbor); } } } std::vector<Pdist>& get_knn() { return heap; } }; /** * Plain class to store node information */ class NodeKNN { public: NodeKNN() { this->pred = -1; } std::set<Pdist> adj; // Node adjacency size_t index; // Index on the list -- makes searches easier int label; // Assigned label int pred; // Predecessor node float value; // Path value float rho; // probability density function }; // Unsupervised OPF classifier template <class T=float> class UnsupervisedOPF { private: // Model std::shared_ptr<const Mat<T>> train_data; // Training data (original vectors or distance matrix) distance_function<T> distance; // Distance function std::vector<NodeKNN> nodes; // Learned model std::vector<int> queue; // Priority queue implemented as a linear search in a vector int k; // The number of neighbors to build the graph int n_clusters; // Number of clusters in the model -- computed during fit // Training attributes float sigma_sq; // Sigma squared, used to compute probability distribution function float delta; // Adjustment term float denominator; // sqrt(2 * math.pi * sigma_sq) -- compute it only once // Options float thresh; bool anomaly; bool precomputed; // Queue capabilities int get_max(); // Training subroutines void build_graph(); void build_initialize(); void cluster(); public: UnsupervisedOPF(int k=5, bool anomaly=false, float thresh=.1, bool precomputed=false, distance_function<T> distance=euclidean_distance<T>); void fit(const Mat<T> &train_data); std::vector<int> fit_predict(const Mat<T> &train_data); std::vector<int> predict(const Mat<T> &test_data); void find_best_k(Mat<float>& train_data, int kmin, int kmax, int step=1, bool precompute=true); // Clustering info float quality_metric(); // Getters & Setters int get_n_clusters() {return this->n_clusters;} int get_k() {return this->k;} bool get_anomaly() {return this->anomaly;} float get_thresh() {return this->thresh;} void set_thresh(float thresh) {this->thresh = thresh;} bool get_precomputed() {return this->precomputed;} // Serialization functions std::string serialize(uchar flags=0); static UnsupervisedOPF<T> unserialize(const std::string& contents); }; template <class T> UnsupervisedOPF<T>::UnsupervisedOPF(int k, bool anomaly, float thresh, bool precomputed, distance_function<T> distance) { this->k = k; this->precomputed = precomputed; this->anomaly = anomaly; if (this->anomaly) this->n_clusters = 2; this->thresh = thresh; this->distance = distance; } // Builds the KNN graph template <class T> void UnsupervisedOPF<T>::build_graph() { this->sigma_sq = 0.; // Proportional to the length of the biggest edge for (size_t i = 0; i < this->nodes.size(); i++) { // Find the k nearest neighbors BestK bk(this->k); for (size_t j = 0; j < this->nodes.size(); j++) { if (i != j) { float dist; if (this->precomputed) dist = this->train_data->at(i, j); else dist = this->distance(this->train_data->row(i), this->train_data->row(j), this->train_data->cols); bk.insert(j, dist); } } std::vector<Pdist> knn = bk.get_knn(); for (auto it = knn.cbegin(); it != knn.cend(); ++it) { // Since the graph is undirected, make connections from both nodes this->nodes[i].adj.insert(*it); this->nodes[it->first].adj.insert(Pdist(i, it->second)); // Finding sigma if (it->second > this->sigma_sq) this->sigma_sq = it->second; } } this->sigma_sq /= 3; this->sigma_sq = 2 * (this->sigma_sq * this->sigma_sq); this->denominator = sqrt(2 * M_PI * this->sigma_sq); } // Initialize the graph nodes template <class T> void UnsupervisedOPF<T>::build_initialize() { // Compute rho std::set<Pdist>::iterator it; for (size_t i = 0; i < this->nodes.size(); i++) { int n_neighbors = this->nodes[i].adj.size(); // A node may have more than k neighbors float div = this->denominator * n_neighbors; float sum = 0; for (it = this->nodes[i].adj.cbegin(); it != this->nodes[i].adj.cend(); ++it) { float dist = it->second; sum += expf((-dist * dist) / this->sigma_sq); } this->nodes[i].rho = sum / div; } // Compute delta this->delta = INF; for (size_t i = 0; i < this->nodes.size(); i++) { for (it = this->nodes[i].adj.begin(); it != this->nodes[i].adj.end(); ++it) { float diff = abs(this->nodes[i].rho - this->nodes[it->first].rho); if (diff != 0 && this->delta > diff) this->delta = diff; } } // And, finally, initialize each node this->queue.resize(this->nodes.size()); for (size_t i = 0; i < this->nodes.size(); i++) { this->nodes[i].value = this->nodes[i].rho - this->delta; this->queue[i] = static_cast<int>(i); } } // Get the node with the biggest path value // TODO: implement it in a more efficient way? template <class T> int UnsupervisedOPF<T>::get_max() { float maxval = -INF; int maxidx = -1; int size = this->queue.size(); for (int i = 0; i < size; i++) { int idx = this->queue[i]; if (this->nodes[idx].value > maxval) { maxidx = i; maxval = this->nodes[idx].value; } } int best = this->queue[maxidx]; int tmp = this->queue[size-1]; this->queue[size-1] = this->queue[maxidx]; this->queue[maxidx] = tmp; this->queue.pop_back(); return best; } // OPF clustering template <class T> void UnsupervisedOPF<T>::cluster() { // Cluster labels int l = 0; // Priority queue while (!this->queue.empty()) { int s = this->get_max(); // Pop the highest value // If it has no predecessor, make it a prototype if (this->nodes[s].pred == -1) { this->nodes[s].label = l++; this->nodes[s].value = this->nodes[s].rho; } // Iterate and conquer over its neighbors for (auto it = this->nodes[s].adj.begin(); it != this->nodes[s].adj.end(); ++it) { int t = it->first; if (this->nodes[t].value < this->nodes[s].value) { float rho = std::min(this->nodes[s].value, this->nodes[t].rho); // std::cout << rho << " " << this->nodes[t].value << std::endl; if (rho > this->nodes[t].value) { this->nodes[t].label = this->nodes[s].label; this->nodes[t].pred = s; this->nodes[t].value = rho; } } } } this->n_clusters = l; } // Fit the model template <class T> void UnsupervisedOPF<T>::fit(const Mat<T> &train_data) { this->train_data = std::shared_ptr<const Mat<T>>(&train_data, [](const Mat<T> *p) {}); this->nodes = std::vector<NodeKNN>(this->train_data->rows); this->build_graph(); this->build_initialize(); if (!this->anomaly) this->cluster(); } // Fit and predict for all nodes template <class T> std::vector<int> UnsupervisedOPF<T>::fit_predict(const Mat<T> &train_data) { this->fit(train_data); std::vector<int> labels(this->nodes.size()); if (this->anomaly) for (size_t i = 0; i < this->nodes.size(); i++) labels[i] = (this->nodes[i].rho < this->thresh) ? 1 : 0; else for (size_t i = 0; i < this->nodes.size(); i++) labels[i] = this->nodes[i].label; return labels; } // Predict cluster pertinence template <class T> std::vector<int> UnsupervisedOPF<T>::predict(const Mat<T> &test_data) { std::vector<int> preds(test_data.rows); // For each test sample for (size_t i = 0; i < test_data.rows; i++) { // Find the k nearest neighbors BestK bk(this->k); for (size_t j = 0; j < this->nodes.size(); j++) { if (i != j) { float dist; if (this->precomputed) dist = test_data.at(i, j); else dist = this->distance(test_data[i], this->train_data->row(j), this->train_data->cols); bk.insert(j, dist); } } // Compute the testing rho std::vector<Pdist> neighbors = bk.get_knn(); int n_neighbors = neighbors.size(); float div = this->denominator * n_neighbors; float sum = 0; for (int j = 0; j < n_neighbors; j++) { float dist = neighbors[j].second; // this->distances[i][*it] sum += expf((-dist * dist) / this->sigma_sq); } float rho = sum / div; if (this->anomaly) { // And returns anomaly detection based on graph density preds[i] = (rho < this->thresh) ? 1 : 0; } else { // And find which node conquers this test sample float maxval = -INF; int maxidx = -1; for (int j = 0; j < n_neighbors; j++) { int s = neighbors[j].first; // idx, distance float val = std::min(this->nodes[s].value, rho); if (val > maxval) { maxval = val; maxidx = s; } } preds[i] = this->nodes[maxidx].label; } } return preds; } // Quality metric // From: A Robust Extension of the Mean Shift Algorithm using Optimum Path Forest // Leonardo Rocha, Alexandre Falcao, and Luis Meloni template <class T> float UnsupervisedOPF<T>::quality_metric() { if (this->anomaly) throw std::invalid_argument("Quality metric not implemented for anomaly detection yet"); std::vector<float> w(this->n_clusters, 0); std::vector<float> w_(this->n_clusters, 0); for (size_t i = 0; i < this->train_data->rows; i++) { int l = this->nodes[i].label; for (auto it = this->nodes[i].adj.begin(); it != this->nodes[i].adj.end(); ++it) { int l_ = this->nodes[it->first].label; float tmp = 0; if (it->second != 0) tmp = 1. / it->second; if (l == l_) w[l] += tmp; else w_[l] += tmp; } } float C = 0; for (int i = 0; i < this->n_clusters; i++) C += w_[i] / (w_[i] + w[i]); return C; } // Brute force method to find the best value of k template <class T> void UnsupervisedOPF<T>::find_best_k(Mat<float>& train_data, int kmin, int kmax, int step, bool precompute) { std::cout << "precompute " << precompute << std::endl; float best_quality = INF; UnsupervisedOPF<float> best_opf; DistMat<float> distances; if (precompute) distances = DistMat<float>(train_data, this->distance); for (int k = kmin; k <= kmax; k += step) { // Instanciate and train the model UnsupervisedOPF<float> opf(k, false, 0, precompute, this->distance); if (precompute) opf.fit(distances); else opf.fit(train_data); std::cout << k << ": " << opf.n_clusters << std::endl; // Compare its clustering grade float quality = opf.quality_metric(); // Normalized cut if (quality < best_quality) { best_quality = quality; best_opf = opf; } } if (best_quality == INF) { std::ostringstream ss; ss << "No search with kmin " << kmin << ", kmax " << kmax << ", and step " << step << ". The arguments might be out of order."; std::cerr << ss.str() << std::endl; throw 0; } if (this->precomputed) this->train_data = std::shared_ptr<Mat<T>>(&distances, std::default_delete<Mat<T>>()); else this->train_data = std::shared_ptr<Mat<T>>(&train_data, [](Mat<T> *p) {}); this->k = best_opf.k; this->n_clusters = best_opf.n_clusters; this->nodes = best_opf.nodes; this->denominator = best_opf.denominator; this->sigma_sq = best_opf.sigma_sq; this->delta = best_opf.delta; } /*****************************************/ /* Persistence */ /*****************************************/ template <class T> std::string UnsupervisedOPF<T>::serialize(uchar flags) { if (this->precomputed) throw std::invalid_argument("Serialization for precomputed OPF not implemented yet"); // Open file std::ostringstream output ; int n_samples = this->train_data->rows; int n_features = this->train_data->cols; // Output flags flags = 0; // For now, there are no user-defined flags if (this->anomaly) flags += SFlags::Unsup_Anomaly; // Header write_bin<char>(output, "OPF", 3); write_bin<uchar>(output, Type::Clustering); write_bin<uchar>(output, flags); write_bin<uchar>(output, static_cast<uchar>(0)); // Reserved byte write_bin<int>(output, n_samples); write_bin<int>(output, n_features); // Scalar data write_bin<int>(output, this->k); if (!this->anomaly) write_bin<int>(output, this->n_clusters); else write_bin<float>(output, this->thresh); write_bin<float>(output, this->denominator); write_bin<float>(output, this->sigma_sq); // Data for (int i = 0; i < n_samples; i++) { const T* data = this->train_data->row(i); write_bin<T>(output, data, n_features); } // Nodes for (int i = 0; i < n_samples; i++) { write_bin<float>(output, this->nodes[i].value); if (!this->anomaly) write_bin<int>(output, this->nodes[i].label); } return output.str(); } template <class T> UnsupervisedOPF<T> UnsupervisedOPF<T>::unserialize(const std::string& contents) { UnsupervisedOPF<float> opf; // Open stream std::istringstream ifs(contents); // , std::ios::in | std::ios::binary /// Header int n_samples; int n_features; char header[4]; // Check if stream is an OPF serialization read_bin<char>(ifs, header, 3); header[3] = '\0'; if (strcmp(header, "OPF")) throw std::invalid_argument("Input is not an OPF serialization"); // Get type and flags uchar type = read_bin<uchar>(ifs); uchar flags = read_bin<uchar>(ifs); // Flags byte read_bin<uchar>(ifs); // reserved byte if (flags & SFlags::Unsup_Anomaly) opf.anomaly = true; if (type != Type::Clustering) throw std::invalid_argument("Input is not an Unsupervised OPF serialization"); // Data size n_samples = read_bin<int>(ifs); n_features = read_bin<int>(ifs); // Scalar data opf.k = read_bin<int>(ifs); if (!opf.anomaly) opf.n_clusters = read_bin<int>(ifs); else { opf.thresh = read_bin<float>(ifs); opf.n_clusters = 2; } opf.denominator = read_bin<float>(ifs); opf.sigma_sq = read_bin<float>(ifs); /// Data // Temporary var to read data, since opf's train_data is const auto train_data = std::shared_ptr<Mat<T>>(new Mat<T>(n_samples, n_features), std::default_delete<Mat<T>>()); // Read data int size = n_samples * n_features; T* data = train_data->row(0); read_bin<T>(ifs, data, size); // Assign to opf opf.train_data = train_data; // Nodes opf.nodes = std::vector<NodeKNN>(n_samples); for (int i = 0; i < n_samples; i++) { opf.nodes[i].value = read_bin<float>(ifs); if (!opf.anomaly) opf.nodes[i].label = read_bin<int>(ifs); } return std::move(opf); } /*****************************************/ } #endif
27.855289
169
0.554595
thierrypin
88c5cdc5e757ed0ae1d023cf9a5501e289a7821d
214
cpp
C++
Loops/displayDigits/displayDigits.cpp
ntjohns1/cppPractice
c9c18bec889cde56217f68996077b9d409ceef04
[ "Apache-2.0" ]
null
null
null
Loops/displayDigits/displayDigits.cpp
ntjohns1/cppPractice
c9c18bec889cde56217f68996077b9d409ceef04
[ "Apache-2.0" ]
null
null
null
Loops/displayDigits/displayDigits.cpp
ntjohns1/cppPractice
c9c18bec889cde56217f68996077b9d409ceef04
[ "Apache-2.0" ]
null
null
null
#include<iostream> using namespace std; int main() { int n, digit; cout<<"enter a number: "; cin>>n; while(n>0) { digit=n%10; n=n/10; cout<<digit<<" "; } }
12.588235
30
0.448598
ntjohns1
88c6dbab693d2a7388d9602126c089369a4a106d
20,322
cpp
C++
src/caffe/multi_node/fc_thread.cpp
AIROBOTAI/caffe-mnode
e8b03bfb04f09dce21c9b5bbf66dacecb095d3e1
[ "BSD-2-Clause" ]
null
null
null
src/caffe/multi_node/fc_thread.cpp
AIROBOTAI/caffe-mnode
e8b03bfb04f09dce21c9b5bbf66dacecb095d3e1
[ "BSD-2-Clause" ]
null
null
null
src/caffe/multi_node/fc_thread.cpp
AIROBOTAI/caffe-mnode
e8b03bfb04f09dce21c9b5bbf66dacecb095d3e1
[ "BSD-2-Clause" ]
null
null
null
#include <map> #include <string> #include <vector> #include "caffe/multi_node/fc_thread.hpp" #include "caffe/multi_node/param_helper.hpp" namespace caffe { template <typename Dtype> ParamBuf<Dtype> *FcWorker<Dtype>::pbuf_ = NULL; template <typename Dtype> boost::once_flag FcWorker<Dtype>::once_; template <typename Dtype> vector<Blob<Dtype>*> * ParamBuf<Dtype>::RefParam(void *psolver, int clock) { boost::mutex::scoped_lock rlock(ref_mutex_); psolver_to_clock_[psolver] = clock; unordered_map<int, int>::iterator clock_iter = clock_to_idx_.find(clock); int idx = -1; if (clock_iter != clock_to_idx_.end()) { // use the param associated with the clock idx = clock_iter->second; } else { // use the latest param for this clock unordered_map<void *, int>::iterator iter = pointer_to_idx_.find(platest_param_); CHECK(iter != pointer_to_idx_.end()) << "cannot find index to pointer: " << platest_param_; idx = iter->second; clock_to_idx_[clock] = idx; } psolver_to_idx_[psolver] = idx; ref_cnt_vec_[idx]++; return param_vec_[idx]; } template <typename Dtype> vector<Blob<Dtype>*> *ParamBuf<Dtype>::FindParam(void *psolver) { boost::mutex::scoped_lock lock(ref_mutex_); unordered_map<void *, int>::iterator iter = psolver_to_idx_.find(psolver); CHECK(iter != psolver_to_idx_.end()) << "cannot find index to pointer: " << psolver; int idx = iter->second; return param_vec_[idx]; } template <typename Dtype> int ParamBuf<Dtype>::DeRefParam(void *psolver) { boost::mutex::scoped_lock lock(ref_mutex_); unordered_map<void *, int>::iterator iter = psolver_to_idx_.find(psolver); CHECK(iter != psolver_to_idx_.end()) << "cannot find index to pointer: " << psolver; int idx = iter->second; psolver_to_idx_.erase(iter); ref_cnt_vec_[idx]--; CHECK_GE(ref_cnt_vec_[idx], 0) << "unexpected reference counter"; unordered_map<void *, int>::iterator clock_iter = psolver_to_clock_.find(psolver); CHECK(clock_iter != psolver_to_clock_.end()); psolver_to_clock_.erase(clock_iter); return ref_cnt_vec_[idx]; } template <typename Dtype> vector<Blob<Dtype>*> *ParamBuf<Dtype>::CreateParam( const vector<Blob<Dtype>*> &params) { vector<Blob<Dtype>*> *pblobs = new vector<Blob<Dtype>*>(); for (int i = 0; i < params.size(); i++) { Blob<Dtype>* pb = new Blob<Dtype>(); pb->ReshapeLike(*params[i]); pblobs->push_back(pb); } // insert the paramter to buffer boost::mutex::scoped_lock lock(ref_mutex_); pointer_to_idx_[pblobs] = param_vec_.size(); param_vec_.push_back(pblobs); ref_cnt_vec_.push_back(0); CHECK_EQ(ref_cnt_vec_.size(), param_vec_.size()); LOG(INFO) << "created " << ref_cnt_vec_.size() << " parameters"; return pblobs; } template <typename Dtype> void ParamBuf<Dtype>::InitParamBuf(const vector<Blob<Dtype>*> &params) { // create 4 paramters in the beginning for (int i = 0; i < 4; i++) { CreateParam(params); } } template <typename Dtype> vector<Blob<Dtype>*> *ParamBuf<Dtype>::GetParam() { return platest_param_; } template <typename Dtype> vector<Blob<Dtype>*> *ParamBuf<Dtype>::FindFreeParam() { boost::mutex::scoped_lock lock(ref_mutex_); // find a free param pointer vector<Blob<Dtype>*> *pfree = NULL; for (int i = 0; i < param_vec_.size(); i++) { if (ref_cnt_vec_[i] == 0 && param_vec_[i] != platest_param_) { pfree = param_vec_[i]; } } return pfree; } template <typename Dtype> void ParamBuf<Dtype>::ReplaceParam(vector<Blob<Dtype>*> *p) { boost::mutex::scoped_lock lock(ref_mutex_); platest_param_ = p; } template <typename Dtype> void FcThread<Dtype>::CopyInputDataFromMsg(shared_ptr<Net<Dtype> > fc_net, shared_ptr<Msg> m) { for (int i = 0; i < fc_net->num_inputs(); i++) { int blob_index = fc_net->input_blob_indices()[i]; const string& blob_name = fc_net->blob_names()[blob_index]; Blob<Dtype>* pblob = fc_net->input_blobs()[i]; ParamHelper<Dtype>::CopyBlobDataFromMsg(pblob, blob_name, m); } } template <typename Dtype> shared_ptr<Msg> FcThread<Dtype>::FcForward(shared_ptr<Msg> m) { Solver<Dtype> *pfc = (Solver<Dtype> *)NodeEnv::Instance()->PopFreeSolver(); Solver<Dtype> *proot = (Solver<Dtype> *)NodeEnv::Instance()->GetRootSolver(); MLOG(INFO) << "Begin forward for src: " << m->src() << ", ID: " << m->conv_id(); if (NULL == pfc) { const SolverParameter& solver_param = NodeEnv::Instance()->SolverParam(); pfc = (Solver<Dtype> *)this->NewSolver(proot, solver_param); } // copy param data from root solver const vector<Blob<Dtype>*>& params = pfc->net()->learnable_params(); // const vector<Blob<Dtype>*>& root_params = proot->net()->learnable_params(); const vector<Blob<Dtype>*> *ref_params = this->GetParamBuf()->RefParam(pfc, m->clock()); CHECK_EQ(params.size(), ref_params->size()); for (int i = 0; i < params.size(); i++) { // CHECK_EQ(params[i]->count(), ref_params->at(i)->count()); params[i]->ShareData(*ref_params->at(i)); } // ParamHelper<Dtype>::PrintParam(pfc->net()); shared_ptr<Net<Dtype> > fc_net = pfc->net(); CopyInputDataFromMsg(fc_net, m); fc_net->ForwardPrefilled(); shared_ptr<Msg> r(new Msg(m)); // broadcast the message r->set_dst(-1); if (NodeEnv::Instance()->num_splits() > 1) { r->set_is_partial(true); r->set_data_offset(NodeEnv::Instance()->node_position()); } ParamHelper<Dtype>::CopyOutputDataToMsg(fc_net, r); NodeEnv::Instance()->PutSolver(m->msg_id(), pfc); return r; } template <typename Dtype> void FcThread<Dtype>::CopyOutputDiffFromMsg(shared_ptr<Net<Dtype> > fc_net, shared_ptr<Msg> m) { for (int i = 0; i < fc_net->num_outputs(); i++) { int blob_index = fc_net->output_blob_indices()[i]; const string& blob_name = fc_net->blob_names()[blob_index]; Blob<Dtype>* pblob = fc_net->output_blobs()[i]; ParamHelper<Dtype>::CopyBlobDiffFromMsg(pblob, blob_name, m); } } template <typename Dtype> void FcThread<Dtype>::FcBackward(shared_ptr<Msg> m, vector<shared_ptr<Msg> > *preplies, bool copy_diff) { Solver<Dtype> *pfc = (Solver<Dtype> *)NodeEnv::Instance()->FindSolver(m->msg_id()); CHECK(pfc != NULL); MLOG(INFO) << "Begin backward for src: " << m->src() << ", ID: " << m->conv_id(); shared_ptr<Net<Dtype> > fc_net = pfc->net(); if (copy_diff) { CopyOutputDiffFromMsg(fc_net, m); } fc_net->Backward(); const vector<int>& pre_ids = NodeEnv::Instance()->prev_node_ids(); if (pre_ids.size() <= 0) { // we are the gateway node shared_ptr<Msg> r(new Msg(m)); r->set_dst(m->src()); preplies->push_back(r); } else { for (int i = 0; i < pre_ids.size(); i++) { shared_ptr<Msg> r(new Msg(m)); r->set_dst(pre_ids[i]); preplies->push_back(r); } } // copy diff to downstream nodes for (int i = 0; i < preplies->size(); i++) { shared_ptr<Msg> r = preplies->at(i); r->set_type(BACKWARD); ParamHelper<Dtype>::CopyInputDiffToMsg(fc_net, r, i, preplies->size()); } // pfc->UpdateDiff(); // notify the param thread shared_ptr<Msg> notify(new Msg(m)); notify->set_dst(ROOT_THREAD_ID); notify->AppendData(&pfc, sizeof(pfc)); preplies->push_back(notify); } template <typename Dtype> void FcThread<Dtype>::ProcessMsg(shared_ptr<Msg> m) { vector<shared_ptr<Msg> > msg_arr; if (m->type() == FORWARD) { shared_ptr<Msg> f = FcForward(m); msg_arr.push_back(f); } else if (m->type() == BACKWARD) { FcBackward(m, &msg_arr, true); } else { LOG(INFO) << "unkown type: " << m->msg_id(); } for (int i = 0; i < msg_arr.size(); i++) { this->SendMsg(msg_arr[i]); } } template <typename Dtype> void FcThread<Dtype>::Run() { #ifdef USE_MKL int n = mkl_get_max_threads(); LOG(INFO) << "max mkl threads: " << n; mkl_set_dynamic(false); #endif while (!this->must_stop()) { shared_ptr<Msg> m = this->RecvMsg(true); vector<shared_ptr<Msg> > msgs; int clock_bound = clock_ + staleness_; if (m->type() == UPDATE_CLOCK) { clock_ = m->clock(); clock_bound = clock_ + staleness_; for (int i = 0; i < msg_buf_.size(); i++) { if (msg_buf_[i]->clock() <= clock_bound) { ProcessMsg(msg_buf_[i]); } else { msgs.push_back(msg_buf_[i]); } } msg_buf_.clear(); for (int i = 0; i < msgs.size(); i++) { msg_buf_.push_back(msgs[i]); } } else if (m->type() == EXIT_TRAIN) { // exit training return; } else { if (m->clock() <= clock_bound) { ProcessMsg(m); } else { LOG(WARNING) << "Wait for param thread"; msg_buf_.push_back(m); } } } } template <typename Dtype> boost::atomic_int FcLossThread<Dtype>::iter_(0); template <typename Dtype> void FcLossThread<Dtype>::ProcessMsg(shared_ptr<Msg> m) { shared_ptr<Msg> f = this->FcForward(m); vector<shared_ptr<Msg> > replies; this->FcBackward(f, &replies, false); iter_++; for (int i = 0; i < replies.size(); i++) { this->SendMsg(replies[i]); } } #if 0 template <typename Dtype> void FcLossThread<Dtype>::Run() { #ifdef USE_MKL int n = mkl_get_max_threads(); LOG(INFO) << "max mkl threads: " << n; mkl_set_dynamic(false); #endif while (!this->must_stop()) { shared_ptr<Msg> m = this->RecvMsg(true); } } #endif template <typename Dtype> int FcParamThread<Dtype>::GetGroupIndex(void *psolver, int64_t msg_id) { int clock = this->GetParamBuf()->GetClock(psolver); CHECK_NE(clock, INVALID_CLOCK) << "invalid clock"; unordered_map<int, int>::iterator iter = clock_to_group_idx_.find(clock); if (iter != clock_to_group_idx_.end()) { return iter->second; } // find or allocate a new slot the store the group solver int i = 0; for (i = 0; i < group_solvers_.size(); i++) { if (group_solvers_[i] == NULL) { break; } } if (i >= group_solvers_.size()) { group_solvers_.push_back(psolver); grad_updates_vec_.push_back(0); msg_id_vec_.push_back(msg_id); group_loss_vec_.push_back(0); clock_vec_.push_back(clock); clock_to_group_idx_[clock] = group_solvers_.size() - 1; } else { group_solvers_[i] = psolver; grad_updates_vec_[i] = 0; msg_id_vec_[i] = msg_id; group_loss_vec_[i] = 0; clock_vec_[i] = clock; clock_to_group_idx_[clock] = i; } return i; } template <typename Dtype> void FcParamThread<Dtype>::ClearGroup(int grp_idx) { Solver<Dtype> *pgroup_solver = (Solver<Dtype> *)group_solvers_[grp_idx]; CHECK(pgroup_solver != NULL); ParamHelper<Dtype>::ScalDiff(pgroup_solver->net(), (Dtype)0.0); this->GetParamBuf()->RemoveClock(clock_vec_[grp_idx]); this->GetParamBuf()->DeRefParam(pgroup_solver); NodeEnv::Instance()->DeleteSolver(msg_id_vec_[grp_idx]); NodeEnv::Instance()->PushFreeSolver(pgroup_solver); unordered_map<int, int>::iterator iter = clock_to_group_idx_.find(clock_vec_[grp_idx]); clock_to_group_idx_.erase(iter); group_solvers_[grp_idx] = NULL; group_loss_vec_[grp_idx] = 0; grad_updates_vec_[grp_idx] = 0; msg_id_vec_[grp_idx] = INVALID_ID; clock_vec_[grp_idx] = INVALID_CLOCK; } template <typename Dtype> int FcParamThread<Dtype>::UpdateParam(shared_ptr<Msg> m) { Solver<Dtype> *psolver = (Solver<Dtype> *)NodeEnv::Instance()->FindSolver(m->msg_id()); CHECK(psolver != NULL); SGDSolver<Dtype> *proot = (SGDSolver<Dtype> *)NodeEnv::Instance()->GetRootSolver(); #if 0 map<int, int>::iterator map_iter = client_idx_map_.find(m->src()); int client_idx = -1; if (map_iter == client_idx_map_.end()) { // add new client client_idx = AddNewClient(m, psolver); } else { client_idx = map_iter->second; client_clocks_[client_idx] = m->clock(); // TODO: allow one client has many solvers CHECK(client_solvers_[client_idx] == NULL); client_solvers_[client_idx] = psolver; msg_ids_[client_idx] = m->msg_id(); } int clock_bound = MinClock() + staleness_; int num_updates = 0; // update net diff for (int i = 0; i < client_ids_.size(); i++) { if (client_clocks_[i] <= clock_bound && client_solvers_[i] != NULL) { num_updates++; ParamHelper<Dtype>::AddDiffFromNet(proot->net(), client_solvers_[i]->net()); NodeEnv::Instance()->DeleteSolver(msg_ids_[i]); NodeEnv::Instance()->PushFreeSolver(client_solvers_[i]); client_solvers_[i] = NULL; // LOG(INFO) << "update client: " << client_ids_[i]; } } if (num_updates > 0) { proot->net()->Update(); proot->net()->ClearParamDiffs(); train_iter_++; } #endif #if 0 if (sub_batches_ == 0) { ParamHelper<Dtype>::CopyDiffFromNet(proot->net(), psolver->net()); } else { ParamHelper<Dtype>::AddDiffFromNet(proot->net(), psolver->net()); } // doesn't have broadcast nodes means we are loss layer const vector<string>& bcast_addrs = NodeEnv::Instance()->bcast_addrs(); if (bcast_addrs.size() == 0) { const vector<Blob<Dtype>*>& output = psolver->net()->output_blobs(); CHECK_EQ(output.size(), 1) << "only deal with output size 1"; Blob<Dtype>* pblob = output[0]; sub_loss_ += pblob->cpu_data()[0]; } // clear diff params ParamHelper<Dtype>::ScalDiff(psolver->net(), (Dtype)0.0); this->GetParamBuf()->DeRefParam(psolver); NodeEnv::Instance()->DeleteSolver(m->msg_id()); NodeEnv::Instance()->PushFreeSolver(psolver); sub_batches_++; if (sub_batches_ < num_conv_workers_ * this->num_sub_solvers_) { return; } #endif int group_id = GetGroupIndex(psolver, m->msg_id()); Solver<Dtype> *pgroup_solver = (Solver<Dtype> *)group_solvers_[group_id]; // doesn't have broadcast nodes means we are loss layer const vector<string>& bcast_addrs = NodeEnv::Instance()->bcast_addrs(); if (bcast_addrs.size() == 0) { const vector<Blob<Dtype>*>& output = psolver->net()->output_blobs(); CHECK_EQ(output.size(), 1) << "only deal with output size 1"; Blob<Dtype>* pblob = output[0]; group_loss_vec_[group_id] += pblob->cpu_data()[0]; } grad_updates_vec_[group_id]++; // total number of gradients in the system int total_grads = grad_updates_vec_[group_id] + this->QueueSize(); int batch_size = num_conv_workers_ * this->num_sub_solvers_; if (total_grads >= batch_size) { #ifdef USE_MKL // use all the availble threads to accerate computing mkl_set_num_threads_local(total_omp_threads_); #endif } if (pgroup_solver != psolver) { ParamHelper<Dtype>::AddDiffFromNet(pgroup_solver->net(), psolver->net()); // clear diff params ParamHelper<Dtype>::ScalDiff(psolver->net(), (Dtype)0.0); this->GetParamBuf()->DeRefParam(psolver); NodeEnv::Instance()->DeleteSolver(m->msg_id()); NodeEnv::Instance()->PushFreeSolver(psolver); // LOG(INFO) << "release solver for group id: " << group_id; } else { // LOG(INFO) << "keep solver for group id: " << group_id; } if (grad_updates_vec_[group_id] < batch_size) { return 0; } // share paramters const vector<Blob<Dtype>*>& root_params = proot->net()->learnable_params(); vector<Blob<Dtype>*> *param = this->GetParamBuf()->FindFreeParam(); if (param == NULL) { param = this->GetParamBuf()->CreateParam(root_params); } CHECK_EQ(root_params.size(), param->size()); for (int i = 0; i < root_params.size(); i++) { CHECK_EQ(root_params[i]->count(), param->at(i)->count()); if (root_params[i]->cpu_data() != param->at(i)->cpu_data()) { ParamHelper<Dtype>::BlasCopy(root_params[i]->count(), root_params[i]->cpu_data(), param->at(i)->mutable_cpu_data()); root_params[i]->ShareData(*param->at(i)); } } ParamHelper<Dtype>::CopyDiffFromNet(proot->net(), pgroup_solver->net()); // scaling gradients Dtype s = (Dtype)(1.0 / (Dtype)(num_conv_workers_ * this->num_sub_solvers_)); ParamHelper<Dtype>::ScalDiff(proot->net(), s); proot->CommitGradient(); if (bcast_addrs.size() == 0) { group_loss_vec_[group_id] *= s; LOG(INFO) << "train iteration: " << train_iter_ << " loss: " << group_loss_vec_[group_id]; } ClearGroup(group_id); // switch the working param this->GetParamBuf()->ReplaceParam(param); #ifdef USE_MKL // reset mkl threads mkl_set_num_threads_local(this->omp_threads_); #endif #if 0 ParamHelper<Dtype>::PrintParam(proot->net()); ParamHelper<Dtype>::PrintDiff(proot->net()); #endif UpdateClock(); if (train_iter_ == max_iter_) { StopModelServer(); } if (test_node_id_ > 0 && (train_iter_ % TRAIN_NOTIFY_INTERVAL == 0 || train_iter_ > max_iter_) && bcast_addrs.size() == 0 ) { this->SendNotify(); } if (test_node_id_ < 0 && train_iter_ > max_iter_) { return -1; } return 0; } template <typename Dtype> void FcParamThread<Dtype>::StopModelServer() { string ms_addr(NodeEnv::model_server_addr()); int node_id = NodeEnv::Instance()->ID(); shared_ptr<SkSock> dealer(new SkSock(ZMQ_DEALER)); dealer->SetId(node_id); dealer->Connect(ms_addr); shared_ptr<Msg> m(new Msg()); m->set_type(EXIT_TRAIN); m->set_src(node_id); m->set_clock(train_iter_); int pad = 0; m->AppendData(&pad, sizeof(pad)); dealer->SendMsg(m); // notify id server shared_ptr<SkSock> req(new SkSock(ZMQ_REQ)); string id_addr(NodeEnv::id_server_addr()); req->Connect(id_addr); req->SendMsg(m); } template <typename Dtype> void FcParamThread<Dtype>::UpdateClock() { train_iter_++; shared_ptr<Msg> r(new Msg()); r->set_type(UPDATE_CLOCK); r->set_dst(WORKER_BCAST); r->set_src(NodeEnv::Instance()->ID()); r->set_clock(train_iter_); r->AppendData(&train_iter_, sizeof(train_iter_)); this->SendMsg(r); } template <typename Dtype> void FcParamThread<Dtype>::SendNotify() { shared_ptr<Msg> r(new Msg()); r->set_type(TRAIN_ITER); r->set_dst(test_node_id_); r->set_src(NodeEnv::Instance()->ID()); r->AppendData(&train_iter_, sizeof(train_iter_)); // LOG(INFO) << "sending notify"; this->SendMsg(r); } template <typename Dtype> int FcParamThread<Dtype>::SendParam(shared_ptr<Msg> m) { shared_ptr<Msg> r(new Msg()); r->set_type(PUT_PARAM); r->set_dst(m->src()); r->set_src(NodeEnv::Instance()->ID()); Solver<Dtype> *psolver = (Solver<Dtype> *)NodeEnv::Instance()->GetRootSolver(); shared_ptr<Net<Dtype> > net = psolver->net(); ParamHelper<Dtype>::CopyParamDataToMsg(net, net->layer_names(), r); // LOG(INFO) << "sending param"; this->SendMsg(r); if (train_iter_ > max_iter_) { return -1; } return 0; } template <typename Dtype> void FcParamThread<Dtype>::Run() { #ifdef USE_MKL // get the number of omp threads in each worker int fc_omp_threads = mkl_get_max_threads(); if (this->omp_threads_ > 0) { mkl_set_num_threads_local(this->omp_threads_); } int n = mkl_get_max_threads(); LOG(INFO) << "max mkl threads in param thread: " << n; this->omp_threads_ = n; total_omp_threads_ = fc_omp_threads * fc_threads_ + n; mkl_set_dynamic(false); #endif // use the root solver Caffe::set_root_solver(true); while (!this->must_stop()) { shared_ptr<Msg> m = this->RecvMsg(true); if (m->type() == GET_PARAM) { test_node_id_ = m->src(); if (SendParam(m) < 0) { this->SendExit(); return; } } else if (m->type() == EXIT_TRAIN) { // exit training this->SendExit(); return; } else { if (UpdateParam(m) < 0) { this->SendExit(); return; } } } } INSTANTIATE_CLASS(ParamBuf); INSTANTIATE_CLASS(FcWorker); INSTANTIATE_CLASS(FcThread); INSTANTIATE_CLASS(FcLossThread); INSTANTIATE_CLASS(FcParamThread); } // end namespace caffe
27.277852
80
0.635026
AIROBOTAI
88c838d2c91fe5fe7986ecd1f2f442f8990ce5c5
4,497
hh
C++
firmware/src/MightyBoard/shared/LcdBoard.hh
MalyanSystem/Malyan-M180-Sailfish
8dd1ee7178a631f0e54c10db91ab3a18b370c363
[ "AAL" ]
2
2020-08-16T00:24:59.000Z
2021-03-17T10:37:18.000Z
firmware/src/MightyBoard/shared/LcdBoard.hh
MalyanSystem/Malyan-M180-Sailfish
8dd1ee7178a631f0e54c10db91ab3a18b370c363
[ "AAL" ]
null
null
null
firmware/src/MightyBoard/shared/LcdBoard.hh
MalyanSystem/Malyan-M180-Sailfish
8dd1ee7178a631f0e54c10db91ab3a18b370c363
[ "AAL" ]
1
2015-02-01T08:47:20.000Z
2015-02-01T08:47:20.000Z
/* * Copyright 2013 by Yongzong Lin <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ #ifndef LCD_BOARD_HH_ #define LCD_BOARD_HH_ #include "Configuration.hh" #include "Menu.hh" #define SCREEN_STACK_DEPTH 7 /// The LcdBoard module provides support for the Malyan System LCD Interface. /// \ingroup HardwareLibraries class LcdBoard { public: private: uint8_t buff_obj[8]; uint8_t buff_value[12]; uint8_t buff_ptr,buff_state; /// Stack of screens to display; the topmost one will actually /// be drawn to the screen, while the other will remain resident /// but not active. uint8_t screenStack[SCREEN_STACK_DEPTH]; int8_t screenIndex; ///< Stack index of the current screen. /// TODO: Delete this. bool building; ///< True if the bot is building uint8_t waitingMask; ///< Mask of buttons the interface is ///< waiting on. bool screen_locked; /// set to true in case of catastrophic failure (ie heater cuttoff triggered) uint16_t buttonRepetitions; /// Number of times a button has been repeated whilst held down /// used for continuous buttons and speed scaling of incrementers/decrementers bool lockoutButtonRepetitionsClear; /// Used to lockout the clearing of buttonRepetitions void ListFile(uint8_t index); public: LcdBoard(); void writeInt(uint16_t value, uint8_t digits); void writeInt32(uint32_t value, uint8_t digits); void process(); void PrintingStatus(); /// Initialze the interface board. This needs to be called once /// at system startup (or reset). void init(); /// This should be called periodically by a high-speed interrupt to /// service the button input pad. void doInterrupt(); /// This is called for a specific button and returns true if the /// button is currently depressed bool isButtonPressed(uint8_t button); /// Add a new screen to the stack. This automatically calls reset() /// and then update() on the screen, to ensure that it displays /// properly. If there are more than SCREEN_STACK_DEPTH screens already /// in the stack, than this function does nothing. /// \param[in] newScreen Screen to display. void pushScreen(uint8_t newScreen); /// Remove the current screen from the stack. If there is only one screen /// being displayed, then this function does nothing. void popScreen(); /// Return a pointer to the currently displayed screen. uint8_t getCurrentScreen() { return screenStack[screenIndex]; } micros_t getUpdateRate(); void doUpdate(); void showMonitorMode(); void setLED(uint8_t id, bool on); /// Tell the interface board that the system is waiting for a button push /// corresponding to one of the bits in the button mask. The interface board /// will not process button pushes directly until one of the buttons in the /// mask is pushed. void waitForButton(uint8_t button_mask); /// Check if the expected button push has been made. If waitForButton was /// never called, always return true. bool buttonPushed(); /// push Error Message Screen void errorMessage(uint8_t errid, bool incomplete = false); /// lock screen so that no pushes/pops can occur /// used in the case of heater failure to force restart void lock(){ screen_locked = true;} /// push screen onto the stack but don't update - this is used to create /// screen queue void pushNoUpdate(uint8_t newScreen); /// re-initialize LCD void resetLCD(); /// Returns the number of times a button has been held down /// Only applicable to continuous buttons uint16_t getButtonRepetitions(void); }; #endif
34.592308
117
0.683567
MalyanSystem
88cbb50b6aeae06e424b64a97f1ff0b684e81f2c
2,868
cpp
C++
BinaryTree.cpp
unigoetheradaw/AbstractDataTypes
5e91af09d159afe68dbb4c19de9387b2139ea5e7
[ "MIT" ]
null
null
null
BinaryTree.cpp
unigoetheradaw/AbstractDataTypes
5e91af09d159afe68dbb4c19de9387b2139ea5e7
[ "MIT" ]
null
null
null
BinaryTree.cpp
unigoetheradaw/AbstractDataTypes
5e91af09d159afe68dbb4c19de9387b2139ea5e7
[ "MIT" ]
null
null
null
// // Created by Robert on 18/09/2019. // #include <iostream> #include <stdio.h> #include <array> #include <iomanip> using namespace std; class BinaryTree { private: typedef struct Node { int data; Node *left = nullptr; Node *right = nullptr; }; Node *root; public: BinaryTree() { root = new Node; root->data = 50; root->left = nullptr; root->right = nullptr; cout << "Root at: " << &root << endl; } Node *getRoot() { return root; } static Node *generateNode(int data) { Node *temp = new Node(); temp->data = data; temp->left = nullptr; temp->right = nullptr; return temp; } void insert(Node *temp, int data) { if (temp->data > data) { if (temp->left != nullptr) { insert(temp->left, data); } else { temp->left = generateNode(data); } } else { if (temp->right != nullptr) { insert(temp->right, data); } else { temp->right = generateNode(data); } } } void inorder(Node *temp, int indent = 0) { if (temp == nullptr) { return; } inorder(temp->left, indent + 1); cout<< " " << indent << " "<< temp->data; inorder(temp->right, indent + 1); } void postorder(Node *temp, int indent = 0) { if (temp == nullptr) { return; } inorder(temp->left, indent + 1); inorder(temp->right, indent + 1); cout<< " " << indent << " "<< temp->data; } void preorder(Node *temp, int indent = 0) { if (temp == nullptr) { return; } cout<< " " << indent << " "<< temp->data; inorder(temp->left, indent + 1); inorder(temp->right, indent + 1); } int isBalanced(Node* temp, int i = 0) { if (temp == nullptr) { return 0; } else { cout << isBalanced(temp->left, i+1) << endl; cout << isBalanced(temp->left, i+1) << endl; } } int depth(Node* temp) { if (temp == nullptr) { return 0; } else { return max(depth(temp->left)+1, depth(temp->right)+1); } } }; int main() { BinaryTree a = *new BinaryTree; a.insert(a.getRoot(), 1); a.insert(a.getRoot(), 55); a.insert(a.getRoot(), 20); a.insert(a.getRoot(), 56); a.insert(a.getRoot(), 98); cout << a.depth(a.getRoot()) << endl; a.postorder(a.getRoot()); cout <<"\n"; a.preorder(a.getRoot()); cout <<"\n"; a.isBalanced(a.getRoot(), 0); return 0; }
23.9
67
0.448396
unigoetheradaw
88d5ff603da09a240e513f72962a969765012868
100
hh
C++
source/src/hardware/driver/serial/pwmcontroller.hh
Dr-MunirShah/black-sheep
e908203d9516e01f90f4ed4c796cf4143d0df0c0
[ "MIT" ]
7
2019-07-25T10:06:31.000Z
2021-02-20T06:00:51.000Z
source/src/hardware/driver/serial/pwmcontroller.hh
Dr-MunirShah/black-sheep
e908203d9516e01f90f4ed4c796cf4143d0df0c0
[ "MIT" ]
null
null
null
source/src/hardware/driver/serial/pwmcontroller.hh
Dr-MunirShah/black-sheep
e908203d9516e01f90f4ed4c796cf4143d0df0c0
[ "MIT" ]
1
2019-08-31T23:32:02.000Z
2019-08-31T23:32:02.000Z
#pragma once #include "serial.hh" class PWMController : public Serial{ using Serial::Serial; };
12.5
36
0.72
Dr-MunirShah
88d8e2a584a1e2ff43810daacdcc69315a79e0bf
6,678
cpp
C++
test/TestAlgorithm.cpp
AdrianWR/ft_containers
a6b519806448853b97dff385cf72dfc0e97c8ea2
[ "MIT" ]
null
null
null
test/TestAlgorithm.cpp
AdrianWR/ft_containers
a6b519806448853b97dff385cf72dfc0e97c8ea2
[ "MIT" ]
3
2022-02-10T12:16:37.000Z
2022-03-24T03:15:01.000Z
test/TestAlgorithm.cpp
AdrianWR/ft_containers
a6b519806448853b97dff385cf72dfc0e97c8ea2
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include "algorithm.hpp" #include <algorithm> #include <deque> #include <map> #include <string> #include <vector> bool pred_int(int a, int b) { return a == b; } bool pred_str(std::string a, std::string b) { return a == b; } bool pred_map(std::pair<int, int> a, std::pair<int, int> b) { return a == b; } bool comp_int(int a, int b) { return a < b; } bool comp_str(std::string a, std::string b) { return a < b; } bool comp_map(std::pair<int, int> a, std::pair<int, int> b) { return a < b; } // Tests ft::equal TEST(TestEqual, TestEqualTrue) { std::vector<int> v1 = {1, 2, 3, 4, 5}; std::vector<int> v2 = {1, 2, 3, 4, 5}; std::vector<std::string> v3 = {"1", "2", "3", "4", "5"}; std::vector<std::string> v4 = {"1", "2", "3", "4", "5"}; std::map<int, int> m1 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}}; std::map<int, int> m2 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}}; // ASSERT_TRUE(ft::equal(v1.begin(), v1.end(), v2.begin())); EXPECT_TRUE(ft::equal(v1.begin(), v1.end(), v2.begin())); EXPECT_TRUE(ft::equal(v1.rbegin(), v1.rend(), v2.rbegin())); EXPECT_TRUE(ft::equal(v3.begin(), v3.end(), v4.begin())); EXPECT_TRUE(ft::equal(m1.begin(), m1.end(), m2.begin())); } TEST(TestEqual, TestEqualFalse) { std::vector<int> v1 = {1, 2, 3, 4, 5}; std::vector<int> v2 = {1, 2, 3, 4, 6}; std::map<int, int> m1 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}}; std::map<int, int> m2 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 6}}; std::deque<int> d1 = {1, 2, 3, 4, 5}; std::deque<int> d2 = {1, 2, 3, 4, 6}; EXPECT_FALSE(ft::equal(v1.begin(), v1.end(), v2.begin())); EXPECT_FALSE(ft::equal(v1.rbegin(), v1.rend(), v2.rbegin())); EXPECT_FALSE(ft::equal(m1.begin(), m1.end(), m2.begin())); EXPECT_FALSE(ft::equal(m1.rbegin(), m1.rend(), m2.rbegin())); EXPECT_FALSE(ft::equal(d1.begin(), d1.end(), d2.begin())); } TEST(TestEqual, TestEqualEmpty) { std::vector<int> v1; std::vector<int> v2; std::map<int, int> m1; std::map<int, int> m2; std::deque<int> d1; std::deque<int> d2; EXPECT_TRUE(ft::equal(v1.begin(), v1.end(), v2.begin())); EXPECT_TRUE(ft::equal(v1.rbegin(), v1.rend(), v2.rbegin())); EXPECT_TRUE(ft::equal(m1.begin(), m1.end(), m2.begin())); EXPECT_TRUE(ft::equal(m1.rbegin(), m1.rend(), m2.rbegin())); EXPECT_TRUE(ft::equal(d1.begin(), d1.end(), d2.begin())); } TEST(TestEqual, TestEqualPredicate) { std::vector<int> v1 = {1, 2, 3, 4, 5}; std::vector<int> v2 = {1, 2, 3, 4, 5}; std::vector<std::string> v3 = {"1", "2", "3", "4", "5"}; std::vector<std::string> v4 = {"1", "2", "3", "4", "5"}; std::map<int, int> m1 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}}; std::map<int, int> m2 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}}; EXPECT_TRUE(ft::equal(v1.begin(), v1.end(), v2.begin(), pred_int)); EXPECT_TRUE(ft::equal(v1.rbegin(), v1.rend(), v2.rbegin(), pred_int)); EXPECT_TRUE(ft::equal(v3.begin(), v3.end(), v4.begin(), pred_str)); EXPECT_TRUE(ft::equal(v3.rbegin(), v3.rend(), v4.rbegin(), pred_str)); EXPECT_TRUE(ft::equal(m1.begin(), m1.end(), m2.begin(), pred_map)); EXPECT_TRUE(ft::equal(m1.rbegin(), m1.rend(), m2.rbegin(), pred_map)); } TEST(TestEqual, TestEqualDifferentContainers) { int v0[] = {1, 2, 3, 4, 5}; std::vector<int> v1 = {1, 2, 3, 4, 5}; EXPECT_TRUE(ft::equal(v1.begin(), v1.end(), v0)); EXPECT_TRUE(ft::equal(v1.begin(), v1.end(), v0, pred_int)); } // Tests ft::lexicographical_compare TEST(TestLexicographicalCompare, TestLexicographicalCompareEqual) { std::vector<int> v1 = {1, 2, 3, 4, 5}; std::vector<int> v2 = {1, 2, 3, 4, 5}; std::vector<std::string> v3 = {"1", "2", "3", "4", "5"}; std::vector<std::string> v4 = {"1", "2", "3", "4", "5"}; std::map<int, int> m1 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}}; std::map<int, int> m2 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}}; EXPECT_FALSE( ft::lexicographical_compare(v1.begin(), v1.end(), v2.begin(), v2.end())); EXPECT_FALSE(ft::lexicographical_compare(v1.rbegin(), v1.rend(), v2.rbegin(), v2.rend())); EXPECT_FALSE( ft::lexicographical_compare(v3.begin(), v3.end(), v4.begin(), v4.end())); EXPECT_FALSE(ft::lexicographical_compare(v3.rbegin(), v3.rend(), v4.rbegin(), v4.rend())); EXPECT_FALSE( ft::lexicographical_compare(m1.begin(), m1.end(), m2.begin(), m2.end())); EXPECT_FALSE(ft::lexicographical_compare(m1.rbegin(), m1.rend(), m2.rbegin(), m2.rend())); } TEST(TestLexicographicalCompare, TestLexicographicalCompareLess) { std::vector<int> v1 = {1, 2, 3, 4, 5}; std::vector<int> v2 = {1, 2, 3, 4, 6}; std::map<int, int> m1 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}}; std::map<int, int> m2 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 6}}; std::deque<int> d1 = {1, 2, 3, 4, 5}; std::deque<int> d2 = {1, 2, 3, 4, 6}; EXPECT_TRUE( ft::lexicographical_compare(v1.begin(), v1.end(), v2.begin(), v2.end())); EXPECT_TRUE( ft::lexicographical_compare(m1.begin(), m1.end(), m2.begin(), m2.end())); EXPECT_TRUE( ft::lexicographical_compare(d1.begin(), d1.end(), d2.begin(), d2.end())); } TEST(TestLexicographicalCompare, TestLexicographicalCompareGreater) { std::vector<int> v1 = {1, 2, 3, 4, 5}; std::vector<int> v2 = {1, 2, 3, 4, 4}; std::map<int, int> m1 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}}; std::map<int, int> m2 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 4}}; std::deque<int> d1 = {1, 2, 3, 4, 5}; std::deque<int> d2 = {1, 2, 3, 4, 4}; EXPECT_FALSE( ft::lexicographical_compare(v1.begin(), v1.end(), v2.begin(), v2.end())); EXPECT_FALSE( ft::lexicographical_compare(m1.begin(), m1.end(), m2.begin(), m2.end())); EXPECT_FALSE( ft::lexicographical_compare(d1.begin(), d1.end(), d2.begin(), d2.end())); } TEST(TestLexicographicalCompare, TestLexicographicalCompareCompFunc) { std::vector<int> v1 = {1, 2, 3, 4, 5}; std::vector<int> v2 = {1, 2, 3, 4, 6}; std::map<int, int> m1 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}}; std::map<int, int> m2 = {{1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 6}}; std::vector<std::string> v3 = {"1", "2", "3", "4", "5"}; std::vector<std::string> v4 = {"1", "2", "3", "4", "6"}; EXPECT_TRUE(ft::lexicographical_compare(v1.begin(), v1.end(), v2.begin(), v2.end(), comp_int)); EXPECT_TRUE(ft::lexicographical_compare(v3.begin(), v3.end(), v4.begin(), v4.end(), comp_str)); EXPECT_TRUE(ft::lexicographical_compare(m1.begin(), m1.end(), m2.begin(), m2.end(), comp_map)); }
41.7375
79
0.549117
AdrianWR
88de24f2162a886a0a7fc0f5fe81527bf16e7306
801
cpp
C++
PATest_paractice/PAT_1005.cpp
Ginuo/DataStructure_Algorithm
3db0b328eeab9270fca14123061551de087d186c
[ "Apache-2.0" ]
null
null
null
PATest_paractice/PAT_1005.cpp
Ginuo/DataStructure_Algorithm
3db0b328eeab9270fca14123061551de087d186c
[ "Apache-2.0" ]
null
null
null
PATest_paractice/PAT_1005.cpp
Ginuo/DataStructure_Algorithm
3db0b328eeab9270fca14123061551de087d186c
[ "Apache-2.0" ]
null
null
null
#include<cstdio> #include<cstring> int main(){ char num[110]; gets(num); int len = strlen(num); int sum = 0; for(int i = 0; i < len; i++){ sum = sum + (num[i] - '0'); } int ans[100]; int index = 0; do{ ans[index++] = sum % 10; sum = sum / 10; }while(sum != 0); for(int i = index-1 ; i >= 0; i--){ switch(ans[i]){ case 0: printf("zero"); break; case 1: printf("one"); break; case 2: printf("two"); break; case 3: printf("three"); break; case 4: printf("four"); break; case 5: printf("five"); break; case 6: printf("six"); break; case 7: printf("seven"); break; case 8: printf("eight"); break; case 9: printf("nine"); break; } if(i > 0) printf(" "); } return 0; }
14.052632
36
0.486891
Ginuo
88df77e9b7aab27a0fce060078d0e5d3c0ee4812
349
cpp
C++
Problems/0026. Remove Duplicates from Sorted Array.cpp
KrKush23/LeetCode
2a87420a65347a34fba333d46e1aa6224c629b7a
[ "MIT" ]
null
null
null
Problems/0026. Remove Duplicates from Sorted Array.cpp
KrKush23/LeetCode
2a87420a65347a34fba333d46e1aa6224c629b7a
[ "MIT" ]
null
null
null
Problems/0026. Remove Duplicates from Sorted Array.cpp
KrKush23/LeetCode
2a87420a65347a34fba333d46e1aa6224c629b7a
[ "MIT" ]
null
null
null
#define pb push_back class Solution { public: int removeDuplicates(vector<int>& nums) { vector<int> v = nums; nums.clear(); if(v.empty()) return 0; nums.pb(v[0]); for(int i=1;i<(int)v.size();i++) if(v[i]!=v[i-1]) nums.pb(v[i]); return nums.size(); } };
21.8125
45
0.461318
KrKush23
88e0f213a66a9ca4bda465c4039eb14e71d9b10f
11,031
cpp
C++
Generation.cpp
DiscoveryInstitute/coaly
3b9617b13887ae30423b192dcf89526d84b64d29
[ "MIT" ]
null
null
null
Generation.cpp
DiscoveryInstitute/coaly
3b9617b13887ae30423b192dcf89526d84b64d29
[ "MIT" ]
null
null
null
Generation.cpp
DiscoveryInstitute/coaly
3b9617b13887ae30423b192dcf89526d84b64d29
[ "MIT" ]
null
null
null
#include "Generation.h" #include <cmath> #include <limits> #include <numeric> #include <vector> using namespace std; const double EPSILON = numeric_limits<double>::epsilon(); /** * Given lambda, the expected number of ancestral children per member of the population, * calculate the probability of having 'ic' ancestral children on the assumption that * the parent has one or more ancestral children. This is the probability of 'ic' lineages * coalescing into one lineage. These probabilities are calculated up to 'max_coalescent' * or until they are numerically negligible. * * The 0th index of the array contains a special case: the probability of having no children. * This quantity is useful for calculating the expected ancestral parent population. */ vector<double> getCoalescenceProbabilities(double n, double p, int max_coalescent) { const double lambda = n * p; const double eml = exp(-lambda); vector<double> coal_probs; coal_probs.reserve(max_coalescent+1); coal_probs.push_back(eml); // special case: p(n=0) double coal_p = eml / (1.0 - eml); // p(n given n!=0) for (long ic=1; ic<=max_coalescent; ++ic) { coal_p *= lambda / ic; // probability that one ancestor has 'ic' ancestral children if (coal_p < EPSILON && lambda < ic) break; coal_probs.push_back(coal_p); } return coal_probs; } /* vector<double> getCoalescenceProbabilities(double n, double p, int max_coalescent) { const double lambda = n * p; vector<double> coal_probs; coal_probs.reserve(max_coalescent+1); const double p0 = pow(1.0-p, n); coal_probs.push_back(p0); // special case: p(n=0) double pre = 1.0 / (1.0 - p0); // p(n given n!=0) double logp = log(p); double logq = log(1.0-p); for (long ic=1; ic<=max_coalescent; ++ic) { double coal_p = pre*exp(lgamma(n+1) -lgamma(ic+1)-lgamma(n-ic+1) + ic*logp +(n-ic)*logq); // probability that one ancestor has 'ic' ancestral children if (coal_p < EPSILON && lambda < ic) break; coal_probs.push_back(coal_p); } return coal_probs; } */ /** * Calculate coalescence for one generation. */ void Generation::coalesceOneGeneration(double new_total_popn) { const auto& weights = this->number_of_descendants_distribution; const long sample_popn = weights.size()-1; const double n = this->ancestral_population; const double p = 1.0 / new_total_popn; vector<double> coal_probs = getCoalescenceProbabilities(n, p, sample_popn); this->total_population = new_total_popn; this->ancestral_population = new_total_popn * (1.0 - coal_probs[0]); this->coalescence_probabilities = move(coal_probs); updateSample(); } /** Determines whether or not probabilities warrant an update of the sample */ inline bool maxed(vector<double>& probs, int imax) { while (!probs.empty() && probs.back() < EPSILON) probs.pop_back(); return (probs.size() > (size_t)imax); } /** * Calculate coalescence for one generation, * but don't update whole sample unless the probabilities warrant it. */ void Generation::coalesceLiteOneGeneration(double new_total_popn, int max_coalescent){ const auto& weights = this->number_of_descendants_distribution; const long sample_popn = weights.size(); const double n = this->ancestral_population; const double p = 1.0 / new_total_popn; vector<double>& accum_probs = this->coalescence_probabilities; vector<double> coal_probs = getCoalescenceProbabilities(n, p, sample_popn); this->total_population = new_total_popn; this->ancestral_population = new_total_popn * (1.0 - coal_probs[0]); // If lots of coalescence this gen, update the sample to flush any existing probabilities. if (maxed(coal_probs, max_coalescent)) { updateSample(); // update to flush existing probabilities first accum_probs = move(coal_probs); updateSample(); // update with new probabilities return; } // If there are no accumulated probabilities (and current probabilities are not maxed), // the initial assignment is simple. if (accum_probs.empty()) { accum_probs = move(coal_probs); return; } // Compare this section with the section for coalescing the whole sample coal_probs.resize(max_coalescent+1); accum_probs.resize(max_coalescent+1); vector<double> new_accum_probs(max_coalescent+1); vector<double> uvec = accum_probs; vector<double> new_uvec(uvec.size()); for (long i=1; i<=max_coalescent; ++i) new_accum_probs[i] = coal_probs[1] * uvec[i]; for (long ic=2; ic<=max_coalescent; ++ic) { fill(new_uvec.begin(), new_uvec.end(), 0.0); for(long i=ic; i<=max_coalescent; ++i) { long pic = ic-1; for(long j=1; j<=i-pic; ++j) { new_uvec[i] += accum_probs[j] * uvec[i-j]; } if (new_uvec[i] < EPSILON && i > 0 && new_uvec[i-1] >= new_uvec[i]) break; } uvec.swap(new_uvec); for(long i=ic;i<=max_coalescent;++i) { new_accum_probs[i] += coal_probs[ic] * uvec[i]; } } this->coalescence_probabilities = move(new_accum_probs); if (maxed(accum_probs, max_coalescent)) updateSample(); } /** * Update the sample (number_of_descendants_distribution) using * the stored coalescence probabilities, * which might be just from this generation, * or may have been accumulated over several generations. */ void Generation::updateSample() { const auto& weights = this->number_of_descendants_distribution; const long sample_popn = weights.size(); vector<double>& coal_probs = this->coalescence_probabilities; while (!coal_probs.empty() && coal_probs.back()<EPSILON) coal_probs.pop_back(); const long max_ic = coal_probs.size()-1; if (max_ic < 2) return; vector<double> new_weights(sample_popn, 0.0); // uvec_n is a helper vector that can be thought of as weights^n // uvec_1[i] is just weights[i] // uvec_2[i] is sum_j weights[j] * weights[i-j] // uvec_3[i] is sum_jk weights[j] * weights[k] * weights[i-j-k] vector<double> uvec = weights; vector<double> new_uvec(uvec.size()); for(long i=1;i<sample_popn;++i) new_weights[i] += coal_probs[1] * uvec[i]; // For each number of ancestral children ic >= 2 for (long ic=2; ic<=max_ic; ++ic) { // Update uvec_ic -> uvec_(ic+1); fill(new_uvec.begin(), new_uvec.end(), 0.0); for(long i=ic; i<sample_popn; ++i) { long pic = ic-1; for(long j=1; j<=i-pic; ++j) { new_uvec[i] += weights[j] * uvec[i-j]; } if (new_uvec[i] < EPSILON && i > 0 && new_uvec[i-1] >= new_uvec[i]) break; } uvec.swap(new_uvec); // Add a contribution to the weights for(long i=ic;i<sample_popn;++i) { new_weights[i] += coal_probs[ic] * uvec[i]; } } this->number_of_descendants_distribution = move(new_weights); this->coalescence_probabilities.clear(); } /** * Add mutations at the given rate, incrementing the allele frequency spectrum using * the number_of_descendants_distribution at this generation. */ void Generation::incrementAlleleFrequencySpectrumMutations( vector<double>& afs, const double mutation_rate) const { const double prefactor = this->ancestral_population * mutation_rate; const auto& weight = this->number_of_descendants_distribution; for (size_t i=1; i<weight.size(); ++i) afs[i] += prefactor * weight[i]; } /** Combinatorial function, "N choose m" or C^n_m = n!/(m!(n-m)!) */ double n_choose_m(int ni, int mi) { double n = (double)ni; double m = (double)min(mi, ni-mi); double numerator = 1.0; for (int i=0; i<m; ++i) numerator *= (double)(n-i); double denominator = 1.0; for (int i=2; i<=m; ++i) denominator *= (double)i; return numerator / denominator; } /** * Add genetic diversity from 1,2,3,... founders, incrementing the allele frequency spectrum * using the number_of_descendants_distribution for that number of founders. */ void Generation::incrementAlleleFrequencySpectrumFoundingDiversity( vector<double>& afs, const vector<double>& founding_diversity) const { const vector<double>& weights = this->number_of_descendants_distribution; const long sample_popn = weights.size(); const long max_ic = founding_diversity.size() - 1; if (max_ic < 1) return; // First transform founding diversity into ancestral founding diversity. vector<double> ancestral_diversity(max_ic+1); double pnonzero = this->ancestral_population / this->total_population; double pzero = 1.0 - pnonzero; for (int i=1;i<=max_ic;++i) { for (int j=i;j<=max_ic;++j) { double pij = pow(pnonzero,i) * pow(pzero,j-i) * n_choose_m(j,i); ancestral_diversity[i] += pij * founding_diversity[j]; } } // Add contributions to the Allele Frequency Spectrum vector<double> uvec = weights; vector<double> new_uvec(uvec.size()); // For single founders for(long i=1;i<sample_popn;++i) afs[i] += ancestral_diversity[1] * uvec[i]; // For multiple founders for (int ic=2; ic<=max_ic; ++ic) { // Update uvec_ic -> uvec_(ic+1); fill(new_uvec.begin(), new_uvec.end(), 0.0); for(long i=ic; i<sample_popn; ++i) { long pic = ic-1; for(long j=1; j<=i-pic; ++j) { new_uvec[i] += weights[j] * uvec[i-j]; } if (new_uvec[i] < EPSILON && i > 0 && new_uvec[i-1] >= new_uvec[i]) break; } uvec.swap(new_uvec); // Add a contribution to the weights for(long i=ic;i<sample_popn;++i) { afs[i] += ancestral_diversity[ic] * uvec[i]; } } } /** Calculate AFS using the population history, mutation rate history, and any founding diversity. */ vector<double> Generation::calculateAFS(const double sample_popn, const vector<double>& popn_history, const vector<double>& mutn_history, const vector<double>& founding_diversity) { const int max_coalescent = 10; Generation generation (popn_history[0], sample_popn); vector<double> afs(sample_popn+1, 0.0); const long ngens = popn_history.size(); for (long igen = 0; igen < ngens; ++igen) { generation.coalesceLiteOneGeneration(popn_history[igen], max_coalescent); generation.incrementAlleleFrequencySpectrumMutations(afs, mutn_history[igen]); } generation.incrementAlleleFrequencySpectrumFoundingDiversity(afs, founding_diversity); return afs; }
39.823105
159
0.637567
DiscoveryInstitute
88e10f35fbebe90c460f2cc957b8d6446c2f40f4
11,947
cpp
C++
src/core/cruntimetracker.cpp
squigglepuff/XonMap
3c426c9fd66eda77c34d78dd45566062c702f6b9
[ "Apache-2.0" ]
null
null
null
src/core/cruntimetracker.cpp
squigglepuff/XonMap
3c426c9fd66eda77c34d78dd45566062c702f6b9
[ "Apache-2.0" ]
null
null
null
src/core/cruntimetracker.cpp
squigglepuff/XonMap
3c426c9fd66eda77c34d78dd45566062c702f6b9
[ "Apache-2.0" ]
null
null
null
#include "core/cruntimetracker.h" std::unique_ptr<GlobalCVariables> g_pCVars; std::unique_ptr<CRuntimeTracker> g_CrtTracker{new CRuntimeTracker}; // These are local to this module only! #if defined(Q_OS_WINDOWS) static PDH_HQUERY gCpuQuery; static PDH_HCOUNTER gCpuTotal; #endif //#if (Q_OS_WINDOWS). CRuntimeTracker::CRuntimeTracker() { // Intentionally left blank. } CRuntimeTracker::~CRuntimeTracker() { // Intentionally left blank. } Error_t CRuntimeTracker::Init() { Error_t iRtn = SUCCESS; // Attempt to reset the pointer back to a sane state. g_pCVars.reset(new GlobalCVariables); // WINDOWS ONLY! Setup the PDH and Symbol stuff. #if defined(Q_OS_WINDOWS) PdhOpenQuery(NULL, NULL, &gCpuQuery); PdhAddEnglishCounter(gCpuQuery, "\\Processor(_Total)\\% Processor Time", NULL, &gCpuTotal); SymSetOptions(SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS); SymInitialize(GetCurrentProcess(), NULL, TRUE); #endif //#if defined(Q_OS_WINDOWS). if (nullptr == g_pCVars) { iRtn = Err_Ptr_AllocFail; } else { iRtn = Update(); } return iRtn; } Error_t CRuntimeTracker::Update() { Error_t iRtn = SUCCESS; #if defined(Q_OS_WINDOWS) // Grab system memory statistics. MEMORYSTATUSEX lMemInfo; lMemInfo.dwLength = sizeof(MEMORYSTATUSEX); if (0 != GlobalMemoryStatusEx(&lMemInfo)) { DWORDLONG iFreeVirtMem = lMemInfo.ullAvailPageFile; DWORDLONG iTotalVirtMem = lMemInfo.ullTotalPageFile; DWORDLONG iUsedVirtMem = iTotalVirtMem - iFreeVirtMem; // Update the CVar. g_pCVars->mMemSysTotal = static_cast<float>(iTotalVirtMem) / 1024 / 1024; g_pCVars->mMemSysFree = static_cast<float>(iFreeVirtMem) / 1024 / 1024; g_pCVars->mMemSysUsed = static_cast<float>(iUsedVirtMem) / 1024 / 1024; // Grab the process memory statistics. PROCESS_MEMORY_COUNTERS lProcMemCnt; if (0 != GetProcessMemoryInfo(GetCurrentProcess(), &lProcMemCnt, sizeof(lProcMemCnt))) { SIZE_T iProcMemUsage = lProcMemCnt.PagefileUsage; // Update the CVar. g_pCVars->mMemProcUsed = static_cast<float>(iProcMemUsage) / 1024 / 1024; // Grab the CPU stats for the system. PDH_FMT_COUNTERVALUE lCountVal; PDH_STATUS lStatus = PdhCollectQueryData(gCpuQuery); if (ERROR_SUCCESS == lStatus) { lStatus = PdhGetFormattedCounterValue(gCpuTotal, PDH_FMT_DOUBLE, NULL, &lCountVal); if (ERROR_SUCCESS == lStatus) { // Update the CVar. g_pCVars->mCPUSysUsage = static_cast<float>(lCountVal.doubleValue); // If needed, we can setup any network statistics right here. } else if (lStatus == PDH_INVALID_ARGUMENT) { fprintf(stderr, "ERR: A parameter is not valid or is incorrectly formatted.\n"); iRtn = GetLastError(); } else if (lStatus == PDH_INVALID_DATA) { fprintf(stderr, "ERR: The specified counter does not contain valid data or a successful status code.\n"); iRtn = SUCCESS; } else if (lStatus == PDH_INVALID_HANDLE) { fprintf(stderr, "ERR: The counter handle is not valid.\n"); iRtn = GetLastError(); } else { iRtn = GetLastError(); } } else if (lStatus == PDH_INVALID_ARGUMENT) { fprintf(stderr, "ERR: A parameter is not valid or is incorrectly formatted.\n"); iRtn = GetLastError(); } else if (lStatus == PDH_INVALID_DATA) { fprintf(stderr, "ERR: The specified counter does not contain valid data or a successful status code.\n"); iRtn = SUCCESS; } else if (lStatus == PDH_INVALID_HANDLE) { fprintf(stderr, "ERR: The counter handle is not valid.\n"); iRtn = GetLastError(); } else { iRtn = GetLastError(); } } else { iRtn = GetLastError(); } } else { iRtn = GetLastError(); } #elif defined(Q_OS_LINUX) #else #endif //#if defined(Q_OS_WINDOWS) // Update the clock time. g_pCVars->mRuntime = clock(); // Done! return iRtn; } Error_t CRuntimeTracker::DumpStack() { Error_t iRtn = SUCCESS; const size_t ciMaxFrames = 63; const size_t ciMaxBuffSz = (0xFF) - 1; #if defined(Q_OS_WINDOWS) PVOID* pFrames = new PVOID[ciMaxFrames]; if (nullptr != pFrames) { memset(pFrames, 0, sizeof(PVOID)*ciMaxFrames); size_t iCapFrames = CaptureStackBackTrace(0, ciMaxFrames, pFrames, NULL); SYMBOL_INFO *pSymbol = new SYMBOL_INFO; if (nullptr != pSymbol) { pSymbol->MaxNameLen = 255; pSymbol->SizeOfStruct = sizeof(SYMBOL_INFO); char* pData = new char[ciMaxBuffSz]; memset(pData, 0, ciMaxBuffSz); if (nullptr != pData) { std::string lDumpStr = ""; for (size_t iIdx = 1; iIdx < iCapFrames; ++iIdx) // We start at 1 since we don't want to dump this function as part of the stack. { SymFromAddr(GetCurrentProcess(), reinterpret_cast<DWORD64>(pFrames[iIdx]), 0, pSymbol); sprintf(pData, "\t%zd: [0x%llX] %s\n", (iCapFrames - iIdx - 1), pSymbol->Address, pSymbol->Name); lDumpStr.append(pData); } // Log the data! #if defined(HAS_LOGGER) #else lDumpStr.append("\n"); fprintf(stdout, lDumpStr.c_str()); #endif //#if defined(HAS_LOGGER) if (nullptr != pData) { delete[] pData; } } else { iRtn = Err_Ptr_AllocFail; } // delete pSymbol; } else { iRtn = Err_Ptr_AllocFail; } delete[] pFrames; } else { iRtn = Err_Ptr_AllocFail; } #elif defined(Q_OS_LINUX) // backtrace(&sStack.mpStack, ciMaxFrames); #elif defined(Q_OS_OSX) #endif //#if defined(Q_OS_WINDOWS). return iRtn; } Error_t CRuntimeTracker::DumpStats(bool iReset) { Error_t iRtn = SUCCESS; const size_t ciMaxBuffSz = 65535; // Allocate a temporary buffer. char* pTmpBuff = new char[ciMaxBuffSz]; memset(pTmpBuff, 0, ciMaxBuffSz); std::string lStatsLine = "Dumping Runtime Statistics...\n"; // Time running. sprintf(pTmpBuff, "Runing time (CPU clocks): %ld\n", g_pCVars->mRuntime); lStatsLine.append(pTmpBuff); memset(pTmpBuff, 0, ciMaxBuffSz); // CPU stats. sprintf(pTmpBuff, "System CPU Usage: %f\n", g_pCVars->mCPUSysUsage); lStatsLine.append(pTmpBuff); memset(pTmpBuff, 0, ciMaxBuffSz); // Memory statistics. sprintf(pTmpBuff, "System Memory Total (MiB): %f\n", g_pCVars->mMemSysTotal); lStatsLine.append(pTmpBuff); memset(pTmpBuff, 0, ciMaxBuffSz); sprintf(pTmpBuff, "System Memory Used (MiB): %f\n", g_pCVars->mMemSysUsed); lStatsLine.append(pTmpBuff); memset(pTmpBuff, 0, ciMaxBuffSz); sprintf(pTmpBuff, "System Memory Free (MiB): %f\n", g_pCVars->mMemSysFree); lStatsLine.append(pTmpBuff); memset(pTmpBuff, 0, ciMaxBuffSz); sprintf(pTmpBuff, "Process Memory Used (MiB): %f\n", g_pCVars->mMemProcUsed); lStatsLine.append(pTmpBuff); memset(pTmpBuff, 0, ciMaxBuffSz); // Network statistics. sprintf(pTmpBuff, "Network Input (KiB): %f\n", g_pCVars->mNetIn); lStatsLine.append(pTmpBuff); memset(pTmpBuff, 0, ciMaxBuffSz); sprintf(pTmpBuff, "Network Output (KiB): %f\n", g_pCVars->mNetOut); lStatsLine.append(pTmpBuff); memset(pTmpBuff, 0, ciMaxBuffSz); // Complete! Dump the data to the log. #if defined(HAS_LOGGER) #else fprintf(stdout, lStatsLine.c_str()); #endif //#if defined(HAS_LOGGER) return iRtn; } std::string CRuntimeTracker::ErrorToString(Error_t iErr) { // Clear the old error. mErrStr.clear(); switch(iErr) { // Errors. case Err_Sig_Hangup: mErrStr = "Recieved a hangup signal! (SIGHUP)\n"; case Err_Sig_Quit: mErrStr = "Recieved a quit signal! (SIGQUIT)\n"; case Err_Sig_Illegal: mErrStr = "Recieved an illegal instruction signal! (SIGILL)\n"; case Err_Sig_Abort: mErrStr = "Recieved an abort signal! (SIGABRT)\n"; case Err_Sig_FloatExcept: mErrStr = "Recieved a floating point exception signal! (SIGFPE)\n"; case Err_Sig_Kill: mErrStr = "Recieved a kill signal! (SIGKILL)\n"; case Err_Sig_Bus: mErrStr = "Recieved a bus error signal! (SIGBUS)\n"; case Err_Sig_SegFault: mErrStr = "Recieved a segmentation fault signal! (SIGSEGV)\n"; case Err_Sig_SysCall: mErrStr = "Recieved a missing system call signal! (SIGSYS)\n"; case Err_Sig_Pipe: mErrStr = "Recieved a broken pipe signal! (SIGPIPE)\n"; case Err_Sig_Alarm: mErrStr = "Recieved an alarm signal! (SIGALRM)\n"; case Err_Sig_Terminate: mErrStr = "Recieved a terminate signal! (SIGTERM)\n"; case Err_Sig_XCPU: mErrStr = "Recieved an excessive CPU signal! (SIGXCPU)\n"; case Err_Sig_FSizeLimit: mErrStr = "Recieved an excessive filesize signal! (SIGXFSZ)\n"; case Err_Sig_VirtAlarm: mErrStr = "Recieved a virtual alarm signal! (SIGVTALRM)\n"; case Err_Sig_ProfAlarm: mErrStr = "Recieved a profile alarm signal! (SIGPROF)\n"; case Err_Ptr_AllocFail: mErrStr = "Was unable to allocate space for a pointer in the system!\n"; case Err_Ptr_AccessVio: mErrStr = "Was unable to access an invalid address or dangling pointer!\n"; case Err_OS_FuncFail: mErrStr = "An internal function has failed!\n"; // Warnings. case Warn_LowMemory: mErrStr = "System is low on memory"; case Warn_LowFD: mErrStr = "System is low on file descriptors"; case Warn_LowThreads: mErrStr = "System is low on available threads"; case Warn_LowSpace: mErrStr = "System is low on HDD space"; case Warn_INetDown: mErrStr = "System doesn't have an network connection"; case Warn_INetLimit: mErrStr = "System seems to have a LAN connection, but no internet."; default: mErrStr.clear(); // This cleared AGAIN just to be sure it's empty. } if (0 >= mErrStr.size()) { // We need to query the OS for an error string! #if defined(Q_OS_WINDOWS) const size_t ciMaxBuffSz = 65535; // Allocate a temporary buffer. char* pTmpBuff = new char[ciMaxBuffSz]; memset(pTmpBuff, 0, ciMaxBuffSz); // Grab the message. FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, iErr, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), pTmpBuff, ciMaxBuffSz, NULL); mErrStr.append(pTmpBuff); if (nullptr != pTmpBuff) { delete[] pTmpBuff; } #elif defined(Q_OS_LINUX) #else #endif //#if defined(Q_OS_WINDOWS) } if (0 >= mErrStr.size()) { mErrStr = "An unknown error has occured!\n"; } return mErrStr; } std::string CRuntimeTracker::GetLastErrorString() { return mErrStr; }
34.232092
167
0.594291
squigglepuff
88e1b0fc6478fec4b82d0773bd836b5a33f953f5
539
hpp
C++
kernel/frame_buffer.hpp
three-0-3/my-mikanos
e85f9e15d735babde1650c6fa87ffed210dece6d
[ "Apache-2.0" ]
null
null
null
kernel/frame_buffer.hpp
three-0-3/my-mikanos
e85f9e15d735babde1650c6fa87ffed210dece6d
[ "Apache-2.0" ]
null
null
null
kernel/frame_buffer.hpp
three-0-3/my-mikanos
e85f9e15d735babde1650c6fa87ffed210dece6d
[ "Apache-2.0" ]
null
null
null
#pragma once #include <memory> #include <vector> #include "error.hpp" #include "frame_buffer_config.hpp" #include "graphics.hpp" class FrameBuffer { public: // Initialize frame buffer by checking config Error Initialize(const FrameBufferConfig& config); FrameBufferWriter& Writer() { return *writer_; } private: FrameBufferConfig config_{}; std::vector<uint8_t> buffer_{}; // unique_ptr as this FrameBuffer owns FrameBufferWriter std::unique_ptr<FrameBufferWriter> writer_{}; }; int BitsPerPixel(PixelFormat format);
22.458333
58
0.755102
three-0-3
88e8a13a7f84538b0c31962a5996f038437f4554
3,112
cpp
C++
BroadCast_QT/group.cpp
mickelfeng/qt_learning
1f565754c36f0c09888cf4fbffa6271298d0678b
[ "Apache-2.0" ]
1
2016-01-05T07:24:32.000Z
2016-01-05T07:24:32.000Z
BroadCast_QT/group.cpp
mickelfeng/qt_learning
1f565754c36f0c09888cf4fbffa6271298d0678b
[ "Apache-2.0" ]
null
null
null
BroadCast_QT/group.cpp
mickelfeng/qt_learning
1f565754c36f0c09888cf4fbffa6271298d0678b
[ "Apache-2.0" ]
null
null
null
/* Copyright (C) 2014 by Project Tox <https://tox.im> This file is part of qTox, a Qt-based graphical interface for Tox. This program is libre software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the COPYING file for more details. */ #include "group.h" #include "widget/groupwidget.h" #include "widget/form/groupchatform.h" #include "friendlist.h" #include "friend.h" #include "widget/widget.h" #include "core.h" #include <QDebug> Group::Group(int GroupId, QString Name) : groupId(GroupId), nPeers{0}, hasPeerInfo{false} { widget = new GroupWidget(groupId, Name); chatForm = new GroupChatForm(this); connect(&peerInfoTimer, SIGNAL(timeout()), this, SLOT(queryPeerInfo())); peerInfoTimer.setInterval(500); peerInfoTimer.setSingleShot(false); //peerInfoTimer.start(); //in groupchats, we only notify on messages containing your name hasNewMessages = 0; userWasMentioned = 0; } Group::~Group() { delete chatForm; delete widget; } void Group::queryPeerInfo() { const Core* core = Widget::getInstance()->getCore(); int nPeersResult = core->getGroupNumberPeers(groupId); if (nPeersResult == -1) { qDebug() << "Group::queryPeerInfo: Can't get number of peers"; return; } nPeers = nPeersResult; widget->onUserListChanged(); chatForm->onUserListChanged(); if (nPeersResult == 0) return; bool namesOk = true; QList<QString> names = core->getGroupPeerNames(groupId); if (names.isEmpty()) { qDebug() << "Group::queryPeerInfo: Can't get names of peers"; return; } for (int i=0; i<names.size(); i++) { QString name = names[i]; if (name.isEmpty()) { name = "<Unknown>"; namesOk = false; } peers[i] = name; } nPeers = names.size(); widget->onUserListChanged(); chatForm->onUserListChanged(); if (namesOk) { qDebug() << "Group::queryPeerInfo: Successfully loaded names"; hasPeerInfo = true; peerInfoTimer.stop(); } } void Group::addPeer(int peerId, QString name) { if (peers.contains(peerId)) qWarning() << "Group::addPeer: peerId already used, overwriting anyway"; if (name.isEmpty()) peers[peerId] = "<Unknown>"; else peers[peerId] = name; nPeers++; widget->onUserListChanged(); chatForm->onUserListChanged(); } void Group::removePeer(int peerId) { peers.remove(peerId); nPeers--; widget->onUserListChanged(); chatForm->onUserListChanged(); } void Group::updatePeer(int peerId, QString name) { peers[peerId] = name; widget->onUserListChanged(); chatForm->onUserListChanged(); }
25.933333
80
0.646208
mickelfeng
88ee8bc44a0180d2b8890165543ced054bbbad66
1,102
cc
C++
callback.cc
stories2/Native-Node-JS
583a2db17b0f398779378294ea21a7034ee2c815
[ "MIT" ]
null
null
null
callback.cc
stories2/Native-Node-JS
583a2db17b0f398779378294ea21a7034ee2c815
[ "MIT" ]
null
null
null
callback.cc
stories2/Native-Node-JS
583a2db17b0f398779378294ea21a7034ee2c815
[ "MIT" ]
null
null
null
#include <node.h> #include <nan.h> namespace function_arg { // using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; using v8::Object; using v8::String; using v8::Value; using v8::Context; using v8::Number; using v8::Function; void CallbackFunc(const Nan::FunctionCallbackInfo<Value> &args) { Isolate *isolate = args.GetIsolate(); Local<Context> context = args.GetIsolate()->GetCurrentContext(); if(args.Length() < 1) { Nan::ThrowTypeError("Wrong number of arguments"); return; } Local<Function> cb = args[0].As<Function>(); const unsigned argc = 1; Local<Value> argv[argc] = { Nan::New("Hello World from c++").ToLocalChecked() }; Nan::MakeCallback(context->Global(), cb, argc, argv); } void init(Local<Object> exports, Local<Object> module) { // NODE_SET_METHOD(exports, "add", Add); Nan::SetMethod(module, "exports", CallbackFunc); } NODE_MODULE(NODE_GYP_MODULE_NAME, init) } // namespace demo
27.55
72
0.599819
stories2
88efae45ad5296fd391e686bde3f9b4bb9c75edf
310
cpp
C++
LeetCode/Problems/Algorithms/#1480_RunningSumOf1DArray_sol2.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
1
2022-01-26T14:50:07.000Z
2022-01-26T14:50:07.000Z
LeetCode/Problems/Algorithms/#1480_RunningSumOf1DArray_sol2.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
LeetCode/Problems/Algorithms/#1480_RunningSumOf1DArray_sol2.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
class Solution { public: vector<int> runningSum(vector<int>& nums) { const int N = nums.size(); vector<int> prefSum(N); prefSum[0] = nums[0]; for(int i = 1; i < N; ++i){ prefSum[i] = prefSum[i - 1] + nums[i]; } return prefSum; } };
25.833333
51
0.464516
Tudor67
88f245d407e5f703cb66c9e7e6d8a2bfee10af68
594
hpp
C++
mpipe/modules/mod_equalizer.hpp
m-kus/mpipe
82e2e93200030b89d76544cee13aabedf318ea0c
[ "MIT" ]
2
2019-02-09T14:31:03.000Z
2019-05-03T05:46:15.000Z
mpipe/modules/mod_equalizer.hpp
m-kus/mpipe
82e2e93200030b89d76544cee13aabedf318ea0c
[ "MIT" ]
null
null
null
mpipe/modules/mod_equalizer.hpp
m-kus/mpipe
82e2e93200030b89d76544cee13aabedf318ea0c
[ "MIT" ]
null
null
null
#pragma once #include <core/mpipe.hpp> #include <algorithm> namespace mpipe { class ModEqualizer : public Module { public: void Mutate(State* state) override { int64_t target_qty = 0; for (auto& order : state->orders) { int64_t common_qty = order.qty / npabs(order.security->leg_factor); if (common_qty < target_qty || target_qty == 0) target_qty = common_qty; } if (target_qty > 0) { for (auto& order : state->orders) order.qty = target_qty * npabs(order.security->leg_factor); } else { state->orders.clear(); } } }; }
16.971429
71
0.624579
m-kus
88f7df8b08b019b9ba10bdf20a3bdf89d2dea2b7
357
hpp
C++
plugins/samefolder/version.hpp
TheChatty/FarManager
0a731ce0b6f9f48f10eb370240309bed48e38f11
[ "BSD-3-Clause" ]
1
2019-11-15T10:13:04.000Z
2019-11-15T10:13:04.000Z
plugins/samefolder/version.hpp
TheChatty/FarManager
0a731ce0b6f9f48f10eb370240309bed48e38f11
[ "BSD-3-Clause" ]
1
2021-01-21T13:57:07.000Z
2021-01-21T13:57:07.000Z
plugins/samefolder/version.hpp
TheChatty/FarManager
0a731ce0b6f9f48f10eb370240309bed48e38f11
[ "BSD-3-Clause" ]
null
null
null
#include "farversion.hpp" #define PLUGIN_BUILD 1 #define PLUGIN_DESC L"Same Folder Plugin for Far Manager" #define PLUGIN_NAME L"SameFolder" #define PLUGIN_FILENAME L"SameFolder.dll" #define PLUGIN_AUTHOR L"Far Group" #define PLUGIN_VERSION MAKEFARVERSION(FARMANAGERVERSION_MAJOR,FARMANAGERVERSION_MINOR,FARMANAGERVERSION_REVISION,PLUGIN_BUILD,VS_RELEASE)
39.666667
137
0.854342
TheChatty
0000dfdb0fea5abd19ee2dc1cfe3801c3a6cc439
5,240
cpp
C++
src/xray/editor/world/sources/particle_graph_node_collection.cpp
ixray-team/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
3
2021-10-30T09:36:14.000Z
2022-03-26T17:00:06.000Z
src/xray/editor/world/sources/particle_graph_node_collection.cpp
acidicMercury8/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
null
null
null
src/xray/editor/world/sources/particle_graph_node_collection.cpp
acidicMercury8/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:08.000Z
2022-03-26T17:00:08.000Z
//////////////////////////////////////////////////////////////////////////// // Created : 27.01.2010 // Author : // Copyright (C) GSC Game World - 2010 //////////////////////////////////////////////////////////////////////////// #include "pch.h" #include "particle_graph_node.h" #include "particle_graph_node_event.h" #include "particle_graph_node_action.h" #include "particle_graph_node_property.h" #include "particle_graph_node_collection.h" #include "particle_hypergraph.h" #include "particle_graph_document.h" #include "particle_links_manager.h" using namespace System; namespace xray { namespace editor { particle_graph_node_collection::particle_graph_node_collection(particle_graph_node^ owner) { m_owner = owner; m_last_property_id = 0; m_last_action_id = 0; m_last_event_id = 0; } void particle_graph_node_collection::Insert (Int32 index , particle_graph_node^ node) { R_ASSERT(m_owner->parent_hypergraph!=nullptr); node->size = m_owner->size; if(node->parent_hypergraph == nullptr){ m_owner->parent_hypergraph->links_manager->on_node_destroyed(node); safe_cast<particle_hypergraph^>(m_owner->parent_hypergraph)->append_node(node); } if (Count == 0) safe_cast<particle_links_manager^>(m_owner->parent_hypergraph->links_manager)->create_link(m_owner, node); else if (index == 0){ safe_cast<particle_links_manager^>(m_owner->parent_hypergraph->links_manager)->destroy_link(m_owner, this[0]); safe_cast<particle_links_manager^>(m_owner->parent_hypergraph->links_manager)->create_link(m_owner, node); } node->parent_node = m_owner; super::Insert(index, node); if (node->GetType() == particle_graph_node_property::typeid){ m_last_property_id = m_last_property_id + 1; } else if (node->GetType() == particle_graph_node_action::typeid){ m_last_action_id = m_last_action_id + 1; } else if (node->GetType() == particle_graph_node_event::typeid){ m_last_event_id = m_last_event_id + 1; } if (m_owner->active_node == nullptr) m_owner->active_node = node; if (m_owner == safe_cast<particle_hypergraph^>(m_owner->parent_hypergraph)->root_node) node->process_node_selection(); else{ m_owner->process_node_selection(); node->process_node_selection(); } m_owner->recalc_children_position_offsets(); m_owner->parent_hypergraph->Invalidate(true); } void particle_graph_node_collection::Add (particle_graph_node^ node) { if (node->GetType() == particle_graph_node_property::typeid){ Insert(m_last_property_id, node); } else if (node->GetType() == particle_graph_node_action::typeid){ Insert(m_last_action_id + m_last_property_id, node); } else if (node->GetType() == particle_graph_node_event::typeid){ Insert(m_last_event_id + m_last_action_id + m_last_property_id, node); } else Insert(Count, node); } void particle_graph_node_collection::Remove (particle_graph_node^ node){ if (node->properties->type == "property"){ m_last_property_id = m_last_property_id - 1; } else if (node->properties->type == "action"){ m_last_action_id = m_last_action_id - 1; } else if (node->properties->type == "event"){ m_last_event_id = m_last_event_id - 1; } node->parent_node = nullptr; if (m_owner->active_node == node) m_owner->active_node = nullptr; safe_cast<particle_links_manager^>(m_owner->parent_hypergraph->links_manager)->destroy_link(m_owner, node); m_owner->parent_hypergraph->Invalidate(true); int node_index = this->IndexOf(node); super::Remove(node); if (node_index == 0 && Count>0) safe_cast<particle_links_manager^>(m_owner->parent_hypergraph->links_manager)->create_link(m_owner, this[0]); m_owner->recalc_children_position_offsets(); m_owner->parent_hypergraph->Invalidate(false); } bool particle_graph_node_collection::MoveToIndex (particle_graph_node^ node, int index){ int min_index = 0; int max_index = Count; if(node->is_property_node()){ min_index = 0; max_index = m_last_property_id; } else if(node->is_action_node()){ min_index = m_last_property_id; max_index = m_last_property_id + m_last_action_id; } else if(node->is_event_node()){ min_index = m_last_property_id + m_last_action_id; max_index = m_last_property_id + m_last_action_id + m_last_event_id; } if (index >= max_index || index < min_index) return false; int node_index = this->IndexOf(node); super::Remove(node); if (node_index == 0){ safe_cast<particle_links_manager^>(m_owner->parent_hypergraph->links_manager)->destroy_link(m_owner, node); safe_cast<particle_links_manager^>(m_owner->parent_hypergraph->links_manager)->create_link(m_owner, this[0]); } else if (index == 0){ safe_cast<particle_links_manager^>(m_owner->parent_hypergraph->links_manager)->create_link(m_owner, node); safe_cast<particle_links_manager^>(m_owner->parent_hypergraph->links_manager)->destroy_link(m_owner, this[0]); } super::Insert(index, node); m_owner->recalc_children_position_offsets(); m_owner->parent_hypergraph->Invalidate(true); return true; } }// namespace editor }// namespace xray
31.005917
114
0.702863
ixray-team
0002cc1256b81fdab140ea63ebd2246830591eb1
637
cpp
C++
src/HiContrastThemeAsCeeCode.cpp
CHRYSICS/audacity
ce1b172825cb8dcc4b7cb2bb52a4f62946f0b141
[ "CC-BY-3.0" ]
1
2021-11-01T10:32:52.000Z
2021-11-01T10:32:52.000Z
src/HiContrastThemeAsCeeCode.cpp
CHRYSICS/audacity
ce1b172825cb8dcc4b7cb2bb52a4f62946f0b141
[ "CC-BY-3.0" ]
null
null
null
src/HiContrastThemeAsCeeCode.cpp
CHRYSICS/audacity
ce1b172825cb8dcc4b7cb2bb52a4f62946f0b141
[ "CC-BY-3.0" ]
null
null
null
/*!******************************************************************** Audacity: A Digital Audio Editor @file HiContrastThemeAsCeeCode.cpp Paul Licameli split from Theme.cpp **********************************************************************/ #include <vector> #include "Theme.h" static const std::vector<unsigned char> ImageCacheAsData { // Include the generated file full of numbers #include "HiContrastThemeAsCeeCode.h" }; static ThemeBase::RegisteredTheme theme{ /* i18n-hint: greater difference between foreground and background colors */ { "high-contrast", XO("High Contrast") }, ImageCacheAsData };
26.541667
72
0.576138
CHRYSICS
322fd6e8955bb801f5a5c6578c0b83bf195344b7
16,027
cpp
C++
Shoot/src/PropertyStream.cpp
franticsoftware/starports
d723404b20383949874868c251c60cfa06120fde
[ "MIT" ]
5
2016-11-13T08:13:57.000Z
2019-03-31T10:22:38.000Z
Shoot/src/PropertyStream.cpp
franticsoftware/starports
d723404b20383949874868c251c60cfa06120fde
[ "MIT" ]
null
null
null
Shoot/src/PropertyStream.cpp
franticsoftware/starports
d723404b20383949874868c251c60cfa06120fde
[ "MIT" ]
1
2016-12-23T11:25:35.000Z
2016-12-23T11:25:35.000Z
/* Amine Rehioui Created: February 24th 2010 */ #include "Shoot.h" #include "PropertyStream.h" #include "MaterialProvider.h" #include "rapidxml.hpp" namespace shoot { //! Destructor PropertyStream::~PropertyStream() { Clear(); } //! reads/write from a property from this stream void PropertyStream::Serialize(int eType, const std::string& strName, void* pValue, const void *pParams /*= NULL*/) { SHOOT_ASSERT(eType != PT_Array, "Use SerializeArray for serializing arrays"); SHOOT_ASSERT(eType != PT_Reference, "Use SerializeReference for serializing references"); switch(m_eMode) { case SM_Read: // check if this property was marked for update if(m_strPropertyToUpdate.length() == 0 || m_strPropertyToUpdate == strName) { IProperty* pProperty = GetProperty(strName); if(pProperty) { SHOOT_ASSERT(pProperty->GetType() == eType, "PropertyType mismatch"); if(pProperty->GetType() == PT_Struct) { StructProperty* pStructProperty = static_cast<StructProperty*>(pProperty); ISerializableStruct* pStruct = static_cast<ISerializableStruct*>(pValue); pStructProperty->GetStream().SetMode(SM_Read); pStructProperty->GetStream().SetTargetObject(m_pTargetObject); pStruct->Serialize(pStructProperty->GetStream()); } else if(pProperty->GetType() == PT_Link) { if(m_pIDMap_OriginalToCopy) { Link<Object> link; pProperty->GetData(&link); if (m_pIDMap_OriginalToCopy->find(link.GetObjectID()) != m_pIDMap_OriginalToCopy->end()) static_cast<ILink*>(pValue)->SetObjectID((*m_pIDMap_OriginalToCopy)[link.GetObjectID()]); else static_cast<ILink*>(pValue)->SetObjectID(link.GetObjectID()); } else pProperty->GetData(pValue); } else { pProperty->GetData(pValue); } } } break; case SM_Write: { IProperty* pProperty = IProperty::CreateFromType(E_PropertyType(eType)); pProperty->SetName(strName); pProperty->SetParams(pParams); if(pProperty->GetType() == PT_Struct) { StructProperty* pStructProperty = static_cast<StructProperty*>(pProperty); ISerializableStruct* pStruct = static_cast<ISerializableStruct*>(pValue); pStructProperty->GetStream().SetMode(SM_Write); pStructProperty->GetStream().SetUsedForObjectCopy(m_bUsedForObjectCopy); pStruct->Serialize(pStructProperty->GetStream()); } else { pProperty->SetData(pValue); } m_aProperties.push_back(pProperty); } break; default: SHOOT_ASSERT(false, "Invalid E_SerializationMode"); } if(eType == PT_Enum) { EnumParams* _pParams = static_cast<EnumParams*>(const_cast<void*>(pParams)); sdelete(_pParams); } } //! returns the property with the specified name IProperty* PropertyStream::GetProperty(const std::string& strName) const { for (size_t i=0; i<m_aProperties.size(); ++i) { IProperty* pProperty = m_aProperties[i]; if(pProperty->GetName() == strName) return pProperty; } return 0; } //! adds a property to the stream void PropertyStream::AddProperty(IProperty* pProperty) { std::vector<IProperty*>::iterator it = std::find(m_aProperties.begin(), m_aProperties.end(), pProperty); SHOOT_ASSERT(it == m_aProperties.end(), "Trying to add a property twice"); m_aProperties.push_back(pProperty); } //! removes a propety from the stream void PropertyStream::RemoveProperty(IProperty* pProperty) { std::vector<IProperty*>::iterator it = std::find(m_aProperties.begin(), m_aProperties.end(), pProperty); SHOOT_ASSERT(it != m_aProperties.end(), "Trying to remove unexisting property"); m_aProperties.erase(it); sdelete(pProperty); } //! fills this stream from xml element void PropertyStream::ReadFromXML(rapidxml::xml_node<char>* pXMLElement, ArrayProperty* pParentArrayProperty /*= NULL*/) { auto pChild = pXMLElement->first_node(); while(pChild) { // get the property type name std::string strPropertyTypeName = pChild->name(); IProperty* pProperty = IProperty::CreateFromTypeName(strPropertyTypeName); // get the property name const char* strPropertyName = pChild->getAttribute("Name"); if(strPropertyName) { pProperty->SetName(std::string(strPropertyName)); } switch(pProperty->GetType()) { case PT_Array: ReadFromXML(pChild, static_cast<ArrayProperty*>(pProperty)); break; case PT_Reference: { ReferenceProperty* pRefProperty = static_cast<ReferenceProperty*>(pProperty); if (const char* strTemplatePath = pChild->getAttribute("TemplatePath")) { pRefProperty->SetTemplatePath(strTemplatePath); } else if (const char* strClassName = pChild->getAttribute("ClassName")) { pRefProperty->SetClassName(strClassName); pRefProperty->GetStream().ReadFromXML(pChild); } } break; case PT_Struct: { StructProperty* pStructProperty = static_cast<StructProperty*>(pProperty); pStructProperty->GetStream().ReadFromXML(pChild); } break; default: { // get the property value const char* pStrPropertyValue = pChild->getAttribute("Value"); SHOOT_ASSERT(pStrPropertyValue, "property missing Value attribute"); pProperty->SetData(std::string(pStrPropertyValue)); } } // add the property to the stream if(pParentArrayProperty) { if(pParentArrayProperty->GetSubType() == PT_Undefined) { pParentArrayProperty->SetSubType(pProperty->GetType()); } else { SHOOT_ASSERT(pParentArrayProperty->GetSubType() == pProperty->GetType(), "Can't have multiple types in an array property"); } pParentArrayProperty->GetProperties().push_back(pProperty); } else { m_aProperties.push_back(pProperty); } pChild = pChild->next_sibling(); } } // writes this stream to xml element void PropertyStream::WriteToXML(rapidxml::xml_node<char>* pXMLElement) { for (size_t i=0; i<m_aProperties.size(); ++i) { WritePropertyToXML(pXMLElement, m_aProperties[i]); } } //! reads/writes an array property from/to this stream void PropertyStream::SerializeArray(const std::string& strName, IArray* pArray, int eSubType) { SHOOT_ASSERT(eSubType != PT_Array, "Arrays of arrays not supported. Encapsulate your inner array into a struct to get around this."); switch(m_eMode) { case SM_Read: // check if this property was marked for update if(m_strPropertyToUpdate.length() == 0 || m_strPropertyToUpdate == strName) { ArrayProperty* pProperty = static_cast<ArrayProperty*>(GetProperty(strName)); if(pProperty) { // update existing elements for (size_t i = 0; i<pArray->GetSize() && i<pProperty->GetProperties().size(); ++i) { IProperty* pSubProperty = pProperty->GetProperties()[i]; SHOOT_ASSERT(pSubProperty->GetType() == eSubType, "Actual sub property type differs from expected type"); void* pElement = pArray->GetPtr(i); FillArrayElement(pElement, pSubProperty); } // attempt to add new elements for (size_t i = pArray->GetSize(); i<pProperty->GetProperties().size(); ++i) { IProperty* pSubProperty = pProperty->GetProperties()[i]; SHOOT_ASSERT(pSubProperty->GetType() == eSubType, "Actual sub property type differs from expected type"); void* pElement = pArray->Alloc(); FillArrayElement(pElement, pSubProperty); pArray->Add(pElement); } // attempt to remove elements for (size_t i = pProperty->GetProperties().size(); i<pArray->GetSize(); ++i) { pArray->Delete(i); --i; } } } break; case SM_Write: { ArrayProperty* pProperty = static_cast<ArrayProperty*>(IProperty::CreateFromType(PT_Array)); pProperty->SetName(strName); pProperty->SetSubType(E_PropertyType(eSubType)); pProperty->SetArray(pArray); for (size_t i = 0; i<pArray->GetSize(); ++i) { IProperty* pSubProperty = IProperty::CreateFromType(E_PropertyType(eSubType)); void* pElement = pArray->GetPtr(i); if(eSubType == PT_Struct) { StructProperty* pStructProperty = static_cast<StructProperty*>(pSubProperty); ISerializableStruct* pStruct = static_cast<ISerializableStruct*>(pElement); pStructProperty->GetStream().SetMode(SM_Write); pStruct->Serialize(pStructProperty->GetStream()); } else if(eSubType == PT_Reference) { IReference* pReference = static_cast<IReference*>(pElement); ReferenceProperty* pRefProperty = static_cast<ReferenceProperty*>(pSubProperty); FillPropertyFromReference(pRefProperty, pReference); } else { pSubProperty->SetData(pElement); } pProperty->GetProperties().push_back(pSubProperty); } m_aProperties.push_back(pProperty); } break; } } //! reads/writes a reference property from/to this stream void PropertyStream::SerializeReference(const std::string& strName, IReference* pReference) { switch(m_eMode) { case SM_Read: // check if this property was marked for update if(m_strPropertyToUpdate.length() == 0 || m_strPropertyToUpdate == strName) { IProperty* pProperty = GetProperty(strName); if(pProperty && pProperty->GetType() == PT_Reference) { FillReferenceFromProperty(pReference, static_cast<ReferenceProperty*>(pProperty)); } } break; case SM_Write: { ReferenceProperty* pProperty = static_cast<ReferenceProperty*>(IProperty::CreateFromType(PT_Reference)); pProperty->SetName(strName); FillPropertyFromReference(pProperty, pReference); m_aProperties.push_back(pProperty); } break; } } //! explicitly clear this stream void PropertyStream::Clear() { for (size_t i=0; i<m_aProperties.size(); ++i) { IProperty* pProperty = m_aProperties[i]; delete pProperty; } m_aProperties.clear(); } //! writes a property to XML void PropertyStream::WritePropertyToXML(rapidxml::xml_node<char>* pXMLElement, IProperty* pProperty, bool bWriteName /*= true*/) { auto pElement = pXMLElement->document()->allocate_node(rapidxml::node_element, pXMLElement->document()->allocate_string(pProperty->GetClassName().c_str())); pXMLElement->append_node(pElement); if(bWriteName) pElement->setAttribute("Name", pProperty->GetName().c_str()); switch(pProperty->GetType()) { case PT_Array: { ArrayProperty* pArrayProperty = static_cast<ArrayProperty*>(pProperty); for(size_t i=0; i<pArrayProperty->GetProperties().size(); ++i) { IProperty* pSubProperty = pArrayProperty->GetProperties()[i]; WritePropertyToXML(pElement, pSubProperty, false); // don't write the name for array sub properties } } break; case PT_Reference: { ReferenceProperty* pRefProperty = static_cast<ReferenceProperty*>(pProperty); if(pRefProperty->GetTemplatePath().empty()) { pElement->setAttribute("ClassName", pRefProperty->GetClassName().c_str()); pRefProperty->GetStream().WriteToXML(pElement); } else { pElement->setAttribute("TemplatePath", pRefProperty->GetTemplatePath().c_str()); } } break; case PT_Struct: { StructProperty* pStructProperty = static_cast<StructProperty*>(pProperty); pStructProperty->GetStream().WriteToXML(pElement); } break; default: { pElement->setAttribute("Value", pProperty->GetString().c_str()); } } } //! fills a user reference from a ReferenceProperty void PropertyStream::FillReferenceFromProperty(IReference* pReference, ReferenceProperty* pProperty) { bool bFromTemplate = !pProperty->GetTemplatePath().empty(); bool bObjectSerialized = false; if (pProperty->GetStream().GetNumProperties() == 0 && !bFromTemplate) return; Object* pObject = pProperty->GetRefInterface() ? pProperty->GetRefInterface()->Get() : NULL; if (!pObject || m_bUsedForObjectCopy) { if (bFromTemplate) { if (!pObject) { auto templatePath = pProperty->GetTemplatePath(); pObject = ObjectManager::Instance()->Find(templatePath); if (!pObject) { pObject = ObjectManager::Instance()->Load(templatePath); if (auto resource = DYNAMIC_CAST(pObject, Resource)) resource->ResourceInit(); } } } else { // hack because materials must only be created through MaterialProvider // TODO find a better way if (pReference->GetTypeID() == Material::TypeID) { if (m_bUsedForObjectCopy) { if (auto material = DYNAMIC_CAST(pObject, Material)) material->SetColor(material->GetCreationInfo().m_Color); } else { Material::CreationInfo materialInfo; pProperty->GetStream().SetMode(SM_Read); pProperty->GetStream().Serialize("CreationInfo", &materialInfo); pObject = MaterialProvider::Instance()->FindMaterial(materialInfo); if (!pObject) { pObject = MaterialProvider::Instance()->CreateMaterial(materialInfo); uint ID = pObject->GetID(); pProperty->GetStream().Serialize("ID", &ID); pObject->SetID(ID); } } bObjectSerialized = true; } else { pObject = ObjectFactory::Instance()->Create(pProperty->GetClassName()); } } } #ifdef SHOOT_EDITOR pReference->SetOwner(m_pTargetObject); if (!ObjectFactory::Instance()->IsDerived(pObject->GetClassName(), pReference->GetClassName())) { SHOOT_WARNING(false, "Invalid Reference, expecting '%s', found '%s'", pReference->GetClassName(), pObject->GetClassName()); return; } #endif pReference->SetObject(pObject); if (pProperty->GetStream().GetNumProperties() && !bObjectSerialized) { pProperty->GetStream().SetMode(SM_Read); pProperty->GetStream().SetIDMap_OriginalToCopy(m_pIDMap_OriginalToCopy); pProperty->GetStream().SetUsedForObjectCopy(m_bUsedForObjectCopy); int ID = pObject->GetID(); pObject->Serialize(pProperty->GetStream()); // If copied, use the ID from the new instance if (m_bUsedForObjectCopy) pObject->SetID(ID); } } //! fills a ReferenceProperty from a user reference void PropertyStream::FillPropertyFromReference(ReferenceProperty* pProperty, IReference* pReference) { pProperty->SetRefInterface(pReference); Object* pObject = pReference->Get(); if(pObject) { std::string strTemplatePath = pObject->GetTemplatePath(); if(!strTemplatePath.empty()) pProperty->SetTemplatePath(strTemplatePath); else pProperty->SetClassName(pObject->GetClassName()); pProperty->GetStream().SetMode(SM_Write); pProperty->GetStream().SetUsedForObjectCopy(m_bUsedForObjectCopy); pObject->Serialize(pProperty->GetStream()); } else { pProperty->SetClassName(pReference->GetClassName()); pProperty->SetTemplatePath(""); } } //! fills an array element from a property void PropertyStream::FillArrayElement(void* pElement, IProperty* pProperty) { if(pProperty->GetType() == PT_Struct) { StructProperty* pStructProperty = static_cast<StructProperty*>(pProperty); ISerializableStruct* pStruct = static_cast<ISerializableStruct*>(pElement); pStructProperty->GetStream().SetMode(SM_Read); pStruct->Serialize(pStructProperty->GetStream()); } else if(pProperty->GetType() == PT_Reference) { IReference* pReference = static_cast<IReference*>(pElement); ReferenceProperty* pRefProperty = static_cast<ReferenceProperty*>(pProperty); FillReferenceFromProperty(pReference, pRefProperty); } else { pProperty->GetData(pElement); } } //! assignment operator PropertyStream& PropertyStream::operator = (const PropertyStream& other) { Clear(); for (size_t i = 0; i<other.GetNumProperties(); ++i) { IProperty* pPropertyCopy = other.GetProperty(i)->Copy(); m_aProperties.push_back(pPropertyCopy); } return *this; } }
29.67963
158
0.683222
franticsoftware