hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
266a9ad44d2dd4daea13178aac7d0e06a0c12ff8
5,039
hpp
C++
include/grid_based_planner.hpp
dabinkim-LGOM/lsc_planner
88dcb1de59bac810d1b1fd194fe2b8d24d1860c9
[ "MIT" ]
9
2021-09-04T15:14:57.000Z
2022-03-29T04:34:13.000Z
include/grid_based_planner.hpp
dabinkim-LGOM/lsc_planner
88dcb1de59bac810d1b1fd194fe2b8d24d1860c9
[ "MIT" ]
null
null
null
include/grid_based_planner.hpp
dabinkim-LGOM/lsc_planner
88dcb1de59bac810d1b1fd194fe2b8d24d1860c9
[ "MIT" ]
4
2021-09-29T11:32:54.000Z
2022-03-06T05:24:33.000Z
#ifndef LSC_PLANNER_GRIDBASEDPLANNER_HPP #define LSC_PLANNER_GRIDBASEDPLANNER_HPP #include <Astar-3D/astarplanner.h> #include <dynamicEDT3D/dynamicEDTOctomap.h> #include <mission.hpp> #include <param.hpp> #include <util.hpp> #include <geometry.hpp> #include <utility> #define GP_OCCUPIED 1 #define GP_EMPTY 0 #define GP_INFINITY 10000 // Wrapper for grid based path planner namespace DynamicPlanning { struct GridVector{ public: GridVector(){ data = {-1, -1, -1}; } GridVector(int i, int j, int k){ data = {i, j, k}; } GridVector operator+(const GridVector& other_node) const; GridVector operator-(const GridVector& other_node) const; GridVector operator*(int integer) const; GridVector operator-() const; bool operator== (const GridVector &other_node) const; bool operator< (const GridVector &other_node) const; int dot(const GridVector& other_agent) const; double norm() const; int i() const { return data[0]; } int j() const { return data[1]; } int k() const { return data[2]; } int& operator[](unsigned int idx) { return data[idx]; } const int& operator[](unsigned int idx) const { return data[idx]; } std::array<int,3> toArray() const { return data; } private: std::array<int,3> data{-1,-1,-1}; }; struct GridInfo{ std::array<double,3> grid_min; std::array<double,3> grid_max; std::array<int,3> dim; }; struct GridMap{ std::vector<std::vector<std::vector<int>>> grid; int getValue(GridVector grid_node) const{ return grid[grid_node[0]][grid_node[1]][grid_node[2]]; } void setValue(GridVector grid_node, int value){ grid[grid_node[0]][grid_node[1]][grid_node[2]] = value; } }; struct GridMission{ GridVector start_point; GridVector goal_point; }; typedef std::vector<octomap::point3d> path_t; typedef std::vector<GridVector> gridpath_t; struct PlanResult{ path_t path; gridpath_t grid_path; }; class GridBasedPlanner { public: GridBasedPlanner(const std::shared_ptr<DynamicEDTOctomap>& _distmap_obj, const DynamicPlanning::Mission &_mission, const DynamicPlanning::Param &_param); path_t plan(const octomap::point3d& current_position, const octomap::point3d& goal_position, int agent_id, double agent_radius, double agent_downwash, const std::vector<dynamic_msgs::Obstacle>& obstacles = {}, const std::set<int>& high_priority_obstacle_ids = {}); // Getter std::vector<octomap::point3d> getFreeGridPoints(); // Goal octomap::point3d findLOSFreeGoal(const octomap::point3d& current_position, const octomap::point3d& goal_position, const std::vector<dynamic_msgs::Obstacle>& obstacles, double agent_radius, const std::vector<octomap::point3d>& additional_check_positions = {}); private: Mission mission; Param param; std::shared_ptr<DynamicEDTOctomap> distmap_obj; GridInfo grid_info{}; GridMap grid_map; GridMission grid_mission; PlanResult plan_result; void updateGridInfo(const octomap::point3d& current_position, double agent_radius); void updateGridMap(const octomap::point3d& current_position, const std::vector<dynamic_msgs::Obstacle>& obstacles, double agent_radius, double agent_downwash, const std::set<int>& high_priority_obstacle_ids = {}); void updateGridMission(const octomap::point3d& current_position, const octomap::point3d& goal_position, int agent_id); bool isValid(const GridVector& grid_node); bool isOccupied(const GridMap& map, const GridVector& grid_node); static gridpath_t plan_impl(const GridMap& grid_map, const GridMission& grid_mission); static gridpath_t planAstar(const GridMap& grid_map, const GridMission& grid_mission); path_t gridPathToPath(const gridpath_t& grid_path) const; octomap::point3d gridVectorToPoint3D(const GridVector& grid_vector) const; octomap::point3d gridVectorToPoint3D(const GridVector& grid_vector, int dimension) const; GridVector point3DToGridVector(const octomap::point3d& point) const; bool castRay(const octomap::point3d& current_position, const octomap::point3d& goal_position, double agent_radius); }; } #endif //LSC_PLANNER_GRIDBASEDPLANNER_HPP
33.818792
111
0.609248
dabinkim-LGOM
267f14b83683bdb1167b4596f72110cba41b72b4
2,069
cpp
C++
libraries/ClockHardware/src/Display.cpp
e-noyau/wordclock
5de70473e291514ee726fe737a3fee84abc33dd5
[ "MIT" ]
1
2019-08-31T16:57:00.000Z
2019-08-31T16:57:00.000Z
libraries/ClockHardware/src/Display.cpp
e-noyau/wordclock
5de70473e291514ee726fe737a3fee84abc33dd5
[ "MIT" ]
2
2019-09-01T13:20:26.000Z
2020-11-02T09:02:29.000Z
libraries/ClockHardware/src/Display.cpp
e-noyau/wordclock
5de70473e291514ee726fe737a3fee84abc33dd5
[ "MIT" ]
1
2020-11-01T22:21:57.000Z
2020-11-01T22:21:57.000Z
#define DEBUG 1 #include "logging.h" #include "Display.h" Display::Display(ClockFace& clockFace, uint8_t pin) : _clockFace(clockFace), _pixels(ClockFace::pixelCount(), pin), _brightnessController(_pixels), _animations(ClockFace::pixelCount(), NEO_CENTISECONDS) {} void Display::setup() { _pixels.Begin(); _brightnessController.setup(); } void Display::loop() { // TODO This has nothing to do here, remove somewhere else. // // If the "boot" button is pressed, move time forward. It's a crude way to // // set the time. // bool buttonPressed = digitalRead(0) != HIGH; // if ((!animations.IsAnimating()) && (buttonPressed)) { // DateTime now = rtc.now() + TimeSpan(20); // rtc.adjust(now); // } // // Adjust the display to show the right time // showtime(buttonPressed? 20 : TIME_CHANGE_ANIMATION_SPEED); // break; _brightnessController.loop(); _animations.UpdateAnimations(); _pixels.Show(); } void Display::updateForTime(int hour, int minute, int second, int animationSpeed) { if (!_clockFace.stateForTime(hour, minute, second)) { return; // Nothing to update. } static const RgbColor white = RgbColor(0xff, 0xff, 0xff); static const RgbColor black = RgbColor(0x00, 0x00, 0x00); DLOG("Time: "); DLOG(hour); DLOG(":"); DLOGLN(minute); // For all the LED animate a change from the current visible state to the new // one. const std::vector<bool>& state = _clockFace.getState(); for (int index = 0; index < state.size(); index++) { RgbColor originalColor = _pixels.GetPixelColor(index); RgbColor targetColor = state[index] ? white : black; AnimUpdateCallback animUpdate = [=](const AnimationParam& param) { float progress = NeoEase::QuadraticIn(param.progress); RgbColor updatedColor = RgbColor::LinearBlend( originalColor, targetColor, progress); _pixels.SetPixelColor(index, updatedColor); }; _animations.StartAnimation(index, animationSpeed, animUpdate); } }
30.426471
83
0.661189
e-noyau
268036a70e851def99db8cf36ad5448f9b7acfae
837
cpp
C++
check_if_it_is_a_straight_line.cpp
shafitek/ArXives
67170d6bde2093703d9cd3e8efa55b61e7b5ea75
[ "MIT" ]
null
null
null
check_if_it_is_a_straight_line.cpp
shafitek/ArXives
67170d6bde2093703d9cd3e8efa55b61e7b5ea75
[ "MIT" ]
null
null
null
check_if_it_is_a_straight_line.cpp
shafitek/ArXives
67170d6bde2093703d9cd3e8efa55b61e7b5ea75
[ "MIT" ]
null
null
null
// https://leetcode.com/problems/check-if-it-is-a-straight-line/ class Solution { public: bool checkStraightLine(vector<vector<int>>& coordinates) { vector<int> og_slope = {coordinates[1][1] - coordinates[0][1], coordinates[1][0] - coordinates[0][0]}; float orig_slope = og_slope[1] == 0 ? LONG_MAX : (float)og_slope[0]/(float)og_slope[1]; vector<int> curr_slope = og_slope; float slope = orig_slope; for(int i = 1; i < coordinates.size()-1; i++) { curr_slope = {coordinates[i+1][1] - coordinates[i][1], coordinates[i+1][0] - coordinates[i][0]}; slope = curr_slope[1] == 0 ? LONG_MAX : (float)curr_slope[0]/(float)curr_slope[1]; if (orig_slope != slope) return false; } return true; } };
38.045455
110
0.568698
shafitek
2680f353d7a0913800427847fd51269880685504
2,059
hpp
C++
practice2/io_service_pool.hpp
MaxHonggg/professional_boost
6fff73d3b9832644068dc8fe0443be813c7237b4
[ "BSD-2-Clause" ]
47
2016-05-20T08:49:47.000Z
2022-01-03T01:17:07.000Z
practice2/io_service_pool.hpp
MaxHonggg/professional_boost
6fff73d3b9832644068dc8fe0443be813c7237b4
[ "BSD-2-Clause" ]
null
null
null
practice2/io_service_pool.hpp
MaxHonggg/professional_boost
6fff73d3b9832644068dc8fe0443be813c7237b4
[ "BSD-2-Clause" ]
37
2016-07-25T04:52:08.000Z
2022-02-14T03:55:08.000Z
// Copyright (c) 2016 // Author: Chrono Law #ifndef _PRO_BOOST_IO_SERVICE_HPP #define _PRO_BOOST_IO_SERVICE_HPP #include <algorithm> #include <boost/assert.hpp> #include <boost/noncopyable.hpp> #include <boost/foreach.hpp> #include <boost/bind.hpp> #include <boost/ref.hpp> #include <boost/functional/factory.hpp> #include <boost/ptr_container/ptr_vector.hpp> #include <boost/asio.hpp> #include <boost/thread.hpp> class io_service_pool final : boost::noncopyable { public: typedef boost::asio::io_service ios_type; typedef boost::asio::io_service::work work_type; typedef boost::ptr_vector<ios_type> io_services_type; typedef boost::ptr_vector<work_type> works_type; private: io_services_type m_io_services; works_type m_works; boost::thread_group m_threads; std::size_t m_next_io_service; public: explicit io_service_pool(int n = 1): m_next_io_service(0) { BOOST_ASSERT(n > 0); init(n); } private: void init(int n) { for (int i = 0;i < n; ++i) { m_io_services.push_back( boost::factory<ios_type*>()()); m_works.push_back( boost::factory<work_type*>() (m_io_services.back())); } } public: ios_type& get() { if (m_next_io_service >= m_io_services.size()) { m_next_io_service = 0; } return m_io_services[m_next_io_service++]; } public: void start() { if (m_threads.size() > 0) { return; } for(ios_type& ios : m_io_services) { m_threads.create_thread( boost::bind(&ios_type::run, boost::ref(ios))); } } void run() { start(); m_threads.join_all(); } public: void stop() { m_works.clear(); std::for_each(m_io_services.begin(), m_io_services.end(), boost::bind(&ios_type::stop, _1)); } }; #endif // _PRO_BOOST_IO_SERVICE_HPP
22.626374
65
0.587178
MaxHonggg
269318de806dfe825259006c755701b4b1c0815a
2,700
hpp
C++
external/boost_1_60_0/qsboost/function_types/detail/classifier.hpp
wouterboomsma/quickstep
a33447562eca1350c626883f21c68125bd9f776c
[ "MIT" ]
1
2019-06-27T17:54:13.000Z
2019-06-27T17:54:13.000Z
external/boost_1_60_0/qsboost/function_types/detail/classifier.hpp
wouterboomsma/quickstep
a33447562eca1350c626883f21c68125bd9f776c
[ "MIT" ]
null
null
null
external/boost_1_60_0/qsboost/function_types/detail/classifier.hpp
wouterboomsma/quickstep
a33447562eca1350c626883f21c68125bd9f776c
[ "MIT" ]
null
null
null
// (C) Copyright Tobias Schwinger // // Use modification and distribution are subject to the boost Software License, // Version 1.0. (See http://www.boost.org/LICENSE_1_0.txt). //------------------------------------------------------------------------------ #ifndef QSBOOST_FT_DETAIL_CLASSIFIER_HPP_INCLUDED #define QSBOOST_FT_DETAIL_CLASSIFIER_HPP_INCLUDED #include <qsboost/type.hpp> #include <qsboost/config.hpp> #include <qsboost/type_traits/is_reference.hpp> #include <qsboost/type_traits/add_reference.hpp> #include <qsboost/function_types/config/config.hpp> #include <qsboost/function_types/property_tags.hpp> namespace qsboost { namespace function_types { namespace detail { template<typename T> struct classifier; template<std::size_t S> struct char_array { typedef char (&type)[S]; }; template<bits_t Flags, bits_t CCID, std::size_t Arity> struct encode_charr { typedef typename char_array< ::qsboost::function_types::detail::encode_charr_impl<Flags,CCID,Arity>::value >::type type; }; #if defined(QSBOOST_MSVC) || (defined(__BORLANDC__) && !defined(QSBOOST_DISABLE_WIN32)) # define QSBOOST_FT_DECL __cdecl #else # define QSBOOST_FT_DECL /**/ #endif char QSBOOST_FT_DECL classifier_impl(...); #define QSBOOST_FT_variations QSBOOST_FT_function|QSBOOST_FT_pointer|\ QSBOOST_FT_member_pointer #define QSBOOST_FT_type_function(cc,name) QSBOOST_FT_SYNTAX( \ R QSBOOST_PP_EMPTY,QSBOOST_PP_LPAREN,cc,* QSBOOST_PP_EMPTY,name,QSBOOST_PP_RPAREN) #define QSBOOST_FT_type_function_pointer(cc,name) QSBOOST_FT_SYNTAX( \ R QSBOOST_PP_EMPTY,QSBOOST_PP_LPAREN,cc,** QSBOOST_PP_EMPTY,name,QSBOOST_PP_RPAREN) #define QSBOOST_FT_type_member_function_pointer(cc,name) QSBOOST_FT_SYNTAX( \ R QSBOOST_PP_EMPTY,QSBOOST_PP_LPAREN,cc,T0::** QSBOOST_PP_EMPTY,name,QSBOOST_PP_RPAREN) #define QSBOOST_FT_al_path qsboost/function_types/detail/classifier_impl #include <qsboost/function_types/detail/pp_loop.hpp> template<typename T> struct classifier_bits { static typename qsboost::add_reference<T>::type tester; QSBOOST_STATIC_CONSTANT(bits_t,value = (bits_t)sizeof( qsboost::function_types::detail::classifier_impl(& tester) )-1); }; template<typename T> struct classifier { typedef detail::constant< ::qsboost::function_types::detail::decode_bits< ::qsboost::function_types::detail::classifier_bits<T>::value >::tag_bits > bits; typedef detail::full_mask mask; typedef detail::constant< ::qsboost::function_types::detail::decode_bits< ::qsboost::function_types::detail::classifier_bits<T>::value >::arity > function_arity; }; } } } // namespace ::boost::function_types::detail #endif
30.681818
91
0.745926
wouterboomsma
2698312aae743931996097469472fdf91ec54465
1,464
hpp
C++
plugins/libimhex/include/hex/helpers/crypto.hpp
Laxer3a/psdebugtool
41efa5f35785afd8f6dc868d8dbdb0dcf8eb25fb
[ "MIT" ]
4
2021-05-09T23:33:54.000Z
2022-03-06T10:16:31.000Z
plugins/libimhex/include/hex/helpers/crypto.hpp
Laxer3a/psdebugtool
41efa5f35785afd8f6dc868d8dbdb0dcf8eb25fb
[ "MIT" ]
null
null
null
plugins/libimhex/include/hex/helpers/crypto.hpp
Laxer3a/psdebugtool
41efa5f35785afd8f6dc868d8dbdb0dcf8eb25fb
[ "MIT" ]
6
2021-05-09T21:41:48.000Z
2021-09-08T10:54:28.000Z
#pragma once #include <hex.hpp> #include <array> #include <optional> #include <string> #include <vector> namespace hex::prv { class Provider; } namespace hex::crypt { void initialize(); void exit(); u16 crc16(prv::Provider* &data, u64 offset, size_t size, u16 polynomial, u16 init); u32 crc32(prv::Provider* &data, u64 offset, size_t size, u32 polynomial, u32 init); std::array<u8, 16> md5(prv::Provider* &data, u64 offset, size_t size); std::array<u8, 20> sha1(prv::Provider* &data, u64 offset, size_t size); std::array<u8, 28> sha224(prv::Provider* &data, u64 offset, size_t size); std::array<u8, 32> sha256(prv::Provider* &data, u64 offset, size_t size); std::array<u8, 48> sha384(prv::Provider* &data, u64 offset, size_t size); std::array<u8, 64> sha512(prv::Provider* &data, u64 offset, size_t size); std::vector<u8> decode64(const std::vector<u8> &input); std::vector<u8> encode64(const std::vector<u8> &input); enum class AESMode : u8 { ECB = 0, CBC = 1, CFB128 = 2, CTR = 3, GCM = 4, CCM = 5, OFB = 6, XTS = 7 }; enum class KeyLength : u8 { Key128Bits = 0, Key192Bits = 1, Key256Bits = 2 }; std::vector<u8> aesDecrypt(AESMode mode, KeyLength keyLength, const std::vector<u8> &key, std::array<u8, 8> nonce, std::array<u8, 8> iv, const std::vector<u8> &input); }
30.5
171
0.60041
Laxer3a
2699125626aca087b562a1e959e2a3e6e7b56ed6
441
cpp
C++
src/Level.cpp
savageking-io/evelengine
f4f31419077e3467db271e82b05164eafa521eb7
[ "Apache-2.0" ]
null
null
null
src/Level.cpp
savageking-io/evelengine
f4f31419077e3467db271e82b05164eafa521eb7
[ "Apache-2.0" ]
null
null
null
src/Level.cpp
savageking-io/evelengine
f4f31419077e3467db271e82b05164eafa521eb7
[ "Apache-2.0" ]
null
null
null
#include "Level.hpp" namespace EvelEngine { Level::Level(const std::string& seed) : _seed(seed) { } Level::~Level() { } bool Level::handleCommand(const std::string& command) { return false; } std::string Level::getSeed() { return _seed; } void Level::build() { } double Level::perlin(double x, double y, double z) { return 0.0; } }
11.918919
57
0.514739
savageking-io
269a29ed1856c4578d99a34f6d309425867d5b98
7,171
cxx
C++
Rendering/OSPRay/vtkOSPRayPass.cxx
romangrothausmann/VTK
60cce86963f29f8f569a7a31348019e095267a50
[ "BSD-3-Clause" ]
null
null
null
Rendering/OSPRay/vtkOSPRayPass.cxx
romangrothausmann/VTK
60cce86963f29f8f569a7a31348019e095267a50
[ "BSD-3-Clause" ]
null
null
null
Rendering/OSPRay/vtkOSPRayPass.cxx
romangrothausmann/VTK
60cce86963f29f8f569a7a31348019e095267a50
[ "BSD-3-Clause" ]
1
2020-01-13T07:19:25.000Z
2020-01-13T07:19:25.000Z
/*========================================================================= Prograxq: Visualization Toolkit Module: vtkOSPRayPass.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkCamera.h" #include "vtkCameraPass.h" #include "vtkLightsPass.h" #include "vtkObjectFactory.h" #include "vtkOSPRayPass.h" #include "vtkOSPRayRendererNode.h" #include "vtkOSPRayViewNodeFactory.h" #include "vtkOverlayPass.h" #include "vtkOpaquePass.h" #include "vtkRenderPassCollection.h" #include "vtkRenderState.h" #include "vtkRenderWindow.h" #include "vtkRenderer.h" #include "vtkSequencePass.h" #include "vtkSequencePass.h" #include "vtkVolumetricPass.h" #include "ospray/ospray.h" #include <sstream> #include <stdexcept> class vtkOSPRayPassInternals : public vtkRenderPass { public: static vtkOSPRayPassInternals *New(); vtkTypeMacro(vtkOSPRayPassInternals,vtkRenderPass); vtkOSPRayPassInternals() { this->Factory = 0; } ~vtkOSPRayPassInternals() { this->Factory->Delete(); } void Render(const vtkRenderState *s) override { this->Parent->RenderInternal(s); } vtkOSPRayViewNodeFactory *Factory; vtkOSPRayPass *Parent; }; int vtkOSPRayPass::OSPDeviceRefCount = 0; // ---------------------------------------------------------------------------- vtkStandardNewMacro(vtkOSPRayPassInternals); // ---------------------------------------------------------------------------- vtkStandardNewMacro(vtkOSPRayPass); // ---------------------------------------------------------------------------- vtkOSPRayPass::vtkOSPRayPass() { this->SceneGraph = nullptr; vtkOSPRayPass::OSPInit(); vtkOSPRayViewNodeFactory *vnf = vtkOSPRayViewNodeFactory::New(); this->Internal = vtkOSPRayPassInternals::New(); this->Internal->Factory = vnf; this->Internal->Parent = this; this->CameraPass = vtkCameraPass::New(); this->LightsPass = vtkLightsPass::New(); this->SequencePass = vtkSequencePass::New(); this->VolumetricPass = vtkVolumetricPass::New(); this->OverlayPass = vtkOverlayPass::New(); this->RenderPassCollection = vtkRenderPassCollection::New(); this->RenderPassCollection->AddItem(this->LightsPass); this->RenderPassCollection->AddItem(this->Internal); this->RenderPassCollection->AddItem(this->OverlayPass); this->SequencePass->SetPasses(this->RenderPassCollection); this->CameraPass->SetDelegatePass(this->SequencePass); } // ---------------------------------------------------------------------------- vtkOSPRayPass::~vtkOSPRayPass() { this->SetSceneGraph(nullptr); this->Internal->Delete(); this->Internal = 0; if (this->CameraPass) { this->CameraPass->Delete(); this->CameraPass = 0; } if (this->LightsPass) { this->LightsPass->Delete(); this->LightsPass = 0; } if (this->SequencePass) { this->SequencePass->Delete(); this->SequencePass = 0; } if (this->VolumetricPass) { this->VolumetricPass->Delete(); this->VolumetricPass = 0; } if (this->OverlayPass) { this->OverlayPass->Delete(); this->OverlayPass = 0; } if (this->RenderPassCollection) { this->RenderPassCollection->Delete(); this->RenderPassCollection = 0; } vtkOSPRayPass::OSPShutdown(); } // ---------------------------------------------------------------------------- void vtkOSPRayPass::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); } // ---------------------------------------------------------------------------- vtkCxxSetObjectMacro(vtkOSPRayPass, SceneGraph, vtkOSPRayRendererNode) // ---------------------------------------------------------------------------- void vtkOSPRayPass::Render(const vtkRenderState *s) { if (!this->SceneGraph) { vtkRenderer *ren = s->GetRenderer(); if (ren) { this->SceneGraph = vtkOSPRayRendererNode::SafeDownCast (this->Internal->Factory->CreateNode(ren)); } } this->CameraPass->Render(s); } // ---------------------------------------------------------------------------- void vtkOSPRayPass::RenderInternal(const vtkRenderState *s) { this->NumberOfRenderedProps=0; if (this->SceneGraph) { this->SceneGraph->TraverseAllPasses(); // copy the result to the window vtkRenderer *ren = s->GetRenderer(); vtkRenderWindow *rwin = vtkRenderWindow::SafeDownCast(ren->GetVTKWindow()); int viewportX, viewportY; int viewportWidth, viewportHeight; int right = 0; if (rwin) { if (rwin->GetStereoRender() == 1) { if (rwin->GetStereoType() == VTK_STEREO_CRYSTAL_EYES) { vtkCamera *camera = ren->GetActiveCamera(); if (camera) { if (!camera->GetLeftEye()) { right = 1; } } } } } ren->GetTiledSizeAndOrigin(&viewportWidth,&viewportHeight, &viewportX,&viewportY); vtkOSPRayRendererNode* oren= vtkOSPRayRendererNode::SafeDownCast (this->SceneGraph->GetViewNodeFor(ren)); int layer = ren->GetLayer(); if (layer == 0) { rwin->SetZbufferData( viewportX, viewportY, viewportX+viewportWidth-1, viewportY+viewportHeight-1, this->SceneGraph->GetZBuffer()); rwin->SetRGBACharPixelData( viewportX, viewportY, viewportX+viewportWidth-1, viewportY+viewportHeight-1, this->SceneGraph->GetBuffer(), 0, vtkOSPRayRendererNode::GetCompositeOnGL(ren), right); } else { float *ontoZ = rwin->GetZbufferData (viewportX, viewportY, viewportX+viewportWidth-1, viewportY+viewportHeight-1); unsigned char *ontoRGBA = rwin->GetRGBACharPixelData (viewportX, viewportY, viewportX+viewportWidth-1, viewportY+viewportHeight-1, 0, right); oren->WriteLayer(ontoRGBA, ontoZ, viewportWidth, viewportHeight, layer); rwin->SetZbufferData( viewportX, viewportY, viewportX+viewportWidth-1, viewportY+viewportHeight-1, ontoZ); rwin->SetRGBACharPixelData( viewportX, viewportY, viewportX+viewportWidth-1, viewportY+viewportHeight-1, ontoRGBA, 0, vtkOSPRayRendererNode::GetCompositeOnGL(ren), right); delete[] ontoZ; delete[] ontoRGBA; } } } // ---------------------------------------------------------------------------- void vtkOSPRayPass::OSPInit() { if (OSPDeviceRefCount == 0) { ospInit(nullptr, nullptr); } OSPDeviceRefCount++; } // ---------------------------------------------------------------------------- void vtkOSPRayPass::OSPShutdown() { --OSPDeviceRefCount; if (OSPDeviceRefCount == 0) { ospShutdown(); } }
27.580769
79
0.583322
romangrothausmann
26a4224f486141596420a88bc99b27d29ee417d8
5,083
cpp
C++
compiler/llvm/c_src/Diagnostics.cpp
mlwilkerson/lumen
048df6c0840c11496e2d15aa9af2e4a8d07a6e0f
[ "Apache-2.0" ]
2,939
2019-08-29T16:52:20.000Z
2022-03-31T05:42:30.000Z
compiler/llvm/c_src/Diagnostics.cpp
mlwilkerson/lumen
048df6c0840c11496e2d15aa9af2e4a8d07a6e0f
[ "Apache-2.0" ]
235
2019-08-29T23:44:13.000Z
2022-03-17T11:43:25.000Z
compiler/llvm/c_src/Diagnostics.cpp
mlwilkerson/lumen
048df6c0840c11496e2d15aa9af2e4a8d07a6e0f
[ "Apache-2.0" ]
95
2019-08-29T19:11:28.000Z
2022-01-03T05:14:16.000Z
#include "lumen/llvm/Diagnostics.h" #include "lumen/llvm/RustString.h" #include "llvm-c/Core.h" #include "llvm-c/Types.h" #include "llvm/IR/DiagnosticInfo.h" #include "llvm/IR/DiagnosticPrinter.h" #include "llvm/IR/Function.h" #include "llvm/Support/CBindingWrapping.h" #include "llvm/Support/Casting.h" using namespace lumen; using llvm::dyn_cast_or_null; using llvm::isa; typedef struct LLVMOpaqueSMDiagnostic *LLVMSMDiagnosticRef; DEFINE_SIMPLE_CONVERSION_FUNCTIONS(llvm::SMDiagnostic, LLVMSMDiagnosticRef); DEFINE_SIMPLE_CONVERSION_FUNCTIONS(llvm::DiagnosticInfo, LLVMDiagnosticInfoRef); DiagnosticKind lumen::toDiagnosticKind(llvm::DiagnosticKind kind) { switch (kind) { case llvm::DK_InlineAsm: return DiagnosticKind::InlineAsm; case llvm::DK_ResourceLimit: return DiagnosticKind::ResourceLimit; case llvm::DK_StackSize: return DiagnosticKind::StackSize; case llvm::DK_Linker: return DiagnosticKind::Linker; case llvm::DK_DebugMetadataVersion: return DiagnosticKind::DebugMetadataVersion; case llvm::DK_DebugMetadataInvalid: return DiagnosticKind::DebugMetadataInvalid; case llvm::DK_ISelFallback: return DiagnosticKind::ISelFallback; case llvm::DK_SampleProfile: return DiagnosticKind::SampleProfile; case llvm::DK_OptimizationRemark: return DiagnosticKind::OptimizationRemark; case llvm::DK_OptimizationRemarkMissed: return DiagnosticKind::OptimizationRemarkMissed; case llvm::DK_OptimizationRemarkAnalysis: return DiagnosticKind::OptimizationRemarkAnalysis; case llvm::DK_OptimizationRemarkAnalysisFPCommute: return DiagnosticKind::OptimizationRemarkAnalysisFPCommute; case llvm::DK_OptimizationRemarkAnalysisAliasing: return DiagnosticKind::OptimizationRemarkAnalysisAliasing; case llvm::DK_MachineOptimizationRemark: return DiagnosticKind::MachineOptimizationRemark; case llvm::DK_MachineOptimizationRemarkMissed: return DiagnosticKind::MachineOptimizationRemarkMissed; case llvm::DK_MachineOptimizationRemarkAnalysis: return DiagnosticKind::MachineOptimizationRemarkAnalysis; case llvm::DK_MIRParser: return DiagnosticKind::MIRParser; case llvm::DK_PGOProfile: return DiagnosticKind::PGOProfile; case llvm::DK_MisExpect: return DiagnosticKind::MisExpect; case llvm::DK_Unsupported: return DiagnosticKind::Unsupported; default: return DiagnosticKind::Other; } } extern "C" DiagnosticKind LLVMLumenGetDiagInfoKind(LLVMDiagnosticInfoRef di) { llvm::DiagnosticInfo *info = unwrap(di); return toDiagnosticKind((llvm::DiagnosticKind)info->getKind()); } extern "C" void LLVMLumenWriteSMDiagnosticToString(LLVMSMDiagnosticRef d, RustStringRef str) { RawRustStringOstream out(str); unwrap(d)->print("", out); } extern "C" void LLVMLumenWriteDiagnosticInfoToString(LLVMDiagnosticInfoRef di, RustStringRef str) { RawRustStringOstream out(str); llvm::DiagnosticPrinterRawOStream printer(out); unwrap(di)->print(printer); } extern "C" bool LLVMLumenIsVerboseOptimizationDiagnostic(LLVMDiagnosticInfoRef di) { // Undefined to call this not on an optimization diagnostic! llvm::DiagnosticInfoOptimizationBase *opt = static_cast<llvm::DiagnosticInfoOptimizationBase *>(unwrap(di)); return opt->isVerbose(); } extern "C" void LLVMLumenUnpackOptimizationDiagnostic(LLVMDiagnosticInfoRef di, RustStringRef passNameOut, RustStringRef remarkNameOut, LLVMValueRef *functionOut, LLVMValueRef *codeRegionOut, unsigned *line, unsigned *column, bool *isVerbose, RustStringRef filenameOut, RustStringRef messageOut) { // Undefined to call this not on an optimization diagnostic! llvm::DiagnosticInfoOptimizationBase *opt = static_cast<llvm::DiagnosticInfoOptimizationBase *>(unwrap(di)); *isVerbose = opt->isVerbose(); RawRustStringOstream passNameOS(passNameOut); passNameOS << opt->getPassName(); RawRustStringOstream remarkNameOS(remarkNameOut); remarkNameOS << opt->getRemarkName(); *functionOut = wrap(&opt->getFunction()); *codeRegionOut = nullptr; if (auto irOpt = dyn_cast_or_null<llvm::DiagnosticInfoIROptimization>(opt)) { *codeRegionOut = wrap(irOpt->getCodeRegion()); } if (opt->isLocationAvailable()) { llvm::DiagnosticLocation loc = opt->getLocation(); *line = loc.getLine(); *column = loc.getColumn(); RawRustStringOstream filenameOS(filenameOut); filenameOS << loc.getAbsolutePath(); } RawRustStringOstream messageOS(messageOut); messageOS << opt->getMsg(); } extern "C" void LLVMLumenUnpackISelFallbackDiagnostic(LLVMDiagnosticInfoRef di, LLVMValueRef *functionOut) { llvm::DiagnosticInfoISelFallback *opt = static_cast<llvm::DiagnosticInfoISelFallback *>(unwrap(di)); *functionOut = wrap(&opt->getFunction()); }
35.795775
92
0.734802
mlwilkerson
26a53835e890a7486faebe6d8fd2b791c564a5cb
14,685
cpp
C++
src/IoTHubDevice.cpp
markrad/Arduino-IoTHubDevice
141f439b7c5064c66c3c603ae395cae2dab7b96d
[ "MIT" ]
null
null
null
src/IoTHubDevice.cpp
markrad/Arduino-IoTHubDevice
141f439b7c5064c66c3c603ae395cae2dab7b96d
[ "MIT" ]
null
null
null
src/IoTHubDevice.cpp
markrad/Arduino-IoTHubDevice
141f439b7c5064c66c3c603ae395cae2dab7b96d
[ "MIT" ]
null
null
null
#include "IoTHubDevice.h" #include <AzureIoTProtocol_MQTT.h> #include <AzureIoTUtility.h> #include <azure_c_shared_utility/connection_string_parser.h> #include <azure_c_shared_utility/shared_util_options.h> #include "iothub_client_version.h" using namespace std; IoTHubDevice::IoTHubDevice(const char *connectionString, Protocol protocol) : _messageCallback(NULL), _messageCallbackUC(NULL), _connectionStatusCallback(NULL), _connectionStatusCallbackUC(NULL), _unknownDeviceMethodCallback(NULL), _unknownDeviceMethodCallbackUC(NULL), _deviceTwinCallback(NULL), _deviceTwinCallbackUC(NULL), _logging(false), _x509Certificate(NULL), _x509PrivateKey(NULL), _deviceHandle(NULL), _startResult(-1) { _connectionString = connectionString; _protocol = protocol; } IoTHubDevice::IoTHubDevice(const char *connectionString, const char *x509Certificate, const char *x509PrivateKey, Protocol protocol) : _messageCallback(NULL), _messageCallbackUC(NULL), _connectionStatusCallback(NULL), _connectionStatusCallbackUC(NULL), _unknownDeviceMethodCallback(NULL), _unknownDeviceMethodCallbackUC(NULL), _deviceTwinCallback(NULL), _deviceTwinCallbackUC(NULL), _logging(false), _x509Certificate(x509Certificate), _x509PrivateKey(x509PrivateKey), _deviceHandle(NULL), _startResult(-1) { _connectionString = connectionString; _protocol = protocol; } IoTHubDevice::~IoTHubDevice() { if (_deviceHandle != NULL) { Stop(); } } int IoTHubDevice::Start() { int result = _startResult = 0; DList_InitializeListHead(&_outstandingEventList); DList_InitializeListHead(&_outstandingReportedStateEventList); _parsedCS = new MapUtil(connectionstringparser_parse_from_char(_connectionString), true); if (_parsedCS == NULL) { LogError("Failed to parse connection string"); result = __FAILURE__; } else if (_parsedCS->ContainsKey("X509") && (_x509Certificate == NULL || _x509PrivateKey == NULL)) { LogError("X509 requires certificate and private key"); result = __FAILURE__; } else { if ((_x509Certificate == NULL && _x509PrivateKey != NULL) || (_x509Certificate != NULL && _x509PrivateKey == NULL)) { LogError("X509 values must both be provided or neither be provided"); result = __FAILURE__; } else { platform_init(); _deviceHandle = IoTHubClient_LL_CreateFromConnectionString(_connectionString, GetProtocol(_protocol)); if (_deviceHandle == NULL) { LogError("Failed to create IoT hub handle"); result = __FAILURE__; } else { if (_x509Certificate != NULL) { if ( (IoTHubClient_LL_SetOption(GetHandle(), OPTION_X509_CERT, _x509Certificate) != IOTHUB_CLIENT_OK) || (IoTHubClient_LL_SetOption(GetHandle(), OPTION_X509_PRIVATE_KEY, _x509PrivateKey) != IOTHUB_CLIENT_OK) ) { LogError("Failed to set X509 parameters"); result = __FAILURE__; } } if (result == 0) { if ( (IoTHubClient_LL_SetConnectionStatusCallback(GetHandle(), InternalConnectionStatusCallback, this) != IOTHUB_CLIENT_OK) || (IoTHubClient_LL_SetMessageCallback(GetHandle(), InternalMessageCallback, this) != IOTHUB_CLIENT_OK) || (IoTHubClient_LL_SetDeviceMethodCallback(GetHandle(), InternalDeviceMethodCallback, this) != IOTHUB_CLIENT_OK) || (IoTHubClient_LL_SetDeviceTwinCallback(GetHandle(), InternalDeviceTwinCallback, this) != IOTHUB_CLIENT_OK) ) { LogError("Failed to set up callbacks"); result = __FAILURE__; } } } } } _startResult = result; return result; } void IoTHubDevice::Stop() { if (_deviceHandle != NULL) { IoTHubClient_LL_Destroy(_deviceHandle); _deviceHandle = NULL; _startResult = -1; } platform_deinit(); while (!DList_IsListEmpty(&_outstandingEventList)) { PDLIST_ENTRY work = _outstandingEventList.Flink; DList_RemoveEntryList(work); delete work; } while(!DList_IsListEmpty(&_outstandingReportedStateEventList)) { PDLIST_ENTRY work = _outstandingReportedStateEventList.Flink; DList_RemoveEntryList(work); delete work; } for (map<std::string, DeviceMethodUserContext *>::iterator it = _deviceMethods.begin(); it != _deviceMethods.end(); it++) { delete it->second; } delete _parsedCS; } IoTHubDevice::MessageCallback IoTHubDevice::SetMessageCallback(MessageCallback messageCallback, void *userContext) { MessageCallback temp = _messageCallback; _messageCallback = messageCallback; _messageCallbackUC = userContext; return temp; } IOTHUB_CLIENT_LL_HANDLE IoTHubDevice::GetHandle() const { if (_deviceHandle == NULL) { LogError("Function called with null device handle"); } else if (_startResult != 0) { LogError("Function called after Start function failed with %d", _startResult); } return _deviceHandle; } const char *IoTHubDevice::GetHostName() { return _parsedCS->GetValue("HostName"); } const char *IoTHubDevice::GetDeviceId() { return _parsedCS->GetValue("DeviceId"); } const char *IoTHubDevice::GetVersion() { return IoTHubClient_GetVersionString(); } IOTHUB_CLIENT_STATUS IoTHubDevice::GetSendStatus() { IOTHUB_CLIENT_STATUS result = IOTHUB_CLIENT_SEND_STATUS_IDLE; IoTHubClient_LL_GetSendStatus(GetHandle(), &result); return result; } IoTHubDevice::ConnectionStatusCallback IoTHubDevice::SetConnectionStatusCallback(ConnectionStatusCallback connectionStatusCallback, void *userContext) { ConnectionStatusCallback temp = _connectionStatusCallback; _connectionStatusCallback = connectionStatusCallback; _connectionStatusCallbackUC = userContext; } IoTHubDevice::DeviceMethodCallback IoTHubDevice::SetDeviceMethodCallback(const char *methodName, DeviceMethodCallback deviceMethodCallback, void *userContext) { DeviceMethodUserContext *deviceMethodUserContext = new DeviceMethodUserContext(deviceMethodCallback, userContext); map<std::string, DeviceMethodUserContext *>::iterator it; DeviceMethodCallback temp = NULL; it = _deviceMethods.find(methodName); if (it == _deviceMethods.end()) { _deviceMethods[methodName] = deviceMethodUserContext; } else { temp = it->second->deviceMethodCallback; delete it->second; if (deviceMethodCallback != NULL) { it->second = deviceMethodUserContext; } else { _deviceMethods.erase(it); } } return temp; } IoTHubDevice::UnknownDeviceMethodCallback IoTHubDevice::SetUnknownDeviceMethodCallback(UnknownDeviceMethodCallback unknownDeviceMethodCallback, void *userContext) { UnknownDeviceMethodCallback temp = _unknownDeviceMethodCallback; _unknownDeviceMethodCallback = unknownDeviceMethodCallback; _unknownDeviceMethodCallbackUC = userContext; return temp; } IoTHubDevice::DeviceTwinCallback IoTHubDevice::SetDeviceTwinCallback(DeviceTwinCallback deviceTwinCallback, void *userContext) { DeviceTwinCallback temp = _deviceTwinCallback; _deviceTwinCallback = deviceTwinCallback; _deviceTwinCallbackUC = userContext; return temp; } IOTHUB_CLIENT_RESULT IoTHubDevice::SendEventAsync(const string &message, EventConfirmationCallback eventConfirmationCallback, void *userContext) { IOTHUB_CLIENT_RESULT result; result = SendEventAsync(message.c_str(), eventConfirmationCallback, userContext); return result; } IOTHUB_CLIENT_RESULT IoTHubDevice::SendEventAsync(const char *message, EventConfirmationCallback eventConfirmationCallback, void *userContext) { IoTHubMessage *hubMessage = new IoTHubMessage(message); IOTHUB_CLIENT_RESULT result; result = SendEventAsync(hubMessage, eventConfirmationCallback, userContext); delete hubMessage; return result; } IOTHUB_CLIENT_RESULT IoTHubDevice::SendEventAsync(const uint8_t *message, size_t length, EventConfirmationCallback eventConfirmationCallback, void *userContext) { IoTHubMessage *hubMessage = new IoTHubMessage(message, length); IOTHUB_CLIENT_RESULT result; result = SendEventAsync(hubMessage, eventConfirmationCallback, userContext); delete hubMessage; return result; } IOTHUB_CLIENT_RESULT IoTHubDevice::SendEventAsync(const IoTHubMessage *message, EventConfirmationCallback eventConfirmationCallback, void *userContext) { MessageUserContext *messageUC = new MessageUserContext(this, eventConfirmationCallback, userContext); IOTHUB_CLIENT_RESULT result; result = IoTHubClient_LL_SendEventAsync(GetHandle(), message->GetHandle(), InternalEventConfirmationCallback, messageUC); if (result == IOTHUB_CLIENT_OK) { DList_InsertTailList(&_outstandingEventList, &(messageUC->dlistEntry)); } return result; } IOTHUB_CLIENT_RESULT IoTHubDevice::SendReportedState(const char* reportedState, ReportedStateCallback reportedStateCallback, void* userContext) { ReportedStateUserContext *reportedStateUC = new ReportedStateUserContext(this, reportedStateCallback, userContext); IOTHUB_CLIENT_RESULT result; result = IoTHubClient_LL_SendReportedState(GetHandle(), (const unsigned char *)reportedState, strlen(reportedState), InternalReportedStateCallback, reportedStateUC); if (result == IOTHUB_CLIENT_OK) { DList_InsertTailList(&_outstandingReportedStateEventList, &(reportedStateUC->dlistEntry)); } } void IoTHubDevice::DoWork() { IoTHubClient_LL_DoWork(GetHandle()); } int IoTHubDevice::WaitingEventsCount() { PDLIST_ENTRY listEntry = &_outstandingEventList; int count = 0; while (listEntry->Flink != &_outstandingEventList) { count++; listEntry = listEntry->Flink; } return count; } void IoTHubDevice::SetLogging(bool value) { _logging = value; IoTHubClient_LL_SetOption(GetHandle(), OPTION_LOG_TRACE, &_logging); } void IoTHubDevice::SetTrustedCertificate(const char *value) { _certificate = value; if (_certificate != NULL) { IoTHubClient_LL_SetOption(GetHandle(), OPTION_TRUSTED_CERT, _certificate); } } IOTHUBMESSAGE_DISPOSITION_RESULT IoTHubDevice::InternalMessageCallback(IOTHUB_MESSAGE_HANDLE message, void *userContext) { IoTHubDevice *that = (IoTHubDevice *)userContext; IOTHUBMESSAGE_DISPOSITION_RESULT result = IOTHUBMESSAGE_REJECTED; if (that->_messageCallback != NULL) { IoTHubMessage *msg = new IoTHubMessage(message); result = that->_messageCallback(*that, *msg, that->_messageCallbackUC); delete msg; } return result; } void IoTHubDevice::InternalConnectionStatusCallback(IOTHUB_CLIENT_CONNECTION_STATUS result, IOTHUB_CLIENT_CONNECTION_STATUS_REASON reason, void* userContext) { IoTHubDevice *that = (IoTHubDevice *)userContext; if (that->_connectionStatusCallback != NULL) { that->_connectionStatusCallback(*that, result, reason, that->_connectionStatusCallbackUC); } } void IoTHubDevice::InternalEventConfirmationCallback(IOTHUB_CLIENT_CONFIRMATION_RESULT result, void *userContext) { MessageUserContext *messageUC = (MessageUserContext *)userContext; if (messageUC->eventConfirmationCallback != NULL) { messageUC->eventConfirmationCallback(*(messageUC->iotHubDevice), result, messageUC->userContext); } DList_RemoveEntryList(&(messageUC->dlistEntry)); delete messageUC; } void IoTHubDevice::InternalReportedStateCallback(int status_code, void* userContext) { ReportedStateUserContext *reportedStateUC = (ReportedStateUserContext *)userContext; if (reportedStateUC->reportedStateCallback != NULL) { reportedStateUC->reportedStateCallback(*(reportedStateUC->iotHubDevice), status_code, reportedStateUC->userContext); } DList_RemoveEntryList(&(reportedStateUC->dlistEntry)); delete reportedStateUC; } int IoTHubDevice::InternalDeviceMethodCallback(const char *methodName, const unsigned char *payload, size_t size, unsigned char **response, size_t *responseSize, void *userContext) { IoTHubDevice *that = (IoTHubDevice *)userContext; map<std::string, DeviceMethodUserContext *>::iterator it; int status = 999; it = that->_deviceMethods.find(methodName); if (it != that->_deviceMethods.end()) { status = it->second->deviceMethodCallback(*that, payload, size, response, responseSize, it->second->userContext); } else if (that->_unknownDeviceMethodCallback != NULL) { status = that->_unknownDeviceMethodCallback(*that, methodName, payload, size, response, responseSize, that->_unknownDeviceMethodCallbackUC); } else { status = 501; const char* RESPONSE_STRING = "{ \"Response\": \"Unknown method requested.\" }"; *responseSize = strlen(RESPONSE_STRING); if ((*response = (unsigned char *)malloc(*responseSize)) == NULL) { status = -1; } else { memcpy(*response, RESPONSE_STRING, *responseSize); } } return status; } void IoTHubDevice::InternalDeviceTwinCallback(DEVICE_TWIN_UPDATE_STATE update_state, const unsigned char* payLoad, size_t size, void* userContext) { IoTHubDevice *that = (IoTHubDevice *)userContext; if (that->_deviceTwinCallback != NULL) { char *json = new char[size + 1]; memcpy(json, payLoad, size); json[size] = '\0'; that->_deviceTwinCallback(update_state, json, that->_deviceTwinCallbackUC); delete [] json; } } IOTHUB_CLIENT_TRANSPORT_PROVIDER IoTHubDevice::GetProtocol(IoTHubDevice::Protocol protocol) { IOTHUB_CLIENT_TRANSPORT_PROVIDER result = NULL; // Currently only MQTT is supported on Arduino - no WebSockets and no proxy switch (protocol) { case Protocol::MQTT: result = MQTT_Protocol; break; default: break; } return result; }
30.466805
180
0.696425
markrad
564f1b6135a5f53c29f793ebfb93046a8d1ff3f6
576
hpp
C++
include/GameConstant.hpp
Tastyep/SFML-GameCore-2D
51dfcd7f3a098b2efa76754703999c6b8d22369d
[ "MIT" ]
null
null
null
include/GameConstant.hpp
Tastyep/SFML-GameCore-2D
51dfcd7f3a098b2efa76754703999c6b8d22369d
[ "MIT" ]
null
null
null
include/GameConstant.hpp
Tastyep/SFML-GameCore-2D
51dfcd7f3a098b2efa76754703999c6b8d22369d
[ "MIT" ]
null
null
null
#ifndef GAME_CORE_GAME_CONSTANT_HPP #define GAME_CORE_GAME_CONSTANT_HPP #include <chrono> #include <string> #include <SFML/System/Vector2.hpp> const std::string kAssetDir = "../assets/"; const std::string kMapDir = "../maps/"; const std::string kConfigDir = "../config/"; const int kMapNumberLength = 2; const int kFrameRate = 30; const auto kTimeStepDuration = std::chrono::milliseconds(1000) / kFrameRate; const float kTimeStep = 1.0f / static_cast<float>(kFrameRate); const int kTileSize = 32; const sf::Vector2f kSpriteOrigin{ kTileSize / 2, kTileSize / 2 }; #endif
26.181818
76
0.744792
Tastyep
5654a2f4a46186c3c7a641ed3c9cdf32af96bdbe
2,164
cc
C++
util/misc/no_cfi_icall_test.cc
dark-richie/crashpad
d573ac113bd5fce5cc970bb5ae76a235a1431a5d
[ "Apache-2.0" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
util/misc/no_cfi_icall_test.cc
dark-richie/crashpad
d573ac113bd5fce5cc970bb5ae76a235a1431a5d
[ "Apache-2.0" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
util/misc/no_cfi_icall_test.cc
dark-richie/crashpad
d573ac113bd5fce5cc970bb5ae76a235a1431a5d
[ "Apache-2.0" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2020 The Crashpad Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "util/misc/no_cfi_icall.h" #include <stdio.h> #include "build/build_config.h" #include "gtest/gtest.h" #if defined(OS_WIN) #include <windows.h> #include "util/win/get_function.h" #else #include <dlfcn.h> #include <sys/types.h> #include <unistd.h> #endif namespace crashpad { namespace test { namespace { TEST(NoCfiIcall, NullptrIsFalse) { NoCfiIcall<void (*)(void) noexcept> call(nullptr); ASSERT_FALSE(call); } int TestFunc() noexcept { return 42; } TEST(NoCfiIcall, SameDSOICall) { NoCfiIcall<decltype(TestFunc)*> call(&TestFunc); ASSERT_TRUE(call); ASSERT_EQ(call(), 42); } TEST(NoCfiIcall, CrossDSOICall) { #if defined(OS_WIN) static const NoCfiIcall<decltype(GetCurrentProcessId)*> call( GET_FUNCTION_REQUIRED(L"kernel32.dll", GetCurrentProcessId)); ASSERT_TRUE(call); EXPECT_EQ(call(), GetCurrentProcessId()); #else static const NoCfiIcall<decltype(getpid)*> call(dlsym(RTLD_NEXT, "getpid")); ASSERT_TRUE(call); EXPECT_EQ(call(), getpid()); #endif } TEST(NoCfiIcall, Args) { #if !defined(OS_WIN) static const NoCfiIcall<decltype(snprintf)*> call( dlsym(RTLD_NEXT, "snprintf")); ASSERT_TRUE(call); char buf[1024]; // Regular args. memset(buf, 0, sizeof(buf)); ASSERT_GT(call(buf, sizeof(buf), "Hello!"), 0); EXPECT_STREQ(buf, "Hello!"); // Variadic args. memset(buf, 0, sizeof(buf)); ASSERT_GT(call(buf, sizeof(buf), "%s, %s!", "Hello", "World"), 0); EXPECT_STREQ(buf, "Hello, World!"); #endif } } // namespace } // namespace test } // namespace crashpad
24.873563
78
0.708872
dark-richie
5658d170b507d311ce22b495e17562ae0dc31f4e
3,496
cpp
C++
lib/msdf-atlas-gen/msdf-atlas-gen/json-export.cpp
Tearnote/Minote
35f63fecc01cf9199db1098256277465e1d41d1e
[ "MIT" ]
8
2021-01-18T12:06:21.000Z
2022-02-13T17:12:56.000Z
lib/msdf-atlas-gen/msdf-atlas-gen/json-export.cpp
Tearnote/Minote
35f63fecc01cf9199db1098256277465e1d41d1e
[ "MIT" ]
null
null
null
lib/msdf-atlas-gen/msdf-atlas-gen/json-export.cpp
Tearnote/Minote
35f63fecc01cf9199db1098256277465e1d41d1e
[ "MIT" ]
null
null
null
#include "json-export.h" namespace msdf_atlas { static const char * imageTypeString(ImageType type) { switch (type) { case ImageType::HARD_MASK: return "hardmask"; case ImageType::SOFT_MASK: return "softmask"; case ImageType::SDF: return "sdf"; case ImageType::PSDF: return "psdf"; case ImageType::MSDF: return "msdf"; case ImageType::MTSDF: return "mtsdf"; } return nullptr; } bool exportJSON(msdfgen::FontHandle *font, const GlyphGeometry *glyphs, int glyphCount, double fontSize, double pxRange, int atlasWidth, int atlasHeight, ImageType imageType, const char *filename) { msdfgen::FontMetrics fontMetrics; if (!msdfgen::getFontMetrics(fontMetrics, font)) return false; double fsScale = 1/fontMetrics.emSize; FILE *f = fopen(filename, "w"); if (!f) return false; fputs("{", f); // Atlas properties fputs("\"atlas\":{", f); { fprintf(f, "\"type\":\"%s\",", imageTypeString(imageType)); if (imageType == ImageType::SDF || imageType == ImageType::PSDF || imageType == ImageType::MSDF || imageType == ImageType::MTSDF) fprintf(f, "\"distanceRange\":%.17g,", pxRange); fprintf(f, "\"size\":%.17g,", fontSize); fprintf(f, "\"width\":%d,", atlasWidth); fprintf(f, "\"height\":%d,", atlasHeight); fputs("\"yOrigin\":\"bottom\"", f); } fputs("},", f); // Font metrics fputs("\"metrics\":{", f); { fprintf(f, "\"lineHeight\":%.17g,", fsScale*fontMetrics.lineHeight); fprintf(f, "\"ascender\":%.17g,", fsScale*fontMetrics.ascenderY); fprintf(f, "\"descender\":%.17g,", fsScale*fontMetrics.descenderY); fprintf(f, "\"underlineY\":%.17g,", fsScale*fontMetrics.underlineY); fprintf(f, "\"underlineThickness\":%.17g", fsScale*fontMetrics.underlineThickness); } fputs("},", f); // Glyph mapping fputs("\"glyphs\":[", f); for (int i = 0; i < glyphCount; ++i) { fputs(i == 0 ? "{" : ",{", f); fprintf(f, "\"index\":%u,", glyphs[i].getCodepoint()); fprintf(f, "\"advance\":%.17g", fsScale*glyphs[i].getAdvance()); double l, b, r, t; glyphs[i].getQuadPlaneBounds(l, b, r, t); if (l || b || r || t) fprintf(f, ",\"planeBounds\":{\"left\":%.17g,\"bottom\":%.17g,\"right\":%.17g,\"top\":%.17g}", fsScale*l, fsScale*b, fsScale*r, fsScale*t); glyphs[i].getQuadAtlasBounds(l, b, r, t); if (l || b || r || t) fprintf(f, ",\"atlasBounds\":{\"left\":%.17g,\"bottom\":%.17g,\"right\":%.17g,\"top\":%.17g}", l, b, r, t); fputs("}", f); } fputs("],", f); // Kerning pairs fputs("\"kerning\":[", f); bool firstPair = true; for (int i = 0; i < glyphCount; ++i) { for (int j = 0; j < glyphCount; ++j) { double kerning; if (msdfgen::getKerning(kerning, font, glyphs[i].getCodepoint(), glyphs[j].getCodepoint()) && kerning) { fputs(firstPair ? "{" : ",{", f); fprintf(f, "\"index1\":%u,", glyphs[i].getCodepoint()); fprintf(f, "\"index2\":%u,", glyphs[j].getCodepoint()); fprintf(f, "\"advance\":%.17g", fsScale*kerning); fputs("}", f); firstPair = false; } } } fputs("]", f); fputs("}\n", f); fclose(f); return true; } }
36.416667
198
0.52889
Tearnote
5660785b9399aeb42d402e6540b34e4715b9e617
227
hpp
C++
nek/container/function/clear.hpp
nekko1119/nek
be43faf5c541fa067ab1e1bcb7a43ebcfefe34e7
[ "BSD-3-Clause" ]
null
null
null
nek/container/function/clear.hpp
nekko1119/nek
be43faf5c541fa067ab1e1bcb7a43ebcfefe34e7
[ "BSD-3-Clause" ]
null
null
null
nek/container/function/clear.hpp
nekko1119/nek
be43faf5c541fa067ab1e1bcb7a43ebcfefe34e7
[ "BSD-3-Clause" ]
null
null
null
#ifndef NEK_CONTAINER_FUNCTION_CLEAR_HPP #define NEK_CONTAINER_FUNCTION_CLEAR_HPP namespace nek { template <class Container> void clear(Container& con) { con.erase(con.begin(), con.end()); } } #endif
16.214286
42
0.696035
nekko1119
5660f2499aa3741496a10854ba6ad622b13408fd
228
cpp
C++
engine/commands/help/source/unit_tests/HelpKeyboardCommandMap_test.cpp
sidav/shadow-of-the-wyrm
747afdeebed885b1a4f7ab42f04f9f756afd3e52
[ "MIT" ]
60
2019-08-21T04:08:41.000Z
2022-03-10T13:48:04.000Z
engine/commands/help/source/unit_tests/HelpKeyboardCommandMap_test.cpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
3
2021-03-18T15:11:14.000Z
2021-10-20T12:13:07.000Z
engine/commands/help/source/unit_tests/HelpKeyboardCommandMap_test.cpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
8
2019-11-16T06:29:05.000Z
2022-01-23T17:33:43.000Z
#include "gtest/gtest.h" TEST(SW_Engine_Commands_Help_HelpKeyboardCommandMap, serialization_id) { HelpKeyboardCommandMap hkcm; EXPECT_EQ(ClassIdentifier::CLASS_ID_HELP_KEYBOARD_COMMAND_MAP, hkcm.get_class_identifier()); }
25.333333
94
0.842105
sidav
566170271eb4daf27aa579be681655190d96bbdd
717
cpp
C++
codeforces/992C - Nastya and a Wardrobe.cpp
Dijkstraido-2/online-judge
31844cd8fbd5038cc5ebc6337d68229cef133a30
[ "MIT" ]
1
2018-12-25T23:55:19.000Z
2018-12-25T23:55:19.000Z
codeforces/992C - Nastya and a Wardrobe.cpp
Dijkstraido-2/online-judge
31844cd8fbd5038cc5ebc6337d68229cef133a30
[ "MIT" ]
null
null
null
codeforces/992C - Nastya and a Wardrobe.cpp
Dijkstraido-2/online-judge
31844cd8fbd5038cc5ebc6337d68229cef133a30
[ "MIT" ]
null
null
null
//============================================================================ // Problem : 992C - Nastya and a Wardrobe // Category : Math //============================================================================ #include <bits/stdc++.h> using namespace std; typedef long long ll; const ll MOD = 1e9+7; ll sub(ll a, ll b) { return (a%MOD - b%MOD + MOD) % MOD; } ll mul(ll a, ll b) { return a%MOD * (b%MOD) % MOD; } ll modP(ll b, ll p) { return !p? 1 : mul(modP(b*b%MOD, p/2), p&1? b:1); } int main() { ll x,k; while(cin >> x >> k) { if(x == 0) cout << 0 << '\n'; else cout << sub(mul(modP(2, k+1), x), sub(modP(2, k), 1)) << '\n'; } return 0; }
24.724138
78
0.380753
Dijkstraido-2
5661b5f36d221b58f79703e7dd72da42a570675e
17,272
cpp
C++
Plugins/StoryGraphPlugin/Source/StoryGraphPluginRuntime/StoryGraphObject.cpp
Xian-Yun-Jun/StoryGraph
36b4a9a24e86e963b1d1d61d4fd5bdfe2eabef9b
[ "MIT" ]
126
2016-12-24T13:58:18.000Z
2022-03-10T03:20:47.000Z
Plugins/StoryGraphPlugin/Source/StoryGraphPluginRuntime/StoryGraphObject.cpp
Xian-Yun-Jun/StoryGraph
36b4a9a24e86e963b1d1d61d4fd5bdfe2eabef9b
[ "MIT" ]
5
2017-01-05T08:23:30.000Z
2018-01-30T19:38:33.000Z
Plugins/StoryGraphPlugin/Source/StoryGraphPluginRuntime/StoryGraphObject.cpp
Xian-Yun-Jun/StoryGraph
36b4a9a24e86e963b1d1d61d4fd5bdfe2eabef9b
[ "MIT" ]
45
2016-12-25T02:21:45.000Z
2022-02-14T16:06:58.000Z
// Copyright 2016 Dmitriy Pavlov #include "StoryGraphObject.h" #include "StoryGraph.h" #include "StoryScenObject.h" #include "HUD_StoryGraph.h" #include "CustomNods.h" #include "StoryGraphWiget.h" #if WITH_EDITORONLY_DATA #include "AssetEditorManager.h" #include "Developer/DesktopPlatform/Public/DesktopPlatformModule.h" #endif //WITH_EDITORONLY_DATA int UStoryGraphObject::CharNum; int UStoryGraphObject::QuestNum; int UStoryGraphObject::PlaceTriggerNum; int UStoryGraphObject::DialogTriggerNum; int UStoryGraphObject::OthersNum; int UStoryGraphObject::InventoryItemNum; UStoryGraphObject::UStoryGraphObject() { Category = "Default"; ObjName = FText::FromString("New Object" + FString::FromInt(OthersNum++)); ObjectType = EStoryObjectType::Non; } TSubclassOf<UStoryGraphObject> UStoryGraphObject::GetClassFromStoryObjectType(EStoryObjectType EnumValue) { switch (EnumValue) { case EStoryObjectType::Character: return UStoryGraphCharecter::StaticClass(); case EStoryObjectType::Quest: return UStoryGraphQuest::StaticClass(); case EStoryObjectType::DialogTrigger: return UStoryGraphDialogTrigger::StaticClass(); case EStoryObjectType::PlaceTrigger: return UStoryGraphPlaceTrigger::StaticClass(); case EStoryObjectType::InventoryItem: return UStoryGraphInventoryItem::StaticClass(); case EStoryObjectType::Others: return UStoryGraphOthers::StaticClass(); default: return UStoryGraphObject::StaticClass(); } } FString UStoryGraphObject::GetObjectTypeEnumAsString(EStoryObjectType EnumValue) { const UEnum* EnumPtr = FindObject<UEnum>(ANY_PACKAGE, TEXT("EStoryObjectType"), true); if (!EnumPtr) return FString("Invalid"); return EnumPtr->GetNameStringByIndex((int)EnumValue); } FString UStoryGraphObject::GetObjectToolTip(EStoryObjectType EnumValue) { switch (EnumValue) { case EStoryObjectType::Character: return "Character has dialogs."; case EStoryObjectType::Quest: return "List of all available quests. After you added quest, will available start quest node."; case EStoryObjectType::DialogTrigger: return "Special facility for interaction dialogue(meesage) graph and main graph."; case EStoryObjectType::PlaceTrigger: return "PlaceTrigger - interactive object on map."; case EStoryObjectType::InventoryItem: return "Story object which can be added to inventory."; case EStoryObjectType::Others: return "Objects that do not have states. But can get messages."; default: return "Non."; } } void UStoryGraphObject::SetCurentState(int NewState) { ObjectState = NewState; ((UStoryGraph*)GetOuter())->RefreshExecutionTrees(); } void UStoryGraphObject::GetXMLSavingProperty(std::map<FString, XMLProperty>& Propertys) { Propertys.clear(); Propertys.insert(std::pair<FString, XMLProperty>("ObjName", XMLProperty(ObjName.ToString()))); Propertys.insert(std::pair<FString, XMLProperty>("ObjectType", XMLProperty(GetEnumValueAsString<EStoryObjectType>("EStoryObjectType", ObjectType)))); Propertys.insert(std::pair<FString, XMLProperty>("Category", XMLProperty( Category))); Propertys.insert(std::pair<FString, XMLProperty>("Comment", XMLProperty(Comment))); } void UStoryGraphObject::LoadPropertyFromXML(std::map<FString, XMLProperty>& Propertys) { ObjName = FText::FromString(Propertys["ObjName"].Val); Category = Propertys["Category"].Val; Comment = Propertys["Comment"].Val; } //UStoryGraphObjectWithScenObject......................................................... UStoryGraphObjectWithScenObject::UStoryGraphObjectWithScenObject() { IsScenObjectActive = true; DependetNodes.Add(ENodeType::GetStoryGraphObjectState); DependetNodes.Add(ENodeType::SetScenObjectActive); DependetNodes.Add(ENodeType::SendMessageCsen); DependetNodes.Add(ENodeType::AddTargetObjectToPhase); } void UStoryGraphObjectWithScenObject::InitializeObject() { SetActiveStateOfScenObjects(); TArray<IStoryScenObject*> ScenObjects; GetScenObjects(ScenObjects); for (int i = 0; i < ObjectMesssageStack.Num(); i++) { for (int j = 0; j < ScenObjects.Num(); j++) { ScenObjects[j]->SendMessageToScenObject(ObjectMesssageStack[i]); } } } void UStoryGraphObjectWithScenObject::SetActiveStateOfScenObjects() { TArray<IStoryScenObject*> ScenObjects; GetScenObjects(ScenObjects); for (int i = 0; i < ScenObjects.Num(); i++) { ScenObjects[i]->RefreshScenObjectActive(); } } void UStoryGraphObjectWithScenObject::SetScenObjectActive(bool Active) { IsScenObjectActive = Active; SetActiveStateOfScenObjects(); } void UStoryGraphObjectWithScenObject::SendMessageToScenObject(FString Message) { TArray<IStoryScenObject*> ScenObjects; GetScenObjects(ScenObjects); for (int i = 0; i < ScenObjects.Num(); i++) { ScenObjects[i]->SendMessageToScenObject(Message); } ObjectMesssageStack.Add(Message); } void UStoryGraphObjectWithScenObject::GetXMLSavingProperty(std::map<FString, XMLProperty>& Propertys) { Super::GetXMLSavingProperty(Propertys); Propertys.insert(std::pair<FString, XMLProperty>("IsScenObjectActive", XMLProperty(IsScenObjectActive ? "true" : "false" ))); } void UStoryGraphObjectWithScenObject::LoadPropertyFromXML(std::map<FString, XMLProperty>& Propertys) { Super::LoadPropertyFromXML(Propertys); IsScenObjectActive = Propertys["IsScenObjectActive"].Val == "true" ? true : false; } //UStoryGraphCharecter................................................................................. UStoryGraphCharecter::UStoryGraphCharecter() { ObjName = FText::FromString("New Character" + FString::FromInt(CharNum++)); ObjectType = EStoryObjectType::Character; DependetNodes.Add(ENodeType::AddDialog); } void UStoryGraphCharecter::GetObjectStateAsString(TArray<FString>& States) { int i = 0; while (i < GetNumberEnums("ECharecterStates")) { States.Add(GetEnumValueAsString<ECharecterStates>("ECharecterStates", (ECharecterStates)i++)); } } void UStoryGraphCharecter::GetScenObjects(TArray<IStoryScenObject*>& ScenObjects) { TExstractScenObgects<IStoryScenObject, ACharecter_StoryGraph>(ScenObjects, ScenCharecters, ScenCharecterPointers); } void UStoryGraphCharecter::GetScenObjects(TArray<AActor*>& ScenObjects) { TExstractScenObgects<AActor, ACharecter_StoryGraph>(ScenObjects, ScenCharecters, ScenCharecterPointers); } void UStoryGraphCharecter::SetScenObjectRealPointers() { ScenCharecterPointers.Empty(); for (int i = 0; i < ScenCharecters.Num(); i++) { ScenCharecterPointers.Add(ScenCharecters[i].Get()); } RealPointersActive = true; } void UStoryGraphCharecter::ClearScenObjects() { ScenCharecters.Empty(); } void UStoryGraphCharecter::GetInternallySaveObjects(TArray<UObject*>& Objects, int WantedObjectsNum) { for (int i = 0; i < GarphNods.Num(); i++) { if (Cast<UDialogStartNode>(GarphNods[i])) { Objects.Add(GarphNods[i]); } } } void UStoryGraphCharecter::GetXMLSavingProperty(std::map<FString, XMLProperty>& Propertys) { Super::GetXMLSavingProperty(Propertys); Propertys.insert(std::pair<FString, XMLProperty>("DefaultAnswer", XMLProperty(DefaultAnswer.ToString()))); } void UStoryGraphCharecter::LoadPropertyFromXML(std::map<FString, XMLProperty>& Propertys) { Super::LoadPropertyFromXML(Propertys); DefaultAnswer = FText::FromString(Propertys["DefaultAnswer"].Val); } //UStoryGraphQuest................................................................................. UStoryGraphQuest::UStoryGraphQuest() { ObjName = FText::FromString("New Quest" + FString::FromInt(QuestNum++)); ObjectType = EStoryObjectType::Quest; MainQuest = true; DependetNodes.Add(ENodeType::GetStoryGraphObjectState); DependetNodes.Add(ENodeType::QuestStart); DependetNodes.Add(ENodeType::CancelQuest); } void UStoryGraphQuest::GetObjectStateAsString(TArray<FString>& States) { int i = 0; while (i < GetNumberEnums("EQuestStates")) { States.Add(GetEnumValueAsString<EQuestStates>("EQuestStates", (EQuestStates)i++)); } } void UStoryGraphQuest::SetCurentState(int NewState) { FText Mesg; ObjectState = NewState; switch ((EQuestStates)NewState) { case EQuestStates::Active: Mesg = FText::Format(NSLOCTEXT("StoryGraph", "Quest active", "New quest {0}"), ObjName); break; case EQuestStates::Canceled: Mesg = FText::Format(NSLOCTEXT("StoryGraph", "Quest cancel", "Quest {0} cancel"), ObjName); break; case EQuestStates::Complite: Mesg = FText::Format(NSLOCTEXT("StoryGraph", "Quest complite", "Quest {0} complite"), ObjName); break; } if (AHUD_StoryGraph* HUD = Cast<AHUD_StoryGraph>(((UStoryGraph*)GetOuter())->OwnedActor->GetWorld()->GetFirstPlayerController()->GetHUD())) { if (HUD->GameScreen) { HUD->GameScreen->AddMessageOnScreen(Mesg, 5); } } ((UStoryGraph*)GetOuter())->QuestStateWasChange = true; } void UStoryGraphQuest::AddPhase(UQuestPhase* Phase) { if (QuestPhase.Num() == 0) { SetCurentState((int)EQuestStates::Active); } else { if (AHUD_StoryGraph* HUD = Cast<AHUD_StoryGraph>((((UStoryGraph*)GetOuter())->OwnedActor->GetWorld()->GetFirstPlayerController()->GetHUD()))) { FText Mesg = FText::Format(NSLOCTEXT("StoryGraph", "AddQuestPhaseMessage2", "Quest {0} changed"), ObjName); if (HUD->GameScreen) { HUD->GameScreen->AddMessageOnScreen(Mesg, 5); } } } QuestPhase.Add(Phase); } void UStoryGraphQuest::GetXMLSavingProperty(std::map<FString, XMLProperty>& Propertys) { Super::GetXMLSavingProperty(Propertys); Propertys.insert(std::pair<FString, XMLProperty>("MainQuest", XMLProperty(MainQuest ? "true" : "false"))); } void UStoryGraphQuest::LoadPropertyFromXML(std::map<FString, XMLProperty>& Propertys) { Super::LoadPropertyFromXML(Propertys); MainQuest = Propertys["MainQuest"].Val == "true" ? true : false; } //UStoryGraphPlaceTrigger................................................................................. UStoryGraphPlaceTrigger::UStoryGraphPlaceTrigger() { ObjName = FText::FromString("Place Trigger" + FString::FromInt(PlaceTriggerNum++)); ObjectType = EStoryObjectType::PlaceTrigger; ObjectState = (int)EPlaceTriggerStates::UnActive; DependetNodes.Add(ENodeType::AddMessageBranch); } void UStoryGraphPlaceTrigger::GetObjectStateAsString(TArray<FString>& States) { int i = 0; while (i < GetNumberEnums("EPlaceTriggerStates")) { States.Add(GetEnumValueAsString<EPlaceTriggerStates>("EPlaceTriggerStates", (EPlaceTriggerStates)i++)); } } void UStoryGraphPlaceTrigger::GetScenObjects(TArray<IStoryScenObject*>& ScenObjects) { TExstractScenObgects<IStoryScenObject, APlaceTrigger_StoryGraph>(ScenObjects, ScenTriggers, PlaceTriggerPointers); } void UStoryGraphPlaceTrigger::GetScenObjects(TArray<AActor*>& ScenObjects) { TExstractScenObgects<AActor, APlaceTrigger_StoryGraph>(ScenObjects, ScenTriggers, PlaceTriggerPointers); } void UStoryGraphPlaceTrigger::SetScenObjectRealPointers() { PlaceTriggerPointers.Empty(); for (int i = 0; i < ScenTriggers.Num(); i++) { PlaceTriggerPointers.Add(ScenTriggers[i].Get()); } RealPointersActive = true; } void UStoryGraphPlaceTrigger::ClearScenObjects() { ScenTriggers.Empty(); } void UStoryGraphPlaceTrigger::GetInternallySaveObjects(TArray<UObject*>& Objects, int WantedObjectsNum) { for (int i = 0; i < GarphNods.Num(); i++) { if (Cast<UDialogStartNode>(GarphNods[i])) { Objects.Add(GarphNods[i]); } } } void UStoryGraphPlaceTrigger::GetXMLSavingProperty(std::map<FString, XMLProperty>& Propertys) { Super::GetXMLSavingProperty(Propertys); Propertys.insert(std::pair<FString, XMLProperty>("DefaultAnswer", XMLProperty(DefaultAnswer.ToString()))); Propertys.insert(std::pair<FString, XMLProperty>("PlaceTriggerType", XMLProperty(GetEnumValueAsString<EPlaceTriggerType>("EPlaceTriggerType", PlaceTriggerType)))); } void UStoryGraphPlaceTrigger::LoadPropertyFromXML(std::map<FString, XMLProperty>& Propertys) { Super::LoadPropertyFromXML(Propertys); DefaultAnswer = FText::FromString(Propertys["DefaultAnswer"].Val); PlaceTriggerType = GetEnumValueFromString<EPlaceTriggerType>("EPlaceTriggerType", Propertys["PlaceTriggerType"].Val); } //UStoryGraphDialogTrigger................................................................................. UStoryGraphDialogTrigger::UStoryGraphDialogTrigger() { ObjName = FText::FromString("Dialog Trigger" + FString::FromInt(DialogTriggerNum++)); ObjectType = EStoryObjectType::DialogTrigger; DependetNodes.Add(ENodeType::GetStoryGraphObjectState); DependetNodes.Add(ENodeType::SetDialogTrigger); } void UStoryGraphDialogTrigger::GetObjectStateAsString(TArray<FString>& States) { int i = 0; while (i < GetNumberEnums("EDialogTriggerStates")) { States.Add(GetEnumValueAsString<EDialogTriggerStates>("EDialogTriggerStates", (EDialogTriggerStates)i++)); } } //UStoryGraphInventoryItem................................................................................. UStoryGraphInventoryItem::UStoryGraphInventoryItem() { ObjName = FText::FromString("Inventory Item" + FString::FromInt(InventoryItemNum++)); ObjectType = EStoryObjectType::InventoryItem; InventoryItemWithoutScenObject = false; DependetNodes.Add(ENodeType::SetInventoryItemState); DependetNodes.Add(ENodeType::SetInventoryItemStateFromMessage); } void UStoryGraphInventoryItem::GetObjectStateAsString(TArray<FString>& States) { States.Add("UnActive"); States.Add("OnLevel"); if (InventoryItemPhase.Num() == 0) { States.Add("InInventory"); } else { for (int i = 0; i < InventoryItemPhase.Num(); i++) { States.Add(InventoryItemPhase[i].ToString()); } } } void UStoryGraphInventoryItem::GetScenObjects(TArray<IStoryScenObject*>& ScenObjects) { TExstractScenObgects<IStoryScenObject, AInventoryItem_StoryGraph>(ScenObjects, ScenInventoryItems, InventoryItemPointers); } void UStoryGraphInventoryItem::GetScenObjects(TArray<AActor*>& ScenObjects) { TExstractScenObgects<AActor, AInventoryItem_StoryGraph>(ScenObjects, ScenInventoryItems, InventoryItemPointers); } void UStoryGraphInventoryItem::SetScenObjectRealPointers() { InventoryItemPointers.Empty(); for (int i = 0; i < ScenInventoryItems.Num(); i++) { InventoryItemPointers.Add(ScenInventoryItems[i].Get()); } RealPointersActive = true; } void UStoryGraphInventoryItem::ClearScenObjects() { ScenInventoryItems.Empty(); } void UStoryGraphInventoryItem::SetCurentState(int NewState) { if (NewState == 0) { SetScenObjectActive(false); } else if (NewState > 0) { if (!IsScenObjectActive) { SetScenObjectActive(false); } } if (NewState == 1) { ObjectState = (int)EInventoryItemeStates::OnLevel; } else if (NewState > 1) { ObjectState = (int)EInventoryItemeStates::InInventory; } if (InventoryItemPhase.Num() > 0 && NewState > 1) { CurrentItemPhase = NewState - 2; } ((UStoryGraph*)GetOuter())->RefreshExecutionTrees(); } int UStoryGraphInventoryItem::GetCurentState() { if (!IsScenObjectActive) { return 0; } if (ObjectState == (int)EInventoryItemeStates::OnLevel) { return 1; } if (ObjectState == (int)EInventoryItemeStates::InInventory) { if (InventoryItemPhase.Num() > 0) { return CurrentItemPhase + 2; } else { return 2; } } return 0; } void UStoryGraphInventoryItem::GetXMLSavingProperty(std::map<FString, XMLProperty>& Propertys) { Super::GetXMLSavingProperty(Propertys); Propertys.insert(std::pair<FString, XMLProperty>("InventoryItemWithoutScenObject", XMLProperty(InventoryItemWithoutScenObject ? "true" : "false"))); Propertys.insert(std::pair<FString, XMLProperty>("Arr_InventoryItemPhase", XMLProperty(""))); XMLProperty& InventoryItemPhasePointer = Propertys["Arr_InventoryItemPhase"]; for (int i = 0; i < InventoryItemPhase.Num(); i++) { InventoryItemPhasePointer.Propertys.insert(std::pair<FString, XMLProperty>(FString::FromInt(i), XMLProperty( InventoryItemPhase[i].ToString()))); } } void UStoryGraphInventoryItem::LoadPropertyFromXML(std::map<FString, XMLProperty>& Propertys) { Super::LoadPropertyFromXML(Propertys); InventoryItemWithoutScenObject = Propertys["InventoryItemWithoutScenObject"].Val == "true" ? true : false; for (auto it = Propertys["Arr_InventoryItemPhase"].Propertys.begin(); it != Propertys["Arr_InventoryItemPhase"].Propertys.end(); ++it) { InventoryItemPhase.Add(FText::FromString(it->second.Val)); } } //UStoryGraphOthers................................................................................. UStoryGraphOthers::UStoryGraphOthers() { ObjName = FText::FromString("Object" + FString::FromInt(OthersNum++)); ObjectType = EStoryObjectType::Others; DependetNodes.RemoveSingle(ENodeType::GetStoryGraphObjectState); } void UStoryGraphOthers::GetScenObjects(TArray<IStoryScenObject*>& ScenObjects) { TExstractScenObgects<IStoryScenObject, AOtherActor_StoryGraph>(ScenObjects, ScenOtherObjects, OtherPointers); } void UStoryGraphOthers::GetScenObjects(TArray<AActor*>& ScenObjects) { TExstractScenObgects<AActor, AOtherActor_StoryGraph>(ScenObjects, ScenOtherObjects, OtherPointers); } void UStoryGraphOthers::SetScenObjectRealPointers() { OtherPointers.Empty(); for (int i = 0; i < ScenOtherObjects.Num(); i++) { OtherPointers.Add(ScenOtherObjects[i].Get()); } RealPointersActive = true; } void UStoryGraphOthers::ClearScenObjects() { ScenOtherObjects.Empty(); }
26.130106
164
0.739868
Xian-Yun-Jun
56624ea6e4db7e72c41abca7c028bf32bca9a125
42
hpp
C++
addons/vehicles_land/XEH_PREP.hpp
SOCOMD/SOCOMD-MODS-2021
834cd5f99831bd456179a1f55f5a91398c29bf57
[ "MIT" ]
null
null
null
addons/vehicles_land/XEH_PREP.hpp
SOCOMD/SOCOMD-MODS-2021
834cd5f99831bd456179a1f55f5a91398c29bf57
[ "MIT" ]
null
null
null
addons/vehicles_land/XEH_PREP.hpp
SOCOMD/SOCOMD-MODS-2021
834cd5f99831bd456179a1f55f5a91398c29bf57
[ "MIT" ]
null
null
null
PREP(BushMasterHitEH); PREP(JackelHitEH);
14
22
0.809524
SOCOMD
566566612126c19727fe46fd806e58fcef23e6c0
2,372
cpp
C++
ecs/src/v2/model/ResizePostPaidServerOption.cpp
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
5
2021-03-03T08:23:43.000Z
2022-02-16T02:16:39.000Z
ecs/src/v2/model/ResizePostPaidServerOption.cpp
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
null
null
null
ecs/src/v2/model/ResizePostPaidServerOption.cpp
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
7
2021-02-26T13:53:35.000Z
2022-03-18T02:36:43.000Z
#include "huaweicloud/ecs/v2/model/ResizePostPaidServerOption.h" namespace HuaweiCloud { namespace Sdk { namespace Ecs { namespace V2 { namespace Model { ResizePostPaidServerOption::ResizePostPaidServerOption() { flavorRef_ = ""; flavorRefIsSet_ = false; mode_ = ""; modeIsSet_ = false; } ResizePostPaidServerOption::~ResizePostPaidServerOption() = default; void ResizePostPaidServerOption::validate() { } web::json::value ResizePostPaidServerOption::toJson() const { web::json::value val = web::json::value::object(); if(flavorRefIsSet_) { val[utility::conversions::to_string_t("flavorRef")] = ModelBase::toJson(flavorRef_); } if(modeIsSet_) { val[utility::conversions::to_string_t("mode")] = ModelBase::toJson(mode_); } return val; } bool ResizePostPaidServerOption::fromJson(const web::json::value& val) { bool ok = true; if(val.has_field(utility::conversions::to_string_t("flavorRef"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("flavorRef")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setFlavorRef(refVal); } } if(val.has_field(utility::conversions::to_string_t("mode"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("mode")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setMode(refVal); } } return ok; } std::string ResizePostPaidServerOption::getFlavorRef() const { return flavorRef_; } void ResizePostPaidServerOption::setFlavorRef(const std::string& value) { flavorRef_ = value; flavorRefIsSet_ = true; } bool ResizePostPaidServerOption::flavorRefIsSet() const { return flavorRefIsSet_; } void ResizePostPaidServerOption::unsetflavorRef() { flavorRefIsSet_ = false; } std::string ResizePostPaidServerOption::getMode() const { return mode_; } void ResizePostPaidServerOption::setMode(const std::string& value) { mode_ = value; modeIsSet_ = true; } bool ResizePostPaidServerOption::modeIsSet() const { return modeIsSet_; } void ResizePostPaidServerOption::unsetmode() { modeIsSet_ = false; } } } } } }
20.273504
100
0.671585
yangzhaofeng
566a4d89f934a44b604fcd743438594aaa2f4903
245
inl
C++
include/volt/gpu/resource.inl
voltengine/volt
fbefe2e0a8e461b6130ffe926870c4848bd6e7d1
[ "MIT" ]
null
null
null
include/volt/gpu/resource.inl
voltengine/volt
fbefe2e0a8e461b6130ffe926870c4848bd6e7d1
[ "MIT" ]
null
null
null
include/volt/gpu/resource.inl
voltengine/volt
fbefe2e0a8e461b6130ffe926870c4848bd6e7d1
[ "MIT" ]
null
null
null
namespace volt::gpu { template<typename T> void resource::map(const std::function<void(T &)> &callback, access_modes access, size_t offset) { map([&](void *data) { callback(*reinterpret_cast<T *>(data)); }, access, sizeof(T), offset); } }
22.272727
98
0.677551
voltengine
566e94fbc34e559b0d13bc828d176a9d942fc6a0
2,440
cpp
C++
Src/Graphics/OpenGL_Desktop.cpp
Eae02/jamlib
66193bc11fee3a8964f2af0aca6c20cdf56b3b4c
[ "Zlib" ]
null
null
null
Src/Graphics/OpenGL_Desktop.cpp
Eae02/jamlib
66193bc11fee3a8964f2af0aca6c20cdf56b3b4c
[ "Zlib" ]
null
null
null
Src/Graphics/OpenGL_Desktop.cpp
Eae02/jamlib
66193bc11fee3a8964f2af0aca6c20cdf56b3b4c
[ "Zlib" ]
null
null
null
#include "OpenGL.hpp" #ifndef JM_USE_GLES #include <iostream> #include <string_view> #include <SDL_video.h> namespace jm::detail { bool hasModernGL; float maxAnistropy; static std::string glVendorName; void OpenGLMessageCallback(GLenum, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void*) { if (id == 1286) return; if (glVendorName == "Intel Open Source Technology Center") { if (id == 17 || id == 14) //Clearing integer framebuffer attachments. return; } const char* severityString = "N"; if (severity == GL_DEBUG_SEVERITY_HIGH || type == GL_DEBUG_TYPE_ERROR) { severityString = "E"; } else if (severity == GL_DEBUG_SEVERITY_LOW || severity == GL_DEBUG_SEVERITY_MEDIUM) { severityString = "W"; } std::string_view messageView(message, static_cast<size_t>(length)); //Some vendors include a newline at the end of the message. This removes the newline if present. if (messageView.back() == '\n') { messageView = messageView.substr(0, messageView.size() - 1); } std::cout << "GL[" << severityString << id << "]: " << messageView << std::endl; if (type == GL_DEBUG_TYPE_ERROR) std::abort(); } static const char* RequiredExtensions[] = { "GL_ARB_texture_storage" }; static const char* ModernExtensions[] = { "GL_ARB_direct_state_access", "GL_ARB_buffer_storage" }; bool InitializeOpenGL(bool debug) { if (gl3wInit()) { std::cerr << "Error initializing OpenGL\n"; return false; } glVendorName = reinterpret_cast<const char*>(glGetString(GL_VENDOR)); for (const char* ext : RequiredExtensions) { if (!SDL_GL_ExtensionSupported(ext)) { std::cerr << "Required OpenGL extension not supported: '" << ext << "'.\n"; return false; } } hasModernGL = true; for (const char* ext : ModernExtensions) { if (!SDL_GL_ExtensionSupported(ext)) { hasModernGL = false; break; } } if (SDL_GL_ExtensionSupported("GL_EXT_texture_filter_anisotropic")) { glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY, &maxAnistropy); } if (debug && glDebugMessageCallback) { glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); glDebugMessageCallback(OpenGLMessageCallback, nullptr); glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_NOTIFICATION, 0, nullptr, GL_FALSE); } return true; } } #endif
22.385321
107
0.672131
Eae02
5670ea398c3074eec3f9b7f4ad7d41390ef5f111
2,775
cpp
C++
src/engine/TextureHandle.cpp
foxostro/arbarlith2
820ffc8c3efcb636eb2c639487815fb9aabdc82e
[ "BSD-3-Clause" ]
1
2019-04-09T18:42:00.000Z
2019-04-09T18:42:00.000Z
src/engine/TextureHandle.cpp
foxostro/arbarlith2
820ffc8c3efcb636eb2c639487815fb9aabdc82e
[ "BSD-3-Clause" ]
null
null
null
src/engine/TextureHandle.cpp
foxostro/arbarlith2
820ffc8c3efcb636eb2c639487815fb9aabdc82e
[ "BSD-3-Clause" ]
null
null
null
/* Original Author: Andrew Fox E-Mail: mailto:foxostro@gmail.com Copyright (c) 2006-2007,2009 Game Creation Society All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Game Creation Society 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 Game Creation Society ``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 Game Creation Society 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 "stdafx.h" #include "gl.h" #include "Effect.h" #include "TextureHandle.h" namespace Engine { TextureHandle::TextureHandle(void) { fileName="(nill)"; width=height=0; alpha=false; id=0; } TextureHandle::TextureHandle(const string &fileName, int width, int height, bool alpha, GLuint id) { this->fileName = fileName; this->width = width; this->height = height; this->alpha = alpha; this->id = id; } void TextureHandle::release(void) { glDeleteTextures(1, &id); id=0; } void TextureHandle::reaquire(void) { release(); Image img(fileName); int depth = img.getDepth(); // get a new id glGenTextures(1, &id); // and bind it as the present texture glBindTexture(GL_TEXTURE_2D, id); // Set the texture filtering according to global performance settings Effect::setTextureFilters(); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // now build mipmaps from the texture data gluBuild2DMipmaps(GL_TEXTURE_2D, depth, img.getWidth(), img.getHeight(), depth==4 ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE, img.getImage()); } }; // namespace
29.521277
98
0.751712
foxostro
56747c5c47b952021c2d327e8348876d709436fa
103
cpp
C++
src/core/BaseException.cpp
Neomer/binc
3af615f36cb23f1cdc9319b7a6e15c6c342a53b9
[ "Apache-2.0" ]
null
null
null
src/core/BaseException.cpp
Neomer/binc
3af615f36cb23f1cdc9319b7a6e15c6c342a53b9
[ "Apache-2.0" ]
26
2017-12-13T12:45:32.000Z
2018-02-06T11:08:04.000Z
src/core/BaseException.cpp
Neomer/binc
3af615f36cb23f1cdc9319b7a6e15c6c342a53b9
[ "Apache-2.0" ]
null
null
null
#include "BaseException.h" BaseException::BaseException(const char *message) : _msg(message) { }
12.875
51
0.718447
Neomer
567dc8c02e6d9572d168cb4090d34b542068725c
2,619
cc
C++
zetasql/testing/test_catalog.cc
wbsouza/zetasql-formatter
3db113adee8d4fcb27dc978123dc75079442bf69
[ "Apache-2.0" ]
1,779
2019-04-23T19:41:49.000Z
2022-03-31T18:53:18.000Z
zetasql/testing/test_catalog.cc
wbsouza/zetasql-formatter
3db113adee8d4fcb27dc978123dc75079442bf69
[ "Apache-2.0" ]
94
2019-05-22T00:30:05.000Z
2022-03-31T06:26:09.000Z
zetasql/testing/test_catalog.cc
wbsouza/zetasql-formatter
3db113adee8d4fcb27dc978123dc75079442bf69
[ "Apache-2.0" ]
153
2019-04-23T22:45:41.000Z
2022-02-18T05:44:10.000Z
// // Copyright 2019 Google LLC // // 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 "zetasql/testing/test_catalog.h" #include "absl/status/status.h" #include "zetasql/base/case.h" #include "zetasql/base/map_util.h" #include "zetasql/base/status_macros.h" namespace zetasql { TestCatalog::~TestCatalog() { } absl::Status TestCatalog::GetErrorForName(const std::string& name) const { const absl::Status* error = zetasql_base::FindOrNull(errors_, absl::AsciiStrToLower(name)); if (error != nullptr) { return *error; } else { return absl::OkStatus(); } } absl::Status TestCatalog::GetTable(const std::string& name, const Table** table, const FindOptions& options) { ZETASQL_RETURN_IF_ERROR(GetErrorForName(name)); return SimpleCatalog::GetTable(name, table, options); } absl::Status TestCatalog::GetFunction(const std::string& name, const Function** function, const FindOptions& options) { ZETASQL_RETURN_IF_ERROR(GetErrorForName(name)); return SimpleCatalog::GetFunction(name, function, options); } absl::Status TestCatalog::GetType(const std::string& name, const Type** type, const FindOptions& options) { ZETASQL_RETURN_IF_ERROR(GetErrorForName(name)); return SimpleCatalog::GetType(name, type, options); } absl::Status TestCatalog::GetCatalog(const std::string& name, Catalog** catalog, const FindOptions& options) { ZETASQL_RETURN_IF_ERROR(GetErrorForName(name)); return SimpleCatalog::GetCatalog(name, catalog, options); } void TestCatalog::AddError(const std::string& name, const absl::Status& error) { zetasql_base::InsertOrDie(&errors_, absl::AsciiStrToLower(name), error); } TestFunction::TestFunction( const std::string& function_name, Function::Mode mode, const std::vector<FunctionSignature>& function_signatures) : Function(function_name, "TestFunction", mode, function_signatures) {} TestFunction::~TestFunction() { } } // namespace zetasql
34.012987
80
0.695304
wbsouza
5683264e2c7c942ce2ef5fe75106d2d2e92ca956
486
cpp
C++
tests/realapplications/libHX_overflow/libHX-3.4/src/tx-compile.cpp
GYJQTYL2/DoubleTake
cdcd0200bb364b5343beae72756420e6c3954a6f
[ "MIT" ]
19
2015-09-17T18:10:14.000Z
2021-08-16T11:26:33.000Z
tests/realapplications/libHX_overflow/libHX-3.4/src/tx-compile.cpp
GYJQTYL2/DoubleTake
cdcd0200bb364b5343beae72756420e6c3954a6f
[ "MIT" ]
17
2015-04-27T14:33:42.000Z
2016-05-23T20:15:48.000Z
tests/realapplications/libHX_overflow/libHX-3.4/src/tx-compile.cpp
plasma-umass/DoubleTake
cdcd0200bb364b5343beae72756420e6c3954a6f
[ "MIT" ]
13
2015-07-29T15:15:00.000Z
2021-01-15T04:53:21.000Z
/* This file is for testing the cumulative include */ #ifndef __cplusplus # include <stdlib.h> #else # include <cstdlib> #endif #include <libHX.h> #define ZZ 64 int main(void) { unsigned long bitmap[HXbitmap_size(unsigned long, 64)]; if (HX_init() <= 0) abort(); printf("sizeof bitmap: %zu, array_size: %zu\n", sizeof(bitmap), ARRAY_SIZE(bitmap)); HXbitmap_set(bitmap, 0); printf(HX_STRINGIFY(1234+2 +2) "," HX_STRINGIFY(ZZ) "\n"); HX_exit(); return EXIT_SUCCESS; }
20.25
59
0.683128
GYJQTYL2
568bb161de43b5b938b17aa4a4ffaf46f4661dbc
11,031
cpp
C++
aegisub/src/search_replace_engine.cpp
rcombs/Aegisub
58f35cd31c7f0f5728e0a28e6a7a9fd6fce70c50
[ "ISC" ]
1
2018-02-12T02:44:57.000Z
2018-02-12T02:44:57.000Z
aegisub/src/search_replace_engine.cpp
rcombs/Aegisub
58f35cd31c7f0f5728e0a28e6a7a9fd6fce70c50
[ "ISC" ]
null
null
null
aegisub/src/search_replace_engine.cpp
rcombs/Aegisub
58f35cd31c7f0f5728e0a28e6a7a9fd6fce70c50
[ "ISC" ]
2
2018-02-12T03:46:24.000Z
2018-02-12T14:36:07.000Z
// Copyright (c) 2013, Thomas Goyne <plorkyeran@aegisub.org> // // Permission to use, copy, modify, and distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // // Aegisub Project http://www.aegisub.org/ #include "config.h" #include "search_replace_engine.h" #include "ass_dialogue.h" #include "ass_file.h" #include "include/aegisub/context.h" #include "selection_controller.h" #include "text_selection_controller.h" #include <libaegisub/of_type_adaptor.h> #include <libaegisub/util.h> #include <boost/locale.hpp> #include <wx/msgdlg.h> static const size_t bad_pos = -1; namespace { auto get_dialogue_field(SearchReplaceSettings::Field field) -> decltype(&AssDialogue::Text) { switch (field) { case SearchReplaceSettings::Field::TEXT: return &AssDialogue::Text; case SearchReplaceSettings::Field::STYLE: return &AssDialogue::Style; case SearchReplaceSettings::Field::ACTOR: return &AssDialogue::Actor; case SearchReplaceSettings::Field::EFFECT: return &AssDialogue::Effect; } throw agi::InternalError("Bad field for search", nullptr); } std::string const& get_normalized(const AssDialogue *diag, decltype(&AssDialogue::Text) field) { auto& value = const_cast<AssDialogue*>(diag)->*field; auto normalized = boost::locale::normalize(value.get()); if (normalized != value) value = normalized; return value.get(); } typedef std::function<MatchState (const AssDialogue*, size_t)> matcher; class noop_accessor { boost::flyweight<std::string> AssDialogue::*field; size_t start; public: noop_accessor(SearchReplaceSettings::Field f) : field(get_dialogue_field(f)), start(0) { } std::string get(const AssDialogue *d, size_t s) { start = s; return get_normalized(d, field).substr(s); } MatchState make_match_state(size_t s, size_t e, boost::u32regex *r = nullptr) { return MatchState(s + start, e + start, r); } }; class skip_tags_accessor { boost::flyweight<std::string> AssDialogue::*field; std::vector<std::pair<size_t, size_t>> blocks; size_t start; void parse_str(std::string const& str) { blocks.clear(); size_t ovr_start = bad_pos; size_t i = 0; for (auto const& c : str) { if (c == '{' && ovr_start == bad_pos) ovr_start = i; else if (c == '}' && ovr_start != bad_pos) { blocks.emplace_back(ovr_start, i); ovr_start = bad_pos; } ++i; } } public: skip_tags_accessor(SearchReplaceSettings::Field f) : field(get_dialogue_field(f)), start(0) { } std::string get(const AssDialogue *d, size_t s) { auto const& str = get_normalized(d, field); parse_str(str); std::string out; size_t last = s; for (auto const& block : blocks) { if (block.second < s) continue; if (block.first > last) out.append(str.begin() + last, str.begin() + block.first); last = block.second + 1; } if (last < str.size()) out.append(str.begin() + last, str.end()); start = s; return out; } MatchState make_match_state(size_t s, size_t e, boost::u32regex *r = nullptr) { s += start; e += start; // Shift the start and end of the match to be relative to the unstripped // match for (auto const& block : blocks) { // Any blocks before start are irrelevant as they're included in `start` if (block.second < s) continue; // Skip over blocks at the very beginning of the match // < should only happen if the cursor was within an override block // when the user started a search if (block.first <= s) { size_t len = block.second - std::max(block.first, s) + 1; s += len; e += len; continue; } assert(block.first > s); // Blocks after the match are irrelevant if (block.first >= e) break; // Extend the match to include blocks within the match // Note that blocks cannot be partially within the match e += block.second - block.first + 1; } return MatchState(s, e, r); } }; template<typename Accessor> matcher get_matcher(SearchReplaceSettings const& settings, Accessor&& a) { if (settings.use_regex) { int flags = boost::u32regex::perl; if (!settings.match_case) flags |= boost::u32regex::icase; auto regex = boost::make_u32regex(settings.find, flags); return [=](const AssDialogue *diag, size_t start) mutable -> MatchState { boost::smatch result; auto const& str = a.get(diag, start); if (!u32regex_search(str, result, regex, start > 0 ? boost::match_not_bol : boost::match_default)) return MatchState(); return a.make_match_state(result.position(), result.position() + result.length(), &regex); }; } bool full_match_only = settings.exact_match; bool match_case = settings.match_case; std::string look_for = settings.find; if (!settings.match_case) look_for = boost::locale::fold_case(look_for); return [=](const AssDialogue *diag, size_t start) mutable -> MatchState { const auto str = a.get(diag, start); if (full_match_only && str.size() != look_for.size()) return MatchState(); if (match_case) { const auto pos = str.find(look_for); return pos == std::string::npos ? MatchState() : a.make_match_state(pos, pos + look_for.size()); } const auto pos = agi::util::ifind(str, look_for); return pos.first == bad_pos ? MatchState() : a.make_match_state(pos.first, pos.second); }; } template<typename Iterator, typename Container> Iterator circular_next(Iterator it, Container& c) { ++it; if (it == c.end()) it = c.begin(); return it; } } std::function<MatchState (const AssDialogue*, size_t)> SearchReplaceEngine::GetMatcher(SearchReplaceSettings const& settings) { if (settings.skip_tags) return get_matcher(settings, skip_tags_accessor(settings.field)); return get_matcher(settings, noop_accessor(settings.field)); } SearchReplaceEngine::SearchReplaceEngine(agi::Context *c) : context(c) , initialized(false) { } void SearchReplaceEngine::Replace(AssDialogue *diag, MatchState &ms) { auto& diag_field = diag->*get_dialogue_field(settings.field); auto text = diag_field.get(); std::string replacement = settings.replace_with; if (ms.re) { auto to_replace = text.substr(ms.start, ms.end - ms.start); replacement = u32regex_replace(to_replace, *ms.re, replacement, boost::format_first_only); } diag_field = text.substr(0, ms.start) + replacement + text.substr(ms.end); ms.end = ms.start + replacement.size(); } bool SearchReplaceEngine::FindReplace(bool replace) { if (!initialized) return false; auto matches = GetMatcher(settings); AssDialogue *line = context->selectionController->GetActiveLine(); auto it = context->ass->Line.iterator_to(*line); size_t pos = 0; MatchState replace_ms; if (replace) { if (settings.field == SearchReplaceSettings::Field::TEXT) pos = context->textSelectionController->GetSelectionStart(); if ((replace_ms = matches(line, pos))) { size_t end = bad_pos; if (settings.field == SearchReplaceSettings::Field::TEXT) end = context->textSelectionController->GetSelectionEnd(); if (end == bad_pos || (pos == replace_ms.start && end == replace_ms.end)) { Replace(line, replace_ms); pos = replace_ms.end; context->ass->Commit(_("replace"), AssFile::COMMIT_DIAG_TEXT); } else { // The current line matches, but it wasn't already selected, // so the match hasn't been "found" and displayed to the user // yet, so do that rather than replacing context->textSelectionController->SetSelection(replace_ms.start, replace_ms.end); return true; } } } // Search from the end of the selection to avoid endless matching the same thing else if (settings.field == SearchReplaceSettings::Field::TEXT) pos = context->textSelectionController->GetSelectionEnd(); // For non-text fields we just look for matching lines rather than each // match within the line, so move to the next line else if (settings.field != SearchReplaceSettings::Field::TEXT) it = circular_next(it, context->ass->Line); auto const& sel = context->selectionController->GetSelectedSet(); bool selection_only = sel.size() > 1 && settings.limit_to == SearchReplaceSettings::Limit::SELECTED; do { AssDialogue *diag = dynamic_cast<AssDialogue*>(&*it); if (!diag) continue; if (selection_only && !sel.count(diag)) continue; if (settings.ignore_comments && diag->Comment) continue; if (MatchState ms = matches(diag, pos)) { if (selection_only) // We're cycling through the selection, so don't muck with it context->selectionController->SetActiveLine(diag); else context->selectionController->SetSelectionAndActive({ diag }, diag); if (settings.field == SearchReplaceSettings::Field::TEXT) context->textSelectionController->SetSelection(ms.start, ms.end); return true; } } while (pos = 0, &*(it = circular_next(it, context->ass->Line)) != line); // Replaced something and didn't find another match, so select the newly // inserted text if (replace_ms && settings.field == SearchReplaceSettings::Field::TEXT) context->textSelectionController->SetSelection(replace_ms.start, replace_ms.end); return true; } bool SearchReplaceEngine::ReplaceAll() { if (!initialized) return false; size_t count = 0; auto matches = GetMatcher(settings); SubtitleSelection const& sel = context->selectionController->GetSelectedSet(); bool selection_only = settings.limit_to == SearchReplaceSettings::Limit::SELECTED; for (auto diag : context->ass->Line | agi::of_type<AssDialogue>()) { if (selection_only && !sel.count(diag)) continue; if (settings.ignore_comments && diag->Comment) continue; if (settings.use_regex) { if (MatchState ms = matches(diag, 0)) { auto& diag_field = diag->*get_dialogue_field(settings.field); std::string const& text = diag_field.get(); count += distance( boost::u32regex_iterator<std::string::const_iterator>(begin(text), end(text), *ms.re), boost::u32regex_iterator<std::string::const_iterator>()); diag_field = u32regex_replace(text, *ms.re, settings.replace_with); } continue; } size_t pos = 0; while (MatchState ms = matches(diag, pos)) { ++count; Replace(diag, ms); pos = ms.end; } } if (count > 0) { context->ass->Commit(_("replace"), AssFile::COMMIT_DIAG_TEXT); wxMessageBox(wxString::Format(_("%i matches were replaced."), (int)count)); } else { wxMessageBox(_("No matches found.")); } return true; } void SearchReplaceEngine::Configure(SearchReplaceSettings const& new_settings) { settings = new_settings; initialized = true; }
31.60745
127
0.707279
rcombs
568dcaf91f6b658f3ca117f73325be96eb025ab7
777
cpp
C++
old-questions/2070-Chaitra/q3.cpp
B33pl0p/ioe-oop
87162561e0ced7e7e9cc7c7a8354d535de16e1f5
[ "MIT" ]
4
2021-02-19T12:19:06.000Z
2022-02-11T14:15:49.000Z
old-questions/2070-Chaitra/q3.cpp
B33pl0p/ioe-oop
87162561e0ced7e7e9cc7c7a8354d535de16e1f5
[ "MIT" ]
null
null
null
old-questions/2070-Chaitra/q3.cpp
B33pl0p/ioe-oop
87162561e0ced7e7e9cc7c7a8354d535de16e1f5
[ "MIT" ]
12
2018-01-29T15:37:51.000Z
2022-02-10T06:45:03.000Z
// Write a C++ program to join two strings using dynamics constructor concept #include <iostream> #include <string.h> using namespace std; class Strings { char *str; public: Strings() {} Strings(char *s) { int length = strlen(s); str = new char[length]; strcpy(str,s); } Strings join(Strings s) { Strings temp; int length = strlen(str) + strlen(s.str); temp.str = new char[length]; strcpy(temp.str,str); strcat(temp.str,s.str); return temp; } void display() { cout << str; } }; int main() { Strings s1("Amit"),s2("Chaudhary"),s3; s3 = s1.join(s2); s3.display(); return 0; }
22.2
77
0.503218
B33pl0p
5693a6b899434cd6f4a9b6d612f5815788b3aee2
558
cpp
C++
CLearn/DiscarnateLayer.cpp
JamesGlare/Neural-Net-LabView-DLL
d912e0bfd0231d22bcd27ae6a71ebfcb23129aba
[ "MIT" ]
12
2018-07-23T17:07:29.000Z
2021-04-26T01:46:48.000Z
CLearn/DiscarnateLayer.cpp
JamesGlare/Neural-Net-LabView-DLL
d912e0bfd0231d22bcd27ae6a71ebfcb23129aba
[ "MIT" ]
null
null
null
CLearn/DiscarnateLayer.cpp
JamesGlare/Neural-Net-LabView-DLL
d912e0bfd0231d22bcd27ae6a71ebfcb23129aba
[ "MIT" ]
9
2019-05-06T13:19:39.000Z
2021-03-23T01:10:25.000Z
#include "stdafx.h" #include "DiscarnateLayer.h" DiscarnateLayer::DiscarnateLayer(size_t _NOUT, size_t _NIN) : CNetLayer(_NOUT, _NIN) {}; DiscarnateLayer::DiscarnateLayer(size_t _NOUT, size_t _NIN, actfunc_t type) : CNetLayer(_NOUT, _NIN, type) {}; DiscarnateLayer::DiscarnateLayer(size_t _NOUT, actfunc_t type, CNetLayer& lower) : CNetLayer(_NOUT, type, lower) {}; void DiscarnateLayer::applyUpdate(const learnPars& pars, MAT& input, bool recursive) { if (getHierachy() != hierarchy_t::output && recursive) { above->applyUpdate(pars, input, true); } }
46.5
116
0.752688
JamesGlare
5695d46f99c3f8c225d2745b02ecd287bbc5d6a8
7,409
cpp
C++
Refureku/Library/Tests/ArchetypeTests.cpp
Angelysse/Refureku
1f01107c94cd81998068ce3fde02bb21c180166b
[ "MIT" ]
null
null
null
Refureku/Library/Tests/ArchetypeTests.cpp
Angelysse/Refureku
1f01107c94cd81998068ce3fde02bb21c180166b
[ "MIT" ]
null
null
null
Refureku/Library/Tests/ArchetypeTests.cpp
Angelysse/Refureku
1f01107c94cd81998068ce3fde02bb21c180166b
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <Refureku/Refureku.h> #include "TestStruct.h" #include "TestClass.h" #include "TestClass2.h" #include "TestEnum.h" #include "TestNamespace.h" #include "TypeTemplateClassTemplate.h" //========================================================= //=========== Archetype::getAccessSpecifier =============== //========================================================= TEST(Rfk_Archetype_getAccessSpecifier, FundamentalArchetypes) { EXPECT_EQ(rfk::getArchetype<void>()->getAccessSpecifier(), rfk::EAccessSpecifier::Undefined); EXPECT_EQ(rfk::getArchetype<int>()->getAccessSpecifier(), rfk::EAccessSpecifier::Undefined); EXPECT_EQ(rfk::getArchetype<char>()->getAccessSpecifier(), rfk::EAccessSpecifier::Undefined); EXPECT_EQ(rfk::getArchetype<long long>()->getAccessSpecifier(), rfk::EAccessSpecifier::Undefined); } TEST(Rfk_Archetype_getAccessSpecifier, NonNestedStructClass) { EXPECT_EQ(rfk::getArchetype<TestClass>()->getAccessSpecifier(), rfk::EAccessSpecifier::Undefined); EXPECT_EQ(rfk::getArchetype<test_namespace::TestNamespaceNestedClass>()->getAccessSpecifier(), rfk::EAccessSpecifier::Undefined); } TEST(Rfk_Archetype_getAccessSpecifier, PublicNestedStructClass) { EXPECT_EQ(rfk::getArchetype<TestStruct::NestedClass>()->getAccessSpecifier(), rfk::EAccessSpecifier::Public); EXPECT_EQ(rfk::getArchetype<TestStruct::NestedStruct>()->getAccessSpecifier(), rfk::EAccessSpecifier::Public); } TEST(Rfk_Archetype_getAccessSpecifier, ProtectedNestedStructClass) { EXPECT_EQ(TestClass::staticGetArchetype().getNestedClassByName("NestedClass")->getAccessSpecifier(), rfk::EAccessSpecifier::Protected); EXPECT_EQ(TestClass::staticGetArchetype().getNestedClassByName("NestedClass", rfk::EAccessSpecifier::Protected)->getAccessSpecifier(), rfk::EAccessSpecifier::Protected); } TEST(Rfk_Archetype_getAccessSpecifier, PrivateNestedStructClass) { EXPECT_EQ(TestClass::staticGetArchetype().getNestedStructByName("NestedStruct")->getAccessSpecifier(), rfk::EAccessSpecifier::Private); EXPECT_EQ(TestClass::staticGetArchetype().getNestedStructByName("NestedStruct", rfk::EAccessSpecifier::Private)->getAccessSpecifier(), rfk::EAccessSpecifier::Private); } TEST(Rfk_Archetype_getAccessSpecifier, NonNestedClassTemplate) { EXPECT_EQ(rfk::getArchetype<SingleTypeTemplateClassTemplate>()->getAccessSpecifier(), rfk::EAccessSpecifier::Undefined); } TEST(Rfk_Archetype_getAccessSpecifier, NamespaceNestedClassTemplate) { EXPECT_EQ(rfk::getArchetype<template_namespace::ClassTemplateInNamespace>()->getAccessSpecifier(), rfk::EAccessSpecifier::Undefined); } TEST(Rfk_Archetype_getAccessSpecifier, ClassNestedClassTemplate) { EXPECT_EQ(rfk::getArchetype<ClassWithNestedClassTemplate::PublicClassTemplateInClass>()->getAccessSpecifier(), rfk::EAccessSpecifier::Public); } TEST(Rfk_Archetype_getAccessSpecifier, NonNestedClassTemplateInstantiation) { EXPECT_EQ(rfk::getArchetype<SingleTypeTemplateClassTemplate<int>>()->getAccessSpecifier(), rfk::EAccessSpecifier::Undefined); } TEST(Rfk_Archetype_getAccessSpecifier, NonNestedEnum) { EXPECT_EQ(rfk::getEnum<TestEnum>()->getAccessSpecifier(), rfk::EAccessSpecifier::Undefined); EXPECT_EQ(rfk::getEnum<test_namespace::TestNamespaceNestedEnum>()->getAccessSpecifier(), rfk::EAccessSpecifier::Undefined); } TEST(Rfk_Archetype_getAccessSpecifier, PublicNestedEnum) { EXPECT_EQ(rfk::getEnum<TestClass::NestedEnum>()->getAccessSpecifier(), rfk::EAccessSpecifier::Public); } TEST(Rfk_Archetype_getAccessSpecifier, ProtectedNestedEnum) { EXPECT_EQ(TestClass2::staticGetArchetype().getNestedEnumByName("ProtectedNestedEnum")->getAccessSpecifier(), rfk::EAccessSpecifier::Protected); EXPECT_EQ(TestClass2::staticGetArchetype().getNestedEnumByName("ProtectedNestedEnum", rfk::EAccessSpecifier::Protected)->getAccessSpecifier(), rfk::EAccessSpecifier::Protected); } TEST(Rfk_Archetype_getAccessSpecifier, PrivateNestedEnum) { EXPECT_EQ(TestClass2::staticGetArchetype().getNestedEnumByName("PrivateNestedEnum")->getAccessSpecifier(), rfk::EAccessSpecifier::Private); EXPECT_EQ(TestClass2::staticGetArchetype().getNestedEnumByName("PrivateNestedEnum", rfk::EAccessSpecifier::Private)->getAccessSpecifier(), rfk::EAccessSpecifier::Private); } //========================================================= //============== Archetype::getMemorySize ================= //========================================================= TEST(Rfk_Archetype_getMemorySize, FundamentalType) { EXPECT_EQ(rfk::getArchetype<void>()->getMemorySize(), 0u); EXPECT_EQ(rfk::getArchetype<std::nullptr_t>()->getMemorySize(), sizeof(std::nullptr_t)); EXPECT_EQ(rfk::getArchetype<bool>()->getMemorySize(), sizeof(bool)); EXPECT_EQ(rfk::getArchetype<char>()->getMemorySize(), sizeof(char)); EXPECT_EQ(rfk::getArchetype<signed char>()->getMemorySize(), sizeof(signed char)); EXPECT_EQ(rfk::getArchetype<unsigned char>()->getMemorySize(), sizeof(unsigned char)); EXPECT_EQ(rfk::getArchetype<wchar_t>()->getMemorySize(), sizeof(wchar_t)); EXPECT_EQ(rfk::getArchetype<char16_t>()->getMemorySize(), sizeof(char16_t)); EXPECT_EQ(rfk::getArchetype<char32_t>()->getMemorySize(), sizeof(char32_t)); EXPECT_EQ(rfk::getArchetype<short>()->getMemorySize(), sizeof(short)); EXPECT_EQ(rfk::getArchetype<unsigned short>()->getMemorySize(), sizeof(unsigned short)); EXPECT_EQ(rfk::getArchetype<int>()->getMemorySize(), sizeof(int)); EXPECT_EQ(rfk::getArchetype<unsigned int>()->getMemorySize(), sizeof(unsigned int)); EXPECT_EQ(rfk::getArchetype<long>()->getMemorySize(), sizeof(long)); EXPECT_EQ(rfk::getArchetype<unsigned long>()->getMemorySize(), sizeof(unsigned long)); EXPECT_EQ(rfk::getArchetype<long long>()->getMemorySize(), sizeof(long long)); EXPECT_EQ(rfk::getArchetype<unsigned long long>()->getMemorySize(), sizeof(unsigned long long)); EXPECT_EQ(rfk::getArchetype<float>()->getMemorySize(), sizeof(float)); EXPECT_EQ(rfk::getArchetype<double>()->getMemorySize(), sizeof(double)); EXPECT_EQ(rfk::getArchetype<long double>()->getMemorySize(), sizeof(long double)); } TEST(Rfk_Archetype_getMemorySize, StructClass) { EXPECT_EQ(rfk::getArchetype<TestClass>()->getMemorySize(), sizeof(TestClass)); } TEST(Rfk_Archetype_getMemorySize, ClassTemplate) { EXPECT_EQ(rfk::getArchetype<SingleTypeTemplateClassTemplate>()->getMemorySize(), 0u); //Dependant type } TEST(Rfk_Archetype_getMemorySize, ClassTemplateInstantiation) { EXPECT_EQ(rfk::getArchetype<SingleTypeTemplateClassTemplate<int>>()->getMemorySize(), sizeof(SingleTypeTemplateClassTemplate<int>)); } TEST(Rfk_Archetype_getMemorySize, Enum) { EXPECT_EQ(rfk::getEnum<TestEnum>()->getMemorySize(), sizeof(TestEnum)); EXPECT_EQ(rfk::getEnum<TestEnumClass>()->getMemorySize(), sizeof(TestEnumClass)); } //========================================================= //============ Archetype::setAccessSpecifier ============== //========================================================= TEST(Rfk_Archetype_setAccessSpecifier, setAccessSpecifier) { rfk::Enum e("Test", 0u, rfk::getArchetype<int>(), nullptr); e.setAccessSpecifier(rfk::EAccessSpecifier::Public); EXPECT_EQ(e.getAccessSpecifier(), rfk::EAccessSpecifier::Public); e.setAccessSpecifier(rfk::EAccessSpecifier::Protected); EXPECT_EQ(e.getAccessSpecifier(), rfk::EAccessSpecifier::Protected); e.setAccessSpecifier(rfk::EAccessSpecifier::Private); EXPECT_EQ(e.getAccessSpecifier(), rfk::EAccessSpecifier::Private); }
47.8
178
0.749764
Angelysse
56a1d4fbcb4734a67c644b256a5c4b66201a2bd2
1,731
hpp
C++
include/kobuki_core/logging.hpp
kobuki-base/kobuki_core
5fb88169d010c3a23f24ff0ba7e9cb45b46b24e8
[ "BSD-3-Clause" ]
10
2020-06-01T05:05:27.000Z
2022-01-18T13:19:58.000Z
include/kobuki_core/logging.hpp
clalancette/kobuki_core
e5bef97d3c1db24441508673e08c67be599faa84
[ "BSD-3-Clause" ]
28
2020-01-10T14:42:54.000Z
2021-07-28T08:01:44.000Z
include/kobuki_core/logging.hpp
clalancette/kobuki_core
e5bef97d3c1db24441508673e08c67be599faa84
[ "BSD-3-Clause" ]
8
2020-02-04T09:59:18.000Z
2021-08-29T01:59:38.000Z
/** * @file include/kobuki_core/logging.hpp * * @brief Log levels and simple logging to screen. * * License: BSD * https://raw.githubusercontent.com/kobuki-base/kobuki_core/license/LICENSE **/ /***************************************************************************** ** Ifdefs *****************************************************************************/ #ifndef KOBUKI_LOGGING_HPP_ #define KOBUKI_LOGGING_HPP_ /***************************************************************************** ** Includes *****************************************************************************/ #include <iostream> #include <string> #include <ecl/console.hpp> /***************************************************************************** ** Namespaces *****************************************************************************/ namespace kobuki { /***************************************************************************** ** Log Levels *****************************************************************************/ /** * @brief Internal logging levels. * * Kobuki will log to stdout the specified log level and higher. For example * if WARNING is specified, it will log both warning and error messages. To * disable logging, use NONE. * * To connect to your own logging infrastructure, use NONE and provide slots * (callbacks) to the kobuki debug, info, warning and error signals. */ enum LogLevel { DEBUG = 0, INFO = 1, WARNING = 2, ERROR = 3, NONE = 4 }; void logDebug(const std::string& message); void logInfo(const std::string& message); void logWarning(const std::string& message); void logError(const std::string& message); } // namespace kobuki #endif /* KOBUKI_LOGGING_HPP_ */
28.85
79
0.450607
kobuki-base
56a221ea1597980da2511f1b2ac086226c64c8a0
9,156
cpp
C++
Packer/Packer/SourceCode/Exporter/ExSgMesh.cpp
GavWood/tutorials
d5140129b6acd6d61f6feedcd352c12e4ebabd40
[ "BSD-2-Clause" ]
8
2017-10-26T14:26:55.000Z
2022-01-07T07:35:39.000Z
Packer/Packer/SourceCode/Exporter/ExSgMesh.cpp
GavWood/tutorials
d5140129b6acd6d61f6feedcd352c12e4ebabd40
[ "BSD-2-Clause" ]
1
2017-09-28T08:21:04.000Z
2017-10-04T09:17:57.000Z
Packer/Packer/SourceCode/Exporter/ExSgMesh.cpp
GavWood/Game-Framework
d5140129b6acd6d61f6feedcd352c12e4ebabd40
[ "BSD-2-Clause" ]
1
2021-07-21T17:37:33.000Z
2021-07-21T17:37:33.000Z
//////////////////////////////////////////////////////////////////////////////// // ExSgMesh.cpp // Includes #include "StdAfx.h" #include "ExMatrix.h" #include "ExSgMesh.h" #include "ExStrip.h" #include "ExScene.h" #include "ExIndexBuffer.h" #include "ExVertexBuffer.h" #include "ExVertex.h" #include "SgRigidBody.h" #include "ApConfig.h" #include "PaTopState.h" #include "FCollada.h" #include "PaRendering.h" //////////////////////////////////////////////////////////////////////////////// // Constructor ExSgMesh::ExSgMesh( ExSgNode *pNode, ExScene *pScene ) { m_pNode = pNode; m_pScene = pScene; } //////////////////////////////////////////////////////////////////////////////// // Destructor ExSgMesh::~ExSgMesh() { BtU32 nSize = (BtU32) m_materialBlocks.size(); for( BtU32 iMaterialBlock=0; iMaterialBlock<nSize; ++iMaterialBlock ) { delete m_materialBlocks[iMaterialBlock]; } } void ExSgMesh::GroupDrawing() { MakeRenderGroups(); OptimiseGeometry(); BoundVertex(); } //////////////////////////////////////////////////////////////////////////////// // MakeRenderGroups void ExSgMesh::MakeRenderGroups() { // Cache the number of material blocks BtU32 nMaterialBlocks = (BtU32) m_materialBlocks.size(); // Flatten the material blocks for( BtU32 iMaterialBlock=0; iMaterialBlock<nMaterialBlocks; iMaterialBlock++ ) { // Cache each material block ExMaterialBlock* pMaterialBlock = m_materialBlocks[iMaterialBlock]; // Cache the number of indices BtU32 nIndices = (BtU32) pMaterialBlock->m_indices.size(); ExRenderBlock renderBlock; for( BtU32 iIndex = 0; iIndex < nIndices; iIndex++ ) { // Add the index renderBlock.m_indices.push_back( pMaterialBlock->m_indices[iIndex] ); // Add the vertex renderBlock.m_vertex.push_back( pMaterialBlock->m_pVertex[iIndex] ); } // Add the render block pMaterialBlock->m_renderBlocks.push_back( renderBlock ); } } //////////////////////////////////////////////////////////////////////////////// // OptimiseGeometry void ExSgMesh::OptimiseGeometry() { // Cache the number of material blocks BtU32 nMaterialBlocks = (BtU32) m_materialBlocks.size(); // Flatten the material blocks for( BtU32 iMaterialBlock=0; iMaterialBlock<nMaterialBlocks; iMaterialBlock++ ) { // Cache each material block ExMaterialBlock* pMaterialBlock = m_materialBlocks[iMaterialBlock]; // Cache the number of Render blocks BtU32 nRenderBlocks = (BtU32) pMaterialBlock->m_renderBlocks.size(); // Flatten the Render blocks for( BtU32 iRenderBlock=0; iRenderBlock<nRenderBlocks; iRenderBlock++ ) { // Cache each render block ExRenderBlock& renderBlock = pMaterialBlock->m_renderBlocks[iRenderBlock]; // Create the geometry stripper ExGeometryOptimise optimise( pMaterialBlock, &renderBlock ); BtBool optimiseEnabled = m_pNode->isStripped(); (void)optimiseEnabled; ErrorLog::Printf( "Merging similar vertex in node %s\r\n", m_pNode->pName() ); if( BtFalse )//m_pNode->isMergeLikeVertex() == BtTrue ) { optimise.MergeVertex(); } else { optimise.CopyVertexNoMerge(); } if( m_pNode->isStripped() == BtTrue ) { ErrorLog::Printf( "Stripping node %s\r\n", m_pNode->pName() ); optimise.Strip(); } } } } //////////////////////////////////////////////////////////////////////////////// // BoundVertex void ExSgMesh::BoundVertex() { // Cache the number of material blocks BtU32 nMaterialBlocks = (BtU32) m_materialBlocks.size(); // Flatten the material blocks for( BtU32 iMaterialBlock=0; iMaterialBlock<nMaterialBlocks; iMaterialBlock++ ) { // Cache each material block ExMaterialBlock* pMaterialBlock = m_materialBlocks[iMaterialBlock]; // Cache the number of Render blocks BtU32 nRenderBlocks = (BtU32) pMaterialBlock->m_renderBlocks.size(); // Flatten the Render blocks for( BtU32 iRenderBlock=0; iRenderBlock<nRenderBlocks; iRenderBlock++ ) { // Cache each render block ExRenderBlock& renderBlock = pMaterialBlock->m_renderBlocks[iRenderBlock]; // Cache the number of vertex BtU32 nVertices = (BtU32) renderBlock.m_pOptimisedVertex.size(); // Add the vertex for( BtU32 iVertex=0; iVertex<nVertices; iVertex++ ) { // Cache each vertex ExVertex* pVertex = (ExVertex*) renderBlock.m_pOptimisedVertex[iVertex]; // Cache each position MtVector3 v3Position = pVertex->Position(); // Expand the bounding box if( ( iMaterialBlock == 0 ) && ( iRenderBlock == 0 ) && ( iVertex == 0 ) ) { m_AABB = MtAABB( v3Position, v3Position ); m_sphere = MtSphere( v3Position, 0 ); } else { m_AABB.Min( v3Position.Min( m_AABB.Min() ) ); m_AABB.Max( v3Position.Max( m_AABB.Max() ) ); m_sphere.ExpandBy( v3Position ); } } } } int a=0; a++; } //////////////////////////////////////////////////////////////////////////////// // MoveToVertexBuffer void ExSgMesh::MoveToVertexBuffers() { // Cache the number of material blocks BtU32 nMaterialBlocks = (BtU32) m_materialBlocks.size(); // Flatten the material blocks for( BtU32 iMaterialBlock=0; iMaterialBlock<nMaterialBlocks; iMaterialBlock++ ) { // Cache each material block ExMaterialBlock* pMaterialBlock = m_materialBlocks[iMaterialBlock]; // Cache the number of Render blocks BtU32 nRenderBlocks = (BtU32) pMaterialBlock->m_renderBlocks.size(); // Flatten the Render blocks for( BtU32 iRenderBlock=0; iRenderBlock<nRenderBlocks; iRenderBlock++ ) { // Cache each render block ExRenderBlock& renderBlock = pMaterialBlock->m_renderBlocks[iRenderBlock]; // Cache the number of vertex BtU32 nVertices = (BtU32) renderBlock.m_pOptimisedVertex.size(); // Export only material blocks with primitives if( nVertices > 0 ) { BtU32 nBaseVertex = 0; // Cache each vertex ExVertex* pVertex = renderBlock.m_pOptimisedVertex[0]; // Get the vertex buffer ExVertexBuffer* pVertexBuffer = m_pScene->pVertexBuffer( pVertex->GetVertexType() ); // Get the base vertex nBaseVertex = pVertexBuffer->Size(); // Add the vertex for( BtU32 iVertex=0; iVertex<nVertices; iVertex++ ) { // Cache each vertex ExVertex* pVertex = renderBlock.m_pOptimisedVertex[iVertex]; // Add each vertex pVertexBuffer->AddVertex( pVertex ); } BtU32 nBaseIndex = (BtU32) m_pScene->pIndexBuffer()->nSize(); BtU32 nIndices = 0; BtU32 offset = 0; if( PaTopState::Instance().IsBaseVertex() ) { offset += nBaseVertex; } BtChar *pStr = m_pNode->pName(); if( strstr( pStr, "Wing" ) ) { int a=0; a++; } ExIndexBuffer *pIndexBuffer = m_pScene->pIndexBuffer(); // Add the indices if( m_pNode->isStripped() == BtTrue ) { nIndices = (BtU32) renderBlock.m_strippedIndex.size(); for( BtU32 iIndex=0; iIndex<nIndices; iIndex++ ) { pIndexBuffer->AddIndex( renderBlock.m_strippedIndex[iIndex] + offset ); } } else { nIndices = (BtU32) renderBlock.m_optimisedIndex.size(); for( BtU32 iIndex=0; iIndex<nIndices; iIndex++ ) { pIndexBuffer->AddIndex( renderBlock.m_optimisedIndex[iIndex] + offset ); } } // Add each primitive RsIndexedPrimitive primitive; BtU32 numprimitives = nIndices; if( renderBlock.m_primitiveType == ExPT_STRIP ) { numprimitives -= 2; } else if( renderBlock.m_primitiveType == ExPT_FAN ) { numprimitives -= 2; } else if( renderBlock.m_primitiveType == ExPT_LIST ) { numprimitives /= 3; } primitive.m_primitiveType = PaExportSizes::GetTriangleType(renderBlock.m_primitiveType); primitive.m_baseVertexIndex = nBaseVertex; primitive.m_startIndex = nBaseIndex; primitive.m_minIndex = 0; primitive.m_numVertices = nVertices; primitive.m_primitives = numprimitives; primitive.m_numIndices = nIndices; primitive.m_indexType = 0; // Not set for now renderBlock.m_primitives.push_back( primitive ); } int a=0; a++; } } } //////////////////////////////////////////////////////////////////////////////// // ChangeCoordinateSystem void ExSgMesh::ChangeCoordinateSystem() { // Cache the number of material blocks BtU32 nMaterialBlocks = (BtU32) m_materialBlocks.size(); // Flatten the material blocks for( BtU32 nMaterialBlock=0; nMaterialBlock<nMaterialBlocks; nMaterialBlock++ ) { // Cache each material block ExMaterialBlock* pMaterialBlock = m_materialBlocks[nMaterialBlock]; // Cache the number of vertex BtU32 nVertex = (BtU32) pMaterialBlock->m_pVertex.size(); // Flip the z position for( BtU32 i=0; i<nVertex; i++ ) { ExVertex* pVertex = pMaterialBlock->m_pVertex[i]; pVertex->ChangeCoordinateSystem(); } } } /////////////////////////////////////////////////////////////////////////////// // CopyAttributes void ExSgMesh::CopyAttributes() { m_pNode->m_meshFileData.m_AABB = m_AABB; m_pNode->m_meshFileData.m_sphere = m_sphere; m_pNode->m_meshFileData.m_nMaterials = (BtU32) m_pNode->m_materialBlocks.size(); }
26.386167
104
0.63543
GavWood
56a2d79362bfcd984696b77159fef85d19d581d3
3,213
hpp
C++
include/tools/types/common/enable_for/enable_for-2013.hpp
Kartonagnick/tools-types
4b3a697e579050eade081b82f9b96309fea8f5e7
[ "MIT" ]
null
null
null
include/tools/types/common/enable_for/enable_for-2013.hpp
Kartonagnick/tools-types
4b3a697e579050eade081b82f9b96309fea8f5e7
[ "MIT" ]
49
2021-02-20T12:08:15.000Z
2021-05-07T19:59:08.000Z
include/tools/types/common/enable_for/enable_for-2013.hpp
Kartonagnick/tools-types
4b3a697e579050eade081b82f9b96309fea8f5e7
[ "MIT" ]
null
null
null
// [2020y-09m-04d][00:00:00] Idrisov Denis R. // [2021y-02m-20d][18:40:18] Idrisov Denis R. // [2021y-04m-10d][01:40:31] Idrisov Denis R. 100 //============================================================================== //============================================================================== #pragma once #ifndef dTOOLS_ENABLE_FOR_2013_USED_ #define dTOOLS_ENABLE_FOR_2013_USED_ 100,2013 #include <tools/types/common/find_type.hpp> //============================================================================== //=== degradate-2013 =========================================================== #ifndef dTOOLS_DEGRADATE_USED_ namespace tools { template<class t> class degradate { using x = ::std::remove_reference_t<t>; public: using type = ::std::remove_cv_t<x>; }; template<class t> using degradate_t = ::std::remove_cv_t< ::std::remove_reference_t<t> >; #define ddegradate(...) degradate_t<__VA_ARGS__> } // namespace tools #endif // !dTOOLS_DEGRADATE_USED_ //============================================================================== //=== enable_if_find/disable_if_find =============== (degradate)(find_type) ==== namespace tools { // if type 't' is in the list 'args' --> compile template<class ret, class t, class ...args> using enable_if_find_t = ::std::enable_if_t< ::tools::find_type< ::tools::degradate_t<t>, args... >::value, ret >; // if type 't' is not in the list 'args' --> compile template<class ret, class t, class ...args> using disable_if_find_t = ::std::enable_if_t< !::tools::find_type< ::tools::degradate_t<t>, args... >::value, ret >; #define dif_enabled(r, ...) \ ::tools::enable_if_find_t<r, __VA_ARGS__> #define dif_disabled(r, ...) \ ::tools::disable_if_find_t<r, __VA_ARGS__> } // namespace tools //============================================================================== //=== enable_for/disable_for ======================= (degradate)(find_type) ==== namespace tools { // if type 't' is in the list 'args' --> compile template<class t, class ...args> using enable_for_t = ::std::enable_if_t< ::tools::find_type< ::tools::degradate_t<t>, args... >::value >; // if type 't' is not in the list 'args' --> compile template<class t, class ...args> using disable_for_t = ::std::enable_if_t< !::tools::find_type< ::tools::degradate_t<t>, args... >::value >; #define dfor_enabled_impl(...) ::tools::enable_for_t <__VA_ARGS__>* #define dfor_disabled_impl(...) ::tools::disable_for_t<__VA_ARGS__>* #define dfor_enabled(...) dfor_enabled_impl(__VA_ARGS__) = nullptr #define dfor_disabled(...) dfor_disabled_impl(__VA_ARGS__) = nullptr } // namespace tools //============================================================================== //============================================================================== #endif // !dTOOLS_ENABLE_FOR_2013_USED_
33.123711
80
0.473078
Kartonagnick
56aae3da6b829bd45813dd50738c6642332e38ff
1,705
cpp
C++
src/utils/data.cpp
jlorenze/asl_fixedwing
9cac7c8d31f5d1c9f7d059d4614d6b60f1a3fbef
[ "MIT" ]
4
2021-06-28T17:30:55.000Z
2022-03-18T09:04:35.000Z
src/utils/data.cpp
jlorenze/asl_fixedwing
9cac7c8d31f5d1c9f7d059d4614d6b60f1a3fbef
[ "MIT" ]
1
2021-08-31T16:22:13.000Z
2021-08-31T16:36:15.000Z
src/utils/data.cpp
jlorenze/asl_fixedwing
9cac7c8d31f5d1c9f7d059d4614d6b60f1a3fbef
[ "MIT" ]
null
null
null
/** @file data.cpp Helper functions for saving and loading data */ #include <utils/data.hpp> #include <fstream> #include <iostream> #include <string> #include <vector> #include <Eigen/Dense> /** Save matrix to .csv file. */ void Data::save_matrix(const std::string& file_name, Eigen::MatrixXd matrix) { const static Eigen::IOFormat CSVFormat(Eigen::FullPrecision, Eigen::DontAlignCols, ", ", "\n"); std::ofstream file(file_name); // open a file to write if (file.is_open()) { file << matrix.format(CSVFormat); file.close(); } } /** Load matrix from .csv file */ Eigen::MatrixXd Data::load_matrix(const std::string& file_name) { std::ifstream file(file_name); // open a file to read if (!file.good()) { std::cerr << "File: " << file_name << " does not exist" << std::endl; exit(1); } // Read through file and extract all data elements std::string row; int i = 0; // row counter std::string entry; std::vector<double> entries; while (std::getline(file, row)) { std::stringstream row_stream(row); while (std::getline(row_stream, entry, ',')) { entries.push_back(std::stod(entry)); } i++; // increment row counter } // Convert vector into matrix of proper shape return Eigen::Map<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>>(entries.data(), i, entries.size() / i); } /** Load vector from .csv file */ Eigen::VectorXd Data::load_vector(const std::string& file_name) { Eigen::MatrixXd M = Data::load_matrix(file_name); return Eigen::Map<Eigen::VectorXd>(M.data(), M.rows()); }
30.446429
133
0.614663
jlorenze
56ab20a2bf8e3c57aec1f51f51c6986961530fad
1,347
cpp
C++
697_find_shortest_subarray/find_shortest_subarray.cpp
Mengsen-W/algorithm
66216b8601e416343a2cc191bd0f2f12eb282262
[ "BSD-3-Clause" ]
null
null
null
697_find_shortest_subarray/find_shortest_subarray.cpp
Mengsen-W/algorithm
66216b8601e416343a2cc191bd0f2f12eb282262
[ "BSD-3-Clause" ]
null
null
null
697_find_shortest_subarray/find_shortest_subarray.cpp
Mengsen-W/algorithm
66216b8601e416343a2cc191bd0f2f12eb282262
[ "BSD-3-Clause" ]
null
null
null
/* * @Author: Mengsen.Wang * @Date: 2021-02-20 09:07:09 * @Last Modified by: Mengsen.Wang * @Last Modified time: 2021-02-20 09:17:11 */ #include <cassert> #include <vector> using namespace std; int find_shortest_subarray(vector<int>& nums) { //统计每个元素出现的频率 vector<int> req(50000, 0); //最大度 int d = 0; //每个元素第一次出现的位置 vector<int> first(50000, -1); //每个元素最后一次出现的位置 vector<int> last(50000, -1); int res = nums.size(); for (int i = 0; i < nums.size(); i++) { req[nums[i]]++; d = max(d, req[nums[i]]); if (first[nums[i]] == -1) first[nums[i]] = i; last[nums[i]] = i; } for (int i = 0; i < nums.size(); i++) { if (req[nums[i]] == d) { res = min(res, last[nums[i]] - first[nums[i]] + 1); } } return res; } int main() { vector<int> nums{}; nums = {1, 2, 2, 3, 1}; assert(find_shortest_subarray(nums) == 2); nums = {1, 2, 2, 3, 1}; assert(find_shortest_subarray(nums) == 2); nums = {1, 2, 2, 3}; assert(find_shortest_subarray(nums) == 2); nums = {2, 2, 3, 1}; assert(find_shortest_subarray(nums) == 2); nums = {1, 2, 2}; assert(find_shortest_subarray(nums) == 2); nums = {2, 2, 3}; assert(find_shortest_subarray(nums) == 2); nums = {2, 2}; assert(find_shortest_subarray(nums) == 2); nums = {1, 2, 2, 3, 1, 4, 2}; assert(find_shortest_subarray(nums) == 6); }
24.490909
57
0.576095
Mengsen-W
56b2bc669d91a122c84bea08820dd50197ea6bf0
921
cpp
C++
PAT/PAT-B/CPP/1018.锤子剪刀布.cpp
hao14293/2021-Postgraduate-408
70e1c40e6bcf0c5afe4a4638a7c168069d9c8319
[ "MIT" ]
950
2020-02-21T02:39:18.000Z
2022-03-31T07:27:36.000Z
PAT/PAT-B/CPP/1018.锤子剪刀布.cpp
RestmeF/2021-Postgraduate-408
70e1c40e6bcf0c5afe4a4638a7c168069d9c8319
[ "MIT" ]
6
2020-04-03T13:08:47.000Z
2022-03-07T08:54:56.000Z
PAT/PAT-B/CPP/1018.锤子剪刀布.cpp
RestmeF/2021-Postgraduate-408
70e1c40e6bcf0c5afe4a4638a7c168069d9c8319
[ "MIT" ]
131
2020-02-22T15:35:59.000Z
2022-03-21T04:23:57.000Z
#include <iostream> using namespace std; int main(){ int n; cin >> n; int jiawin = 0, yiwin = 0; int jia[3] = {0}, yi[3] = {0}; for(int i = 0; i < n; i++ ){ char s, t; cin >> s >> t; if(s == 'B' && t == 'C'){ jiawin++; jia[0]++; }else if(s == 'B' && t == 'J'){ yiwin++; yi[2]++; }else if(s == 'C' && t == 'B'){ yiwin++; yi[0]++; }else if(s == 'C' && t == 'J'){ jiawin++; jia[1]++; }else if(s == 'J' && t == 'B'){ jiawin++; jia[2]++; }else if(s == 'J' && t == 'C'){ yiwin++; yi[1]++; } } cout << jiawin << " " << n - jiawin - yiwin << " " << yiwin << endl << yiwin << " " << n - yiwin - jiawin << " "<< jiawin << endl; int maxjia = jia[0] >= jia[1] ? 0: 1; maxjia = jia[maxjia] >= jia[2] ? maxjia : 2; int maxyi = yi[0] >= yi[1] ? 0: 1; maxyi = yi[maxyi] >= yi[2] ? maxyi : 2; char str[4] = {"BCJ"}; cout << str[maxjia] << " " << str[maxyi]; return 0; }
23.025
131
0.41911
hao14293
56c1b0a833b492e6f545340d6fab31648eb920b3
1,649
cpp
C++
cpp/segment_trees_2017/segtree.cpp
petuhovskiy/Templates-CP
7419d5b5c6a92a98ba4d93525f6db22b7c3afa9e
[ "MIT" ]
8
2016-06-05T19:19:27.000Z
2019-05-14T10:33:37.000Z
cpp/segment_trees_2017/segtree.cpp
petuhovskiy/Templates-CP
7419d5b5c6a92a98ba4d93525f6db22b7c3afa9e
[ "MIT" ]
2
2017-02-21T12:38:27.000Z
2018-01-28T20:05:00.000Z
cpp/segment_trees_2017/segtree.cpp
petuhovskiy/Templates-CP
7419d5b5c6a92a98ba4d93525f6db22b7c3afa9e
[ "MIT" ]
6
2015-12-26T21:12:17.000Z
2022-03-26T21:40:17.000Z
template<typename T, typename U> struct segtree { int n; int h; std::vector<T> t; std::vector<U> u; template<typename U2> void apply(int x, U2 upd) { t[x].apply(upd); if (x < n) u[x].apply(upd); } void push(int x) { for (int i = h; i > 0; i--) { int y = x >> i; if (!u[y].empty()) { apply(y << 1, u[y]); apply(y << 1 | 1, u[y]); u[y].clear(); } } } void recalc(int x) { while ((x >>= 1) > 0) { t[x] = t[x << 1] + t[x << 1 | 1]; t[x].apply(u[x]); } } template<typename U2> void update(int l, int r, U2 upd) { l += n; r += n; int l0 = l, r0 = r - 1; push(l0); push(r0); for (; l < r; l >>= 1, r >>= 1) { if (l & 1) apply(l++, upd); if (r & 1) apply(--r, upd); } recalc(l0); recalc(r0); } T query(int l, int r) { l += n; r += n; push(l); push(r - 1); T al, ar; for (; l < r; l >>= 1, r >>= 1) { if (l & 1) al = al + t[l++]; if (r & 1) ar = t[--r] + ar; } return al + ar; } void rebuildLayers() { for (int i = n - 1; i > 0; i--) { t[i] = t[i << 1] + t[i << 1 | 1]; } } segtree(int n) : n(n), h(32 - __builtin_clz(n)), t(n << 1), u(n) {} segtree(std::vector<T> v) : segtree(v.size()) { std::copy(v.begin(), v.end(), t.begin() + n); rebuildLayers(); } segtree(int n, T def) : segtree(std::vector<T>(n, def)) {} };
23.557143
71
0.363857
petuhovskiy
56c7bc9c5e57bde17ed2ebe4aee5336406aa3e5c
142
cpp
C++
contest/yukicoder/159.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
7
2018-04-14T14:55:51.000Z
2022-01-31T10:49:49.000Z
contest/yukicoder/159.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
5
2018-04-14T14:28:49.000Z
2019-05-11T02:22:10.000Z
contest/yukicoder/159.cpp
not522/Competitive-Programming
be4a7d25caf5acbb70783b12899474a56c34dedb
[ "Unlicense" ]
null
null
null
#include "template.hpp" int main() { setBoolName("YES", "NO"); double p(in), q(in); cout << ((1 - p) * q < p * (1 - q) * q) << endl; }
17.75
50
0.478873
not522
08cbc5884ae6e5a991bbf315d056721f69138e0d
1,507
cpp
C++
breeze/text/test/string_builder_test.cpp
gennaroprota/breeze
f1dfd7154222ae358f5ece936c2897a3ae110003
[ "BSD-3-Clause" ]
1
2021-04-03T22:35:52.000Z
2021-04-03T22:35:52.000Z
breeze/text/test/string_builder_test.cpp
gennaroprota/breeze
f1dfd7154222ae358f5ece936c2897a3ae110003
[ "BSD-3-Clause" ]
null
null
null
breeze/text/test/string_builder_test.cpp
gennaroprota/breeze
f1dfd7154222ae358f5ece936c2897a3ae110003
[ "BSD-3-Clause" ]
1
2021-10-01T04:26:48.000Z
2021-10-01T04:26:48.000Z
// =========================================================================== // Copyright 2021 Gennaro Prota // // Licensed under the 3-Clause BSD License. // (See accompanying file 3_CLAUSE_BSD_LICENSE.txt or // <https://opensource.org/licenses/BSD-3-Clause>.) // ___________________________________________________________________________ #include "breeze/text/string_builder.hpp" #include "breeze/testing/testing.hpp" #include <ios> #include <ostream> #include <iomanip> int test_string_builder() ; namespace { void do_test() { using breeze::string_builder ; // Format with a named string builder. { string_builder builder ; builder << "This is a number: " << 100 ; BREEZE_CHECK( builder.str() == "This is a number: 100" ) ; } // Format with a temporary string builder. { BREEZE_CHECK( ( string_builder() << "This is a number: " << 100 ).str() == "This is a number: 100" ) ; } // Use manipulators. { std::string const s = "bar" ; BREEZE_CHECK( ( string_builder() << std::setw( 8 ) << std::setfill( '*' ) << "foo" << std::hex << 64 << s << std::endl ).str() == "*****foo40bar\n" ) ; } } } int test_string_builder() { return breeze::test_runner::instance().run( "string_builder", { do_test } ) ; }
25.542373
78
0.512276
gennaroprota
08eccc436ec610da1ebbe503ed6e5fcd5fb7399d
434
cpp
C++
src/commands/ServerDeviceListCommand.cpp
jalowiczor/beeon-gateway-with-nemea-sources
195d8209302a42e03bafe33811236d7aeedb188d
[ "BSD-3-Clause" ]
7
2018-06-09T05:55:59.000Z
2021-01-05T05:19:02.000Z
src/commands/ServerDeviceListCommand.cpp
jalowiczor/beeon-gateway-with-nemea-sources
195d8209302a42e03bafe33811236d7aeedb188d
[ "BSD-3-Clause" ]
1
2019-12-25T10:39:06.000Z
2020-01-03T08:35:29.000Z
src/commands/ServerDeviceListCommand.cpp
jalowiczor/beeon-gateway-with-nemea-sources
195d8209302a42e03bafe33811236d7aeedb188d
[ "BSD-3-Clause" ]
11
2018-05-10T08:29:05.000Z
2020-01-22T20:49:32.000Z
#include "commands/ServerDeviceListCommand.h" using namespace BeeeOn; using namespace std; ServerDeviceListCommand::ServerDeviceListCommand( const DevicePrefix &prefix): m_prefix(prefix) { } ServerDeviceListCommand::~ServerDeviceListCommand() { } DevicePrefix ServerDeviceListCommand::devicePrefix() const { return m_prefix; } string ServerDeviceListCommand::toString() const { return name() + " " + m_prefix.toString(); }
17.36
58
0.781106
jalowiczor
08f1142801945f003535a870a05b21a6a8b3fe44
2,089
cpp
C++
src/zwave/ZWaveDriverEvent.cpp
jalowiczor/beeon-gateway-with-nemea-sources
195d8209302a42e03bafe33811236d7aeedb188d
[ "BSD-3-Clause" ]
7
2018-06-09T05:55:59.000Z
2021-01-05T05:19:02.000Z
src/zwave/ZWaveDriverEvent.cpp
jalowiczor/beeon-gateway-with-nemea-sources
195d8209302a42e03bafe33811236d7aeedb188d
[ "BSD-3-Clause" ]
1
2019-12-25T10:39:06.000Z
2020-01-03T08:35:29.000Z
src/zwave/ZWaveDriverEvent.cpp
jalowiczor/beeon-gateway-with-nemea-sources
195d8209302a42e03bafe33811236d7aeedb188d
[ "BSD-3-Clause" ]
11
2018-05-10T08:29:05.000Z
2020-01-22T20:49:32.000Z
#include <Poco/Exception.h> #include "zwave/ZWaveDriverEvent.h" using namespace std; using namespace Poco; using namespace BeeeOn; ZWaveDriverEvent::ZWaveDriverEvent(const map<string, uint32_t> &stats): m_stats(stats) { } uint32_t ZWaveDriverEvent::lookup(const string &key) const { auto it = m_stats.find(key); if (it == m_stats.end()) throw NotFoundException("no such driver statistic " + key); return it->second; } uint32_t ZWaveDriverEvent::SOFCount() const { return lookup("SOFCnt"); } uint32_t ZWaveDriverEvent::ACKWaiting() const { return lookup("ACKWaiting"); } uint32_t ZWaveDriverEvent::readAborts() const { return lookup("readAborts"); } uint32_t ZWaveDriverEvent::badChecksum() const { return lookup("badChecksum"); } uint32_t ZWaveDriverEvent::readCount() const { return lookup("readCnt"); } uint32_t ZWaveDriverEvent::writeCount() const { return lookup("writeCnt"); } uint32_t ZWaveDriverEvent::CANCount() const { return lookup("CANCnt"); } uint32_t ZWaveDriverEvent::NAKCount() const { return lookup("NAKCnt"); } uint32_t ZWaveDriverEvent::ACKCount() const { return lookup("ACKCnt"); } uint32_t ZWaveDriverEvent::OOFCount() const { return lookup("OOFCnt"); } uint32_t ZWaveDriverEvent::dropped() const { return lookup("dropped"); } uint32_t ZWaveDriverEvent::retries() const { return lookup("retries"); } uint32_t ZWaveDriverEvent::callbacks() const { return lookup("callbacks"); } uint32_t ZWaveDriverEvent::badroutes() const { return lookup("badroutes"); } uint32_t ZWaveDriverEvent::noACK() const { return lookup("noACK"); } uint32_t ZWaveDriverEvent::netBusy() const { return lookup("netbusy"); } uint32_t ZWaveDriverEvent::notIdle() const { return lookup("notidle"); } uint32_t ZWaveDriverEvent::nonDelivery() const { return lookup("nondelivery"); } uint32_t ZWaveDriverEvent::routedBusy() const { return lookup("routedbusy"); } uint32_t ZWaveDriverEvent::broadcastReadCount() const { return lookup("broadcastReadCnt"); } uint32_t ZWaveDriverEvent::broadcastWriteCount() const { return lookup("broadcastWriteCnt"); }
16.579365
71
0.746769
jalowiczor
08f27218e1d7766b91876bd6e2836fd0aec7beb2
1,428
cpp
C++
Practice/2018/2018.8.15/HDU5608.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
4
2017-10-31T14:25:18.000Z
2018-06-10T16:10:17.000Z
Practice/2018/2018.8.15/HDU5608.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
null
null
null
Practice/2018/2018.8.15/HDU5608.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
null
null
null
#include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> #include<map> using namespace std; #define ll long long #define mem(Arr,x) memset(Arr,x,sizeof(Arr)) const int maxN=1000000; const int Mod=1e9+7; const int inf=2147483647; bool notprime[maxN]; int pcnt,Prime[maxN],Mu[maxN]; int inv3; int F[maxN]; map<int,int> Rc; int QPow(int x,int cnt); void Init(); int Calc(int n); int main(){ inv3=QPow(3,Mod-2); Init(); int TTT;scanf("%d",&TTT); while (TTT--){ int n;scanf("%d",&n); printf("%d\n",Calc(n)); } return 0; } int QPow(int x,int cnt){ int ret=1; while (cnt){ if (cnt&1) ret=1ll*ret*x%Mod; x=1ll*x*x%Mod;cnt>>=1; } return ret; } void Init(){ Mu[1]=1;notprime[1]=1; for (int i=2;i<maxN;i++){ if (notprime[i]==0) Prime[++pcnt]=i,Mu[i]=-1; for (int j=1;(j<=pcnt)&&(1ll*i*Prime[j]<maxN);j++){ notprime[i*Prime[j]]=1; if (i%Prime[j]==0){ Mu[i*Prime[j]]=0;break; } Mu[i*Prime[j]]=-Mu[i]; } } for (int i=1;i<maxN;i++){ int g=((1ll*i*i%Mod-3ll*i+2)%Mod+Mod)%Mod; for (int j=i;j<maxN;j+=i) F[j]=(F[j]+1ll*g*Mu[j/i]+Mod)%Mod; } for (int i=1;i<maxN;i++) F[i]=(F[i-1]+F[i])%Mod; return; } int Calc(int n){ if (n<maxN) return F[n]; if (Rc.count(n)) return Rc[n]; int ret=0; for (int i=2,j;i<=n;i=j+1){ j=n/(int)(n/i); ret=(ret+1ll*(j-i+1)*Calc(n/i)%Mod)%Mod; } return Rc[n]=(1ll*n*(n-1)%Mod*(n-2)%Mod*inv3%Mod+Mod-ret)%Mod; }
18.075949
63
0.584734
SYCstudio
08f41bb96ec1e898fbcac9a8e314b2486240411c
335
hpp
C++
external/boost/logging/boost/logging/detail/raw_doc/customize_manipulator.hpp
saga-project/saga-cpp
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
[ "BSL-1.0" ]
5
2015-09-15T16:24:14.000Z
2021-08-12T11:05:55.000Z
external/boost/logging/boost/logging/detail/raw_doc/customize_manipulator.hpp
saga-project/saga-cpp
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
[ "BSL-1.0" ]
null
null
null
external/boost/logging/boost/logging/detail/raw_doc/customize_manipulator.hpp
saga-project/saga-cpp
7376c0de0529e7d7b80cf08b94ec484c2e56d38e
[ "BSL-1.0" ]
3
2016-11-17T04:38:38.000Z
2021-04-10T17:23:52.000Z
namespace boost { namespace logging { /** @page customize_manipulator Customizing manipulator arguments (Advanced) FIXME optimize::cache_string_on_str optimize::cache_string_several_str @section customize_optimize Optimizing manipulator arguments optimize::cache_string_on_str optimize::cache_string_several_str FIXME */ }}
14.565217
72
0.826866
saga-project
1c0bc29f6f372f1a32d6571391dd1bcac5fb73da
1,633
hpp
C++
Node/Software/ShellMMap.hpp
UofT-HPRC/FFIVE
4bb17f9669b0c731fe23ea06de26a8921c708ab5
[ "BSD-Source-Code" ]
3
2021-08-17T11:07:32.000Z
2022-01-14T15:52:23.000Z
Node/Software/ShellMMap.hpp
UofT-HPRC/FFIVE
4bb17f9669b0c731fe23ea06de26a8921c708ab5
[ "BSD-Source-Code" ]
null
null
null
Node/Software/ShellMMap.hpp
UofT-HPRC/FFIVE
4bb17f9669b0c731fe23ea06de26a8921c708ab5
[ "BSD-Source-Code" ]
null
null
null
#ifndef SHELL_MMAP_HPP #define SHELL_MMAP_HPP #include <iostream> #include <cstdint> #include <fcntl.h> #include <sys/mman.h> #include <unistd.h> #include "ShellUtils.hpp" namespace FPGA_SHELL { // Open /dev/mem, if not already done, to give access to physical addresses int32_t OpenPhysical(int32_t fd) { if (fd == -1) { if ((fd = open( "/dev/mem", O_RDWR | O_SYNC)) == -1) { std::cout << "ERROR: Could not open \"/dev/mem\".\n"; PrintTrace(); } } return fd; } // Close /dev/mem to give access to physical addresses void ClosePhysical(int32_t fd) { close (fd); } // Establish a virtual address mapping for the physical addresses starting at base, and // extending by span bytes. void* MapPhysical(int32_t fd, uint64_t base, uint32_t span) { void *virtual_base; // Get a mapping from physical addresses to virtual addresses virtual_base = mmap (NULL, span, (PROT_READ | PROT_WRITE), MAP_SHARED, fd, base); if (virtual_base == MAP_FAILED) { std::cout << "ERROR: mmap() failed.\n"; close (fd); PrintTrace(); } return virtual_base; } // Close the previously-opened virtual address mapping int32_t UnmapPhysical(volatile void * virtual_base, uint32_t span) { if (munmap ((void *) virtual_base, span) != 0) { std::cout << "ERROR: munmap() failed.\n"; PrintTrace(); } return 0; } } #endif // SHELL_MMAP_HPP
25.515625
91
0.568279
UofT-HPRC
1c136acbf99428c3715e72a45f52aa31e837c7b2
3,461
cpp
C++
src/core/util/DenseFlagArray.cpp
Kelan0/WorldEngine
e76e7ff47278e837f4d1b9216773dd79eeee1b52
[ "MIT" ]
null
null
null
src/core/util/DenseFlagArray.cpp
Kelan0/WorldEngine
e76e7ff47278e837f4d1b9216773dd79eeee1b52
[ "MIT" ]
null
null
null
src/core/util/DenseFlagArray.cpp
Kelan0/WorldEngine
e76e7ff47278e837f4d1b9216773dd79eeee1b52
[ "MIT" ]
null
null
null
#include "DenseFlagArray.h" #define BIT(bitIndex) (1 << (bitIndex)) #define SET_BIT(val, bitIndex, isSet) if (isSet) val |= BIT(bitIndex); else val &= ~BIT(bitIndex); #define GET_BIT(val, bitIndex) (((val) >> (bitIndex)) & 1) DenseFlagArray::DenseFlagArray(): m_size(0) { } DenseFlagArray::~DenseFlagArray() { } size_t DenseFlagArray::size() const { return m_size; } size_t DenseFlagArray::capacity() const { return m_data.capacity() * pack_bits; } void DenseFlagArray::clear() { m_data.clear(); m_size = 0; } void DenseFlagArray::reserve(const size_t& capacity) { m_data.reserve(capacity * pack_bits); } void DenseFlagArray::resize(const size_t& size, const bool& flag) { PROFILE_SCOPE("DenseFlagArray::resize") size_t packedSize = INT_DIV_CEIL(size, pack_bits); if (packedSize != m_data.size()) m_data.resize(packedSize, flag ? TRUE_BITS : FALSE_BITS); m_size = size; } void DenseFlagArray::ensureSize(const size_t& size, const bool& flag) { if (m_size < size) resize(size, flag); } void DenseFlagArray::expand(const size_t& index, const bool& flag) { if (m_size <= index) { size_t next = index + 1; if (next >= capacity()) reserve(next + next / 2); resize(next, flag); } } bool DenseFlagArray::get(const size_t& index) const { if (index >= size()) { assert(false); } assert(index < size()); if constexpr (pack_bits == 1) { return m_data[index]; } else { return GET_BIT(m_data[index / pack_bits], index % pack_bits); } } void DenseFlagArray::set(const size_t& index, const bool& flag) { assert(index < size()); // ensureCapacity(index); SET_BIT(m_data[index / pack_bits], index % pack_bits, flag); } void DenseFlagArray::set(const size_t& index, const size_t& count, const bool& flag) { PROFILE_SCOPE("DenseFlagArray::set"); assert(index + count <= size()); if (count == 0) { return; } if (count == 1) { SET_BIT(m_data[index / pack_bits], index % pack_bits, flag); return; } size_t firstPackIndex = index / pack_bits; size_t firstBitIndex = index % pack_bits; size_t lastPackIndex = (index + count) / pack_bits; size_t lastBitIndex = (index + count) % pack_bits; PROFILE_REGION("Set first unaligned bits") if (firstBitIndex != 0) { if (firstPackIndex == lastPackIndex) { for (size_t i = firstBitIndex; i < lastBitIndex; ++i) SET_BIT(m_data[firstPackIndex], i, flag); lastBitIndex = 0; } else { for (size_t i = firstBitIndex; i < pack_bits; ++i) SET_BIT(m_data[firstPackIndex], i, flag); ++firstPackIndex; } } PROFILE_REGION("Set all aligned bits") if (firstPackIndex != lastPackIndex) memset(&m_data[firstPackIndex], flag ? TRUE_BITS : FALSE_BITS, (lastPackIndex - firstPackIndex) * sizeof(pack_t)); // for (size_t i = firstPackIndex; i != lastPackIndex; ++i) // m_data[i] = flag ? TRUE_BITS : FALSE_BITS; PROFILE_REGION("Set last unaligned bits") for (size_t i = 0; i < lastBitIndex; ++i) SET_BIT(m_data[lastPackIndex], i, flag); } bool DenseFlagArray::operator[](const size_t& index) const { return get(index); } void DenseFlagArray::push_back(const bool& flag) { size_t index = size(); expand(index); set(index, flag); }
26.419847
122
0.625253
Kelan0
1c1374a5937184a0749c23e341dea52f0f75a73a
8,431
cpp
C++
src/ObjectPool.cpp
9chu/Moe.Core
24fc7701fe8f4b70911fac18438b8f7557aa1773
[ "MIT" ]
29
2018-09-05T09:50:32.000Z
2021-04-19T15:39:38.000Z
src/ObjectPool.cpp
9chu/Moe.Core
24fc7701fe8f4b70911fac18438b8f7557aa1773
[ "MIT" ]
1
2017-09-12T09:07:51.000Z
2017-12-08T15:49:24.000Z
src/ObjectPool.cpp
9chu/MOE.Core
24fc7701fe8f4b70911fac18438b8f7557aa1773
[ "MIT" ]
2
2018-09-19T13:49:23.000Z
2021-01-13T08:52:35.000Z
/** * @file * @author chu * @date 2018/8/2 */ #include <Moe.Core/ObjectPool.hpp> using namespace std; using namespace moe; //////////////////////////////////////////////////////////////////////////////// Node #ifndef NDEBUG void ObjectPool::Node::Attach(Node* node)noexcept { assert(node); Header.Prev = node; Header.Next = node->Header.Next; node->Header.Next = this; if (Header.Next) Header.Next->Header.Prev = this; } void ObjectPool::Node::Detach()noexcept { if (Header.Prev) { assert(Header.Prev->Header.Next == this); Header.Prev->Header.Next = Header.Next; } if (Header.Next) { assert(Header.Next->Header.Prev == this); Header.Next->Header.Prev = Header.Prev; } Header.Prev = Header.Next = nullptr; } #else void ObjectPool::Node::Attach(Node* parent)noexcept { assert(parent); Header.Next = parent->Header.Next; parent->Header.Next = this; } void ObjectPool::Node::Detach(Node* parent)noexcept { assert(parent); assert(parent->Header.Next == this); parent->Header.Next = Header.Next; Header.Next = nullptr; } #endif //////////////////////////////////////////////////////////////////////////////// ObjectPool namespace { size_t SizeToIndex(size_t size)noexcept { if (size <= ObjectPool::kSmallSizeThreshold) return (size + (ObjectPool::kSmallSizeBlockSize - 1)) / ObjectPool::kSmallSizeBlockSize; else if (size <= ObjectPool::kLargeSizeThreshold) { size -= ObjectPool::kSmallSizeThreshold; return (size + (ObjectPool::kLargeSizeBlockSize - 1)) / ObjectPool::kLargeSizeBlockSize + ObjectPool::kSmallSizeBlocks; } assert(false); return 0; } } ObjectPool* ObjectPool::GetPoolFromPointer(void* p)noexcept { if (!p) return nullptr; Node* n = reinterpret_cast<Node*>(static_cast<uint8_t*>(p) - offsetof(Node, Data)); assert(n->Header.Status == NodeStatus::Used); assert(n->Header.Parent); return n->Header.Parent->Pool; } void ObjectPool::Free(void* p)noexcept { if (!p) return; Node* n = reinterpret_cast<Node*>(static_cast<uint8_t*>(p) - offsetof(Node, Data)); assert(n->Header.Status == NodeStatus::Used); assert(n->Header.Parent); n->Header.Parent->Pool->InternalFree(n); } ObjectPool::ObjectPool() { m_stBuckets[0].NodeSize = 0; for (unsigned i = 1; i <= kSmallSizeBlocks; ++i) { m_stBuckets[i].Pool = this; m_stBuckets[i].NodeSize = i * kSmallSizeBlockSize; } for (unsigned i = kSmallSizeBlocks + 1; i < kTotalBlocks; ++i) { m_stBuckets[i].Pool = this; m_stBuckets[i].NodeSize = (i - kSmallSizeBlocks) * kLargeSizeBlockSize + kSmallSizeThreshold; } } ObjectPool::~ObjectPool() { CollectGarbage(); // 收集所有节点 // 检查内存泄漏 bool leak = false; for (unsigned i = 0; i < CountOf(m_stBuckets); ++i) { auto& bucket = m_stBuckets[i]; #ifndef NDEBUG auto p = bucket.UseList.Header.Next; if (p) { while (p && m_pLeakReporter) { m_pLeakReporter(p->Data, bucket.NodeSize, p->Header.Context); p = p->Header.Next; } leak = true; } #else if (bucket.AllocatedCount) { if (m_pLeakReporter) m_pLeakReporter(bucket.NodeSize, bucket.AllocatedCount - bucket.FreeCount); leak = true; } #endif } assert(!leak); MOE_UNUSED(leak); } size_t ObjectPool::GetAllocatedSize()const noexcept { size_t ret = 0; for (unsigned i = 0; i < CountOf(m_stBuckets); ++i) ret += m_stBuckets[i].AllocatedCount * m_stBuckets[i].NodeSize; return ret; } size_t ObjectPool::GetFreeSize()const noexcept { size_t ret = 0; for (unsigned i = 0; i < CountOf(m_stBuckets); ++i) ret += m_stBuckets[i].FreeCount * m_stBuckets[i].NodeSize; return ret; } size_t ObjectPool::CollectGarbage(unsigned factor, size_t maxFree)noexcept { factor = max<unsigned>(factor, 1); size_t ret = 0; auto i = CountOf(m_stBuckets); while (i-- > 0) { auto& bucket = m_stBuckets[i]; if (bucket.FreeCount == 0) { assert(bucket.FreeList.Header.Next == nullptr); continue; } size_t collects = bucket.FreeCount / factor; for (unsigned j = 0; j < collects; ++j) { auto obj = bucket.FreeList.Header.Next; assert(obj); #ifndef NDEBUG obj->Detach(); #else obj->Detach(&bucket.FreeList); #endif ::free(obj); --bucket.FreeCount; --bucket.AllocatedCount; ret += bucket.NodeSize; if (maxFree && ret >= maxFree) return ret; } } return ret; } #ifndef NDEBUG void* ObjectPool::InternalAlloc(size_t sz, const AllocContext& context) #else void* ObjectPool::InternalAlloc(size_t sz) #endif { Node* ret = nullptr; sz = max<size_t>(sz, 1); if (sz > kLargeSizeThreshold) // 直接从系统分配,并挂在大小为0的节点上 { ret = reinterpret_cast<Node*>(::malloc(offsetof(Node, Data) + sz)); if (!ret) throw bad_alloc(); ret->Header.Status = NodeStatus::Used; ret->Header.Parent = &m_stBuckets[0]; #ifndef NDEBUG ret->Header.Context = context; ret->Attach(&m_stBuckets->UseList); #else ret->Header.Next = nullptr; #endif ++m_stBuckets[0].AllocatedCount; return static_cast<void*>(ret->Data); } // 获取对应的Bucket auto index = SizeToIndex(sz); assert(m_stBuckets[index].NodeSize >= sz); Bucket& bucket = m_stBuckets[index]; if (bucket.FreeList.Header.Next) // 如果有空闲节点,就分配 { assert(bucket.FreeCount > 0); ret = bucket.FreeList.Header.Next; #ifndef NDEBUG ret->Detach(); #else ret->Detach(&bucket.FreeList); #endif --bucket.FreeCount; } else { ret = reinterpret_cast<Node*>(::malloc(offsetof(Node, Data) + bucket.NodeSize)); if (!ret) throw bad_alloc(); ret->Header.Parent = &bucket; ++bucket.AllocatedCount; } assert(ret); ret->Header.Status = NodeStatus::Used; #ifndef NDEBUG ret->Header.Context = context; ret->Attach(&bucket.UseList); #else ret->Header.Next = nullptr; #endif return static_cast<void*>(ret->Data); } #ifndef NDEBUG void* ObjectPool::InternalRealloc(void* p, size_t sz, const AllocContext& context) #else void* ObjectPool::InternalRealloc(void* p, size_t sz) #endif { if (!p) // 当传入的p为nullptr时,Realloc的行为和Alloc一致 #ifndef NDEBUG return InternalAlloc(sz, context); #else return InternalAlloc(sz); #endif Node* n = reinterpret_cast<Node*>(static_cast<uint8_t*>(p) - offsetof(Node, Data)); assert(n->Header.Parent->Pool == this); if (sz == 0) // 当大小为0,其行为和Free一致 { InternalFree(n); return nullptr; } auto nodeSize = n->Header.Parent->NodeSize; if (nodeSize == 0) // 超大对象,调用系统的realloc { auto ret = static_cast<Node*>(::realloc(n, offsetof(Node, Data) + sz)); if (!ret) throw bad_alloc(); return static_cast<void*>(ret->Data); } if (nodeSize >= sz) // 如果本身分配的内存就足够使用,则直接返回 return p; // 这里,只能新分配一块内存(当bad_alloc发生时,不影响已分配的内存) #ifndef NDEBUG auto* np = InternalAlloc(sz, context); #else auto* np = InternalAlloc(sz); #endif memcpy(np, p, nodeSize); // 内存拷贝完毕,释放老内存,返回新内存 InternalFree(n); return np; } void ObjectPool::InternalFree(Node* p)noexcept { assert(p); assert(p->Header.Parent->Pool == this); p->Header.Status = NodeStatus::Free; #ifndef NDEBUG p->Detach(); #endif Bucket& bucket = *p->Header.Parent; if (bucket.NodeSize == 0) // 超大对象,直接释放 { ::free(p); --bucket.AllocatedCount; return; } // 回收到FreeList p->Attach(&bucket.FreeList); ++bucket.FreeCount; }
25.394578
102
0.56316
9chu
1c140d3dbcbc615613735a575bfeef40d18ce949
2,535
cpp
C++
Seagull-Core/src/Platform/DirectX/DirectX12CommandList.cpp
ILLmew/Seagull-Engine
fb51b66812eca6b70ed0e35ecba091e9874b5bea
[ "MIT" ]
null
null
null
Seagull-Core/src/Platform/DirectX/DirectX12CommandList.cpp
ILLmew/Seagull-Engine
fb51b66812eca6b70ed0e35ecba091e9874b5bea
[ "MIT" ]
null
null
null
Seagull-Core/src/Platform/DirectX/DirectX12CommandList.cpp
ILLmew/Seagull-Engine
fb51b66812eca6b70ed0e35ecba091e9874b5bea
[ "MIT" ]
null
null
null
#include "sgpch.h" #include "DirectX12CommandList.h" #include "DirectX12RenderQueue.h" #include "DirectXHelper.h" #include "d3dx12.h" namespace SG { DirectX12CommandList::DirectX12CommandList(ID3D12Device1* device, const Ref<DirectX12RenderQueue>& renderQueue) { ThrowIfFailed(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, renderQueue->GetCommandAllocatorNative(), nullptr /* PSO */, IID_PPV_ARGS(m_CommandList.GetAddressOf()))); } void DirectX12CommandList::ResourceBarrier(UINT numBarriers, ID3D12Resource* resource, D3D12_RESOURCE_STATES stateBefore, D3D12_RESOURCE_STATES stateAfter) const noexcept { m_CommandList->ResourceBarrier(numBarriers, &CD3DX12_RESOURCE_BARRIER::Transition(resource, stateBefore, stateAfter)); } void DirectX12CommandList::ResourceBarrier(UINT numBarriers, const D3D12_RESOURCE_BARRIER* pBarriers) const noexcept { m_CommandList->ResourceBarrier(numBarriers, pBarriers); } void DirectX12CommandList::SetViewports(UINT num, const D3D12_VIEWPORT* viewport) const noexcept { m_CommandList->RSSetViewports(num, viewport); } void DirectX12CommandList::SetScissorRect(UINT num, const D3D12_RECT* rect) const noexcept { m_CommandList->RSSetScissorRects(num, rect); } void DirectX12CommandList::SetDescriptorHeaps(UINT numDescritorHeaps, ID3D12DescriptorHeap* const* ppHeaps) { m_CommandList->SetDescriptorHeaps(numDescritorHeaps, ppHeaps); } void DirectX12CommandList::ClearRtv(D3D12_CPU_DESCRIPTOR_HANDLE Rtv, const FLOAT* color, UINT numRects, const D3D12_RECT* pRects) const noexcept { m_CommandList->ClearRenderTargetView(Rtv, color, numRects, pRects); } void DirectX12CommandList::ClearDsv(D3D12_CPU_DESCRIPTOR_HANDLE Dsv, D3D12_CLEAR_FLAGS clearFlags, FLOAT depth, UINT8 stencil, UINT numRects, const D3D12_RECT* pRects) const noexcept { m_CommandList->ClearDepthStencilView(Dsv, clearFlags, depth, stencil, numRects, pRects); } void DirectX12CommandList::SetRenderTarget(UINT numRenderTargetDesc, const D3D12_CPU_DESCRIPTOR_HANDLE* Rtv, bool RTsSingleHandleToDescriptorRange, const D3D12_CPU_DESCRIPTOR_HANDLE* Dsv) const noexcept { m_CommandList->OMSetRenderTargets(numRenderTargetDesc, Rtv, RTsSingleHandleToDescriptorRange, Dsv); } void DirectX12CommandList::Reset(ID3D12CommandAllocator* commandAllocator, ID3D12PipelineState* pipelineState) const { ThrowIfFailed(m_CommandList->Reset(commandAllocator, pipelineState)); } void DirectX12CommandList::Close() const noexcept { m_CommandList->Close(); } }
35.704225
118
0.810651
ILLmew
1c15e45d2310aaee410919816d445b997d345c38
990
cpp
C++
design_pattern/2_Structural_Patterns/2.3_CompositePattern/main.cpp
guangjung/linux_cplusplus
3000303c6680db17715c4802fd05c84a4ce84c1e
[ "MIT" ]
null
null
null
design_pattern/2_Structural_Patterns/2.3_CompositePattern/main.cpp
guangjung/linux_cplusplus
3000303c6680db17715c4802fd05c84a4ce84c1e
[ "MIT" ]
null
null
null
design_pattern/2_Structural_Patterns/2.3_CompositePattern/main.cpp
guangjung/linux_cplusplus
3000303c6680db17715c4802fd05c84a4ce84c1e
[ "MIT" ]
null
null
null
//https://blog.csdn.net/liang19890820/article/details/71240662 //main.cpp #include "composite.h" #include "leaf.h" int main() { // 创建一个树形结构 // 创建根节点 Composite *pRoot = new Composite("江湖公司(任我行)"); // 创建分支 Composite *pDepart1 = new Composite("日月神教(东方不败)"); pDepart1->Add(new Leaf("光明左使(向问天)")); pDepart1->Add(new Leaf("光明右使(曲洋)")); pRoot->Add(pDepart1); Composite *pDepart2 = new Composite("五岳剑派(左冷蝉)"); pDepart2->Add(new Leaf("嵩山(左冷蝉)")); pDepart2->Add(new Leaf("衡山(莫大)")); pDepart2->Add(new Leaf("华山(岳不群)")); pDepart2->Add(new Leaf("泰山(天门道长)")); pDepart2->Add(new Leaf("恒山(定闲师太)")); pRoot->Add(pDepart2); // 添加和删除叶子 pRoot->Add(new Leaf("少林(方证大师)")); pRoot->Add(new Leaf("武当(冲虚道长)")); Component *pLeaf = new Leaf("青城(余沧海)"); pRoot->Add(pLeaf); // 小丑,直接裁掉 pRoot->Remove(pLeaf); // 递归地显示组织架构 pRoot->Operation(1); // 删除分配的内存 SAFE_DELETE(pRoot); //getchar(); return 0; }
21.521739
63
0.590909
guangjung
1c1dbe3a713c269519a286b0765fcf6c0b2034bc
329
cpp
C++
test/Test.cpp
mzh19940817/MyAllocator
5ff72b13775caf76cd30cc232dcd9542427f4ea3
[ "MIT" ]
null
null
null
test/Test.cpp
mzh19940817/MyAllocator
5ff72b13775caf76cd30cc232dcd9542427f4ea3
[ "MIT" ]
null
null
null
test/Test.cpp
mzh19940817/MyAllocator
5ff72b13775caf76cd30cc232dcd9542427f4ea3
[ "MIT" ]
null
null
null
#include "MyAllocator.h" #include <vector> #include "gtest/gtest.h" struct MyAllocatorTest : testing::Test { }; TEST_F(MyAllocatorTest, test_for_my_allocator) { int arr[3] {1, 2, 3}; std::vector<int, MA::allocator<int>> vec{arr, arr + 3}; ASSERT_EQ(1, vec[0]); ASSERT_EQ(2, vec[1]); ASSERT_EQ(3, vec[2]); }
19.352941
59
0.644377
mzh19940817
1c1ee7480aa05d516af8d3e8eebbfd42381e8be6
2,691
cpp
C++
src/trap.cpp
prinsij/RogueReborn
20e6ba4d2e61a47283747ba207a758e604fa89d9
[ "BSD-3-Clause" ]
null
null
null
src/trap.cpp
prinsij/RogueReborn
20e6ba4d2e61a47283747ba207a758e604fa89d9
[ "BSD-3-Clause" ]
null
null
null
src/trap.cpp
prinsij/RogueReborn
20e6ba4d2e61a47283747ba207a758e604fa89d9
[ "BSD-3-Clause" ]
null
null
null
/** * @file trap.cpp * @author Team Rogue++ * @date December 08, 2016 * * @brief Member definitions for the Trap class */ #include "include/armor.h" #include "include/coord.h" #include "include/feature.h" #include "include/level.h" #include "include/playerchar.h" #include "include/random.h" #include "include/trap.h" Trap::Trap(Coord location, unsigned char type, bool visible) : Feature('^', location, visible) , type(type) {} Level* Trap::activate(Mob* mob, Level* level) { this->visible = true; PlayerChar* player = dynamic_cast<PlayerChar*>(mob); if (player) { if (Generator::randPercent() <= player->getLevel() + player->getDexterity()) { player->appendLog("The trap failed"); return level; } } // Door Trap if (this->type == 0) { if (!player || player->hasCondition(PlayerChar::LEVITATING)) return level; int currDepth = level->getDepth(); player->appendLog("You fell down a trap, you are now in level " + std::to_string(currDepth+1)); Level* l = new Level(currDepth+1, player); l->registerMob(player); l->generate(); return l; // Rust Trap } else if (this->type == 1) { mob->hit(Generator::intFromRange(1, 6)); if (player) { player->appendLog("A gush of water hits you on the head"); Armor* armor = player->getArmor(); if (armor == NULL || armor->getRating() == 1) return level; if (!player->hasCondition(PlayerChar::MAINTAIN_ARMOR) && !armor->hasEffect(Item::PROTECTED)) { armor->setEnchantment(armor->getEnchantment() - 1); } } // Sleep Trap } else if (this->type == 2) { if (!player) return level; player->appendLog("A strange white mist envelops you and you fall asleep"); player->applyCondition(PlayerChar::SLEEPING, Generator::intFromRange(2, 5)); // Bear Trap } else if (this->type == 3) { if (!player || player->hasCondition(PlayerChar::LEVITATING)) return level; player->appendLog("You are caught in a bear trap"); player->applyCondition(PlayerChar::IMMOBILIZED, Generator::intFromRange(4, 7)); // Teleport Trap } else if (this->type == 4) { if (player) { player->appendLog("You are suddenly taken aback"); } player->setLocation(level->getRandomEmptyPosition()); // Dart Trap } else if (this->type == 5) { mob->hit(Generator::intFromRange(1, 6)); if (player) { player->appendLog("A small dart just hit you in the shoulder"); if (!player->hasCondition(PlayerChar::SUSTAIN_STRENGTH) && Generator::randPercent() <= 40 && player->getStrength() >= 3) { player->changeCurrentStrength(-1); } } } return level; } Trap* Trap::randomTrap(Coord location) { return new Trap(location, Generator::intFromRange(1, Trap::MAX_TYPE), false); }
26.126214
97
0.665552
prinsij
1c2076f3c2443d007c280d234ac4862564d868b5
2,305
cpp
C++
VulkanTutorials/Plugins/VulkanRendering/VulkanDynamicRenderBuilder.cpp
RichDavisonNCL/VulkanTutorialsRelease
a26b053b170fafa764dee6a575695ff9c3495640
[ "MIT" ]
null
null
null
VulkanTutorials/Plugins/VulkanRendering/VulkanDynamicRenderBuilder.cpp
RichDavisonNCL/VulkanTutorialsRelease
a26b053b170fafa764dee6a575695ff9c3495640
[ "MIT" ]
null
null
null
VulkanTutorials/Plugins/VulkanRendering/VulkanDynamicRenderBuilder.cpp
RichDavisonNCL/VulkanTutorialsRelease
a26b053b170fafa764dee6a575695ff9c3495640
[ "MIT" ]
null
null
null
/****************************************************************************** This file is part of the Newcastle Vulkan Tutorial Series Author:Rich Davison Contact:richgdavison@gmail.com License: MIT (see LICENSE file at the top of the source tree) *////////////////////////////////////////////////////////////////////////////// #include "Precompiled.h" #include "VulkanDynamicRenderBuilder.h" #include "Vulkan.h" using namespace NCL; using namespace Rendering; VulkanDynamicRenderBuilder::VulkanDynamicRenderBuilder() { usingStencil = false; layerCount = 1; } VulkanDynamicRenderBuilder::~VulkanDynamicRenderBuilder() { } VulkanDynamicRenderBuilder& VulkanDynamicRenderBuilder::WithColourAttachment( vk::ImageView texture, vk::ImageLayout layout, bool clear, vk::ClearValue clearValue ) { vk::RenderingAttachmentInfoKHR colourAttachment; colourAttachment.setImageView(texture) .setImageLayout(layout) .setLoadOp(clear ? vk::AttachmentLoadOp::eClear : vk::AttachmentLoadOp::eDontCare) .setStoreOp(vk::AttachmentStoreOp::eStore) .setClearValue(clearValue); colourAttachments.push_back(colourAttachment); return *this; } VulkanDynamicRenderBuilder& VulkanDynamicRenderBuilder::WithDepthAttachment( vk::ImageView texture, vk::ImageLayout layout, bool clear, vk::ClearValue clearValue, bool withStencil ) { depthAttachment.setImageView(texture) .setImageLayout(layout) .setLoadOp(clear ? vk::AttachmentLoadOp::eClear : vk::AttachmentLoadOp::eDontCare) .setStoreOp(vk::AttachmentStoreOp::eStore) .setClearValue(clearValue); usingStencil = withStencil; return *this; } VulkanDynamicRenderBuilder& VulkanDynamicRenderBuilder::WithRenderArea(vk::Rect2D area) { renderArea = area; return *this; } VulkanDynamicRenderBuilder& VulkanDynamicRenderBuilder::WithLayerCount(int count) { layerCount = count; return *this; } VulkanDynamicRenderBuilder& VulkanDynamicRenderBuilder::Begin(vk::CommandBuffer buffer) { vk::RenderingInfoKHR renderInfo; renderInfo.setLayerCount(layerCount) .setRenderArea(renderArea) .setColorAttachments(colourAttachments) .setPDepthAttachment(&depthAttachment); if (usingStencil) { renderInfo.setPStencilAttachment(&depthAttachment); } buffer.beginRenderingKHR(renderInfo, *NCL::Rendering::Vulkan::dispatcher); return *this; }
29.177215
103
0.746204
RichDavisonNCL
1c215b01709cf6e871ea75c953a511b6e09fcfd8
378
cpp
C++
core/Source/CodaStringTransform.cpp
paxbun/dear-my-prof
a1e0032f17d9a62a58673b5dbe2de1446006e528
[ "MIT" ]
1
2020-01-19T14:14:13.000Z
2020-01-19T14:14:13.000Z
core/Source/CodaStringTransform.cpp
paxbun/dear-my-prof
a1e0032f17d9a62a58673b5dbe2de1446006e528
[ "MIT" ]
null
null
null
core/Source/CodaStringTransform.cpp
paxbun/dear-my-prof
a1e0032f17d9a62a58673b5dbe2de1446006e528
[ "MIT" ]
1
2020-11-18T05:24:38.000Z
2020-11-18T05:24:38.000Z
// Copyright (c) 2019 Dear My Professor Authors // Author: paxbun #include <core/CodaStringTransform.hpp> #include <boost/locale.hpp> bool CodaStringTransform::_EndsWithCoda(std::string const& input) { auto conv = boost::locale::conv::utf_to_utf<wchar_t>(input); auto back = conv.back(); return back >= 0xAC00 && back <= 0xD7A3 && ((back - 0xAC00) % 28 != 0); }
25.2
75
0.679894
paxbun
1c26d8f2c8f8524fe4bfce4920a1b730f97794d8
432
cpp
C++
tests/server/TcpConnection/tests.cpp
batburger/Native-Backend
aaed26851e09f9e110061025fb2140aed1b4f9b5
[ "Apache-2.0" ]
null
null
null
tests/server/TcpConnection/tests.cpp
batburger/Native-Backend
aaed26851e09f9e110061025fb2140aed1b4f9b5
[ "Apache-2.0" ]
null
null
null
tests/server/TcpConnection/tests.cpp
batburger/Native-Backend
aaed26851e09f9e110061025fb2140aed1b4f9b5
[ "Apache-2.0" ]
null
null
null
#define BOOST_TEST_MODULE server_TcpConnection_tests #include <boost/test/unit_test.hpp> #include <native-backend/server/Server.h> BOOST_AUTO_TEST_SUITE(server_TcpConnection_tests) /*There's no use full way of testing this class outside of the * Server class, because one would require to mimic all behavior * of the Server class at which point you may as well just use * Server.*/ BOOST_AUTO_TEST_SUITE_END()
33.230769
68
0.773148
batburger
1c29af64cae69959b521a29b13c9a4d1321134eb
5,217
hpp
C++
matrix_inverse.hpp
janezz55/vxl
415bdcb7d5304c6229ac2c910fbdc2988103fdba
[ "Unlicense" ]
28
2016-11-15T09:16:43.000Z
2021-04-12T15:38:46.000Z
matrix_inverse.hpp
janezz55/vxl
415bdcb7d5304c6229ac2c910fbdc2988103fdba
[ "Unlicense" ]
null
null
null
matrix_inverse.hpp
janezz55/vxl
415bdcb7d5304c6229ac2c910fbdc2988103fdba
[ "Unlicense" ]
1
2020-09-04T22:27:20.000Z
2020-09-04T22:27:20.000Z
#ifndef VXL_MATRIX_INVERSE_HPP # define VXL_MATRIX_INVERSE_HPP # pragma once #include "matrix_determinant.hpp" namespace vxl { ////////////////////////////////////////////////////////////////////////////// template <class T> //__attribute__ ((noinline)) inline matrix<T, 2, 2> inv(matrix<T, 2, 2> const& ma) noexcept { decltype(inv(ma)) mb; #ifndef VXL_ROW_MAJOR mb.template set_col<0>(vector<T, 2>{ma(1, 1), -ma(1, 0)}); mb.template set_col<1>(vector<T, 2>{-ma(0, 1), ma(0, 0)}); #else mb.template set_row<0>(vector<T, 2>{ma(1, 1), -ma(0, 1)}); mb.template set_row<1>(vector<T, 2>{-ma(1, 0), ma(0, 0)}); #endif // VXL_ROW_MAJOR return mb / det(ma); } ////////////////////////////////////////////////////////////////////////////// template <class T> inline matrix<T, 3, 3> inv(matrix<T, 3, 3> const& ma) noexcept { decltype(inv(ma)) mb; mb(0, 0, ma(1, 1) * ma(2, 2) - ma(1, 2) * ma(2, 1)); mb(0, 1, ma(0, 2) * ma(2, 1) - ma(0, 1) * ma(2, 2)); mb(0, 2, ma(0, 1) * ma(1, 2) - ma(0, 2) * ma(1, 1)); mb(1, 0, ma(1, 2) * ma(2, 0) - ma(1, 0) * ma(2, 2)); mb(1, 1, ma(0, 0) * ma(2, 2) - ma(0, 2) * ma(2, 0)); mb(1, 2, ma(0, 2) * ma(1, 0) - ma(0, 0) * ma(1, 2)); mb(2, 0, ma(1, 0) * ma(2, 1) - ma(1, 1) * ma(2, 0)); mb(2, 1, ma(0, 1) * ma(2, 0) - ma(0, 0) * ma(2, 1)); mb(2, 2, ma(0, 0) * ma(1, 1) - ma(0, 1) * ma(1, 0)); return mb / det(ma); } ////////////////////////////////////////////////////////////////////////////// template <class T> inline matrix<T, 4, 4> inv(matrix<T, 4, 4> const& ma) noexcept { decltype(inv(ma)) mb; mb(0, 0, ma(1, 2) * ma(2, 3) * ma(3, 1) - ma(1, 3) * ma(2, 2) * ma(3, 1) + ma(1, 3) * ma(2, 1) * ma(3, 2) - ma(1, 1) * ma(2, 3) * ma(3, 2) - ma(1, 2) * ma(2, 1) * ma(3, 3) + ma(1, 1) * ma(2, 2) * ma(3, 3) ); mb(0, 1, ma(0, 3) * ma(2, 2) * ma(3, 1) - ma(0, 2) * ma(2, 3) * ma(3, 1) - ma(0, 3) * ma(2, 1) * ma(3, 2) + ma(0, 1) * ma(2, 3) * ma(3, 2) + ma(0, 2) * ma(2, 1) * ma(3, 3) - ma(0, 1) * ma(2, 2) * ma(3, 3) ); mb(0, 2, ma(0, 2) * ma(1, 3) * ma(3, 1) - ma(0, 3) * ma(1, 2) * ma(3, 1) + ma(0, 3) * ma(1, 1) * ma(3, 2) - ma(0, 1) * ma(1, 3) * ma(3, 2) - ma(0, 2) * ma(1, 1) * ma(3, 3) + ma(0, 1) * ma(1, 2) * ma(3, 3) ); mb(0, 3, ma(0, 3) * ma(1, 2) * ma(2, 1) - ma(0, 2) * ma(1, 3) * ma(2, 1) - ma(0, 3) * ma(1, 1) * ma(2, 2) + ma(0, 1) * ma(1, 3) * ma(2, 2) + ma(0, 2) * ma(1, 1) * ma(2, 3) - ma(0, 1) * ma(1, 2) * ma(2, 3) ); mb(1, 0, ma(1, 3) * ma(2, 2) * ma(3, 0) - ma(1, 2) * ma(2, 3) * ma(3, 0) - ma(1, 3) * ma(2, 0) * ma(3, 2) + ma(1, 0) * ma(2, 3) * ma(3, 2) + ma(1, 2) * ma(2, 0) * ma(3, 3) - ma(1, 0) * ma(2, 2) * ma(3, 3) ); mb(1, 1, ma(0, 2) * ma(2, 3) * ma(3, 0) - ma(0, 3) * ma(2, 2) * ma(3, 0) + ma(0, 3) * ma(2, 0) * ma(3, 2) - ma(0, 0) * ma(2, 3) * ma(3, 2) - ma(0, 2) * ma(2, 0) * ma(3, 3) + ma(0, 0) * ma(2, 2) * ma(3, 3) ); mb(1, 2, ma(0, 3) * ma(1, 2) * ma(3, 0) - ma(0, 2) * ma(1, 3) * ma(3, 0) - ma(0, 3) * ma(1, 0) * ma(3, 2) + ma(0, 0) * ma(1, 3) * ma(3, 2) + ma(0, 2) * ma(1, 0) * ma(3, 3) - ma(0, 0) * ma(1, 2) * ma(3, 3) ); mb(1, 3, ma(0, 2) * ma(1, 3) * ma(2, 0) - ma(0, 3) * ma(1, 2) * ma(2, 0) + ma(0, 3) * ma(1, 0) * ma(2, 2) - ma(0, 0) * ma(1, 3) * ma(2, 2) - ma(0, 2) * ma(1, 0) * ma(2, 3) + ma(0, 0) * ma(1, 2) * ma(2, 3) ); mb(2, 0, ma(1, 1) * ma(2, 3) * ma(3, 0) - ma(1, 3) * ma(2, 1) * ma(3, 0) + ma(1, 3) * ma(2, 0) * ma(3, 1) - ma(1, 0) * ma(2, 3) * ma(3, 1) - ma(1, 1) * ma(2, 0) * ma(3, 3) + ma(1, 0) * ma(2, 1) * ma(3, 3) ); mb(2, 1, ma(0, 3) * ma(2, 1) * ma(3, 0) - ma(0, 1) * ma(2, 3) * ma(3, 0) - ma(0, 3) * ma(2, 0) * ma(3, 1) + ma(0, 0) * ma(2, 3) * ma(3, 1) + ma(0, 1) * ma(2, 0) * ma(3, 3) - ma(0, 0) * ma(2, 1) * ma(3, 3) ); mb(2, 2, ma(0, 1) * ma(1, 3) * ma(3, 0) - ma(0, 3) * ma(1, 1) * ma(3, 0) + ma(0, 3) * ma(1, 0) * ma(3, 1) - ma(0, 0) * ma(1, 3) * ma(3, 1) - ma(0, 1) * ma(1, 0) * ma(3, 3) + ma(0, 0) * ma(1, 1) * ma(3, 3) ); mb(2, 3, ma(0, 3) * ma(1, 1) * ma(2, 0) - ma(0, 1) * ma(1, 3) * ma(2, 0) - ma(0, 3) * ma(1, 0) * ma(2, 1) + ma(0, 0) * ma(1, 3) * ma(2, 1) + ma(0, 1) * ma(1, 0) * ma(2, 3) - ma(0, 0) * ma(1, 1) * ma(2, 3) ); mb(3, 0, ma(1, 2) * ma(2, 1) * ma(3, 0) - ma(1, 1) * ma(2, 2) * ma(3, 0) - ma(1, 2) * ma(2, 0) * ma(3, 1) + ma(1, 0) * ma(2, 2) * ma(3, 1) + ma(1, 1) * ma(2, 0) * ma(3, 2) - ma(1, 0) * ma(2, 1) * ma(3, 2) ); mb(3, 1, ma(0, 1) * ma(2, 2) * ma(3, 0) - ma(0, 2) * ma(2, 1) * ma(3, 0) + ma(0, 2) * ma(2, 0) * ma(3, 1) - ma(0, 0) * ma(2, 2) * ma(3, 1) - ma(0, 1) * ma(2, 0) * ma(3, 2) + ma(0, 0) * ma(2, 1) * ma(3, 2) ); mb(3, 2, ma(0, 2) * ma(1, 1) * ma(3, 0) - ma(0, 1) * ma(1, 2) * ma(3, 0) - ma(0, 2) * ma(1, 0) * ma(3, 1) + ma(0, 0) * ma(1, 2) * ma(3, 1) + ma(0, 1) * ma(1, 0) * ma(3, 2) - ma(0, 0) * ma(1, 1) * ma(3, 2) ); mb(3, 3, ma(0, 1) * ma(1, 2) * ma(2, 0) - ma(0, 2) * ma(1, 1) * ma(2, 0) + ma(0, 2) * ma(1, 0) * ma(2, 1) - ma(0, 0) * ma(1, 2) * ma(2, 1) - ma(0, 1) * ma(1, 0) * ma(2, 2) + ma(0, 0) * ma(1, 1) * ma(2, 2) ); return mb / det(ma); } } #endif // VXL_MATRIX_INVERSE_HPP
36.739437
78
0.379337
janezz55
1c2fccf62da3e58f82082e09b5e3398d05384f15
51,411
hpp
C++
glfw3_app/ignitor/wave_cap.hpp
hirakuni45/glfw3_app
d9ceeef6d398229fda4849afe27f8b48d1597fcf
[ "BSD-3-Clause" ]
9
2015-09-22T21:36:57.000Z
2021-04-01T09:16:53.000Z
glfw3_app/ignitor/wave_cap.hpp
hirakuni45/glfw3_app
d9ceeef6d398229fda4849afe27f8b48d1597fcf
[ "BSD-3-Clause" ]
null
null
null
glfw3_app/ignitor/wave_cap.hpp
hirakuni45/glfw3_app
d9ceeef6d398229fda4849afe27f8b48d1597fcf
[ "BSD-3-Clause" ]
2
2019-02-21T04:22:13.000Z
2021-03-02T17:24:32.000Z
#pragma once //=====================================================================// /*! @file @brief 波形キャプチャー・クラス @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2018 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include <array> #include "core/glcore.hpp" #include "utils/i_scene.hpp" #include "utils/director.hpp" #include "widgets/widget.hpp" #include "widgets/widget_utils.hpp" #include "widgets/widget_frame.hpp" #include "widgets/widget_null.hpp" #include "widgets/widget_sheet.hpp" #include "widgets/widget_button.hpp" #include "widgets/widget_filer.hpp" #include "widgets/widget_terminal.hpp" #include "widgets/widget_list.hpp" #include "widgets/widget_view.hpp" #include "widgets/widget_radio.hpp" #include "widgets/widget_spinbox.hpp" #include "widgets/widget_chip.hpp" #include "gl_fw/render_waves.hpp" #include "img_io/img_files.hpp" #include "ign_client_tcp.hpp" #include "interlock.hpp" #include "test.hpp" // #define TEST_SIN namespace app { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief wave_cap クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// class wave_cap { static constexpr const char* WAVE_DATA_EXT_ = "wad"; public: //=================================================================// /*! @brief 情報構造体 */ //=================================================================// struct info_t { double sample_org_; ///< サンプリング開始時間 double sample_width_; ///< サンプリング領域(時間) double sig_[4]; ///< 各チャネル電圧 double min_[4]; ///< 領域の最低値 double max_[4]; ///< 領域の最大値 double average_[4]; ///< 領域のアベレージ uint32_t id_; ///< 領域更新 ID info_t() : sample_org_(0.0), sample_width_(0.0), sig_{ 0.0 }, min_{ 0.0 }, max_{ 0.0 }, average_{ 0.0 }, id_(0) { } }; //=================================================================// /*! @brief サンプリング・パラメーター構造体 */ //=================================================================// struct sample_param { double rate; double gain[4]; sample_param() : rate(1e-6) { gain[0] = 1.0; gain[1] = 1.0; gain[2] = 1.0; gain[3] = 1.0; } }; private: typedef utils::director<core> DR; DR& director_; typedef net::ign_client_tcp CLIENT; CLIENT& client_; interlock& interlock_; typedef view::render_waves<uint16_t, CLIENT::WAVE_BUFF_SIZE, 4> WAVES; WAVES waves_; gui::widget_frame* frame_; gui::widget_view* core_; gui::widget_frame* terminal_frame_; gui::widget_terminal* terminal_core_; gui::widget_frame* tools_; gui::widget_check* smooth_; gui::widget_button* load_; gui::widget_button* save_; gui::widget_list* mesa_type_; gui::widget_label* mesa_filt_; gui::widget_list* org_trg_; gui::widget_spinbox* org_slope_; gui::widget_check* org_ena_; gui::widget_list* fin_trg_; gui::widget_spinbox* fin_slope_; gui::widget_check* fin_ena_; gui::widget_list* time_mesa_ch_; gui::widget_spinbox* time_delay_; gui::widget_check* time_delay_ena_; gui::widget_text* ch_to_time_; gui::widget_button* wdm_exec_; uint32_t meas_id_before_; uint32_t meas_id_; float org_value_; float fin_value_; gui::widget_sheet* share_frame_; sample_param sample_param_; uint32_t wdm_id_[4]; uint32_t treg_id_[2]; WAVES::analize_param treg_1st_; WAVES::analize_param treg_2nd_; float treg_value_; float treg_value2_; uint32_t treg_value_id_; bool info_in_; vtx::ipos info_org_; info_t info_; gui::widget_chip* chip_; // チャネル補正ゲイン static float get_optional_gain_(uint32_t ch) { if(ch == 0) return 1.067f; // CH1 補正ゲイン else if(ch == 1) return 1.029f; // CH2 補正ゲイン // else if(ch == 2) return 1.111f; // CH3 補正ゲイン // else if(ch == 2) return 1.0777f; // CH3 補正ゲイン else if(ch == 2) return 1.0566f; // CH3 補正ゲイン else return 1.0179f; // CH4 補正ゲイン } // チャネル毎の電圧スケールサイズ static const uint32_t volt_scale_0_size_ = 8; static const uint32_t volt_scale_1_size_ = 15; static const uint32_t volt_scale_2_size_ = 10; static const uint32_t volt_scale_3_size_ = 12; static uint32_t get_volt_scale_size_(uint32_t ch) { if(ch == 0) return volt_scale_0_size_; else if(ch == 1) return volt_scale_1_size_; else if(ch == 2) return volt_scale_2_size_; else return volt_scale_3_size_; } static float get_volt_scale_value_(uint32_t ch, uint32_t idx) { if(ch == 0) { static const float tbl[volt_scale_0_size_] = { 0.25f, 0.5f, 1.0f, 2.0f, 2.5f, 5.0f, 7.5f, 10.0f }; return tbl[idx % get_volt_scale_size_(ch)]; } else if(ch == 1) { static const float tbl[volt_scale_1_size_] = { 0.125f, 0.25f, 0.5f, 1.0f, 2.5f, 5.0f, 10.0f, 20.0f, 25.0f, 50.0f, 75.0f, 100.0f, 125.0f, 150.0f, 200.0f }; return tbl[idx % get_volt_scale_size_(ch)]; } else if(ch == 2) { static const float tbl[volt_scale_2_size_] = { 0.05f, 0.1f, 0.2f, 0.25f, 0.5f, 1.0f, 1.5f, 2.0f, 2.5f, 5.0f }; return tbl[idx % get_volt_scale_size_(ch)]; } else { static const float tbl[volt_scale_3_size_] = { 0.0625f, 0.125f, 0.25f, 0.5f, 1.0f, 1.25f, 2.5f, 5.0f, 7.5f, 10.0f, 15.0f, 20.0f }; return tbl[idx % get_volt_scale_size_(ch)]; } } static float get_volt_scale_limit_(uint32_t ch) { if(ch == 0) return 32.768f; else if(ch == 1) return 655.36f; else if(ch == 2) return 16.384f; else return 65.536f; } static const uint32_t time_unit_size_ = 20; static double get_time_unit_(uint32_t idx) { static const double tbl[time_unit_size_] = { 100e-9, 250e-9, 500e-9, 1e-6, 2.5e-6, 5e-6, 10e-6, 25e-6, 50e-6, 100e-6, 250e-6, 500e-6, 1e-3, 2.5e-3, 5e-3, 10e-3, 25e-3, 50e-3, 75e-3, 100e-3 }; return tbl[idx % time_unit_size_]; } static float get_time_unit_base_(uint32_t idx) { static const float tbl[time_unit_size_] = { 1e-9, 1e-9, 1e-9, 1e-6, 1e-6, 1e-6, 1e-6, 1e-6, 1e-6, 1e-6, 1e-6, 1e-6, 1e-3, 1e-3, 1e-3, 1e-3, 1e-3, 1e-3, 1e-3, 1e-3 }; return tbl[idx % time_unit_size_]; } static const char* get_time_unit_str_(uint32_t idx) { static const char* tbl[time_unit_size_] = { "nS", "nS", "nS", "uS", "uS", "uS", "uS", "uS", "uS", "uS", "uS", "uS", "mS", "mS", "mS", "mS", "mS", "mS", "mS", "mS" }; return tbl[idx % time_unit_size_]; } static uint32_t get_time_scale_(uint32_t idx, uint32_t grid, float rate) { float g = static_cast<float>(grid); float step = get_time_unit_(idx) / g; return static_cast<uint32_t>(65536.0f * step / rate); } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief チャネル・クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// struct chn_t { WAVES& waves_; ///< 波形レンダリング gui::widget_null* root_; ///< ルート gui::widget_check* ena_; ///< チャネル有効、無効 gui::widget_check* gnd_; ///< GND 電位 gui::widget_spinbox* pos_; ///< 水平位置 gui::widget_spinbox* scale_; ///< 電圧スケール gui::widget_check* mes_; ///< メジャー有効 gui::widget_spinbox* org_; ///< 計測開始位置 gui::widget_spinbox* len_; ///< 計測長さ // fs: フルスケール電圧 chn_t(WAVES& waves, float fs) : waves_(waves), root_(nullptr), ena_(nullptr), gnd_(nullptr), pos_(nullptr), scale_(nullptr), mes_(nullptr), org_(nullptr), len_(nullptr) { } void init(DR& dr, gui::widget_sheet* share, int ch) { using namespace gui; auto& wd = dr.at().widget_director_; { // 仮想フレーム widget::param wp(vtx::irect(0, 0, 0, 0), share); widget_null::param wp_; root_ = wd.add_widget<widget_null>(wp, wp_); share->add((boost::format("CH%d") % (ch + 1)).str(), root_); } { // 有効、無効 widget::param wp(vtx::irect(10, 30, 80, 40), root_); widget_check::param wp_((boost::format("CH%d") % (ch + 1)).str()); ena_ = wd.add_widget<widget_check>(wp, wp_); ena_->at_local_param().select_func_ = [=](bool f) { waves_.at_param(ch).render_ = f; }; } { // GND 電位 widget::param wp(vtx::irect(10 + 90, 30, 80, 40), root_); widget_check::param wp_("GND"); gnd_ = wd.add_widget<widget_check>(wp, wp_); } { // 電圧位置 (+-1.0) widget::param wp(vtx::irect(10, 70, 130, 40), root_); widget_spinbox::param wp_(-20, 0, 20); // grid 数の倍 pos_ = wd.add_widget<widget_spinbox>(wp, wp_); pos_->at_local_param().select_func_ = [=](widget_spinbox::state st, int before, int newpos) { int wy = share->get_param().rect_.size.y; float a = static_cast<float>(-newpos) / static_cast<float>(wy * 2 / waves_.get_info().grid_step_); return (boost::format("%3.2f") % a).str(); }; } { // 電圧スケール widget::param wp(vtx::irect(10 + 140, 70, 160, 40), root_); widget_spinbox::param wp_(0, 0, (get_volt_scale_size_(ch) - 1)); scale_ = wd.add_widget<widget_spinbox>(wp, wp_); scale_->at_local_param().select_func_ = [=](widget_spinbox::state st, int before, int newpos) { // グリッドに対する電圧表示 auto a = get_volt_scale_value_(ch, newpos); static const char* unit[4] = { "A", "V", "V", "KV" }; org_->exec(); len_->exec(); return (boost::format("%3.2f %s") % a % unit[ch]).str(); }; } { // メジャー有効、無効 widget::param wp(vtx::irect(10, 120, 130, 40), root_); widget_check::param wp_("Measure"); mes_ = wd.add_widget<widget_check>(wp, wp_); } { // メジャー開始位置 widget::param wp(vtx::irect(10, 170, 145, 40), root_); widget_spinbox::param wp_(0, 0, 100); org_ = wd.add_widget<widget_spinbox>(wp, wp_); org_->at_local_param().select_func_ = [=](widget_spinbox::state st, int before, int newpos) { float a = static_cast<float>(-newpos) / static_cast<float>(waves_.get_info().grid_step_) * get_volt_scale_value_(ch, scale_->get_select_pos()); float b = static_cast<float>(-pos_->get_select_pos()) / 2.0f; b *= get_volt_scale_value_(ch, scale_->get_select_pos()); return (boost::format("%3.2f") % (a - b)).str(); }; } { // メジャー長さ widget::param wp(vtx::irect(10 + 155, 170, 145, 40), root_); widget_spinbox::param wp_(0, 0, 100); // grid 数の倍 len_ = wd.add_widget<widget_spinbox>(wp, wp_); len_->at_local_param().select_func_ = [=](widget_spinbox::state st, int before, int newpos) { // メジャーに対する電圧、電流表示 float a = static_cast<float>(-newpos) / static_cast<float>(waves_.get_info().grid_step_) * get_volt_scale_value_(ch, scale_->get_select_pos()); return (boost::format("%3.2f") % a).str(); }; } } void update(uint32_t ch, const vtx::ipos& size, float gainrate) { if(pos_ == nullptr || scale_ == nullptr) return; if(org_ == nullptr || len_ == nullptr) return; int grid = waves_.get_info().grid_step_; auto pos = (size.y / grid) * 3 / 2; pos_->at_local_param().min_pos_ = -pos; pos_->at_local_param().max_pos_ = pos; int msofs = size.y / 2; org_->at_local_param().min_pos_ = -msofs; org_->at_local_param().max_pos_ = msofs; org_->at_local_param().page_div_ = 0; org_->at_local_param().page_step_ = -grid; len_->at_local_param().min_pos_ = -size.y; len_->at_local_param().max_pos_ = size.y; len_->at_local_param().page_div_ = 0; len_->at_local_param().page_step_ = -grid; // 波形位置 waves_.at_param(ch).offset_.y = (size.y / 2) + pos_->get_select_pos() * (grid / 2); // 波形拡大、縮小 float value = get_volt_scale_value_(ch, scale_->get_select_pos()) / static_cast<float>(grid); float u = get_volt_scale_limit_(ch) / static_cast<float>(32768); if(gnd_->get_check()) u = 0.0f; ////////////////////////////////////////////////////////// waves_.at_param(ch).gain_ = u / value / gainrate * get_optional_gain_(ch); // 電圧計測設定 if(mes_->get_check()) { waves_.at_info().volt_enable_[ch] = true; waves_.at_info().volt_org_[ch] = org_->get_select_pos() + msofs; waves_.at_info().volt_len_[ch] = len_->get_select_pos(); } else { waves_.at_info().volt_enable_[ch] = false; } } void load(sys::preference& pre) { if(ena_ != nullptr) { ena_->load(pre); } if(gnd_ != nullptr) { gnd_->load(pre); } if(pos_ != nullptr) { pos_->load(pre); pos_->exec(); } if(scale_ != nullptr) { scale_->load(pre); scale_->exec(); } if(mes_ != nullptr) { mes_->load(pre); } if(org_ != nullptr) { org_->load(pre); org_->exec(); } if(len_ != nullptr) { len_->load(pre); len_->exec(); } ena_->exec(); gnd_->exec(); mes_->exec(); } void save(sys::preference& pre) { if(ena_ != nullptr) { ena_->save(pre); } if(gnd_ != nullptr) { gnd_->save(pre); } if(pos_ != nullptr) { pos_->save(pre); } if(scale_ != nullptr) { scale_->save(pre); } if(mes_ != nullptr) { mes_->save(pre); } if(org_ != nullptr) { org_->save(pre); } if(len_ != nullptr) { len_->save(pre); } } }; chn_t chn0_; chn_t chn1_; chn_t chn2_; chn_t chn3_; chn_t& at_ch(uint32_t no) { switch(no) { case 0: return chn0_; case 1: return chn1_; case 2: return chn2_; case 3: return chn3_; default: return chn0_; } } const chn_t& get_ch(uint32_t no) const { switch(no) { case 0: return chn0_; case 1: return chn1_; case 2: return chn2_; case 3: return chn3_; default: return chn0_; } } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief 時間軸計測クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// struct measure_t { WAVES& waves_; gui::widget_null* root_; gui::widget_check* ena_; gui::widget_spinbox* org_; gui::widget_spinbox* len_; gui::widget_text* frq_; ///< 周波数表示 uint32_t tbp_; ///< タイム・ベース位置 measure_t(WAVES& waves) : waves_(waves), root_(nullptr), ena_(nullptr), org_(nullptr), len_(nullptr), frq_(nullptr), tbp_(0) { } void init(DR& dr, gui::widget_sheet* share, const std::string& text) { using namespace gui; widget_director& wd = dr.at().widget_director_; { // 仮想フレーム widget::param wp(vtx::irect(0, 0, 0, 0), share); widget_null::param wp_; root_ = wd.add_widget<widget_null>(wp, wp_); share->add(text, root_); } { // メジャー有効、無効 widget::param wp(vtx::irect(10, 30, 140, 40), root_); widget_check::param wp_("Enable"); ena_ = wd.add_widget<widget_check>(wp, wp_); ena_->at_local_param().select_func_ = [=](bool f) { waves_.at_info().time_enable_ = f; }; } { widget::param wp(vtx::irect(10, 70, 200, 40), root_); widget_spinbox::param wp_(0, 0, 100); org_ = wd.add_widget<widget_spinbox>(wp, wp_); org_->at_local_param().select_func_ = [=](widget_spinbox::state st, int before, int newpos) { float t = get_time_unit_(tbp_) * static_cast<float>(newpos) / waves_.get_info().grid_step_; float a = t / get_time_unit_base_(tbp_); return (boost::format("%2.1f %s") % a % get_time_unit_str_(tbp_)).str(); }; } { widget::param wp(vtx::irect(10, 120, 200, 40), root_); widget_spinbox::param wp_(0, 0, 100); len_ = wd.add_widget<widget_spinbox>(wp, wp_); len_->at_local_param().select_func_ = [=](widget_spinbox::state st, int before, int newpos) { float t = get_time_unit_(tbp_) * static_cast<float>(newpos) / waves_.get_info().grid_step_; float a = t / get_time_unit_base_(tbp_); if(t > 0.0f) { float f = 1.0f / t; if(f >= 1000.0) { f /= 1000.0; frq_->set_text((boost::format("%4.3f KHz") % f).str()); } else if(f >= 1000000.0) { f /= 1000000.0; frq_->set_text((boost::format("%4.3f MHz") % f).str()); } else { frq_->set_text((boost::format("%4.3f Hz") % f).str()); } } else { frq_->set_text("---"); } return (boost::format("%3.2f %s") % a % get_time_unit_str_(tbp_)).str(); }; } { widget::param wp(vtx::irect(10, 170, 150, 40), root_); widget_text::param wp_; frq_ = wd.add_widget<widget_text>(wp, wp_); } } void update(const vtx::ipos& size) { if(org_ == nullptr || len_ == nullptr) return; auto grid = waves_.get_info().grid_step_; org_->at_local_param().min_pos_ = 0; org_->at_local_param().max_pos_ = size.x; org_->at_local_param().page_div_ = 0; org_->at_local_param().page_step_ = grid; waves_.at_info().time_org_ = org_->get_select_pos(); len_->at_local_param().min_pos_ = 0; len_->at_local_param().max_pos_ = size.x; len_->at_local_param().page_div_ = 0; len_->at_local_param().page_step_ = grid; waves_.at_info().time_len_ = len_->get_select_pos(); } void load(sys::preference& pre) { if(ena_ != nullptr) { ena_->load(pre); } if(org_ != nullptr) { org_->load(pre); org_->exec(); } if(len_ != nullptr) { len_->load(pre); len_->exec(); } } void save(sys::preference& pre) { if(ena_ != nullptr) { ena_->save(pre); } if(org_ != nullptr) { org_->save(pre); } if(len_ != nullptr) { len_->save(pre); } } }; measure_t measure_time_; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief 時間軸クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// struct time_t { WAVES& waves_; gui::widget_null* root_; gui::widget_spinbox* scale_; ///< 時間スケール gui::widget_spinbox* offset_; ///< 時間オフセット gui::widget_button* res_ofs_; ///< 時間オフセット、リセット gui::widget_check* trg_gate_; ///< トリガー表示 uint32_t id_; time_t(WAVES& waves) : waves_(waves), root_(nullptr), scale_(nullptr), offset_(nullptr), res_ofs_(nullptr), trg_gate_(nullptr), id_(0) { } void init(DR& dr, gui::widget_sheet* share) { using namespace gui; auto& wd = dr.at().widget_director_; { // 仮想フレーム widget::param wp(vtx::irect(0, 0, 0, 0), share); widget_null::param wp_; root_ = wd.add_widget<widget_null>(wp, wp_); share->add("Time Scale", root_); } { // タイム・スケール widget::param wp(vtx::irect(10, 40, 200, 40), root_); widget_spinbox::param wp_(0, 0, time_unit_size_ - 1); scale_ = wd.add_widget<widget_spinbox>(wp, wp_); scale_->at_local_param().select_func_ = [=](widget_spinbox::state st, int before, int newpos) { ++id_; float a = get_time_unit_(newpos) / get_time_unit_base_(newpos); return (boost::format("%2.1f %s") % a % get_time_unit_str_(newpos)).str(); }; } { // タイム・オフセット(グリッド単位) widget::param wp(vtx::irect(10, 90, 200, 40), root_); widget_spinbox::param wp_(-50, 0, 50); offset_ = wd.add_widget<widget_spinbox>(wp, wp_); offset_->at_local_param().select_func_ = [=](widget_spinbox::state st, int before, int newpos) { ++id_; float t = get_time_unit_(scale_->get_select_pos()) * newpos; auto un = scale_->get_select_pos(); float a = t / get_time_unit_base_(un); return (boost::format("%2.1f %s") % a % get_time_unit_str_(un)).str(); }; } { // オフセット・リセット widget::param wp(vtx::irect(10 + 215, 95, 30, 30), root_); widget_button::param wp_("R"); res_ofs_ = wd.add_widget<widget_button>(wp, wp_); res_ofs_->at_local_param().select_func_ = [=](uint32_t id) { ++id_; offset_->set_select_pos(0); }; } { // トリガー・ゲート有効、無効 widget::param wp(vtx::irect(10, 140, 140, 40), root_); widget_check::param wp_("Trigger"); trg_gate_ = wd.add_widget<widget_check>(wp, wp_); trg_gate_->at_local_param().select_func_ = [=](bool ena) { ++id_; }; } } void update(const vtx::ipos& size, float rate) { int grid = waves_.get_info().grid_step_; auto ts = get_time_scale_(scale_->get_select_pos(), grid, rate); int w = (waves_.size() / 2 * ts / 65536 - size.x) / grid; offset_->at_local_param().min_pos_ = -w; offset_->at_local_param().max_pos_ = w; auto ofs = offset_->get_select_pos(); // 波形のトリガー先頭 waves_.at_param(0).offset_.x = ofs * grid; waves_.at_param(1).offset_.x = ofs * grid; waves_.at_param(2).offset_.x = ofs * grid; waves_.at_param(3).offset_.x = ofs * grid; if(trg_gate_->get_check()) { waves_.at_info().trig_enable_ = true; waves_.at_info().trig_pos_ = -offset_->get_select_pos() * grid; } else { waves_.at_info().trig_enable_ = false; } } void load(sys::preference& pre) { if(scale_ != nullptr) { scale_->load(pre); scale_->exec(); } if(offset_ != nullptr) { offset_->load(pre); offset_->exec(); } if(trg_gate_ != nullptr) { trg_gate_->load(pre); } } void save(sys::preference& pre) { if(scale_ != nullptr) { scale_->save(pre); } if(offset_ != nullptr) { offset_->save(pre); } if(trg_gate_ != nullptr) { trg_gate_->save(pre); } } }; time_t time_; uint32_t time_id_; vtx::ipos size_; double mesa_value_; uint32_t mesa_id_; double time_meas_delay_; void volt_scale_conv_(uint32_t ch, const WAVES::analize_param& ap, info_t& t) { float gain = 1.0f / sample_param_.gain[ch]; t.min_[ch] = get_volt_scale_limit_(ch) * ap.min_ * gain; t.max_[ch] = get_volt_scale_limit_(ch) * ap.max_ * gain; t.average_[ch] = get_volt_scale_limit_(ch) * ap.average_ * gain; } // 波形描画 void update_view_() { if(core_->get_select_in()) { info_in_ = true; info_org_ = core_->get_param().in_point_; } if(core_->get_selected()) { uint32_t n = 0; if(time_.scale_ != nullptr) { n = time_.scale_->get_select_pos(); } auto msp = core_->get_param().in_point_; info_in_ = false; auto grid = waves_.get_info().grid_step_; int32_t sta = info_org_.x + time_.offset_->get_select_pos() * grid; int32_t fin = msp.x + time_.offset_->get_select_pos() * grid; if(sta > fin) std::swap(sta, fin); auto tu = get_time_unit_(n); info_.sample_org_ = static_cast<double>(sta) * tu; double org = static_cast<double>(sta) / static_cast<double>(grid) * tu; double end = static_cast<double>(fin) / static_cast<double>(grid) * tu; info_.sample_width_ = end - org; for(uint32_t i = 0; i < 4; ++i) { if(!get_ch(i).ena_->get_check()) continue; auto a = waves_.get(i, sample_param_.rate, org); a *= get_optional_gain_(i); a *= get_volt_scale_limit_(i); a /= sample_param_.gain[i]; if(get_ch(i).gnd_->get_check()) { a = 0.0f; } info_.sig_[i] = a; static const char* t[4] = { "A", "V", "V", "KV" }; double len = info_.sample_width_; static const char* ut[4] = { "S", "mS", "uS", "nS" }; uint32_t uti = 0; if(len < 1e-6) { len *= 1e9; uti = 3; } else if(len < 1e-3) { len *= 1e6; uti = 2; } else if(len < 1.0) { len *= 1e3; uti = 1; } std::string s = (boost::format("CH%d: %4.3f %s, %4.3f %s\n") % (i + 1) % a % t[i] % len % ut[uti]).str(); terminal_core_->output(s); { // 波形解析 double step = tu / static_cast<double>(grid); auto ap = waves_.analize(i, sample_param_.rate, org, end - org, step); volt_scale_conv_(i, ap, info_); s = (boost::format("Min: %4.3f %s, ") % info_.min_[i] % t[i]).str(); terminal_core_->output(s); s = (boost::format("Max: %4.3f %s\n") % info_.max_[i] % t[i]).str(); terminal_core_->output(s); s = (boost::format("Ave: %4.3f %s\n") % info_.average_[i] % t[i]).str(); terminal_core_->output(s); ++info_.id_; } } } // フォーカスが外れたら、情報(IN) を強制終了 if(!core_->get_focus()) { info_in_ = false; } } void render_view_(const vtx::irect& clip) { glDisable(GL_TEXTURE_2D); if(info_in_ && core_->get_select()) { vtx::sposs r; r.emplace_back(info_org_.x, info_org_.y); auto msp = core_->get_param().in_point_; r.emplace_back(msp.x, info_org_.y); r.emplace_back(msp.x, msp.y); r.emplace_back(info_org_.x, msp.y); gl::glColor(img::rgba8(255, 255)); gl::draw_line_loop(r); } uint32_t n = 0; if(time_.scale_ != nullptr) { n = time_.scale_->get_select_pos(); } waves_.render(clip.size, sample_param_.rate, get_time_unit_(n)); glEnable(GL_TEXTURE_2D); size_ = clip.size; } void service_view_() { } void meas_run_() { // スキャンする長さは、見えている範囲に制限する。 auto grid = waves_.get_info().grid_step_; double unit = get_time_unit_(time_.scale_->get_select_pos()); double length = static_cast<double>(size_.x / grid) * unit; double offset = static_cast<double>(time_.offset_->get_select_pos()) * unit; WAVES::measure_param param; double tm = 0.0; switch(mesa_type_->get_select_pos()) { case 0: // single { param.org_ch_ = org_trg_->get_select_pos() / 2; float base = 100.0f; if(org_trg_->get_select_pos() & 1) base = -100.0f; param.org_slope_ = static_cast<float>(org_slope_->get_select_pos()) / base; auto srate = sample_param_.rate; tm = waves_.measure_org(srate, offset, 0.0, length, param); uint32_t idx = time_.scale_->get_select_pos(); auto ofs = time_.offset_->get_select_pos() * -grid; waves_.at_info().meas_pos_[0] = ofs + (tm / get_time_unit_(idx)) * grid; waves_.at_info().meas_color_[0] = waves_.get_info().volt_color_[param.org_ch_]; } break; case 1: // multi { param.org_ch_ = org_trg_->get_select_pos() / 2; float base = 100.0f; if(org_trg_->get_select_pos() & 1) base = -100.0f; param.org_slope_ = static_cast<float>(org_slope_->get_select_pos()) / base; param.fin_ch_ = fin_trg_->get_select_pos() / 2; base = 100.0f; if(fin_trg_->get_select_pos() & 1) base = -100.0f; param.fin_slope_ = static_cast<float>(fin_slope_->get_select_pos()) / base; auto srate = sample_param_.rate; auto a = waves_.measure_org(srate, offset, 0.0, length, param); uint32_t idx = time_.scale_->get_select_pos(); auto ofs = time_.offset_->get_select_pos() * -grid; waves_.at_info().meas_pos_[0] = ofs + (a / get_time_unit_(idx)) * grid; waves_.at_info().meas_color_[0] = waves_.get_info().volt_color_[param.org_ch_]; auto b = waves_.measure_fin(srate, offset, a, length, param); waves_.at_info().meas_pos_[1] = ofs + (b / get_time_unit_(idx)) * grid; waves_.at_info().meas_color_[1] = waves_.get_info().volt_color_[param.fin_ch_]; tm = b - a; } break; case 2: // トリガ電圧測定 { auto srate = sample_param_.rate; auto ch = time_mesa_ch_->get_select_pos(); tm = waves_.get(ch, srate, 0.0); } break; case 3: // max { auto srate = sample_param_.rate; auto ch = time_mesa_ch_->get_select_pos(); auto ana = waves_.analize(ch, srate, 0.0, time_meas_delay_ + srate, srate); tm = ana.max_ / sample_param_.gain[ch]; waves_.at_info().delay_color_ = waves_.get_info().volt_color_[ch]; } break; case 4: // min { auto srate = sample_param_.rate; auto ch = time_mesa_ch_->get_select_pos(); auto ana = waves_.analize(ch, srate, 0.0, time_meas_delay_ + srate, srate); tm = ana.min_ / sample_param_.gain[ch]; waves_.at_info().delay_color_ = waves_.get_info().volt_color_[ch]; } break; case 5: // average { auto srate = sample_param_.rate; auto ch = time_mesa_ch_->get_select_pos(); auto ana = waves_.analize(ch, srate, 0.0, time_meas_delay_ + srate, srate); tm = ana.average_ / sample_param_.gain[ch]; waves_.at_info().delay_color_ = waves_.get_info().volt_color_[ch]; } break; default: break; } if(mesa_type_->get_select_pos() < 2) { uint32_t idx = time_.scale_->get_select_pos(); tm /= get_time_unit_base_(idx); std::string un = get_time_unit_str_(idx); ch_to_time_->set_text((boost::format("%5.4f [%s]") % tm % un).str()); } else { auto ch = time_mesa_ch_->get_select_pos(); tm *= get_volt_scale_limit_(ch) * get_optional_gain_(ch); static const char* unit[4] = { "A", "V", "V", "KV" }; auto str = (boost::format("%4.3f [%s]") % tm % unit[ch]).str(); if(mesa_type_->get_select_pos() >= 3) { float t = time_meas_delay_ / get_time_unit_base_(time_.scale_->get_select_pos()); auto u = get_time_unit_str_(time_.scale_->get_select_pos()); str += (boost::format(", %3.2f %s") % t % u).str(); } ch_to_time_->set_text(str); } mesa_value_ = tm; } std::string proj_root_; utils::select_file data_load_filer_; utils::select_file data_save_filer_; public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// wave_cap(utils::director<core>& d, CLIENT& client, interlock& ilock) : director_(d), client_(client), interlock_(ilock), waves_(), frame_(nullptr), core_(nullptr), terminal_frame_(nullptr), terminal_core_(nullptr), tools_(nullptr), smooth_(nullptr), load_(nullptr), save_(nullptr), mesa_type_(nullptr), mesa_filt_(nullptr), org_trg_(nullptr), org_slope_(nullptr), org_ena_(nullptr), fin_trg_(nullptr), fin_slope_(nullptr), fin_ena_(nullptr), time_mesa_ch_(nullptr), time_delay_(nullptr), time_delay_ena_(nullptr), ch_to_time_(nullptr), wdm_exec_(nullptr), meas_id_before_(0), meas_id_(0), org_value_(0.0f), fin_value_(0.0f), share_frame_(nullptr), sample_param_(), wdm_id_{ 0 }, treg_id_{ 0 }, treg_1st_(), treg_2nd_(), treg_value_(0.0f), treg_value2_(0.0f), treg_value_id_(0), info_in_(false), info_org_(0), info_(), chn0_(waves_, 1.25f), chn1_(waves_, 1.25f), chn2_(waves_, 1.25f), chn3_(waves_, 1.25f), measure_time_(waves_), time_(waves_), time_id_(0), size_(0), mesa_value_(0.0), mesa_id_(0), time_meas_delay_(0.0), proj_root_(), data_load_filer_(), data_save_filer_() { } //-----------------------------------------------------------------// /*! @brief プロジェクト・ルートの設定 @param[in] root プロジェクト・ルート */ //-----------------------------------------------------------------// void set_project_root(const std::string& root) { proj_root_ = root; } //-----------------------------------------------------------------// /*! @brief 計測結果の取得 @return 計測結果 */ //-----------------------------------------------------------------// uint32_t get_mesa_id() const { return mesa_id_; } //-----------------------------------------------------------------// /*! @brief 計測結果の取得 @return 計測結果 */ //-----------------------------------------------------------------// double get_mesa_value() const { return mesa_value_; } //-----------------------------------------------------------------// /*! @brief 時間スケール値を取得 @return 時間スケール値 */ //-----------------------------------------------------------------// double get_time_scale() const { uint32_t newpos = time_.scale_->get_select_pos(); return get_time_unit_(newpos) / get_time_unit_base_(newpos); } //-----------------------------------------------------------------// /*! @brief 電圧スケール値を取得 @param[in] ch チャネル @return 電圧スケール値 */ //-----------------------------------------------------------------// float get_volt_scale(uint32_t ch) const { uint32_t newpos = 0; switch(ch) { case 0: newpos = chn0_.scale_->get_select_pos(); break; case 1: newpos = chn1_.scale_->get_select_pos(); break; case 2: newpos = chn2_.scale_->get_select_pos(); break; case 3: newpos = chn3_.scale_->get_select_pos(); break; default: break; } return get_volt_scale_value_(ch, newpos); } //-----------------------------------------------------------------// /*! @brief 波形情報の取得 @return 波形情報 */ //-----------------------------------------------------------------// const info_t& get_info() const { return info_; } //-----------------------------------------------------------------// /*! @brief 転送ボタンを取得 @return 転送ボタン */ //-----------------------------------------------------------------// gui::widget_button* get_exec_button() const { return wdm_exec_; } //-----------------------------------------------------------------// /*! @brief 測定単位文字列の取得 @return 測定単位文字列 */ //-----------------------------------------------------------------// std::string get_unit_str() const { std::string u; auto n = mesa_type_->get_select_pos(); if(n == 0 || n == 1) { // 時間 return get_time_unit_str_(time_.scale_->get_select_pos()); } else { // 電圧 auto ch = time_mesa_ch_->get_select_pos(); static const char* unit[4] = { "A", "V", "V", "KV" }; return unit[ch]; } return u; } float get_treg_value() const { return treg_value_; } float get_treg_value2() const { return treg_value2_; } uint32_t get_treg_value_id() const { return treg_value_id_; } //-----------------------------------------------------------------// /*! @brief 許可、不許可 @param[in] ena 不許可の場合「false」 */ //-----------------------------------------------------------------// void enable(bool ena = true) { using namespace gui; widget_director& wd = director_.at().widget_director_; if(frame_->get_enable() != ena) { wd.enable(frame_, ena, true); wd.enable(tools_, ena, true); wd.enable(terminal_frame_, ena, true); } } //-----------------------------------------------------------------// /*! @brief サンプリング・パラメーターの設定 @param[in] rate サンプリング・パラメーター */ //-----------------------------------------------------------------// void set_sample_param(const sample_param& sp) { sample_param_ = sp; } //-----------------------------------------------------------------// /*! @brief 初期化 */ //-----------------------------------------------------------------// void initialize() { using namespace gui; widget_director& wd = director_.at().widget_director_; size_.set(930, 820); { // 波形描画フレーム widget::param wp(vtx::irect(610, 5, size_.x, size_.y)); widget_frame::param wp_; wp_.plate_param_.set_caption(12); wp_.color_param_.fore_color_ = img::rgba8(65, 100, 150); wp_.color_param_.back_color_ = wp_.color_param_.fore_color_ * 0.7f; frame_ = wd.add_widget<widget_frame>(wp, wp_); } { // 波形描画ビュー widget::param wp(vtx::irect(0), frame_); widget_view::param wp_; wp_.update_func_ = [=]() { update_view_(); }; wp_.render_func_ = [=](const vtx::irect& clip) { render_view_(clip); }; wp_.service_func_ = [=]() { service_view_(); }; core_ = wd.add_widget<widget_view>(wp, wp_); } { // ターミナル { widget::param wp(vtx::irect(270, 610, 330, 220)); widget_frame::param wp_; wp_.plate_param_.set_caption(12); terminal_frame_ = wd.add_widget<widget_frame>(wp, wp_); } { widget::param wp(vtx::irect(0), terminal_frame_); widget_terminal::param wp_; wp_.enter_func_ = [=](const utils::lstring& text) { // term_enter_(text); }; terminal_core_ = wd.add_widget<widget_terminal>(wp, wp_); term_chaout::set_output(terminal_core_); } } int mw = 330; int mh = 600; { // 波形ツールフレーム widget::param wp(vtx::irect(270, 5, mw, mh)); widget_frame::param wp_; wp_.plate_param_.set_caption(12); tools_ = wd.add_widget<widget_frame>(wp, wp_); tools_->set_state(gui::widget::state::SIZE_LOCK); } { // スムース widget::param wp(vtx::irect(10, 20, 110, 40), tools_); widget_check::param wp_("Smooth"); smooth_ = wd.add_widget<widget_check>(wp, wp_); } { // ロード widget::param wp(vtx::irect(140, 20, 80, 40), tools_); widget_button::param wp_("Load"); load_ = wd.add_widget<widget_button>(wp, wp_); load_->at_local_param().select_func_ = [=](uint32_t id) { std::string filter = "波形データ(*."; filter += WAVE_DATA_EXT_; filter += ")\t*."; filter += WAVE_DATA_EXT_; filter += "\t"; data_load_filer_.open(filter, false, proj_root_); }; } { // セーブ widget::param wp(vtx::irect(230, 20, 80, 40), tools_); widget_button::param wp_("Save"); save_ = wd.add_widget<widget_button>(wp, wp_); save_->at_local_param().select_func_ = [=](uint32_t id) { std::string filter = "波形データ(*."; filter += WAVE_DATA_EXT_; filter += ")\t*."; filter += WAVE_DATA_EXT_; filter += "\t"; data_save_filer_.open(filter, true, proj_root_); }; } { // 計測開始チャネルとスロープ widget::param wp(vtx::irect(10, 120, 110, 40), tools_); widget_list::param wp_; wp_.init_list_.push_back("CH1 ↑"); wp_.init_list_.push_back("CH1 ↓"); wp_.init_list_.push_back("CH2 ↑"); wp_.init_list_.push_back("CH2 ↓"); wp_.init_list_.push_back("CH3 ↑"); wp_.init_list_.push_back("CH3 ↓"); wp_.init_list_.push_back("CH4 ↑"); wp_.init_list_.push_back("CH4 ↓"); org_trg_ = wd.add_widget<widget_list>(wp, wp_); org_trg_->at_local_param().select_func_ = [=](const std::string& t, uint32_t p) { ++meas_id_; }; } { // 計測開始トリガー・レベル widget::param wp(vtx::irect(130, 120, 110, 40), tools_); widget_spinbox::param wp_(0, 50, 100); org_slope_ = wd.add_widget<widget_spinbox>(wp, wp_); org_slope_->at_local_param().select_func_ = [=](widget_spinbox::state st, int before, int newpos) { ++meas_id_; return (boost::format("%d") % newpos).str(); }; } { // 計測終了チャネルとスロープ widget::param wp(vtx::irect(10, 170, 110, 40), tools_); widget_list::param wp_; wp_.init_list_.push_back("CH1 ↑"); wp_.init_list_.push_back("CH1 ↓"); wp_.init_list_.push_back("CH2 ↑"); wp_.init_list_.push_back("CH2 ↓"); wp_.init_list_.push_back("CH3 ↑"); wp_.init_list_.push_back("CH3 ↓"); wp_.init_list_.push_back("CH4 ↑"); wp_.init_list_.push_back("CH4 ↓"); fin_trg_ = wd.add_widget<widget_list>(wp, wp_); fin_trg_->at_local_param().select_func_ = [=](const std::string& t, uint32_t p) { ++meas_id_; }; } { // 計測終了トリガー・レベル widget::param wp(vtx::irect(130, 170, 110, 40), tools_); widget_spinbox::param wp_(0, 50, 100); fin_slope_ = wd.add_widget<widget_spinbox>(wp, wp_); fin_slope_->at_local_param().select_func_ = [=](widget_spinbox::state st, int before, int newpos) { ++meas_id_; return (boost::format("%d") % newpos).str(); }; } { // 時間計測チャネル widget::param wp(vtx::irect(10, 220, 110, 40), tools_); widget_list::param wp_; wp_.init_list_.push_back("CH1"); wp_.init_list_.push_back("CH2"); wp_.init_list_.push_back("CH3"); wp_.init_list_.push_back("CH4"); time_mesa_ch_ = wd.add_widget<widget_list>(wp, wp_); time_mesa_ch_->at_local_param().select_func_ = [=](const std::string& t, uint32_t p) { ++meas_id_; }; } { // 計測ディレイ widget::param wp(vtx::irect(10 + 120, 220, 110, 40), tools_); wp.pre_group_ = widget::PRE_GROUP::_1; auto grid = waves_.get_info().grid_step_; widget_spinbox::param wp_(-size_.x / grid * 4, 0, size_.x / grid * 4); time_delay_ = wd.add_widget<widget_spinbox>(wp, wp_); time_delay_->at_local_param().select_func_ = [=](widget_spinbox::state st, int before, int newpos) { auto grid = waves_.get_info().grid_step_; waves_.at_info().delay_pos_ = newpos * grid / 4 + (-time_.offset_->get_select_pos() * grid); float t = get_time_unit_(time_.scale_->get_select_pos()); time_meas_delay_ = t * static_cast<double>(newpos) / 4.0; ++meas_id_; return (boost::format("%d") % newpos).str(); }; } { // 計測ディレイ、ライン描画 widget::param wp(vtx::irect(250, 220, 100, 40), tools_); widget_check::param wp_("Del"); time_delay_ena_ = wd.add_widget<widget_check>(wp, wp_); } { // 計測時間表示 widget::param wp(vtx::irect(10, 270, 260, 40), tools_); widget_text::param wp_; ch_to_time_ = wd.add_widget<widget_text>(wp, wp_); } { // 共有フレーム(プロパティシート) widget::param wp(vtx::irect(5, 310, mw - 10, mh - 310 - 5), tools_); widget_sheet::param wp_; share_frame_ = wd.add_widget<widget_sheet>(wp, wp_); } measure_time_.init(director_, share_frame_, "Time Measure"); chn0_.init(director_, share_frame_, 0); chn1_.init(director_, share_frame_, 1); chn2_.init(director_, share_frame_, 2); chn3_.init(director_, share_frame_, 3); time_.init(director_, share_frame_); { // 計測タイプ widget::param wp(vtx::irect(10, 20 + 50, 140, 40), tools_); widget_list::param wp_; wp_.init_list_.push_back("SINGLE T"); wp_.init_list_.push_back("MULTI T"); wp_.init_list_.push_back("SINGLE V"); wp_.init_list_.push_back("Max"); wp_.init_list_.push_back("Min"); wp_.init_list_.push_back("Average"); mesa_type_ = wd.add_widget<widget_list>(wp, wp_); mesa_type_->at_local_param().select_func_ = [=](const std::string& t, uint32_t p) { }; } { // 計測フィルタ係数 widget::param wp(vtx::irect(10 + 150, 20 + 50, 110, 40), tools_); widget_label::param wp_("1.0", false); mesa_filt_ = wd.add_widget<widget_label>(wp, wp_); } { // 計測開始ボタン widget::param wp(vtx::irect(270, 270, 30, 30), tools_); widget_button::param wp_(">"); wdm_exec_ = wd.add_widget<widget_button>(wp, wp_); } { // 計測ライン描画 (org) widget::param wp(vtx::irect(250, 120, 90, 40), tools_); widget_check::param wp_("1st"); org_ena_ = wd.add_widget<widget_check>(wp, wp_); } { // 計測ライン描画 (fin) widget::param wp(vtx::irect(250, 170, 90, 40), tools_); widget_check::param wp_("2nd"); fin_ena_ = wd.add_widget<widget_check>(wp, wp_); } { // help message (widget_chip) widget::param wp(vtx::irect(0, 0, 100, 40), tools_); widget_chip::param wp_; chip_ = wd.add_widget<widget_chip>(wp, wp_); chip_->active(0); } waves_.create_buffer(); waves_.at_param(0).color_ = img::rgba8(255, 64, 255, 255); waves_.at_info().volt_color_[0] = waves_.get_param(0).color_; waves_.at_param(1).color_ = img::rgba8( 64, 255, 255, 255); waves_.at_info().volt_color_[1] = waves_.get_param(1).color_; waves_.at_param(2).color_ = img::rgba8(255, 255, 32, 255); waves_.at_info().volt_color_[2] = waves_.get_param(2).color_; waves_.at_param(3).color_ = img::rgba8( 64, 255, 64, 255); waves_.at_info().volt_color_[3] = waves_.get_param(3).color_; #ifdef TEST_SIN waves_.build_sin(0, sample_param_.rate, 15000.0, 1.0f); waves_.build_sin(1, sample_param_.rate, 10000.0, 0.75f); #endif } //-----------------------------------------------------------------// /*! @brief アップデート */ //-----------------------------------------------------------------// void update() { if(frame_ == nullptr) return; if(share_frame_ == nullptr) return; auto sheetpos = share_frame_->get_select_pos(); switch(sheetpos) { case 1: case 2: case 3: case 4: share_frame_->at_local_param().text_param_.fore_color_ = waves_.get_param(sheetpos - 1).color_; break; default: share_frame_->at_local_param().text_param_.fore_color_ = img::rgba8( 255, 255, 255, 255); break; } switch(mesa_type_->get_select_pos()) { case 0: // トリガーからの時間計測 org_trg_->set_stall(false); org_slope_->set_stall(false); org_ena_->set_stall(false); fin_trg_->set_stall(); fin_slope_->set_stall(); fin_ena_->set_stall(); time_mesa_ch_->set_stall(); time_delay_->set_stall(); time_delay_ena_->set_stall(); break; case 1: // チャネル間時間計測 org_trg_->set_stall(false); org_slope_->set_stall(false); org_ena_->set_stall(false); fin_trg_->set_stall(false); fin_slope_->set_stall(false); fin_ena_->set_stall(false); time_mesa_ch_->set_stall(); time_delay_->set_stall(); time_delay_ena_->set_stall(); break; case 2: // トリガーからの電圧 org_trg_->set_stall(); org_slope_->set_stall(); org_ena_->set_stall(); fin_trg_->set_stall(); fin_slope_->set_stall(); fin_ena_->set_stall(); time_mesa_ch_->set_stall(false); time_delay_->set_stall(); time_delay_ena_->set_stall(); break; case 3: // Max case 4: // Min case 5: // Average org_trg_->set_stall(); org_slope_->set_stall(); org_ena_->set_stall(); fin_trg_->set_stall(); fin_slope_->set_stall(); fin_ena_->set_stall(); time_mesa_ch_->set_stall(false); time_delay_->set_stall(false); time_delay_ena_->set_stall(false); break; default: break; } if(org_ena_->get_enable() && !org_ena_->get_stall()) { waves_.at_info().meas_enable_[0] = org_ena_->get_check(); } else { waves_.at_info().meas_enable_[0] = false; } if(fin_ena_->get_enable() && !fin_ena_->get_stall()) { waves_.at_info().meas_enable_[1] = fin_ena_->get_check(); } else { waves_.at_info().meas_enable_[1] = false; } if(time_delay_ena_->get_enable() && !time_delay_ena_->get_stall()) { waves_.at_info().delay_enable_ = time_delay_ena_->get_check(); } else { waves_.at_info().delay_enable_ = false; } wdm_exec_->set_stall(!client_.probe()); waves_.enable_smooth(smooth_->get_check()); measure_time_.tbp_ = time_.scale_->get_select_pos(); measure_time_.update(size_); chn0_.update(0, size_, sample_param_.gain[0]); chn1_.update(1, size_, sample_param_.gain[1]); chn2_.update(2, size_, sample_param_.gain[2]); chn3_.update(3, size_, sample_param_.gain[3]); time_.update(size_, sample_param_.rate); // 波形のコピー(中間位置がトリガーポイント) { uint32_t nnn = wdm_id_[3]; for(uint32_t i = 0; i < 4; ++i) { auto id = client_.get_mod_status().wdm_id_[i]; if(wdm_id_[i] != id) { auto sz = waves_.size(); waves_.copy(i, client_.get_wdm(i), sz, sz / 2); wdm_id_[i] = id; } } if(wdm_id_[3] != nnn) { meas_run_(); ++mesa_id_; } } if(time_id_ != time_.id_) { time_id_ = time_.id_; ++meas_id_; } // 時間計測 (single, multi) if(meas_id_before_ != meas_id_) { meas_run_(); meas_id_before_ = meas_id_; } // 仮熱抵抗表示 for(uint32_t i = 0; i < 2; ++i) { auto id = client_.get_mod_status().treg_id_[i]; if(treg_id_[i] != id) { auto sz = waves_.size(); if(i == 0) { waves_.copy(1, client_.get_treg(i) + sz / 2, sz / 2, sz / 2); } else { waves_.copy(1, client_.get_treg(i) + sz / 2, sz / 2, 0); // treg_2nd_ = waves_.analize(1, 1.0, (800.0 - 50.0), 100.0, 1.0); // treg_1st_ = waves_.analize(1, 1.0, (1024.0 + 800.0 - 50.0), 100.0, 1.0); treg_2nd_ = waves_.analize(1, 1.0, (800.0 - 100.0), 128.0 + 64.0, 1.0); treg_1st_ = waves_.analize(1, 1.0, (1024.0 + 800.0 - 100.0), 128.0 + 64.0, 1.0); // std::cout << "1ST: " << treg_1st_.average_ << std::endl; // std::cout << "2ND: " << treg_2nd_.average_ << std::endl; float a = treg_1st_.average_ - treg_2nd_.average_; // std::cout << " D: " << a << std::endl; float u = get_volt_scale_limit_(1); treg_value_ = a * u / 64.0; auto b = waves_.analize(1, 1.0, (256.0 - 32.0), 64.0, 1.0); // std::cout << "3RD: " << b.average_ << std::endl; treg_value2_ = b.average_ * u / 64.0; ++treg_value_id_; } treg_id_[i] = id; } } { uint32_t act = 60 * 3; if(org_slope_->get_focus()) { std::string s; // tools::set_help(chip_, org_slope_, s); } else if(fin_slope_->get_focus()) { std::string s; // tools::set_help(chip_, fin_slope_, s); } else { act = 0; } // chip_->active(act); } if(data_load_filer_.state()) { auto path = data_load_filer_.get(); if(!path.empty()) { if(utils::get_file_ext(path).empty()) { path += '.'; path += WAVE_DATA_EXT_; } if(waves_.load(path)) { ++meas_id_; } } } if(data_save_filer_.state()) { auto path = data_save_filer_.get(); if(!path.empty()) { if(utils::get_file_ext(path).empty()) { path += '.'; path += WAVE_DATA_EXT_; } if(waves_.save(path)) { } } } } //-----------------------------------------------------------------// /*! @brief ロード */ //-----------------------------------------------------------------// void load(sys::preference& pre) { if(frame_ != nullptr) { frame_->load(pre); } if(terminal_frame_ != nullptr) { terminal_frame_->load(pre); } if(tools_ != nullptr) { tools_->load(pre); } if(smooth_ != nullptr) { smooth_->load(pre); smooth_->exec(); } if(share_frame_ != nullptr) { share_frame_->load(pre); } chn0_.load(pre); chn1_.load(pre); chn2_.load(pre); chn3_.load(pre); time_.load(pre); measure_time_.load(pre); mesa_type_->load(pre); mesa_filt_->load(pre); org_trg_->load(pre); org_slope_->load(pre); org_slope_->exec(); org_ena_->load(pre); fin_trg_->load(pre); fin_slope_->load(pre); fin_slope_->exec(); fin_ena_->load(pre); time_mesa_ch_->load(pre); time_delay_->load(pre); time_delay_->exec(); time_delay_ena_->load(pre); } //-----------------------------------------------------------------// /*! @brief セーブ */ //-----------------------------------------------------------------// void save(sys::preference& pre) { if(frame_ != nullptr) { frame_->save(pre); } if(terminal_frame_ != nullptr) { terminal_frame_->save(pre); } if(tools_ != nullptr) { tools_->save(pre); } if(smooth_ != nullptr) { smooth_->save(pre); } if(share_frame_ != nullptr) { share_frame_->save(pre); } chn0_.save(pre); chn1_.save(pre); chn2_.save(pre); chn3_.save(pre); time_.save(pre); measure_time_.save(pre); mesa_type_->save(pre); mesa_filt_->save(pre); org_trg_->save(pre); org_slope_->save(pre); org_ena_->save(pre); fin_trg_->save(pre); fin_slope_->save(pre); fin_ena_->save(pre); time_mesa_ch_->save(pre); time_delay_->save(pre); time_delay_ena_->save(pre); } //-----------------------------------------------------------------// /*! @brief 波形画像のセーブ @param[in] path セーブ・パス @return 成功なら「true」 */ //-----------------------------------------------------------------// bool save_image(const std::string& path) const { bool ret = false; if(path.empty()) return ret; if(core_ == nullptr) return ret; vtx::ipos pos; gui::final_position(core_, pos); const auto& size = core_->get_param().rect_.size; auto simg = gl::get_frame_buffer(pos.x , pos.y, size.x, size.y); img::img_files imfs; imfs.set_image(simg); ret = imfs.save(path); return ret; } }; }
29.128045
87
0.570053
hirakuni45
1c40415d373b86ce2e000fe8d3cd0e1c51117f3c
977
cpp
C++
UnitTests/TestApp/ActionCreateData.cpp
lmj0591/mygui
311fb9d07089f64558eb7f77e9b37c4cb91e3559
[ "MIT" ]
590
2015-01-06T09:22:06.000Z
2022-03-21T18:23:02.000Z
UnitTests/TestApp/ActionCreateData.cpp
lmj0591/mygui
311fb9d07089f64558eb7f77e9b37c4cb91e3559
[ "MIT" ]
159
2015-01-07T03:34:23.000Z
2022-02-21T21:28:51.000Z
UnitTests/TestApp/ActionCreateData.cpp
lmj0591/mygui
311fb9d07089f64558eb7f77e9b37c4cb91e3559
[ "MIT" ]
212
2015-01-05T07:33:33.000Z
2022-03-28T22:11:51.000Z
/*! @file @author Albert Semenov @date 07/2012 */ #include "ActionCreateData.h" #include "DataManager.h" #include "DataInfoManager.h" namespace tools { ActionCreateData::ActionCreateData() : mData(nullptr), mComplete(false) { } ActionCreateData::~ActionCreateData() { if (mData != nullptr && !mComplete) { delete mData; mData = nullptr; } } void ActionCreateData::doAction() { if (mData == nullptr) { mData = new Data(); mData->setType(DataInfoManager::getInstance().getData("ResourceImageSet")); mData->setPropertyValue("Name", mName); } DataManager::getInstance().getRoot()->addChild(mData); DataManager::getInstance().invalidateDatas(); mComplete = true; } void ActionCreateData::undoAction() { DataManager::getInstance().getRoot()->removeChild(mData); DataManager::getInstance().invalidateDatas(); mComplete = false; } void ActionCreateData::setName(const std::string& _value) { mName = _value; } }
17.446429
78
0.685773
lmj0591
1c440155b03beee5ee8039970d6cad6fe77ce1a8
792
hpp
C++
book/not_so_basics/testing/Dealer.hpp
luanics/cpp-illustrated
6049de2119a53d656a63b65d9441e680355ef196
[ "MIT" ]
null
null
null
book/not_so_basics/testing/Dealer.hpp
luanics/cpp-illustrated
6049de2119a53d656a63b65d9441e680355ef196
[ "MIT" ]
null
null
null
book/not_so_basics/testing/Dealer.hpp
luanics/cpp-illustrated
6049de2119a53d656a63b65d9441e680355ef196
[ "MIT" ]
null
null
null
#pragma once #include "Action.hpp" #include "Hand.hpp" namespace luanics::cards::blackjack { ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// /// /// @class Dealer /// /// @brief Following standard rules, hits until 17 reached. /// /// Dealer takes action based on own hand only. /// ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// class Dealer { public: static constexpr int minScore = 17; Action nextActionGiven(Hand const & dealers) { if (dealers.score() < minScore) { return Action::HIT; } else { return Action::STAND; } } }; // class Dealer } // namespace luanics::cards::blackjack
23.294118
69
0.431818
luanics
1c44630469d3718b7cca2a5836a6ccebe4c1ea7c
304
cpp
C++
Tasks/year3-demo-workspace/Lecture01-PortOut/main.cpp
ConnorD02/Embedded-Systems
3e42b3da487fbe3bf7cfa897a6dd4cdb568d97e1
[ "Apache-2.0" ]
33
2020-08-05T12:58:51.000Z
2022-03-28T12:00:20.000Z
Tasks/year3-demo-workspace/Lecture01-PortOut/main.cpp
ConnorD02/Embedded-Systems
3e42b3da487fbe3bf7cfa897a6dd4cdb568d97e1
[ "Apache-2.0" ]
37
2020-08-05T12:53:22.000Z
2022-03-04T10:24:47.000Z
Tasks/year3-demo-workspace/Lecture01-PortOut/main.cpp
ConnorD02/Embedded-Systems
3e42b3da487fbe3bf7cfa897a6dd4cdb568d97e1
[ "Apache-2.0" ]
51
2020-10-06T11:04:40.000Z
2022-03-28T12:00:11.000Z
#include "mbed.h" //BusOut leds(PC_2, PC_3, PC_6, PB_0, PB_7, PB_14); PortOut portc(PortC, 0b0000000001001100); PortOut portb(PortB, 0b0100000010000001); int main() { while (true) { portb = 0; portc = 0xFFFF; wait_us(500000); portb = 0xFFFF; portc = 0; wait_us(500000); } }
17.882353
51
0.634868
ConnorD02
1c62982fa529dc9f0dd8cee2272f4cded59f225d
1,795
cpp
C++
leetcode/_236_lowest_common_ancestor_of_a_binary_tree_2.cpp
WindyDarian/OJ_Submissions
a323595c3a32ed2e07af65374ef90c81d5333f96
[ "Apache-2.0" ]
3
2017-02-19T14:38:32.000Z
2017-07-22T17:06:55.000Z
leetcode/_236_lowest_common_ancestor_of_a_binary_tree_2.cpp
WindyDarian/OJ_Submissions
a323595c3a32ed2e07af65374ef90c81d5333f96
[ "Apache-2.0" ]
null
null
null
leetcode/_236_lowest_common_ancestor_of_a_binary_tree_2.cpp
WindyDarian/OJ_Submissions
a323595c3a32ed2e07af65374ef90c81d5333f96
[ "Apache-2.0" ]
null
null
null
//============================================================================== // Copyright 2016 Windy Darian (Ruoyu Fan) // // 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. //============================================================================== // // Created on Nov 28, 2016 // https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* findOneOrLca(TreeNode* root, TreeNode* p, TreeNode* q) { if (!root) {return nullptr;} if (root == p || root == q) { return root; } auto lfound = findOneOrLca(root->left, p, q); auto rfound = findOneOrLca(root->right, p, q); if (lfound && rfound) { return root; } if (!lfound && rfound) { return rfound; } else if (lfound && !rfound) { return lfound; } return nullptr; } TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { return findOneOrLca(root, p, q); } };
28.046875
80
0.545404
WindyDarian
1c6acf7ce271c21eb9918c68cce3d24bd9d1333f
3,130
hpp
C++
library/inc/argo/action/Callback.hpp
phforest/Argo
bd45b2bf53f88fbd9f6215dc6293bbb3614e37d8
[ "MIT" ]
null
null
null
library/inc/argo/action/Callback.hpp
phforest/Argo
bd45b2bf53f88fbd9f6215dc6293bbb3614e37d8
[ "MIT" ]
null
null
null
library/inc/argo/action/Callback.hpp
phforest/Argo
bd45b2bf53f88fbd9f6215dc6293bbb3614e37d8
[ "MIT" ]
null
null
null
#ifndef HEADER_argo_action_Callback_hpp_INCLUDE_GUARD #define HEADER_argo_action_Callback_hpp_INCLUDE_GUARD #include "argo/Context.hpp" #include "argo/action/IAction.hpp" #include "argo/details/log.hpp" #include "argo/details/mss.hpp" #include "argo/details/optional.hpp" #include "argo/traits/conversion.hpp" #include "argo/utility.hpp" #include <functional> namespace argo { namespace action { template<typename Type, typename ConversionTraits = traits::conversion<Type>> class Callback: public IAction { public: using callback_type = std::function<bool(const Type &)>; using callback_with_context_type = std::function<bool(Context &, const Type &)>; explicit Callback(const callback_type &callback): simple_(callback) {} explicit Callback(const callback_with_context_type &callback): extended_(callback) {} virtual Ptr clone() const override { if (!!simple_) return details::make_unique<Callback>(*simple_); assert(!!extended_); return details::make_unique<Callback>(*extended_); } virtual bool apply(Context &context, const std::string &value) override { MSS_BEGIN(bool); //if (!!simple_) L("Invoking simple callback"); //else trace("Invoking extended callback"); //trace(C(value)); const auto res = convert<Type, ConversionTraits>(context, value); MSS(!!res); MSS(!!simple_ ? (*simple_)(*res) : (*extended_)(context, *res), { std::ostringstream os; os << "Could not process '" << context.option() << "'"; context.error(os.str()); }); MSS_END(); } private: details::optional<callback_type> simple_; details::optional<callback_with_context_type> extended_; }; template<typename Type, typename ConversionTraits = traits::conversion<Type>> Callback<Type, ConversionTraits> callback(typename Callback<Type, ConversionTraits>::callback_type &cb) { return Callback<Type, ConversionTraits>{cb}; } inline Callback<std::string> callback(const std::function<bool(const std::string &)> &cb) { return Callback<std::string>{cb}; } inline Callback<std::string> callback(const std::function<bool()> &cb) { auto wrapper = [cb](const std::string &){ return cb(); }; return Callback<std::string>{wrapper}; } template<typename Type, typename ConversionTraits = traits::conversion<Type>> Callback<Type, ConversionTraits> callback(typename Callback<Type, ConversionTraits>::callback_type_with_context &cb) { return Callback<Type, ConversionTraits>{cb}; } inline Callback<std::string> callback(const std::function<bool(Context &, const std::string &)> &cb) { return Callback<std::string>{cb}; } inline Callback<std::string> callback(const std::function<bool(Context &)> &cb) { auto wrapper = [cb](Context &context, const std::string &) { return cb(context); }; return Callback<std::string>{wrapper}; } } } #endif
41.733333
169
0.650799
phforest
1c6b0464f5d4891666abda68087b97aec4fdcefa
2,618
cpp
C++
src/hypro/representations/Box/intervalMethods.cpp
hypro/hypro
52ae4ffe0a8427977fce8d7979fffb82a1bc28f6
[ "MIT" ]
22
2016-10-05T12:19:01.000Z
2022-01-23T09:14:41.000Z
src/hypro/representations/Box/intervalMethods.cpp
hypro/hypro
52ae4ffe0a8427977fce8d7979fffb82a1bc28f6
[ "MIT" ]
23
2017-05-08T15:02:39.000Z
2021-11-03T16:43:39.000Z
src/hypro/representations/Box/intervalMethods.cpp
hypro/hypro
52ae4ffe0a8427977fce8d7979fffb82a1bc28f6
[ "MIT" ]
12
2017-06-07T23:51:09.000Z
2022-01-04T13:06:21.000Z
#include "intervalMethods.h" namespace hypro { void reduceIntervalsNumberRepresentation( std::vector<carl::Interval<mpq_class>>& intervals, unsigned limit ) { mpq_class limit2 = mpq_class( limit ) * mpq_class( limit ); for ( unsigned d = 0; d < intervals.size(); ++d ) { //std::cout << "(Upper Bound) mpq_class: " << intervals[d].upper() << std::endl; if ( intervals[d].upper() != 0 ) { mpq_class numerator = carl::getNum( intervals[d].upper() ); mpq_class denominator = carl::getDenom( intervals[d].upper() ); mpq_class largest = carl::abs( numerator ) > carl::abs( denominator ) ? carl::abs( numerator ) : carl::abs( denominator ); if ( largest > limit2 ) { mpq_class dividend = largest / mpq_class( limit ); assert( largest / dividend == limit ); mpq_class val = mpq_class( carl::ceil( numerator / dividend ) ); mpq_class newDenom; if ( intervals[d].upper() > 0 ) { newDenom = mpq_class( carl::floor( denominator / dividend ) ); } else { newDenom = mpq_class( carl::ceil( denominator / dividend ) ); } if ( newDenom != 0 ) { val = val / newDenom; assert( val >= intervals[d].upper() ); intervals[d].setUpper( mpq_class( val ) ); } //std::cout << "Assert: " << val << " >= " << intervals[d].upper() << std::endl; //std::cout << "(Upper bound) Rounding Error: " << carl::convert<mpq_class,double>(val - intervals[d].upper()) << std::endl; } } //std::cout << "(Lower Bound) mpq_class: " << intervals[d].lower() << std::endl; if ( intervals[d].lower() != 0 ) { mpq_class numerator = carl::getNum( intervals[d].lower() ); mpq_class denominator = carl::getDenom( intervals[d].lower() ); mpq_class largest = carl::abs( numerator ) > carl::abs( denominator ) ? carl::abs( numerator ) : carl::abs( denominator ); if ( largest > limit2 ) { mpq_class dividend = largest / mpq_class( limit ); assert( largest / dividend == limit ); mpq_class val = mpq_class( carl::floor( numerator / dividend ) ); mpq_class newDenom; if ( intervals[d].lower() > 0 ) { newDenom = mpq_class( carl::ceil( denominator / dividend ) ); } else { newDenom = mpq_class( carl::floor( denominator / dividend ) ); } if ( newDenom != 0 ) { val = val / newDenom; assert( val <= intervals[d].lower() ); intervals[d].setLower( val ); } //std::cout << "Assert: " << val << " <= " << intervals[d].lower() << std::endl; //std::cout << "(Lower bound) Rounding Error: " << carl::convert<mpq_class,double>(val - intervals[d].lower()) << std::endl; } } } } } // namespace hypro
42.918033
128
0.606188
hypro
1c6cd514bbb1e87b74a40651a751a12f92307405
3,332
hh
C++
src/Xi-Crypto/include/Xi/Crypto/Hash/Sha2.hh
ElSamaritan/blockchain-OLD
ca3422c8873613226db99b7e6735c5ea1fac9f1a
[ "Apache-2.0" ]
null
null
null
src/Xi-Crypto/include/Xi/Crypto/Hash/Sha2.hh
ElSamaritan/blockchain-OLD
ca3422c8873613226db99b7e6735c5ea1fac9f1a
[ "Apache-2.0" ]
null
null
null
src/Xi-Crypto/include/Xi/Crypto/Hash/Sha2.hh
ElSamaritan/blockchain-OLD
ca3422c8873613226db99b7e6735c5ea1fac9f1a
[ "Apache-2.0" ]
null
null
null
/* ============================================================================================== * * * * Galaxia Blockchain * * * * ---------------------------------------------------------------------------------------------- * * This file is part of the Xi framework. * * ---------------------------------------------------------------------------------------------- * * * * Copyright 2018-2019 Xi Project Developers <support.xiproject.io> * * * * This program is free software: you can redistribute it and/or modify it under the terms of the * * GNU General Public License as published by the Free Software Foundation, either version 3 of * * the License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with this program. * * If not, see <https://www.gnu.org/licenses/>. * * * * ============================================================================================== */ #pragma once #include <Xi/Global.hh> #include <Xi/Byte.hh> #include "Xi/Crypto/Hash/Hash.hh" #if defined(__cplusplus) extern "C" { #endif #include <stdio.h> int xi_crypto_hash_sha2_224(const xi_byte_t *data, size_t length, xi_crypto_hash_224 out); int xi_crypto_hash_sha2_256(const xi_byte_t *data, size_t length, xi_crypto_hash_256 out); int xi_crypto_hash_sha2_384(const xi_byte_t *data, size_t length, xi_crypto_hash_384 out); int xi_crypto_hash_sha2_512(const xi_byte_t *data, size_t length, xi_crypto_hash_512 out); #if defined(__cplusplus) } #endif #if defined(__cplusplus) namespace Xi { namespace Crypto { namespace Hash { namespace Sha2 { XI_CRYPTO_HASH_DECLARE_HASH_TYPE(Hash224, 224) XI_CRYPTO_HASH_DECLARE_HASH_TYPE(Hash256, 256) XI_CRYPTO_HASH_DECLARE_HASH_TYPE(Hash384, 384) XI_CRYPTO_HASH_DECLARE_HASH_TYPE(Hash512, 512) void compute(ConstByteSpan data, Hash224 &out); void compute(ConstByteSpan data, Hash256 &out); void compute(ConstByteSpan data, Hash384 &out); void compute(ConstByteSpan data, Hash512 &out); } // namespace Sha2 } // namespace Hash } // namespace Crypto } // namespace Xi #endif
49.731343
100
0.444778
ElSamaritan
1c6dfcba405fcbc6ada048b7837745a2a6b620f1
201
cpp
C++
examples/s3/boo.cpp
Costallat/hunter
dc0d79cb37b30cad6d6472d7143fe27be67e26d5
[ "BSD-2-Clause" ]
2,146
2015-01-10T07:26:58.000Z
2022-03-21T02:28:01.000Z
examples/s3/boo.cpp
koinos/hunter
fc17bc391210bf139c55df7f947670c5dff59c57
[ "BSD-2-Clause" ]
1,778
2015-01-03T11:50:30.000Z
2019-12-26T05:31:20.000Z
examples/s3/boo.cpp
koinos/hunter
fc17bc391210bf139c55df7f947670c5dff59c57
[ "BSD-2-Clause" ]
734
2015-03-05T19:52:34.000Z
2022-02-22T23:18:54.000Z
#include <libs3.h> int main() { const char *userAgentInfo = ""; int flags = 0; const char *defaultS3HostName = ""; S3Status result = S3_initialize(userAgentInfo, flags, defaultS3HostName); }
20.1
75
0.691542
Costallat
1c78a06ce6df0438fcb3464340f1c05f56aff8d2
7,774
cpp
C++
vm/src/vm/Core.cpp
lordadamson/tethys
8bad2155462fb436a3da6ce1c69242486f62fe9f
[ "BSD-3-Clause" ]
null
null
null
vm/src/vm/Core.cpp
lordadamson/tethys
8bad2155462fb436a3da6ce1c69242486f62fe9f
[ "BSD-3-Clause" ]
null
null
null
vm/src/vm/Core.cpp
lordadamson/tethys
8bad2155462fb436a3da6ce1c69242486f62fe9f
[ "BSD-3-Clause" ]
null
null
null
#include "vm/Core.h" #include "vm/Op.h" #include "vm/Util.h" namespace vm { inline static Op pop_op(Core& self, const mn::Buf<uint8_t>& code) { return Op(pop8(code, self.r[Reg_IP].u64)); } inline static Reg pop_reg(Core& self, const mn::Buf<uint8_t>& code) { return Reg(pop8(code, self.r[Reg_IP].u64)); } inline static Reg_Val& load_reg(Core& self, const mn::Buf<uint8_t>& code) { Reg i = pop_reg(self, code); assert(i < Reg_COUNT); return self.r[i]; } // API void core_ins_execute(Core& self, const mn::Buf<uint8_t>& code) { auto op = pop_op(self, code); switch(op) { case Op_LOAD8: { auto& dst = load_reg(self, code); dst.u8 = pop8(code, self.r[Reg_IP].u64); break; } case Op_LOAD16: { auto& dst = load_reg(self, code); dst.u16 = pop16(code, self.r[Reg_IP].u64); break; } case Op_LOAD32: { auto& dst = load_reg(self, code); dst.u32 = pop32(code, self.r[Reg_IP].u64); break; } case Op_LOAD64: { auto& dst = load_reg(self, code); dst.u64 = pop64(code, self.r[Reg_IP].u64); break; } case Op_ADD8: { auto& dst = load_reg(self, code); auto& src = load_reg(self, code); dst.u8 += src.u8; break; } case Op_ADD16: { auto& dst = load_reg(self, code); auto& src = load_reg(self, code); dst.u16 += src.u16; break; } case Op_ADD32: { auto& dst = load_reg(self, code); auto& src = load_reg(self, code); dst.u32 += src.u32; break; } case Op_ADD64: { auto& dst = load_reg(self, code); auto& src = load_reg(self, code); dst.u64 += src.u64; break; } case Op_SUB8: { auto& dst = load_reg(self, code); auto& src = load_reg(self, code); dst.u8 -= src.u8; break; } case Op_SUB16: { auto& dst = load_reg(self, code); auto& src = load_reg(self, code); dst.u16 -= src.u16; break; } case Op_SUB32: { auto& dst = load_reg(self, code); auto& src = load_reg(self, code); dst.u32 -= src.u32; break; } case Op_SUB64: { auto& dst = load_reg(self, code); auto& src = load_reg(self, code); dst.u64 -= src.u64; break; } case Op_MUL8: { auto& dst = load_reg(self, code); auto& src = load_reg(self, code); dst.u8 *= src.u8; break; } case Op_MUL16: { auto& dst = load_reg(self, code); auto& src = load_reg(self, code); dst.u16 *= src.u16; break; } case Op_MUL32: { auto& dst = load_reg(self, code); auto& src = load_reg(self, code); dst.u32 *= src.u32; break; } case Op_MUL64: { auto& dst = load_reg(self, code); auto& src = load_reg(self, code); dst.u64 *= src.u64; break; } case Op_IMUL8: { auto& dst = load_reg(self, code); auto& src = load_reg(self, code); dst.i8 *= src.i8; break; } case Op_IMUL16: { auto& dst = load_reg(self, code); auto& src = load_reg(self, code); dst.i16 *= src.i16; break; } case Op_IMUL32: { auto& dst = load_reg(self, code); auto& src = load_reg(self, code); dst.i32 *= src.i32; break; } case Op_IMUL64: { auto& dst = load_reg(self, code); auto& src = load_reg(self, code); dst.i64 *= src.i64; break; } case Op_DIV8: { auto& dst = load_reg(self, code); auto& src = load_reg(self, code); dst.u8 /= src.u8; break; } case Op_DIV16: { auto& dst = load_reg(self, code); auto& src = load_reg(self, code); dst.u16 /= src.u16; break; } case Op_DIV32: { auto& dst = load_reg(self, code); auto& src = load_reg(self, code); dst.u32 /= src.u32; break; } case Op_DIV64: { auto& dst = load_reg(self, code); auto& src = load_reg(self, code); dst.u64 /= src.u64; break; } case Op_IDIV8: { auto& dst = load_reg(self, code); auto& src = load_reg(self, code); dst.i8 /= src.i8; break; } case Op_IDIV16: { auto& dst = load_reg(self, code); auto& src = load_reg(self, code); dst.i16 /= src.i16; break; } case Op_IDIV32: { auto& dst = load_reg(self, code); auto& src = load_reg(self, code); dst.i32 /= src.i32; break; } case Op_IDIV64: { auto& dst = load_reg(self, code); auto& src = load_reg(self, code); dst.i64 /= src.i64; break; } case Op_CMP8: { auto& op1 = load_reg(self, code); auto& op2 = load_reg(self, code); if (op1.u8 > op2.u8) self.cmp = Core::CMP_GREATER; else if (op1.u8 < op2.u8) self.cmp = Core::CMP_LESS; else self.cmp = Core::CMP_EQUAL; break; } case Op_CMP16: { auto& op1 = load_reg(self, code); auto& op2 = load_reg(self, code); if (op1.u16 > op2.u16) self.cmp = Core::CMP_GREATER; else if (op1.u16 < op2.u16) self.cmp = Core::CMP_LESS; else self.cmp = Core::CMP_EQUAL; break; } case Op_CMP32: { auto& op1 = load_reg(self, code); auto& op2 = load_reg(self, code); if (op1.u32 > op2.u32) self.cmp = Core::CMP_GREATER; else if (op1.u32 < op2.u32) self.cmp = Core::CMP_LESS; else self.cmp = Core::CMP_EQUAL; break; } case Op_CMP64: { auto& op1 = load_reg(self, code); auto& op2 = load_reg(self, code); if (op1.u64 > op2.u64) self.cmp = Core::CMP_GREATER; else if (op1.u64 < op2.u64) self.cmp = Core::CMP_LESS; else self.cmp = Core::CMP_EQUAL; break; } case Op_ICMP8: { auto& op1 = load_reg(self, code); auto& op2 = load_reg(self, code); if (op1.i8 > op2.i8) self.cmp = Core::CMP_GREATER; else if (op1.i8 < op2.i8) self.cmp = Core::CMP_LESS; else self.cmp = Core::CMP_EQUAL; break; } case Op_ICMP16: { auto& op1 = load_reg(self, code); auto& op2 = load_reg(self, code); if (op1.i16 > op2.i16) self.cmp = Core::CMP_GREATER; else if (op1.i16 < op2.i16) self.cmp = Core::CMP_LESS; else self.cmp = Core::CMP_EQUAL; break; } case Op_ICMP32: { auto& op1 = load_reg(self, code); auto& op2 = load_reg(self, code); if (op1.i32 > op2.i32) self.cmp = Core::CMP_GREATER; else if (op1.i32 < op2.i32) self.cmp = Core::CMP_LESS; else self.cmp = Core::CMP_EQUAL; break; } case Op_ICMP64: { auto& op1 = load_reg(self, code); auto& op2 = load_reg(self, code); if (op1.i64 > op2.i64) self.cmp = Core::CMP_GREATER; else if (op1.i64 < op2.i64) self.cmp = Core::CMP_LESS; else self.cmp = Core::CMP_EQUAL; break; } case Op_JMP: { int64_t offset = int64_t(pop64(code, self.r[Reg_IP].u64)); self.r[Reg_IP].u64 += offset; break; } case Op_JE: { int64_t offset = int64_t(pop64(code, self.r[Reg_IP].u64)); if (self.cmp == Core::CMP_EQUAL) { self.r[Reg_IP].u64 += offset; } break; } case Op_JNE: { int64_t offset = int64_t(pop64(code, self.r[Reg_IP].u64)); if (self.cmp != Core::CMP_EQUAL) { self.r[Reg_IP].u64 += offset; } break; } case Op_JL: { int64_t offset = int64_t(pop64(code, self.r[Reg_IP].u64)); if (self.cmp == Core::CMP_LESS) { self.r[Reg_IP].u64 += offset; } break; } case Op_JLE: { int64_t offset = int64_t(pop64(code, self.r[Reg_IP].u64)); if (self.cmp == Core::CMP_LESS || self.cmp == Core::CMP_EQUAL) { self.r[Reg_IP].u64 += offset; } break; } case Op_JG: { int64_t offset = int64_t(pop64(code, self.r[Reg_IP].u64)); if (self.cmp == Core::CMP_GREATER) { self.r[Reg_IP].u64 += offset; } break; } case Op_JGE: { int64_t offset = int64_t(pop64(code, self.r[Reg_IP].u64)); if (self.cmp == Core::CMP_GREATER || self.cmp == Core::CMP_EQUAL) { self.r[Reg_IP].u64 += offset; } break; } case Op_HALT: self.state = Core::STATE_HALT; break; case Op_IGL: default: self.state = Core::STATE_ERR; break; } } }
19.882353
68
0.583483
lordadamson
cc5f0159c6737950cf8497fcaf3281e8eca65677
93
cpp
C++
CsCoreDEPRECATED/Source/CsCoreDEPRECATED/AI/CsTypes_AI.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
2
2019-03-17T10:43:53.000Z
2021-04-20T21:24:19.000Z
CsCoreDEPRECATED/Source/CsCoreDEPRECATED/AI/CsTypes_AI.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
null
null
null
CsCoreDEPRECATED/Source/CsCoreDEPRECATED/AI/CsTypes_AI.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
null
null
null
// Copyright 2017-2019 Closed Sum Games, LLC. All Rights Reserved. #include "AI/CsTypes_AI.h"
46.5
66
0.763441
closedsum
cc644814ced864e55f84434873e4d5590205f56e
7,856
cc
C++
chapter-casa/exp-6/main.cc
Mark1626/road-to-plus-plus
500db757051e32e6ccd144b70171c826527610d4
[ "CC0-1.0" ]
1
2021-07-04T12:41:16.000Z
2021-07-04T12:41:16.000Z
chapter-casa/exp-6/main.cc
Mark1626/road-to-plus-plus
500db757051e32e6ccd144b70171c826527610d4
[ "CC0-1.0" ]
null
null
null
chapter-casa/exp-6/main.cc
Mark1626/road-to-plus-plus
500db757051e32e6ccd144b70171c826527610d4
[ "CC0-1.0" ]
null
null
null
#include <casacore/casa/Arrays/IPosition.h> #include <casacore/casa/Arrays/Matrix.h> #include <casacore/casa/Containers/Record.h> #include <casacore/casa/Quanta/MVTime.h> #include <casacore/coordinates/Coordinates/Coordinate.h> #include <casacore/coordinates/Coordinates/CoordinateSystem.h> #include <casacore/coordinates/Coordinates/DirectionCoordinate.h> #include <casacore/fits/FITS/FITSDateUtil.h> #include <casacore/fits/FITS/FITSKeywordUtil.h> #include <casacore/fits/FITS/FITSReader.h> #include <casacore/fits/FITS/fits.h> #include <casacore/measures/Measures/MDirection.h> #include <fitsio.h> #include <fstream> #include <longnam.h> #include <stdexcept> #include <string> namespace casa = casacore; class FITSImageW { static const int BITPIX = -32; float minPix; float maxPix; casa::FitsKeywordList keywordList; std::string name; casa::IPosition shape; public: FITSImageW(std::string name, casa::IPosition shape) : name(name), shape(shape) {} bool create(casa::CoordinateSystem csys) { std::ofstream outfile(name); if (!outfile.is_open()) { throw std::runtime_error("Unable to create file"); } auto ndim = shape.nelements(); casa::Record header; casa::Double b_scale, b_zero; // if (BITPIX == -32) { b_scale = 1.0; b_zero = 0.0; header.define("bitpix", BITPIX); header.setComment("bitpix", "Floating point (32 bit)"); // } casa::Vector<casa::Int> naxis(ndim); for (int i = 0; i < ndim; i++) naxis(i) = shape(i); header.define("naxis", naxis); header.define("bscale", b_scale); header.setComment("bscale", "PHYSICAL = PIXEL * BSCALE + BZERO"); header.define("bzero", b_zero); header.define("COMMENT1", ""); header.define("BUNIT", "Jy"); header.setComment("BUNIT", "Brightness (pixel) unit"); casa::IPosition shapeCpy = shape; casa::CoordinateSystem wcs_copy = csys; casa::Record saveHeader(header); bool res = wcs_copy.toFITSHeader(header, shapeCpy, casa::True); // if (!res) { // } if (naxis.nelements() != shapeCpy.nelements()) { naxis.resize(shapeCpy.nelements()); for (int idx = 0; idx < shapeCpy.nelements(); idx++) naxis(idx) = shapeCpy(idx); header.define("NAXIS", naxis); } casa::String date, timesys; casa::Time nowtime; casa::MVTime now(nowtime); casa::FITSDateUtil::toFITS(date, timesys, now); header.define("date", date); header.setComment("date", "Date FITS file was created"); if (!header.isDefined("timesys") && !header.isDefined("TIMESYS")) { header.define("timesys", timesys); header.setComment("timesys", "Time system for HDU"); } header.define("ORIGIN", "Simulation"); keywordList = casa::FITSKeywordUtil::makeKeywordList(); casa::FITSKeywordUtil::addKeywords(keywordList, header); keywordList.end(); keywordList.first(); keywordList.next(); casa::FitsKeyCardTranslator keycard; const size_t card_size = 2880 * 4; char cards[card_size]; memset(cards, 0, sizeof(cards)); while (keycard.build(cards, keywordList)) { outfile << cards; memset(cards, 0, sizeof(cards)); } if (cards[0] != 0) { outfile << cards; } return true; } static void wrapError(int code, int &status) { if (code) { char status_str[FLEN_STATUS]; fits_get_errstatus(status, status_str); throw std::runtime_error("Error " + std::string(status_str) + " " + std::to_string(status)); } } void setUnits(const std::string &units) { fitsfile *fptr; int status = 0; wrapError(fits_open_file(&fptr, name.c_str(), READWRITE, &status), status); wrapError(fits_update_key(fptr, TSTRING, "BUNIT", (void *)(units.c_str()), "Brightness unit", &status), status); wrapError(fits_close_file(fptr, &status), status); } void setRestoringBeam(double bmaj, double bmin, double bpa) { fitsfile *fptr; int status = 0; double radtodeg = 180.0 / M_PI; wrapError(fits_open_file(&fptr, name.c_str(), READWRITE, &status), status); double value = radtodeg * bmaj; wrapError(fits_update_key(fptr, TDOUBLE, "BMAJ", &value, "Restoring beam major axis", &status), status); value = radtodeg * bmin; wrapError(fits_update_key(fptr, TDOUBLE, "BMIN", &value, "Restoring beam minor axis", &status), status); value = radtodeg * bpa; wrapError(fits_update_key(fptr, TDOUBLE, "BPA", &value, "Restoring beam position angle", &status), status); wrapError(fits_update_key(fptr, TSTRING, "BTYPE", (void *)"Intensity", " ", &status), status); wrapError(fits_close_file(fptr, &status), status); } bool write(casa::Array<float> &arr, casa::IPosition &where) { fitsfile *fptr; int status = 0; double radtodeg = 180.0 / M_PI; wrapError(fits_open_file(&fptr, name.c_str(), READWRITE, &status), status); int hdutype; wrapError(fits_movabs_hdu(fptr, 1, &hdutype, &status), status); int naxis; wrapError(fits_movabs_hdu(fptr, 1, &hdutype, &status), status); wrapError(fits_get_img_dim(fptr, &naxis, &status), status); long *axes = new long[naxis]; wrapError(fits_get_img_size(fptr, naxis, axes, &status), status); long fpixel[4], lpixel[4]; int array_dim = arr.shape().nelements(); int location_dim = where.nelements(); fpixel[0] = where[0] + 1; lpixel[0] = where[0] + arr.shape()[0]; fpixel[1] = where[1] + 1; lpixel[1] = where[1] + arr.shape()[1]; if (array_dim == 2 && location_dim >= 3) { fpixel[2] = where[2] + 1; lpixel[2] = where[2] + 1; if (location_dim == 4) { fpixel[3] = where[3] + 1; lpixel[3] = where[3] + 1; } } else if (array_dim == 3 && location_dim >= 3) { fpixel[2] = where[2] + 1; lpixel[2] = where[2] + arr.shape()[2]; if (location_dim == 4) { fpixel[3] = where[3] + 1; lpixel[3] = where[3] + 1; } } else if (array_dim == 4 && location_dim == 4) { fpixel[2] = where[2] + 1; lpixel[2] = where[2] + arr.shape()[2]; fpixel[3] = where[3] + 1; lpixel[3] = where[3] + arr.shape()[3]; } int64_t nelements = arr.nelements(); bool toDelete = false; const float *data = arr.getStorage(toDelete); float *dataptr = (float *)data; long group = 0; wrapError(fits_write_subset_flt(fptr, group, naxis, axes, fpixel, lpixel, dataptr, &status), status); wrapError(fits_close_file(fptr, &status), status); delete[] axes; return true; } }; int main() { std::string name = "dummy.fits"; int xsize = 128; int ysize = 128; casa::IPosition shape(2, xsize, ysize); casa::CoordinateSystem wcs; /* 1 0 0 1 */ casacore::Matrix<double> xform(2, 2); xform = 0.0; xform.diagonal() = 1.0; casa::DirectionCoordinate direction( casa::MDirection::J2000, casa::Projection(casa::Projection::SIN), 294 * casa::C::pi / 180.0, -60 * casa::C::pi / 180, -0.001 * casa::C::pi / 180.0, 0.001 * casa::C::pi / 180.0, xform, xsize / 2.0, ysize / 2.0); casa::Vector<casa::String> units(2); units = "deg"; direction.setWorldAxisUnits(units); wcs.addCoordinate(direction); casa::Matrix<casa::Float> pixels(xsize, ysize); pixels = 0.0; pixels.diagonal() = 0.001; pixels.diagonal(2) = 0.002; casa::IPosition where(2, 0, 0); FITSImageW fits(name, shape); fits.create(wcs); fits.setUnits("Jy/pixel"); fits.setRestoringBeam(2.0e-4, 1.0e-4, 1.0e-1); fits.write(pixels, where); }
28.671533
79
0.60998
Mark1626
cc7017dda9b6c5b938f6d22364ea0d0ab6dbd4a6
44,110
cpp
C++
unittest/obproxy/test_event_processor.cpp
stutiredboy/obproxy
b5f98a6e1c45e6a878376df49b9c10b4249d3626
[ "Apache-2.0" ]
74
2021-05-31T15:23:49.000Z
2022-03-12T04:46:39.000Z
unittest/obproxy/test_event_processor.cpp
stutiredboy/obproxy
b5f98a6e1c45e6a878376df49b9c10b4249d3626
[ "Apache-2.0" ]
16
2021-05-31T15:26:38.000Z
2022-03-30T06:02:43.000Z
unittest/obproxy/test_event_processor.cpp
stutiredboy/obproxy
b5f98a6e1c45e6a878376df49b9c10b4249d3626
[ "Apache-2.0" ]
64
2021-05-31T15:25:36.000Z
2022-02-23T08:43:58.000Z
/** * Copyright (c) 2021 OceanBase * OceanBase Database Proxy(ODP) is licensed under Mulan PubL v2. * You can use this software according to the terms and conditions of the Mulan PubL v2. * You may obtain a copy of Mulan PubL v2 at: * http://license.coscl.org.cn/MulanPubL-2.0 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PubL v2 for more details. */ #define USING_LOG_PREFIX PROXY_EVENT #define private public #define protected public #include <gtest/gtest.h> #include <pthread.h> #include "test_eventsystem_api.h" namespace oceanbase { namespace obproxy { using namespace proxy; using namespace common; using namespace event; #define TEST_SPAWN_THREADS_NUM 1 #define TEST_DEFAULT_NEXT_THREAD 0 #define TEST_DEFAULT_DTHREAD_NUM 0 #define TEST_ET_SPAWN (ET_CALL + 1) #define OB_ALIGN(size, boundary) (((size) + ((boundary) - 1)) & ~((boundary) - 1)) #define INVALID_SPAWN_EVENT_THREADS(...) \ { \ ASSERT_TRUE(OB_INVALID_ARGUMENT == g_event_processor.spawn_event_threads(__VA_ARGS__));\ } #define NULL_SCHEDULE_IMM(...) \ { \ ASSERT_TRUE(NULL == g_event_processor.schedule_imm(__VA_ARGS__)); \ } #define NULL_SCHEDULE_AT(...) \ { \ ASSERT_TRUE(NULL == g_event_processor.schedule_at(__VA_ARGS__)); \ } #define NULL_SCHEDULE_IN(...) \ { \ ASSERT_TRUE(NULL == g_event_processor.schedule_in(__VA_ARGS__)); \ } #define NULL_SCHEDULE_EVERY(...) \ { \ ASSERT_TRUE(NULL == g_event_processor.schedule_every(__VA_ARGS__)); \ } #define NULL_SCHEDULE_IMM_SIGNAL(...) \ { \ ASSERT_TRUE(NULL == g_event_processor.schedule_imm_signal(__VA_ARGS__)); \ } #define NULL_SCHEDULE(...) \ { \ ASSERT_TRUE(NULL == g_event_processor.schedule(__VA_ARGS__)->ethread_); \ } #define NULL_PREPARE_SCHEDULE_IMM(...) \ { \ ASSERT_TRUE(NULL == g_event_processor.prepare_schedule_imm(__VA_ARGS__)); \ } enum TestProcessorFuncType { TEST_NULL = 0, TEST_SCHEDULE_IMM = 1, TEST_SCHEDULE_IMM_SIGNAL, TEST_SCHEDULE_AT, TEST_SCHEDULE_IN , TEST_SCHEDULE_EVERY, TEST_PREPARE_SCHEDULE_IMM, TEST_DO_SCHEDULE, TEST_SCHEDULE, TEST_SPAWN_THREAD }; unsigned int next_thread[2] = {TEST_DEFAULT_NEXT_THREAD, TEST_DEFAULT_NEXT_THREAD}; unsigned int event_thread_count[2] = {TEST_ET_CALL_THREADS_NUM, TEST_SPAWN_THREADS_NUM}; unsigned int event_type_count = 0; int64_t dthread_num = TEST_DEFAULT_DTHREAD_NUM; int handle_schedule_test(ObContInternal *contp, ObEventType event, void *edata); void *thread_main_start_test(void *func_param); void set_fast_signal_true(TestFuncParam *param); class TestEventProcessor : public ::testing::Test { public: virtual void SetUp(); virtual void TearDown(); static void check_start(TestFuncParam *param); static void check_spawn_event_threads(TestFuncParam *param); static void check_schedule_common(TestFuncParam *param); static void check_schedule_imm(TestFuncParam *param); static void check_schedule_imm_signal(TestFuncParam *param); static void check_schedule_at(TestFuncParam *param); static void check_schedule_in(TestFuncParam *param); static void check_schedule_every(TestFuncParam *param); static void check_schedule(TestFuncParam *param); static void check_prepare_schedule_imm(TestFuncParam *param); static void check_do_schedule(TestFuncParam *param); static void check_allocate(TestFuncParam *param); static void check_assign_thread(TestFuncParam *param); static void check_spawn_thread(TestFuncParam *param); public: TestFuncParam *test_param[MAX_PARAM_ARRAY_SIZE]; }; void TestEventProcessor::SetUp() { for (int i = 0; i < MAX_PARAM_ARRAY_SIZE; ++i) { test_param[i] = NULL; } } void TestEventProcessor::TearDown() { for (int i = 0; i < MAX_PARAM_ARRAY_SIZE; ++i) { if (NULL != test_param[i]) { destroy_funcparam_test(test_param[i]); } else {} } } void TestEventProcessor::check_start(TestFuncParam *param) { init_event_system(EVENT_SYSTEM_MODULE_VERSION); ASSERT_EQ(0, g_event_processor.event_thread_count_); ASSERT_EQ(0, g_event_processor.thread_group_count_); ASSERT_EQ(0, g_event_processor.dedicate_thread_count_); ASSERT_EQ(0, g_event_processor.thread_data_used_); ASSERT_FALSE(g_event_processor.started_); for (int i = 0; i < MAX_EVENT_TYPES; ++i) { ASSERT_EQ(0, g_event_processor.thread_count_for_type_[i]); ASSERT_EQ(0U, g_event_processor.next_thread_for_type_[i]); for (int64_t j = 0; j < MAX_THREADS_IN_EACH_TYPE; ++j) { ASSERT_TRUE(NULL == g_event_processor.event_thread_[i][j]); } } for (int64_t i = 0; i < MAX_EVENT_THREADS; ++i) { ASSERT_TRUE(NULL == g_event_processor.all_event_threads_[i]); ASSERT_TRUE(NULL == g_event_processor.all_dedicate_threads_[i]); } ASSERT_EQ(OB_INVALID_ARGUMENT, g_event_processor.start(-100)); ASSERT_EQ(OB_INVALID_ARGUMENT, g_event_processor.start(-1)); ASSERT_EQ(OB_INVALID_ARGUMENT, g_event_processor.start(0)); ASSERT_EQ(OB_INVALID_ARGUMENT, g_event_processor.start(MAX_EVENT_THREADS + 1)); ASSERT_EQ(OB_INVALID_ARGUMENT, g_event_processor.start(MAX_EVENT_THREADS + 100)); ASSERT_EQ(OB_INVALID_ARGUMENT, g_event_processor.start(1, -100)); ASSERT_EQ(OB_INVALID_ARGUMENT, g_event_processor.start(1, -1)); ASSERT_EQ(OB_SUCCESS, g_event_processor.start(TEST_ET_CALL_THREADS_NUM, DEFAULT_STACKSIZE, false, false)); ASSERT_EQ(OB_INIT_TWICE, g_event_processor.start(MAX_EVENT_THREADS)); ASSERT_EQ(OB_INIT_TWICE, g_event_processor.start(0)); ASSERT_EQ(OB_INIT_TWICE, g_event_processor.start(-1)); ASSERT_EQ(OB_INIT_TWICE, g_event_processor.start(-1, 0)); ASSERT_EQ(TEST_ET_CALL_THREADS_NUM, g_event_processor.event_thread_count_); ASSERT_EQ(TEST_ET_CALL_THREADS_NUM, g_event_processor.thread_count_for_type_[ET_CALL]); ASSERT_EQ(1, g_event_processor.thread_group_count_); ASSERT_EQ(0, g_event_processor.dedicate_thread_count_); ASSERT_TRUE(g_event_processor.started_); for (int64_t i = 0; i < TEST_ET_CALL_THREADS_NUM; ++i) { ASSERT_TRUE(g_event_processor.all_event_threads_[i] != NULL); ASSERT_TRUE(g_event_processor.event_thread_[ET_CALL][i] == g_event_processor.all_event_threads_[i]); ASSERT_TRUE(REGULAR == g_event_processor.all_event_threads_[i]->tt_); ASSERT_TRUE(g_event_processor.all_event_threads_[i]->is_event_thread_type(ET_CALL)); } next_thread[ET_CALL] = TEST_DEFAULT_NEXT_THREAD; ++event_type_count; param->test_ok_ = true; } void TestEventProcessor::check_spawn_event_threads(TestFuncParam *param) { int64_t stacksize = DEFAULT_STACKSIZE; ObEventThreadType etype = 0; char thr_name[MAX_THREAD_NAME_LENGTH]; snprintf(thr_name, MAX_THREAD_NAME_LENGTH, "[T_ET_SPAWN]"); char *thr_null = NULL; INVALID_SPAWN_EVENT_THREADS(-100, thr_name, stacksize, etype); INVALID_SPAWN_EVENT_THREADS(-1, thr_name, stacksize, etype); INVALID_SPAWN_EVENT_THREADS(0, thr_name, stacksize, etype); INVALID_SPAWN_EVENT_THREADS(MAX_EVENT_THREADS - TEST_ET_CALL_THREADS_NUM + 1, thr_name, stacksize, etype); int64_t thread_group_count = g_event_processor.thread_group_count_;//save g_event_processor.thread_group_count_ = MAX_EVENT_TYPES;//update error key INVALID_SPAWN_EVENT_THREADS(TEST_SPAWN_THREADS_NUM, thr_name, stacksize, etype); g_event_processor.thread_group_count_ = MAX_EVENT_TYPES + 1;//update error key INVALID_SPAWN_EVENT_THREADS(TEST_SPAWN_THREADS_NUM, thr_name, stacksize, etype); g_event_processor.thread_group_count_ = thread_group_count;//reset INVALID_SPAWN_EVENT_THREADS(TEST_SPAWN_THREADS_NUM, thr_null, stacksize, etype); INVALID_SPAWN_EVENT_THREADS(TEST_SPAWN_THREADS_NUM, thr_name, -100, etype); INVALID_SPAWN_EVENT_THREADS(TEST_SPAWN_THREADS_NUM, thr_name, -1, etype); ASSERT_TRUE(OB_SUCCESS == g_event_processor.spawn_event_threads(TEST_SPAWN_THREADS_NUM, thr_name, stacksize, etype)); ASSERT_EQ(TEST_ET_SPAWN, etype); ASSERT_EQ(2, g_event_processor.thread_group_count_); ASSERT_EQ(TEST_SPAWN_THREADS_NUM, g_event_processor.thread_count_for_type_[TEST_ET_SPAWN]); int64_t tmp_n = g_event_processor.event_thread_count_ - TEST_SPAWN_THREADS_NUM; for (int64_t i = tmp_n; i < g_event_processor.event_thread_count_; ++i) { ASSERT_TRUE(NULL != g_event_processor.all_event_threads_[i]); ASSERT_TRUE(g_event_processor.event_thread_[TEST_ET_SPAWN][i - tmp_n] == g_event_processor.all_event_threads_[i]); ASSERT_TRUE(REGULAR == g_event_processor.all_event_threads_[i]->tt_); ASSERT_TRUE(g_event_processor.all_event_threads_[i]->is_event_thread_type(TEST_ET_SPAWN)); } next_thread[TEST_ET_SPAWN] = TEST_DEFAULT_NEXT_THREAD; ++event_type_count; param->test_ok_ = true; } void TestEventProcessor::check_schedule_common(TestFuncParam *param) { ASSERT_EQ(param->callback_event_, param->event_->callback_event_); ASSERT_TRUE(param->cookie_ == param->event_->cookie_); ASSERT_TRUE(param->cont_ == param->event_->continuation_); ASSERT_FALSE(param->event_->cancelled_); ASSERT_TRUE(param->event_->continuation_->mutex_ == param->event_->mutex_); if (event_thread_count[param->event_type_] > 1) ASSERT_EQ(++next_thread[param->event_type_], g_event_processor.next_thread_for_type_[param->event_type_]); else { ASSERT_EQ(0U, g_event_processor.next_thread_for_type_[param->event_type_]); } } void TestEventProcessor::check_schedule_imm(TestFuncParam *param) { if (!param->started_) { param->started_ = true; param->func_type_ = TEST_SCHEDULE_IMM; param->cookie_ = param; param->callback_event_ = EVENT_IMMEDIATE; ObContinuation *cont_null = NULL; NULL_SCHEDULE_IMM(cont_null, param->event_type_, param->callback_event_, param->cookie_); NULL_SCHEDULE_IMM(param->cont_, MAX_EVENT_TYPES, param->callback_event_, param->cookie_); NULL_SCHEDULE_IMM(param->cont_, MAX_EVENT_TYPES + 1, param->callback_event_, param->cookie_); NULL_SCHEDULE_IMM(param->cont_, -10, param->callback_event_, param->cookie_); NULL_SCHEDULE_IMM(param->cont_, -1, param->callback_event_, param->cookie_); NULL_SCHEDULE_IMM(param->cont_, event_type_count + 1, param->callback_event_, param->cookie_); ((ObContInternal *)param->cont_)->event_count_++; param->last_time_ = get_hrtime_internal(); param->event_ = g_event_processor.schedule_imm(param->cont_, param->event_type_, param->callback_event_, param->cookie_); ASSERT_TRUE(NULL != param->event_); } else { check_schedule_common(param); ASSERT_EQ(0, param->event_->timeout_at_); ASSERT_EQ(0, param->event_->period_); param->test_ok_ = check_imm_test_ok(hrtime_diff(param->cur_time_, param->last_time_)); } } void TestEventProcessor::check_schedule_at(TestFuncParam *param) { if (!param->started_) { param->started_ = true; param->func_type_ = TEST_SCHEDULE_AT; param->cookie_ = param; param->callback_event_ = EVENT_INTERVAL; param->atimeout_ = TEST_TIME_SECOND_AT(param); ObContinuation *cont_null = NULL; NULL_SCHEDULE_AT(cont_null, param->atimeout_, param->event_type_, param->callback_event_, param->cookie_); NULL_SCHEDULE_AT(param->cont_, param->atimeout_, MAX_EVENT_TYPES, param->callback_event_, param->cookie_); NULL_SCHEDULE_AT(param->cont_, param->atimeout_, MAX_EVENT_TYPES + 1, param->callback_event_, param->cookie_); NULL_SCHEDULE_AT(param->cont_, param->atimeout_, -10, param->callback_event_, param->cookie_); NULL_SCHEDULE_AT(param->cont_, param->atimeout_, -1, param->callback_event_, param->cookie_); NULL_SCHEDULE_AT(param->cont_, param->atimeout_, event_type_count + 1, param->callback_event_, param->cookie_); NULL_SCHEDULE_AT(param->cont_, HRTIME_SECONDS(0), param->event_type_, param->callback_event_, param->cookie_); NULL_SCHEDULE_AT(param->cont_, HRTIME_SECONDS(-1), param->event_type_, param->callback_event_, param->cookie_); ((ObContInternal *)param->cont_)->event_count_++; param->last_time_ = get_hrtime_internal(); param->event_ = g_event_processor.schedule_at(param->cont_, param->atimeout_, param->event_type_, param->callback_event_, param->cookie_); ASSERT_TRUE(NULL != param->event_); ASSERT_TRUE(param->at_delta_ > 0 ? 1 == param->event_->in_the_prot_queue_ : true); } else { check_schedule_common(param); ASSERT_GE(TEST_TIME_SECOND_AT(param), param->event_->timeout_at_); ASSERT_EQ(0, param->event_->period_); check_test_ok(param, param->at_delta_); // param->at_delta_ <= 0,//at the past point, equal to imm // param->at_delta_ > 0,//at the future point, equal to in } } void TestEventProcessor::check_schedule_in(TestFuncParam *param) { if (!param->started_) { param->started_ = true; param->func_type_ = TEST_SCHEDULE_IN; param->cookie_ = param; param->callback_event_ = EVENT_INTERVAL; ObContinuation *cont_null = NULL; NULL_SCHEDULE_IN(cont_null, param->atimeout_, param->event_type_, param->callback_event_, param->cookie_); NULL_SCHEDULE_IN(param->cont_, param->atimeout_, MAX_EVENT_TYPES, param->callback_event_, param->cookie_); NULL_SCHEDULE_IN(param->cont_, param->atimeout_, MAX_EVENT_TYPES + 1, param->callback_event_, param->cookie_); NULL_SCHEDULE_IN(param->cont_, param->atimeout_, -10, param->callback_event_, param->cookie_); NULL_SCHEDULE_IN(param->cont_, param->atimeout_, -1, param->callback_event_, param->cookie_); NULL_SCHEDULE_IN(param->cont_, param->atimeout_, event_type_count + 1, param->callback_event_, param->cookie_); ((ObContInternal *)param->cont_)->event_count_++; param->last_time_ = get_hrtime_internal(); param->event_ = g_event_processor.schedule_in(param->cont_, param->atimeout_, param->event_type_, param->callback_event_, param->cookie_); ASSERT_TRUE(NULL != param->event_); ASSERT_TRUE(param->atimeout_ > 0 ? 1 == param->event_->in_the_prot_queue_ : true); if (param->event_->timeout_at_ < 0) {//drop into poll queue, can not update deletable_ ((ObContInternal *)(param->cont_))->deletable_ = true; } else {} } else { check_schedule_common(param); ASSERT_LT(param->atimeout_, param->event_->timeout_at_); ASSERT_GE(get_hrtime_internal() + param->atimeout_, param->event_->timeout_at_); ASSERT_EQ(0, param->event_->period_); check_test_ok(param, param->atimeout_); //param->atimeout_ <= 0 //in the past point,equal to imm } } void TestEventProcessor::check_schedule_every(TestFuncParam *param) { if (!param->started_) { param->started_ = true; param->func_type_ = TEST_SCHEDULE_EVERY; param->cookie_ = param; param->callback_event_ = EVENT_INTERVAL; ObContinuation *cont_null = NULL; NULL_SCHEDULE_EVERY(cont_null, param->aperiod_, param->event_type_, param->callback_event_, param->cookie_); NULL_SCHEDULE_EVERY(param->cont_, param->aperiod_, MAX_EVENT_TYPES, param->callback_event_, param->cookie_); NULL_SCHEDULE_EVERY(param->cont_, param->aperiod_, MAX_EVENT_TYPES + 1, param->callback_event_, param->cookie_); NULL_SCHEDULE_EVERY(param->cont_, param->aperiod_, -10, param->callback_event_, param->cookie_); NULL_SCHEDULE_EVERY(param->cont_, param->aperiod_, -1, param->callback_event_, param->cookie_); NULL_SCHEDULE_EVERY(param->cont_, param->aperiod_, event_type_count + 1, param->callback_event_, param->cookie_); NULL_SCHEDULE_EVERY(param->cont_, HRTIME_SECONDS(0), param->event_type_, param->callback_event_, param->cookie_); ((ObContInternal *)param->cont_)->event_count_ += TEST_DEFAULT_PERIOD_COUNT; param->last_time_ = get_hrtime_internal(); param->event_ = g_event_processor.schedule_every(param->cont_, param->aperiod_, param->event_type_, param->callback_event_, param->cookie_); ASSERT_TRUE(NULL != param->event_); ASSERT_TRUE(param->aperiod_ > 0 ? 1 == param->event_->in_the_prot_queue_ : true); if (param->aperiod_ < 0) {//drop into poll queue, can not update deletable_ ((ObContInternal *)(param->cont_))->deletable_ = true; } else {} } else { SCHEDULE_EVERY_FIRST_CHECK; param->test_ok_ = param->test_ok_ && check_test_ok(param, param->aperiod_); //param->aperiod_ < 0 ;//equal to schedule at, will fall into negative_queue } } void TestEventProcessor::check_schedule(TestFuncParam *param) { if (!param->started_) { param->started_ = true; param->func_type_ = TEST_SCHEDULE; param->callback_event_ = param->event_->callback_event_; param->cookie_ = param; param->event_->cookie_ = param; param->last_time_ = get_hrtime_internal(); param->event_ = g_event_processor.schedule(param->event_, param->event_type_, param->fast_signal_); ASSERT_TRUE(NULL != param->event_); ASSERT_TRUE(NULL != param->event_->ethread_); } else { check_schedule_result(param, check_schedule_imm, check_schedule_at, check_schedule_in, check_schedule_every); if (param->fast_signal_) { param->test_ok_ = param->test_ok_ && g_signal_hook_success; } } } void TestEventProcessor::check_schedule_imm_signal(TestFuncParam *param) { if (!param->started_) { param->started_ = true; param->func_type_ = TEST_SCHEDULE_IMM_SIGNAL; param->cookie_ = param; param->callback_event_ = EVENT_IMMEDIATE; set_fast_signal_true(param); ObContinuation *cont_null = NULL; NULL_SCHEDULE_IMM_SIGNAL(cont_null, param->event_type_, param->callback_event_, param->cookie_); NULL_SCHEDULE_IMM_SIGNAL(param->cont_, MAX_EVENT_TYPES, param->callback_event_, param->cookie_); NULL_SCHEDULE_IMM_SIGNAL(param->cont_, MAX_EVENT_TYPES + 1, param->callback_event_, param->cookie_); NULL_SCHEDULE_IMM_SIGNAL(param->cont_, -10, param->callback_event_, param->cookie_); NULL_SCHEDULE_IMM_SIGNAL(param->cont_, -1, param->callback_event_, param->cookie_); NULL_SCHEDULE_IMM_SIGNAL(param->cont_, event_type_count + 1, param->callback_event_, param->cookie_); ((ObContInternal *)param->cont_)->event_count_++; param->last_time_ = get_hrtime_internal(); param->event_ = g_event_processor.schedule_imm_signal(param->cont_, param->event_type_, param->callback_event_, param->cookie_); ASSERT_TRUE(NULL != param->event_); } else { check_schedule_imm(param); param->test_ok_ = param->test_ok_ && g_signal_hook_success; } } void TestEventProcessor::check_prepare_schedule_imm(TestFuncParam *param) { if (!param->started_) { param->started_ = true; param->func_type_ = TEST_PREPARE_SCHEDULE_IMM; param->callback_event_ = EVENT_IMMEDIATE; param->cookie_ = param; ObContinuation *cont_null = NULL; NULL_PREPARE_SCHEDULE_IMM(cont_null, param->event_type_, param->callback_event_, param->cookie_); NULL_PREPARE_SCHEDULE_IMM(param->cont_, MAX_EVENT_TYPES, param->callback_event_, param->cookie_); NULL_PREPARE_SCHEDULE_IMM(param->cont_, MAX_EVENT_TYPES + 1, param->callback_event_, param->cookie_); NULL_PREPARE_SCHEDULE_IMM(param->cont_, -10, param->callback_event_, param->cookie_); NULL_PREPARE_SCHEDULE_IMM(param->cont_, -1, param->callback_event_, param->cookie_); NULL_PREPARE_SCHEDULE_IMM(param->cont_, event_type_count + 1, param->callback_event_, param->cookie_); ((ObContInternal *)param->cont_)->event_count_++; param->last_time_ = get_hrtime_internal(); param->event_ = g_event_processor.prepare_schedule_imm(param->cont_, param->event_type_, param->callback_event_, param->cookie_); ASSERT_TRUE(NULL != param->event_); param->event_->ethread_->event_queue_external_.enqueue(param->event_); } else { check_schedule_imm(param); } } void TestEventProcessor::check_do_schedule(TestFuncParam *param) { if (!param->started_) { param->started_ = true; param->func_type_ = TEST_DO_SCHEDULE; param->callback_event_ = param->event_->callback_event_; param->cookie_ = param; param->event_->cookie_ = param; ObEvent *event_null = NULL; g_event_processor.do_schedule(event_null, param->fast_signal_); param->last_time_ = get_hrtime_internal(); g_event_processor.do_schedule(param->event_, param->fast_signal_); } else { check_schedule(param); } } void TestEventProcessor::check_allocate(TestFuncParam *param) { int64_t start = OB_ALIGN(offsetof(ObEThread, thread_private_), 16); int64_t old = g_event_processor.thread_data_used_; int64_t loss = start - offsetof(ObEThread, thread_private_); ASSERT_TRUE(-1 == g_event_processor.allocate(-10)); ASSERT_TRUE((old + start) == g_event_processor.allocate(0)); ASSERT_TRUE(-1 == g_event_processor.allocate(ObEThread::MAX_THREAD_DATA_SIZE - old - loss + 1)); ASSERT_TRUE((start + old) == g_event_processor.allocate(1)); ASSERT_TRUE(g_event_processor.thread_data_used_ == old + 16); old = old + 16; ASSERT_TRUE((start + old) == g_event_processor.allocate(17)); ASSERT_TRUE(g_event_processor.thread_data_used_ == old + 32); old = old + 32; ASSERT_TRUE((start + old) == g_event_processor.allocate(16)); ASSERT_TRUE(g_event_processor.thread_data_used_ == old + 16); param->test_ok_ = true; } void TestEventProcessor::check_assign_thread(TestFuncParam *param) { ObEventThreadType event_type = ET_CALL; for (int i = 0; i < 10; ++i) { ASSERT_TRUE(NULL != g_event_processor.assign_thread(event_type)); if (g_event_processor.next_thread_for_type_[event_type] > 1) { ASSERT_EQ(g_event_processor.next_thread_for_type_[event_type], ++next_thread[event_type]); } else { ASSERT_EQ(g_event_processor.next_thread_for_type_[event_type], 0U); } } event_type = TEST_ET_SPAWN; for (int i = 0; i < 10; ++i) { ASSERT_TRUE(NULL != g_event_processor.assign_thread(event_type)); if (g_event_processor.next_thread_for_type_[event_type] > 1) { ASSERT_EQ(g_event_processor.next_thread_for_type_[event_type], ++next_thread[event_type]); } else { ASSERT_EQ(g_event_processor.next_thread_for_type_[event_type], 0U); } } param->test_ok_ = true; } void TestEventProcessor::check_spawn_thread(TestFuncParam *param) { if (!param->started_) { param->started_ = true; param->func_type_ = TEST_SPAWN_THREAD; snprintf(param->thr_name_, MAX_THREAD_NAME_LENGTH, "[T_ET_SPAWN_D]"); ((ObContInternal *)param->cont_)->event_count_++; char *thr_null = NULL; ObContinuation *cont_null = NULL; int64_t dedicate_thread_count = g_event_processor.dedicate_thread_count_; ASSERT_TRUE(NULL == g_event_processor.spawn_thread(cont_null, param->thr_name_, param->stacksize_)); g_event_processor.dedicate_thread_count_ = MAX_EVENT_THREADS; ASSERT_TRUE(NULL == g_event_processor.spawn_thread(param->cont_, param->thr_name_, param->stacksize_)); g_event_processor.dedicate_thread_count_ = MAX_EVENT_THREADS + 10; ASSERT_TRUE(NULL == g_event_processor.spawn_thread(param->cont_, param->thr_name_, param->stacksize_)); g_event_processor.dedicate_thread_count_ = dedicate_thread_count; ASSERT_TRUE(NULL == g_event_processor.spawn_thread(param->cont_, thr_null, param->stacksize_)); ASSERT_TRUE(NULL == g_event_processor.spawn_thread(param->cont_, param->thr_name_, -100)); param->last_time_ = get_hrtime_internal(); param->event_ = g_event_processor.spawn_thread(param->cont_, param->thr_name_, param->stacksize_); param->event_->cookie_ = param; ASSERT_TRUE(NULL != param->event_); } else { ASSERT_TRUE(param->cont_ == param->event_->continuation_); ASSERT_EQ(0, param->event_->timeout_at_); ASSERT_EQ(0, param->event_->period_); ASSERT_FALSE(param->event_->cancelled_); ASSERT_TRUE(param->event_->continuation_->mutex_ == param->event_->mutex_); ASSERT_TRUE(DEDICATED == g_event_processor.all_dedicate_threads_[dthread_num]->tt_); ASSERT_TRUE(++dthread_num == g_event_processor.dedicate_thread_count_); param->test_ok_ = check_imm_test_ok(hrtime_diff(param->cur_time_, param->last_time_)); } } int handle_schedule_test(ObContInternal *contp, ObEventType event, void *edata) { UNUSED(event); UNUSED(contp); TestFuncParam *param; param = static_cast<TestFuncParam *>((static_cast<ObEvent *>(edata))->cookie_); ++param->seq_no_; param->cur_time_ = get_hrtime_internal(); switch (param->func_type_) { case TEST_SCHEDULE_IMM: case TEST_PREPARE_SCHEDULE_IMM: { TestEventProcessor::check_schedule_imm(param); break; } case TEST_SCHEDULE_IN: { TestEventProcessor::check_schedule_in(param); break; } case TEST_SCHEDULE_AT: { TestEventProcessor::check_schedule_at(param); break; } case TEST_SCHEDULE_EVERY: { TestEventProcessor::check_schedule_every(param); break; } case TEST_SCHEDULE_IMM_SIGNAL: { TestEventProcessor::check_schedule_imm_signal(param); break; } case TEST_SCHEDULE: { TestEventProcessor::check_schedule(param); break; } case TEST_DO_SCHEDULE: { TestEventProcessor::check_do_schedule(param); break; } case TEST_SPAWN_THREAD: { TestEventProcessor::check_spawn_thread(param); break; } default: { LOG_ERROR("handle_schedule_test, invalid event type"); break; } } #ifdef DEBUG_TEST // print the process print_process(param->seq_no_, param->cur_time_, param->last_time_); #endif int ret = OB_ERROR; if (TEST_SCHEDULE_EVERY == param->func_type_ || (EVENT_INTERVAL == param->event_->callback_event_ && 0 != param->event_->period_)) { param->last_time_ = param->cur_time_; if (param->period_count_ > 1) { --param->period_count_; } else { ret = OB_SUCCESS; param->event_->cancelled_ = true; } } else { ret = OB_SUCCESS; } if (OB_SUCC(ret)) { signal_condition(param->wait_cond_); } return ret; } void *thread_main_start_test(void *func_param) { TestEventProcessor::check_start((TestFuncParam *)func_param); signal_condition(((TestFuncParam *)func_param)->wait_cond_); this_ethread()->execute(); return NULL; } void set_fast_signal_true(TestFuncParam *param) { int next = 0; param->fast_signal_ = true; g_signal_hook_success = false; if (event_thread_count[param->event_type_] > 1) { next = next_thread[param->event_type_] % event_thread_count[param->event_type_]; } else { next = 0; } ObEThread *tmp_ethread = g_event_processor.event_thread_[param->event_type_][next]; tmp_ethread->signal_hook_ = handle_hook_test; } TEST_F(TestEventProcessor, eventprocessor_start) { LOG_DEBUG("eventprocessor start"); pthread_t thread; test_param[0] = create_funcparam_test(); pthread_attr_t *attr_null = NULL; if (0 != pthread_create(&thread, attr_null, thread_main_start_test, (void *)test_param[0])) { LOG_ERROR("failed to create processor_start"); } else { wait_condition(test_param[0]->wait_cond_); ASSERT_TRUE(test_param[0]->test_ok_); } } TEST_F(TestEventProcessor, eventprocessor_spawn_event_threads) { LOG_DEBUG("eventprocessor spawn_event_threads"); test_param[0] = create_funcparam_test(); TestEventProcessor::check_spawn_event_threads(test_param[0]); ASSERT_TRUE(test_param[0]->test_ok_); } TEST_F(TestEventProcessor, eventprocessor_schedule_imm1) { LOG_DEBUG("eventprocessor schedule_imm"); test_param[0] = create_funcparam_test(true, handle_schedule_test); test_param[0]->event_type_ = ET_CALL; TestEventProcessor::check_schedule_imm(test_param[0]); wait_condition(test_param[0]->wait_cond_); ASSERT_TRUE(test_param[0]->test_ok_); } TEST_F(TestEventProcessor, eventprocessor_schedule_imm2_spawn) { LOG_DEBUG("eventprocessor schedule_imm (spawn)"); test_param[0] = create_funcparam_test(true, handle_schedule_test, new_proxy_mutex()); test_param[0]->event_type_ = TEST_ET_SPAWN; TestEventProcessor::check_schedule_imm(test_param[0]); wait_condition(test_param[0]->wait_cond_); ASSERT_TRUE(test_param[0]->test_ok_); } TEST_F(TestEventProcessor, eventprocessor_schedule_at1) { LOG_DEBUG("eventprocessor schedule_at"); test_param[0] = create_funcparam_test(true, handle_schedule_test); test_param[0]->at_delta_ = HRTIME_SECONDS(2); test_param[0]->event_type_ = ET_CALL; TestEventProcessor::check_schedule_at(test_param[0]); wait_condition(test_param[0]->wait_cond_); ASSERT_TRUE(test_param[0]->test_ok_); }; TEST_F(TestEventProcessor, eventprocessor_schedule_at2_minus_spawn) { LOG_DEBUG("eventprocessor schedule_at (-spawn)"); test_param[0] = create_funcparam_test(true, handle_schedule_test, new_proxy_mutex()); test_param[0]->at_delta_ = HRTIME_SECONDS(-2); test_param[0]->event_type_ = TEST_ET_SPAWN; TestEventProcessor::check_schedule_at(test_param[0]); wait_condition(test_param[0]->wait_cond_); ASSERT_TRUE(test_param[0]->test_ok_); }; TEST_F(TestEventProcessor, eventprocessor_schedule_in1) { LOG_DEBUG("eventprocessor schedule_in"); test_param[0] = create_funcparam_test(true, handle_schedule_test); test_param[0]->event_type_ = ET_CALL; test_param[0]->atimeout_ = TEST_TIME_SECOND_IN; TestEventProcessor::check_schedule_in(test_param[0]); wait_condition(test_param[0]->wait_cond_); ASSERT_TRUE(test_param[0]->test_ok_); }; TEST_F(TestEventProcessor, eventprocessor_schedule_in2_minus_spawn) { LOG_DEBUG("eventprocessor schedule_in (-spawn)"); test_param[0] = create_funcparam_test(true, handle_schedule_test, new_proxy_mutex()); test_param[0]->event_type_ = TEST_ET_SPAWN; test_param[0]->atimeout_ = 0 - TEST_TIME_SECOND_IN; TestEventProcessor::check_schedule_in(test_param[0]); wait_condition(test_param[0]->wait_cond_); ASSERT_TRUE(test_param[0]->test_ok_); }; TEST_F(TestEventProcessor, eventprocessor_schedule_in3_minus_negative_queue) { LOG_DEBUG("eventprocessor schedule_in (-negative_queue)"); test_param[0] = create_funcparam_test(true, handle_schedule_test); test_param[0]->event_type_ = ET_CALL; test_param[0]->atimeout_ = 0 - TEST_TIME_SECOND_IN - get_hrtime_internal(); TestEventProcessor::check_schedule_in(test_param[0]); wait_condition(test_param[0]->wait_cond_); ASSERT_TRUE(test_param[0]->test_ok_); }; TEST_F(TestEventProcessor, eventprocessor_schedule_every1) { LOG_DEBUG("eventprocessor schedule_every"); test_param[0] = create_funcparam_test(true, handle_schedule_test); test_param[0]->event_type_ = ET_CALL; test_param[0]->aperiod_ = TEST_TIME_SECOND_EVERY; TestEventProcessor::check_schedule_every(test_param[0]); wait_condition(test_param[0]->wait_cond_); ASSERT_TRUE(test_param[0]->test_ok_); }; TEST_F(TestEventProcessor, eventprocessor_schedule_every2_minus_spawn_negative_queue) { LOG_DEBUG("eventprocessor schedule_every (-spawn negative_queue)"); test_param[0] = create_funcparam_test(true, handle_schedule_test, new_proxy_mutex()); test_param[0]->event_type_ = TEST_ET_SPAWN; test_param[0]->aperiod_ = 0 - TEST_TIME_SECOND_EVERY; TestEventProcessor::check_schedule_every(test_param[0]); wait_condition(test_param[0]->wait_cond_); ASSERT_TRUE(test_param[0]->test_ok_); }; TEST_F(TestEventProcessor, eventprocessor_schedule1_in) { LOG_DEBUG("eventprocessor schedule (ET_CALL in)"); test_param[0] = create_funcparam_test(true, handle_schedule_test, new_proxy_mutex()); ASSERT_TRUE(NULL != test_param[0]->cont_->mutex_); if (NULL == (test_param[0]->event_ = op_reclaim_alloc(ObEvent))) { LOG_ERROR("fail to alloc mem for processor_schedule test"); } else { test_param[0]->event_type_ = ET_CALL; test_param[0]->event_->callback_event_ = EVENT_INTERVAL; test_param[0]->atimeout_ = TEST_TIME_SECOND_IN; ASSERT_EQ(common::OB_SUCCESS, test_param[0]->event_->init(*test_param[0]->cont_, get_hrtime_internal() + test_param[0]->atimeout_, 0)); ASSERT_TRUE(test_param[0]->event_->is_inited_); test_param[0]->fast_signal_ = false; ((ObContInternal *)test_param[0]->cont_)->event_count_++; TestEventProcessor::check_schedule(test_param[0]); wait_condition(test_param[0]->wait_cond_); ASSERT_TRUE(test_param[0]->test_ok_); } }; TEST_F(TestEventProcessor, eventprocessor_schedule2_at) { LOG_DEBUG("eventprocessor schedule (spawn at)"); test_param[0] = create_funcparam_test(true, handle_schedule_test); if (NULL == (test_param[0]->event_ = op_reclaim_alloc(ObEvent))) { LOG_ERROR("fail to alloc mem for processor_schedule test"); } else { test_param[0]->event_type_ = TEST_ET_SPAWN; test_param[0]->event_->callback_event_ = EVENT_INTERVAL; test_param[0]->at_delta_ = HRTIME_SECONDS(2); test_param[0]->atimeout_ = TEST_TIME_SECOND_AT(test_param[0]); ASSERT_EQ(common::OB_SUCCESS, test_param[0]->event_->init(*test_param[0]->cont_, test_param[0]->atimeout_, 0)); ASSERT_TRUE(test_param[0]->event_->is_inited_); ((ObContInternal *)test_param[0]->cont_)->event_count_++; set_fast_signal_true(test_param[0]); TestEventProcessor::check_schedule(test_param[0]); wait_condition(test_param[0]->wait_cond_); ASSERT_TRUE(test_param[0]->test_ok_); } }; TEST_F(TestEventProcessor, eventprocessor_schedule_imm_signal1) { LOG_DEBUG("eventprocessor schedule_imm_signal"); test_param[0] = create_funcparam_test(true, handle_schedule_test); test_param[0]->event_type_ = ET_CALL; TestEventProcessor::check_schedule_imm_signal(test_param[0]); wait_condition(test_param[0]->wait_cond_); ASSERT_TRUE(test_param[0]->test_ok_); }; TEST_F(TestEventProcessor, eventprocessor_schedule_imm_signal2_spawn) { LOG_DEBUG("eventprocessor schedule_imm_signal (spawn)"); test_param[0] = create_funcparam_test(true, handle_schedule_test, new_proxy_mutex()); test_param[0]->event_type_ = TEST_ET_SPAWN; TestEventProcessor::check_schedule_imm_signal(test_param[0]); wait_condition(test_param[0]->wait_cond_); ASSERT_TRUE(test_param[0]->test_ok_); }; TEST_F(TestEventProcessor, eventprocessor_prepare_schedule_imm1) { LOG_DEBUG("eventprocessor prepare_schedule_imm"); test_param[0] = create_funcparam_test(true, handle_schedule_test); test_param[0]->event_type_ = ET_CALL; TestEventProcessor::check_prepare_schedule_imm(test_param[0]); wait_condition(test_param[0]->wait_cond_); ASSERT_TRUE(test_param[0]->test_ok_); }; TEST_F(TestEventProcessor, eventprocessor_prepare_schedule_imm2_spawn) { LOG_DEBUG("eventprocessor prepare_schedule_imm (spawn)"); test_param[0] = create_funcparam_test(true, handle_schedule_test, new_proxy_mutex()); test_param[0]->event_type_ = TEST_ET_SPAWN; TestEventProcessor::check_prepare_schedule_imm(test_param[0]); wait_condition(test_param[0]->wait_cond_); ASSERT_TRUE(test_param[0]->test_ok_); }; TEST_F(TestEventProcessor, eventprocessor_do_schedule1_every) { LOG_DEBUG("eventprocessor do_schedule (ET_CALL every)"); test_param[0] = create_funcparam_test(true, handle_schedule_test); // test_param[0]->func_type_ = TEST_DO_SCHEDULE; if (NULL == (test_param[0]->event_ = op_reclaim_alloc(ObEvent))) { LOG_ERROR("fail to alloc mem for do_schedule"); } else { test_param[0]->event_->callback_event_ = EVENT_INTERVAL; test_param[0]->aperiod_ = TEST_TIME_SECOND_EVERY; ((ObContInternal *)test_param[0]->cont_)->event_count_ += TEST_DEFAULT_PERIOD_COUNT; ASSERT_EQ(common::OB_SUCCESS, test_param[0]->event_->init(*test_param[0]->cont_, get_hrtime_internal() + test_param[0]->aperiod_, test_param[0]->aperiod_)); ASSERT_TRUE(test_param[0]->event_->is_inited_); test_param[0]->event_type_ = ET_CALL; test_param[0]->event_->ethread_ = g_event_processor.assign_thread( test_param[0]->event_type_); if (NULL != test_param[0]->event_->continuation_->mutex_) { test_param[0]->event_->mutex_ = test_param[0]->event_->continuation_->mutex_; } else { test_param[0]->event_->continuation_->mutex_ = test_param[0]->event_->ethread_->mutex_; test_param[0]->event_->mutex_ = test_param[0]->event_->continuation_->mutex_; } TestEventProcessor::check_do_schedule(test_param[0]); wait_condition(test_param[0]->wait_cond_); ASSERT_TRUE(test_param[0]->test_ok_); } }; TEST_F(TestEventProcessor, eventprocessor_do_schedule2_minus_every) { LOG_DEBUG("eventprocessor do_schedule (spawn every-)"); test_param[0] = create_funcparam_test(true, handle_schedule_test, new_proxy_mutex()); ASSERT_TRUE(NULL != test_param[0]->cont_->mutex_); if (NULL == (test_param[0]->event_ = op_reclaim_alloc(ObEvent))) { LOG_ERROR("fail to alloc mem for do_schedule"); } else { test_param[0]->event_->callback_event_ = EVENT_INTERVAL; test_param[0]->aperiod_ = 0 - TEST_TIME_SECOND_EVERY; ((ObContInternal *)test_param[0]->cont_)->event_count_ += TEST_DEFAULT_PERIOD_COUNT; ASSERT_EQ(common::OB_SUCCESS, test_param[0]->event_->init(*test_param[0]->cont_, test_param[0]->aperiod_, test_param[0]->aperiod_)); ASSERT_TRUE(test_param[0]->event_->is_inited_); test_param[0]->event_type_ = TEST_ET_SPAWN; test_param[0]->event_->ethread_ = g_event_processor.assign_thread( test_param[0]->event_type_); if (NULL != test_param[0]->event_->continuation_->mutex_) { test_param[0]->event_->mutex_ = test_param[0]->event_->continuation_->mutex_; } else { test_param[0]->event_->continuation_->mutex_ = test_param[0]->event_->ethread_->mutex_; test_param[0]->event_->mutex_ = test_param[0]->event_->continuation_->mutex_; } set_fast_signal_true(test_param[0]); ((ObContInternal *)(test_param[0]->cont_))->deletable_ = true; TestEventProcessor::check_do_schedule(test_param[0]); wait_condition(test_param[0]->wait_cond_); ASSERT_TRUE(test_param[0]->test_ok_); } }; TEST_F(TestEventProcessor, eventprocessor_assign_thread) { LOG_DEBUG("eventprocessor _assign_thread"); test_param[0] = create_funcparam_test(); TestEventProcessor::check_assign_thread(test_param[0]); ASSERT_TRUE(test_param[0]->test_ok_); }; TEST_F(TestEventProcessor, eventprocessor_allocate) { LOG_DEBUG("eventprocessor allocate"); test_param[0] = create_funcparam_test(); TestEventProcessor::check_allocate(test_param[0]); ASSERT_TRUE(test_param[0]->test_ok_); }; TEST_F(TestEventProcessor, eventprocessor_spawn_thread1_0) { LOG_DEBUG("eventprocessor spawn_thread (0)"); test_param[0] = create_funcparam_test(true, handle_schedule_test); test_param[0]->stacksize_ = 0; TestEventProcessor::check_spawn_thread(test_param[0]); wait_condition(test_param[0]->wait_cond_); ASSERT_TRUE(test_param[0]->test_ok_); }; TEST_F(TestEventProcessor, eventprocessor_spawn_thread2_default) { LOG_DEBUG("eventprocessor spawn_thread (default)"); test_param[0] = create_funcparam_test(true, handle_schedule_test, new_proxy_mutex()); test_param[0]->stacksize_ = DEFAULT_STACKSIZE; TestEventProcessor::check_spawn_thread(test_param[0]); wait_condition(test_param[0]->wait_cond_); ASSERT_TRUE(test_param[0]->test_ok_); }; TEST_F(TestEventProcessor, processor) { LOG_DEBUG("processor"); ObTasksProcessor *task_processor = NULL; test_param[0] = create_funcparam_test(); if (NULL == (test_param[0]->processor_ = new(std::nothrow) ObProcessor())) { LOG_ERROR("failed to create ObProcessor"); } else { ASSERT_TRUE(0 == test_param[0]->processor_->get_thread_count()); ASSERT_TRUE(0 == test_param[0]->processor_->start(0)); test_param[0]->processor_->shutdown(); delete test_param[0]->processor_; test_param[0]->processor_ = NULL; } if (NULL == (task_processor = new(std::nothrow) ObTasksProcessor())) { LOG_ERROR("failed to create ObTasksProcessor"); } else { test_param[0]->processor_ = static_cast<ObProcessor *>(task_processor); ASSERT_TRUE(OB_INVALID_ARGUMENT == task_processor->start(-10)); ASSERT_TRUE(OB_INVALID_ARGUMENT == task_processor->start(0)); ASSERT_TRUE(OB_SUCCESS == task_processor->start(1)); delete task_processor; test_param[0]->processor_ = NULL; } g_event_processor.shutdown();//do nothing } } // end of namespace obproxy } // end of namespace oceanbase int main(int argc, char **argv) { oceanbase::common::ObLogger::get_logger().set_log_level("WARN"); OB_LOGGER.set_log_level("WARN"); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
40.880445
115
0.683428
stutiredboy
cc70e6c4befbc4621a267274e49806a5a78331b1
2,690
cpp
C++
AlphaEngine/Source/Math/Vector4.cpp
Sh1ft0/alpha
6726d366f0c8d2e1434b87f815b2644ebf170adf
[ "Apache-2.0" ]
null
null
null
AlphaEngine/Source/Math/Vector4.cpp
Sh1ft0/alpha
6726d366f0c8d2e1434b87f815b2644ebf170adf
[ "Apache-2.0" ]
null
null
null
AlphaEngine/Source/Math/Vector4.cpp
Sh1ft0/alpha
6726d366f0c8d2e1434b87f815b2644ebf170adf
[ "Apache-2.0" ]
null
null
null
/** Copyright 2014-2015 Jason R. Wendlandt 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 "Math/Vector4.h" namespace alpha { Vector4::Vector4() : x(0.f), y(0.f), z(0.f), w(0.f) { } Vector4::Vector4(float _x, float _y, float _z, float _w) : x(_x), y(_y), z(_z), w(_w) { } Vector4::Vector4(const Vector3 & vec3, float _w) : x(vec3.x), y(vec3.y), z(vec3.z), w(_w) { } Vector4::Vector4(const Vector4 &vec) { this->x = vec.x; this->y = vec.y; this->z = vec.z; this->w = vec.w; } Vector4 & Vector4::operator=(const Vector4 & right) { this->x = right.x; this->y = right.y; this->z = right.z; this->w = right.w; return *this; } Vector4 operator+(const Vector4 & left, const Vector4 & right) { return Vector4(left.x + right.x, left.y + right.y, left.z + right.z, left.w + right.w); } Vector4 operator-(const Vector4 & left, const Vector4 & right) { return Vector4(left.x - right.x, left.y - right.y, left.z - right.z, left.w - right.w); } Vector4 operator*(const Vector4 & left, const Vector4 & right) { return Vector4(left.x * right.x, left.y * right.y, left.z * right.z, left.w * right.w); } Vector4 operator*(const Vector4 & left, float right) { return Vector4(left.x * right, left.y * right, left.z * right, left.w * right); } Vector4 operator/(const Vector4 & left, const Vector4 & right) { return Vector4(left.x / right.x, left.y / right.y, left.z / right.z, left.w / right.w); } Vector4 operator*(float left, const Vector4 & right) { return Vector4(left * right.x, left * right.y, left * right.z, left * right.w); } }
28.020833
72
0.51487
Sh1ft0
cc71ca850c8d94a413d3537d9a6677411b073e79
471
hpp
C++
src/internal/compiler_specifics.hpp
bmknecht/palnatoki
0522d690f034d9f52730f9666731c3376dd33405
[ "MIT" ]
null
null
null
src/internal/compiler_specifics.hpp
bmknecht/palnatoki
0522d690f034d9f52730f9666731c3376dd33405
[ "MIT" ]
null
null
null
src/internal/compiler_specifics.hpp
bmknecht/palnatoki
0522d690f034d9f52730f9666731c3376dd33405
[ "MIT" ]
null
null
null
#ifndef PALNATOKI_COMPILER_SPECIFICS_HPP #define PALNATOKI_COMPILER_SPECIFICS_HPP /** This file is part of the Palnatoki optimization library. For licensing * information refer to the LICENSE file that is included in the project. * * This file in particular contains compiler specific defines. */ // On my system MINGW fails to define _hypot but needs it in a std-header. #ifdef __MINGW32__ #define _hypot hypot #endif #endif // PALNATOKI_COMPILER_SPECIFICS_HPP
29.4375
74
0.796178
bmknecht
cc734a5f8a6328bfefc86ac8a7d925ceee9f70f6
4,589
hpp
C++
cpp_algs/data_structures/tree/trie.hpp
pskrunner14/cpp-practice
c59928bb9b91204588a0bafdc9f42deaacc64d29
[ "MIT" ]
2
2018-09-14T14:17:27.000Z
2020-01-02T00:20:52.000Z
cpp_algs/data_structures/tree/trie.hpp
pskrunner14/cpp-practice
c59928bb9b91204588a0bafdc9f42deaacc64d29
[ "MIT" ]
1
2018-10-28T19:45:20.000Z
2018-10-28T19:50:02.000Z
cpp_algs/data_structures/tree/trie.hpp
pskrunner14/cpp-practice
c59928bb9b91204588a0bafdc9f42deaacc64d29
[ "MIT" ]
1
2019-12-29T19:58:08.000Z
2019-12-29T19:58:08.000Z
/** * MIT License * * Copyright (c) 2018 Prabhsimran Singh * * 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. */ #pragma once /** * Data Structures - trie * trie.hpp * Purpose: Trie interface * * @author Prabhsimran Singh * @version 1.0 27/11/18 */ #include <iostream> #include <memory> #include <queue> #include <string> namespace ds { // ---------------------------------------------- Interface ---------------------------------------------------// class Trie { private: // pointer to root std::shared_ptr<TrieNode> root; // recursive remove func. void remove(std::shared_ptr<TrieNode> const &, const std::string &); // recursive print func. void print(std::shared_ptr<TrieNode>, string) const; public: // trie default constructor Trie(); // trie copy constructor Trie(const Trie &); // inserts word into trie void insertWord(const std::string &); // removes the word from trie if present void removeWord(const std::string &); // checks if trie contains the given word bool containsWord(const std::string &) const; // prints all the words in the trie void printWords() const; }; // -------------------------------------------- Implementation --------------------------------------------------// Trie::Trie() : root(std::shared_ptr<TrieNode>(new TrieNode('\0'))) {} Trie::Trie(const Trie &t) { throw NotImplementedError(); } void Trie::insertWord(const std::string &str) { std::shared_ptr<TrieNode> temp = root; size_t i = 0; while (i < str.size() && temp->contains(str[i])) { temp = temp->children[str[i]]; i++; } if (i == str.size() && temp->data == str[i - 1]) { temp->isTerminal = true; return; } for (; i < str.size() - 1; i++) { std::shared_ptr<TrieNode> child(new TrieNode(str[i])); temp->children[str[i]] = child; temp = child; } if (i < str.size()) { std::shared_ptr<TrieNode> child(new TrieNode(str[i], true)); temp->children[str[i]] = child; } } bool Trie::containsWord(const std::string &str) const { std::shared_ptr<TrieNode> temp = root; size_t i = 0; while (i < str.size() && temp->contains(str[i])) { temp = temp->children[str[i]]; i++; } if (i == str.size()) { if (temp->isTerminal) { return true; } } return false; } void Trie::remove(std::shared_ptr<TrieNode> const &node, const string &str) { if (str.empty()) { node->isTerminal = false; return; } if (node->contains(str[0])) { std::shared_ptr<TrieNode> child = node->children[str[0]]; remove(child, str.substr(1)); if (child->children.empty() && !child->isTerminal) { node->remove(str[0]); } } } void Trie::removeWord(const string &str) { if (root->contains(str[0])) { std::shared_ptr<TrieNode> child = root->children[str[0]]; // keep root safe remove(child, str.substr(1)); if (child->children.empty() && !child->isTerminal) { root->remove(str[0]); } } } void Trie::print(std::shared_ptr<TrieNode> node, string str) const { str += node->data; if (node->isTerminal) { cout << str << endl; } for (const auto &child : node->children) { print(child.second, str); } } void Trie::printWords() const { string str = ""; for (const auto &child : root->children) { print(child.second, str); } } } // namespace ds
28.68125
115
0.594247
pskrunner14
cc79a10f195b24ee64dee6b05423e5d472e61e41
1,790
hpp
C++
libember/Headers/ember/glow/GlowSignal.hpp
purefunsolutions/ember-plus
d022732f2533ad697238c6b5210d7fc3eb231bfc
[ "BSL-1.0" ]
78
2015-07-31T14:46:38.000Z
2022-03-28T09:28:28.000Z
libember/Headers/ember/glow/GlowSignal.hpp
purefunsolutions/ember-plus
d022732f2533ad697238c6b5210d7fc3eb231bfc
[ "BSL-1.0" ]
81
2015-08-03T07:58:19.000Z
2022-02-28T16:21:19.000Z
libember/Headers/ember/glow/GlowSignal.hpp
purefunsolutions/ember-plus
d022732f2533ad697238c6b5210d7fc3eb231bfc
[ "BSL-1.0" ]
49
2015-08-03T12:53:10.000Z
2022-03-17T17:25:49.000Z
/* libember -- C++ 03 implementation of the Ember+ Protocol Copyright (C) 2012-2016 Lawo GmbH (http://www.lawo.com). 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 __LIBEMBER_GLOW_GLOWSIGNAL_HPP #define __LIBEMBER_GLOW_GLOWSIGNAL_HPP #include "GlowContainer.hpp" namespace libember { namespace glow { /** * GlowSignal is the base class for GlowTarget and GlowSource */ class LIBEMBER_API GlowSignal : public GlowContainer { public: /** * Returns the signal number. * @return The signal number. */ int number() const; protected: /** * Initializes a new instance of GlowSignal * @param type The type of the instance. Either target or source. * @param tag The application tag to set */ GlowSignal(GlowType const& type, ber::Tag const& tag); /** * Initializes a new instance of GlowSignal * @param type The type of the instance. Either target or source. * @param number The signal number. */ GlowSignal(GlowType const& type, int number); /** * Initializes a new instance of GlowSignal * @param type The type of the instance. Either target or source. * @param tag The application tag to set * @param number The signal number. */ GlowSignal(GlowType const& type, ber::Tag const& tag, int number); }; } } #ifdef LIBEMBER_HEADER_ONLY # include "impl/GlowSignal.ipp" #endif #endif // __LIBEMBER_GLOW_GLOWSIGNAL_HPP
30.338983
91
0.6
purefunsolutions
cc7b8e491205d45097cb667f8eabebbe167534ac
4,818
hpp
C++
source/GcLib/directx/VertexBuffer.hpp
Mugenri/Touhou-Danmakufu-ph3sx-2
4ab7e40682341ff41d7467b83bb64c9a669a6064
[ "MIT" ]
null
null
null
source/GcLib/directx/VertexBuffer.hpp
Mugenri/Touhou-Danmakufu-ph3sx-2
4ab7e40682341ff41d7467b83bb64c9a669a6064
[ "MIT" ]
null
null
null
source/GcLib/directx/VertexBuffer.hpp
Mugenri/Touhou-Danmakufu-ph3sx-2
4ab7e40682341ff41d7467b83bb64c9a669a6064
[ "MIT" ]
null
null
null
#pragma once #include "../pch.h" #include "DxConstant.hpp" namespace directx { struct BufferLockParameter { UINT lockOffset = 0U; DWORD lockFlag = 0U; void* data = nullptr; size_t dataCount = 0U; size_t dataStride = 1U; BufferLockParameter() { lockOffset = 0U; lockFlag = 0U; data = nullptr; dataCount = 0U; dataStride = 1U; }; BufferLockParameter(DWORD _lockFlag) { lockOffset = 0U; lockFlag = _lockFlag; data = nullptr; dataCount = 0U; dataStride = 1U; }; BufferLockParameter(void* _data, size_t _count, size_t _stride, DWORD _lockFlag) { lockOffset = 0U; lockFlag = _lockFlag; data = 0U; dataCount = _count; dataStride = _stride; }; template<typename T> void SetSource(T& vecSrc, size_t countMax, size_t _stride) { data = vecSrc.data(); dataCount = std::min(countMax, vecSrc.size()); dataStride = _stride; } }; class VertexBufferManager; template<typename T> class BufferBase { static_assert(std::is_base_of<IDirect3DResource9, T>::value, "T must be a Direct3D resource"); public: BufferBase(); BufferBase(IDirect3DDevice9* device); virtual ~BufferBase(); inline void Release() { ptr_release(buffer_); } HRESULT UpdateBuffer(BufferLockParameter* pLock); virtual HRESULT Create(DWORD usage, D3DPOOL pool) = 0; T* GetBuffer() { return buffer_; } size_t GetSize() { return size_; } size_t GetSizeInBytes() { return sizeInBytes_; } protected: IDirect3DDevice9* pDevice_; T* buffer_; size_t size_; size_t stride_; size_t sizeInBytes_; }; class FixedVertexBuffer : public BufferBase<IDirect3DVertexBuffer9> { public: FixedVertexBuffer(IDirect3DDevice9* device); virtual ~FixedVertexBuffer(); virtual void Setup(size_t iniSize, size_t stride, DWORD fvf); virtual HRESULT Create(DWORD usage = D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DPOOL pool = D3DPOOL_DEFAULT); private: DWORD fvf_; }; class FixedIndexBuffer : public BufferBase<IDirect3DIndexBuffer9> { public: FixedIndexBuffer(IDirect3DDevice9* device); virtual ~FixedIndexBuffer(); virtual void Setup(size_t iniSize, size_t stride, D3DFORMAT format); virtual HRESULT Create(DWORD usage = D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DPOOL pool = D3DPOOL_DEFAULT); private: D3DFORMAT format_; }; template<typename T> class GrowableBuffer : public BufferBase<T> { public: GrowableBuffer(IDirect3DDevice9* device); virtual ~GrowableBuffer(); virtual HRESULT Create(DWORD usage, D3DPOOL pool) = 0; virtual void Expand(size_t newSize) = 0; }; class GrowableVertexBuffer : public GrowableBuffer<IDirect3DVertexBuffer9> { public: GrowableVertexBuffer(IDirect3DDevice9* device); virtual ~GrowableVertexBuffer(); virtual void Setup(size_t iniSize, size_t stride, DWORD fvf); virtual HRESULT Create(DWORD usage = D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DPOOL pool = D3DPOOL_DEFAULT); virtual void Expand(size_t newSize); private: DWORD fvf_; }; class GrowableIndexBuffer : public GrowableBuffer<IDirect3DIndexBuffer9> { public: GrowableIndexBuffer(IDirect3DDevice9* device); virtual ~GrowableIndexBuffer(); virtual void Setup(size_t iniSize, size_t stride, D3DFORMAT format); virtual HRESULT Create(DWORD usage = D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DPOOL pool = D3DPOOL_DEFAULT); virtual void Expand(size_t newSize); private: D3DFORMAT format_; }; class DirectGraphics; class VertexBufferManager : public DirectGraphicsListener { static VertexBufferManager* thisBase_; public: enum : size_t { MAX_STRIDE_STATIC = 65536U, }; VertexBufferManager(); ~VertexBufferManager(); static VertexBufferManager* GetBase() { return thisBase_; } virtual void ReleaseDxResource(); virtual void RestoreDxResource(); virtual bool Initialize(DirectGraphics* graphics); virtual void Release(); FixedVertexBuffer* GetVertexBufferTLX() { return vertexBuffers_[0]; } FixedVertexBuffer* GetVertexBufferLX() { return vertexBuffers_[1]; } FixedVertexBuffer* GetVertexBufferNX() { return vertexBuffers_[2]; } FixedIndexBuffer* GetIndexBuffer() { return indexBuffer_; } GrowableVertexBuffer* GetGrowableVertexBuffer() { return vertexBufferGrowable_; } GrowableIndexBuffer* GetGrowableIndexBuffer() { return indexBufferGrowable_; } GrowableVertexBuffer* GetInstancingVertexBuffer() { return vertexBuffer_HWInstancing_; } static void AssertBuffer(HRESULT hr, const std::wstring& bufferID); private: /* * 0 -> TLX * 1 -> LX * 2 -> NX */ std::vector<FixedVertexBuffer*> vertexBuffers_; FixedIndexBuffer* indexBuffer_; GrowableVertexBuffer* vertexBufferGrowable_; GrowableIndexBuffer* indexBufferGrowable_; GrowableVertexBuffer* vertexBuffer_HWInstancing_; virtual void CreateBuffers(IDirect3DDevice9* device); }; }
28.011628
110
0.74616
Mugenri
cc808f61475662d3cc8815b2816b27415f5377ea
2,234
cpp
C++
datastructures/binarytrees/largest_nonadj_sum.cpp
oishikm12/cpp-collection
4a454a6ed5b24570c7df0d4f0b692ae98c1ffa97
[ "MIT" ]
5
2021-05-17T12:32:42.000Z
2021-12-12T21:09:55.000Z
datastructures/binarytrees/largest_nonadj_sum.cpp
oishikm12/cpp-collection
4a454a6ed5b24570c7df0d4f0b692ae98c1ffa97
[ "MIT" ]
null
null
null
datastructures/binarytrees/largest_nonadj_sum.cpp
oishikm12/cpp-collection
4a454a6ed5b24570c7df0d4f0b692ae98c1ffa97
[ "MIT" ]
1
2021-05-13T20:29:57.000Z
2021-05-13T20:29:57.000Z
#include <iostream> using namespace std; class Node { public: int data; Node *left, *right; Node() = default; Node(int d) : data(d), left(NULL), right(NULL) {} ~Node() { delete left, delete right, left = right = NULL; } }; Node* buildTree(); pair<int, int> getLargestDisjointSum(Node *); int main() { /** * In order to find the largest disjoint node sum, we will * return two things as a pair, the first being the sum if the * current node is seleceted, other being if not selected */ cout << "\nThis program finds out the largest disjoint node in the given tree.\n" << endl; Node *root; cout << "Enter space seperated elements of the tree :" << endl; root = buildTree(); pair<int, int> disjointSum = getLargestDisjointSum(root); int maxSum = max(disjointSum.first, disjointSum.second); cout << "\nThe largest disjoint node sum possible here is: " << maxSum << "." << endl; cout << endl; delete root; return 0; } Node* buildTree() { int data; cin >> data; // -1 means an end Node aka leaf if (data == -1) return NULL; // Recursively build tree Node *curr = new Node(data); curr->left = buildTree(); curr->right = buildTree(); return curr; } pair<int, int> getLargestDisjointSum(Node *root) { // Base condition when we reach NULL after leaf // First pair is value when considering current // Second pair is when we are not including it if (!root) return make_pair(0, 0); // Postorder traversal to acquire values of left & right pair<int, int> left = getLargestDisjointSum(root->left); pair<int, int> right = getLargestDisjointSum(root->right); // When we include current, we cannot select left // or right child, we must select nodes after them, // so we access second element of the pair int includingCurrent = root->data + left.second + right.second; // If we are not including current, we simply select // whatever is max including / excluding the left & right nodes int excludingCurrent = max(left.first, left.second) + max(right.first, right.second); return make_pair(includingCurrent, excludingCurrent); }
30.189189
95
0.647269
oishikm12
cc85072f23c7cc6c31573bf529aadbee3c0ed4c6
1,153
hpp
C++
ex00/Cat.hpp
Gundul42/CPP_04
61cf8baeb9a9ed931ba423517937e697984c009b
[ "MIT" ]
null
null
null
ex00/Cat.hpp
Gundul42/CPP_04
61cf8baeb9a9ed931ba423517937e697984c009b
[ "MIT" ]
null
null
null
ex00/Cat.hpp
Gundul42/CPP_04
61cf8baeb9a9ed931ba423517937e697984c009b
[ "MIT" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Cat.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: graja <graja@student.42wolfsburg.de> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2022/02/17 16:57:04 by graja #+# #+# */ /* Updated: 2022/02/18 13:36:44 by graja ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef CAT_H # define CAT_H # include "Animal.hpp" # include <iostream> class Cat: public Animal { public: Cat(void); Cat(const Cat &cpy); virtual ~Cat(void); Cat& operator=(const Cat &ovr); virtual std::string makeSound(void) const; }; #endif
36.03125
80
0.235039
Gundul42
cc870d8419fa4828708cf513941a4e2d2b0f6a29
4,627
cpp
C++
tests/bm_heterogeneous_count_ptr.cpp
mpusz/unordered_v2
a3ab5a08b335b15fc60454ecc0c1d2199d01a5a1
[ "MIT" ]
5
2018-04-08T17:03:16.000Z
2019-06-01T19:12:47.000Z
tests/bm_heterogeneous_count_ptr.cpp
mpusz/unordered_v2
a3ab5a08b335b15fc60454ecc0c1d2199d01a5a1
[ "MIT" ]
null
null
null
tests/bm_heterogeneous_count_ptr.cpp
mpusz/unordered_v2
a3ab5a08b335b15fc60454ecc0c1d2199d01a5a1
[ "MIT" ]
null
null
null
// The MIT License (MIT) // // Copyright (c) 2017 Mateusz Pusz // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include "unordered_map" #include "unordered_set" #include <benchmark/benchmark.h> #include <array> #include <memory> #include <random> #include <vector> namespace { struct my_data { size_t i; std::array<char, 256> data; explicit my_data(size_t i_) : i{i_} { std::iota(begin(data), end(data), 0); } }; struct my_data_equal { using is_transparent = void; bool operator()(const std::unique_ptr<my_data>& l, const std::unique_ptr<my_data>& r) const { return l == r; } bool operator()(const std::unique_ptr<my_data>& l, my_data* ptr) const { return l.get() == ptr; } bool operator()(my_data* ptr, const std::unique_ptr<my_data>& r) const { return ptr == r.get(); } }; struct my_data_hash { using transparent_key_equal = my_data_equal; // KeyEqual to use size_t operator()(const std::unique_ptr<my_data>& v) const { return std::hash<const my_data*>{}(v.get()); } size_t operator()(const my_data* ptr) const { return std::hash<const my_data*>{}(ptr); } }; // based on https://stackoverflow.com/a/17853770 class opt_out_deleter { bool delete_; public: explicit opt_out_deleter(bool do_delete = true) : delete_{do_delete} {} template<typename T> void operator()(T* p) const { if(delete_) delete p; } }; template<typename T> using set_unique_ptr = std::unique_ptr<T, opt_out_deleter>; template<typename T> set_unique_ptr<T> make_find_ptr(T* raw) { return set_unique_ptr<T>{raw, opt_out_deleter{false}}; } constexpr size_t item_count = 4096; struct test_data { std::vector<std::unique_ptr<my_data>> storage; std::vector<my_data*> test_sequence; }; test_data make_test_data() { test_data data; data.storage.reserve(item_count); data.test_sequence.reserve(item_count); for(size_t i = 0; i < item_count; ++i) { data.storage.push_back(std::make_unique<my_data>(i)); data.test_sequence.push_back(data.storage.back().get()); } std::mt19937 g; std::shuffle(begin(data.test_sequence), end(data.test_sequence), g); return data; } using regular_set = std::unordered_set<set_unique_ptr<my_data>>; using regular_map = std::unordered_map<my_data*, std::unique_ptr<my_data>>; using heterogeneous_set = std::unordered_set<std::unique_ptr<my_data>, my_data_hash>; void bm_heterogeneous_set_count_ptr_regular(benchmark::State& state) { auto data = make_test_data(); regular_set set; for(auto& ptr : data.storage) set.emplace(ptr.release()); for(auto _ : state) for(auto ptr : data.test_sequence) benchmark::DoNotOptimize(set.count(make_find_ptr(ptr))); } void bm_heterogeneous_map_count_ptr_regular(benchmark::State& state) { auto data = make_test_data(); regular_map map; for(auto& ptr : data.storage) { auto p = ptr.release(); map.emplace(p, p); } for(auto _ : state) for(auto ptr : data.test_sequence) benchmark::DoNotOptimize(map.count(ptr)); } void bm_heterogeneous_set_count_ptr_heterogeneous(benchmark::State& state) { auto data = make_test_data(); heterogeneous_set set; for(auto& ptr : data.storage) set.emplace(std::move(ptr)); for(auto _ : state) for(auto ptr : data.test_sequence) benchmark::DoNotOptimize(set.count(ptr)); } BENCHMARK(bm_heterogeneous_set_count_ptr_regular); BENCHMARK(bm_heterogeneous_map_count_ptr_regular); BENCHMARK(bm_heterogeneous_set_count_ptr_heterogeneous); } // namespace
33.773723
114
0.707154
mpusz
cc8a5816aeb17ade6844422e5df3784f6a38df3b
1,887
cpp
C++
tests/board_test.cpp
JAOP1/GO
48c0275fd37bb552c0db4b968391a5a95ed6c860
[ "MIT" ]
null
null
null
tests/board_test.cpp
JAOP1/GO
48c0275fd37bb552c0db4b968391a5a95ed6c860
[ "MIT" ]
null
null
null
tests/board_test.cpp
JAOP1/GO
48c0275fd37bb552c0db4b968391a5a95ed6c860
[ "MIT" ]
2
2019-12-12T18:55:35.000Z
2019-12-12T19:03:35.000Z
#include "../Include/BoardGame.hpp" #include <gtest/gtest.h> #include <iostream> TEST(Board_Test, Creation) { Graph G = graphs::Grid(4, 4); BoardGame Go(G, 0.5); std::vector<char> initial_state(25, 'N'); ASSERT_EQ(Go.show_current_state(), initial_state); } TEST(Board_Test, Valid_action) { Graph G = graphs::Grid(3, 3); // Grid size is 4 x 4. BoardGame Go(G, 0.5); std::vector<char> state(16, 'N'); state[1] = 'B'; state[4] = 'B'; state[5] = 'W'; Go.make_action(1); // Black has done an action in node 1. Go.make_action(-1); // White pass. Go.make_action(4); // Black has done an action in node 4. Go.make_action(5); // White. auto v = Go.get_current_node_state(0); auto v1 = Go.get_current_node_state(1); auto v2 = Go.get_current_node_state(4); ASSERT_EQ(Go.show_current_state(), state); ASSERT_EQ(Go.player_status(), 'B'); ASSERT_EQ(v.type, 'N'); ASSERT_EQ(v1.type, 'B'); ASSERT_EQ(v2.type, 'B'); ASSERT_EQ(v1.libertiesNodes.size(), 2); ASSERT_EQ(v2.libertiesNodes.size(), 2); ASSERT_EQ(v.libertiesNodes.size(), 0); ASSERT_TRUE(Go.is_valid_move(0)); ASSERT_TRUE(Go.is_valid_move(2)); ASSERT_TRUE(!Go.is_valid_move(5)); } TEST(Board_Test, Eliminate) { Graph G = graphs::Complete(3); BoardGame Go(G); Go.make_action(1); Go.make_action(2); std::vector<char> state(3, 'N'); state[1] = 'B'; state[2] = 'W'; ASSERT_EQ(Go.show_current_state(), state); state[2] = 'N'; state[0] = 'B'; Go.make_action(0); ASSERT_EQ(Go.show_current_state(), state); } TEST(Board_Test, reward) { Graph G = graphs::Grid(2, 2); BoardGame Go(G); Go.make_action(4); Go.make_action(-1); Go.make_action(3); Go.make_action(-1); Go.make_action(1); ASSERT_EQ(Go.reward('B'), 1); ASSERT_EQ(Go.reward('W'), -1); }
23.886076
61
0.615262
JAOP1
cc8c6ce05dd60ee0584e8e40f3aa68c2e377f35d
356
cpp
C++
spriterengine/objectinfo/tagobjectinfo.cpp
Squalr/SpriterPlusPlus
ad728307b1d31238c6164b7b42936e6212e77a9e
[ "Zlib" ]
92
2015-11-03T08:46:58.000Z
2021-03-12T22:36:45.000Z
spriterengine/objectinfo/tagobjectinfo.cpp
Squalr/SpriterPlusPlus
ad728307b1d31238c6164b7b42936e6212e77a9e
[ "Zlib" ]
15
2015-11-04T12:16:36.000Z
2019-09-03T17:13:16.000Z
spriterengine/objectinfo/tagobjectinfo.cpp
Squalr/SpriterPlusPlus
ad728307b1d31238c6164b7b42936e6212e77a9e
[ "Zlib" ]
53
2015-11-04T12:25:50.000Z
2021-04-30T06:14:37.000Z
#include "tagobjectinfo.h" namespace SpriterEngine { TagObjectInfo::TagObjectInfo() { } void TagObjectInfo::setObjectToLinear(UniversalObjectInterface *bObject, real t, UniversalObjectInterface *resultObject) { resultObject->setTagList(&tagList); } void TagObjectInfo::pushBackTag(const std::string * tag) { tagList.pushBackTag(tag); } }
16.952381
121
0.758427
Squalr
cc8e38dd536004284e8293e73b86b9c6766c613e
2,090
cpp
C++
TurboX-Engine/TurboX-Engine/W_Hierarchy.cpp
moon-funding/TurboX-Engine
0ebcc94f0c93fa0a5d1f88f8f46e90df28b5c8a6
[ "MIT", "Zlib", "Apache-2.0", "BSD-3-Clause" ]
6
2020-10-08T03:21:06.000Z
2022-01-19T14:50:01.000Z
TurboX-Engine/TurboX-Engine/W_Hierarchy.cpp
moon-funding/TurboX-Engine
0ebcc94f0c93fa0a5d1f88f8f46e90df28b5c8a6
[ "MIT", "Zlib", "Apache-2.0", "BSD-3-Clause" ]
11
2021-01-09T09:40:54.000Z
2021-12-01T22:28:35.000Z
TurboX-Engine/TurboX-Engine/W_Hierarchy.cpp
moon-funding/TurboX-Engine
0ebcc94f0c93fa0a5d1f88f8f46e90df28b5c8a6
[ "MIT", "Zlib", "Apache-2.0", "BSD-3-Clause" ]
3
2020-12-15T00:36:33.000Z
2021-01-05T08:28:17.000Z
#include "W_Hierarchy.h" #include "ModuleScene.h" #include "Application.h" W_Hierarchy::W_Hierarchy() { open_pop_up = false; } W_Hierarchy::~W_Hierarchy() { } void W_Hierarchy::Draw() { ImGui::Begin("Hierarchy"); ImGuiTreeNodeFlags default_flags = ImGuiTreeNodeFlags_NoTreePushOnOpen; DrawGameObject(App->scene->GetRoot(), default_flags, App->scene->GetRoot()); ImGui::End(); } void W_Hierarchy::DrawGameObject(GameObject* gameObject, ImGuiTreeNodeFlags default_flags, GameObject* root) { bool drawAgain = true; ImGuiTreeNodeFlags flags = default_flags; if (gameObject->childs.empty()) { flags |= ImGuiTreeNodeFlags_Leaf; } if (gameObject->is_selected) { flags |= ImGuiTreeNodeFlags_Selected; } if (gameObject != root) drawAgain = ImGui::TreeNodeEx(gameObject, flags, gameObject->name.c_str()); else drawAgain = true; if (ImGui::IsItemClicked(0)) { App->scene->selectGameObject(gameObject); } if (ImGui::BeginPopupContextItem((gameObject->name + "rightClick").c_str(), 1)) { if (ImGui::Button("Delete")) { gameObject->to_delete = true; } ImGui::EndPopup(); } if (App->scene->selected_GO != nullptr) { if (App->scene->selected_GO->to_delete == true) { App->scene->DestroyGameObject(gameObject); } } if (ImGui::BeginDragDropSource()) { uint gameObject_UUID = gameObject->GetUUID(); ImGui::SetDragDropPayload("Reparenting", &gameObject_UUID, sizeof(uint)); ImGui::Text(gameObject->name.c_str()); ImGui::EndDragDropSource(); } if (ImGui::BeginDragDropTarget()) { if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("Reparenting", ImGuiDragDropFlags_SourceAllowNullID)) { GameObject* draggedGameobject = App->scene->GetGameObjectByUUID(*(uint*)payload->Data); if (draggedGameobject != nullptr) draggedGameobject->SetParent(gameObject); } ImGui::EndDragDropTarget(); } if (drawAgain) { for (uint i = 0; i < gameObject->childs.size(); i++) { DrawGameObject(gameObject->childs[i], flags, root); } } } void W_Hierarchy::SetShowWindow() { showWindow = !showWindow; }
21.111111
118
0.705263
moon-funding
cc9c4fbdb45d79d0fd9d176302543bd38330349a
875
cpp
C++
Linked List/stackImplementionLinkedList.cpp
harshallgarg/Diversified-Programming
7e6fb135c4639dbaa0651b85f98397f994a5b11d
[ "MIT" ]
2
2020-08-09T02:09:50.000Z
2020-08-09T07:07:47.000Z
Linked List/stackImplementionLinkedList.cpp
harshallgarg/Diversified-Programming
7e6fb135c4639dbaa0651b85f98397f994a5b11d
[ "MIT" ]
null
null
null
Linked List/stackImplementionLinkedList.cpp
harshallgarg/Diversified-Programming
7e6fb135c4639dbaa0651b85f98397f994a5b11d
[ "MIT" ]
5
2020-09-21T12:49:07.000Z
2020-09-29T16:13:09.000Z
// // stackImplementionLinkedList.cpp // C++ // // Created by Anish Mookherjee on 31/03/20. // Copyright © 2020 Anish Mookherjee. All rights reserved. // #include <iostream> using namespace std; struct StackNode { int data; StackNode *next; StackNode(int a) { data = a; next = NULL; } }; class MyStack { private: StackNode *top; public : void push(int); int pop(); MyStack() { top = NULL; } }; void MyStack ::push(int x) { StackNode *newNode=(struct StackNode*)malloc(sizeof(struct StackNode)); newNode->data=x; if(top==NULL) { top=newNode; } else { newNode->next=top; top=newNode; } } int MyStack ::pop() { if(top==NULL) return -1; StackNode *temp; temp=top; top=top->next; temp->next=NULL; return temp->data; }
14.830508
75
0.56
harshallgarg
cc9d4c05139e6626c27df4354e9a42179b77abaa
884
cpp
C++
HDUOJ/6324/observation.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
2
2018-02-14T01:59:31.000Z
2018-03-28T03:30:45.000Z
HDUOJ/6324/observation.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
null
null
null
HDUOJ/6324/observation.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
2
2017-12-30T02:46:35.000Z
2018-03-28T03:30:49.000Z
#include <iostream> #include <cstdio> #include <algorithm> #include <cmath> #include <string> #include <cstring> #include <iomanip> #include <climits> #include <stack> #include <queue> #include <vector> #include <set> #include <map> #include <functional> #include <iterator> using namespace std; #define SIZE 100010 int arr[SIZE]; int main() { int caseNum; scanf("%d", &caseNum); while (caseNum--) { int num; scanf("%d", &num); int xorSum = 0; for (int i = 0; i < num; i++) { scanf("%d", arr + i); xorSum ^= arr[i]; } for (int i = 0; i < num - 1; i++) { int from, to; scanf("%d%d", &from, &to); } if (xorSum == 0) { puts("D"); } else { puts("Q"); } } return 0; }
16.37037
41
0.46267
codgician
cca299c64288ae42223e36c1a26c99d8b4c9b402
1,095
cpp
C++
src/lib/helium_us915_netjoin.cpp
olicooper/arduino-lorawan
caceeb49b1f5520d11668aeb7c587ef1a96ca9ad
[ "MIT" ]
198
2016-11-04T13:49:53.000Z
2022-03-30T13:25:51.000Z
src/lib/helium_us915_netjoin.cpp
olicooper/arduino-lorawan
caceeb49b1f5520d11668aeb7c587ef1a96ca9ad
[ "MIT" ]
134
2017-03-02T05:25:20.000Z
2022-03-31T19:26:33.000Z
src/lib/helium_us915_netjoin.cpp
olicooper/arduino-lorawan
caceeb49b1f5520d11668aeb7c587ef1a96ca9ad
[ "MIT" ]
51
2017-11-16T15:14:38.000Z
2022-03-09T09:41:43.000Z
/* Module: helium_us915_netjoin.cpp Function: Arduino_LoRaWAN_Helium_us915::NetBeginRegionInit() Copyright notice: See LICENSE file accompanying this project. Author: Terry Moore, MCCI Corporation February 2020 */ #include <Arduino_LoRaWAN_Helium.h> #include <Arduino_LoRaWAN_lmic.h> /****************************************************************************\ | | Manifest constants & typedefs. | \****************************************************************************/ /****************************************************************************\ | | Read-only data. | \****************************************************************************/ /****************************************************************************\ | | Variables. | \****************************************************************************/ #if defined(CFG_us915) void Arduino_LoRaWAN_Helium_us915::NetJoin() { // do the common work. this->Super::NetJoin(); // Helium is bog standard, and our DNW2 value is already right. } #endif // defined(CFG_us915)
21.9
78
0.400913
olicooper
cca7779d4cd5e5cd70a4749115a3ec5bd72eebd3
23
cpp
C++
ch15/ex15.34.35.36.38/andquery.cpp
shawabhishek/Cpp-Primer
c93143965e62c7ab833f43586ab1c759a5707cfc
[ "CC0-1.0" ]
7,897
2015-01-02T04:35:38.000Z
2022-03-31T08:32:50.000Z
ch15/ex15.34.35.36.38/andquery.cpp
shawabhishek/Cpp-Primer
c93143965e62c7ab833f43586ab1c759a5707cfc
[ "CC0-1.0" ]
456
2015-01-01T15:47:52.000Z
2022-02-07T04:17:56.000Z
ch15/ex15.34.35.36.38/andquery.cpp
shawabhishek/Cpp-Primer
c93143965e62c7ab833f43586ab1c759a5707cfc
[ "CC0-1.0" ]
3,887
2015-01-01T13:23:23.000Z
2022-03-31T15:05:21.000Z
#include "andquery.h"
7.666667
21
0.695652
shawabhishek
cca8c4e26b768dddcf516e3d929d11c4b025470c
1,656
cpp
C++
leetcode_cpp/reverse_linked_list_II.cpp
jialing3/corner_cases
54a316518fcf4b43ae96ed9935b4cf91ade1eed9
[ "Apache-2.0" ]
1
2015-05-29T08:40:48.000Z
2015-05-29T08:40:48.000Z
leetcode_cpp/reverse_linked_list_II.cpp
jialing3/corner_cases
54a316518fcf4b43ae96ed9935b4cf91ade1eed9
[ "Apache-2.0" ]
null
null
null
leetcode_cpp/reverse_linked_list_II.cpp
jialing3/corner_cases
54a316518fcf4b43ae96ed9935b4cf91ade1eed9
[ "Apache-2.0" ]
null
null
null
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *reverseBetween(ListNode *head, int m, int n) { // case in which no swap is needed if (m == n) { return head; } ListNode *current = head; ListNode *next; ListNode *previous; int counter = 1; ListNode *node_m_minus_1; ListNode *node_m; ListNode *node_n; ListNode *node_n_plus_1; // case in which swap starts from the beginning while (true) { if (current != NULL) { next = current -> next; } if (counter == m - 1) { node_m_minus_1 = current; } else if (counter == m) { node_m = current; } else if (counter == n) { node_n = current; } else if (counter == n + 1) { node_n_plus_1 = current; } if (counter >= m + 1 && counter <= n) { current -> next = previous; } if (current == NULL) { break; } counter += 1; previous = current; current = next; } if (m != 1) { node_m_minus_1 -> next = node_n; } else { head = node_n; } node_m -> next = node_n_plus_1; return head; } };
23.657143
61
0.407005
jialing3
ccad57f059424cb47150cc48cf0d7c1a417233bc
1,294
cpp
C++
Code/C++/sorted_zig_zag_array.cpp
Atul-Kashyap/Algo-Tree
5ab65e86551be2843cae85a7c9860a91883abede
[ "MIT" ]
356
2021-01-24T11:34:15.000Z
2022-03-16T08:39:02.000Z
Code/C++/sorted_zig_zag_array.cpp
Atul-Kashyap/Algo-Tree
5ab65e86551be2843cae85a7c9860a91883abede
[ "MIT" ]
1,778
2021-01-24T10:52:44.000Z
2022-01-30T12:34:05.000Z
Code/C++/sorted_zig_zag_array.cpp
Atul-Kashyap/Algo-Tree
5ab65e86551be2843cae85a7c9860a91883abede
[ "MIT" ]
782
2021-01-24T10:54:10.000Z
2022-03-23T10:16:04.000Z
/* Approach : First sort the array then, swap pairs of elements except the first element. Example - keep a[0], swap a[1] with a[2], swap a[3] with a[4], and so on. So, we will take array and its size as parameters, run a loop from i to size of the array and swap every pair of element using swap function. At the end of loop, we will print the array. */ #include <bits/stdc++.h> using namespace std; //helper function that converts given array in zig-zag form void zigzag(int a[] , int n) { for(int i = 1 ; i < n ; i += 2) { if(i+1 < n) swap(a[i] , a[i+1]); } cout << "\nZig - Zag array : "; for(int i = 0 ; i < n ; i++) cout << a[i] << " "; } int main() { int a[] = {4,3,7,8,6,2,1}; int n = sizeof(a)/sizeof(a[0]); sort(a , a+n); cout << "Original array : "; for(int i=0 ; i<n ; i++) cout << a[i]<<" "; zigzag(a , n); return 0; } /* Test Case - Sample Input/Output (1): Original array : 1 2 3 4 6 7 8 Zig - Zag array : 1 3 2 6 4 8 7 Sample Input/Output (2): Original array : 11 12 13 14 16 17 18 Zig - Zag array : 11 13 12 16 14 18 17 Time Complexity : O(n log n), where n is the number of elements. Space Complexity : O(1) */
23.527273
99
0.544822
Atul-Kashyap
ccaf786c723eb9e2b5b472bcfd90366cc2650e7a
1,767
cc
C++
src/bin/ngrammerge.cc
unixnme/opengrm_ngram
ce9b55b406c681902a20c4b547bdd254a8a399e7
[ "Apache-2.0" ]
1
2020-05-11T00:44:55.000Z
2020-05-11T00:44:55.000Z
src/bin/ngrammerge.cc
unixnme/opengrm_ngram
ce9b55b406c681902a20c4b547bdd254a8a399e7
[ "Apache-2.0" ]
null
null
null
src/bin/ngrammerge.cc
unixnme/opengrm_ngram
ce9b55b406c681902a20c4b547bdd254a8a399e7
[ "Apache-2.0" ]
null
null
null
// 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. // // Copyright 2005-2016 Brian Roark and Google, Inc. #include <fst/flags.h> #include <ngram/ngram-model.h> DEFINE_double(alpha, 1.0, "Weight for first FST"); DEFINE_double(beta, 1.0, "Weight for second (and subsequent) FST(s)"); DEFINE_string(context_pattern, "", "Context pattern for second FST"); DEFINE_string(contexts, "", "Context patterns file (all FSTs)"); DEFINE_bool(normalize, false, "Normalize resulting model"); DEFINE_string(method, "count_merge", "One of: \"context_merge\", \"count_merge\", \"model_merge\" " "\"bayes_model_merge\", \"histogram_merge\", \"replace_merge\""); DEFINE_int32(max_replace_order, -1, "Maximum order to replace in replace_merge, ignored if < 1."); DEFINE_string(ofile, "", "Output file"); DEFINE_int64(backoff_label, 0, "Backoff label"); DEFINE_double(norm_eps, ngram::kNormEps, "Normalization check epsilon"); DEFINE_bool(check_consistency, false, "Check model consistency"); DEFINE_bool(complete, false, "Complete partial models"); DEFINE_bool(round_to_int, false, "Round all merged counts to integers"); int ngrammerge_main(int argc, char** argv); int main(int argc, char** argv) { return ngrammerge_main(argc, argv); }
45.307692
79
0.728919
unixnme
ccb088631b6ec9d949e90b8364b37129fe8757a2
7,307
cpp
C++
src/app/app.cpp
zgpio/tree.nvim
5ff3644fb4eddc6754488263c21745e057a16f05
[ "BSD-3-Clause" ]
199
2019-10-20T12:53:41.000Z
2022-03-28T09:04:41.000Z
src/app/app.cpp
zgpio/tree.nvim
5ff3644fb4eddc6754488263c21745e057a16f05
[ "BSD-3-Clause" ]
12
2019-10-21T01:16:56.000Z
2022-01-27T03:22:55.000Z
src/app/app.cpp
zgpio/tree.nvim
5ff3644fb4eddc6754488263c21745e057a16f05
[ "BSD-3-Clause" ]
7
2019-11-01T02:13:58.000Z
2021-11-30T17:34:24.000Z
#include <cinttypes> #include <iostream> #include "app.h" using std::cout; using std::endl; using std::string; namespace tree { App::App(nvim::Nvim *nvim, int chan_id) : m_nvim(nvim), chan_id(chan_id) { INFO("chan_id: %d\n", chan_id); auto &a = *m_nvim; // NOTE: 必须同步调用 a.execute_lua("require('tree').channel_id = ...", {chan_id}); Tree::api = m_nvim; init_highlight(); } void App::init_highlight() { auto &a = *m_nvim; // init highlight char name[40]; char cmd[80]; // sprintf(cmd, "silent hi %s guifg=%s", name, cell.color.toStdString().c_str()); sprintf(name, "tree_%d_0", FILENAME); // file sprintf(cmd, "hi %s guifg=%s", name, gui_colors[YELLOW].data()); a.command(cmd); sprintf(name, "tree_%d_1", FILENAME); // dir sprintf(cmd, "hi %s guifg=%s", name, gui_colors[BLUE].data()); a.command(cmd); sprintf(name, "tree_%d", SIZE); sprintf(cmd, "hi %s guifg=%s", name, gui_colors[GREEN].data()); a.command(cmd); sprintf(name, "tree_%d", INDENT); sprintf(cmd, "hi %s guifg=%s", name, "#41535b"); a.command(cmd); sprintf(name, "tree_%d", TIME); sprintf(cmd, "hi %s guifg=%s", name, gui_colors[BLUE].data()); a.command(cmd); for (int i = 0; i < 83; ++i) { sprintf(name, "tree_%d_%d", ICON, i); sprintf(cmd, "hi %s guifg=%s", name, icons[i].second.data()); a.command(cmd); } for (int i = 0; i < 16; ++i) { sprintf(name, "tree_%d_%d", MARK, i); sprintf(cmd, "hi %s guifg=%s", name, gui_colors[i].data()); a.command(cmd); } for (int i = 0; i < 8; ++i) { sprintf(name, "tree_%d_%d", GIT, i); sprintf(cmd, "hi %s guifg=%s", name, git_indicators[i].second.data()); a.command(cmd); } } void App::createTree(int bufnr, string &path) { auto &b = m_nvim; int ns_id = b->create_namespace("tree_icon"); if (path.back() == '/') // path("/foo/bar/").parent_path(); // "/foo/bar" path.pop_back(); INFO("bufnr:%d ns_id:%d path:%s\n", bufnr, ns_id, path.c_str()); Tree &tree = *(new Tree(bufnr, ns_id)); trees.insert({bufnr, &tree}); treebufs.insert(treebufs.begin(), bufnr); tree.cfg.update(m_cfgmap); m_ctx.prev_bufnr = bufnr; tree.changeRoot(path); b->async_buf_set_option(bufnr, "buflisted", tree.cfg.listed); nvim::Dictionary tree_cfg{ {"toggle", tree.cfg.toggle}, }; b->execute_lua("tree.resume(...)", {m_ctx.prev_bufnr, tree_cfg}); } void App::handleNvimNotification(const string &method, const vector<nvim::Object> &args) { INFO("method: %s\n", method.c_str()); if (method == "_tree_async_action" && args.size() > 0) { // _tree_async_action [action: string, args: vector, context: multimap] string action = args.at(0).as_string(); vector<nvim::Object> act_args = args.at(1).as_vector(); auto context = args.at(2).as_multimap(); // INFO("\taction: %s\n", action.c_str()); m_ctx = context; // INFO("\tprev_bufnr: %d\n", m_ctx.prev_bufnr); auto search = trees.find(m_ctx.prev_bufnr); if (search != trees.end()) { // if (action == "quit" && args.size() > 0) search->second->action(action, act_args, context); } } else if (method == "function") { string fn = args.at(0).as_string(); // TODO The logic of tree.nvim calling lua code and then calling back cpp code should be placed in tree.cpp if (fn == "paste") { vector<nvim::Object> fargs = args.at(1).as_vector(); vector<nvim::Object> pos = fargs[0].as_vector(); string src = fargs[1].as_string(); string dest = fargs[2].as_string(); int buf = pos[0].as_uint64_t(); int line = pos[1].as_uint64_t(); trees[buf]->paste(line, src, dest); } else if (fn == "new_file") { vector<nvim::Object> fargs = args.at(1).as_vector(); string input = fargs[0].as_string(); int bufnr = fargs[1].as_uint64_t(); trees[bufnr]->handleNewFile(input); } else if (fn == "rename") { vector<nvim::Object> fargs = args.at(1).as_vector(); string input = fargs[0].as_string(); int bufnr = fargs[1].as_uint64_t(); trees[bufnr]->handleRename(input); } else if (fn == "remove") { vector<nvim::Object> fargs = args.at(1).as_vector(); int buf = fargs[0].as_uint64_t(); int choice = fargs[1].as_uint64_t(); trees[buf]->remove(); } else if (fn == "on_detach") { const int buf = args.at(1).as_uint64_t(); auto got = trees.find(buf); if (got != trees.end()) { delete trees[buf]; trees.erase(buf); // TODO: 修改tree_buf printf("\tAfter remove %d, trees:", buf); for (auto i : trees) { cout << i.first << ","; } cout << endl; } } } } void App::handleRequest(nvim::NvimRPC &rpc, uint64_t msgid, const string &method, const vector<nvim::Object> &args) { INFO("method: %s args.size: %lu\n", method.c_str(), args.size()); if (method == "_tree_start" && args.size() > 0) { // _tree_start [paths: List, context: Dictionary] auto paths = args[0].as_vector(); // TODO: 支持path列表(多个path源) string path = paths[0].as_string(); m_cfgmap = args[1].as_multimap(); auto *b = m_nvim; auto search = m_cfgmap.find("bufnr"); if (search != m_cfgmap.end()) { // TODO: createTree时存在request和此处的response好像产生冲突 createTree(search->second.as_uint64_t(), path); } else { // NOTE: Resume tree buffer by default. // TODO: consider to use treebufs[0] Tree &tree = *trees[m_ctx.prev_bufnr]; auto it = std::find(treebufs.begin(), treebufs.end(), m_ctx.prev_bufnr); if (it != treebufs.end()) { treebufs.erase(it); treebufs.insert(treebufs.begin(), m_ctx.prev_bufnr); } // NOTE: 暂时不支持通过_tree_start动态更新columns auto got = m_cfgmap.find("columns"); if (got != m_cfgmap.end()) { m_cfgmap.erase(got); } tree.cfg.update(m_cfgmap); nvim::Array bufnrs; for (const int item : treebufs) bufnrs.push_back(item); Map tree_cfg = { {"toggle", tree.cfg.toggle}, }; b->async_execute_lua("tree.resume(...)", {bufnrs, tree_cfg}); // TODO: columns 状态更新需要清除不需要的columns } rpc.send_response(msgid, {}, {}); } else if (method == "_tree_get_candidate") { Map context = args[0].as_multimap(); Tree &tree = *trees[m_ctx.prev_bufnr]; auto search = context.find("cursor"); auto rv = tree.get_candidate(search->second.as_uint64_t() - 1); rpc.send_response(msgid, {}, rv); } else { // be sure to return early or this message will be sent rpc.send_response(msgid, {"Unknown method"}, {}); } } } // namespace tree
34.630332
115
0.545641
zgpio
ccb2ac203882c1bd30851b880da094ac75bbbf43
1,470
hpp
C++
code/jsbind/v8/global.hpp
Chobolabs/jsbind
874b41df6bbc9a3b756e828c64e43e1b6cbd4386
[ "MIT" ]
57
2019-03-30T21:26:08.000Z
2022-03-11T02:22:09.000Z
code/jsbind/v8/global.hpp
Chobolabs/jsbind
874b41df6bbc9a3b756e828c64e43e1b6cbd4386
[ "MIT" ]
null
null
null
code/jsbind/v8/global.hpp
Chobolabs/jsbind
874b41df6bbc9a3b756e828c64e43e1b6cbd4386
[ "MIT" ]
3
2020-04-11T09:19:44.000Z
2021-09-30T07:30:45.000Z
// jsbind // Copyright (c) 2019 Chobolabs Inc. // http://www.chobolabs.com/ // // Distributed under the MIT Software License // See accompanying file LICENSE.txt or copy at // http://opensource.org/licenses/MIT // #pragma once #if defined(JSBIND_NODE) # include <node.h> #endif #include <v8.h> #include <new> namespace jsbind { extern void v8_initialize_with_global(v8::Local<v8::Object> global); namespace internal { extern v8::Isolate* isolate; struct context { v8::Locker* m_locker = nullptr; void enter() { if (!m_locker) // simple reentry { m_locker = new (buf)v8::Locker(isolate); isolate->Enter(); auto ctx = to_local(); ctx->Enter(); } } void exit() { if (m_locker) { auto ctx = to_local(); ctx->Exit(); isolate->Exit(); m_locker->~Locker(); m_locker = nullptr; } } const v8::Local<v8::Context>& to_local() const { return *reinterpret_cast<const v8::Handle<v8::Context>*>(&v8ctx); } v8::Persistent<v8::Context> v8ctx; char buf[sizeof(v8::Locker)]; // placing the locker here to avoid needless allocations }; extern context ctx; extern void report_exception(const v8::TryCatch& try_catch); } }
19.6
94
0.533333
Chobolabs
ccb569defcd3a351a7d493e3bccf21d2d98e4c18
703
cpp
C++
backend/drone_ros_ws/src/drone_app/test/BBoxTest.cpp
Flytte/flytte
36e2dc886c7437c3e3fff5a082296d5bc1f10bd7
[ "BSD-3-Clause" ]
3
2018-05-08T18:01:48.000Z
2019-06-27T07:31:20.000Z
backend/drone_ros_ws/src/drone_app/test/BBoxTest.cpp
Flytte/flytte
36e2dc886c7437c3e3fff5a082296d5bc1f10bd7
[ "BSD-3-Clause" ]
null
null
null
backend/drone_ros_ws/src/drone_app/test/BBoxTest.cpp
Flytte/flytte
36e2dc886c7437c3e3fff5a082296d5bc1f10bd7
[ "BSD-3-Clause" ]
null
null
null
#include "common/BBox.hpp" #include <gtest/gtest.h> TEST(BBox, defaultConstructor) { BBox box; EXPECT_EQ(0, box.posX); EXPECT_EQ(0, box.posY); EXPECT_EQ(0, box.w); EXPECT_EQ(0, box.h); EXPECT_EQ(0, box.rotX); EXPECT_EQ(0, box.rotY); EXPECT_EQ(0, box.rotZ); } TEST(BBox, copyConstructor) { BBox box0(10, 20, 30, 40, 50, 60, 70); BBox box1(box0); EXPECT_EQ(10, box1.posX); EXPECT_EQ(20, box1.posY); EXPECT_EQ(30, box1.w); EXPECT_EQ(40, box1.h); EXPECT_EQ(50, box1.rotX); EXPECT_EQ(60, box1.rotY); EXPECT_EQ(70, box1.rotZ); } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
19
42
0.623044
Flytte
ccb5c6c9346c1270e6beacf912fe3b038cdd64fb
4,923
cpp
C++
owGame/Sky/Sky.cpp
Chaos192/OpenWow
1d91a51fafeedadc67122a3e9372ec4637a48434
[ "Apache-2.0" ]
30
2017-09-02T20:25:47.000Z
2021-12-31T10:12:07.000Z
owGame/Sky/Sky.cpp
Chaos192/OpenWow
1d91a51fafeedadc67122a3e9372ec4637a48434
[ "Apache-2.0" ]
null
null
null
owGame/Sky/Sky.cpp
Chaos192/OpenWow
1d91a51fafeedadc67122a3e9372ec4637a48434
[ "Apache-2.0" ]
23
2018-02-04T17:18:33.000Z
2022-03-22T09:45:36.000Z
#include "stdafx.h" // Include #include "SkyManager.h" // General #include "Sky.h" namespace { const float cSkyMultiplier = 36.0f; template<typename T> inline T GetByTimeTemplate(std::vector<Sky::SSkyInterpolatedParam<T>> param, uint32 _time) { if (param.empty()) return T(); T parBegin, parEnd; uint32 timeBegin, timeEnd; uint32_t last = static_cast<uint32>(param.size()) - 1; if (_time < param[0].time) { // interpolate between last and first parBegin = param[last].value; timeBegin = param[last].time; parEnd = param[0].value; timeEnd = param[0].time + C_Game_SecondsInDay; // next day _time += C_Game_SecondsInDay; } else { for (uint32 i = last; i >= 0; i--) { if (_time >= param[i].time) { parBegin = param[i].value; timeBegin = param[i].time; if (i == last) // if current is last, then interpolate with first { parEnd = param[0].value; timeEnd = param[0].time + C_Game_SecondsInDay; } else { parEnd = param[i + 1].value; timeEnd = param[i + 1].time; } break; } } } float tt = (float)(_time - timeBegin) / (float)(timeEnd - timeBegin); return parBegin * (1.0f - tt) + (parEnd * tt); } } Sky::Sky() : m_LightRecord(nullptr) {} Sky::Sky(const CDBCStorage* DBCStorage, const DBC_LightRecord* LightData) : m_LightRecord(LightData) { m_Position.x = m_LightRecord->Get_PositionX() / cSkyMultiplier; m_Position.y = m_LightRecord->Get_PositionY() / cSkyMultiplier; m_Position.z = m_LightRecord->Get_PositionZ() / cSkyMultiplier; m_Range.min = m_LightRecord->Get_RadiusInner() / cSkyMultiplier; m_Range.max = m_LightRecord->Get_RadiusOuter() / cSkyMultiplier; m_IsGlobalSky = (m_Position.x == 0.0f && m_Position.y == 0.0f && m_Position.z == 0.0f); if (m_IsGlobalSky) Log::Info("Sky: [%d] is global sky.", m_LightRecord->Get_ID()); LoadParams(DBCStorage, ESkyParamsNames::SKY_ParamsClear); } Sky::~Sky() {} class SkyParam_Color : public Sky::SSkyInterpolatedParam<ColorRGB> { public: SkyParam_Color(uint32 _time, uint32 _color) : SSkyInterpolatedParam<ColorRGB>(_time, fromRGB(_color)) {} }; class SkyParam_Fog : public Sky::SSkyInterpolatedParam<float> { public: SkyParam_Fog(uint32 _time, float _param) : SSkyInterpolatedParam<float>(_time, _param) {} }; void Sky::LoadParams(const CDBCStorage* DBCStorage, ESkyParamsNames _param) { for (uint32 i = 0; i < ESkyColors::SKY_COLOR_COUNT; i++) m_IntBand_Colors[i].clear(); for (uint32 i = 0; i < ESkyFogs::SKY_FOG_COUNT; i++) m_FloatBand_Fogs[i].clear(); const DBC_LightParamsRecord* paramRecord = DBCStorage->DBC_LightParams()[m_LightRecord->Get_LightParams(_param)]; _ASSERT(paramRecord != nullptr); uint32 paramSet = paramRecord->Get_ID(); //-- LightParams m_Params.HighlightSky = paramRecord->Get_HighlightSky(); m_Params.LightSkyBoxRecord = DBCStorage->DBC_LightSkybox()[paramRecord->Get_LightSkyboxID()]; m_Params.Glow = paramRecord->Get_Glow(); if (m_Params.LightSkyBoxRecord != nullptr) { // TODO //Log::Info("Sky: Skybox name = '%s'.", m_Params.GetSkybox()->Get_Filename().c_str()); } //-- Color params for (uint32 i = 0; i < ESkyColors::SKY_COLOR_COUNT; i++) { const DBC_LightIntBandRecord* lightColorsRecord = DBCStorage->DBC_LightIntBand()[paramSet * ESkyColors::SKY_COLOR_COUNT - (ESkyColors::SKY_COLOR_COUNT - 1) + i]; _ASSERT(lightColorsRecord != nullptr); for (uint32 l = 0; l < lightColorsRecord->Get_Count(); l++) { // Read time & color value m_IntBand_Colors[i].push_back(SkyParam_Color(lightColorsRecord->Get_Times(l), lightColorsRecord->Get_Values(l))); } } //-- Fog, Sun, Clouds param for (uint32 i = 0; i < ESkyFogs::SKY_FOG_COUNT; i++) { const DBC_LightFloatBandRecord* lightFogRecord = DBCStorage->DBC_LightFloatBand()[paramSet * ESkyFogs::SKY_FOG_COUNT - (ESkyFogs::SKY_FOG_COUNT - 1) + i]; _ASSERT(lightFogRecord != nullptr); for (uint32 l = 0; l < lightFogRecord->Get_Count(); l++) { // Read time & fog param float param = lightFogRecord->Get_Values(l); if (i == ESkyFogs::SKY_FOG_DISTANCE) param /= cSkyMultiplier; m_FloatBand_Fogs[i].push_back(SkyParam_Fog(lightFogRecord->Get_Times(l), param)); } } m_Params.WaterAplha[ESkyWaterAlpha::SKY_WATER_SHALLOW] = paramRecord->Get_WaterShallowAlpha(); m_Params.WaterAplha[ESkyWaterAlpha::SKY_WATER_DEEP] = paramRecord->Get_WaterDeepAlpha(); m_Params.WaterAplha[ESkyWaterAlpha::SKY_OCEAN_SHALLOW] = paramRecord->Get_OceanShallowAlpha(); m_Params.WaterAplha[ESkyWaterAlpha::SKY_OCEAN_DEEP] = paramRecord->Get_OceanDeepAlpha(); } SSkyParams& Sky::Interpolate(uint32 _time) { for (uint8 i = 0; i < ESkyColors::SKY_COLOR_COUNT; i++) m_Params.Colors[i] = GetByTimeTemplate(m_IntBand_Colors[i], _time); for (uint8 i = 0; i < ESkyFogs::SKY_FOG_COUNT; i++) m_Params.Fogs[i] = GetByTimeTemplate(m_FloatBand_Fogs[i], _time); return m_Params; }
28.789474
163
0.700995
Chaos192
ccbeadcd7cdc4214ba78636dafecb47cb6bcc123
441
hpp
C++
sort/shaker_sort.hpp
lis411/sorting
57b113849c0a598c96aecc5fe6fd27582f141bfa
[ "MIT" ]
null
null
null
sort/shaker_sort.hpp
lis411/sorting
57b113849c0a598c96aecc5fe6fd27582f141bfa
[ "MIT" ]
null
null
null
sort/shaker_sort.hpp
lis411/sorting
57b113849c0a598c96aecc5fe6fd27582f141bfa
[ "MIT" ]
null
null
null
#ifndef SHAKER_SORT_HPP #define SHAKER_SORT_HPP template<typename Iterator> void shaker_sort(Iterator b, Iterator e) { while(b != e) { for(auto bb = b; std::next(bb) != e; ++bb) { if(*bb > *std::next(bb)) std::swap(*bb, *std::next(bb)); } --e; if(b == e) break; for(auto ee = std::prev(e); ee != b; --ee) { if(*std::prev(ee) > *ee) std::swap(*std::prev(ee), *ee); } ++b; } return; } #endif
11.605263
44
0.530612
lis411
ccc0093f23ef2a08aee93406c0284dec8b6fc9b4
2,725
cpp
C++
AdventOfCode/2020/c.cpp
onexmaster/cp
b78b0f1e586d6977d86c97b32f48fed33f1469af
[ "Apache-2.0", "MIT" ]
null
null
null
AdventOfCode/2020/c.cpp
onexmaster/cp
b78b0f1e586d6977d86c97b32f48fed33f1469af
[ "Apache-2.0", "MIT" ]
null
null
null
AdventOfCode/2020/c.cpp
onexmaster/cp
b78b0f1e586d6977d86c97b32f48fed33f1469af
[ "Apache-2.0", "MIT" ]
null
null
null
// Created by Tanuj Jain #include<bits/stdc++.h> #include<ext/pb_ds/assoc_container.hpp> #include<ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define pb push_back #define mp make_pair # define M_PI 3.14159265358979323846 /* pi */ #define FIO ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); typedef long long ll; typedef pair<int,int> pii; typedef pair<ll,ll>pll; template<class T> using oset=tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; const int INF = 0x3f3f3f3f; int knight_moves[8][2]={{-2,-1},{-1,-2},{1,-2},{2,-1},{-2,1},{-1,2},{1,2},{2,1}}; int moves[4][2]={{0,1},{0,-1},{1,0},{-1,0}}; struct custom_hash { static uint64_t splitmix64(uint64_t x) { // http://xorshift.di.unimi.it/splitmix64.c x += 0x9e3779b97f4a7c15; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9; x = (x ^ (x >> 27)) * 0x94d049bb133111eb; return x ^ (x >> 31); } size_t operator()(uint64_t x) const { static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count(); return splitmix64(x + FIXED_RANDOM); } }; char grid[324][5000]; int main() { FIO; #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif string temp; int i=0; int m; while(getline(cin,temp)) { m=temp.size(); for(int j=0;j<m;j++) grid[i][j]=temp[j]; for(int j=m;j<5000;j++) grid[i][j]=grid[i][j%m]; i++; } ll trees1=0; int sx=0,sy=0; while(sx<323) { //cout<<sx<<" "<<sy<<endl; if(grid[sx][sy]=='#') trees1++; sy+=3; sx+=1; } ll trees2=0; sx=0,sy=0; while(sx<323) { //cout<<sx<<" "<<sy<<endl; if(grid[sx][sy]=='#') trees2++; sy+=1; sx+=1; } ll trees3=0; sx=0,sy=0; while(sx<323) { //cout<<sx<<" "<<sy<<endl; if(grid[sx][sy]=='#') trees3++; sy+=5; sx+=1; } ll trees4=0; sx=0,sy=0; while(sx<323) { //cout<<sx<<" "<<sy<<endl; if(grid[sx][sy]=='#') trees4++; sy+=7; sx+=1; } ll trees5=0; sx=0,sy=0; while(sx<323) { //cout<<sx<<" "<<sy<<endl; if(grid[sx][sy]=='#') trees5++; sy+=1; sx+=2; } cout<<trees1*trees2*trees3*trees4*trees5; return 0; }
25
106
0.473394
onexmaster
ccc27e2f3eb0a50fb1390a42327c25e9cc291628
2,791
cpp
C++
samples/ListApp/ListApp.cpp
r3dl3g/guipp
3d3179be3022935b46b59f1b988a029abeabfcbf
[ "MIT" ]
null
null
null
samples/ListApp/ListApp.cpp
r3dl3g/guipp
3d3179be3022935b46b59f1b988a029abeabfcbf
[ "MIT" ]
null
null
null
samples/ListApp/ListApp.cpp
r3dl3g/guipp
3d3179be3022935b46b59f1b988a029abeabfcbf
[ "MIT" ]
null
null
null
#include <gui/layout/layout_container.h> #include <gui/layout/adaption_layout.h> #include <gui/ctrl/virtual_view.h> #include <gui/ctrl/file_tree.h> #include <gui/ctrl/std_dialogs.h> // -------------------------------------------------------------------------- int gui_main(const std::vector<std::string>& /*args*/) { using namespace gui; using namespace gui::win; using namespace gui::layout; using namespace gui::ctrl; using namespace gui::core; layout_main_window<gui::layout::horizontal_adaption<>> main; virtual_view<file_list<path_tree::sorted_path_info, default_file_item_drawer, core::selector::multi>> multi_client; virtual_view<file_list<path_tree::sorted_path_info, default_file_item_drawer, core::selector::single>> single_client; virtual_view<file_list<path_tree::sorted_path_info, default_file_item_drawer, core::selector::none>> none_client; multi_client->on_selection_commit([&] () { auto path = multi_client->get_selected_path(); if (sys_fs::is_directory(path)) { multi_client->set_path(path); multi_client.layout(); } }); multi_client->on_key_down<core::keys::up, core::state::alt>([&] () { auto path = multi_client->get_current_path(); multi_client->set_path(path.parent_path()); multi_client.layout(); }); single_client->on_key_down<core::keys::enter>([&] () { auto path = single_client->get_selected_path(); if (sys_fs::is_directory(path)) { single_client->set_path(path); single_client.layout(); } }); single_client->on_key_down<core::keys::up, core::state::alt>([&] () { auto path = single_client->get_current_path(); single_client->set_path(path.parent_path()); single_client.layout(); }); single_client->on_left_btn_dblclk([&] (gui::os::key_state ks, const core::native_point& pt) { const int idx = single_client->get_index_at_point(single_client->surface_to_client(pt)); auto path = single_client->get_selected_path(); message_dialog::show(main, "Info", str_fmt() << "Double click at index: " << idx << "\nfor path; '" << path << "'", "Ok"); }); none_client->on_selection_commit([&] () { auto path = none_client->get_selected_path(); if (sys_fs::is_directory(path)) { none_client->set_path(path); none_client.layout(); } }); main.add({multi_client, single_client, none_client}); main.on_create([&] () { multi_client->set_path("/"); single_client->set_path("/"); none_client->set_path("/"); }); main.create({50, 50, 800, 600}); main.on_destroy(&quit_main_loop); main.set_title("filelist"); main.set_visible(); return run_main_loop(); }
33.626506
95
0.636689
r3dl3g
ccc38e9ee25e0fc1d201b389f548a591f9ab70c3
8,123
cpp
C++
src/plugins/bittorrent/torrenttabfileswidget.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
120
2015-01-22T14:10:39.000Z
2021-11-25T12:57:16.000Z
src/plugins/bittorrent/torrenttabfileswidget.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
8
2015-02-07T19:38:19.000Z
2017-11-30T20:18:28.000Z
src/plugins/bittorrent/torrenttabfileswidget.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
33
2015-02-07T16:59:55.000Z
2021-10-12T00:36:40.000Z
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt) **********************************************************************/ #include "torrenttabfileswidget.h" #include <QMenu> #include <QTimer> #include <QSortFilterProxyModel> #include <util/gui/clearlineeditaddon.h> #include <util/sll/prelude.h> #include <util/util.h> #include "filesviewdelegate.h" #include "ltutils.h" #include "torrentfilesmodel.h" namespace LC::BitTorrent { namespace { class FilesProxyModel final : public QSortFilterProxyModel { public: FilesProxyModel (QObject *parent) : QSortFilterProxyModel { parent } { setDynamicSortFilter (true); } protected: bool filterAcceptsRow (int row, const QModelIndex& parent) const override { const auto& idx = sourceModel ()->index (row, TorrentFilesModel::ColumnPath, parent); if (idx.data ().toString ().contains (filterRegExp ().pattern (), Qt::CaseInsensitive)) return true; const auto rc = sourceModel ()->rowCount (idx); for (int i = 0; i < rc; ++i) if (filterAcceptsRow (i, idx)) return true; return false; } }; } TorrentTabFilesWidget::TorrentTabFilesWidget (QWidget *parent) : QWidget { parent } , ProxyModel_ { new FilesProxyModel { this } } { Ui_.setupUi (this); new Util::ClearLineEditAddon { GetProxyHolder (), Ui_.SearchLine_ }; ProxyModel_->setSortRole (TorrentFilesModel::RoleSort); Ui_.FilesView_->setItemDelegate (new FilesViewDelegate (Ui_.FilesView_)); Ui_.FilesView_->setModel (ProxyModel_); connect (Ui_.FilesView_->selectionModel (), &QItemSelectionModel::currentChanged, this, &TorrentTabFilesWidget::HandleFileSelected); HandleFileSelected ({}); connect (Ui_.SearchLine_, &QLineEdit::textChanged, [this] (const QString& text) { ProxyModel_->setFilterFixedString (text); Ui_.FilesView_->expandAll (); }); connect (Ui_.FilePriorityRegulator_, qOverload<int> (&QSpinBox::valueChanged), [this] (int prio) { for (auto idx : GetSelectedIndexes ()) { idx = idx.siblingAtColumn (TorrentFilesModel::ColumnPriority); Ui_.FilesView_->model ()->setData (idx, prio); } }); connect (Ui_.FilesView_, &QTreeView::customContextMenuRequested, this, &TorrentTabFilesWidget::ShowContextMenu); } void TorrentTabFilesWidget::SetAlertDispatcher (AlertDispatcher& dispatcher) { AlertDispatcher_ = &dispatcher; } void TorrentTabFilesWidget::SetCurrentIndex (const QModelIndex& index) { ProxyModel_->setSourceModel (nullptr); delete CurrentFilesModel_; Ui_.SearchLine_->clear (); const auto& handle = GetTorrentHandle (index); CurrentFilesModel_ = new TorrentFilesModel { handle, *AlertDispatcher_ }; ProxyModel_->setSourceModel (CurrentFilesModel_); QTimer::singleShot (0, Ui_.FilesView_, &QTreeView::expandAll); const auto filesCount = GetFilesCount (handle); Ui_.SearchLine_->setVisible (filesCount > 1); const auto& fm = Ui_.FilesView_->fontMetrics (); Ui_.FilesView_->header ()->resizeSection (0, fm.horizontalAdvance (QStringLiteral ("some very long file name or a directory name in a torrent file"))); } QList<QModelIndex> TorrentTabFilesWidget::GetSelectedIndexes () const { const auto selModel = Ui_.FilesView_->selectionModel (); const auto& current = selModel->currentIndex (); auto selected = selModel->selectedRows (); if (!selected.contains (current)) selected.append (current); return selected; } void TorrentTabFilesWidget::HandleFileSelected (const QModelIndex& index) { Ui_.FilePriorityRegulator_->setEnabled (index.isValid ()); if (!index.isValid ()) { Ui_.FilePath_->setText ({}); Ui_.FileProgress_->setText ({}); Ui_.FilePriorityRegulator_->blockSignals (true); Ui_.FilePriorityRegulator_->setValue (0); Ui_.FilePriorityRegulator_->blockSignals (false); } else { auto path = index.data (TorrentFilesModel::RoleFullPath).toString (); path = fontMetrics ().elidedText (path, Qt::ElideLeft, Ui_.FilePath_->width ()); Ui_.FilePath_->setText (path); auto sindex = index.siblingAtColumn (TorrentFilesModel::ColumnProgress); double progress = sindex.data (TorrentFilesModel::RoleProgress).toDouble (); qint64 size = sindex.data (TorrentFilesModel::RoleSize).toLongLong (); qint64 done = progress * size; Ui_.FileProgress_->setText (tr ("%1% (%2 of %3)") .arg (progress * 100, 0, 'f', 1) .arg (Util::MakePrettySize (done), Util::MakePrettySize (size))); Ui_.FilePriorityRegulator_->blockSignals (true); if (index.model ()->rowCount (index)) Ui_.FilePriorityRegulator_->setValue (1); else { auto prindex = index.siblingAtColumn (TorrentFilesModel::ColumnPriority); int priority = prindex.data ().toInt (); Ui_.FilePriorityRegulator_->setValue (priority); } Ui_.FilePriorityRegulator_->blockSignals (false); } } void TorrentTabFilesWidget::ShowContextMenu (const QPoint& pos) { const auto itm = GetProxyHolder ()->GetIconThemeManager (); QMenu menu; const auto& selected = GetSelectedIndexes (); const auto& openable = Util::Filter (selected, [] (const QModelIndex& idx) { const auto progress = idx.data (TorrentFilesModel::RoleProgress).toDouble (); return idx.model ()->rowCount (idx) || std::abs (progress - 1) < std::numeric_limits<double>::epsilon (); }); if (!openable.isEmpty ()) { const auto& openActName = openable.size () == 1 ? tr ("Open file") : tr ("Open %n file(s)", 0, openable.size ()); const auto openAct = menu.addAction (openActName, this, [openable, this] { for (const auto& idx : openable) CurrentFilesModel_->HandleFileActivated (ProxyModel_->mapToSource (idx)); }); openAct->setIcon (itm->GetIcon (QStringLiteral ("document-open"))); menu.addSeparator (); } const auto& cachedRoots = Util::Map (selected, [] (const QModelIndex& idx) { return qMakePair (idx, idx.data (TorrentFilesModel::RoleFullPath).toString ()); }); const auto& priorityRoots = Util::Map (Util::Filter (cachedRoots, [&cachedRoots] (const QPair<QModelIndex, QString>& idxPair) { return std::none_of (cachedRoots.begin (), cachedRoots.end (), [&idxPair] (const QPair<QModelIndex, QString>& existing) { return idxPair.first != existing.first && idxPair.second.startsWith (existing.second); }); }), [] (const QPair<QModelIndex, QString>& idxPair) { return idxPair.first.siblingAtColumn (TorrentFilesModel::ColumnPriority); }); if (!priorityRoots.isEmpty ()) { const auto subMenu = menu.addMenu (tr ("Change priority")); const QList<QPair<int, QString>> descrs { { 0, tr ("File is not downloaded.") }, { 1, tr ("Normal priority, download order depends on availability.") }, { 2, tr ("Pieces are preferred over the pieces with same availability.") }, { 3, tr ("Empty pieces are preferred just as much as partial pieces.") }, { 4, tr ("Empty pieces are preferred over partial pieces with the same availability.") }, { 5, tr ("Same as previous.") }, { 6, tr ("Pieces are considered to have highest availability.") }, { 7, tr ("Maximum file priority.") } }; for (const auto& descr : descrs) { const auto prio = descr.first; subMenu->addAction (QString::number (prio) + " " + descr.second, this, [this, prio, priorityRoots] { for (const auto& idx : priorityRoots) ProxyModel_->setData (idx, prio); }); } } menu.addAction (tr ("Expand all"), Ui_.FilesView_, &QTreeView::expandAll); menu.addAction (tr ("Collapse all"), Ui_.FilesView_, &QTreeView::collapseAll); menu.exec (Ui_.FilesView_->viewport ()->mapToGlobal (pos)); } }
31.242308
110
0.666256
Maledictus
ccc437b9b6c4dfcc1e5ae048e15d00a691019e2c
1,530
hpp
C++
src/sounds/Mp3Decoder.hpp
vgmoose/space
8f72c1d155b16b9705aa248ae8e84989f28fb498
[ "MIT" ]
25
2016-02-02T14:13:29.000Z
2018-04-27T18:57:43.000Z
src/sounds/Mp3Decoder.hpp
vgmoose/wiiu-space
8f72c1d155b16b9705aa248ae8e84989f28fb498
[ "MIT" ]
14
2016-03-18T17:41:59.000Z
2017-01-04T11:00:25.000Z
src/sounds/Mp3Decoder.hpp
vgmoose/space
8f72c1d155b16b9705aa248ae8e84989f28fb498
[ "MIT" ]
8
2016-03-18T07:05:24.000Z
2018-04-24T14:38:11.000Z
/*************************************************************************** * Copyright (C) 2010 * by Dimok * * 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. * * for WiiXplorer 2010 ***************************************************************************/ #include <mad.h> #include "SoundDecoder.hpp" class Mp3Decoder : public SoundDecoder { public: Mp3Decoder(const char * filepath); Mp3Decoder(const u8 * sound, int len); virtual ~Mp3Decoder(); int Rewind(); int Read(u8 * buffer, int buffer_size, int pos); protected: void OpenFile(); struct mad_stream Stream; struct mad_frame Frame; struct mad_synth Synth; mad_timer_t Timer; u8 * GuardPtr; u8 * ReadBuffer; u32 SynthPos; };
31.875
77
0.660131
vgmoose
ccc55ae9d8e24241afd8176f50ccf373a55130ec
2,893
hpp
C++
inc/Helpers/Parameter.hpp
ACubeSAT/ecss-services
92d81c1ff455d9baef9417e656388c98ec552751
[ "MIT" ]
null
null
null
inc/Helpers/Parameter.hpp
ACubeSAT/ecss-services
92d81c1ff455d9baef9417e656388c98ec552751
[ "MIT" ]
null
null
null
inc/Helpers/Parameter.hpp
ACubeSAT/ecss-services
92d81c1ff455d9baef9417e656388c98ec552751
[ "MIT" ]
null
null
null
#ifndef ECSS_SERVICES_PARAMETER_HPP #define ECSS_SERVICES_PARAMETER_HPP #include "etl/String.hpp" #include "Message.hpp" #include "ECSS_Definitions.hpp" /** * Implementation of a Parameter field, as specified in ECSS-E-ST-70-41C. * * @author Grigoris Pavlakis <grigpavl@ece.auth.gr> * @author Athanasios Theocharis <athatheoc@gmail.com> * * @section Introduction * The Parameter class implements a way of storing and updating system parameters * of arbitrary size and type, while avoiding std::any and dynamic memory allocation. * It is split in two distinct parts: * 1) an abstract \ref ParameterBase class which provides a * common data type used to create any pointers to \ref Parameter objects, as well as * virtual functions for accessing the parameter's data part, and * 2) a templated \ref Parameter used to store any type-specific parameter information, * such as the actual data field where the parameter's value will be stored. * * @section Architecture Rationale * The ST[20] Parameter service is implemented with the need of arbitrary type storage * in mind, while avoiding any use of dynamic memory allocation, a requirement for use * in embedded systems. Since lack of Dynamic Memory Access precludes usage of stl::any * and the need for truly arbitrary (even for template-based objects like etl::string) type storage * would exclude from consideration constructs like etl::variant due to limitations on * the number of supported distinct types, a custom solution was needed. * Furthermore, the \ref ParameterService should provide ID-based access to parameters. */ class ParameterBase { public: virtual void appendValueToMessage(Message& message) = 0; virtual void setValueFromMessage(Message& message) = 0; virtual double getValueAsDouble() = 0; }; /** * Implementation of a parameter containing its value. See \ref ParameterBase for more information. * @tparam DataType The type of the Parameter value. This is the type used for transmission and reception * as per the PUS. */ template <typename DataType> class Parameter : public ParameterBase { private: DataType currentValue; public: explicit Parameter(DataType initialValue) : currentValue(initialValue) {} inline void setValue(DataType value) { currentValue = value; } inline DataType getValue() { return currentValue; } inline double getValueAsDouble() override { return static_cast<double>(currentValue); } /** * Given an ECSS message that contains this parameter as its first input, this loads the value from that paremeter */ inline void setValueFromMessage(Message& message) override { currentValue = message.read<DataType>(); }; /** * Appends the parameter as an ECSS value to an ECSS Message */ inline void appendValueToMessage(Message& message) override { message.append<DataType>(currentValue); }; }; #endif // ECSS_SERVICES_PARAMETER_HPP
35.716049
115
0.766678
ACubeSAT
ccd75449587615b2d6b8be5cbf43c63ca7aea6b1
120,789
cpp
C++
olp-cpp-sdk-dataservice-read/test/unit/src/CatalogClientTest.cpp
ystefinko/here-olp-edge-sdk-cpp
59f814cf98acd8f6c62572104a21ebdff4027171
[ "Apache-2.0" ]
1
2021-01-27T13:10:32.000Z
2021-01-27T13:10:32.000Z
olp-cpp-sdk-dataservice-read/test/unit/src/CatalogClientTest.cpp
ystefinko/here-olp-edge-sdk-cpp
59f814cf98acd8f6c62572104a21ebdff4027171
[ "Apache-2.0" ]
null
null
null
olp-cpp-sdk-dataservice-read/test/unit/src/CatalogClientTest.cpp
ystefinko/here-olp-edge-sdk-cpp
59f814cf98acd8f6c62572104a21ebdff4027171
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2019 HERE Europe B.V. * * 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. * * SPDX-License-Identifier: Apache-2.0 * License-Filename: LICENSE */ #include <chrono> #include <iostream> #include <regex> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include <olp/authentication/AuthenticationCredentials.h> #include <olp/authentication/Settings.h> #include <olp/authentication/TokenEndpoint.h> #include <olp/authentication/TokenProvider.h> #include <olp/authentication/TokenResult.h> #include <olp/core/cache/DefaultCache.h> #include <olp/core/client/CancellationToken.h> #include <olp/core/client/HRN.h> #include <olp/core/client/OlpClient.h> #include <olp/core/client/OlpClientFactory.h> #include <olp/core/logging/Log.h> #include <olp/core/network/HttpResponse.h> #include <olp/core/network/Network.h> #include <olp/core/network/NetworkConfig.h> #include <olp/core/network/NetworkRequest.h> #include <olp/core/porting/make_unique.h> #include <olp/core/utils/Dir.h> #include <olp/dataservice/read/PrefetchTilesRequest.h> #include "HttpResponses.h" #include "olp/dataservice/read/CatalogClient.h" #include "olp/dataservice/read/CatalogRequest.h" #include "olp/dataservice/read/CatalogVersionRequest.h" #include "olp/dataservice/read/DataRequest.h" #include "olp/dataservice/read/PartitionsRequest.h" #include "olp/dataservice/read/model/Catalog.h" #include "testutils/CustomParameters.hpp" using namespace olp::dataservice::read; using namespace testing; #ifdef _WIN32 const std::string k_client_test_dir("\\catalog_client_test"); const std::string k_client_test_cache_dir("\\catalog_client_test\\cache"); #else const std::string k_client_test_dir("/catalog_client_test"); const std::string k_client_test_cache_dir("/catalog_client_test/cache"); #endif class MockHandler { public: MOCK_METHOD3(op, olp::client::CancellationToken( const olp::network::NetworkRequest& request, const olp::network::NetworkConfig& config, const olp::client::NetworkAsyncCallback& callback)); olp::client::CancellationToken operator()( const olp::network::NetworkRequest& request, const olp::network::NetworkConfig& config, const olp::client::NetworkAsyncCallback& callback) { return op(request, config, callback); } }; enum CacheType { InMemory = 0, Disk, Both }; using ClientTestParameter = std::pair<bool, CacheType>; class CatalogClientTestBase : public ::testing::TestWithParam<ClientTestParameter> { protected: virtual bool isOnlineTest() { return std::get<0>(GetParam()); } std::string GetTestCatalog() { static std::string mockCatalog{"hrn:here:data:::hereos-internal-test-v2"}; return isOnlineTest() ? CustomParameters::getArgument("catalog") : mockCatalog; } std::string PrintError(const olp::client::ApiError& error) { std::ostringstream resultStream; resultStream << "ERROR: code: " << static_cast<int>(error.GetErrorCode()) << ", status: " << error.GetHttpStatusCode() << ", message: " << error.GetMessage(); return resultStream.str(); } template <typename T> T GetExecutionTime(std::function<T()> func) { auto startTime = std::chrono::high_resolution_clock::now(); auto result = func(); auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> time = end - startTime; std::cout << "duration: " << time.count() * 1000000 << " us" << std::endl; return result; } protected: std::shared_ptr<olp::client::OlpClientSettings> settings_; std::shared_ptr<olp::client::OlpClient> client_; std::shared_ptr<MockHandler> handler_; }; class CatalogClientOnlineTest : public CatalogClientTestBase { void SetUp() { // olp::logging::Log::setLevel(olp::logging::Level::Trace); handler_ = std::make_shared<MockHandler>(); olp::authentication::TokenProviderDefault provider( CustomParameters::getArgument("appid"), CustomParameters::getArgument("secret")); olp::client::AuthenticationSettings authSettings; authSettings.provider = provider; settings_ = std::make_shared<olp::client::OlpClientSettings>(); settings_->authentication_settings = authSettings; client_ = olp::client::OlpClientFactory::Create(*settings_); } }; INSTANTIATE_TEST_SUITE_P(TestOnline, CatalogClientOnlineTest, ::testing::Values(std::make_pair(true, Both))); TEST_P(CatalogClientOnlineTest, GetCatalog) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::CatalogRequest(); auto catalogResponse = GetExecutionTime<olp::dataservice::read::CatalogResponse>([&] { auto future = catalogClient->GetCatalog(request); return future.GetFuture().get(); }); ASSERT_TRUE(catalogResponse.IsSuccessful()) << PrintError(catalogResponse.GetError()); } TEST_P(CatalogClientOnlineTest, GetPartitionsWithInvalidHrn) { olp::client::HRN hrn("hrn:here:data:::nope-test-v2"); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("testlayer"); auto partitionsResponse = GetExecutionTime<olp::dataservice::read::PartitionsResponse>([&] { auto future = catalogClient->GetPartitions(request); return future.GetFuture().get(); }); ASSERT_FALSE(partitionsResponse.IsSuccessful()); ASSERT_EQ(403, partitionsResponse.GetError().GetHttpStatusCode()); } TEST_P(CatalogClientOnlineTest, GetPartitions) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("testlayer"); auto partitionsResponse = GetExecutionTime<olp::dataservice::read::PartitionsResponse>([&] { auto future = catalogClient->GetPartitions(request); return future.GetFuture().get(); }); ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(4u, partitionsResponse.GetResult().GetPartitions().size()); } TEST_P(CatalogClientOnlineTest, GetPartitionsForInvalidLayer) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("invalidLayer"); auto partitionsResponse = GetExecutionTime<olp::dataservice::read::PartitionsResponse>([&] { auto future = catalogClient->GetPartitions(request); return future.GetFuture().get(); }); ASSERT_FALSE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(olp::client::ErrorCode::InvalidArgument, partitionsResponse.GetError().GetErrorCode()); } TEST_P(CatalogClientOnlineTest, GetDataWithInvalidHrn) { olp::client::HRN hrn("hrn:here:data:::nope-test-v2"); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer") .WithDataHandle("d5d73b64-7365-41c3-8faf-aa6ad5bab135"); auto dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_FALSE(dataResponse.IsSuccessful()); ASSERT_EQ(403, dataResponse.GetError().GetHttpStatusCode()); } TEST_P(CatalogClientOnlineTest, GetDataWithHandle) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer") .WithDataHandle("d5d73b64-7365-41c3-8faf-aa6ad5bab135"); auto dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); std::string dataStr(dataResponse.GetResult()->begin(), dataResponse.GetResult()->end()); ASSERT_EQ("DT_2_0031", dataStr); } TEST_P(CatalogClientOnlineTest, GetDataWithInvalidDataHandle) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithDataHandle("invalidDataHandle"); auto dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_FALSE(dataResponse.IsSuccessful()); ASSERT_EQ(404, dataResponse.GetError().GetHttpStatusCode()); } TEST_P(CatalogClientOnlineTest, GetDataHandleWithInvalidLayer) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("invalidLayer").WithDataHandle("invalidDataHandle"); auto dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_FALSE(dataResponse.IsSuccessful()); ASSERT_EQ(olp::client::ErrorCode::InvalidArgument, dataResponse.GetError().GetErrorCode()); } TEST_P(CatalogClientOnlineTest, GetDataWithPartitionId) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("269"); auto dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); std::string dataStr(dataResponse.GetResult()->begin(), dataResponse.GetResult()->end()); ASSERT_EQ("DT_2_0031", dataStr); } TEST_P(CatalogClientOnlineTest, GetDataWithPartitionIdVersion2) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("269").WithVersion(2); auto dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); std::string dataStr(dataResponse.GetResult()->begin(), dataResponse.GetResult()->end()); ASSERT_EQ("DT_2_0031", dataStr); } TEST_P(CatalogClientOnlineTest, GetDataWithPartitionIdInvalidVersion) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("269").WithVersion(10); auto dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_FALSE(dataResponse.IsSuccessful()); ASSERT_EQ(olp::client::ErrorCode::BadRequest, dataResponse.GetError().GetErrorCode()); ASSERT_EQ(400, dataResponse.GetError().GetHttpStatusCode()); request.WithVersion(-1); dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_FALSE(dataResponse.IsSuccessful()); ASSERT_EQ(olp::client::ErrorCode::BadRequest, dataResponse.GetError().GetErrorCode()); ASSERT_EQ(400, dataResponse.GetError().GetHttpStatusCode()); } TEST_P(CatalogClientOnlineTest, GetPartitionsVersion2) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("testlayer").WithVersion(2); auto partitionsResponse = GetExecutionTime<olp::dataservice::read::PartitionsResponse>([&] { auto future = catalogClient->GetPartitions(request); return future.GetFuture().get(); }); ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_LT(0, partitionsResponse.GetResult().GetPartitions().size()); } TEST_P(CatalogClientOnlineTest, GetPartitionsInvalidVersion) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("testlayer").WithVersion(10); auto partitionsResponse = GetExecutionTime<olp::dataservice::read::PartitionsResponse>([&] { auto future = catalogClient->GetPartitions(request); return future.GetFuture().get(); }); ASSERT_FALSE(partitionsResponse.IsSuccessful()); ASSERT_EQ(olp::client::ErrorCode::BadRequest, partitionsResponse.GetError().GetErrorCode()); ASSERT_EQ(400, partitionsResponse.GetError().GetHttpStatusCode()); request.WithVersion(-1); partitionsResponse = GetExecutionTime<olp::dataservice::read::PartitionsResponse>([&] { auto future = catalogClient->GetPartitions(request); return future.GetFuture().get(); }); ASSERT_FALSE(partitionsResponse.IsSuccessful()); ASSERT_EQ(olp::client::ErrorCode::BadRequest, partitionsResponse.GetError().GetErrorCode()); ASSERT_EQ(400, partitionsResponse.GetError().GetHttpStatusCode()); } TEST_P(CatalogClientOnlineTest, GetDataWithNonExistentPartitionId) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("noPartition"); auto dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_FALSE(dataResponse.GetResult()); } TEST_P(CatalogClientOnlineTest, GetDataWithInvalidLayerId) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("invalidLayer").WithPartitionId("269"); auto dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_FALSE(dataResponse.IsSuccessful()); ASSERT_EQ(olp::client::ErrorCode::InvalidArgument, dataResponse.GetError().GetErrorCode()); } TEST_P(CatalogClientOnlineTest, GetDataWithInlineField) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("3"); auto dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); std::string dataStr(dataResponse.GetResult()->begin(), dataResponse.GetResult()->end()); ASSERT_EQ(0u, dataStr.find("data:")); } TEST_P(CatalogClientOnlineTest, GetDataWithEmptyField) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("1"); auto dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_FALSE(dataResponse.GetResult()); } TEST_P(CatalogClientOnlineTest, GetDataCompressed) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("here_van_wc2018_pool"); auto dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0u, dataResponse.GetResult()->size()); auto requestCompressed = olp::dataservice::read::DataRequest(); requestCompressed.WithLayerId("testlayer_gzip") .WithPartitionId("here_van_wc2018_pool"); auto dataResponseCompressed = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(requestCompressed); return future.GetFuture().get(); }); ASSERT_TRUE(dataResponseCompressed.IsSuccessful()) << PrintError(dataResponseCompressed.GetError()); ASSERT_LT(0u, dataResponseCompressed.GetResult()->size()); ASSERT_EQ(dataResponse.GetResult()->size(), dataResponseCompressed.GetResult()->size()); } void dumpTileKey(const olp::geo::TileKey& tileKey) { std::cout << "Tile: " << tileKey.ToHereTile() << ", level: " << tileKey.Level() << ", parent: " << tileKey.Parent().ToHereTile() << std::endl; } TEST_P(CatalogClientOnlineTest, Prefetch) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); std::vector<olp::geo::TileKey> tileKeys; tileKeys.emplace_back(olp::geo::TileKey::FromHereTile("5904591")); auto request = olp::dataservice::read::PrefetchTilesRequest() .WithLayerId("hype-test-prefetch") .WithTileKeys(tileKeys) .WithMinLevel(10) .WithMaxLevel(12); auto future = catalogClient->PrefetchTiles(request); auto response = future.GetFuture().get(); ASSERT_TRUE(response.IsSuccessful()); auto& result = response.GetResult(); for (auto tileResult : result) { ASSERT_TRUE(tileResult->IsSuccessful()); ASSERT_TRUE(tileResult->tile_key_.IsValid()); dumpTileKey(tileResult->tile_key_); } ASSERT_EQ(6u, result.size()); // Second part, use the cache, fetch a partition that's the child of 5904591 { auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("hype-test-prefetch") .WithPartitionId("23618365") .WithFetchOption(FetchOptions::CacheOnly); auto future = catalogClient->GetData(request); auto dataResponse = future.GetFuture().get(); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); } // The parent of 5904591 should be fetched too { auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("hype-test-prefetch") .WithPartitionId("1476147") .WithFetchOption(FetchOptions::CacheOnly); auto future = catalogClient->GetData(request); auto dataResponse = future.GetFuture().get(); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); } } //** ** ** ** MOCK TESTS ** ** ** ** **// MATCHER_P(IsGetRequest, url, "") { // uri, verb, null body return olp::network::NetworkRequest::HttpVerb::GET == arg.Verb() && url == arg.Url() && (!arg.Content() || arg.Content()->empty()); } olp::client::NetworkAsyncHandler setsPromiseWaitsAndReturns( std::shared_ptr<std::promise<void>> preSignal, std::shared_ptr<std::promise<void>> waitForSignal, olp::network::HttpResponse response, std::shared_ptr<std::promise<void>> postSignal = std::make_shared<std::promise<void>>()) { return [preSignal, waitForSignal, response, postSignal]( const olp::network::NetworkRequest& request, const olp::network::NetworkConfig& /*config*/, const olp::client::NetworkAsyncCallback& callback) -> olp::client::CancellationToken { auto completed = std::make_shared<std::atomic_bool>(false); std::thread([request, preSignal, waitForSignal, completed, callback, response, postSignal]() { // emulate a small response delay std::this_thread::sleep_for(std::chrono::milliseconds(50)); preSignal->set_value(); waitForSignal->get_future().get(); if (!completed->exchange(true)) { callback(response); } postSignal->set_value(); }) .detach(); return olp::client::CancellationToken([request, completed, callback, postSignal]() { if (!completed->exchange(true)) { callback({olp::network::Network::ErrorCode::Cancelled, "Cancelled"}); } }); }; } olp::client::NetworkAsyncHandler returnsResponse( olp::network::HttpResponse response) { return [=](const olp::network::NetworkRequest& /*request*/, const olp::network::NetworkConfig& /*config*/, const olp::client::NetworkAsyncCallback& callback) -> olp::client::CancellationToken { std::thread([callback, response]() { callback(response); }).detach(); return olp::client::CancellationToken(); }; } class CatalogClientMockTest : public CatalogClientTestBase { protected: void SetUp() { handler_ = std::make_shared<MockHandler>(); auto weakHandler = std::weak_ptr<MockHandler>(handler_); auto handle = [weakHandler]( const olp::network::NetworkRequest& request, const olp::network::NetworkConfig& config, const olp::client::NetworkAsyncCallback& callback) -> olp::client::CancellationToken { auto sharedHandler = weakHandler.lock(); if (sharedHandler) { return (*sharedHandler)(request, config, callback); } return olp::client::CancellationToken(); }; settings_ = std::make_shared<olp::client::OlpClientSettings>(); settings_->network_async_handler = handle; client_ = olp::client::OlpClientFactory::Create(*settings_); SetUpCommonNetworkMockCalls(); } void SetUpCommonNetworkMockCalls() { ON_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_CONFIG), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_LOOKUP_CONFIG}))); ON_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .WillByDefault( testing::Invoke(returnsResponse({200, HTTP_RESPONSE_CONFIG}))); ON_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_METADATA), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_LOOKUP_METADATA}))); ON_CALL(*handler_, op(IsGetRequest(URL_LATEST_CATALOG_VERSION), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_LATEST_CATALOG_VERSION}))); ON_CALL(*handler_, op(IsGetRequest(URL_LAYER_VERSIONS), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_LAYER_VERSIONS}))); ON_CALL(*handler_, op(IsGetRequest(URL_PARTITIONS), testing::_, testing::_)) .WillByDefault( testing::Invoke(returnsResponse({200, HTTP_RESPONSE_PARTITIONS}))); ON_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_QUERY), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_LOOKUP_QUERY}))); ON_CALL(*handler_, op(IsGetRequest(URL_QUERY_PARTITION_269), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_PARTITION_269}))); ON_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_BLOB), testing::_, testing::_)) .WillByDefault( testing::Invoke(returnsResponse({200, HTTP_RESPONSE_LOOKUP_BLOB}))); ON_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_269), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_BLOB_DATA_269}))); ON_CALL(*handler_, op(IsGetRequest(URL_PARTITION_3), testing::_, testing::_)) .WillByDefault( testing::Invoke(returnsResponse({200, HTTP_RESPONSE_PARTITION_3}))); ON_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_VOLATILE_BLOB), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_LOOKUP_VOLATILE_BLOB}))); ON_CALL(*handler_, op(IsGetRequest(URL_LAYER_VERSIONS_V2), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_LAYER_VERSIONS_V2}))); ON_CALL(*handler_, op(IsGetRequest(URL_PARTITIONS_V2), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_PARTITIONS_V2}))); ON_CALL(*handler_, op(IsGetRequest(URL_QUERY_PARTITION_269_V2), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_PARTITION_269_V2}))); ON_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_269_V2), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_BLOB_DATA_269_V2}))); ON_CALL(*handler_, op(IsGetRequest(URL_QUERY_PARTITION_269_V10), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({400, HTTP_RESPONSE_INVALID_VERSION_V10}))); ON_CALL(*handler_, op(IsGetRequest(URL_QUERY_PARTITION_269_VN1), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({400, HTTP_RESPONSE_INVALID_VERSION_VN1}))); ON_CALL(*handler_, op(IsGetRequest(URL_LAYER_VERSIONS_V10), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({400, HTTP_RESPONSE_INVALID_VERSION_V10}))); ON_CALL(*handler_, op(IsGetRequest(URL_LAYER_VERSIONS_VN1), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({400, HTTP_RESPONSE_INVALID_VERSION_VN1}))); ON_CALL(*handler_, op(IsGetRequest(URL_CONFIG_V2), testing::_, testing::_)) .WillByDefault( testing::Invoke(returnsResponse({200, HTTP_RESPONSE_CONFIG_V2}))); ON_CALL(*handler_, op(IsGetRequest(URL_QUADKEYS_23618364), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_QUADKEYS_23618364}))); ON_CALL(*handler_, op(IsGetRequest(URL_QUADKEYS_1476147), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_QUADKEYS_1476147}))); ON_CALL(*handler_, op(IsGetRequest(URL_QUADKEYS_5904591), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_QUADKEYS_5904591}))); ON_CALL(*handler_, op(IsGetRequest(URL_QUADKEYS_369036), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_QUADKEYS_369036}))); ON_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_PREFETCH_1), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_BLOB_DATA_PREFETCH_1}))); ON_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_PREFETCH_2), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_BLOB_DATA_PREFETCH_2}))); ON_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_PREFETCH_3), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_BLOB_DATA_PREFETCH_3}))); ON_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_PREFETCH_4), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_BLOB_DATA_PREFETCH_4}))); ON_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_PREFETCH_5), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_BLOB_DATA_PREFETCH_5}))); ON_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_PREFETCH_6), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_BLOB_DATA_PREFETCH_6}))); ON_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_PREFETCH_7), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_BLOB_DATA_PREFETCH_7}))); // Catch any non-interesting network calls that don't need to be verified EXPECT_CALL(*handler_, op(testing::_, testing::_, testing::_)) .Times(testing::AtLeast(0)); } }; INSTANTIATE_TEST_SUITE_P(TestMock, CatalogClientMockTest, ::testing::Values(std::make_pair(false, Both))); TEST_P(CatalogClientMockTest, GetCatalog) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .Times(1); auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_); catalogClient = nullptr; // Release crash. Do delete this line if you found it. auto request = CatalogRequest(); auto future = catalogClient->GetCatalog(request); CatalogResponse catalogResponse = future.GetFuture().get(); ASSERT_TRUE(catalogResponse.IsSuccessful()) << PrintError(catalogResponse.GetError()); } TEST_P(CatalogClientMockTest, GetCatalogCallback) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .Times(1); auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_); auto request = CatalogRequest(); std::promise<CatalogResponse> promise; CatalogResponseCallback callback = [&promise](CatalogResponse response) { promise.set_value(response); }; catalogClient->GetCatalog(request, callback); CatalogResponse catalogResponse = promise.get_future().get(); ASSERT_TRUE(catalogResponse.IsSuccessful()) << PrintError(catalogResponse.GetError()); } TEST_P(CatalogClientMockTest, GetCatalog403) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke(returnsResponse({403, HTTP_RESPONSE_403}))); auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_); auto request = CatalogRequest(); auto future = catalogClient->GetCatalog(request); CatalogResponse catalogResponse = future.GetFuture().get(); ASSERT_FALSE(catalogResponse.IsSuccessful()) << PrintError(catalogResponse.GetError()); ASSERT_EQ(403, catalogResponse.GetError().GetHttpStatusCode()); } TEST_P(CatalogClientMockTest, GetPartitions) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_PARTITIONS), testing::_, testing::_)) .Times(1); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("testlayer"); auto future = catalogClient->GetPartitions(request); auto partitionsResponse = future.GetFuture().get(); ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(4u, partitionsResponse.GetResult().GetPartitions().size()); } TEST_P(CatalogClientMockTest, GetDataWithPartitionId) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_269), testing::_, testing::_)) .Times(1); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("269"); auto future = catalogClient->GetData(request); auto dataResponse = future.GetFuture().get(); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); std::string dataStr(dataResponse.GetResult()->begin(), dataResponse.GetResult()->end()); ASSERT_EQ("DT_2_0031", dataStr); } TEST_P(CatalogClientMockTest, GetDataWithInlineField) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_PARTITION_3), testing::_, testing::_)) .Times(1); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("3"); auto future = catalogClient->GetData(request); auto dataResponse = future.GetFuture().get(); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); std::string dataStr(dataResponse.GetResult()->begin(), dataResponse.GetResult()->end()); ASSERT_EQ(0u, dataStr.find("data:")); } TEST_P(CatalogClientMockTest, GetEmptyPartitions) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_PARTITIONS), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_EMPTY_PARTITIONS}))); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("testlayer"); auto future = catalogClient->GetPartitions(request); auto partitionsResponse = future.GetFuture().get(); ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(0u, partitionsResponse.GetResult().GetPartitions().size()); } TEST_P(CatalogClientMockTest, GetVolatileDataHandle) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest( "https://volatile-blob-ireland.data.api.platform.here.com/" "blobstore/v1/catalogs/hereos-internal-test-v2/layers/" "testlayer_volatile/data/volatileHandle"), testing::_, testing::_)) .Times(1) .WillRepeatedly(testing::Invoke(returnsResponse({200, "someData"}))); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer_volatile").WithDataHandle("volatileHandle"); auto future = catalogClient->GetData(request); auto dataResponse = future.GetFuture().get(); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); std::string dataStr(dataResponse.GetResult()->begin(), dataResponse.GetResult()->end()); ASSERT_EQ("someData", dataStr); } TEST_P(CatalogClientMockTest, GetVolatilePartitions) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LATEST_CATALOG_VERSION), testing::_, testing::_)) .Times(0); EXPECT_CALL( *handler_, op(IsGetRequest( "https://metadata.data.api.platform.here.com/metadata/v1/catalogs/" "hereos-internal-test-v2/layers/testlayer_volatile/partitions"), testing::_, testing::_)) .Times(1) .WillRepeatedly( testing::Invoke(returnsResponse({200, HTTP_RESPONSE_PARTITIONS_V2}))); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("testlayer_volatile"); auto future = catalogClient->GetPartitions(request); auto partitionsResponse = future.GetFuture().get(); ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(1u, partitionsResponse.GetResult().GetPartitions().size()); request.WithVersion(18); future = catalogClient->GetPartitions(request); partitionsResponse = future.GetFuture().get(); ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(1u, partitionsResponse.GetResult().GetPartitions().size()); } TEST_P(CatalogClientMockTest, GetVolatileDataByPartitionId) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LATEST_CATALOG_VERSION), testing::_, testing::_)) .Times(0); EXPECT_CALL(*handler_, op(IsGetRequest("https://query.data.api.platform.here.com/query/" "v1/catalogs/hereos-internal-test-v2/layers/" "testlayer_volatile/partitions?partition=269"), testing::_, testing::_)) .Times(1) .WillRepeatedly( testing::Invoke(returnsResponse({200, HTTP_RESPONSE_PARTITIONS_V2}))); EXPECT_CALL( *handler_, op(IsGetRequest( "https://volatile-blob-ireland.data.api.platform.here.com/" "blobstore/v1/catalogs/hereos-internal-test-v2/layers/" "testlayer_volatile/data/4eed6ed1-0d32-43b9-ae79-043cb4256410"), testing::_, testing::_)) .Times(1) .WillRepeatedly(testing::Invoke(returnsResponse({200, "someData"}))); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer_volatile").WithPartitionId("269"); auto future = catalogClient->GetData(request); auto dataResponse = future.GetFuture().get(); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); std::string dataStr(dataResponse.GetResult()->begin(), dataResponse.GetResult()->end()); ASSERT_EQ("someData", dataStr); } TEST_P(CatalogClientMockTest, GetStreamDataHandle) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer_stream").WithDataHandle("streamHandle"); auto future = catalogClient->GetData(request); auto dataResponse = future.GetFuture().get(); ASSERT_FALSE(dataResponse.IsSuccessful()); ASSERT_EQ(olp::client::ErrorCode::ServiceUnavailable, dataResponse.GetError().GetErrorCode()); } TEST_P(CatalogClientMockTest, GetData429Error) { olp::client::HRN hrn(GetTestCatalog()); { testing::InSequence s; EXPECT_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_269), testing::_, testing::_)) .Times(2) .WillRepeatedly(testing::Invoke( returnsResponse({429, "Server busy at the moment."}))); EXPECT_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_269), testing::_, testing::_)) .Times(1); } olp::client::RetrySettings retrySettings; retrySettings.retry_condition = [](const olp::network::HttpResponse& response) { return 429 == response.status; }; settings_->retry_settings = retrySettings; auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer") .WithDataHandle("4eed6ed1-0d32-43b9-ae79-043cb4256432"); auto future = catalogClient->GetData(request); auto dataResponse = future.GetFuture().get(); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); std::string dataStr(dataResponse.GetResult()->begin(), dataResponse.GetResult()->end()); ASSERT_EQ("DT_2_0031", dataStr); } TEST_P(CatalogClientMockTest, GetPartitions429Error) { olp::client::HRN hrn(GetTestCatalog()); { testing::InSequence s; EXPECT_CALL(*handler_, op(IsGetRequest(URL_PARTITIONS), testing::_, testing::_)) .Times(2) .WillRepeatedly(testing::Invoke( returnsResponse({429, "Server busy at the moment."}))); EXPECT_CALL(*handler_, op(IsGetRequest(URL_PARTITIONS), testing::_, testing::_)) .Times(1); } olp::client::RetrySettings retrySettings; retrySettings.retry_condition = [](const olp::network::HttpResponse& response) { return 429 == response.status; }; settings_->retry_settings = retrySettings; auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("testlayer"); auto future = catalogClient->GetPartitions(request); auto partitionsResponse = future.GetFuture().get(); ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(4u, partitionsResponse.GetResult().GetPartitions().size()); } TEST_P(CatalogClientMockTest, ApiLookup429) { olp::client::HRN hrn(GetTestCatalog()); { testing::InSequence s; EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_METADATA), testing::_, testing::_)) .Times(2) .WillRepeatedly(testing::Invoke( returnsResponse({429, "Server busy at the moment."}))); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_METADATA), testing::_, testing::_)) .Times(1); } olp::client::RetrySettings retrySettings; retrySettings.retry_condition = [](const olp::network::HttpResponse& response) { return 429 == response.status; }; settings_->retry_settings = retrySettings; auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("testlayer"); auto future = catalogClient->GetPartitions(request); auto partitionsResponse = future.GetFuture().get(); ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(4u, partitionsResponse.GetResult().GetPartitions().size()); } TEST_P(CatalogClientMockTest, GetPartitionsForInvalidLayer) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("invalidLayer"); auto future = catalogClient->GetPartitions(request); auto partitionsResponse = future.GetFuture().get(); ASSERT_FALSE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(olp::client::ErrorCode::InvalidArgument, partitionsResponse.GetError().GetErrorCode()); } TEST_P(CatalogClientMockTest, GetData404Error) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest("https://blob-ireland.data.api.platform.here.com/" "blobstore/v1/catalogs/hereos-internal-test-v2/" "layers/testlayer/data/invalidDataHandle"), testing::_, testing::_)) .Times(1) .WillRepeatedly( testing::Invoke(returnsResponse({404, "Resource not found."}))); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithDataHandle("invalidDataHandle"); auto future = catalogClient->GetData(request); auto dataResponse = future.GetFuture().get(); ASSERT_FALSE(dataResponse.IsSuccessful()); ASSERT_EQ(404, dataResponse.GetError().GetHttpStatusCode()); } TEST_P(CatalogClientMockTest, GetPartitionsGarbageResponse) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_METADATA), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke( returnsResponse({200, R"jsonString(kd3sdf\)jsonString"}))); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("testlayer"); auto future = catalogClient->GetPartitions(request); auto partitionsResponse = future.GetFuture().get(); ASSERT_FALSE(partitionsResponse.IsSuccessful()); ASSERT_EQ(olp::client::ErrorCode::ServiceUnavailable, partitionsResponse.GetError().GetErrorCode()); } TEST_P(CatalogClientMockTest, GetCatalogCancelApiLookup) { olp::client::HRN hrn(GetTestCatalog()); auto waitForCancel = std::make_shared<std::promise<void>>(); auto pauseForCancel = std::make_shared<std::promise<void>>(); // Setup the expected calls : EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_CONFIG), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke(setsPromiseWaitsAndReturns( waitForCancel, pauseForCancel, {200, HTTP_RESPONSE_LOOKUP_CONFIG}))); EXPECT_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .Times(0); // Run it! auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_); auto request = CatalogRequest(); std::promise<CatalogResponse> promise; CatalogResponseCallback callback = [&promise](CatalogResponse response) { promise.set_value(response); }; olp::client::CancellationToken cancelToken = catalogClient->GetCatalog(request, callback); waitForCancel->get_future().get(); cancelToken.cancel(); pauseForCancel->set_value(); CatalogResponse catalogResponse = promise.get_future().get(); ASSERT_FALSE(catalogResponse.IsSuccessful()) << PrintError(catalogResponse.GetError()); ASSERT_EQ(olp::network::Network::ErrorCode::Cancelled, static_cast<int>(catalogResponse.GetError().GetHttpStatusCode())); ASSERT_EQ(olp::client::ErrorCode::Cancelled, catalogResponse.GetError().GetErrorCode()); } TEST_P(CatalogClientMockTest, GetCatalogCancelConfig) { olp::client::HRN hrn(GetTestCatalog()); auto waitForCancel = std::make_shared<std::promise<void>>(); auto pauseForCancel = std::make_shared<std::promise<void>>(); // Setup the expected calls : EXPECT_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke(setsPromiseWaitsAndReturns( waitForCancel, pauseForCancel, {200, HTTP_RESPONSE_CONFIG}))); // Run it! auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_); auto request = CatalogRequest(); std::promise<CatalogResponse> promise; CatalogResponseCallback callback = [&promise](CatalogResponse response) { promise.set_value(response); }; olp::client::CancellationToken cancelToken = catalogClient->GetCatalog(request, callback); waitForCancel->get_future().get(); std::cout << "Cancelling" << std::endl; cancelToken.cancel(); // crashing? std::cout << "Cancelled, unblocking response" << std::endl; pauseForCancel->set_value(); std::cout << "Post Cancel, get response" << std::endl; CatalogResponse catalogResponse = promise.get_future().get(); ASSERT_FALSE(catalogResponse.IsSuccessful()) << PrintError(catalogResponse.GetError()); ASSERT_EQ(olp::network::Network::ErrorCode::Cancelled, static_cast<int>(catalogResponse.GetError().GetHttpStatusCode())); ASSERT_EQ(olp::client::ErrorCode::Cancelled, catalogResponse.GetError().GetErrorCode()); std::cout << "Post Test" << std::endl; } TEST_P(CatalogClientMockTest, GetCatalogCancelAfterCompletion) { olp::client::HRN hrn(GetTestCatalog()); // Run it! auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_); auto request = CatalogRequest(); std::promise<CatalogResponse> promise; CatalogResponseCallback callback = [&promise](CatalogResponse response) { promise.set_value(response); }; olp::client::CancellationToken cancelToken = catalogClient->GetCatalog(request, callback); CatalogResponse catalogResponse = promise.get_future().get(); ASSERT_TRUE(catalogResponse.IsSuccessful()) << PrintError(catalogResponse.GetError()); cancelToken.cancel(); } TEST_P(CatalogClientMockTest, GetPartitionsCancelLookupMetadata) { olp::client::HRN hrn(GetTestCatalog()); // Setup the expected calls : auto waitForCancel = std::make_shared<std::promise<void>>(); auto pauseForCancel = std::make_shared<std::promise<void>>(); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_METADATA), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke( setsPromiseWaitsAndReturns(waitForCancel, pauseForCancel, {200, HTTP_RESPONSE_LOOKUP_METADATA}))); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LATEST_CATALOG_VERSION), testing::_, testing::_)) .Times(0); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest().WithLayerId("testlayer"); std::promise<PartitionsResponse> promise; PartitionsResponseCallback callback = [&promise](PartitionsResponse response) { promise.set_value(response); }; olp::client::CancellationToken cancelToken = catalogClient->GetPartitions(request, callback); waitForCancel->get_future().get(); // wait for handler to get the request cancelToken.cancel(); pauseForCancel->set_value(); // unblock the handler PartitionsResponse partitionsResponse = promise.get_future().get(); ASSERT_FALSE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ( olp::network::Network::ErrorCode::Cancelled, static_cast<int>(partitionsResponse.GetError().GetHttpStatusCode())); ASSERT_EQ(olp::client::ErrorCode::Cancelled, partitionsResponse.GetError().GetErrorCode()); } TEST_P(CatalogClientMockTest, GetPartitionsCancelLatestCatalogVersion) { olp::client::HRN hrn(GetTestCatalog()); // Setup the expected calls : auto waitForCancel = std::make_shared<std::promise<void>>(); auto pauseForCancel = std::make_shared<std::promise<void>>(); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LATEST_CATALOG_VERSION), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke(setsPromiseWaitsAndReturns( waitForCancel, pauseForCancel, {200, HTTP_RESPONSE_LATEST_CATALOG_VERSION}))); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LAYER_VERSIONS), testing::_, testing::_)) .Times(0); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest().WithLayerId("testlayer"); std::promise<PartitionsResponse> promise; PartitionsResponseCallback callback = [&promise](PartitionsResponse response) { promise.set_value(response); }; olp::client::CancellationToken cancelToken = catalogClient->GetPartitions(request, callback); waitForCancel->get_future().get(); // wait for handler to get the request cancelToken.cancel(); pauseForCancel->set_value(); // unblock the handler PartitionsResponse partitionsResponse = promise.get_future().get(); ASSERT_FALSE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(olp::network::Network::ErrorCode::Cancelled, static_cast<int>(partitionsResponse.GetError().GetHttpStatusCode())) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(olp::client::ErrorCode::Cancelled, partitionsResponse.GetError().GetErrorCode()) << PrintError(partitionsResponse.GetError()); } TEST_P(CatalogClientMockTest, GetPartitionsCancelLayerVersions) { olp::client::HRN hrn(GetTestCatalog()); // Setup the expected calls : auto waitForCancel = std::make_shared<std::promise<void>>(); auto pauseForCancel = std::make_shared<std::promise<void>>(); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LAYER_VERSIONS), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke(setsPromiseWaitsAndReturns( waitForCancel, pauseForCancel, {200, HTTP_RESPONSE_LAYER_VERSIONS}))); EXPECT_CALL(*handler_, op(IsGetRequest(URL_PARTITIONS), testing::_, testing::_)) .Times(0); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest().WithLayerId("testlayer"); std::promise<PartitionsResponse> promise; PartitionsResponseCallback callback = [&promise](PartitionsResponse response) { promise.set_value(response); }; olp::client::CancellationToken cancelToken = catalogClient->GetPartitions(request, callback); waitForCancel->get_future().get(); // wait for handler to get the request cancelToken.cancel(); pauseForCancel->set_value(); // unblock the handler PartitionsResponse partitionsResponse = promise.get_future().get(); ASSERT_FALSE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(olp::network::Network::ErrorCode::Cancelled, static_cast<int>(partitionsResponse.GetError().GetHttpStatusCode())) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(olp::client::ErrorCode::Cancelled, partitionsResponse.GetError().GetErrorCode()) << PrintError(partitionsResponse.GetError()); } TEST_P(CatalogClientMockTest, GetDataWithPartitionIdCancelLookupConfig) { olp::client::HRN hrn(GetTestCatalog()); // Setup the expected calls : auto waitForCancel = std::make_shared<std::promise<void>>(); auto pauseForCancel = std::make_shared<std::promise<void>>(); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_CONFIG), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke(setsPromiseWaitsAndReturns( waitForCancel, pauseForCancel, {200, HTTP_RESPONSE_LOOKUP_CONFIG}))); EXPECT_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .Times(0); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("269"); std::promise<DataResponse> promise; DataResponseCallback callback = [&promise](DataResponse response) { promise.set_value(response); }; olp::client::CancellationToken cancelToken = catalogClient->GetData(request, callback); waitForCancel->get_future().get(); // wait for handler to get the request cancelToken.cancel(); pauseForCancel->set_value(); // unblock the handler DataResponse dataResponse = promise.get_future().get(); ASSERT_FALSE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::network::Network::ErrorCode::Cancelled, static_cast<int>(dataResponse.GetError().GetHttpStatusCode())) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::client::ErrorCode::Cancelled, dataResponse.GetError().GetErrorCode()) << PrintError(dataResponse.GetError()); } TEST_P(CatalogClientMockTest, GetDataWithPartitionIdCancelConfig) { olp::client::HRN hrn(GetTestCatalog()); // Setup the expected calls : auto waitForCancel = std::make_shared<std::promise<void>>(); auto pauseForCancel = std::make_shared<std::promise<void>>(); EXPECT_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke(setsPromiseWaitsAndReturns( waitForCancel, pauseForCancel, {200, HTTP_RESPONSE_CONFIG}))); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_METADATA), testing::_, testing::_)) .Times(0); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("269"); std::promise<DataResponse> promise; DataResponseCallback callback = [&promise](DataResponse response) { promise.set_value(response); }; olp::client::CancellationToken cancelToken = catalogClient->GetData(request, callback); waitForCancel->get_future().get(); // wait for handler to get the request cancelToken.cancel(); pauseForCancel->set_value(); // unblock the handler DataResponse dataResponse = promise.get_future().get(); ASSERT_FALSE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::network::Network::ErrorCode::Cancelled, static_cast<int>(dataResponse.GetError().GetHttpStatusCode())) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::client::ErrorCode::Cancelled, dataResponse.GetError().GetErrorCode()) << PrintError(dataResponse.GetError()); } TEST_P(CatalogClientMockTest, GetDataWithPartitionIdCancelLookupMetadata) { olp::client::HRN hrn(GetTestCatalog()); // Setup the expected calls : auto waitForCancel = std::make_shared<std::promise<void>>(); auto pauseForCancel = std::make_shared<std::promise<void>>(); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_METADATA), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke( setsPromiseWaitsAndReturns(waitForCancel, pauseForCancel, {200, HTTP_RESPONSE_LOOKUP_METADATA}))); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LATEST_CATALOG_VERSION), testing::_, testing::_)) .Times(0); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("269"); std::promise<DataResponse> promise; DataResponseCallback callback = [&promise](DataResponse response) { promise.set_value(response); }; olp::client::CancellationToken cancelToken = catalogClient->GetData(request, callback); waitForCancel->get_future().get(); // wait for handler to get the request cancelToken.cancel(); pauseForCancel->set_value(); // unblock the handler DataResponse dataResponse = promise.get_future().get(); ASSERT_FALSE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::network::Network::ErrorCode::Cancelled, static_cast<int>(dataResponse.GetError().GetHttpStatusCode())) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::client::ErrorCode::Cancelled, dataResponse.GetError().GetErrorCode()) << PrintError(dataResponse.GetError()); } TEST_P(CatalogClientMockTest, GetDataWithPartitionIdCancelLatestCatalogVersion) { olp::client::HRN hrn(GetTestCatalog()); // Setup the expected calls : auto waitForCancel = std::make_shared<std::promise<void>>(); auto pauseForCancel = std::make_shared<std::promise<void>>(); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LATEST_CATALOG_VERSION), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke(setsPromiseWaitsAndReturns( waitForCancel, pauseForCancel, {200, HTTP_RESPONSE_LATEST_CATALOG_VERSION}))); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_QUERY), testing::_, testing::_)) .Times(0); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("269"); std::promise<DataResponse> promise; DataResponseCallback callback = [&promise](DataResponse response) { promise.set_value(response); }; olp::client::CancellationToken cancelToken = catalogClient->GetData(request, callback); waitForCancel->get_future().get(); // wait for handler to get the request cancelToken.cancel(); pauseForCancel->set_value(); // unblock the handler DataResponse dataResponse = promise.get_future().get(); ASSERT_FALSE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::network::Network::ErrorCode::Cancelled, static_cast<int>(dataResponse.GetError().GetHttpStatusCode())) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::client::ErrorCode::Cancelled, dataResponse.GetError().GetErrorCode()) << PrintError(dataResponse.GetError()); } TEST_P(CatalogClientMockTest, GetDataWithPartitionIdCancelInnerConfig) { olp::client::HRN hrn(GetTestCatalog()); // Setup the expected calls : auto waitForCancel = std::make_shared<std::promise<void>>(); auto pauseForCancel = std::make_shared<std::promise<void>>(); { testing::InSequence s; EXPECT_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke(setsPromiseWaitsAndReturns( waitForCancel, pauseForCancel, {200, HTTP_RESPONSE_CONFIG}))); } EXPECT_CALL(*handler_, op(IsGetRequest(URL_LATEST_CATALOG_VERSION), testing::_, testing::_)) .Times(0); olp::cache::CacheSettings cacheSettings; cacheSettings.max_memory_cache_size = 0; auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>( hrn, settings_, olp::dataservice::read::CreateDefaultCache(cacheSettings)); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("269"); std::promise<DataResponse> promise; DataResponseCallback callback = [&promise](DataResponse response) { promise.set_value(response); }; olp::client::CancellationToken cancelToken = catalogClient->GetData(request, callback); waitForCancel->get_future().get(); // wait for handler to get the request cancelToken.cancel(); pauseForCancel->set_value(); // unblock the handler DataResponse dataResponse = promise.get_future().get(); ASSERT_FALSE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::network::Network::ErrorCode::Cancelled, static_cast<int>(dataResponse.GetError().GetHttpStatusCode())) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::client::ErrorCode::Cancelled, dataResponse.GetError().GetErrorCode()) << PrintError(dataResponse.GetError()); } TEST_P(CatalogClientMockTest, GetDataWithPartitionIdCancelLookupQuery) { olp::client::HRN hrn(GetTestCatalog()); // Setup the expected calls : auto waitForCancel = std::make_shared<std::promise<void>>(); auto pauseForCancel = std::make_shared<std::promise<void>>(); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_QUERY), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke(setsPromiseWaitsAndReturns( waitForCancel, pauseForCancel, {200, HTTP_RESPONSE_LOOKUP_QUERY}))); EXPECT_CALL(*handler_, op(IsGetRequest(URL_QUERY_PARTITION_269), testing::_, testing::_)) .Times(0); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("269"); std::promise<DataResponse> promise; DataResponseCallback callback = [&promise](DataResponse response) { promise.set_value(response); }; olp::client::CancellationToken cancelToken = catalogClient->GetData(request, callback); waitForCancel->get_future().get(); // wait for handler to get the request cancelToken.cancel(); pauseForCancel->set_value(); // unblock the handler DataResponse dataResponse = promise.get_future().get(); ASSERT_FALSE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::network::Network::ErrorCode::Cancelled, static_cast<int>(dataResponse.GetError().GetHttpStatusCode())) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::client::ErrorCode::Cancelled, dataResponse.GetError().GetErrorCode()) << PrintError(dataResponse.GetError()); } TEST_P(CatalogClientMockTest, GetDataWithPartitionIdCancelQuery) { olp::client::HRN hrn(GetTestCatalog()); // Setup the expected calls : auto waitForCancel = std::make_shared<std::promise<void>>(); auto pauseForCancel = std::make_shared<std::promise<void>>(); EXPECT_CALL(*handler_, op(IsGetRequest(URL_QUERY_PARTITION_269), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke(setsPromiseWaitsAndReturns( waitForCancel, pauseForCancel, {200, HTTP_RESPONSE_PARTITION_269}))); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_BLOB), testing::_, testing::_)) .Times(0); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("269"); std::promise<DataResponse> promise; DataResponseCallback callback = [&promise](DataResponse response) { promise.set_value(response); }; olp::client::CancellationToken cancelToken = catalogClient->GetData(request, callback); waitForCancel->get_future().get(); // wait for handler to get the request cancelToken.cancel(); pauseForCancel->set_value(); // unblock the handler DataResponse dataResponse = promise.get_future().get(); ASSERT_FALSE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::network::Network::ErrorCode::Cancelled, static_cast<int>(dataResponse.GetError().GetHttpStatusCode())) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::client::ErrorCode::Cancelled, dataResponse.GetError().GetErrorCode()) << PrintError(dataResponse.GetError()); } TEST_P(CatalogClientMockTest, GetDataWithPartitionIdCancelLookupBlob) { olp::client::HRN hrn(GetTestCatalog()); // Setup the expected calls : auto waitForCancel = std::make_shared<std::promise<void>>(); auto pauseForCancel = std::make_shared<std::promise<void>>(); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_BLOB), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke(setsPromiseWaitsAndReturns( waitForCancel, pauseForCancel, {200, HTTP_RESPONSE_LOOKUP_BLOB}))); EXPECT_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_269), testing::_, testing::_)) .Times(0); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("269"); std::promise<DataResponse> promise; DataResponseCallback callback = [&promise](DataResponse response) { promise.set_value(response); }; olp::client::CancellationToken cancelToken = catalogClient->GetData(request, callback); waitForCancel->get_future().get(); // wait for handler to get the request cancelToken.cancel(); pauseForCancel->set_value(); // unblock the handler DataResponse dataResponse = promise.get_future().get(); ASSERT_FALSE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::network::Network::ErrorCode::Cancelled, static_cast<int>(dataResponse.GetError().GetHttpStatusCode())) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::client::ErrorCode::Cancelled, dataResponse.GetError().GetErrorCode()) << PrintError(dataResponse.GetError()); } TEST_P(CatalogClientMockTest, GetDataWithPartitionIdCancelBlob) { olp::client::HRN hrn(GetTestCatalog()); // Setup the expected calls : auto waitForCancel = std::make_shared<std::promise<void>>(); auto pauseForCancel = std::make_shared<std::promise<void>>(); EXPECT_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_269), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke(setsPromiseWaitsAndReturns( waitForCancel, pauseForCancel, {200, HTTP_RESPONSE_BLOB_DATA_269}))); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("269"); std::promise<DataResponse> promise; DataResponseCallback callback = [&promise](DataResponse response) { promise.set_value(response); }; olp::client::CancellationToken cancelToken = catalogClient->GetData(request, callback); waitForCancel->get_future().get(); // wait for handler to get the request cancelToken.cancel(); pauseForCancel->set_value(); // unblock the handler DataResponse dataResponse = promise.get_future().get(); ASSERT_FALSE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::network::Network::ErrorCode::Cancelled, static_cast<int>(dataResponse.GetError().GetHttpStatusCode())) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::client::ErrorCode::Cancelled, dataResponse.GetError().GetErrorCode()) << PrintError(dataResponse.GetError()); } TEST_P(CatalogClientMockTest, GetCatalogVersion) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_METADATA), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LATEST_CATALOG_VERSION), testing::_, testing::_)) .Times(1); auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_); auto request = CatalogVersionRequest().WithStartVersion(-1); auto future = catalogClient->GetCatalogMetadataVersion(request); auto catalogVersionResponse = future.GetFuture().get(); ASSERT_TRUE(catalogVersionResponse.IsSuccessful()) << PrintError(catalogVersionResponse.GetError()); } TEST_P(CatalogClientMockTest, GetDataWithPartitionIdVersion2) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LATEST_CATALOG_VERSION), testing::_, testing::_)) .Times(0); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LAYER_VERSIONS_V2), testing::_, testing::_)) .Times(0); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("269").WithVersion(2); auto dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); std::string dataStr(dataResponse.GetResult()->begin(), dataResponse.GetResult()->end()); ASSERT_EQ("DT_2_0031_V2", dataStr); } TEST_P(CatalogClientMockTest, GetDataWithPartitionIdInvalidVersion) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("269").WithVersion(10); auto dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_FALSE(dataResponse.IsSuccessful()); ASSERT_EQ(olp::client::ErrorCode::BadRequest, dataResponse.GetError().GetErrorCode()); ASSERT_EQ(400, dataResponse.GetError().GetHttpStatusCode()); request.WithVersion(-1); dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_FALSE(dataResponse.IsSuccessful()); ASSERT_EQ(olp::client::ErrorCode::BadRequest, dataResponse.GetError().GetErrorCode()); ASSERT_EQ(400, dataResponse.GetError().GetHttpStatusCode()); } TEST_P(CatalogClientMockTest, GetPartitionsVersion2) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LATEST_CATALOG_VERSION), testing::_, testing::_)) .Times(0); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LAYER_VERSIONS_V2), testing::_, testing::_)) .Times(1); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("testlayer").WithVersion(2); auto partitionsResponse = GetExecutionTime<olp::dataservice::read::PartitionsResponse>([&] { auto future = catalogClient->GetPartitions(request); return future.GetFuture().get(); }); ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(1u, partitionsResponse.GetResult().GetPartitions().size()); } TEST_P(CatalogClientMockTest, GetPartitionsInvalidVersion) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("testlayer").WithVersion(10); auto partitionsResponse = GetExecutionTime<olp::dataservice::read::PartitionsResponse>([&] { auto future = catalogClient->GetPartitions(request); return future.GetFuture().get(); }); ASSERT_FALSE(partitionsResponse.IsSuccessful()); ASSERT_EQ(olp::client::ErrorCode::BadRequest, partitionsResponse.GetError().GetErrorCode()); ASSERT_EQ(400, partitionsResponse.GetError().GetHttpStatusCode()); request.WithVersion(-1); partitionsResponse = GetExecutionTime<olp::dataservice::read::PartitionsResponse>([&] { auto future = catalogClient->GetPartitions(request); return future.GetFuture().get(); }); ASSERT_FALSE(partitionsResponse.IsSuccessful()); ASSERT_EQ(olp::client::ErrorCode::BadRequest, partitionsResponse.GetError().GetErrorCode()); ASSERT_EQ(400, partitionsResponse.GetError().GetHttpStatusCode()); } TEST_P(CatalogClientMockTest, GetCatalogVersionCancel) { olp::client::HRN hrn(GetTestCatalog()); auto waitForCancel = std::make_shared<std::promise<void>>(); auto pauseForCancel = std::make_shared<std::promise<void>>(); // Setup the expected calls : EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_METADATA), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke( setsPromiseWaitsAndReturns(waitForCancel, pauseForCancel, {200, HTTP_RESPONSE_LOOKUP_METADATA}))); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LATEST_CATALOG_VERSION), testing::_, testing::_)) .Times(0); // Run it! auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_); auto request = CatalogVersionRequest().WithStartVersion(-1); std::promise<CatalogVersionResponse> promise; CatalogVersionCallback callback = [&promise](CatalogVersionResponse response) { promise.set_value(response); }; olp::client::CancellationToken cancelToken = catalogClient->GetCatalogMetadataVersion(request, callback); waitForCancel->get_future().get(); cancelToken.cancel(); pauseForCancel->set_value(); CatalogVersionResponse versionResponse = promise.get_future().get(); ASSERT_FALSE(versionResponse.IsSuccessful()) << PrintError(versionResponse.GetError()); ASSERT_EQ(olp::network::Network::ErrorCode::Cancelled, static_cast<int>(versionResponse.GetError().GetHttpStatusCode())); ASSERT_EQ(olp::client::ErrorCode::Cancelled, versionResponse.GetError().GetErrorCode()); } TEST_P(CatalogClientMockTest, GetCatalogCacheOnly) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .Times(0); auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_); auto request = CatalogRequest(); request.WithFetchOption(CacheOnly); auto future = catalogClient->GetCatalog(request); CatalogResponse catalogResponse = future.GetFuture().get(); ASSERT_FALSE(catalogResponse.IsSuccessful()) << PrintError(catalogResponse.GetError()); } TEST_P(CatalogClientMockTest, GetCatalogOnlineOnly) { olp::client::HRN hrn(GetTestCatalog()); { testing::InSequence s; EXPECT_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke( returnsResponse({429, "Server busy at the moment."}))); } auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_); auto request = CatalogRequest(); request.WithFetchOption(OnlineOnly); auto future = catalogClient->GetCatalog(request); CatalogResponse catalogResponse = future.GetFuture().get(); ASSERT_TRUE(catalogResponse.IsSuccessful()) << PrintError(catalogResponse.GetError()); future = catalogClient->GetCatalog(request); // Should fail despite valid cache entry. catalogResponse = future.GetFuture().get(); ASSERT_FALSE(catalogResponse.IsSuccessful()) << PrintError(catalogResponse.GetError()); } TEST_P(CatalogClientMockTest, GetCatalogCacheWithUpdate) { olp::logging::Log::setLevel(olp::logging::Level::Trace); olp::client::HRN hrn(GetTestCatalog()); auto waitToStartSignal = std::make_shared<std::promise<void>>(); auto preCallbackWait = std::make_shared<std::promise<void>>(); preCallbackWait->set_value(); auto waitForEnd = std::make_shared<std::promise<void>>(); EXPECT_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke( setsPromiseWaitsAndReturns(waitToStartSignal, preCallbackWait, {200, HTTP_RESPONSE_CONFIG}, waitForEnd))); auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_); auto request = CatalogRequest(); request.WithFetchOption(CacheWithUpdate); // Request 1 EDGE_SDK_LOG_TRACE_F("CatalogClientMockTest", "Request Catalog, CacheWithUpdate"); auto future = catalogClient->GetCatalog(request); EDGE_SDK_LOG_TRACE_F("CatalogClientMockTest", "get CatalogResponse1"); CatalogResponse catalogResponse = future.GetFuture().get(); // Request 1 return. Cached value (nothing) ASSERT_FALSE(catalogResponse.IsSuccessful()) << PrintError(catalogResponse.GetError()); // Wait for background cache update to finish EDGE_SDK_LOG_TRACE_F("CatalogClientMockTest", "wait some time for update to conclude"); waitForEnd->get_future().get(); // Request 2 to check there is a cached value. EDGE_SDK_LOG_TRACE_F("CatalogClientMockTest", "Request Catalog, CacheOnly"); request.WithFetchOption(CacheOnly); future = catalogClient->GetCatalog(request); EDGE_SDK_LOG_TRACE_F("CatalogClientMockTest", "get CatalogResponse2"); catalogResponse = future.GetFuture().get(); // Cache should be available here. ASSERT_TRUE(catalogResponse.IsSuccessful()) << PrintError(catalogResponse.GetError()); } TEST_P(CatalogClientMockTest, GetDataCacheOnly) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_269), testing::_, testing::_)) .Times(0); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer") .WithPartitionId("269") .WithFetchOption(CacheOnly); auto future = catalogClient->GetData(request); auto dataResponse = future.GetFuture().get(); ASSERT_FALSE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); } TEST_P(CatalogClientMockTest, GetDataOnlineOnly) { olp::client::HRN hrn(GetTestCatalog()); { testing::InSequence s; EXPECT_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_269), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_269), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke( returnsResponse({429, "Server busy at the moment."}))); } auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer") .WithPartitionId("269") .WithFetchOption(OnlineOnly); auto future = catalogClient->GetData(request); auto dataResponse = future.GetFuture().get(); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); std::string dataStr(dataResponse.GetResult()->begin(), dataResponse.GetResult()->end()); ASSERT_EQ("DT_2_0031", dataStr); // Should fail despite cached response future = catalogClient->GetData(request); dataResponse = future.GetFuture().get(); ASSERT_FALSE(dataResponse.IsSuccessful()); } TEST_P(CatalogClientMockTest, GetDataCacheWithUpdate) { olp::logging::Log::setLevel(olp::logging::Level::Trace); olp::client::HRN hrn(GetTestCatalog()); // Setup the expected calls : auto waitToStartSignal = std::make_shared<std::promise<void>>(); auto preCallbackWait = std::make_shared<std::promise<void>>(); preCallbackWait->set_value(); auto waitForEndSignal = std::make_shared<std::promise<void>>(); EXPECT_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_269), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke(setsPromiseWaitsAndReturns( waitToStartSignal, preCallbackWait, {200, HTTP_RESPONSE_BLOB_DATA_269}, waitForEndSignal))); auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_); auto request = DataRequest(); request.WithLayerId("testlayer") .WithPartitionId("269") .WithFetchOption(CacheWithUpdate); // Request 1 auto future = catalogClient->GetData(request); DataResponse dataResponse = future.GetFuture().get(); // Request 1 return. Cached value (nothing) ASSERT_FALSE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); // Request 2 to check there is a cached value. // waiting for cache to fill-in waitForEndSignal->get_future().get(); request.WithFetchOption(CacheOnly); future = catalogClient->GetData(request); dataResponse = future.GetFuture().get(); // Cache should be available here. ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); } TEST_P(CatalogClientMockTest, GetPartitionsCacheOnly) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_PARTITIONS), testing::_, testing::_)) .Times(0); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("testlayer").WithFetchOption(CacheOnly); auto future = catalogClient->GetPartitions(request); auto partitionsResponse = future.GetFuture().get(); ASSERT_FALSE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); } TEST_P(CatalogClientMockTest, GetPartitionsOnlineOnly) { olp::client::HRN hrn(GetTestCatalog()); { testing::InSequence s; EXPECT_CALL(*handler_, op(IsGetRequest(URL_PARTITIONS), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_PARTITIONS), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke( returnsResponse({429, "Server busy at the moment."}))); } auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("testlayer").WithFetchOption(OnlineOnly); auto future = catalogClient->GetPartitions(request); auto partitionsResponse = future.GetFuture().get(); ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(4u, partitionsResponse.GetResult().GetPartitions().size()); future = catalogClient->GetPartitions(request); partitionsResponse = future.GetFuture().get(); // Should fail despite valid cache entry ASSERT_FALSE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); } TEST_P(CatalogClientMockTest, GetPartitionsCacheWithUpdate) { olp::logging::Log::setLevel(olp::logging::Level::Trace); olp::client::HRN hrn(GetTestCatalog()); auto waitToStartSignal = std::make_shared<std::promise<void>>(); auto preCallbackWait = std::make_shared<std::promise<void>>(); preCallbackWait->set_value(); auto waitForEndSignal = std::make_shared<std::promise<void>>(); EXPECT_CALL(*handler_, op(IsGetRequest(URL_PARTITIONS), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke(setsPromiseWaitsAndReturns( waitToStartSignal, preCallbackWait, {200, HTTP_RESPONSE_PARTITIONS}, waitForEndSignal))); auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_); auto request = PartitionsRequest(); request.WithLayerId("testlayer").WithFetchOption(CacheWithUpdate); // Request 1 auto future = catalogClient->GetPartitions(request); PartitionsResponse partitionsResponse = future.GetFuture().get(); // Request 1 return. Cached value (nothing) ASSERT_FALSE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); // Request 2 to check there is a cached value. waitForEndSignal->get_future().get(); request.WithFetchOption(CacheOnly); future = catalogClient->GetPartitions(request); partitionsResponse = future.GetFuture().get(); // Cache should be available here. ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); } TEST_P(CatalogClientMockTest, GetCatalog403CacheClear) { olp::client::HRN hrn(GetTestCatalog()); { testing::InSequence s; EXPECT_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke(returnsResponse({403, HTTP_RESPONSE_403}))); } auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_); auto request = CatalogRequest(); // Populate cache auto future = catalogClient->GetCatalog(request); CatalogResponse catalogResponse = future.GetFuture().get(); ASSERT_TRUE(catalogResponse.IsSuccessful()); auto datarequest = DataRequest(); datarequest.WithLayerId("testlayer").WithPartitionId("269"); auto datafuture = catalogClient->GetData(datarequest); auto dataresponse = datafuture.GetFuture().get(); // Receive 403 request.WithFetchOption(OnlineOnly); future = catalogClient->GetCatalog(request); catalogResponse = future.GetFuture().get(); ASSERT_FALSE(catalogResponse.IsSuccessful()); ASSERT_EQ(403, catalogResponse.GetError().GetHttpStatusCode()); // Check for cached response request.WithFetchOption(CacheOnly); future = catalogClient->GetCatalog(request); catalogResponse = future.GetFuture().get(); ASSERT_FALSE(catalogResponse.IsSuccessful()); // Check the associated data has also been cleared datarequest.WithFetchOption(CacheOnly); datafuture = catalogClient->GetData(datarequest); dataresponse = datafuture.GetFuture().get(); ASSERT_FALSE(dataresponse.IsSuccessful()); } TEST_P(CatalogClientMockTest, GetData403CacheClear) { olp::client::HRN hrn(GetTestCatalog()); { testing::InSequence s; EXPECT_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_269), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_269), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke(returnsResponse({403, HTTP_RESPONSE_403}))); } auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_); auto request = DataRequest(); request.WithLayerId("testlayer").WithPartitionId("269"); // Populate cache auto future = catalogClient->GetData(request); DataResponse dataResponse = future.GetFuture().get(); ASSERT_TRUE(dataResponse.IsSuccessful()); // Receive 403 request.WithFetchOption(OnlineOnly); future = catalogClient->GetData(request); dataResponse = future.GetFuture().get(); ASSERT_FALSE(dataResponse.IsSuccessful()); ASSERT_EQ(403, dataResponse.GetError().GetHttpStatusCode()); // Check for cached response request.WithFetchOption(CacheOnly); future = catalogClient->GetData(request); dataResponse = future.GetFuture().get(); ASSERT_FALSE(dataResponse.IsSuccessful()); } TEST_P(CatalogClientMockTest, GetPartitions403CacheClear) { olp::client::HRN hrn(GetTestCatalog()); auto catalog_client = std::make_unique<CatalogClient>(hrn, settings_); { InSequence s; EXPECT_CALL(*handler_, op(IsGetRequest(URL_PARTITIONS), _, _)).Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_PARTITIONS), _, _)) .WillOnce(Invoke(returnsResponse({403, HTTP_RESPONSE_403}))); } // Populate cache auto request = PartitionsRequest().WithLayerId("testlayer"); auto future = catalog_client->GetPartitions(request); auto partitions_response = future.GetFuture().get(); ASSERT_TRUE(partitions_response.IsSuccessful()); // Receive 403 request.WithFetchOption(OnlineOnly); future = catalog_client->GetPartitions(request); partitions_response = future.GetFuture().get(); ASSERT_FALSE(partitions_response.IsSuccessful()); ASSERT_EQ(403, partitions_response.GetError().GetHttpStatusCode()); // Check for cached response request.WithFetchOption(CacheOnly); future = catalog_client->GetPartitions(request); partitions_response = future.GetFuture().get(); ASSERT_FALSE(partitions_response.IsSuccessful()); } TEST_P(CatalogClientMockTest, CancelPendingRequestsCatalog) { olp::client::HRN hrn(GetTestCatalog()); testing::InSequence s; std::vector<std::shared_ptr<std::promise<void>>> waits; std::vector<std::shared_ptr<std::promise<void>>> pauses; auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_); auto catalogRequest = CatalogRequest().WithFetchOption(OnlineOnly); auto versionRequest = CatalogVersionRequest().WithFetchOption(OnlineOnly); // Make a few requests auto waitForCancel1 = std::make_shared<std::promise<void>>(); auto pauseForCancel1 = std::make_shared<std::promise<void>>(); auto waitForCancel2 = std::make_shared<std::promise<void>>(); auto pauseForCancel2 = std::make_shared<std::promise<void>>(); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_CONFIG), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke( setsPromiseWaitsAndReturns(waitForCancel1, pauseForCancel1, {200, HTTP_RESPONSE_LOOKUP_CONFIG}))); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_METADATA), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke( setsPromiseWaitsAndReturns(waitForCancel2, pauseForCancel2, {200, HTTP_RESPONSE_LOOKUP_METADATA}))); waits.push_back(waitForCancel1); pauses.push_back(pauseForCancel1); auto catalogFuture = catalogClient->GetCatalog(catalogRequest); waits.push_back(waitForCancel2); pauses.push_back(pauseForCancel2); auto versionFuture = catalogClient->GetCatalogMetadataVersion(versionRequest); for (auto wait : waits) { wait->get_future().get(); } // Cancel them all catalogClient->cancelPendingRequests(); for (auto pause : pauses) { pause->set_value(); } // Verify they are all cancelled CatalogResponse catalogResponse = catalogFuture.GetFuture().get(); ASSERT_FALSE(catalogResponse.IsSuccessful()) << PrintError(catalogResponse.GetError()); ASSERT_EQ(olp::network::Network::ErrorCode::Cancelled, static_cast<int>(catalogResponse.GetError().GetHttpStatusCode())); ASSERT_EQ(olp::client::ErrorCode::Cancelled, catalogResponse.GetError().GetErrorCode()); CatalogVersionResponse versionResponse = versionFuture.GetFuture().get(); ASSERT_FALSE(versionResponse.IsSuccessful()) << PrintError(versionResponse.GetError()); ASSERT_EQ(olp::network::Network::ErrorCode::Cancelled, static_cast<int>(versionResponse.GetError().GetHttpStatusCode())); ASSERT_EQ(olp::client::ErrorCode::Cancelled, versionResponse.GetError().GetErrorCode()); } TEST_P(CatalogClientMockTest, CancelPendingRequestsPartitions) { olp::client::HRN hrn(GetTestCatalog()); testing::InSequence s; std::vector<std::shared_ptr<std::promise<void>>> waits; std::vector<std::shared_ptr<std::promise<void>>> pauses; auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_); auto partitionsRequest = PartitionsRequest().WithLayerId("testlayer").WithFetchOption(OnlineOnly); auto dataRequest = DataRequest() .WithLayerId("testlayer") .WithPartitionId("269") .WithFetchOption(OnlineOnly); // Make a few requests auto waitForCancel1 = std::make_shared<std::promise<void>>(); auto pauseForCancel1 = std::make_shared<std::promise<void>>(); auto waitForCancel2 = std::make_shared<std::promise<void>>(); auto pauseForCancel2 = std::make_shared<std::promise<void>>(); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LAYER_VERSIONS), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke( setsPromiseWaitsAndReturns(waitForCancel1, pauseForCancel1, {200, HTTP_RESPONSE_LAYER_VERSIONS}))); EXPECT_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_269), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke( setsPromiseWaitsAndReturns(waitForCancel2, pauseForCancel2, {200, HTTP_RESPONSE_BLOB_DATA_269}))); waits.push_back(waitForCancel1); pauses.push_back(pauseForCancel1); auto partitionsFuture = catalogClient->GetPartitions(partitionsRequest); waits.push_back(waitForCancel2); pauses.push_back(pauseForCancel2); auto dataFuture = catalogClient->GetData(dataRequest); std::cout << "waiting" << std::endl; for (auto wait : waits) { wait->get_future().get(); } std::cout << "done waitingg" << std::endl; // Cancel them all catalogClient->cancelPendingRequests(); std::cout << "done cancelling" << std::endl; for (auto pause : pauses) { pause->set_value(); } // Verify they are all cancelled PartitionsResponse partitionsResponse = partitionsFuture.GetFuture().get(); ASSERT_FALSE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ( olp::network::Network::ErrorCode::Cancelled, static_cast<int>(partitionsResponse.GetError().GetHttpStatusCode())); ASSERT_EQ(olp::client::ErrorCode::Cancelled, partitionsResponse.GetError().GetErrorCode()); DataResponse dataResponse = dataFuture.GetFuture().get(); ASSERT_FALSE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::network::Network::ErrorCode::Cancelled, static_cast<int>(dataResponse.GetError().GetHttpStatusCode())); ASSERT_EQ(olp::client::ErrorCode::Cancelled, dataResponse.GetError().GetErrorCode()); } TEST_P(CatalogClientMockTest, Prefetch) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); std::vector<olp::geo::TileKey> tileKeys; tileKeys.emplace_back(olp::geo::TileKey::FromHereTile("5904591")); auto request = olp::dataservice::read::PrefetchTilesRequest() .WithLayerId("hype-test-prefetch") .WithTileKeys(tileKeys) .WithMinLevel(10) .WithMaxLevel(12); auto future = catalogClient->PrefetchTiles(request); auto response = future.GetFuture().get(); ASSERT_TRUE(response.IsSuccessful()); auto& result = response.GetResult(); for (auto tileResult : result) { ASSERT_TRUE(tileResult->IsSuccessful()); ASSERT_TRUE(tileResult->tile_key_.IsValid()); dumpTileKey(tileResult->tile_key_); } ASSERT_EQ(6u, result.size()); // Second part, use the cache, fetch a partition that's the child of 5904591 { auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("hype-test-prefetch") .WithPartitionId("23618365") .WithFetchOption(FetchOptions::CacheOnly); auto future = catalogClient->GetData(request); auto dataResponse = future.GetFuture().get(); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); } // The parent of 5904591 should be fetched too { auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("hype-test-prefetch") .WithPartitionId("1476147") .WithFetchOption(FetchOptions::CacheOnly); auto future = catalogClient->GetData(request); auto dataResponse = future.GetFuture().get(); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); } } TEST_P(CatalogClientMockTest, PrefetchEmbedded) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); std::vector<olp::geo::TileKey> tileKeys; tileKeys.emplace_back(olp::geo::TileKey::FromHereTile("369036")); auto request = olp::dataservice::read::PrefetchTilesRequest() .WithLayerId("hype-test-prefetch") .WithTileKeys(tileKeys) .WithMinLevel(9) .WithMaxLevel(9); auto future = catalogClient->PrefetchTiles(request); auto response = future.GetFuture().get(); ASSERT_TRUE(response.IsSuccessful()); auto& result = response.GetResult(); for (auto tileResult : result) { ASSERT_TRUE(tileResult->IsSuccessful()); ASSERT_TRUE(tileResult->tile_key_.IsValid()); dumpTileKey(tileResult->tile_key_); } ASSERT_EQ(1u, result.size()); // Second part, use the cache to fetch the partition { auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("hype-test-prefetch") .WithPartitionId("369036") .WithFetchOption(FetchOptions::CacheOnly); auto future = catalogClient->GetData(request); auto dataResponse = future.GetFuture().get(); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); // expected data = "data:Embedded Data for 369036" std::string dataStrDup(dataResponse.GetResult()->begin(), dataResponse.GetResult()->end()); ASSERT_EQ("data:Embedded Data for 369036", dataStrDup); } } TEST_P(CatalogClientMockTest, PrefetchBusy) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); // Prepare the first request std::vector<olp::geo::TileKey> tileKeys1; tileKeys1.emplace_back(olp::geo::TileKey::FromHereTile("5904591")); auto request1 = olp::dataservice::read::PrefetchTilesRequest() .WithLayerId("hype-test-prefetch") .WithTileKeys(tileKeys1) .WithMinLevel(10) .WithMaxLevel(12); // Prepare to delay the response of URL_QUADKEYS_5904591 until we've issued // the second request auto waitForQuadKeyRequest = std::make_shared<std::promise<void>>(); auto pauseForSecondRequest = std::make_shared<std::promise<void>>(); EXPECT_CALL(*handler_, op(IsGetRequest(URL_QUADKEYS_5904591), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke(setsPromiseWaitsAndReturns( waitForQuadKeyRequest, pauseForSecondRequest, {200, HTTP_RESPONSE_QUADKEYS_5904591}))); // Issue the first request auto future1 = catalogClient->PrefetchTiles(request1); // Wait for QuadKey request waitForQuadKeyRequest->get_future().get(); // Prepare the second request std::vector<olp::geo::TileKey> tileKeys2; tileKeys2.emplace_back(olp::geo::TileKey::FromHereTile("369036")); auto request2 = olp::dataservice::read::PrefetchTilesRequest() .WithLayerId("hype-test-prefetch") .WithTileKeys(tileKeys2) .WithMinLevel(9) .WithMaxLevel(9); // Issue the second request auto future2 = catalogClient->PrefetchTiles(request2); // Unblock the QuadKey request pauseForSecondRequest->set_value(); // Validate that the second request failed auto response2 = future2.GetFuture().get(); ASSERT_FALSE(response2.IsSuccessful()); auto& error = response2.GetError(); ASSERT_EQ(olp::client::ErrorCode::SlowDown, error.GetErrorCode()); // Get and validate the first request auto response1 = future1.GetFuture().get(); ASSERT_TRUE(response1.IsSuccessful()); auto& result1 = response1.GetResult(); for (auto tileResult : result1) { ASSERT_TRUE(tileResult->IsSuccessful()); ASSERT_TRUE(tileResult->tile_key_.IsValid()); dumpTileKey(tileResult->tile_key_); } ASSERT_EQ(6u, result1.size()); } class CatalogClientCacheTest : public CatalogClientMockTest { void SetUp() { CatalogClientMockTest::SetUp(); olp::cache::CacheSettings settings; switch (std::get<1>(GetParam())) { case InMemory: { // use the default value break; } case Disk: { settings.max_memory_cache_size = 0; settings.disk_path = olp::utils::Dir::TempDirectory() + k_client_test_cache_dir; ClearCache(settings.disk_path.get()); break; } case Both: { settings.disk_path = olp::utils::Dir::TempDirectory() + k_client_test_cache_dir; ClearCache(settings.disk_path.get()); break; } default: // shouldn't get here break; } cache_ = std::make_shared<olp::cache::DefaultCache>(settings); ASSERT_EQ(olp::cache::DefaultCache::StorageOpenResult::Success, cache_->Open()); } void ClearCache(const std::string& path) { olp::utils::Dir::remove(path); } void TearDown() { if (cache_) { cache_->Close(); } ClearCache(olp::utils::Dir::TempDirectory() + k_client_test_dir); handler_.reset(); } protected: std::shared_ptr<olp::cache::DefaultCache> cache_; }; INSTANTIATE_TEST_SUITE_P(TestInMemoryCache, CatalogClientCacheTest, ::testing::Values(std::make_pair(false, InMemory))); INSTANTIATE_TEST_SUITE_P(TestDiskCache, CatalogClientCacheTest, ::testing::Values(std::make_pair(false, Disk))); INSTANTIATE_TEST_SUITE_P(TestBothCache, CatalogClientCacheTest, ::testing::Values(std::make_pair(false, Both))); TEST_P(CatalogClientCacheTest, GetApi) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_METADATA), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LATEST_CATALOG_VERSION), testing::_, testing::_)) .Times(2); auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_, cache_); auto request = CatalogVersionRequest().WithStartVersion(-1); auto future = catalogClient->GetCatalogMetadataVersion(request); auto catalogVersionResponse = future.GetFuture().get(); ASSERT_TRUE(catalogVersionResponse.IsSuccessful()) << PrintError(catalogVersionResponse.GetError()); auto partitionsRequest = olp::dataservice::read::PartitionsRequest(); partitionsRequest.WithLayerId("testlayer"); auto partitionsFuture = catalogClient->GetPartitions(partitionsRequest); auto partitionsResponse = partitionsFuture.GetFuture().get(); ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(4u, partitionsResponse.GetResult().GetPartitions().size()); } TEST_P(CatalogClientCacheTest, GetCatalog) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_CONFIG), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .Times(1); auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_, cache_); auto request = CatalogRequest(); auto future = catalogClient->GetCatalog(request); CatalogResponse catalogResponse = future.GetFuture().get(); ASSERT_TRUE(catalogResponse.IsSuccessful()) << PrintError(catalogResponse.GetError()); future = catalogClient->GetCatalog(request); CatalogResponse catalogResponse2 = future.GetFuture().get(); ASSERT_TRUE(catalogResponse2.IsSuccessful()) << PrintError(catalogResponse2.GetError()); ASSERT_EQ(catalogResponse2.GetResult().GetName(), catalogResponse.GetResult().GetName()); } TEST_P(CatalogClientCacheTest, GetDataWithPartitionId) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_METADATA), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LATEST_CATALOG_VERSION), testing::_, testing::_)) .Times(2); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_CONFIG), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_BLOB), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_QUERY), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_QUERY_PARTITION_269), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_269), testing::_, testing::_)) .Times(1); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>( hrn, settings_, cache_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("269"); auto future = catalogClient->GetData(request); auto dataResponse = future.GetFuture().get(); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); std::string dataStr(dataResponse.GetResult()->begin(), dataResponse.GetResult()->end()); ASSERT_EQ("DT_2_0031", dataStr); future = catalogClient->GetData(request); dataResponse = future.GetFuture().get(); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); std::string dataStrDup(dataResponse.GetResult()->begin(), dataResponse.GetResult()->end()); ASSERT_EQ("DT_2_0031", dataStrDup); } TEST_P(CatalogClientCacheTest, GetPartitionsLayerVersions) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_METADATA), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LATEST_CATALOG_VERSION), testing::_, testing::_)) .Times(2); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LAYER_VERSIONS), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_PARTITIONS), testing::_, testing::_)) .Times(1); std::string url_testlayer_res = std::regex_replace( URL_PARTITIONS, std::regex("testlayer"), "testlayer_res"); std::string http_response_testlayer_res = std::regex_replace( HTTP_RESPONSE_PARTITIONS, std::regex("testlayer"), "testlayer_res"); EXPECT_CALL(*handler_, op(IsGetRequest(url_testlayer_res), testing::_, testing::_)) .Times(1) .WillOnce( testing::Invoke(returnsResponse({200, http_response_testlayer_res}))); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>( hrn, settings_, cache_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("testlayer"); auto future = catalogClient->GetPartitions(request); auto partitionsResponse = future.GetFuture().get(); ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(4u, partitionsResponse.GetResult().GetPartitions().size()); request.WithLayerId("testlayer_res"); future = catalogClient->GetPartitions(request); partitionsResponse = future.GetFuture().get(); ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(4u, partitionsResponse.GetResult().GetPartitions().size()); } TEST_P(CatalogClientCacheTest, GetPartitions) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_METADATA), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LATEST_CATALOG_VERSION), testing::_, testing::_)) .Times(2); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LAYER_VERSIONS), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_PARTITIONS), testing::_, testing::_)) .Times(1); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>( hrn, settings_, cache_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("testlayer"); auto future = catalogClient->GetPartitions(request); auto partitionsResponse = future.GetFuture().get(); ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(4u, partitionsResponse.GetResult().GetPartitions().size()); future = catalogClient->GetPartitions(request); partitionsResponse = future.GetFuture().get(); ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(4u, partitionsResponse.GetResult().GetPartitions().size()); } TEST_P(CatalogClientCacheTest, GetDataWithPartitionIdDifferentVersions) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_METADATA), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LATEST_CATALOG_VERSION), testing::_, testing::_)) .Times(2); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_CONFIG), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_BLOB), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_QUERY), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_QUERY_PARTITION_269), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_269), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_QUERY_PARTITION_269_V2), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_269_V2), testing::_, testing::_)) .Times(1); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); { request.WithLayerId("testlayer").WithPartitionId("269"); auto dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); std::string dataStr(dataResponse.GetResult()->begin(), dataResponse.GetResult()->end()); ASSERT_EQ("DT_2_0031", dataStr); } { request.WithVersion(2); auto dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); std::string dataStr(dataResponse.GetResult()->begin(), dataResponse.GetResult()->end()); ASSERT_EQ("DT_2_0031_V2", dataStr); } { request.WithVersion(boost::none); auto dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); std::string dataStr(dataResponse.GetResult()->begin(), dataResponse.GetResult()->end()); ASSERT_EQ("DT_2_0031", dataStr); } { request.WithVersion(2); auto dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); std::string dataStr(dataResponse.GetResult()->begin(), dataResponse.GetResult()->end()); ASSERT_EQ("DT_2_0031_V2", dataStr); } } TEST_P(CatalogClientCacheTest, GetVolatilePartitionsExpiry) { olp::client::HRN hrn(GetTestCatalog()); { testing::InSequence s; EXPECT_CALL( *handler_, op(IsGetRequest( "https://metadata.data.api.platform.here.com/metadata/v1/" "catalogs/" "hereos-internal-test-v2/layers/testlayer_volatile/partitions"), testing::_, testing::_)) .Times(1) .WillRepeatedly(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_PARTITIONS_V2}))); EXPECT_CALL( *handler_, op(IsGetRequest( "https://metadata.data.api.platform.here.com/metadata/v1/" "catalogs/" "hereos-internal-test-v2/layers/testlayer_volatile/partitions"), testing::_, testing::_)) .Times(1) .WillRepeatedly(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_EMPTY_PARTITIONS}))); } auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>( hrn, settings_, cache_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("testlayer_volatile"); auto future = catalogClient->GetPartitions(request); auto partitionsResponse = future.GetFuture().get(); ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(1u, partitionsResponse.GetResult().GetPartitions().size()); // hit the cache only, should be still be there request.WithFetchOption(olp::dataservice::read::CacheOnly); future = catalogClient->GetPartitions(request); partitionsResponse = future.GetFuture().get(); ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(1u, partitionsResponse.GetResult().GetPartitions().size()); // wait for the layer to expire in cache std::this_thread::sleep_for(std::chrono::seconds(2)); request.WithFetchOption(olp::dataservice::read::OnlineIfNotFound); future = catalogClient->GetPartitions(request); partitionsResponse = future.GetFuture().get(); ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(0u, partitionsResponse.GetResult().GetPartitions().size()); }
36.74749
81
0.695146
ystefinko
ccd7f0ecb1012bc3172bb0343849506f7eba3e34
18,220
cxx
C++
3rd/fltk/OpenGL/Fl_Gl_Window.cxx
MarioHenze/cgv
bacb2d270b1eecbea1e933b8caad8d7e11d807c2
[ "BSD-3-Clause" ]
11
2017-09-30T12:21:55.000Z
2021-04-29T21:31:57.000Z
3rd/fltk/OpenGL/Fl_Gl_Window.cxx
MarioHenze/cgv
bacb2d270b1eecbea1e933b8caad8d7e11d807c2
[ "BSD-3-Clause" ]
2
2017-07-11T11:20:08.000Z
2018-03-27T12:09:02.000Z
3rd/fltk/OpenGL/Fl_Gl_Window.cxx
MarioHenze/cgv
bacb2d270b1eecbea1e933b8caad8d7e11d807c2
[ "BSD-3-Clause" ]
24
2018-03-27T11:46:16.000Z
2021-05-01T20:28:34.000Z
// "$Id: Fl_Gl_Window.cxx 5936 2007-07-24 11:25:53Z spitzak $" // // Copyright 1998-2006 by Bill Spitzak and others. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library 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 // Library General Public License for more details. // // You should have received a copy of the GNU Library General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 // USA. // // Please report all bugs and problems to "fltk-bugs@fltk.org". #include <config.h> #if HAVE_GL #include "GlChoice.h" #include <fltk/GlWindow.h> #include <fltk/damage.h> #include <fltk/error.h> #include <fltk/visual.h> #include <fltk/layout.h> #include <fltk/run.h> #include <fltk/events.h> #include <stdlib.h> #include <string.h> using namespace fltk; /** \class fltk::GlWindow Provides an area in which the draw() method can use OpenGL to draw. This widget sets things up so OpenGL works, and also keeps an OpenGL "context" for that window, so that changes to the lighting and projection may be reused between redraws. GlWindow also flushes the OpenGL streams and swaps buffers after draw() returns. draw() is a pure virtual method. You must subclass GlWindow and provide an implementation for draw(). You can avoid reinitializing the viewport and lights and other things by checking valid() at the start of draw() and only doing the initialization if it is false. draw() can \e only use OpenGL calls. Do not attempt to call any of the functions in &lt;fltk/draw.h&gt;, or X or GDI32 or any other drawing api. Do not call glstart() or glfinish(). <h2>Double Buffering</h2> Normally double-buffering is enabled. You can disable it by chaning the mode() to turn off the DOUBLE_BUFFER bit. If double-buffering is enabled, the back buffer is made current before draw() is called, and the back and front buffers are \e automatically swapped after draw() is completed. Some tricks using the front buffer require you to control the swapping. You can call swap_buffers() to swap them (OpenGL does not provide a portable function for this, so we provide it). But you will need to turn off the auto-swap, you do this by adding the NO_AUTO_SWAP bit to the mode(). <h2>Overlays</h2> The method draw_overlay() is a second drawing operation that is put atop the main image. You can implement this, and call redraw_overlay() to indicate that the image in this overlay has changed and that draw_overlay() must be called. Originally this was written to support hardware overlays, but FLTK emulated it if the hardware was missing so programs were portable. FLTK 2.0 is not normally compiled to support hardware overlays, but the emulation still remains, so you can use these functions. (Modern hardware typically has no overlays, and besides it is fast enough that the original purpose of them is moot) By default the emulation is to call draw_overlay() after draw() and before swapping the buffers, so the overlay is just part of the normal image and does not blink. You can get some of the advantages of overlay hardware by setting the GL_SWAP_TYPE environment variable, which will cause the front buffer to be used for the draw_overlay() method, and not call draw() each time the overlay changes. This will be faster if draw() is very complex, but the overlay will blink. GL_SWAP_TYPE can be set to: - "USE_COPY" use glCopyPixels to copy the back buffer to the front. This should always work. - "COPY" indicates that the swap_buffers() function actually copies the back to the front buffer, rather than swapping them. If your card does this (most do) then this is best. - "NODAMAGE" indicates that behavior is like "COPY" but \e nothing changes the back buffer, including overlapping it with another OpenGL window. This is true of software OpenGL emulation, and may be true of some modern cards with lots of memory. */ //////////////////////////////////////////////////////////////// // The symbol SWAP_TYPE defines what is in the back buffer after doing // a glXSwapBuffers(). // The OpenGl documentation says that the contents of the backbuffer // are "undefined" after glXSwapBuffers(). However, if we know what // is in the backbuffers then we can save a good deal of time. For // this reason you can define some symbols to describe what is left in // the back buffer. // Having not found any way to determine this from glx (or wgl) I have // resorted to letting the user specify it with an environment variable, // GL_SWAP_TYPE, it should be equal to one of these symbols: // contents of back buffer after glXSwapBuffers(): #define SWAP 1 // assumme garbage is in back buffer (default) #define USE_COPY 2 // use glCopyPixels to imitate COPY behavior #define COPY 3 // unchanged #define NODAMAGE 4 // unchanged even by X expose() events static char SWAP_TYPE = 0; // 0 = determine it from environment variable //////////////////////////////////////////////////////////////// /** \fn bool GlWindow::can_do() const Returns true if the hardware supports the current value of mode(). If false, attempts to show or draw this window will cause an fltk::error(). */ /** Returns true if the hardware supports \a mode, see mode() for the meaning of the bits. */ bool GlWindow::can_do(int mode) { return GlChoice::find(mode) != 0; } void GlWindow::create() { if (!gl_choice) { gl_choice = GlChoice::find(mode_); if (!gl_choice) {error("Insufficient GL support"); return;} } #ifdef WIN32 Window::create(); #elif USE_QUARTZ Window::create(); #else CreatedWindow::create(this, gl_choice->vis, gl_choice->colormap, -1); //if (overlay && overlay != this) ((GlWindow*)overlay)->show(); //fltk::flush(); glXWaitGL(); glXWaitX(); #endif } /** \fn char GlWindow::valid() const; This flag is turned off on a new window or if the window is ever resized or the context is changed. It is turned on after draw() is called. draw() can use this to skip initializing the viewport, lights, or other pieces of the context. \code void My_GlWindow_Subclass::draw() { if (!valid()) { glViewport(0,0,w(),h()); glFrustum(...); glLight(...); glEnable(...); ...other initialization... } ... draw your geometry here ... } \endcode */ /** Turn off valid(). */ void GlWindow::invalidate() { valid(0); #if USE_X11 if (overlay) ((GlWindow*)overlay)->valid(0); #endif } /** Set or change the OpenGL capabilites of the window. The value can be any of the symbols from \link visual.h <fltk/visual.h> \endlink OR'd together: - fltk::INDEXED_COLOR indicates that a colormapped visual is ok. This call will normally fail if a TrueColor visual cannot be found. - fltk::RGB_COLOR this value is zero and may be passed to indicate that fltk::INDEXED_COLOR is \e not wanted. - fltk::RGB24_COLOR indicates that the visual must have at least 8 bits of red, green, and blue (Windows calls this "millions of colors"). - fltk::DOUBLE_BUFFER indicates that double buffering is wanted. - fltk::SINGLE_BUFFER is zero and can be used to indicate that double buffering is \a not wanted. - fltk::ACCUM_BUFFER makes the accumulation buffer work - fltk::ALPHA_BUFFER makes an alpha buffer - fltk::DEPTH_BUFFER makes a depth/Z buffer - fltk::STENCIL_BUFFER makes a stencil buffer - fltk::MULTISAMPLE makes it multi-sample antialias if possible (X only) - fltk::STEREO stereo if possible - NO_AUTO_SWAP disables the automatic call to swap_buffers() after draw(). - NO_ERASE_OVERLAY if overlay hardware is used, don't call glClear before calling draw_overlay(). If the desired combination cannot be done, FLTK will try turning off MULTISAMPLE and STERERO. If this also fails then attempts to create the context will cause fltk::error() to be called, aborting the program. Use can_do() to check for this and try other combinations. You can change the mode while the window is displayed. This is most useful for turning double-buffering on and off. Under X this will cause the old X window to be destroyed and a new one to be created. If this is a top-level window this will unfortunately also cause the window to blink, raise to the top, and be de-iconized, and the ID will change, possibly breaking other code. It is best to make the GL window a child of another window if you wish to do this! */ bool GlWindow::mode(int m) { if (m == mode_) return false; mode_ = m; // destroy context and g: if (shown()) { bool reshow = visible_r(); destroy(); gl_choice = 0; if (reshow) {create(); show();} } return true; } #define NON_LOCAL_CONTEXT 0x80000000 /** Selects the OpenGL context for the widget, creating it if necessary. It is called automatically prior to the draw() method being called. You can call it in handle() to set things up to do OpenGL hit detection, or call it other times to do incremental update of the window. */ void GlWindow::make_current() { Window::make_current(); // so gc is correct for non-OpenGL calls #if USE_QUARTZ if (!gl_choice) { gl_choice = GlChoice::find(mode_); if (!gl_choice) {error("Insufficient GL support"); return;} } #endif if (!context_) { mode_ &= ~NON_LOCAL_CONTEXT; context_ = create_gl_context(this, gl_choice); set_gl_context(this, context_); valid(0); } else { set_gl_context(this, context_); } } /** Set the projection so 0,0 is in the lower left of the window and each pixel is 1 unit wide/tall. If you are drawing 2D images, your draw() method may want to call this when valid() is false. */ void GlWindow::ortho() { #if 1 // simple version glLoadIdentity(); glViewport(0, 0, w(), h()); glOrtho(0, w(), 0, h(), -1, 1); #else // this makes glRasterPos off the edge much less likely to clip, // but a lot of OpenGL drivers do not like it. GLint v[2]; glGetIntegerv(GL_MAX_VIEWPORT_DIMS, v); glLoadIdentity(); glViewport(w()-v[0], h()-v[1], v[0], v[1]); glOrtho(w()-v[0], w(), h()-v[1], h(), -1, 1); #endif } /** Swap the front and back buffers of this window (or copy the back buffer to the front, possibly clearing or garbaging the back one, depending on your OpenGL implementation. This is called automatically after draw() unless the NO_AUTO_SWAP flag is set in the mode(). */ void GlWindow::swap_buffers() { #ifdef _WIN32 #if USE_GL_OVERLAY // Do not swap the overlay, to match GLX: wglSwapLayerBuffers(CreatedWindow::find(this)->dc, WGL_SWAP_MAIN_PLANE); #else SwapBuffers(CreatedWindow::find(this)->dc); #endif #elif USE_QUARTZ aglSwapBuffers((AGLContext)context_); #else glXSwapBuffers(xdisplay, xid(this)); #endif } #if USE_GL_OVERLAY && defined(_WIN32) int fl_overlay_depth = 0; bool fl_overlay; #endif void GlWindow::flush() { uchar save_valid = valid_; uchar save_damage = damage(); CreatedWindow* i = CreatedWindow::find(this); #if USE_GL_OVERLAY && defined(_WIN32) if (save_damage == DAMAGE_OVERLAY && overlay && overlay != this && !i->region) goto OVERLAY_ONLY; #endif make_current(); if (mode_ & DOUBLE_BUFFER) { glDrawBuffer(GL_BACK); if (!SWAP_TYPE) { SWAP_TYPE = SWAP; const char* c = getenv("GL_SWAP_TYPE"); if (c) switch (c[0]) { case 'U' : SWAP_TYPE = USE_COPY; break; case 'C' : SWAP_TYPE = COPY; break; case 'N' : SWAP_TYPE = NODAMAGE; break; default : SWAP_TYPE = SWAP; break; } } if (SWAP_TYPE == NODAMAGE) { // don't draw if only overlay damage or expose events: if (save_damage != DAMAGE_OVERLAY || !save_valid) { draw(); if (!(mode_ & NO_AUTO_SWAP)) swap_buffers(); } else { swap_buffers(); } } else if (SWAP_TYPE == COPY) { // don't draw if only the overlay is damaged: if (save_damage != DAMAGE_OVERLAY || i->region || !save_valid) { draw(); if (!(mode_ & NO_AUTO_SWAP)) swap_buffers(); } else { swap_buffers(); } } else if (SWAP_TYPE == USE_COPY && overlay == this) { // If we are faking the overlay, use CopyPixels to act like // SWAP_TYPE == COPY. Otherwise overlay redraw is way too slow. // don't draw if only the overlay is damaged: if (damage1_ || save_damage != DAMAGE_OVERLAY || i->region || !save_valid) draw(); // we use a seperate context for the copy because rasterpos must be 0 // and depth test needs to be off: static GLContext ortho_context = 0; static GlWindow* ortho_window = 0; if (!ortho_context) { ortho_context = create_gl_context(this, gl_choice); save_valid = 0; } set_gl_context(this, ortho_context); if (!save_valid || ortho_window != this) { ortho_window = this; glDisable(GL_DEPTH_TEST); glReadBuffer(GL_BACK); glDrawBuffer(GL_FRONT); glLoadIdentity(); glViewport(0, 0, w(), h()); glOrtho(0, w(), 0, h(), -1, 1); glRasterPos2i(0,0); } glCopyPixels(0,0,w(),h(),GL_COLOR); make_current(); // set current context back to draw overlay damage1_ = 0; } else { damage1_ = save_damage; set_damage(DAMAGE_ALL); draw(); if (overlay == this) draw_overlay(); if (!(mode_ & NO_AUTO_SWAP)) swap_buffers(); goto NO_OVERLAY; } if (overlay==this) { // fake overlay in front buffer glDrawBuffer(GL_FRONT); draw_overlay(); glDrawBuffer(GL_BACK); glFlush(); } NO_OVERLAY:; } else { // single-buffered context is simpler: draw(); if (overlay == this) draw_overlay(); glFlush(); } #if USE_GL_OVERLAY && defined(_WIN32) OVERLAY_ONLY: // Draw into hardware overlay planes if they are damaged: if (overlay && overlay != this && (i->region || save_damage&DAMAGE_OVERLAY || !save_valid)) { #if SGI320_BUG // SGI 320 messes up overlay with user-defined cursors: bool fixcursor = false; if (i->cursor && i->cursor != fl_default_cursor) { fixcursor = true; // make it restore cursor later SetCursor(0); } #endif set_gl_context(this, (GLContext)overlay); if (fl_overlay_depth) wglRealizeLayerPalette(i->dc, 1, TRUE); glDisable(GL_SCISSOR_TEST); if (!(mode_&NO_ERASE_OVERLAY)) glClear(GL_COLOR_BUFFER_BIT); fl_overlay = true; valid(save_valid); draw_overlay(); fl_overlay = false; wglSwapLayerBuffers(i->dc, WGL_SWAP_OVERLAY1); #if SGI320_BUG if (fixcursor) SetCursor(i->cursor); #endif } #endif valid(1); } void GlWindow::layout() { if (layout_damage() & LAYOUT_WH) { valid(0); #if USE_QUARTZ no_gl_context(); // because the BUFFER_RECT may change #endif #if USE_X11 if (!resizable() && overlay && overlay != this) ((GlWindow*)overlay)->resize(0,0,w(),h()); #endif } Window::layout(); #if USE_X11 glXWaitX(); #endif } /** \fn GLContext GlWindow::context() const; Return the current OpenGL context object being used by this window, or 0 if there is none. */ /** \fn void GlWindow::context(GLContext v, bool destroy_flag); Set the OpenGL context object to use to draw this window. This is a system-dependent structure (HGLRC on Windows,GLXContext on X, and AGLContext (may change) on OS/X), but it is portable to copy the context from one window to another. You can also set it to NULL, which will force FLTK to recreate the context the next time make_current() is called, this is useful for getting around bugs in OpenGL implementations. \a destroy_flag indicates that the context belongs to this window and should be destroyed by it when no longer needed. It will be destroyed when the window is destroyed, or when the mode() is changed, or if the context is changed to a new value with this call. */ void GlWindow::_context(void* v, bool destroy_flag) { if (context_ && context_ != v && !(mode_&NON_LOCAL_CONTEXT)) delete_gl_context(context_); context_ = (GLContext)v; if (destroy_flag) mode_ &= ~NON_LOCAL_CONTEXT; else mode_ |= NON_LOCAL_CONTEXT; } /** Besides getting rid of the window, this will destroy the context if it belongs to the window. */ void GlWindow::destroy() { context(0); #if USE_GL_OVERLAY if (overlay && overlay != this) { #ifdef _WIN32 delete_gl_context((GLContext)overlay); #endif overlay = 0; } #endif Window::destroy(); } /** The destructor will destroy the context() if it belongs to the window. */ GlWindow::~GlWindow() { destroy(); } /** \fn GlWindow::GlWindow(int x, int y, int w, int h, const char *label=0); The constructor sets the mode() to RGB_COLOR|DEPTH_BUFFER|DOUBLE_BUFFER which is probably all that is needed for most 3D OpenGL graphics. */ void GlWindow::init() { mode_ = DEPTH_BUFFER | DOUBLE_BUFFER; context_ = 0; gl_choice = 0; overlay = 0; damage1_ = 0; } /** You must implement this virtual function if you want to draw into the overlay. The overlay is cleared before this is called (unless the NO_ERASE_OVERLAY bit is set in the mode \e and hardware overlay is supported). You should draw anything that is not clear using OpenGL. If the hardware overlay is being used it will probably be color indexed. You must use glsetcolor() to choose colors (it allocates them from the colormap using system-specific calls), and remember that you are in an indexed OpenGL mode and drawing anything other than flat-shaded will probably not work. Depending on the OS and whether or not the overlay is being simulated, the context may be shared with the main window. This means if you check valid() in draw() to avoid initialization, you must do so here and initialize to exactly the same setting. */ void GlWindow::draw_overlay() {} int GlWindow::handle( int event ) { #if USE_QUARTZ switch ( event ) { case HIDE: aglSetDrawable( context(), NULL ); break; } #endif return Window::handle( event ); } #endif // // End of "$Id: Fl_Gl_Window.cxx 5936 2007-07-24 11:25:53Z spitzak $". //
32.710952
99
0.704007
MarioHenze
ccd8312594e55bf962aa855e1fefc1e514fe86db
20,619
cpp
C++
frameworks/render/libs/isect/dmzRenderIsect.cpp
dmzgroup/dmz
fc2d9ddcb04ed71f4106b8d33539529807b3dea6
[ "MIT" ]
2
2015-11-05T03:03:43.000Z
2017-05-15T12:55:39.000Z
frameworks/render/libs/isect/dmzRenderIsect.cpp
dmzgroup/dmz
fc2d9ddcb04ed71f4106b8d33539529807b3dea6
[ "MIT" ]
null
null
null
frameworks/render/libs/isect/dmzRenderIsect.cpp
dmzgroup/dmz
fc2d9ddcb04ed71f4106b8d33539529807b3dea6
[ "MIT" ]
null
null
null
#include <dmzRenderIsect.h> #include <dmzTypesHandleContainer.h> #include <dmzTypesHashTableUInt32Template.h> #include <dmzTypesVector.h> //! \cond const dmz::UInt32 dmz::IsectPolygonBackCulledMask (0x01); const dmz::UInt32 dmz::IsectPolygonFrontCulledMask (0x02); const dmz::UInt32 dmz::IsectPolygonInvisibleMask (0x04); //! \endcond namespace { struct testStruct { dmz::UInt32 testID; dmz::IsectTestTypeEnum type; dmz::Vector pt1; dmz::Vector pt2; testStruct &operator= (const testStruct &Value) { testID = Value.testID; type = Value.type; pt1 = Value.pt1; pt2 = Value.pt2; return *this; } testStruct () : testID (0), type (dmz::IsectUnknownTest) {;} testStruct ( const dmz::UInt32 TestID, const dmz::IsectTestTypeEnum TheType, const dmz::Vector &ThePt1, const dmz::Vector &ThePt2) : testID (TestID), type (TheType), pt1 (ThePt1), pt2 (ThePt2) {;} testStruct (const testStruct &Value) : testID (0), type (dmz::IsectUnknownTest) { *this = Value; } }; }; /*! \class dmz::IsectTestContainer \ingroup Render \brief Intersection test container. \details The intersection test container stores multiple intersection tests so that the tests may be batch processed if the underlying implementation supports it. Intersection test may use either rays or segments. */ struct dmz::IsectTestContainer::State { UInt32 count; HashTableUInt32Iterator it; HashTableUInt32Template<testStruct> table; State () : count (0) {;} ~State () { table.empty (); } void clear () { it.reset (); count = 0; table.empty (); } }; //! Constructor. dmz::IsectTestContainer::IsectTestContainer () : _state (*(new State)) {;} //! Copy constructor. dmz::IsectTestContainer::IsectTestContainer (const IsectTestContainer &Value) : _state (*(new State)) { *this = Value; } //! Destructor. dmz::IsectTestContainer::~IsectTestContainer () { delete &_state; } //! Assignment operator. dmz::IsectTestContainer & dmz::IsectTestContainer::operator= (const IsectTestContainer &Value) { _state.count = Value._state.count; _state.table.empty (); _state.table.copy (Value._state.table); return *this; } //! Clear container. void dmz::IsectTestContainer::clear () { _state.clear (); } /*! \brief Adds or updates an intersection test in the container. \param[in] TestID Intersection test identification value. ID values do not need to be sequential. \param[in] TestType Type intersection test to perform. Defines how \a Value1 and \a Value2 are interpreted. \param[in] Value1 The start point. \param[in] Value2 Either the ray's direction or the end of the segment. \return Returns dmz::True if the test was successfully stored in the container. \sa dmz::IsectTestTypeEnum */ dmz::Boolean dmz::IsectTestContainer::set_test ( const UInt32 TestID, const IsectTestTypeEnum TestType, const Vector &Value1, const Vector &Value2) { Boolean result (False); testStruct *ts = _state.table.lookup (TestID); if (!ts) { ts = new testStruct (TestID, TestType, Value1, Value2); if (_state.table.store (TestID, ts)) { result = True; } else { delete ts; ts = 0; } } else { ts->type = TestType; ts->pt1 = Value1; ts->pt2 = Value2; result = True; } return result; } /*! \brief Adds or updates a ray intersection test in the container. \param[in] TestID Intersection test identification value. ID values do not need to be sequential. \param[in] Position Starting point of the ray. \param[in] Direction Unit vector containing the direction of the ray. \return Returns dmz::True if the ray test was successfully stored in the container. */ dmz::Boolean dmz::IsectTestContainer::set_ray_test ( const UInt32 TestID, const Vector &Position, const Vector &Direction) { return set_test (TestID, IsectRayTest, Position, Direction); } /*! \brief Adds or updates a segment intersection test in the container. \param[in] TestID Intersection test identification value. ID values do not need to be sequential. \param[in] StartPoint Starting point of the segment. \param[in] EndPoint End point of the segment. \return Returns dmz::True if the segment test was successfully stored in the container. */ dmz::Boolean dmz::IsectTestContainer::set_segment_test ( const UInt32 TestID, const Vector &StartPoint, const Vector &EndPoint) { return set_test (TestID, IsectSegmentTest, StartPoint, EndPoint); } /*! \brief Adds an intersection test in the container. \param[in] TestType Type intersection test to perform. Defines how \a Value1 and \a Value2 are interpreted. \param[in] Value1 The start point. \param[in] Value2 Either the ray's direction or the end of the segment. \return Returns the test ID. Returns zero if the test was not added. \sa dmz::IsectTestTypeEnum */ dmz::UInt32 dmz::IsectTestContainer::add_test ( const IsectTestTypeEnum TestType, const Vector &Value1, const Vector &Value2) { UInt32 result (0); testStruct *ts (new testStruct (0, TestType, Value1, Value2)); if (ts) { _state.count++; if (!_state.count) { _state.count++; } if (_state.table.store (_state.count, ts)) { result = ts->testID = _state.count; } else { const UInt32 Start (_state.count); _state.count++; if (!_state.count) { _state.count++; } while ((_state.count != Start) && _state.table.lookup (_state.count)) { _state.count++; if (!_state.count) { _state.count++; } } if (_state.count != Start) { if (_state.table.store (_state.count, ts)) { result = ts->testID = _state.count; } else { delete ts; ts = 0; } } } } return result; } /*! \brief Adds a ray intersection test in the container. \param[in] Position Starting point of the ray. \param[in] Direction Unit vector containing the direction of the ray. \return Returns the test ID. Returns zero if the test was not added. */ dmz::UInt32 dmz::IsectTestContainer::add_ray_test (const Vector &Position, const Vector &Direction) { return add_test (IsectRayTest, Position, Direction); } /*! \brief Adds a segment intersection test in the container. \param[in] StartPoint Starting point of the segment. \param[in] EndPoint End point of the segment. \return Returns the test ID. Returns zero if the test was not added. */ dmz::UInt32 dmz::IsectTestContainer::add_segment_test ( const Vector &StartPoint, const Vector &EndPoint) { return add_test (IsectSegmentTest, StartPoint, EndPoint); } /*! \brief Removes intersection test. \param[in] TestID Intersection test ID value. \return Returns dmz::True if the test was successfully removed from the container. */ dmz::Boolean dmz::IsectTestContainer::remove_test (const UInt32 TestID) { Boolean result (False); testStruct *ts = _state.table.remove (TestID); if (ts) { result = True; delete ts; ts = 0; } return result; } /*! \brief Looks up intersection test. \param[in] TestID Intersection test ID value. \param[out] testType The type of the test. \param[out] value1 First Vector value of the intersection test. \param[out] value2 Second Vector value of the intersection test. \return Returns dmz::True if the intersection test specified by \a TestID is found. */ dmz::Boolean dmz::IsectTestContainer::lookup_test ( const UInt32 TestID, IsectTestTypeEnum &testType, Vector &value1, Vector &value2) const { Boolean result (False); testStruct *ts = _state.table.lookup (TestID); if (ts) { testType = ts->type; value1 = ts->pt1; value2 = ts->pt2; result = True; } return result; } /*! \brief Gets first intersection test. \param[out] testID Intersection test ID value. \param[out] testType The type of the test. \param[out] value1 First Vector value of the intersection test. \param[out] value2 Second Vector value of the intersection test. \return Returns dmz::True if the first intersection test is returned. Returns dmz::False if the container is empty. */ dmz::Boolean dmz::IsectTestContainer::get_first_test ( UInt32 &testID, IsectTestTypeEnum &testType, Vector &value1, Vector &value2) const { Boolean result (False); testStruct *ts = _state.table.get_first (_state.it); if (ts) { testID = ts->testID; testType = ts->type; value1 = ts->pt1; value2 = ts->pt2; result = True; } return result; } /*! \brief Gets next intersection test. \param[out] testID Intersection test ID value. \param[out] testType The type of the test. \param[out] value1 First Vector value of the intersection test. \param[out] value2 Second Vector value of the intersection test. \return Returns dmz::True if the next intersection test is returned. Returns dmz::False if the container has returned all intersection tests. */ dmz::Boolean dmz::IsectTestContainer::get_next_test ( UInt32 &testID, IsectTestTypeEnum &testType, Vector &value1, Vector &value2) const { Boolean result (False); testStruct *ts = _state.table.get_next (_state.it); if (ts) { testID = ts->testID; testType = ts->type; value1 = ts->pt1; value2 = ts->pt2; result = True; } return result; } /*! \class dmz::IsectParameters \ingroup Render \brief Intersection test parameters. \details The dmz::IsectParameters specifies what results should be collect from the intersection test. Bu default, all parameters are set to dmz::True. */ struct dmz::IsectParameters::State { IsectTestResultTypeEnum type; Boolean findNormal; Boolean findHandle; Boolean findDistance; Boolean findCullMode; Boolean attrSet; HandleContainer attr; State () : type (IsectAllPoints), findNormal (True), findHandle (True), findDistance (True), findCullMode (True), attrSet (False) {;} }; //! Constructor. dmz::IsectParameters::IsectParameters () : _state (*(new State)) {;} //! Copy constructor. dmz::IsectParameters::IsectParameters (const IsectParameters &Value) : _state (*(new State)) { *this = Value; } //! Destructor. dmz::IsectParameters::~IsectParameters () { delete &_state; } //! Assignment operator. dmz::IsectParameters & dmz::IsectParameters::operator= (const IsectParameters &Value) { _state.type = Value._state.type; _state.findNormal = Value._state.findNormal; _state.findHandle = Value._state.findHandle; _state.findDistance = Value._state.findDistance; _state.findCullMode = Value._state.findCullMode; return *this; } //! Specifies how test points should be processed and returned. void dmz::IsectParameters::set_test_result_type (const IsectTestResultTypeEnum Type) { _state.type = Type; } //! Gets how test points should be processed and returned. dmz::IsectTestResultTypeEnum dmz::IsectParameters::get_test_result_type () const { return _state.type; } //! Specifies if intersection normal should be calculated for each result. void dmz::IsectParameters::set_calculate_normal (const Boolean AttrState) { _state.findNormal = AttrState; } //! Returns if intersection normal should be calculated for each result. dmz::Boolean dmz::IsectParameters::get_calculate_normal () const { return _state.findNormal; } //! Specifies if the objects Handle should be calculated for each result. void dmz::IsectParameters::set_calculate_object_handle (const Boolean AttrState) { _state.findHandle = AttrState; } //! Returns if the objects Handle should be calculated for each result. dmz::Boolean dmz::IsectParameters::get_calculate_object_handle () const { return _state.findHandle; } //! Specifies if the intersection distance should be calculated for each result. void dmz::IsectParameters::set_calculate_distance (const Boolean AttrState) { _state.findDistance = AttrState; } //! Returns if the intersection distance should be calculated for each result. dmz::Boolean dmz::IsectParameters::get_calculate_distance () const { return _state.findDistance; } //! Specifies if the polygon cull mode should be calculated for each result. void dmz::IsectParameters::set_calculate_cull_mode (const Boolean Value) { _state.findCullMode = Value; } //! Returns if the polygon cull mode should be calculated for each result. dmz::Boolean dmz::IsectParameters::get_calculate_cull_mode () const { return _state.findCullMode; } /*! \brief Sets the isect attributes to use in the intersection tests. \details By default, all intersections are tested against dmz::RenderIsectStaticName and dmz::RenderIsectEntityName. \param[in] Attr HandleContainer containing the isect attribute handles. */ void dmz::IsectParameters::set_isect_attributes (const HandleContainer &Attr) { if (Attr.get_count () > 0) { _state.attrSet = True; _state.attr = Attr; } } /*! \brief Gets the isect attributes to use in the intersection tests. \param[out] attr HandleContainer containing the isect attribute handles. \return Return dmz::True if any handles were returned in the HandleContainer. */ dmz::Boolean dmz::IsectParameters::get_isect_attributes (HandleContainer &attr) const { Boolean result (_state.attrSet); if (result) { attr = _state.attr; } return result; } /*! \class dmz::IsectResult \ingroup Render \brief Intersection test result. */ struct dmz::IsectResult::State { UInt32 testID; Boolean pointSet; Vector point; Boolean normalSet; Vector normal; Boolean objHandleSet; Handle objHandle; Boolean distanceSet; Float64 distance; Boolean cullModeSet; UInt32 cullMode; State () : testID (0), pointSet (False), normalSet (False), objHandleSet (False), objHandle (0), distanceSet (False), distance (0.0), cullModeSet (False), cullMode (0) {;} }; //! Base constructor. dmz::IsectResult::IsectResult () : _state (*(new State)) {;} /*! \brief Test ID Constructor. \param[in] TestID Intersection test identification value. */ dmz::IsectResult::IsectResult (const UInt32 TestID) : _state (*(new State)) { _state.testID = TestID; } //! Copy constructor. dmz::IsectResult::IsectResult (const IsectResult &Value) : _state (*(new State)) { *this = Value; } //! Destructor. dmz::IsectResult::~IsectResult () { delete &_state; } //! Assignment operator. dmz::IsectResult & dmz::IsectResult::operator= (const IsectResult &Value) { _state.testID = Value._state.testID; _state.pointSet = Value._state.pointSet; _state.point = Value._state.point; _state.normalSet = Value._state.normalSet; _state.normal = Value._state.normal; _state.objHandleSet = Value._state.objHandleSet; _state.objHandle = Value._state.objHandle; _state.distanceSet = Value._state.distanceSet; _state.distance = Value._state.distance; _state.cullModeSet = Value._state.cullModeSet; _state.cullMode = Value._state.cullMode; return *this; } //! Sets intersection test identification value. void dmz::IsectResult::set_isect_test_id (const UInt32 TestID) { _state.testID = TestID; } //! Gets intersection test identification value. dmz::UInt32 dmz::IsectResult::get_isect_test_id () const { return _state.testID; } //! Sets intersection point. void dmz::IsectResult::set_point (const Vector &Value) { _state.pointSet = True; _state.point = Value; } /*! \brief Gets intersection point. \param[out] value Vector containing intersection point. \return Returns dmz::True if the intersection point was set. */ dmz::Boolean dmz::IsectResult::get_point (Vector &value) const { value = _state.point; return _state.pointSet; } //! Sets intersection point normal. void dmz::IsectResult::set_normal (const Vector &Value) { _state.normalSet = True; _state.normal = Value; } /*! \brief Gets intersection point normal. \param[out] value Vector containing intersection point normal. \return Returns dmz::True if the intersection point normal was set. */ dmz::Boolean dmz::IsectResult::get_normal (Vector &value) const { value = _state.normal; return _state.normalSet; } //! Sets intersected object's Handle. void dmz::IsectResult::set_object_handle (const Handle Value) { _state.objHandleSet = True; _state.objHandle = Value; } /*! \brief Gets intersection point object Handle. \param[out] value Handle containing intersection point object Handle. \return Returns dmz::True if the intersection point object Handle was set. */ dmz::Boolean dmz::IsectResult::get_object_handle (Handle &value) const { value = _state.objHandle; return _state.objHandleSet; } //! Sets intersection distance from start point. void dmz::IsectResult::set_distance (const Float64 Value) { _state.distanceSet = True; _state.distance = Value; } /*! \brief Gets intersection distance from the intersection start point. \param[out] value Distance from the intersection start point. \return Returns dmz::True if the intersection distance was set. */ dmz::Boolean dmz::IsectResult::get_distance (Float64 &value) const { value = _state.distance; return _state.distanceSet; } //! Sets cull mode of intersected polygon. void dmz::IsectResult::set_cull_mode (const UInt32 Value) { _state.cullModeSet = True; _state.cullMode = Value; } /*! \brief Gets intersection point cull mode. \param[out] value Mask containing the polygons cull mode. \return Returns dmz::True if the cull mode was set. */ dmz::Boolean dmz::IsectResult::get_cull_mode (UInt32 &value) const { value = _state.cullMode; return _state.cullModeSet; } /*! \class dmz::IsectResultContainer \ingroup Render \brief Intersection test result container. \details The intersection result container will have an IsectResult for each intersection point that is returned. Multiple IsectResult objects may result from a single test. */ struct dmz::IsectResultContainer::State { UInt32 count; HashTableUInt32Iterator it; HashTableUInt32Template<IsectResult> table; State () : count (0) {;} ~State () { table.empty (); } }; //! Base constructor. dmz::IsectResultContainer::IsectResultContainer () : _state (*(new State)) {;} //! Copy constructor. dmz::IsectResultContainer::IsectResultContainer (const IsectResultContainer &Value) : _state (*(new State)) { *this = Value; } //! Destructor. dmz::IsectResultContainer::~IsectResultContainer () { delete &_state; } //! Assignment operator. dmz::IsectResultContainer & dmz::IsectResultContainer::operator= (const IsectResultContainer &Value) { _state.count = Value._state.count; _state.table.empty (); _state.table.copy (Value._state.table); return *this; } //! Returns number of intersection results are stored in the container. dmz::Int32 dmz::IsectResultContainer::get_result_count () const { return _state.table.get_count (); } //! Resets the iterator. void dmz::IsectResultContainer::reset () { _state.it.reset (); } //! Clears the container. void dmz::IsectResultContainer::clear () { _state.it.reset (); _state.table.empty (); _state.count = 0; } //! Adds a result to the container. void dmz::IsectResultContainer::add_result (const IsectResult &Value) { IsectResult *ir (new IsectResult (Value)); if (ir) { if (_state.table.store (_state.count, ir)) { _state.count++; } else { delete ir; ir = 0; } } } /*! \brief Gets first result stored in the container. \param[out] value First result stored in the container. \return Returns dmz::True if the first result is returned in \a value. Returns dmz::False if the container is empty. */ dmz::Boolean dmz::IsectResultContainer::get_first (IsectResult &value) const { Boolean result (False); IsectResult *ir (_state.table.get_first (_state.it)); if (ir) { value = *ir; result = True; } return result; } /*! \brief Gets next result stored in the container. \param[out] value next result stored in the container. \return Returns dmz::True if the next result is returned in \a value. Returns dmz::False if the container has returned all results. */ dmz::Boolean dmz::IsectResultContainer::get_next (IsectResult &value) const { Boolean result (False); IsectResult *ir (_state.table.get_next (_state.it)); if (ir) { value = *ir; result = True; } return result; }
23.193476
90
0.701392
dmzgroup
ccda31c2812b512e71f448266234ec53ea6dc35b
1,498
hpp
C++
include/cppgit2/tag.hpp
koordinates/cppgit2
49c36843f828f2f628aacdd04daf9d0812a220a4
[ "MIT" ]
null
null
null
include/cppgit2/tag.hpp
koordinates/cppgit2
49c36843f828f2f628aacdd04daf9d0812a220a4
[ "MIT" ]
null
null
null
include/cppgit2/tag.hpp
koordinates/cppgit2
49c36843f828f2f628aacdd04daf9d0812a220a4
[ "MIT" ]
1
2022-01-26T20:23:12.000Z
2022-01-26T20:23:12.000Z
#pragma once #include <cppgit2/libgit2_api.hpp> #include <cppgit2/object.hpp> #include <cppgit2/oid.hpp> #include <cppgit2/ownership.hpp> #include <cppgit2/signature.hpp> #include <git2.h> namespace cppgit2 { class tag : public libgit2_api { public: // Default construct a tag tag(); // Construct from libgit2 C ptr // If owned by user, this will be free'd in destructor tag(git_tag *c_ptr, ownership owner = ownership::libgit2); // Cleanup tag ptr ~tag(); // Move constructor (appropriate other's c_ptr_) tag(tag&& other); // Move assignment constructor (appropriate other's c_ptr_) tag& operator= (tag&& other); // Create an in-memory copy of a tag tag copy() const; // Copy constructor tag(tag const& other); // Id of the tag oid id() const; // Tag mesage std::string message() const; // Tag name std::string name() const; // Recursively peel until a non-tag git_object is found object peel() const; // Get tagger (author) of this tag signature tagger() const; // Get the tagged object of this tag object target() const; // Get the OID of the tagged object oid target_id() const; // Get the type of a tag's tagged object object::object_type target_type() const; // Owner repository for this tag class repository owner() const; // Access to libgit2 C ptr git_tag *c_ptr(); const git_tag *c_ptr() const; private: friend class repository; git_tag *c_ptr_; ownership owner_; }; } // namespace cppgit2
20.520548
61
0.685581
koordinates
ef9ddb8bf2a42a685700817d638d505ef1a0f0a5
397
cpp
C++
higan/fc/cpu/serialization.cpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
38
2018-04-05T05:00:05.000Z
2022-02-06T00:02:02.000Z
higan/fc/cpu/serialization.cpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
1
2018-04-29T19:45:14.000Z
2018-04-29T19:45:14.000Z
higan/fc/cpu/serialization.cpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
8
2018-04-16T22:37:46.000Z
2021-02-10T07:37:03.000Z
auto CPU::serialize(serializer& s) -> void { MOS6502::serialize(s); Thread::serialize(s); s.array(ram); s.integer(io.interruptPending); s.integer(io.nmiPending); s.integer(io.nmiLine); s.integer(io.irqLine); s.integer(io.apuLine); s.integer(io.rdyLine); s.integer(io.rdyAddrValid); s.integer(io.rdyAddrValue); s.integer(io.oamdmaPending); s.integer(io.oamdmaPage); }
19.85
44
0.690176
13824125580
efa042dc4136bec3323bfe0cefe543bcbd5721e4
2,356
cc
C++
gcj2019/Round_1b/Problem1.cc
maciej-marek-mielczarek/gcj
b3ccdd48f24c2e89f4135f6d8f53d12c404f327b
[ "MIT" ]
null
null
null
gcj2019/Round_1b/Problem1.cc
maciej-marek-mielczarek/gcj
b3ccdd48f24c2e89f4135f6d8f53d12c404f327b
[ "MIT" ]
null
null
null
gcj2019/Round_1b/Problem1.cc
maciej-marek-mielczarek/gcj
b3ccdd48f24c2e89f4135f6d8f53d12c404f327b
[ "MIT" ]
null
null
null
#include<iostream> #include<string> #include<vector> using std::cin; using std::cout; using std::endl; using std::vector; int main() { int test_case = 1, n_test_cases; cin >> n_test_cases; for(;test_case <= n_test_cases; ++test_case) { int p, q; cin >> p >> q; if(q>100) break; vector<int> tmp(11, 0); vector< vector<int> > interest(11, tmp); for(int n=0;n<p;++n) { int xx, yy; cin >> xx >> yy; char d; cin >> d; if(d=='N') { for(int x=0;x<=q;++x) { for(int y=yy+1;y<=q;++y) { ++(interest[x][y]); } } } if(d=='S') { for(int x=0;x<=q;++x) { for(int y=0;y<=yy-1;++y) { ++(interest[x][y]); } } } if(d=='E') { for(int x=xx+1;x<=q;++x) { for(int y=0;y<=q;++y) { ++(interest[x][y]); } } } if(d=='W') { for(int x=0;x<=xx-1;++x) { for(int y=0;y<=q;++y) { ++(interest[x][y]); } } } } int x=0, y=0, score=interest[0][0]; for(int xi=0;xi<=q;++xi) { for(int yi=0;yi<=q;++yi) { if(interest[xi][yi]>score) { score = interest[xi][yi]; x=xi; y=yi; } } } cout << "Case #" << test_case << ": " << x << " " << y<<"\n"; } /* int test_case = 1, n_test_cases = 0; string tmp{}; std::getline(cin, tmp); for(char digit : tmp) { if(digit >= '0' && digit <= '9') { n_test_cases *= 10; n_test_cases += (digit - '0'); } } for(;test_case <= n_test_cases; ++test_case) { } */ return 0; }
23.098039
69
0.290323
maciej-marek-mielczarek