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
108
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
67k
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
e2fe893b9533c1deaf371e183092fa7daf7e13ea
3,980
cxx
C++
sprokit/processes/core/unwrap_detections_process.cxx
neal-siekierski/kwiver
1c97ad72c8b6237cb4b9618665d042be16825005
[ "BSD-3-Clause" ]
null
null
null
sprokit/processes/core/unwrap_detections_process.cxx
neal-siekierski/kwiver
1c97ad72c8b6237cb4b9618665d042be16825005
[ "BSD-3-Clause" ]
null
null
null
sprokit/processes/core/unwrap_detections_process.cxx
neal-siekierski/kwiver
1c97ad72c8b6237cb4b9618665d042be16825005
[ "BSD-3-Clause" ]
null
null
null
/*ckwg +29 * Copyright 2018 by Kitware, Inc. * 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 name of Kitware, Inc. 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 AUTHORS 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 * \brief Unwrap the object detections from object tracks. */ #include "unwrap_detections_process.h" #include <vital/vital_types.h> #include <kwiver_type_traits.h> #include <sprokit/pipeline/process_exception.h> namespace kwiver { //---------------------------------------------------------------- // Private implementation class class unwrap_detections_process::priv { public: priv(); ~priv(); vital::frame_id_t m_current_idx; }; // =============================================================================== unwrap_detections_process ::unwrap_detections_process( kwiver::vital::config_block_sptr const& config ) : process( config ), d( new unwrap_detections_process::priv ) { make_ports(); make_config(); } unwrap_detections_process ::~unwrap_detections_process() { } // ------------------------------------------------------------------------------- void unwrap_detections_process ::_configure() { } // ------------------------------------------------------------------------------- void unwrap_detections_process ::_step() { auto object_tracks = grab_from_port_using_trait( object_track_set ); auto detected_objects = std::make_shared< kwiver::vital::detected_object_set >(); for( auto& trk : object_tracks->tracks() ) { for( auto& state : *trk ) { auto obj_state = std::static_pointer_cast< kwiver::vital::object_track_state >( state ); if( state->frame() == d->m_current_idx ) { detected_objects->add( obj_state->detection() ); } } } push_to_port_using_trait( detected_object_set, detected_objects ); d->m_current_idx++; } // ------------------------------------------------------------------------------- void unwrap_detections_process ::make_ports() { // Set up for required ports sprokit::process::port_flags_t required; required.insert( flag_required ); // -- input -- declare_input_port_using_trait( object_track_set, required ); // -- output -- declare_output_port_using_trait( detected_object_set, required ); } // ------------------------------------------------------------------------------- void unwrap_detections_process ::make_config() { } // =============================================================================== unwrap_detections_process::priv ::priv() : m_current_idx( 0 ) { } unwrap_detections_process::priv ::~priv() { } } // end namespace
26.533333
94
0.631407
neal-siekierski
e2fffc29f48d61bbb1fd0392d17ef7142a1b37af
3,606
hh
C++
include/maxscale/response_distribution.hh
sdrik/MaxScale
c6c318b36dde0a25f22ac3fd59c9d33d774fe37a
[ "BSD-3-Clause" ]
null
null
null
include/maxscale/response_distribution.hh
sdrik/MaxScale
c6c318b36dde0a25f22ac3fd59c9d33d774fe37a
[ "BSD-3-Clause" ]
null
null
null
include/maxscale/response_distribution.hh
sdrik/MaxScale
c6c318b36dde0a25f22ac3fd59c9d33d774fe37a
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2021 MariaDB Corporation Ab * * Use of this software is governed by the Business Source License included * in the LICENSE.TXT file and at www.mariadb.com/bsl11. * * Change Date: 2025-12-13 * * On the date above, in accordance with the Business Source License, use * of this software will be governed by version 2 or later of the General * Public License. */ #pragma once #include <maxscale/ccdefs.hh> #include <maxbase/stopwatch.hh> #include <map> using namespace std::chrono_literals; namespace maxscale { /** * Distribution of queries into buckets of response time, similar to * the Query Response Time Plugin in mariadb. * https://mariadb.com/kb/en/query-response-time-plugin/ * * From Query Response Time Plugin documentation: * The user can define time intervals that divide the range 0 to positive infinity into smaller * intervals and then collect the number of commands whose execution times fall into each of * those intervals. * Each interval is described as: * (range_base ^ n; range_base ^ (n+1)] * * SELECT * FROM INFORMATION_SCHEMA.QUERY_RESPONSE_TIME; * +----------------+-------+----------------+ * | TIME | COUNT | TOTAL | * +----------------+-------+----------------+ * | 0.000001 | 0 | 0.000000 | * | 0.000010 | 17 | 0.000094 | * | 0.000100 | 4301 0.236555 | * | 0.001000 | 1499 | 0.824450 | * | 0.010000 | 14851 | 81.680502 | * | 0.100000 | 8066 | 443.635693 | * | 1.000000 | 0 | 0.000000 | * | 10.000000 | 0 | 0.000000 | * | 100.000000 | 1 | 55.937094 | * | 1000.000000 | 0 | 0.000000 | * | 10000.000000 | 0 | 0.000000 | * | 100000.000000 | 0 | 0.000000 | * | 1000000.000000 | 0 | 0.000000 | * | TOO LONG | 0 | TOO LONG | * +----------------+-------+----------------+ * * This class tallies the response times added to it maintaining * a vector of the results. * * The limits are rounded to microseconds (a bit differently than the plugin). * The first limit is >= 1us, depends on the given range_base. * The last limit < 10'000'000 (1M for range_base=10, 11.6 days). In the server * the last limit is followed by a "TOO LONG" entry. There is no too-long entry * in class ResponseDistribution (not needed, can't convert to consistent json). */ class ResponseDistribution { public: /** * @brief ResponseDistribution * @param range_base - minimum 2 */ ResponseDistribution(int range_base = 10); struct Element { // These are all "atomic" sizes (64 bits). mxb::Duration limit; // upper limit for a bucket int64_t count; mxb::Duration total; }; int range_base() const; void add(mxb::Duration dur); const std::vector<Element>& get() const; // Get an initial copy for summing up using operator+= ResponseDistribution with_stats_reset() const; ResponseDistribution& operator+(const ResponseDistribution& rhs); ResponseDistribution& operator+=(const ResponseDistribution& rhs); private: int m_range_base; // initialized in the constructor after which // the underlying array (size) remains unchanged std::vector<Element> m_elements; }; inline void ResponseDistribution::add(mxb::Duration dur) { for (auto& element : m_elements) { if (dur <= element.limit) { ++element.count; element.total += dur; break; } } } }
31.356522
95
0.602329
sdrik
390256ec44b496ef5a71c4b2e584dc48afee9a61
2,706
hpp
C++
example/client_console/client_console.hpp
wo3kie/server
63e93c88c04db792b6d3fcb20591f07e5c1ae4f0
[ "MIT" ]
20
2015-09-14T01:38:56.000Z
2020-11-20T13:01:34.000Z
example/client_console/client_console.hpp
wo3kie/server
63e93c88c04db792b6d3fcb20591f07e5c1ae4f0
[ "MIT" ]
null
null
null
example/client_console/client_console.hpp
wo3kie/server
63e93c88c04db792b6d3fcb20591f07e5c1ae4f0
[ "MIT" ]
12
2017-01-23T18:46:32.000Z
2019-06-20T02:22:09.000Z
#ifndef _CLIENT_CONSOLE_ #define _CLIENT_CONSOLE_ #include "core/client.hpp" struct Writer : Task { Writer( asio::io_service & ioService, #ifdef SERVER_SSL ssl::stream< ip::tcp::socket > & socket, #else ip::tcp::socket & socket, #endif int argc, char* argv[] ) : Task( ioService, socket ) { } protected: void runImpl() override { auto const onRequestWritten = [ this ]( sys::error_code const & errorCode, size_t const bytesTransferred ) { this->onRequestWritten( errorCode ); }; while( std::cin.getline( m_request, m_maxLength ) ) { std::size_t const size = strlen( m_request ); asio::async_write( m_socket, asio::buffer( m_request, size ), onRequestWritten ); } } private: void onRequestWritten( sys::error_code const & errorCode ) { if( errorCode ) { std::cerr << "ClientConsole::onRequestWritten Error: " << errorCode.message() << std::endl; } } private: enum { m_maxLength = 1024 + 2 }; char m_request[ m_maxLength ]; }; struct Reader : Task { Reader( asio::io_service & ioService, #ifdef SERVER_SSL ssl::stream< ip::tcp::socket > & socket, #else ip::tcp::socket & socket, #endif int argc, char* argv[] ) : Task( ioService, socket ) { } protected: void runImpl() override { auto const onResponseRead = [ this ]( sys::error_code const & errorCode, size_t const bytesTransferred ) { this->onResponseRead( errorCode, bytesTransferred ); }; m_socket.async_read_some( asio::buffer( m_response, m_maxLength ), onResponseRead ); } private: void onResponseRead( sys::error_code const & errorCode, size_t const bytesTransferred ) { if( errorCode ) { std::cerr << "ClientConsole::onResponseRead Error: " << errorCode.message() << std::endl; } else { std::cout << "> "; std::cout.write( m_response, bytesTransferred ); std::cout << std::endl; m_ioService.post( [ this ](){ this->runImpl(); } ); } } private: enum { m_maxLength = 1024 }; char m_response[ m_maxLength ]; }; #endif
19.751825
64
0.4915
wo3kie
390abeb5824edd87d529070e13d838c0c2467c31
17,059
cpp
C++
engine/src/ph/util/GltfLoader.cpp
PetorSFZ/PhantasyEngine
befe8e9499b7fd93d8765721b6841337a57b0dd6
[ "Zlib" ]
null
null
null
engine/src/ph/util/GltfLoader.cpp
PetorSFZ/PhantasyEngine
befe8e9499b7fd93d8765721b6841337a57b0dd6
[ "Zlib" ]
null
null
null
engine/src/ph/util/GltfLoader.cpp
PetorSFZ/PhantasyEngine
befe8e9499b7fd93d8765721b6841337a57b0dd6
[ "Zlib" ]
null
null
null
// Copyright (c) Peter Hillerström (skipifzero.com, peter@hstroem.se) // // 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 "ph/util/GltfLoader.hpp" #include <sfz/Logging.hpp> #include <sfz/strings/StackString.hpp> #define TINYGLTF_NOEXCEPTION #define JSON_NOEXCEPTION #define TINYGLTF_IMPLEMENTATION #define TINYGLTF_NO_STB_IMAGE #define TINYGLTF_NO_STB_IMAGE_WRITE #include <sfz/PushWarnings.hpp> #include "tiny_gltf.h" #include <sfz/PopWarnings.hpp> #include <sfz/Assert.hpp> #include <ph/Context.hpp> namespace ph { using sfz::str320; using sfz::vec2; using sfz::vec3; using sfz::vec3_u8; using sfz::vec4; using sfz::vec4_u8; // Statics // ------------------------------------------------------------------------------------------------ static bool dummyLoadImageDataFunction( tinygltf::Image*, const int, std::string*, std::string*, int, int, const unsigned char*, int, void*) { return true; } static str320 calculateBasePath(const char* path) noexcept { str320 str("%s", path); // Go through path until the path separator is found bool success = false; for (uint32_t i = str.size() - 1; i > 0; i--) { const char c = str.str[i - 1]; if (c == '\\' || c == '/') { str.str[i] = '\0'; success = true; break; } } // If no path separator is found, assume we have no base path if (!success) str.printf(""); return str; } enum class ComponentType : uint32_t { INT8 = 5120, UINT8 = 5121, INT16 = 5122, UINT16 = 5123, UINT32 = 5125, FLOAT32 = 5126, }; static uint32_t numBytes(ComponentType type) { switch (type) { case ComponentType::INT8: return 1; case ComponentType::UINT8: return 1; case ComponentType::INT16: return 2; case ComponentType::UINT16: return 2; case ComponentType::UINT32: return 4; case ComponentType::FLOAT32: return 4; } return 0; } enum class ComponentDimensions : uint32_t { SCALAR = TINYGLTF_TYPE_SCALAR, VEC2 = TINYGLTF_TYPE_VEC2, VEC3 = TINYGLTF_TYPE_VEC3, VEC4 = TINYGLTF_TYPE_VEC4, MAT2 = TINYGLTF_TYPE_MAT2, MAT3 = TINYGLTF_TYPE_MAT3, MAT4 = TINYGLTF_TYPE_MAT4, }; static uint32_t numDimensions(ComponentDimensions dims) { switch (dims) { case ComponentDimensions::SCALAR: return 1; case ComponentDimensions::VEC2: return 2; case ComponentDimensions::VEC3: return 3; case ComponentDimensions::VEC4: return 4; case ComponentDimensions::MAT2: return 4; case ComponentDimensions::MAT3: return 9; case ComponentDimensions::MAT4: return 16; } return 0; } struct DataAccess final { const uint8_t* rawPtr = nullptr; uint32_t numElements = 0; ComponentType compType = ComponentType::UINT8; ComponentDimensions compDims = ComponentDimensions::SCALAR; template<typename T> const T& at(uint32_t index) const noexcept { return reinterpret_cast<const T*>(rawPtr)[index]; } }; static DataAccess accessData( const tinygltf::Model& model, int accessorIdx) noexcept { // Access Accessor if (accessorIdx < 0) return DataAccess(); if (accessorIdx >= int32_t(model.accessors.size())) return DataAccess(); const tinygltf::Accessor& accessor = model.accessors[accessorIdx]; // Access BufferView if (accessor.bufferView < 0) return DataAccess(); if (accessor.bufferView >= int32_t(model.bufferViews.size())) return DataAccess(); const tinygltf::BufferView& bufferView = model.bufferViews[accessor.bufferView]; // Access Buffer if (bufferView.buffer < 0) return DataAccess(); if (bufferView.buffer >= int32_t(model.buffers.size())) return DataAccess(); const tinygltf::Buffer& buffer = model.buffers[bufferView.buffer]; // Fill DataAccess struct DataAccess tmp; tmp.rawPtr = &buffer.data[accessor.byteOffset + bufferView.byteOffset]; tmp.numElements = uint32_t(accessor.count); tmp.compType = ComponentType(accessor.componentType); tmp.compDims = ComponentDimensions(accessor.type); // For now we require that that there is no padding between elements in buffer sfz_assert_hard( bufferView.byteStride == 0 || bufferView.byteStride == size_t(numDimensions(tmp.compDims) * numBytes(tmp.compType))); return tmp; } static DataAccess accessData( const tinygltf::Model& model, const tinygltf::Primitive& primitive, const char* type) noexcept { const auto& itr = primitive.attributes.find(type); if (itr == primitive.attributes.end()) return DataAccess(); return accessData(model, itr->second); } static uint8_t toU8(float val) noexcept { return uint8_t(std::roundf(val * 255.0f)); } static vec4_u8 toSfz(const tinygltf::ColorValue& val) noexcept { vec4_u8 tmp; tmp.x = toU8(float(val[0])); tmp.y = toU8(float(val[1])); tmp.z = toU8(float(val[2])); tmp.w = toU8(float(val[3])); return tmp; } static bool extractAssets( const char* basePath, const tinygltf::Model& model, Mesh& meshOut, DynArray<ImageAndPath>& texturesOut, bool (*checkIfTextureIsLoaded)(StringID id, void* userPtr), void* userPtr, sfz::Allocator* allocator) noexcept { StringCollection& resStrings = getResourceStrings(); // Load textures texturesOut.init(uint32_t(model.textures.size()), allocator, sfz_dbg("")); for (uint32_t i = 0; i < model.textures.size(); i++) { const tinygltf::Texture& tex = model.textures[i]; if (tex.source < 0 || int(model.images.size()) <= tex.source) { SFZ_ERROR("tinygltf", "Bad texture source: %i", tex.source); return false; } const tinygltf::Image& img = model.images[tex.source]; // Create global path (path relative to game executable) const str320 globalPath("%s%s", basePath, img.uri.c_str()); StringID globalPathId = resStrings.getStringID(globalPath.str); // Check if texture is already loaded, skip it if it is if (checkIfTextureIsLoaded != nullptr) { if (checkIfTextureIsLoaded(globalPathId, userPtr)) continue; } // Load and store image ImageAndPath pack; pack.globalPathId = globalPathId; pack.image = loadImage("", globalPath); if (pack.image.rawData.data() == nullptr) { SFZ_ERROR("tinygltf", "Could not load texture: \"%s\"", globalPath.str); return false; } texturesOut.add(std::move(pack)); // TODO: We need to store these two values somewhere. Likely in material (because it does // not make perfect sense that everything should access the texture the same way) //const tinygltf::Sampler& sampler = model.samplers[tex.sampler]; //int wrapS = sampler.wrapS; // ["CLAMP_TO_EDGE", "MIRRORED_REPEAT", "REPEAT"], default "REPEAT" //int wrapT = sampler.wrapT; // ["CLAMP_TO_EDGE", "MIRRORED_REPEAT", "REPEAT"], default "REPEAT" } // Lambda for getting the StringID from a material auto getStringID = [&](int texIndex) -> StringID { const tinygltf::Texture& tex = model.textures[texIndex]; const tinygltf::Image& img = model.images[tex.source]; str320 globalPath("%s%s", basePath, img.uri.c_str()); StringID globalPathId = resStrings.getStringID(globalPath.str); return globalPathId; }; // Load materials meshOut.materials.init(uint32_t(model.materials.size()), allocator, sfz_dbg("")); for (uint32_t i = 0; i < model.materials.size(); i++) { const tinygltf::Material& material = model.materials[i]; Material phMat; // Lambda for checking if parameter exists auto hasParamValues = [&](const char* key) { return material.values.find(key) != material.values.end(); }; auto hasParamAdditionalValues = [&](const char* key) { return material.additionalValues.find(key) != material.additionalValues.end(); }; // Albedo value if (hasParamValues("baseColorFactor")) { const tinygltf::Parameter& param = material.values.find("baseColorFactor")->second; tinygltf::ColorValue color = param.ColorFactor(); phMat.albedo = toSfz(color); } // Albedo texture if (hasParamValues("baseColorTexture")) { const tinygltf::Parameter& param = material.values.find("baseColorTexture")->second; int texIndex = param.TextureIndex(); if (texIndex < 0 || int(model.textures.size()) <= texIndex) { SFZ_ERROR("tinygltf", "Bad texture index for material %u", i); continue; } phMat.albedoTex = getStringID(texIndex); // TODO: Store which texcoords to use } // Roughness Value if (hasParamValues("roughnessFactor")) { const tinygltf::Parameter& param = material.values.find("roughnessFactor")->second; phMat.roughness = toU8(float(param.Factor())); } // Metallic Value if (hasParamValues("metallicFactor")) { const tinygltf::Parameter& param = material.values.find("metallicFactor")->second; phMat.metallic = toU8(float(param.Factor())); } // Emissive value if (hasParamAdditionalValues("emissiveFactor")) { const tinygltf::Parameter& param = material.additionalValues.find("emissiveFactor")->second; phMat.emissive.x = float(param.ColorFactor()[0]); phMat.emissive.y = float(param.ColorFactor()[1]); phMat.emissive.z = float(param.ColorFactor()[2]); } // Roughness and Metallic texture if (hasParamValues("metallicRoughnessTexture")) { const tinygltf::Parameter& param = material.values.find("metallicRoughnessTexture")->second; int texIndex = param.TextureIndex(); if (texIndex < 0 || int(model.textures.size()) <= texIndex) { SFZ_ERROR("tinygltf", "Bad texture index for material %u", i); continue; } phMat.metallicRoughnessTex = getStringID(texIndex); // TODO: Store which texcoords to use } // Normal texture if (hasParamAdditionalValues("normalTexture")) { const tinygltf::Parameter& param = material.additionalValues.find("normalTexture")->second; int texIndex = param.TextureIndex(); if (texIndex < 0 || int(model.textures.size()) <= texIndex) { SFZ_ERROR("tinygltf", "Bad texture index for material %u", i); continue; } phMat.normalTex = getStringID(texIndex); // TODO: Store which texcoords to use } // Occlusion texture if (hasParamAdditionalValues("occlusionTexture")) { const tinygltf::Parameter& param = material.additionalValues.find("occlusionTexture")->second; int texIndex = param.TextureIndex(); if (texIndex < 0 || int(model.textures.size()) <= texIndex) { SFZ_ERROR("tinygltf", "Bad texture index for material %u", i); continue; } phMat.occlusionTex = getStringID(texIndex); // TODO: Store which texcoords to use } // Emissive texture if (hasParamAdditionalValues("emissiveTexture")) { const tinygltf::Parameter& param = material.additionalValues.find("emissiveTexture")->second; int texIndex = param.TextureIndex(); if (texIndex < 0 || int(model.textures.size()) <= texIndex) { SFZ_ERROR("tinygltf", "Bad texture index for material %u", i); continue; } phMat.emissiveTex = getStringID(texIndex); // TODO: Store which texcoords to use } // Remove default emissive factor if no emissive is specified if (phMat.emissiveTex == StringID::invalid() && !hasParamAdditionalValues("emissiveFactor")) { phMat.emissive = vec3(0.0f); } // Add material to assets meshOut.materials.add(phMat); } // Add single default material if no materials if (meshOut.materials.size() == 0) { ph::Material defaultMaterial; defaultMaterial.emissive = vec3(1.0, 0.0, 0.0); meshOut.materials.add(defaultMaterial); } // Add meshes uint32_t numVertexGuess = uint32_t(model.meshes.size()) * 256; meshOut.vertices.init(numVertexGuess, allocator, sfz_dbg("")); meshOut.indices.init(numVertexGuess * 2, allocator, sfz_dbg("")); meshOut.components.init(uint32_t(model.meshes.size()), allocator, sfz_dbg("")); for (uint32_t i = 0; i < uint32_t(model.meshes.size()); i++) { const tinygltf::Mesh& mesh = model.meshes[i]; MeshComponent phMeshComp; // TODO: For now, stupidly assume each mesh only have one primitive const tinygltf::Primitive& primitive = mesh.primitives[0]; // Mode can be: // TINYGLTF_MODE_POINTS (0) // TINYGLTF_MODE_LINE (1) // TINYGLTF_MODE_LINE_LOOP (2) // TINYGLTF_MODE_TRIANGLES (4) // TINYGLTF_MODE_TRIANGLE_STRIP (5) // TINYGLTF_MODE_TRIANGLE_FAN (6) sfz_assert_hard(primitive.mode == TINYGLTF_MODE_TRIANGLES); sfz_assert_hard( primitive.indices >= 0 && primitive.indices < int(model.accessors.size())); // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry // // Allowed attributes: // POSITION, NORMAL, TANGENT, TEXCOORD_0, TEXCOORD_1, COLOR_0, JOINTS_0, WEIGHTS_0 // // Stupidly assume positions, normals, and texcoord_0 exists DataAccess posAccess = accessData(model, primitive, "POSITION"); sfz_assert_hard(posAccess.rawPtr != nullptr); sfz_assert_hard(posAccess.compType == ComponentType::FLOAT32); sfz_assert_hard(posAccess.compDims == ComponentDimensions::VEC3); DataAccess normalAccess = accessData(model, primitive, "NORMAL"); sfz_assert_hard(normalAccess.rawPtr != nullptr); sfz_assert_hard(normalAccess.compType == ComponentType::FLOAT32); sfz_assert_hard(normalAccess.compDims == ComponentDimensions::VEC3); DataAccess texcoord0Access = accessData(model, primitive, "TEXCOORD_0"); sfz_assert_hard(texcoord0Access.rawPtr != nullptr) sfz_assert_hard(texcoord0Access.compType == ComponentType::FLOAT32); sfz_assert_hard(texcoord0Access.compDims == ComponentDimensions::VEC2); // Assume texcoord_1 does NOT exist DataAccess texcoord1Access = accessData(model, primitive, "TEXCOORD_1"); sfz_assert_hard(texcoord1Access.rawPtr == nullptr); // Create vertices from positions and normals // TODO: Texcoords sfz_assert_hard(posAccess.numElements == normalAccess.numElements); uint32_t compVertexOffset = meshOut.vertices.size(); for (uint32_t j = 0; j < posAccess.numElements; j++) { Vertex vertex; vertex.pos = posAccess.at<vec3>(j); vertex.normal = normalAccess.at<vec3>(j); vertex.texcoord = texcoord0Access.at<vec2>(j); meshOut.vertices.add(vertex); } // Create indices DataAccess idxAccess = accessData(model, primitive.indices); sfz_assert_hard(idxAccess.rawPtr != nullptr); sfz_assert_hard(idxAccess.compDims == ComponentDimensions::SCALAR); phMeshComp.firstIndex = meshOut.indices.size(); phMeshComp.numIndices = idxAccess.numElements; if (idxAccess.compType == ComponentType::UINT32) { for (uint32_t j = 0; j < idxAccess.numElements; j++) { meshOut.indices.add(compVertexOffset + idxAccess.at<uint32_t>(j)); } } else if (idxAccess.compType == ComponentType::UINT16) { for (uint32_t j = 0; j < idxAccess.numElements; j++) { meshOut.indices.add(compVertexOffset + uint32_t(idxAccess.at<uint16_t>(j))); } } else { sfz_assert_hard(false); } // Material uint32_t materialIdx = primitive.material < 0 ? 0 : primitive.material; sfz_assert_hard(materialIdx < meshOut.materials.size()); phMeshComp.materialIdx = materialIdx; // Add component to mesh meshOut.components.add(phMeshComp); } return true; } // Function for loading from gltf // ------------------------------------------------------------------------------------------------ bool loadAssetsFromGltf( const char* gltfPath, Mesh& meshOut, DynArray<ImageAndPath>& texturesOut, sfz::Allocator* allocator, bool (*checkIfTextureIsLoaded)(StringID id, void* userPtr), void* userPtr) noexcept { str320 basePath = calculateBasePath(gltfPath); // Initializing loader with dummy image loader function tinygltf::TinyGLTF loader; loader.SetImageLoader(dummyLoadImageDataFunction, nullptr); // Read model from file tinygltf::Model model; std::string error; std::string warnings; bool result = loader.LoadASCIIFromFile(&model, &error, &warnings, gltfPath); // Check error string if (!warnings.empty()) { SFZ_WARNING("tinygltf", "Warnings loading \"%s\": %s", gltfPath, warnings.c_str()); } if (!error.empty()) { SFZ_ERROR("tinygltf", "Error loading \"%s\": %s", gltfPath, error.c_str()); return false; } // Check return code if (!result) { SFZ_ERROR("tinygltf", "Error loading \"%s\"", gltfPath); return false; } // Log that model was succesfully loaded SFZ_INFO_NOISY("tinygltf", "Model \"%s\" loaded succesfully", gltfPath); // Extract assets from results bool extractSuccess = extractAssets( basePath.str, model, meshOut, texturesOut, checkIfTextureIsLoaded, userPtr, allocator); if (!extractSuccess) { SFZ_ERROR("tinygltf", "Failed to create ph::Mesh from gltf: \"%s\"", gltfPath); return false; } return true; } } // namespace ph
33.318359
101
0.712762
PetorSFZ
390ff228cd4db2d07d9236a1271bdac3a64c1706
4,848
cpp
C++
src/loaders/PE.cpp
LucasDblt/QBDL
fc873087740f10ac56c023cad8b1c8ca42aa8d28
[ "Apache-2.0" ]
52
2021-05-21T20:17:13.000Z
2022-03-26T11:08:44.000Z
src/loaders/PE.cpp
LucasDblt/QBDL
fc873087740f10ac56c023cad8b1c8ca42aa8d28
[ "Apache-2.0" ]
2
2021-06-06T09:32:09.000Z
2021-09-03T10:25:19.000Z
src/loaders/PE.cpp
LucasDblt/QBDL
fc873087740f10ac56c023cad8b1c8ca42aa8d28
[ "Apache-2.0" ]
7
2021-05-22T02:17:20.000Z
2022-01-25T16:21:07.000Z
#include "logging.hpp" #include <LIEF/PE.hpp> #include <QBDL/Engine.hpp> #include <QBDL/arch.hpp> #include <QBDL/loaders/PE.hpp> #include <QBDL/utils.hpp> using namespace LIEF::PE; namespace QBDL::Loaders { std::unique_ptr<PE> PE::from_file(const char *path, TargetSystem &engines, BIND binding) { Logger::info("Loading {}", path); if (!is_pe(path)) { Logger::err("{} is not an PE file", path); return {}; } std::unique_ptr<Binary> bin = Parser::parse(path); if (bin == nullptr) { Logger::err("Can't parse {}", path); return {}; } return from_binary(std::move(bin), engines, binding); } std::unique_ptr<PE> PE::from_binary(std::unique_ptr<Binary> bin, TargetSystem &engines, BIND binding) { if (!engines.supports(*bin)) { return {}; } std::unique_ptr<PE> loader(new PE{std::move(bin), engines}); loader->load(binding); return loader; } PE::PE(std::unique_ptr<Binary> bin, TargetSystem &engines) : Loader::Loader(engines), bin_{std::move(bin)} {} uint64_t PE::get_address(const std::string &sym) const { const Binary &binary = get_binary(); const LIEF::Symbol *symbol = nullptr; if (binary.has_symbol(sym)) { symbol = &binary.get_symbol(sym); } if (symbol == nullptr) { return 0; } return base_address_ + get_rva(binary, symbol->value()); } uint64_t PE::get_address(uint64_t offset) const { return base_address_ + offset; } uint64_t PE::entrypoint() const { const Binary &binary = get_binary(); return base_address_ + (binary.entrypoint() - binary.optional_header().imagebase()); } void PE::load(BIND binding) { Binary &binary = get_binary(); const uint64_t imagebase = binary.optional_header().imagebase(); uint64_t virtual_size = binary.virtual_size(); virtual_size = page_align(virtual_size); mem_size_ = virtual_size; Logger::debug("Virtual size: 0x{:x}", virtual_size); const uint64_t base_address_hint = engine_->base_address_hint(imagebase, virtual_size); const uint64_t base_address = engine_->mem().mmap(base_address_hint, virtual_size); if (base_address == 0 || base_address == -1ull) { Logger::err("mmap() failed! Abort."); return; } base_address_ = base_address; // Map sections // ======================================================= for (const Section &section : binary.sections()) { QBDL_DEBUG("Mapping: {:<10}: (0x{:06x} - 0x{:06x})", section.name(), section.virtual_address(), section.virtual_address() + section.virtual_size()); const uint64_t rva = section.virtual_address(); const std::vector<uint8_t> &content = section.content(); if (!content.empty()) { engine_->mem().write(base_address_ + rva, content.data(), content.size()); } } // Perform relocations // ======================================================= if (binary.has_relocations()) { const Arch binarch = arch(); const uint64_t fixup = base_address_ - imagebase; for (const Relocation &relocation : binary.relocations()) { const uint64_t rva = relocation.virtual_address(); for (const RelocationEntry &entry : relocation.entries()) { switch (entry.type()) { case RELOCATIONS_BASE_TYPES::IMAGE_REL_BASED_DIR64: { const uint64_t relocation_addr = base_address_ + rva + entry.position(); const uint64_t value = engine_->mem().read_ptr(binarch, relocation_addr); engine_->mem().write_ptr(binarch, relocation_addr, value + fixup); break; } default: { QBDL_ERROR("PE relocation {} is not supported!", to_string(entry.type())); break; } } } } } // Perform symbol resolution // ======================================================= // TODO(romain): Find a mechanism to support import by ordinal if (binary.has_imports()) { const Arch binarch = arch(); for (const Import &imp : binary.imports()) { for (const ImportEntry &entry : imp.entries()) { const uint64_t iat_addr = entry.iat_address(); QBDL_DEBUG("Resolving: {}:{} (0x{:x})", imp.name(), entry.name(), iat_addr); LIEF::Symbol sym{entry.name()}; const uintptr_t sym_addr = engine_->symlink(*this, sym); // Write the value in the IAT: engine_->mem().write_ptr(binarch, base_address_ + iat_addr, sym_addr); } } } } Arch PE::arch() const { return Arch::from_bin(get_binary()); } uint64_t PE::get_rva(const Binary &bin, uint64_t addr) const { const uint64_t imagebase = bin.optional_header().imagebase(); if (addr >= imagebase) { return addr - imagebase; } return addr; } PE::~PE() = default; } // namespace QBDL::Loaders
31.277419
80
0.607673
LucasDblt
391258a61b2f516878fedbf96255bda38df9868f
3,927
cpp
C++
qt-4.8.4/src/gui/kernel/qdesktopwidget_gix.cpp
easion/qt_for_gix
f5b41cc1a048fb8ebecab7f9a1646e1e3b2accb8
[ "Apache-2.0" ]
null
null
null
qt-4.8.4/src/gui/kernel/qdesktopwidget_gix.cpp
easion/qt_for_gix
f5b41cc1a048fb8ebecab7f9a1646e1e3b2accb8
[ "Apache-2.0" ]
null
null
null
qt-4.8.4/src/gui/kernel/qdesktopwidget_gix.cpp
easion/qt_for_gix
f5b41cc1a048fb8ebecab7f9a1646e1e3b2accb8
[ "Apache-2.0" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** ** Copyright (C) 2011 www.hanxuantech.com. The Gix parts. ** Written by Easion <easion@hanxuantech.com> ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at qt-sales@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qdesktopwidget.h" #include <stdio.h> #include <gi/gi.h> QDesktopWidget::QDesktopWidget() : QWidget(0, Qt::Desktop) { //fprintf(stderr, "Unimplemented: QDesktopWidget::QDesktopWidget\n"); } QDesktopWidget::~QDesktopWidget() { //fprintf(stderr, "Unimplemented: QDesktopWidget::~QDesktopWidget\n"); } void QDesktopWidget::resizeEvent(QResizeEvent*) { fprintf(stderr, "Unimplemented: QDesktopWidget::resizeEvent\n"); } const QRect QDesktopWidget::availableGeometry(int screen) const { int workarea[4]; int rv; QRect workArea; rv = gi_wm_get_workarea(workarea); if (!rv) { workArea = QRect(workarea[0], workarea[1], workarea[2], workarea[3]); } else{ workArea = screenGeometry(0); } return workArea;//QRect(0,0,info.scr_width,info.scr_height); } const QRect QDesktopWidget::screenGeometry(int screen) const { gi_screen_info_t info; gi_get_screen_info(&info); return QRect(0,0,info.scr_width,info.scr_height); } int QDesktopWidget::screenNumber(const QWidget *widget) const { Q_UNUSED(widget); //fprintf(stderr, "Reimplemented: QDesktopWidget::screenNumber(widget) \n"); return 0; } int QDesktopWidget::screenNumber(const QPoint &point) const { Q_UNUSED(point); //fprintf(stderr, "Reimplemented: QDesktopWidget::screenNumber\n"); return 0; } bool QDesktopWidget::isVirtualDesktop() const { //fprintf(stderr, "Unimplemented: QDesktopWidget::isVirtualDesktop\n"); return true; } int QDesktopWidget::primaryScreen() const { //fprintf(stderr, "Unimplemented: QDesktopWidget::primaryScreen\n"); return 0; } int QDesktopWidget::numScreens() const { //fprintf(stderr, "Unimplemented: QDesktopWidget::numScreens\n"); return 1; } QWidget *QDesktopWidget::screen(int /* screen */) { //fprintf(stderr, "Unimplemented: QDesktopWidget::screen\n"); // It seems that a Qt::WType_Desktop cannot be moved? return this; }
29.30597
77
0.718615
easion
3912b1cc54d2b24986c1b54851f0b0eb1ce44980
637
cpp
C++
Problems/codility/CyclicRotation/main.cpp
grand87/timus
8edcae276ab74b68fff18da3722460f492534a8a
[ "MIT" ]
null
null
null
Problems/codility/CyclicRotation/main.cpp
grand87/timus
8edcae276ab74b68fff18da3722460f492534a8a
[ "MIT" ]
1
2019-05-09T19:17:00.000Z
2019-05-09T19:17:00.000Z
Problems/codility/CyclicRotation/main.cpp
grand87/timus
8edcae276ab74b68fff18da3722460f492534a8a
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; vector<int> solution(vector<int> &A, int K) { const int size = A.size(); if(size != 0 && K % size != 0) { vector<int> result(size); for (int i = 0; i < size; i++) { result[(i + K) % size] = A[i]; } return result; } return A; } int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "rt", stdin); #endif int n,k; cin >> n >> k; vector<int> b(n); for (int i = 0; i < n; i++) cin >> b[i]; vector<int> a = solution(b, k); for (int i = 0; i < n; i++) cout << a[i] << " "; }
18.735294
45
0.467818
grand87
3915750d1eb18c97faa2696719710f45cb2ef94d
916
cpp
C++
Codeforces/731A - Night at the Museum.cpp
naimulcsx/online-judge-solutions
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
[ "MIT" ]
null
null
null
Codeforces/731A - Night at the Museum.cpp
naimulcsx/online-judge-solutions
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
[ "MIT" ]
null
null
null
Codeforces/731A - Night at the Museum.cpp
naimulcsx/online-judge-solutions
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
[ "MIT" ]
null
null
null
#include <iostream> #include <cctype> #include <cmath> #include <string> using namespace std; int get_minimum_distance(char src, char dest) { int distance; src = tolower(src); dest = tolower(dest); // if the distance between the pointed charecter and the destination charecter is greater than 13, then we want make our movement to the opposite side if (abs(src - dest) > 13) distance = 26 - abs(src - dest); // else the distance is the differce between the source and the dest else distance = abs(src-dest); return distance; } int main() { string input; cin >> input; int minimum_rotations = get_minimum_distance('a', input.at(0)); char pointer = input.at(0); for (int i = 0, j = 1; i < input.length() - 1; i++, j++) minimum_rotations += get_minimum_distance(input.at(i), input.at(j)); cout << minimum_rotations << endl; }
26.171429
154
0.644105
naimulcsx
39186a85e96ca0f5d099d05e8241ea93483e058a
5,307
cpp
C++
src/gui/pen.cpp
strandfield/yasl
d109eb3166184febfe48d1a2d1c96683c4a813f7
[ "MIT" ]
1
2020-12-28T01:41:35.000Z
2020-12-28T01:41:35.000Z
src/gui/pen.cpp
strandfield/yasl
d109eb3166184febfe48d1a2d1c96683c4a813f7
[ "MIT" ]
null
null
null
src/gui/pen.cpp
strandfield/yasl
d109eb3166184febfe48d1a2d1c96683c4a813f7
[ "MIT" ]
null
null
null
// Copyright (C) 2018 Vincent Chambrin // This file is part of the Yasl project // For conditions of distribution and use, see copyright notice in LICENSE #include "yasl/gui/pen.h" #include "yasl/common/binding/class.h" #include "yasl/common/binding/default_arguments.h" #include "yasl/common/binding/namespace.h" #include "yasl/common/genericvarianthandler.h" #include "yasl/core/datastream.h" #include "yasl/core/enums.h" #include "yasl/gui/brush.h" #include "yasl/gui/color.h" #include "yasl/gui/pen.h" #include <script/classbuilder.h> static void register_pen_class(script::Namespace ns) { using namespace script; Class pen = ns.newClass("Pen").setId(script::Type::QPen).get(); // QPen(); bind::default_constructor<QPen>(pen).create(); // QPen(Qt::PenStyle); bind::constructor<QPen, Qt::PenStyle>(pen).create(); // QPen(const QColor &); bind::constructor<QPen, const QColor &>(pen).create(); // QPen(const QBrush &, qreal, Qt::PenStyle = Qt::SolidLine, Qt::PenCapStyle = Qt::SquareCap, Qt::PenJoinStyle = Qt::BevelJoin); bind::constructor<QPen, const QBrush &, qreal, Qt::PenStyle, Qt::PenCapStyle, Qt::PenJoinStyle>(pen) .apply(bind::default_arguments(Qt::BevelJoin, Qt::SquareCap, Qt::SolidLine)).create(); // QPen(const QPen &); bind::constructor<QPen, const QPen &>(pen).create(); // ~QPen(); bind::destructor<QPen>(pen).create(); // QPen & operator=(const QPen &); bind::memop_assign<QPen, const QPen &>(pen); // QPen(QPen &&); bind::constructor<QPen, QPen &&>(pen).create(); // QPen & operator=(QPen &&); bind::memop_assign<QPen, QPen &&>(pen); // void swap(QPen &); bind::void_member_function<QPen, QPen &, &QPen::swap>(pen, "swap").create(); // Qt::PenStyle style() const; bind::member_function<QPen, Qt::PenStyle, &QPen::style>(pen, "style").create(); // void setStyle(Qt::PenStyle); bind::void_member_function<QPen, Qt::PenStyle, &QPen::setStyle>(pen, "setStyle").create(); // QVector<qreal> dashPattern() const; /// TODO: QVector<qreal> dashPattern() const; // void setDashPattern(const QVector<qreal> &); /// TODO: void setDashPattern(const QVector<qreal> &); // qreal dashOffset() const; bind::member_function<QPen, qreal, &QPen::dashOffset>(pen, "dashOffset").create(); // void setDashOffset(qreal); bind::void_member_function<QPen, qreal, &QPen::setDashOffset>(pen, "setDashOffset").create(); // qreal miterLimit() const; bind::member_function<QPen, qreal, &QPen::miterLimit>(pen, "miterLimit").create(); // void setMiterLimit(qreal); bind::void_member_function<QPen, qreal, &QPen::setMiterLimit>(pen, "setMiterLimit").create(); // qreal widthF() const; bind::member_function<QPen, qreal, &QPen::widthF>(pen, "widthF").create(); // void setWidthF(qreal); bind::void_member_function<QPen, qreal, &QPen::setWidthF>(pen, "setWidthF").create(); // int width() const; bind::member_function<QPen, int, &QPen::width>(pen, "width").create(); // void setWidth(int); bind::void_member_function<QPen, int, &QPen::setWidth>(pen, "setWidth").create(); // QColor color() const; bind::member_function<QPen, QColor, &QPen::color>(pen, "color").create(); // void setColor(const QColor &); bind::void_member_function<QPen, const QColor &, &QPen::setColor>(pen, "setColor").create(); // QBrush brush() const; bind::member_function<QPen, QBrush, &QPen::brush>(pen, "brush").create(); // void setBrush(const QBrush &); bind::void_member_function<QPen, const QBrush &, &QPen::setBrush>(pen, "setBrush").create(); // bool isSolid() const; bind::member_function<QPen, bool, &QPen::isSolid>(pen, "isSolid").create(); // Qt::PenCapStyle capStyle() const; bind::member_function<QPen, Qt::PenCapStyle, &QPen::capStyle>(pen, "capStyle").create(); // void setCapStyle(Qt::PenCapStyle); bind::void_member_function<QPen, Qt::PenCapStyle, &QPen::setCapStyle>(pen, "setCapStyle").create(); // Qt::PenJoinStyle joinStyle() const; bind::member_function<QPen, Qt::PenJoinStyle, &QPen::joinStyle>(pen, "joinStyle").create(); // void setJoinStyle(Qt::PenJoinStyle); bind::void_member_function<QPen, Qt::PenJoinStyle, &QPen::setJoinStyle>(pen, "setJoinStyle").create(); // bool isCosmetic() const; bind::member_function<QPen, bool, &QPen::isCosmetic>(pen, "isCosmetic").create(); // void setCosmetic(bool); bind::void_member_function<QPen, bool, &QPen::setCosmetic>(pen, "setCosmetic").create(); // bool operator==(const QPen &) const; bind::memop_eq<QPen, const QPen &>(pen); // bool operator!=(const QPen &) const; bind::memop_neq<QPen, const QPen &>(pen); // bool isDetached(); bind::member_function<QPen, bool, &QPen::isDetached>(pen, "isDetached").create(); // QPen::DataPtr & data_ptr(); /// TODO: QPen::DataPtr & data_ptr(); yasl::registerVariantHandler<yasl::GenericVariantHandler<QPen, QMetaType::QPen>>(); } void register_pen_file(script::Namespace gui) { using namespace script; Namespace ns = gui; register_pen_class(ns); // QDataStream & operator<<(QDataStream &, const QPen &); bind::op_put_to<QDataStream &, const QPen &>(ns); // QDataStream & operator>>(QDataStream &, QPen &); bind::op_read_from<QDataStream &, QPen &>(ns); // QDebug operator<<(QDebug, const QPen &); /// TODO: QDebug operator<<(QDebug, const QPen &); }
43.5
130
0.689278
strandfield
391da41161d8c93e6cd163901fb74d288ce51d8d
12,227
cpp
C++
src/mesh.cpp
mohawkjohn/projected_area
d7c65d3d5b2a46a8f0d6d949dab04c2ac70ed1c2
[ "Unlicense" ]
1
2020-06-28T19:46:40.000Z
2020-06-28T19:46:40.000Z
src/mesh.cpp
autumnsault/projected_area
d7c65d3d5b2a46a8f0d6d949dab04c2ac70ed1c2
[ "Unlicense" ]
null
null
null
src/mesh.cpp
autumnsault/projected_area
d7c65d3d5b2a46a8f0d6d949dab04c2ac70ed1c2
[ "Unlicense" ]
null
null
null
/* * Copyright (c) 2014 - 2017, John O. Woods, Ph.D. * West Virginia University Applied Space Exploration Lab (2014 - 2015) * West Virginia Robotic Technology Center (2014 - 2015) * Intuitive Machines (2017) * 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. * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 ** ** @brief Implementation for Assimp-loaded Mesh. See notes on mesh.hpp. **/ #include "../include/mesh.hpp" void Mesh::render(Shader* shader_program) { shader_program->bind(); check_gl_error(); GLuint position_loc = glGetAttribLocation(shader_program->id(), "position"); //GLuint normal_loc = glGetAttribLocation(shader_program->id(), "normal"); check_gl_error(); glEnableVertexAttribArray(position_loc); check_gl_error(); //glEnableVertexAttribArray(normal_loc); //check_gl_error(); for (size_t i = 0; i < entries.size(); ++i) { glBindBuffer(GL_ARRAY_BUFFER, entries[i].vb); // I think this tells it where to look for the vertex information we've loaded. glVertexAttribPointer(position_loc, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0); //glVertexAttribPointer(normal_loc, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)28); // makes room for 7 floats glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, entries[i].ib); //glColor4f(1.0, 1.0, 1.0, 1.0); glDrawElements(GL_TRIANGLES, entries[i].num_indices, GL_UNSIGNED_INT, 0); } check_gl_error(); glDisableVertexAttribArray(position_loc); //glDisableVertexAttribArray(normal_loc); check_gl_error(); shader_program->unbind(); glFlush(); // replaces glfwSwapBuffers() } void Mesh::init_mesh(const aiScene* scene, const aiMesh* mesh, size_t index) { std::cerr << "Loading mesh named '" << mesh->mName.C_Str() << "'" << std::endl; if (!mesh->HasNormals()) { std::cerr << "Mesh has no normals!" << std::endl; } else { if (mesh->mNumVertices > 0) std::cerr << "First normal:" << mesh->mNormals[0].x << "," << mesh->mNormals[0].y << "," << mesh->mNormals[0].z << std::endl; } // Create vectors to store the transformed position and normals; initialize them to the origin. std::vector<aiVector3D> final_pos(mesh->mNumVertices); // final_normal(mesh->mNumVertices); for (size_t i = 0; i < mesh->mNumVertices; ++i) { final_pos[i] = aiVector3D(0.0, 0.0, 0.0); // final_normal[i] = } std::vector<Vertex> vertices; std::vector<unsigned int> indices; const aiVector3D zero_3d(0.0, 0.0, 0.0); if (mesh->mNumBones) { std::vector<aiMatrix4x4> bone_matrices(mesh->mNumBones); // Calculate bone matrices. for (size_t i = 0; i < mesh->mNumBones; ++i) { const aiBone* bone = mesh->mBones[i]; bone_matrices[i] = bone->mOffsetMatrix; std::cerr << "Bone '" << bone->mName.C_Str() << "' includes " << bone->mNumWeights << " vertices:" << std::endl; for (size_t j = 0; j < bone->mNumWeights; ++j) { std::cerr << ' ' << bone->mWeights[j].mVertexId; } std::cerr << std::endl; const aiNode* node = scene->mRootNode->FindNode(bone->mName.C_Str()); const aiNode* temp_node = node; while (temp_node != NULL) { bone_matrices[i] = temp_node->mTransformation * bone_matrices[i]; temp_node = temp_node->mParent; } } // Update vertex positions according to calculated matrices for (size_t i = 0; i < mesh->mNumBones; ++i) { const aiBone* bone = mesh->mBones[i]; //aiMatrix3x3 normal_matrix = aiMatrix3x3(bone_matrices[i]); for (size_t j = 0; j < bone->mNumWeights; ++j) { const aiVertexWeight *vertex_weight = &(bone->mWeights[j]); size_t v = (size_t)(vertex_weight->mVertexId); float w = vertex_weight->mWeight; const aiVector3D *src_pos = &(mesh->mVertices[v]); //const aiVector3D *src_normal = &(mesh->mNormals[v]); final_pos[v] += w * (bone_matrices[i] * (*src_pos)); //final_normal[v] += w * (normal_matrix * (*src_normal)); } std::cerr << "bone " << i << ":" << std::endl; std::cerr << bone_matrices[i].a1 << ' ' << bone_matrices[i].a2 << ' ' << bone_matrices[i].a3 << ' ' << bone_matrices[i].a4 << std::endl; std::cerr << bone_matrices[i].b1 << ' ' << bone_matrices[i].b2 << ' ' << bone_matrices[i].b3 << ' ' << bone_matrices[i].b4 << std::endl; std::cerr << bone_matrices[i].c1 << ' ' << bone_matrices[i].c2 << ' ' << bone_matrices[i].c3 << ' ' << bone_matrices[i].c4 << std::endl; std::cerr << bone_matrices[i].d1 << ' ' << bone_matrices[i].d2 << ' ' << bone_matrices[i].d3 << ' ' << bone_matrices[i].d4 << std::endl; } // initialize our dimension trackers. if (mesh->mNumVertices != 0) { min_extremities.x = final_pos[0].x; min_extremities.y = final_pos[0].y; min_extremities.z = final_pos[0].z; max_extremities = min_extremities; } // Add each updated vertex and calculate its extremities. for (size_t i = 0; i < mesh->mNumVertices; ++i) { // Find the extremities of this mesh so we can get a measurement for the object in object units. if (final_pos[i].x < min_extremities.x) min_extremities.x = final_pos[i].x; else if (final_pos[i].x > max_extremities.x) max_extremities.x = final_pos[i].x; if (final_pos[i].y < min_extremities.y) min_extremities.y = final_pos[i].y; else if (final_pos[i].y > max_extremities.y) max_extremities.y = final_pos[i].y; if (final_pos[i].z < min_extremities.z) min_extremities.z = final_pos[i].z; else if (final_pos[i].z > max_extremities.z) max_extremities.z = final_pos[i].z; Vertex vertex(glm::vec3(final_pos[i].x, final_pos[i].y, final_pos[i].z)); // glm::vec3(final_normal[i].x, final_normal[i].y, final_normal[i].z)); std::cerr << "Adding vertex " << i << ": " << final_pos[i].x << "," << final_pos[i].y << "," << final_pos[i].z; // std::cerr << "\t" << final_normal[i].x << "," << final_normal[i].y << "," << final_normal[i].z << std::endl; std::cerr << " was: " << mesh->mVertices[i].x << "," << mesh->mVertices[i].y << "," << mesh->mVertices[i].z << std::endl; // std::cerr << mesh->mNormals[i].x << "," << mesh->mNormals[i].y << "," << mesh->mNormals[i].z << std::endl; // Accumulate the centroid_ of the object. centroid_ += vertex.pos; vertices.push_back(vertex); } } else { for (unsigned int i = 0; i < mesh->mNumVertices; i++) { const aiVector3D* pos = &(mesh->mVertices[i]); //const aiVector3D* normal = &(mesh->mNormals[i]); // Find the extremities of this mesh so we can get a measurement for the object in object units. if (pos->x < min_extremities.x) min_extremities.x = pos->x; else if (pos->x > max_extremities.x) max_extremities.x = pos->x; if (pos->y < min_extremities.y) min_extremities.y = pos->y; else if (pos->y > max_extremities.y) max_extremities.y = pos->y; if (pos->z < min_extremities.z) min_extremities.z = pos->z; else if (pos->z > max_extremities.z) max_extremities.z = pos->z; Vertex v(glm::vec3(pos->x, pos->y, pos->z)); // glm::vec3(normal->x, normal->y, normal->z)); // Accumulate the centroid_ of the object. centroid_ += v.pos; vertices.push_back(v); } } centroid_ /= mesh->mNumVertices; // Add vertices for each face for (size_t i = 0; i < mesh->mNumFaces; ++i) { const aiFace& face = mesh->mFaces[i]; if (face.mNumIndices != 3) { std::cerr << "Face has " << face.mNumIndices << " indices; skipping" << std::endl; continue; } indices.push_back(face.mIndices[0]); indices.push_back(face.mIndices[1]); indices.push_back(face.mIndices[2]); } // Create index buffer. entries[index].init(vertices, indices); } bool Mesh::load_mesh(const std::string& filename) { bool ret = false; Assimp::Importer importer; const aiScene* scene = importer.ReadFile(filename.c_str(), aiProcess_Triangulate | aiProcess_GenNormals ); if (scene) ret = init_from_scene(scene, filename); else std::cerr << "Error parsing '" << filename << "': " << importer.GetErrorString() << std::endl; return ret; } /** @brief Find the nearest point among all the meshes to some point p. * * @param[in] query point. * @param[out] result point. * * @returns a distance. */ float Mesh::nearest_point(const glm::vec4& p, glm::vec4& result) const { float d = entries[0].nearest_point(p, result); for (size_t i = 1; i < entries.size(); ++i) { glm::vec4 tmp_result; float tmp_distance; tmp_distance = entries[i].nearest_point(p, tmp_result); if (tmp_distance < d) { d = tmp_distance; result = tmp_result; } } return d; } /** @brief Find the ideal location of the near plane. * * @param[in] model coordinate matrix. * @param[in] camera position. * * @returns The distance from the camera to the ideal near plane if we didn't mind the plane intersecting the nearest point. */ float Mesh::near_plane_bound(const glm::mat4& model_to_object_coords, const glm::vec4& camera_pos) const { glm::vec4 nearest; // Find the nearest point in the mesh. nearest_point(camera_pos, nearest); nearest.w = 0.0; float bound = (model_to_object_coords * (camera_pos - nearest)).z; if (bound <= 0) { std::cerr << "WARNING: Nearest point on object is behind the sensor, which makes for an invalid near plane setting. Using MIN_NEAR_PLANE=" << MIN_NEAR_PLANE << " distance units for the bound. Actual near plane will be slightly closer, depending on your value for NEAR_PLANE_FACTOR." << std::endl; bound = MIN_NEAR_PLANE; } return bound; } /** @brief Find the ideal location of the far plane. * * @param[in] model coordinate matrix. * @param[in] camera position. * * @returns The distance from the camera to the ideal far plane if we didn't mind the plane intersecting the farthest point. */ float Mesh::far_plane_bound(const glm::mat4& model_to_object_coords, const glm::vec4& camera_pos) const { // Find the farthest point in the mesh glm::vec4 negative_camera_pos(-camera_pos); glm::vec4 farthest; nearest_point(negative_camera_pos, farthest); farthest.w = 0.0; return (model_to_object_coords * (camera_pos - farthest)).z; } bool Mesh::init_from_scene(const aiScene* scene, const std::string& filename) { entries.resize(scene->mNumMeshes); std::cerr << "Reading " << entries.size() << " meshes" << std::endl; // Initialize the meshes in the scene one by one for (size_t i = 0; i < entries.size(); ++i) { const aiMesh* mesh = scene->mMeshes[i]; init_mesh(scene, mesh, i); } return true; }
37.391437
158
0.649301
mohawkjohn
3920af713b3a1c2f83dd434fb1f913cdc16794c4
2,096
cpp
C++
API/ReconDemo/Geometry/Rect2D.cpp
PengJinFa/YAPNew
fafee8031669b24d0cc74876a477c97d0d7ebadc
[ "MIT" ]
null
null
null
API/ReconDemo/Geometry/Rect2D.cpp
PengJinFa/YAPNew
fafee8031669b24d0cc74876a477c97d0d7ebadc
[ "MIT" ]
null
null
null
API/ReconDemo/Geometry/Rect2D.cpp
PengJinFa/YAPNew
fafee8031669b24d0cc74876a477c97d0d7ebadc
[ "MIT" ]
null
null
null
#include "Rect2D.h" #include <utility> #include <assert.h> using namespace Geometry; /** Default constructor. All members initialized to zero. */ CRect2D::CRect2D() { _left = _right = _top = _bottom = 0.0; } /** Constructs an object from the four side of the rectangle. */ CRect2D::CRect2D(double left, double top, double right, double bottom) { _left = left; _right = right; _top = top; _bottom = bottom; } /** Normalize the rectangle, that is, to make sure the left side of rectangle is less than the right and the top is less than the bottom. */ void CRect2D::Normalize() { if (_left > _right) { std::swap(_left, _right); } if (_top > _bottom) { std::swap(_top, _bottom); } } /** Check to see if a given point is in the rectangle. @param pt Point to test. \pre The rectangle must be normalized before calling this function. You can call NormallizeRect() to normalize the rectangle. */ bool CRect2D::Contains(const Point2D& pt) { // the rectangle must be normalized before calling this function. assert((_left <= _right) && (_top <= _bottom)); return (pt.x >= _left && pt.x < _right && pt.y >= _top && pt.y < _bottom); } /** Inflate the rectangle by the given value. @param dDeltaX Amount to inflate on left and right side. @param dDeltaY Amount to inflate on top and bottom side. \pre The rectangle must be normalized before calling this function. */ void CRect2D::InflateRect(double delta_x, double delta_y) { // the rectangle must be normalized before calling this function. assert((_left <= _right) && (_top <= _bottom)); _left -= delta_x; _right += delta_x; _top -= delta_y; _bottom += delta_y; } /// Constructor. /** This function constructs a CGenericRect from its top left corner and size. @param point Coordinate ot the top left corner of the rectangle. @param size Size of the rectangle. */ CRect2D::CRect2D(const Point2D& point, const Vector2D& size) { _left = point.x; _right = point.x + size.cx; _top = point.y; _bottom = point.y + size.cy; }
23.032967
75
0.671756
PengJinFa
392427e59bed278479a35b3e6ff5951f21cb75ed
2,802
cpp
C++
unit_tests/test_playable_moves.cpp
julienlopez/Aronda
8fb6625bc037736dc2926f97f46a59441d7dc221
[ "MIT" ]
null
null
null
unit_tests/test_playable_moves.cpp
julienlopez/Aronda
8fb6625bc037736dc2926f97f46a59441d7dc221
[ "MIT" ]
4
2018-02-21T15:38:56.000Z
2019-04-03T07:57:22.000Z
unit_tests/test_playable_moves.cpp
julienlopez/Aronda
8fb6625bc037736dc2926f97f46a59441d7dc221
[ "MIT" ]
null
null
null
#include <catch.hpp> #include "game.hpp" #include <numeric_range.hpp> #include <boost/optional/optional_io.hpp> using Aronda::Board; using Aronda::Game; using Aronda::InvalidMove; using Aronda::Square; using Aronda::SquareState; template <class T> bool contains(const std::vector<T>& container, const T& value) { return std::find(begin(container), end(container), value) != end(container); } TEST_CASE("Testing playable moves throughout the game", "[board]") { SECTION("Only the outside squares are playable on an empty board") { Board g; const std::vector<std::size_t> playable_moves = {17, 18, 19, 20, 21, 22, 23, 24}; for(const auto square : range<std::size_t>(0, Aronda::c_number_of_squares)) { const auto res = g.placeStone({Square{square}, Aronda::black, 1}); if(contains(playable_moves, square)) { CHECK(res.has_value()); } else { REQUIRE_FALSE(res.has_value()); CHECK(res.error() == InvalidMove::SquareUnreachable); } } } SECTION("Only the outside squares are playable for white's first move") { Board b; const auto res = b.placeStone({Square{24}, Aronda::black, 1}); REQUIRE(res.has_value()); b = res.value(); const std::vector<std::size_t> playable_moves = {17, 18, 19, 20, 21, 22, 23, 24}; for(const auto square : range<std::size_t>(0, Aronda::c_number_of_squares)) { const auto res = b.placeStone({Square{square}, Aronda::white, 1}); if(contains(playable_moves, square)) { CHECK(res.has_value()); } else { REQUIRE_FALSE(res.has_value()); CHECK(res.error() == InvalidMove::SquareUnreachable); } } } SECTION("Playing one stone on an outside square unlocks all underlying squares") { Game g; auto res = g.placeStone({Square{24}, Aronda::black, 1}); REQUIRE(res.has_value()); res = g.placeStone({Square{24}, Aronda::white, 1}); REQUIRE(res.has_value()); const std::vector<std::size_t> playable_moves = {9, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}; for(const auto square : range<std::size_t>(0, Aronda::c_number_of_squares)) { const auto res = g.currentState().placeStone({Square{square}, Aronda::white, 1}); if(contains(playable_moves, square)) { CHECK(res.has_value()); } else { REQUIRE_FALSE(res.has_value()); CHECK(res.error() == InvalidMove::SquareUnreachable); } } } }
32.206897
100
0.557459
julienlopez
3925abaa7badfff6e1e3812a0746619d5ddfbaa4
132
cpp
C++
OpenGLTutorial/src/physics/collisionmodel.cpp
michaelg29/OpenGLTutorial
e1db34109eca435581c4224976d669e0fe44afd4
[ "CC-BY-4.0" ]
2
2022-03-20T11:20:19.000Z
2022-03-23T01:58:25.000Z
OpenGLTutorial/src/physics/collisionmodel.cpp
michaelg29/OpenGLTutorial
e1db34109eca435581c4224976d669e0fe44afd4
[ "CC-BY-4.0" ]
12
2020-02-17T05:19:01.000Z
2022-03-17T14:56:38.000Z
OpenGLTutorial/src/physics/collisionmodel.cpp
michaelg29/OpenGLTutorial
e1db34109eca435581c4224976d669e0fe44afd4
[ "CC-BY-4.0" ]
1
2022-01-25T16:48:21.000Z
2022-01-25T16:48:21.000Z
#include "collisionmodel.h" #include "../graphics/objects/model.h" CollisionModel::CollisionModel(Model* model) : model(model) {}
22
44
0.742424
michaelg29
3927538b461a290b31713b17dcd1b427bbf1a297
736
cpp
C++
tests/test18.cpp
varnie/giraffe
0448536cdca5dad66110aa64fdf24688b2a0050a
[ "MIT" ]
null
null
null
tests/test18.cpp
varnie/giraffe
0448536cdca5dad66110aa64fdf24688b2a0050a
[ "MIT" ]
1
2020-06-16T14:25:17.000Z
2020-06-16T14:25:17.000Z
tests/test18.cpp
varnie/giraffe
0448536cdca5dad66110aa64fdf24688b2a0050a
[ "MIT" ]
null
null
null
// // Created by varnie on 2/23/16. // #include <gtest/gtest.h> #include "../include/Giraffe.h" TEST(StorageTest, CheckRetrievingAllEntities) { struct Foo { Foo() { } }; using StorageT = Giraffe::Storage<>; using EntityT = Giraffe::Entity<StorageT>; StorageT storage; for (int i = 0; i < 5; ++i) { EntityT e = storage.addEntity(); } std::size_t count1 = 0, count2 = 0; for (const auto &entity: storage.range()) { ++count1; } EXPECT_EQ(count1, 5); storage.process([&](const EntityT &entity) { ++count2; }); EXPECT_EQ(count2, 5); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
17.52381
48
0.576087
varnie
392770182075de0f956a67a461d133ca273fc07b
1,231
cpp
C++
Notes_Week3/composition.cpp
WeiChienHsu/CS165
65e95efc90415c8acc707e2d544eb384d3982e18
[ "MIT" ]
1
2019-01-06T22:36:01.000Z
2019-01-06T22:36:01.000Z
Notes_Week3/composition.cpp
WeiChienHsu/CS165
65e95efc90415c8acc707e2d544eb384d3982e18
[ "MIT" ]
null
null
null
Notes_Week3/composition.cpp
WeiChienHsu/CS165
65e95efc90415c8acc707e2d544eb384d3982e18
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; class Rectangle { private: double length; double width; public: void setLength(double len) { length = len; } void setWidth(double wid) { width = wid; } double getLength() { return length; } double getWidth() { return width; } double calcArea() { return length * width; } }; class Carpet { private: double pricePerSqYd; Rectangle size; // Instance of the Rentangle class public: void setPricePerYd(double p) { pricePerSqYd = p; } void setDimensions(double len, double wid) { size.setLength(len/3); size.setWidth(wid/3); } double getTotalPrice() { return (size.calcArea() * pricePerSqYd); } }; int main() { Carpet purchase; double pricePerSqYd; double length; double width; cout << "Room length in feat: "; cin >> length; cout << "Room width in feet: "; cin >> width; cout << "Carpet price per sq. yard: "; cin >> pricePerSqYd; purchase.setDimensions(length, width); purchase.setPricePerYd(pricePerSqYd); cout << "\n The total price of my new carpet is $" << purchase.getTotalPrice() << endl; return 0; }
17.84058
89
0.607636
WeiChienHsu
392b50d729fc87eed2c45f0554e10b2f27e19709
1,949
cpp
C++
texture-packer/src/main/Functions/main.cpp
ii887522/texture-packer
0dc2b6656329f427881c36ddafc0196447c74926
[ "MIT" ]
null
null
null
texture-packer/src/main/Functions/main.cpp
ii887522/texture-packer
0dc2b6656329f427881c36ddafc0196447c74926
[ "MIT" ]
null
null
null
texture-packer/src/main/Functions/main.cpp
ii887522/texture-packer
0dc2b6656329f427881c36ddafc0196447c74926
[ "MIT" ]
null
null
null
// Copyright ii887522 #ifndef TEST #define ALLOCATOR_IMPLEMENTATIONS #include <nitro/nitro.h> #include <SDL.h> #include <viewify/viewify.h> #include <iostream> #include <stdexcept> #include <filesystem> #include "../ViewGroupFactory/TexturePackerViewGroupFactory.h" #include "../Any/CommandLine.h" #include <SDL_image.h> using ii887522::viewify::App; using ii887522::viewify::Subsystems; using ii887522::viewify::Size; using ii887522::viewify::Color; using ii887522::viewify::eventLoop; using std::cerr; using std::invalid_argument; using std::filesystem::directory_iterator; namespace ii887522::texturePacker { static int main(int argc, char** argv) try { const CommandLine commandLine{ argc, argv }; commandLine.validate(); const Subsystems subsystems; TexturePackerViewGroupFactory texturePackerViewGroupFactory{ commandLine.getInputDirPath(), commandLine.getOutputDirPath(), commandLine.getAtlasSize() }; // See also ../ViewGroupFactory/TexturePackerViewGroupFactory.h for more details eventLoop(App{ "Texture Packer", commandLine.getAtlasSize(), Color{ 0u, 0u, 0u, 0u }, &texturePackerViewGroupFactory, SDL_WINDOW_MINIMIZED }); return EXIT_SUCCESS; } catch (const invalid_argument&) { cerr << "Command Line: texture-packer <input-directory-path> <output-directory-path> <atlas-width> <atlas-height>\n"; cerr << "Param <input-directory-path>: it must exists, has at least 1 png file and ends with either '/' or '\\'\n"; cerr << "Param <output-directory-path>: it must ends with either '/' or '\\'\n"; cerr << "Param <atlas-width>: it must be equal to 2^n where n is a non-negative integer, and big enough to fill sprites\n"; cerr << "Param <atlas-height>: it must be equal to 2^n where n is a non-negative integer, and big enough to fill sprites\n"; return EXIT_FAILURE; } } // namespace ii887522::texturePacker int main(int argc, char** argv) { return ii887522::texturePacker::main(argc, argv); } #endif
37.480769
155
0.746537
ii887522
3930edb38c8069acc6af05d921b0fc3c51491186
982
cpp
C++
LoveLiveWallpaper/src/Interactable.cpp
Juvwxyz/LoveLiveWallpaper
a0eeac941b5ccd53af538192cb92b7df049839c4
[ "MIT" ]
2
2020-05-09T00:13:06.000Z
2020-05-25T05:49:40.000Z
LoveLiveWallpaper/src/Interactable.cpp
Juvwxyz/LoveLiveWallpaper
a0eeac941b5ccd53af538192cb92b7df049839c4
[ "MIT" ]
null
null
null
LoveLiveWallpaper/src/Interactable.cpp
Juvwxyz/LoveLiveWallpaper
a0eeac941b5ccd53af538192cb92b7df049839c4
[ "MIT" ]
1
2020-05-25T05:49:44.000Z
2020-05-25T05:49:44.000Z
#include "Interactable.h" #include "Component.h" #include "Mouse.h" #include "MouseEventArg.h" #include "Transform.h" namespace LLWP { Interactable::Interactable() { Mouse::OnHitTest += (*this, &Interactable::OnHitTest); } bool Interactable::OnHitTest(Interactable*& hitted, const MouseEventArg& arg) { Component* thisComponent = dynamic_cast<Component*>(this); if (thisComponent->transform().HitTest(arg.position().x, arg.position().y)) { if (hitted == nullptr) { hitted = this; return true; } else if (dynamic_cast<Component*>(hitted)->transform().position().z() <= thisComponent->transform().position().z()) { hitted = this; return true; } } return false; } Interactable::~Interactable() { Mouse::OnHitTest -= (*this, &Interactable::OnHitTest); } }
26.540541
127
0.550916
Juvwxyz
3932962e99e15a87428393817850c8fb38c73874
1,441
hpp
C++
include/argot/concepts/reference.hpp
mattcalabrese/argot
97349baaf27659c9dc4d67cf8963b2e871eaedae
[ "BSL-1.0" ]
49
2018-05-09T23:17:45.000Z
2021-07-21T10:05:19.000Z
include/argot/concepts/reference.hpp
mattcalabrese/argot
97349baaf27659c9dc4d67cf8963b2e871eaedae
[ "BSL-1.0" ]
null
null
null
include/argot/concepts/reference.hpp
mattcalabrese/argot
97349baaf27659c9dc4d67cf8963b2e871eaedae
[ "BSL-1.0" ]
2
2019-08-04T03:51:36.000Z
2020-12-28T06:53:29.000Z
/*============================================================================== Copyright (c) 2017, 2018, 2019 Matt Calabrese 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 ARGOT_CONCEPTS_REFERENCE_HPP_ #define ARGOT_CONCEPTS_REFERENCE_HPP_ //[description /*` Reference is an [argot_gen_concept] that is satisfied by reference types. */ //] #include <argot/concepts/detail/concepts_preprocessing_helpers.hpp> #include <argot/gen/explicit_concept.hpp> #include <argot/gen/make_concept_map.hpp> namespace argot { #define ARGOT_DETAIL_PREPROCESSED_CONCEPT_HEADER_NAME() \ s/reference.h #ifdef ARGOT_CONCEPTS_DETAIL_SHOULD_INCLUDE_PREPROCESSED_HEADER #include ARGOT_CONCEPTS_DETAIL_PREPROCESSED_HEADER #else #include <argot/concepts/detail/preprocess_header_begin.hpp> ARGOT_CONCEPTS_DETAIL_CREATE_LINE_DIRECTIVE( __LINE__ ) template< class T > ARGOT_EXPLICIT_CONCEPT( Reference ) ( ); #include <argot/concepts/detail/preprocess_header_end.hpp> #endif // ARGOT_CONCEPTS_DETAIL_SHOULD_INCLUDE_PREPROCESSED_HEADER template< class T > struct make_concept_map< Reference< T& > > {}; template< class T > struct make_concept_map< Reference< T&& > > {}; } // namespace argot #endif // ARGOT_CONCEPTS_REFERENCE_HPP_
27.711538
80
0.700902
mattcalabrese
39410f0a0e8766d77f03a940a2f9f9f063b966d9
4,968
cpp
C++
test/path_append_test.cpp
abdes/asap_filesystem
44b8ab19900db6ce58a8802817a5b42d6ab6a4b3
[ "BSD-3-Clause" ]
3
2019-05-20T14:21:11.000Z
2019-05-21T19:09:13.000Z
test/path_append_test.cpp
abdes/asap_filesystem
44b8ab19900db6ce58a8802817a5b42d6ab6a4b3
[ "BSD-3-Clause" ]
null
null
null
test/path_append_test.cpp
abdes/asap_filesystem
44b8ab19900db6ce58a8802817a5b42d6ab6a4b3
[ "BSD-3-Clause" ]
null
null
null
// Copyright The Authors 2018. // Distributed under the 3-Clause BSD License. // (See accompanying file LICENSE or copy at // https://opensource.org/licenses/BSD-3-Clause) #if defined(__clang__) #pragma clang diagnostic push // Catch2 uses a lot of macro names that will make clang go crazy #if (__clang_major__ >= 13) && !defined(__APPLE__) #pragma clang diagnostic ignored "-Wreserved-identifier" #endif // Big mess created because of the way spdlog is organizing its source code // based on header only builds vs library builds. The issue is that spdlog // places the template definitions in a separate file and explicitly // instantiates them, so we have no problem at link, but we do have a problem // with clang (rightfully) complaining that the template definitions are not // available when the template needs to be instantiated here. #pragma clang diagnostic ignored "-Wundefined-func-template" #endif // __clang__ #include <catch2/catch.hpp> #include "fs_testsuite.h" using testing::ComparePaths; using testing::TEST_PATHS; // path::operator/=(const path&) namespace { auto Append(fs::path l, const fs::path &r) -> fs::path { l /= r; return l; } } // namespace // ----------------------------------------------------------------------------- // Append // ----------------------------------------------------------------------------- TEST_CASE("Path / append / path", "[common][filesystem][path][append]") { ComparePaths(Append("/foo/bar", "/foo/"), "/foo/"); ComparePaths(Append("baz", "baz"), "baz/baz"); ComparePaths(Append("baz/", "baz"), "baz/baz"); ComparePaths(Append("baz", "/foo/bar"), "/foo/bar"); ComparePaths(Append("baz/", "/foo/bar"), "/foo/bar"); REQUIRE(Append("", "").empty()); REQUIRE(!Append("", "rel").is_absolute()); ComparePaths(Append("dir/", "/file"), "/file"); ComparePaths(Append("dir/", "file"), "dir/file"); // path("foo") / ""; // yields "foo/" ComparePaths(Append("foo", ""), "foo/"); // path("foo") / "/bar"; // yields "/bar" ComparePaths(Append("foo", "/bar"), "/bar"); // path("foo") / ""; // yields "foo/" ComparePaths(Append("foo", ""), "foo/"); // path("foo") / "/bar"; // yields "/bar" ComparePaths(Append("foo", "/bar"), "/bar"); #if defined(ASAP_WINDOWS) ComparePaths(Append("//host", "foo"), "//host/foo"); ComparePaths(Append("//host/", "foo"), "//host/foo"); ComparePaths(Append("//host/bar", "foo"), "//host/bar/foo"); ComparePaths(Append("//host", "/foo"), "//host/foo"); ComparePaths(Append("//host", "//other/foo"), "//other/foo"); ComparePaths(Append("//host/bar", "//other/foo"), "//other/foo"); ComparePaths(Append("c:/foo", "/bar"), "c:/bar"); // path("c:") / ""; // yields "c:" ComparePaths(Append("c:", ""), "c:"); // path("c:foo") / "/bar"; // yields "c:/bar" ComparePaths(Append("c:foo", "/bar"), "c:/bar"); // path("c:foo") / "c:bar"; // yields "c:foo/bar" ComparePaths(Append("c:foo", "c:bar"), "c:foo/bar"); // path("foo") / "c:/bar"; // yields "c:/bar" ComparePaths(Append("foo", "c:/bar"), "c:/bar"); // path("foo") / "c:"; // yields "c:" ComparePaths(Append("foo", "c:"), "c:"); #endif // ASAP_WINDOWS } // path::operator/=(const Source& source) // path::Append(const Source& source) // Equivalent to: return operator/=(path(source)); // path::Append(InputIterator first, InputIterator last) // Equivalent to: return operator/=(path(first, last)); template <typename Char> void test(const fs::path &p, const Char *s) { fs::path expected = p; expected /= fs::path(s); fs::path oper = p; oper /= s; fs::path func = p; func.append(s); std::vector<char> input_range(s, s + std::char_traits<Char>::length(s)); fs::path range = p; range.append(input_range.begin(), input_range.end()); ComparePaths(oper, expected); ComparePaths(func, expected); ComparePaths(range, expected); } TEST_CASE("Path / append / source", "[common][filesystem][fs::path][append]") { test("/foo/bar", "/foo/"); test("baz", "baz"); test("baz/", "baz"); test("baz", "/foo/bar"); test("baz/", "/foo/bar"); test("", ""); test("", "rel"); test("dir/", "/file"); test("dir/", "file"); // C++17 [fs.fs::path.append] p4 test("//host", "foo"); test("//host/", "foo"); test("foo", ""); test("foo", "/bar"); test("foo", "c:/bar"); test("foo", "c:"); test("c:", ""); test("c:foo", "/bar"); test("foo", "c:\\bar"); } TEST_CASE("Path / append / source / TEST_PATHS", "[common][filesystem][fs::path][append]") { for (const fs::path p : TEST_PATHS()) { for (const fs::path q : TEST_PATHS()) { test(p, q.c_str()); } } } // TODO(abdessattar): figure later wstring vs string correct impl /* TEST_CASE("Path / append / source / wstring", "[common][filesystem][path][append]") { test( "foo", L"/bar" ); test( L"foo", "/bar" ); test( L"foo", L"/bar" ); } */ #if defined(__clang__) #pragma clang diagnostic pop #endif // __clang__
29.748503
92
0.589171
abdes
3944cbb3e9853cc8dcee395ce7b63ca6fcc45742
5,847
cc
C++
gem5-gpu/src/graphics/graphic_calls.cc
ayoubg/gem5-graphics_v1
d74a968d5854dc02797139558430ccda1f71108e
[ "BSD-3-Clause" ]
1
2019-01-26T10:34:02.000Z
2019-01-26T10:34:02.000Z
gem5-gpu/src/graphics/graphic_calls.cc
ayoubg/gem5-graphics_v1
d74a968d5854dc02797139558430ccda1f71108e
[ "BSD-3-Clause" ]
null
null
null
gem5-gpu/src/graphics/graphic_calls.cc
ayoubg/gem5-graphics_v1
d74a968d5854dc02797139558430ccda1f71108e
[ "BSD-3-Clause" ]
1
2021-07-06T10:40:34.000Z
2021-07-06T10:40:34.000Z
#include "graphics/libOpenglRender/dll.h" #include "graphics/graphic_calls.hh" #include "base/misc.hh" #include <pthread.h> #include<ctime> #include<X11/Xlib.h> #include <SDL/SDL.h> #include <SDL/SDL_syswm.h> #include "graphics/serialize_graphics.hh" #define RENDER_API_NO_PROTOTYPES 1 #include "graphics/libOpenglRender/render_api.h" /* These definitions *must* match those under: * development/tools/emulator/opengl/host/include/libOpenglRender/render_api.h */ #define DYNLINK_FUNCTIONS \ DYNLINK_FUNC(initLibrary) \ DYNLINK_FUNC(setStreamMode) \ DYNLINK_FUNC(initOpenGLRenderer) \ DYNLINK_FUNC(setPostCallback) \ DYNLINK_FUNC(getHardwareStrings) \ DYNLINK_FUNC(createOpenGLSubwindow) \ DYNLINK_FUNC(destroyOpenGLSubwindow) \ DYNLINK_FUNC(repaintOpenGLDisplay) \ DYNLINK_FUNC(stopOpenGLRenderer) \ DYNLINK_FUNC(gem5GetOpenGLContexts) \ DYNLINK_FUNC(gem5CreateOpenGLContext) #define RENDERER_LIB_NAME "lib64OpenglRender" static ADynamicLibrary* rendererLib; static int rendererStarted =0; static char rendererAddress[256]; /* Define the function pointers */ #define DYNLINK_FUNC(name) \ static name##Fn name = NULL; DYNLINK_FUNCTIONS #undef DYNLINK_FUNC int initOpenglesEmulationFuncs(ADynamicLibrary* rendererLib) { void* symbol; char* error; #define DYNLINK_FUNC(name) \ symbol = adynamicLibrary_findSymbol(rendererLib, #name, &error); \ if (symbol != NULL) { \ name = reinterpret_cast<name##Fn>(reinterpret_cast<long long>(symbol)); \ } else { \ inform("GLES emulation: Could not find required symbol (%s): %s", #name, error); \ free(error); \ return -1; \ } DYNLINK_FUNCTIONS #undef DYNLINK_FUNC return 0; } int android_initOpenglesEmulation(void) { char* error = NULL; if (rendererLib != NULL) return 0; DPRINTF(GraphicsCalls,"Initializing hardware OpenGLES emulation support\n"); rendererLib = adynamicLibrary_open(RENDERER_LIB_NAME, &error); if (rendererLib == NULL) { fatal("Error: Could not load OpenGLES emulation library: %s", error); } /* Resolve the functions */ if (initOpenglesEmulationFuncs(rendererLib) < 0) { inform("Error: OpenGLES emulation library mismatch. Be sure to use the correct version!"); goto BAD_EXIT; } if (!initLibrary()) { inform("Error: OpenGLES initialization failed!"); goto BAD_EXIT; } setStreamMode(STREAM_MODE_UNIX); //should not have a real effect as TCP mode will be used anyway return 0; BAD_EXIT: inform("Error: OpenGLES emulation library could not be initialized!"); adynamicLibrary_close(rendererLib); rendererLib = NULL; return -1; } int android_startOpenglesRenderer(int width, int height) { if (!rendererLib) { inform("Can't start OpenGLES renderer without support libraries"); return -1; } if (rendererStarted) { return 0; } if (!initOpenGLRenderer(width, height, rendererAddress, sizeof(rendererAddress))) { fatal("Can't start OpenGLES renderer?"); } else {inform("rendererAddress=%s\n",rendererAddress);} setPostCallback(NULL,NULL); //disabling it rendererStarted = 1; return 0; } int android_showOpenglesWindow(FBNativeWindowType window, int x, int y, int width, int height, float rotation) { if (rendererStarted) { int success = createOpenGLSubwindow(window, x, y, width, height, rotation); return success ? 0 : -1; } else { return -1; } } int android_hideOpenglesWindow(void) { if (rendererStarted) { int success = destroyOpenGLSubwindow(); return success ? 0 : -1; } else { return -1; } } void android_gles_server_path(char* buff, size_t buffsize) { strncpy(buff, rendererAddress, buffsize); } SDL_Surface * surface; void android_showWindow() { #ifdef __linux__ // some OpenGL implementations may call X functions // it is safer to synchronize all X calls made by all the // rendering threads. (although the calls we do are locked // in the FrameBuffer singleton object). XInitThreads(); #endif // initialize SDL window if (SDL_Init(SDL_INIT_NOPARACHUTE | SDL_INIT_VIDEO)) { fatal("SDL init failed: %s\n", SDL_GetError()); } const SDL_VideoInfo* info = SDL_GetVideoInfo( ); info = info; //to not complain about unused variable DPRINTF(GraphicsCalls,"android_showWindow: bpp is %d \n",info->vfmt->BitsPerPixel); surface = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, 32, SDL_SWSURFACE); if (surface == NULL) { fatal("Failed to set video mode: %s\n", SDL_GetError()); } FBNativeWindowType windowId = (FBNativeWindowType)NULL; SDL_SysWMinfo wminfo; memset(&wminfo, 0, sizeof(wminfo)); SDL_GetWMInfo(&wminfo); windowId = wminfo.info.x11.window; DPRINTF(GraphicsCalls,"initializing renderer process\n"); if(!(0==android_initOpenglesEmulation() and 0==android_startOpenglesRenderer(SCREEN_WIDTH, SCREEN_HEIGHT))) { fatal("couldn't initialize openglesEmulation and/or starting openglesRenderer"); } android_showOpenglesWindow(windowId,0,0,SCREEN_WIDTH,SCREEN_HEIGHT,0.0); } void* android_repaint_t(void * arg) { //repaintOpenGLDisplay(); //SDL_Flip(surface); return NULL; } void android_repaint() { android_repaint_t(NULL); } void init_gem5_graphics(){ static bool init= false; if(!init){ android_showWindow(); init=true; } } void get_android_OpenGL_contexts(void** list, int* n){ gem5GetOpenGLContexts((gem5Ctx**)list, n); } void* create_android_OpenGL_context(int config, int isGl2){ return gem5CreateOpenGLContext(config, isGl2); }
26.337838
111
0.687532
ayoubg
394ed15fdfce934a47f9793194eb0550087ba44b
10,260
cc
C++
modules/loader-grub/arch/x86_64/mmu-loader.cc
eryjus/centuryos2
526a39c0f434b29a43d85e6b5b1ffa1ced885b25
[ "BSD-3-Clause" ]
null
null
null
modules/loader-grub/arch/x86_64/mmu-loader.cc
eryjus/centuryos2
526a39c0f434b29a43d85e6b5b1ffa1ced885b25
[ "BSD-3-Clause" ]
null
null
null
modules/loader-grub/arch/x86_64/mmu-loader.cc
eryjus/centuryos2
526a39c0f434b29a43d85e6b5b1ffa1ced885b25
[ "BSD-3-Clause" ]
null
null
null
//=================================================================================================================== // // mmu-loader.cc -- Functions related to managing the Paging Tables // // Copyright (c) 2017-2021 -- Adam Clark // Licensed under "THE BEER-WARE LICENSE" // See License.md for details. // // ----------------------------------------------------------------------------------------------------------------- // // Date Tracker Version Pgmr Description // ----------- ------- ------- ---- --------------------------------------------------------------------------- // 2021-Jan-03 Initial v0.0.1 ADCL Initial version // //=================================================================================================================== #define USE_SERIAL #include "types.h" #include "serial.h" #include "mmu.h" #define PG_NONE (0) #define PG_WRT (1<<0) #define PG_KRN (1<<1) #define PG_DEV (1<<15) // // -- This is a 64-bit page entry for all levels of the page tables // ------------------------------------------------------------- typedef struct PageEntry_t { unsigned int p : 1; // Is the page present? unsigned int rw : 1; // set to 1 to allow writes unsigned int us : 1; // 0=Supervisor; 1=user unsigned int pwt : 1; // Page Write Through unsigned int pcd : 1; // Page-level cache disable unsigned int a : 1; // accessed unsigned int d : 1; // dirty (needs to be written for a swap) unsigned int pat : 1; // set to 0 for tables, page Page Attribute Table (set to 0) unsigned int g : 1; // Global (set to 0) unsigned int k : 1; // Is this a kernel page? unsigned int avl : 2; // Available for software use Frame_t frame : 36; // This is the 4K aligned page frame address (or table address) unsigned int reserved : 4; // reserved bits unsigned int software : 11; // software use bits unsigned int xd : 1; // execute disable } __attribute__((packed)) PageEntry_t; // // -- some inline functions to handle access to Page Table Entries // ------------------------------------------------------------ PageEntry_t *GetPML4Entry(Addr_t a) { PageEntry_t *t = (PageEntry_t *)0xfffffffffffff000; uint64_t idx = (a >> (12 + (9 * 3))) & 0x1ff; #if DEBUG_ENABLED(GetPML4Entry) SerialPutString("PML4 idx = "); SerialPutHex64(idx); SerialPutChar('\n'); #endif return &t[idx]; } PageEntry_t *GetPDPTEntry(Addr_t a) { PageEntry_t *t = (PageEntry_t *)0xffffffffffe00000; uint64_t idx = (a >> (12 + (9 * 2))) & 0x3ffff; #if DEBUG_ENABLED(GetPDPTEntry) SerialPutString("PDPT idx = "); SerialPutHex64(idx); SerialPutChar('\n'); #endif return &t[idx]; } PageEntry_t *GetPDEntry(Addr_t a) { PageEntry_t *t = (PageEntry_t *)0xffffffffc0000000; uint64_t idx = (a >> (12 + (9 * 1))) & 0x7ffffff; #if DEBUG_ENABLED(GetPDEntry) SerialPutString("PD idx = "); SerialPutHex64(idx); SerialPutChar('\n'); #endif return &t[idx]; } PageEntry_t *GetPTEntry(Addr_t a) { PageEntry_t *t = (PageEntry_t *)0xffffff8000000000; uint64_t idx = (a >> (12 + (9 * 0))) & 0xfffffffff; #if DEBUG_ENABLED(GetPTEntry) SerialPutString("PT idx = "); SerialPutHex64(idx); SerialPutChar('\n'); #endif return &t[idx]; } // // -- Some assembly CPU instructions // ------------------------------ static inline void INVLPG(Addr_t a) { __asm volatile("invlpg (%0)" :: "r"(a) : "memory"); } // // -- allocate a new frame // -------------------- Frame_t MmuGetTable(void) { extern Frame_t earlyFrame; return earlyFrame ++; } // // -- Some wrapper functions // ---------------------- //void MmuMapPage(Addr_t a, Frame_t f, int flags) { ldr_MmuMapPage(a, f, flags); } //void MmuUnmapPage(Addr_t a) { ldr_MmuUnmapPage(a); } // // -- Check if an address is mapped // ----------------------------- bool MmuIsMapped(Addr_t a) { #if DEBUG_ENABLED(MmuIsMapped) SerialPutString("Checking if address "); SerialPutHex64(a); SerialPutString(" is mapped\n"); #endif INVLPG((Addr_t)GetPML4Entry(a)); INVLPG((Addr_t)GetPDPTEntry(a)); INVLPG((Addr_t)GetPDEntry(a)); INVLPG((Addr_t)GetPTEntry(a)); #if DEBUG_ENABLED(MmuIsMapped) SerialPutString("Mapped? PML4 at "); SerialPutHex64((Addr_t)GetPML4Entry(a)); SerialPutChar('\n'); #endif if (!GetPML4Entry(a)->p) return false; #if DEBUG_ENABLED(MmuIsMapped) SerialPutString("mapped? PDPT at "); SerialPutHex64((Addr_t)GetPDPTEntry(a)); SerialPutChar('\n'); #endif if (!GetPDPTEntry(a)->p) return false; #if DEBUG_ENABLED(MmuIsMapped) SerialPutString("mapped? PD at "); SerialPutHex64((Addr_t)GetPDEntry(a)); SerialPutChar('\n'); #endif if (!GetPDEntry(a)->p) return false; #if DEBUG_ENABLED(MmuIsMapped) SerialPutString("mapped? PT at "); SerialPutHex64((Addr_t)GetPTEntry(a)); SerialPutChar('\n'); #endif if (!GetPTEntry(a)->p) return false; #if DEBUG_ENABLED(MmuIsMapped) SerialPutString("mapped.\n"); #endif return true; } // // -- Safely Unmap a page // ------------------- void ldr_MmuUnmapPage(Addr_t a) { #if DEBUG_ENABLED(ldr_MmuUnmapPage) SerialPutString("In address space "); SerialPutHex64(GetCr3()); SerialPutString(", Unmapping page at address "); SerialPutHex64(a); SerialPutChar('\n'); #endif if (MmuIsMapped(a)) { *(uint64_t *)GetPTEntry(a) = 0; INVLPG(a); } } // // -- Map a page to a frame // --------------------- void ldr_MmuMapPage(Addr_t a, Frame_t f, int flags) { #if DEBUG_ENABLED(ldr_MmuMapPage) SerialPutString("In address space "); SerialPutHex64(GetCr3()); SerialPutString(", request was made to map address "); SerialPutHex64(a); SerialPutString(" to frame "); SerialPutHex64(f); SerialPutChar('\n'); SerialPutString("Checking if the page is mapped\n"); #endif if (MmuIsMapped(a)) ldr_MmuUnmapPage(a); #if DEBUG_ENABLED(ldr_MmuMapPage) SerialPutString(".. Done -- guaranteed unmapped\n"); #endif Frame_t t; PageEntry_t *ent = GetPML4Entry(a); #if DEBUG_ENABLED(ldr_MmuMapPage) SerialPutString(".. Mapping PML4 @ "); SerialPutHex64((Addr_t)ent); SerialPutChar('\n'); #endif if (!ent->p) { t = MmuGetTable(); ent->frame = t; ent->rw = 1; ent->p = 1; __asm volatile ("wbnoinvd" ::: "memory"); INVLPG((Addr_t)GetPDPTEntry(a)); uint64_t *tbl = (uint64_t *)((Addr_t)GetPDPTEntry(a) & 0xfffffffffffff000); for (int i = 0; i < 512; i ++) { tbl[i] = 0; } } #if DEBUG_ENABLED(ldr_MmuMapPage) SerialPutString(".... [hex "); SerialPutHex64(*(uint64_t *)ent); SerialPutString("]\n"); #endif ent = GetPDPTEntry(a); #if DEBUG_ENABLED(ldr_MmuMapPage) SerialPutString(".. Mapping PDPT @ "); SerialPutHex64((Addr_t)ent); SerialPutChar('\n'); #endif if (!ent->p) { t = MmuGetTable(); ent->frame = t; ent->rw = 1; ent->p = 1; __asm volatile ("wbnoinvd" ::: "memory"); INVLPG((Addr_t)GetPDEntry(a)); uint64_t *tbl = (uint64_t *)((Addr_t)GetPDEntry(a) & 0xfffffffffffff000); for (int i = 0; i < 512; i ++) tbl[i] = 0; } #if DEBUG_ENABLED(ldr_MmuMapPage) SerialPutString(".... [hex "); SerialPutHex64(*(uint64_t *)ent); SerialPutString("]\n"); #endif ent = GetPDEntry(a); #if DEBUG_ENABLED(ldr_MmuMapPage) SerialPutString(".. Mapping PD @ "); SerialPutHex64((Addr_t)ent); SerialPutChar('\n'); #endif if (!ent->p) { t = MmuGetTable(); ent->frame = t; ent->rw = 1; ent->p = 1; __asm volatile ("wbnoinvd" ::: "memory"); INVLPG((Addr_t)GetPTEntry(a)); uint64_t *tbl = (uint64_t *)((Addr_t)GetPTEntry(a) & 0xfffffffffffff000); for (int i = 0; i < 512; i ++) tbl[i] = 0; #if DEBUG_ENABLED(ldr_MmuMapPage) SerialPutString("Address: "); SerialPutHex64((uint64_t)ent); SerialPutString(" .... [hex "); SerialPutHex64(*((uint64_t *)ent)); SerialPutString("]\n"); #endif } #if DEBUG_ENABLED(ldr_MmuMapPage) SerialPutString(".... [hex "); SerialPutHex64(*(uint64_t *)ent); SerialPutString("]\n"); #endif ent = GetPTEntry(a); #if DEBUG_ENABLED(ldr_MmuMapPage) SerialPutString(".. Mapping PT @ "); SerialPutHex64((Addr_t)ent); SerialPutChar('\n'); #endif ent->frame = f; ent->rw = (flags&PG_WRT?1:0); ent->pcd = (flags&PG_DEV?1:0); ent->pwt = (flags&PG_DEV?1:0); ent->us = (flags&PG_DEV?1:0); ent->p = 1; __asm volatile ("wbnoinvd" ::: "memory"); INVLPG((Addr_t)a); #if DEBUG_ENABLED(ldr_MmuMapPage) SerialPutString("Mapping complete!!\n"); #endif } // // -- Create an empty PDPT Table // -------------------------- void MmuEmptyPdpt(int index) { extern Frame_t earlyFrame; #if DEBUG_ENABLED(MmuEmptyPdpt) SerialPutString("Creating a PDPT table for PML4 index: "); SerialPutHex64(index); SerialPutChar('\n'); #endif PageEntry_t *ent = &((PageEntry_t *)0xfffffffffffff000)[index]; if (!ent->p) { ent->frame = earlyFrame ++; #if DEBUG_ENABLED(MmuEmptyPdpt) SerialPutString("Next frame is: "); SerialPutHex64(ent->frame); SerialPutChar('\n'); #endif ent->rw = 1; ent->p = 1; uint64_t *tbl = (uint64_t *)(0xffffffffffe00000 | (index << 12)); INVLPG((Addr_t)tbl); #if DEBUG_ENABLED(MmuEmptyPdpt) SerialPutString("Clearing the table starting at: "); SerialPutHex64((Addr_t)tbl); SerialPutChar('\n'); #endif for (int i = 0; i < 512; i ++) { #if DEBUG_ENABLED(MmuEmptyPdpt) SerialPutString("At address: "); SerialPutHex64((Addr_t)&tbl[i]); SerialPutChar('\n'); #endif tbl[i] = 0; } } }
22.649007
117
0.552729
eryjus
39503020253aa1fc8bd888aea2ab04ff9816e6bc
49
hpp
C++
src/agl/opengl/function/vertex_attribute/all.hpp
the-last-willy/abstractgl
d685bef25ac18773d3eea48ca52806c3a3485ddb
[ "MIT" ]
null
null
null
src/agl/opengl/function/vertex_attribute/all.hpp
the-last-willy/abstractgl
d685bef25ac18773d3eea48ca52806c3a3485ddb
[ "MIT" ]
null
null
null
src/agl/opengl/function/vertex_attribute/all.hpp
the-last-willy/abstractgl
d685bef25ac18773d3eea48ca52806c3a3485ddb
[ "MIT" ]
null
null
null
#pragma once #include "get_vertex_location.hpp"
12.25
34
0.795918
the-last-willy
39514b46fc36f061eaefc57aff06033acea5d384
1,023
cpp
C++
src/homework/tic_tac_toe/tic_tac_toe_manager.cpp
acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-Irvingperez
52f01b57eea81445f5ef13325969a8a1bd868c50
[ "MIT" ]
null
null
null
src/homework/tic_tac_toe/tic_tac_toe_manager.cpp
acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-Irvingperez
52f01b57eea81445f5ef13325969a8a1bd868c50
[ "MIT" ]
null
null
null
src/homework/tic_tac_toe/tic_tac_toe_manager.cpp
acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-Irvingperez
52f01b57eea81445f5ef13325969a8a1bd868c50
[ "MIT" ]
null
null
null
#include "tic_tac_toe_manager.h" void TicTacToeManager::save_game(std::unique_ptr<TicTacToe> & b) { update_winner_count(b->get_winner()); games.push_back(std::move(b)); } ostream& operator << (ostream& out, const TicTacToeManager& manager) { for(auto& x : manager.games) { out << *x; } out << "X won: " << manager.x_win << "\n"; out << "O won: " << manager.o_win << "\n"; out << "Ties: " << manager.tie << "\n"; return out; } void TicTacToeManager :: get_winner_total(int& o, int& x, int& t) { cout << endl << "X Wins =" << x << endl << "O Wins =" << o << endl << "Ties =" << t << endl << endl; } void TicTacToeManager :: update_winner_count(string winner) { if(winner== "X") x_win++; else if(winner =="O") o_win++; else tie++; } TicTacToeManager::TicTacToeManager(TicTacToeData& d) { games = d.get_games(); for(auto& g : games) { update_winner_count(g->get_winner()); } }
21.3125
68
0.545455
acc-cosc-1337-fall-2020
395242967db1c79c99f873570497994265193717
671
hpp
C++
src/input.hpp
MaemiKozue/hexceed
11ddcdfe3f7cadc23ca8ccba950df05fe49ce60a
[ "MIT" ]
null
null
null
src/input.hpp
MaemiKozue/hexceed
11ddcdfe3f7cadc23ca8ccba950df05fe49ce60a
[ "MIT" ]
null
null
null
src/input.hpp
MaemiKozue/hexceed
11ddcdfe3f7cadc23ca8ccba950df05fe49ce60a
[ "MIT" ]
null
null
null
#ifndef INPUT_H #define INPUT_H #include <iostream> typedef enum InputType { MOUSE, KEYBOARD } InputType; typedef enum KEY { KEY_ENTER } KEY; typedef enum MOUSE_BUTTON { MB_MIDDLE, MB_LEFT, MB_RIGHT } MOUSE_BUTTON; class Input { private: InputType type; int x, y; // mouse position MOUSE_BUTTON mb; // mouse button KEY key; // key press public: Input(MOUSE_BUTTON mb, int x, int y); Input(KEY key); ~Input(); InputType getType() const; int getX() const; int getY() const; MOUSE_BUTTON getButton() const; KEY getKey() const; }; std::ostream& operator<<(std::ostream& out, Input in); #endif // INPUT_H
15.97619
54
0.654247
MaemiKozue
39552ab957f0e29367375be85c5dd153557f0466
604
hpp
C++
Autoclicker GUI/Autoclicker GUI/GUI/Elements/Element/Element.hpp
CovERUshKA/Autoclicker
2f7f7cc3924495440c8afa797abadb92dba07faa
[ "MIT" ]
6
2020-07-05T05:52:30.000Z
2021-12-19T11:03:00.000Z
Autoclicker GUI/Autoclicker GUI/GUI/Elements/Element/Element.hpp
CovERUshKA/Autoclicker
2f7f7cc3924495440c8afa797abadb92dba07faa
[ "MIT" ]
null
null
null
Autoclicker GUI/Autoclicker GUI/GUI/Elements/Element/Element.hpp
CovERUshKA/Autoclicker
2f7f7cc3924495440c8afa797abadb92dba07faa
[ "MIT" ]
null
null
null
#pragma once #include <Windows.h> #include <string> #include "../../Def.hpp" class Element { public: // Type of the element( Button, TextEdit and etc. ) INT type; // Visible element or not bool visible; // ID of the element INT ID; // Position of the lement FLOAT x, y; // Size of the element FLOAT width, height; // Additional parameters for the element UINT params = 0; // Name of the element std::wstring wchElementName; Element(); virtual void Init(COGUI_ElementCreateStruct createStruct); virtual BOOL Render() = 0; virtual BOOL ApplyMessage(LPVOID lpCOGUIWndProc) = 0; };
17.257143
59
0.701987
CovERUshKA
395693c05065645deeca76b1e0fbb8443b352707
2,080
hpp
C++
ext/src/java/awt/BasicStroke.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
ext/src/java/awt/BasicStroke.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
ext/src/java/awt/BasicStroke.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar #pragma once #include <fwd-POI.hpp> #include <java/awt/fwd-POI.hpp> #include <java/lang/fwd-POI.hpp> #include <java/lang/Object.hpp> #include <java/awt/Stroke.hpp> struct default_init_tag; class java::awt::BasicStroke : public virtual ::java::lang::Object , public virtual Stroke { public: typedef ::java::lang::Object super; static constexpr int32_t CAP_BUTT { int32_t(0) }; static constexpr int32_t CAP_ROUND { int32_t(1) }; static constexpr int32_t CAP_SQUARE { int32_t(2) }; static constexpr int32_t JOIN_BEVEL { int32_t(2) }; static constexpr int32_t JOIN_MITER { int32_t(0) }; static constexpr int32_t JOIN_ROUND { int32_t(1) }; public: /* package */ int32_t cap { }; ::floatArray* dash { }; float dash_phase { }; int32_t join { }; float miterlimit { }; float width { }; protected: void ctor(); void ctor(float width); void ctor(float width, int32_t cap, int32_t join); void ctor(float width, int32_t cap, int32_t join, float miterlimit); void ctor(float width, int32_t cap, int32_t join, float miterlimit, ::floatArray* dash, float dash_phase); public: Shape* createStrokedShape(Shape* s) override; bool equals(::java::lang::Object* obj) override; virtual ::floatArray* getDashArray_(); virtual float getDashPhase(); virtual int32_t getEndCap(); virtual int32_t getLineJoin(); virtual float getLineWidth(); virtual float getMiterLimit(); int32_t hashCode() override; // Generated BasicStroke(); BasicStroke(float width); BasicStroke(float width, int32_t cap, int32_t join); BasicStroke(float width, int32_t cap, int32_t join, float miterlimit); BasicStroke(float width, int32_t cap, int32_t join, float miterlimit, ::floatArray* dash, float dash_phase); protected: BasicStroke(const ::default_init_tag&); public: static ::java::lang::Class *class_(); private: virtual ::java::lang::Class* getClass0(); };
30.144928
112
0.694231
pebble2015
39599126185e37194126c4ae8f0c418c2f957a66
487
hpp
C++
EntitySystemGenerator/Include/ComponentMapsSourceGenerator.hpp
jordanlittlefair/Foundation
ab737b933ea5bbe2be76133ed78c8e882f072fd0
[ "BSL-1.0" ]
null
null
null
EntitySystemGenerator/Include/ComponentMapsSourceGenerator.hpp
jordanlittlefair/Foundation
ab737b933ea5bbe2be76133ed78c8e882f072fd0
[ "BSL-1.0" ]
null
null
null
EntitySystemGenerator/Include/ComponentMapsSourceGenerator.hpp
jordanlittlefair/Foundation
ab737b933ea5bbe2be76133ed78c8e882f072fd0
[ "BSL-1.0" ]
null
null
null
#pragma once #ifndef _ENTITYSYSTEMGENERATOR_COMPONENTMAPSSOURCEGENERATOR_HPP_ #define _ENTITYSYSTEMGENERATOR_COMPONENTMAPSSOURCEGENERATOR_HPP_ #include "CodeGenerator.hpp" #include "ComponentDefinitions.hpp" namespace Fnd { namespace EntitySystemCodeGeneration { class ComponentMapsSourceGenerator: public CodeGenerator { public: bool Generate( const ComponentDefinitions& component_definitions, const std::string& output_file ); }; } } #endif
18.037037
68
0.780287
jordanlittlefair
395b252c334d240cbe37b6be91d0904cb2f834af
349
cpp
C++
cpp/cpp_primer/chapter10/ex_10_42.cpp
KaiserLancelot/Cpp-Primer
a4791a6765f0b6c864e8881e6a5328e2a3d68974
[ "MIT" ]
2
2019-12-21T00:53:47.000Z
2020-01-01T10:36:30.000Z
cpp/cpp_primer/chapter10/ex_10_42.cpp
KaiserLancelot/Cpp-Primer
a4791a6765f0b6c864e8881e6a5328e2a3d68974
[ "MIT" ]
null
null
null
cpp/cpp_primer/chapter10/ex_10_42.cpp
KaiserLancelot/Cpp-Primer
a4791a6765f0b6c864e8881e6a5328e2a3d68974
[ "MIT" ]
null
null
null
// // Created by kaiser on 18-12-17. // #include <algorithm> #include <iostream> #include <list> #include <string> void elim_dups(std::list<std::string>& words) { words.sort(); words.unique(); } int main() { std::list<std::string> vs{"a", "a", "c", "c", "b"}; elim_dups(vs); for (const auto& s : vs) { std::cout << s << '\n'; } }
15.863636
53
0.56447
KaiserLancelot
395f6301e153f9d9d7d2dd3428f88d665133c104
850
cpp
C++
PTA-B/right/1013-right.cpp
chiangyung/PTA
c8e6bcbc9e552dad5ab71679d861a235b8ad0730
[ "MIT" ]
2
2018-08-23T06:58:56.000Z
2018-09-04T02:07:44.000Z
PTA-B/right/1013-right.cpp
chiangyung/PTA
c8e6bcbc9e552dad5ab71679d861a235b8ad0730
[ "MIT" ]
null
null
null
PTA-B/right/1013-right.cpp
chiangyung/PTA
c8e6bcbc9e552dad5ab71679d861a235b8ad0730
[ "MIT" ]
null
null
null
#include <iostream> #include <math.h> using namespace std; const int INTMAX = pow(2, 30); bool is_prime(const int n) { for (int i = 2; i <= sqrt(n); i++) { if (n % i == 0) { return false; } } return true; } int main(int argc, char *argv[]) { int m, n; int count1 = 0, count2 = 0; cin >> m >> n; for (int i = 2; i < INTMAX; i++) { if (is_prime(i)) { count1++; if (count1 >= m && count1 <= n) { cout << i; count2++; if (count1 == n) { cout << endl; break; } if (count2 % 10 == 0) { cout << endl; } else { cout << " "; } } } } return 0; }
18.888889
45
0.342353
chiangyung
395f7c953cc08a36d29401fb4b839e28b84b46d3
531
cpp
C++
test/Model/Header.cpp
jxx-project/JXXRS
0d788e3aba5231ec1782699c9d397b9d81fdb1fd
[ "BSL-1.0" ]
null
null
null
test/Model/Header.cpp
jxx-project/JXXRS
0d788e3aba5231ec1782699c9d397b9d81fdb1fd
[ "BSL-1.0" ]
null
null
null
test/Model/Header.cpp
jxx-project/JXXRS
0d788e3aba5231ec1782699c9d397b9d81fdb1fd
[ "BSL-1.0" ]
null
null
null
// // Copyright (C) 2018 Dr. Michael Steffens // // SPDX-License-Identifier: BSL-1.0 // #include "Model/Header.h" namespace Model { Header::Header() { } Header::Header(const std::string& name, const std::string& value) : name(name), value(value) { } Header::Header(const JXXON::Json& json) : name(json.get<decltype(name)>("name")), value(json.get<decltype(value)>("value")) { } JXXON::Json Header::toJson() const { JXXON::Json json; json.set("name", name); json.set("value", value); return json; } } // namespace Model
16.090909
123
0.661017
jxx-project
396289f2ff22620325ab55248496538c6b002707
3,553
cpp
C++
src/caffe/test/test_training_utils.cpp
ayzk/ft-caffe-public
888399c2fcf90c227416576a5a265b218c6be5da
[ "BSD-2-Clause" ]
933
2016-08-29T14:29:20.000Z
2022-03-20T09:03:49.000Z
src/caffe/test/test_training_utils.cpp
ayzk/ft-caffe-public
888399c2fcf90c227416576a5a265b218c6be5da
[ "BSD-2-Clause" ]
286
2016-08-30T01:33:01.000Z
2021-08-22T08:34:19.000Z
src/caffe/test/test_training_utils.cpp
ayzk/ft-caffe-public
888399c2fcf90c227416576a5a265b218c6be5da
[ "BSD-2-Clause" ]
611
2016-08-30T07:22:04.000Z
2021-12-18T11:53:08.000Z
/* All modification made by Intel Corporation: © 2016 Intel Corporation All contributions by the University of California: Copyright (c) 2014, 2015, The Regents of the University of California (Regents) All rights reserved. All other contributions: Copyright (c) 2014, 2015, the respective contributors All rights reserved. For the list of contributors go to https://github.com/BVLC/caffe/blob/master/CONTRIBUTORS.md Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 <string> #include <utility> #include "boost/algorithm/string.hpp" #include "boost/lexical_cast.hpp" #include "google/protobuf/text_format.h" #include "gtest/gtest.h" #include "caffe/solver.hpp" #include "caffe/test/test_caffe_main.hpp" #include "caffe/util/io.hpp" #include "caffe/util/upgrade_proto.hpp" #include "caffe/training_utils.hpp" namespace caffe { class TrainingUtilsTest : public ::testing::Test { protected: TrainingUtilsTest() : topology_file_name_( CMAKE_SOURCE_DIR "caffe/test/test_data/test_topology.prototxt") { } string topology_file_name_; }; TEST_F(TrainingUtilsTest, GetStagesFromFlags) { string stages_flag = "stage1,stage2, stage3"; EXPECT_EQ(get_stages_from_flags(stages_flag).size(), 3); } TEST_F(TrainingUtilsTest, SetSolverParamsFromFlags) { caffe::SolverParameter solver_param; string solver; string engine = "new engine"; string stages = "stage1,stage2"; int level = 1; use_flags(&solver_param, solver, engine, level, stages); EXPECT_EQ(solver_param.engine(), engine); EXPECT_EQ(solver_param.train_state().stage_size(), 2); EXPECT_EQ(solver_param.train_state().level(), 1); } TEST_F(TrainingUtilsTest, MultiphaseTrainNegativeCpuMode) { caffe::MultiPhaseSolverParameter multi_solver_param; caffe::SolverBatchSizePair* solver_param_pair = multi_solver_param.add_params_pair(); solver_param_pair->mutable_solver_params()->set_solver_mode( caffe::SolverParameter_SolverMode_GPU); solver_param_pair->mutable_solver_params()->set_net( this->topology_file_name_); EXPECT_EQ(multiphase_train(&multi_solver_param, "", "", 0, ""), -1); } } // namespace caffe
35.178218
92
0.777934
ayzk
39644976619fc7b047dc5bfb77f4732ad44a2038
621
cxx
C++
test_code/test_fdstream_simple.cxx
m-renaud/posix-lib
0296999e252e2b40a80bcc01ea6a1742e8ef1c49
[ "BSD-2-Clause" ]
1
2020-11-11T12:50:30.000Z
2020-11-11T12:50:30.000Z
test_code/test_fdstream_simple.cxx
m-renaud/posix-lib
0296999e252e2b40a80bcc01ea6a1742e8ef1c49
[ "BSD-2-Clause" ]
null
null
null
test_code/test_fdstream_simple.cxx
m-renaud/posix-lib
0296999e252e2b40a80bcc01ea6a1742e8ef1c49
[ "BSD-2-Clause" ]
null
null
null
#include <iostream> #include "../fdstream.hxx" #include "../pipe.hxx" int main() { try { mrr::posix::pipe successful_auth; mrr::posix::fd_ostream write_end(successful_auth.write_end()); mrr::posix::fd_istream read_end(successful_auth.read_end()); int received[2]; write_end << 5 << std::endl; write_end << 8 << std::endl; read_end >> received[0]; read_end >> received[1]; std::cout << received[0] << std::endl << received[1] << std::endl; successful_auth.close(); } catch(std::system_error const& except) { mrr::posix::output_system_error_msg(); exit(1); } return 0; }
17.25
64
0.639291
m-renaud
396aeaba14dfb506f287778ba27e13dd0c0d77f0
1,473
hpp
C++
include/sprout/predef/compiler/sgi_mipspro.hpp
thinkoid/Sprout
a5a5944bb1779d3bb685087c58c20a4e18df2f39
[ "BSL-1.0" ]
4
2021-12-29T22:17:40.000Z
2022-03-23T11:53:44.000Z
dsp/lib/sprout/sprout/predef/compiler/sgi_mipspro.hpp
TheSlowGrowth/TapeLooper
ee8d8dccc27e39a6f6f6f435847e4d5e1b97c264
[ "MIT" ]
16
2021-10-31T21:41:09.000Z
2022-01-22T10:51:34.000Z
include/sprout/predef/compiler/sgi_mipspro.hpp
thinkoid/Sprout
a5a5944bb1779d3bb685087c58c20a4e18df2f39
[ "BSL-1.0" ]
null
null
null
/*============================================================================= Copyright (c) 2011-2019 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprout Distributed under the sprout Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.sprout.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef SPROUT_PREDEF_COMPILER_SGI_MIPSPRO_HPP #define SPROUT_PREDEF_COMPILER_SGI_MIPSPRO_HPP #include <sprout/config.hpp> #include <sprout/predef/make.hpp> #define SPROUT_COMP_SGI 0 #if defined(__sgi) || defined(sgi) # if !defined(SPROUT_COMP_SGI_DETECTION) && defined(_SGI_COMPILER_VERSION) # define SPROUT_COMP_SGI_DETECTION SPROUT_PREDEF_MAKE_10_VRP(_SGI_COMPILER_VERSION) # endif # if !defined(SPROUT_COMP_SGI_DETECTION) && defined(_COMPILER_VERSION) # define SPROUT_COMP_SGI_DETECTION SPROUT_PREDEF_MAKE_10_VRP(_COMPILER_VERSION) # endif # if !defined(SPROUT_COMP_SGI_DETECTION) # define SPROUT_COMP_SGI_DETECTION 1 # endif #endif #ifdef SPROUT_COMP_SGI_DETECTION # if defined(SPROUT_PREDEF_DETAIL_COMP_DETECTED) # define SPROUT_COMP_SGI_EMULATED SPROUT_COMP_SGI_DETECTION # else # undef SPROUT_COMP_SGI # define SPROUT_COMP_SGI SPROUT_COMP_SGI_DETECTION # endif # define SPROUT_COMP_SGI_AVAILABLE # include <sprout/predef/detail/comp_detected.hpp> #endif #define SPROUT_COMP_SGI_NAME "SGI MIPSpro" #endif //#ifndef SPROUT_PREDEF_COMPILER_SGI_MIPSPRO_HPP
35.071429
84
0.739308
thinkoid
396b1304f779670ccebfe8e01a457de7da6c4d38
1,764
hpp
C++
tasks/FrameFilter.hpp
PhischDotOrg/stm32f4-common
4b6b9c436018c89d3668c6ee107e97abb930bae2
[ "MIT" ]
1
2022-01-31T01:59:52.000Z
2022-01-31T01:59:52.000Z
tasks/FrameFilter.hpp
PhischDotOrg/stm32-common
4b6b9c436018c89d3668c6ee107e97abb930bae2
[ "MIT" ]
5
2020-04-13T21:55:12.000Z
2020-06-27T17:44:44.000Z
tasks/FrameFilter.hpp
PhischDotOrg/stm32f4-common
4b6b9c436018c89d3668c6ee107e97abb930bae2
[ "MIT" ]
null
null
null
/*- * $Copyright$ -*/ #ifndef _FRAME_FILTER_HPP_3532115b_b86b_48e5_a4c1_810606f79dfe #define _FRAME_FILTER_HPP_3532115b_b86b_48e5_a4c1_810606f79dfe #include <tasks/Task.hpp> #if defined(__cplusplus) extern "C" { #endif /* defined(__cplusplus) */ #include "FreeRTOS/FreeRTOS.h" #include "FreeRTOS/queue.h" #if defined(__cplusplus) } /* extern "C" */ #endif /* defined(__cplusplus) */ namespace tasks { template<typename InputBufferT, typename OutputBufferT, size_t N, typename FilterChainT, typename PinT, typename UartT> class FrameFilterT : public Task { private: UartT & m_uart; OutputBufferT (&m_frames)[N]; FilterChainT & m_filter; PinT * m_activeIndicationPin; unsigned m_current; QueueHandle_t * m_rxQueue; QueueHandle_t * m_txQueue; virtual void run(void); public: FrameFilterT(const char * const p_name, const unsigned p_priority, UartT &p_uart, OutputBufferT (&p_frames)[N], FilterChainT &p_filter); virtual ~FrameFilterT(); void setTxQueue(QueueHandle_t* p_txQueue) { m_txQueue = p_txQueue; } QueueHandle_t* getTxQueue() const { return m_txQueue; } void setRxQueue(QueueHandle_t* p_rxQueue) { m_rxQueue = p_rxQueue; } QueueHandle_t* getRxQueue() const { return m_rxQueue; } void setActiveIndicationPin(PinT* p_activeIndicationPin) { m_activeIndicationPin = p_activeIndicationPin; } PinT* getActiveIndicationPin() const { return m_activeIndicationPin; } typedef OutputBufferT Buffer_t; }; }; /* namespace tasks */ #include "FrameFilter.cpp" #endif /* _FRAME_FILTER_HPP_3532115b_b86b_48e5_a4c1_810606f79dfe */
25.2
119
0.679705
PhischDotOrg
396b3b879ceeafa68fd880dd22e30b04d2b335db
1,180
cpp
C++
SPOJ/MFLAR10 - Flowers Flourish From France/mflar10.cpp
Zubieta/CPP
fb4a3cbf2e4edcc590df15663cd28fb9ecab679c
[ "MIT" ]
8
2017-03-02T07:56:45.000Z
2021-08-07T20:20:19.000Z
SPOJ/MFLAR10 - Flowers Flourish From France/mflar10.cpp
zubie7a/Algorithms
fb4a3cbf2e4edcc590df15663cd28fb9ecab679c
[ "MIT" ]
null
null
null
SPOJ/MFLAR10 - Flowers Flourish From France/mflar10.cpp
zubie7a/Algorithms
fb4a3cbf2e4edcc590df15663cd28fb9ecab679c
[ "MIT" ]
1
2021-08-07T20:20:20.000Z
2021-08-07T20:20:20.000Z
/*Santiago Zubieta*/ #include <iostream> #include <numeric> #include <fstream> #include <climits> #include <cstring> #include <cstdio> #include <cmath> #include <queue> #include <list> #include <map> #include <set> #include <stack> #include <deque> #include <vector> #include <string> #include <cstdlib> #include <cassert> #include <sstream> #include <iterator> #include <algorithm> using namespace std; int main(){ bool worda=true,meg=false; char mega; int j; string word=""; while(word!="*"){ worda=true; meg=false; getline(cin,word); if (word=="*"){ break; } for(int i=0; i < word.size(); ++i){ word[i] = tolower(word[i]); } for(j=0;(j<word.size())&&(meg==false);++j){ if(word[j]!=' '){ mega=word[j]; meg=true; } } for(int i=j;(i<word.size())&&(worda==true);++i){ if((mega==word[i])&&(word[i-1]==' ')){ worda=true; } if((mega!=word[i])&&(word[i-1]==' ')){ worda=false; } } if(worda==true){ cout<<"Y"<<endl; } else{ cout<<"N"<<endl; } } }
18.730159
56
0.499153
Zubieta
396c73354d9d9ef8cf18366a2a474450ef4f9501
1,774
cc
C++
map-structure/vi-map/test/test_map_get_vertex_ids_in_mission_test.cc
AdronTech/maplab
1340e01466fc1c02994860723b8117daf9ad226d
[ "Apache-2.0" ]
1,936
2017-11-27T23:11:37.000Z
2022-03-30T14:24:14.000Z
map-structure/vi-map/test/test_map_get_vertex_ids_in_mission_test.cc
AdronTech/maplab
1340e01466fc1c02994860723b8117daf9ad226d
[ "Apache-2.0" ]
353
2017-11-29T18:40:39.000Z
2022-03-30T15:53:46.000Z
map-structure/vi-map/test/test_map_get_vertex_ids_in_mission_test.cc
AdronTech/maplab
1340e01466fc1c02994860723b8117daf9ad226d
[ "Apache-2.0" ]
661
2017-11-28T07:20:08.000Z
2022-03-28T08:06:29.000Z
#include <Eigen/Core> #include <gtest/gtest.h> #include <maplab-common/test/testing-entrypoint.h> #include "vi-map/test/vi-map-generator.h" namespace vi_map { class VIMapTest : public ::testing::Test { protected: VIMapTest() : map_(), generator_(map_, 42) {} virtual void SetUp() { pose::Transformation T_G_V; pose::Transformation T_G_M; missions_[0] = generator_.createMission(T_G_M); missions_[1] = generator_.createMission(T_G_M); vertices_[0] = generator_.createVertex(missions_[0], T_G_V); vertices_[1] = generator_.createVertex(missions_[0], T_G_V); vertices_[2] = generator_.createVertex(missions_[0], T_G_V); vertices_[3] = generator_.createVertex(missions_[1], T_G_V); vertices_[4] = generator_.createVertex(missions_[1], T_G_V); vertices_[5] = generator_.createVertex(missions_[1], T_G_V); generator_.generateMap(); } vi_map::MissionId missions_[2]; pose_graph::VertexId vertices_[6]; VIMap map_; VIMapGenerator generator_; public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW }; TEST_F(VIMapTest, TestGetAllVertexIdsInMission) { pose_graph::VertexIdList vertex_ids; map_.getAllVertexIdsInMission(missions_[0], &vertex_ids); for (const pose_graph::VertexId& vertex_id : vertex_ids) { EXPECT_EQ(map_.getVertex(vertex_id).getMissionId(), missions_[0]); } } TEST_F(VIMapTest, TestGetAllVertexIdsInMissionAlongGraph) { pose_graph::VertexIdList vertex_ids; map_.getAllVertexIdsInMissionAlongGraph(missions_[0], &vertex_ids); EXPECT_FALSE(vertex_ids.empty()); for (size_t i = 0; i < vertex_ids.size(); ++i) { EXPECT_EQ(map_.getVertex(vertex_ids[i]).getMissionId(), missions_[0]); EXPECT_EQ(vertex_ids[i], vertices_[i]); } } } // namespace vi_map MAPLAB_UNITTEST_ENTRYPOINT
27.71875
74
0.73168
AdronTech
397170c480ab89b57d5c1d86eefd61c9657a072d
10,484
cc
C++
src/io/scene_loader.cc
hyungman/SpRay
96380740dd88e6fbc21c0fdbf232cff357b1235d
[ "Apache-2.0" ]
7
2018-10-22T17:13:36.000Z
2020-04-17T08:28:55.000Z
src/io/scene_loader.cc
hyungman/SpRay
96380740dd88e6fbc21c0fdbf232cff357b1235d
[ "Apache-2.0" ]
null
null
null
src/io/scene_loader.cc
hyungman/SpRay
96380740dd88e6fbc21c0fdbf232cff357b1235d
[ "Apache-2.0" ]
1
2018-11-01T14:53:22.000Z
2018-11-01T14:53:22.000Z
// ========================================================================== // // Copyright (c) 2017-2018 The University of Texas at Austin. // // All rights reserved. // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // A copy of the License is included with this software in the file LICENSE. // // If your copy does not contain the License, you may obtain a copy of the // // License at: // // // // https://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // // // ========================================================================== // #include "io/scene_loader.h" #include <cstdlib> #include <cstring> #include <fstream> #include <string> #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #include "glog/logging.h" #include "render/aabb.h" #include "render/light.h" #include "render/reflection.h" #include "render/spray.h" // #define SPRAY_PRINT_LINES // #define SPRAY_PRINT_TOKENS namespace spray { SceneLoader::DomainTokenType SceneLoader::getTokenType(const std::string& tag) { DomainTokenType type; if (tag[0] == '#') { type = DomainTokenType::kComment; } else if (tag == "domain") { type = DomainTokenType::kDomain; } else if (tag == "file") { type = DomainTokenType::kFile; } else if (tag == "mtl") { type = DomainTokenType::kMaterial; } else if (tag == "bound") { type = DomainTokenType::kBound; } else if (tag == "scale") { type = DomainTokenType::kScale; } else if (tag == "rotate") { type = DomainTokenType::kRotate; } else if (tag == "translate") { type = DomainTokenType::kTranslate; } else if (tag == "face") { type = DomainTokenType::kFace; } else if (tag == "vertex") { type = DomainTokenType::kVertex; } else if (tag == "light") { type = DomainTokenType::kLight; } else { LOG(FATAL) << "unknown tag name " << tag; } return type; } void SceneLoader::parseDomain(const std::vector<std::string>& tokens) { nextDomain(); Domain& d = currentDomain(); d.id = domain_id_; d.transform = glm::mat4(1.f); } void SceneLoader::parseFile(const std::string& ply_path, const std::vector<std::string>& tokens) { Domain& d = currentDomain(); CHECK_EQ(tokens.size(), 2); d.filename = ply_path.empty() ? tokens[1] : ply_path + "/" + tokens[1]; } void SceneLoader::parseMaterial(const std::vector<std::string>& tokens) { Domain& d = currentDomain(); if (tokens[1] == "diffuse") { // mtl diffuse albedo<r g b> CHECK_EQ(tokens.size(), 5); glm::vec3 albedo; albedo[0] = atof(tokens[2].c_str()); albedo[1] = atof(tokens[3].c_str()); albedo[2] = atof(tokens[4].c_str()); d.bsdf = new DiffuseBsdf(albedo); } else if (tokens[1] == "mirror") { // mtl mirror reflectance<r g b> CHECK_EQ(tokens.size(), 5); glm::vec3 reflectance; reflectance[0] = atof(tokens[2].c_str()); reflectance[1] = atof(tokens[3].c_str()); reflectance[2] = atof(tokens[4].c_str()); d.bsdf = new MirrorBsdf(reflectance); } else if (tokens[1] == "glass") { // mtl mirror etaA etaB CHECK_EQ(tokens.size(), 4); float eta_a = atof(tokens[2].c_str()); float eta_b = atof(tokens[3].c_str()); d.bsdf = new GlassBsdf(eta_a, eta_b); } else if (tokens[1] == "transmission") { // mtl transmission etaA etaB CHECK_EQ(tokens.size(), 4); float eta_a = atof(tokens[2].c_str()); float eta_b = atof(tokens[3].c_str()); d.bsdf = new TransmissionBsdf(eta_a, eta_b); } else { LOG(FATAL) << "unknown material type " << tokens[1]; } } void SceneLoader::parseBound(const std::vector<std::string>& tokens) { Domain& d = currentDomain(); CHECK_EQ(tokens.size(), 7); glm::vec3 min(atof(tokens[1].c_str()), atof(tokens[2].c_str()), atof(tokens[3].c_str())); glm::vec3 max(atof(tokens[4].c_str()), atof(tokens[5].c_str()), atof(tokens[6].c_str())); d.object_aabb.bounds[0] = min; d.object_aabb.bounds[1] = max; } void SceneLoader::parseScale(const std::vector<std::string>& tokens) { Domain& d = currentDomain(); CHECK_EQ(tokens.size(), 4); d.transform = glm::scale( d.transform, glm::vec3(atof(tokens[1].c_str()), atof(tokens[2].c_str()), atof(tokens[3].c_str()))); } void SceneLoader::parseRotate(const std::vector<std::string>& tokens) { Domain& d = currentDomain(); CHECK_EQ(tokens.size(), 3); glm::vec3 axis; if (tokens[1] == "x") { axis = glm::vec3(1.f, 0.f, 0.f); } else if (tokens[1] == "y") { axis = glm::vec3(0.f, 1.f, 0.f); } else if (tokens[1] == "z") { axis = glm::vec3(0.f, 0.f, 1.f); } else { LOG(FATAL) << "invalid axis name " << tokens[1]; } d.transform = glm::rotate(d.transform, (float)glm::radians(atof(tokens[2].c_str())), axis); } void SceneLoader::parseTranslate(const std::vector<std::string>& tokens) { Domain& d = currentDomain(); CHECK_EQ(tokens.size(), 4); d.transform = glm::translate( d.transform, glm::vec3(atof(tokens[1].c_str()), atof(tokens[2].c_str()), atof(tokens[3].c_str()))); } void SceneLoader::parseFace(const std::vector<std::string>& tokens) { Domain& d = currentDomain(); CHECK_EQ(tokens.size(), 2); d.num_faces = std::stoul(tokens[1]); } void SceneLoader::parseVertex(const std::vector<std::string>& tokens) { Domain& d = currentDomain(); CHECK_EQ(tokens.size(), 2); d.num_vertices = std::stoul(tokens[1]); } void SceneLoader::parseLight(const std::vector<std::string>& tokens) { if (tokens[1] == "point") { CHECK_EQ(tokens.size(), 8); glm::vec3 position, radiance; position[0] = atof(tokens[2].c_str()); position[1] = atof(tokens[3].c_str()); position[2] = atof(tokens[4].c_str()); radiance[0] = atof(tokens[5].c_str()); radiance[1] = atof(tokens[6].c_str()); radiance[2] = atof(tokens[7].c_str()); addLight(new PointLight(position, radiance)); } else if (tokens[1] == "diffuse") { CHECK_EQ(tokens.size(), 5); glm::vec3 position, radiance; radiance[0] = atof(tokens[2].c_str()); radiance[1] = atof(tokens[3].c_str()); radiance[2] = atof(tokens[4].c_str()); addLight(new DiffuseHemisphereLight(radiance)); } else { LOG(FATAL) << "unknown light source " << tokens[1]; } } void SceneLoader::parseLineTokens(const std::string& ply_path, const std::vector<std::string>& tokens) { DomainTokenType type = getTokenType(tokens[0]); switch (type) { case DomainTokenType::kDomain: parseDomain(tokens); break; case DomainTokenType::kFile: parseFile(ply_path, tokens); break; case DomainTokenType::kMaterial: parseMaterial(tokens); break; case DomainTokenType::kBound: parseBound(tokens); break; case DomainTokenType::kScale: parseScale(tokens); break; case DomainTokenType::kRotate: parseRotate(tokens); break; case DomainTokenType::kTranslate: parseTranslate(tokens); break; case DomainTokenType::kFace: parseFace(tokens); break; case DomainTokenType::kVertex: parseVertex(tokens); break; case DomainTokenType::kLight: parseLight(tokens); break; default: break; } } void SceneLoader::countAndAllocate(std::ifstream& infile) { int ndomains = 0; int nlights = 0; std::string line; while (infile.good()) { getline(infile, line); char* token = std::strtok(&line[0], " "); if (token != NULL) { if (strcmp(token, "domain") == 0) { ++ndomains; } else if (strcmp(token, "light") == 0) { ++nlights; } } } CHECK_GT(ndomains, 0); domains_->resize(ndomains); if (nlights) lights_->resize(nlights); else std::cout << "[WARNING] no lights detected\n"; std::cout << "[INFO] number of domains: " << ndomains << "\n"; std::cout << "[INFO] number of lights: " << nlights << "\n"; } // # domain 0 // domain // file CornellBox-Original.obj // mtl 1 // bound -1 -1 -1 1 1 1 // scale 1 1 1 // rotate 0 0 0 // translate 0 0 0 // // # domain 1 // # tbd void SceneLoader::load(const std::string& filename, const std::string& ply_path, std::vector<Domain>* domains_out, std::vector<Light*>* lights_out) { reset(domains_out, lights_out); std::ifstream infile(filename); CHECK(infile.is_open()) << "unable to open input file " << filename; countAndAllocate(infile); infile.clear(); infile.seekg(infile.beg); char delim[] = " "; std::vector<std::string> tokens; while (infile.good()) { std::string line; getline(infile, line); #ifdef SPRAY_PRINT_LINES std::cout << line << "\n"; #endif char* token = std::strtok(&line[0], delim); tokens.clear(); while (token != NULL) { #ifdef SPRAY_PRINT_TOKENS std::cout << token << " token len:" << std::string(token).size() << "\n"; #endif tokens.push_back(token); token = std::strtok(NULL, delim); } if (tokens.size()) parseLineTokens(ply_path, tokens); } infile.close(); // apply transformation matrix for (auto& d : (*domains_out)) { glm::vec4 min = d.transform * glm::vec4(d.object_aabb.bounds[0], 1.0f); glm::vec4 max = d.transform * glm::vec4(d.object_aabb.bounds[1], 1.0f); d.world_aabb.bounds[0] = glm::vec3(min); d.world_aabb.bounds[1] = glm::vec3(max); } } } // namespace spray
29.041551
80
0.572778
hyungman
3974218429c4050238314f3d62724d1d653797df
10,436
hpp
C++
OpenAutoItParser/include/OpenAutoIt/TokenKind.hpp
OpenAutoit/OpenAutoit
f58c98c6e2a706ba7f06dcbc08a54a5a6440063e
[ "MIT" ]
null
null
null
OpenAutoItParser/include/OpenAutoIt/TokenKind.hpp
OpenAutoit/OpenAutoit
f58c98c6e2a706ba7f06dcbc08a54a5a6440063e
[ "MIT" ]
6
2022-02-01T04:07:12.000Z
2022-03-01T04:43:49.000Z
OpenAutoItParser/include/OpenAutoIt/TokenKind.hpp
OpenAutoit/OpenAutoit
f58c98c6e2a706ba7f06dcbc08a54a5a6440063e
[ "MIT" ]
null
null
null
#pragma once namespace OpenAutoIt { enum class TokenKind { NotAToken, EndOfFile, // '\0' NewLine, // '\n' Comment, // ; Comment VariableIdentifier, // $var FunctionIdentifier, // my_func /* Literals */ IntegerLiteral, // 123 FloatLiteral, // 0.123 StringLiteral, // "String" /* Punctioation */ Comma, // , LParen, // ( RParen, // ) Dot, // . LSquare, // [ RSquare, // ] /* Macros */ // https://www.autoitscript.com/autoit3/docs/macros.htm MK_AppDataCommonDir, // @AppDataCommonDir MK_AppDataDir, // @AppDataDir MK_AutoItExe, // @AutoItExe MK_AutoItPID, // @AutoItPID MK_AutoItVersion, // @AutoItVersion MK_AutoItX64, // @AutoItX64 MK_COM_EventObj, // @COM_EventObj MK_CommonFilesDir, // @CommonFilesDir MK_Compiled, // @Compiled MK_ComputerName, // @ComputerName MK_ComSpec, // @ComSpec MK_CPUArch, // @CPUArch MK_CR, // @CR MK_CRLF, // @CRLF MK_DesktopCommonDir, // @DesktopCommonDir MK_DesktopDepth, // @DesktopDepth MK_DesktopDir, // @DesktopDir MK_DesktopHeight, // @DesktopHeight MK_DesktopRefresh, // @DesktopRefresh MK_DesktopWidth, // @DesktopWidth MK_DocumentsCommonDir, // @DocumentsCommonDir MK_error, // @error MK_exitCode, // @exitCode MK_exitMethod, // @exitMethod MK_extended, // @extended MK_FavoritesCommonDir, // @FavoritesCommonDir MK_FavoritesDir, // @FavoritesDir MK_GUI_CtrlHandle, // @GUI_CtrlHandle MK_GUI_CtrlId, // @GUI_CtrlId MK_GUI_DragFile, // @GUI_DragFile MK_GUI_DragId, // @GUI_DragId MK_GUI_DropId, // @GUI_DropId MK_GUI_WinHandle, // @GUI_WinHandle MK_HomeDrive, // @HomeDrive MK_HomePath, // @HomePath MK_HomeShare, // @HomeShare MK_HotKeyPressed, // @HotKeyPressed MK_HOUR, // @HOUR MK_IPAddress1, // @IPAddress1 MK_IPAddress2, // @IPAddress2 MK_IPAddress3, // @IPAddress3 MK_IPAddress4, // @IPAddress4 MK_KBLayout, // @KBLayout MK_LF, // @LF MK_LocalAppDataDir, // @LocalAppDataDir MK_LogonDNSDomain, // @LogonDNSDomain MK_LogonDomain, // @LogonDomain MK_LogonServer, // @LogonServer MK_MDAY, // @MDAY MK_MIN, // @MIN MK_MON, // @MON MK_MSEC, // @MSEC MK_MUILang, // @MUILang MK_MyDocumentsDir, // @MyDocumentsDir MK_NumParams, // @NumParams MK_OSArch, // @OSArch MK_OSBuild, // @OSBuild MK_OSLang, // @OSLang MK_OSServicePack, // @OSServicePack MK_OSType, // @OSType MK_OSVersion, // @OSVersion MK_ProgramFilesDir, // @ProgramFilesDir MK_ProgramsCommonDir, // @ProgramsCommonDir MK_ProgramsDir, // @ProgramsDir MK_ScriptDir, // @ScriptDir MK_ScriptFullPath, // @ScriptFullPath MK_ScriptLineNumber, // @ScriptLineNumber MK_ScriptName, // @ScriptName MK_SEC, // @SEC MK_StartMenuCommonDir, // @StartMenuCommonDir MK_StartMenuDir, // @StartMenuDir MK_StartupCommonDir, // @StartupCommonDir MK_StartupDir, // @StartupDir MK_SW_DISABLE, // @SW_DISABLE MK_SW_ENABLE, // @SW_ENABLE MK_SW_HIDE, // @SW_HIDE MK_SW_LOCK, // @SW_LOCK MK_SW_MAXIMIZE, // @SW_MAXIMIZE MK_SW_MINIMIZE, // @SW_MINIMIZE MK_SW_RESTORE, // @SW_RESTORE MK_SW_SHOW, // @SW_SHOW MK_SW_SHOWDEFAULT, // @SW_SHOWDEFAULT MK_SW_SHOWMAXIMIZED, // @SW_SHOWMAXIMIZED MK_SW_SHOWMINIMIZED, // @SW_SHOWMINIMIZED MK_SW_SHOWMINNOACTIVE, // @SW_SHOWMINNOACTIVE MK_SW_SHOWNA, // @SW_SHOWNA MK_SW_SHOWNOACTIVATE, // @SW_SHOWNOACTIVATE MK_SW_SHOWNORMAL, // @SW_SHOWNORMAL MK_SW_UNLOCK, // @SW_UNLOCK MK_SystemDir, // @SystemDir MK_TAB, // @TAB MK_TempDir, // @TempDir MK_TRAY_ID, // @TRAY_ID MK_TrayIconFlashing, // @TrayIconFlashing MK_TrayIconVisible, // @TrayIconVisible MK_UserName, // @UserName MK_UserProfileDir, // @UserProfileDir MK_WDAY, // @WDAY MK_WindowsDir, // @WindowsDir MK_WorkingDir, // @WorkingDir MK_YDAY, // @YDAY MK_YEAR, // @YEAR /* Preprocessor identifiers */ // https://www.autoitscript.com/autoit3/docs/intro/lang_directives.htm // https://www.autoitscript.com/autoit3/docs/keywords/comments-start.htm // TODO: Do we really need both variants as seperate tokens? PP_CommentsStart, // #Comments-Start PP_CommentsEnd, // #Comments-End PP_CS, // #cs PP_CE, // #ce // https://www.autoitscript.com/autoit3/docs/keywords/include.htm PP_Include, // #include // https://www.autoitscript.com/autoit3/docs/keywords/include-once.htm PP_IncludeOnce, // #include-once // https://www.autoitscript.com/autoit3/docs/keywords/NoTrayIcon.htm PP_NoTrayIcon, // #NoTrayIcon // https://www.autoitscript.com/autoit3/docs/keywords/OnAutoItStartRegister.htm PP_OnAutoItStartRegister, // #OnAutoitStartRegister // https://www.autoitscript.com/autoit3/docs/keywords/pragma.htm PP_Pragma, // #pragma // https://www.autoitscript.com/autoit3/docs/keywords/RequireAdmin.htm PP_RequireAdmin, // # RequireAdmin /* Keywords */ // https://www.autoitscript.com/autoit3/docs/keywords.htm // https://www.autoitscript.com/autoit3/docs/intro/lang_operators.htm // https://www.autoitscript.com/autoit3/docs/keywords/Booleans.htm KW_False, // False KW_True, // True // https://www.autoitscript.com/autoit3/docs/keywords/ContinueCase.htm KW_ContinueCase, // ContinueCase // https://www.autoitscript.com/autoit3/docs/keywords/ContinueLoop.htm KW_ContinueLoop, // ContinueLoop // https://www.autoitscript.com/autoit3/docs/keywords/Default.htm KW_Default, // Default // https://www.autoitscript.com/autoit3/docs/keywords/Dim.htm KW_Dim, // Dim KW_Local, // Local KW_Global, // Global KW_Const, // Const // https://www.autoitscript.com/autoit3/docs/keywords/Do.htm KW_Do, // Do KW_Until, // Until // https://www.autoitscript.com/autoit3/docs/keywords/Enum.htm KW_Enum, // Enum // https://www.autoitscript.com/autoit3/docs/keywords/Exit.htm KW_Exit, // Exit // https://www.autoitscript.com/autoit3/docs/keywords/ExitLoop.htm KW_ExitLoop, // ExitLoop // https://www.autoitscript.com/autoit3/docs/keywords/For.htm KW_For, // For KW_To, // To KW_Step, // Step KW_Next, // Next // https://www.autoitscript.com/autoit3/docs/keywords/ForInNext.htm KW_In, // In // https://www.autoitscript.com/autoit3/docs/keywords/Func.htm KW_Func, // Func KW_Return, // Return KW_EndFunc, // EndFunc // https://www.autoitscript.com/autoit3/docs/keywords/If.htm KW_If, // If KW_Then, // Then KW_EndIf, // EndIf // https://www.autoitscript.com/autoit3/docs/keywords/IfElseEndIf.htm KW_ElseIf, // ElseIf KW_Else, // Else // https://www.autoitscript.com/autoit3/docs/keywords/Null.htm KW_Null, // Null // https://www.autoitscript.com/autoit3/docs/keywords/ReDim.htm KW_ReDim, // ReDim // https://www.autoitscript.com/autoit3/docs/keywords/Select.htm KW_Select, // Select KW_Case, // Case KW_EndSelect, // EndSelect // https://www.autoitscript.com/autoit3/docs/keywords/Static.htm KW_Static, // Static // https://www.autoitscript.com/autoit3/docs/keywords/Switch.htm KW_Switch, // Switch KW_EndSwitch, // EndSwitch // https://www.autoitscript.com/autoit3/docs/keywords/Volatile.htm KW_Volatile, // Volatile // https://www.autoitscript.com/autoit3/docs/keywords/While.htm KW_While, // While KW_WEnd, // WEnd // https://www.autoitscript.com/autoit3/docs/keywords/With.htm KW_With, // With KW_EndWith, // EndWith // https://www.autoitscript.com/autoit3/docs/intro/lang_operators.htm KW_And, // And KW_Or, // Or KW_Not, // Not /* Operator */ // https://www.autoitscript.com/autoit3/docs/intro/lang_operators.htm OP_Equals, // = (Note includes assignment and case insensitive comparision) OP_PlusEquals, // += OP_MinusEquals, // -= OP_MultiplyEquals, // *= OP_DivideEquals, // /= OP_Concatenate, // & OP_ConcatenateEquals, // &= OP_Plus, // + OP_Minus, // - OP_Multiply, // * OP_Divide, // / OP_Raise, // ^ OP_EqualsEquals, // == OP_NotEqual, // <> OP_GreaterThan, // > OP_GreaterThanEqual, // >= OP_LessThan, // < OP_LessThanEqual, // <= OP_TernaryIf, // ? OP_TernaryElse, // : }; } // namespace OpenAutoIt
41.412698
94
0.542353
OpenAutoit
3976a580c60f6c867eaa81ee34c727b5c0186dbd
2,118
cxx
C++
STEER/STEERBase/AliGenEposEventHeader.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
STEER/STEERBase/AliGenEposEventHeader.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
STEER/STEERBase/AliGenEposEventHeader.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ /* * AliGenEposEventHeader.h * * Header for EPOS generated event. * * Author: Piotr Ostrowski */ #include "AliGenEposEventHeader.h" ClassImp(AliGenEposEventHeader) AliGenEposEventHeader::AliGenEposEventHeader(const char* name): AliGenEventHeader(name), fBimevt(0), fPhievt(0), fKolevt(0), fKoievt(0), fPmxevt(0), fEgyevt(0), fNpjevt(0), fNtgevt(0), fNpnevt(0), fNppevt(0), fNtnevt(0), fNtpevt(0), fJpnevt(0), fJppevt(0), fJtnevt(0), fJtpevt(0), fXbjevt(0), fQsqevt(0), fNglevt(0), fZppevt(0), fZptevt(0) { // Constructor } AliGenEposEventHeader::AliGenEposEventHeader() : fBimevt(0), fPhievt(0), fKolevt(0), fKoievt(0), fPmxevt(0), fEgyevt(0), fNpjevt(0), fNtgevt(0), fNpnevt(0), fNppevt(0), fNtnevt(0), fNtpevt(0), fJpnevt(0), fJppevt(0), fJtnevt(0), fJtpevt(0), fXbjevt(0), fQsqevt(0), fNglevt(0), fZppevt(0), fZptevt(0) { // Default constructor }
25.518072
76
0.531161
AllaMaevskaya
397909e5ff617b46401a0c2a6bf3af3550b1f4c6
344
cpp
C++
Problemset/climbing-stairs/climbing-stairs.cpp
Singularity0909/LeetCode
d46fb1c8ed9b16339d46d5c37f69d44e5c178954
[ "MIT" ]
1
2020-10-06T01:06:45.000Z
2020-10-06T01:06:45.000Z
Problemset/climbing-stairs/climbing-stairs.cpp
Singularity0909/LeetCode
d46fb1c8ed9b16339d46d5c37f69d44e5c178954
[ "MIT" ]
null
null
null
Problemset/climbing-stairs/climbing-stairs.cpp
Singularity0909/LeetCode
d46fb1c8ed9b16339d46d5c37f69d44e5c178954
[ "MIT" ]
1
2021-11-17T13:52:51.000Z
2021-11-17T13:52:51.000Z
// @Title: 爬楼梯 (Climbing Stairs) // @Author: Singularity0909 // @Date: 2020-06-11 21:10:10 // @Runtime: 0 ms // @Memory: 5.6 MB class Solution { public: int ans[50] = { 0 }; int climbStairs(int n) { if (n <= 3) return n; return ans[n] ? ans[n] : ans[n] = climbStairs(n - 1) + climbStairs(n - 2); } };
19.111111
82
0.52907
Singularity0909
397adea56a014b5fc6911d96ffdb6695d6a84410
2,181
hpp
C++
VcppBits/Settings/SettingsException.hpp
faesong/vcppbits
9ad70f8e398110df48e4e2640a06fca09ef994f9
[ "MIT" ]
null
null
null
VcppBits/Settings/SettingsException.hpp
faesong/vcppbits
9ad70f8e398110df48e4e2640a06fca09ef994f9
[ "MIT" ]
null
null
null
VcppBits/Settings/SettingsException.hpp
faesong/vcppbits
9ad70f8e398110df48e4e2640a06fca09ef994f9
[ "MIT" ]
null
null
null
// The MIT License (MIT) // Copyright 2015-2020 Vitalii Minnakhmetov <restlessmonkey@ya.ru> // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. #ifndef VcppBits_SETTINGS_EXCEPTION_HPP_INCLUDED__ #define VcppBits_SETTINGS_EXCEPTION_HPP_INCLUDED__ #include <string> #include <stdexcept> #include "VcppBits/Settings/SettingsStringUtils.hpp" namespace VcppBits { class SettingsException : std::exception { public: enum TYPE { ALREADY_LOADED, NOT_FOUND, OUT_OF_RANGE }; SettingsException (const std::string &setting_name, TYPE t) : settingName(setting_name), type (t) { } ~SettingsException () throw () {} const std::string& getFullDescription () const { _errorMessage = std::string("Setting Error ") + SettingsStringUtils::toString(this->type) + ": \"" + settingName + "\""; return _errorMessage; } const char *what () const throw() { return this->getFullDescription().c_str(); } const std::string settingName; mutable std::string _errorMessage; const TYPE type; }; } // namespace VcppBits #endif // VcppBits_SETTINGS_EXCEPTION_HPP_INCLUDED__
34.619048
76
0.727648
faesong
397c9213cf3e3a4a6135912c2a1bfeec42dd44f7
51,295
cc
C++
c/test/cpp/auto_check_sbp_tracking_MsgMeasurementState.cc
Patrick-Luo-THR/libsbp
d42e4a1e3cedf6a82b1d993b82e0da148401f80d
[ "MIT" ]
65
2015-03-25T10:28:10.000Z
2022-02-24T12:36:49.000Z
c/test/cpp/auto_check_sbp_tracking_MsgMeasurementState.cc
Patrick-Luo-THR/libsbp
d42e4a1e3cedf6a82b1d993b82e0da148401f80d
[ "MIT" ]
654
2015-03-24T17:43:55.000Z
2022-03-31T21:42:49.000Z
c/test/cpp/auto_check_sbp_tracking_MsgMeasurementState.cc
Patrick-Luo-THR/libsbp
d42e4a1e3cedf6a82b1d993b82e0da148401f80d
[ "MIT" ]
110
2015-03-24T17:38:35.000Z
2022-03-21T02:05:19.000Z
/* * Copyright (C) 2015-2021 Swift Navigation Inc. * Contact: https://support.swiftnav.com * * This source is subject to the license found in the file 'LICENSE' which must * be be distributed together with this source. All other rights reserved. * * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. */ // This file was auto-generated from // spec/tests/yaml/swiftnav/sbp/tracking/test_MsgMeasurementState.yaml by // generate.py. Do not modify by hand! #include <gtest/gtest.h> #include <libsbp/cpp/message_handler.h> #include <libsbp/cpp/message_traits.h> #include <libsbp/cpp/state.h> #include <cstring> class Test_auto_check_sbp_tracking_MsgMeasurementState0 : public ::testing::Test, public sbp::State, public sbp::IReader, public sbp::IWriter, sbp::MessageHandler<sbp_msg_measurement_state_t> { public: Test_auto_check_sbp_tracking_MsgMeasurementState0() : ::testing::Test(), sbp::State(), sbp::IReader(), sbp::IWriter(), sbp::MessageHandler<sbp_msg_measurement_state_t>(this), last_msg_(), last_msg_len_(), last_sender_id_(), n_callbacks_logged_(), dummy_wr_(), dummy_rd_(), dummy_buff_() { set_reader(this); set_writer(this); } s32 read(uint8_t *buf, const uint32_t n) override { uint32_t real_n = n; memcpy(buf, dummy_buff_ + dummy_rd_, real_n); dummy_rd_ += real_n; return (s32)real_n; } s32 write(const uint8_t *buf, uint32_t n) override { uint32_t real_n = n; memcpy(dummy_buff_ + dummy_wr_, buf, real_n); dummy_wr_ += real_n; return (s32)real_n; } protected: void handle_sbp_msg(uint16_t sender_id, const sbp_msg_measurement_state_t &msg) override { last_msg_ = msg; last_sender_id_ = sender_id; n_callbacks_logged_++; } sbp_msg_measurement_state_t last_msg_; uint8_t last_msg_len_; uint16_t last_sender_id_; size_t n_callbacks_logged_; uint32_t dummy_wr_; uint32_t dummy_rd_; uint8_t dummy_buff_[1024]; }; TEST_F(Test_auto_check_sbp_tracking_MsgMeasurementState0, Test) { uint8_t encoded_frame[] = { 85, 97, 0, 207, 121, 237, 29, 0, 162, 0, 0, 0, 0, 0, 0, 27, 0, 201, 20, 0, 168, 32, 0, 184, 15, 0, 187, 0, 0, 0, 18, 0, 210, 16, 0, 167, 0, 0, 0, 23, 0, 213, 10, 0, 223, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 131, 2, 202, 27, 1, 192, 15, 1, 165, 29, 1, 146, 32, 1, 170, 18, 1, 201, 0, 0, 0, 0, 0, 0, 0, 0, 0, 23, 1, 212, 10, 1, 205, 0, 0, 0, 96, 3, 230, 0, 0, 0, 101, 3, 214, 103, 3, 212, 104, 3, 209, 106, 3, 157, 102, 3, 230, 0, 0, 0, 0, 0, 0, 101, 4, 189, 96, 4, 207, 106, 4, 164, 104, 4, 193, 0, 0, 0, 102, 4, 208, 0, 0, 0, 27, 12, 212, 29, 12, 161, 32, 12, 216, 30, 12, 216, 20, 12, 178, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 36, 14, 203, 0, 0, 0, 5, 14, 158, 4, 14, 194, 11, 14, 192, 9, 14, 207, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 20, 218, 5, 20, 176, 36, 20, 217, 11, 20, 200, 4, 20, 205, 0, 0, 0, 0, 0, 0, 35, 54, }; sbp_msg_measurement_state_t test_msg{}; test_msg.n_states = 79; test_msg.states[0].cn0 = 162; test_msg.states[0].mesid.code = 0; test_msg.states[0].mesid.sat = 29; test_msg.states[1].cn0 = 0; test_msg.states[1].mesid.code = 0; test_msg.states[1].mesid.sat = 0; test_msg.states[2].cn0 = 0; test_msg.states[2].mesid.code = 0; test_msg.states[2].mesid.sat = 0; test_msg.states[3].cn0 = 201; test_msg.states[3].mesid.code = 0; test_msg.states[3].mesid.sat = 27; test_msg.states[4].cn0 = 168; test_msg.states[4].mesid.code = 0; test_msg.states[4].mesid.sat = 20; test_msg.states[5].cn0 = 184; test_msg.states[5].mesid.code = 0; test_msg.states[5].mesid.sat = 32; test_msg.states[6].cn0 = 187; test_msg.states[6].mesid.code = 0; test_msg.states[6].mesid.sat = 15; test_msg.states[7].cn0 = 0; test_msg.states[7].mesid.code = 0; test_msg.states[7].mesid.sat = 0; test_msg.states[8].cn0 = 210; test_msg.states[8].mesid.code = 0; test_msg.states[8].mesid.sat = 18; test_msg.states[9].cn0 = 167; test_msg.states[9].mesid.code = 0; test_msg.states[9].mesid.sat = 16; test_msg.states[10].cn0 = 0; test_msg.states[10].mesid.code = 0; test_msg.states[10].mesid.sat = 0; test_msg.states[11].cn0 = 213; test_msg.states[11].mesid.code = 0; test_msg.states[11].mesid.sat = 23; test_msg.states[12].cn0 = 223; test_msg.states[12].mesid.code = 0; test_msg.states[12].mesid.sat = 10; test_msg.states[13].cn0 = 0; test_msg.states[13].mesid.code = 0; test_msg.states[13].mesid.sat = 0; test_msg.states[14].cn0 = 0; test_msg.states[14].mesid.code = 0; test_msg.states[14].mesid.sat = 0; test_msg.states[15].cn0 = 0; test_msg.states[15].mesid.code = 0; test_msg.states[15].mesid.sat = 0; test_msg.states[16].cn0 = 0; test_msg.states[16].mesid.code = 0; test_msg.states[16].mesid.sat = 0; test_msg.states[17].cn0 = 202; test_msg.states[17].mesid.code = 2; test_msg.states[17].mesid.sat = 131; test_msg.states[18].cn0 = 192; test_msg.states[18].mesid.code = 1; test_msg.states[18].mesid.sat = 27; test_msg.states[19].cn0 = 165; test_msg.states[19].mesid.code = 1; test_msg.states[19].mesid.sat = 15; test_msg.states[20].cn0 = 146; test_msg.states[20].mesid.code = 1; test_msg.states[20].mesid.sat = 29; test_msg.states[21].cn0 = 170; test_msg.states[21].mesid.code = 1; test_msg.states[21].mesid.sat = 32; test_msg.states[22].cn0 = 201; test_msg.states[22].mesid.code = 1; test_msg.states[22].mesid.sat = 18; test_msg.states[23].cn0 = 0; test_msg.states[23].mesid.code = 0; test_msg.states[23].mesid.sat = 0; test_msg.states[24].cn0 = 0; test_msg.states[24].mesid.code = 0; test_msg.states[24].mesid.sat = 0; test_msg.states[25].cn0 = 0; test_msg.states[25].mesid.code = 0; test_msg.states[25].mesid.sat = 0; test_msg.states[26].cn0 = 212; test_msg.states[26].mesid.code = 1; test_msg.states[26].mesid.sat = 23; test_msg.states[27].cn0 = 205; test_msg.states[27].mesid.code = 1; test_msg.states[27].mesid.sat = 10; test_msg.states[28].cn0 = 0; test_msg.states[28].mesid.code = 0; test_msg.states[28].mesid.sat = 0; test_msg.states[29].cn0 = 230; test_msg.states[29].mesid.code = 3; test_msg.states[29].mesid.sat = 96; test_msg.states[30].cn0 = 0; test_msg.states[30].mesid.code = 0; test_msg.states[30].mesid.sat = 0; test_msg.states[31].cn0 = 214; test_msg.states[31].mesid.code = 3; test_msg.states[31].mesid.sat = 101; test_msg.states[32].cn0 = 212; test_msg.states[32].mesid.code = 3; test_msg.states[32].mesid.sat = 103; test_msg.states[33].cn0 = 209; test_msg.states[33].mesid.code = 3; test_msg.states[33].mesid.sat = 104; test_msg.states[34].cn0 = 157; test_msg.states[34].mesid.code = 3; test_msg.states[34].mesid.sat = 106; test_msg.states[35].cn0 = 230; test_msg.states[35].mesid.code = 3; test_msg.states[35].mesid.sat = 102; test_msg.states[36].cn0 = 0; test_msg.states[36].mesid.code = 0; test_msg.states[36].mesid.sat = 0; test_msg.states[37].cn0 = 0; test_msg.states[37].mesid.code = 0; test_msg.states[37].mesid.sat = 0; test_msg.states[38].cn0 = 189; test_msg.states[38].mesid.code = 4; test_msg.states[38].mesid.sat = 101; test_msg.states[39].cn0 = 207; test_msg.states[39].mesid.code = 4; test_msg.states[39].mesid.sat = 96; test_msg.states[40].cn0 = 164; test_msg.states[40].mesid.code = 4; test_msg.states[40].mesid.sat = 106; test_msg.states[41].cn0 = 193; test_msg.states[41].mesid.code = 4; test_msg.states[41].mesid.sat = 104; test_msg.states[42].cn0 = 0; test_msg.states[42].mesid.code = 0; test_msg.states[42].mesid.sat = 0; test_msg.states[43].cn0 = 208; test_msg.states[43].mesid.code = 4; test_msg.states[43].mesid.sat = 102; test_msg.states[44].cn0 = 0; test_msg.states[44].mesid.code = 0; test_msg.states[44].mesid.sat = 0; test_msg.states[45].cn0 = 212; test_msg.states[45].mesid.code = 12; test_msg.states[45].mesid.sat = 27; test_msg.states[46].cn0 = 161; test_msg.states[46].mesid.code = 12; test_msg.states[46].mesid.sat = 29; test_msg.states[47].cn0 = 216; test_msg.states[47].mesid.code = 12; test_msg.states[47].mesid.sat = 32; test_msg.states[48].cn0 = 216; test_msg.states[48].mesid.code = 12; test_msg.states[48].mesid.sat = 30; test_msg.states[49].cn0 = 178; test_msg.states[49].mesid.code = 12; test_msg.states[49].mesid.sat = 20; test_msg.states[50].cn0 = 0; test_msg.states[50].mesid.code = 0; test_msg.states[50].mesid.sat = 0; test_msg.states[51].cn0 = 0; test_msg.states[51].mesid.code = 0; test_msg.states[51].mesid.sat = 0; test_msg.states[52].cn0 = 0; test_msg.states[52].mesid.code = 0; test_msg.states[52].mesid.sat = 0; test_msg.states[53].cn0 = 0; test_msg.states[53].mesid.code = 0; test_msg.states[53].mesid.sat = 0; test_msg.states[54].cn0 = 0; test_msg.states[54].mesid.code = 0; test_msg.states[54].mesid.sat = 0; test_msg.states[55].cn0 = 0; test_msg.states[55].mesid.code = 0; test_msg.states[55].mesid.sat = 0; test_msg.states[56].cn0 = 0; test_msg.states[56].mesid.code = 0; test_msg.states[56].mesid.sat = 0; test_msg.states[57].cn0 = 0; test_msg.states[57].mesid.code = 0; test_msg.states[57].mesid.sat = 0; test_msg.states[58].cn0 = 0; test_msg.states[58].mesid.code = 0; test_msg.states[58].mesid.sat = 0; test_msg.states[59].cn0 = 0; test_msg.states[59].mesid.code = 0; test_msg.states[59].mesid.sat = 0; test_msg.states[60].cn0 = 0; test_msg.states[60].mesid.code = 0; test_msg.states[60].mesid.sat = 0; test_msg.states[61].cn0 = 0; test_msg.states[61].mesid.code = 0; test_msg.states[61].mesid.sat = 0; test_msg.states[62].cn0 = 0; test_msg.states[62].mesid.code = 0; test_msg.states[62].mesid.sat = 0; test_msg.states[63].cn0 = 203; test_msg.states[63].mesid.code = 14; test_msg.states[63].mesid.sat = 36; test_msg.states[64].cn0 = 0; test_msg.states[64].mesid.code = 0; test_msg.states[64].mesid.sat = 0; test_msg.states[65].cn0 = 158; test_msg.states[65].mesid.code = 14; test_msg.states[65].mesid.sat = 5; test_msg.states[66].cn0 = 194; test_msg.states[66].mesid.code = 14; test_msg.states[66].mesid.sat = 4; test_msg.states[67].cn0 = 192; test_msg.states[67].mesid.code = 14; test_msg.states[67].mesid.sat = 11; test_msg.states[68].cn0 = 207; test_msg.states[68].mesid.code = 14; test_msg.states[68].mesid.sat = 9; test_msg.states[69].cn0 = 0; test_msg.states[69].mesid.code = 0; test_msg.states[69].mesid.sat = 0; test_msg.states[70].cn0 = 0; test_msg.states[70].mesid.code = 0; test_msg.states[70].mesid.sat = 0; test_msg.states[71].cn0 = 0; test_msg.states[71].mesid.code = 0; test_msg.states[71].mesid.sat = 0; test_msg.states[72].cn0 = 218; test_msg.states[72].mesid.code = 20; test_msg.states[72].mesid.sat = 9; test_msg.states[73].cn0 = 176; test_msg.states[73].mesid.code = 20; test_msg.states[73].mesid.sat = 5; test_msg.states[74].cn0 = 217; test_msg.states[74].mesid.code = 20; test_msg.states[74].mesid.sat = 36; test_msg.states[75].cn0 = 200; test_msg.states[75].mesid.code = 20; test_msg.states[75].mesid.sat = 11; test_msg.states[76].cn0 = 205; test_msg.states[76].mesid.code = 20; test_msg.states[76].mesid.sat = 4; test_msg.states[77].cn0 = 0; test_msg.states[77].mesid.code = 0; test_msg.states[77].mesid.sat = 0; test_msg.states[78].cn0 = 0; test_msg.states[78].mesid.code = 0; test_msg.states[78].mesid.sat = 0; EXPECT_EQ(send_message(31183, test_msg), SBP_OK); EXPECT_EQ(dummy_wr_, sizeof(encoded_frame)); EXPECT_EQ(memcmp(dummy_buff_, encoded_frame, sizeof(encoded_frame)), 0); while (dummy_rd_ < dummy_wr_) { process(); } EXPECT_EQ(n_callbacks_logged_, 1); EXPECT_EQ(last_sender_id_, 31183); EXPECT_EQ(last_msg_, test_msg); EXPECT_EQ(last_msg_.n_states, 79) << "incorrect value for last_msg_.n_states, expected 79, is " << last_msg_.n_states; EXPECT_EQ(last_msg_.states[0].cn0, 162) << "incorrect value for last_msg_.states[0].cn0, expected 162, is " << last_msg_.states[0].cn0; EXPECT_EQ(last_msg_.states[0].mesid.code, 0) << "incorrect value for last_msg_.states[0].mesid.code, expected 0, is " << last_msg_.states[0].mesid.code; EXPECT_EQ(last_msg_.states[0].mesid.sat, 29) << "incorrect value for last_msg_.states[0].mesid.sat, expected 29, is " << last_msg_.states[0].mesid.sat; EXPECT_EQ(last_msg_.states[1].cn0, 0) << "incorrect value for last_msg_.states[1].cn0, expected 0, is " << last_msg_.states[1].cn0; EXPECT_EQ(last_msg_.states[1].mesid.code, 0) << "incorrect value for last_msg_.states[1].mesid.code, expected 0, is " << last_msg_.states[1].mesid.code; EXPECT_EQ(last_msg_.states[1].mesid.sat, 0) << "incorrect value for last_msg_.states[1].mesid.sat, expected 0, is " << last_msg_.states[1].mesid.sat; EXPECT_EQ(last_msg_.states[2].cn0, 0) << "incorrect value for last_msg_.states[2].cn0, expected 0, is " << last_msg_.states[2].cn0; EXPECT_EQ(last_msg_.states[2].mesid.code, 0) << "incorrect value for last_msg_.states[2].mesid.code, expected 0, is " << last_msg_.states[2].mesid.code; EXPECT_EQ(last_msg_.states[2].mesid.sat, 0) << "incorrect value for last_msg_.states[2].mesid.sat, expected 0, is " << last_msg_.states[2].mesid.sat; EXPECT_EQ(last_msg_.states[3].cn0, 201) << "incorrect value for last_msg_.states[3].cn0, expected 201, is " << last_msg_.states[3].cn0; EXPECT_EQ(last_msg_.states[3].mesid.code, 0) << "incorrect value for last_msg_.states[3].mesid.code, expected 0, is " << last_msg_.states[3].mesid.code; EXPECT_EQ(last_msg_.states[3].mesid.sat, 27) << "incorrect value for last_msg_.states[3].mesid.sat, expected 27, is " << last_msg_.states[3].mesid.sat; EXPECT_EQ(last_msg_.states[4].cn0, 168) << "incorrect value for last_msg_.states[4].cn0, expected 168, is " << last_msg_.states[4].cn0; EXPECT_EQ(last_msg_.states[4].mesid.code, 0) << "incorrect value for last_msg_.states[4].mesid.code, expected 0, is " << last_msg_.states[4].mesid.code; EXPECT_EQ(last_msg_.states[4].mesid.sat, 20) << "incorrect value for last_msg_.states[4].mesid.sat, expected 20, is " << last_msg_.states[4].mesid.sat; EXPECT_EQ(last_msg_.states[5].cn0, 184) << "incorrect value for last_msg_.states[5].cn0, expected 184, is " << last_msg_.states[5].cn0; EXPECT_EQ(last_msg_.states[5].mesid.code, 0) << "incorrect value for last_msg_.states[5].mesid.code, expected 0, is " << last_msg_.states[5].mesid.code; EXPECT_EQ(last_msg_.states[5].mesid.sat, 32) << "incorrect value for last_msg_.states[5].mesid.sat, expected 32, is " << last_msg_.states[5].mesid.sat; EXPECT_EQ(last_msg_.states[6].cn0, 187) << "incorrect value for last_msg_.states[6].cn0, expected 187, is " << last_msg_.states[6].cn0; EXPECT_EQ(last_msg_.states[6].mesid.code, 0) << "incorrect value for last_msg_.states[6].mesid.code, expected 0, is " << last_msg_.states[6].mesid.code; EXPECT_EQ(last_msg_.states[6].mesid.sat, 15) << "incorrect value for last_msg_.states[6].mesid.sat, expected 15, is " << last_msg_.states[6].mesid.sat; EXPECT_EQ(last_msg_.states[7].cn0, 0) << "incorrect value for last_msg_.states[7].cn0, expected 0, is " << last_msg_.states[7].cn0; EXPECT_EQ(last_msg_.states[7].mesid.code, 0) << "incorrect value for last_msg_.states[7].mesid.code, expected 0, is " << last_msg_.states[7].mesid.code; EXPECT_EQ(last_msg_.states[7].mesid.sat, 0) << "incorrect value for last_msg_.states[7].mesid.sat, expected 0, is " << last_msg_.states[7].mesid.sat; EXPECT_EQ(last_msg_.states[8].cn0, 210) << "incorrect value for last_msg_.states[8].cn0, expected 210, is " << last_msg_.states[8].cn0; EXPECT_EQ(last_msg_.states[8].mesid.code, 0) << "incorrect value for last_msg_.states[8].mesid.code, expected 0, is " << last_msg_.states[8].mesid.code; EXPECT_EQ(last_msg_.states[8].mesid.sat, 18) << "incorrect value for last_msg_.states[8].mesid.sat, expected 18, is " << last_msg_.states[8].mesid.sat; EXPECT_EQ(last_msg_.states[9].cn0, 167) << "incorrect value for last_msg_.states[9].cn0, expected 167, is " << last_msg_.states[9].cn0; EXPECT_EQ(last_msg_.states[9].mesid.code, 0) << "incorrect value for last_msg_.states[9].mesid.code, expected 0, is " << last_msg_.states[9].mesid.code; EXPECT_EQ(last_msg_.states[9].mesid.sat, 16) << "incorrect value for last_msg_.states[9].mesid.sat, expected 16, is " << last_msg_.states[9].mesid.sat; EXPECT_EQ(last_msg_.states[10].cn0, 0) << "incorrect value for last_msg_.states[10].cn0, expected 0, is " << last_msg_.states[10].cn0; EXPECT_EQ(last_msg_.states[10].mesid.code, 0) << "incorrect value for last_msg_.states[10].mesid.code, expected 0, is " << last_msg_.states[10].mesid.code; EXPECT_EQ(last_msg_.states[10].mesid.sat, 0) << "incorrect value for last_msg_.states[10].mesid.sat, expected 0, is " << last_msg_.states[10].mesid.sat; EXPECT_EQ(last_msg_.states[11].cn0, 213) << "incorrect value for last_msg_.states[11].cn0, expected 213, is " << last_msg_.states[11].cn0; EXPECT_EQ(last_msg_.states[11].mesid.code, 0) << "incorrect value for last_msg_.states[11].mesid.code, expected 0, is " << last_msg_.states[11].mesid.code; EXPECT_EQ(last_msg_.states[11].mesid.sat, 23) << "incorrect value for last_msg_.states[11].mesid.sat, expected 23, is " << last_msg_.states[11].mesid.sat; EXPECT_EQ(last_msg_.states[12].cn0, 223) << "incorrect value for last_msg_.states[12].cn0, expected 223, is " << last_msg_.states[12].cn0; EXPECT_EQ(last_msg_.states[12].mesid.code, 0) << "incorrect value for last_msg_.states[12].mesid.code, expected 0, is " << last_msg_.states[12].mesid.code; EXPECT_EQ(last_msg_.states[12].mesid.sat, 10) << "incorrect value for last_msg_.states[12].mesid.sat, expected 10, is " << last_msg_.states[12].mesid.sat; EXPECT_EQ(last_msg_.states[13].cn0, 0) << "incorrect value for last_msg_.states[13].cn0, expected 0, is " << last_msg_.states[13].cn0; EXPECT_EQ(last_msg_.states[13].mesid.code, 0) << "incorrect value for last_msg_.states[13].mesid.code, expected 0, is " << last_msg_.states[13].mesid.code; EXPECT_EQ(last_msg_.states[13].mesid.sat, 0) << "incorrect value for last_msg_.states[13].mesid.sat, expected 0, is " << last_msg_.states[13].mesid.sat; EXPECT_EQ(last_msg_.states[14].cn0, 0) << "incorrect value for last_msg_.states[14].cn0, expected 0, is " << last_msg_.states[14].cn0; EXPECT_EQ(last_msg_.states[14].mesid.code, 0) << "incorrect value for last_msg_.states[14].mesid.code, expected 0, is " << last_msg_.states[14].mesid.code; EXPECT_EQ(last_msg_.states[14].mesid.sat, 0) << "incorrect value for last_msg_.states[14].mesid.sat, expected 0, is " << last_msg_.states[14].mesid.sat; EXPECT_EQ(last_msg_.states[15].cn0, 0) << "incorrect value for last_msg_.states[15].cn0, expected 0, is " << last_msg_.states[15].cn0; EXPECT_EQ(last_msg_.states[15].mesid.code, 0) << "incorrect value for last_msg_.states[15].mesid.code, expected 0, is " << last_msg_.states[15].mesid.code; EXPECT_EQ(last_msg_.states[15].mesid.sat, 0) << "incorrect value for last_msg_.states[15].mesid.sat, expected 0, is " << last_msg_.states[15].mesid.sat; EXPECT_EQ(last_msg_.states[16].cn0, 0) << "incorrect value for last_msg_.states[16].cn0, expected 0, is " << last_msg_.states[16].cn0; EXPECT_EQ(last_msg_.states[16].mesid.code, 0) << "incorrect value for last_msg_.states[16].mesid.code, expected 0, is " << last_msg_.states[16].mesid.code; EXPECT_EQ(last_msg_.states[16].mesid.sat, 0) << "incorrect value for last_msg_.states[16].mesid.sat, expected 0, is " << last_msg_.states[16].mesid.sat; EXPECT_EQ(last_msg_.states[17].cn0, 202) << "incorrect value for last_msg_.states[17].cn0, expected 202, is " << last_msg_.states[17].cn0; EXPECT_EQ(last_msg_.states[17].mesid.code, 2) << "incorrect value for last_msg_.states[17].mesid.code, expected 2, is " << last_msg_.states[17].mesid.code; EXPECT_EQ(last_msg_.states[17].mesid.sat, 131) << "incorrect value for last_msg_.states[17].mesid.sat, expected 131, is " << last_msg_.states[17].mesid.sat; EXPECT_EQ(last_msg_.states[18].cn0, 192) << "incorrect value for last_msg_.states[18].cn0, expected 192, is " << last_msg_.states[18].cn0; EXPECT_EQ(last_msg_.states[18].mesid.code, 1) << "incorrect value for last_msg_.states[18].mesid.code, expected 1, is " << last_msg_.states[18].mesid.code; EXPECT_EQ(last_msg_.states[18].mesid.sat, 27) << "incorrect value for last_msg_.states[18].mesid.sat, expected 27, is " << last_msg_.states[18].mesid.sat; EXPECT_EQ(last_msg_.states[19].cn0, 165) << "incorrect value for last_msg_.states[19].cn0, expected 165, is " << last_msg_.states[19].cn0; EXPECT_EQ(last_msg_.states[19].mesid.code, 1) << "incorrect value for last_msg_.states[19].mesid.code, expected 1, is " << last_msg_.states[19].mesid.code; EXPECT_EQ(last_msg_.states[19].mesid.sat, 15) << "incorrect value for last_msg_.states[19].mesid.sat, expected 15, is " << last_msg_.states[19].mesid.sat; EXPECT_EQ(last_msg_.states[20].cn0, 146) << "incorrect value for last_msg_.states[20].cn0, expected 146, is " << last_msg_.states[20].cn0; EXPECT_EQ(last_msg_.states[20].mesid.code, 1) << "incorrect value for last_msg_.states[20].mesid.code, expected 1, is " << last_msg_.states[20].mesid.code; EXPECT_EQ(last_msg_.states[20].mesid.sat, 29) << "incorrect value for last_msg_.states[20].mesid.sat, expected 29, is " << last_msg_.states[20].mesid.sat; EXPECT_EQ(last_msg_.states[21].cn0, 170) << "incorrect value for last_msg_.states[21].cn0, expected 170, is " << last_msg_.states[21].cn0; EXPECT_EQ(last_msg_.states[21].mesid.code, 1) << "incorrect value for last_msg_.states[21].mesid.code, expected 1, is " << last_msg_.states[21].mesid.code; EXPECT_EQ(last_msg_.states[21].mesid.sat, 32) << "incorrect value for last_msg_.states[21].mesid.sat, expected 32, is " << last_msg_.states[21].mesid.sat; EXPECT_EQ(last_msg_.states[22].cn0, 201) << "incorrect value for last_msg_.states[22].cn0, expected 201, is " << last_msg_.states[22].cn0; EXPECT_EQ(last_msg_.states[22].mesid.code, 1) << "incorrect value for last_msg_.states[22].mesid.code, expected 1, is " << last_msg_.states[22].mesid.code; EXPECT_EQ(last_msg_.states[22].mesid.sat, 18) << "incorrect value for last_msg_.states[22].mesid.sat, expected 18, is " << last_msg_.states[22].mesid.sat; EXPECT_EQ(last_msg_.states[23].cn0, 0) << "incorrect value for last_msg_.states[23].cn0, expected 0, is " << last_msg_.states[23].cn0; EXPECT_EQ(last_msg_.states[23].mesid.code, 0) << "incorrect value for last_msg_.states[23].mesid.code, expected 0, is " << last_msg_.states[23].mesid.code; EXPECT_EQ(last_msg_.states[23].mesid.sat, 0) << "incorrect value for last_msg_.states[23].mesid.sat, expected 0, is " << last_msg_.states[23].mesid.sat; EXPECT_EQ(last_msg_.states[24].cn0, 0) << "incorrect value for last_msg_.states[24].cn0, expected 0, is " << last_msg_.states[24].cn0; EXPECT_EQ(last_msg_.states[24].mesid.code, 0) << "incorrect value for last_msg_.states[24].mesid.code, expected 0, is " << last_msg_.states[24].mesid.code; EXPECT_EQ(last_msg_.states[24].mesid.sat, 0) << "incorrect value for last_msg_.states[24].mesid.sat, expected 0, is " << last_msg_.states[24].mesid.sat; EXPECT_EQ(last_msg_.states[25].cn0, 0) << "incorrect value for last_msg_.states[25].cn0, expected 0, is " << last_msg_.states[25].cn0; EXPECT_EQ(last_msg_.states[25].mesid.code, 0) << "incorrect value for last_msg_.states[25].mesid.code, expected 0, is " << last_msg_.states[25].mesid.code; EXPECT_EQ(last_msg_.states[25].mesid.sat, 0) << "incorrect value for last_msg_.states[25].mesid.sat, expected 0, is " << last_msg_.states[25].mesid.sat; EXPECT_EQ(last_msg_.states[26].cn0, 212) << "incorrect value for last_msg_.states[26].cn0, expected 212, is " << last_msg_.states[26].cn0; EXPECT_EQ(last_msg_.states[26].mesid.code, 1) << "incorrect value for last_msg_.states[26].mesid.code, expected 1, is " << last_msg_.states[26].mesid.code; EXPECT_EQ(last_msg_.states[26].mesid.sat, 23) << "incorrect value for last_msg_.states[26].mesid.sat, expected 23, is " << last_msg_.states[26].mesid.sat; EXPECT_EQ(last_msg_.states[27].cn0, 205) << "incorrect value for last_msg_.states[27].cn0, expected 205, is " << last_msg_.states[27].cn0; EXPECT_EQ(last_msg_.states[27].mesid.code, 1) << "incorrect value for last_msg_.states[27].mesid.code, expected 1, is " << last_msg_.states[27].mesid.code; EXPECT_EQ(last_msg_.states[27].mesid.sat, 10) << "incorrect value for last_msg_.states[27].mesid.sat, expected 10, is " << last_msg_.states[27].mesid.sat; EXPECT_EQ(last_msg_.states[28].cn0, 0) << "incorrect value for last_msg_.states[28].cn0, expected 0, is " << last_msg_.states[28].cn0; EXPECT_EQ(last_msg_.states[28].mesid.code, 0) << "incorrect value for last_msg_.states[28].mesid.code, expected 0, is " << last_msg_.states[28].mesid.code; EXPECT_EQ(last_msg_.states[28].mesid.sat, 0) << "incorrect value for last_msg_.states[28].mesid.sat, expected 0, is " << last_msg_.states[28].mesid.sat; EXPECT_EQ(last_msg_.states[29].cn0, 230) << "incorrect value for last_msg_.states[29].cn0, expected 230, is " << last_msg_.states[29].cn0; EXPECT_EQ(last_msg_.states[29].mesid.code, 3) << "incorrect value for last_msg_.states[29].mesid.code, expected 3, is " << last_msg_.states[29].mesid.code; EXPECT_EQ(last_msg_.states[29].mesid.sat, 96) << "incorrect value for last_msg_.states[29].mesid.sat, expected 96, is " << last_msg_.states[29].mesid.sat; EXPECT_EQ(last_msg_.states[30].cn0, 0) << "incorrect value for last_msg_.states[30].cn0, expected 0, is " << last_msg_.states[30].cn0; EXPECT_EQ(last_msg_.states[30].mesid.code, 0) << "incorrect value for last_msg_.states[30].mesid.code, expected 0, is " << last_msg_.states[30].mesid.code; EXPECT_EQ(last_msg_.states[30].mesid.sat, 0) << "incorrect value for last_msg_.states[30].mesid.sat, expected 0, is " << last_msg_.states[30].mesid.sat; EXPECT_EQ(last_msg_.states[31].cn0, 214) << "incorrect value for last_msg_.states[31].cn0, expected 214, is " << last_msg_.states[31].cn0; EXPECT_EQ(last_msg_.states[31].mesid.code, 3) << "incorrect value for last_msg_.states[31].mesid.code, expected 3, is " << last_msg_.states[31].mesid.code; EXPECT_EQ(last_msg_.states[31].mesid.sat, 101) << "incorrect value for last_msg_.states[31].mesid.sat, expected 101, is " << last_msg_.states[31].mesid.sat; EXPECT_EQ(last_msg_.states[32].cn0, 212) << "incorrect value for last_msg_.states[32].cn0, expected 212, is " << last_msg_.states[32].cn0; EXPECT_EQ(last_msg_.states[32].mesid.code, 3) << "incorrect value for last_msg_.states[32].mesid.code, expected 3, is " << last_msg_.states[32].mesid.code; EXPECT_EQ(last_msg_.states[32].mesid.sat, 103) << "incorrect value for last_msg_.states[32].mesid.sat, expected 103, is " << last_msg_.states[32].mesid.sat; EXPECT_EQ(last_msg_.states[33].cn0, 209) << "incorrect value for last_msg_.states[33].cn0, expected 209, is " << last_msg_.states[33].cn0; EXPECT_EQ(last_msg_.states[33].mesid.code, 3) << "incorrect value for last_msg_.states[33].mesid.code, expected 3, is " << last_msg_.states[33].mesid.code; EXPECT_EQ(last_msg_.states[33].mesid.sat, 104) << "incorrect value for last_msg_.states[33].mesid.sat, expected 104, is " << last_msg_.states[33].mesid.sat; EXPECT_EQ(last_msg_.states[34].cn0, 157) << "incorrect value for last_msg_.states[34].cn0, expected 157, is " << last_msg_.states[34].cn0; EXPECT_EQ(last_msg_.states[34].mesid.code, 3) << "incorrect value for last_msg_.states[34].mesid.code, expected 3, is " << last_msg_.states[34].mesid.code; EXPECT_EQ(last_msg_.states[34].mesid.sat, 106) << "incorrect value for last_msg_.states[34].mesid.sat, expected 106, is " << last_msg_.states[34].mesid.sat; EXPECT_EQ(last_msg_.states[35].cn0, 230) << "incorrect value for last_msg_.states[35].cn0, expected 230, is " << last_msg_.states[35].cn0; EXPECT_EQ(last_msg_.states[35].mesid.code, 3) << "incorrect value for last_msg_.states[35].mesid.code, expected 3, is " << last_msg_.states[35].mesid.code; EXPECT_EQ(last_msg_.states[35].mesid.sat, 102) << "incorrect value for last_msg_.states[35].mesid.sat, expected 102, is " << last_msg_.states[35].mesid.sat; EXPECT_EQ(last_msg_.states[36].cn0, 0) << "incorrect value for last_msg_.states[36].cn0, expected 0, is " << last_msg_.states[36].cn0; EXPECT_EQ(last_msg_.states[36].mesid.code, 0) << "incorrect value for last_msg_.states[36].mesid.code, expected 0, is " << last_msg_.states[36].mesid.code; EXPECT_EQ(last_msg_.states[36].mesid.sat, 0) << "incorrect value for last_msg_.states[36].mesid.sat, expected 0, is " << last_msg_.states[36].mesid.sat; EXPECT_EQ(last_msg_.states[37].cn0, 0) << "incorrect value for last_msg_.states[37].cn0, expected 0, is " << last_msg_.states[37].cn0; EXPECT_EQ(last_msg_.states[37].mesid.code, 0) << "incorrect value for last_msg_.states[37].mesid.code, expected 0, is " << last_msg_.states[37].mesid.code; EXPECT_EQ(last_msg_.states[37].mesid.sat, 0) << "incorrect value for last_msg_.states[37].mesid.sat, expected 0, is " << last_msg_.states[37].mesid.sat; EXPECT_EQ(last_msg_.states[38].cn0, 189) << "incorrect value for last_msg_.states[38].cn0, expected 189, is " << last_msg_.states[38].cn0; EXPECT_EQ(last_msg_.states[38].mesid.code, 4) << "incorrect value for last_msg_.states[38].mesid.code, expected 4, is " << last_msg_.states[38].mesid.code; EXPECT_EQ(last_msg_.states[38].mesid.sat, 101) << "incorrect value for last_msg_.states[38].mesid.sat, expected 101, is " << last_msg_.states[38].mesid.sat; EXPECT_EQ(last_msg_.states[39].cn0, 207) << "incorrect value for last_msg_.states[39].cn0, expected 207, is " << last_msg_.states[39].cn0; EXPECT_EQ(last_msg_.states[39].mesid.code, 4) << "incorrect value for last_msg_.states[39].mesid.code, expected 4, is " << last_msg_.states[39].mesid.code; EXPECT_EQ(last_msg_.states[39].mesid.sat, 96) << "incorrect value for last_msg_.states[39].mesid.sat, expected 96, is " << last_msg_.states[39].mesid.sat; EXPECT_EQ(last_msg_.states[40].cn0, 164) << "incorrect value for last_msg_.states[40].cn0, expected 164, is " << last_msg_.states[40].cn0; EXPECT_EQ(last_msg_.states[40].mesid.code, 4) << "incorrect value for last_msg_.states[40].mesid.code, expected 4, is " << last_msg_.states[40].mesid.code; EXPECT_EQ(last_msg_.states[40].mesid.sat, 106) << "incorrect value for last_msg_.states[40].mesid.sat, expected 106, is " << last_msg_.states[40].mesid.sat; EXPECT_EQ(last_msg_.states[41].cn0, 193) << "incorrect value for last_msg_.states[41].cn0, expected 193, is " << last_msg_.states[41].cn0; EXPECT_EQ(last_msg_.states[41].mesid.code, 4) << "incorrect value for last_msg_.states[41].mesid.code, expected 4, is " << last_msg_.states[41].mesid.code; EXPECT_EQ(last_msg_.states[41].mesid.sat, 104) << "incorrect value for last_msg_.states[41].mesid.sat, expected 104, is " << last_msg_.states[41].mesid.sat; EXPECT_EQ(last_msg_.states[42].cn0, 0) << "incorrect value for last_msg_.states[42].cn0, expected 0, is " << last_msg_.states[42].cn0; EXPECT_EQ(last_msg_.states[42].mesid.code, 0) << "incorrect value for last_msg_.states[42].mesid.code, expected 0, is " << last_msg_.states[42].mesid.code; EXPECT_EQ(last_msg_.states[42].mesid.sat, 0) << "incorrect value for last_msg_.states[42].mesid.sat, expected 0, is " << last_msg_.states[42].mesid.sat; EXPECT_EQ(last_msg_.states[43].cn0, 208) << "incorrect value for last_msg_.states[43].cn0, expected 208, is " << last_msg_.states[43].cn0; EXPECT_EQ(last_msg_.states[43].mesid.code, 4) << "incorrect value for last_msg_.states[43].mesid.code, expected 4, is " << last_msg_.states[43].mesid.code; EXPECT_EQ(last_msg_.states[43].mesid.sat, 102) << "incorrect value for last_msg_.states[43].mesid.sat, expected 102, is " << last_msg_.states[43].mesid.sat; EXPECT_EQ(last_msg_.states[44].cn0, 0) << "incorrect value for last_msg_.states[44].cn0, expected 0, is " << last_msg_.states[44].cn0; EXPECT_EQ(last_msg_.states[44].mesid.code, 0) << "incorrect value for last_msg_.states[44].mesid.code, expected 0, is " << last_msg_.states[44].mesid.code; EXPECT_EQ(last_msg_.states[44].mesid.sat, 0) << "incorrect value for last_msg_.states[44].mesid.sat, expected 0, is " << last_msg_.states[44].mesid.sat; EXPECT_EQ(last_msg_.states[45].cn0, 212) << "incorrect value for last_msg_.states[45].cn0, expected 212, is " << last_msg_.states[45].cn0; EXPECT_EQ(last_msg_.states[45].mesid.code, 12) << "incorrect value for last_msg_.states[45].mesid.code, expected 12, is " << last_msg_.states[45].mesid.code; EXPECT_EQ(last_msg_.states[45].mesid.sat, 27) << "incorrect value for last_msg_.states[45].mesid.sat, expected 27, is " << last_msg_.states[45].mesid.sat; EXPECT_EQ(last_msg_.states[46].cn0, 161) << "incorrect value for last_msg_.states[46].cn0, expected 161, is " << last_msg_.states[46].cn0; EXPECT_EQ(last_msg_.states[46].mesid.code, 12) << "incorrect value for last_msg_.states[46].mesid.code, expected 12, is " << last_msg_.states[46].mesid.code; EXPECT_EQ(last_msg_.states[46].mesid.sat, 29) << "incorrect value for last_msg_.states[46].mesid.sat, expected 29, is " << last_msg_.states[46].mesid.sat; EXPECT_EQ(last_msg_.states[47].cn0, 216) << "incorrect value for last_msg_.states[47].cn0, expected 216, is " << last_msg_.states[47].cn0; EXPECT_EQ(last_msg_.states[47].mesid.code, 12) << "incorrect value for last_msg_.states[47].mesid.code, expected 12, is " << last_msg_.states[47].mesid.code; EXPECT_EQ(last_msg_.states[47].mesid.sat, 32) << "incorrect value for last_msg_.states[47].mesid.sat, expected 32, is " << last_msg_.states[47].mesid.sat; EXPECT_EQ(last_msg_.states[48].cn0, 216) << "incorrect value for last_msg_.states[48].cn0, expected 216, is " << last_msg_.states[48].cn0; EXPECT_EQ(last_msg_.states[48].mesid.code, 12) << "incorrect value for last_msg_.states[48].mesid.code, expected 12, is " << last_msg_.states[48].mesid.code; EXPECT_EQ(last_msg_.states[48].mesid.sat, 30) << "incorrect value for last_msg_.states[48].mesid.sat, expected 30, is " << last_msg_.states[48].mesid.sat; EXPECT_EQ(last_msg_.states[49].cn0, 178) << "incorrect value for last_msg_.states[49].cn0, expected 178, is " << last_msg_.states[49].cn0; EXPECT_EQ(last_msg_.states[49].mesid.code, 12) << "incorrect value for last_msg_.states[49].mesid.code, expected 12, is " << last_msg_.states[49].mesid.code; EXPECT_EQ(last_msg_.states[49].mesid.sat, 20) << "incorrect value for last_msg_.states[49].mesid.sat, expected 20, is " << last_msg_.states[49].mesid.sat; EXPECT_EQ(last_msg_.states[50].cn0, 0) << "incorrect value for last_msg_.states[50].cn0, expected 0, is " << last_msg_.states[50].cn0; EXPECT_EQ(last_msg_.states[50].mesid.code, 0) << "incorrect value for last_msg_.states[50].mesid.code, expected 0, is " << last_msg_.states[50].mesid.code; EXPECT_EQ(last_msg_.states[50].mesid.sat, 0) << "incorrect value for last_msg_.states[50].mesid.sat, expected 0, is " << last_msg_.states[50].mesid.sat; EXPECT_EQ(last_msg_.states[51].cn0, 0) << "incorrect value for last_msg_.states[51].cn0, expected 0, is " << last_msg_.states[51].cn0; EXPECT_EQ(last_msg_.states[51].mesid.code, 0) << "incorrect value for last_msg_.states[51].mesid.code, expected 0, is " << last_msg_.states[51].mesid.code; EXPECT_EQ(last_msg_.states[51].mesid.sat, 0) << "incorrect value for last_msg_.states[51].mesid.sat, expected 0, is " << last_msg_.states[51].mesid.sat; EXPECT_EQ(last_msg_.states[52].cn0, 0) << "incorrect value for last_msg_.states[52].cn0, expected 0, is " << last_msg_.states[52].cn0; EXPECT_EQ(last_msg_.states[52].mesid.code, 0) << "incorrect value for last_msg_.states[52].mesid.code, expected 0, is " << last_msg_.states[52].mesid.code; EXPECT_EQ(last_msg_.states[52].mesid.sat, 0) << "incorrect value for last_msg_.states[52].mesid.sat, expected 0, is " << last_msg_.states[52].mesid.sat; EXPECT_EQ(last_msg_.states[53].cn0, 0) << "incorrect value for last_msg_.states[53].cn0, expected 0, is " << last_msg_.states[53].cn0; EXPECT_EQ(last_msg_.states[53].mesid.code, 0) << "incorrect value for last_msg_.states[53].mesid.code, expected 0, is " << last_msg_.states[53].mesid.code; EXPECT_EQ(last_msg_.states[53].mesid.sat, 0) << "incorrect value for last_msg_.states[53].mesid.sat, expected 0, is " << last_msg_.states[53].mesid.sat; EXPECT_EQ(last_msg_.states[54].cn0, 0) << "incorrect value for last_msg_.states[54].cn0, expected 0, is " << last_msg_.states[54].cn0; EXPECT_EQ(last_msg_.states[54].mesid.code, 0) << "incorrect value for last_msg_.states[54].mesid.code, expected 0, is " << last_msg_.states[54].mesid.code; EXPECT_EQ(last_msg_.states[54].mesid.sat, 0) << "incorrect value for last_msg_.states[54].mesid.sat, expected 0, is " << last_msg_.states[54].mesid.sat; EXPECT_EQ(last_msg_.states[55].cn0, 0) << "incorrect value for last_msg_.states[55].cn0, expected 0, is " << last_msg_.states[55].cn0; EXPECT_EQ(last_msg_.states[55].mesid.code, 0) << "incorrect value for last_msg_.states[55].mesid.code, expected 0, is " << last_msg_.states[55].mesid.code; EXPECT_EQ(last_msg_.states[55].mesid.sat, 0) << "incorrect value for last_msg_.states[55].mesid.sat, expected 0, is " << last_msg_.states[55].mesid.sat; EXPECT_EQ(last_msg_.states[56].cn0, 0) << "incorrect value for last_msg_.states[56].cn0, expected 0, is " << last_msg_.states[56].cn0; EXPECT_EQ(last_msg_.states[56].mesid.code, 0) << "incorrect value for last_msg_.states[56].mesid.code, expected 0, is " << last_msg_.states[56].mesid.code; EXPECT_EQ(last_msg_.states[56].mesid.sat, 0) << "incorrect value for last_msg_.states[56].mesid.sat, expected 0, is " << last_msg_.states[56].mesid.sat; EXPECT_EQ(last_msg_.states[57].cn0, 0) << "incorrect value for last_msg_.states[57].cn0, expected 0, is " << last_msg_.states[57].cn0; EXPECT_EQ(last_msg_.states[57].mesid.code, 0) << "incorrect value for last_msg_.states[57].mesid.code, expected 0, is " << last_msg_.states[57].mesid.code; EXPECT_EQ(last_msg_.states[57].mesid.sat, 0) << "incorrect value for last_msg_.states[57].mesid.sat, expected 0, is " << last_msg_.states[57].mesid.sat; EXPECT_EQ(last_msg_.states[58].cn0, 0) << "incorrect value for last_msg_.states[58].cn0, expected 0, is " << last_msg_.states[58].cn0; EXPECT_EQ(last_msg_.states[58].mesid.code, 0) << "incorrect value for last_msg_.states[58].mesid.code, expected 0, is " << last_msg_.states[58].mesid.code; EXPECT_EQ(last_msg_.states[58].mesid.sat, 0) << "incorrect value for last_msg_.states[58].mesid.sat, expected 0, is " << last_msg_.states[58].mesid.sat; EXPECT_EQ(last_msg_.states[59].cn0, 0) << "incorrect value for last_msg_.states[59].cn0, expected 0, is " << last_msg_.states[59].cn0; EXPECT_EQ(last_msg_.states[59].mesid.code, 0) << "incorrect value for last_msg_.states[59].mesid.code, expected 0, is " << last_msg_.states[59].mesid.code; EXPECT_EQ(last_msg_.states[59].mesid.sat, 0) << "incorrect value for last_msg_.states[59].mesid.sat, expected 0, is " << last_msg_.states[59].mesid.sat; EXPECT_EQ(last_msg_.states[60].cn0, 0) << "incorrect value for last_msg_.states[60].cn0, expected 0, is " << last_msg_.states[60].cn0; EXPECT_EQ(last_msg_.states[60].mesid.code, 0) << "incorrect value for last_msg_.states[60].mesid.code, expected 0, is " << last_msg_.states[60].mesid.code; EXPECT_EQ(last_msg_.states[60].mesid.sat, 0) << "incorrect value for last_msg_.states[60].mesid.sat, expected 0, is " << last_msg_.states[60].mesid.sat; EXPECT_EQ(last_msg_.states[61].cn0, 0) << "incorrect value for last_msg_.states[61].cn0, expected 0, is " << last_msg_.states[61].cn0; EXPECT_EQ(last_msg_.states[61].mesid.code, 0) << "incorrect value for last_msg_.states[61].mesid.code, expected 0, is " << last_msg_.states[61].mesid.code; EXPECT_EQ(last_msg_.states[61].mesid.sat, 0) << "incorrect value for last_msg_.states[61].mesid.sat, expected 0, is " << last_msg_.states[61].mesid.sat; EXPECT_EQ(last_msg_.states[62].cn0, 0) << "incorrect value for last_msg_.states[62].cn0, expected 0, is " << last_msg_.states[62].cn0; EXPECT_EQ(last_msg_.states[62].mesid.code, 0) << "incorrect value for last_msg_.states[62].mesid.code, expected 0, is " << last_msg_.states[62].mesid.code; EXPECT_EQ(last_msg_.states[62].mesid.sat, 0) << "incorrect value for last_msg_.states[62].mesid.sat, expected 0, is " << last_msg_.states[62].mesid.sat; EXPECT_EQ(last_msg_.states[63].cn0, 203) << "incorrect value for last_msg_.states[63].cn0, expected 203, is " << last_msg_.states[63].cn0; EXPECT_EQ(last_msg_.states[63].mesid.code, 14) << "incorrect value for last_msg_.states[63].mesid.code, expected 14, is " << last_msg_.states[63].mesid.code; EXPECT_EQ(last_msg_.states[63].mesid.sat, 36) << "incorrect value for last_msg_.states[63].mesid.sat, expected 36, is " << last_msg_.states[63].mesid.sat; EXPECT_EQ(last_msg_.states[64].cn0, 0) << "incorrect value for last_msg_.states[64].cn0, expected 0, is " << last_msg_.states[64].cn0; EXPECT_EQ(last_msg_.states[64].mesid.code, 0) << "incorrect value for last_msg_.states[64].mesid.code, expected 0, is " << last_msg_.states[64].mesid.code; EXPECT_EQ(last_msg_.states[64].mesid.sat, 0) << "incorrect value for last_msg_.states[64].mesid.sat, expected 0, is " << last_msg_.states[64].mesid.sat; EXPECT_EQ(last_msg_.states[65].cn0, 158) << "incorrect value for last_msg_.states[65].cn0, expected 158, is " << last_msg_.states[65].cn0; EXPECT_EQ(last_msg_.states[65].mesid.code, 14) << "incorrect value for last_msg_.states[65].mesid.code, expected 14, is " << last_msg_.states[65].mesid.code; EXPECT_EQ(last_msg_.states[65].mesid.sat, 5) << "incorrect value for last_msg_.states[65].mesid.sat, expected 5, is " << last_msg_.states[65].mesid.sat; EXPECT_EQ(last_msg_.states[66].cn0, 194) << "incorrect value for last_msg_.states[66].cn0, expected 194, is " << last_msg_.states[66].cn0; EXPECT_EQ(last_msg_.states[66].mesid.code, 14) << "incorrect value for last_msg_.states[66].mesid.code, expected 14, is " << last_msg_.states[66].mesid.code; EXPECT_EQ(last_msg_.states[66].mesid.sat, 4) << "incorrect value for last_msg_.states[66].mesid.sat, expected 4, is " << last_msg_.states[66].mesid.sat; EXPECT_EQ(last_msg_.states[67].cn0, 192) << "incorrect value for last_msg_.states[67].cn0, expected 192, is " << last_msg_.states[67].cn0; EXPECT_EQ(last_msg_.states[67].mesid.code, 14) << "incorrect value for last_msg_.states[67].mesid.code, expected 14, is " << last_msg_.states[67].mesid.code; EXPECT_EQ(last_msg_.states[67].mesid.sat, 11) << "incorrect value for last_msg_.states[67].mesid.sat, expected 11, is " << last_msg_.states[67].mesid.sat; EXPECT_EQ(last_msg_.states[68].cn0, 207) << "incorrect value for last_msg_.states[68].cn0, expected 207, is " << last_msg_.states[68].cn0; EXPECT_EQ(last_msg_.states[68].mesid.code, 14) << "incorrect value for last_msg_.states[68].mesid.code, expected 14, is " << last_msg_.states[68].mesid.code; EXPECT_EQ(last_msg_.states[68].mesid.sat, 9) << "incorrect value for last_msg_.states[68].mesid.sat, expected 9, is " << last_msg_.states[68].mesid.sat; EXPECT_EQ(last_msg_.states[69].cn0, 0) << "incorrect value for last_msg_.states[69].cn0, expected 0, is " << last_msg_.states[69].cn0; EXPECT_EQ(last_msg_.states[69].mesid.code, 0) << "incorrect value for last_msg_.states[69].mesid.code, expected 0, is " << last_msg_.states[69].mesid.code; EXPECT_EQ(last_msg_.states[69].mesid.sat, 0) << "incorrect value for last_msg_.states[69].mesid.sat, expected 0, is " << last_msg_.states[69].mesid.sat; EXPECT_EQ(last_msg_.states[70].cn0, 0) << "incorrect value for last_msg_.states[70].cn0, expected 0, is " << last_msg_.states[70].cn0; EXPECT_EQ(last_msg_.states[70].mesid.code, 0) << "incorrect value for last_msg_.states[70].mesid.code, expected 0, is " << last_msg_.states[70].mesid.code; EXPECT_EQ(last_msg_.states[70].mesid.sat, 0) << "incorrect value for last_msg_.states[70].mesid.sat, expected 0, is " << last_msg_.states[70].mesid.sat; EXPECT_EQ(last_msg_.states[71].cn0, 0) << "incorrect value for last_msg_.states[71].cn0, expected 0, is " << last_msg_.states[71].cn0; EXPECT_EQ(last_msg_.states[71].mesid.code, 0) << "incorrect value for last_msg_.states[71].mesid.code, expected 0, is " << last_msg_.states[71].mesid.code; EXPECT_EQ(last_msg_.states[71].mesid.sat, 0) << "incorrect value for last_msg_.states[71].mesid.sat, expected 0, is " << last_msg_.states[71].mesid.sat; EXPECT_EQ(last_msg_.states[72].cn0, 218) << "incorrect value for last_msg_.states[72].cn0, expected 218, is " << last_msg_.states[72].cn0; EXPECT_EQ(last_msg_.states[72].mesid.code, 20) << "incorrect value for last_msg_.states[72].mesid.code, expected 20, is " << last_msg_.states[72].mesid.code; EXPECT_EQ(last_msg_.states[72].mesid.sat, 9) << "incorrect value for last_msg_.states[72].mesid.sat, expected 9, is " << last_msg_.states[72].mesid.sat; EXPECT_EQ(last_msg_.states[73].cn0, 176) << "incorrect value for last_msg_.states[73].cn0, expected 176, is " << last_msg_.states[73].cn0; EXPECT_EQ(last_msg_.states[73].mesid.code, 20) << "incorrect value for last_msg_.states[73].mesid.code, expected 20, is " << last_msg_.states[73].mesid.code; EXPECT_EQ(last_msg_.states[73].mesid.sat, 5) << "incorrect value for last_msg_.states[73].mesid.sat, expected 5, is " << last_msg_.states[73].mesid.sat; EXPECT_EQ(last_msg_.states[74].cn0, 217) << "incorrect value for last_msg_.states[74].cn0, expected 217, is " << last_msg_.states[74].cn0; EXPECT_EQ(last_msg_.states[74].mesid.code, 20) << "incorrect value for last_msg_.states[74].mesid.code, expected 20, is " << last_msg_.states[74].mesid.code; EXPECT_EQ(last_msg_.states[74].mesid.sat, 36) << "incorrect value for last_msg_.states[74].mesid.sat, expected 36, is " << last_msg_.states[74].mesid.sat; EXPECT_EQ(last_msg_.states[75].cn0, 200) << "incorrect value for last_msg_.states[75].cn0, expected 200, is " << last_msg_.states[75].cn0; EXPECT_EQ(last_msg_.states[75].mesid.code, 20) << "incorrect value for last_msg_.states[75].mesid.code, expected 20, is " << last_msg_.states[75].mesid.code; EXPECT_EQ(last_msg_.states[75].mesid.sat, 11) << "incorrect value for last_msg_.states[75].mesid.sat, expected 11, is " << last_msg_.states[75].mesid.sat; EXPECT_EQ(last_msg_.states[76].cn0, 205) << "incorrect value for last_msg_.states[76].cn0, expected 205, is " << last_msg_.states[76].cn0; EXPECT_EQ(last_msg_.states[76].mesid.code, 20) << "incorrect value for last_msg_.states[76].mesid.code, expected 20, is " << last_msg_.states[76].mesid.code; EXPECT_EQ(last_msg_.states[76].mesid.sat, 4) << "incorrect value for last_msg_.states[76].mesid.sat, expected 4, is " << last_msg_.states[76].mesid.sat; EXPECT_EQ(last_msg_.states[77].cn0, 0) << "incorrect value for last_msg_.states[77].cn0, expected 0, is " << last_msg_.states[77].cn0; EXPECT_EQ(last_msg_.states[77].mesid.code, 0) << "incorrect value for last_msg_.states[77].mesid.code, expected 0, is " << last_msg_.states[77].mesid.code; EXPECT_EQ(last_msg_.states[77].mesid.sat, 0) << "incorrect value for last_msg_.states[77].mesid.sat, expected 0, is " << last_msg_.states[77].mesid.sat; EXPECT_EQ(last_msg_.states[78].cn0, 0) << "incorrect value for last_msg_.states[78].cn0, expected 0, is " << last_msg_.states[78].cn0; EXPECT_EQ(last_msg_.states[78].mesid.code, 0) << "incorrect value for last_msg_.states[78].mesid.code, expected 0, is " << last_msg_.states[78].mesid.code; EXPECT_EQ(last_msg_.states[78].mesid.sat, 0) << "incorrect value for last_msg_.states[78].mesid.sat, expected 0, is " << last_msg_.states[78].mesid.sat; }
44.838287
80
0.666673
Patrick-Luo-THR
302a65d5a1b2de8810875e5cf049bac9efdda89e
1,680
cpp
C++
S3DWrapper10/Commands/DsSetShaderWithIfaces11_0.cpp
bo3b/iZ3D
ced8b3a4b0a152d0177f2e94008918efc76935d5
[ "MIT" ]
27
2020-11-12T19:24:54.000Z
2022-03-27T23:10:45.000Z
S3DWrapper10/Commands/DsSetShaderWithIfaces11_0.cpp
bo3b/iZ3D
ced8b3a4b0a152d0177f2e94008918efc76935d5
[ "MIT" ]
2
2020-11-02T06:30:39.000Z
2022-02-23T18:39:55.000Z
S3DWrapper10/Commands/DsSetShaderWithIfaces11_0.cpp
bo3b/iZ3D
ced8b3a4b0a152d0177f2e94008918efc76935d5
[ "MIT" ]
3
2021-08-16T00:21:08.000Z
2022-02-23T19:19:36.000Z
#include "stdafx.h" #include "DsSetShaderWithIfaces11_0.h" #include "..\Streamer\CodeGenerator.h" #include "D3DDeviceWrapper.h" #include "ShaderWrapper.h" namespace Commands { void DsSetShaderWithIfaces11_0::UpdateDeviceState( D3DDeviceWrapper *pWrapper, D3DDeviceState* pState ) { pState->DS.m_Shader = this; pState->DS.m_IsStereoShader = false; if (hShader_.pDrvPrivate) { ShaderWrapper* pDSWrp = NULL; InitWrapper(hShader_, pDSWrp); if ( pDSWrp->IsMatrixFounded() ) pState->DS.m_IsStereoShader = true; } } void DsSetShaderWithIfaces11_0::Execute( D3DDeviceWrapper *pWrapper ) { BEFORE_EXECUTE(this); pWrapper->OriginalDeviceFuncs11.pfnDsSetShaderWithIfaces( pWrapper->hDevice, GET_SHADER_HANDLE(hShader_), NumClassInstances_, GetPointerToVector(pIfaces_), GetPointerToVector(pPointerData_) ); AFTER_EXECUTE(this); } bool DsSetShaderWithIfaces11_0::WriteToFile( D3DDeviceWrapper *pWrapper ) const { return WriteToFileEx(pWrapper, "DsSetShaderWithIfaces11_0"); } } VOID ( APIENTRY DsSetShaderWithIfaces11_0 )( D3D10DDI_HDEVICE hDevice, D3D10DDI_HSHADER hShader, UINT NumClassInstances, const UINT* pIfaces, const D3D11DDIARG_POINTERDATA* pPointerData ) { _ASSERT(D3D10_GET_WRAPPER()->GetD3DVersion() >= TD3DVersion_11_0); #ifndef EXECUTE_IMMEDIATELY_G1 Commands::DsSetShaderWithIfaces11_0* command = new Commands::DsSetShaderWithIfaces11_0(hShader, NumClassInstances, pIfaces, pPointerData); D3D10_GET_WRAPPER()->AddCommand(command); #else { THREAD_GUARD_D3D10(); D3D11_GET_ORIG().pfnDsSetShaderWithIfaces( D3D10_DEVICE, GET_SHADER_HANDLE( hShader ), NumClassInstances, pIfaces, pPointerData ); } #endif }
31.698113
107
0.780952
bo3b
302aac1280b7be982666485af5edd0c478eac7cd
57,052
cpp
C++
frameworks/compile/slang/slang_rs_object_ref_count.cpp
touxiong88/92_mediatek
5e96a7bb778fd9d9b335825584664e0c8b5ff2c7
[ "Apache-2.0" ]
1
2022-01-07T01:53:19.000Z
2022-01-07T01:53:19.000Z
frameworks/compile/slang/slang_rs_object_ref_count.cpp
touxiong88/92_mediatek
5e96a7bb778fd9d9b335825584664e0c8b5ff2c7
[ "Apache-2.0" ]
null
null
null
frameworks/compile/slang/slang_rs_object_ref_count.cpp
touxiong88/92_mediatek
5e96a7bb778fd9d9b335825584664e0c8b5ff2c7
[ "Apache-2.0" ]
1
2020-02-28T02:48:42.000Z
2020-02-28T02:48:42.000Z
/* * Copyright 2010, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "slang_rs_object_ref_count.h" #include <list> #include "clang/AST/DeclGroup.h" #include "clang/AST/Expr.h" #include "clang/AST/NestedNameSpecifier.h" #include "clang/AST/OperationKinds.h" #include "clang/AST/Stmt.h" #include "clang/AST/StmtVisitor.h" #include "slang_assert.h" #include "slang_rs.h" #include "slang_rs_ast_replace.h" #include "slang_rs_export_type.h" namespace slang { clang::FunctionDecl *RSObjectRefCount:: RSSetObjectFD[RSExportPrimitiveType::LastRSObjectType - RSExportPrimitiveType::FirstRSObjectType + 1]; clang::FunctionDecl *RSObjectRefCount:: RSClearObjectFD[RSExportPrimitiveType::LastRSObjectType - RSExportPrimitiveType::FirstRSObjectType + 1]; void RSObjectRefCount::GetRSRefCountingFunctions(clang::ASTContext &C) { for (unsigned i = 0; i < (sizeof(RSClearObjectFD) / sizeof(clang::FunctionDecl*)); i++) { RSSetObjectFD[i] = NULL; RSClearObjectFD[i] = NULL; } clang::TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl(); for (clang::DeclContext::decl_iterator I = TUDecl->decls_begin(), E = TUDecl->decls_end(); I != E; I++) { if ((I->getKind() >= clang::Decl::firstFunction) && (I->getKind() <= clang::Decl::lastFunction)) { clang::FunctionDecl *FD = static_cast<clang::FunctionDecl*>(*I); // points to RSSetObjectFD or RSClearObjectFD clang::FunctionDecl **RSObjectFD; if (FD->getName() == "rsSetObject") { slangAssert((FD->getNumParams() == 2) && "Invalid rsSetObject function prototype (# params)"); RSObjectFD = RSSetObjectFD; } else if (FD->getName() == "rsClearObject") { slangAssert((FD->getNumParams() == 1) && "Invalid rsClearObject function prototype (# params)"); RSObjectFD = RSClearObjectFD; } else { continue; } const clang::ParmVarDecl *PVD = FD->getParamDecl(0); clang::QualType PVT = PVD->getOriginalType(); // The first parameter must be a pointer like rs_allocation* slangAssert(PVT->isPointerType() && "Invalid rs{Set,Clear}Object function prototype (pointer param)"); // The rs object type passed to the FD clang::QualType RST = PVT->getPointeeType(); RSExportPrimitiveType::DataType DT = RSExportPrimitiveType::GetRSSpecificType(RST.getTypePtr()); slangAssert(RSExportPrimitiveType::IsRSObjectType(DT) && "must be RS object type"); RSObjectFD[(DT - RSExportPrimitiveType::FirstRSObjectType)] = FD; } } } namespace { // This function constructs a new CompoundStmt from the input StmtList. static clang::CompoundStmt* BuildCompoundStmt(clang::ASTContext &C, std::list<clang::Stmt*> &StmtList, clang::SourceLocation Loc) { unsigned NewStmtCount = StmtList.size(); unsigned CompoundStmtCount = 0; clang::Stmt **CompoundStmtList; CompoundStmtList = new clang::Stmt*[NewStmtCount]; std::list<clang::Stmt*>::const_iterator I = StmtList.begin(); std::list<clang::Stmt*>::const_iterator E = StmtList.end(); for ( ; I != E; I++) { CompoundStmtList[CompoundStmtCount++] = *I; } slangAssert(CompoundStmtCount == NewStmtCount); clang::CompoundStmt *CS = new(C) clang::CompoundStmt(C, llvm::makeArrayRef(CompoundStmtList, CompoundStmtCount), Loc, Loc); delete [] CompoundStmtList; return CS; } static void AppendAfterStmt(clang::ASTContext &C, clang::CompoundStmt *CS, clang::Stmt *S, std::list<clang::Stmt*> &StmtList) { slangAssert(CS); clang::CompoundStmt::body_iterator bI = CS->body_begin(); clang::CompoundStmt::body_iterator bE = CS->body_end(); clang::Stmt **UpdatedStmtList = new clang::Stmt*[CS->size() + StmtList.size()]; unsigned UpdatedStmtCount = 0; unsigned Once = 0; for ( ; bI != bE; bI++) { if (!S && ((*bI)->getStmtClass() == clang::Stmt::ReturnStmtClass)) { // If we come across a return here, we don't have anything we can // reasonably replace. We should have already inserted our destructor // code in the proper spot, so we just clean up and return. delete [] UpdatedStmtList; return; } UpdatedStmtList[UpdatedStmtCount++] = *bI; if ((*bI == S) && !Once) { Once++; std::list<clang::Stmt*>::const_iterator I = StmtList.begin(); std::list<clang::Stmt*>::const_iterator E = StmtList.end(); for ( ; I != E; I++) { UpdatedStmtList[UpdatedStmtCount++] = *I; } } } slangAssert(Once <= 1); // When S is NULL, we are appending to the end of the CompoundStmt. if (!S) { slangAssert(Once == 0); std::list<clang::Stmt*>::const_iterator I = StmtList.begin(); std::list<clang::Stmt*>::const_iterator E = StmtList.end(); for ( ; I != E; I++) { UpdatedStmtList[UpdatedStmtCount++] = *I; } } CS->setStmts(C, UpdatedStmtList, UpdatedStmtCount); delete [] UpdatedStmtList; return; } // This class visits a compound statement and inserts DtorStmt // in proper locations. This includes inserting it before any // return statement in any sub-block, at the end of the logical enclosing // scope (compound statement), and/or before any break/continue statement that // would resume outside the declared scope. We will not handle the case for // goto statements that leave a local scope. // // To accomplish these goals, it collects a list of sub-Stmt's that // correspond to scope exit points. It then uses an RSASTReplace visitor to // transform the AST, inserting appropriate destructors before each of those // sub-Stmt's (and also before the exit of the outermost containing Stmt for // the scope). class DestructorVisitor : public clang::StmtVisitor<DestructorVisitor> { private: clang::ASTContext &mCtx; // The loop depth of the currently visited node. int mLoopDepth; // The switch statement depth of the currently visited node. // Note that this is tracked separately from the loop depth because // SwitchStmt-contained ContinueStmt's should have destructors for the // corresponding loop scope. int mSwitchDepth; // The outermost statement block that we are currently visiting. // This should always be a CompoundStmt. clang::Stmt *mOuterStmt; // The destructor to execute for this scope/variable. clang::Stmt* mDtorStmt; // The stack of statements which should be replaced by a compound statement // containing the new destructor call followed by the original Stmt. std::stack<clang::Stmt*> mReplaceStmtStack; // The source location for the variable declaration that we are trying to // insert destructors for. Note that InsertDestructors() will not generate // destructor calls for source locations that occur lexically before this // location. clang::SourceLocation mVarLoc; public: DestructorVisitor(clang::ASTContext &C, clang::Stmt* OuterStmt, clang::Stmt* DtorStmt, clang::SourceLocation VarLoc); // This code walks the collected list of Stmts to replace and actually does // the replacement. It also finishes up by appending the destructor to the // current outermost CompoundStmt. void InsertDestructors() { clang::Stmt *S = NULL; clang::SourceManager &SM = mCtx.getSourceManager(); std::list<clang::Stmt *> StmtList; StmtList.push_back(mDtorStmt); while (!mReplaceStmtStack.empty()) { S = mReplaceStmtStack.top(); mReplaceStmtStack.pop(); // Skip all source locations that occur before the variable's // declaration, since it won't have been initialized yet. if (SM.isBeforeInTranslationUnit(S->getLocStart(), mVarLoc)) { continue; } StmtList.push_back(S); clang::CompoundStmt *CS = BuildCompoundStmt(mCtx, StmtList, S->getLocEnd()); StmtList.pop_back(); RSASTReplace R(mCtx); R.ReplaceStmt(mOuterStmt, S, CS); } clang::CompoundStmt *CS = llvm::dyn_cast<clang::CompoundStmt>(mOuterStmt); slangAssert(CS); AppendAfterStmt(mCtx, CS, NULL, StmtList); } void VisitStmt(clang::Stmt *S); void VisitCompoundStmt(clang::CompoundStmt *CS); void VisitBreakStmt(clang::BreakStmt *BS); void VisitCaseStmt(clang::CaseStmt *CS); void VisitContinueStmt(clang::ContinueStmt *CS); void VisitDefaultStmt(clang::DefaultStmt *DS); void VisitDoStmt(clang::DoStmt *DS); void VisitForStmt(clang::ForStmt *FS); void VisitIfStmt(clang::IfStmt *IS); void VisitReturnStmt(clang::ReturnStmt *RS); void VisitSwitchCase(clang::SwitchCase *SC); void VisitSwitchStmt(clang::SwitchStmt *SS); void VisitWhileStmt(clang::WhileStmt *WS); }; DestructorVisitor::DestructorVisitor(clang::ASTContext &C, clang::Stmt *OuterStmt, clang::Stmt *DtorStmt, clang::SourceLocation VarLoc) : mCtx(C), mLoopDepth(0), mSwitchDepth(0), mOuterStmt(OuterStmt), mDtorStmt(DtorStmt), mVarLoc(VarLoc) { return; } void DestructorVisitor::VisitStmt(clang::Stmt *S) { for (clang::Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I != E; I++) { if (clang::Stmt *Child = *I) { Visit(Child); } } return; } void DestructorVisitor::VisitCompoundStmt(clang::CompoundStmt *CS) { VisitStmt(CS); return; } void DestructorVisitor::VisitBreakStmt(clang::BreakStmt *BS) { VisitStmt(BS); if ((mLoopDepth == 0) && (mSwitchDepth == 0)) { mReplaceStmtStack.push(BS); } return; } void DestructorVisitor::VisitCaseStmt(clang::CaseStmt *CS) { VisitStmt(CS); return; } void DestructorVisitor::VisitContinueStmt(clang::ContinueStmt *CS) { VisitStmt(CS); if (mLoopDepth == 0) { // Switch statements can have nested continues. mReplaceStmtStack.push(CS); } return; } void DestructorVisitor::VisitDefaultStmt(clang::DefaultStmt *DS) { VisitStmt(DS); return; } void DestructorVisitor::VisitDoStmt(clang::DoStmt *DS) { mLoopDepth++; VisitStmt(DS); mLoopDepth--; return; } void DestructorVisitor::VisitForStmt(clang::ForStmt *FS) { mLoopDepth++; VisitStmt(FS); mLoopDepth--; return; } void DestructorVisitor::VisitIfStmt(clang::IfStmt *IS) { VisitStmt(IS); return; } void DestructorVisitor::VisitReturnStmt(clang::ReturnStmt *RS) { mReplaceStmtStack.push(RS); return; } void DestructorVisitor::VisitSwitchCase(clang::SwitchCase *SC) { slangAssert(false && "Both case and default have specialized handlers"); VisitStmt(SC); return; } void DestructorVisitor::VisitSwitchStmt(clang::SwitchStmt *SS) { mSwitchDepth++; VisitStmt(SS); mSwitchDepth--; return; } void DestructorVisitor::VisitWhileStmt(clang::WhileStmt *WS) { mLoopDepth++; VisitStmt(WS); mLoopDepth--; return; } clang::Expr *ClearSingleRSObject(clang::ASTContext &C, clang::Expr *RefRSVar, clang::SourceLocation Loc) { slangAssert(RefRSVar); const clang::Type *T = RefRSVar->getType().getTypePtr(); slangAssert(!T->isArrayType() && "Should not be destroying arrays with this function"); clang::FunctionDecl *ClearObjectFD = RSObjectRefCount::GetRSClearObjectFD(T); slangAssert((ClearObjectFD != NULL) && "rsClearObject doesn't cover all RS object types"); clang::QualType ClearObjectFDType = ClearObjectFD->getType(); clang::QualType ClearObjectFDArgType = ClearObjectFD->getParamDecl(0)->getOriginalType(); // Example destructor for "rs_font localFont;" // // (CallExpr 'void' // (ImplicitCastExpr 'void (*)(rs_font *)' <FunctionToPointerDecay> // (DeclRefExpr 'void (rs_font *)' FunctionDecl='rsClearObject')) // (UnaryOperator 'rs_font *' prefix '&' // (DeclRefExpr 'rs_font':'rs_font' Var='localFont'))) // Get address of targeted RS object clang::Expr *AddrRefRSVar = new(C) clang::UnaryOperator(RefRSVar, clang::UO_AddrOf, ClearObjectFDArgType, clang::VK_RValue, clang::OK_Ordinary, Loc); clang::Expr *RefRSClearObjectFD = clang::DeclRefExpr::Create(C, clang::NestedNameSpecifierLoc(), clang::SourceLocation(), ClearObjectFD, false, ClearObjectFD->getLocation(), ClearObjectFDType, clang::VK_RValue, NULL); clang::Expr *RSClearObjectFP = clang::ImplicitCastExpr::Create(C, C.getPointerType(ClearObjectFDType), clang::CK_FunctionToPointerDecay, RefRSClearObjectFD, NULL, clang::VK_RValue); llvm::SmallVector<clang::Expr*, 1> ArgList; ArgList.push_back(AddrRefRSVar); clang::CallExpr *RSClearObjectCall = new(C) clang::CallExpr(C, RSClearObjectFP, ArgList, ClearObjectFD->getCallResultType(), clang::VK_RValue, Loc); return RSClearObjectCall; } static int ArrayDim(const clang::Type *T) { if (!T || !T->isArrayType()) { return 0; } const clang::ConstantArrayType *CAT = static_cast<const clang::ConstantArrayType *>(T); return static_cast<int>(CAT->getSize().getSExtValue()); } static clang::Stmt *ClearStructRSObject( clang::ASTContext &C, clang::DeclContext *DC, clang::Expr *RefRSStruct, clang::SourceLocation StartLoc, clang::SourceLocation Loc); static clang::Stmt *ClearArrayRSObject( clang::ASTContext &C, clang::DeclContext *DC, clang::Expr *RefRSArr, clang::SourceLocation StartLoc, clang::SourceLocation Loc) { const clang::Type *BaseType = RefRSArr->getType().getTypePtr(); slangAssert(BaseType->isArrayType()); int NumArrayElements = ArrayDim(BaseType); // Actually extract out the base RS object type for use later BaseType = BaseType->getArrayElementTypeNoTypeQual(); clang::Stmt *StmtArray[2] = {NULL}; int StmtCtr = 0; if (NumArrayElements <= 0) { return NULL; } // Example destructor loop for "rs_font fontArr[10];" // // (CompoundStmt // (DeclStmt "int rsIntIter") // (ForStmt // (BinaryOperator 'int' '=' // (DeclRefExpr 'int' Var='rsIntIter') // (IntegerLiteral 'int' 0)) // (BinaryOperator 'int' '<' // (DeclRefExpr 'int' Var='rsIntIter') // (IntegerLiteral 'int' 10) // NULL << CondVar >> // (UnaryOperator 'int' postfix '++' // (DeclRefExpr 'int' Var='rsIntIter')) // (CallExpr 'void' // (ImplicitCastExpr 'void (*)(rs_font *)' <FunctionToPointerDecay> // (DeclRefExpr 'void (rs_font *)' FunctionDecl='rsClearObject')) // (UnaryOperator 'rs_font *' prefix '&' // (ArraySubscriptExpr 'rs_font':'rs_font' // (ImplicitCastExpr 'rs_font *' <ArrayToPointerDecay> // (DeclRefExpr 'rs_font [10]' Var='fontArr')) // (DeclRefExpr 'int' Var='rsIntIter'))))))) // Create helper variable for iterating through elements clang::IdentifierInfo& II = C.Idents.get("rsIntIter"); clang::VarDecl *IIVD = clang::VarDecl::Create(C, DC, StartLoc, Loc, &II, C.IntTy, C.getTrivialTypeSourceInfo(C.IntTy), clang::SC_None); clang::Decl *IID = (clang::Decl *)IIVD; clang::DeclGroupRef DGR = clang::DeclGroupRef::Create(C, &IID, 1); StmtArray[StmtCtr++] = new(C) clang::DeclStmt(DGR, Loc, Loc); // Form the actual destructor loop // for (Init; Cond; Inc) // RSClearObjectCall; // Init -> "rsIntIter = 0" clang::DeclRefExpr *RefrsIntIter = clang::DeclRefExpr::Create(C, clang::NestedNameSpecifierLoc(), clang::SourceLocation(), IIVD, false, Loc, C.IntTy, clang::VK_RValue, NULL); clang::Expr *Int0 = clang::IntegerLiteral::Create(C, llvm::APInt(C.getTypeSize(C.IntTy), 0), C.IntTy, Loc); clang::BinaryOperator *Init = new(C) clang::BinaryOperator(RefrsIntIter, Int0, clang::BO_Assign, C.IntTy, clang::VK_RValue, clang::OK_Ordinary, Loc, /* fpContractable */false); // Cond -> "rsIntIter < NumArrayElements" clang::Expr *NumArrayElementsExpr = clang::IntegerLiteral::Create(C, llvm::APInt(C.getTypeSize(C.IntTy), NumArrayElements), C.IntTy, Loc); clang::BinaryOperator *Cond = new(C) clang::BinaryOperator(RefrsIntIter, NumArrayElementsExpr, clang::BO_LT, C.IntTy, clang::VK_RValue, clang::OK_Ordinary, Loc, /* fpContractable */false); // Inc -> "rsIntIter++" clang::UnaryOperator *Inc = new(C) clang::UnaryOperator(RefrsIntIter, clang::UO_PostInc, C.IntTy, clang::VK_RValue, clang::OK_Ordinary, Loc); // Body -> "rsClearObject(&VD[rsIntIter]);" // Destructor loop operates on individual array elements clang::Expr *RefRSArrPtr = clang::ImplicitCastExpr::Create(C, C.getPointerType(BaseType->getCanonicalTypeInternal()), clang::CK_ArrayToPointerDecay, RefRSArr, NULL, clang::VK_RValue); clang::Expr *RefRSArrPtrSubscript = new(C) clang::ArraySubscriptExpr(RefRSArrPtr, RefrsIntIter, BaseType->getCanonicalTypeInternal(), clang::VK_RValue, clang::OK_Ordinary, Loc); RSExportPrimitiveType::DataType DT = RSExportPrimitiveType::GetRSSpecificType(BaseType); clang::Stmt *RSClearObjectCall = NULL; if (BaseType->isArrayType()) { RSClearObjectCall = ClearArrayRSObject(C, DC, RefRSArrPtrSubscript, StartLoc, Loc); } else if (DT == RSExportPrimitiveType::DataTypeUnknown) { RSClearObjectCall = ClearStructRSObject(C, DC, RefRSArrPtrSubscript, StartLoc, Loc); } else { RSClearObjectCall = ClearSingleRSObject(C, RefRSArrPtrSubscript, Loc); } clang::ForStmt *DestructorLoop = new(C) clang::ForStmt(C, Init, Cond, NULL, // no condVar Inc, RSClearObjectCall, Loc, Loc, Loc); StmtArray[StmtCtr++] = DestructorLoop; slangAssert(StmtCtr == 2); clang::CompoundStmt *CS = new(C) clang::CompoundStmt(C, StmtArray, Loc, Loc); return CS; } static unsigned CountRSObjectTypes(clang::ASTContext &C, const clang::Type *T, clang::SourceLocation Loc) { slangAssert(T); unsigned RSObjectCount = 0; if (T->isArrayType()) { return CountRSObjectTypes(C, T->getArrayElementTypeNoTypeQual(), Loc); } RSExportPrimitiveType::DataType DT = RSExportPrimitiveType::GetRSSpecificType(T); if (DT != RSExportPrimitiveType::DataTypeUnknown) { return (RSExportPrimitiveType::IsRSObjectType(DT) ? 1 : 0); } if (T->isUnionType()) { clang::RecordDecl *RD = T->getAsUnionType()->getDecl(); RD = RD->getDefinition(); for (clang::RecordDecl::field_iterator FI = RD->field_begin(), FE = RD->field_end(); FI != FE; FI++) { const clang::FieldDecl *FD = *FI; const clang::Type *FT = RSExportType::GetTypeOfDecl(FD); if (CountRSObjectTypes(C, FT, Loc)) { slangAssert(false && "can't have unions with RS object types!"); return 0; } } } if (!T->isStructureType()) { return 0; } clang::RecordDecl *RD = T->getAsStructureType()->getDecl(); RD = RD->getDefinition(); for (clang::RecordDecl::field_iterator FI = RD->field_begin(), FE = RD->field_end(); FI != FE; FI++) { const clang::FieldDecl *FD = *FI; const clang::Type *FT = RSExportType::GetTypeOfDecl(FD); if (CountRSObjectTypes(C, FT, Loc)) { // Sub-structs should only count once (as should arrays, etc.) RSObjectCount++; } } return RSObjectCount; } static clang::Stmt *ClearStructRSObject( clang::ASTContext &C, clang::DeclContext *DC, clang::Expr *RefRSStruct, clang::SourceLocation StartLoc, clang::SourceLocation Loc) { const clang::Type *BaseType = RefRSStruct->getType().getTypePtr(); slangAssert(!BaseType->isArrayType()); // Structs should show up as unknown primitive types slangAssert(RSExportPrimitiveType::GetRSSpecificType(BaseType) == RSExportPrimitiveType::DataTypeUnknown); unsigned FieldsToDestroy = CountRSObjectTypes(C, BaseType, Loc); unsigned StmtCount = 0; clang::Stmt **StmtArray = new clang::Stmt*[FieldsToDestroy]; for (unsigned i = 0; i < FieldsToDestroy; i++) { StmtArray[i] = NULL; } // Populate StmtArray by creating a destructor for each RS object field clang::RecordDecl *RD = BaseType->getAsStructureType()->getDecl(); RD = RD->getDefinition(); for (clang::RecordDecl::field_iterator FI = RD->field_begin(), FE = RD->field_end(); FI != FE; FI++) { // We just look through all field declarations to see if we find a // declaration for an RS object type (or an array of one). bool IsArrayType = false; clang::FieldDecl *FD = *FI; const clang::Type *FT = RSExportType::GetTypeOfDecl(FD); const clang::Type *OrigType = FT; while (FT && FT->isArrayType()) { FT = FT->getArrayElementTypeNoTypeQual(); IsArrayType = true; } if (RSExportPrimitiveType::IsRSObjectType(FT)) { clang::DeclAccessPair FoundDecl = clang::DeclAccessPair::make(FD, clang::AS_none); clang::MemberExpr *RSObjectMember = clang::MemberExpr::Create(C, RefRSStruct, false, clang::NestedNameSpecifierLoc(), clang::SourceLocation(), FD, FoundDecl, clang::DeclarationNameInfo(), NULL, OrigType->getCanonicalTypeInternal(), clang::VK_RValue, clang::OK_Ordinary); slangAssert(StmtCount < FieldsToDestroy); if (IsArrayType) { StmtArray[StmtCount++] = ClearArrayRSObject(C, DC, RSObjectMember, StartLoc, Loc); } else { StmtArray[StmtCount++] = ClearSingleRSObject(C, RSObjectMember, Loc); } } else if (FT->isStructureType() && CountRSObjectTypes(C, FT, Loc)) { // In this case, we have a nested struct. We may not end up filling all // of the spaces in StmtArray (sub-structs should handle themselves // with separate compound statements). clang::DeclAccessPair FoundDecl = clang::DeclAccessPair::make(FD, clang::AS_none); clang::MemberExpr *RSObjectMember = clang::MemberExpr::Create(C, RefRSStruct, false, clang::NestedNameSpecifierLoc(), clang::SourceLocation(), FD, FoundDecl, clang::DeclarationNameInfo(), NULL, OrigType->getCanonicalTypeInternal(), clang::VK_RValue, clang::OK_Ordinary); if (IsArrayType) { StmtArray[StmtCount++] = ClearArrayRSObject(C, DC, RSObjectMember, StartLoc, Loc); } else { StmtArray[StmtCount++] = ClearStructRSObject(C, DC, RSObjectMember, StartLoc, Loc); } } } slangAssert(StmtCount > 0); clang::CompoundStmt *CS = new(C) clang::CompoundStmt(C, llvm::makeArrayRef(StmtArray, StmtCount), Loc, Loc); delete [] StmtArray; return CS; } static clang::Stmt *CreateSingleRSSetObject(clang::ASTContext &C, clang::Expr *DstExpr, clang::Expr *SrcExpr, clang::SourceLocation StartLoc, clang::SourceLocation Loc) { const clang::Type *T = DstExpr->getType().getTypePtr(); clang::FunctionDecl *SetObjectFD = RSObjectRefCount::GetRSSetObjectFD(T); slangAssert((SetObjectFD != NULL) && "rsSetObject doesn't cover all RS object types"); clang::QualType SetObjectFDType = SetObjectFD->getType(); clang::QualType SetObjectFDArgType[2]; SetObjectFDArgType[0] = SetObjectFD->getParamDecl(0)->getOriginalType(); SetObjectFDArgType[1] = SetObjectFD->getParamDecl(1)->getOriginalType(); clang::Expr *RefRSSetObjectFD = clang::DeclRefExpr::Create(C, clang::NestedNameSpecifierLoc(), clang::SourceLocation(), SetObjectFD, false, Loc, SetObjectFDType, clang::VK_RValue, NULL); clang::Expr *RSSetObjectFP = clang::ImplicitCastExpr::Create(C, C.getPointerType(SetObjectFDType), clang::CK_FunctionToPointerDecay, RefRSSetObjectFD, NULL, clang::VK_RValue); llvm::SmallVector<clang::Expr*, 2> ArgList; ArgList.push_back(new(C) clang::UnaryOperator(DstExpr, clang::UO_AddrOf, SetObjectFDArgType[0], clang::VK_RValue, clang::OK_Ordinary, Loc)); ArgList.push_back(SrcExpr); clang::CallExpr *RSSetObjectCall = new(C) clang::CallExpr(C, RSSetObjectFP, ArgList, SetObjectFD->getCallResultType(), clang::VK_RValue, Loc); return RSSetObjectCall; } static clang::Stmt *CreateStructRSSetObject(clang::ASTContext &C, clang::Expr *LHS, clang::Expr *RHS, clang::SourceLocation StartLoc, clang::SourceLocation Loc); /*static clang::Stmt *CreateArrayRSSetObject(clang::ASTContext &C, clang::Expr *DstArr, clang::Expr *SrcArr, clang::SourceLocation StartLoc, clang::SourceLocation Loc) { clang::DeclContext *DC = NULL; const clang::Type *BaseType = DstArr->getType().getTypePtr(); slangAssert(BaseType->isArrayType()); int NumArrayElements = ArrayDim(BaseType); // Actually extract out the base RS object type for use later BaseType = BaseType->getArrayElementTypeNoTypeQual(); clang::Stmt *StmtArray[2] = {NULL}; int StmtCtr = 0; if (NumArrayElements <= 0) { return NULL; } // Create helper variable for iterating through elements clang::IdentifierInfo& II = C.Idents.get("rsIntIter"); clang::VarDecl *IIVD = clang::VarDecl::Create(C, DC, StartLoc, Loc, &II, C.IntTy, C.getTrivialTypeSourceInfo(C.IntTy), clang::SC_None, clang::SC_None); clang::Decl *IID = (clang::Decl *)IIVD; clang::DeclGroupRef DGR = clang::DeclGroupRef::Create(C, &IID, 1); StmtArray[StmtCtr++] = new(C) clang::DeclStmt(DGR, Loc, Loc); // Form the actual loop // for (Init; Cond; Inc) // RSSetObjectCall; // Init -> "rsIntIter = 0" clang::DeclRefExpr *RefrsIntIter = clang::DeclRefExpr::Create(C, clang::NestedNameSpecifierLoc(), IIVD, Loc, C.IntTy, clang::VK_RValue, NULL); clang::Expr *Int0 = clang::IntegerLiteral::Create(C, llvm::APInt(C.getTypeSize(C.IntTy), 0), C.IntTy, Loc); clang::BinaryOperator *Init = new(C) clang::BinaryOperator(RefrsIntIter, Int0, clang::BO_Assign, C.IntTy, clang::VK_RValue, clang::OK_Ordinary, Loc); // Cond -> "rsIntIter < NumArrayElements" clang::Expr *NumArrayElementsExpr = clang::IntegerLiteral::Create(C, llvm::APInt(C.getTypeSize(C.IntTy), NumArrayElements), C.IntTy, Loc); clang::BinaryOperator *Cond = new(C) clang::BinaryOperator(RefrsIntIter, NumArrayElementsExpr, clang::BO_LT, C.IntTy, clang::VK_RValue, clang::OK_Ordinary, Loc); // Inc -> "rsIntIter++" clang::UnaryOperator *Inc = new(C) clang::UnaryOperator(RefrsIntIter, clang::UO_PostInc, C.IntTy, clang::VK_RValue, clang::OK_Ordinary, Loc); // Body -> "rsSetObject(&Dst[rsIntIter], Src[rsIntIter]);" // Loop operates on individual array elements clang::Expr *DstArrPtr = clang::ImplicitCastExpr::Create(C, C.getPointerType(BaseType->getCanonicalTypeInternal()), clang::CK_ArrayToPointerDecay, DstArr, NULL, clang::VK_RValue); clang::Expr *DstArrPtrSubscript = new(C) clang::ArraySubscriptExpr(DstArrPtr, RefrsIntIter, BaseType->getCanonicalTypeInternal(), clang::VK_RValue, clang::OK_Ordinary, Loc); clang::Expr *SrcArrPtr = clang::ImplicitCastExpr::Create(C, C.getPointerType(BaseType->getCanonicalTypeInternal()), clang::CK_ArrayToPointerDecay, SrcArr, NULL, clang::VK_RValue); clang::Expr *SrcArrPtrSubscript = new(C) clang::ArraySubscriptExpr(SrcArrPtr, RefrsIntIter, BaseType->getCanonicalTypeInternal(), clang::VK_RValue, clang::OK_Ordinary, Loc); RSExportPrimitiveType::DataType DT = RSExportPrimitiveType::GetRSSpecificType(BaseType); clang::Stmt *RSSetObjectCall = NULL; if (BaseType->isArrayType()) { RSSetObjectCall = CreateArrayRSSetObject(C, DstArrPtrSubscript, SrcArrPtrSubscript, StartLoc, Loc); } else if (DT == RSExportPrimitiveType::DataTypeUnknown) { RSSetObjectCall = CreateStructRSSetObject(C, DstArrPtrSubscript, SrcArrPtrSubscript, StartLoc, Loc); } else { RSSetObjectCall = CreateSingleRSSetObject(C, DstArrPtrSubscript, SrcArrPtrSubscript, StartLoc, Loc); } clang::ForStmt *DestructorLoop = new(C) clang::ForStmt(C, Init, Cond, NULL, // no condVar Inc, RSSetObjectCall, Loc, Loc, Loc); StmtArray[StmtCtr++] = DestructorLoop; slangAssert(StmtCtr == 2); clang::CompoundStmt *CS = new(C) clang::CompoundStmt(C, StmtArray, StmtCtr, Loc, Loc); return CS; } */ static clang::Stmt *CreateStructRSSetObject(clang::ASTContext &C, clang::Expr *LHS, clang::Expr *RHS, clang::SourceLocation StartLoc, clang::SourceLocation Loc) { clang::QualType QT = LHS->getType(); const clang::Type *T = QT.getTypePtr(); slangAssert(T->isStructureType()); slangAssert(!RSExportPrimitiveType::IsRSObjectType(T)); // Keep an extra slot for the original copy (memcpy) unsigned FieldsToSet = CountRSObjectTypes(C, T, Loc) + 1; unsigned StmtCount = 0; clang::Stmt **StmtArray = new clang::Stmt*[FieldsToSet]; for (unsigned i = 0; i < FieldsToSet; i++) { StmtArray[i] = NULL; } clang::RecordDecl *RD = T->getAsStructureType()->getDecl(); RD = RD->getDefinition(); for (clang::RecordDecl::field_iterator FI = RD->field_begin(), FE = RD->field_end(); FI != FE; FI++) { bool IsArrayType = false; clang::FieldDecl *FD = *FI; const clang::Type *FT = RSExportType::GetTypeOfDecl(FD); const clang::Type *OrigType = FT; if (!CountRSObjectTypes(C, FT, Loc)) { // Skip to next if we don't have any viable RS object types continue; } clang::DeclAccessPair FoundDecl = clang::DeclAccessPair::make(FD, clang::AS_none); clang::MemberExpr *DstMember = clang::MemberExpr::Create(C, LHS, false, clang::NestedNameSpecifierLoc(), clang::SourceLocation(), FD, FoundDecl, clang::DeclarationNameInfo(), NULL, OrigType->getCanonicalTypeInternal(), clang::VK_RValue, clang::OK_Ordinary); clang::MemberExpr *SrcMember = clang::MemberExpr::Create(C, RHS, false, clang::NestedNameSpecifierLoc(), clang::SourceLocation(), FD, FoundDecl, clang::DeclarationNameInfo(), NULL, OrigType->getCanonicalTypeInternal(), clang::VK_RValue, clang::OK_Ordinary); if (FT->isArrayType()) { FT = FT->getArrayElementTypeNoTypeQual(); IsArrayType = true; } RSExportPrimitiveType::DataType DT = RSExportPrimitiveType::GetRSSpecificType(FT); if (IsArrayType) { clang::DiagnosticsEngine &DiagEngine = C.getDiagnostics(); DiagEngine.Report( clang::FullSourceLoc(Loc, C.getSourceManager()), DiagEngine.getCustomDiagID( clang::DiagnosticsEngine::Error, "Arrays of RS object types within structures cannot be copied")); // TODO(srhines): Support setting arrays of RS objects // StmtArray[StmtCount++] = // CreateArrayRSSetObject(C, DstMember, SrcMember, StartLoc, Loc); } else if (DT == RSExportPrimitiveType::DataTypeUnknown) { StmtArray[StmtCount++] = CreateStructRSSetObject(C, DstMember, SrcMember, StartLoc, Loc); } else if (RSExportPrimitiveType::IsRSObjectType(DT)) { StmtArray[StmtCount++] = CreateSingleRSSetObject(C, DstMember, SrcMember, StartLoc, Loc); } else { slangAssert(false); } } slangAssert(StmtCount > 0 && StmtCount < FieldsToSet); // We still need to actually do the overall struct copy. For simplicity, // we just do a straight-up assignment (which will still preserve all // the proper RS object reference counts). clang::BinaryOperator *CopyStruct = new(C) clang::BinaryOperator(LHS, RHS, clang::BO_Assign, QT, clang::VK_RValue, clang::OK_Ordinary, Loc, /* fpContractable */false); StmtArray[StmtCount++] = CopyStruct; clang::CompoundStmt *CS = new(C) clang::CompoundStmt(C, llvm::makeArrayRef(StmtArray, StmtCount), Loc, Loc); delete [] StmtArray; return CS; } } // namespace void RSObjectRefCount::Scope::ReplaceRSObjectAssignment( clang::BinaryOperator *AS) { clang::QualType QT = AS->getType(); clang::ASTContext &C = RSObjectRefCount::GetRSSetObjectFD( RSExportPrimitiveType::DataTypeRSFont)->getASTContext(); clang::SourceLocation Loc = AS->getExprLoc(); clang::SourceLocation StartLoc = AS->getLHS()->getExprLoc(); clang::Stmt *UpdatedStmt = NULL; if (!RSExportPrimitiveType::IsRSObjectType(QT.getTypePtr())) { // By definition, this is a struct assignment if we get here UpdatedStmt = CreateStructRSSetObject(C, AS->getLHS(), AS->getRHS(), StartLoc, Loc); } else { UpdatedStmt = CreateSingleRSSetObject(C, AS->getLHS(), AS->getRHS(), StartLoc, Loc); } RSASTReplace R(C); R.ReplaceStmt(mCS, AS, UpdatedStmt); return; } void RSObjectRefCount::Scope::AppendRSObjectInit( clang::VarDecl *VD, clang::DeclStmt *DS, RSExportPrimitiveType::DataType DT, clang::Expr *InitExpr) { slangAssert(VD); if (!InitExpr) { return; } clang::ASTContext &C = RSObjectRefCount::GetRSSetObjectFD( RSExportPrimitiveType::DataTypeRSFont)->getASTContext(); clang::SourceLocation Loc = RSObjectRefCount::GetRSSetObjectFD( RSExportPrimitiveType::DataTypeRSFont)->getLocation(); clang::SourceLocation StartLoc = RSObjectRefCount::GetRSSetObjectFD( RSExportPrimitiveType::DataTypeRSFont)->getInnerLocStart(); if (DT == RSExportPrimitiveType::DataTypeIsStruct) { const clang::Type *T = RSExportType::GetTypeOfDecl(VD); clang::DeclRefExpr *RefRSVar = clang::DeclRefExpr::Create(C, clang::NestedNameSpecifierLoc(), clang::SourceLocation(), VD, false, Loc, T->getCanonicalTypeInternal(), clang::VK_RValue, NULL); clang::Stmt *RSSetObjectOps = CreateStructRSSetObject(C, RefRSVar, InitExpr, StartLoc, Loc); std::list<clang::Stmt*> StmtList; StmtList.push_back(RSSetObjectOps); AppendAfterStmt(C, mCS, DS, StmtList); return; } clang::FunctionDecl *SetObjectFD = RSObjectRefCount::GetRSSetObjectFD(DT); slangAssert((SetObjectFD != NULL) && "rsSetObject doesn't cover all RS object types"); clang::QualType SetObjectFDType = SetObjectFD->getType(); clang::QualType SetObjectFDArgType[2]; SetObjectFDArgType[0] = SetObjectFD->getParamDecl(0)->getOriginalType(); SetObjectFDArgType[1] = SetObjectFD->getParamDecl(1)->getOriginalType(); clang::Expr *RefRSSetObjectFD = clang::DeclRefExpr::Create(C, clang::NestedNameSpecifierLoc(), clang::SourceLocation(), SetObjectFD, false, Loc, SetObjectFDType, clang::VK_RValue, NULL); clang::Expr *RSSetObjectFP = clang::ImplicitCastExpr::Create(C, C.getPointerType(SetObjectFDType), clang::CK_FunctionToPointerDecay, RefRSSetObjectFD, NULL, clang::VK_RValue); const clang::Type *T = RSExportType::GetTypeOfDecl(VD); clang::DeclRefExpr *RefRSVar = clang::DeclRefExpr::Create(C, clang::NestedNameSpecifierLoc(), clang::SourceLocation(), VD, false, Loc, T->getCanonicalTypeInternal(), clang::VK_RValue, NULL); llvm::SmallVector<clang::Expr*, 2> ArgList; ArgList.push_back(new(C) clang::UnaryOperator(RefRSVar, clang::UO_AddrOf, SetObjectFDArgType[0], clang::VK_RValue, clang::OK_Ordinary, Loc)); ArgList.push_back(InitExpr); clang::CallExpr *RSSetObjectCall = new(C) clang::CallExpr(C, RSSetObjectFP, ArgList, SetObjectFD->getCallResultType(), clang::VK_RValue, Loc); std::list<clang::Stmt*> StmtList; StmtList.push_back(RSSetObjectCall); AppendAfterStmt(C, mCS, DS, StmtList); return; } void RSObjectRefCount::Scope::InsertLocalVarDestructors() { for (std::list<clang::VarDecl*>::const_iterator I = mRSO.begin(), E = mRSO.end(); I != E; I++) { clang::VarDecl *VD = *I; clang::Stmt *RSClearObjectCall = ClearRSObject(VD, VD->getDeclContext()); if (RSClearObjectCall) { DestructorVisitor DV((*mRSO.begin())->getASTContext(), mCS, RSClearObjectCall, VD->getSourceRange().getBegin()); DV.Visit(mCS); DV.InsertDestructors(); } } return; } clang::Stmt *RSObjectRefCount::Scope::ClearRSObject( clang::VarDecl *VD, clang::DeclContext *DC) { slangAssert(VD); clang::ASTContext &C = VD->getASTContext(); clang::SourceLocation Loc = VD->getLocation(); clang::SourceLocation StartLoc = VD->getInnerLocStart(); const clang::Type *T = RSExportType::GetTypeOfDecl(VD); // Reference expr to target RS object variable clang::DeclRefExpr *RefRSVar = clang::DeclRefExpr::Create(C, clang::NestedNameSpecifierLoc(), clang::SourceLocation(), VD, false, Loc, T->getCanonicalTypeInternal(), clang::VK_RValue, NULL); if (T->isArrayType()) { return ClearArrayRSObject(C, DC, RefRSVar, StartLoc, Loc); } RSExportPrimitiveType::DataType DT = RSExportPrimitiveType::GetRSSpecificType(T); if (DT == RSExportPrimitiveType::DataTypeUnknown || DT == RSExportPrimitiveType::DataTypeIsStruct) { return ClearStructRSObject(C, DC, RefRSVar, StartLoc, Loc); } slangAssert((RSExportPrimitiveType::IsRSObjectType(DT)) && "Should be RS object"); return ClearSingleRSObject(C, RefRSVar, Loc); } bool RSObjectRefCount::InitializeRSObject(clang::VarDecl *VD, RSExportPrimitiveType::DataType *DT, clang::Expr **InitExpr) { slangAssert(VD && DT && InitExpr); const clang::Type *T = RSExportType::GetTypeOfDecl(VD); // Loop through array types to get to base type while (T && T->isArrayType()) { T = T->getArrayElementTypeNoTypeQual(); } bool DataTypeIsStructWithRSObject = false; *DT = RSExportPrimitiveType::GetRSSpecificType(T); if (*DT == RSExportPrimitiveType::DataTypeUnknown) { if (RSExportPrimitiveType::IsStructureTypeWithRSObject(T)) { *DT = RSExportPrimitiveType::DataTypeIsStruct; DataTypeIsStructWithRSObject = true; } else { return false; } } bool DataTypeIsRSObject = false; if (DataTypeIsStructWithRSObject) { DataTypeIsRSObject = true; } else { DataTypeIsRSObject = RSExportPrimitiveType::IsRSObjectType(*DT); } *InitExpr = VD->getInit(); if (!DataTypeIsRSObject && *InitExpr) { // If we already have an initializer for a matrix type, we are done. return DataTypeIsRSObject; } clang::Expr *ZeroInitializer = CreateZeroInitializerForRSSpecificType(*DT, VD->getASTContext(), VD->getLocation()); if (ZeroInitializer) { ZeroInitializer->setType(T->getCanonicalTypeInternal()); VD->setInit(ZeroInitializer); } return DataTypeIsRSObject; } clang::Expr *RSObjectRefCount::CreateZeroInitializerForRSSpecificType( RSExportPrimitiveType::DataType DT, clang::ASTContext &C, const clang::SourceLocation &Loc) { clang::Expr *Res = NULL; switch (DT) { case RSExportPrimitiveType::DataTypeIsStruct: case RSExportPrimitiveType::DataTypeRSElement: case RSExportPrimitiveType::DataTypeRSType: case RSExportPrimitiveType::DataTypeRSAllocation: case RSExportPrimitiveType::DataTypeRSSampler: case RSExportPrimitiveType::DataTypeRSScript: case RSExportPrimitiveType::DataTypeRSMesh: case RSExportPrimitiveType::DataTypeRSPath: case RSExportPrimitiveType::DataTypeRSProgramFragment: case RSExportPrimitiveType::DataTypeRSProgramVertex: case RSExportPrimitiveType::DataTypeRSProgramRaster: case RSExportPrimitiveType::DataTypeRSProgramStore: case RSExportPrimitiveType::DataTypeRSFont: { // (ImplicitCastExpr 'nullptr_t' // (IntegerLiteral 0))) llvm::APInt Zero(C.getTypeSize(C.IntTy), 0); clang::Expr *Int0 = clang::IntegerLiteral::Create(C, Zero, C.IntTy, Loc); clang::Expr *CastToNull = clang::ImplicitCastExpr::Create(C, C.NullPtrTy, clang::CK_IntegralToPointer, Int0, NULL, clang::VK_RValue); llvm::SmallVector<clang::Expr*, 1>InitList; InitList.push_back(CastToNull); Res = new(C) clang::InitListExpr(C, Loc, InitList, Loc); break; } case RSExportPrimitiveType::DataTypeRSMatrix2x2: case RSExportPrimitiveType::DataTypeRSMatrix3x3: case RSExportPrimitiveType::DataTypeRSMatrix4x4: { // RS matrix is not completely an RS object. They hold data by themselves. // (InitListExpr rs_matrix2x2 // (InitListExpr float[4] // (FloatingLiteral 0) // (FloatingLiteral 0) // (FloatingLiteral 0) // (FloatingLiteral 0))) clang::QualType FloatTy = C.FloatTy; // Constructor sets value to 0.0f by default llvm::APFloat Val(C.getFloatTypeSemantics(FloatTy)); clang::FloatingLiteral *Float0Val = clang::FloatingLiteral::Create(C, Val, /* isExact = */true, FloatTy, Loc); unsigned N = 0; if (DT == RSExportPrimitiveType::DataTypeRSMatrix2x2) N = 2; else if (DT == RSExportPrimitiveType::DataTypeRSMatrix3x3) N = 3; else if (DT == RSExportPrimitiveType::DataTypeRSMatrix4x4) N = 4; unsigned N_2 = N * N; // Assume we are going to be allocating 16 elements, since 4x4 is max. llvm::SmallVector<clang::Expr*, 16> InitVals; for (unsigned i = 0; i < N_2; i++) InitVals.push_back(Float0Val); clang::Expr *InitExpr = new(C) clang::InitListExpr(C, Loc, InitVals, Loc); InitExpr->setType(C.getConstantArrayType(FloatTy, llvm::APInt(32, N_2), clang::ArrayType::Normal, /* EltTypeQuals = */0)); llvm::SmallVector<clang::Expr*, 1> InitExprVec; InitExprVec.push_back(InitExpr); Res = new(C) clang::InitListExpr(C, Loc, InitExprVec, Loc); break; } case RSExportPrimitiveType::DataTypeUnknown: case RSExportPrimitiveType::DataTypeFloat16: case RSExportPrimitiveType::DataTypeFloat32: case RSExportPrimitiveType::DataTypeFloat64: case RSExportPrimitiveType::DataTypeSigned8: case RSExportPrimitiveType::DataTypeSigned16: case RSExportPrimitiveType::DataTypeSigned32: case RSExportPrimitiveType::DataTypeSigned64: case RSExportPrimitiveType::DataTypeUnsigned8: case RSExportPrimitiveType::DataTypeUnsigned16: case RSExportPrimitiveType::DataTypeUnsigned32: case RSExportPrimitiveType::DataTypeUnsigned64: case RSExportPrimitiveType::DataTypeBoolean: case RSExportPrimitiveType::DataTypeUnsigned565: case RSExportPrimitiveType::DataTypeUnsigned5551: case RSExportPrimitiveType::DataTypeUnsigned4444: case RSExportPrimitiveType::DataTypeMax: { slangAssert(false && "Not RS object type!"); } // No default case will enable compiler detecting the missing cases } return Res; } void RSObjectRefCount::VisitDeclStmt(clang::DeclStmt *DS) { for (clang::DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end(); I != E; I++) { clang::Decl *D = *I; if (D->getKind() == clang::Decl::Var) { clang::VarDecl *VD = static_cast<clang::VarDecl*>(D); RSExportPrimitiveType::DataType DT = RSExportPrimitiveType::DataTypeUnknown; clang::Expr *InitExpr = NULL; if (InitializeRSObject(VD, &DT, &InitExpr)) { getCurrentScope()->addRSObject(VD); getCurrentScope()->AppendRSObjectInit(VD, DS, DT, InitExpr); } } } return; } void RSObjectRefCount::VisitCompoundStmt(clang::CompoundStmt *CS) { if (!CS->body_empty()) { // Push a new scope Scope *S = new Scope(CS); mScopeStack.push(S); VisitStmt(CS); // Destroy the scope slangAssert((getCurrentScope() == S) && "Corrupted scope stack!"); S->InsertLocalVarDestructors(); mScopeStack.pop(); delete S; } return; } void RSObjectRefCount::VisitBinAssign(clang::BinaryOperator *AS) { clang::QualType QT = AS->getType(); if (CountRSObjectTypes(mCtx, QT.getTypePtr(), AS->getExprLoc())) { getCurrentScope()->ReplaceRSObjectAssignment(AS); } return; } void RSObjectRefCount::VisitStmt(clang::Stmt *S) { for (clang::Stmt::child_iterator I = S->child_begin(), E = S->child_end(); I != E; I++) { if (clang::Stmt *Child = *I) { Visit(Child); } } return; } // This function walks the list of global variables and (potentially) creates // a single global static destructor function that properly decrements // reference counts on the contained RS object types. clang::FunctionDecl *RSObjectRefCount::CreateStaticGlobalDtor() { Init(); clang::DeclContext *DC = mCtx.getTranslationUnitDecl(); clang::SourceLocation loc; llvm::StringRef SR(".rs.dtor"); clang::IdentifierInfo &II = mCtx.Idents.get(SR); clang::DeclarationName N(&II); clang::FunctionProtoType::ExtProtoInfo EPI; clang::QualType T = mCtx.getFunctionType(mCtx.VoidTy, llvm::ArrayRef<clang::QualType>(), EPI); clang::FunctionDecl *FD = NULL; // Generate rsClearObject() call chains for every global variable // (whether static or extern). std::list<clang::Stmt *> StmtList; for (clang::DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end(); I != E; I++) { clang::VarDecl *VD = llvm::dyn_cast<clang::VarDecl>(*I); if (VD) { if (CountRSObjectTypes(mCtx, VD->getType().getTypePtr(), loc)) { if (!FD) { // Only create FD if we are going to use it. FD = clang::FunctionDecl::Create(mCtx, DC, loc, loc, N, T, NULL, clang::SC_None); } // Make sure to create any helpers within the function's DeclContext, // not the one associated with the global translation unit. clang::Stmt *RSClearObjectCall = Scope::ClearRSObject(VD, FD); StmtList.push_back(RSClearObjectCall); } } } // Nothing needs to be destroyed, so don't emit a dtor. if (StmtList.empty()) { return NULL; } clang::CompoundStmt *CS = BuildCompoundStmt(mCtx, StmtList, loc); FD->setBody(CS); return FD; } } // namespace slang
36.200508
80
0.552864
touxiong88
302fe2d3f3f102b03543aea9ee36bd7b982fb4a3
8,462
cpp
C++
ConnectOptionDialog.cpp
hyo0913/MQTT-Client-with-QMQTT
d9974d755dcc4f16c1e89b426c45be3854bcdbb5
[ "MIT" ]
1
2021-02-10T08:56:12.000Z
2021-02-10T08:56:12.000Z
ConnectOptionDialog.cpp
hyo0913/MQTT-Client-using-qmqtt
d9974d755dcc4f16c1e89b426c45be3854bcdbb5
[ "MIT" ]
null
null
null
ConnectOptionDialog.cpp
hyo0913/MQTT-Client-using-qmqtt
d9974d755dcc4f16c1e89b426c45be3854bcdbb5
[ "MIT" ]
null
null
null
#include "ConnectOptionDialog.h" #include "ui_ConnectOptionDialog.h" #include "QFileDialog" #include "QApplication" ConnectOptionDialog::ConnectOptionDialog(QWidget *parent) : QDialog(parent), ui(new Ui::ConnectOptionDialog) { ui->setupUi(this); connect(ui->checkBoxWillFlag, SIGNAL(toggled(bool)), this, SLOT(willFlagToggled(bool))); willFlagToggled(false); connect(ui->checkBoxUserNameFlag, SIGNAL(toggled(bool)), this, SLOT(userNameFlagToggled(bool))); userNameFlagToggled(false); connect(ui->checkBoxAutoReconnect, SIGNAL(toggled(bool)), this, SLOT(autoReconnectToggled(bool))); autoReconnectToggled(false); connect(ui->checkBoxSsl, SIGNAL(toggled(bool)), this, SLOT(useSslToggled(bool))); useSslToggled(false); connect(ui->toolButtonCertifiacte, SIGNAL(clicked(bool)), this, SLOT(btnCertificateClicked())); connect(ui->toolButtonPrivateKey, SIGNAL(clicked(bool)), this, SLOT(btnPriavteKeyClicked())); } ConnectOptionDialog::~ConnectOptionDialog() { delete ui; } bool ConnectOptionDialog::needWebsocket() const { bool result = false; if( ui->comboBoxNetwork->currentIndex() == 1 ) { result = true; } return result; } quint32 ConnectOptionDialog::port() const { return ui->spinBoxPort->value(); } bool ConnectOptionDialog::cleanSession() const { return ui->checkBoxCleanSession->isChecked(); } bool ConnectOptionDialog::willFlag() const { return ui->checkBoxWillFlag->isChecked(); } bool ConnectOptionDialog::willQosFlag() const { return ui->checkBoxWillQoS->isChecked(); } const QString ConnectOptionDialog::willTopic() const { return ui->lineEditWillTopic->text(); } const QByteArray ConnectOptionDialog::willMessage() const { return ui->lineEditWillMessage->text().toUtf8(); } quint8 ConnectOptionDialog::willQoS() const { return static_cast<quint8>(ui->spinBoxWillQoS->value()); } bool ConnectOptionDialog::willRetainFlag() const { return ui->checkBoxWillRetain->isChecked(); } bool ConnectOptionDialog::userNameFlag() const { return ui->checkBoxUserNameFlag->isChecked(); } const QString ConnectOptionDialog::userName() const { return ui->lineEditUserName->text(); } bool ConnectOptionDialog::passwordFlag() const { return ui->checkBoxPasswordFlag->isChecked(); } const QByteArray ConnectOptionDialog::password() const { return ui->lineEditPassword->text().toUtf8(); } quint16 ConnectOptionDialog::keepAlive() const { return static_cast<quint16>(ui->spinBoxKeepAlive->value()); } bool ConnectOptionDialog::autoReconnect() const { return ui->checkBoxAutoReconnect->isChecked(); } int ConnectOptionDialog::autoReconnectInterval() const { return ui->spinBoxAutoReconnectInterval->value(); } bool ConnectOptionDialog::useSsl() const { return ui->checkBoxSsl->isChecked(); } QSslCertificate ConnectOptionDialog::certificate() const { // QSslCertificate result; // QString certFileName = ui->lineEditCertifiacte->text(); // if( certFileName.isEmpty() ) return QSslCertificate(); // QFile file(certFileName); // if( file.open(QIODevice::ReadOnly) ) // { // QByteArray data = file.readAll(); // file.close(); // if( certFileName.contains(".pem") ) // { // result = QSslCertificate(data, QSsl::Pem); // } // else if( certFileName.contains(".der") ) // { // result = QSslCertificate(data, QSsl::Der); // } // } // return result; QList<QSslCertificate> lstCerts; QString certFileName = ui->lineEditCertifiacte->text(); if( certFileName.isEmpty() ) return QSslCertificate(); lstCerts = QSslCertificate::fromPath(certFileName); if( lstCerts.count() <= 0 ) return QSslCertificate(); return lstCerts.first(); } QSslKey ConnectOptionDialog::privateKey() const { QSslKey result; QString keyFileName = ui->lineEditPrivateKey->text(); if( keyFileName.isEmpty() ) return QSslKey(); QFile file(keyFileName); if( file.open(QIODevice::ReadOnly) ) { result = QSslKey(file.readAll(), QSsl::Rsa); } return result; } bool ConnectOptionDialog::ignoreSelfSigned() const { return ui->checkBoxIgnoreSelfSigned->isChecked(); } void ConnectOptionDialog::setEditable(bool editable) { ui->labelNetwork->setEnabled(editable); ui->comboBoxNetwork->setEnabled(editable); ui->labelPort->setEnabled(editable); ui->spinBoxPort->setEnabled(editable); ui->checkBoxCleanSession->setEnabled(editable); ui->checkBoxWillFlag->setEnabled(editable); ui->labelWillTopic->setEnabled(editable); ui->lineEditWillTopic->setEnabled(editable); ui->labelWillMessage->setEnabled(editable); ui->lineEditWillMessage->setEnabled(editable); ui->checkBoxWillQoS->setEnabled(editable); ui->spinBoxWillQoS->setEnabled(editable); ui->checkBoxWillRetain->setEnabled(editable); ui->checkBoxUserNameFlag->setEnabled(editable); ui->lineEditUserName->setEnabled(editable); ui->checkBoxPasswordFlag->setEnabled(editable); ui->lineEditPassword->setEnabled(editable); ui->labelKeepAlive->setEnabled(editable); ui->spinBoxKeepAlive->setEnabled(editable); ui->labelKeepAliveSec->setEnabled(editable); ui->checkBoxAutoReconnect->setEnabled(editable); ui->labelAutoReconnectInterval->setEnabled(editable); ui->spinBoxAutoReconnectInterval->setEnabled(editable); ui->labelAutoReconnectIntervalSec->setEnabled(editable); ui->checkBoxSsl->setEnabled(editable); ui->labelCertificate->setEnabled(editable); ui->lineEditCertifiacte->setEnabled(editable); ui->toolButtonCertifiacte->setEnabled(editable); ui->labelPrivateKey->setEnabled(editable); ui->lineEditPrivateKey->setEnabled(editable); ui->toolButtonPrivateKey->setEnabled(editable); ui->checkBoxIgnoreSelfSigned->setEnabled(editable); if( editable ) { willFlagToggled(ui->checkBoxWillFlag->isChecked()); userNameFlagToggled(ui->checkBoxUserNameFlag->isChecked()); autoReconnectToggled(ui->checkBoxAutoReconnect->isChecked()); useSslToggled(ui->checkBoxSsl->isChecked()); } } void ConnectOptionDialog::willFlagToggled(bool toggled) { if( toggled == false ) { ui->checkBoxWillQoS->setChecked(false); ui->checkBoxWillRetain->setChecked(false); } ui->labelWillTopic->setEnabled(toggled); ui->labelWillMessage->setEnabled(toggled); ui->lineEditWillTopic->setEnabled(toggled); ui->lineEditWillMessage->setEnabled(toggled); ui->checkBoxWillQoS->setEnabled(toggled); ui->spinBoxWillQoS->setEnabled(toggled); ui->checkBoxWillRetain->setEnabled(toggled); } void ConnectOptionDialog::userNameFlagToggled(bool toggled) { if( toggled == false ) { ui->checkBoxPasswordFlag->setChecked(false); } ui->checkBoxPasswordFlag->setEnabled(toggled); ui->lineEditPassword->setEnabled(toggled); } void ConnectOptionDialog::autoReconnectToggled(bool toggled) { ui->labelAutoReconnectInterval->setEnabled(toggled); ui->spinBoxAutoReconnectInterval->setEnabled(toggled); ui->labelAutoReconnectIntervalSec->setEnabled(toggled); } void ConnectOptionDialog::useSslToggled(bool toggled) { ui->labelCertificate->setEnabled(toggled); ui->lineEditCertifiacte->setEnabled(toggled); ui->toolButtonCertifiacte->setEnabled(toggled); ui->labelPrivateKey->setEnabled(toggled); ui->lineEditPrivateKey->setEnabled(toggled); ui->toolButtonPrivateKey->setEnabled(toggled); ui->checkBoxIgnoreSelfSigned->setEnabled(toggled); } void ConnectOptionDialog::btnCertificateClicked() { QFileDialog dialog(this, "Certificate", QApplication::applicationDirPath(), "Certificate (*.pem *.der)"); if( dialog.exec() ) { ui->lineEditCertifiacte->setText(dialog.selectedFiles().first()); } } void ConnectOptionDialog::btnPriavteKeyClicked() { QFileDialog dialog(this, "Private Key", QApplication::applicationDirPath(), "Private Key (*.pem)"); if( dialog.exec() ) { ui->lineEditPrivateKey->setText(dialog.selectedFiles().first()); } }
28.979452
110
0.69109
hyo0913
3030085cec3c16ba6b029381746dd0a63baff54c
1,446
cc
C++
test/config_test.cc
lilialexlee/kit
94492e04832749fcdfb7f9fb8a778bb949d5e7d6
[ "MIT" ]
1
2015-09-22T15:33:30.000Z
2015-09-22T15:33:30.000Z
test/config_test.cc
lilialexlee/kit
94492e04832749fcdfb7f9fb8a778bb949d5e7d6
[ "MIT" ]
null
null
null
test/config_test.cc
lilialexlee/kit
94492e04832749fcdfb7f9fb8a778bb949d5e7d6
[ "MIT" ]
null
null
null
/* * config_test.cc * */ #include "util/config.h" #include <iostream> int main() { kit::Config config; config.Init("./test/example_conf"); std::string str_value; int ret = config.GetStr("str", &str_value); if (ret == 0) { std::cout << "get str: " << str_value << "\n"; } else { std::cerr << "get str failed.\n"; } std::vector<std::string> str_values; ret = config.GetStrs("strs", &str_values); if (ret == 0) { std::cout << "get strs:"; for (size_t i = 0; i < str_values.size(); ++i) { std::cout << " " << str_values[i]; } std::cout << "\n"; } else { std::cerr << "get strs failed.\n"; } int int_value; ret = config.GetInt("int", &int_value); if (ret == 0) { std::cout << "get int: " << int_value << "\n"; } else { std::cerr << "get int failed.\n"; } std::vector<int> int_values; ret = config.GetInts("ints", &int_values); if (ret == 0) { std::cout << "get ints:"; for (size_t i = 0; i < int_values.size(); ++i) { std::cout << " " << int_values[i]; } std::cout << "\n"; } else { std::cerr << "get ints failed.\n"; } ret = config.GetStr("not_exist", &str_value); if (ret == 0) { std::cerr << "get not exist config.\n"; } ret = config.GetStr("comments", &str_value); if (ret == 0) { std::cerr << "get not exist config.\n"; } return 0; }
21.909091
53
0.502766
lilialexlee
30315f2c2da15598ac8a5ff4725bec76120052dd
2,307
hxx
C++
src/tcl_iface/array.hxx
AltSysrq/Abendstern
106e1ad2457f7bfd90080eecf49a33f6079f8e1e
[ "BSD-3-Clause" ]
null
null
null
src/tcl_iface/array.hxx
AltSysrq/Abendstern
106e1ad2457f7bfd90080eecf49a33f6079f8e1e
[ "BSD-3-Clause" ]
null
null
null
src/tcl_iface/array.hxx
AltSysrq/Abendstern
106e1ad2457f7bfd90080eecf49a33f6079f8e1e
[ "BSD-3-Clause" ]
1
2022-01-29T11:54:41.000Z
2022-01-29T11:54:41.000Z
/** * @file * @author Jason Lingle * @brief Makes C automatic/static arrays accessible to trusted Tcl. */ /* * array.hxx * Make C arrays accessible to trusted Tcl. * * Created on: 12.07.2010 * Author: jason */ #ifndef ARRAY_HXX_ #define ARRAY_HXX_ #include <stdexcept> #include <exception> #include "src/core/aobject.hxx" /** Represents an automatically-allocated array of fixed * size. Tcl can also create them, in which case the data * is automatically deleted. * Uses of this in the definition must always be C++-outgoing, * immediate, and steal. */ template<typename T, unsigned S> class StaticArray: public AObject { T* data; bool del; public: /** Tcl constructor */ StaticArray() : data(new T[S]), del(true) {} /** Construct the array on the given array */ StaticArray(T* d) : data(d), del(false) {} virtual ~StaticArray() { if (del) delete[] data; } operator T*() { return data; } /** Array read */ T at(unsigned i) { if (i>=0 && i<S) return data[i]; throw std::range_error("Out of bounds"); } /** Array set */ T set(unsigned i, T t) { if (i>=0 && i<S) return data[i]=t; throw std::range_error("Out of bounds"); } /** Array size */ unsigned size() { return S; } /** Equality is determined solely by comparing the pointers. */ bool eq(StaticArray<T,S>* other) { return data==other->data; } }; /** Represents a dynamically-allocated array. * * The glue * definition should ensure that Tcl always has control * over this class. Tcl is responsible for knowing whether * to delete the contents. * * The array does not keep track of allocation size. * If Tcl "allocates" an array of size 0, a NULL array * is actually created. */ template<typename T> class DynArray: public AObject { T* data; public: /** Constructs a DynArray on the given array */ DynArray(T* d) : data(d) {} /** Allocates an array of the given size */ explicit DynArray(unsigned sz) : data(sz? new T[sz] : 0) {} operator T*() { return data; } T at(unsigned i) { return data[i]; } ///< Array read T set(unsigned i, T t) { return data[i]=t; } ///< Array write bool eq(DynArray<T>* other) { return other->data==data; } ///< Pointer equality void del() { delete[] data; } ///< Deallocation }; #endif /* ARRAY_HXX_ */
24.806452
81
0.647161
AltSysrq
30351cdc1536feb813463363d184c60765f63aa0
799
cpp
C++
20-Valid_Parentheses.cpp
elsdrium/LeetCode-practice
a3b1fa5dd200155a636d36cd570e2454f7194e10
[ "MIT" ]
null
null
null
20-Valid_Parentheses.cpp
elsdrium/LeetCode-practice
a3b1fa5dd200155a636d36cd570e2454f7194e10
[ "MIT" ]
null
null
null
20-Valid_Parentheses.cpp
elsdrium/LeetCode-practice
a3b1fa5dd200155a636d36cd570e2454f7194e10
[ "MIT" ]
null
null
null
class Solution { public: bool isValid(string s) { list<char> stack; for( char c : s ) { switch ( c ) { case '(': case '{': case '[': stack.push_back(c); break; case ')': if ( stack.back() != '(' ) return false; stack.pop_back(); break; case '}': if ( stack.back() != '{' ) return false; stack.pop_back(); break; case ']': if ( stack.back() != '[' ) return false; stack.pop_back(); break; } } return stack.empty(); } };
27.551724
60
0.307885
elsdrium
3037f5e0b45bf4e649a6f55f8b430cc7717b11be
6,782
cc
C++
gnuradio-3.7.13.4/gr-atsc/lib/atsci_trellis_encoder.cc
v1259397/cosmic-gnuradio
64c149520ac6a7d44179c3f4a38f38add45dd5dc
[ "BSD-3-Clause" ]
1
2021-03-09T07:32:37.000Z
2021-03-09T07:32:37.000Z
gnuradio-3.7.13.4/gr-atsc/lib/atsci_trellis_encoder.cc
v1259397/cosmic-gnuradio
64c149520ac6a7d44179c3f4a38f38add45dd5dc
[ "BSD-3-Clause" ]
null
null
null
gnuradio-3.7.13.4/gr-atsc/lib/atsci_trellis_encoder.cc
v1259397/cosmic-gnuradio
64c149520ac6a7d44179c3f4a38f38add45dd5dc
[ "BSD-3-Clause" ]
null
null
null
/* -*- c++ -*- */ /* * Copyright 2002,2006 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio 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, or (at your option) * any later version. * * GNU Radio 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 GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #include <gnuradio/atsc/trellis_encoder_impl.h> #include <assert.h> #include <stdio.h> #include <string.h> static const int DIBITS_PER_BYTE = 4; #define SEGOF(x) ( (x) / ((SEGMENT_SIZE+1) * DIBITS_PER_BYTE)) #define SYMOF(x) (((x) % ((SEGMENT_SIZE+1) * DIBITS_PER_BYTE))-4) /* How many separate Trellis encoders / Viterbi decoders run in parallel */ static const int NCODERS = 12; #define ENCODER_SEG_BUMP 4 /* A Segment sync symbol is an 8VSB +5,-5,-5,+5 sequence that occurs at the start of each 207-byte segment (including field sync segments). */ #define DSEG_SYNC_SYM1 0x06 /* +5 */ #define DSEG_SYNC_SYM2 0x01 /* -5 */ #define DSEG_SYNC_SYM3 0x01 /* -5 */ #define DSEG_SYNC_SYM4 0x06 /* +5 */ /* Shift counts to bit numbers (high order, low order); 9x entries unused */ static const int bit1[8] = {1, 99, 3, 98, 5, 97, 7, 96}; static const int bit2[8] = {0, 99, 2, 98, 4, 97, 6, 96}; atsci_trellis_encoder::atsci_trellis_encoder () { debug = false; reset (); } atsci_trellis_encoder::~atsci_trellis_encoder () { } void atsci_trellis_encoder::reset () { for (int i = 0; i < NCODERS; i++) enc[i].reset (); } void atsci_trellis_encoder::encode (atsc_data_segment out[NCODERS], const atsc_mpeg_packet_rs_encoded in[NCODERS]) { unsigned char out_copy[OUTPUT_SIZE]; unsigned char in_copy[INPUT_SIZE]; assert (sizeof (in_copy) == sizeof (in[0].data) * NCODERS); assert (sizeof (out_copy) == sizeof (out[0].data) * NCODERS); // copy input into continguous temporary buffer for (int i = 0; i < NCODERS; i++){ assert (in[i].pli.regular_seg_p ()); plinfo::sanity_check (in[i].pli); memcpy (&in_copy[i * INPUT_SIZE/NCODERS], &in[i].data[0], ATSC_MPEG_RS_ENCODED_LENGTH * sizeof (in_copy[0])); } memset (out_copy, 0, sizeof (out_copy)); // FIXME, sanity check // do the deed... encode_helper (out_copy, in_copy); // copy output from contiguous temp buffer into final output for (int i = 0; i < NCODERS; i++){ memcpy (&out[i].data[0], &out_copy[i * OUTPUT_SIZE/NCODERS], ATSC_DATA_SEGMENT_LENGTH * sizeof (out_copy[0])); // copy pipeline info out[i].pli = in[i].pli; plinfo::sanity_check (out[i].pli); assert (out[i].pli.regular_seg_p ()); } } /* * This code expects contiguous arrrays. Use it as is, it computes * the correct answer. Maybe someday, when we've run out of better * things to do, rework to avoid the copying in encode. */ void atsci_trellis_encoder::encode_helper (unsigned char output[OUTPUT_SIZE], const unsigned char input[INPUT_SIZE]) { int i; int encoder; unsigned char trellis_buffer[NCODERS]; int trellis_wherefrom[NCODERS]; unsigned char *out, *next_out_seg; int chunk; int shift; unsigned char dibit; unsigned char symbol; int skip_encoder_bump; /* FIXME, we may want special processing here for a flag byte to keep track of which part of the field we're in? */ encoder = NCODERS - ENCODER_SEG_BUMP; skip_encoder_bump = 0; out = output; next_out_seg = out; for (chunk = 0; chunk < INPUT_SIZE; chunk += NCODERS) { /* Load a new chunk of bytes into the Trellis encoder buffers. They get loaded in an order that depends on where we are in the segment sync progress (sigh). GRR! When the chunk reload happens at the same time as the segment boundary, we should bump the encoder NOW for the reload, rather than LATER during the bitshift transition!!! */ if (out >= next_out_seg) { encoder = (encoder + ENCODER_SEG_BUMP) % NCODERS; skip_encoder_bump = 1; } for (i = 0; i < NCODERS; i++) { /* for debug */ trellis_wherefrom[encoder] = chunk+i; trellis_buffer[encoder] = input [chunk+i]; encoder++; if (encoder >= NCODERS) encoder = 0; } for (shift = 6; shift >= 0; shift -= 2) { /* Segment boundaries happen to occur on some bitshift transitions. */ if (out >= next_out_seg) { /* Segment transition. Output a data segment sync symbol, and mess with the trellis encoder mux. */ *out++ = DSEG_SYNC_SYM1; *out++ = DSEG_SYNC_SYM2; *out++ = DSEG_SYNC_SYM3; *out++ = DSEG_SYNC_SYM4; if (debug) printf ("SYNC SYNC SYNC SYNC\n"); next_out_seg = out + (SEGMENT_SIZE * DIBITS_PER_BYTE); if (!skip_encoder_bump) encoder = (encoder + ENCODER_SEG_BUMP) % NCODERS; skip_encoder_bump = 0; } /* Now run each of the 12 Trellis encoders to spit out 12 symbols. Each encoder takes input from the same byte of the chunk, but the outputs of the encoders come out in various orders. NOPE -- this is false. The encoders take input from various bytes of the chunk (which changes at segment sync time), AND they also come out in various orders. You really do have to keep separate track of: the input bytes, the encoders, and the output bytes -- because they're all moving with respect to each other!!! */ for (i = 0; i < NCODERS; i++) { dibit = 0x03 & (trellis_buffer[encoder] >> shift); if (debug) printf ("Seg %ld Symb %3ld Trell %2d Byte %6d Bits %d-%d = dibit %d ", (long) SEGOF(out-output), (long) SYMOF(out-output), encoder, trellis_wherefrom[encoder], bit1[shift], bit2[shift], dibit); symbol = enc[encoder].encode (dibit); *out++ = symbol; encoder++; if (encoder >= NCODERS) encoder = 0; if (debug) printf ("sym %d\n", symbol); } /* Encoders */ } /* Bit shifts */ } /* Chunks */ /* Check up on ourselves */ #if 0 assertIntsEqual (0, (INPUT_SIZE * DIBITS_PER_BYTE) % NCODERS, "not %"); assertIntsEqual (OUTPUT_SIZE, out - output, "outptr"); assertIntsEqual (NCODERS - ENCODER_SEG_BUMP, encoder, "mux sync"); #else assert (0 == (INPUT_SIZE * DIBITS_PER_BYTE) % NCODERS); assert (OUTPUT_SIZE == out - output); assert (NCODERS - ENCODER_SEG_BUMP == encoder); #endif }
32.449761
76
0.664406
v1259397
303880210283d85be75660b6f91578dee964ab52
4,210
cpp
C++
002_disparity_panorama.cpp
DreamVu/Code-Samples
2fccd9e649fbe7d9895df7d799cb1ec33066d1c2
[ "MIT" ]
null
null
null
002_disparity_panorama.cpp
DreamVu/Code-Samples
2fccd9e649fbe7d9895df7d799cb1ec33066d1c2
[ "MIT" ]
null
null
null
002_disparity_panorama.cpp
DreamVu/Code-Samples
2fccd9e649fbe7d9895df7d799cb1ec33066d1c2
[ "MIT" ]
null
null
null
/* CODE SAMPLE # 002: Disparity panorama This code will grab the basic stereo panoramas (left and right images) and ALSO the Disparity panorama, and all these 3 images are displayed in an opencv window >>>>>> Compile this code using the following command.... g++ 002_disparity_panorama.cpp ../lib/libPAL.so `pkg-config --libs --cflags opencv` -g -o 002_disparity_panorama.out -I../include/ -lv4l2 -lpthread -std=c++11 >>>>>> Execute the binary file by typing the following command... ./002_disparity_panorama.out >>>>>> KEYBOARD CONTROLS: ESC key closes the window Press v/V key to toggle the vertical flip of panorama Press f/F to toggle filter rgb property. Press d/D to toggle fast depth property Press r/R to toggle near range property */ # include <stdio.h> # include <opencv2/opencv.hpp> # include <chrono> # include <bits/stdc++.h> # include "PAL.h" using namespace cv; using namespace std; using namespace std::chrono; int main(int argc, char *argv[]) { namedWindow("PAL Disparity Panorama", WINDOW_NORMAL); // Create a window for display. int width, height; if (PAL::Init(width, height, -1) != PAL::SUCCESS) //Connect to the PAL camera { printf("Init failed\n"); return 1; } PAL::CameraProperties data; PAL::Acknowledgement ack = PAL::LoadProperties("../Explorer/SavedPalProperties.txt", &data); if(ack != PAL::SUCCESS) { printf("Error Loading settings\n"); } PAL::CameraProperties prop; unsigned int flag = PAL::MODE; flag = flag | PAL::FD; flag = flag | PAL::NR; flag = flag | PAL::FILTER_SPOTS; flag = flag | PAL::VERTICAL_FLIP; prop.mode = PAL::Mode::FAST_DEPTH; // The other available option is PAL::Mode::HIGH_QUALITY_DEPTH prop.fd = 1; prop.nr = 0; prop.filter_spots = 1; prop.vertical_flip =0; PAL::SetCameraProperties(&prop, &flag); bool isDisparityNormalized = true; //width and height are the dimensions of each panorama. //Each of the panoramas are displayed at quarter their original resolution. //Since the left+right+disparity are vertically stacked, the window height should be thrice the quarter-height resizeWindow("PAL Disparity Panorama", width / 4, (height / 4) * 3); int key = ' '; printf("Press ESC to close the window\n"); printf("Press v/V key to toggle the vertical flip of panorama\n"); printf("Press f/F to toggle filter rgb property.\n"); printf("Press d/D to toggle fast depth property\n"); printf("Press r/R to toggle near range property\n"); size_t currentResolution = 0; bool flip = false; bool filter_spots = true; bool nr = false; bool fd = true; //27 = esc key. Run the loop until the ESC key is pressed while (key != 27) { PAL::Image left, right, depth, disparity; PAL::GrabFrames(&left, &right, &depth); Mat output; //Convert PAL::Image to Mat Mat l = Mat(left.rows, left.cols, CV_8UC3, left.Raw.u8_data); Mat r = Mat(right.rows, right.cols, CV_8UC3, right.Raw.u8_data); Mat d = Mat(depth.rows, depth.cols, CV_32FC1, depth.Raw.f32_data); d.convertTo(d, CV_8UC1); cvtColor(d, d, cv::COLOR_GRAY2BGR); //Vertical concatenation of temp and disparity into the final output vconcat(l, d, output); //Display the final output image imshow("PAL Disparity Panorama", output); //Wait for the keypress - with a timeout of 1 ms key = waitKey(1) & 255; if (key == 'v' || key == 'V') { PAL::CameraProperties prop; flip = !flip; prop.vertical_flip = flip; unsigned int flags = PAL::VERTICAL_FLIP; PAL::SetCameraProperties(&prop, &flags); } if (key == 'f' || key == 'F') { PAL::CameraProperties prop; filter_spots = !filter_spots; prop.filter_spots = filter_spots; unsigned int flags = PAL::FILTER_SPOTS; PAL::SetCameraProperties(&prop, &flags); } if(key == 'd' || key == 'D') { PAL::CameraProperties prop; fd = !fd; prop.fd = fd; unsigned int flags = PAL::FD; PAL::SetCameraProperties(&prop, &flags); } if(key == 'r' || key == 'R') { PAL::CameraProperties prop; nr = !nr; prop.nr = nr; unsigned int flags = PAL::NR; PAL::SetCameraProperties(&prop, &flags); } } printf("exiting the application\n"); PAL::Destroy(); return 0; }
26.3125
162
0.676485
DreamVu
303cbece338cb8a60e1ccda8430c5e1b98e53dcb
2,493
cpp
C++
src/Common/Instruction_test.cpp
skyzh/RISCV-Simulator
8989a09c357a69b68612f653380d60816f5176c2
[ "MIT" ]
106
2019-07-04T12:20:25.000Z
2022-03-20T10:50:52.000Z
src/Common/Instruction_test.cpp
qshan/RISCV-Simulator
8989a09c357a69b68612f653380d60816f5176c2
[ "MIT" ]
2
2019-07-02T13:38:42.000Z
2019-09-06T02:09:30.000Z
src/Common/Instruction_test.cpp
qshan/RISCV-Simulator
8989a09c357a69b68612f653380d60816f5176c2
[ "MIT" ]
12
2020-01-02T05:41:28.000Z
2022-03-10T11:57:46.000Z
// // Created by Alex Chi on 2019-07-01. // #include "gtest/gtest.h" #include "Instruction.hpp" TEST(Instruction, CorrectSize) { EXPECT_EQ(sizeof(Instruction), 4); } TEST(Instruction, InstructionR) { // 10987654321098765432109876543210 InstructionR inst(0b10101010101010101010101010101010); // 10987654321098765432109876543210 EXPECT_EQ(inst.opcode, 0b0101010); EXPECT_EQ(inst.rd, 0b10101); EXPECT_EQ(inst.rs1, 0b10101); EXPECT_EQ(inst.rs2, 0b01010); EXPECT_EQ(inst.funct3, 0b010); } TEST(Instruction, InstructionI) { // 10987654321098765432109876543210 InstructionI inst(0b10101010101010101010101010101010); // 10987654321098765432109876543210 EXPECT_EQ(inst.imm, 0b11111111111111111111101010101010); EXPECT_EQ(inst.opcode, 0b0101010); EXPECT_EQ(inst.rd, 0b10101); EXPECT_EQ(inst.rs1, 0b10101); EXPECT_EQ(inst.funct3, 0b010); } TEST(Instruction, InstructionS) { // 10987654321098765432109876543210 InstructionS inst(0b10101010101010101010101010101010); // 10987654321098765432109876543210 EXPECT_EQ(inst.imm, 0b11111111111111111111101010110101); EXPECT_EQ(inst.opcode, 0b0101010); EXPECT_EQ(inst.rs1, 0b10101); EXPECT_EQ(inst.rs2, 0b01010); EXPECT_EQ(inst.funct3, 0b010); } TEST(Instruction, InstructionB) { // 10987654321098765432109876543210 InstructionB inst(0b10101010101010101010101010101010); // 10987654321098765432109876543210 EXPECT_EQ(inst.imm, 0b11111111111111111111101010110100); EXPECT_EQ(inst.opcode, 0b0101010); EXPECT_EQ(inst.rs1, 0b10101); EXPECT_EQ(inst.rs2, 0b01010); EXPECT_EQ(inst.funct3, 0b010); } TEST(Instruction, InstructionU) { // 10987654321098765432109876543210 InstructionU inst(0b10101010101010101010101010101010); // 10987654321098765432109876543210 EXPECT_EQ(inst.imm, 0b10101010101010101010000000000000); EXPECT_EQ(inst.opcode, 0b0101010); EXPECT_EQ(inst.rd, 0b10101); } TEST(Instruction, InstructionJ) { // 10987654321098765432109876543210 InstructionJ inst(0b10101010101010101010101010101010); // 10987654321098765432109876543210 EXPECT_EQ(inst.imm, 0b11111111111110101010001010101010); EXPECT_EQ(inst.opcode, 0b0101010); EXPECT_EQ(inst.rd, 0b10101); }
34.150685
60
0.69274
skyzh
303fb3bc53beaf5ea5c43b46203287c27e904f92
13,179
hpp
C++
sources/RenderSystem/spShaderClass.hpp
rontrek/softpixel
73a13a67e044c93f5c3da9066eedbaf3805d6807
[ "Zlib" ]
14
2015-08-16T21:05:20.000Z
2019-08-21T17:22:01.000Z
sources/RenderSystem/spShaderClass.hpp
rontrek/softpixel
73a13a67e044c93f5c3da9066eedbaf3805d6807
[ "Zlib" ]
null
null
null
sources/RenderSystem/spShaderClass.hpp
rontrek/softpixel
73a13a67e044c93f5c3da9066eedbaf3805d6807
[ "Zlib" ]
3
2020-02-15T09:17:41.000Z
2020-05-21T14:10:40.000Z
/* * Shader class header * * This file is part of the "SoftPixel Engine" (Copyright (c) 2008 by Lukas Hermanns) * See "SoftPixelEngine.hpp" for license information. */ #ifndef __SP_SHADER_CLASS_H__ #define __SP_SHADER_CLASS_H__ #include "Base/spStandard.hpp" #include "Base/spInputOutput.hpp" #include "Base/spBaseObject.hpp" #include "RenderSystem/spShaderConfigTypes.hpp" namespace sp { namespace scene { class MaterialNode; } namespace video { class Shader; class ShaderResource; class VertexFormat; class ConstantBuffer; /** Build shader flags. This is used for the two static functions "ShaderClass::getShaderVersion" and "ShaderClass::build". \since Version 3.2 */ enum EBuildShaderFlags { SHADERBUILD_CG = 0x0002, SHADERBUILD_GLSL = 0x0004, SHADERBUILD_HLSL3 = 0x0008, SHADERBUILD_HLSL5 = 0x0010, SHADERBUILD_VERTEX = 0x0100, SHADERBUILD_PIXEL = 0x0200, SHADERBUILD_GEOMETRY = 0x0400, SHADERBUILD_HULL = 0x0800, SHADERBUILD_DOMAIN = 0x1000, }; /** C-pre-processor directives used for shading languages. \todo Move this to a token parser/ lexer or something like that. \since Version 3.3 */ enum ECPPDirectives { CPPDIRECTIVE_NONE, //!< Invalid CPP directive. CPPDIRECTIVE_INCLUDE_STRING, //!< #include "HeaderFile.h" CPPDIRECTIVE_INCLUDE_BRACE, //!< #include <core> }; //! Shader resource binding structure. struct SShaderResourceBinding { SShaderResourceBinding() : Resource (0), AccessFlags (0) { } SShaderResourceBinding(ShaderResource* BindResource, u8 BindAccessFlags) : Resource (BindResource ), AccessFlags (BindAccessFlags) { } ~SShaderResourceBinding() { } /* Members */ ShaderResource* Resource; u8 AccessFlags; //!< \see EResourceAccess }; /** Shader classes are used to link several shaders (Vertex-, Pixel shaders etc.) to one shader program. Modern graphics hardware has the following shader stages: - Vertex Shader - Hull Shader (In OpenGL "Tessellation Control" Shader) - Domain Shader (In OpenGL "Tessellation Evaluation" Shader) - Geometry Shader - Pixel Shader (In OpenGL "Fragment" Shader) - Compute Shader (This is seperated from the graphics pipeline) \ingroup group_shader */ class SP_EXPORT ShaderClass : public BaseObject { public: virtual ~ShaderClass(); /* === Functions === */ /** Binds the table with its shaders. \param[in] Object Pointer to a MaterialNode object which shall be used for the shader callback if set. */ virtual void bind(const scene::MaterialNode* Object = 0) = 0; //! Unbinds the table with its shaders. virtual void unbind() = 0; //! Compiles and links the whole shader class. virtual bool compile() = 0; /** Adds the specified shader resource object. \param[in] Resource Pointer to the shader resource object which is to be added. \param[in] AccessFlags Specifies which access parts of the shader resources are to be added. By default RESOURCE_ACCESS_READ_WRITE which means that the read- and write access resources will be added. For HLSL the shader-resource-view (SRV) for read access and the unordered-access-view (UAV) for write access will be added. Use RESOURCE_ACCESS_READ or RESOURCE_ACCESS_WRITE to only bind the SRV or UAV. \note At first all textures are bound to a shader and then all shader resources. This is order is important for the resource registers in the shader. \see ShaderResource \see addRWTexture \see EResourceAccess \since Version 3.3 */ virtual void addShaderResource(ShaderResource* Resource, u8 AccessFlags = RESOURCE_ACCESS_READ_WRITE); /** Removes the specified shader resource object. \see addShaderResource \since Version 3.3 */ virtual void removeShaderResource(ShaderResource* Resource); virtual void clearShaderResources(); /** Adds the specified shader R/W texture object. \param[in] Tex Pointer to the R/W texture object which is to be added. In this case the texture must be an R/W texture, i.e. from the type TEXTURE_*_RW. \see addShaderResource \see Texture \see ETextureTypes \since Version 3.3 */ virtual void addRWTexture(Texture* Tex); /** Removes the specified shader R/W texture object. \see addRWTexture \since Version 3.3 */ virtual void removeRWTexture(Texture* Tex); virtual void clearRWTextures(); /* === Static functions === */ /** Returns the shader version used for the specified flags. \param[in] Flags Specifies the build flags. This can be a combination of the values in the "EBuildShaderFlags" enumeration. \return Shader version specified in the "EShaderVersions" enumeration. If no version could be found "DUMMYSHADER_VERSION" will be returned. \see EBuildShaderFlags \since Version 3.2 */ static EShaderVersions getShaderVersion(s32 Flags); /** Builds a complete shader class with the specified vertex-format, shader source code and build flags. This is particularly used internally for the deferred-renderer and post-processing effects. \param[in] Name Specifies the shader name and is used for possible error messages. \param[out] ShdClass Specifies the resulting shader class object. \param[in] VertFmt Constant pointer to the vertex format used for the shader class. \param[in] ShdBufferVertex Constant pointer to the vertex shader source code (std::list<io::stringc>). \param[in] ShdBufferPixel Constant pointer to the pixel shader source code (std::list<io::stringc>). \param[in] VertexMain Specifies the name of the vertex shader main function. \param[in] PixelMain Specifies the name of the pixel shader main function. \param[in] Flags Specifies the compilation flags. This can be one of the following values: SHADERBUILD_CG, SHADERBUILD_GLSL, SHADERBUILD_HLSL3 or SHADERBUILD_HLSL5. \return True if the shader class could be created successful. \note This function always failes if "ShdBufferVertex" is null pointers. \see VertexFormat \see EBuildShaderFlags \since Version 3.2 */ static bool build( const io::stringc &Name, ShaderClass* &ShdClass, const VertexFormat* VertFmt, const std::list<io::stringc>* ShdBufferVertex, const std::list<io::stringc>* ShdBufferPixel, const io::stringc &VertexMain = "VertexMain", const io::stringc &PixelMain = "PixelMain", s32 Flags = SHADERBUILD_CG ); /** Loads a shader resource file and parses it for '#include' directives. \param[in] FileSys Specifies the file system you want to use. \param[in] Filename Specifies the filename of the shader resource which is to be loaded. \param[in,out] ShaderBuffer Specifies the shader source code container which is to be filled. \param[in] UseCg Specifies whether Cg shaders are to be used or not. By default false. \since Version 3.3 */ static bool loadShaderResourceFile( io::FileSystem &FileSys, const io::stringc &Filename, std::list<io::stringc> &ShaderBuffer, bool UseCg = false ); /** Determines whether the given string has an '#include' directive. \param[in] Line Specifies the string (or rather source code line) which is to be parsed. \param[out] Filename Specifies the output filename which can be expressed between the quotation marks inside the '#include' directive (e.g. #include "HeaderFile.h" -> will result in the string "HeaderFile.h"). \return CPPDIRECTIVE_INCLUDE_STRING if the given string has an '#include' directive with a string, CPPDIRECTIVE_INCLUDE_BRACE if the given string has an '#include' directive with brace or CPPDIRECTIVE_NONE otherwise. \note This is actually only used by the "loadShaderResourceFile" function. \see ECPPDirectives \see loadShaderResourceFile \since Version 3.3 */ static ECPPDirectives parseIncludeDirective(const io::stringc &Line, io::stringc &Filename); /* === Inline functions === */ /** Sets the shader object callback function. \param CallbackProc: Callback function in the form of "void Callback(ShaderClass* Table, const scene::MaterialNode* Object);". This callback normally is used to update the world- view matrix. In GLSL these matrices are integrated but in HLSL you have to set these shader-constants manually. */ inline void setObjectCallback(const ShaderObjectCallback &CallbackProc) { ObjectCallback_ = CallbackProc; } /** Sets the shader surface callback function. \param[in] CallbackProc Specifies the surface callback function. This callback normally is used to update texture settings for each surface. \see ShaderSurfaceCallback */ inline void setSurfaceCallback(const ShaderSurfaceCallback &CallbackProc) { SurfaceCallback_ = CallbackProc; } inline Shader* getVertexShader() const { return VertexShader_; } inline Shader* getPixelShader() const { return PixelShader_; } inline Shader* getGeometryShader() const { return GeometryShader_; } inline Shader* getHullShader() const { return HullShader_; } inline Shader* getDomainShader() const { return DomainShader_; } inline Shader* getComputeShader() const { return ComputeShader_; } /** Returns the list of all shader constant buffers used in the shader-class. To get the list of all shader constant buffers used in a single shader object, use the equivalent function of the respective shader. \see Shader::getConstantBufferList */ inline const std::vector<ConstantBuffer*>& getConstantBufferList() const { return ConstBufferList_; } //! Returns the count of shader constant buffers. inline size_t getConstantBufferCount() const { return ConstBufferList_.size(); } /** Returns the list of all shader resources. \see SShaderResourceBinding */ inline const std::vector<SShaderResourceBinding>& getShaderResourceList() const { return ShaderResources_; } //! Returns the count of shader resources. inline size_t getShaderResourceCount() const { return ShaderResources_.size(); } //! Returns the list of all R/W textures. inline const std::vector<Texture*>& getRWTextureList() const { return RWTextures_; } //! Returns the count of R/W textures. inline size_t getRWTextureCount() const { return RWTextures_.size(); } //! Returns true if the shader is a high level shader. inline bool isHighLevel() const { return HighLevel_; } //! Returns true if the shader class has been compiled successfully. inline bool valid() const { return CompiledSuccessfully_; } protected: friend class Shader; ShaderClass(); /* === Functions === */ void printError(const io::stringc &Message); void printWarning(const io::stringc &Message); /* === Members === */ ShaderObjectCallback ObjectCallback_; ShaderSurfaceCallback SurfaceCallback_; Shader* VertexShader_; Shader* PixelShader_; Shader* GeometryShader_; Shader* HullShader_; Shader* DomainShader_; Shader* ComputeShader_; std::vector<ConstantBuffer*> ConstBufferList_; //!< List of constant buffers of all shaders in the shader-class. std::vector<SShaderResourceBinding> ShaderResources_; std::vector<Texture*> RWTextures_; bool HighLevel_; bool CompiledSuccessfully_; }; } // /namespace scene } // /namespace sp #endif // ================================================================================
34.865079
131
0.629866
rontrek
303fd170eef267427715ae2218bd05a1403ec51d
3,942
hpp
C++
examples/accumulator/accumulators/stubs/template_function_accumulator.hpp
kempj/hpx
ffdbfed5dfa029a0f2e97e7367cb66d12103df67
[ "BSL-1.0" ]
null
null
null
examples/accumulator/accumulators/stubs/template_function_accumulator.hpp
kempj/hpx
ffdbfed5dfa029a0f2e97e7367cb66d12103df67
[ "BSL-1.0" ]
null
null
null
examples/accumulator/accumulators/stubs/template_function_accumulator.hpp
kempj/hpx
ffdbfed5dfa029a0f2e97e7367cb66d12103df67
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2007-2012 Hartmut Kaiser // Copyright (c) 2011 Bryce Adelstein-Lelbach // // 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) #if !defined(HPX_EXAMPLES_STUBS_TEMPLATE_FUNCTION_ACCUMULATOR_JUL_12_2012_1056AM) #define HPX_EXAMPLES_STUBS_TEMPLATE_FUNCTION_ACCUMULATOR_JUL_12_2012_1056AM #include <hpx/hpx_fwd.hpp> #include <hpx/include/components.hpp> #include <hpx/include/applier.hpp> #include <hpx/include/async.hpp> #include "../server/template_function_accumulator.hpp" namespace examples { namespace stubs { /////////////////////////////////////////////////////////////////////////// struct managed_accumulator : hpx::components::stub_base<server::template_function_accumulator> { /////////////////////////////////////////////////////////////////////// /// Reset the accumulator's value to 0. /// /// \note This function has fire-and-forget semantics. It will not wait /// for the action to be executed. Instead, it will return /// immediately after the action has has been dispatched. static void reset_non_blocking(hpx::naming::id_type const& gid) { typedef server::template_function_accumulator::reset_action action_type; hpx::apply<action_type>(gid); } /// Reset the accumulator's value to 0. /// /// \note This function is fully synchronous. static void reset_sync(hpx::naming::id_type const& gid) { typedef server::template_function_accumulator::reset_action action_type; hpx::async<action_type>(gid).get(); } /////////////////////////////////////////////////////////////////////// /// Add \p arg to the accumulator's value. /// /// \note This function has fire-and-forget semantics. It will not wait /// for the action to be executed. Instead, it will return /// immediately after the action has has been dispatched. template <typename T> static void add_non_blocking(hpx::naming::id_type const& gid, T arg) { typedef server::template_function_accumulator::add_action<T> action_type; hpx::apply<action_type>(gid, arg); } /// Add \p arg to the accumulator's value. /// /// \note This function is fully synchronous. //[managed_accumulator_stubs_add_sync template <typename T> static void add_sync(hpx::naming::id_type const& gid, T arg) { typedef typename server::template_function_accumulator::add_action<T> action_type; hpx::async<action_type>(gid, arg).get(); } /////////////////////////////////////////////////////////////////////// /// Asynchronously query the current value of the accumulator. /// /// \returns This function returns an \a hpx::lcos::future. When the /// value of this computation is needed, the get() method of /// the future should be called. If the value is available, /// get() will return immediately; otherwise, it will block /// until the value is ready. static hpx::lcos::future<double> query_async(hpx::naming::id_type const& gid) { typedef server::template_function_accumulator::query_action action_type; return hpx::async<action_type>(gid); } /// Query the current value of the accumulator. /// /// \note This function is fully synchronous. static double query_sync(hpx::naming::id_type const& gid) { // The following get yields control while the action is executed. return query_async(gid).get(); } }; }} #endif
40.22449
94
0.58067
kempj
3044e789aeef2de9d1302d7043c1282d0b844e00
7,189
cc
C++
kernel/fat32/fat32_dirent.cc
mit-pdos/ward
91b598932d161f907590b9ad21d7df395e5d6712
[ "MIT-0" ]
29
2019-12-12T02:30:35.000Z
2022-01-06T17:13:09.000Z
kernel/fat32/fat32_dirent.cc
mit-pdos/ward
91b598932d161f907590b9ad21d7df395e5d6712
[ "MIT-0" ]
47
2019-12-11T02:34:13.000Z
2020-06-08T19:26:59.000Z
kernel/fat32/fat32_dirent.cc
mit-pdos/ward
91b598932d161f907590b9ad21d7df395e5d6712
[ "MIT-0" ]
4
2020-12-08T13:46:55.000Z
2022-01-04T20:25:10.000Z
#include "types.h" #include "fat32.hh" static void strip_char(char *buf, char s) { assert(buf); char *lastch = buf; while (*lastch) lastch++; lastch--; while (lastch >= buf && *lastch == s) { *lastch = '\0'; lastch--; } } u32 fat32_dirent::cluster_id() { return ((u32) cluster_id_high << 16u) | cluster_id_low; } void fat32_dirent::set_cluster_id(u32 id) { cluster_id_high = (u16) (id >> 16u); cluster_id_low = (u16) id; } strbuf<12> fat32_dirent::extract_filename() { strbuf<sizeof(filename) + 1 + sizeof(extension)> out; // TODO: make this code less sketchy static_assert(sizeof(filename) + 1 + sizeof(extension) + 1 <= FILENAME_MAX, "8.3 filename must fit in FILENAME_MAX"); memcpy(out.buf_, filename, sizeof(filename)); out.buf_[sizeof(filename)] = '\0'; strip_char(out.buf_, ' '); memcpy(&out.buf_[strlen(out.buf_)], ".", 2); out.buf_[strlen(out.buf_)+sizeof(extension)] = '\0'; memcpy(&out.buf_[strlen(out.buf_)], extension, sizeof(extension)); strip_char(out.buf_, ' '); strip_char(out.buf_, '.'); if (strlen(out.ptr()) == 0) panic("file had zero-length filename constructed from '%8s.%3s' (first byte %2x, attributes %2x)\n", filename, extension, filename[0], attributes); return out; } u8 fat32_dirent::checksum() { // based on https://en.wikipedia.org/wiki/Design_of_the_FAT_file_system#VFAT_long_file_names u8 checksum = 0; for (u8 c : filename) checksum = ((checksum & 1u) << 7u) + (checksum >> 1u) + c; for (u8 c : extension) checksum = ((checksum & 1u) << 7u) + (checksum >> 1u) + c; return checksum; } static u32 count_char(const char *s, char c) { u32 count = 0; for (; *s; s++) if (*s == c) count++; return count; } // TODO: check all this filename manipulation code for appropriate bounds checks and correctness u32 fat32_dirent::count_filename_entries(const char *name) { strbuf<FILENAME_MAX> nbuf = name; strip_char(nbuf.buf_, '.'); if (!*nbuf.ptr()) return 0; // too short; empty u32 dots = count_char(nbuf.ptr(), '.'); if (dots == 0) { if (strlen(nbuf.ptr()) <= sizeof(fat32_dirent::filename)) return 1; } else if (dots == 1) { const char *dot = strchr(nbuf.ptr(), '.'); const char *last = nbuf.ptr() + strlen(nbuf.ptr()) - 1; if (last - dot <= sizeof(fat32_dirent::extension) && dot - nbuf.ptr() <= sizeof(fat32_dirent::filename)) return 1; } // otherwise, we need to use a long filename // 13 to match max number of characters in fat32_dirent_lfn; 12 is to round up; 1 is because we need a \0 at the end. u32 long_entries = (strlen(nbuf.ptr()) + 1 + 12) / 13; if (long_entries > 20 || strlen(nbuf.ptr()) > 255) return 0; // too long return long_entries + 1; // plus one because we need a guard entry } fat32_dirent fat32_dirent::short_filename(const char *name) { strbuf<FILENAME_MAX> nbuf = name; strip_char(nbuf.buf_, '.'); assert(*nbuf.ptr()); // non-empty fat32_dirent out = {}; char *dot = (char*)strchr(nbuf.ptr(), '.'); if (!dot) { memset((char*) out.extension, ' ', sizeof(out.extension)); } else { assert(*dot == '.'); *dot = '\0'; // just changing nbuf, so this is fine u32 elen = strlen(dot+1); assert(elen <= sizeof(out.extension)); memcpy((char*) out.extension, dot+1, elen); memset((char*) &out.extension[elen], ' ', sizeof(out.extension) - elen); } // populate filename u32 len = strlen(nbuf.ptr()); assert(len <= sizeof(out.filename)); memcpy((char*) out.filename, nbuf.ptr(), len); memset((char*) &out.filename[len], ' ', sizeof(out.filename) - len); return out; } fat32_dirent fat32_dirent::guard_filename(const char *name) { // FIXME: it isn't clear whether this is supposed to be something specific, but it's probably not supposed to be this // format, which is just <first eight filename letters>.<first three extension letters>. strbuf<FILENAME_MAX> nbuf = name; strip_char(nbuf.buf_, '.'); assert(*nbuf.ptr()); // non-empty char *dot = (char*)strchr(nbuf.ptr(), '.'); if (dot) *dot = '\0'; strbuf<sizeof(filename) + sizeof(extension) + 1> buf; strncpy(buf.buf_, nbuf.ptr(), sizeof(filename)); buf.buf_[sizeof(filename)] = '\0'; // just in case not otherwise terminated if (dot) { char *wptr = buf.buf_ + strlen(buf.buf_); *wptr++ = '.'; strncpy(wptr, dot+1, sizeof(extension)); wptr[sizeof(extension)] = '\0'; // just in case not otherwise terminated } return short_filename(buf.ptr()); } unsigned int fat32_dirent_lfn::index() { return sequence_number & 0x1Fu; } bool fat32_dirent_lfn::is_continuation() { return (sequence_number & 0x40u) == 0; } bool fat32_dirent_lfn::validate() { return zero_cluster == 0 && attributes == ATTR_LFN && vfat_type == 0x00 && (sequence_number & 0xA0u) == 0 && convert_char(name_a[0]) != 0; } strbuf<13> fat32_dirent_lfn::extract_name_segment() { strbuf<(sizeof(name_a) + sizeof(name_b) + sizeof(name_c)) / sizeof(u16)> out; int oi = 0; for (int i = 0; i < sizeof(name_a) / sizeof(u16); i++) out.buf_[oi++] = convert_char(name_a[i]); for (int i = 0; i < sizeof(name_b) / sizeof(u16); i++) out.buf_[oi++] = convert_char(name_b[i]); for (int i = 0; i < sizeof(name_c) / sizeof(u16); i++) out.buf_[oi++] = convert_char(name_c[i]); out.buf_[oi++] = '\0'; assert(oi == sizeof(out.buf_)); return out; } fat32_dirent fat32_dirent_lfn::filename_fragment(const char *name, u32 index, u8 checksum) { strbuf<FILENAME_MAX> nbuf = name; strip_char(nbuf.buf_, '.'); assert(*nbuf.ptr()); // non-empty u32 total_len = strlen(nbuf.ptr()) + 1; // plus one for NUL terminator u32 len_of_my_part = MIN(total_len - index * 13, 13); assert(len_of_my_part >= 1); bool last_entry = (total_len <= (index + 1) * 13); assert(index < 0x1Fu); fat32_dirent_lfn l = {}; l.sequence_number = (u8) ((last_entry ? 0x40u : 0x00u) | ((index + 1) & 0x1Fu)); l.checksum = checksum; l.attributes = ATTR_LFN; l.vfat_type = 0; l.zero_cluster = 0; u32 ri = index * 13; u32 rend = ri + len_of_my_part; for (int i = 0; i < sizeof(name_a) / sizeof(u16); i++) l.name_a[i] = ri < rend ? unconvert_char(nbuf.ptr()[ri++]) : 0xFFFF; for (int i = 0; i < sizeof(name_b) / sizeof(u16); i++) l.name_b[i] = ri < rend ? unconvert_char(nbuf.ptr()[ri++]) : 0xFFFF; for (int i = 0; i < sizeof(name_c) / sizeof(u16); i++) l.name_c[i] = ri < rend ? unconvert_char(nbuf.ptr()[ri++]) : 0xFFFF; assert(ri == rend); fat32_dirent out = {}; static_assert(sizeof(l) == sizeof(out), "expected directory entries to be the same size"); memcpy(&out, &l, sizeof(fat32_dirent)); return out; } u8 fat32_dirent_lfn::convert_char(u16 ucs_2) { if (ucs_2 == 0xFFFF) // used as padding return '\0'; if (ucs_2 > 0xFF) { static bool has_reported_warning = false; if (!has_reported_warning) { has_reported_warning = true; cprintf("warning: FAT32 driver does not support non-ASCII characters, but found %u in long filename entry [not reporting future unsupported characters]\n", ucs_2); } } return (u8) ucs_2; } u16 fat32_dirent_lfn::unconvert_char(u8 ascii) { return (u16) ascii; }
29.829876
169
0.641953
mit-pdos
30492562f44dbe9294a88209c703116a098d00bd
7,356
cpp
C++
srm 195 div1/FanFailure.cpp
emiliot/topcoder
c58e105424b484a4e5600bad2c58d664cdcae935
[ "MIT" ]
null
null
null
srm 195 div1/FanFailure.cpp
emiliot/topcoder
c58e105424b484a4e5600bad2c58d664cdcae935
[ "MIT" ]
null
null
null
srm 195 div1/FanFailure.cpp
emiliot/topcoder
c58e105424b484a4e5600bad2c58d664cdcae935
[ "MIT" ]
null
null
null
// Paste me into the FileEdit configuration dialog #include "assert.h" #include "ctype.h" #include "float.h" #include "math.h" #include "stdio.h" #include "string.h" #include "stdlib.h" #include "stdarg.h" #include "time.h" #include "algorithm" #include "numeric" #include "functional" #include "utility" #include "bitset" #include "vector" #include "list" #include "set" #include "map" #include "queue" #include "stack" #include "string" #include "sstream" #include "iostream" using namespace std; #define all(v) (v).begin(), (v).end() typedef long long i64; template <class T> void make_unique(T& v) {sort(all(v)); v.resize(unique(all(v)) - v.begin());} int memo[51][50001]; bool mark[51][50001]; const int INF = 0x3f3f3f3f; int f(vector <int> &v, int low, int i, int cap){ if(i >= (int)v.size()){ return 0; } int &best = memo[i][cap]; if(mark[i][cap])return best; mark[i][cap] = true; best = f(v, low, i+1, cap); if(cap - v[i] >= low){ best = max(best, f(v, low, i+1, cap - v[i]) + 1); } return best; } int g(vector <int> &v, int low, int i, int cap){ if(i >= (int)v.size()){ if(cap < low)return 0; else return INF; } int &best = memo[i][cap]; if(mark[i][cap])return best; mark[i][cap] = true; best = g(v, low, i+1, cap); best = min(best, g(v, low, i+1, cap - v[i]) + 1); return best; } class FanFailure { public: vector <int> getRange( vector <int> capacities, int minCooling ) { vector <int> res(2, 0); int cap = 0; for(int i=0, n=capacities.size(); i<n; ++i) cap += capacities[i]; memset(mark, false, sizeof(mark)); res[0] = f(capacities, minCooling, 0, cap); memset(mark, false, sizeof(mark)); res[1] = g(capacities, minCooling, 0, cap)-1; return res; } }; // BEGIN CUT HERE namespace moj_harness { int run_test_case(int); void run_test(int casenum = -1, bool quiet = false) { if (casenum != -1) { if (run_test_case(casenum) == -1 && !quiet) { cerr << "Illegal input! Test case " << casenum << " does not exist." << endl; } return; } int correct = 0, total = 0; for (int i=0;; ++i) { int x = run_test_case(i); if (x == -1) { if (i >= 100) break; continue; } correct += x; ++total; } if (total == 0) { cerr << "No test cases run." << endl; } else if (correct < total) { cerr << "Some cases FAILED (passed " << correct << " of " << total << ")." << endl; } else { cerr << "All " << total << " tests passed!" << endl; } } template<typename T> ostream& operator<<(ostream &os, const vector<T> &v) { os << "{"; for (typename vector<T>::const_iterator vi=v.begin(); vi!=v.end(); ++vi) { if (vi != v.begin()) os << ","; os << " " << *vi; } os << " }"; return os; } int verify_case(int casenum, const vector <int> &expected, const vector <int> &received, clock_t elapsed) { cerr << "Example " << casenum << "... "; string verdict; vector<string> info; char buf[100]; if (elapsed > CLOCKS_PER_SEC / 200) { sprintf(buf, "time %.2fs", elapsed * (1.0/CLOCKS_PER_SEC)); info.push_back(buf); } if (expected == received) { verdict = "PASSED"; } else { verdict = "FAILED"; } cerr << verdict; if (!info.empty()) { cerr << " ("; for (int i=0; i<(int)info.size(); ++i) { if (i > 0) cerr << ", "; cerr << info[i]; } cerr << ")"; } cerr << endl; if (verdict == "FAILED") { cerr << " Expected: " << expected << endl; cerr << " Received: " << received << endl; } return verdict == "PASSED"; } int run_test_case(int casenum__) { switch (casenum__) { case 0: { int capacities[] = {1,2,3}; int minCooling = 2; int expected__[] = { 2, 1 }; clock_t start__ = clock(); vector <int> received__ = FanFailure().getRange(vector <int>(capacities, capacities + (sizeof capacities / sizeof capacities[0])), minCooling); return verify_case(casenum__, vector <int>(expected__, expected__ + (sizeof expected__ / sizeof expected__[0])), received__, clock()-start__); } case 1: { int capacities[] = {8,5,6,7}; int minCooling = 22; int expected__[] = { 0, 0 }; clock_t start__ = clock(); vector <int> received__ = FanFailure().getRange(vector <int>(capacities, capacities + (sizeof capacities / sizeof capacities[0])), minCooling); return verify_case(casenum__, vector <int>(expected__, expected__ + (sizeof expected__ / sizeof expected__[0])), received__, clock()-start__); } case 2: { int capacities[] = {676, 11, 223, 413, 823, 122, 547, 187, 28}; int minCooling = 1000; int expected__[] = { 7, 2 }; clock_t start__ = clock(); vector <int> received__ = FanFailure().getRange(vector <int>(capacities, capacities + (sizeof capacities / sizeof capacities[0])), minCooling); return verify_case(casenum__, vector <int>(expected__, expected__ + (sizeof expected__ / sizeof expected__[0])), received__, clock()-start__); } case 3: { int capacities[] = {955, 96, 161, 259, 642, 242, 772, 369, 311, 785, 92, 991, 620, 394, 128, 774, 973, 94, 681, 771, 916, 373, 523, 100, 220, 993, 472, 798, 132, 361, 33, 362, 573, 624, 722, 520, 451, 231, 37, 921, 408, 170, 303, 559, 866, 412, 339, 757, 822, 192}; int minCooling = 3619; int expected__[] = { 46, 30 }; clock_t start__ = clock(); vector <int> received__ = FanFailure().getRange(vector <int>(capacities, capacities + (sizeof capacities / sizeof capacities[0])), minCooling); return verify_case(casenum__, vector <int>(expected__, expected__ + (sizeof expected__ / sizeof expected__[0])), received__, clock()-start__); } // custom cases /* case 4: { int capacities[] = ; int minCooling = ; int expected__[] = ; clock_t start__ = clock(); vector <int> received__ = FanFailure().getRange(vector <int>(capacities, capacities + (sizeof capacities / sizeof capacities[0])), minCooling); return verify_case(casenum__, vector <int>(expected__, expected__ + (sizeof expected__ / sizeof expected__[0])), received__, clock()-start__); }*/ /* case 5: { int capacities[] = ; int minCooling = ; int expected__[] = ; clock_t start__ = clock(); vector <int> received__ = FanFailure().getRange(vector <int>(capacities, capacities + (sizeof capacities / sizeof capacities[0])), minCooling); return verify_case(casenum__, vector <int>(expected__, expected__ + (sizeof expected__ / sizeof expected__[0])), received__, clock()-start__); }*/ /* case 6: { int capacities[] = ; int minCooling = ; int expected__[] = ; clock_t start__ = clock(); vector <int> received__ = FanFailure().getRange(vector <int>(capacities, capacities + (sizeof capacities / sizeof capacities[0])), minCooling); return verify_case(casenum__, vector <int>(expected__, expected__ + (sizeof expected__ / sizeof expected__[0])), received__, clock()-start__); }*/ default: return -1; } } } int main(int argc, char *argv[]) { if (argc == 1) { moj_harness::run_test(); } else { for (int i=1; i<argc; ++i) moj_harness::run_test(atoi(argv[i])); } } // END CUT HERE
30.396694
277
0.592577
emiliot
304ca01da15122c17a533bad4bf5c6afe013c09a
4,046
cpp
C++
OverEngine/src/OverEngine/Scene/Components.cpp
gitter-badger/OverEngine
7ade00f120ccc62804f1bfdeb34daf7e179d33bb
[ "MIT" ]
1
2020-11-24T06:13:34.000Z
2020-11-24T06:13:34.000Z
OverEngine/src/OverEngine/Scene/Components.cpp
gitter-badger/OverEngine
7ade00f120ccc62804f1bfdeb34daf7e179d33bb
[ "MIT" ]
null
null
null
OverEngine/src/OverEngine/Scene/Components.cpp
gitter-badger/OverEngine
7ade00f120ccc62804f1bfdeb34daf7e179d33bb
[ "MIT" ]
null
null
null
#include "pcheader.h" #include "Components.h" namespace OverEngine { SerializationContext* SpriteRendererComponent::Reflect() { static bool initialized = false; static SerializationContext ctx; if (!initialized) { initialized = true; if (!Serializer::GlobalEnumExists("TextureWrapping")) { Serializer::DefineGlobalEnum("TextureWrapping", { { 0, "None" }, { 1, "Repeat" }, { 2, "MirroredRepeat" }, { 3, "ClampToEdge" }, { 4, "ClampToBorder" } }); } if (!Serializer::GlobalEnumExists("TextureFiltering")) { Serializer::DefineGlobalEnum("TextureFiltering", { { 0, "None" }, { 1, "Nearest" }, { 2, "Linear" } }); } ctx.AddField(SerializableType::Float4, SERIALIZE_FIELD(SpriteRendererComponent, Tint)); ctx.AddField(SerializableType::Float2, SERIALIZE_FIELD(SpriteRendererComponent, Tiling)); ctx.AddField(SerializableType::Float2, SERIALIZE_FIELD(SpriteRendererComponent, Offset)); ctx.AddField(SerializableType::Bool, OffsetOf(&SpriteRendererComponent::Flip), "Flip.x"); ctx.AddField(SerializableType::Bool, OffsetOf(&SpriteRendererComponent::Flip) + sizeof(bool), "Flip.y"); ctx.AddEnumField(SerializableType::Int8Enum, "TextureWrapping", OffsetOf(&SpriteRendererComponent::Wrapping), "Wrapping.x"); ctx.AddEnumField(SerializableType::Int8Enum, "TextureWrapping", OffsetOf(&SpriteRendererComponent::Wrapping) + sizeof(TextureWrapping), "Wrapping.y"); ctx.AddEnumField(SerializableType::Int8Enum, "TextureFiltering", SERIALIZE_FIELD(SpriteRendererComponent, Filtering)); ctx.AddField(SerializableType::Float, SERIALIZE_FIELD(SpriteRendererComponent, AlphaClipThreshold)); ctx.AddField(SerializableType::Bool, OffsetOf(&SpriteRendererComponent::TextureBorderColor) + OffsetOf(&std::pair<bool, Color>::first), "IsOverridingTextureBorderColor"); ctx.AddField(SerializableType::Float4, OffsetOf(&SpriteRendererComponent::TextureBorderColor) + OffsetOf(&std::pair<bool, Color>::second), "TextureBorderColor"); } return &ctx; } SerializationContext* CameraComponent::Reflect() { static bool initialized = false; static SerializationContext ctx; if (!initialized) { initialized = true; auto& cameraReflection = *SceneCamera::Reflect(); for (const auto& elem : cameraReflection.Elements) { ctx.Elements.push_back(elem); (ctx.Elements.end() - 1)->Offset += OffsetOf(&CameraComponent::Camera); } } return &ctx; } SerializationContext* RigidBody2DComponent::Reflect() { static bool initialized = false; static SerializationContext ctx; if (!initialized) { initialized = true; if (!Serializer::GlobalEnumExists("RigidBody2DType")) { Serializer::DefineGlobalEnum("RigidBody2DType", { { 0, "Static" }, { 1, "Kinematic" }, { 2, "Dynamic" } }); } auto offset = OffsetOf(&RigidBody2DComponent::Initializer); ctx.AddEnumField(SerializableType::UInt8Enum, "RigidBody2DType", offset + OffsetOf(&RigidBody2DProps::Type), "Type"); ctx.AddField(SerializableType::Float2, offset + OffsetOf(&RigidBody2DProps::LinearVelocity), "LinearVelocity"); ctx.AddField(SerializableType::Float, offset + OffsetOf(&RigidBody2DProps::AngularVelocity), "AngularVelocity"); ctx.AddField(SerializableType::Float, offset + OffsetOf(&RigidBody2DProps::LinearDamping), "LinearDamping"); ctx.AddField(SerializableType::Float, offset + OffsetOf(&RigidBody2DProps::AngularDamping), "AngularDamping"); ctx.AddField(SerializableType::Bool, offset + OffsetOf(&RigidBody2DProps::AllowSleep), "AllowSleep"); ctx.AddField(SerializableType::Bool, offset + OffsetOf(&RigidBody2DProps::Awake), "Awake"); ctx.AddField(SerializableType::Bool, offset + OffsetOf(&RigidBody2DProps::FixedRotation), "FixedRotation"); ctx.AddField(SerializableType::Float, offset + OffsetOf(&RigidBody2DProps::GravityScale), "GravityScale"); ctx.AddField(SerializableType::Bool, offset + OffsetOf(&RigidBody2DProps::Bullet), "Bullet"); } return &ctx; } }
34.87931
173
0.726149
gitter-badger
304f206ea3efb19f7470a6edb5116fce5b896372
552
hpp
C++
src/Type.hpp
pawelprazak/jeff-native-agent
1554a8f69d0f0ca719ae5a794564e0e155b82545
[ "Apache-2.0" ]
7
2017-12-10T16:37:18.000Z
2021-01-19T06:33:23.000Z
src/Type.hpp
pawelprazak/jeff-native-agent
1554a8f69d0f0ca719ae5a794564e0e155b82545
[ "Apache-2.0" ]
3
2016-01-13T13:39:50.000Z
2016-02-19T18:08:38.000Z
src/Type.hpp
pawelprazak/jeff-native-agent
1554a8f69d0f0ca719ae5a794564e0e155b82545
[ "Apache-2.0" ]
5
2015-12-08T09:03:10.000Z
2019-07-29T16:13:13.000Z
#ifndef JEFF_NATIVE_AGENT_TYPE_HPP #define JEFF_NATIVE_AGENT_TYPE_HPP #include <jni.h> #include <jvmti.h> #include "Object.hpp" class Type : Object { public: Type(); Type(const std::string signature); virtual ~Type(); private: const std::string signature; public: static const Type *const from(jvmtiEnv &jvmti, JNIEnv &jni, std::string signature); static const Type *const from(jvmtiEnv &jvmti, JNIEnv &jni, char primitive_signature); const std::string getSignature() const; }; #endif //JEFF_NATIVE_AGENT_TYPE_HPP
19.034483
90
0.721014
pawelprazak
30513d53b2a1b4498bffe6aa1f399aff96408a17
657
hpp
C++
RainbowNoise/src/Library/ColorTransformer.hpp
1iyiwei/noise
0d1be2030518517199dff5c7e7514ee072037d59
[ "MIT" ]
24
2016-12-13T09:48:17.000Z
2022-01-13T03:24:45.000Z
RainbowNoise/src/Library/ColorTransformer.hpp
1iyiwei/noise
0d1be2030518517199dff5c7e7514ee072037d59
[ "MIT" ]
2
2019-03-29T06:44:41.000Z
2019-11-12T03:14:25.000Z
RainbowNoise/src/Library/ColorTransformer.hpp
1iyiwei/noise
0d1be2030518517199dff5c7e7514ee072037d59
[ "MIT" ]
8
2016-11-09T15:54:19.000Z
2021-04-08T14:04:17.000Z
/* ColorTransformer.hpp the base class for all color transfomers Li-Yi Wei 09/26/2009 */ #ifndef _COLOR_TRANSFORMER_HPP #define _COLOR_TRANSFORMER_HPP #include <vector> using namespace std; class ColorTransformer { public: typedef vector<float> Vector; // each basis vector component can be either 0 or a fixed positive value ColorTransformer(const int input_dimension, const vector<Vector> & output_basis); virtual ~ColorTransformer(void) = 0; virtual int Transform(const Vector & input_color, Vector & output_weight) const; protected: const int _input_dimension; const vector<Vector> _output_basis; }; #endif
19.323529
85
0.747336
1iyiwei
30534b9793b2207074a3d48925d19d11f017d241
142
cpp
C++
src/app/camera/camera.cpp
JonCG90/Goby
da1bfcea23c058427e6bad1c58f1cd5405fe4c5f
[ "MIT" ]
null
null
null
src/app/camera/camera.cpp
JonCG90/Goby
da1bfcea23c058427e6bad1c58f1cd5405fe4c5f
[ "MIT" ]
null
null
null
src/app/camera/camera.cpp
JonCG90/Goby
da1bfcea23c058427e6bad1c58f1cd5405fe4c5f
[ "MIT" ]
null
null
null
// // camera.cpp // Goby // // Created by Jonathan Graham on 8/18/19. // #include "camera.hpp" namespace Goby { } // namespace Goby
10.142857
42
0.598592
JonCG90
3054fbf14a79cbdc41baa36817c2127adc340035
12,908
cpp
C++
test/diamond_complex.cpp
rwols/yaml-archive
4afec73e557c15350c5e068c010f4e378edc95ef
[ "BSL-1.0" ]
1
2018-01-27T23:35:21.000Z
2018-01-27T23:35:21.000Z
test/diamond_complex.cpp
rwols/yaml-archive
4afec73e557c15350c5e068c010f4e378edc95ef
[ "BSL-1.0" ]
2
2019-08-17T05:37:36.000Z
2019-08-17T22:57:26.000Z
test/diamond_complex.cpp
rwols/yaml-archive
4afec73e557c15350c5e068c010f4e378edc95ef
[ "BSL-1.0" ]
1
2021-03-19T11:53:53.000Z
2021-03-19T11:53:53.000Z
#include "io_count_fixture.hpp" #include <boost/serialization/export.hpp> #include <boost/serialization/map.hpp> #include <boost/test/unit_test.hpp> #define NVP(name) BOOST_SERIALIZATION_NVP(name) using boost::serialization::make_nvp; namespace { // used to detect when base_diamond class is saved multiple times int diamond_save_count = 0; // used to detect when base_diamond class is loaded multiple times int diamond_load_count = 0; } class EX1Level1 { public: EX1Level1() : i(0) {} EX1Level1(int i) : i(i) { m[i] = "text"; } template <class Archive> void save(Archive& ar, const unsigned int /* file_version */) const { BOOST_TEST_MESSAGE("Saving EX1Level1"); ar << BOOST_SERIALIZATION_NVP(i); ar << BOOST_SERIALIZATION_NVP(m); ++diamond_save_count; } template <class Archive> void load(Archive& ar, const unsigned int /* file_version */) { BOOST_TEST_MESSAGE("Restoring EX1Level1"); ar >> BOOST_SERIALIZATION_NVP(i); ar >> BOOST_SERIALIZATION_NVP(m); ++diamond_load_count; } BOOST_SERIALIZATION_SPLIT_MEMBER() bool operator==(const EX1Level1& another) const { return i == another.i && m == another.m; } // make polymorphic by marking at least one function virtual virtual ~EX1Level1(){}; private: int i; std::map<int, std::string> m; }; // note: the default is for object tracking to be performed if and only // if and object of the corresponding class is anywhere serialized // through a pointer. In this example, that doesn't occur so // by default, the shared EX1Level1 object wouldn't normally be tracked. // This would leave to multiple save/load operation of the data in // this shared EX1Level1 class. This wouldn't cause an error, but it would // be a waste of time. So set the tracking behavior trait of the EX1Level1 // class to always track serialized objects of that class. This permits // the system to detect and elminate redundent save/load operations. // (It is concievable that this might someday be detected automatically // but for now, this is not done so we have to rely on the programmer // to specify this trait) BOOST_CLASS_TRACKING(EX1Level1, track_always) class EX1Level2_A : virtual public EX1Level1 { public: template <class Archive> void save(Archive& ar, const unsigned int /* file_version */) const { BOOST_TEST_MESSAGE("Saving EX1Level2_A"); ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level1); } template <class Archive> void load(Archive& ar, const unsigned int /* file_version */) { BOOST_TEST_MESSAGE("Restoring EX1Level2_A"); ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level1); } BOOST_SERIALIZATION_SPLIT_MEMBER() }; class EX1Level2_B : virtual public EX1Level1 { public: template <class Archive> void save(Archive& ar, const unsigned int /* file_version */) const { BOOST_TEST_MESSAGE("Saving EX1Level2_B"); ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level1); } template <class Archive> void load(Archive& ar, const unsigned int /* file_version */) { BOOST_TEST_MESSAGE("Restoring EX1Level2_B"); ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level1); } BOOST_SERIALIZATION_SPLIT_MEMBER() }; class EX1Level3_A : public EX1Level2_A, public EX1Level2_B { public: EX1Level3_A() {} EX1Level3_A(int i) : EX1Level1(i) {} template <class Archive> void save(Archive& ar, const unsigned int /* file_version */) const { BOOST_TEST_MESSAGE("Saving EX1Level3_A"); ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level2_A); ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level2_B); } template <class Archive> void load(Archive& ar, const unsigned int /* file_version */) { BOOST_TEST_MESSAGE("Restoring EX1Level3_A"); ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level2_A); ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level2_B); } BOOST_SERIALIZATION_SPLIT_MEMBER() }; class EX1Level3_B : public EX1Level2_A, public EX1Level2_B { public: EX1Level3_B() {} EX1Level3_B(int) {} template <class Archive> void save(Archive& ar, const unsigned int /* file_version */) const { BOOST_TEST_MESSAGE("Saving EX1Level3_B"); ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level2_A); ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level2_B); } template <class Archive> void load(Archive& ar, const unsigned int /* file_version */) { BOOST_TEST_MESSAGE("Restoring EX1Level3_B"); ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level2_A); ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level2_B); } BOOST_SERIALIZATION_SPLIT_MEMBER() }; class EX1Level4 : public EX1Level3_B { public: EX1Level4() {} EX1Level4(int i) : EX1Level1(i) {} template <class Archive> void save(Archive& ar, const unsigned int /* file_version */) const { BOOST_TEST_MESSAGE("Saving EX1Level4"); ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level3_B); } template <class Archive> void load(Archive& ar, const unsigned int /* file_version */) { BOOST_TEST_MESSAGE("Restoring EX1Level4"); ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX1Level3_B); } BOOST_SERIALIZATION_SPLIT_MEMBER() }; class EX2Level1 { public: EX2Level1() : i(0) {} EX2Level1(int i) : i(i) { m[i] = "text"; } template <class Archive> void save(Archive& ar, const unsigned int /* file_version */) const { BOOST_TEST_MESSAGE("Saving EX2Level1"); ar << BOOST_SERIALIZATION_NVP(i); ar << BOOST_SERIALIZATION_NVP(m); ++diamond_save_count; } template <class Archive> void load(Archive& ar, const unsigned int /* file_version */) { BOOST_TEST_MESSAGE("Restoring EX2Level1"); ar >> BOOST_SERIALIZATION_NVP(i); ar >> BOOST_SERIALIZATION_NVP(m); ++diamond_load_count; } BOOST_SERIALIZATION_SPLIT_MEMBER() bool operator==(const EX2Level1& another) const { return i == another.i && m == another.m; } // make polymorphic by marking at least one function virtual virtual ~EX2Level1(){}; private: int i; std::map<int, std::string> m; }; // note: the default is for object tracking to be performed if and only // if and object of the corresponding class is anywhere serialized // through a pointer. In this example, that doesn't occur so // by default, the shared EX2Level1 object wouldn't normally be tracked. // This would leave to multiple save/load operation of the data in // this shared EX2Level1 class. This wouldn't cause an error, but it would // be a waste of time. So set the tracking behavior trait of the EX2Level1 // class to always track serialized objects of that class. This permits // the system to detect and elminate redundent save/load operations. // (It is concievable that this might someday be detected automatically // but for now, this is not done so we have to rely on the programmer // to specify this trait) BOOST_CLASS_TRACKING(EX2Level1, track_always) class EX2Level2_A : virtual public EX2Level1 { public: template <class Archive> void save(Archive& ar, const unsigned int /* file_version */) const { BOOST_TEST_MESSAGE("Saving EX2Level2_A"); ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level1); } template <class Archive> void load(Archive& ar, const unsigned int /* file_version */) { BOOST_TEST_MESSAGE("Restoring EX2Level2_A"); ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level1); } BOOST_SERIALIZATION_SPLIT_MEMBER() }; class EX2Level2_B : virtual public EX2Level1 { public: template <class Archive> void save(Archive& ar, const unsigned int /* file_version */) const { BOOST_TEST_MESSAGE("Saving EX2Level2_B"); ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level1); } template <class Archive> void load(Archive& ar, const unsigned int /* file_version */) { BOOST_TEST_MESSAGE("Restoring EX2Level2_B"); ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level1); } BOOST_SERIALIZATION_SPLIT_MEMBER() }; class EX2Level3_A : public EX2Level2_A, public EX2Level2_B { public: EX2Level3_A() {} EX2Level3_A(int i) : EX2Level1(i) {} template <class Archive> void save(Archive& ar, const unsigned int /* file_version */) const { BOOST_TEST_MESSAGE("Saving EX2Level3_A"); ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level2_A); ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level2_B); } template <class Archive> void load(Archive& ar, const unsigned int /* file_version */) { BOOST_TEST_MESSAGE("Restoring EX2Level3_A"); ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level2_A); ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level2_B); } BOOST_SERIALIZATION_SPLIT_MEMBER() }; class EX2Level3_B : public EX2Level2_A, public EX2Level2_B { public: EX2Level3_B() {} EX2Level3_B(int i) : EX2Level1(i) {} template <class Archive> void save(Archive& ar, const unsigned int /* file_version */) const { BOOST_TEST_MESSAGE("Saving EX2Level3_B"); ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level2_A); ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level2_B); } template <class Archive> void load(Archive& ar, const unsigned int /* file_version */) { BOOST_TEST_MESSAGE("Restoring EX2Level3_B"); ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level2_A); ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level2_B); } BOOST_SERIALIZATION_SPLIT_MEMBER() }; class EX2Level4 : public EX2Level3_B { public: EX2Level4() {} EX2Level4(int i) : EX2Level1(i) {} template <class Archive> void save(Archive& ar, const unsigned int /* file_version */) const { BOOST_TEST_MESSAGE("Saving EX2Level4"); ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level3_B); } template <class Archive> void load(Archive& ar, const unsigned int /* file_version */) { BOOST_TEST_MESSAGE("Restoring EX2Level4"); ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(EX2Level3_B); } BOOST_SERIALIZATION_SPLIT_MEMBER() }; BOOST_CLASS_EXPORT(EX1Level4) BOOST_CLASS_EXPORT(EX1Level3_A) BOOST_CLASS_EXPORT(EX2Level3_A) BOOST_CLASS_EXPORT(EX2Level4) BOOST_FIXTURE_TEST_CASE(diamond_complex1, io_count_fixture) { diamond_save_count = 0; diamond_load_count = 0; const EX1Level3_A ex1L3a_save(3); const EX1Level1* ex1L1_save = &ex1L3a_save; { output() << make_nvp("ex1L1", ex1L1_save); } EX1Level1* ex1L1_load; { input() >> make_nvp("ex1L1", ex1L1_load); } BOOST_CHECK(1 == diamond_save_count); BOOST_CHECK(1 == diamond_load_count); BOOST_CHECK(*ex1L1_save == *ex1L1_load); } BOOST_FIXTURE_TEST_CASE(diamond_complex2, io_count_fixture) { diamond_save_count = 0; diamond_load_count = 0; const EX1Level4 ex1L4_save(3); const EX1Level1* ex1L1_save = &ex1L4_save; { output() << make_nvp("ex1L1", ex1L1_save); } EX1Level1* ex1L1_load; { input() >> make_nvp("ex1L1", ex1L1_load); } BOOST_CHECK(1 == diamond_save_count); BOOST_CHECK(1 == diamond_load_count); BOOST_CHECK(*ex1L1_save == *ex1L1_load); } BOOST_FIXTURE_TEST_CASE(diamond_complex3, io_count_fixture) { diamond_save_count = 0; diamond_load_count = 0; const EX2Level3_A ex2L3a_save(3); const EX2Level1* ex2L1_save = &ex2L3a_save; { output() << make_nvp("ex2L1", ex2L1_save); } EX2Level1* ex2L1_load; { input() >> make_nvp("ex2L1", ex2L1_load); } BOOST_CHECK(1 == diamond_save_count); BOOST_CHECK(1 == diamond_load_count); BOOST_CHECK(*ex2L1_save == *ex2L1_load); } BOOST_FIXTURE_TEST_CASE(diamond_complex4, io_count_fixture) { diamond_save_count = 0; diamond_load_count = 0; const EX2Level4 ex2L4_save(3); const EX2Level1* ex2L1_save = &ex2L4_save; { output() << make_nvp("ex2L1", ex2L1_save); } EX2Level1* ex2L1_load; { input() >> make_nvp("ex2L1", ex2L1_load); } // { // test_ostream ofs(testfile, TEST_STREAM_FLAGS); // test_oarchive oa(ofs); // oa << boost::serialization::make_nvp("ex2L1", ex2L1_save); // } // { // test_istream ifs(testfile, TEST_STREAM_FLAGS); // test_iarchive ia(ifs); // ia >> boost::serialization::make_nvp("ex2L1", ex2L1_load); // } BOOST_CHECK(1 == diamond_save_count); BOOST_CHECK(1 == diamond_load_count); BOOST_CHECK(*ex2L1_save == *ex2L1_load); }
29.47032
75
0.68353
rwols
305b0147381455dd98f6417efd6da68f5d915c91
2,275
cpp
C++
C++/Brute Force Password Cracker.cpp
CyanCoding/Brute-Force-Password-Cracker
dcc753618e1de8294b118721adca35f87eb2bfe7
[ "MIT" ]
30
2019-02-07T23:41:24.000Z
2022-03-13T15:39:37.000Z
C++/Brute Force Password Cracker.cpp
CyanCoding/Brute-Force-Password-Cracker
dcc753618e1de8294b118721adca35f87eb2bfe7
[ "MIT" ]
3
2020-09-22T19:55:16.000Z
2021-10-01T19:48:13.000Z
C++/Brute Force Password Cracker.cpp
CyanCoding/Brute-Force-Password-Cracker
dcc753618e1de8294b118721adca35f87eb2bfe7
[ "MIT" ]
28
2018-06-08T15:27:03.000Z
2022-02-07T05:40:29.000Z
#include <iostream> #include <string> // to_string #include <iomanip> // setprecision using namespace std; bool stop = false; long long amount = 0; string password; clock_t start; const char Alphabet[62] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U','V', 'W', 'X', 'Y', 'Z' }; string separateWithCommas(long long num) { string s = to_string(num); int thousands = s.length() - 3; while (thousands > 0) { s.insert(thousands, ","); thousands -= 3; } return s; } void inline crack(unsigned int length, string current) { if (length == 0 && stop == false) { amount++; if (amount % 10000000 == 0) { cout << '\r' << separateWithCommas(amount) << " - " << current << " - " << separateWithCommas(amount / ((float)(clock() - start) / CLOCKS_PER_SEC)) << " p/sec"; cout.flush(); } if (current == password) { stop = true; } return; } if (stop == false) { for (unsigned int i = 0; i < 62; i++) { crack(length - 1, current + Alphabet[i]); } } } int main() { // Greet the user cout << "Welcome to CyanCoding's Brute Force Password Cracker!" << endl << endl; cout << "What do you want your password to be? > "; cin >> password; cout << "\rAttempting to crack " << password << "..." << endl; start = clock(); while (stop == false) { static unsigned int pwLength = 1; crack(pwLength, ""); pwLength++; if (stop == true) { break; } } cout << "\rCyanCoding's C++ BFPC cracked the password \"" << password << "\" in " << separateWithCommas(amount) << " attempts and " << setprecision(2) << fixed << (float)(clock() - start) / CLOCKS_PER_SEC << " seconds." << endl << endl << "That's about " << setprecision(0) << separateWithCommas(amount / ((float)(clock() - start) / CLOCKS_PER_SEC)) << " passwords per second!" << endl << endl; return 0; }
30.333333
311
0.487912
CyanCoding
305e00e4be433b098a54686754f91b0d53e16b0f
336
hpp
C++
include/mil/utils/index_sequence.hpp
vhapiak/meta_info_lib
677984960028c6ef0f2b462c2f6ae8ac7fc714ea
[ "MIT" ]
null
null
null
include/mil/utils/index_sequence.hpp
vhapiak/meta_info_lib
677984960028c6ef0f2b462c2f6ae8ac7fc714ea
[ "MIT" ]
null
null
null
include/mil/utils/index_sequence.hpp
vhapiak/meta_info_lib
677984960028c6ef0f2b462c2f6ae8ac7fc714ea
[ "MIT" ]
null
null
null
#pragma once #include <cstddef> #include "detail/index_sequence.hpp" namespace mil { namespace utils { template <std::size_t... Idx> using index_sequnece = detail::index_sequnece<Idx...>; template <std::size_t N> using make_index_sequence = typename detail::make_index_sequence<N>::type; } // namespace utils } // namespace mil
18.666667
74
0.738095
vhapiak
305e1854791154a3b617f08dda01e2fada435e2f
4,627
cpp
C++
src/platform/mbino_critical.cpp
tkem/mbino
6fa2251048a8409170602049f29b231c67f5b8fe
[ "Apache-2.0" ]
10
2017-10-06T14:27:03.000Z
2021-11-08T11:18:58.000Z
src/platform/mbino_critical.cpp
tkem/mbino
6fa2251048a8409170602049f29b231c67f5b8fe
[ "Apache-2.0" ]
49
2017-08-12T13:45:55.000Z
2018-12-22T21:35:54.000Z
src/platform/mbino_critical.cpp
tkem/mbino
6fa2251048a8409170602049f29b231c67f5b8fe
[ "Apache-2.0" ]
2
2018-07-15T11:06:47.000Z
2019-05-25T01:10:32.000Z
/* mbino - mbed APIs for the Arduino platform * Copyright (c) 2017, 2018 Thomas Kemmer * * mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "platform/mbed_critical.h" #include "platform/mbed_toolchain.h" #include "hal/critical_section_api.h" // mbino limits this to 8 bit for atomic access on AVR, and since 255 // recursive invocations should be enough... static volatile uint8_t critical_section_reentrancy_counter = 0; // no matching Arduino API, therefore moved to target //bool core_util_are_interrupts_enabled(void); //bool core_util_is_isr_active(void); bool core_util_in_critical_section(void) { return hal_in_critical_section(); } void core_util_critical_section_enter(void) { hal_critical_section_enter(); ++critical_section_reentrancy_counter; } void core_util_critical_section_exit(void) { if (--critical_section_reentrancy_counter == 0) { hal_critical_section_exit(); } } // TODO: MBED_WEAK doesn't work for symbols redefined in the same library - move all to HAL? template<typename T> static bool core_util_atomic_cas(volatile T* ptr, T* expectedCurrentValue, T desiredValue) { bool success; T currentValue; core_util_critical_section_enter(); currentValue = *ptr; if (currentValue == *expectedCurrentValue) { *ptr = desiredValue; success = true; } else { *expectedCurrentValue = currentValue; success = false; } core_util_critical_section_exit(); return success; } template<typename T, typename U> static T core_util_atomic_incr(volatile T* valuePtr, U delta) { T newValue; core_util_critical_section_enter(); newValue = *valuePtr + delta; *valuePtr = newValue; core_util_critical_section_exit(); return newValue; } template<typename T, typename U> static T core_util_atomic_decr(volatile T* valuePtr, U delta) { T newValue; core_util_critical_section_enter(); newValue = *valuePtr - delta; *valuePtr = newValue; core_util_critical_section_exit(); return newValue; } MBED_WEAK bool core_util_atomic_cas_u8(volatile uint8_t* ptr, uint8_t* expectedCurrentValue, uint8_t desiredValue) { return core_util_atomic_cas(ptr, expectedCurrentValue, desiredValue); } MBED_WEAK bool core_util_atomic_cas_u16(volatile uint16_t* ptr, uint16_t* expectedCurrentValue, uint16_t desiredValue) { return core_util_atomic_cas(ptr, expectedCurrentValue, desiredValue); } MBED_WEAK bool core_util_atomic_cas_u32(volatile uint32_t* ptr, uint32_t* expectedCurrentValue, uint32_t desiredValue) { return core_util_atomic_cas(ptr, expectedCurrentValue, desiredValue); } MBED_WEAK bool core_util_atomic_cas_ptr(void* volatile* ptr, void** expectedCurrentValue, void* desiredValue) { return core_util_atomic_cas(ptr, expectedCurrentValue, desiredValue); } MBED_WEAK uint8_t core_util_atomic_incr_u8(volatile uint8_t* valuePtr, uint8_t delta) { return core_util_atomic_incr(valuePtr, delta); } MBED_WEAK uint16_t core_util_atomic_incr_u16(volatile uint16_t* valuePtr, uint16_t delta) { return core_util_atomic_incr(valuePtr, delta); } MBED_WEAK uint32_t core_util_atomic_incr_u32(volatile uint32_t* valuePtr, uint32_t delta) { return core_util_atomic_incr(valuePtr, delta); } MBED_WEAK void* core_util_atomic_incr_ptr(void* volatile* valuePtr, ptrdiff_t delta) { return core_util_atomic_incr(reinterpret_cast<char* volatile*>(valuePtr), delta); } MBED_WEAK uint8_t core_util_atomic_decr_u8(volatile uint8_t* valuePtr, uint8_t delta) { return core_util_atomic_decr(valuePtr, delta); } MBED_WEAK uint16_t core_util_atomic_decr_u16(volatile uint16_t* valuePtr, uint16_t delta) { return core_util_atomic_decr(valuePtr, delta); } MBED_WEAK uint32_t core_util_atomic_decr_u32(volatile uint32_t* valuePtr, uint32_t delta) { return core_util_atomic_decr(valuePtr, delta); } MBED_WEAK void* core_util_atomic_decr_ptr(void* volatile* valuePtr, ptrdiff_t delta) { return core_util_atomic_decr(reinterpret_cast<char* volatile*>(valuePtr), delta); }
30.846667
118
0.770478
tkem
30608a5bc5e5b05a736a10130fb51f16f51e84ee
3,614
cxx
C++
FIT/FITcalib/AliFITCalibTimeEq.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
FIT/FITcalib/AliFITCalibTimeEq.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
FIT/FITcalib/AliFITCalibTimeEq.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ /////////////////////////////////////////////////////////////////////////////// // // // class for FIT calibration TM-AC-AM_6-02-2006 // equalize time shift for each time CFD channel // // /////////////////////////////////////////////////////////////////////////////// #include "AliFITCalibTimeEq.h" #include "AliLog.h" #include <TFile.h> #include <TMath.h> #include <TF1.h> #include <TSpectrum.h> #include <TProfile.h> #include <iostream> ClassImp(AliFITCalibTimeEq) //________________________________________________________________ AliFITCalibTimeEq::AliFITCalibTimeEq():TNamed() { // for(Int_t i=0; i<200; i++) { fTimeEq[i] = 0; // Time Equalized for OCDB fCFDvalue[i] = 0; } } //________________________________________________________________ AliFITCalibTimeEq::AliFITCalibTimeEq(const char* name):TNamed() { //constructor TString namst = "Calib_"; namst += name; SetName(namst.Data()); SetTitle(namst.Data()); for(Int_t i=0; i<200; i++) { fTimeEq[i] = 0; // Time Equalized for OCDB fCFDvalue[i] = 0; } } //________________________________________________________________ AliFITCalibTimeEq::AliFITCalibTimeEq(const AliFITCalibTimeEq& calibda):TNamed(calibda) { // copy constructor SetName(calibda.GetName()); SetTitle(calibda.GetName()); ((AliFITCalibTimeEq &) calibda).Copy(*this); } //________________________________________________________________ AliFITCalibTimeEq &AliFITCalibTimeEq::operator =(const AliFITCalibTimeEq& calibda) { // assignment operator SetName(calibda.GetName()); SetTitle(calibda.GetName()); if (this != &calibda) (( AliFITCalibTimeEq &) calibda).Copy(*this); return *this; } //________________________________________________________________ AliFITCalibTimeEq::~AliFITCalibTimeEq() { // // destrictor } //________________________________________________________________ void AliFITCalibTimeEq::Reset() { //reset values memset(fCFDvalue,0,200*sizeof(Float_t)); memset(fTimeEq,1,200*sizeof(Float_t)); } //________________________________________________________________ void AliFITCalibTimeEq::Print(Option_t*) const { // print time values printf("\n ---- PM Arrays ----\n\n"); printf(" Time delay CFD \n"); for (Int_t i=0; i<200; i++) printf(" CFD %f diff %f \n",fCFDvalue[i],fTimeEq[i]); }
31.982301
91
0.57969
AllaMaevskaya
30657cd12bea49e681cd2756206affac7f565829
4,202
cpp
C++
src/drive.cpp
sizeofvoid/openbsdisks2
4bc053a9d15f4e367a9f7601e7e506cd3d72bd7c
[ "BSD-3-Clause" ]
7
2021-05-13T07:43:10.000Z
2022-01-09T12:18:48.000Z
src/drive.cpp
sizeofvoid/openbsdisks2
4bc053a9d15f4e367a9f7601e7e506cd3d72bd7c
[ "BSD-3-Clause" ]
null
null
null
src/drive.cpp
sizeofvoid/openbsdisks2
4bc053a9d15f4e367a9f7601e7e506cd3d72bd7c
[ "BSD-3-Clause" ]
null
null
null
/* Copyright 2016 Gleb Popov <6yearold@gmail.com> 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. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <fcntl.h> #include <sys/cdio.h> #include <sys/ioctl.h> #include <QDBusConnection> #include <QDBusConnectionInterface> #include <QDBusObjectPath> #include <QUuid> #include "bsdisks.h" #include "drive.h" Drive::Drive(const QString& devName) : QDBusContext() , m_deviceName(devName) , m_dbusPath(QDBusObjectPath(UDisksDrives + devName)) { } const QDBusObjectPath Drive::getDbusPath() const { return m_dbusPath; } QString Drive::getDeviceName() const { return m_deviceName; } void Drive::setVendor(const QString& vendor) { m_Vendor = vendor; } void Drive::setRemovable(bool r) { isRemovable = r; } void Drive::addBlock(const TBlock& block) { qDebug() << "Disk " << getDeviceName() << " add block: " << block->getName(); m_blocks.push_back(block); } const TBlockVec Drive::getBlocks() const { return m_blocks; } void Drive::Eject(const QVariantMap& options) { if (!optical()) return; int fd = open((QStringLiteral("/dev/") + getDeviceName()).toLocal8Bit().constData(), O_RDONLY); if (fd < 0 && errno != ENXIO) { QString errorMessage = ::strerror(errno); connection().send( message().createErrorReply("org.freedesktop.UDisks2.Error.Failed", errorMessage)); qDebug() << "Eject failed: " << errorMessage; return; } ::ioctl(fd, CDIOCALLOW); int rc = ::ioctl(fd, CDIOCEJECT); if (rc < 0) { QString errorMessage = ::strerror(errno); connection().send( message().createErrorReply("org.freedesktop.UDisks2.Error.Failed", errorMessage)); qDebug() << "Eject failed: " << errorMessage; return; } } Configuration Drive::configuration() const { Configuration c; return c; } bool Drive::optical() const { return getDeviceName().startsWith("cd"); } QStringList Drive::mediaCompatibility() const { if (optical()) return {QStringLiteral("optical_cd")}; return QStringList(); } QString Drive::vendor() const { return m_Vendor; } qulonglong Drive::driveSize() const { return size; } void Drive::setId(const QString& id) { m_Id = id; } QString Drive::id() const { return m_Id; } QString Drive::serial() const { return m_Duid.toString(); } void Drive::setSize(qulonglong s) { size = s; } void Drive::setDuid(const QUuid& duid) { m_Duid = duid; } bool Drive::ejectable() const { return removable(); } bool Drive::removable() const { return optical() || isRemovable; } bool Drive::mediaRemovable() const { return optical() || removable(); } QString Drive::connectionBus() const { return QString(); }
24.011429
99
0.694669
sizeofvoid
3065e0634838c6a4728f0c0528a5fc7a269dc115
675
cpp
C++
src/cbtCore/Rendering/Buffer/cbtBufferLayout.cpp
TypeDefinition/cbtEngine
9ddbc6a5436cc31efc475f6d1c37fade4a003c0d
[ "MIT" ]
null
null
null
src/cbtCore/Rendering/Buffer/cbtBufferLayout.cpp
TypeDefinition/cbtEngine
9ddbc6a5436cc31efc475f6d1c37fade4a003c0d
[ "MIT" ]
null
null
null
src/cbtCore/Rendering/Buffer/cbtBufferLayout.cpp
TypeDefinition/cbtEngine
9ddbc6a5436cc31efc475f6d1c37fade4a003c0d
[ "MIT" ]
null
null
null
// Include CBT #include "cbtBufferLayout.h" NS_CBT_BEGIN cbtU32 GetByteSize(cbtBufferDataType _dataType) { switch (_dataType) { case cbtBufferDataType::CBT_S8: case cbtBufferDataType::CBT_U8: return 1; case cbtBufferDataType::CBT_S16: case cbtBufferDataType::CBT_U16: case cbtBufferDataType::CBT_F16: return 2; case cbtBufferDataType::CBT_S32: case cbtBufferDataType::CBT_U32: case cbtBufferDataType::CBT_F32: return 4; case cbtBufferDataType::CBT_F64: return 8; default: return 0; } } NS_CBT_END
24.107143
51
0.6
TypeDefinition
3068245fb2012c6185a50f5ed6d9c464cbf886c1
1,717
cpp
C++
control_app/joystick.cpp
houcy/wall-e-1
b159d05b0afa343cb161f60ec98974bc2f063afd
[ "MIT" ]
1
2021-05-05T14:11:03.000Z
2021-05-05T14:11:03.000Z
control_app/joystick.cpp
houcy/wall-e-1
b159d05b0afa343cb161f60ec98974bc2f063afd
[ "MIT" ]
null
null
null
control_app/joystick.cpp
houcy/wall-e-1
b159d05b0afa343cb161f60ec98974bc2f063afd
[ "MIT" ]
null
null
null
#include "joystick.h" #include "log.h" #include <QTimer> // Linux headers #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> /* Standard C++ API does not allow to read char device file in unblocking mode, * so used Linux API */ #define JOYSTICK_FILE "/dev/input/js0" #define READ_DATA_INTERVAL 50 Joystick::Joystick(QObject *parent) : QObject(parent) { if ((jsFile = open(JOYSTICK_FILE, O_RDONLY | O_NONBLOCK, S_IRUSR | S_IRGRP | S_IROTH)) == -1) { critical("Failed to open joystick file %d: %s", errno, strerror(errno)); return; } readDataTimer = new QTimer(this); connect(readDataTimer, SIGNAL(timeout()), this, SLOT(slotReadData())); readDataTimer->setInterval(READ_DATA_INTERVAL); readDataTimer->start(); } Joystick::~Joystick() { if (jsFile != -1) { if (close(jsFile)) critical("Failed to close joystick file"); } } void Joystick::slotReadData() { int n; while((n = read(jsFile, &jsEvent, sizeof(jsEvent))) == sizeof(jsEvent)) { switch (jsEvent.type) { case JS_EVENT_TYPE_AXIS: switch (jsEvent.number) { case JS_EVENT_AXIS_X_NS: case JS_EVENT_AXIS_X_WE: emit joystickEvent(jsEvent.type, jsEvent.number, jsEvent.value); default: break; } break; case JS_EVENT_TYPE_BUTTON: case JS_EVENT_TYPE_INIT: default: break; } } if (!n || (n > 0 && n != sizeof(jsEvent)) || (n == -1 && errno != EAGAIN)) { critical("Failed to read joystick file"); return; } }
22.893333
80
0.576005
houcy
3069a83b76d7aa1d62e769e3c75bcc32085ad3e2
2,168
cpp
C++
src/sorts/CombSort/comb_sort.cpp
delightedok/TGSToolkits
7570378fde1f3045a545c293fddb275143701114
[ "MIT" ]
null
null
null
src/sorts/CombSort/comb_sort.cpp
delightedok/TGSToolkits
7570378fde1f3045a545c293fddb275143701114
[ "MIT" ]
null
null
null
src/sorts/CombSort/comb_sort.cpp
delightedok/TGSToolkits
7570378fde1f3045a545c293fddb275143701114
[ "MIT" ]
null
null
null
#include "../../comms/comm_headers.h" #include <sorts/comb_sort.h> #define THIS_FILE "comb_sort.cpp" #define LOG_TAG "SORTS-COMB" TGSTK_EXPORT SortCombObject::SortCombObject(SortVTable & vTable, float factor) : SortObject(vTable) { this->factor = factor; if (factor <= 1) { mlog_e(LOG_TAG, THIS_FILE, "Param[factor](%d) should be larger than 1. Now set to 1.3F.", factor); this->factor = 1.3F; } } int SortCombObject::onSort(void * objs, int elemSize, int size, SortType type) { COMM_ASSERT_RETURN(objs && size > 0, -1); int ret = 0; int rc = 0; int i = 0; int hasExchange = 0; int gap = size; while (gap > 1 || hasExchange) { hasExchange = 0; gap = gap > 1 ? (int)((float)gap / this->factor) : gap; for (i = gap; i < size; i++) { rc = this->onCompare(COMM_ARRAY_ELEM(objs, elemSize, i - gap), COMM_ARRAY_ELEM(objs, elemSize, i)); switch (type) { case emSortDesc: { if (rc < 0) { this->onExchange( COMM_ARRAY_ELEM(objs, elemSize, i - gap), COMM_ARRAY_ELEM(objs, elemSize, i)); hasExchange = 1; } } break; case emSortAsc: { if (rc > 0) { this->onExchange( COMM_ARRAY_ELEM(objs, elemSize, i - gap), COMM_ARRAY_ELEM(objs, elemSize, i)); hasExchange = 1; } } break; default: { ret = -1; mlog_e(LOG_TAG, THIS_FILE, "Invalid Param[type]: %d\n", type); } break; } } } return ret; }
31.42029
112
0.398985
delightedok
306f23f5921876eb6705efe778fd911d6c548e85
294
cpp
C++
FruitManageSystem/Fruit.cpp
grahamitdev/FruitManageSystem
c3c9effaa84ad1d900767a8bc4aad9b35a2473fe
[ "Apache-2.0" ]
1
2021-02-17T12:33:12.000Z
2021-02-17T12:33:12.000Z
FruitManageSystem/Fruit.cpp
grahamitdev/FruitManageSystem
c3c9effaa84ad1d900767a8bc4aad9b35a2473fe
[ "Apache-2.0" ]
null
null
null
FruitManageSystem/Fruit.cpp
grahamitdev/FruitManageSystem
c3c9effaa84ad1d900767a8bc4aad9b35a2473fe
[ "Apache-2.0" ]
3
2018-02-07T01:58:30.000Z
2021-12-16T03:17:24.000Z
#include "Fruit.h" Fruit::Fruit(const QString &name, const double &price, const double &num) :name(name),price(price),num(num) { } QString Fruit::getName() const { return name; } double Fruit::getPrice() const { return price; } double Fruit::getNum() const { return num; }
12.782609
73
0.656463
grahamitdev
307373a68a63c0a7466f75495fb6cfd8d2e2b32e
4,271
cpp
C++
test/lab/test_client.cpp
brigid-jp/brigid-core
edd7e1cdbfeb1babbc8fcf39c71c5d90d0137589
[ "MIT" ]
6
2019-12-24T01:55:57.000Z
2021-01-18T02:51:28.000Z
test/lab/test_client.cpp
brigid-jp/brigid-core
edd7e1cdbfeb1babbc8fcf39c71c5d90d0137589
[ "MIT" ]
11
2021-09-16T12:58:45.000Z
2021-12-08T08:14:58.000Z
test/lab/test_client.cpp
brigid-jp/brigid-core
edd7e1cdbfeb1babbc8fcf39c71c5d90d0137589
[ "MIT" ]
null
null
null
// Copyright (c) 2021 <dev@brigid.jp> // This software is released under the MIT License. // https://opensource.org/licenses/mit-license.php #include <brigid/error.hpp> #include "test_common.hpp" #include <exception> #include <iomanip> #include <iostream> #include <vector> #include <netinet/in.h> #include <netinet/tcp.h> #include <sys/socket.h> #include <errno.h> #include <time.h> #include <unistd.h> namespace brigid { namespace { void run(const char* node, const char* serv) { int fd = -1; try { std::cout << std::setfill('0'); timer t; t.start(); addrinfo_t ai = getaddrinfo(node, serv, AI_ADDRCONFIG, AF_INET, SOCK_STREAM); t.stop(); t.print("getaddrinfo"); t.start(); fd = socket(ai->ai_family, ai->ai_socktype, 0); if (fd == -1) { throw BRIGID_RUNTIME_ERROR(std::generic_category().message(errno), make_error_code("error number", errno)); } t.stop(); t.print("socket"); { int v = 1; if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &v, sizeof(v)) == -1) { throw BRIGID_RUNTIME_ERROR(std::generic_category().message(errno), make_error_code("error number", errno)); } } t.start(); if (connect(fd, ai->ai_addr, ai->ai_addrlen) == -1) { throw BRIGID_RUNTIME_ERROR(std::generic_category().message(errno), make_error_code("error number", errno)); } t.stop(); t.print("connect"); t.start(); { int v = 0; socklen_t size = sizeof(v); if (getsockopt(fd, SOL_SOCKET, SO_SNDBUF, &v, &size) == -1) { throw BRIGID_RUNTIME_ERROR(std::generic_category().message(errno), make_error_code("error number", errno)); } std::cout << "SOL_SOCKET SO_SNDBUF " << v << "\n"; std::string buffer = "GET / HTTP/1.0\r\n\r\n"; if (send(fd, buffer.data(), buffer.size(), 0) == -1) { throw BRIGID_RUNTIME_ERROR(std::generic_category().message(errno), make_error_code("error number", errno)); } } t.stop(); t.print("send"); t.start(); { std::vector<char> buffer(4096); if (send(fd, buffer.data(), buffer.size(), 0) == -1) { throw BRIGID_RUNTIME_ERROR(std::generic_category().message(errno), make_error_code("error number", errno)); } } t.stop(); t.print("send"); t.start(); { if (shutdown(fd, SHUT_WR) == -1) { throw BRIGID_RUNTIME_ERROR(std::generic_category().message(errno), make_error_code("error number", errno)); } } t.stop(); t.print("shutdown"); t.start(); { std::vector<char> buffer(1); while (true) { { int v = 0; socklen_t size = sizeof(v); if (getsockopt(fd, SOL_SOCKET, SO_RCVBUF, &v, &size) == -1) { throw BRIGID_RUNTIME_ERROR(std::generic_category().message(errno), make_error_code("error number", errno)); } std::cout << "SOL_SOCKET SO_RCVBUF " << v << "\n"; } ssize_t size = read(fd, buffer.data(), buffer.size()); if (size > 0) { std::cout << "read " << size << "\n"; } else if (size == 0) { std::cout << "closed\n"; break; } else { int code = errno; throw BRIGID_RUNTIME_ERROR(std::generic_category().message(code), make_error_code("error number", code)); } struct timespec timeout = {}; timeout.tv_nsec = 100 * 1000 * 1000; nanosleep(&timeout, nullptr); } } t.stop(); t.print("read"); close(fd); } catch (...) { if (fd != -1) { close(fd); } throw; } } } } int main(int ac, char* av[]) { try { if (ac < 3) { std::cout << "usage: " << av[0] << " node serv\n"; return 1; } brigid::run(av[1], av[2]); return 0; } catch (const std::exception& e) { std::cerr << e.what() << "\n"; } return 1; }
29.054422
123
0.510887
brigid-jp
30777d7ac5ce4310015b27a34498b181e760e9f1
1,068
cpp
C++
cpp/UniqueBinarySearchTreesII.cpp
thinksource/code_interview
08be992240508b73894eaf6b8c025168fd19df19
[ "Apache-2.0" ]
12
2015-03-12T03:27:26.000Z
2021-03-11T09:26:16.000Z
cpp/UniqueBinarySearchTreesII.cpp
thinksource/code_interview
08be992240508b73894eaf6b8c025168fd19df19
[ "Apache-2.0" ]
null
null
null
cpp/UniqueBinarySearchTreesII.cpp
thinksource/code_interview
08be992240508b73894eaf6b8c025168fd19df19
[ "Apache-2.0" ]
11
2015-01-28T16:45:40.000Z
2017-03-28T20:01:38.000Z
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<TreeNode *> generateTrees(int n) { vector<TreeNode *> v; generateTrees(1,n,v); return v; } void generateTrees(int start, int end, vector<TreeNode *>& trees) { if(start>end) { trees.push_back(NULL); return; } for(int i=start;i<=end;i++) { vector<TreeNode *> leftTrees; generateTrees(start, i-1, leftTrees); vector<TreeNode *> rightTrees; generateTrees(i+1, end, rightTrees); for(int j=0;j<leftTrees.size();j++) { for(int k=0;k<rightTrees.size();k++) { TreeNode* t = new TreeNode(i); t->left = leftTrees[j]; t->right = rightTrees[k]; trees.push_back(t); } } } } };
27.384615
71
0.476592
thinksource
307aff939a124a82f61ec044b639cc285b500a99
2,296
hxx
C++
opencascade/StdSelect_FaceFilter.hxx
valgur/OCP
2f7d9da73a08e4ffe80883614aedacb27351134f
[ "Apache-2.0" ]
117
2020-03-07T12:07:05.000Z
2022-03-27T07:35:22.000Z
opencascade/StdSelect_FaceFilter.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
66
2019-12-20T16:07:36.000Z
2022-03-15T21:56:10.000Z
opencascade/StdSelect_FaceFilter.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
76
2020-03-16T01:47:46.000Z
2022-03-21T16:37:07.000Z
// Created on: 1996-03-08 // Created by: Robert COUBLANC // Copyright (c) 1996-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _StdSelect_FaceFilter_HeaderFile #define _StdSelect_FaceFilter_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <StdSelect_TypeOfFace.hxx> #include <SelectMgr_Filter.hxx> #include <Standard_Boolean.hxx> #include <TopAbs_ShapeEnum.hxx> class SelectMgr_EntityOwner; class StdSelect_FaceFilter; DEFINE_STANDARD_HANDLE(StdSelect_FaceFilter, SelectMgr_Filter) //! A framework to define a filter to select a specific type of face. //! The types available include: //! - any face //! - a planar face //! - a cylindrical face //! - a spherical face //! - a toroidal face //! - a revol face. class StdSelect_FaceFilter : public SelectMgr_Filter { public: //! Constructs a face filter object defined by the type of face aTypeOfFace. Standard_EXPORT StdSelect_FaceFilter(const StdSelect_TypeOfFace aTypeOfFace); //! Sets the type of face aNewType. aNewType is to be highlighted in selection. Standard_EXPORT void SetType (const StdSelect_TypeOfFace aNewType); //! Returns the type of face to be highlighted in selection. Standard_EXPORT StdSelect_TypeOfFace Type() const; Standard_EXPORT virtual Standard_Boolean IsOk (const Handle(SelectMgr_EntityOwner)& anobj) const Standard_OVERRIDE; Standard_EXPORT virtual Standard_Boolean ActsOn (const TopAbs_ShapeEnum aStandardMode) const Standard_OVERRIDE; DEFINE_STANDARD_RTTIEXT(StdSelect_FaceFilter,SelectMgr_Filter) protected: private: StdSelect_TypeOfFace mytype; }; #endif // _StdSelect_FaceFilter_HeaderFile
27.011765
117
0.77831
valgur
307e4dcc379f086608ed6971559fccc25010eecc
2,928
cpp
C++
Graphs/MazeRunner.cpp
TheArquitect/Classic-Algorithms
29ef20af79346142df8c76dd266e728b5e12cd10
[ "BSD-2-Clause" ]
1
2019-09-30T17:47:41.000Z
2019-09-30T17:47:41.000Z
Graphs/MazeRunner.cpp
TheArquitect/Classic-Algorithms
29ef20af79346142df8c76dd266e728b5e12cd10
[ "BSD-2-Clause" ]
null
null
null
Graphs/MazeRunner.cpp
TheArquitect/Classic-Algorithms
29ef20af79346142df8c76dd266e728b5e12cd10
[ "BSD-2-Clause" ]
null
null
null
/** File : MazeRunner.cpp Author : Menashe Rosemberg Created : 2019.04.02 Version: 20190402.12 Check all spaces reachable in a maze from a random start place BSD License Copyright (c) 2019 TheArquitect (Menashe Rosemberg) rosemberg@ymail.com 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 "MazeRunner.h" #include "MazeRunner_Running.h" void Run_MazeRunner_DFS() { MazeMap Maze = { "WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW", "W WWW W W W W", "W WW W W WWW WWWW WWWWW W WWWW W", "W W W W W W W W W", "WWWWWWWWWW W WWWW W W W", "W W W W WWWWWW W", "WWWWWW W WW W W WWWW WWW W", "W W W W W WWWW W W W W WWWW W", "W WWWW W W W W W W W W", "W W W W WWWW W W WWW WWWW W", "WWWWWWWWWWWWWWWWWWW W W W W W W", "W WW W W", "W WWWWWWWWWWWWWWWWW WWWWWWWWWWW W W", "W W WWWWWW W W W", "W W WWWWWWWWWWWWW W W WWWWWWWWW W W", "W W W WW W W", "W WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW W", "W W", "WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW" }; RunRunner(Maze); }
49.627119
83
0.563525
TheArquitect
3082d2b7b359e5c3f2df5d7dd1534c7b330b0f79
1,299
cpp
C++
microcontroller/lib/Timer/Timer.cpp
robfors/nut_sorter-microcontroller
bc909fdaa1cc856341fe16773aefe9f1af773c83
[ "Apache-2.0" ]
null
null
null
microcontroller/lib/Timer/Timer.cpp
robfors/nut_sorter-microcontroller
bc909fdaa1cc856341fe16773aefe9f1af773c83
[ "Apache-2.0" ]
null
null
null
microcontroller/lib/Timer/Timer.cpp
robfors/nut_sorter-microcontroller
bc909fdaa1cc856341fe16773aefe9f1af773c83
[ "Apache-2.0" ]
null
null
null
#include "Timer.h" // // public // Timer::Timer(Units units) { _default_length = 0; _length = 0; _units = units; _is_active = false; _start_time = 0; } Timer::Timer(unsigned long default_length, Units units) { _default_length = default_length; _length = 0; _units = units; _is_active = false; _start_time = 0; } boolean Timer::is_complete() { return !is_running(); } boolean Timer::is_running() { _update(); return _is_active; } void Timer::start() { _start_time = _current_time(); // save time first if (_default_length == 0) { _start_time = 0; return; } _length = _default_length; _is_active = true; } void Timer::start(unsigned long length) { _start_time = _current_time(); // save time first _length = length; _is_active = true; } void Timer::stop() { _start_time = 0; _length = 0; _is_active = false; } // // private // unsigned long Timer::_current_time() { switch (_units) { case Timer::Units::Microseconds: return micros(); break; case Timer::Units::Milliseconds: return millis(); break; case Timer::Units::Seconds: return millis()/1000; break; } return 0; } void Timer::_update() { if (_is_active && _current_time() >= _start_time + _length) _is_active = false; }
13.121212
61
0.639723
robfors
30863a06f9bb3bb0f2714fb003ace0def7f08e26
155
cpp
C++
benignware/1000.cpp
CodmingOut/SecretProjectAI
addc43117eab30a25453c18fa042739c33cc6cfb
[ "MIT" ]
8
2018-04-12T15:54:09.000Z
2020-06-05T07:41:15.000Z
src/1000/1000.cpp14.cpp
upple/BOJ
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
[ "MIT" ]
null
null
null
src/1000/1000.cpp14.cpp
upple/BOJ
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int count_0 = 0, count_1 = 0; int main(void) { int a, b; cin >> a >> b; cout << a + b << endl; return 0; }
11.071429
29
0.574194
CodmingOut
308846f94715c810eea8e4c19b8358fdaa42b62a
309
cpp
C++
Sorting-and-Order-Statistics/Selection sort.cpp
Fresher001/Competitive-Programming-2
e1e953bb1d4ade46cc670b2d0432f68504538ed2
[ "MIT" ]
86
2016-10-18T23:30:36.000Z
2022-01-09T21:57:34.000Z
Sorting-and-Order-Statistics/Selection sort.cpp
Fresher001/Competitive-Programming-2
e1e953bb1d4ade46cc670b2d0432f68504538ed2
[ "MIT" ]
1
2018-04-13T09:38:36.000Z
2018-04-13T09:38:36.000Z
Sorting-and-Order-Statistics/Selection sort.cpp
Fresher001/Competitive-Programming-2
e1e953bb1d4ade46cc670b2d0432f68504538ed2
[ "MIT" ]
39
2017-03-02T07:25:40.000Z
2020-12-14T12:13:50.000Z
#include <bits/stdc++.h> using namespace std; void selection_sort(int A[], int l, int r) { for (int i = l; i < r; ++i) { int p = i; for (int j = i + 1; j <= r; ++j) if (A[j] < A[p]) p = j; swap(A[i], A[p]); } } int main() { return 0; }
13.434783
42
0.391586
Fresher001
3088a13f78577e5dd7fc484a9a15ea8b0dd1cc3e
829
cpp
C++
clang/test/SemaCXX/align-x86-abi7.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
3,102
2015-01-04T02:28:35.000Z
2022-03-30T12:53:41.000Z
clang/test/SemaCXX/align-x86-abi7.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
clang/test/SemaCXX/align-x86-abi7.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
1,868
2015-01-03T04:27:11.000Z
2022-03-25T13:37:35.000Z
// RUN: %clang_cc1 -std=c++11 -triple i386-apple-darwin9 -fsyntax-only -verify -fclang-abi-compat=7 %s // expected-no-diagnostics using size_t = decltype(sizeof(0)); template <typename T, size_t Preferred> struct check_alignment { using type = T; static type value; static_assert(__alignof__(value) == Preferred, "__alignof__(value) != Preferred"); static_assert(__alignof__(type) == Preferred, "__alignof__(type) != Preferred"); static_assert(alignof(type) == Preferred, "alignof(type) != Preferred"); }; // PR3433 template struct check_alignment<double, 8>; template struct check_alignment<long long, 8>; template struct check_alignment<unsigned long long, 8>; // PR6362 template struct check_alignment<double[3], 8>; enum big_enum { x = 18446744073709551615ULL }; template struct check_alignment<big_enum, 8>;
31.884615
102
0.746683
medismailben
308acdf55b1fd94729126e79d44df30fb1e46fdf
419
hpp
C++
src/PheromonWeight.hpp
mwieczor/ACO
aa30ecd728d6b205188da4993857e2291a464255
[ "MIT" ]
null
null
null
src/PheromonWeight.hpp
mwieczor/ACO
aa30ecd728d6b205188da4993857e2291a464255
[ "MIT" ]
null
null
null
src/PheromonWeight.hpp
mwieczor/ACO
aa30ecd728d6b205188da4993857e2291a464255
[ "MIT" ]
null
null
null
#pragma once #include "Ant.hpp" class WeightGraph; class Node; class PheromonWeight{ public: PheromonWeight(){} virtual ~PheromonWeight()=default; protected: virtual void leavePheromon(IWeightGraph &mGraph, Node lastNode, Node position, double weight); // virtual void leavePheromon(WeightGraph &mGraph, Node lastNode, Node position); virtual void evaporatePheromon(IWeightGraph &mGraph); };
19.952381
98
0.747017
mwieczor
308ee7bdaf4678260b1812aa891a01dd171bce97
46,577
cpp
C++
plugins/chain_plugin/test/test_trx_finality_status_processing.cpp
abitmore/mandel
dfa3c92a713e7a093fc671fefa453a3033e27b0a
[ "MIT" ]
60
2022-01-03T18:41:12.000Z
2022-03-25T07:08:19.000Z
plugins/chain_plugin/test/test_trx_finality_status_processing.cpp
abitmore/mandel
dfa3c92a713e7a093fc671fefa453a3033e27b0a
[ "MIT" ]
37
2022-01-13T22:23:58.000Z
2022-03-31T13:32:38.000Z
plugins/chain_plugin/test/test_trx_finality_status_processing.cpp
abitmore/mandel
dfa3c92a713e7a093fc671fefa453a3033e27b0a
[ "MIT" ]
11
2022-01-14T21:14:11.000Z
2022-03-25T07:08:29.000Z
#define BOOST_TEST_MODULE transaction_finality_status #include <boost/test/included/unit_test.hpp> #include <eosio/chain_plugin/trx_finality_status_processing.hpp> #include <eosio/testing/tester.hpp> #include <eosio/chain/block_header.hpp> #include <eosio/chain/genesis_state.hpp> #include <eosio/chain/name.hpp> #include <eosio/chain/trace.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <fc/mock_time.hpp> #include <fc/bitutil.hpp> #include <deque> #include <memory> namespace eosio::test::detail { using namespace eosio::chain; using namespace eosio::chain::literals; struct testit { uint64_t id; testit( uint64_t id = 0 ) : id(id){} static account_name get_account() { return chain::config::system_account_name; } static action_name get_name() { return "testit"_n; } }; } // eosio::test::detail FC_REFLECT( eosio::test::detail::testit, (id) ) namespace { using namespace eosio; using namespace eosio::chain; using namespace eosio::chain_apis; using namespace eosio::test::detail; auto get_private_key( chain::name keyname, std::string role = "owner" ) { auto secret = fc::sha256::hash( keyname.to_string() + role ); return chain::private_key_type::regenerate<fc::ecc::private_key_shim>( secret ); } auto get_public_key( chain::name keyname, std::string role = "owner" ) { return get_private_key( keyname, role ).get_public_key(); } auto make_unique_trx( const fc::microseconds& expiration ) { static uint64_t unique_id = 0; ++unique_id; genesis_state gs{}; const auto& chain_id = gs.compute_chain_id(); account_name creator = config::system_account_name; signed_transaction trx; const auto now_exp = fc::time_point::now() + expiration; trx.expiration = now_exp; trx.actions.emplace_back( vector<permission_level>{{creator, config::active_name}}, testit{ unique_id } ); trx.sign( get_private_key("test"_n), chain_id ); return std::make_shared<packed_transaction>( std::move(trx), packed_transaction::compression_type::none); } chain::block_id_type make_block_id( uint32_t block_num ) { chain::block_id_type block_id; block_id._hash[0] &= 0xffffffff00000000; block_id._hash[0] += fc::endian_reverse_u32(block_num); return block_id; } chain::transaction_trace_ptr make_transaction_trace( const packed_transaction_ptr trx, uint32_t block_number, const eosio::chain::block_state_ptr& bs_ptr, chain::transaction_receipt_header::status_enum status = eosio::chain::transaction_receipt_header::executed ) { return std::make_shared<chain::transaction_trace>(chain::transaction_trace{ trx->id(), block_number, chain::block_timestamp_type(fc::time_point::now()), bs_ptr ? bs_ptr->id : std::optional<block_id_type> {}, chain::transaction_receipt_header{status}, fc::microseconds(0), 0, false, {}, // actions {}, {}, {}, {}, {} }); } auto make_block_state( uint32_t block_num ) { static uint64_t unique_num = 0; ++unique_num; chain::block_id_type block_id = make_block_id(block_num); block_id._hash[3] = unique_num; name producer = "brianj"_n; chain::signed_block_ptr block = std::make_shared<chain::signed_block>(); block->producer = producer; block->timestamp = fc::time_point::now(); block->previous = make_block_id(block_num - 1); auto priv_key = get_private_key( block->producer, "active" ); auto pub_key = get_public_key( block->producer, "active" ); auto prev = std::make_shared<chain::block_state>(); auto header_bmroot = chain::digest_type::hash( std::make_pair( block->digest(), prev->blockroot_merkle.get_root())); auto sig_digest = chain::digest_type::hash( std::make_pair( header_bmroot, prev->pending_schedule.schedule_hash )); block->producer_signature = priv_key.sign( sig_digest ); std::vector<chain::private_key_type> signing_keys; signing_keys.emplace_back( priv_key ); auto signer = [&]( chain::digest_type d ) { std::vector<chain::signature_type> result; result.reserve( signing_keys.size()); for( const auto& k: signing_keys ) result.emplace_back( k.sign( d )); return result; }; chain::pending_block_header_state pbhs; pbhs.producer = block->producer; pbhs.timestamp = block->timestamp; pbhs.previous = block->previous; chain::producer_authority_schedule schedule = {0, {chain::producer_authority{block->producer, chain::block_signing_authority_v0{1, {{pub_key, 1}}}}}}; pbhs.active_schedule = schedule; pbhs.valid_block_signing_authority = chain::block_signing_authority_v0{1, {{pub_key, 1}}}; auto bsp = std::make_shared<chain::block_state>( std::move( pbhs ), std::move( block ), std::vector<chain::transaction_metadata_ptr>(), chain::protocol_feature_set(), []( chain::block_timestamp_type timestamp, const fc::flat_set<chain::digest_type>& cur_features, const std::vector<chain::digest_type>& new_features ) {}, signer ); bsp->id = block_id; bsp->block_num = block_num; return bsp; } std::string set_now(const char* date, const char* time) { std::string date_time = std::string(date) + " " + time; auto pnow = boost::posix_time::time_from_string(date_time); fc::mock_time_traits::set_now(pnow); return std::string(date) + "T" + time; }; } // anonymous namespace BOOST_AUTO_TEST_SUITE(trx_finality_status_processing_test) BOOST_AUTO_TEST_CASE(trx_finality_status_logic) { try { const auto pre_block_20_time = set_now("2022-04-04", "04:44:44.450"); fc::microseconds max_success_duration = fc::seconds(25); fc::microseconds max_failure_duration = fc::seconds(45); trx_finality_status_processing status(10'000, max_success_duration, max_failure_duration); using trx_deque = eosio::chain::deque< std::tuple< chain::transaction_trace_ptr, packed_transaction_ptr > >; uint32_t bn = 20; auto add = [&bn, &status](trx_deque& trx_pairs, const eosio::chain::block_state_ptr& bs_ptr) { auto trx = make_unique_trx(fc::seconds(2)); auto trace = make_transaction_trace( trx, bn, bs_ptr); trx_pairs.push_back(std::tuple(trace, trx)); status.signal_applied_transaction(trace, trx); }; trx_deque trx_pairs_20; // Create speculative block to begin applying transactions locally status.signal_block_start(bn); const eosio::chain::block_state_ptr no_bs; add(trx_pairs_20, no_bs); add(trx_pairs_20, no_bs); add(trx_pairs_20, no_bs); add(trx_pairs_20, no_bs); auto cs = status.get_chain_state(); BOOST_CHECK(cs.head_id == eosio::chain::block_id_type{}); BOOST_TEST(!std::get<0>(trx_pairs_20[0])->producer_block_id.has_value()); BOOST_CHECK(cs.head_block_timestamp == eosio::chain::block_timestamp_type{}); BOOST_CHECK(cs.irr_id == eosio::chain::block_id_type{}); BOOST_CHECK(cs.earliest_tracked_block_id == eosio::chain::block_id_type{}); using op_ts = std::optional<eosio::chain_apis::trx_finality_status_processing::trx_state>; op_ts ts = status.get_trx_state(std::get<1>(trx_pairs_20[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == eosio::chain::block_id_type{}); BOOST_CHECK(ts->block_timestamp == eosio::chain::block_timestamp_type{}); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "LOCALLY_APPLIED"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[1])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == eosio::chain::block_id_type{}); BOOST_CHECK(ts->block_timestamp == eosio::chain::block_timestamp_type{}); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "LOCALLY_APPLIED"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[2])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == eosio::chain::block_id_type{}); BOOST_CHECK(ts->block_timestamp == eosio::chain::block_timestamp_type{}); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "LOCALLY_APPLIED"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[3])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == eosio::chain::block_id_type{}); BOOST_CHECK(ts->block_timestamp == eosio::chain::block_timestamp_type{}); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "LOCALLY_APPLIED"); // Simulate situation where the last 2 trxs do not make it into the block. trx_deque hold_pairs; std::vector<chain::packed_transaction_ptr> holds; hold_pairs.push_back(trx_pairs_20[2]); hold_pairs.push_back(trx_pairs_20[3]); trx_pairs_20.pop_back(); trx_pairs_20.pop_back(); //Make a real block start. Pull these before any updates to the trx/trace objects. // send block 20 const auto bs_20 = make_block_state(bn); status.signal_block_start(bn); for (const auto& trx_tuple : trx_pairs_20) { const auto& trace = std::get<0>(trx_tuple); const auto& txn = std::get<1>(trx_tuple); trace->producer_block_id = bs_20->id; trace->block_time = bs_20->block->timestamp; status.signal_applied_transaction(trace, txn); } // and 2 new transactions const auto block_20_time = set_now("2022-04-04", "04:44:44.500"); add(trx_pairs_20, bs_20); add(trx_pairs_20, bs_20); status.signal_accepted_block(bs_20); cs = status.get_chain_state(); BOOST_CHECK(cs.head_id == bs_20->id); BOOST_CHECK(cs.head_id == *std::get<0>(trx_pairs_20[0])->producer_block_id); BOOST_CHECK(cs.head_id == *std::get<0>(trx_pairs_20[1])->producer_block_id); BOOST_CHECK(cs.head_id == *std::get<0>(trx_pairs_20[2])->producer_block_id); BOOST_CHECK(cs.head_id == *std::get<0>(trx_pairs_20[3])->producer_block_id); BOOST_CHECK(cs.head_block_timestamp == bs_20->block->timestamp); BOOST_CHECK(cs.irr_id == eosio::chain::block_id_type{}); BOOST_CHECK(cs.earliest_tracked_block_id == bs_20->id); ts = status.get_trx_state(std::get<1>(trx_pairs_20[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[1])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK(fc::time_point_sec(ts->expiration) == (std::get<1>(trx_pairs_20[1])->expiration())); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[2])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[3])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(hold_pairs[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == eosio::chain::block_id_type{}); BOOST_CHECK(ts->block_timestamp == eosio::chain::block_timestamp_type{}); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "LOCALLY_APPLIED"); ts = status.get_trx_state(std::get<1>(hold_pairs[1])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == eosio::chain::block_id_type{}); BOOST_CHECK(ts->block_timestamp == eosio::chain::block_timestamp_type{}); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "LOCALLY_APPLIED"); // send block 21 const auto block_21_time = set_now("2022-04-04", "04:44:45.000"); trx_deque trx_pairs_21; bn = 21; const auto bs_21 = make_block_state(bn); status.signal_block_start(bn); fc::logger::get(DEFAULT_LOGGER).set_log_level(fc::log_level::debug); add(trx_pairs_21, bs_21); status.signal_accepted_block(bs_21); cs = status.get_chain_state(); BOOST_CHECK(cs.head_id == bs_21->id); BOOST_CHECK(cs.head_id == *std::get<0>(trx_pairs_21[0])->producer_block_id); BOOST_CHECK(cs.head_block_timestamp == bs_21->block->timestamp); BOOST_CHECK(cs.irr_id == eosio::chain::block_id_type{}); BOOST_CHECK(cs.earliest_tracked_block_id == bs_20->id); ts = status.get_trx_state(std::get<1>(trx_pairs_20[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[1])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[2])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[3])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(hold_pairs[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == eosio::chain::block_id_type{}); BOOST_CHECK(ts->block_timestamp == eosio::chain::block_timestamp_type{}); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "LOCALLY_APPLIED"); ts = status.get_trx_state(std::get<1>(hold_pairs[1])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == eosio::chain::block_id_type{}); BOOST_CHECK(ts->block_timestamp == eosio::chain::block_timestamp_type{}); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "LOCALLY_APPLIED"); ts = status.get_trx_state(std::get<1>(trx_pairs_21[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_21->id); BOOST_CHECK(ts->block_timestamp == bs_21->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_21_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); // send block 22 const auto block_22_time = set_now("2022-04-04", "04:44:45.500"); trx_deque trx_pairs_22; bn = 22; const auto bs_22 = make_block_state(bn); status.signal_block_start(bn); add(trx_pairs_22, bs_22); status.signal_accepted_block(bs_22); cs = status.get_chain_state(); BOOST_CHECK(cs.head_id == bs_22->id); BOOST_CHECK(cs.head_id == *std::get<0>(trx_pairs_22[0])->producer_block_id); BOOST_CHECK(cs.head_block_timestamp == bs_22->block->timestamp); BOOST_CHECK(cs.irr_id == eosio::chain::block_id_type{}); BOOST_CHECK(cs.earliest_tracked_block_id == bs_20->id); ts = status.get_trx_state(std::get<1>(trx_pairs_20[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[1])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[2])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[3])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(hold_pairs[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == eosio::chain::block_id_type{}); BOOST_CHECK(ts->block_timestamp == eosio::chain::block_timestamp_type{}); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "LOCALLY_APPLIED"); ts = status.get_trx_state(std::get<1>(hold_pairs[1])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == eosio::chain::block_id_type{}); BOOST_CHECK(ts->block_timestamp == eosio::chain::block_timestamp_type{}); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "LOCALLY_APPLIED"); ts = status.get_trx_state(std::get<1>(trx_pairs_21[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_21->id); BOOST_CHECK(ts->block_timestamp == bs_21->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_21_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(trx_pairs_22[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_22->id); BOOST_CHECK(ts->block_timestamp == bs_22->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_22_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); // send block 22 const auto block_22_alt_time = set_now("2022-04-04", "04:44:46.000"); trx_deque trx_pairs_22_alt; bn = 22; const auto bs_22_alt = make_block_state(bn); status.signal_block_start(bn); add(trx_pairs_22_alt, bs_22_alt); status.signal_accepted_block(bs_22_alt); cs = status.get_chain_state(); BOOST_CHECK(cs.head_id == bs_22_alt->id); BOOST_CHECK(cs.head_id == *std::get<0>(trx_pairs_22_alt[0])->producer_block_id); BOOST_CHECK(cs.head_block_timestamp == bs_22_alt->block->timestamp); BOOST_CHECK(cs.irr_id == eosio::chain::block_id_type{}); BOOST_CHECK(cs.earliest_tracked_block_id == bs_20->id); ts = status.get_trx_state(std::get<1>(trx_pairs_20[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[1])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[2])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[3])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(hold_pairs[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == eosio::chain::block_id_type{}); BOOST_CHECK(ts->block_timestamp == eosio::chain::block_timestamp_type{}); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "FAILED"); ts = status.get_trx_state(std::get<1>(hold_pairs[1])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == eosio::chain::block_id_type{}); BOOST_CHECK(ts->block_timestamp == eosio::chain::block_timestamp_type{}); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "FAILED"); ts = status.get_trx_state(std::get<1>(trx_pairs_21[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_21->id); BOOST_CHECK(ts->block_timestamp == bs_21->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_21_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(trx_pairs_22[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_22->id); BOOST_CHECK(ts->block_timestamp == bs_22->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_22_time); BOOST_CHECK_EQUAL(ts->status, "FORKED_OUT"); ts = status.get_trx_state(std::get<1>(trx_pairs_22_alt[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_22_alt->id); BOOST_CHECK(ts->block_timestamp == bs_22_alt->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_22_alt_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); // send block 19 (forking out previous blocks.) // Testing that code handles getting blocks before when it started const auto block_19_time = set_now("2022-04-04", "04:44:47.000"); trx_deque trx_pairs_19; bn = 19; const auto bs_19 = make_block_state(bn); status.signal_block_start(bn); add(trx_pairs_19, bs_19); status.signal_accepted_block(bs_19); cs = status.get_chain_state(); BOOST_CHECK(cs.head_id == bs_19->id); BOOST_CHECK(cs.head_id == *std::get<0>(trx_pairs_19[0])->producer_block_id); BOOST_CHECK(cs.head_block_timestamp == bs_19->block->timestamp); BOOST_CHECK(cs.irr_id == eosio::chain::block_id_type{}); BOOST_CHECK(cs.earliest_tracked_block_id == bs_19->id); ts = status.get_trx_state(std::get<1>(trx_pairs_20[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "FAILED"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[1])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "FAILED"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[2])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_20_time); BOOST_CHECK_EQUAL(ts->status, "FAILED"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[3])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_20->id); BOOST_CHECK(ts->block_timestamp == bs_20->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_20_time); BOOST_CHECK_EQUAL(ts->status, "FAILED"); ts = status.get_trx_state(std::get<1>(hold_pairs[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == eosio::chain::block_id_type{}); BOOST_CHECK(ts->block_timestamp == eosio::chain::block_timestamp_type{}); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "FAILED"); ts = status.get_trx_state(std::get<1>(hold_pairs[1])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == eosio::chain::block_id_type{}); BOOST_CHECK(ts->block_timestamp == eosio::chain::block_timestamp_type{}); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "FAILED"); ts = status.get_trx_state(std::get<1>(trx_pairs_21[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_21->id); BOOST_CHECK(ts->block_timestamp == bs_21->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_21_time); BOOST_CHECK_EQUAL(ts->status, "FAILED"); fc::logger::get(DEFAULT_LOGGER).set_log_level(fc::log_level::debug); ts = status.get_trx_state(std::get<1>(trx_pairs_22[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_22->id); BOOST_CHECK(ts->block_timestamp == bs_22->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_22_time); BOOST_CHECK_EQUAL(ts->status, "FAILED"); ts = status.get_trx_state(std::get<1>(trx_pairs_22_alt[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_22_alt->id); BOOST_CHECK(ts->block_timestamp == bs_22_alt->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_22_alt_time); BOOST_CHECK_EQUAL(ts->status, "FORKED_OUT"); ts = status.get_trx_state(std::get<1>(trx_pairs_19[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_19->id); BOOST_CHECK(ts->block_timestamp == bs_19->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_19_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); // send block 19 alternate const auto block_19_alt_time = set_now("2022-04-04", "04:44:44.000"); trx_deque trx_pairs_19_alt; bn = 19; trx_pairs_19_alt.push_back(trx_pairs_19[0]); trx_pairs_19_alt.push_back(trx_pairs_20[0]); trx_pairs_19_alt.push_back(trx_pairs_20[1]); trx_pairs_19_alt.push_back(trx_pairs_20[2]); trx_pairs_19_alt.push_back(trx_pairs_20[3]); trx_pairs_19_alt.push_back(hold_pairs[0]); const auto bs_19_alt = make_block_state(bn); // const auto bs_19_alt = make_block_state(make_block_id(bn), std::vector<chain::packed_transaction_ptr>{}); status.signal_block_start(bn); for (const auto& trx_tuple : trx_pairs_19_alt) { const auto& trace = std::get<0>(trx_tuple); const auto& txn = std::get<1>(trx_tuple); trace->producer_block_id = bs_19_alt->id; trace->block_time = bs_19_alt->block->timestamp; status.signal_applied_transaction(trace, txn); } status.signal_accepted_block(bs_19_alt); cs = status.get_chain_state(); BOOST_CHECK(cs.head_id == bs_19_alt->id); BOOST_CHECK(cs.head_id == *std::get<0>(trx_pairs_19[0])->producer_block_id); BOOST_CHECK(cs.head_block_timestamp == bs_19_alt->block->timestamp); BOOST_CHECK(cs.irr_id == eosio::chain::block_id_type{}); BOOST_CHECK(cs.earliest_tracked_block_id == bs_19_alt->id); ts = status.get_trx_state(std::get<1>(trx_pairs_20[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_19_alt->id); BOOST_CHECK(ts->block_timestamp == bs_19_alt->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[1])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_19_alt->id); BOOST_CHECK(ts->block_timestamp == bs_19_alt->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[2])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_19_alt->id); BOOST_CHECK(ts->block_timestamp == bs_19_alt->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[3])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_19_alt->id); BOOST_CHECK(ts->block_timestamp == bs_19_alt->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(hold_pairs[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_19_alt->id); BOOST_CHECK(ts->block_timestamp == bs_19_alt->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); ts = status.get_trx_state(std::get<1>(hold_pairs[1])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == eosio::chain::block_id_type{}); BOOST_CHECK(ts->block_timestamp == eosio::chain::block_timestamp_type{}); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "LOCALLY_APPLIED"); ts = status.get_trx_state(std::get<1>(trx_pairs_21[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_21->id); BOOST_CHECK(ts->block_timestamp == bs_21->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_21_time); BOOST_CHECK_EQUAL(ts->status, "FORKED_OUT"); fc::logger::get(DEFAULT_LOGGER).set_log_level(fc::log_level::debug); ts = status.get_trx_state(std::get<1>(trx_pairs_22[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_22->id); BOOST_CHECK(ts->block_timestamp == bs_22->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_22_time); BOOST_CHECK_EQUAL(ts->status, "FORKED_OUT"); ts = status.get_trx_state(std::get<1>(trx_pairs_22_alt[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_22_alt->id); BOOST_CHECK(ts->block_timestamp == bs_22_alt->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_22_alt_time); BOOST_CHECK_EQUAL(ts->status, "FORKED_OUT"); ts = status.get_trx_state(std::get<1>(trx_pairs_19[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_19_alt->id); BOOST_CHECK(ts->block_timestamp == bs_19_alt->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_19_time); BOOST_CHECK_EQUAL(ts->status, "IN_BLOCK"); // look for unknown transaction auto trx = make_unique_trx(fc::seconds(2)); ts = status.get_trx_state(trx->id()); BOOST_REQUIRE(!ts); // irreversible status.signal_irreversible_block(bs_19_alt); cs = status.get_chain_state(); BOOST_CHECK(cs.head_id == bs_19_alt->id); BOOST_CHECK(cs.irr_id == bs_19_alt->id); BOOST_CHECK(cs.irr_block_timestamp == bs_19_alt->block->timestamp); BOOST_CHECK(cs.earliest_tracked_block_id == bs_19_alt->id); ts = status.get_trx_state(std::get<1>(trx_pairs_20[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_19_alt->id); BOOST_CHECK(ts->block_timestamp == bs_19_alt->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "IRREVERSIBLE"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[1])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_19_alt->id); BOOST_CHECK(ts->block_timestamp == bs_19_alt->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "IRREVERSIBLE"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[2])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_19_alt->id); BOOST_CHECK(ts->block_timestamp == bs_19_alt->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_20_time); BOOST_CHECK_EQUAL(ts->status, "IRREVERSIBLE"); ts = status.get_trx_state(std::get<1>(trx_pairs_20[3])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_19_alt->id); BOOST_CHECK(ts->block_timestamp == bs_19_alt->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_20_time); BOOST_CHECK_EQUAL(ts->status, "IRREVERSIBLE"); ts = status.get_trx_state(std::get<1>(hold_pairs[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_19_alt->id); BOOST_CHECK(ts->block_timestamp == bs_19_alt->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "IRREVERSIBLE"); ts = status.get_trx_state(std::get<1>(hold_pairs[1])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == eosio::chain::block_id_type{}); BOOST_CHECK(ts->block_timestamp == eosio::chain::block_timestamp_type{}); BOOST_CHECK_EQUAL(std::string(ts->received), pre_block_20_time); BOOST_CHECK_EQUAL(ts->status, "LOCALLY_APPLIED"); ts = status.get_trx_state(std::get<1>(trx_pairs_21[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_21->id); BOOST_CHECK(ts->block_timestamp == bs_21->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_21_time); BOOST_CHECK_EQUAL(ts->status, "FORKED_OUT"); fc::logger::get(DEFAULT_LOGGER).set_log_level(fc::log_level::debug); ts = status.get_trx_state(std::get<1>(trx_pairs_22[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_22->id); BOOST_CHECK(ts->block_timestamp == bs_22->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_22_time); BOOST_CHECK_EQUAL(ts->status, "FORKED_OUT"); ts = status.get_trx_state(std::get<1>(trx_pairs_22_alt[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_22_alt->id); BOOST_CHECK(ts->block_timestamp == bs_22_alt->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_22_alt_time); BOOST_CHECK_EQUAL(ts->status, "FORKED_OUT"); ts = status.get_trx_state(std::get<1>(trx_pairs_19[0])->id()); BOOST_REQUIRE(ts); BOOST_CHECK(ts->block_id == bs_19_alt->id); BOOST_CHECK(ts->block_timestamp == bs_19_alt->block->timestamp); BOOST_CHECK_EQUAL(std::string(ts->received), block_19_time); BOOST_CHECK_EQUAL(ts->status, "IRREVERSIBLE"); } FC_LOG_AND_RETHROW() } namespace { using trx_deque = eosio::chain::deque< std::tuple< chain::transaction_trace_ptr, packed_transaction_ptr > >; const eosio::chain::block_state_ptr no_bs; struct block_frame { static uint32_t last_used_block_num; static const uint32_t num = 5; trx_finality_status_processing& status; const uint32_t bn; const std::string time; trx_deque pre_block; trx_deque block; chain::block_state_ptr bs; std::string context; block_frame(trx_finality_status_processing& finality_status, const char* block_time, uint32_t block_num = 0) : status(finality_status), bn(block_num == 0 ? block_frame::last_used_block_num + 1 : block_num), time(set_now("2022-04-04", block_time)) { block_frame::last_used_block_num = bn; for (uint32_t i = 0; i < block_frame::num; ++i) { auto trx = make_unique_trx(fc::seconds(30)); auto trace = make_transaction_trace( trx, bn, no_bs); pre_block.push_back(std::tuple(trace, trx)); status.signal_applied_transaction(trace, trx); } bs = make_block_state(bn); for (uint32_t i = 0; i < block_frame::num; ++i) { auto trx = make_unique_trx(fc::seconds(30)); auto trace = make_transaction_trace( trx, bn, bs); block.push_back(std::tuple(trace, trx)); status.signal_applied_transaction(trace, trx); } } void verify_block(uint32_t begin = 0, uint32_t end = std::numeric_limits<uint32_t>::max()) { context = "verify_block"; verify(block, bs, begin, end); } void verify_block_not_there(uint32_t begin = 0, uint32_t end = std::numeric_limits<uint32_t>::max()) { context = "verify_block_not_there"; verify_not_there(block, begin, end); } void verify_spec_block(uint32_t begin = 0, uint32_t end = std::numeric_limits<uint32_t>::max()) { context = "verify_spec_block"; verify(pre_block, no_bs, begin, end); } void verify_spec_block_not_there(uint32_t begin = 0, uint32_t end = std::numeric_limits<uint32_t>::max()) { context = "verify_spec_block_not_there"; verify_not_there(pre_block, begin, end); } void send_block() { status.signal_block_start(bn); for (const auto& trx_tuple : block) { const auto& trace = std::get<0>(trx_tuple); const auto& txn = std::get<1>(trx_tuple); status.signal_applied_transaction(trace, txn); } status.signal_accepted_block(bs); } void send_spec_block() { status.signal_block_start(bn); for (const auto& trx_tuple : pre_block) { const auto& trace = std::get<0>(trx_tuple); const auto& txn = std::get<1>(trx_tuple); status.signal_applied_transaction(trace, txn); } } private: void verify(const trx_deque& trx_pairs, const chain::block_state_ptr& bs, uint32_t begin, uint32_t end) { if (end == std::numeric_limits<uint32_t>::max()) { end = block.size(); } const auto id = bs ? bs->id : eosio::chain::transaction_id_type{}; for (auto i = begin; i < end; ++i) { const auto& trx_pair = trx_pairs[i]; std::string msg = context + ": block_num==" + std::to_string(bn) + ", i==" + std::to_string(i) + ", id: " + std::string(std::get<1>(trx_pair)->id()); auto ts = status.get_trx_state(std::get<1>(trx_pair)->id()); BOOST_REQUIRE_MESSAGE(ts, msg); BOOST_CHECK_MESSAGE(ts->block_id == id, msg); } } void verify_not_there(const trx_deque& trx_pairs, uint32_t begin, uint32_t end) { if (end == std::numeric_limits<uint32_t>::max()) { end = block.size(); } for (auto i = begin; i < end; ++i) { std::string msg = context + "block_num==" + std::to_string(bn) + " i==" + std::to_string(i); const auto& trx_pair = trx_pairs[i]; auto ts = status.get_trx_state(std::get<1>(trx_pair)->id()); BOOST_REQUIRE_MESSAGE(!ts, msg); } } }; uint32_t block_frame::last_used_block_num = 0; } BOOST_AUTO_TEST_CASE(trx_finality_status_storage_reduction) { try { set_now("2022-04-04", "04:44:44.450"); fc::microseconds max_success_duration = fc::seconds(25); fc::microseconds max_failure_duration = fc::seconds(45); const uint64_t max_storage = 10'000; trx_finality_status_processing status(max_storage, max_success_duration, max_failure_duration); // auto verify_trx = [&status](trx_deque& trx_pairs, const eosio::chain::block_state_ptr& bs) { // const auto id = bs ? bs->id : eosio::chain::transaction_id_type{}; // for (const auto& trx_pair : trx_pairs) { // auto ts = status.get_trx_state(std::get<1>(trx_pair)->id()); // BOOST_REQUIRE(ts); // BOOST_CHECK(ts->block_id == id); // } // }; block_frame b_01(status, "04:44:00.500", 1); b_01.send_spec_block(); b_01.verify_spec_block(); b_01.send_block(); b_01.verify_block(); const auto block_and_speculative_size = status.get_storage_memory_size(); // test expects to not hit the storage limitation till the 12th block BOOST_REQUIRE(max_storage / 11 > block_and_speculative_size); BOOST_REQUIRE(max_storage / 12 < block_and_speculative_size); block_frame b_02(status, "04:44:01.500"); b_02.send_spec_block(); b_02.verify_spec_block(); b_02.send_block(); b_02.verify_block(); block_frame b_03(status, "04:44:02.500"); b_03.send_spec_block(); b_03.verify_spec_block(); b_03.send_block(); b_03.verify_block(); block_frame b_04(status, "04:44:03.500"); b_04.send_spec_block(); b_04.verify_spec_block(); b_04.send_block(); b_04.verify_block(); block_frame b_05(status, "04:44:04.500"); b_05.send_spec_block(); b_05.verify_spec_block(); b_05.send_block(); b_05.verify_block(); block_frame b_06(status, "04:44:05.500"); b_06.send_spec_block(); b_06.verify_spec_block(); b_06.send_block(); b_06.verify_block(); block_frame b_07(status, "04:44:06.500"); b_07.send_spec_block(); b_07.verify_spec_block(); b_07.send_block(); b_07.verify_block(); block_frame b_08(status, "04:44:07.500"); b_08.send_spec_block(); b_08.verify_spec_block(); b_08.send_block(); b_08.verify_block(); block_frame b_09(status, "04:44:08.500"); b_09.send_spec_block(); b_09.verify_spec_block(); b_09.send_block(); b_09.verify_block(); block_frame b_10(status, "04:44:09.500"); b_10.send_spec_block(); b_10.verify_spec_block(); b_10.send_block(); b_10.verify_block(); block_frame b_11(status, "04:44:10.500"); b_11.send_spec_block(); b_11.verify_spec_block(); b_11.send_block(); b_11.verify_block(); auto cs = status.get_chain_state(); BOOST_CHECK(cs.head_id == b_11.bs->id); BOOST_CHECK(cs.irr_id == eosio::chain::block_id_type{}); BOOST_CHECK(cs.earliest_tracked_block_id == b_01.bs->id); // Test expects the next block range to exceed max_storage. Need to adjust // this test if this fails. BOOST_REQUIRE(status.get_storage_memory_size() + block_and_speculative_size > max_storage); block_frame b_12(status, "04:44:11.500"); b_12.send_spec_block(); b_12.verify_spec_block(); b_12.send_block(); b_12.verify_block(); cs = status.get_chain_state(); BOOST_CHECK(cs.head_id == b_12.bs->id); BOOST_CHECK(cs.head_block_timestamp == b_12.bs->block->timestamp); BOOST_CHECK(cs.irr_id == eosio::chain::block_id_type{}); BOOST_CHECK(cs.irr_block_timestamp == eosio::chain::block_timestamp_type{}); BOOST_CHECK(cs.earliest_tracked_block_id == b_03.bs->id); b_01.verify_spec_block_not_there(); b_01.verify_block_not_there(); b_02.verify_spec_block_not_there(); b_02.verify_block_not_there(); b_03.verify_spec_block(); b_03.verify_block(); b_04.verify_spec_block(); b_04.verify_block(); b_05.verify_spec_block(); b_05.verify_block(); b_06.verify_spec_block(); b_06.verify_block(); b_07.verify_spec_block(); b_07.verify_block(); b_08.verify_spec_block(); b_08.verify_block(); b_09.verify_spec_block(); b_09.verify_block(); b_10.verify_spec_block(); b_10.verify_block(); b_11.verify_spec_block(); b_11.verify_block(); b_12.verify_spec_block(); b_12.verify_block(); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE(trx_finality_status_lifespan) { try { set_now("2022-04-04", "04:44:44.450"); fc::microseconds max_success_duration = fc::seconds(25); fc::microseconds max_failure_duration = fc::seconds(35); const uint64_t max_storage = 10'000; trx_finality_status_processing status(max_storage, max_success_duration, max_failure_duration); // auto verify_trx = [&status](trx_deque& trx_pairs, const eosio::chain::block_state_ptr& bs) { // const auto id = bs ? bs->id : eosio::chain::transaction_id_type{}; // for (const auto& trx_pair : trx_pairs) { // auto ts = status.get_trx_state(std::get<1>(trx_pair)->id()); // BOOST_REQUIRE(ts); // BOOST_CHECK(ts->block_id == id); // } // }; block_frame b_01(status, "04:44:00.500", 1); b_01.send_spec_block(); b_01.verify_spec_block(); b_01.send_block(); b_01.verify_block(); block_frame b_02(status, "04:44:05.500"); b_02.send_spec_block(); b_02.verify_spec_block(); b_02.send_block(); b_02.verify_block(); block_frame b_03(status, "04:44:10.500"); b_03.send_spec_block(); b_03.verify_spec_block(); b_03.send_block(); b_03.verify_block(); block_frame b_04(status, "04:44:15.500"); b_04.send_spec_block(); b_04.verify_spec_block(); b_04.send_block(); b_04.verify_block(); block_frame b_05(status, "04:44:20.500"); b_05.send_spec_block(); b_05.verify_spec_block(); b_05.send_block(); b_05.verify_block(); // should be still available b_01.verify_block(); b_01.verify_spec_block(); // still available and will continue till failure time block_frame b_06(status, "04:44:25.500"); b_06.send_spec_block(); b_06.verify_spec_block(); b_06.send_block(); b_06.verify_block(); // block 1 now removed b_01.verify_block_not_there(); b_02.verify_block(); b_01.verify_spec_block(); auto cs = status.get_chain_state(); BOOST_CHECK(cs.head_id == b_06.bs->id); BOOST_CHECK(cs.irr_id == eosio::chain::block_id_type{}); BOOST_CHECK(cs.earliest_tracked_block_id == b_02.bs->id); block_frame b_07(status, "04:44:30.500"); b_07.send_spec_block(); b_07.verify_spec_block(); b_07.send_block(); b_07.verify_block(); // block 2 now removed b_02.verify_block_not_there(); b_03.verify_block(); b_01.verify_spec_block(); b_02.verify_spec_block(); cs = status.get_chain_state(); BOOST_CHECK(cs.head_id == b_07.bs->id); BOOST_CHECK(cs.irr_id == eosio::chain::block_id_type{}); BOOST_CHECK(cs.earliest_tracked_block_id == b_03.bs->id); block_frame b_08(status, "04:44:35.500"); b_08.send_spec_block(); b_08.verify_spec_block(); b_08.send_block(); b_08.verify_block(); // block 3 now removed and speculative's from block 1 time frame b_03.verify_block_not_there(); b_04.verify_block(); b_01.verify_spec_block_not_there(); b_02.verify_spec_block(); b_03.verify_spec_block(); block_frame b_09(status, "04:44:40.500"); b_09.send_spec_block(); b_09.verify_spec_block(); b_09.send_block(); b_09.verify_block(); // block 4 now removed and speculative's from block 2 time frame b_04.verify_block_not_there(); b_05.verify_block(); b_02.verify_spec_block_not_there(); b_03.verify_spec_block(); b_04.verify_spec_block(); block_frame b_10(status, "04:44:45.500"); b_10.send_spec_block(); b_10.verify_spec_block(); b_10.send_block(); b_10.verify_block(); // block 5 now removed and speculative's from block 3 time frame b_05.verify_block_not_there(); b_06.verify_block(); b_03.verify_spec_block_not_there(); b_04.verify_spec_block(); b_05.verify_spec_block(); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_SUITE_END()
36.790679
163
0.694313
abitmore
3091aa4676803d92ae456bcbb9262bf7557229fb
5,095
cpp
C++
modules/core/src/Slot/gmSlotBase.cpp
GraphMIC/GraphMIC
8fc2aeb0143ee1292c6757f010fc9e8c68823e2b
[ "BSD-3-Clause" ]
43
2016-04-11T11:34:05.000Z
2022-03-31T03:37:57.000Z
modules/core/src/Slot/gmSlotBase.cpp
kevinlq/GraphMIC
8fc2aeb0143ee1292c6757f010fc9e8c68823e2b
[ "BSD-3-Clause" ]
1
2016-05-17T12:58:16.000Z
2016-05-17T12:58:16.000Z
modules/core/src/Slot/gmSlotBase.cpp
kevinlq/GraphMIC
8fc2aeb0143ee1292c6757f010fc9e8c68823e2b
[ "BSD-3-Clause" ]
14
2016-05-13T20:23:16.000Z
2021-12-20T10:33:19.000Z
#include "gmSlotBase.hpp" #include "gmSlotInput.hpp" #include "gmSlotOutput.hpp" #include "gmNodeEditor.hpp" #include "gmNodeConnector.hpp" #include "gmSlotInputBase.hpp" #include "gmSlotOutputBase.hpp" #include "gmSlotConstraints.hpp" #include "gmAsync.hpp" namespace gm { namespace Slot { Base::Base(Component::Type componentType, Data::Type dataType, const QString& name, Constraints* constraints) : Component::Base(componentType, name), /*m_constraints(constraints),*/ m_dataType(dataType) { if (componentType == Component::Type::Input) { this->m_slotType = Type::Input; } else { this->m_slotType = Type::Output; } switch (dataType) { case Data::Type::Image: this->m_dataTypeString = "image"; break; case Data::Type::Number: this->m_dataTypeString = "number"; break; case Data::Type::Vector: this->m_dataTypeString = "vector"; break; case Data::Type::Pointset: this->m_dataTypeString = "pointset"; break; } this->setConstraints(constraints); } auto Base::setConstraints(Constraints* constraints) -> void { this->m_constraints = constraints; emit this->constraintsChanged(); } auto Base::getConstraints() -> Constraints* { return this->m_constraints; } auto Base::getDataTypeString() -> QString { return this->m_dataTypeString; } auto Base::moveConnectX(int x) -> void { if (this->m_slotType == Type::Output) { Node::Connector::instance->setX2(this->m_x + x); } else { Node::Connector::instance->setX1(this->m_x + x); } } auto Base::moveConnectY(int y) -> void { if (this->m_slotType == Type::Output) { Node::Connector::instance->setY2(this->m_y + y); } else { Node::Connector::instance->setY1(this->m_y + y); } } auto Base::setConnecting(bool connecting) -> void { if (this->m_connecting != connecting) { this->m_connecting = connecting; if (connecting) { Node::Connector::instance->setX1(this->m_x); Node::Connector::instance->setY1(this->m_y); Node::Connector::instance->setX2(this->m_x); Node::Connector::instance->setY2(this->m_y); Node::Connector::instance->setActive(true); } else { Node::Connector::instance->setActive(false); } } } auto Base::getConnecting() -> bool { return this->m_connecting; } auto Base::setX(int x) -> void { this->m_x = x; emit this->xChanged(); this->onPositionChanged(); } auto Base::getX() -> int { return this->m_x; } auto Base::setY(int y) -> void { this->m_y = y; emit this->yChanged(); this->onPositionChanged(); } auto Base::getY() -> int { return this->m_y; } auto Base::getDataType() -> Data::Type { return this->m_dataType; } auto Base::getSlotType() -> Slot::Type { return this->m_slotType; } auto Base::getSlotTypeID() -> int { return this->m_slotType == Type::Output; } auto Base::connect(Base* other) -> void { if (!other) { return; } Slot::InputBase* input = reinterpret_cast<Slot::InputBase*>(this->m_slotType == Type::Input ? this : other->m_slotType == Type::Input ? other : nullptr); Slot::OutputBase* output = reinterpret_cast<Slot::OutputBase*>(this->m_slotType == Type::Output ? this : other->m_slotType == Type::Output ? other : nullptr); if (input && output) { if (input->isConnected(output)) { return; } output->connect(input); } } auto Base::moveToMain() -> void { if (this->m_constraints) { Async::MoveToMain(this->m_constraints); } } Base::~Base() { delete this->m_constraints; } } }
28.305556
210
0.452208
GraphMIC
309438d436575dc3a725135e24f23899ef17ab21
344
cpp
C++
leetcode/cpp/qt_reverse_string.cpp
qiaotian/CodeInterview
294c1ba86d8ace41a121c5ada4ba4c3765ccc17d
[ "WTFPL" ]
5
2016-10-29T09:28:11.000Z
2019-10-19T23:02:48.000Z
leetcode/cpp/qt_reverse_string.cpp
qiaotian/CodeInterview
294c1ba86d8ace41a121c5ada4ba4c3765ccc17d
[ "WTFPL" ]
null
null
null
leetcode/cpp/qt_reverse_string.cpp
qiaotian/CodeInterview
294c1ba86d8ace41a121c5ada4ba4c3765ccc17d
[ "WTFPL" ]
null
null
null
/* Write a function that takes a string as input and returns the string reversed. Example: Given s = "hello", return "olleh". */ class Solution { public: string reverseString(string s) { int start = 0; int end = s.size()-1; while(start < end) { swap(s[start++], s[end--]); } return s; } };
19.111111
78
0.561047
qiaotian
3098c961a04a961a07a9b587f9e56fac7d56ba21
287
hpp
C++
src/modules/osg/generated_code/TransformFeedbackBufferBinding.pypp.hpp
JaneliaSciComp/osgpyplusplus
a5ae3f69c7e9101a32d8cc95fe680dab292f75ac
[ "BSD-3-Clause" ]
17
2015-06-01T12:19:46.000Z
2022-02-12T02:37:48.000Z
src/modules/osg/generated_code/TransformFeedbackBufferBinding.pypp.hpp
cmbruns/osgpyplusplus
f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75
[ "BSD-3-Clause" ]
7
2015-07-04T14:36:49.000Z
2015-07-23T18:09:49.000Z
src/modules/osg/generated_code/TransformFeedbackBufferBinding.pypp.hpp
cmbruns/osgpyplusplus
f8bfca2cf841e15f6ddb41c958f3ad0d0b9e4b75
[ "BSD-3-Clause" ]
7
2015-11-28T17:00:31.000Z
2020-01-08T07:00:59.000Z
// This file has been generated by Py++. #ifndef TransformFeedbackBufferBinding_hpp__pyplusplus_wrapper #define TransformFeedbackBufferBinding_hpp__pyplusplus_wrapper void register_TransformFeedbackBufferBinding_class(); #endif//TransformFeedbackBufferBinding_hpp__pyplusplus_wrapper
31.888889
62
0.891986
JaneliaSciComp
309cd4cf8ee842ba93c661842641de1cb0b0f4e5
42,488
cc
C++
src/cats/sql_create.cc
Acidburn0zzz/bareos
34a60296af2e2e948c8cd983876eebf5d4d31fc9
[ "MIT" ]
1
2018-04-28T14:03:39.000Z
2018-04-28T14:03:39.000Z
src/cats/sql_create.cc
Acidburn0zzz/bareos
34a60296af2e2e948c8cd983876eebf5d4d31fc9
[ "MIT" ]
null
null
null
src/cats/sql_create.cc
Acidburn0zzz/bareos
34a60296af2e2e948c8cd983876eebf5d4d31fc9
[ "MIT" ]
null
null
null
/* BAREOS® - Backup Archiving REcovery Open Sourced Copyright (C) 2000-2012 Free Software Foundation Europe e.V. Copyright (C) 2011-2016 Planets Communications B.V. Copyright (C) 2013-2017 Bareos GmbH & Co. KG This program is Free Software; you can redistribute it and/or modify it under the terms of version three of the GNU Affero General Public License as published by the Free Software Foundation and included in the file LICENSE. 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* * Kern Sibbald, March 2000 */ /** * @file * BAREOS Catalog Database Create record interface routines */ #include "bareos.h" static const int dbglevel = 100; #if HAVE_SQLITE3 || HAVE_MYSQL || HAVE_POSTGRESQL || HAVE_INGRES || HAVE_DBI #include "cats.h" /* ----------------------------------------------------------------------- * * Generic Routines (or almost generic) * * ----------------------------------------------------------------------- */ /** * Forward referenced subroutines */ /** * Create a new record for the Job * Returns: false on failure * true on success */ bool B_DB::create_job_record(JCR *jcr, JOB_DBR *jr) { bool retval = false;; POOL_MEM buf; char dt[MAX_TIME_LENGTH]; time_t stime; int len; utime_t JobTDate; char ed1[30], ed2[30]; char esc_ujobname[MAX_ESCAPE_NAME_LENGTH]; char esc_jobname[MAX_ESCAPE_NAME_LENGTH]; db_lock(this); stime = jr->SchedTime; ASSERT(stime != 0); bstrutime(dt, sizeof(dt), stime); JobTDate = (utime_t)stime; len = strlen(jcr->comment); /* TODO: use jr instead of jcr to get comment */ buf.check_size(len * 2 + 1); escape_string(jcr, buf.c_str(), jcr->comment, len); escape_string(jcr, esc_ujobname, jr->Job, strlen(jr->Job)); escape_string(jcr, esc_jobname, jr->Name, strlen(jr->Name)); /* * Must create it */ Mmsg(cmd, "INSERT INTO Job (Job,Name,Type,Level,JobStatus,SchedTime,JobTDate," "ClientId,Comment) " "VALUES ('%s','%s','%c','%c','%c','%s',%s,%s,'%s')", esc_ujobname, esc_jobname, (char)(jr->JobType), (char)(jr->JobLevel), (char)(jr->JobStatus), dt, edit_uint64(JobTDate, ed1), edit_int64(jr->ClientId, ed2), buf.c_str()); jr->JobId = sql_insert_autokey_record(cmd, NT_("Job")); if (jr->JobId == 0) { Mmsg2(errmsg, _("Create DB Job record %s failed. ERR=%s\n"), cmd, sql_strerror()); } else { retval = true; } db_unlock(this); return retval; } /** * Create a JobMedia record for medium used this job * Returns: false on failure * true on success */ bool B_DB::create_jobmedia_record(JCR *jcr, JOBMEDIA_DBR *jm) { bool retval = false; int count; char ed1[50], ed2[50], ed3[50]; db_lock(this); /* * Now get count for VolIndex */ Mmsg(cmd, "SELECT count(*) from JobMedia WHERE JobId=%s", edit_int64(jm->JobId, ed1)); count = get_sql_record_max(jcr); if (count < 0) { count = 0; } count++; Mmsg(cmd, "INSERT INTO JobMedia (JobId,MediaId,FirstIndex,LastIndex," "StartFile,EndFile,StartBlock,EndBlock,VolIndex,JobBytes) " "VALUES (%s,%s,%u,%u,%u,%u,%u,%u,%u,%s)", edit_int64(jm->JobId, ed1), edit_int64(jm->MediaId, ed2), jm->FirstIndex, jm->LastIndex, jm->StartFile, jm->EndFile, jm->StartBlock, jm->EndBlock, count, edit_uint64(jm->JobBytes, ed3)); Dmsg0(300, cmd); if (!INSERT_DB(jcr, cmd)) { Mmsg2(errmsg, _("Create JobMedia record %s failed: ERR=%s\n"), cmd, sql_strerror()); } else { /* * Worked, now update the Media record with the EndFile and EndBlock */ Mmsg(cmd, "UPDATE Media SET EndFile=%u, EndBlock=%u WHERE MediaId=%u", jm->EndFile, jm->EndBlock, jm->MediaId); if (!UPDATE_DB(jcr, cmd)) { Mmsg2(errmsg, _("Update Media record %s failed: ERR=%s\n"), cmd, sql_strerror()); } else { retval = true; } } db_unlock(this); Dmsg0(300, "Return from JobMedia\n"); return retval; } /** * Create Unique Pool record * Returns: false on failure * true on success */ bool B_DB::create_pool_record(JCR *jcr, POOL_DBR *pr) { bool retval = false; char ed1[30], ed2[30], ed3[50], ed4[50], ed5[50]; char esc_poolname[MAX_ESCAPE_NAME_LENGTH]; char esc_lf[MAX_ESCAPE_NAME_LENGTH]; int num_rows; Dmsg0(200, "In create pool\n"); db_lock(this); escape_string(jcr, esc_poolname, pr->Name, strlen(pr->Name)); escape_string(jcr, esc_lf, pr->LabelFormat, strlen(pr->LabelFormat)); Mmsg(cmd, "SELECT PoolId,Name FROM Pool WHERE Name='%s'", esc_poolname); Dmsg1(200, "selectpool: %s\n", cmd); if (QUERY_DB(jcr, cmd)) { num_rows = sql_num_rows(); if (num_rows > 0) { Mmsg1(errmsg, _("pool record %s already exists\n"), pr->Name); sql_free_result(); goto bail_out; } sql_free_result(); } /* * Must create it */ Mmsg(cmd, "INSERT INTO Pool (Name,NumVols,MaxVols,UseOnce,UseCatalog," "AcceptAnyVolume,AutoPrune,Recycle,VolRetention,VolUseDuration," "MaxVolJobs,MaxVolFiles,MaxVolBytes,PoolType,LabelType,LabelFormat," "RecyclePoolId,ScratchPoolId,ActionOnPurge,MinBlocksize,MaxBlocksize) " "VALUES ('%s',%u,%u,%d,%d,%d,%d,%d,%s,%s,%u,%u,%s,'%s',%d,'%s',%s,%s,%d,%d,%d)", esc_poolname, pr->NumVols, pr->MaxVols, pr->UseOnce, pr->UseCatalog, pr->AcceptAnyVolume, pr->AutoPrune, pr->Recycle, edit_uint64(pr->VolRetention, ed1), edit_uint64(pr->VolUseDuration, ed2), pr->MaxVolJobs, pr->MaxVolFiles, edit_uint64(pr->MaxVolBytes, ed3), pr->PoolType, pr->LabelType, esc_lf, edit_int64(pr->RecyclePoolId,ed4), edit_int64(pr->ScratchPoolId,ed5), pr->ActionOnPurge, pr->MinBlocksize, pr->MaxBlocksize); Dmsg1(200, "Create Pool: %s\n", cmd); pr->PoolId = sql_insert_autokey_record(cmd, NT_("Pool")); if (pr->PoolId == 0) { Mmsg2(errmsg, _("Create db Pool record %s failed: ERR=%s\n"), cmd, sql_strerror()); } else { retval = true; } bail_out: db_unlock(this); Dmsg0(500, "Create Pool: done\n"); return retval; } /** * Create Unique Device record * Returns: false on failure * true on success */ bool B_DB::create_device_record(JCR *jcr, DEVICE_DBR *dr) { bool retval = false; SQL_ROW row; char ed1[30], ed2[30]; char esc[MAX_ESCAPE_NAME_LENGTH]; int num_rows; Dmsg0(200, "In create Device\n"); db_lock(this); escape_string(jcr, esc, dr->Name, strlen(dr->Name)); Mmsg(cmd, "SELECT DeviceId,Name FROM Device WHERE Name='%s' AND StorageId = %s", esc, edit_int64(dr->StorageId, ed1)); Dmsg1(200, "selectdevice: %s\n", cmd); if (QUERY_DB(jcr, cmd)) { num_rows = sql_num_rows(); /* * If more than one, report error, but return first row */ if (num_rows > 1) { Mmsg1(errmsg, _("More than one Device!: %d\n"), num_rows); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); } if (num_rows >= 1) { if ((row = sql_fetch_row()) == NULL) { Mmsg1(errmsg, _("error fetching Device row: %s\n"), sql_strerror()); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); sql_free_result(); goto bail_out; } dr->DeviceId = str_to_int64(row[0]); if (row[1]) { bstrncpy(dr->Name, row[1], sizeof(dr->Name)); } else { dr->Name[0] = 0; /* no name */ } sql_free_result(); retval = true; goto bail_out; } sql_free_result(); } /* * Must create it */ Mmsg(cmd, "INSERT INTO Device (Name,MediaTypeId,StorageId) VALUES ('%s',%s,%s)", esc, edit_uint64(dr->MediaTypeId, ed1), edit_int64(dr->StorageId, ed2)); Dmsg1(200, "Create Device: %s\n", cmd); dr->DeviceId = sql_insert_autokey_record(cmd, NT_("Device")); if (dr->DeviceId == 0) { Mmsg2(errmsg, _("Create db Device record %s failed: ERR=%s\n"), cmd, sql_strerror()); } else { retval = true; } bail_out: db_unlock(this); return retval; } /** * Create a Unique record for Storage -- no duplicates * Returns: false on failure * true on success with id in sr->StorageId */ bool B_DB::create_storage_record(JCR *jcr, STORAGE_DBR *sr) { SQL_ROW row; bool retval = false; int num_rows; char esc[MAX_ESCAPE_NAME_LENGTH]; db_lock(this); escape_string(jcr, esc, sr->Name, strlen(sr->Name)); Mmsg(cmd, "SELECT StorageId,AutoChanger FROM Storage WHERE Name='%s'", esc); sr->StorageId = 0; sr->created = false; /* * Check if it already exists */ if (QUERY_DB(jcr, cmd)) { num_rows = sql_num_rows(); /* * If more than one, report error, but return first row */ if (num_rows > 1) { Mmsg1(errmsg, _("More than one Storage record!: %d\n"), num_rows); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); } if (num_rows >= 1) { if ((row = sql_fetch_row()) == NULL) { Mmsg1(errmsg, _("error fetching Storage row: %s\n"), sql_strerror()); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); sql_free_result(); goto bail_out; } sr->StorageId = str_to_int64(row[0]); sr->AutoChanger = atoi(row[1]); /* bool */ sql_free_result(); retval = true; goto bail_out; } sql_free_result(); } /* * Must create it */ Mmsg(cmd, "INSERT INTO Storage (Name,AutoChanger)" " VALUES ('%s',%d)", esc, sr->AutoChanger); sr->StorageId = sql_insert_autokey_record(cmd, NT_("Storage")); if (sr->StorageId == 0) { Mmsg2(errmsg, _("Create DB Storage record %s failed. ERR=%s\n"), cmd, sql_strerror()); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); } else { sr->created = true; retval = true; } bail_out: db_unlock(this); return retval; } /** * Create Unique MediaType record * Returns: false on failure * true on success */ bool B_DB::create_mediatype_record(JCR *jcr, MEDIATYPE_DBR *mr) { bool retval = false; int num_rows; char esc[MAX_ESCAPE_NAME_LENGTH]; Dmsg0(200, "In create mediatype\n"); db_lock(this); escape_string(jcr, esc, mr->MediaType, strlen(mr->MediaType)); Mmsg(cmd, "SELECT MediaTypeId,MediaType FROM MediaType WHERE MediaType='%s'", esc); Dmsg1(200, "selectmediatype: %s\n", cmd); if (QUERY_DB(jcr, cmd)) { num_rows = sql_num_rows(); if (num_rows > 0) { Mmsg1(errmsg, _("mediatype record %s already exists\n"), mr->MediaType); sql_free_result(); goto bail_out; } sql_free_result(); } /* * Must create it */ Mmsg(cmd, "INSERT INTO MediaType (MediaType,ReadOnly) " "VALUES ('%s',%d)", mr->MediaType, mr->ReadOnly); Dmsg1(200, "Create mediatype: %s\n", cmd); mr->MediaTypeId = sql_insert_autokey_record(cmd, NT_("MediaType")); if (mr->MediaTypeId == 0) { Mmsg2(errmsg, _("Create db mediatype record %s failed: ERR=%s\n"), cmd, sql_strerror()); goto bail_out; } else { retval = true; } bail_out: db_unlock(this); return retval; } /** * Create Media record. VolumeName and non-zero Slot must be unique * Returns: false on failure * true on success with id in mr->MediaId */ bool B_DB::create_media_record(JCR *jcr, MEDIA_DBR *mr) { bool retval = false; char ed1[50], ed2[50], ed3[50], ed4[50], ed5[50], ed6[50], ed7[50], ed8[50]; char ed9[50], ed10[50], ed11[50], ed12[50]; int num_rows; char esc_medianame[MAX_ESCAPE_NAME_LENGTH]; char esc_mtype[MAX_ESCAPE_NAME_LENGTH]; char esc_status[MAX_ESCAPE_NAME_LENGTH]; db_lock(this); escape_string(jcr, esc_medianame, mr->VolumeName, strlen(mr->VolumeName)); escape_string(jcr, esc_mtype, mr->MediaType, strlen(mr->MediaType)); escape_string(jcr, esc_status, mr->VolStatus, strlen(mr->VolStatus)); Mmsg(cmd, "SELECT MediaId FROM Media WHERE VolumeName='%s'", esc_medianame); Dmsg1(500, "selectpool: %s\n", cmd); if (QUERY_DB(jcr, cmd)) { num_rows = sql_num_rows(); if (num_rows > 0) { Mmsg1(errmsg, _("Volume \"%s\" already exists.\n"), mr->VolumeName); sql_free_result(); goto bail_out; } sql_free_result(); } /* * Must create it */ Mmsg(cmd, "INSERT INTO Media (VolumeName,MediaType,MediaTypeId,PoolId,MaxVolBytes," "VolCapacityBytes,Recycle,VolRetention,VolUseDuration,MaxVolJobs,MaxVolFiles," "VolStatus,Slot,VolBytes,InChanger,VolReadTime,VolWriteTime," "EndFile,EndBlock,LabelType,StorageId,DeviceId,LocationId," "ScratchPoolId,RecyclePoolId,Enabled,ActionOnPurge,EncryptionKey," "MinBlocksize,MaxBlocksize) " "VALUES ('%s','%s',0,%u,%s,%s,%d,%s,%s,%u,%u,'%s',%d,%s,%d,%s,%s,0,0,%d,%s," "%s,%s,%s,%s,%d,%d,'%s',%d,%d)", esc_medianame, esc_mtype, mr->PoolId, edit_uint64(mr->MaxVolBytes,ed1), edit_uint64(mr->VolCapacityBytes, ed2), mr->Recycle, edit_uint64(mr->VolRetention, ed3), edit_uint64(mr->VolUseDuration, ed4), mr->MaxVolJobs, mr->MaxVolFiles, esc_status, mr->Slot, edit_uint64(mr->VolBytes, ed5), mr->InChanger, edit_int64(mr->VolReadTime, ed6), edit_int64(mr->VolWriteTime, ed7), mr->LabelType, edit_int64(mr->StorageId, ed8), edit_int64(mr->DeviceId, ed9), edit_int64(mr->LocationId, ed10), edit_int64(mr->ScratchPoolId, ed11), edit_int64(mr->RecyclePoolId, ed12), mr->Enabled, mr->ActionOnPurge, mr->EncrKey, mr->MinBlocksize, mr->MaxBlocksize); Dmsg1(500, "Create Volume: %s\n", cmd); mr->MediaId = sql_insert_autokey_record(cmd, NT_("Media")); if (mr->MediaId == 0) { Mmsg2(errmsg, _("Create DB Media record %s failed. ERR=%s\n"), cmd, sql_strerror()); } else { retval = true; if (mr->set_label_date) { char dt[MAX_TIME_LENGTH]; if (mr->LabelDate == 0) { mr->LabelDate = time(NULL); } bstrutime(dt, sizeof(dt), mr->LabelDate); Mmsg(cmd, "UPDATE Media SET LabelDate='%s' " "WHERE MediaId=%d", dt, mr->MediaId); retval = UPDATE_DB(jcr, cmd); } /* * Make sure that if InChanger is non-zero any other identical slot * has InChanger zero. */ make_inchanger_unique(jcr, mr); } bail_out: db_unlock(this); return retval; } /** * Create a Unique record for the client -- no duplicates * Returns: false on failure * true on success with id in cr->ClientId */ bool B_DB::create_client_record(JCR *jcr, CLIENT_DBR *cr) { bool retval = false; SQL_ROW row; char ed1[50], ed2[50]; int num_rows; char esc_clientname[MAX_ESCAPE_NAME_LENGTH]; char esc_uname[MAX_ESCAPE_NAME_LENGTH]; db_lock(this); escape_string(jcr, esc_clientname, cr->Name, strlen(cr->Name)); escape_string(jcr, esc_uname, cr->Uname, strlen(cr->Uname)); Mmsg(cmd, "SELECT ClientId,Uname FROM Client WHERE Name='%s'", esc_clientname); cr->ClientId = 0; if (QUERY_DB(jcr, cmd)) { num_rows = sql_num_rows(); /* * If more than one, report error, but return first row */ if (num_rows > 1) { Mmsg1(errmsg, _("More than one Client!: %d\n"), num_rows); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); } if (num_rows >= 1) { if ((row = sql_fetch_row()) == NULL) { Mmsg1(errmsg, _("error fetching Client row: %s\n"), sql_strerror()); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); sql_free_result(); goto bail_out; } cr->ClientId = str_to_int64(row[0]); if (row[1]) { bstrncpy(cr->Uname, row[1], sizeof(cr->Uname)); } else { cr->Uname[0] = 0; /* no name */ } sql_free_result(); retval = true; goto bail_out; } sql_free_result(); } /* * Must create it */ Mmsg(cmd, "INSERT INTO Client (Name,Uname,AutoPrune," "FileRetention,JobRetention) VALUES " "('%s','%s',%d,%s,%s)", esc_clientname, esc_uname, cr->AutoPrune, edit_uint64(cr->FileRetention, ed1), edit_uint64(cr->JobRetention, ed2)); cr->ClientId = sql_insert_autokey_record(cmd, NT_("Client")); if (cr->ClientId == 0) { Mmsg2(errmsg, _("Create DB Client record %s failed. ERR=%s\n"), cmd, sql_strerror()); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); } else { retval = true; } bail_out: db_unlock(this); return retval; } /** * Create a Unique record for the Path -- no duplicates * Returns: false on failure * true on success with id in cr->ClientId */ bool B_DB::create_path_record(JCR *jcr, ATTR_DBR *ar) { bool retval = false; SQL_ROW row; int num_rows; errmsg[0] = 0; esc_name = check_pool_memory_size(esc_name, 2 * pnl + 2); escape_string(jcr, esc_name, path, pnl); if (cached_path_id != 0 && cached_path_len == pnl && bstrcmp(cached_path, path)) { ar->PathId = cached_path_id; return true; } Mmsg(cmd, "SELECT PathId FROM Path WHERE Path='%s'", esc_name); if (QUERY_DB(jcr, cmd)) { num_rows = sql_num_rows(); if (num_rows > 1) { char ed1[30]; Mmsg2(errmsg, _("More than one Path!: %s for path: %s\n"), edit_uint64(num_rows, ed1), path); Jmsg(jcr, M_WARNING, 0, "%s", errmsg); } /* * Even if there are multiple paths, take the first one */ if (num_rows >= 1) { if ((row = sql_fetch_row()) == NULL) { Mmsg1(errmsg, _("error fetching row: %s\n"), sql_strerror()); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); sql_free_result(); ar->PathId = 0; ASSERT(ar->PathId); goto bail_out; } ar->PathId = str_to_int64(row[0]); sql_free_result(); /* * Cache path */ if (ar->PathId != cached_path_id) { cached_path_id = ar->PathId; cached_path_len = pnl; pm_strcpy(cached_path, path); } ASSERT(ar->PathId); retval = true; goto bail_out; } sql_free_result(); } Mmsg(cmd, "INSERT INTO Path (Path) VALUES ('%s')", esc_name); ar->PathId = sql_insert_autokey_record(cmd, NT_("Path")); if (ar->PathId == 0) { Mmsg2(errmsg, _("Create db Path record %s failed. ERR=%s\n"), cmd, sql_strerror()); Jmsg(jcr, M_FATAL, 0, "%s", errmsg); ar->PathId = 0; goto bail_out; } /* * Cache path */ if (ar->PathId != cached_path_id) { cached_path_id = ar->PathId; cached_path_len = pnl; pm_strcpy(cached_path, path); } retval = true; bail_out: return retval; } /** * Create a Unique record for the counter -- no duplicates * Returns: false on failure * true on success with counter filled in */ bool B_DB::create_counter_record(JCR *jcr, COUNTER_DBR *cr) { bool retval = false; char esc[MAX_ESCAPE_NAME_LENGTH]; COUNTER_DBR mcr; db_lock(this); memset(&mcr, 0, sizeof(mcr)); bstrncpy(mcr.Counter, cr->Counter, sizeof(mcr.Counter)); if (get_counter_record(jcr, &mcr)) { memcpy(cr, &mcr, sizeof(COUNTER_DBR)); retval = true; goto bail_out; } escape_string(jcr, esc, cr->Counter, strlen(cr->Counter)); /* * Must create it */ fill_query(SQL_QUERY_insert_counter_values, esc, cr->MinValue, cr->MaxValue, cr->CurrentValue, cr->WrapCounter); if (!INSERT_DB(jcr, cmd)) { Mmsg2(errmsg, _("Create DB Counters record %s failed. ERR=%s\n"), cmd, sql_strerror()); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); } else { retval = true; } bail_out: db_unlock(this); return retval; } /** * Create a FileSet record. This record is unique in the * name and the MD5 signature of the include/exclude sets. * Returns: false on failure * true on success with FileSetId in record */ bool B_DB::create_fileset_record(JCR *jcr, FILESET_DBR *fsr) { bool retval = false; SQL_ROW row; int num_rows, len; char esc_fs[MAX_ESCAPE_NAME_LENGTH]; char esc_md5[MAX_ESCAPE_NAME_LENGTH]; db_lock(this); fsr->created = false; escape_string(jcr, esc_fs, fsr->FileSet, strlen(fsr->FileSet)); escape_string(jcr, esc_md5, fsr->MD5, strlen(fsr->MD5)); Mmsg(cmd, "SELECT FileSetId,CreateTime FROM FileSet WHERE " "FileSet='%s' AND MD5='%s'", esc_fs, esc_md5); fsr->FileSetId = 0; if (QUERY_DB(jcr, cmd)) { num_rows = sql_num_rows(); if (num_rows > 1) { Mmsg1(errmsg, _("More than one FileSet!: %d\n"), num_rows); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); } if (num_rows >= 1) { if ((row = sql_fetch_row()) == NULL) { Mmsg1(errmsg, _("error fetching FileSet row: ERR=%s\n"), sql_strerror()); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); sql_free_result(); goto bail_out; } fsr->FileSetId = str_to_int64(row[0]); if (row[1] == NULL) { fsr->cCreateTime[0] = 0; } else { bstrncpy(fsr->cCreateTime, row[1], sizeof(fsr->cCreateTime)); } sql_free_result(); retval = true; goto bail_out; } sql_free_result(); } /* * Must create it */ if (fsr->CreateTime == 0 && fsr->cCreateTime[0] == 0) { fsr->CreateTime = time(NULL); } bstrutime(fsr->cCreateTime, sizeof(fsr->cCreateTime), fsr->CreateTime); if (fsr->FileSetText) { POOL_MEM esc_filesettext(PM_MESSAGE); len = strlen(fsr->FileSetText); esc_filesettext.check_size(len * 2 + 1); escape_string(jcr, esc_filesettext.c_str(), fsr->FileSetText, len); Mmsg(cmd, "INSERT INTO FileSet (FileSet,MD5,CreateTime,FileSetText) " "VALUES ('%s','%s','%s','%s')", esc_fs, esc_md5, fsr->cCreateTime, esc_filesettext.c_str()); } else { Mmsg(cmd, "INSERT INTO FileSet (FileSet,MD5,CreateTime,FileSetText) " "VALUES ('%s','%s','%s','')", esc_fs, esc_md5, fsr->cCreateTime); } fsr->FileSetId = sql_insert_autokey_record(cmd, NT_("FileSet")); if (fsr->FileSetId == 0) { Mmsg2(errmsg, _("Create DB FileSet record %s failed. ERR=%s\n"), cmd, sql_strerror()); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); goto bail_out; } else { fsr->created = true; retval = true; } bail_out: db_unlock(this); return retval; } /** * All sql_batch_* functions are used to do bulk batch insert in File/Filename/Path * tables. * * To sum up : * - bulk load a temp table * - insert missing paths into path with another single query (lock Path table to avoid duplicates). * - then insert the join between the temp, filename and path tables into file. * * Returns: false on failure * true on success */ bool B_DB::write_batch_file_records(JCR *jcr) { bool retval = false; int JobStatus = jcr->JobStatus; if (!jcr->batch_started) { /* no files to backup ? */ Dmsg0(50,"db_create_file_record : no files\n"); return true; } if (job_canceled(jcr)) { goto bail_out; } Dmsg1(50,"db_create_file_record changes=%u\n", changes); jcr->JobStatus = JS_AttrInserting; Jmsg(jcr, M_INFO, 0, "Insert of attributes batch table with %u entries start\n", jcr->db_batch->changes); if (!jcr->db_batch->sql_batch_end(jcr, NULL)) { Jmsg1(jcr, M_FATAL, 0, "Batch end %s\n", errmsg); goto bail_out; } if (job_canceled(jcr)) { goto bail_out; } /* * We have to lock tables */ if (!jcr->db_batch->sql_query(SQL_QUERY_batch_lock_path_query)) { Jmsg1(jcr, M_FATAL, 0, "Lock Path table %s\n", errmsg); goto bail_out; } if (!jcr->db_batch->sql_query(SQL_QUERY_batch_fill_path_query)) { Jmsg1(jcr, M_FATAL, 0, "Fill Path table %s\n",errmsg); jcr->db_batch->sql_query(SQL_QUERY_batch_unlock_tables_query); goto bail_out; } if (!jcr->db_batch->sql_query(SQL_QUERY_batch_unlock_tables_query)) { Jmsg1(jcr, M_FATAL, 0, "Unlock Path table %s\n", errmsg); goto bail_out; } if (!jcr->db_batch->sql_query( "INSERT INTO File (FileIndex, JobId, PathId, Name, LStat, MD5, DeltaSeq, Fhinfo, Fhnode) " "SELECT batch.FileIndex, batch.JobId, Path.PathId, " "batch.Name, batch.LStat, batch.MD5, batch.DeltaSeq, batch.Fhinfo, batch.Fhnode " "FROM batch " "JOIN Path ON (batch.Path = Path.Path) ")) { Jmsg1(jcr, M_FATAL, 0, "Fill File table %s\n", errmsg); goto bail_out; } jcr->JobStatus = JobStatus; /* reset entry status */ Jmsg(jcr, M_INFO, 0, "Insert of attributes batch table done\n"); retval = true; bail_out: sql_query("DROP TABLE batch"); jcr->batch_started = false; changes = 0; return retval; } /** * Create File record in B_DB * * In order to reduce database size, we store the File attributes, * the FileName, and the Path separately. In principle, there * is a single FileName record and a single Path record, no matter * how many times it occurs. This is this subroutine, we separate * the file and the path and fill temporary tables with this three records. * * Note: all routines that call this expect to be able to call * db_strerror(mdb) to get the error message, so the error message * MUST be edited into mdb->errmsg before returning an error status. * * Returns: false on failure * true on success */ bool B_DB::create_batch_file_attributes_record(JCR *jcr, ATTR_DBR *ar) { ASSERT(ar->FileType != FT_BASE); Dmsg1(dbglevel, "Fname=%s\n", ar->fname); Dmsg0(dbglevel, "put_file_into_catalog\n"); if (jcr->batch_started && jcr->db_batch->changes > BATCH_FLUSH) { jcr->db_batch->write_batch_file_records(jcr); } /* * Open the dedicated connection */ if (!jcr->batch_started) { if (!open_batch_connection(jcr)) { return false; /* error already printed */ } if (!jcr->db_batch->sql_batch_start(jcr)) { Mmsg1(errmsg, "Can't start batch mode: ERR=%s", jcr->db_batch->strerror()); Jmsg(jcr, M_FATAL, 0, "%s", errmsg); return false; } jcr->batch_started = true; } jcr->db_batch->split_path_and_file(jcr, ar->fname); return jcr->db_batch->sql_batch_insert(jcr, ar); } /** * Create File record in B_DB * * In order to reduce database size, we store the File attributes, * the FileName, and the Path separately. In principle, there * is a single Path record, no matter how many times it occurs. * This is this subroutine, we separate * the file name and the path and create two database records. * * Returns: false on failure * true on success */ bool B_DB::create_file_attributes_record(JCR *jcr, ATTR_DBR *ar) { bool retval = false; db_lock(this); Dmsg1(dbglevel, "Fname=%s\n", ar->fname); Dmsg0(dbglevel, "put_file_into_catalog\n"); split_path_and_file(jcr, ar->fname); if (!create_path_record(jcr, ar)) { goto bail_out; } Dmsg1(dbglevel, "create_path_record: %s\n", esc_name); /* Now create master File record */ if (!create_file_record(jcr, ar)) { goto bail_out; } Dmsg0(dbglevel, "create_file_record OK\n"); Dmsg2(dbglevel, "CreateAttributes Path=%s File=%s\n", path, fname); retval = true; bail_out: db_unlock(this); return retval; } /** * This is the master File entry containing the attributes. * The filename and path records have already been created. * Returns: false on failure * true on success with fileid filled in */ bool B_DB::create_file_record(JCR *jcr, ATTR_DBR *ar) { bool retval = false; static const char *no_digest = "0"; const char *digest; ASSERT(ar->JobId); ASSERT(ar->PathId); esc_name = check_pool_memory_size(esc_name, 2*fnl+2); escape_string(jcr, esc_name, fname, fnl); if (ar->Digest == NULL || ar->Digest[0] == 0) { digest = no_digest; } else { digest = ar->Digest; } /* Must create it */ Mmsg(cmd, "INSERT INTO File (FileIndex,JobId,PathId,Name," "LStat,MD5,DeltaSeq,Fhinfo,Fhnode) VALUES (%u,%u,%u,'%s','%s','%s',%u,%llu,%llu)", ar->FileIndex, ar->JobId, ar->PathId, esc_name, ar->attr, digest, ar->DeltaSeq, ar->Fhinfo, ar->Fhnode); ar->FileId = sql_insert_autokey_record(cmd, NT_("File")); if (ar->FileId == 0) { Mmsg2(errmsg, _("Create db File record %s failed. ERR=%s"), cmd, sql_strerror()); Jmsg(jcr, M_FATAL, 0, "%s", errmsg); } else { retval = true; } return retval; } /** * Create file attributes record, or base file attributes record * Returns: false on failure * true on success */ bool B_DB::create_attributes_record(JCR *jcr, ATTR_DBR *ar) { bool retval; errmsg[0] = 0; /* * Make sure we have an acceptable attributes record. */ if (!(ar->Stream == STREAM_UNIX_ATTRIBUTES || ar->Stream == STREAM_UNIX_ATTRIBUTES_EX)) { Mmsg1(errmsg, _("Attempt to put non-attributes into catalog. Stream=%d\n"), ar->Stream); Jmsg(jcr, M_FATAL, 0, "%s", errmsg); return false; } if (ar->FileType != FT_BASE) { if (batch_insert_available()) { retval = create_batch_file_attributes_record(jcr, ar); /* * Error message already printed */ } else { retval = create_file_attributes_record(jcr, ar); } } else if (jcr->HasBase) { retval = create_base_file_attributes_record(jcr, ar); } else { Mmsg0(errmsg, _("Cannot Copy/Migrate job using BaseJob.\n")); Jmsg(jcr, M_FATAL, 0, "%s", errmsg); retval = true; /* in copy/migration what do we do ? */ } return retval; } /** * Create Base File record in B_DB * Returns: false on failure * true on success */ bool B_DB::create_base_file_attributes_record(JCR *jcr, ATTR_DBR *ar) { bool retval; Dmsg1(dbglevel, "create_base_file Fname=%s\n", ar->fname); Dmsg0(dbglevel, "put_base_file_into_catalog\n"); db_lock(this); split_path_and_file(jcr, ar->fname); esc_name = check_pool_memory_size(esc_name, fnl * 2 + 1); escape_string(jcr, esc_name, fname, fnl); esc_path = check_pool_memory_size(esc_path, pnl * 2 + 1); escape_string(jcr, esc_path, path, pnl); Mmsg(cmd, "INSERT INTO basefile%lld (Path, Name) VALUES ('%s','%s')", (uint64_t)jcr->JobId, esc_path, esc_name); retval = INSERT_DB(jcr, cmd); db_unlock(this); return retval; } /** * Cleanup the base file temporary tables */ void B_DB::cleanup_base_file(JCR *jcr) { POOL_MEM buf(PM_MESSAGE); Mmsg(buf, "DROP TABLE new_basefile%lld", (uint64_t) jcr->JobId); sql_query(buf.c_str()); Mmsg(buf, "DROP TABLE basefile%lld", (uint64_t) jcr->JobId); sql_query(buf.c_str()); } /** * Put all base file seen in the backup to the BaseFile table * and cleanup temporary tables * Returns: false on failure * true on success */ bool B_DB::commit_base_file_attributes_record(JCR *jcr) { bool retval; char ed1[50]; db_lock(this); Mmsg(cmd, "INSERT INTO BaseFiles (BaseJobId, JobId, FileId, FileIndex) " "SELECT B.JobId AS BaseJobId, %s AS JobId, " "B.FileId, B.FileIndex " "FROM basefile%s AS A, new_basefile%s AS B " "WHERE A.Path = B.Path " "AND A.Name = B.Name " "ORDER BY B.FileId", edit_uint64(jcr->JobId, ed1), ed1, ed1); retval = sql_query(cmd); jcr->nb_base_files_used = sql_affected_rows(); cleanup_base_file(jcr); db_unlock(this); return retval; } /** * Find the last "accurate" backup state with Base jobs * 1) Get all files with jobid in list (F subquery) * 2) Take only the last version of each file (Temp subquery) => accurate list is ok * 3) Put the result in a temporary table for the end of job * * Returns: false on failure * true on success */ bool B_DB::create_base_file_list(JCR *jcr, char *jobids) { bool retval = false; POOL_MEM buf(PM_MESSAGE); db_lock(this); if (!*jobids) { Mmsg(errmsg, _("ERR=JobIds are empty\n")); goto bail_out; } fill_query(SQL_QUERY_create_temp_basefile, (uint64_t)jcr->JobId); if (!sql_query(cmd)) { goto bail_out; } fill_query(buf, SQL_QUERY_select_recent_version, jobids, jobids); fill_query(SQL_QUERY_create_temp_new_basefile, (uint64_t)jcr->JobId, buf.c_str()); retval = sql_query(cmd); bail_out: db_unlock(this); return retval; } /** * Create Restore Object record in B_DB * Returns: false on failure * true on success */ bool B_DB::create_restore_object_record(JCR *jcr, ROBJECT_DBR *ro) { bool retval = false; int plug_name_len; POOLMEM *esc_plug_name = get_pool_memory(PM_MESSAGE); db_lock(this); Dmsg1(dbglevel, "Oname=%s\n", ro->object_name); Dmsg0(dbglevel, "put_object_into_catalog\n"); fnl = strlen(ro->object_name); esc_name = check_pool_memory_size(esc_name, fnl * 2 + 1); escape_string(jcr, esc_name, ro->object_name, fnl); escape_object(jcr, ro->object, ro->object_len); plug_name_len = strlen(ro->plugin_name); esc_plug_name = check_pool_memory_size(esc_plug_name, plug_name_len*2+1); escape_string(jcr, esc_plug_name, ro->plugin_name, plug_name_len); Mmsg(cmd, "INSERT INTO RestoreObject (ObjectName,PluginName,RestoreObject," "ObjectLength,ObjectFullLength,ObjectIndex,ObjectType," "ObjectCompression,FileIndex,JobId) " "VALUES ('%s','%s','%s',%d,%d,%d,%d,%d,%d,%u)", esc_name, esc_plug_name, esc_obj, ro->object_len, ro->object_full_len, ro->object_index, ro->FileType, ro->object_compression, ro->FileIndex, ro->JobId); ro->RestoreObjectId = sql_insert_autokey_record(cmd, NT_("RestoreObject")); if (ro->RestoreObjectId == 0) { Mmsg2(errmsg, _("Create db Object record %s failed. ERR=%s"), cmd, sql_strerror()); Jmsg(jcr, M_FATAL, 0, "%s", errmsg); } else { retval = true; } db_unlock(this); free_pool_memory(esc_plug_name); return retval; } /** * Create a quota record if it does not exist. * Returns: false on failure * true on success */ bool B_DB::create_quota_record(JCR *jcr, CLIENT_DBR *cr) { bool retval = false; char ed1[50]; int num_rows; db_lock(this); Mmsg(cmd, "SELECT ClientId FROM Quota WHERE ClientId='%s'", edit_uint64(cr->ClientId,ed1)); if (QUERY_DB(jcr, cmd)) { num_rows = sql_num_rows(); if (num_rows == 1) { sql_free_result(); retval = true; goto bail_out; } sql_free_result(); } /* * Must create it */ Mmsg(cmd, "INSERT INTO Quota (ClientId, GraceTime, QuotaLimit)" " VALUES ('%s', '%s', %s)", edit_uint64(cr->ClientId, ed1), "0", "0"); if (!INSERT_DB(jcr, cmd)) { Mmsg2(errmsg, _("Create DB Quota record %s failed. ERR=%s\n"), cmd, sql_strerror()); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); } else { retval = true; } bail_out: db_unlock(this); return retval; } /** * Create a NDMP level mapping if it does not exist. * Returns: false on failure * true on success */ bool B_DB::create_ndmp_level_mapping(JCR *jcr, JOB_DBR *jr, char *filesystem) { bool retval = false; char ed1[50], ed2[50]; int num_rows; db_lock(this); esc_name = check_pool_memory_size(esc_name, strlen(filesystem) * 2 + 1); escape_string(jcr, esc_name, filesystem, strlen(filesystem)); Mmsg(cmd, "SELECT ClientId FROM NDMPLevelMap WHERE " "ClientId='%s' AND FileSetId='%s' AND FileSystem='%s'", edit_uint64(jr->ClientId, ed1), edit_uint64(jr->FileSetId, ed2), esc_name); if (QUERY_DB(jcr, cmd)) { num_rows = sql_num_rows(); if (num_rows == 1) { sql_free_result(); retval = true; goto bail_out; } sql_free_result(); } /* * Must create it */ Mmsg(cmd, "INSERT INTO NDMPLevelMap (ClientId, FilesetId, FileSystem, DumpLevel)" " VALUES ('%s', '%s', '%s', %s)", edit_uint64(jr->ClientId, ed1), edit_uint64(jr->FileSetId, ed2), esc_name, "0"); if (!INSERT_DB(jcr, cmd)) { Mmsg2(errmsg, _("Create DB NDMP Level Map record %s failed. ERR=%s\n"), cmd, sql_strerror()); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); } else { retval = true; } bail_out: db_unlock(this); return retval; } /** * Create a NDMP Job Environment String * Returns: false on failure * true on success */ bool B_DB::create_ndmp_environment_string(JCR *jcr, JOB_DBR *jr, char *name, char *value) { bool retval = false; char ed1[50], ed2[50]; char esc_envname[MAX_ESCAPE_NAME_LENGTH]; char esc_envvalue[MAX_ESCAPE_NAME_LENGTH]; db_lock(this); escape_string(jcr, esc_envname, name, strlen(name)); escape_string(jcr, esc_envvalue, value, strlen(value)); Mmsg(cmd, "INSERT INTO NDMPJobEnvironment (JobId, FileIndex, EnvName, EnvValue)" " VALUES ('%s', '%s', '%s', '%s')", edit_int64(jr->JobId, ed1), edit_uint64(jr->FileIndex, ed2), esc_envname, esc_envvalue); if (!INSERT_DB(jcr, cmd)) { Mmsg2(errmsg, _("Create DB NDMP Job Environment record %s failed. ERR=%s\n"), cmd, sql_strerror()); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); } else { retval = true; } db_unlock(this); return retval; } /** * Create a Job Statistics record. * Returns: false on failure * true on success */ bool B_DB::create_job_statistics(JCR *jcr, JOB_STATS_DBR *jsr) { time_t stime; bool retval = false; char dt[MAX_TIME_LENGTH]; char ed1[50], ed2[50], ed3[50], ed4[50]; db_lock(this); stime = jsr->SampleTime; ASSERT(stime != 0); bstrutime(dt, sizeof(dt), stime); /* * Create job statistics record */ Mmsg(cmd, "INSERT INTO JobStats (SampleTime, JobId, JobFiles, JobBytes, DeviceId)" " VALUES ('%s', %s, %s, %s, %s)", dt, edit_int64(jsr->JobId, ed1), edit_uint64(jsr->JobFiles, ed2), edit_uint64(jsr->JobBytes, ed3), edit_int64(jsr->DeviceId, ed4)); Dmsg1(200, "Create job stats: %s\n", cmd); if (!INSERT_DB(jcr, cmd)) { Mmsg2(errmsg, _("Create DB JobStats record %s failed. ERR=%s\n"), cmd, sql_strerror()); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); goto bail_out; } else { retval = true; } bail_out: db_unlock(this); return retval; } /** * Create a Device Statistics record. * Returns: false on failure * true on success */ bool B_DB::create_device_statistics(JCR *jcr, DEVICE_STATS_DBR *dsr) { time_t stime; bool retval = false; char dt[MAX_TIME_LENGTH]; char ed1[50], ed2[50], ed3[50], ed4[50], ed5[50], ed6[50]; char ed7[50], ed8[50], ed9[50], ed10[50], ed11[50], ed12[50]; db_lock(this); stime = dsr->SampleTime; ASSERT(stime != 0); bstrutime(dt, sizeof(dt), stime); /* * Create device statistics record */ Mmsg(cmd, "INSERT INTO DeviceStats (DeviceId, SampleTime, ReadTime, WriteTime," " ReadBytes, WriteBytes, SpoolSize, NumWaiting, NumWriters, MediaId," " VolCatBytes, VolCatFiles, VolCatBlocks)" " VALUES (%s, '%s', %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", edit_int64(dsr->DeviceId, ed1), dt, edit_uint64(dsr->ReadTime, ed2), edit_uint64(dsr->WriteTime, ed3), edit_uint64(dsr->ReadBytes, ed4), edit_uint64(dsr->WriteBytes, ed5), edit_uint64(dsr->SpoolSize, ed6), edit_uint64(dsr->NumWaiting, ed7), edit_uint64(dsr->NumWriters, ed8), edit_int64(dsr->MediaId, ed9), edit_uint64(dsr->VolCatBytes, ed10), edit_uint64(dsr->VolCatFiles, ed11), edit_uint64(dsr->VolCatBlocks, ed12)); Dmsg1(200, "Create device stats: %s\n", cmd); if (!INSERT_DB(jcr, cmd)) { Mmsg2(errmsg, _("Create DB DeviceStats record %s failed. ERR=%s\n"), cmd, sql_strerror()); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); goto bail_out; } else { retval = true; } bail_out: db_unlock(this); return retval; } /** * Create a tapealert record. * Returns: false on failure * true on success */ bool B_DB::create_tapealert_statistics(JCR *jcr, TAPEALERT_STATS_DBR *tsr) { time_t stime; bool retval = false; char dt[MAX_TIME_LENGTH]; char ed1[50], ed2[50]; db_lock(this); stime = tsr->SampleTime; ASSERT(stime != 0); bstrutime(dt, sizeof(dt), stime); /* * Create device statistics record */ Mmsg(cmd, "INSERT INTO TapeAlerts (DeviceId, SampleTime, AlertFlags)" " VALUES (%s, '%s', %s)", edit_int64(tsr->DeviceId, ed1), dt, edit_uint64(tsr->AlertFlags, ed2)); Dmsg1(200, "Create tapealert: %s\n", cmd); if (!INSERT_DB(jcr, cmd)) { Mmsg2(errmsg, _("Create DB TapeAlerts record %s failed. ERR=%s\n"), cmd, sql_strerror()); Jmsg(jcr, M_ERROR, 0, "%s", errmsg); goto bail_out; } else { retval = true; } bail_out: db_unlock(this); return retval; } #endif /* HAVE_SQLITE3 || HAVE_MYSQL || HAVE_POSTGRESQL || HAVE_INGRES || HAVE_DBI */
28.708108
115
0.605583
Acidburn0zzz
30a19e7445d08c0baac9ae0bbc2d884232c675a1
1,446
hpp
C++
apps/las2oci.hpp
libLAS/libLAS-1.6
92b4c1370785481f212cc7fec9623637233c1418
[ "BSD-3-Clause" ]
1
2019-02-13T14:41:23.000Z
2019-02-13T14:41:23.000Z
apps/las2oci.hpp
libLAS/libLAS-1.6
92b4c1370785481f212cc7fec9623637233c1418
[ "BSD-3-Clause" ]
1
2018-03-13T07:12:06.000Z
2018-03-13T07:12:06.000Z
apps/las2oci.hpp
libLAS/libLAS-1.6
92b4c1370785481f212cc7fec9623637233c1418
[ "BSD-3-Clause" ]
2
2021-05-17T02:09:16.000Z
2021-06-21T12:15:52.000Z
#ifndef LAS2OCI_HPP_INCLUDED #define LAS2OCI_HPP_INCLUDED #include "oci_wrapper.h" #include <stdlib.h> // god-awful hack because of GDAL/GeoTIFF's shitty include structure #define CPL_SERV_H_INCLUDED #include <liblas/liblas.hpp> #include <boost/cstdint.hpp> #include <boost/concept_check.hpp> #include <string> #include <sstream> #include <iostream> #include <fstream> #include <exception> #include <algorithm> #include <vector> #include <cctype> #include <cmath> #include <sys/stat.h> using namespace std; using namespace liblas; #ifdef _WIN32 #define compare_no_case(a,b,n) _strnicmp( (a), (b), (n) ) #else #define compare_no_case(a,b,n) strncasecmp( (a), (b), (n) ) #endif #include <boost/array.hpp> #include <boost/shared_ptr.hpp> typedef std::vector<boost::uint32_t> IDVector; typedef boost::shared_ptr< IDVector > IDVectorPtr; typedef struct { long* pc_ids; long* block_ids; long* num_points; OCILobLocator** locators; // =(OCILobLocator**) VSIMalloc( sizeof(OCILobLocator*) * 1 ); std::vector<boost::uint8_t>** blobs; long* srids; long* gtypes; OCIArray** element_arrays; OCIArray** coordinate_arrays; long size; } blocks; // typedef struct // { // double x0; // double x1; // double y0; // double y1; // double z0; // double z1; // bool bUse3d; // // } extent; #include "kdx_util.hpp" #include "oci_util.hpp" #endif // LAS2OCI
17.421687
92
0.674965
libLAS
30a2394057ff68551582ba148aa198343ee00668
407
cpp
C++
src/system/kernel/arch/sparc/arch_platform.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
2
2020-02-02T06:48:30.000Z
2020-04-05T13:58:32.000Z
src/system/kernel/arch/sparc/arch_platform.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
null
null
null
src/system/kernel/arch/sparc/arch_platform.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
1
2022-02-05T11:40:54.000Z
2022-02-05T11:40:54.000Z
/* Copyright 2019, Adrien Destugues, pulkomandy@pulkomandy.tk. * Distributed under the terms of the MIT License. */ #include <arch/platform.h> status_t arch_platform_init(struct kernel_args *kernelArgs) { return B_OK; } status_t arch_platform_init_post_vm(struct kernel_args *kernelArgs) { return B_OK; } status_t arch_platform_init_post_thread(struct kernel_args *kernelArgs) { return B_OK; }
14.535714
62
0.781327
Kirishikesan
30a7ede92394a9d33e79057d72973a78de7eb231
1,903
cpp
C++
detect_all_cycles.cpp
poojacos/graph_algos
a6e5d5f29b2c18fda73cfdace8781cbddc294650
[ "MIT" ]
null
null
null
detect_all_cycles.cpp
poojacos/graph_algos
a6e5d5f29b2c18fda73cfdace8781cbddc294650
[ "MIT" ]
null
null
null
detect_all_cycles.cpp
poojacos/graph_algos
a6e5d5f29b2c18fda73cfdace8781cbddc294650
[ "MIT" ]
null
null
null
// C++ program to print all the cycles // in an undirected graph //CONCEPT-use colors #include <bits/stdc++.h> using namespace std; const int N = 100000; // variables to be used // in both functions vector<int> graph[N]; vector<int> cycles[N]; // Function to mark the vertex with // different colors for different cycles void dfs_cycle(int node,int parent,int color[],int mark[],int par[],int cyclenumber){ if(color[node]==2)return; if(color[node]==1){ int curr=parent; cyclenumber++; mark[parent]=cyclenumber; //backtrack while(curr!=node){ curr=par[curr]; mark[curr]=cyclenumber; } return; } par[node]=parent; color[node]=1; for(int ii=0;ii<graph[node].size();ii++){ //if not visited previously if(graph[node][ii]==par[node])continue; dfs_cycle(graph[node][ii],node,color,mark,par,cyclenumber); } //all descendants seen so change the color color[node]=2; } // add the edges to the graph void addEdge(int u, int v) { graph[u].push_back(v); graph[v].push_back(u); } // Function to print the cycles void printCycles(int edges, int mark[], int& cyclenumber) { for (int i = 1; i <= edges; i++) { if (mark[i] != 0) cycles[mark[i]].push_back(i); } // print all the vertex with same cycle for (int i = 1; i <= cyclenumber; i++) { // Print the i-th cycle cout << "Cycle Number " << i << ": "; for (int x : cycles[i]) cout << x << " "; cout << endl; } } // Driver Code int main() { addEdge(1, 2); addEdge(2, 3); addEdge(3, 4); addEdge(4, 6); addEdge(4, 7); addEdge(5, 6); addEdge(3, 5); addEdge(7, 8); addEdge(6, 10); addEdge(5, 9); addEdge(10, 11); addEdge(11, 12); addEdge(11, 13); addEdge(12, 13); int color[N]; int par[N]; int mark[N]; int cyclenumber = 0; int edges = 13; dfs_cycle(1, 0, color, mark, par, cyclenumber); printCycles(edges, mark, cyclenumber); }
21.144444
85
0.620074
poojacos
30a90f9ce996f0be688e897fbc53ec7af868bc92
2,752
cpp
C++
csvreader.cpp
VITObelgium/cpp-infra
2a95a112439b21ff9125c2e6e29810a418b94a4d
[ "MIT" ]
1
2022-02-23T03:15:54.000Z
2022-02-23T03:15:54.000Z
csvreader.cpp
VITObelgium/cpp-infra
2a95a112439b21ff9125c2e6e29810a418b94a4d
[ "MIT" ]
null
null
null
csvreader.cpp
VITObelgium/cpp-infra
2a95a112439b21ff9125c2e6e29810a418b94a4d
[ "MIT" ]
null
null
null
#include "infra/csvreader.h" namespace inf { CsvReader::CsvReader(const fs::path& filename) : _charset(detect_character_set(filename)) , _dataset(gdal::VectorDataSet::open(filename, gdal::VectorType::Csv)) , _layer(_dataset.layer(0)) { } int32_t CsvReader::column_count() const { return _layer.layer_definition().field_count(); } std::string_view CsvReader::column_name(int32_t index) const { return _layer.layer_definition().field_definition(index).name(); } std::optional<int32_t> CsvReader::column_index(const std::string& name) const { if (auto index = _layer.layer_definition().field_index(name); index >= 0) { return index; } return {}; } CsvRowIterator CsvReader::begin() const { return CsvRowIterator(_layer, _charset); } CsvRowIterator CsvReader::end() const { return CsvRowIterator(); } CsvRow::CsvRow(const gdal::Feature& feat, inf::CharacterSet charSet) : _feature(&feat) , _charSet(charSet) { } bool CsvRow::column_is_empty(int32_t index) const noexcept { return _feature->field_as<std::string_view>(index).empty(); } std::string CsvRow::get_string(int32_t index) const noexcept { if (_charSet == CharacterSet::Utf8) { return std::string(_feature->field_as<std::string_view>(index)); } else { return convert_to_utf8(_feature->field_as<std::string_view>(index)); } } std::optional<int32_t> CsvRow::get_int32(int32_t index) const noexcept { return _feature->opt_field_as<int32_t>(index); } std::optional<int64_t> CsvRow::get_int64(int32_t index) const noexcept { return _feature->opt_field_as<int64_t>(index); } std::optional<double> CsvRow::get_double(int32_t index) const noexcept { auto val = _feature->field_as<std::string>(index); if (val.empty()) { return {}; } return CPLAtofM(val.c_str()); } bool CsvRow::operator==(const CsvRow& other) const { return _feature == other._feature; } CsvRowIterator::CsvRowIterator(gdal::Layer layer, inf::CharacterSet charSet) : _iterator(std::move(layer)) , _charset(charSet) , _currentRow(*_iterator, _charset) { } const CsvRow& CsvRowIterator::operator*() { return _currentRow; } const CsvRow* CsvRowIterator::operator->() { return &_currentRow; } CsvRowIterator& CsvRowIterator::operator++() { ++_iterator; _currentRow = CsvRow(*_iterator, _charset); return *this; } CsvRowIterator& CsvRowIterator::operator=(CsvRowIterator&& other) { if (this != &other) { _iterator = std::move(other._iterator); } return *this; } bool CsvRowIterator::operator==(const CsvRowIterator& other) const { return _iterator == other._iterator; } bool CsvRowIterator::operator!=(const CsvRowIterator& other) const { return !(*this == other); } }
21.5
79
0.704578
VITObelgium
dd63164241ee268e1eb32e5e92a5a6d709794b61
766
cpp
C++
interview_preparation_kit/string_manipulation/common_child.cpp
Surya-06/hackerrank
dc001aebe4d2a01adbb711d18089117ba6629b2b
[ "MIT" ]
null
null
null
interview_preparation_kit/string_manipulation/common_child.cpp
Surya-06/hackerrank
dc001aebe4d2a01adbb711d18089117ba6629b2b
[ "MIT" ]
null
null
null
interview_preparation_kit/string_manipulation/common_child.cpp
Surya-06/hackerrank
dc001aebe4d2a01adbb711d18089117ba6629b2b
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using namespace std; int** data; string a ,b; int max ( int a , int b ){ if ( a > b ) return a; return b; } int ss ( int ina , int inb ) { if ( ina == a.size() or inb==b.size() ) return 0; if ( data[ina][inb]!=-1 ) return data[ina][inb]; if ( a[ina]==b[inb] ){ data[ina][inb] = ss(ina+1,inb+1) + 1; return data[ina][inb]; } else{ data[ina][inb] = max ( ss(ina+1,inb) , ss(ina,inb+1) ); return data[ina][inb]; } return 0; } int main(int argc, char const *argv[]) { cin>>a>>b; data = new int*[a.size()+1]; for(int i=0;i<a.size()+1;i++){ data[i] = new int[b.size()+1]; for ( int j=0;j<b.size()+1;j++) data[i][j]=-1; } cout << ss (0,0) <<endl; return 0; }
18.682927
59
0.513055
Surya-06
dd645f424261ce5b53ea1744ecac4d11c2ca18b4
14,422
hpp
C++
include/types/mat.hpp
Oxsomi/core2
96d64fc5f47b6aee2e205205196e4bb1ddee59f6
[ "MIT" ]
null
null
null
include/types/mat.hpp
Oxsomi/core2
96d64fc5f47b6aee2e205205196e4bb1ddee59f6
[ "MIT" ]
12
2020-01-17T21:40:53.000Z
2020-11-18T18:13:35.000Z
include/types/mat.hpp
Oxsomi/core2
96d64fc5f47b6aee2e205205196e4bb1ddee59f6
[ "MIT" ]
null
null
null
#pragma once #include "vec.hpp" //Helper for generating matrices //All rotations and fovs are in radians //Matrix storage template<typename T, usz W, usz H> struct TMatStorage { union { T f[W * H]; T m[W][H]; Vec<T, W> axes[H]; }; constexpr inline TMatStorage(): f{} {} template<typename ...args> constexpr inline TMatStorage(const Vec<T, W> &axis, const args &...arg): axes{ axis, arg... } {} }; template<typename T> struct TMatStorage<T, 2, 2> { union { T f[4]; T m[2][2]; Vec2<T> axes[2]; struct { Vec2<T> x, y; }; }; constexpr inline TMatStorage(): f{} {} template<typename ...args> constexpr inline TMatStorage(const Vec2<T> &axis, const args &...arg): axes{ axis, arg... } {} }; template<typename T> struct TMatStorage<T, 3, 3> { union { T f[9]; T m[3][3]; Vec3<T> axes[3]; struct { Vec3<T> xAxis, yAxis, zAxis; }; struct { Vec2<T> x; T wx; Vec2<T> y; T wy; Vec2<T> pos; T one; }; }; constexpr inline TMatStorage(): f{} {} template<typename ...args> constexpr inline TMatStorage(const Vec3<T> &axis, const args &...arg): axes{ axis, arg... } {} }; template<typename T> struct TMatStorage<T, 4, 4> { union { T f[16]; T m[4][4]; Vec4<T> axes[4]; struct { Vec4<T> xAxis, yAxis, zAxis, pos4; }; struct { Vec3<T> x; T wx; Vec3<T> y; T wy; Vec3<T> z; T wz; Vec3<T> pos; T one; }; }; constexpr inline TMatStorage(): f{} {} template<typename ...args> constexpr inline TMatStorage(const Vec4<T> &axis0, const Vec4<T> &axis1, const args &...arg): axes{ axis0, axis1, arg... } {} }; template<typename T> struct TMatStorage<T, 4, 3> { union { T f[12]; T m[4][3]; Vec3<T> axes[4]; struct { Vec3<T> x, y, z, pos; }; }; constexpr inline TMatStorage(): f{} {} template<typename ...args> constexpr inline TMatStorage(const Vec3<T> &axis, const args &...arg): axes{ axis, arg... } {} }; //Col major matrix base template<typename T, usz W, usz H> struct Mat : public TMatStorage<T, W, H> { //Constants and types static constexpr usz N = W * H, diagonalN = W < H ? W : H; using Type = T; using Diagonal = Vec<T, diagonalN>; using Horizontal = Vec<T, W>; using Vertical = Vec<T, H>; using TMatStorage<T, W, H>::TMatStorage; using TMatStorage<T, W, H>::m; using TMatStorage<T, W, H>::f; using TMatStorage<T, W, H>::axes; static constexpr usz Height = H, Width = W; //Constructors Mat(const Mat&) = default; Mat(Mat&&) = default; Mat &operator=(const Mat&) = default; Mat &operator=(Mat&&) = default; //Scale matrix explicit constexpr inline Mat(const Diagonal &scale) { for (usz i = 0; i < diagonalN; ++i) m[i][i] = scale[i]; } //Identity constexpr inline Mat(): Mat(Diagonal(1)) { } // template<typename ...args> constexpr inline Mat(const Vec<T, W> &axis0, const Vec<T, W> &axis1, const args &...arg): TMatStorage<T, W, H>{ axis0, axis1, arg... } {} //Value matrix constexpr inline Mat(const T &t) { for (usz i = 0; i < N; ++i) f[i] = t; } //TODO: Constructor with T[N] and T[W][H] and T, T, T, ... //Empty matrix static constexpr inline Mat nil() { return Mat(0); } //Access to rows, cols and values static constexpr usz horizontal() { return W; } static constexpr usz vertical() { return H; } Vertical &operator[](const usz i) { return axes[i]; } constexpr const Vertical &operator[](const usz i) const { return axes[i]; } T &operator[](const Vec2usz &xy) { return m[xy.x][xy.y]; } constexpr const T &operator[](const Vec2usz &xy) const { return axes[xy.x][xy.y]; } constexpr Horizontal getHorizontal(const usz j) const { Vertical res; for (usz i = 0; i < W; ++i) res[i] = m[i][j]; return res; } constexpr const Vertical &getVertical(const usz i) const { return axes[i]; } //Arithmetic overloads constexpr Mat &operator+=(const Mat &other) { for (usz i = 0; i < W; ++i) axes[i] += other.axes[i]; return *this; } constexpr Mat &operator-=(const Mat &other) { for (usz i = 0; i < W; ++i) axes[i] -= other.axes[i]; return *this; } constexpr Mat &operator/=(const Mat &other) { for (usz i = 0; i < W; ++i) axes[i] /= other.axes[i]; return *this; } constexpr Mat &operator%=(const Mat &other) { for (usz i = 0; i < W; ++i) axes[i] %= other.axes[i]; return *this; } constexpr Mat operator+(const Mat &other) const { return Mat(*this) += other; } constexpr Mat operator-(const Mat &other) const { return Mat(*this) -= other; } constexpr Mat operator/(const Mat &other) const { return Mat(*this) /= other; } constexpr Mat operator%(const Mat &other) const { return Mat(*this) %= other; } //Since Matrix multiply is different, mulVal can be used to perform regular multiplications on the values constexpr Mat &mulVal(const Mat &other) { for (usz i = 0; i < W; ++i) axes[i] *= other.axes[i]; return *this; } static constexpr inline Mat mulVal(const Mat &a, const Mat &b) { return Mat(a).mulVal(b); } static constexpr inline Mat scale(const Diagonal &diag) { return Mat(diag); } //Comparison constexpr bool operator==(const Mat &other) const { return std::memcmp(f, other.f, sizeof(other)) == 0; } constexpr bool operator!=(const Mat &other) const { return std::memcmp(f, other.f, sizeof(other)); } //Matrix math //TODO: Inverse, determinant constexpr inline Vec<T, H> operator*(const Vec<T, W> &other) const { Vec<T, H> res{}; for (usz i = 0; i < W; ++i) for (usz j = 0; j < H; ++j) res[j] += m[i][j] * other[i]; return res; } constexpr inline Mat operator*(const Mat &other) const { Mat res; for (usz i = 0; i < W; ++i) for (usz j = 0; j < H; ++j) res.m[i][j] = getHorizontal(j).dot(other.getVertical(i)); return res; } constexpr inline Mat &operator*=(const Mat &other) { return *this = *this * other; } constexpr inline Mat<T, H, W> transpose() const { Mat<T, H, W> res{}; for (usz i = 0; i < W && i < H; ++i) for (usz j = 0; j < H && j < W; ++j) res.m[j][i] = m[i][j]; return res; } //Helpers inline Buffer toData() const { return Buffer((u8*)f, (u8*)(f + N)); } template<typename T2, usz W2, usz H2> constexpr inline Mat<T2, W2, H2> cast() const { Mat<T2, W2, H2> res{}; for (usz i = 0; i < W && i < W2; ++i) for (usz j = 0; j < H && j < H2; ++j) res.m[i][j] = T2(m[i][j]); return res; } template<typename T2> constexpr inline T2 cast() const { T2 res{}; for (usz i = 0; i < W && i < T2::horizontal(); ++i) for (usz j = 0; j < H && j < T2::vertical(); ++j) res.m[i][j] = typename T2::Type(m[i][j]); return res; } }; //Helper functions that carry to multiple types of matrices template<typename Mat, typename T> struct TMatHelper { static constexpr inline Mat rotateX(T v) { static_assert( std::is_floating_point_v<typename Mat::Type>, "Can't call TMatHelper<Mat>::rotateX if T isn't a floating point" ); static_assert( Mat::horizontal() > 2 && Mat::vertical() > 2, "Can't call TMatHelper<Mat>::rotateX if Mat's dimensions are less than 3x3" ); Mat res{}; res[1][1] = std::cos(v); res[2][1] = -std::sin(v); res[1][2] = std::sin(v); res[2][2] = std::cos(v); return res; } static constexpr inline Mat rotateY(T v) { static_assert( std::is_floating_point_v<typename Mat::Type>, "Can't call TMatHelper<Mat>::rotateY if T isn't a floating point" ); static_assert( Mat::horizontal() > 2 && Mat::vertical() > 2, "Can't call TMatHelper<Mat>::rotateY if Mat's dimensions are less than 3x3" ); Mat res{}; res[0][0] = std::cos(v); res[0][2] = -std::sin(v); res[2][0] = std::sin(v); res[2][2] = std::cos(v); return res; } static constexpr inline Mat rotateZ(T v) { static_assert( std::is_floating_point_v<typename Mat::Type>, "Can't call TMatHelper<Mat>::rotateZ if T isn't a floating point" ); static_assert( Mat::horizontal() > 1 && Mat::vertical() > 1, "Can't call TMatHelper<Mat>::rotateZ if Mat's dimensions are less than 2x2" ); Mat res{}; res[0][0] = std::cos(v); res[0][1] = -std::sin(v); res[1][0] = std::sin(v); res[1][1] = std::cos(v); return res; } }; //2x2 matrix template<typename T> struct Mat2x2 : public Mat<T, 2, 2> { using Mat<T, 2, 2>::Mat; using Mat<T, 2, 2>::f; constexpr inline Mat2x2(const Mat<T, 2, 2> &dat) : Mat<T, 2, 2>(dat) {} constexpr inline Mat2x2(Mat<T, 2, 2> &&dat) : Mat<T, 2, 2>(dat) {} //Rotate z static constexpr inline Mat2x2 rotateZ(T v) { return TMatHelper<Mat2x2, T>::rotateZ(v); } //Pad to vec4s inline Buffer toGPUData() const { Buffer result(0x20); //2 vec4s std::memcpy(result.data() + 0x00, f + 0x00, 0x08); std::memcpy(result.data() + 0x10, f + 0x08, 0x08); return result; } }; //3x3 matrix template<typename T> struct Mat3x3 : public Mat<T, 3, 3> { using Mat<T, 3, 3>::Mat; using Mat<T, 3, 3>::f; constexpr inline Mat3x3(const Mat<T, 3, 3> &dat) : Mat<T, 3, 3>(dat) {} constexpr inline Mat3x3(Mat<T, 3, 3> &&dat) : Mat<T, 3, 3>(dat) {} //TODO: rotateY3D, rotateZ3D, translate2D, transform2D, orientation3D, perspective/ortho //Rotate z static constexpr Mat3x3 rotateZ(T v) { return TMatHelper<Mat3x3, T>::rotateZ(v); } //Pad to vec4s inline Buffer toGPUData() const { Buffer result(0x30); //3 vec4s std::memcpy(result.data() + 0x00, f + 0x00, 0x0C); std::memcpy(result.data() + 0x10, f + 0x0C, 0x0C); std::memcpy(result.data() + 0x20, f + 0x18, 0x0C); return result; } }; //4x4 matrix template<typename T, usz W, usz H, typename = std::enable_if_t<W == 4 && (H == 3 || W == 4)>> struct MatOT : public Mat<T, W, H> { using Mat<T, W, H>::Mat; using Mat<T, W, H>::f; using Mat<T, W, H>::toData; constexpr inline MatOT(const Mat<T, W, H> &dat) : Mat<T, W, H>(dat) { } constexpr inline MatOT(Mat<T, W, H> &&dat) : Mat<T, W, H>(dat) {} //Rotation static constexpr inline MatOT rotateX(T v) { return TMatHelper<MatOT, T>::rotateX(v); } static constexpr inline MatOT rotateY(T v) { return TMatHelper<MatOT, T>::rotateY(v); } static constexpr inline MatOT rotateZ(T v) { return TMatHelper<MatOT, T>::rotateZ(v); } //Helper functions static constexpr inline MatOT translate(const Vec3<T> &pos) { MatOT res{}; res.pos = pos; return res; } static inline MatOT perspective(T fov, T asp, T n, T f) { static_assert( std::is_floating_point_v<T>, "Can't call MatOT::perspective if T isn't a floating point" ); static_assert(H == 4, "MatOT::perspective only allowed on 4x4 matrices"); T scale = T(1 / tan(fov / 2)); MatOT res( Vec4<T>(scale / asp, -scale, n / (f - n), 0) ); res.m[2][3] = -1; res.m[3][2] = f * n / (f - n); return res; } //TODO: Ortho static constexpr inline MatOT rotate(const Vec3<T> &rot) { return rotateX(rot.x) * rotateY(rot.y) * rotateZ(rot.z); } static constexpr inline MatOT scale(const Vec3<T> &scl) { if constexpr (H == 4) return Mat4x4<T>(Vec4<T>(scl.x, scl.y, scl.z, 1)); else return Mat4x3<T>(Vec3<T>(scl.x, scl.y, scl.z)); } static constexpr inline MatOT transform( const Vec3<T> &pos, const Vec3<T> &rot, const Vec3<T> &scl ) { return translate(pos) * rotate(rot) * scale(scl); } static constexpr inline MatOT view( const Vec3<T> &pos, const Vec3<T> &rot ) { return translate(-pos) * rotate(rot); } static constexpr inline MatOT lookAt( const Vec3<T> &eye, const Vec3<T> &center, const Vec3<T> &up ) { Vec3<T> z = (eye - center).normalize(); Vec3<T> x = (up.cross(z)).normalize(); Vec3<T> y = (z.cross(x)).normalize(); MatOT res; res.x = x; res.y = y; res.z = z; res.pos = -eye; if constexpr (H == 4) res.one = 1; return res; } static constexpr inline MatOT lookDirection( const Vec3<T> &eye, const Vec3<T> &dir, const Vec3<T> &up ) { Vec3<T> z = dir.normalize(); Vec3<T> x = (z.cross(up)).normalize(); Vec3<T> y = (x.cross(z)).normalize(); MatOT res; res.x = x; res.y = y; res.z = z; res.pos = -eye; if constexpr (H == 4) res.one = 1; return res; } //Get gpu data inline Buffer toGPUData() const { return toData(); } }; //Types //2x2 matrices (2d orientation) using Mat2x2i16 = Mat2x2<i16>; using Mat2x2u16 = Mat2x2<u16>; using Mat2x2i16 = Mat2x2<i16>; using Mat2x2u16 = Mat2x2<u16>; using Mat2x2b32 = Mat2x2<u32>; using Mat2x2f32 = Mat2x2<f32>; using Mat2x2i32 = Mat2x2<i32>; using Mat2x2u32 = Mat2x2<u32>; using Mat2x2i64 = Mat2x2<i64>; using Mat2x2u64 = Mat2x2<u64>; using Mat2x2f64 = Mat2x2<f64>; //3x3 matrices (3d orientation or 2d orientation + translation) using Mat3x3i16 = Mat3x3<i16>; using Mat3x3u16 = Mat3x3<u16>; using Mat3x3i16 = Mat3x3<i16>; using Mat3x3u16 = Mat3x3<u16>; using Mat3x3b32 = Mat3x3<u32>; using Mat3x3f32 = Mat3x3<f32>; using Mat3x3i32 = Mat3x3<i32>; using Mat3x3u32 = Mat3x3<u32>; using Mat3x3i64 = Mat3x3<i64>; using Mat3x3u64 = Mat3x3<u64>; using Mat3x3f64 = Mat3x3<f64>; //4x4 matrices (3d orientation + translation) template<typename T> using Mat4x4 = MatOT<T, 4, 4>; using Mat4x4i16 = Mat4x4<i16>; using Mat4x4u16 = Mat4x4<u16>; using Mat4x4i16 = Mat4x4<i16>; using Mat4x4u16 = Mat4x4<u16>; using Mat4x4b32 = Mat4x4<u32>; using Mat4x4f32 = Mat4x4<f32>; using Mat4x4i32 = Mat4x4<i32>; using Mat4x4u32 = Mat4x4<u32>; using Mat4x4i64 = Mat4x4<i64>; using Mat4x4u64 = Mat4x4<u64>; using Mat4x4f64 = Mat4x4<f64>; //4x3 matrices (3d orientation + translation) template<typename T> using Mat4x3 = MatOT<T, 4, 3>; using Mat4x3i16 = Mat4x3<i16>; using Mat4x3u16 = Mat4x3<u16>; using Mat4x3i16 = Mat4x3<i16>; using Mat4x3u16 = Mat4x3<u16>; using Mat4x3b32 = Mat4x3<u32>; using Mat4x3f32 = Mat4x3<f32>; using Mat4x3i32 = Mat4x3<i32>; using Mat4x3u32 = Mat4x3<u32>; using Mat4x3i64 = Mat4x3<i64>; using Mat4x3u64 = Mat4x3<u64>; using Mat4x3f64 = Mat4x3<f64>; namespace oic { template<typename T> struct is_matrix { static constexpr bool value = false; }; template<typename T, usz W, usz H> struct is_matrix<Mat<T, W, H>> { static constexpr bool value = true; }; template<typename T> struct is_matrix<Mat2x2<T>> { static constexpr bool value = true; }; template<typename T> struct is_matrix<Mat3x3<T>> { static constexpr bool value = true; }; template<typename T> struct is_matrix<Mat4x4<T>> { static constexpr bool value = true; }; template<typename T> struct is_matrix<Mat4x3<T>> { static constexpr bool value = true; }; template<typename T> static constexpr bool is_matrix_v = is_matrix<T>::value; }
23.112179
138
0.630495
Oxsomi
dd67e82e2b5df1e6dae23bcb1b1e013aedecc0ed
1,542
cpp
C++
src/DynamicRank.FreeForm.Library/libs/External/FreeForm2ExternalData.cpp
ltxtech/lightgbm-transform
ca3bdaae4e594c1bf74503c5ec151f2b794f855c
[ "MIT" ]
17
2021-11-02T13:52:10.000Z
2022-02-10T07:43:38.000Z
src/DynamicRank.FreeForm.Library/libs/External/FreeForm2ExternalData.cpp
ltxtech/lightgbm-transform
ca3bdaae4e594c1bf74503c5ec151f2b794f855c
[ "MIT" ]
2
2022-01-23T16:15:40.000Z
2022-03-07T15:54:34.000Z
src/DynamicRank.FreeForm.Library/libs/External/FreeForm2ExternalData.cpp
ltxtech/lightgbm-transform
ca3bdaae4e594c1bf74503c5ec151f2b794f855c
[ "MIT" ]
1
2022-01-21T09:42:59.000Z
2022-01-21T09:42:59.000Z
/*! * Copyright (c) 2021 Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE file in the project root for * license information. */ #include "FreeForm2ExternalData.h" #include <string> #include "FreeForm2Type.h" #include "TypeImpl.h" #include "TypeManager.h" FreeForm2::ExternalData::ExternalData(const std::string &p_name, const FreeForm2::TypeImpl &p_typeImpl) : m_name(p_name), m_type(&p_typeImpl), m_isCompileTimeConst(false) {} FreeForm2::ExternalData::ExternalData(const std::string &p_name, const TypeImpl &p_typeImpl, ConstantValue p_value) : m_name(p_name), m_type(&p_typeImpl), m_isCompileTimeConst(true), m_constantValue(p_value) {} FreeForm2::ExternalData::~ExternalData() {} const std::string &FreeForm2::ExternalData::GetName() const { return m_name; } const FreeForm2::TypeImpl &FreeForm2::ExternalData::GetType() const { return *m_type; } bool FreeForm2::ExternalData::IsCompileTimeConstant() const { return m_isCompileTimeConst; } FreeForm2::ConstantValue FreeForm2::ExternalData::GetCompileTimeValue() const { return m_constantValue; } FreeForm2::ExternalDataManager::ExternalDataManager() : m_typeFactory(new TypeFactory(TypeManager::CreateTypeManager())) {} FreeForm2::ExternalDataManager::~ExternalDataManager() {} FreeForm2::TypeFactory &FreeForm2::ExternalDataManager::GetTypeFactory() { return *m_typeFactory; }
30.84
79
0.705577
ltxtech
dd6bc353fe58b13922c2ef58692429852b1ed9ef
2,360
hpp
C++
framework/platform/android/tcuAndroidWindow.hpp
iabernikhin/VK-GL-CTS
a3338eb2ded98b5befda64f9325db0d219095a00
[ "Apache-2.0" ]
354
2017-01-24T17:12:38.000Z
2022-03-30T07:40:19.000Z
framework/platform/android/tcuAndroidWindow.hpp
iabernikhin/VK-GL-CTS
a3338eb2ded98b5befda64f9325db0d219095a00
[ "Apache-2.0" ]
275
2017-01-24T20:10:36.000Z
2022-03-24T16:24:50.000Z
framework/platform/android/tcuAndroidWindow.hpp
iabernikhin/VK-GL-CTS
a3338eb2ded98b5befda64f9325db0d219095a00
[ "Apache-2.0" ]
190
2017-01-24T18:02:04.000Z
2022-03-27T13:11:23.000Z
#ifndef _TCUANDROIDWINDOW_HPP #define _TCUANDROIDWINDOW_HPP /*------------------------------------------------------------------------- * drawElements Quality Program Tester Core * ---------------------------------------- * * Copyright 2014 The Android Open Source Project * * 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. * *//*! * \file * \brief Android window. *//*--------------------------------------------------------------------*/ #include "tcuDefs.hpp" #include "tcuVector.hpp" #include "deSemaphore.hpp" #include "deMutex.hpp" #include <vector> #include <android/native_window.h> namespace tcu { namespace Android { // \note Window is thread-safe, WindowRegistry is not class Window { public: enum State { STATE_AVAILABLE = 0, STATE_IN_USE, STATE_PENDING_DESTROY, STATE_READY_FOR_DESTROY, STATE_ACQUIRED_FOR_DESTROY, STATE_LAST }; Window (ANativeWindow* window); ~Window (void); bool tryAcquire (void); void release (void); void markForDestroy (void); bool isPendingDestroy (void) const; bool tryAcquireForDestroy(bool onlyMarked); ANativeWindow* getNativeWindow (void) { return m_window; } void setBuffersGeometry (int width, int height, int32_t format); IVec2 getSize (void) const; private: Window (const Window& other); Window& operator= (const Window& other); ANativeWindow* m_window; mutable de::Mutex m_stateLock; State m_state; }; class WindowRegistry { public: WindowRegistry (void); ~WindowRegistry (void); void addWindow (ANativeWindow* window); void destroyWindow (ANativeWindow* window); Window* tryAcquireWindow (void); void garbageCollect (void); private: std::vector<Window*> m_windows; }; } // Android } // tcu #endif // _TCUANDROIDWINDOW_HPP
23.137255
75
0.645339
iabernikhin
dd6d7a2708379614a1841ffc927dedf6ff8c7859
4,257
cpp
C++
blast/src/objtools/eutils/api/elink.cpp
mycolab/ncbi-blast
e59746cec78044d2bf6d65de644717c42f80b098
[ "Apache-2.0" ]
null
null
null
blast/src/objtools/eutils/api/elink.cpp
mycolab/ncbi-blast
e59746cec78044d2bf6d65de644717c42f80b098
[ "Apache-2.0" ]
null
null
null
blast/src/objtools/eutils/api/elink.cpp
mycolab/ncbi-blast
e59746cec78044d2bf6d65de644717c42f80b098
[ "Apache-2.0" ]
null
null
null
/* $Id: elink.cpp 196493 2010-07-06 00:37:12Z dicuccio $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: Aleksey Grichenko * * File Description: * EFetch request * */ #include <ncbi_pch.hpp> #include <objtools/eutils/api/elink.hpp> #include <cgi/cgi_util.hpp> BEGIN_NCBI_SCOPE CELink_Request::CELink_Request(const string& db, CRef<CEUtils_ConnContext>& ctx) : CEUtils_Request(ctx, "elink.fcgi"), m_RelDate(0), m_RetMode(eRetMode_none), m_Cmd(eCmd_none) { SetDatabase(db); } CELink_Request::~CELink_Request(void) { } inline const char* CELink_Request::x_GetRetModeName(void) const { static const char* s_RetModeName[] = { "none", "xml", "ref" }; return s_RetModeName[m_RetMode]; } inline const char* CELink_Request::x_GetCommandName(void) const { static const char* s_CommandName[] = { "none", "prlinks", "llinks", "llinkslib", "lcheck", "ncheck", "neighbor", "neighbor_score", "neighbor_history", "acheck" }; return s_CommandName[m_Cmd]; } string CELink_Request::GetQueryString(void) const { string args = TParent::GetQueryString(); if ( !m_DbFrom.empty() ) { args += "&dbfrom=" + NStr::URLEncode(m_DbFrom, NStr::eUrlEnc_ProcessMarkChars); } string ids = m_IdGroups.AsQueryString(); if ( !ids.empty() ) { args += "&" + ids; } if ( !m_Term.empty() ) { args += "&term=" + NStr::URLEncode(m_Term, NStr::eUrlEnc_ProcessMarkChars); } if ( m_RelDate ) { args += "&reldate" + NStr::IntToString(m_RelDate); } if ( !m_MinDate.IsEmpty() ) { args += "&mindate=" + NStr::URLEncode(m_MinDate.AsString("M/D/Y"), NStr::eUrlEnc_ProcessMarkChars); } if ( !m_MaxDate.IsEmpty() ) { args += "&maxdate=" + NStr::URLEncode(m_MaxDate.AsString("M/D/Y"), NStr::eUrlEnc_ProcessMarkChars); } if ( !m_DateType.empty() ) { args += "&datetype=" + m_DateType; } if ( m_RetMode != eRetMode_none ) { args += "&retmode="; args += x_GetRetModeName(); } if ( m_Cmd != eCmd_none ) { args += "&cmd="; args += x_GetCommandName(); } if ( !m_LinkName.empty() ) { args += "&linkname="; args += NStr::URLEncode(m_LinkName, NStr::eUrlEnc_ProcessMarkChars); } if ( !m_Holding.empty() ) { args += "&holding="; args += NStr::URLEncode(m_Holding, NStr::eUrlEnc_ProcessMarkChars); } if ( !m_Version.empty() ) { args += "&version="; args += NStr::URLEncode(m_Version, NStr::eUrlEnc_ProcessMarkChars); } return args; } ESerialDataFormat CELink_Request::GetSerialDataFormat(void) const { return eSerial_Xml; } CRef<elink::CELinkResult> CELink_Request::GetELinkResult(void) { CObjectIStream* is = GetObjectIStream(); _ASSERT(is); CRef<elink::CELinkResult> res(new elink::CELinkResult); *is >> *res; Disconnect(); return res; } END_NCBI_SCOPE
28.192053
77
0.612403
mycolab
dd6fc2943c3e92cafa915e06f0f9a2191e0dbd71
7,484
cpp
C++
source/MultiLibrary/Filesystem/Windows/Filesystem.cpp
danielga/multilibrary
3d1177dd3affa875e06015f5e3e42dda525f3336
[ "BSD-3-Clause" ]
2
2018-06-22T12:43:57.000Z
2019-05-31T21:56:27.000Z
source/MultiLibrary/Filesystem/Windows/Filesystem.cpp
danielga/multilibrary
3d1177dd3affa875e06015f5e3e42dda525f3336
[ "BSD-3-Clause" ]
1
2017-09-09T01:21:31.000Z
2017-11-12T17:52:56.000Z
source/MultiLibrary/Filesystem/Windows/Filesystem.cpp
danielga/multilibrary
3d1177dd3affa875e06015f5e3e42dda525f3336
[ "BSD-3-Clause" ]
1
2022-03-30T18:57:41.000Z
2022-03-30T18:57:41.000Z
/************************************************************************* * MultiLibrary - https://danielga.github.io/multilibrary/ * A C++ library that covers multiple low level systems. *------------------------------------------------------------------------ * Copyright (c) 2014-2022, Daniel Almeida * 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. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ #include <MultiLibrary/Filesystem/Filesystem.hpp> #include <MultiLibrary/Filesystem/File.hpp> #include <MultiLibrary/Filesystem/FileSimple.hpp> #include <MultiLibrary/Common/Unicode.hpp> #include <cstdlib> #include <cstdio> #include <iterator> #include <sys/stat.h> #include <windows.h> #include <direct.h> #undef CreateFile namespace MultiLibrary { namespace Internal { static uint64_t Find( const std::wstring &widefind, std::vector<std::wstring> &files, std::vector<std::wstring> &folders ) { WIN32_FIND_DATA find_data; uint64_t num_files = 0; HANDLE find_handle = FindFirstFileEx( widefind.c_str( ), FindExInfoStandard, &find_data, FindExSearchNameMatch, nullptr, 0 ); while( find_handle != INVALID_HANDLE_VALUE ) { std::wstring filename = find_data.cFileName; if( find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) { if( filename != L"." && filename != L".." ) { folders.push_back( filename ); ++num_files; } } else { files.push_back( filename ); ++num_files; } if( FindNextFile( find_handle, &find_data ) == FALSE ) break; } FindClose( find_handle ); return num_files; } static bool IsFolder( const std::wstring &widepath ) { struct _stat64 stat; if( _wstat64( widepath.c_str( ), &stat ) != 0 ) return false; return ( stat.st_mode & S_IFMT ) == S_IFDIR; } static bool RemoveFolder( const std::wstring &widepath, bool recursive ) { if( !IsFolder( widepath ) ) return false; if( recursive ) { std::vector<std::wstring> files; std::vector<std::wstring> folders; Find( widepath + L"/*", files, folders ); for( size_t k = 0; k != files.size( ); ++k ) if ( _wunlink( widepath.c_str( ) ) != 0 ) return false; for( size_t k = 0; k < folders.size( ); ++k ) if ( !RemoveFolder( widepath + L"/" + folders[k], true ) ) return false; } return _wrmdir( widepath.c_str( ) ) == 0; } } Filesystem::~Filesystem( ) { std::vector<FileInternal *>::iterator it, end = open_files.end( ); for( it = open_files.begin( ); it != end; ++it ) fclose( static_cast<FILE *>( ( *it )->Release( ) ) ); } File Filesystem::Open( const std::string &path, const char *mode ) { std::wstring widepath; UTF16::FromUTF8( path.begin( ), path.end( ), std::back_inserter( widepath ) ); std::wstring widemode; UTF16::FromUTF8( mode, mode + strlen( mode ), std::back_inserter( widemode ) ); FILE *file = _wfopen( widepath.c_str( ), widemode.c_str( ) ); if( file == nullptr ) return File( std::shared_ptr<FileInternal>( ) ); FileSimple *finternal = new FileSimple( this, file, path ); open_files.push_back( finternal ); return File( std::shared_ptr<FileInternal>( finternal ) ); } int64_t Filesystem::Size( const std::string &path ) { std::wstring widepath; UTF16::FromUTF8( path.begin( ), path.end( ), std::back_inserter( widepath ) ); struct _stat64 stat; if( _wstat64( widepath.c_str( ), &stat ) == 0 ) return stat.st_size; return -1; } bool Filesystem::Exists( const std::string &path ) { File file = Open( path, "r" ); if( file.IsValid( ) ) { file.Close( ); return true; } return false; } bool Filesystem::RemoveFile( const std::string &path ) { std::wstring widepath; UTF16::FromUTF8( path.begin( ), path.end( ), std::back_inserter( widepath ) ); return _wunlink( widepath.c_str( ) ) == 0; } uint64_t Filesystem::Find( const std::string &find, std::vector<std::string> &files, std::vector<std::string> &folders ) { std::wstring widefind; UTF16::FromUTF8( find.begin( ), find.end( ), std::back_inserter( widefind ) ); std::vector<std::wstring> wfiles; std::vector<std::wstring> wfolders; uint64_t num_files = Internal::Find( widefind, wfiles, wfolders ); files.reserve( wfiles.size( ) ); folders.reserve( wfolders.size( ) ); for( std::vector<std::wstring>::iterator it = wfiles.begin( ); it != wfiles.end( ); ++it ) { std::wstring &wfile = *it; std::string file; UTF8::FromUTF16( wfile.begin( ), wfile.end( ), std::back_inserter( file ) ); files.push_back( file ); } for( std::vector<std::wstring>::iterator it = wfolders.begin( ); it != wfolders.end( ); ++it ) { std::wstring &wfolder = *it; std::string folder; UTF8::FromUTF16( wfolder.begin( ), wfolder.end( ), std::back_inserter( folder ) ); folders.push_back( folder ); } return num_files; } bool Filesystem::IsFolder( const std::string &path ) { std::wstring widepath; UTF16::FromUTF8( path.begin( ), path.end( ), std::back_inserter( widepath ) ); return Internal::IsFolder( widepath ); } bool Filesystem::CreateFolder( const std::string &path ) { std::wstring widepath; UTF16::FromUTF8( path.begin( ), path.end( ), std::back_inserter( widepath ) ); return _wmkdir( widepath.c_str( ) ) == 0; } bool Filesystem::RemoveFolder( const std::string &path, bool recursive ) { std::wstring widepath; UTF16::FromUTF8( path.begin( ), path.end( ), std::back_inserter( widepath ) ); return Internal::RemoveFolder( widepath, recursive ); } std::string Filesystem::GetExecutablePath( ) { std::string path; wchar_t *widepath = _wpgmptr; if( widepath == nullptr ) return path; UTF8::FromUTF16( widepath, widepath + wcslen( widepath ), std::back_inserter( path ) ); return path; } bool Filesystem::Close( FileInternal *file ) { if( file == nullptr ) return false; std::vector<FileInternal *>::iterator it, end = open_files.end( ); for( it = open_files.begin( ); it != end; ++it ) if( *it == file ) { fclose( static_cast<FILE *>( file->Release( ) ) ); open_files.erase( it ); return true; } return false; } } // namespace MultiLibrary
29.234375
126
0.671833
danielga
dd707db35956550729f91f23ed4253756285de90
644
hpp
C++
C++/problems/0182_n_queens.hpp
raulhsant/algorithms
1578a0dc0a34d63c74c28dd87b0873e0b725a0bd
[ "MIT" ]
6
2019-03-20T22:23:26.000Z
2020-08-28T03:10:27.000Z
C++/problems/0182_n_queens.hpp
raulhsant/algorithms
1578a0dc0a34d63c74c28dd87b0873e0b725a0bd
[ "MIT" ]
15
2019-10-13T20:53:53.000Z
2022-03-31T02:01:35.000Z
C++/problems/0182_n_queens.hpp
raulhsant/algorithms
1578a0dc0a34d63c74c28dd87b0873e0b725a0bd
[ "MIT" ]
3
2019-03-11T10:57:46.000Z
2020-02-26T21:13:21.000Z
#ifndef N_QUEENS_HPP_INCLUDED #define N_QUEENS_HPP_INCLUDED #include <bits/stdc++.h> using namespace std; class Solution { private: vector<vector<string>> result; vector<string> createBoard(int n); bool checkColumn(const vector<string> &board,const int &row,const int & column); bool checkDiagonal(const vector<string> &board, const int &row, const int &column); bool checkIDiagonal(const vector<string> &board, const int &row, const int &column); void placeQueen(vector<string> board, int row); public: vector<vector<string>> solveNQueens(int n); }; #include "0182_n_queens.cpp" #endif
23.851852
88
0.704969
raulhsant
dd79134f524c1814c3c0b766e319640d6e358297
3,301
cpp
C++
libraries/ArduinoJson/test/JsonArray/add.cpp
tarontop/IRmqtt
5b3c0a4e442aeae46b62f6d8e0013d19c76e00d8
[ "MIT" ]
null
null
null
libraries/ArduinoJson/test/JsonArray/add.cpp
tarontop/IRmqtt
5b3c0a4e442aeae46b62f6d8e0013d19c76e00d8
[ "MIT" ]
1
2020-01-09T07:07:44.000Z
2020-01-09T07:07:44.000Z
libraries/ArduinoJson/test/JsonArray/add.cpp
tarontop/IRmqtt
5b3c0a4e442aeae46b62f6d8e0013d19c76e00d8
[ "MIT" ]
null
null
null
// ArduinoJson - arduinojson.org // Copyright Benoit Blanchon 2014-2018 // MIT License #include <ArduinoJson.h> #include <catch.hpp> TEST_CASE("JsonArray::add()") { DynamicJsonDocument doc; JsonArray _array = doc.to<JsonArray>(); SECTION("int") { _array.add(123); REQUIRE(123 == _array[0].as<int>()); REQUIRE(_array[0].is<int>()); REQUIRE(_array[0].is<double>()); } SECTION("double") { _array.add(123.45); REQUIRE(123.45 == _array[0].as<double>()); REQUIRE(_array[0].is<double>()); REQUIRE_FALSE(_array[0].is<bool>()); } SECTION("bool") { _array.add(true); REQUIRE(true == _array[0].as<bool>()); REQUIRE(_array[0].is<bool>()); REQUIRE_FALSE(_array[0].is<int>()); } SECTION("const char*") { const char* str = "hello"; _array.add(str); REQUIRE(str == _array[0].as<std::string>()); REQUIRE(_array[0].is<const char*>()); REQUIRE_FALSE(_array[0].is<int>()); } SECTION("nested array") { DynamicJsonDocument doc2; JsonArray arr = doc2.to<JsonArray>(); _array.add(arr); REQUIRE(arr == _array[0].as<JsonArray>()); REQUIRE(_array[0].is<JsonArray>()); REQUIRE_FALSE(_array[0].is<int>()); } SECTION("nested object") { DynamicJsonDocument doc2; JsonObject obj = doc2.to<JsonObject>(); _array.add(obj); REQUIRE(obj == _array[0].as<JsonObject>()); REQUIRE(_array[0].is<JsonObject>()); REQUIRE_FALSE(_array[0].is<int>()); } SECTION("array subscript") { const char* str = "hello"; DynamicJsonDocument doc2; JsonArray arr = doc2.to<JsonArray>(); arr.add(str); _array.add(arr[0]); REQUIRE(str == _array[0]); } SECTION("object subscript") { const char* str = "hello"; DynamicJsonDocument doc2; JsonObject obj = doc2.to<JsonObject>(); obj["x"] = str; _array.add(obj["x"]); REQUIRE(str == _array[0]); } SECTION("should not duplicate const char*") { _array.add("world"); const size_t expectedSize = JSON_ARRAY_SIZE(1); REQUIRE(expectedSize == doc.memoryUsage()); } SECTION("should duplicate char*") { _array.add(const_cast<char*>("world")); const size_t expectedSize = JSON_ARRAY_SIZE(1) + 6; REQUIRE(expectedSize == doc.memoryUsage()); } SECTION("should duplicate std::string") { _array.add(std::string("world")); const size_t expectedSize = JSON_ARRAY_SIZE(1) + 6; REQUIRE(expectedSize == doc.memoryUsage()); } SECTION("should not duplicate serialized(const char*)") { _array.add(serialized("{}")); const size_t expectedSize = JSON_ARRAY_SIZE(1); REQUIRE(expectedSize == doc.memoryUsage()); } SECTION("should duplicate serialized(char*)") { _array.add(serialized(const_cast<char*>("{}"))); const size_t expectedSize = JSON_ARRAY_SIZE(1) + 2; REQUIRE(expectedSize == doc.memoryUsage()); } SECTION("should duplicate serialized(std::string)") { _array.add(serialized(std::string("{}"))); const size_t expectedSize = JSON_ARRAY_SIZE(1) + 2; REQUIRE(expectedSize == doc.memoryUsage()); } SECTION("should duplicate serialized(std::string)") { _array.add(serialized(std::string("\0XX", 3))); const size_t expectedSize = JSON_ARRAY_SIZE(1) + 3; REQUIRE(expectedSize == doc.memoryUsage()); } }
25.992126
59
0.633141
tarontop
dd7ff997434a60045ef2756e488b922394b5f920
2,285
cc
C++
cc_mocks/socket.cc
piskorzj/node-packet-socket
151d985dced6fbbd3619e46572b9a6006a689d7a
[ "MIT" ]
7
2017-02-28T14:07:10.000Z
2019-10-08T18:49:42.000Z
cc_mocks/socket.cc
piskorzj/node-packet-socket
151d985dced6fbbd3619e46572b9a6006a689d7a
[ "MIT" ]
2
2017-04-02T12:24:00.000Z
2017-06-08T23:03:00.000Z
cc_mocks/socket.cc
piskorzj/node-packet-socket
151d985dced6fbbd3619e46572b9a6006a689d7a
[ "MIT" ]
null
null
null
#include "CppUTestExt/MockSupport.h" #include "socket.hh" #include <stdexcept> Socket::Socket(const char * device) { mock().actualCall("socket_constructor") .withStringParameter("device", device); if(!mock().returnBoolValueOrDefault(true)) { throw std::runtime_error("forced creation failure"); } } Socket::~Socket() {} int Socket::get_descriptor(void) { return mock().actualCall("get_descriptor").returnIntValue(); } int Socket::send_message(const unsigned char *destination_address, const char *message, int message_length) { mock().actualCall("send_message") .withMemoryBufferParameter("destination_address", destination_address, ETHER_ADDR_LEN) .withMemoryBufferParameter("message", (const unsigned char*)message, message_length) .withIntParameter("message_length", message_length); int return_value = mock().returnIntValueOrDefault(6); if(return_value == -1) { throw std::runtime_error("forced send_message failure"); } return return_value; } int Socket::receive_message(unsigned char *source_address, unsigned char *destination_address, char *buffer, int buffer_size) { mock().actualCall("receive_message") .withOutputParameter("source_address", source_address) .withOutputParameter("destination_address", destination_address) .withOutputParameter("buffer", buffer) .withIntParameter("buffer_size", buffer_size); int return_value = mock().returnIntValueOrDefault(6); if(return_value == -1) { throw std::runtime_error("forced receive_message failure"); } return return_value; } void Socket::add_membership(Socket::MembershipType type, const unsigned char *multicast_address) { mock().actualCall("add_membership") .withIntParameter("type", type) .withMemoryBufferParameter("multicast_address", multicast_address, ETHER_ADDR_LEN); if(!mock().returnBoolValueOrDefault(true)) { throw std::runtime_error("forced add_membership failure"); } } void Socket::drop_membership(Socket::MembershipType type, const unsigned char *multicast_address) { mock().actualCall("drop_membership") .withIntParameter("type", type) .withMemoryBufferParameter("multicast_address", multicast_address, ETHER_ADDR_LEN); if(!mock().returnBoolValueOrDefault(true)) { throw std::runtime_error("forced drop_membership failure"); } }
34.621212
89
0.76849
piskorzj
dd832ab319ce4878ad080464c4635919732aee27
1,687
hpp
C++
jsonrpc/serverMgr.hpp
flexibity-team/boost-tools
a6c67eacf7374136f9903680308334fc3408ba91
[ "MIT" ]
null
null
null
jsonrpc/serverMgr.hpp
flexibity-team/boost-tools
a6c67eacf7374136f9903680308334fc3408ba91
[ "MIT" ]
null
null
null
jsonrpc/serverMgr.hpp
flexibity-team/boost-tools
a6c67eacf7374136f9903680308334fc3408ba91
[ "MIT" ]
2
2019-12-26T13:54:29.000Z
2020-10-31T10:19:13.000Z
/* * serverMgr.hpp * * Created on: Oct 8, 2015 * Author: romeo */ #ifndef INCLUDE_FLEXIBITY_JSONRPC_SERVERMGR_HPP_ #define INCLUDE_FLEXIBITY_JSONRPC_SERVERMGR_HPP_ #include "flexibity/jsonrpc/jsonRpcSerial.hpp" #include "flexibity/jsonrpc/jsonRpcWebsocketClient.hpp" #include "flexibity/genericMgr.hpp" namespace Flexibity{ class serverMgr: public genericMgr<jsonRpcTransport::sPtr>{ public: static constexpr const char* uriOption = "uri"; static constexpr const char* nameOption = "name"; static constexpr const char* serialPrefix = "serial://"; static constexpr const char* wsPrefix = "ws://"; static constexpr const char* wssPrefix = "wss://"; serverMgr(const Json::Value& cfg, serialPortMgr::sPtr pm){ ILOG_INIT(); populateItems(cfg, [&](const Json::Value& iCfg){ return serverFactory(iCfg, pm); }); } static jsonRpcTransport::sPtr serverFactory(const Json::Value& iCfg, serialPortMgr::sPtr pm){ string uri = iCfg[uriOption].asString(); string name = iCfg[nameOption].asString(); //setInstanceName(name); auto resource = getResource(uri, serialPrefix); if (resource.length() > 0) { auto srv = make_shared<jsonRpcSerial>(pm, resource); srv->setInstanceName(name); return srv; } resource = getResource(uri, wsPrefix); if (resource.length() > 0) { return make_shared<jsonRpcWebsocketClient>(iCfg); } //TODO: wss scheme return make_shared<jsonRpcTransport>(); } static const string getResource(const string& uri, const string& prefix){ auto pos = uri.find(prefix); if(pos == 0){ return string(uri, prefix.length()); } return ""; } }; } #endif /* INCLUDE_FLEXIBITY_JSONRPC_SERVERMGR_HPP_ */
23.109589
94
0.713693
flexibity-team
dd8497defaf062ee6fc3a88753ba4c155c430632
717
hpp
C++
include/SerialFiller/Crc16Ccitt1021.hpp
gbmhunter/SerialFiller
d678acbf6d29de7042d48c6be8ecef556bb6d857
[ "MIT" ]
9
2019-04-01T16:27:15.000Z
2022-03-14T19:45:34.000Z
include/SerialFiller/Crc16Ccitt1021.hpp
gbmhunter/SerialFiller
d678acbf6d29de7042d48c6be8ecef556bb6d857
[ "MIT" ]
12
2017-06-18T05:06:36.000Z
2018-01-30T21:55:39.000Z
include/SerialFiller/Crc16Ccitt1021.hpp
mbedded-ninja/SerialFiller
d678acbf6d29de7042d48c6be8ecef556bb6d857
[ "MIT" ]
3
2019-09-07T16:56:57.000Z
2022-02-08T03:25:28.000Z
/// /// \file Crc16Ccitt1021.hpp /// \author Geoffrey Hunter <gbmhunter@gmail.com> (www.mbedded.ninja) /// \edited n/a /// \created 2017-06-10 /// \last-modified 2018-01-25 /// \brief Contains the Crc16Ccitt1021 class. /// \details /// See README.rst in root dir for more info. #ifndef MN_SERIAL_FILLER_CRC16_CCITT_1021_H_ #define MN_SERIAL_FILLER_CRC16_CCITT_1021_H_ // Local includes #include "SerialFiller/SerialFiller.hpp" namespace mn { namespace SerialFiller { class Crc16Ccitt1021 { public: static uint16_t Calc(ByteArray data); }; } // namespace SerialFiller } // namespace mn #endif // #ifndef MN_SERIAL_FILLER_CRC16_CCITT_1021_H_
24.724138
72
0.680614
gbmhunter
dd849dbe0685f69864b08ab75120ea54905c2858
2,024
cpp
C++
DSA Crack Sheet/solutions/Minimum Cost of ropes.cpp
Akshad7829/DataStructures-Algorithms
439822c6a374672d1734e2389d3fce581a35007d
[ "MIT" ]
5
2021-08-10T18:47:49.000Z
2021-08-21T15:42:58.000Z
DSA Crack Sheet/solutions/Minimum Cost of ropes.cpp
Akshad7829/DataStructures-Algorithms
439822c6a374672d1734e2389d3fce581a35007d
[ "MIT" ]
2
2022-02-25T13:36:46.000Z
2022-02-25T14:06:44.000Z
DSA Crack Sheet/solutions/Minimum Cost of ropes.cpp
Akshad7829/DataStructures-Algorithms
439822c6a374672d1734e2389d3fce581a35007d
[ "MIT" ]
1
2021-08-11T06:36:42.000Z
2021-08-11T06:36:42.000Z
/* Minimum Cost of ropes ===================== There are given N ropes of different lengths, we need to connect these ropes into one rope. The cost to connect two ropes is equal to sum of their lengths. The task is to connect the ropes with minimum cost. Example 1: Input: n = 4 arr[] = {4, 3, 2, 6} Output: 29 Explanation: For example if we are given 4 ropes of lengths 4, 3, 2 and 6. We can connect the ropes in following ways. 1) First connect ropes of lengths 2 and 3. Now we have three ropes of lengths 4, 6 and 5. 2) Now connect ropes of lengths 4 and 5. Now we have two ropes of lengths 6 and 9. 3) Finally connect the two ropes and all ropes have connected. Total cost for connecting all ropes is 5 + 9 + 15 = 29. This is the optimized cost for connecting ropes. Other ways of connecting ropes would always have same or more cost. For example, if we connect 4 and 6 first (we get three strings of 3, 2 and 10), then connect 10 and 3 (we get two strings of 13 and 2). Finally we connect 13 and 2. Total cost in this way is 10 + 13 + 15 = 38. Example 2: Input: n = 5 arr[] = {4, 2, 7, 6, 9} Output: 62 Explanation: First, connect ropes 4 and 2, which makes the array {6,7,6,9}. Next, add ropes 6 and 6, which results in {12,7,9}. Then, add 7 and 9, which makes the array {12,16}. And finally add these two which gives {28}. Hence, the total cost is 6 + 12 + 16 + 28 = 62. Your Task: You don't need to read input or print anything. Your task isto complete the function minCost() which takes 2 arguments and returns the minimum cost. Expected Time Complexity : O(nlogn) Expected Auxilliary Space : O(n) Constraints: 1 ≤ N ≤ 100000 1 ≤ arr[i] ≤ 106 */ long long minCost(long long arr[], long long n) { priority_queue<long long, vector<long long>, greater<long long>> pq; long long cost = 0; for (int i = 0; i < n; ++i) pq.push(arr[i]); while (pq.size() > 1) { auto a = pq.top(); pq.pop(); auto b = pq.top(); pq.pop(); cost += (a + b); pq.push(a + b); } return cost; }
25.948718
207
0.676877
Akshad7829
dd8ef8e0c9f40df27ada5889ed871b1821998a93
12,579
cpp
C++
experiments/rmi_lookup.cpp
alhuan/analysis-rmi
be787ee9a02e04210d41af51c8a053f6dea575e9
[ "Apache-2.0" ]
9
2021-07-01T17:00:42.000Z
2022-03-23T09:21:17.000Z
experiments/rmi_lookup.cpp
alhuan/analysis-rmi
be787ee9a02e04210d41af51c8a053f6dea575e9
[ "Apache-2.0" ]
1
2021-07-20T13:39:27.000Z
2021-07-20T13:39:27.000Z
experiments/rmi_lookup.cpp
alhuan/analysis-rmi
be787ee9a02e04210d41af51c8a053f6dea575e9
[ "Apache-2.0" ]
1
2022-01-25T16:39:34.000Z
2022-01-25T16:39:34.000Z
#include <chrono> #include <random> #include "argparse/argparse.hpp" #include "rmi/models.hpp" #include "rmi/rmi.hpp" #include "rmi/util/fn.hpp" #include "rmi/util/search.hpp" using key_type = uint64_t; using namespace std::chrono; std::size_t s_glob; ///< global size_t variable /** * Measures lookup times of @p samples on a given @p Rmi and writes results to `std::cout`. * @tparam Key key type * @tparam Rmi RMI type * @tparam Search search type * @param keys on which the RMI is built * @param n_models number of models in the second layer of the RMI * @param samples for which the lookup time is measured * @param n_reps number of repetitions * @param dataset_name name of the dataset * @param layer1 model type of the first layer * @param layer2 model type of the second layer * @param bound_type used by the RMI * @param search used by the RMI for correction prediction errors */ template<typename Key, typename Rmi, typename Search> void experiment(const std::vector<key_type> &keys, const std::size_t n_models, const std::vector<key_type> &samples, const std::size_t n_reps, const std::string dataset_name, const std::string layer1, const std::string layer2, const std::string bound_type, const std::string search) { using rmi_type = Rmi; auto search_fn = Search(); // Build RMI. rmi_type rmi(keys, n_models); // Perform n_reps runs. for (std::size_t rep = 0; rep != n_reps; ++rep) { // Lookup time. std::size_t lookup_accu = 0; auto start = steady_clock::now(); for (std::size_t i = 0; i != samples.size(); ++i) { auto key = samples.at(i); auto range = rmi.search(key); auto pos = search_fn(keys.begin() + range.lo, keys.begin() + range.hi, keys.begin() + range.pos, key); lookup_accu += std::distance(keys.begin(), pos); } auto stop = steady_clock::now(); auto lookup_time = duration_cast<nanoseconds>(stop - start).count(); s_glob = lookup_accu; // Report results. // Dataset std::cout << dataset_name << ',' << keys.size() << ',' // Index << layer1 << ',' << layer2 << ',' << n_models << ',' << bound_type << ',' << search << ',' << rmi.size_in_bytes() << ',' // Experiment << rep << ',' << samples.size() << ',' // Results << lookup_time << ',' // Checksums << lookup_accu << std::endl; } // reps } /** * @brief experiment function pointer */ typedef void (*exp_fn_ptr)(const std::vector<key_type>&, const std::size_t, const std::vector<key_type>&, const std::size_t, const std::string, const std::string, const std::string, const std::string, const std::string); /** * RMI configuration that holds the string representation of model types of layer 1 and layer 2, error bound type, and * search algorithm. */ struct Config { std::string layer1; std::string layer2; std::string bound_type; std::string search; }; /** * Comparator class for @p Config objects. */ struct ConfigCompare { bool operator() (const Config &lhs, const Config &rhs) const { if (lhs.layer1 != rhs.layer1) return lhs.layer1 < rhs.layer1; if (lhs.layer2 != rhs.layer2) return lhs.layer2 < rhs.layer2; if (lhs.bound_type != rhs.bound_type) return lhs.bound_type < rhs.bound_type; return lhs.search < rhs.search; } }; #define ENTRIES(L1, L2, LT1, LT2) \ { {#L1, #L2, "none", "binary"}, &experiment<key_type, rmi::Rmi<key_type, LT1, LT2>, BinarySearch> }, \ { {#L1, #L2, "labs", "binary"}, &experiment<key_type, rmi::RmiLAbs<key_type, LT1, LT2>, BinarySearch> }, \ { {#L1, #L2, "lind", "binary"}, &experiment<key_type, rmi::RmiLInd<key_type, LT1, LT2>, BinarySearch> }, \ { {#L1, #L2, "gabs", "binary"}, &experiment<key_type, rmi::RmiGAbs<key_type, LT1, LT2>, BinarySearch> }, \ { {#L1, #L2, "gind", "binary"}, &experiment<key_type, rmi::RmiGInd<key_type, LT1, LT2>, BinarySearch> }, \ { {#L1, #L2, "none", "model_biased_binary"}, &experiment<key_type, rmi::Rmi<key_type, LT1, LT2>, ModelBiasedBinarySearch> }, \ { {#L1, #L2, "labs", "model_biased_binary"}, &experiment<key_type, rmi::RmiLAbs<key_type, LT1, LT2>, ModelBiasedBinarySearch> }, \ { {#L1, #L2, "lind", "model_biased_binary"}, &experiment<key_type, rmi::RmiLInd<key_type, LT1, LT2>, ModelBiasedBinarySearch> }, \ { {#L1, #L2, "gabs", "model_biased_binary"}, &experiment<key_type, rmi::RmiGAbs<key_type, LT1, LT2>, ModelBiasedBinarySearch> }, \ { {#L1, #L2, "gind", "model_biased_binary"}, &experiment<key_type, rmi::RmiGInd<key_type, LT1, LT2>, ModelBiasedBinarySearch> }, \ { {#L1, #L2, "none", "linear"}, &experiment<key_type, rmi::Rmi<key_type, LT1, LT2>, LinearSearch> }, \ { {#L1, #L2, "labs", "linear"}, &experiment<key_type, rmi::RmiLAbs<key_type, LT1, LT2>, LinearSearch> }, \ { {#L1, #L2, "lind", "linear"}, &experiment<key_type, rmi::RmiLInd<key_type, LT1, LT2>, LinearSearch> }, \ { {#L1, #L2, "gabs", "linear"}, &experiment<key_type, rmi::RmiGAbs<key_type, LT1, LT2>, LinearSearch> }, \ { {#L1, #L2, "gind", "linear"}, &experiment<key_type, rmi::RmiGInd<key_type, LT1, LT2>, LinearSearch> }, \ { {#L1, #L2, "none", "model_biased_linear"}, &experiment<key_type, rmi::Rmi<key_type, LT1, LT2>, ModelBiasedLinearSearch> }, \ { {#L1, #L2, "labs", "model_biased_linear"}, &experiment<key_type, rmi::RmiLAbs<key_type, LT1, LT2>, ModelBiasedLinearSearch> }, \ { {#L1, #L2, "lind", "model_biased_linear"}, &experiment<key_type, rmi::RmiLInd<key_type, LT1, LT2>, ModelBiasedLinearSearch> }, \ { {#L1, #L2, "gabs", "model_biased_linear"}, &experiment<key_type, rmi::RmiGAbs<key_type, LT1, LT2>, ModelBiasedLinearSearch> }, \ { {#L1, #L2, "gind", "model_biased_linear"}, &experiment<key_type, rmi::RmiGInd<key_type, LT1, LT2>, ModelBiasedLinearSearch> }, \ { {#L1, #L2, "none", "exponential"}, &experiment<key_type, rmi::Rmi<key_type, LT1, LT2>, ExponentialSearch> }, \ { {#L1, #L2, "labs", "exponential"}, &experiment<key_type, rmi::RmiLAbs<key_type, LT1, LT2>, ExponentialSearch> }, \ { {#L1, #L2, "lind", "exponential"}, &experiment<key_type, rmi::RmiLInd<key_type, LT1, LT2>, ExponentialSearch> }, \ { {#L1, #L2, "gabs", "exponential"}, &experiment<key_type, rmi::RmiGAbs<key_type, LT1, LT2>, ExponentialSearch> }, \ { {#L1, #L2, "gind", "exponential"}, &experiment<key_type, rmi::RmiGInd<key_type, LT1, LT2>, ExponentialSearch> }, \ { {#L1, #L2, "none", "model_biased_exponential"}, &experiment<key_type, rmi::Rmi<key_type, LT1, LT2>, ModelBiasedExponentialSearch> }, \ { {#L1, #L2, "labs", "model_biased_exponential"}, &experiment<key_type, rmi::RmiLAbs<key_type, LT1, LT2>, ModelBiasedExponentialSearch> }, \ { {#L1, #L2, "lind", "model_biased_exponential"}, &experiment<key_type, rmi::RmiLInd<key_type, LT1, LT2>, ModelBiasedExponentialSearch> }, \ { {#L1, #L2, "gabs", "model_biased_exponential"}, &experiment<key_type, rmi::RmiGAbs<key_type, LT1, LT2>, ModelBiasedExponentialSearch> }, \ { {#L1, #L2, "gind", "model_biased_exponential"}, &experiment<key_type, rmi::RmiGInd<key_type, LT1, LT2>, ModelBiasedExponentialSearch> }, \ static std::map<Config, exp_fn_ptr, ConfigCompare> exp_map { ENTRIES(linear_regression, linear_regression, rmi::LinearRegression, rmi::LinearRegression) ENTRIES(linear_regression, linear_spline, rmi::LinearRegression, rmi::LinearSpline) ENTRIES(linear_spline, linear_regression, rmi::LinearSpline, rmi::LinearRegression) ENTRIES(linear_spline, linear_spline, rmi::LinearSpline, rmi::LinearSpline) ENTRIES(cubic_spline, linear_regression, rmi::CubicSpline, rmi::LinearRegression) ENTRIES(cubic_spline, linear_spline, rmi::CubicSpline, rmi::LinearSpline) ENTRIES(radix, linear_regression, rmi::Radix<key_type>, rmi::LinearRegression) ENTRIES(radix, linear_spline, rmi::Radix<key_type>, rmi::LinearSpline) }; ///< Map that assigns an experiment function pointer to RMI configurations. #undef ENTRIES /** * Triggers measurement of lookup times for an RMI configuration provided via command line arguments. * @param argc arguments counter * @param argv arguments vector */ int main(int argc, char *argv[]) { // Initialize argument parser. argparse::ArgumentParser program(argv[0], "0.1"); // Define arguments. program.add_argument("filename") .help("path to binary file containing uin64_t keys"); program.add_argument("layer1") .help("layer1 model type, either linear_regression, linear_spline, cubic_spline, or radix."); program.add_argument("layer2") .help("layer2 model type, either linear_regression, linear_spline, or cubic_spline."); program.add_argument("n_models") .help("number of models on layer2, power of two is recommended.") .action([](const std::string &s) { return std::stoul(s); }); program.add_argument("bound_type") .help("type of error bounds used, either none, labs, lind, gabs, or gind."); program.add_argument("search") .help("search algorithm for error correction, either binary, model_biased_binary, exponential, model_biased_exponential, linear, or model_biased_linear."); program.add_argument("-n", "--n_reps") .help("number of experiment repetitions") .default_value(std::size_t(3)) .action([](const std::string &s) { return std::stoul(s); }); program.add_argument("-s", "--n_samples") .help("number of sampled lookup keys") .default_value(std::size_t(1'000'000)) .action([](const std::string &s) { return std::stoul(s); }); program.add_argument("--header") .help("output csv header") .default_value(false) .implicit_value(true); // Parse arguments. try { program.parse_args(argc, argv); } catch (const std::runtime_error &err) { std::cout << err.what() << '\n' << program; exit(EXIT_FAILURE); } // Read arguments. const auto filename = program.get<std::string>("filename"); const auto dataset_name = split(filename, '/').back(); const auto layer1 = program.get<std::string>("layer1"); const auto layer2 = program.get<std::string>("layer2"); const auto n_models = program.get<std::size_t>("n_models"); const auto bound_type = program.get<std::string>("bound_type"); const auto search = program.get<std::string>("search"); const auto n_reps = program.get<std::size_t>("-n"); const auto n_samples = program.get<std::size_t>("-s"); // Load keys. auto keys = load_data<key_type>(filename); // Sample keys. uint64_t seed = 42; std::mt19937 gen(seed); std::uniform_int_distribution<> distrib(0, keys.size() - 1); std::vector<key_type> samples; samples.reserve(n_samples); for (std::size_t i = 0; i != n_samples; ++i) samples.push_back(keys[distrib(gen)]); // Lookup experiment. Config config{layer1, layer2, bound_type, search}; if (exp_map.find(config) == exp_map.end()) { std::cerr << "Error: " << layer1 << ',' << layer2 << ',' << bound_type << ',' << search << " is not a valid RMI configuration." << std::endl; exit(EXIT_FAILURE); } exp_fn_ptr exp_fn = exp_map[config]; // Output header. if (program["--header"] == true) std::cout << "dataset," << "n_keys," << "layer1," << "layer2," << "n_models," << "bounds," << "search," << "size_in_bytes," << "rep," << "n_samples," << "lookup_time," << "lookup_accu," << std::endl; // Run experiment. (*exp_fn)(keys, n_models, samples, n_reps, dataset_name, layer1, layer2, bound_type, search); exit(EXIT_SUCCESS); }
45.908759
163
0.608156
alhuan