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
e1ce9759b140f8c7ca5502f85a2418431599d8ed
4,863
cpp
C++
test/talker_test.cpp
ltsimps/metis_ros
f00fafe028d2a30508b2fc59daa9da35ff48eece
[ "MIT" ]
null
null
null
test/talker_test.cpp
ltsimps/metis_ros
f00fafe028d2a30508b2fc59daa9da35ff48eece
[ "MIT" ]
null
null
null
test/talker_test.cpp
ltsimps/metis_ros
f00fafe028d2a30508b2fc59daa9da35ff48eece
[ "MIT" ]
null
null
null
#include <tf/transform_broadcaster.h> #include <tf/transform_listener.h> #include <gtest/gtest.h> #include <ros/service_client.h> #include <map> #include <vector> #include <iostream> #include <fstream> #include <string> #include <set> #include <memory> #include <Parser.hpp> #include <Sentiment.hpp> #include <PositiveSentiment.hpp> #include <NegativeSentiment.hpp> #include <ros/ros.h> #include <ros/service_client.h> #include "metis_ros/strings.h" using std::string; using std::cout; using std::cin; /* //test the strings service existence TEST(TalkeSuite, existence_Test) { ros::NodeHandle nh; ros::ServiceClient client; //call service and check for existence client = nh.serviceClient < metis_ros::strings > ("change_output"); bool exists(client.waitForExistence(ros::Duration(20))); EXPECT_TRUE(exists); } /** * @brief Test the histogram function to make sure it returns words and frequencies. * */ TEST(input, histogram) { Parser p; std::vector<string> words; words.push_back("GUESS"); words.push_back("HANGMAN"); words.push_back("DIFFICULT"); words.push_back("TOM"); words.push_back("JOB"); words.push_back("HELLO"); words.push_back("HELLO"); words.push_back("HELLO"); words.push_back("GUESS"); std::map<string , int > testMap = p.generateHistogram(words); EXPECT_EQ(testMap["GUESS"] , 2); EXPECT_EQ(testMap["HANGMAN"] , 1); EXPECT_EQ(testMap["DIFFICULT"] , 1); EXPECT_EQ(testMap["TOM"] , 1); EXPECT_EQ(testMap["JOB"] , 1); EXPECT_EQ(testMap["HELLO"] , 3); } TEST(file_test, NegLoadWordlist) { NegativeSentiment ns; ns.loadWordlist(); EXPECT_GT(ns.getWordlist().size(), 0); } TEST(file_test, posLoadWordlist) { PositiveSentiment ps; ps.loadWordlist(); EXPECT_GT(ps.getWordlist().size(), 0); } /** * @brief Test analysis of Sentiment class for detection of negative words given stub histogram simulating voice input. * */ TEST(input, NegAnalysis) { Parser p; NegativeSentiment ns; ns.loadWordlist(); std::vector<string> words; words.push_back("GUESS"); words.push_back("HANGMAN"); words.push_back("DIFFICULT"); words.push_back("TOM"); words.push_back("JOB"); words.push_back("HELLO"); words.push_back("HELLO"); words.push_back("HELLO"); words.push_back("GUESS"); std::map<string , int > testMap = p.generateHistogram(words); EXPECT_EQ(testMap["GUESS"] , 2); EXPECT_EQ(testMap["HANGMAN"] , 1); EXPECT_EQ(testMap["DIFFICULT"] , 1); EXPECT_EQ(testMap["TOM"] , 1); EXPECT_EQ(testMap["JOB"] , 1); EXPECT_EQ(testMap["HELLO"] , 3); ns.analysis(testMap); int negativeEmotionScore = ns.getEmotionScore(); EXPECT_GT(negativeEmotionScore, 0); } /** * @brief Test analysis of Sentiment class for specific number of negative words. * */ TEST(input, exactWordScoreNegative) { Parser p; NegativeSentiment ns; ns.loadWordlist(); std::vector<string> words; words.push_back("GUESS"); words.push_back("HANGMAN"); words.push_back("DIFFICULT"); words.push_back("TOM"); words.push_back("HELLO"); words.push_back("HELLO"); words.push_back("GUESS"); std::map<string , int > testMap = p.generateHistogram(words); ns.analysis(testMap); int negativeEmotionScore = ns.getEmotionScore(); EXPECT_EQ(negativeEmotionScore, 1); } /* * @brief analysis of Sentiment class for specific number of positive words. * */ TEST(input, exactWordScorePositive) { Parser p; NegativeSentiment ns; ns.loadWordlist(); std::vector<string> words; words.push_back("LOVE"); words.push_back("HELLO"); words.push_back("HELLO"); words.push_back("GUESS"); std::map<string , int > testMap = p.generateHistogram(words); ns.analysis(testMap); int negativeEmotionScore = ns.getEmotionScore(); EXPECT_EQ(negativeEmotionScore, 1); } /** * @brief Test analysis of Sentiment class for detection of positive words given stub histogram simulating voice input. * */ TEST(input, posAnalysis) { Parser p; PositiveSentiment ps; ps.loadWordlist(); std::vector<string> words; words.push_back("GUESS"); words.push_back("HANGMAN"); words.push_back("DIFFICULT"); words.push_back("TOM"); words.push_back("JOB"); words.push_back("HELLO"); words.push_back("HELLO"); words.push_back("HELLO"); words.push_back("GUESS"); std::map<string , int > testMap = p.generateHistogram(words); EXPECT_EQ(testMap["GUESS"] , 2); EXPECT_EQ(testMap["HANGMAN"] , 1); EXPECT_EQ(testMap["DIFFICULT"] , 1); EXPECT_EQ(testMap["TOM"] , 1); EXPECT_EQ(testMap["JOB"] , 1); EXPECT_EQ(testMap["HELLO"] , 3); ps.analysis(testMap); int positiveEmotionScore = ps.getEmotionScore(); EXPECT_GT(positiveEmotionScore, 0); } int main(int argc, char **argv) { ros::init(argc, argv, "talker_test"); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
20.961207
121
0.693194
ltsimps
e1d0ed3d88e05154ff0559046e3dc92456942820
1,832
cpp
C++
chap1/DataSet.cpp
jasonmray/NeuralNetworks
037d038d5bdf62cb898ee3cd8ee84aca9ef92ee2
[ "MIT" ]
null
null
null
chap1/DataSet.cpp
jasonmray/NeuralNetworks
037d038d5bdf62cb898ee3cd8ee84aca9ef92ee2
[ "MIT" ]
null
null
null
chap1/DataSet.cpp
jasonmray/NeuralNetworks
037d038d5bdf62cb898ee3cd8ee84aca9ef92ee2
[ "MIT" ]
null
null
null
#include "DataSet.h" namespace J{ namespace Mnist{ DataSet::DataSet(){ } DataSet::~DataSet(){ } bool DataSet::load(const std::string & path) { return loadTrainingImages(path) && loadTestingImages(path); } bool DataSet::loadTrainingImages(const std::string & path) { if (!trainingImages.load( (path + "\\train-images-idx3-ubyte.gz").c_str() )) { return false; } LabelSet trainingLabels; if (!trainingLabels.load( (path + "\\train-labels-idx1-ubyte.gz").c_str(), &trainingImages)) { return false; } return true; } bool DataSet::loadTestingImages(const std::string & path) { if (!testingImages.load( (path + "\\t10k-images-idx3-ubyte.gz").c_str() )) { return false; } LabelSet testingLabels; if (!testingLabels.load( (path + "\\t10k-labels-idx1-ubyte.gz").c_str(), &testingImages)) { return false; } return true; } DataSet::ImageList DataSet::getTrainingImageRefs() const { ImageList imageRefs; imageRefs.reserve(MnistTrainingImageCount); for (size_t i = 0; i < MnistTrainingImageCount; i++) { imageRefs.push_back(&trainingImages.images[i]); } return imageRefs; } Jargon::IteratorRange<DataSet::ConstImageIterator> DataSet::getTrainingImages() const { return Jargon::IteratorRange<DataSet::ConstImageIterator>( trainingImages.images.begin(), trainingImages.images.begin() + 50000 ); } Jargon::IteratorRange<DataSet::ConstImageIterator> DataSet::getValidationImages() const { return Jargon::IteratorRange<DataSet::ConstImageIterator>( trainingImages.images.begin() + 50000, trainingImages.images.end() ); } Jargon::IteratorRange<DataSet::ConstImageIterator> DataSet::getTestingImages() const { return Jargon::IteratorRange<DataSet::ConstImageIterator>( testingImages.images.begin(), testingImages.images.end() ); } } }
24.426667
96
0.706878
jasonmray
e1d1eff22d4b4b6e88c929934ba1e02e3b954b78
5,274
hpp
C++
sources/FileFormats/Mesh/spMeshLoader3DS.hpp
rontrek/softpixel
73a13a67e044c93f5c3da9066eedbaf3805d6807
[ "Zlib" ]
14
2015-08-16T21:05:20.000Z
2019-08-21T17:22:01.000Z
sources/FileFormats/Mesh/spMeshLoader3DS.hpp
rontrek/softpixel
73a13a67e044c93f5c3da9066eedbaf3805d6807
[ "Zlib" ]
null
null
null
sources/FileFormats/Mesh/spMeshLoader3DS.hpp
rontrek/softpixel
73a13a67e044c93f5c3da9066eedbaf3805d6807
[ "Zlib" ]
3
2020-02-15T09:17:41.000Z
2020-05-21T14:10:40.000Z
/* * Mesh loader 3DS header * * This file is part of the "SoftPixel Engine" (Copyright (c) 2008 by Lukas Hermanns) * See "SoftPixelEngine.hpp" for license information. */ #ifndef __SP_MESHLOADER_3DS_H__ #define __SP_MESHLOADER_3DS_H__ #include "Base/spStandard.hpp" #ifdef SP_COMPILE_WITH_MESHLOADER_3DS #include "Base/spInputOutput.hpp" #include "Base/spDimension.hpp" #include "FileFormats/Mesh/spMeshLoader.hpp" #include <vector> namespace sp { namespace scene { class SP_EXPORT MeshLoader3DS : public MeshLoader { public: MeshLoader3DS(); ~MeshLoader3DS(); Mesh* loadMesh(const io::stringc &Filename, const io::stringc &TexturePath); private: /* === Enumerations === */ enum EMesh3DSChunks { CHUNK_MAGICNUMBER = 0x4D4D, CHUNK_VERSION = 0x0002, CHUNK_COLOR_F32 = 0x0010, CHUNK_COLOR_U8 = 0x0011, CHUNK_EDIT = 0x3D3D, CHUNK_EDIT_OBJECT = 0x4000, CHUNK_OBJECT_MESH = 0x4100, CHUNK_MESH_VERTICES = 0x4110, CHUNK_MESH_TRIANGLES = 0x4120, CHUNK_MESH_MATERIAL = 0x4130, CHUNK_MESH_TEXCOORDS = 0x4140, CHUNK_MESH_MATRIX = 0x4160, CHUNK_EDIT_MATERIAL = 0xAFFF, CHUNK_MATERIAL_NAME = 0xA000, CHUNK_MATERIAL_DIFFUSE = 0xA020, CHUNK_MATERIAL_SHADING = 0xA100, CHUNK_MATERIAL_COLORMAP = 0xA200, CHUNK_TEXTURE_FILE = 0xA300, CHUNK_KEYFRAME = 0xB000, CHUNK_KEYFRAME_CURTIME = 0xB009, CHUNK_KEYFRAME_TRACK = 0xB002, CHUNK_TRACK_BONENAME = 0xB010, CHUNK_TRACK_PIVOTPOINT = 0xB013, CHUNK_TRACK_BOUNDBOX = 0xB014, CHUNK_TRACK_BONEPOS = 0xB020, CHUNK_TRACK_BONEROT = 0xB021, CHUNK_TRACK_BONESCL = 0xB022, CHUNK_TRACK_NODE_ID = 0xB030, }; /* === Structures === */ struct SChunk3DS { u16 ID; u32 Length, Readed; }; struct SMaterial3DS { io::stringc Name; io::stringc TextureFilename; video::color Diffuse; }; struct SMaterialGroup3DS { io::stringc Name; std::vector<u16> TriangleEnum; }; struct SObjectGroup3DS { Mesh* Object; dim::matrix4f Transformation; std::vector<dim::vector3df> VertexList; std::vector<dim::point2df> TexCoordList; std::vector<SMeshTriangle3D> TriangleList; std::vector<SMaterialGroup3DS> MaterialGroupList; }; struct SJoint3DS { s16 NodeID; io::stringc Name; s16 ParentJointID; Mesh* Object; std::vector<dim::vector3df> PositionList; std::vector<dim::quaternion> RotationList; std::vector<dim::vector3df> ScaleList; }; /* === Templates === */ template <typename T> T readValue() { CurChunk_->Readed += sizeof(T); return File_->readValue<T>(); } template <typename T> void readStream(T* Buffer, u32 Count) { CurChunk_->Readed += sizeof(T) * Count; File_->readBuffer(Buffer, sizeof(T), Count); } /* === Functions === */ void readChunk(SChunk3DS* Chunk); void readChunk(); void ignore(u32 ByteCount); io::stringc readString(); video::color readColor(); bool readHeader(); bool readNextChunk(SChunk3DS* PrevChunk); bool readMeshVertices(); bool readMeshTriangles(); bool readMeshMaterial(); bool readMeshTexCoords(); bool readMeshMatrix(); bool readTrackPosition(); bool readTrackRotation(); bool readTrackScale(); void addNewMesh(); void buildMesh(const SObjectGroup3DS &ObjectGroup); /* === Members === */ SChunk3DS* CurChunk_; Mesh* RootMesh_; std::vector<SObjectGroup3DS> ObjectGroupList_; SObjectGroup3DS* CurObjGroup_; std::vector<SJoint3DS> JointList_; SJoint3DS* CurJoint_; std::vector<SMaterial3DS> MaterialList_; }; } // /namespace scene } // /namespace sp #endif #endif // ================================================================================
27.46875
85
0.481229
rontrek
e1d2c5c08b775327b76adf5d41d57eac45e87649
1,549
hpp
C++
simulation/traffic_simulator/include/traffic_simulator/traffic_lights/traffic_light_state.hpp
autocore-ai/scenario_simulator_v2
bb9569043e20649f0e4390e9225b6bb7b4de10b6
[ "Apache-2.0" ]
null
null
null
simulation/traffic_simulator/include/traffic_simulator/traffic_lights/traffic_light_state.hpp
autocore-ai/scenario_simulator_v2
bb9569043e20649f0e4390e9225b6bb7b4de10b6
[ "Apache-2.0" ]
null
null
null
simulation/traffic_simulator/include/traffic_simulator/traffic_lights/traffic_light_state.hpp
autocore-ai/scenario_simulator_v2
bb9569043e20649f0e4390e9225b6bb7b4de10b6
[ "Apache-2.0" ]
null
null
null
// Copyright 2015-2020 Tier IV, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef TRAFFIC_SIMULATOR__TRAFFIC_LIGHTS__TRAFFIC_LIGHT_STATE_HPP_ #define TRAFFIC_SIMULATOR__TRAFFIC_LIGHTS__TRAFFIC_LIGHT_STATE_HPP_ #include <autoware_perception_msgs/msg/lamp_state.hpp> #include <iostream> #include <stdexcept> namespace traffic_simulator { enum class TrafficLightColor { NONE, RED, GREEN, YELLOW }; std::istream & operator>>(std::istream &, TrafficLightColor &); std::ostream & operator<<(std::ostream &, const TrafficLightColor &); autoware_perception_msgs::msg::LampState makeLampState(const TrafficLightColor &); enum class TrafficLightArrow { NONE, STRAIGHT, LEFT, RIGHT }; std::istream & operator>>(std::istream &, TrafficLightArrow &); std::ostream & operator<<(std::ostream &, const TrafficLightArrow &); autoware_perception_msgs::msg::LampState makeLampState(const TrafficLightArrow &); } // namespace traffic_simulator #endif // TRAFFIC_SIMULATOR__TRAFFIC_LIGHTS__TRAFFIC_LIGHT_STATE_HPP_
36.880952
82
0.778567
autocore-ai
e1d45b30fe99e12f97664fa205679ea9db31ac39
3,378
hpp
C++
src/sim/sim.hpp
compstruct/hornet
44d8368ae39778c1c838b9d23b747be17e82e3a4
[ "MIT" ]
null
null
null
src/sim/sim.hpp
compstruct/hornet
44d8368ae39778c1c838b9d23b747be17e82e3a4
[ "MIT" ]
null
null
null
src/sim/sim.hpp
compstruct/hornet
44d8368ae39778c1c838b9d23b747be17e82e3a4
[ "MIT" ]
1
2021-03-25T18:07:20.000Z
2021-03-25T18:07:20.000Z
// -*- mode:c++; c-style:k&r; c-basic-offset:4; indent-tabs-mode: nil; -*- // vi:set et cin sw=4 cino=>se0n0f0{0}0^0\:0=sl1g0hspst0+sc3C0/0(0u0U0w0m0: #ifndef __SIM_HPP__ #define __SIM_HPP__ #include <vector> #include <memory> #include <boost/thread.hpp> #include <boost/thread/barrier.hpp> #include "random.hpp" #include "vcd.hpp" #include "sys.hpp" #include "logger.hpp" using namespace std; using namespace boost; class sim_thread { public: sim_thread(uint32_t thread_index, std::shared_ptr<sys> system, const vector<tile_id> &my_tiles, const uint64_t num_cycles, const uint64_t num_packets, const uint64_t sync_period, std::shared_ptr<barrier> sync_barrier, bool &global_drained, uint64_t &global_next_time, uint64_t &global_max_sync_count, vector<bool> &per_thread_drained, vector<bool> &per_thread_time_exceeded, vector<uint64_t> &per_thread_packet_count, vector<uint64_t> &per_thread_next_time, bool enable_fast_forward, int cpu_affinity, // -1 if none std::shared_ptr<vcd_writer> vcd #ifdef PROGRESSIVE_STATISTICS_REPORT , std::shared_ptr<system_statistics> stats #endif ); void operator()(); private: uint32_t my_thread_index; std::shared_ptr<sys> s; const vector<tile_id> my_tile_ids; const uint64_t max_num_cycles; const uint64_t max_num_packets; const uint64_t sync_period; std::shared_ptr<barrier> sync_barrier; bool &global_drained; // written only by thread 0 uint64_t &global_next_time; // written only by thread 0 uint64_t &global_max_sync_count; // written only by thread 0 vector<bool> &per_thread_drained; vector<bool> &per_thread_time_exceeded; vector<uint64_t> &per_thread_packet_count; vector<uint64_t> &per_thread_next_time; bool enable_fast_forward; int cpu; // CPU this thread should be pinned to; -1 if none std::shared_ptr<vcd_writer> vcd; #ifdef PROGRESSIVE_STATISTICS_REPORT std::shared_ptr<system_statistics> stats; #endif }; class sim { public: typedef enum { TM_SEQUENTIAL, TM_ROUND_ROBIN, TM_RANDOM } tile_mapping_t; public: sim(std::shared_ptr<sys> system, const uint64_t num_cycles, const uint64_t num_packets, const uint64_t sync_period, const uint32_t concurrency, bool enable_fast_forward, tile_mapping_t tile_mapping, const vector<unsigned> &cpu_affinities, std::shared_ptr<vcd_writer> vcd, logger &log, std::shared_ptr<random_gen> rng #ifdef PROGRESSIVE_STATISTICS_REPORT , std::shared_ptr<system_statistics> stats #endif ); virtual ~sim(); private: vector<std::shared_ptr<sim_thread> > sim_threads; thread_group threads; std::shared_ptr<barrier> sync_barrier; bool global_drained; // written only by thread 0 uint64_t global_next_time; // written only by thread 0 uint64_t global_max_sync_count; // written only by thread 0 vector<bool> per_thread_drained; vector<bool> per_thread_time_exceeded; vector<uint64_t> per_thread_packet_count; vector<uint64_t> per_thread_next_time; logger &log; std::shared_ptr<random_gen> rng; }; #endif // __SIM_HPP__
34.121212
77
0.686797
compstruct
e1d57716cd775f1006d67999a369ccac3a6d0c72
6,892
cpp
C++
src/prod/src/httpgateway/HttpClaimsAuthHandler.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
2,542
2018-03-14T21:56:12.000Z
2019-05-06T01:18:20.000Z
src/prod/src/httpgateway/HttpClaimsAuthHandler.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
994
2019-05-07T02:39:30.000Z
2022-03-31T13:23:04.000Z
src/prod/src/httpgateway/HttpClaimsAuthHandler.cpp
AnthonyM/service-fabric
c396ea918714ea52eab9c94fd62e018cc2e09a68
[ "MIT" ]
300
2018-03-14T21:57:17.000Z
2019-05-06T20:07:00.000Z
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace Common; using namespace HttpGateway; using namespace Transport; using namespace HttpServer; StringLiteral const TraceType("HttpClaimsAuthHandler"); HttpClaimsAuthHandler::HttpClaimsAuthHandler( __in Transport::SecurityProvider::Enum handlerType, __in FabricClientWrapperSPtr &client) : HttpAuthHandler(handlerType) , client_(client) , clientClaims_() , adminClientClaims_() , isAadServiceEnabled_(false) { LoadIsAadServiceEnabled(); } ErrorCode HttpClaimsAuthHandler::OnInitialize(SecuritySettings const& securitySettings) { clientClaims_ = securitySettings.ClientClaims(); adminClientClaims_ = securitySettings.AdminClientClaims(); WriteInfo(TraceType, "AdminClientClaims - {0}", adminClientClaims_); WriteInfo(TraceType, "UserClientClaims - {0}", clientClaims_); return ErrorCode::Success(); } ErrorCode HttpClaimsAuthHandler::OnSetSecurity(SecuritySettings const& securitySettings) { return OnInitialize(securitySettings); } void HttpClaimsAuthHandler::OnCheckAccess(AsyncOperationSPtr const& operation) { auto castedOperation = AsyncOperation::Get<AccessCheckAsyncOperation>(operation); wstring authHeader; auto error = castedOperation->request_.GetRequestHeader(Constants::AuthorizationHeader, authHeader); if (!error.IsSuccess()) { WriteWarning( TraceType, "Authorization header not found: uri={0} error={1}", castedOperation->request_.GetUrl(), error); castedOperation->TryComplete(operation, ErrorCodeValue::InvalidCredentials); return; } if (AzureActiveDirectory::ServerWrapper::IsAadEnabled() && !isAadServiceEnabled_) { this->ValidateAadToken(operation, authHeader); } else { if (isAadServiceEnabled_) { wstring jwt; error = ExtractJwtFromAuthHeader(authHeader, jwt); if (!error.IsSuccess()) { operation->TryComplete(operation, error); return; } authHeader = move(jwt); } auto innerOperation = client_->TvsClient->BeginValidateToken( authHeader, castedOperation->RemainingTime, [this](AsyncOperationSPtr const& innerOperation) { this->OnValidateTokenComplete(innerOperation, false); }, operation); this->OnValidateTokenComplete(innerOperation, true); } } void HttpClaimsAuthHandler::OnValidateTokenComplete(Common::AsyncOperationSPtr const& innerOperation, bool expectedCompletedSynchronously) { if (innerOperation->CompletedSynchronously != expectedCompletedSynchronously) { return; } auto const & operation = innerOperation->Parent; auto castedOperation = AsyncOperation::Get<AccessCheckAsyncOperation>(operation); TimeSpan expirationTime; std::vector<ServiceModel::Claim> claimList; auto error = client_->TvsClient->EndValidateToken( innerOperation, expirationTime, claimList); if (!error.IsSuccess()) { WriteInfo(TraceType, "Invalid claims token specified in Authorization header for uri: {0}", castedOperation->request_.GetUrl()); operation->TryComplete(operation, error); return; } SecuritySettings::RoleClaims parsedClaims; if (!SecuritySettings::ClaimListToRoleClaim(claimList, parsedClaims)) { WriteWarning(TraceType, "ClaimListToRoleClaim failed for claimlist: {0}", claimList); operation->TryComplete(operation, ErrorCodeValue::InvalidCredentials); return; } this->FinishAccessCheck(operation, castedOperation->request_, parsedClaims); } ErrorCode HttpClaimsAuthHandler::ExtractJwtFromAuthHeader( wstring const & authHeader, __out wstring & jwt) { size_t jwtIndex = authHeader.find(*Constants::Bearer); if (jwtIndex == wstring::npos) { WriteWarning( TraceType, "{0} token not found in Authorization header", Constants::Bearer); return ErrorCodeValue::InvalidCredentials; } // strip off "Bearer" and leading space // jwt = authHeader.substr(jwtIndex + Constants::Bearer->size() + 1); return ErrorCodeValue::Success; } void HttpClaimsAuthHandler::ValidateAadToken( AsyncOperationSPtr const & operation, wstring const & authHeader) { wstring jwt; auto error = ExtractJwtFromAuthHeader(authHeader, jwt); if (!error.IsSuccess()) { operation->TryComplete(operation, error); return; } wstring claims; TimeSpan unusedExpiration; error = AzureActiveDirectory::ServerWrapper::ValidateClaims( jwt, claims, // out unusedExpiration); // out SecuritySettings::RoleClaims roleClaims; if (error.IsSuccess()) { error = SecuritySettings::StringToRoleClaims(claims, roleClaims); } if (error.IsSuccess()) { auto castedOperation = AsyncOperation::Get<AccessCheckAsyncOperation>(operation); this->FinishAccessCheck(operation, castedOperation->request_, roleClaims); } else { operation->TryComplete(operation, error); } } void HttpClaimsAuthHandler::FinishAccessCheck( AsyncOperationSPtr const & operation, IRequestMessageContext & requestContext, SecuritySettings::RoleClaims & roleClaims) { if (!roleClaims.IsInRole(clientClaims_)) { WriteWarning( TraceType, "Client claims '{0}' given for uri {1} does not meet requirement '{2}'", roleClaims, requestContext.GetUrl(), clientClaims_); operation->TryComplete(operation, ErrorCodeValue::InvalidCredentials); return; } if (roleClaims.IsInRole(adminClientClaims_)) { role_ = RoleMask::Admin; WriteInfo( TraceType, "client claims '{0}' given for uri {1} meets Admin role requirements '{2}'", roleClaims, requestContext.GetUrl(), adminClientClaims_); } else { role_ = RoleMask::User; WriteInfo( TraceType, "client claims '{0}' given for uri {1} meets User role requirements '{2}'", roleClaims, requestContext.GetUrl(), clientClaims_); } operation->TryComplete(operation, ErrorCodeValue::Success); } void HttpClaimsAuthHandler::LoadIsAadServiceEnabled() { isAadServiceEnabled_ = AzureActiveDirectory::ServerWrapper::IsAadServiceEnabled(); }
30.09607
138
0.661056
AnthonyM
e1d594e590a8d19c7b53c3c57a47e9189430a27d
32,943
cpp
C++
src/wlen.cpp
puckbee/RePlAce
67f505f8a858b8da430bbdc1debc264020edf8f2
[ "BSD-3-Clause" ]
null
null
null
src/wlen.cpp
puckbee/RePlAce
67f505f8a858b8da430bbdc1debc264020edf8f2
[ "BSD-3-Clause" ]
null
null
null
src/wlen.cpp
puckbee/RePlAce
67f505f8a858b8da430bbdc1debc264020edf8f2
[ "BSD-3-Clause" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // Authors: Ilgweon Kang and Lutong Wang // (respective Ph.D. advisors: Chung-Kuan Cheng, Andrew B. Kahng), // based on Dr. Jingwei Lu with ePlace and ePlace-MS // // Many subsequent improvements were made by Mingyu Woo // leading up to the initial release. // // BSD 3-Clause License // // Copyright (c) 2018, The Regents of the University of California // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /////////////////////////////////////////////////////////////////////////////// #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <iomanip> #include <omp.h> #include "global.h" #include "macro.h" #include "mkl.h" #include "opt.h" #include "wlen.h" #include "lefdefIO.h" int wcof_flg; int MAX_EXP; int NEG_MAX_EXP; prec hpwl_mGP3D; prec hpwl_mGP2D; prec hpwl_cGP3D; prec hpwl_cGP2D; prec TSV_WEIGHT; FPOS wcof00; FPOS wcof00_dim1; FPOS wcof00_org; FPOS total_hpwl; FPOS total_stnwl; // lutong FPOS total_wlen; FPOS gp_wlen_weight; FPOS dp_wlen_weight; FPOS base_wcof; FPOS wlen_cof; FPOS wlen_cof_inv; EXP_ST *exp_st; void SetMAX_EXP_wlen() { MAX_EXP = 300; NEG_MAX_EXP = -300; } FPOS get_wlen_cof(prec ovf) { switch(wcof_flg) { case 1: return get_wlen_cof1(ovf); break; case 2: return get_wlen_cof2(ovf); break; default: return get_wlen_cof3(ovf); break; } } FPOS get_wlen_cof3(prec ovf) { FPOS cof; prec tmp = 0; if(ovf > 1.0) { cof.x = 1.0 / 10.0; cof.y = 1.0 / 10.0; } else if(ovf < 0.1) { cof.x = 1.0 / 0.01; cof.y = 1.0 / 0.01; } else { tmp = 1.0 / pow(10.0, (ovf - 0.1) * 10.0 / 3.0 - 2.0); cof.x = cof.y = tmp; } return cof; } FPOS get_wlen_cof1(prec ovf) { FPOS cof; if(ovf > 1.0) cof.x = cof.y = 1.0 / 10.0; else if(ovf < 0.1) cof.x = cof.y = 1.0 / 0.01; else cof.x = cof.y = 1.0 / pow(10.0, (ovf - 0.1) * 10.0 / 3.0 - 2.0); return cof; } FPOS get_wlen_cof2(prec ovf) { FPOS cof; prec tmp = 0.0; if(ovf > 1.0) { cof.x = 0.1; cof.y = 0.1; } else if(ovf < 0.1) { cof.x = 10.0; cof.y = 10.0; } else { tmp = 1.0 / pow(10.0, (ovf - 0.1) * 20 / 9.0 - 1.0); cof.x = cof.y = tmp; } return cof; } void wlen_init(void) { int i = 0 /* ,cnt=exp_st_cnt */; /* prec interval = exp_interval ; */ exp_st = (EXP_ST *)mkl_malloc(sizeof(EXP_ST) * exp_st_cnt, 64); for(i = 0; i < exp_st_cnt; i++) { exp_st[i].x = (prec)i * exp_interval - MAX_EXP; exp_st[i].val = exp(exp_st[i].x); if(i > 0) { exp_st[i - 1].y_h = (exp_st[i].val - exp_st[i - 1].val) / exp_interval; } } if(GP_DIM_ONE) { gp_wlen_weight.x = 1.0; gp_wlen_weight.y = place_backup.cnt.y / place_backup.cnt.x; // gp_wlen_weight.y = place.cnt.y / place.cnt.x; } else { gp_wlen_weight.x = gp_wlen_weight.y = 1.0; } dp_wlen_weight.x = 1.0; dp_wlen_weight.y = 1.0; } void wlen_init_mGP2D(void) { gp_wlen_weight.x = 1.0; gp_wlen_weight.y = 1.0; dp_wlen_weight.x = 1.0; dp_wlen_weight.y = 1.0; } void wlen_init_cGP2D(void) { gp_wlen_weight.x = 1.0; gp_wlen_weight.y = 1.0; dp_wlen_weight.x = 1.0; dp_wlen_weight.y = 1.0; } void wcof_init(FPOS bstp) { if(GP_DIM_ONE) wcof00 = wcof00_dim1; else wcof00 = wcof00_org; base_wcof.x = wcof00.x / (0.5 * (bstp.x + bstp.y)); base_wcof.y = wcof00.y / (0.5 * (bstp.x + bstp.y)); wlen_cof = fp_scal(0.1, base_wcof); wlen_cof_inv = fp_inv(wlen_cof); } prec get_wlen() { //////////////////////////// switch(WLEN_MODEL) { case WA: return get_wlen_wa(); break; case LSE: return get_wlen_lse(); break; } //////////////////////////// // return 0; } prec get_wlen_wa() { FPOS net_wlen; prec tot_wlen = 0; total_wlen.SetZero(); for(int i = 0; i < netCNT; i++) { net_wlen = get_net_wlen_wa(&netInstance[i]); total_wlen.x += net_wlen.x; total_wlen.y += net_wlen.y; } if(GP_DIM_ONE) { total_wlen.x *= place_backup.cnt.x * GP_SCAL; total_wlen.y *= place_backup.cnt.y * GP_SCAL; } tot_wlen = total_wlen.x + total_wlen.y; // + return tot_wlen; } prec get_wlen_lse(void) { NET *net = NULL; FPOS net_wlen; prec tot_wlen = 0; total_wlen.SetZero(); for(int i = 0; i < netCNT; i++) { net = &netInstance[i]; if(net->pinCNTinObject <= 1) continue; net_wlen = get_net_wlen_lse(net); total_wlen.x += net_wlen.x; total_wlen.y += net_wlen.y; } if(GP_DIM_ONE) { total_wlen.x *= wlen_cof_inv.x * place_backup.cnt.x * GP_SCAL; // * gp_wlen_weight.x + total_wlen.y *= wlen_cof_inv.y * place_backup.cnt.y * GP_SCAL; // * gp_wlen_weight.y + } tot_wlen = total_wlen.x + total_wlen.y; return tot_wlen; /* return */ /* total_wlen.x * wlen_cof_inv.x * gp_wlen_weight.x + */ /* total_wlen.y * wlen_cof_inv.y * gp_wlen_weight.y + */ } FPOS get_net_wlen_wa(NET *net) { FPOS net_wlen; FPOS sum_num1 = net->sum_num1; FPOS sum_num2 = net->sum_num2; FPOS sum_denom1 = net->sum_denom1; FPOS sum_denom2 = net->sum_denom2; if(net->pinCNTinObject <= 1) return zeroFPoint; net_wlen.x = sum_num1.x / sum_denom1.x - sum_num2.x / sum_denom2.x; net_wlen.y = sum_num1.y / sum_denom1.y - sum_num2.y / sum_denom2.y; return net_wlen; } FPOS get_net_wlen_lse(NET *net) { FPOS sum1, sum2; FPOS fp, wlen; PIN *pin = NULL; for(int i = 0; i < net->pinCNTinObject; i++) { pin = net->pin[i]; fp = pin->fp; sum1.x += get_exp(wlen_cof.x * fp.x); sum1.y += get_exp(wlen_cof.y * fp.y); sum2.x += get_exp(-1.0 * wlen_cof.x * fp.x); sum2.y += get_exp(-1.0 * wlen_cof.y * fp.y); } wlen.x = log(sum1.x) + log(sum2.x); wlen.y = log(sum1.y) + log(sum2.y); return wlen; } // // this only calculate HPWL based on the stored value in NET's ure prec GetHpwl() { total_hpwl.SetZero(); total_stnwl.SetZero(); for(int i = 0; i < netCNT; i++) { NET *curNet = &netInstance[i]; if(curNet->pinCNTinObject <= 1) continue; total_hpwl.x += curNet->max_x - curNet->min_x; total_hpwl.y += curNet->max_y - curNet->min_y; //// lutong // total_stnwl.x += curNet->stn_cof * (curNet->max_x - curNet->min_x) ; // total_stnwl.y += curNet->stn_cof * (curNet->max_y - curNet->min_y) ; // if(GP_DIM_ONE) // { // if(curNet->max_x - curNet->min_x > 1.0 / GP_SCAL * 1.1 || // curNet->max_x - curNet->min_x > 1.0 / GP_SCAL * 1.1 || // curNet->max_x - curNet->min_x > 1.0 / GP_SCAL * 1.1 ) // { // g_rrr ++; // } // } } if(GP_DIM_ONE) { total_hpwl.x *= place_backup.cnt.x * GP_SCAL; total_hpwl.y *= place_backup.cnt.y * GP_SCAL; } return total_hpwl.x + total_hpwl.y; // total_hpwl_xyz = // total_hpwl.x + // total_hpwl.y; // return total_hpwl_xyz; } // // this calculate current NET's informations (min_xyz/max_xyz) & calculate HPWL // simultaneously prec UpdateNetAndGetHpwl() { FPOS pof, fp; total_hpwl.SetZero(); for(int i = 0; i < netCNT; i++) { NET *curNet = &netInstance[i]; curNet->min_x = curNet->terminalMin.x; curNet->min_y = curNet->terminalMin.y; curNet->max_x = curNet->terminalMax.x; curNet->max_y = curNet->terminalMax.y; // update min_xyz, max_xyz in NET's info for(int j = 0; j < curNet->pinCNTinObject; j++) { PIN *pin = curNet->pin[j]; // only for modules if(pin->term) { continue; } MODULE *curModule = &moduleInstance[pin->moduleID]; pin->fp.SetAdd(curModule->center, curModule->pof[pin->pinIDinModule]); // pof = curModule->pof[pin->pinIDinModule]; // center = curModule->center; // fp.x = center.x + pof.x; // fp.y = center.y + pof.y; // pin->fp = fp; curNet->min_x = min(curNet->min_x, pin->fp.x); curNet->min_y = min(curNet->min_y, pin->fp.y); curNet->max_x = max(curNet->max_x, pin->fp.x); curNet->max_y = max(curNet->max_y, pin->fp.y); } if(curNet->pinCNTinObject <= 1) { continue; } // calculate HPWL total_hpwl.x += curNet->max_x - curNet->min_x; total_hpwl.y += curNet->max_y - curNet->min_y; } return total_hpwl.x + total_hpwl.y; // total_hpwl_xyz = total_hpwl.x + total_hpwl.y + total_hpwl.z; // return total_hpwl_xyz; } void wlen_grad2(int cell_idx, FPOS *grad2) { switch(WLEN_MODEL) { case LSE: wlen_grad2_lse(cell_idx, grad2); break; case WA: wlen_grad2_wa(grad2); break; } return; } void wlen_grad(int cell_idx, FPOS *grad) { grad->SetZero(); #ifdef NO_WLEN return; #endif switch(WLEN_MODEL) { case LSE: wlen_grad_lse(cell_idx, grad); break; case WA: wlen_grad_wa(cell_idx, grad); break; } grad->x *= -1.0 * gp_wlen_weight.x; grad->y *= -1.0 * gp_wlen_weight.y; } void wlen_grad2_wa(FPOS *grad) { grad->x = 1.0; grad->y = 1.0; return; } void wlen_grad2_lse(int cell_idx, FPOS *grad2) { FPOS net_grad2; CELL *cell = &gcell_st[cell_idx]; NET *net = NULL; PIN *pin = NULL; grad2->SetZero(); for(int i = 0; i < cell->pinCNTinObject; i++) { pin = cell->pin[i]; net = &netInstance[pin->netID]; if(net->pinCNTinObject <= 1) continue; get_net_wlen_grad2_lse(net, pin, &net_grad2); grad2->x += net_grad2.x; grad2->y += net_grad2.y; } } void wlen_grad_lse(int cell_idx, FPOS *grad) { FPOS net_grad = zeroFPoint; CELL *cell = &gcell_st[cell_idx]; NET *net = NULL; PIN *pin = NULL; grad->SetZero(); for(int i = 0; i < cell->pinCNTinObject; i++) { pin = cell->pin[i]; net = &netInstance[pin->netID]; if(net->pinCNTinObject <= 1) continue; get_net_wlen_grad_lse(net, pin, &net_grad); grad->x += net_grad.x; grad->y += net_grad.y; } } /* void wlen_grad_debug ( FPOS grad) { if(! ( grad.x >-10000000.0 && grad.x < 10000000.0 ) ) { g_rrr ++ ; } if(! ( grad.y >-10000000.0 && grad.y < 10000000.0 ) ) { g_rrr ++ ; } if(flg_3dic) { if(! ( grad.z >-10000000.0 && grad.z < 10000000.0 ) ) { g_rrr ++ ; } } } */ void wlen_grad_wa(int cell_idx, FPOS *grad) { CELL *cell = &gcell_st[cell_idx]; PIN *pin = NULL; NET *net = NULL; FPOS net_grad = zeroFPoint; grad->SetZero(); for(int i = 0; i < cell->pinCNTinObject; i++) { pin = cell->pin[i]; net = &netInstance[pin->netID]; if(net->pinCNTinObject <= 1) continue; get_net_wlen_grad_wa(pin->fp, net, pin, &net_grad); float curWeight = netInstance[pin->netID].timingWeight; // Timing Control Parts if(isTiming && curWeight > 0) { curWeight = netWeightBase + min(max(0.0f, netWeightBound - netWeightBase), curWeight / netWeightScale); // cout << "calNetWeight: " << curWeight << endl; if(hasNetWeight) { net_grad.x *= netWeight; net_grad.y *= netWeight; } else { net_grad.x *= curWeight; net_grad.y *= curWeight; } } grad->x += net_grad.x; grad->y += net_grad.y; } } void get_net_wlen_grad2_lse(NET *net, PIN *pin, FPOS *grad2) { POS flg1 = pin->flg1, flg2 = pin->flg2; FPOS e1 = pin->e1, e2 = pin->e2; FPOS grad2_1 = zeroFPoint, grad2_2 = zeroFPoint; FPOS sum_denom1 = net->sum_denom1; FPOS sum_denom2 = net->sum_denom2; if(flg1.x) { grad2_1.x = (e1.x) * (sum_denom1.x - e1.x) / (sum_denom1.x * sum_denom1.x); } if(flg2.x) { grad2_2.x = (e2.x) * (sum_denom2.x - e2.x) / (sum_denom2.x * sum_denom2.x); } grad2->x = grad2_1.x + grad2_2.x; if(flg1.y) { grad2_1.y = (e1.y) * (sum_denom1.y - e1.y) / (sum_denom1.y * sum_denom1.y); } if(flg2.y) { grad2_2.y = (e2.y) * (sum_denom2.y - e2.y) / (sum_denom2.y * sum_denom2.y); } grad2->y = grad2_1.y + grad2_2.y; return; } void get_net_wlen_grad_lse(NET *net, PIN *pin, FPOS *grad) { POS flg1 = pin->flg1, flg2 = pin->flg2; FPOS grad1 = zeroFPoint, grad2 = zeroFPoint; FPOS e1 = pin->e1, e2 = pin->e2; FPOS sum_denom1 = net->sum_denom1; FPOS sum_denom2 = net->sum_denom2; if(flg1.x) { grad1.x = e1.x / sum_denom1.x; } if(flg2.x) { grad2.x = e2.x / sum_denom2.x; } grad->x = grad1.x - grad2.x; if(flg1.y) { grad1.y = e1.y / sum_denom1.y; } if(flg2.y) { grad2.y = e2.y / sum_denom2.y; } grad->y = grad1.y - grad2.y; return; } // wlen_cof // obj? // void get_net_wlen_grad_wa(FPOS obj, NET *net, PIN *pin, FPOS *grad) { FPOS grad_sum_num1 = zeroFPoint, grad_sum_num2 = zeroFPoint; FPOS grad_sum_denom1 = zeroFPoint, grad_sum_denom2 = zeroFPoint; FPOS grad1 = zeroFPoint; FPOS grad2 = zeroFPoint; FPOS e1 = pin->e1; FPOS e2 = pin->e2; POS flg1 = pin->flg1; POS flg2 = pin->flg2; FPOS sum_num1 = net->sum_num1; FPOS sum_num2 = net->sum_num2; FPOS sum_denom1 = net->sum_denom1; FPOS sum_denom2 = net->sum_denom2; if(flg1.x) { grad_sum_denom1.x = wlen_cof.x * e1.x; grad_sum_num1.x = e1.x + obj.x * grad_sum_denom1.x; grad1.x = (grad_sum_num1.x * sum_denom1.x - grad_sum_denom1.x * sum_num1.x) / (sum_denom1.x * sum_denom1.x); } if(flg1.y) { grad_sum_denom1.y = wlen_cof.y * e1.y; grad_sum_num1.y = e1.y + obj.y * grad_sum_denom1.y; grad1.y = (grad_sum_num1.y * sum_denom1.y - grad_sum_denom1.y * sum_num1.y) / (sum_denom1.y * sum_denom1.y); } if(flg2.x) { grad_sum_denom2.x = wlen_cof.x * e2.x; grad_sum_num2.x = e2.x - obj.x * grad_sum_denom2.x; grad2.x = (grad_sum_num2.x * sum_denom2.x + grad_sum_denom2.x * sum_num2.x) / (sum_denom2.x * sum_denom2.x); } if(flg2.y) { grad_sum_denom2.y = wlen_cof.y * e2.y; grad_sum_num2.y = e2.y - obj.y * grad_sum_denom2.y; grad2.y = (grad_sum_num2.y * sum_denom2.y + grad_sum_denom2.y * sum_num2.y) / (sum_denom2.y * sum_denom2.y); } grad->x = grad1.x - grad2.x; grad->y = grad1.y - grad2.y; } void net_update_init(void) { for(int i = 0; i < netCNT; i++) { NET *net = &netInstance[i]; net->terminalMin.Set(place.end); net->terminalMax.Set(place.org); bool first_term = true; for(int j = 0; j < net->pinCNTinObject; j++) { PIN *pin = net->pin[j]; if(pin->term) { if(first_term) { first_term = false; // net->terminalMin.x = pin->fp.x; // net->terminalMin.y = pin->fp.y; // net->terminalMin.z = pin->fp.z; net->terminalMin.Set(pin->fp); // net->terminalMax.x = pin->fp.x; // net->terminalMax.y = pin->fp.y; // net->terminalMax.z = pin->fp.z; net->terminalMax.Set(pin->fp); } else { // net->terminalMin.x = min // (net->terminalMin.x, pin->fp.x); // net->terminalMin.y = min // (net->terminalMin.y, pin->fp.y); // net->terminalMin.z = min // (net->terminalMin.z, pin->fp.z); net->terminalMin.Min(pin->fp); // net->terminalMax.x = max // (net->terminalMax.x, pin->fp.x); // net->terminalMax.y = max // (net->terminalMax.y, pin->fp.y); // net->terminalMax.z = max // (net->terminalMax.z, pin->fp.z); net->terminalMax.Max(pin->fp); } } } } } void net_update(FPOS *st) { switch(WLEN_MODEL) { case LSE: return net_update_lse(st); break; case WA: return net_update_wa(st); break; } } void net_update_lse(FPOS *st) { int i = 0, j = 0; CELL *cell = NULL; NET *net = NULL; PIN *pin = NULL; MODULE *curModule = NULL; FPOS fp = zeroFPoint, pof = zeroFPoint, center = zeroFPoint; FPOS sum_denom1, sum_denom2; prec exp_val = 0; prec min_x = 0, min_y = 0; prec max_x = 0, max_y = 0; prec exp_min_x = 0, exp_min_y = 0; prec exp_max_x = 0, exp_max_y = 0; for(i = 0; i < gcell_cnt; i++) { cell = &gcell_st[i]; cell->center = st[i]; cell->den_pmin.x = cell->center.x - cell->half_den_size.x; cell->den_pmin.y = cell->center.y - cell->half_den_size.y; // cell->den_pmin.z = cell->center.z - cell->half_den_size.z; cell->den_pmax.x = cell->center.x + cell->half_den_size.x; cell->den_pmax.y = cell->center.y + cell->half_den_size.y; // cell->den_pmax.z = cell->center.z + cell->half_den_size.z; } for(i = 0; i < netCNT; i++) { net = &netInstance[i]; net->min_x = net->terminalMin.x; net->min_y = net->terminalMin.y; // net->min_z = net->terminalMin.z; net->max_x = net->terminalMax.x; net->max_y = net->terminalMax.y; // net->max_z = net->terminalMax.z; for(j = 0; j < net->pinCNTinObject; j++) { pin = net->pin[j]; if(!pin->term) { curModule = &moduleInstance[pin->moduleID]; pof = curModule->pof[pin->pinIDinModule]; center = st[pin->moduleID]; fp.x = center.x + pof.x; fp.y = center.y + pof.y; // fp.z = center.z + pof.z ; pin->fp = fp; net->min_x = min(net->min_x, fp.x); net->min_y = min(net->min_y, fp.y); // net->min_z = min ( net->min_z , fp.z ) ; net->max_x = max(net->max_x, fp.x); net->max_y = max(net->max_y, fp.y); // net->max_z = max ( net->max_z , fp.z ) ; } else { continue; } } min_x = net->min_x; min_y = net->min_y; // min_z = net->min_z ; max_x = net->max_x; max_y = net->max_y; // max_z = net->max_z; sum_denom1 = zeroFPoint; sum_denom2 = zeroFPoint; for(j = 0; j < net->pinCNTinObject; j++) { pin = net->pin[j]; if(!pin->term) { #ifdef CELL_CENTER_WLEN_GRAD fp = st[pin->moduleID]; #else fp = pin->fp; #endif } else { fp = pin->fp; } exp_max_x = (fp.x - max_x) * wlen_cof.x; if(fabs(exp_max_x) < MAX_EXP) { exp_val = get_exp(exp_max_x); sum_denom1.x += exp_val; pin->flg1.x = 1; pin->e1.x = exp_val; } else { exp_val = 0; pin->flg1.x = 0; } exp_min_x = (min_x - fp.x) * wlen_cof.x; if(fabs(exp_min_x) < MAX_EXP) { exp_val = get_exp(exp_min_x); sum_denom2.x += exp_val; pin->flg2.x = 1; pin->e2.x = exp_val; } else { pin->flg2.x = 0; } exp_max_y = (fp.y - max_y) * wlen_cof.y; if(fabs(exp_max_y) < MAX_EXP) { exp_val = get_exp(exp_max_y); sum_denom1.y += exp_val; pin->flg1.y = 1; pin->e1.y = exp_val; } else { pin->flg1.y = 0; } exp_min_y = (min_y - fp.y) * wlen_cof.y; if(fabs(exp_min_y) < MAX_EXP) { exp_val = get_exp(exp_min_y); sum_denom2.y += exp_val; pin->flg2.y = 1; pin->e2.y = exp_val; } else { pin->flg2.y = 0; } // exp_max_z = ( fp.z - max_z ) * wlen_cof.z; // if( fabs(exp_max_z) < MAX_EXP ) // { // exp_val = get_exp ( exp_max_z ) ; // sum_denom1.z += exp_val ; // pin->flg1.z = 1; // pin->e1.z = exp_val ; // } // else // { // pin->flg1.z = 0 ; // } // exp_min_z = ( min_z - fp.z ) * wlen_cof.z; // if( fabs(exp_min_z) < MAX_EXP ) // { // exp_val = get_exp ( exp_min_z ) ; // sum_denom2.z += exp_val ; // pin->flg2.z = 1 ; // pin->e2.z = exp_val ; // } // else // { // pin->flg2.z = 0 ; // } } // net->sum_num1 = sum_num1 ; // net->sum_num2 = sum_num2 ; net->sum_denom1 = sum_denom1; net->sum_denom2 = sum_denom2; } } prec net_update_hpwl_mac(void) { int i = 0, j = 0; prec hpwl = 0; NET *net = NULL; PIN *pin = NULL; MODULE *curModule = NULL; FPOS fp = zeroFPoint, pof = zeroFPoint, p0 = zeroFPoint; total_hpwl = zeroFPoint; for(i = 0; i < netCNT; i++) { net = &netInstance[i]; net->min_x = net->terminalMin.x; net->min_y = net->terminalMin.y; net->max_x = net->terminalMax.x; net->max_y = net->terminalMax.y; for(j = 0; j < net->pinCNTinObject; j++) { pin = net->pin[j]; if(!pin->term) { curModule = &moduleInstance[pin->moduleID]; // cell = & gcell_st [pin->moduleID]; p0 = curModule->center; pof = curModule->pof[pin->pinIDinModule]; fp.x = p0.x + pof.x; fp.y = p0.y + pof.y; pin->fp = fp; net->min_x = min(net->min_x, fp.x); net->min_y = min(net->min_y, fp.y); net->max_x = max(net->max_x, fp.x); net->max_y = max(net->max_y, fp.y); } } if(net->pinCNTinObject <= 1) continue; total_hpwl.x += (net->max_x - net->min_x); total_hpwl.y += (net->max_y - net->min_y); } /* total_hpwl_xy = total_hpwl.x + total_hpwl.y; */ // total_hpwl_xyz = total_hpwl.x + total_hpwl.y + total_hpwl.z; hpwl = total_hpwl.x * dp_wlen_weight.x + total_hpwl.y * dp_wlen_weight.y; return hpwl; } void net_update_wa(FPOS *st) { int i = 0; bool timeon = false; double time = 0.0f; if(timeon) time_start(&time); omp_set_num_threads(numThread); #pragma omp parallel default(none) shared(gcell_cnt, gcell_st, st) private(i) { // CELL* cell = NULL; #pragma omp for for(i = 0; i < gcell_cnt; i++) { CELL *cell = &gcell_st[i]; cell->center = st[i]; cell->den_pmin.x = cell->center.x - cell->half_den_size.x; cell->den_pmin.y = cell->center.y - cell->half_den_size.y; cell->den_pmax.x = cell->center.x + cell->half_den_size.x; cell->den_pmax.y = cell->center.y + cell->half_den_size.y; } } if(timeon) { time_end(&time); cout << "parallelTime : " << time << endl; }; #pragma omp parallel default(none) shared( \ netInstance, moduleInstance, st, netCNT, NEG_MAX_EXP, wlen_cof) private(i) { // NET *net = NULL; // PIN *pin = NULL; // MODULE *curModule = NULL; // prec exp_min_x = 0, exp_min_y = 0; // prec exp_max_x = 0, exp_max_y = 0; // prec min_x = 0, min_y = 0; // prec max_x = 0, max_y = 0; // FPOS fp, pof, center; // FPOS sum_num1, sum_num2, sum_denom1, sum_denom2; #pragma omp for for(i = 0; i < netCNT; i++) { NET *net = &netInstance[i]; net->min_x = net->terminalMin.x; net->min_y = net->terminalMin.y; net->max_x = net->terminalMax.x; net->max_y = net->terminalMax.y; // cout << "size: " << sizeof(PIN) << endl; // cout << net->pinCNTinObject << endl; for(int j = 0; j < net->pinCNTinObject; j++) { PIN *pin = net->pin[j]; // cout << j << " " << pin << endl; if(!pin->term) { MODULE *curModule = &moduleInstance[pin->moduleID]; FPOS pof = curModule->pof[pin->pinIDinModule]; FPOS center = st[pin->moduleID]; FPOS fp; fp.x = center.x + pof.x; fp.y = center.y + pof.y; pin->fp = fp; net->min_x = min(net->min_x, fp.x); net->min_y = min(net->min_y, fp.y); net->max_x = max(net->max_x, fp.x); net->max_y = max(net->max_y, fp.y); } else { continue; } } // if( i >=2 ) // exit(1); prec min_x = net->min_x; prec min_y = net->min_y; prec max_x = net->max_x; prec max_y = net->max_y; FPOS sum_num1, sum_num2; FPOS sum_denom1, sum_denom2; // sum_num1.x = sum_num1.y = sum_num2.x = sum_num2.y = 0; // sum_denom1.x = sum_denom1.y = sum_denom2.x = sum_denom2.y = 0; // UPDATE // pin->e1 (MAX) // net->sum_num1 (MAX) // net->sum_denom1 (MAX) // pin->flg1 (MAX) // // pin->e2 (MIN) // net->sum_num2 (MIN) // net->sum_denom2 (MIN) // pin->flg2 (MIN) // for(int j = 0; j < net->pinCNTinObject; j++) { PIN *pin = net->pin[j]; FPOS fp = pin->fp; prec exp_max_x = (fp.x - max_x) * wlen_cof.x; prec exp_min_x = (min_x - fp.x) * wlen_cof.x; prec exp_max_y = (fp.y - max_y) * wlen_cof.y; prec exp_min_y = (min_y - fp.y) * wlen_cof.y; if(exp_max_x > NEG_MAX_EXP) { pin->e1.x = get_exp(exp_max_x); sum_num1.x += fp.x * pin->e1.x; sum_denom1.x += pin->e1.x; pin->flg1.x = 1; } else { pin->flg1.x = 0; } if(exp_min_x > NEG_MAX_EXP) { pin->e2.x = get_exp(exp_min_x); sum_num2.x += fp.x * pin->e2.x; sum_denom2.x += pin->e2.x; pin->flg2.x = 1; } else { pin->flg2.x = 0; } if(exp_max_y > NEG_MAX_EXP) { pin->e1.y = get_exp(exp_max_y); sum_num1.y += fp.y * pin->e1.y; sum_denom1.y += pin->e1.y; pin->flg1.y = 1; } else { pin->flg1.y = 0; } if(exp_min_y > NEG_MAX_EXP) { pin->e2.y = get_exp(exp_min_y); sum_num2.y += fp.y * pin->e2.y; sum_denom2.y += pin->e2.y; pin->flg2.y = 1; } else { pin->flg2.y = 0; } } net->sum_num1 = sum_num1; net->sum_num2 = sum_num2; net->sum_denom1 = sum_denom1; net->sum_denom2 = sum_denom2; } } } prec get_mac_hpwl(int idx) { MODULE *mac = macro_st[idx]; PIN *pin = NULL; NET *net = NULL; int i = 0, j = 0; int moduleID = mac->idx; CELL *cell = &gcell_st[moduleID]; FPOS fp = zeroFPoint; mac_hpwl = zeroFPoint; mac_hpwl_xyz = 0; for(i = 0; i < cell->pinCNTinObject; i++) { pin = cell->pin[i]; net = &netInstance[pin->netID]; net->min_x = net->terminalMin.x; net->min_y = net->terminalMin.y; net->max_x = net->terminalMax.x; net->max_y = net->terminalMax.y; for(j = 0; j < net->pinCNTinObject; j++) { fp = net->pin[j]->fp; net->min_x = min(net->min_x, fp.x); net->min_y = min(net->min_y, fp.y); net->max_x = max(net->max_x, fp.x); net->max_y = max(net->max_y, fp.y); } if(net->pinCNTinObject <= 1) continue; mac_hpwl.x += (net->max_x - net->min_x); mac_hpwl.y += (net->max_y - net->min_y); } mac_hpwl_xyz = mac_hpwl.x * dp_wlen_weight.x + mac_hpwl.y * dp_wlen_weight.y; return mac_hpwl_xyz; } // update net->pin2->fp as updated version (modules' center + modules' offset) void update_pin2(void) { // cout << "called update_pin2" << endl; for(int i = 0; i < netCNT; i++) { NET *net = &netInstance[i]; // cout << net->pinCNTinObject2 << endl; for(int j = 0; j < net->pinCNTinObject2; j++) { PIN *pin = net->pin2[j]; // if pin is terminal pin, then skip this procedure. if(pin->term) { continue; } MODULE *curModule = &moduleInstance[pin->moduleID]; pin->fp.SetAdd(curModule->center, curModule->pof[pin->pinIDinModule]); // if( i == 0 ) { // cout << j << endl; // curModule->center.Dump("curModule->center"); // curModule->pof[pin->pinIDinModule].Dump("pof"); // pin->fp.Dump("Added pin->fp"); // } // original code // FPOS pof = curModule->pof[pin->pinIDinModule]; // FPOS center = curModule->center; // fp = pin->fp; // fp.x = center.x + pof.x; // fp.y = center.y + pof.y; // fp.z = center.z + pof.z; // pin->fp = fp; } } } prec get_modu_hpwl(void) { int i = 0, j = 0; NET *net = NULL; FPOS fp; PIN *pin = NULL; tot_HPWL = tx_HPWL = ty_HPWL = tz_HPWL = 0; for(i = 0; i < netCNT; i++) { net = &netInstance[i]; net->min_x = net->terminalMin.x; net->min_y = net->terminalMin.y; // net->min_z = net->terminalMin.z; net->max_x = net->terminalMax.x; net->max_y = net->terminalMax.y; // net->max_z = net->terminalMax.z; for(j = 0; j < net->pinCNTinObject2; j++) { pin = net->pin2[j]; if(!pin->term) { fp = pin->fp; net->min_x = min(net->min_x, fp.x); net->min_y = min(net->min_y, fp.y); // net->min_z = min ( net->min_z , fp.z ) ; net->max_x = max(net->max_x, fp.x); net->max_y = max(net->max_y, fp.y); // net->max_z = max ( net->max_z , fp.z ) ; } } if(net->pinCNTinObject2 <= 1) continue; tx_HPWL += net->max_x - net->min_x; ty_HPWL += net->max_y - net->min_y; // tz_HPWL += net->max_z - net->min_z; } tot_HPWL = tx_HPWL + ty_HPWL; // + tz_HPWL; return tot_HPWL; } int HPWL_count() { NET *curNet = NULL; tot_HPWL = 0; tx_HPWL = 0; ty_HPWL = 0; for(int i = 0; i < netCNT; i++) { curNet = &netInstance[i]; tx_HPWL += (curNet->max_x - curNet->min_x); ty_HPWL += (curNet->max_y - curNet->min_y); if(curNet->max_x - curNet->min_x < 0) { cout << "NEGATIVE HPWL ERROR! " << curNet->Name() << " " << curNet->max_x << " " << curNet->min_x << endl; } if(curNet->max_y - curNet->min_y < 0) { cout << "NEGATIVE HPWL ERROR! " << curNet->Name() << " " << curNet->max_y << " " << curNet->min_y << endl; } if(tx_HPWL < 0 || ty_HPWL < 0) { printf("NEGATIVE HPWL ERROR! \n"); cout << curNet->Name() << tx_HPWL << " " << ty_HPWL << endl; exit(1); } } // exit(0); tot_HPWL = tx_HPWL + ty_HPWL; return 0; } // Get HPWL as micron units pair<double, double> GetUnscaledHpwl() { double x = 0.0f, y = 0.0f; NET *curNet = NULL; for(int i = 0; i < netCNT; i++) { curNet = &netInstance[i]; x += (curNet->max_x - curNet->min_x) * GetUnitX() / GetDefDbu(); y += (curNet->max_y - curNet->min_y) * GetUnitY() / GetDefDbu(); if(curNet->max_x - curNet->min_x < 0) { cout << "NEGATIVE HPWL ERROR! " << curNet->Name() << " " << curNet->max_x << " " << curNet->min_x << endl; } if(curNet->max_y - curNet->min_y < 0) { cout << "NEGATIVE HPWL ERROR! " << curNet->Name() << " " << curNet->max_y << " " << curNet->min_y << endl; } if(x < 0 || y < 0) { printf("NEGATIVE HPWL ERROR! \n"); cout << curNet->Name() << tx_HPWL << " " << ty_HPWL << endl; exit(1); } } return make_pair(x, y); } void PrintUnscaledHpwl(string mode) { pair<double, double> hpwl = GetUnscaledHpwl(); cout << "===HPWL(MICRON)====================================" << endl; cout << " Mode : " << mode << endl; cout << " HPWL : " << std::fixed << std::setprecision(4) << hpwl.first + hpwl.second << endl << " x= " << hpwl.first << " y= " << hpwl.second << endl; cout << "===================================================" << endl; }
25.340769
80
0.545913
puckbee
e1db06e0073a76ded2df969d0ae484384256b12c
3,811
hh
C++
src/heap.hh
MikolasJanota/minibones
5413f7a10e410fd88cbac53fb79c8df40cbde650
[ "MIT" ]
2
2019-06-03T08:19:50.000Z
2019-09-20T03:10:23.000Z
src/heap.hh
MikolasJanota/minibones
5413f7a10e410fd88cbac53fb79c8df40cbde650
[ "MIT" ]
null
null
null
src/heap.hh
MikolasJanota/minibones
5413f7a10e410fd88cbac53fb79c8df40cbde650
[ "MIT" ]
null
null
null
//jpms:bc /*----------------------------------------------------------------------------*\ * File: heap.hh * * Description: Abstract heap, with extended priority queue interface. * * Author: jpms * * Copyright (c) 2010, Joao Marques-Silva \*----------------------------------------------------------------------------*/ //jpms:ec #ifndef _HEAP_H #define _HEAP_H 1 #include <vector> using namespace std; #define fixindex(i) _heap[i]->index() = i; //jpms:bc /*----------------------------------------------------------------------------*\ * Class: Abstract heap, with extended priority queue interface. * * Purpose: To be used in standard heap/priority queue apps. \*----------------------------------------------------------------------------*/ //jpms:ec template <typename T, typename U> class heap { public: heap(vector<T>& ref) { _heap.resize(ref.size()); copy(ref.begin(), ref.end(), _heap.begin()); build_heap(); fixindexes(); } inline bool contains(T element) {return (element->index()>0) && (element->index()<=heap_size());} inline size_t size() { return heap_size(); } T maximum() { return _heap[1]; } // Return element 1; element 0 is *unused* T extract_max() { // Return element 1 and remove it from heap T tmax = _heap[1]; heap_swap(1,heap_size()); _heap.pop_back(); if (heap_size()>0) siftdown(1); return tmax; } void update_key(T elem, U nv) { U cv = _heap[elem->index()]->key(); if (cv > nv) { decrease_key(elem, nv); } else if (cv < nv) { increase_key(elem, nv); } } void increase_key(T elem, U nv) { elem->key() = nv; siftup(elem->index()); } void decrease_key(T elem, U nv) { elem->key() = nv; siftdown(elem->index()); } bool is_heap() { bool heapok = true; for(size_t i=heap_size()/2; i>=1; --i) { size_t l = left(i); size_t r = right(i); if (_heap[i]->key() < _heap[l]->key() || r <= heap_size() && _heap[i]->key() < _heap[r]->key()) { heapok = false; break; } } return heapok; } void clear() { _heap.clear(); } public: void dump(ostream& outs=cout) { typename vector<T>::iterator hpos = _heap.begin(); typename vector<T>::iterator hend = _heap.end(); if (hpos != hend) { hpos++; } for (; hpos != hend; ++hpos) { outs << **hpos << " "; outs << endl; } } friend ostream & operator << (ostream& outs, heap<T,U>& h) { h.dump(outs); return outs; } protected: void build_heap() { for(size_t i=heap_size()/2; i>=1; --i) { siftdown(i); } } void siftdown(size_t i) { assert(i <= heap_size()); size_t l = left(i); size_t r = right(i); size_t largest = i; if (l <= heap_size() && _heap[l]->key() > _heap[i]->key()) { largest = l; } if (r <= heap_size() && _heap[r]->key() > _heap[largest]->key()) { largest = r; } if (largest != i) { heap_swap(i, largest); siftdown(largest); } } void siftup(size_t i) { size_t j = parent(i); while (j >= 1 && _heap[j]->key() < _heap[i]->key()) { heap_swap(i, j); i = j; j = parent(i); } assert(i>=1); } protected: inline size_t parent(size_t i) const { return i >> 1; } inline size_t left(size_t i) const { return i << 1; } inline size_t right(size_t i) const { return (i << 1) + 1; } inline size_t heap_size() const { return _heap.size() - 1; } inline void heap_swap(size_t i, size_t j) { T tmp = _heap[i]; _heap[i] = _heap[j]; _heap[j] = tmp; _heap[i]->index() = i; _heap[j]->index() = j; } void fixindexes() { for(size_t i=1; i<=heap_size(); ++i) { fixindex(i); } } protected: vector<T> _heap; }; #endif /* _HEAP_H */ /*----------------------------------------------------------------------------*/
26.282759
80
0.506429
MikolasJanota
e1df3f3d941011807b5e282621b5443e9f94eb99
2,035
hpp
C++
ysu/node/gap_cache.hpp
lik2129/ysu_coin
47e40ed5d4000fc59566099929bd08a9ae16a4c1
[ "BSD-3-Clause" ]
null
null
null
ysu/node/gap_cache.hpp
lik2129/ysu_coin
47e40ed5d4000fc59566099929bd08a9ae16a4c1
[ "BSD-3-Clause" ]
null
null
null
ysu/node/gap_cache.hpp
lik2129/ysu_coin
47e40ed5d4000fc59566099929bd08a9ae16a4c1
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <ysu/lib/numbers.hpp> #include <ysu/lib/utility.hpp> #include <ysu/secure/common.hpp> #include <boost/multi_index/hashed_index.hpp> #include <boost/multi_index/member.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/multi_index/sequenced_index.hpp> #include <boost/multi_index_container.hpp> #include <chrono> #include <memory> #include <mutex> #include <vector> namespace ysu { class node; class transaction; /** For each gap in account chains, track arrival time and voters */ class gap_information final { public: std::chrono::steady_clock::time_point arrival; ysu::block_hash hash; std::vector<ysu::account> voters; bool bootstrap_started{ false }; }; /** Maintains voting and arrival information for gaps (missing source or previous blocks in account chains) */ class gap_cache final { public: explicit gap_cache (ysu::node &); void add (ysu::block_hash const &, std::chrono::steady_clock::time_point = std::chrono::steady_clock::now ()); void erase (ysu::block_hash const & hash_a); void vote (std::shared_ptr<ysu::vote>); bool bootstrap_check (std::vector<ysu::account> const &, ysu::block_hash const &); void bootstrap_start (ysu::block_hash const & hash_a); ysu::uint128_t bootstrap_threshold (); size_t size (); // clang-format off class tag_arrival {}; class tag_hash {}; using ordered_gaps = boost::multi_index_container<ysu::gap_information, boost::multi_index::indexed_by< boost::multi_index::ordered_non_unique<boost::multi_index::tag<tag_arrival>, boost::multi_index::member<gap_information, std::chrono::steady_clock::time_point, &gap_information::arrival>>, boost::multi_index::hashed_unique<boost::multi_index::tag<tag_hash>, boost::multi_index::member<gap_information, ysu::block_hash, &gap_information::hash>>>>; ordered_gaps blocks; // clang-format on size_t const max = 256; std::mutex mutex; ysu::node & node; }; std::unique_ptr<container_info_component> collect_container_info (gap_cache & gap_cache, const std::string & name); }
32.301587
115
0.756757
lik2129
e1e2d7a518de5598a116be8da68ebd030db40f8b
1,953
cxx
C++
src/xyzzy/delta.cxx
gburdell/xyzzy
5b29d84c1684cfe0b0dfb9ceedb59f0d6f6cbb19
[ "MIT" ]
2
2015-08-01T10:20:43.000Z
2015-11-04T21:16:11.000Z
src/xyzzy/delta.cxx
gburdell/xyzzy
5b29d84c1684cfe0b0dfb9ceedb59f0d6f6cbb19
[ "MIT" ]
null
null
null
src/xyzzy/delta.cxx
gburdell/xyzzy
5b29d84c1684cfe0b0dfb9ceedb59f0d6f6cbb19
[ "MIT" ]
null
null
null
//The MIT License // //xyzzy - c++ library //Copyright (c) 2007-2010 Karl W. Pfalzer // //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 <list> #include <fstream> #include <iostream> #include "xyzzy/assert.hxx" #include "xyzzy/delta.hxx" namespace xyzzy { using namespace std; /*static*/ PTSlist<double> TDeltaDouble::m_stList; /*static*/ bool TDeltaDouble::m_stDoTrace = true; void TDeltaDouble::setTrace(bool on) { m_stDoTrace = on; } void TDeltaDouble::addDelta(double d) { //caller should check: if (m_stDoTrace) if (0 != d) m_stList.append(d); } void TDeltaDouble::dumpTrace(const char *fname) { if (false == m_stDoTrace) return; ofstream os(fname); ASSERT_TRUE(os.good()); cout << "Info: \"" << fname << "\": creating ..."; PTSlist<double>::Iterator iter(m_stList); for (int i = 0; iter.hasMore(); ++iter, i++) { os << i << " " << *iter << endl; } os.close(); cout << " done" << endl; } };
27.9
79
0.714798
gburdell
e1e35ef27eb8f700ba3a66f02588841948f5cedb
646
hpp
C++
test/rocksdb.hpp
sdulloor/cyclone
a4606bfb50fb8ce01e21f245624d2f4a98961039
[ "Apache-2.0" ]
7
2017-11-21T03:08:15.000Z
2019-02-13T08:05:37.000Z
test/rocksdb.hpp
IntelLabs/LogReplicationRocksDB
74f33e9a54f3ae820060230e28c42274696bf2f7
[ "Apache-2.0" ]
null
null
null
test/rocksdb.hpp
IntelLabs/LogReplicationRocksDB
74f33e9a54f3ae820060230e28c42274696bf2f7
[ "Apache-2.0" ]
3
2018-05-15T16:51:36.000Z
2021-05-08T07:41:33.000Z
#ifndef _ROCKSDB_COMMON_ #define _ROCKSDB_COMMON_ const unsigned long OP_PUT = 0; const unsigned long OP_GET = 1; const unsigned long OP_ADD = 2; const unsigned long value_sz = 8; typedef struct rock_kv_st{ unsigned long op; unsigned long key; char value[value_sz]; }rock_kv_t; typedef struct rock_kv_pair_st { unsigned long key; char value[value_sz]; }rock_kv_pair_t; const char *preload_dir = "/dev/shm/preloaded"; const char *data_dir = "/dev/shm/checkpoint"; const char *log_dir = "/mnt/ssd/logs"; const unsigned long rocks_keys = 100000000; const int use_flashlog = 1; const int use_rocksdbwal = 0; #endif
28.086957
47
0.732198
sdulloor
e1e786a6245d4c907c1f0890c8b0814268545ddd
23,157
cpp
C++
TimingAnalyzer/macros/TimeFitter.cpp
kmcdermo/Timing
f2f41e24350e14daf795f6551aa52a0687cda3f2
[ "MIT" ]
2
2017-10-19T12:28:53.000Z
2019-05-22T14:36:05.000Z
TimingAnalyzer/macros/TimeFitter.cpp
kmcdermo/Timing
f2f41e24350e14daf795f6551aa52a0687cda3f2
[ "MIT" ]
null
null
null
TimingAnalyzer/macros/TimeFitter.cpp
kmcdermo/Timing
f2f41e24350e14daf795f6551aa52a0687cda3f2
[ "MIT" ]
6
2017-09-13T13:16:10.000Z
2019-01-28T17:39:51.000Z
#include "TimeFitter.hh" #include "TVirtualFitter.h" TimeFitter::TimeFitter(const TString & infilename, const TString & plotconfig, const TString & miscconfig, const TString & timefitconfig, const TString & era, const Bool_t savemetadata, const TString & outfiletext) : fInFileName(infilename), fPlotConfig(plotconfig), fMiscConfig(miscconfig), fTimeFitConfig(timefitconfig), fEra(era), fSaveMetaData(savemetadata), fOutFileText(outfiletext) { std::cout << "Initializing TimeFitter..." << std::endl; //////////////// // // // Initialize // // // //////////////// // Get input file fInFile = TFile::Open(Form("%s",fInFileName.Data())); Common::CheckValidFile(fInFile,fInFileName); // set style fTDRStyle = new TStyle("TDRStyle","Style for P-TDR"); Common::SetTDRStyle(fTDRStyle); // output root file for quick inspection fOutFile = TFile::Open(Form("%s.root",fOutFileText.Data()),"UPDATE"); // setup config TimeFitter::SetupDefaults(); TimeFitter::SetupCommon(); TimeFitter::SetupPlotConfig(); TimeFitter::SetupMiscConfig(); TimeFitter::SetupTimeFitConfig(); // set fitter TVirtualFitter::SetDefaultFitter("Minuit2"); } TimeFitter::~TimeFitter() { std::cout << "Tidying up in destructor..." << std::endl; if (fSaveMetaData) delete fConfigPave; delete fOutFile; delete fTDRStyle; delete fInFile; } void TimeFitter::MakeTimeFits() { std::cout << "Making time fits..." << std::endl; // Do data first FitStruct DataInfo("Data",Common::HistNameMap["Data"].Data()); TimeFitter::MakeTimeFit(DataInfo); // Do MC bkgd first FitStruct MCInfo("MC",Common::BkgdHistName.Data()); TimeFitter::MakeTimeFit(MCInfo); // Fit sigma plot if asked if (fDoSigmaFit) { TimeFitter::MakeSigmaFit(DataInfo); TimeFitter::MakeSigmaFit(MCInfo); } // Make Plots TimeFitter::MakePlots(DataInfo,MCInfo); // MakeConfigPave if (fSaveMetaData) TimeFitter::MakeConfigPave(); // Dump mu's and sigma's into text file TimeFitter::DumpFitInfo(DataInfo,MCInfo); // Delete infos TimeFitter::DeleteInfo(DataInfo); TimeFitter::DeleteInfo(MCInfo); } void TimeFitter::MakeTimeFit(FitStruct & FitInfo) { const auto & label = FitInfo.label; std::cout << "Making time fits for: " << label.Data() << std::endl; // Get input hist TimeFitter::GetInputHist(FitInfo); // Init time fits TimeFitter::InitTimeFits(FitInfo); // Project out 2D hists into map TimeFitter::Project2Dto1DHists(FitInfo); // Fit each 1D hist TimeFitter::Fit1DHists(FitInfo); // Extract mu and sigma into maps TimeFitter::ExtractFitResults(FitInfo); } void TimeFitter::MakeSigmaFit(FitStruct & FitInfo) { const auto & label = FitInfo.label; std::cout << "Making sigma fit for: " << label.Data() << std::endl; // Prep sigma fit TimeFitter::PrepSigmaFit(FitInfo); // Fit sigma hist TimeFitter::FitSigmaHist(FitInfo); } void TimeFitter::MakePlots(FitStruct & DataInfo, FitStruct & MCInfo) { std::cout << "Make overlay plots..." << std::endl; // make temp vector of hist key names std::vector<TString> keys = {"mu","sigma"}; // can add chi2prob and chi2ndf // loop over keys for (const auto & key : keys) { // get hists const auto & DataHist = DataInfo.ResultsMap[key]; const auto & MCHist = MCInfo .ResultsMap[key]; // tmp max, min Float_t min = 1e9; Float_t max = -1e9; TimeFitter::GetMinMax(DataHist,min,max,key); TimeFitter::GetMinMax(MCHist ,min,max,key); // lin first, then log --> log disabled for now TimeFitter::PrintCanvas(DataInfo,MCInfo,min,max,key,false); if (key.EqualTo("sigma",TString::kExact)) TimeFitter::PrintCanvas(DataInfo,MCInfo,min,max,key,true); } } void TimeFitter::GetInputHist(FitStruct & FitInfo) { const auto & label = FitInfo.label; std::cout << "Getting input hist: " << label.Data() << std::endl; // get input const auto & inHistName = FitInfo.inHistName; auto & Hist2D = FitInfo.Hist2D; // get the hist Hist2D = (TH2F*)fInFile->Get(inHistName.Data()); // save to output Common::Write(fOutFile,Hist2D); } void TimeFitter::InitTimeFits(FitStruct & FitInfo) { const auto & label = FitInfo.label; std::cout << "Initializing TimeFitStructMap for: " << label.Data() << std::endl; // get inputs/outputs auto & TimeFitStructMap = FitInfo.TimeFitStructMap; // setup a time fit struct for each bin! for (auto ibinX = 1; ibinX <= fNBinsX; ibinX++) { TimeFitStructMap[ibinX] = new TimeFitStruct(fTimeFitType,fRangeLow,fRangeUp); } } void TimeFitter::Project2Dto1DHists(FitStruct & FitInfo) { const auto & label = FitInfo.label; std::cout << "Projecting to 1D from 2D plot: " << label.Data() << std::endl; // get inputs/outputs const auto & Hist2D = FitInfo.Hist2D; auto & TimeFitStructMap = FitInfo.TimeFitStructMap; const TString histname = Hist2D->GetName(); for (auto ibinX = 1; ibinX <= fNBinsX; ibinX++) { auto & hist = TimeFitStructMap[ibinX]->hist; hist = (TH1F*)Hist2D->ProjectionY(Form("%s_ibin%i",histname.Data(),ibinX),ibinX,ibinX); } } void TimeFitter::Fit1DHists(FitStruct & FitInfo) { const auto & label = FitInfo.label; std::cout << "Fitting hists for: " << label.Data() << std::endl; // get inputs/outputs auto & TimeFitStructMap = FitInfo.TimeFitStructMap; for (auto ibinX = 1; ibinX <= fNBinsX; ibinX++) { // get pair input auto & TimeFit = TimeFitStructMap[ibinX]; // get hist, and skip if no entries if (TimeFit->isEmpty()) continue; // Prep the fit TimeFit->PrepFit(); // do the fit! TimeFit->DoFit(); // save output Common::Write(fOutFile,TimeFit->hist); Common::Write(fOutFile,TimeFit->form); Common::Write(fOutFile,TimeFit->fit); } } void TimeFitter::ExtractFitResults(FitStruct & FitInfo) { const auto & label = FitInfo.label; std::cout << "Extracting results for: " << label.Data() << std::endl; // get inputs/outputs auto & TimeFitStructMap = FitInfo.TimeFitStructMap; auto & ResultsMap = FitInfo.ResultsMap; // setup hists ResultsMap["chi2ndf"] = TimeFitter::SetupHist("#chi^{2}/NDF","chi2ndf",label); ResultsMap["chi2prob"] = TimeFitter::SetupHist("#chi^{2} Prob.","chi2prob",label); ResultsMap["mu"] = TimeFitter::SetupHist(Form("#mu(%s) [ns]",fTimeText.Data()),"mu",label); ResultsMap["sigma"] = TimeFitter::SetupHist(Form("#sigma(%s) [ns]",fTimeText.Data()),"sigma",label); // set bin content! for (auto ibinX = 1; ibinX <= fNBinsX; ibinX++) { // get time fit auto & TimeFit = TimeFitStructMap[ibinX]; // skip if fit not present if (TimeFit->isEmpty()) continue; // get results TimeFit->GetFitResult(); const auto & result = TimeFit->result; // set bin content ResultsMap["chi2ndf"] ->SetBinContent(ibinX,result.chi2ndf); ResultsMap["chi2prob"]->SetBinContent(ibinX,result.chi2prob); ResultsMap["mu"] ->SetBinContent(ibinX,result.mu); ResultsMap["mu"] ->SetBinError (ibinX,result.emu); ResultsMap["sigma"] ->SetBinContent(ibinX,result.sigma); ResultsMap["sigma"] ->SetBinError (ibinX,result.esigma); } // save output Common::WriteMap(fOutFile,ResultsMap); } void TimeFitter::PrepSigmaFit(FitStruct & FitInfo) { const auto & label = FitInfo.label; std::cout << "Prepping sigma fit for: " << label.Data() << std::endl; // get input hist const auto & hist = FitInfo.ResultsMap["sigma"]; // get range const auto x_low = hist->GetXaxis()->GetBinLowEdge(hist->GetXaxis()->GetFirst()); const auto x_up = hist->GetXaxis()->GetBinUpEdge (hist->GetXaxis()->GetLast()); // set names const TString histname = hist->GetName(); const TString formname = histname+"_form"; const TString fitname = histname+"_fit"; // get and set formula auto & form = FitInfo.SigmaForm; form = new TFormula(formname.Data(),Form("sqrt((([0]*[0])/(x*x))+(%s[1]*[1]))",fUseSqrt2?"2*":"")); // get and set fit auto & fit = FitInfo.SigmaFit; fit = new TF1(fitname.Data(),form->GetName(),x_low,x_up); // init params fit->SetParName(0,"N"); fit->SetParameter(0,fSigmaInitN.val); fit->SetParLimits(0,fSigmaInitN.low,fSigmaInitN.up); fit->SetParName(1,"C"); fit->SetParameter(1,fSigmaInitC.val); fit->SetParLimits(1,fSigmaInitC.low,fSigmaInitC.up); // set line color fit->SetLineColor(hist->GetLineColor()); // save form Common::Write(fOutFile,form); } void TimeFitter::FitSigmaHist(FitStruct & FitInfo) { const auto & label = FitInfo.label; std::cout << "Fitting sigma hist for: " << label.Data() << std::endl; // get inputs/outputs auto & hist = FitInfo.ResultsMap["sigma"]; auto & fit = FitInfo.SigmaFit; // and fit it hist->Fit(fit->GetName(),"RBQ0"); // save to output Common::Write(fOutFile,fit); } void TimeFitter::PrintCanvas(FitStruct & DataInfo, FitStruct & MCInfo, Float_t min, Float_t max, const TString & key, const Bool_t isLogy) { std::cout << "Printing canvas for: " << key.Data() << " isLogy: " << Common::PrintBool(isLogy).Data() << std::endl; // do sigma fit? const Bool_t doSigmaFit = (fDoSigmaFit && (key.EqualTo("sigma",TString::kExact))); // get hists auto & DataHist = DataInfo.ResultsMap[key]; auto & MCHist = MCInfo .ResultsMap[key]; // get labels const auto & DataLabel = DataInfo.label; const auto & MCLabel = MCInfo .label; // make canvas first auto Canvas = new TCanvas("Canvas_"+key,""); Canvas->cd(); Canvas->SetGridx(); Canvas->SetGridy(); Canvas->SetLogy(isLogy); if (key.EqualTo("sigma",TString::kExact)) { min = (isLogy ? 0.07f : 0.f); max = 1.f; } else { const Float_t factor = (isLogy ? 3.f : 1.5f); min = (min > 0.f ? (min / factor) : (min * factor)); max = (max > 0.f ? (max * factor) : (max / factor)); if (key.EqualTo("mu",TString::kExact)) { if (min < -10.f) { min = -1.f; if (max < min) max = 0.f; } if (max > 10.f) { max = 1.f; if (max < min) min = 0.f; } } } // set min, max DataHist->SetMinimum(min); DataHist->SetMaximum(max); // draw! DataHist->Draw("ep"); MCHist ->Draw("ep same"); // draw sigma fit TF1 * DataFit; TF1 * MCFit; TPaveText * FitText = 0; if (doSigmaFit) { DataFit = DataInfo.SigmaFit; MCFit = MCInfo .SigmaFit; // draw fits DataFit->Draw("same"); MCFit ->Draw("same"); // setup output text FitText = new TPaveText(0.52,0.605,0.82,0.925,"NDC"); FitText->SetName("SigmaFitText"); FitText->AddText(Form("#sigma(t)=#frac{N}{%s} #oplus %sC",fSigmaVarText.Data(),fUseSqrt2?"#sqrt{2}":"")); FitText->AddText(Form("N^{%s} = %4.1f #pm %3.1f [%sns]",DataLabel.Data(),DataFit->GetParameter(0),DataFit->GetParError(0),fSigmaVarUnit.Data())); FitText->AddText(Form("C^{%s} = %6.4f #pm %6.4f [ns]" ,DataLabel.Data(),DataFit->GetParameter(1),DataFit->GetParError(1))); FitText->AddText(Form("N^{%s} = %4.1f #pm %3.1f [%sns]",MCLabel .Data(),MCFit ->GetParameter(0),MCFit ->GetParError(0),fSigmaVarUnit.Data())); FitText->AddText(Form("C^{%s} = %6.4f #pm %6.4f [ns]" ,MCLabel .Data(),MCFit ->GetParameter(1),MCFit ->GetParError(1))); FitText->SetTextAlign(11); FitText->SetFillColorAlpha(FitText->GetFillColor(),0); // draw text! FitText->Draw("same"); } // make legend auto Legend = new TLegend(0.72,0.855,0.82,0.925); Legend->SetName("Legend_"+key); Legend->SetBorderSize(1); Legend->SetLineColor(kBlack); // add to legend Legend->AddEntry(DataHist,DataInfo.label.Data(),"epl"); Legend->AddEntry(MCHist ,MCInfo .label.Data(),"epl"); // draw legend Legend->Draw("same"); // pretty up Common::CMSLumi(Canvas,0,fEra); // make images Common::SaveAs(Canvas,Form("%s_%s_%s",key.Data(),fOutFileText.Data(),(isLogy?"log":"lin"))); // do log-x? if (fDoLogX) { Canvas->cd(); Canvas->SetLogx(); // make images Common::SaveAs(Canvas,Form("%s_%s_%s_logx",key.Data(),fOutFileText.Data(),(isLogy?"log":"lin"))); } // save output if lin if (!isLogy) { Common::Write(fOutFile,Legend); Common::Write(fOutFile,Canvas); if (doSigmaFit) { Common::Write(fOutFile,FitText); } } // delete all if (doSigmaFit) { delete FitText; } delete Legend; delete Canvas; } void TimeFitter::GetMinMax(const TH1F * hist, Float_t & min, Float_t & max, const TString & key) { for (auto ibinX = 1; ibinX <= fNBinsX; ibinX++) { const auto content = hist->GetBinContent(ibinX); // bool to allow negative values const Bool_t canBeNeg = (key.EqualTo("mu",TString::kExact)); if ( ((!canBeNeg && min > 0.f) || (canBeNeg)) && content < min) min = content; if ( ((!canBeNeg && max > 0.f) || (canBeNeg)) && content > max) max = content; } } void TimeFitter::MakeConfigPave() { std::cout << "Dumping config to a pave..." << std::endl; // create the pave, copying in old info fOutFile->cd(); fConfigPave = new TPaveText(); fConfigPave->SetName(Form("%s",Common::pavename.Data())); // give grand title fConfigPave->AddText("***** TimeFitter Config *****"); // add era info Common::AddEraInfoToPave(fConfigPave,fEra); // dump time fit config Common::AddTextFromInputConfig(fConfigPave,"TimeFit Config",fTimeFitConfig); // dump plot config Common::AddTextFromInputConfig(fConfigPave,"Plot Config",fPlotConfig); // dump misc config Common::AddTextFromInputConfig(fConfigPave,"Misc Config",fMiscConfig); // padding Common::AddPaddingToPave(fConfigPave,3); // save name of infile, redundant fConfigPave->AddText(Form("InFile name: %s",fInFileName.Data())); // dump in old config Common::AddTextFromInputPave(fConfigPave,fInFile); // save to output file Common::Write(fOutFile,fConfigPave); } void TimeFitter::DumpFitInfo(FitStruct & DataInfo, FitStruct & MCInfo) { std::cout << "Dumping fit info into text file..." << std::endl; // get histograms! const auto & data_mu_hist = DataInfo.ResultsMap["mu"]; const auto & mc_mu_hist = MCInfo .ResultsMap["mu"]; const auto & data_sigma_hist = DataInfo.ResultsMap["sigma"]; const auto & mc_sigma_hist = MCInfo .ResultsMap["sigma"]; // make dumpfile object const TString filename = fOutFileText+Common::outFitText+"."+Common::outTextExt; std::ofstream dumpfile(Form("%s",filename.Data()),std::ios_base::out); dumpfile << std::setw(5) << "Bin |" << std::setw(18) << " pT range |" << std::setw(19) << " Data mu |" << std::setw(19) << " MC mu |" << std::setw(19) << " Data sigma |" << std::setw(19) << " MC sigma |" << std::setw(17) << " Diff sigma " << std::endl; std::string space = ""; const auto nw = 5+18+19+19+19+19+17; for (auto i = 0; i < nw; i++) space += "-"; dumpfile << space.c_str() << std::endl; for (auto ibinX = 1; ibinX <= fNBinsX; ibinX++) { const auto pt_low = fXBins[ibinX-1]; const auto pt_up = fXBins[ibinX]; const auto data_mu = data_mu_hist->GetBinContent(ibinX); const auto data_mu_e = data_mu_hist->GetBinError (ibinX); const auto mc_mu = mc_mu_hist ->GetBinContent(ibinX); const auto mc_mu_e = mc_mu_hist ->GetBinError (ibinX); const auto data_sigma = data_sigma_hist->GetBinContent(ibinX); const auto data_sigma_e = data_sigma_hist->GetBinError (ibinX); const auto mc_sigma = mc_sigma_hist ->GetBinContent(ibinX); const auto mc_sigma_e = mc_sigma_hist ->GetBinError (ibinX); const auto diff_sigma = std::sqrt(std::pow(data_sigma,2.f)-std::pow(mc_sigma,2.f)); const auto diff_sigma_e = std::sqrt(std::pow(data_sigma*data_sigma_e/diff_sigma,2.f)+std::pow(mc_sigma*mc_sigma_e/diff_sigma,2.f)); dumpfile << std::setw(5) << Form("%i |",ibinX) << std::setw(17) << Form(" %6.1f - %6.1f |",pt_low,pt_up) << std::setw(19) << Form(" %6.3f +/- %5.3f |",data_mu,data_mu_e) << std::setw(19) << Form(" %6.3f +/- %5.3f |",mc_mu ,mc_mu_e) << std::setw(19) << Form(" %6.3f +/- %5.3f |",data_sigma,data_sigma_e) << std::setw(19) << Form(" %6.3f +/- %5.3f |",mc_sigma ,mc_sigma_e) << std::setw(17) << Form(" %6.3f +/- %5.3f" ,diff_sigma,diff_sigma_e) << std::endl; if (ibinX % 20 == 0) dumpfile << space.c_str() << std::endl; } if (fDoSigmaFit) { // get fits! const auto & data_sigma_fit = DataInfo.SigmaFit; const auto & mc_sigma_fit = MCInfo .SigmaFit; dumpfile << space.c_str() << std::endl << std::endl; dumpfile << "Sigma Fit Results" << std::endl; dumpfile << std::setw(5) << "Par |" << std::setw(23) << " Data |" << std::setw(23) << " MC |" << std::endl; // loop over params and dump for (auto ipar = 0; ipar < data_sigma_fit->GetNpar(); ipar++) { // get constants const auto data_sigma_fit_par = data_sigma_fit->GetParameter(ipar); const auto data_sigma_fit_par_e = data_sigma_fit->GetParError (ipar); const auto mc_sigma_fit_par = mc_sigma_fit ->GetParameter(ipar); const auto mc_sigma_fit_par_e = mc_sigma_fit ->GetParError (ipar); dumpfile << std::setw(5) << Form("%s |",data_sigma_fit->GetParName(ipar)) << std::setw(23) << Form(" %8.3f +/- %7.3f |",data_sigma_fit_par,data_sigma_fit_par_e) << std::setw(23) << Form(" %8.3f +/- %7.3f |",mc_sigma_fit_par ,mc_sigma_fit_par_e) << std::endl; } } } void TimeFitter::SetupDefaults() { std::cout << "Setting up defaults for some params..." << std::endl; fDoLogX = false; fDoSigmaFit = false; fUseSqrt2 = false; } void TimeFitter::SetupCommon() { std::cout << "Setting up Common..." << std::endl; Common::SetupEras(); Common::SetupSamples(); Common::SetupGroups(); Common::SetupHistNames(); } void TimeFitter::SetupPlotConfig() { std::cout << "Reading plot config..." << std::endl; std::ifstream infile(Form("%s",fPlotConfig.Data()),std::ios::in); std::string str; while (std::getline(infile,str)) { if (str.find("plot_title=") != std::string::npos) { fTitle = Common::RemoveDelim(str,"plot_title="); } else if (str.find("x_title=") != std::string::npos) { fXTitle = Common::RemoveDelim(str,"x_title="); } else if (str.find("x_bins=") != std::string::npos) { str = Common::RemoveDelim(str,"x_bins="); Common::SetupBins(str,fXBins,fXVarBins); fNBinsX = fXBins.size()-1; } } } void TimeFitter::SetupMiscConfig() { std::cout << "Reading misc config..." << std::endl; std::ifstream infile(Form("%s",fMiscConfig.Data()),std::ios::in); std::string str; while (std::getline(infile,str)) { if (str == "") continue; else if (str.find("do_logx=") != std::string::npos) { str = Common::RemoveDelim(str,"do_logx="); Common::SetupBool(str,fDoLogX); } else { std::cerr << "Aye... your fit config is messed up, try again! Offending line: " << str.c_str() << std::endl; std::cerr << "Offending line: " << str.c_str() << std::endl; exit(1); } } } void TimeFitter::SetupTimeFitConfig() { std::cout << "Reading time fit config..." << std::endl; std::ifstream infile(Form("%s",fTimeFitConfig.Data()),std::ios::in); std::string str; while (std::getline(infile,str)) { if (str == "") continue; else if (str.find("fit_type=") != std::string::npos) { str = Common::RemoveDelim(str,"fit_type="); Common::SetupTimeFitType(str,fTimeFitType); } else if (str.find("range_low=") != std::string::npos) // if "core" = how many sigma from mean down, else absolute low edge of fit { str = Common::RemoveDelim(str,"range_low="); fRangeLow = std::atof(str.c_str()); } else if (str.find("range_up=") != std::string::npos) // if "core" = how many sigma from mean up, else absolute up edge of fit { str = Common::RemoveDelim(str,"range_up="); fRangeUp = std::atof(str.c_str()); } else if (str.find("time_text=") != std::string::npos) { fTimeText = Common::RemoveDelim(str,"time_text="); } else if (str.find("do_sigma_fit=") != std::string::npos) { str = Common::RemoveDelim(str,"do_sigma_fit="); Common::SetupBool(str,fDoSigmaFit); } else if (str.find("use_sqrt2=") != std::string::npos) { str = Common::RemoveDelim(str,"use_sqrt2="); Common::SetupBool(str,fUseSqrt2); } else if (str.find("sigma_var_text=") != std::string::npos) { fSigmaVarText = Common::RemoveDelim(str,"sigma_var_text="); } else if (str.find("sigma_var_unit=") != std::string::npos) { fSigmaVarUnit = Common::RemoveDelim(str,"sigma_var_unit="); // set to null character if none is specified if (fSigmaVarUnit.EqualTo("NONE",TString::kExact)) fSigmaVarUnit = ""; } else if (str.find("sigma_init_N_params=") != std::string::npos) { str = Common::RemoveDelim(str,"sigma_init_N_params="); TimeFitter::ReadInitParams(str,fSigmaInitN); } else if (str.find("sigma_init_C_params=") != std::string::npos) { str = Common::RemoveDelim(str,"sigma_init_C_params="); TimeFitter::ReadInitParams(str,fSigmaInitC); } else { std::cerr << "Aye... your fit config is messed up, try again! Offending line: " << str.c_str() << std::endl; std::cerr << "Offending line: " << str.c_str() << std::endl; exit(1); } } } void TimeFitter::ReadInitParams(const std::string & str, SigmaFitParams & params) { std::stringstream ss(str); ss >> params.low >> params.val >> params.up; } TH1F * TimeFitter::SetupHist(const TString & ytitle, const TString & yextra, const TString & label) { // get bins const auto xbins = &fXBins[0]; // make new hist auto hist = new TH1F(label+"_"+yextra,fTitle+" "+ytitle+";"+fXTitle+";"+ytitle,fNBinsX,xbins); hist->Sumw2(); Color_t color = kBlack; if (label.EqualTo("Data",TString::kExact)) { color = kBlue; } else if (label.EqualTo("MC",TString::kExact)) { color = kRed; } else { std::cerr << "How did this happen?? Specified neither Data nor MC for hist! Exiting..." << std::endl; exit(1); } hist->SetLineColor(color); hist->SetMarkerColor(color); return hist; } void TimeFitter::DeleteInfo(FitStruct & FitInfo) { const auto & label = FitInfo.label; std::cout << "Deleting info for: " << label.Data() << std::endl; if (fDoSigmaFit) { delete FitInfo.SigmaFit; delete FitInfo.SigmaForm; } Common::DeleteMap(FitInfo.ResultsMap); // loop over good bins to delete things auto & TimeFitStructMap = FitInfo.TimeFitStructMap; for (auto ibinX = 1; ibinX <= fNBinsX; ibinX++) { // get pair input auto & TimeFit = TimeFitStructMap[ibinX]; // delete internal members TimeFit->DeleteInternal(); // finally, delete the object itself delete TimeFit; } delete FitInfo.Hist2D; }
29.387056
149
0.631688
kmcdermo
e1e9b71e0ac361e75debaa047b3570601b869964
1,041
hpp
C++
Code/Engine/General/Time/Clock.hpp
ntaylorbishop/Copycat
c02f2881f0700a33a2630fd18bc409177d80b8cd
[ "MIT" ]
2
2017-10-02T03:18:55.000Z
2018-11-21T16:30:36.000Z
Code/Engine/General/Time/Clock.hpp
ntaylorbishop/Copycat
c02f2881f0700a33a2630fd18bc409177d80b8cd
[ "MIT" ]
null
null
null
Code/Engine/General/Time/Clock.hpp
ntaylorbishop/Copycat
c02f2881f0700a33a2630fd18bc409177d80b8cd
[ "MIT" ]
null
null
null
#pragma once #include "Engine/General/Core/EngineCommon.hpp" #include "Engine/General/Time/Time.hpp" #include <vector> class Clock { public: //STRUCTORS Clock(); Clock(Clock* parent); Clock(Clock* parent, float scale); ~Clock(); //UPDATE void Update(float deltaSeconds); //GETTERS double GetCurrent() const { return m_currentTime; } double GetDelta() const { return m_deltaTime; } void SetScale(float scale) { m_scale = scale; } void Reset() { m_currentTime = 0.f; } void Pause() { m_paused = true; } void Unpause() { m_paused = false; } bool operator==(const Clock& other) const { return (m_id == other.m_id); } bool operator!=(const Clock& other) const { return (m_id != other.m_id); } private: size_t m_id = 0; bool m_paused = false; double m_scale = 0.0; double m_currentTime = 0.0; double m_deltaTime = 0.0; Clock* m_parent = nullptr; std::vector<Clock*> m_children; void AttachChild(Clock* clock); void DetachChild(Clock* clock); static ulong s_clockId; };
23.659091
75
0.667627
ntaylorbishop
e1ead10e7d940923679324d4cce31cc01c339ced
681
cpp
C++
branchingLogic/E-JA-2009-3.MaxCifra.cpp
kilarionov/cppTopics
94461d25832b53e6c40c374fb2ff1695b3dfe3c7
[ "MIT" ]
null
null
null
branchingLogic/E-JA-2009-3.MaxCifra.cpp
kilarionov/cppTopics
94461d25832b53e6c40c374fb2ff1695b3dfe3c7
[ "MIT" ]
null
null
null
branchingLogic/E-JA-2009-3.MaxCifra.cpp
kilarionov/cppTopics
94461d25832b53e6c40c374fb2ff1695b3dfe3c7
[ "MIT" ]
1
2019-05-24T03:44:06.000Z
2019-05-24T03:44:06.000Z
#include<iostream> using namespace std; int main() { int b, c, d, k, digB, digC, digD, maxDigit ; cin >>b >>c >>d >>k; switch (k) { case 1:{ digB = b/100%10 ; digC = c/100%10 ; digD = d/100%10 ; break; } case 2:{ digB = b/10%10 ; digC = c/10%10 ; digD = d/10%10 ; break; } case 3:{ digB = b%10 ; digC = c%10 ; digD = d%10 ; break; } } ; // 9+(A-5)>8 <=> a>4 maxDigit = (digB>4) ? digB : 0 ; maxDigit = (digD>4 && digD>maxDigit) ? digD : maxDigit ; maxDigit = (digC>4 && digC>maxDigit) ? digC : maxDigit ; if (0==maxDigit) cout <<"No"<<endl ; // arena requires <<endl else cout <<maxDigit<<endl; return 0; }
17.025
57
0.515419
kilarionov
e1f12eef09656f22f863650ca0d6675857e6b0fb
2,953
cpp
C++
src/axl_core/axl_sl_Packer.cpp
vovkos/axl
5969bfda2fdfbb04a081dde16dcde0c5ddef0654
[ "MIT" ]
2
2021-03-19T09:32:02.000Z
2021-12-30T11:22:56.000Z
src/axl_core/axl_sl_Packer.cpp
vovkos/axl
5969bfda2fdfbb04a081dde16dcde0c5ddef0654
[ "MIT" ]
3
2019-04-19T19:20:59.000Z
2021-07-16T10:08:05.000Z
src/axl_core/axl_sl_Packer.cpp
vovkos/axl
5969bfda2fdfbb04a081dde16dcde0c5ddef0654
[ "MIT" ]
3
2019-04-19T18:19:52.000Z
2021-06-15T00:31:36.000Z
//.............................................................................. // // This file is part of the AXL library. // // AXL is distributed under the MIT license. // For details see accompanying license.txt file, // the public copy of which is also available at: // http://tibbo.com/downloads/archive/axl/license.txt // //.............................................................................. #include "pch.h" #include "axl_sl_Packer.h" namespace axl { namespace sl { //.............................................................................. axl_va_list PackerSeq::pack_va( void* _p, size_t* size, axl_va_list va ) { size_t count = m_sequence.getCount(); size_t totalSize = 0; if (!_p) { for (size_t i = 0; i < count; i++) { size_t size = 0; va = m_sequence[i]->pack_va(NULL, &size, va); totalSize += size; } } else { uchar_t* p = (uchar_t*)_p; for (size_t i = 0; i < count; i++) { size_t size = 0; va = m_sequence[i]->pack_va(p, &size, va); p += size; totalSize += size; } } *size = totalSize; return va; } size_t PackerSeq::appendFormat(const char* formatString) { if (!formatString) return m_sequence.getCount(); const char* pF = formatString; for (; *pF; pF++) { if (*pF != '%') continue; pF++; switch (*pF) { case 'd': case 'i': case 'o': case 'u': case 'x': case 'X': append<Pack<int> > (); break; case 'e': case 'E': case 'f': case 'g': case 'G': append<Pack<double> > (); break; case 'p': append<Pack<size_t> > (); break; case 's': append<PackString> (); break; case 'c': append<Pack<char> > (); break; case 'S': append<PackString_w> (); break; case 'C': append<Pack<wchar_t> > (); break; case 'B': append<Pack<uint8_t> > (); break; case 'W': append<Pack<uint16_t> > (); break; case 'D': append<Pack<uint32_t> > (); break; case 'Z': append<Pack<size_t> > (); break; case 'P': append<PackPtrSize> (); break; case 'R': append<PackLastError> (); break; } } return m_sequence.getCount(); } //.............................................................................. size_t Package::append_va( Packer* packer, axl_va_list va ) { bool result; size_t size; packer->pack_va(NULL, &size, va); size_t oldSize = m_buffer.getCount(); size_t newSize = oldSize + size; result = m_buffer.setCount(newSize); if (!result) return oldSize; packer->pack_va(m_buffer + oldSize, &size, va); return newSize; } size_t Package::append( const void* p, size_t size ) { bool result; size_t oldSize = m_buffer.getCount(); size_t newSize = oldSize + size; result = m_buffer.setCount(newSize); if (!result) return oldSize; memcpy(m_buffer + oldSize, p, size); return newSize; } //.............................................................................. } // namespace err } // namespace axl
16.683616
80
0.51981
vovkos
e1f3626e5f88ea5aa7eee49071e5b2eaa04735e0
243
cpp
C++
08_pointers_2d_arrays/02/02.cpp
bilyanhadzhi/intro_to_programming_labs
083bfaad1fdb423c0d8320b3e882316fa56c0bf8
[ "MIT" ]
3
2020-11-05T10:11:31.000Z
2020-11-14T16:10:27.000Z
08_pointers_2d_arrays/02/02.cpp
bilyanhadzhi/intro_to_programming_labs
083bfaad1fdb423c0d8320b3e882316fa56c0bf8
[ "MIT" ]
null
null
null
08_pointers_2d_arrays/02/02.cpp
bilyanhadzhi/intro_to_programming_labs
083bfaad1fdb423c0d8320b3e882316fa56c0bf8
[ "MIT" ]
1
2021-06-17T13:21:58.000Z
2021-06-17T13:21:58.000Z
#include <iostream> void swap(int* a, int* b) { int tmp = *a; *a = *b; *b = tmp; } int main() { int a = 5; int b = 4; std::cout << a << " " << b << "\n"; swap(&a, &b); std::cout << a << " " << b << "\n"; }
11.571429
39
0.358025
bilyanhadzhi
e1f3b0010b6b35ba82c98e4bcd160a802b33ffb6
10,022
cpp
C++
CMinus/CMinus/evaluator/integral_evaluator.cpp
benbraide/CMinus
3b845e0bc22840b549f108bf6600f1f34d865e7b
[ "MIT" ]
null
null
null
CMinus/CMinus/evaluator/integral_evaluator.cpp
benbraide/CMinus
3b845e0bc22840b549f108bf6600f1f34d865e7b
[ "MIT" ]
null
null
null
CMinus/CMinus/evaluator/integral_evaluator.cpp
benbraide/CMinus
3b845e0bc22840b549f108bf6600f1f34d865e7b
[ "MIT" ]
null
null
null
#include "../type/string_type.h" #include "../node/memory_reference_node.h" #include "integral_evaluator.h" cminus::evaluator::integral::~integral() = default; std::shared_ptr<cminus::memory::reference> cminus::evaluator::integral::evaluate_unary_left(logic::runtime &runtime, const operator_type &op, std::shared_ptr<memory::reference> target) const{ if (target == nullptr || !std::holds_alternative<operator_id>(op)) throw logic::exception("Operator '" + object::convert_operator_to_string(op) + "' does not take the specified operand", 0u, 0u); auto type = target->get_type(); auto primitive_type = dynamic_cast<type::primitive *>(type.get()); auto will_write = (std::get<operator_id>(op) == operator_id::increment || std::get<operator_id>(op) == operator_id::decrement); if (!will_write && std::get<operator_id>(op) != operator_id::bitwise_inverse && std::get<operator_id>(op) != operator_id::plus){ if (std::get<operator_id>(op) != operator_id::minus || primitive_type->is_unsigned_integral()) throw logic::exception("Operator '" + object::convert_operator_to_string(op) + "' does not take the specified operand", 0u, 0u); } if (will_write && !target->is_lvalue()) throw logic::exception("Operator '" + object::convert_operator_to_string(op) + "' requires an l-value operand", 0u, 0u); switch (primitive_type->get_id()){ case type::primitive::id_type::int16_: return arithmetic::evaluate_integral_unary_left_<__int16>(runtime, std::get<operator_id>(op), target); case type::primitive::id_type::uint16_: return arithmetic::evaluate_unsigned_integral_unary_left_<unsigned __int16>(runtime, std::get<operator_id>(op), target); case type::primitive::id_type::int32_: return arithmetic::evaluate_integral_unary_left_<__int32>(runtime, std::get<operator_id>(op), target); case type::primitive::id_type::uint32_: return arithmetic::evaluate_unsigned_integral_unary_left_<unsigned __int32>(runtime, std::get<operator_id>(op), target); case type::primitive::id_type::int64_: return arithmetic::evaluate_integral_unary_left_<__int64>(runtime, std::get<operator_id>(op), target); case type::primitive::id_type::uint64_: return arithmetic::evaluate_unsigned_integral_unary_left_<unsigned __int64>(runtime, std::get<operator_id>(op), target); default: break; } throw logic::exception("Operator '" + object::convert_operator_to_string(op) + "' does not take the specified operand", 0u, 0u); return nullptr; } std::shared_ptr<cminus::memory::reference> cminus::evaluator::integral::evaluate_unary_right(logic::runtime &runtime, const operator_type &op, std::shared_ptr<memory::reference> target) const{ if (target == nullptr || !std::holds_alternative<operator_id>(op)) throw logic::exception("Operator '" + object::convert_operator_to_string(op) + "' does not take the specified operand", 0u, 0u); if (std::get<operator_id>(op) != operator_id::increment && std::get<operator_id>(op) != operator_id::decrement) throw logic::exception("Operator '" + object::convert_operator_to_string(op) + "' does not take the specified operand", 0u, 0u); if (!target->is_lvalue()) throw logic::exception("Operator '" + object::convert_operator_to_string(op) + "' requires an l-value operand", 0u, 0u); auto type = target->get_type(); switch (dynamic_cast<type::primitive *>(type.get())->get_id()){ case type::primitive::id_type::int16_: return arithmetic::evaluate_unsigned_unary_right_<__int16>(runtime, std::get<operator_id>(op), target); case type::primitive::id_type::uint16_: return arithmetic::evaluate_unsigned_unary_right_<unsigned __int16>(runtime, std::get<operator_id>(op), target); case type::primitive::id_type::int32_: return arithmetic::evaluate_unsigned_unary_right_<__int32>(runtime, std::get<operator_id>(op), target); case type::primitive::id_type::uint32_: return arithmetic::evaluate_unsigned_unary_right_<unsigned __int32>(runtime, std::get<operator_id>(op), target); case type::primitive::id_type::int64_: return arithmetic::evaluate_unsigned_unary_right_<__int64>(runtime, std::get<operator_id>(op), target); case type::primitive::id_type::uint64_: return arithmetic::evaluate_unsigned_unary_right_<unsigned __int64>(runtime, std::get<operator_id>(op), target); default: break; } throw logic::exception("Operator '" + object::convert_operator_to_string(op) + "' does not take the specified operand", 0u, 0u); return nullptr; } std::shared_ptr<cminus::memory::reference> cminus::evaluator::integral::evaluate_binary(logic::runtime &runtime, const operator_type &op, std::shared_ptr<memory::reference> left_value, const operand_type &right) const{ if (auto result = explicit_comparison::evaluate_(runtime, op, left_value, right); result != nullptr)//Handled return result; if (auto result = assignment::evaluate_(runtime, op, left_value, right); result != nullptr)//Handled return result; if (auto result = compound_assignment::evaluate_(runtime, op, left_value, right); result != nullptr)//Handled return result; if (left_value == nullptr || !std::holds_alternative<operator_id>(op) || !object::operator_is_integral(std::get<operator_id>(op))) throw logic::exception("Operator '" + object::convert_operator_to_string(op) + "' does not take the specified operands", 0u, 0u); auto right_value = object::convert_operand_to_memory_reference(runtime, right); if (right_value == nullptr) throw logic::exception("Operator '" + object::convert_operator_to_string(op) + "' does not take the specified operands", 0u, 0u); auto left_type = left_value->get_type(), right_type = right_value->get_type(); if (left_type == nullptr || right_type == nullptr) throw logic::exception("Operator '" + object::convert_operator_to_string(op) + "' does not take the specified operands", 0u, 0u); auto left_primitive_type = dynamic_cast<type::primitive *>(left_type.get()); if (left_primitive_type == nullptr) throw logic::exception("Operator '" + object::convert_operator_to_string(op) + "' does not take the specified operands", 0u, 0u); if (dynamic_cast<type::string *>(right_type.get()) != nullptr){ return right_type->get_evaluator(runtime)->evaluate_binary( runtime, op, left_type->cast(runtime, left_value, right_type, type::object::cast_type::static_), std::make_shared<node::memory_reference>(nullptr, right_value) ); } if (object::operator_is_shift(std::get<operator_id>(op), true)){ std::shared_ptr<memory::reference> result; switch (left_primitive_type->get_id()){ case type::primitive::id_type::int16_: result = arithmetic::evaluate_integral_shift_<__int16>(runtime, std::get<operator_id>(op), left_value, right_value); break; case type::primitive::id_type::uint16_: result = arithmetic::evaluate_integral_shift_<unsigned __int16>(runtime, std::get<operator_id>(op), left_value, right_value); break; case type::primitive::id_type::int32_: result = arithmetic::evaluate_integral_shift_<__int32>(runtime, std::get<operator_id>(op), left_value, right_value); break; case type::primitive::id_type::uint32_: result = arithmetic::evaluate_integral_shift_<unsigned __int32>(runtime, std::get<operator_id>(op), left_value, right_value); break; case type::primitive::id_type::int64_: result = arithmetic::evaluate_integral_shift_<__int64>(runtime, std::get<operator_id>(op), left_value, right_value); break; case type::primitive::id_type::uint64_: result = arithmetic::evaluate_integral_shift_<unsigned __int64>(runtime, std::get<operator_id>(op), left_value, right_value); break; default: break; } if (result == nullptr) throw logic::exception("Operator '" + object::convert_operator_to_string(op) + "' does not take the specified operands", 0u, 0u); return result; } auto left_value_copy = left_value, right_value_copy = right_value; switch (left_type->get_score(runtime, *right_type, false)){ case type::object::score_result_type::exact: case type::object::score_result_type::assignable://Conversion from NaN value break; case type::object::score_result_type::shortened: case type::object::score_result_type::too_shortened: left_value = left_type->cast(runtime, left_value, right_type, type::object::cast_type::static_); break; default: right_value = right_type->cast(runtime, right_value, left_type, type::object::cast_type::static_); break; } if (left_value == nullptr || right_value == nullptr) throw logic::exception("Operator '" + object::convert_operator_to_string(op) + "' does not take the specified operands", 0u, 0u); switch (left_primitive_type->get_id()){ case type::primitive::id_type::int16_: return evaluate_binary_<__int16>(runtime, std::get<operator_id>(op), left_value, right_value); case type::primitive::id_type::uint16_: return evaluate_binary_<unsigned __int16>(runtime, std::get<operator_id>(op), left_value, right_value); case type::primitive::id_type::int32_: return evaluate_binary_<__int32>(runtime, std::get<operator_id>(op), left_value, right_value); case type::primitive::id_type::uint32_: return evaluate_binary_<unsigned __int32>(runtime, std::get<operator_id>(op), left_value, right_value); case type::primitive::id_type::int64_: return evaluate_binary_<__int64>(runtime, std::get<operator_id>(op), left_value, right_value); case type::primitive::id_type::uint64_: return evaluate_binary_<unsigned __int64>(runtime, std::get<operator_id>(op), left_value, right_value); default: break; } throw logic::exception("Operator '" + object::convert_operator_to_string(op) + "' does not take the specified operands", 0u, 0u); return nullptr; } void cminus::evaluator::integral::after_value_copy_(logic::runtime &runtime, std::shared_ptr<memory::reference> left_value, std::shared_ptr<memory::reference> right_value) const{ assignment::after_value_copy_(runtime, left_value, right_value); if (right_value->is_nan()) left_value->add_attribute(runtime.global_storage->find_attribute("#NaN#", false)); else left_value->remove_attribute("#NaN#", true); }
53.593583
218
0.751048
benbraide
e1f7a0bac32bb591473c4a90e97017a286e7c2d9
2,990
cpp
C++
ouzel/audio/opensl/AudioSL.cpp
keima97/ouzel
e6673e678b4739235371a15ae3863942b692c5fb
[ "BSD-2-Clause" ]
null
null
null
ouzel/audio/opensl/AudioSL.cpp
keima97/ouzel
e6673e678b4739235371a15ae3863942b692c5fb
[ "BSD-2-Clause" ]
null
null
null
ouzel/audio/opensl/AudioSL.cpp
keima97/ouzel
e6673e678b4739235371a15ae3863942b692c5fb
[ "BSD-2-Clause" ]
null
null
null
// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #include "AudioSL.h" #include "SoundDataSL.h" #include "SoundSL.h" #include "utils/Log.h" namespace ouzel { namespace audio { AudioSL::AudioSL(): Audio(Driver::OPENSL) { } AudioSL::~AudioSL() { if (outputMixObject) { (*outputMixObject)->Destroy(outputMixObject); } if (engineObject) { (*engineObject)->Destroy(engineObject); } } void AudioSL::free() { Audio::free(); if (outputMixObject) { (*outputMixObject)->Destroy(outputMixObject); outputMixObject = nullptr; } if (engineObject) { (*engineObject)->Destroy(engineObject); engineObject = nullptr; engine = nullptr; } } bool AudioSL::init() { if (!Audio::init()) { return false; } free(); const SLuint32 engineMixIIDCount = 1; const SLInterfaceID engineMixIID = SL_IID_ENGINE; const SLboolean engineMixReq = SL_BOOLEAN_TRUE; if (slCreateEngine(&engineObject, 0, NULL, engineMixIIDCount, &engineMixIID, &engineMixReq) != SL_RESULT_SUCCESS) { Log(Log::Level::ERR) << "Failed to create OpenSL engine object"; return false; } if ((*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE) != SL_RESULT_SUCCESS) { Log(Log::Level::ERR) << "Failed to create OpenSL engine object"; return false; } if ((*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engine) != SL_RESULT_SUCCESS) { Log(Log::Level::ERR) << "Failed to get OpenSL engine"; return false; } if ((*engine)->CreateOutputMix(engine, &outputMixObject, 0, nullptr, nullptr) != SL_RESULT_SUCCESS) { Log(Log::Level::ERR) << "Failed to create OpenSL output mix"; return false; } if ((*outputMixObject)->Realize(outputMixObject, SL_BOOLEAN_FALSE) != SL_RESULT_SUCCESS) { Log(Log::Level::ERR) << "Failed to create OpenSL output mix"; return false; } ready = true; return true; } SoundDataPtr AudioSL::createSoundData() { SoundDataPtr soundData = std::make_shared<SoundDataSL>(); return soundData; } SoundPtr AudioSL::createSound() { SoundPtr sound = std::make_shared<SoundSL>(); return sound; } } // namespace audio } // namespace ouzel
27.181818
125
0.498662
keima97
e1fdf70f20a746d33b693e08911948e147cac155
1,455
hpp
C++
src/vendor/type_safe/detail/aligned_union.hpp
rolandwalker/Karabiner-Elements
3a537d3dd7a47100baf95bb3477e897a6e59bee8
[ "Unlicense" ]
null
null
null
src/vendor/type_safe/detail/aligned_union.hpp
rolandwalker/Karabiner-Elements
3a537d3dd7a47100baf95bb3477e897a6e59bee8
[ "Unlicense" ]
null
null
null
src/vendor/type_safe/detail/aligned_union.hpp
rolandwalker/Karabiner-Elements
3a537d3dd7a47100baf95bb3477e897a6e59bee8
[ "Unlicense" ]
null
null
null
// Copyright (C) 2016-2018 Jonathan Müller <jonathanmueller.dev@gmail.com> // This file is subject to the license terms in the LICENSE file // found in the top-level directory of this distribution. #ifndef TYPE_SAFE_DETAIL_ALIGNED_UNION_HPP_INCLUDED #define TYPE_SAFE_DETAIL_ALIGNED_UNION_HPP_INCLUDED #include <type_traits> namespace type_safe { namespace detail { // max for variadic number of types. template <typename T> constexpr const T& max(const T& a) { return a; } template <typename T> constexpr const T& max(const T& a, const T& b) { return a < b ? b : a; } template <typename T, typename... Ts> constexpr const T& max(const T& t, const Ts&... ts) { return max(t, max(ts...)); } // std::aligned_union not available on all compilers template <typename... Types> struct aligned_union { static constexpr auto size_value = detail::max(sizeof(Types)...); static constexpr auto alignment_value = detail::max(alignof(Types)...); using type = typename std::aligned_storage<size_value, alignment_value>::type; }; template <typename... Types> using aligned_union_t = typename aligned_union<Types...>::type; } } // namespace type_safe::detail #endif // TYPE_SAFE_DETAIL_ALIGNED_UNION_HPP_INCLUDED
29.693878
90
0.62268
rolandwalker
c00274d16a48baad017adb4603c7179fd32591fc
5,898
cpp
C++
OrbitGl/SessionsDataView.cpp
ehei1/orbit
f990a7f9abb7d330e93d0d20018a62869890f04e
[ "BSD-2-Clause" ]
null
null
null
OrbitGl/SessionsDataView.cpp
ehei1/orbit
f990a7f9abb7d330e93d0d20018a62869890f04e
[ "BSD-2-Clause" ]
null
null
null
OrbitGl/SessionsDataView.cpp
ehei1/orbit
f990a7f9abb7d330e93d0d20018a62869890f04e
[ "BSD-2-Clause" ]
null
null
null
//----------------------------------- // Copyright Pierric Gimmig 2013-2017 //----------------------------------- #include "Core.h" #include "SessionsDataView.h" #include "ModuleDataView.h" #include "Pdb.h" #include "OrbitType.h" #include "Capture.h" #include "App.h" #include "Callstack.h" #include "OrbitSession.h" //----------------------------------------------------------------------------- SessionsDataView::SessionsDataView() { m_SortingToggles.resize(SDV_NumColumns, false); GOrbitApp->RegisterSessionsDataView(this); } //----------------------------------------------------------------------------- std::vector<float> SessionsDataView::s_HeaderRatios; //----------------------------------------------------------------------------- const std::vector<std::wstring>& SessionsDataView::GetColumnHeaders() { static std::vector<std::wstring> Columns; if( Columns.size() == 0 ) { Columns.push_back( L"Session" ); s_HeaderRatios.push_back( 0.5 ); Columns.push_back( L"Process" ); s_HeaderRatios.push_back( 0 ); //Columns.push_back( L"LastUsed" ); s_HeaderRatios.push_back( 0 ); }; return Columns; } //----------------------------------------------------------------------------- enum SessionsContextMenuIDs { SESSIONS_LOAD }; //----------------------------------------------------------------------------- const std::vector<std::wstring>& SessionsDataView::GetContextMenu( int a_Index ) { static std::vector<std::wstring> Menu = { L"Load Session" }; return Menu; } //----------------------------------------------------------------------------- const std::vector<float>& SessionsDataView::GetColumnHeadersRatios() { return s_HeaderRatios; } //----------------------------------------------------------------------------- std::wstring SessionsDataView::GetValue( int row, int col ) { std::wstring value; const std::shared_ptr<Session> & session = GetSession(row); switch (col) { case SDV_SessionName: value = Path::GetFileName( session->m_FileName ); break; case SDV_ProcessName: value = Path::GetFileName( session->m_ProcessFullPath ); break; /*case SDV_LastUsed: value = "LastUsed"; break;*/ break; default: break; } return value; } //----------------------------------------------------------------------------- std::wstring SessionsDataView::GetToolTip( int a_Row, int a_Column ) { const Session & session = *GetSession(a_Row); return session.m_FileName; } //----------------------------------------------------------------------------- #define ORBIT_SESSION_SORT( Member ) [&](int a, int b) { return OrbitUtils::Compare(m_Sessions[a]->##Member, m_Sessions[b]->##Member, ascending); } //----------------------------------------------------------------------------- void SessionsDataView::OnSort(int a_Column, bool a_Toggle) { SdvColumn pdvColumn = SdvColumn(a_Column); if (a_Toggle) { m_SortingToggles[pdvColumn] = !m_SortingToggles[pdvColumn]; } bool ascending = m_SortingToggles[pdvColumn]; std::function<bool(int a, int b)> sorter = nullptr; switch (pdvColumn) { case SDV_SessionName: sorter = ORBIT_SESSION_SORT(m_FileName); break; case SDV_ProcessName: sorter = ORBIT_SESSION_SORT(m_ProcessFullPath); break; } if (sorter) { std::sort(m_Indices.begin(), m_Indices.end(), sorter); } m_LastSortedColumn = a_Column; } //----------------------------------------------------------------------------- void SessionsDataView::OnContextMenu( int a_Index, std::vector<int> & a_ItemIndices ) { switch( a_Index ) { case SESSIONS_LOAD: { for( int index : a_ItemIndices ) { const std::shared_ptr<Session> & session = GetSession( index ); if( GOrbitApp->SelectProcess( Path::GetFileName( session->m_ProcessFullPath ) ) ) { Capture::LoadSession( session ); } } GOrbitApp->LoadModules(); break; } default: break; } } //----------------------------------------------------------------------------- void SessionsDataView::OnFilter( const std::wstring & a_Filter ) { std::vector<int> indices; std::vector< std::wstring > tokens = Tokenize( ToLower( a_Filter ) ); for (int i = 0; i < (int)m_Sessions.size(); ++i) { const Session & session = *m_Sessions[i]; std::wstring name = Path::GetFileName( ToLower( session.m_FileName ) ); std::wstring path = ToLower( session.m_ProcessFullPath ); bool match = true; for( std::wstring & filterToken : tokens ) { if (!(name.find(filterToken) != std::wstring::npos || path.find(filterToken) != std::wstring::npos)) { match = false; break; } } if (match) { indices.push_back(i); } } m_Indices = indices; if (m_LastSortedColumn != -1) { OnSort(m_LastSortedColumn, false); } } //----------------------------------------------------------------------------- void SessionsDataView::OnDataChanged() { m_Indices.resize( m_Sessions.size() ); for( int i = 0; i < m_Sessions.size(); ++i ) { m_Indices[i] = i; } if( m_LastSortedColumn != -1 ) { OnSort( m_LastSortedColumn, false ); } } //----------------------------------------------------------------------------- void SessionsDataView::SetSessions( const std::vector< std::shared_ptr< Session > > & a_Sessions ) { m_Sessions = a_Sessions; OnDataChanged(); } //----------------------------------------------------------------------------- const std::shared_ptr<Session> & SessionsDataView::GetSession( unsigned int a_Row ) const { return m_Sessions[m_Indices[a_Row]]; }
28.631068
147
0.494405
ehei1
c0040779a9ae219daeb57e1605a61ffd89aebba8
10,206
cpp
C++
vm/external_libs/llvm/lib/Target/X86/X86Subtarget.cpp
marnen/rubinius
05b3f9789d01bada0604a7f09921c956bc9487e7
[ "BSD-3-Clause" ]
1
2016-05-08T16:58:14.000Z
2016-05-08T16:58:14.000Z
vm/external_libs/llvm/lib/Target/X86/X86Subtarget.cpp
taf2/rubinius
493bfa2351fc509ca33d3bb03991c2e9c2b6dafa
[ "BSD-3-Clause" ]
null
null
null
vm/external_libs/llvm/lib/Target/X86/X86Subtarget.cpp
taf2/rubinius
493bfa2351fc509ca33d3bb03991c2e9c2b6dafa
[ "BSD-3-Clause" ]
null
null
null
//===-- X86Subtarget.cpp - X86 Subtarget Information ------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the X86 specific subclass of TargetSubtarget. // //===----------------------------------------------------------------------===// #include "X86Subtarget.h" #include "X86GenSubtarget.inc" #include "llvm/Module.h" #include "llvm/Support/CommandLine.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" using namespace llvm; cl::opt<X86Subtarget::AsmWriterFlavorTy> AsmWriterFlavor("x86-asm-syntax", cl::init(X86Subtarget::Unset), cl::desc("Choose style of code to emit from X86 backend:"), cl::values( clEnumValN(X86Subtarget::ATT, "att", " Emit AT&T-style assembly"), clEnumValN(X86Subtarget::Intel, "intel", " Emit Intel-style assembly"), clEnumValEnd)); /// True if accessing the GV requires an extra load. For Windows, dllimported /// symbols are indirect, loading the value at address GV rather then the /// value of GV itself. This means that the GlobalAddress must be in the base /// or index register of the address, not the GV offset field. bool X86Subtarget::GVRequiresExtraLoad(const GlobalValue* GV, const TargetMachine& TM, bool isDirectCall) const { // FIXME: PIC if (TM.getRelocationModel() != Reloc::Static) { if (isTargetDarwin()) { return (!isDirectCall && (GV->hasWeakLinkage() || GV->hasLinkOnceLinkage() || (GV->isDeclaration() && !GV->hasNotBeenReadFromBitcode()))); } else if (isTargetELF()) { // Extra load is needed for all non-statics. return (!isDirectCall && (GV->isDeclaration() || !GV->hasInternalLinkage())); } else if (isTargetCygMing() || isTargetWindows()) { return (GV->hasDLLImportLinkage()); } } return false; } /// This function returns the name of a function which has an interface /// like the non-standard bzero function, if such a function exists on /// the current subtarget and it is considered prefereable over /// memset with zero passed as the second argument. Otherwise it /// returns null. const char *X86Subtarget::getBZeroEntry() const { // Darwin 10 has a __bzero entry point for this purpose. if (getDarwinVers() >= 10) return "__bzero"; return 0; } /// GetCpuIDAndInfo - Execute the specified cpuid and return the 4 values in the /// specified arguments. If we can't run cpuid on the host, return true. bool X86::GetCpuIDAndInfo(unsigned value, unsigned *rEAX, unsigned *rEBX, unsigned *rECX, unsigned *rEDX) { #if defined(__x86_64__) // gcc doesn't know cpuid would clobber ebx/rbx. Preseve it manually. asm ("movq\t%%rbx, %%rsi\n\t" "cpuid\n\t" "xchgq\t%%rbx, %%rsi\n\t" : "=a" (*rEAX), "=S" (*rEBX), "=c" (*rECX), "=d" (*rEDX) : "a" (value)); return false; #elif defined(i386) || defined(__i386__) || defined(__x86__) || defined(_M_IX86) #if defined(__GNUC__) asm ("movl\t%%ebx, %%esi\n\t" "cpuid\n\t" "xchgl\t%%ebx, %%esi\n\t" : "=a" (*rEAX), "=S" (*rEBX), "=c" (*rECX), "=d" (*rEDX) : "a" (value)); return false; #elif defined(_MSC_VER) __asm { mov eax,value cpuid mov esi,rEAX mov dword ptr [esi],eax mov esi,rEBX mov dword ptr [esi],ebx mov esi,rECX mov dword ptr [esi],ecx mov esi,rEDX mov dword ptr [esi],edx } return false; #endif #endif return true; } void X86Subtarget::AutoDetectSubtargetFeatures() { unsigned EAX = 0, EBX = 0, ECX = 0, EDX = 0; union { unsigned u[3]; char c[12]; } text; if (X86::GetCpuIDAndInfo(0, &EAX, text.u+0, text.u+2, text.u+1)) return; X86::GetCpuIDAndInfo(0x1, &EAX, &EBX, &ECX, &EDX); if ((EDX >> 23) & 0x1) X86SSELevel = MMX; if ((EDX >> 25) & 0x1) X86SSELevel = SSE1; if ((EDX >> 26) & 0x1) X86SSELevel = SSE2; if (ECX & 0x1) X86SSELevel = SSE3; if ((ECX >> 9) & 0x1) X86SSELevel = SSSE3; if ((ECX >> 19) & 0x1) X86SSELevel = SSE41; if ((ECX >> 20) & 0x1) X86SSELevel = SSE42; if (memcmp(text.c, "GenuineIntel", 12) == 0 || memcmp(text.c, "AuthenticAMD", 12) == 0) { X86::GetCpuIDAndInfo(0x80000001, &EAX, &EBX, &ECX, &EDX); HasX86_64 = (EDX >> 29) & 0x1; } } static const char *GetCurrentX86CPU() { unsigned EAX = 0, EBX = 0, ECX = 0, EDX = 0; if (X86::GetCpuIDAndInfo(0x1, &EAX, &EBX, &ECX, &EDX)) return "generic"; unsigned Family = (EAX >> 8) & 0xf; // Bits 8 - 11 unsigned Model = (EAX >> 4) & 0xf; // Bits 4 - 7 X86::GetCpuIDAndInfo(0x80000001, &EAX, &EBX, &ECX, &EDX); bool Em64T = (EDX >> 29) & 0x1; union { unsigned u[3]; char c[12]; } text; X86::GetCpuIDAndInfo(0, &EAX, text.u+0, text.u+2, text.u+1); if (memcmp(text.c, "GenuineIntel", 12) == 0) { switch (Family) { case 3: return "i386"; case 4: return "i486"; case 5: switch (Model) { case 4: return "pentium-mmx"; default: return "pentium"; } case 6: switch (Model) { case 1: return "pentiumpro"; case 3: case 5: case 6: return "pentium2"; case 7: case 8: case 10: case 11: return "pentium3"; case 9: case 13: return "pentium-m"; case 14: return "yonah"; case 15: return "core2"; default: return "i686"; } case 15: { switch (Model) { case 3: case 4: return (Em64T) ? "nocona" : "prescott"; default: return (Em64T) ? "x86-64" : "pentium4"; } } default: return "generic"; } } else if (memcmp(text.c, "AuthenticAMD", 12) == 0) { // FIXME: this poorly matches the generated SubtargetFeatureKV table. There // appears to be no way to generate the wide variety of AMD-specific targets // from the information returned from CPUID. switch (Family) { case 4: return "i486"; case 5: switch (Model) { case 6: case 7: return "k6"; case 8: return "k6-2"; case 9: case 13: return "k6-3"; default: return "pentium"; } case 6: switch (Model) { case 4: return "athlon-tbird"; case 6: case 7: case 8: return "athlon-mp"; case 10: return "athlon-xp"; default: return "athlon"; } case 15: switch (Model) { case 1: return "opteron"; case 5: return "athlon-fx"; // also opteron default: return "athlon64"; } default: return "generic"; } } else { return "generic"; } } X86Subtarget::X86Subtarget(const Module &M, const std::string &FS, bool is64Bit) : AsmFlavor(AsmWriterFlavor) , PICStyle(PICStyle::None) , X86SSELevel(NoMMXSSE) , X863DNowLevel(NoThreeDNow) , HasX86_64(false) , DarwinVers(0) , IsLinux(false) , stackAlignment(8) // FIXME: this is a known good value for Yonah. How about others? , MaxInlineSizeThreshold(128) , Is64Bit(is64Bit) , TargetType(isELF) { // Default to ELF unless otherwise specified. // Determine default and user specified characteristics if (!FS.empty()) { // If feature string is not empty, parse features string. std::string CPU = GetCurrentX86CPU(); ParseSubtargetFeatures(FS, CPU); } else { // Otherwise, use CPUID to auto-detect feature set. AutoDetectSubtargetFeatures(); } // If requesting codegen for X86-64, make sure that 64-bit and SSE2 features // are enabled. These are available on all x86-64 CPUs. if (Is64Bit) { HasX86_64 = true; if (X86SSELevel < SSE2) X86SSELevel = SSE2; } // Set the boolean corresponding to the current target triple, or the default // if one cannot be determined, to true. const std::string& TT = M.getTargetTriple(); if (TT.length() > 5) { size_t Pos; if ((Pos = TT.find("-darwin")) != std::string::npos) { TargetType = isDarwin; // Compute the darwin version number. if (isdigit(TT[Pos+7])) DarwinVers = atoi(&TT[Pos+7]); else DarwinVers = 8; // Minimum supported darwin is Tiger. } else if (TT.find("linux") != std::string::npos) { // Linux doesn't imply ELF, but we don't currently support anything else. TargetType = isELF; IsLinux = true; } else if (TT.find("cygwin") != std::string::npos) { TargetType = isCygwin; } else if (TT.find("mingw") != std::string::npos) { TargetType = isMingw; } else if (TT.find("win32") != std::string::npos) { TargetType = isWindows; } else if (TT.find("windows") != std::string::npos) { TargetType = isWindows; } } else if (TT.empty()) { #if defined(__CYGWIN__) TargetType = isCygwin; #elif defined(__MINGW32__) || defined(__MINGW64__) TargetType = isMingw; #elif defined(__APPLE__) TargetType = isDarwin; #if __APPLE_CC__ > 5400 DarwinVers = 9; // GCC 5400+ is Leopard. #else DarwinVers = 8; // Minimum supported darwin is Tiger. #endif #elif defined(_WIN32) || defined(_WIN64) TargetType = isWindows; #elif defined(__linux__) // Linux doesn't imply ELF, but we don't currently support anything else. TargetType = isELF; IsLinux = true; #endif } // If the asm syntax hasn't been overridden on the command line, use whatever // the target wants. if (AsmFlavor == X86Subtarget::Unset) { AsmFlavor = (TargetType == isWindows) ? X86Subtarget::Intel : X86Subtarget::ATT; } // Stack alignment is 16 bytes on Darwin (both 32 and 64 bit) and for all 64 // bit targets. if (TargetType == isDarwin || Is64Bit) stackAlignment = 16; if (StackAlignment) stackAlignment = StackAlignment; }
30.740964
80
0.589065
marnen
c005b8be8fb5ec2afacb6ae90d91eb45bf233f36
1,138
hpp
C++
include/boost/simd/function/simd/tofloat.hpp
yaeldarmon/boost.simd
561316cc54bdc6353ca78f3b6d7e9120acd11144
[ "BSL-1.0" ]
null
null
null
include/boost/simd/function/simd/tofloat.hpp
yaeldarmon/boost.simd
561316cc54bdc6353ca78f3b6d7e9120acd11144
[ "BSL-1.0" ]
null
null
null
include/boost/simd/function/simd/tofloat.hpp
yaeldarmon/boost.simd
561316cc54bdc6353ca78f3b6d7e9120acd11144
[ "BSL-1.0" ]
null
null
null
//================================================================================================== /*! @file @copyright 2016 NumScale SAS @copyright 2016 J.T. Lapreste Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ //================================================================================================== #ifndef BOOST_SIMD_FUNCTION_SIMD_TOFLOAT_INCLUDED #define BOOST_SIMD_FUNCTION_SIMD_TOFLOAT_INCLUDED #include <boost/simd/function/scalar/tofloat.hpp> #include <boost/simd/arch/common/generic/function/autodispatcher.hpp> #if defined(BOOST_HW_SIMD_X86) # if BOOST_HW_SIMD_X86 >= BOOST_HW_SIMD_X86_SSE2_VERSION # include <boost/simd/arch/x86/sse2/simd/function/tofloat.hpp> # endif # if BOOST_HW_SIMD_X86 >= BOOST_HW_SIMD_X86_AVX_VERSION // # include <boost/simd/arch/x86/avx/simd/function/tofloat.hpp> # endif #endif #if defined(BOOST_HW_SIMD_PPC) # if BOOST_HW_SIMD_PPC >= BOOST_HW_SIMD_PPC_VMX_VERSION // # include <boost/simd/arch/power/vmx/simd/function/tofloat.hpp> # endif #endif #endif
29.947368
100
0.63884
yaeldarmon
c00685b3f1cf3339b87fcf0961d4e970161dd33a
1,239
hpp
C++
sdk/keyvault/azure-security-keyvault-keys/inc/azure/keyvault/keys/list_keys_single_page_result.hpp
kyle-patterson/azure-sdk-for-cpp
0c24db5a10eeea46840c3e8ee7089fd9857cd7b4
[ "MIT" ]
null
null
null
sdk/keyvault/azure-security-keyvault-keys/inc/azure/keyvault/keys/list_keys_single_page_result.hpp
kyle-patterson/azure-sdk-for-cpp
0c24db5a10eeea46840c3e8ee7089fd9857cd7b4
[ "MIT" ]
null
null
null
sdk/keyvault/azure-security-keyvault-keys/inc/azure/keyvault/keys/list_keys_single_page_result.hpp
kyle-patterson/azure-sdk-for-cpp
0c24db5a10eeea46840c3e8ee7089fd9857cd7b4
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. All rights reserved. // SPDX-License-Identifier: MIT /** * @file * @brief Defines a page of listing keys from a Key Vault. * */ #pragma once #include "azure/keyvault/keys/deleted_key.hpp" #include "azure/keyvault/keys/json_web_key.hpp" #include "azure/keyvault/keys/key_vault_key.hpp" #include <azure/keyvault/common/internal/single_page.hpp> #include <azure/core/http/http.hpp> #include <vector> namespace Azure { namespace Security { namespace KeyVault { namespace Keys { struct KeyPropertiesSinglePage : public Azure::Security::KeyVault::_internal::SinglePage { std::vector<KeyProperties> Items; }; struct DeletedKeySinglePage : public Azure::Security::KeyVault::_internal::SinglePage { std::vector<DeletedKey> Items; }; struct GetPropertiesOfKeysSinglePageOptions : public Azure::Security::KeyVault::_internal::GetSinglePageOptions { }; struct GetPropertiesOfKeyVersionsSinglePageOptions : public Azure::Security::KeyVault::_internal::GetSinglePageOptions { }; struct GetDeletedKeysSinglePageOptions : public Azure::Security::KeyVault::_internal::GetSinglePageOptions { }; }}}} // namespace Azure::Security::KeyVault::Keys
25.285714
90
0.744149
kyle-patterson
c0079ed7063ed907c62eddf790c74875bf3186a6
3,895
cpp
C++
loop-functions/complexity/AggregationTwoSpotsXOR2.cpp
vvanpelt/experiments-loop-functions
1c2883b044a03df4a7fb6cd9e83376d0899df5c0
[ "MIT" ]
null
null
null
loop-functions/complexity/AggregationTwoSpotsXOR2.cpp
vvanpelt/experiments-loop-functions
1c2883b044a03df4a7fb6cd9e83376d0899df5c0
[ "MIT" ]
1
2020-10-19T09:16:29.000Z
2020-10-19T09:16:29.000Z
loop-functions/complexity/AggregationTwoSpotsXOR2.cpp
vvanpelt/experiments-loop-functions
1c2883b044a03df4a7fb6cd9e83376d0899df5c0
[ "MIT" ]
3
2019-09-18T09:47:42.000Z
2020-10-25T14:13:48.000Z
/** * @file <loop-functions/AggregationTwoSpotsLoopFunc.cpp> * * @author Antoine Ligot - <aligot@ulb.ac.be> * * @license MIT License */ #include "AggregationTwoSpotsXOR2.h" /****************************************/ /****************************************/ AggregationTwoSpotsXOR2::AggregationTwoSpotsXOR2() { m_fRadius = 0.3; m_cCoordSpot1 = CVector2(0.5,0); m_cCoordSpot2 = CVector2(-0.5,0); m_unScoreSpot1 = 0; m_unScoreSpot2 = 0; m_fObjectiveFunction = 0; } /****************************************/ /****************************************/ AggregationTwoSpotsXOR2::AggregationTwoSpotsXOR2(const AggregationTwoSpotsXOR2& orig) {} /****************************************/ /****************************************/ void AggregationTwoSpotsXOR2::Init(TConfigurationNode& t_tree) { CoreLoopFunctions::Init(t_tree); } /****************************************/ /****************************************/ AggregationTwoSpotsXOR2::~AggregationTwoSpotsXOR2() {} /****************************************/ /****************************************/ void AggregationTwoSpotsXOR2::Destroy() {} /****************************************/ /****************************************/ argos::CColor AggregationTwoSpotsXOR2::GetFloorColor(const argos::CVector2& c_position_on_plane) { CVector2 vCurrentPoint(c_position_on_plane.GetX(), c_position_on_plane.GetY()); Real d = (m_cCoordSpot1 - vCurrentPoint).Length(); if (d <= m_fRadius) { return CColor::BLACK; } d = (m_cCoordSpot2 - vCurrentPoint).Length(); if (d <= m_fRadius) { return CColor::BLACK; } return CColor::GRAY50; } /****************************************/ /****************************************/ void AggregationTwoSpotsXOR2::Reset() { m_fObjectiveFunction = 0; m_unScoreSpot1 = 0; m_unScoreSpot2 = 0; CoreLoopFunctions::Reset(); } /****************************************/ /****************************************/ void AggregationTwoSpotsXOR2::PostStep() { m_unScoreSpot1 = 0; m_unScoreSpot2 = 0; CSpace::TMapPerType& tEpuckMap = GetSpace().GetEntitiesByType("epuck"); CVector2 cEpuckPosition(0,0); for (CSpace::TMapPerType::iterator it = tEpuckMap.begin(); it != tEpuckMap.end(); ++it) { CEPuckEntity* pcEpuck = any_cast<CEPuckEntity*>(it->second); cEpuckPosition.Set(pcEpuck->GetEmbodiedEntity().GetOriginAnchor().Position.GetX(), pcEpuck->GetEmbodiedEntity().GetOriginAnchor().Position.GetY()); Real fDistanceSpot1 = (m_cCoordSpot1 - cEpuckPosition).Length(); Real fDistanceSpot2 = (m_cCoordSpot2 - cEpuckPosition).Length(); if (fDistanceSpot1 <= m_fRadius) { m_unScoreSpot1 += 1; } else if (fDistanceSpot2 <= m_fRadius){ m_unScoreSpot2 += 1; } } //LOG << "Sco1 = " << m_unScoreSpot1 << "Sco2 = " << m_unScoreSpot2 << std::endl; m_fObjectiveFunction += Max(m_unScoreSpot1, m_unScoreSpot2); } void AggregationTwoSpotsXOR2::PostExperiment() { LOG << "Score = " << m_fObjectiveFunction << std::endl; } /****************************************/ /****************************************/ Real AggregationTwoSpotsXOR2::GetObjectiveFunction() { return m_fObjectiveFunction; } /****************************************/ /****************************************/ CVector3 AggregationTwoSpotsXOR2::GetRandomPosition() { Real temp; Real a = m_pcRng->Uniform(CRange<Real>(0.0f, 1.0f)); Real b = m_pcRng->Uniform(CRange<Real>(0.0f, 1.0f)); // If b < a, swap them if (b < a) { temp = a; a = b; b = temp; } Real fPosX = b * m_fDistributionRadius * cos(2 * CRadians::PI.GetValue() * (a/b)); Real fPosY = b * m_fDistributionRadius * sin(2 * CRadians::PI.GetValue() * (a/b)); return CVector3(fPosX, fPosY, 0); } REGISTER_LOOP_FUNCTIONS(AggregationTwoSpotsXOR2, "aggregation_xor2");
29.732824
98
0.533504
vvanpelt
c007c9f642b1685202d19087dff8b3dbf161023e
3,502
cpp
C++
trview.app/UI/LevelInfo.cpp
chreden/trview
e2a5e3539036f27adfa54fc7fcf4c3537b99a221
[ "MIT" ]
20
2018-10-17T02:00:03.000Z
2022-03-24T09:37:20.000Z
trview.app/UI/LevelInfo.cpp
chreden/trview
e2a5e3539036f27adfa54fc7fcf4c3537b99a221
[ "MIT" ]
396
2018-07-22T16:11:47.000Z
2022-03-29T11:57:03.000Z
trview.app/UI/LevelInfo.cpp
chreden/trview
e2a5e3539036f27adfa54fc7fcf4c3537b99a221
[ "MIT" ]
8
2018-07-25T21:31:06.000Z
2021-11-01T14:36:26.000Z
#include "LevelInfo.h" #include <trview.ui/Control.h> #include <trview.ui/Image.h> #include <trview.ui/Label.h> #include <trview.ui/Button.h> #include <trview.app/Graphics/ITextureStorage.h> #include <trview.common/Strings.h> #include <trview.ui/Layouts/StackLayout.h> namespace trview { namespace { // Ideally this will be stored somewhere else. const std::unordered_map<trlevel::LevelVersion, std::string> texture_names { { trlevel::LevelVersion::Unknown, "unknown_icon" }, { trlevel::LevelVersion::Tomb1, "tomb1_icon" }, { trlevel::LevelVersion::Tomb2, "tomb2_icon" }, { trlevel::LevelVersion::Tomb3, "tomb3_icon" }, { trlevel::LevelVersion::Tomb4, "tomb4_icon" }, { trlevel::LevelVersion::Tomb5, "tomb5_icon" }, }; } LevelInfo::LevelInfo(ui::Control& control, const ITextureStorage& texture_storage) { for (const auto& tex : texture_names) { _version_textures.insert({ tex.first, texture_storage.lookup(tex.second) }); } using namespace ui; auto panel = std::make_unique<ui::Window>(Point(control.size().width / 2.0f - 50, 0), Size(100, 24), Colour(0.5f, 0.0f, 0.0f, 0.0f)); auto panel_layout = std::make_unique<StackLayout>(5.0f, StackLayout::Direction::Horizontal); panel_layout->set_margin(Size(5, 5)); panel->set_layout(std::move(panel_layout)); auto version = std::make_unique<Image>(Size(16, 16)); version->set_background_colour(Colour(0, 0, 0, 0)); version->set_texture(get_version_image(trlevel::LevelVersion::Unknown)); auto name = std::make_unique<Label>(Size(74, 16), Colour::Transparent, L"No level", 8, graphics::TextAlignment::Centre, graphics::ParagraphAlignment::Centre, SizeMode::Auto); name->set_vertical_alignment(Align::Centre); auto settings = std::make_unique<Button>(Size(16, 16), texture_storage.lookup("settings"), texture_storage.lookup("settings")); settings->on_click += on_toggle_settings; _version = panel->add_child(std::move(version)); _name = panel->add_child(std::move(name)); panel->add_child(std::move(settings)); _panel = control.add_child(std::move(panel)); // Have the control move itself when the parent control resizes. _token_store += control.on_size_changed += [&](const Size& size) { _panel->set_position(Point(size.width / 2.0f - _panel->size().width / 2.0f, 0)); }; _token_store += _panel->on_size_changed += [&](const Size& size) { auto parent = _panel->parent(); _panel->set_position(Point(parent->size().width / 2.0f - size.width / 2.0f, 0)); }; } // Set the name of the level. // name: The level name. void LevelInfo::set_level(const std::string& name) { _name->set_text(to_utf16(name)); } // Set the version of the game that level was created for. // version: The version of the game. void LevelInfo::set_level_version(trlevel::LevelVersion version) { _version->set_texture(get_version_image(version)); } graphics::Texture LevelInfo::get_version_image(trlevel::LevelVersion version) const { auto found = _version_textures.find(version); if (found == _version_textures.end()) { return graphics::Texture(); } return found->second; } }
39.348315
182
0.632496
chreden
c00a9aaf693e37d05c3ad752b308900ba185993e
696
cpp
C++
ciao/Valuetype_Factories/ConfigValue.cpp
qinwang13/CIAO
e69add1b5da8e9602bcc85d581ecbf1bd41c49a3
[ "DOC" ]
10
2016-07-20T00:55:50.000Z
2020-10-04T19:07:10.000Z
ciao/Valuetype_Factories/ConfigValue.cpp
qinwang13/CIAO
e69add1b5da8e9602bcc85d581ecbf1bd41c49a3
[ "DOC" ]
13
2016-09-27T14:08:27.000Z
2020-11-11T10:45:56.000Z
ciao/Valuetype_Factories/ConfigValue.cpp
qinwang13/CIAO
e69add1b5da8e9602bcc85d581ecbf1bd41c49a3
[ "DOC" ]
12
2016-04-20T09:57:02.000Z
2021-12-24T17:23:45.000Z
#include "ConfigValue.h" namespace CIAO { ConfigValue_impl::ConfigValue_impl() { CORBA::Any any; any <<= CORBA::Short(0); name((const char*)""); value(any); } ConfigValue_impl::ConfigValue_impl(const char* the_name, const CORBA::Any& the_value) : OBV_Components::ConfigValue(the_name, the_value) { } CORBA::ValueBase* ConfigValue_impl::_copy_value() { return new ConfigValue_impl(name(),value()); } ConfigValue_impl::~ConfigValue_impl() throw () { } CORBA::ValueBase * ConfigValueFactory::create_for_unmarshal () { return new ConfigValue_impl(); } }
19.333333
66
0.591954
qinwang13
c00b1bfcbd5a80da4131b8581744b9026f53c63c
4,168
cpp
C++
igl/setdiff.cpp
sabinaRachev/3D-Snake-Game-Final-Project
5c1f2044d848f24d6ce60dc61411393b503c8da2
[ "Apache-2.0" ]
null
null
null
igl/setdiff.cpp
sabinaRachev/3D-Snake-Game-Final-Project
5c1f2044d848f24d6ce60dc61411393b503c8da2
[ "Apache-2.0" ]
null
null
null
igl/setdiff.cpp
sabinaRachev/3D-Snake-Game-Final-Project
5c1f2044d848f24d6ce60dc61411393b503c8da2
[ "Apache-2.0" ]
null
null
null
// This file is part of libigl, a simple c++ geometry processing library. // // Copyright (C) 2014 Alec Jacobson <alecjacobson@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla Public License // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. #include "setdiff.h" #include "LinSpaced.h" #include "list_to_matrix.h" #include "sort.h" #include "unique.h" template < typename DerivedA, typename DerivedB, typename DerivedC, typename DerivedIA> IGL_INLINE void igl::setdiff( const Eigen::DenseBase<DerivedA> & A, const Eigen::DenseBase<DerivedB> & B, Eigen::PlainObjectBase<DerivedC> & C, Eigen::PlainObjectBase<DerivedIA> & IA) { using namespace Eigen; using namespace std; // boring base cases if(A.size() == 0) { C.resize(0,1); IA.resize(0,1); return; } // Get rid of any duplicates typedef Matrix<typename DerivedA::Scalar,Dynamic,1> VectorA; typedef Matrix<typename DerivedB::Scalar,Dynamic,1> VectorB; VectorA uA; VectorB uB; typedef DerivedIA IAType; IAType uIA,uIuA,uIB,uIuB; unique(A,uA,uIA,uIuA); unique(B,uB,uIB,uIuB); // Sort both VectorA sA; VectorB sB; IAType sIA,sIB; sort(uA,1,true,sA,sIA); sort(uB,1,true,sB,sIB); vector<typename DerivedB::Scalar> vC; vector<typename DerivedIA::Scalar> vIA; int bi = 0; // loop over sA bool past = false; bool sBempty = sB.size()==0; for(int a = 0;a<sA.size();a++) { while(!sBempty && !past && sA(a)>sB(bi)) { bi++; past = bi>=sB.size(); } if(sBempty || past || sA(a)<sB(bi)) { // then sA(a) did not appear in sB vC.push_back(sA(a)); vIA.push_back(uIA(sIA(a))); } } list_to_matrix(vC,C); list_to_matrix(vIA,IA); } #ifdef IGL_STATIC_LIBRARY // Explicit template instantiation // generated by autoexplicit.sh template void igl::setdiff<Eigen::Matrix<int, -1, 2, 0, -1, 2>, Eigen::Matrix<int, -1, 2, 0, -1, 2>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::DenseBase<Eigen::Matrix<int, -1, 2, 0, -1, 2> > const&, Eigen::DenseBase<Eigen::Matrix<int, -1, 2, 0, -1, 2> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&); template void igl::setdiff<Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::DenseBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> > const&, Eigen::DenseBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&); template void igl::setdiff<Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::DenseBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> > const&, Eigen::DenseBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&); template void igl::setdiff<Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::DenseBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::DenseBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&); template void igl::setdiff<Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::DenseBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::DenseBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&); #endif
49.035294
445
0.605086
sabinaRachev
c00eb2d2ed08883c3a53bb4a5fe447747aa9cd04
6,526
cpp
C++
classes/graphics/backends/gdiplus/bitmapgdiplus.cpp
XilizaX/smooth
a65851f3bc9f83860e404bebe224d28388025625
[ "Artistic-2.0" ]
null
null
null
classes/graphics/backends/gdiplus/bitmapgdiplus.cpp
XilizaX/smooth
a65851f3bc9f83860e404bebe224d28388025625
[ "Artistic-2.0" ]
null
null
null
classes/graphics/backends/gdiplus/bitmapgdiplus.cpp
XilizaX/smooth
a65851f3bc9f83860e404bebe224d28388025625
[ "Artistic-2.0" ]
null
null
null
/* The smooth Class Library * Copyright (C) 1998-2020 Robert Kausch <robert.kausch@gmx.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of "The Artistic License, Version 2.0". * * THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include <smooth/graphics/backends/gdiplus/bitmapgdiplus.h> S::GUI::BitmapBackend *CreateBitmapGDIPlus_pV(S::Void *iBitmap) { return new S::GUI::BitmapGDIPlus(iBitmap); } S::GUI::BitmapBackend *CreateBitmapGDIPlus_crSI(const S::GUI::Size &iSize, S::Int iDepth) { return new S::GUI::BitmapGDIPlus(iSize, iDepth); } S::GUI::BitmapBackend *CreateBitmapGDIPlus_cI(const int nil) { return new S::GUI::BitmapGDIPlus(nil); } S::GUI::BitmapBackend *CreateBitmapGDIPlus_crB(const S::GUI::BitmapBackend &iBitmap) { return new S::GUI::BitmapGDIPlus((const S::GUI::BitmapGDIPlus &) iBitmap); } S::Int bitmapGDIPlusTmp_pV = S::GUI::BitmapBackend::SetBackend(&CreateBitmapGDIPlus_pV); S::Int bitmapGDIPlusTmp_crSI = S::GUI::BitmapBackend::SetBackend(&CreateBitmapGDIPlus_crSI); S::Int bitmapGDIPlusTmp_cI = S::GUI::BitmapBackend::SetBackend(&CreateBitmapGDIPlus_cI); S::Int bitmapGDIPlusTmp_crB = S::GUI::BitmapBackend::SetBackend(&CreateBitmapGDIPlus_crB); S::GUI::BitmapGDIPlus::BitmapGDIPlus(Void *iBitmap) { type = BITMAP_GDIPLUS; bitmap = NIL; hBitmap = NIL; SetSystemBitmap(iBitmap); } S::GUI::BitmapGDIPlus::BitmapGDIPlus(const Size &iSize, Int iDepth) { type = BITMAP_GDIPLUS; bitmap = NIL; hBitmap = NIL; CreateBitmap(iSize, iDepth); } S::GUI::BitmapGDIPlus::BitmapGDIPlus(const int nil) { type = BITMAP_GDIPLUS; bitmap = NIL; hBitmap = NIL; SetSystemBitmap(NIL); } S::GUI::BitmapGDIPlus::BitmapGDIPlus(const BitmapGDIPlus &iBitmap) { type = BITMAP_GDIPLUS; bitmap = NIL; hBitmap = NIL; if (iBitmap != NIL) { CreateBitmap(iBitmap.GetSize(), iBitmap.GetDepth()); memcpy(bytes, iBitmap.GetBytes(), (bpp / 8) * size.cx * size.cy); } } S::GUI::BitmapGDIPlus::~BitmapGDIPlus() { DeleteBitmap(); } S::Bool S::GUI::BitmapGDIPlus::CreateBitmap(const Size &nSize, Int nDepth) { DeleteBitmap(); if (nDepth == -1) nDepth = 32; if (nDepth != 32) nDepth = 32; UnsignedByte *buffer = new UnsignedByte [sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD)]; BITMAPINFO *bmpInfo = (BITMAPINFO *) buffer; bmpInfo->bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmpInfo->bmiHeader.biWidth = nSize.cx; bmpInfo->bmiHeader.biHeight = nSize.cy; bmpInfo->bmiHeader.biPlanes = 1; bmpInfo->bmiHeader.biBitCount = nDepth; bmpInfo->bmiHeader.biCompression = BI_RGB; bmpInfo->bmiHeader.biSizeImage = 0; bmpInfo->bmiHeader.biXPelsPerMeter = 0; bmpInfo->bmiHeader.biYPelsPerMeter = 0; bmpInfo->bmiHeader.biClrUsed = 0; bmpInfo->bmiHeader.biClrImportant = 0; bmpInfo->bmiColors[0].rgbBlue = 0; bmpInfo->bmiColors[0].rgbGreen = 0; bmpInfo->bmiColors[0].rgbRed = 0; bmpInfo->bmiColors[0].rgbReserved = 0; bytes = new UnsignedByte [(nDepth / 8) * nSize.cx * nSize.cy]; bitmap = new Gdiplus::Bitmap(bmpInfo, bytes); delete [] buffer; if (bitmap == NIL) return False; size = nSize; depth = nDepth; bpp = depth; align = 4; return True; } S::Bool S::GUI::BitmapGDIPlus::DeleteBitmap() { if (bitmap != NIL) { delete bitmap; if (hBitmap != NIL) ::DeleteObject(hBitmap); bitmap = NIL; hBitmap = NIL; size = Size(0, 0); depth = 0; delete [] (UnsignedByte *) bytes; bytes = NIL; bpp = 0; align = 0; } return True; } S::Bool S::GUI::BitmapGDIPlus::SetSystemBitmap(Void *nBitmap) { if (nBitmap == NIL) { DeleteBitmap(); } else { BITMAP bmp; GetObject(nBitmap, sizeof(bmp), &bmp); HBITMAP oBitmap = hBitmap; hBitmap = NIL; CreateBitmap(Size(bmp.bmWidth, bmp.bmHeight), bmp.bmBitsPixel); Gdiplus::Graphics graphics(bitmap); Gdiplus::Bitmap nBitmapB((HBITMAP) nBitmap, NIL); graphics.DrawImage(&nBitmapB, 0, 0, bmp.bmWidth, bmp.bmHeight); if (oBitmap != NIL) ::DeleteObject(oBitmap); } return True; } S::Void *S::GUI::BitmapGDIPlus::GetSystemBitmap() const { if (bitmap == NIL) return NIL; if (hBitmap != NIL) ::DeleteObject(hBitmap); bitmap->GetHBITMAP(Gdiplus::Color(255, 255, 255), &hBitmap); return (Void *) hBitmap; } S::Bool S::GUI::BitmapGDIPlus::SetPixel(const Point &point, const Color &iColor) { if (bytes == NIL) return False; if (point.y >= size.cy || point.x >= size.cx) return False; Color color = iColor.ConvertTo(Color::RGBA); UnsignedByte *data = ((UnsignedByte *) bytes); Int offset = 0; switch (depth) { case 24: offset = (size.cy - point.y - 1) * (((4 - ((size.cx * 3) & 3)) & 3) + size.cx * 3) + point.x * 3; data[offset + 0] = (color >> 16) & 255; data[offset + 1] = (color >> 8) & 255; data[offset + 2] = color & 255; return True; case 32: offset = (size.cy - point.y - 1) * ( size.cx * 4) + point.x * 4; data[offset + 0] = (color >> 16) & 255; data[offset + 1] = (color >> 8) & 255; data[offset + 2] = color & 255; data[offset + 3] = (color >> 24) & 255; return True; } return False; } S::GUI::Color S::GUI::BitmapGDIPlus::GetPixel(const Point &point) const { if (bytes == NIL) return 0; if (point.y >= size.cy || point.x >= size.cx) return 0; UnsignedByte *data = ((UnsignedByte *) bytes); Int offset = 0; switch (depth) { case 24: offset = (size.cy - point.y - 1) * (((4 - ((size.cx * 3) & 3)) & 3) + size.cx * 3) + point.x * 3; return Color( data[offset + 0] << 16 | data[offset + 1] << 8 | data[offset + 2], Color::RGB); case 32: offset = (size.cy - point.y - 1) * ( size.cx * 4) + point.x * 4; return Color(data[offset + 3] << 24 | data[offset + 0] << 16 | data[offset + 1] << 8 | data[offset + 2], Color::RGBA); } return 0; } S::GUI::BitmapBackend &S::GUI::BitmapGDIPlus::operator =(const BitmapBackend &newBitmap) { if (&newBitmap == this) return *this; DeleteBitmap(); if (newBitmap != NIL) { CreateBitmap(newBitmap.GetSize(), newBitmap.GetDepth()); memcpy(bytes, newBitmap.GetBytes(), (bpp / 8) * size.cx * size.cy); } return *this; } S::Bool S::GUI::BitmapGDIPlus::operator ==(const int nil) const { if (bitmap == NIL) return True; else return False; } S::Bool S::GUI::BitmapGDIPlus::operator !=(const int nil) const { if (bitmap == NIL) return False; else return True; }
23.992647
121
0.661355
XilizaX
84ffa253eede71ab5e074ab6ff435953756310e2
1,252
cpp
C++
src/caffe/layers/gradient_reversal_layer.cpp
Andeling/caffe_unet
f713104e5c76eea1b618b21b3a3f303dd673081c
[ "Intel", "BSD-2-Clause" ]
null
null
null
src/caffe/layers/gradient_reversal_layer.cpp
Andeling/caffe_unet
f713104e5c76eea1b618b21b3a3f303dd673081c
[ "Intel", "BSD-2-Clause" ]
null
null
null
src/caffe/layers/gradient_reversal_layer.cpp
Andeling/caffe_unet
f713104e5c76eea1b618b21b3a3f303dd673081c
[ "Intel", "BSD-2-Clause" ]
null
null
null
#include <algorithm> #include <vector> #include "caffe/layer.hpp" #include "caffe/util/math_functions.hpp" #include "caffe/layers/gradient_reversal_layer.hpp" namespace caffe { template <typename Dtype> void GradientReversalLayer<Dtype>::LayerSetUp( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { NeuronLayer<Dtype>::LayerSetUp(bottom, top); } template <typename Dtype> void GradientReversalLayer<Dtype>::Forward_cpu( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { caffe_copy( bottom[0]->count(), bottom[0]->cpu_data(), top[0]->mutable_cpu_data()); } template <typename Dtype> void GradientReversalLayer<Dtype>::Backward_cpu( const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { if (propagate_down[0]) { const Dtype* top_diff = top[0]->cpu_diff(); Dtype* bottom_diff = bottom[0]->mutable_cpu_diff(); caffe_set(bottom[0]->count(), Dtype(-1.0), bottom_diff); caffe_mul(bottom[0]->count(), top_diff, bottom_diff, bottom_diff); } } #ifdef CPU_ONLY STUB_GPU(GradientReversalLayer); #endif INSTANTIATE_CLASS(GradientReversalLayer); REGISTER_LAYER_CLASS(GradientReversal); } // namespace caffe
27.822222
77
0.722843
Andeling
17000129d350c2531e083b4dfb9559186d243404
19,067
cpp
C++
src/geometry_aux.cpp
cjwyett/openmc
a9e85f4d5b59d133c17caccf4704a032184841d4
[ "MIT" ]
1
2020-02-07T20:23:33.000Z
2020-02-07T20:23:33.000Z
src/geometry_aux.cpp
cjwyett/openmc
a9e85f4d5b59d133c17caccf4704a032184841d4
[ "MIT" ]
3
2020-05-22T07:57:36.000Z
2021-05-21T17:34:35.000Z
src/geometry_aux.cpp
cjwyett/openmc
a9e85f4d5b59d133c17caccf4704a032184841d4
[ "MIT" ]
null
null
null
#include "openmc/geometry_aux.h" #include <algorithm> // for std::max #include <sstream> #include <unordered_set> #include <fmt/core.h> #include <pugixml.hpp> #include "openmc/cell.h" #include "openmc/constants.h" #include "openmc/container_util.h" #include "openmc/dagmc.h" #include "openmc/error.h" #include "openmc/file_utils.h" #include "openmc/geometry.h" #include "openmc/lattice.h" #include "openmc/material.h" #include "openmc/settings.h" #include "openmc/surface.h" #include "openmc/tallies/filter.h" #include "openmc/tallies/filter_cell_instance.h" #include "openmc/tallies/filter_distribcell.h" namespace openmc { namespace model { std::unordered_map<int32_t, std::unordered_map<int32_t, int32_t>> universe_cell_counts; std::unordered_map<int32_t, int32_t> universe_level_counts; } // namespace model // adds the cell counts of universe b to universe a void update_universe_cell_count(int32_t a, int32_t b) { auto& universe_a_counts = model::universe_cell_counts[a]; const auto& universe_b_counts = model::universe_cell_counts[b]; for (const auto& it : universe_b_counts) { universe_a_counts[it.first] += it.second; } } void read_geometry_xml() { #ifdef DAGMC if (settings::dagmc) { read_geometry_dagmc(); return; } #endif // Display output message write_message("Reading geometry XML file...", 5); // Check if geometry.xml exists std::string filename = settings::path_input + "geometry.xml"; if (!file_exists(filename)) { fatal_error("Geometry XML file '" + filename + "' does not exist!"); } // Parse settings.xml file pugi::xml_document doc; auto result = doc.load_file(filename.c_str()); if (!result) { fatal_error("Error processing geometry.xml file."); } // Get root element pugi::xml_node root = doc.document_element(); // Read surfaces, cells, lattice read_surfaces(root); read_cells(root); read_lattices(root); // Allocate universes, universe cell arrays, and assign base universe model::root_universe = find_root_universe(); } //============================================================================== void adjust_indices() { // Adjust material/fill idices. for (auto& c : model::cells) { if (c->fill_ != C_NONE) { int32_t id = c->fill_; auto search_univ = model::universe_map.find(id); auto search_lat = model::lattice_map.find(id); if (search_univ != model::universe_map.end()) { c->type_ = Fill::UNIVERSE; c->fill_ = search_univ->second; } else if (search_lat != model::lattice_map.end()) { c->type_ = Fill::LATTICE; c->fill_ = search_lat->second; } else { fatal_error(fmt::format("Specified fill {} on cell {} is neither a " "universe nor a lattice.", id, c->id_)); } } else { c->type_ = Fill::MATERIAL; for (auto& mat_id : c->material_) { if (mat_id != MATERIAL_VOID) { auto search = model::material_map.find(mat_id); if (search == model::material_map.end()) { fatal_error(fmt::format( "Could not find material {} specified on cell {}", mat_id, c->id_)); } // Change from ID to index mat_id = search->second; } } } } // Change cell.universe values from IDs to indices. for (auto& c : model::cells) { auto search = model::universe_map.find(c->universe_); if (search != model::universe_map.end()) { c->universe_ = search->second; } else { fatal_error(fmt::format("Could not find universe {} specified on cell {}", c->universe_, c->id_)); } } // Change all lattice universe values from IDs to indices. for (auto& l : model::lattices) { l->adjust_indices(); } } //============================================================================== //! Partition some universes with many z-planes for faster find_cell searches. void partition_universes() { // Iterate over universes with more than 10 cells. (Fewer than 10 is likely // not worth partitioning.) for (const auto& univ : model::universes) { if (univ->cells_.size() > 10) { // Collect the set of surfaces in this universe. std::unordered_set<int32_t> surf_inds; for (auto i_cell : univ->cells_) { for (auto token : model::cells[i_cell]->rpn_) { if (token < OP_UNION) surf_inds.insert(std::abs(token) - 1); } } // Partition the universe if there are more than 5 z-planes. (Fewer than // 5 is likely not worth it.) int n_zplanes = 0; for (auto i_surf : surf_inds) { if (dynamic_cast<const SurfaceZPlane*>(model::surfaces[i_surf].get())) { ++n_zplanes; if (n_zplanes > 5) { univ->partitioner_ = make_unique<UniversePartitioner>(*univ); break; } } } } } } //============================================================================== void assign_temperatures() { for (auto& c : model::cells) { // Ignore non-material cells and cells with defined temperature. if (c->material_.size() == 0) continue; if (c->sqrtkT_.size() > 0) continue; c->sqrtkT_.reserve(c->material_.size()); for (auto i_mat : c->material_) { if (i_mat == MATERIAL_VOID) { // Set void region to 0K. c->sqrtkT_.push_back(0); } else { const auto& mat {model::materials[i_mat]}; c->sqrtkT_.push_back(std::sqrt(K_BOLTZMANN * mat->temperature())); } } } } //============================================================================== void get_temperatures( vector<vector<double>>& nuc_temps, vector<vector<double>>& thermal_temps) { for (const auto& cell : model::cells) { // Skip non-material cells. if (cell->fill_ != C_NONE) continue; for (int j = 0; j < cell->material_.size(); ++j) { // Skip void materials int i_material = cell->material_[j]; if (i_material == MATERIAL_VOID) continue; // Get temperature(s) of cell (rounding to nearest integer) vector<double> cell_temps; if (cell->sqrtkT_.size() == 1) { double sqrtkT = cell->sqrtkT_[0]; cell_temps.push_back(sqrtkT*sqrtkT / K_BOLTZMANN); } else if (cell->sqrtkT_.size() == cell->material_.size()) { double sqrtkT = cell->sqrtkT_[j]; cell_temps.push_back(sqrtkT*sqrtkT / K_BOLTZMANN); } else { for (double sqrtkT : cell->sqrtkT_) cell_temps.push_back(sqrtkT*sqrtkT / K_BOLTZMANN); } const auto& mat {model::materials[i_material]}; for (const auto& i_nuc : mat->nuclide_) { for (double temperature : cell_temps) { // Add temperature if it hasn't already been added if (!contains(nuc_temps[i_nuc], temperature)) nuc_temps[i_nuc].push_back(temperature); } } for (const auto& table : mat->thermal_tables_) { // Get index in data::thermal_scatt array int i_sab = table.index_table; for (double temperature : cell_temps) { // Add temperature if it hasn't already been added if (!contains(thermal_temps[i_sab], temperature)) thermal_temps[i_sab].push_back(temperature); } } } } } //============================================================================== void finalize_geometry() { // Perform some final operations to set up the geometry adjust_indices(); count_cell_instances(model::root_universe); partition_universes(); // Assign temperatures to cells that don't have temperatures already assigned assign_temperatures(); // Determine number of nested coordinate levels in the geometry model::n_coord_levels = maximum_levels(model::root_universe); } //============================================================================== int32_t find_root_universe() { // Find all the universes listed as a cell fill. std::unordered_set<int32_t> fill_univ_ids; for (const auto& c : model::cells) { fill_univ_ids.insert(c->fill_); } // Find all the universes contained in a lattice. for (const auto& lat : model::lattices) { for (auto it = lat->begin(); it != lat->end(); ++it) { fill_univ_ids.insert(*it); } if (lat->outer_ != NO_OUTER_UNIVERSE) { fill_univ_ids.insert(lat->outer_); } } // Figure out which universe is not in the set. This is the root universe. bool root_found {false}; int32_t root_univ; for (int32_t i = 0; i < model::universes.size(); i++) { auto search = fill_univ_ids.find(model::universes[i]->id_); if (search == fill_univ_ids.end()) { if (root_found) { fatal_error("Two or more universes are not used as fill universes, so " "it is not possible to distinguish which one is the root " "universe."); } else { root_found = true; root_univ = i; } } } if (!root_found) fatal_error("Could not find a root universe. Make sure " "there are no circular dependencies in the geometry."); return root_univ; } //============================================================================== void prepare_distribcell() { write_message("Preparing distributed cell instances...", 5); // Find all cells listed in a DistribcellFilter or CellInstanceFilter std::unordered_set<int32_t> distribcells; for (auto& filt : model::tally_filters) { auto* distrib_filt = dynamic_cast<DistribcellFilter*>(filt.get()); if (distrib_filt) { distribcells.insert(distrib_filt->cell()); } } // By default, add material cells to the list of distributed cells if (settings::material_cell_offsets) { for (gsl::index i = 0; i < model::cells.size(); ++i) { if (model::cells[i]->type_ == Fill::MATERIAL) distribcells.insert(i); } } // Make sure that the number of materials/temperatures matches the number of // cell instances. for (int i = 0; i < model::cells.size(); i++) { Cell& c {*model::cells[i]}; if (c.material_.size() > 1) { if (c.material_.size() != c.n_instances_) { fatal_error(fmt::format( "Cell {} was specified with {} materials but has {} distributed " "instances. The number of materials must equal one or the number " "of instances.", c.id_, c.material_.size(), c.n_instances_ )); } } if (c.sqrtkT_.size() > 1) { if (c.sqrtkT_.size() != c.n_instances_) { fatal_error(fmt::format( "Cell {} was specified with {} temperatures but has {} distributed " "instances. The number of temperatures must equal one or the number " "of instances.", c.id_, c.sqrtkT_.size(), c.n_instances_ )); } } } // Search through universes for material cells and assign each one a // unique distribcell array index. int distribcell_index = 0; vector<int32_t> target_univ_ids; for (const auto& u : model::universes) { for (auto idx : u->cells_) { if (distribcells.find(idx) != distribcells.end()) { model::cells[idx]->distribcell_index_ = distribcell_index++; target_univ_ids.push_back(u->id_); } } } // Allocate the cell and lattice offset tables. int n_maps = target_univ_ids.size(); for (auto& c : model::cells) { if (c->type_ != Fill::MATERIAL) { c->offset_.resize(n_maps, C_NONE); } } for (auto& lat : model::lattices) { lat->allocate_offset_table(n_maps); } // Fill the cell and lattice offset tables. #pragma omp parallel for for (int map = 0; map < target_univ_ids.size(); map++) { auto target_univ_id = target_univ_ids[map]; std::unordered_map<int32_t, int32_t> univ_count_memo; for (const auto& univ : model::universes) { int32_t offset = 0; for (int32_t cell_indx : univ->cells_) { Cell& c = *model::cells[cell_indx]; if (c.type_ == Fill::UNIVERSE) { c.offset_[map] = offset; int32_t search_univ = c.fill_; offset += count_universe_instances(search_univ, target_univ_id, univ_count_memo); } else if (c.type_ == Fill::LATTICE) { Lattice& lat = *model::lattices[c.fill_]; offset = lat.fill_offset_table(offset, target_univ_id, map, univ_count_memo); } } } } } //============================================================================== void count_cell_instances(int32_t univ_indx) { const auto univ_counts = model::universe_cell_counts.find(univ_indx); if (univ_counts != model::universe_cell_counts.end()) { for (const auto& it : univ_counts->second) { model::cells[it.first]->n_instances_ += it.second; } } else { for (int32_t cell_indx : model::universes[univ_indx]->cells_) { Cell& c = *model::cells[cell_indx]; ++c.n_instances_; model::universe_cell_counts[univ_indx][cell_indx] += 1; if (c.type_ == Fill::UNIVERSE) { // This cell contains another universe. Recurse into that universe. count_cell_instances(c.fill_); update_universe_cell_count(univ_indx, c.fill_); } else if (c.type_ == Fill::LATTICE) { // This cell contains a lattice. Recurse into the lattice universes. Lattice& lat = *model::lattices[c.fill_]; for (auto it = lat.begin(); it != lat.end(); ++it) { count_cell_instances(*it); update_universe_cell_count(univ_indx, *it); } } } } } //============================================================================== int count_universe_instances(int32_t search_univ, int32_t target_univ_id, std::unordered_map<int32_t, int32_t>& univ_count_memo) { // If this is the target, it can't contain itself. if (model::universes[search_univ]->id_ == target_univ_id) { return 1; } // If we have already counted the number of instances, reuse that value. auto search = univ_count_memo.find(search_univ); if (search != univ_count_memo.end()) { return search->second; } int count {0}; for (int32_t cell_indx : model::universes[search_univ]->cells_) { Cell& c = *model::cells[cell_indx]; if (c.type_ == Fill::UNIVERSE) { int32_t next_univ = c.fill_; count += count_universe_instances(next_univ, target_univ_id, univ_count_memo); } else if (c.type_ == Fill::LATTICE) { Lattice& lat = *model::lattices[c.fill_]; for (auto it = lat.begin(); it != lat.end(); ++it) { int32_t next_univ = *it; count += count_universe_instances(next_univ, target_univ_id, univ_count_memo); } } } // Remember the number of instances in this universe. univ_count_memo[search_univ] = count; return count; } //============================================================================== std::string distribcell_path_inner(int32_t target_cell, int32_t map, int32_t target_offset, const Universe& search_univ, int32_t offset) { std::stringstream path; path << "u" << search_univ.id_ << "->"; // Check to see if this universe directly contains the target cell. If so, // write to the path and return. for (int32_t cell_indx : search_univ.cells_) { if ((cell_indx == target_cell) && (offset == target_offset)) { Cell& c = *model::cells[cell_indx]; path << "c" << c.id_; return path.str(); } } // The target must be further down the geometry tree and contained in a fill // cell or lattice cell in this universe. Find which cell contains the // target. vector<std::int32_t>::const_reverse_iterator cell_it { search_univ.cells_.crbegin()}; for (; cell_it != search_univ.cells_.crend(); ++cell_it) { Cell& c = *model::cells[*cell_it]; // Material cells don't contain other cells so ignore them. if (c.type_ != Fill::MATERIAL) { int32_t temp_offset; if (c.type_ == Fill::UNIVERSE) { temp_offset = offset + c.offset_[map]; } else { Lattice& lat = *model::lattices[c.fill_]; int32_t indx = lat.universes_.size()*map + lat.begin().indx_; temp_offset = offset + lat.offsets_[indx]; } // The desired cell is the first cell that gives an offset smaller or // equal to the target offset. if (temp_offset <= target_offset) break; } } // Add the cell to the path string. Cell& c = *model::cells[*cell_it]; path << "c" << c.id_ << "->"; if (c.type_ == Fill::UNIVERSE) { // Recurse into the fill cell. offset += c.offset_[map]; path << distribcell_path_inner(target_cell, map, target_offset, *model::universes[c.fill_], offset); return path.str(); } else { // Recurse into the lattice cell. Lattice& lat = *model::lattices[c.fill_]; path << "l" << lat.id_; for (ReverseLatticeIter it = lat.rbegin(); it != lat.rend(); ++it) { int32_t indx = lat.universes_.size()*map + it.indx_; int32_t temp_offset = offset + lat.offsets_[indx]; if (temp_offset <= target_offset) { offset = temp_offset; path << "(" << lat.index_to_string(it.indx_) << ")->"; path << distribcell_path_inner(target_cell, map, target_offset, *model::universes[*it], offset); return path.str(); } } throw std::runtime_error{"Error determining distribcell path."}; } } std::string distribcell_path(int32_t target_cell, int32_t map, int32_t target_offset) { auto& root_univ = *model::universes[model::root_universe]; return distribcell_path_inner(target_cell, map, target_offset, root_univ, 0); } //============================================================================== int maximum_levels(int32_t univ) { const auto level_count = model::universe_level_counts.find(univ); if (level_count != model::universe_level_counts.end()) { return level_count->second; } int levels_below {0}; for (int32_t cell_indx : model::universes[univ]->cells_) { Cell& c = *model::cells[cell_indx]; if (c.type_ == Fill::UNIVERSE) { int32_t next_univ = c.fill_; levels_below = std::max(levels_below, maximum_levels(next_univ)); } else if (c.type_ == Fill::LATTICE) { Lattice& lat = *model::lattices[c.fill_]; for (auto it = lat.begin(); it != lat.end(); ++it) { int32_t next_univ = *it; levels_below = std::max(levels_below, maximum_levels(next_univ)); } } } ++levels_below; model::universe_level_counts[univ] = levels_below; return levels_below; } //============================================================================== void free_memory_geometry() { model::cells.clear(); model::cell_map.clear(); model::universes.clear(); model::universe_map.clear(); model::lattices.clear(); model::lattice_map.clear(); model::overlap_check_count.clear(); } } // namespace openmc
31.515702
89
0.595532
cjwyett
17038b166a022ef36b6c3fef388c40bc91b39e4c
1,647
cpp
C++
#002.cpp
LiFantastic/LeetCode
ed7a25b96595531009e55de9aeebe758ca0734d2
[ "Apache-2.0" ]
null
null
null
#002.cpp
LiFantastic/LeetCode
ed7a25b96595531009e55de9aeebe758ca0734d2
[ "Apache-2.0" ]
null
null
null
#002.cpp
LiFantastic/LeetCode
ed7a25b96595531009e55de9aeebe758ca0734d2
[ "Apache-2.0" ]
null
null
null
/*============================================================ Problem: Add Two Numbers ============================================================== You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 ============================================================*/ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode *dummyl3=new ListNode(0), *p1=l1, *p2=l2, *p3=dummyl3; int num, carry=0; while (p1 && p2) { num = p1->val+p2->val+carry; if (num > 9) { num -= 10; carry = 1; } else carry = 0; p3->next = new ListNode(num); p1 = p1->next; p2 = p2->next; p3 = p3->next; } p1 = (p1) ? p1 : p2; while (p1) { num = p1->val+carry; if (num > 9) { num -= 10; carry = 1; } else carry = 0; p3->next = new ListNode(num); p1 = p1->next; p3 = p3->next; } if (carry == 1) p3->next = new ListNode(1); p3 = dummyl3->next; delete dummyl3; return p3; } };
27.915254
71
0.399514
LiFantastic
1703d219b1823a709eef4fa5148b44b6aa1ec0eb
2,074
cxx
C++
Utilities/Benchmarks/TimingTests.cxx
stephansmit/VTK
caa1eabb4612a0253171723bd1f1ddc599d7eea8
[ "BSD-3-Clause" ]
3
2015-07-28T18:07:50.000Z
2018-02-28T20:59:58.000Z
Utilities/Benchmarks/TimingTests.cxx
AndyJMR/VTK
3cc9e5f7539107e5dbaeadc2d28f7a8db6de8571
[ "BSD-3-Clause" ]
null
null
null
Utilities/Benchmarks/TimingTests.cxx
AndyJMR/VTK
3cc9e5f7539107e5dbaeadc2d28f7a8db6de8571
[ "BSD-3-Clause" ]
4
2016-09-08T02:11:00.000Z
2019-08-15T02:38:39.000Z
/*========================================================================= Program: Visualization Toolkit Module: Timingtests.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. =========================================================================*/ /* To add a test you must define a subclass of vtkRTTest and implement the pure virtual functions. Then in the main section at the bottom of this file add your test to the tests to be run and rebuild. See some of the existing tests to get an idea of what to do. */ #include "vtkRenderTimingTests.h" /*========================================================================= The main entry point =========================================================================*/ int main( int argc, char *argv[] ) { // create the timing framework vtkRenderTimings a; // add the tests a.TestsToRun.push_back(new surfaceTest("Surface", false, false)); a.TestsToRun.push_back(new surfaceTest("SurfaceColored", true, false)); a.TestsToRun.push_back(new surfaceTest("SurfaceWithNormals", false, true)); a.TestsToRun.push_back( new surfaceTest("SurfaceColoredWithNormals", true, true)); a.TestsToRun.push_back(new glyphTest("Glyphing")); a.TestsToRun.push_back(new moleculeTest("Molecule")); a.TestsToRun.push_back(new moleculeTest("MoleculeAtomsOnly",true)); a.TestsToRun.push_back(new volumeTest("Volume", false)); a.TestsToRun.push_back(new volumeTest("VolumeWithShading", true)); a.TestsToRun.push_back(new depthPeelingTest("DepthPeeling", false)); a.TestsToRun.push_back(new depthPeelingTest("DepthPeelingWithNormals", true)); a.TestsToRun.push_back(new manyActorTest("ManyActors")); // process them return a.ParseCommandLineArguments(argc, argv); }
37.035714
80
0.646577
stephansmit
1707fecbc6f1f496b2d6ca400d4d4370044de11c
1,221
hpp
C++
include/beauty/route.hpp
nside/beauty
b68c88260d12442376c09043803809bc0a8aca15
[ "MIT" ]
38
2020-08-12T11:59:26.000Z
2022-03-26T11:26:39.000Z
include/beauty/route.hpp
nside/beauty
b68c88260d12442376c09043803809bc0a8aca15
[ "MIT" ]
2
2021-08-01T10:15:36.000Z
2022-03-26T11:40:03.000Z
include/beauty/route.hpp
nside/beauty
b68c88260d12442376c09043803809bc0a8aca15
[ "MIT" ]
6
2020-09-23T16:02:30.000Z
2022-03-16T16:01:38.000Z
#pragma once #include <beauty/request.hpp> #include <beauty/response.hpp> #include <beauty/swagger.hpp> #include <iostream> #include <vector> #include <string> #include <string_view> #include <functional> namespace beauty { using route_cb = std::function<void(const beauty::request& req, beauty::response& res)>; // -------------------------------------------------------------------------- class route { public: explicit route(const std::string& path, route_cb&& cb = {}); explicit route(const std::string& path, const beauty::route_info& route_info, route_cb&& cb = {}); bool match(beauty::request& req) const noexcept; void execute(const beauty::request& req, beauty::response& res) const { _cb(req, res); } const std::string& path() const noexcept { return _path; } const std::vector<std::string>& segments() const noexcept { return _segments; } const beauty::route_info& route_info() const noexcept { return _route_info; } private: void extract_route_info(); void update_route_info(const beauty::route_info& route_info); private: std::string _path; std::vector<std::string> _segments; route_cb _cb; beauty::route_info _route_info; }; }
25.4375
102
0.651925
nside
170c5c88dc055f1c1803208b672ba1410fce3226
9,074
hpp
C++
src/dgate/dicomlib/aarq.hpp
theorose49/conquest-dicom-server
aba35e1da51d7bb288ecde0f31d6963f47b8252c
[ "Apache-2.0" ]
null
null
null
src/dgate/dicomlib/aarq.hpp
theorose49/conquest-dicom-server
aba35e1da51d7bb288ecde0f31d6963f47b8252c
[ "Apache-2.0" ]
6
2021-06-09T19:39:27.000Z
2021-09-30T16:41:40.000Z
radiomicsfeatureextractionpipeline/conquest/src/dgate/dicomlib/aarq.hpp
Maastro-CDS-Imaging-Group/SQLite4Radiomics
e3a7afc181eec0fe04c18da00edc3772064e6758
[ "Apache-2.0" ]
null
null
null
/* mvh 20001106: Use memcpy instead of ByteCopy bcb 20091231: Changed char* to const char* for gcc4.2 warnings mvh 20100111: Merged bcb 20100619: Fix gcc4 warnings, improve speed and added UNUSED_ARGUMENT. mvh 20100717: Merged; Q1 OK bcb 20100728: Added PresentationContext(const PresentationContext&) mvh 20100815: Merged lsp 20140528: Member initialization and assignment operator are not GNUC specific: latter is used in CqDicom project mvh 20150908: Added HasImpVersion to UserInformation; needed for VITREA which does not send it */ /**************************************************************************** Copyright (C) 1995, University of California, Davis THIS SOFTWARE IS MADE AVAILABLE, AS IS, AND THE UNIVERSITY OF CALIFORNIA DOES NOT MAKE ANY WARRANTY ABOUT THE SOFTWARE, ITS PERFORMANCE, ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR USE, FREEDOM FROM ANY COMPUTER DISEASES OR ITS CONFORMITY TO ANY SPECIFICATION. THE ENTIRE RISK AS TO QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH THE USER. Copyright of the software and supporting documentation is owned by the University of California, and free access is hereby granted as a license to use this software, copy this software and prepare derivative works based upon this software. However, any distribution of this software source code or supporting documentation or derivative works (source code and supporting documentation) must include this copyright notice. ****************************************************************************/ /*************************************************************************** * * University of California, Davis * UCDMC DICOM Network Transport Libraries * Version 0.1 Beta * * Technical Contact: mhoskin@ucdavis.edu * ***************************************************************************/ /*********************************************************************** * PDU Service Classes: * A-ASSOCIATE-RQ Class. * * Base Classes: * UID * ApplicationContext * AbstractSyntax * TransferSyntax * PresentationContext * MaximumSubLength * ImplementationClass * ImplementationVersion * UserInformation * * * *********************************************************************/ #ifndef UNUSED_ARGUMENT #define UNUSED_ARGUMENT(x) (void)x #endif class UID { UINT Length; BYTE uid[65]; public: UID():Length(0) { ZeroMem(uid, 64);}; UID(BYTE *s):Length(0) { Set ( s ); }; UID(const char *s):Length(0) { Set ( (BYTE*)s ); }; void Set(BYTE *s) { if(!s) return; ZeroMem(uid, 64); strcpy((char *) uid, (char *) s); Length = strlen((char*) uid); }; void Set(UID &u) { (*this) = u; }; void Set(const char *s) { this->Set((BYTE *) s); }; BYTE *GetBuffer(UINT Min) { UNUSED_ARGUMENT(Min); return(&uid[0]); }; void SetLength(UINT L) { Length = L; while (L < 65) uid[L++] = '\0'; }; UINT GetSize() { return ( Length ); }; BOOL operator == (UID &ud) { //if(GetSize()!=ud.GetSize()) return(FALSE); if(!strcmp((char*) GetBuffer(1), (char*) ud.GetBuffer(1)/*, (int) GetSize()*/)) return(TRUE); return(FALSE); }; BOOL operator != (UID &ud) { return (!((*this)==ud)); }; UID operator = (UID &ud) { memcpy(uid, ud.GetBuffer(1), 64); SetLength(ud.GetSize()); return(*this); } }; class ApplicationContext { private: BYTE ItemType; // 0x10 BYTE Reserved1; UINT16 Length; public: UID ApplicationContextName; ApplicationContext(); ApplicationContext(UID &); ApplicationContext(BYTE *); ~ApplicationContext(); void Set(UID &); void Set(BYTE *); BOOL Write(Buffer &); BOOL Read(Buffer &); BOOL ReadDynamic(Buffer &); UINT32 Size(); }; class AbstractSyntax { private: BYTE ItemType; // 0x30 BYTE Reserved1; UINT16 Length; public: UID AbstractSyntaxName; AbstractSyntax(); AbstractSyntax(BYTE *); AbstractSyntax(UID &); ~AbstractSyntax(); void Set(UID &); void Set(BYTE *); BOOL Write(Buffer &); BOOL Read(Buffer &); BOOL ReadDynamic(Buffer &); UINT32 Size(); }; class TransferSyntax { private: BYTE ItemType; // 0x40 BYTE Reserved1; UINT16 Length; public: UID TransferSyntaxName; UINT EndianType; TransferSyntax(); TransferSyntax(BYTE *); TransferSyntax(UID &); ~TransferSyntax(); void Set(UID &); void Set(BYTE *); void SetType(UINT T) { EndianType = T; }; BOOL Write(Buffer &); BOOL Read(Buffer &); BOOL ReadDynamic(Buffer &); UINT32 Size(); }; class ImplementationClass { private: BYTE ItemType; // 0x52 BYTE Reserved1; UINT16 Length; public: UID ImplementationName; UINT EndianType; ImplementationClass(); ImplementationClass(BYTE *); ImplementationClass(UID &); ~ImplementationClass(); void Set(UID &); void Set(BYTE *); BOOL Write(Buffer &); BOOL Read(Buffer &); BOOL ReadDynamic(Buffer &); UINT32 Size(); }; class ImplementationVersion { private: BYTE ItemType; // 0x55 BYTE Reserved1; UINT16 Length; public: UID Version; UINT EndianType; ImplementationVersion(); ImplementationVersion(BYTE *); ImplementationVersion(UID &); ~ImplementationVersion(); void Set(UID &); void Set(BYTE *); BOOL Write(Buffer &); BOOL Read(Buffer &); BOOL ReadDynamic(Buffer &); UINT32 Size(); }; class SCPSCURoleSelect { private: BYTE ItemType; // 0x54 BYTE Reserved1; UINT16 Length; public: UID uid; BYTE SCURole; BYTE SCPRole; SCPSCURoleSelect(); ~SCPSCURoleSelect(); BOOL Write(Buffer &); BOOL Read(Buffer &); BOOL ReadDynamic(Buffer &); UINT32 Size(); }; class PresentationContext { private: BYTE ItemType; // 0x20 BYTE Reserved1; UINT16 Length; public: BYTE PresentationContextID; private: BYTE Reserved2; BYTE Reserved3; BYTE Reserved4; public: AbstractSyntax AbsSyntax; Array<TransferSyntax> TrnSyntax; PresentationContext(); PresentationContext(AbstractSyntax &, TransferSyntax &); ~PresentationContext(); void SetAbstractSyntax(AbstractSyntax &); void AddTransferSyntax(TransferSyntax &); BOOL Write(Buffer &); BOOL Read(Buffer &); BOOL ReadDynamic(Buffer &); UINT32 Size(); // Used in PDU_Service::AddAbstractSyntaxAlias (UID &UIDSource, UID &UIDAlias) // in the line PresentationContext vPresContext = PresContext; // Since it is used, we need to control it. Current commented out. /* PresentationContext(const PresentationContext&):ItemType(0x20), Reserved1(Reserved1), Length(Length), PresentationContextID(PresentationContextID), Reserved2(Reserved2), Reserved3(Reserved3), Reserved4(Reserved4), AbsSyntax(AbsSyntax), TrnSyntax(TrnSyntax) {};*/ private:// Prevents copying PresentationContext(const PresentationContext&):ItemType(0x20), Reserved1(0), Length(0), PresentationContextID(0), Reserved2(0), Reserved3(0), Reserved4(0), AbsSyntax(NULL), TrnSyntax() {}; }; class MaximumSubLength { private: BYTE ItemType; // 0x51 BYTE Reserved1; UINT16 Length; UINT32 MaximumLength; public: MaximumSubLength(); MaximumSubLength(UINT32); ~MaximumSubLength(); void Set(UINT32); UINT32 Get(); BOOL Write(Buffer &); BOOL Read(Buffer &); BOOL ReadDynamic(Buffer &); UINT32 Size(); }; class UserInformation { private: BYTE ItemType; // 0x50 BYTE Reserved1; UINT16 Length; BOOL HasImpVersion; public: UINT32 UserInfoBaggage; MaximumSubLength MaxSubLength; ImplementationClass ImpClass; ImplementationVersion ImpVersion; SCPSCURoleSelect SCPSCURole; public: UserInformation(); ~UserInformation(); void SetMax(MaximumSubLength &); UINT32 GetMax(); BOOL Write(Buffer &); BOOL Read(Buffer &); BOOL ReadDynamic(Buffer &); UINT32 Size(); }; class AAssociateRQ { private: BYTE ItemType; // 0x01 BYTE Reserved1; UINT32 Length; UINT16 ProtocolVersion; // 0x01 UINT16 Reserved2; public: BYTE CalledApTitle[17]; // 16 bytes transfered BYTE CallingApTitle[17]; // 16 bytes transfered BYTE Reserved3[32]; ApplicationContext AppContext; Array<PresentationContext> PresContexts; UserInformation UserInfo; public: AAssociateRQ(); AAssociateRQ(BYTE *, BYTE *); virtual ~AAssociateRQ(); void SetCalledApTitle(BYTE *); void SetCallingApTitle(BYTE *); void SetApplicationContext(ApplicationContext &); void SetApplicationContext(UID &); void AddPresentationContext(PresentationContext &); void ClearPresentationContexts(); void SetUserInformation(UserInformation &); BOOL Write(Buffer &); BOOL Read(Buffer &); BOOL ReadDynamic(Buffer &); UINT32 Size(); };
26.074713
97
0.629821
theorose49
170cbe7a42aee1815d6600e4746f332fea6af6b1
1,002
cpp
C++
Source/Core/Matrix/Vector.cpp
CCSEPBVR/KVS
f6153b3f52aa38904cc96d38d5cd609c5dccfc59
[ "BSD-3-Clause" ]
null
null
null
Source/Core/Matrix/Vector.cpp
CCSEPBVR/KVS
f6153b3f52aa38904cc96d38d5cd609c5dccfc59
[ "BSD-3-Clause" ]
null
null
null
Source/Core/Matrix/Vector.cpp
CCSEPBVR/KVS
f6153b3f52aa38904cc96d38d5cd609c5dccfc59
[ "BSD-3-Clause" ]
null
null
null
/****************************************************************************/ /** * @file Vector.cpp * @author Naohisa Sakamoto */ /*---------------------------------------------------------------------------- * * Copyright (c) Visualization Laboratory, Kyoto University. * All rights reserved. * See http://www.viz.media.kyoto-u.ac.jp/kvs/copyright/ for details. * * $Id: Vector.cpp 1340 2012-11-07 07:31:06Z s.yamada0808@gmail.com $ */ /****************************************************************************/ #include "Vector.h" #include <kvs/Type> namespace kvs { // Template instantiation. template class Vector<kvs::Int8>; template class Vector<kvs::UInt8>; template class Vector<kvs::Int16>; template class Vector<kvs::UInt16>; template class Vector<kvs::Int32>; template class Vector<kvs::UInt32>; template class Vector<kvs::Int64>; template class Vector<kvs::UInt64>; template class Vector<kvs::Real32>; template class Vector<kvs::Real64>; } // end of namespace kvs
29.470588
78
0.548902
CCSEPBVR
171cf6fe9d1a7fde985385964f7ff30b028fc49d
5,318
hpp
C++
include/codegen/include/System/Linq/Enumerable_-RepeatIterator-d__117_1.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/System/Linq/Enumerable_-RepeatIterator-d__117_1.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/System/Linq/Enumerable_-RepeatIterator-d__117_1.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:16 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.Object #include "System/Object.hpp" // Including type: System.Linq.Enumerable #include "System/Linq/Enumerable.hpp" // Including type: System.Collections.Generic.IEnumerable`1 #include "System/Collections/Generic/IEnumerable_1.hpp" // Including type: System.Collections.Generic.IEnumerator`1 #include "System/Collections/Generic/IEnumerator_1.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Completed forward declares // Type namespace: System.Linq namespace System::Linq { // Autogenerated type: System.Linq.Enumerable/<RepeatIterator>d__117`1 template<typename TResult> class Enumerable::$RepeatIterator$d__117_1 : public ::Il2CppObject, public System::Collections::Generic::IEnumerable_1<TResult>, public System::Collections::IEnumerable, public System::Collections::Generic::IEnumerator_1<TResult>, public System::IDisposable, public System::Collections::IEnumerator { public: // private System.Int32 <>1__state // Offset: 0x0 int $$1__state; // private TResult <>2__current // Offset: 0x0 TResult $$2__current; // private System.Int32 <>l__initialThreadId // Offset: 0x0 int $$l__initialThreadId; // private TResult element // Offset: 0x0 TResult element; // public TResult <>3__element // Offset: 0x0 TResult $$3__element; // private System.Int32 <i>5__1 // Offset: 0x0 int $i$5__1; // private System.Int32 count // Offset: 0x0 int count; // public System.Int32 <>3__count // Offset: 0x0 int $$3__count; // public System.Void .ctor(System.Int32 $$1__state) // Offset: 0x127973C static Enumerable::$RepeatIterator$d__117_1<TResult>* New_ctor(int $$1__state) { return (Enumerable::$RepeatIterator$d__117_1<TResult>*)CRASH_UNLESS(il2cpp_utils::New(il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<Enumerable::$RepeatIterator$d__117_1<TResult>*>::get(), $$1__state)); } // private System.Void System.IDisposable.Dispose() // Offset: 0x127977C // Implemented from: System.IDisposable // Base method: System.Void IDisposable::Dispose() void System_IDisposable_Dispose() { CRASH_UNLESS(il2cpp_utils::RunMethod(this, "System.IDisposable.Dispose")); } // private System.Boolean MoveNext() // Offset: 0x1279780 // Implemented from: System.Collections.IEnumerator // Base method: System.Boolean IEnumerator::MoveNext() bool MoveNext() { return CRASH_UNLESS(il2cpp_utils::RunMethod<bool>(this, "MoveNext")); } // private TResult System.Collections.Generic.IEnumerator<TResult>.get_Current() // Offset: 0x12797E0 // Implemented from: System.Collections.Generic.IEnumerator`1 // Base method: T IEnumerator`1::get_Current() TResult System_Collections_Generic_IEnumerator_1_get_Current() { return CRASH_UNLESS(il2cpp_utils::RunMethod<TResult>(this, "System.Collections.Generic.IEnumerator<TResult>.get_Current")); } // private System.Void System.Collections.IEnumerator.Reset() // Offset: 0x12797E8 // Implemented from: System.Collections.IEnumerator // Base method: System.Void IEnumerator::Reset() void System_Collections_IEnumerator_Reset() { CRASH_UNLESS(il2cpp_utils::RunMethod(this, "System.Collections.IEnumerator.Reset")); } // private System.Object System.Collections.IEnumerator.get_Current() // Offset: 0x1279848 // Implemented from: System.Collections.IEnumerator // Base method: System.Object IEnumerator::get_Current() ::Il2CppObject* System_Collections_IEnumerator_get_Current() { return CRASH_UNLESS(il2cpp_utils::RunMethod<::Il2CppObject*>(this, "System.Collections.IEnumerator.get_Current")); } // private System.Collections.Generic.IEnumerator`1<TResult> System.Collections.Generic.IEnumerable<TResult>.GetEnumerator() // Offset: 0x1279890 // Implemented from: System.Collections.Generic.IEnumerable`1 // Base method: System.Collections.Generic.IEnumerator`1<T> IEnumerable`1::GetEnumerator() System::Collections::Generic::IEnumerator_1<TResult>* System_Collections_Generic_IEnumerable_1_GetEnumerator() { return CRASH_UNLESS(il2cpp_utils::RunMethod<System::Collections::Generic::IEnumerator_1<TResult>*>(this, "System.Collections.Generic.IEnumerable<TResult>.GetEnumerator")); } // private System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() // Offset: 0x1279940 // Implemented from: System.Collections.IEnumerable // Base method: System.Collections.IEnumerator IEnumerable::GetEnumerator() System::Collections::IEnumerator* System_Collections_IEnumerable_GetEnumerator() { return CRASH_UNLESS(il2cpp_utils::RunMethod<System::Collections::IEnumerator*>(this, "System.Collections.IEnumerable.GetEnumerator")); } }; // System.Linq.Enumerable/<RepeatIterator>d__117`1 } DEFINE_IL2CPP_ARG_TYPE_GENERIC_CLASS(System::Linq::Enumerable::$RepeatIterator$d__117_1, "System.Linq", "Enumerable/<RepeatIterator>d__117`1"); #pragma pack(pop)
49.240741
302
0.732042
Futuremappermydud
171e8dc38cd0fdefebb8f1ed874d5d2447f7ca7e
238
cpp
C++
ch02/2-8.cpp
stanleywxchen/acceleratedcpp
fdcfff2bcaf9196655d77e1d80634a78d9ea7f00
[ "Apache-2.0" ]
null
null
null
ch02/2-8.cpp
stanleywxchen/acceleratedcpp
fdcfff2bcaf9196655d77e1d80634a78d9ea7f00
[ "Apache-2.0" ]
null
null
null
ch02/2-8.cpp
stanleywxchen/acceleratedcpp
fdcfff2bcaf9196655d77e1d80634a78d9ea7f00
[ "Apache-2.0" ]
null
null
null
/* This program calculates the product of the numbers in the range [1, 10). */ #include <iostream> int main() { int product = 1; for (int i = 1; i < 10; ++i) { product *= i; } std::cout << "9! is " << product << std::endl; }
18.307692
72
0.558824
stanleywxchen
17206de39a0a784b608bd0a2a466ba0673b7c59d
8,162
cpp
C++
src/scriptvariableswidget.cpp
st4ll1/dust3d
c1de02f7ddcfdacc730cc96740f8073f87e7818c
[ "MIT" ]
null
null
null
src/scriptvariableswidget.cpp
st4ll1/dust3d
c1de02f7ddcfdacc730cc96740f8073f87e7818c
[ "MIT" ]
null
null
null
src/scriptvariableswidget.cpp
st4ll1/dust3d
c1de02f7ddcfdacc730cc96740f8073f87e7818c
[ "MIT" ]
null
null
null
#include <QDoubleSpinBox> #include <QFormLayout> #include <QDebug> #include <QCheckBox> #include <QComboBox> #include <QLabel> #include <QColorDialog> #include "scriptvariableswidget.h" #include "util.h" #include "theme.h" #include "floatnumberwidget.h" #include "intnumberwidget.h" ScriptVariablesWidget::ScriptVariablesWidget(const Document *document, QWidget *parent) : QScrollArea(parent), m_document(document) { connect(this, &ScriptVariablesWidget::updateVariableValue, m_document, &Document::updateVariableValue); setWidgetResizable(true); reload(); } void ScriptVariablesWidget::reload() { QWidget *widget = new QWidget; QFormLayout *formLayout = new QFormLayout; for (const auto &variable: m_document->variables()) { auto name = variable.first; auto input = valueOfKeyInMapOrEmpty(variable.second, "input"); if ("Float" == input) { auto minValue = valueOfKeyInMapOrEmpty(variable.second, "minValue").toFloat(); auto maxValue = valueOfKeyInMapOrEmpty(variable.second, "maxValue").toFloat(); auto value = valueOfKeyInMapOrEmpty(variable.second, "value").toFloat(); auto defaultValue = valueOfKeyInMapOrEmpty(variable.second, "defaultValue").toFloat(); FloatNumberWidget *floatWidget = new FloatNumberWidget; floatWidget->setItemName(name); floatWidget->setRange(minValue, maxValue); floatWidget->setValue(value); connect(floatWidget, &FloatNumberWidget::valueChanged, [=](float toValue) { emit updateVariableValue(name, QString::number(toValue)); }); QPushButton *floatEraser = new QPushButton(QChar(fa::eraser)); Theme::initAwesomeToolButton(floatEraser); connect(floatEraser, &QPushButton::clicked, [=]() { floatWidget->setValue(defaultValue); }); QHBoxLayout *floatLayout = new QHBoxLayout; floatLayout->addWidget(floatEraser); floatLayout->addWidget(floatWidget); formLayout->addRow(floatLayout); } else if ("Int" == input) { auto minValue = valueOfKeyInMapOrEmpty(variable.second, "minValue").toInt(); auto maxValue = valueOfKeyInMapOrEmpty(variable.second, "maxValue").toInt(); auto value = valueOfKeyInMapOrEmpty(variable.second, "value").toInt(); auto defaultValue = valueOfKeyInMapOrEmpty(variable.second, "defaultValue").toInt(); IntNumberWidget *intWidget = new IntNumberWidget; intWidget->setItemName(name); intWidget->setRange(minValue, maxValue); intWidget->setValue(value); connect(intWidget, &IntNumberWidget::valueChanged, [=](int toValue) { emit updateVariableValue(name, QString::number(toValue)); }); QPushButton *intEraser = new QPushButton(QChar(fa::eraser)); Theme::initAwesomeToolButton(intEraser); connect(intEraser, &QPushButton::clicked, [=]() { intWidget->setValue(defaultValue); }); QHBoxLayout *intLayout = new QHBoxLayout; intLayout->addWidget(intEraser); intLayout->addWidget(intWidget); formLayout->addRow(intLayout); } else if ("Check" == input) { auto value = isTrueValueString(valueOfKeyInMapOrEmpty(variable.second, "value")); auto defaultValue = isTrueValueString(valueOfKeyInMapOrEmpty(variable.second, "defaultValue")); QCheckBox *checkBox = new QCheckBox; Theme::initCheckbox(checkBox); checkBox->setText(name); checkBox->setChecked(value); connect(checkBox, &QCheckBox::stateChanged, [=](int) { emit updateVariableValue(name, checkBox->isChecked() ? "true" : "false"); }); QPushButton *checkEraser = new QPushButton(QChar(fa::eraser)); Theme::initAwesomeToolButton(checkEraser); connect(checkEraser, &QPushButton::clicked, [=]() { checkBox->setChecked(defaultValue); }); QHBoxLayout *checkLayout = new QHBoxLayout; checkLayout->addWidget(checkEraser); checkLayout->addWidget(checkBox); formLayout->addRow(checkLayout); } else if ("Select" == input) { auto value = valueOfKeyInMapOrEmpty(variable.second, "value").toInt(); auto defaultValue = valueOfKeyInMapOrEmpty(variable.second, "defaultValue").toInt(); auto length = valueOfKeyInMapOrEmpty(variable.second, "length").toInt(); QComboBox *selectBox = new QComboBox; selectBox->setEditable(false); selectBox->setSizeAdjustPolicy(QComboBox::AdjustToContents); for (auto i = 0; i < length; ++i) { selectBox->addItem(valueOfKeyInMapOrEmpty(variable.second, "option" + QString::number(i))); } selectBox->setCurrentIndex(value); connect(selectBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), [=](int index) { emit updateVariableValue(name, QString::number(index)); }); QPushButton *selectEraser = new QPushButton(QChar(fa::eraser)); Theme::initAwesomeToolButton(selectEraser); connect(selectEraser, &QPushButton::clicked, [=]() { selectBox->setCurrentIndex(defaultValue); }); QLabel *selectLabel = new QLabel; selectLabel->setText(name); QHBoxLayout *selectLayout = new QHBoxLayout; selectLayout->addWidget(selectEraser); selectLayout->addWidget(selectBox); selectLayout->addWidget(selectLabel); formLayout->addRow(selectLayout); } else if ("Color" == input) { auto value = valueOfKeyInMapOrEmpty(variable.second, "value"); auto defaultValue = valueOfKeyInMapOrEmpty(variable.second, "defaultValue"); QPushButton *colorEraser = new QPushButton(QChar(fa::eraser)); Theme::initAwesomeToolButton(colorEraser); QPushButton *pickButton = new QPushButton(); Theme::initAwesomeToolButtonWithoutFont(pickButton); auto updatePickButtonColor = [=](const QColor &color) { QPalette palette = pickButton->palette(); palette.setColor(QPalette::Window, color); palette.setColor(QPalette::Button, color); pickButton->setPalette(palette); }; updatePickButtonColor(QColor(value)); connect(colorEraser, &QPushButton::clicked, [=]() { updatePickButtonColor(defaultValue); emit updateVariableValue(name, defaultValue); }); connect(pickButton, &QPushButton::clicked, [=]() { QColor color = QColorDialog::getColor(value, this); if (color.isValid()) { updatePickButtonColor(color.name()); emit updateVariableValue(name, color.name()); } }); QLabel *selectLabel = new QLabel; selectLabel->setText(name); QHBoxLayout *colorLayout = new QHBoxLayout; colorLayout->addWidget(colorEraser); colorLayout->addWidget(pickButton); colorLayout->addWidget(selectLabel); colorLayout->addStretch(); formLayout->addRow(colorLayout); } } widget->setLayout(formLayout); setWidget(widget); } QSize ScriptVariablesWidget::sizeHint() const { return QSize(Theme::sidebarPreferredWidth, 0); }
41.85641
119
0.589439
st4ll1
172103e1c59353f73377b8ac1fcd14317e1b8564
3,264
cxx
C++
src/hblas/cxx/hblas3/kern.cxx
wavefunction91/HAXX
e0c282b70ee009a2a01871979f505bcca89713ba
[ "BSD-3-Clause" ]
6
2018-11-05T22:20:28.000Z
2020-12-28T22:22:55.000Z
src/hblas/cxx/hblas3/kern.cxx
wavefunction91/HAXX
e0c282b70ee009a2a01871979f505bcca89713ba
[ "BSD-3-Clause" ]
null
null
null
src/hblas/cxx/hblas3/kern.cxx
wavefunction91/HAXX
e0c282b70ee009a2a01871979f505bcca89713ba
[ "BSD-3-Clause" ]
null
null
null
/* * This file is a part of HAXX * * Copyright (c) 2017 David Williams-Young * All rights reserved. * * See LICENSE.txt */ #include "haxx.hpp" #include "hblas/hblas1.hpp" #include "hblas/hblas3.hpp" #include "util/simd.hpp" #include "util/macro.hpp" #include "hblas/config/types.hpp" #include "hblas/config/hblas3/gemm.hpp" namespace HAXX { template <typename T, typename U, typename V> void Kern(HAXX_INT M, HAXX_INT N, HAXX_INT K, T* __restrict__ A, U* __restrict__ B, V* __restrict__ C, HAXX_INT LDC); template<> void Kern(HAXX_INT M, HAXX_INT N, HAXX_INT K, quaternion<double>* __restrict__ A, quaternion<double>* __restrict__ B, quaternion<double>* __restrict__ C, HAXX_INT LDC) { __m256d t1,t2,t3,t4; const bool M2 = (M == 2); const bool N2 = (N == 2); // Load C __m256d c00 = LOAD_256D_UNALIGNED_AS(double,C ); __m256d c10 = M2 ? LOAD_256D_UNALIGNED_AS(double,C+1 ) : _mm256_setzero_pd(); __m256d c01 = N2 ? LOAD_256D_UNALIGNED_AS(double,C+LDC ) : _mm256_setzero_pd(); __m256d c11 = ( M2 and N2 ) ? LOAD_256D_UNALIGNED_AS(double,C+LDC+1) : _mm256_setzero_pd(); _MM_TRANSPOSE_4x4_PD(c00,c01,c10,c11,t1,t2,t3,t4); quaternion<double> *locB = B, *locA = A; HAXX_INT k = K; if( k > 0 ) do { // Load A __m256d a00 = LOAD_256D_ALIGNED_AS(double,locA); __m256d a10 = LOAD_256D_ALIGNED_AS(double,locA+1); locA += 2; // Load B #ifndef _FACTOR_TRANSPOSE_INTO_B_PACK __m256d b00 = LOAD_256D_ALIGNED_AS(double,locB); __m256d b10 = LOAD_256D_ALIGNED_AS(double,locB+1); #else double *BasDouble = reinterpret_cast<double*>(locB); __m128d b00lo = LOAD_128D_ALIGNED(BasDouble); __m128d b00hi = LOAD_128D_ALIGNED(BasDouble+2); __m128d b10lo = LOAD_128D_ALIGNED(BasDouble+4); __m128d b10hi = LOAD_128D_ALIGNED(BasDouble+6); #endif locB += 2; #ifdef _FACTOR_TRANSPOSE_INTO_A_PACK __m256d a_IIII = _mm256_permute_pd(a00,0xF); a00 = _mm256_permute_pd(a00,0x0); // SSSS __m256d a_KKKK = _mm256_permute_pd(a10,0xF); a10 = _mm256_permute_pd(a10,0x0); // SSSS __m256d &a00c = a_IIII; __m256d &a10c = a_KKKK; #else __m256d a00c = a00; __m256d a10c = a10; _MM_TRANSPOSE_4x4_PD(a00,a00c,a10,a10c,t1,t2,t3,t4); #endif #ifdef _FACTOR_TRANSPOSE_INTO_B_PACK __m256d bSSSS = SET_256D_FROM_128D(b00lo,b00lo); __m256d bIIII = SET_256D_FROM_128D(b10lo,b10lo); __m256d bJJJJ = SET_256D_FROM_128D(b00hi,b00hi); __m256d bKKKK = SET_256D_FROM_128D(b10hi,b10hi); __m256d &b00 = bSSSS; __m256d &b10 = bIIII; __m256d &b00c = bJJJJ; __m256d &b10c = bKKKK; #else __m256d b00c = b00; __m256d b10c = b10; _MM_TRANSPOSE_4x4_PD(b00,b10,b00c,b10c,t1,t2,t3,t4); #endif INC_MULD4Q_NN(a00,a00c,a10,a10c,b00,b10,b00c,b10c,c00,c01,c10,c11); k--; } while( k > 0 ); _MM_TRANSPOSE_4x4_PD(c00,c01,c10,c11,t1,t2,t3,t4); STORE_256D_UNALIGNED_AS(double,C ,c00); if( M2 ) STORE_256D_UNALIGNED_AS(double,C+1 ,c10); if( N2 ) STORE_256D_UNALIGNED_AS(double,C+LDC ,c01); if( M2 and N2 ) STORE_256D_UNALIGNED_AS(double,C+LDC+1,c11); } };
24.177778
104
0.661152
wavefunction91
17259883290525ae3c72e8fd7d7cda36b7c17527
2,686
cpp
C++
aws-cpp-sdk-securityhub/source/model/IntegrationType.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-securityhub/source/model/IntegrationType.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-securityhub/source/model/IntegrationType.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/securityhub/model/IntegrationType.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace SecurityHub { namespace Model { namespace IntegrationTypeMapper { static const int SEND_FINDINGS_TO_SECURITY_HUB_HASH = HashingUtils::HashString("SEND_FINDINGS_TO_SECURITY_HUB"); static const int RECEIVE_FINDINGS_FROM_SECURITY_HUB_HASH = HashingUtils::HashString("RECEIVE_FINDINGS_FROM_SECURITY_HUB"); static const int UPDATE_FINDINGS_IN_SECURITY_HUB_HASH = HashingUtils::HashString("UPDATE_FINDINGS_IN_SECURITY_HUB"); IntegrationType GetIntegrationTypeForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == SEND_FINDINGS_TO_SECURITY_HUB_HASH) { return IntegrationType::SEND_FINDINGS_TO_SECURITY_HUB; } else if (hashCode == RECEIVE_FINDINGS_FROM_SECURITY_HUB_HASH) { return IntegrationType::RECEIVE_FINDINGS_FROM_SECURITY_HUB; } else if (hashCode == UPDATE_FINDINGS_IN_SECURITY_HUB_HASH) { return IntegrationType::UPDATE_FINDINGS_IN_SECURITY_HUB; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<IntegrationType>(hashCode); } return IntegrationType::NOT_SET; } Aws::String GetNameForIntegrationType(IntegrationType enumValue) { switch(enumValue) { case IntegrationType::SEND_FINDINGS_TO_SECURITY_HUB: return "SEND_FINDINGS_TO_SECURITY_HUB"; case IntegrationType::RECEIVE_FINDINGS_FROM_SECURITY_HUB: return "RECEIVE_FINDINGS_FROM_SECURITY_HUB"; case IntegrationType::UPDATE_FINDINGS_IN_SECURITY_HUB: return "UPDATE_FINDINGS_IN_SECURITY_HUB"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace IntegrationTypeMapper } // namespace Model } // namespace SecurityHub } // namespace Aws
34.435897
130
0.674609
perfectrecall
1727a837911f2f3c2d6e6f639117a0b003ef12c6
252
cpp
C++
src/SystemQ/Program.cpp
BclEx/GpuStructs
b93acb1c7196477d1d023453a75b480f75cdd29a
[ "MIT" ]
null
null
null
src/SystemQ/Program.cpp
BclEx/GpuStructs
b93acb1c7196477d1d023453a75b480f75cdd29a
[ "MIT" ]
null
null
null
src/SystemQ/Program.cpp
BclEx/GpuStructs
b93acb1c7196477d1d023453a75b480f75cdd29a
[ "MIT" ]
null
null
null
#include <cstdio> extern void TestHeap(); extern void TestSort(); extern void TestList(); extern void TestString(); void main() { TestHeap(); TestSort(); TestList(); TestString(); // printf("End."); char c; scanf_s("%c", &c); }
14.823529
28
0.603175
BclEx
173637332c1cfe034ee0f6f6fcbd5d45e038bc37
5,902
cpp
C++
source/projects/ar.buildatpdf_tilde/ar.buildatpdf_tilde.cpp
isabelgk/airfx
bc97f9a093ceba9cd27020f4b4db1c508a37545f
[ "MIT" ]
16
2021-06-20T04:51:09.000Z
2022-03-30T03:03:32.000Z
source/projects/ar.buildatpdf_tilde/ar.buildatpdf_tilde.cpp
isabelgk/airfx
bc97f9a093ceba9cd27020f4b4db1c508a37545f
[ "MIT" ]
7
2021-06-20T01:22:22.000Z
2022-01-24T14:33:31.000Z
source/projects/ar.buildatpdf_tilde/ar.buildatpdf_tilde.cpp
isabelgk/airfx
bc97f9a093ceba9cd27020f4b4db1c508a37545f
[ "MIT" ]
null
null
null
#include "c74_min.h" using namespace c74::min; class buildatpdf : public object<buildatpdf>, public vector_operator<> { public: MIN_DESCRIPTION {"a dither-making toolkit"}; MIN_TAGS {"dither"}; MIN_AUTHOR {"Isabel Kaspriskie"}; inlet<> in1 {this, "(signal) Input1"}; inlet<> in2 {this, "(signal) Input2"}; outlet<> out1 {this, "(signal) Output1", "signal"}; outlet<> out2 {this, "(signal) Output2", "signal"}; attribute<number, threadsafe::no, limit::clamp> A {this, "first", 0.5, range {0.0, 1.0} }; attribute<number, threadsafe::no, limit::clamp> B {this, "second", 0.5, range {0.0, 1.0} }; attribute<number, threadsafe::no, limit::clamp> C {this, "third", 0.5, range {0.0, 1.0} }; attribute<number, threadsafe::no, limit::clamp> D {this, "fourth", 0.5, range {0.0, 1.0} }; attribute<number, threadsafe::no, limit::clamp> E {this, "fifth", 0.5, range {0.0, 1.0} }; attribute<number, threadsafe::no, limit::clamp> F {this, "sixth", 0.5, range {0.0, 1.0} }; attribute<number, threadsafe::no, limit::clamp> G {this, "seventh", 0.5, range {0.0, 1.0} }; attribute<number, threadsafe::no, limit::clamp> H {this, "eighth", 0.5, range {0.0, 1.0} }; attribute<number, threadsafe::no, limit::clamp> I {this, "ninth", 0.5, range {0.0, 1.0} }; attribute<number, threadsafe::no, limit::clamp> J {this, "tenth", 0.5, range {0.0, 1.0} }; message<> dspsetup {this, "dspsetup", MIN_FUNCTION { A = 0.5; B = 0.5; C = 0.5; D = 0.5; E = 0.5; F = 0.5; G = 0.5; H = 0.5; I = 0.5; J = 0.5; for(int count = 0; count < 11; count++) {bL[count] = 0.0; bR[count] = 0.0; f[count] = 0.0;} //this is reset: values being initialized only once. Startup values, whatever they are. return {}; } }; void operator()(audio_bundle _input, audio_bundle _output) { double* in1 = _input.samples(0); double* in2 = _input.samples(1); double* out1 = _output.samples(0); double* out2 = _output.samples(1); long sampleFrames = _input.frame_count(); f[0] = (A*2)-1; f[1] = (B*2)-1; f[2] = (C*2)-1; f[3] = (D*2)-1; f[4] = (E*2)-1; f[5] = (F*2)-1; f[6] = (G*2)-1; f[7] = (H*2)-1; f[8] = (I*2)-1; f[9] = (J*2)-1; double currentDither; double inputSampleL; double inputSampleR; while (--sampleFrames >= 0) { inputSampleL = *in1; inputSampleR = *in2; if (inputSampleL<1.2e-38 && -inputSampleL<1.2e-38) { static int noisesource = 0; //this declares a variable before anything else is compiled. It won't keep assigning //it to 0 for every sample, it's as if the declaration doesn't exist in this context, //but it lets me add this denormalization fix in a single place rather than updating //it in three different locations. The variable isn't thread-safe but this is only //a random seed and we can share it with whatever. noisesource = noisesource % 1700021; noisesource++; int residue = noisesource * noisesource; residue = residue % 170003; residue *= residue; residue = residue % 17011; residue *= residue; residue = residue % 1709; residue *= residue; residue = residue % 173; residue *= residue; residue = residue % 17; double applyresidue = residue; applyresidue *= 0.00000001; applyresidue *= 0.00000001; inputSampleL = applyresidue; } if (inputSampleR<1.2e-38 && -inputSampleR<1.2e-38) { static int noisesource = 0; noisesource = noisesource % 1700021; noisesource++; int residue = noisesource * noisesource; residue = residue % 170003; residue *= residue; residue = residue % 17011; residue *= residue; residue = residue % 1709; residue *= residue; residue = residue % 173; residue *= residue; residue = residue % 17; double applyresidue = residue; applyresidue *= 0.00000001; applyresidue *= 0.00000001; inputSampleR = applyresidue; //this denormalization routine produces a white noise at -300 dB which the noise //shaping will interact with to produce a bipolar output, but the noise is actually //all positive. That should stop any variables from going denormal, and the routine //only kicks in if digital black is input. As a final touch, if you save to 24-bit //the silence will return to being digital black again. } inputSampleL *= 8388608.0; inputSampleR *= 8388608.0; //0-1 is now one bit, now we dither bL[9] = bL[8]; bL[8] = bL[7]; bL[7] = bL[6]; bL[6] = bL[5]; bL[5] = bL[4]; bL[4] = bL[3]; bL[3] = bL[2]; bL[2] = bL[1]; bL[1] = bL[0]; bL[0] = (rand()/(double)RAND_MAX); currentDither = (bL[0] * f[0]); currentDither += (bL[1] * f[1]); currentDither += (bL[2] * f[2]); currentDither += (bL[3] * f[3]); currentDither += (bL[4] * f[4]); currentDither += (bL[5] * f[5]); currentDither += (bL[6] * f[6]); currentDither += (bL[7] * f[7]); currentDither += (bL[8] * f[8]); currentDither += (bL[9] * f[9]); inputSampleL += currentDither; bR[9] = bR[8]; bR[8] = bR[7]; bR[7] = bR[6]; bR[6] = bR[5]; bR[5] = bR[4]; bR[4] = bR[3]; bR[3] = bR[2]; bR[2] = bR[1]; bR[1] = bR[0]; bR[0] = (rand()/(double)RAND_MAX); currentDither = (bR[0] * f[0]); currentDither += (bR[1] * f[1]); currentDither += (bR[2] * f[2]); currentDither += (bR[3] * f[3]); currentDither += (bR[4] * f[4]); currentDither += (bR[5] * f[5]); currentDither += (bR[6] * f[6]); currentDither += (bR[7] * f[7]); currentDither += (bR[8] * f[8]); currentDither += (bR[9] * f[9]); inputSampleR += currentDither; inputSampleL = floor(inputSampleL); inputSampleR = floor(inputSampleR); inputSampleL /= 8388608.0; inputSampleR /= 8388608.0; *out1 = inputSampleL; *out2 = inputSampleR; *in1++; *in2++; *out1++; *out2++; } } private: double bL[11]; double bR[11]; double f[11]; //default stuff }; MIN_EXTERNAL(buildatpdf);
33.91954
94
0.605727
isabelgk
17376cb752bb6c52e2ca52519fdf58b888ae6c80
12,583
cpp
C++
Metaprogramming/E09_transform_and_filter/main.cpp
QBouts/BitsOfQ
a0d29a65316474f2c7064769c509aa4497a79b1b
[ "MIT" ]
8
2022-01-24T19:52:18.000Z
2022-03-28T22:08:14.000Z
Metaprogramming/E09_transform_and_filter/main.cpp
QBouts/BitsOfQ
a0d29a65316474f2c7064769c509aa4497a79b1b
[ "MIT" ]
null
null
null
Metaprogramming/E09_transform_and_filter/main.cpp
QBouts/BitsOfQ
a0d29a65316474f2c7064769c509aa4497a79b1b
[ "MIT" ]
null
null
null
/****************************************************************************** * MIT License * * Copyright (c) 2022 Quirijn Bouts * * 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 <iostream> #include <type_traits> #include <utility> #include "Metaprogramming.h" #include "TestUtilities.h" #include "Tuple.h" constexpr size_t boq_tuple = 1; constexpr size_t std_tuple = 2; namespace boq = bits_of_q; using boq::testing::Tester; using boq::testing::TesterWithBuilder; int main() { using namespace bits_of_q; Tester::test("constructor", []() { auto c1 = make_copy_counter<boq_tuple>(); auto c2 = make_copy_counter<std_tuple>(); boq::Tuple t1{9, c1, 1.4}; std::tuple t2{9, c2, 1.4}; ASSERT_EQ(c1, c2); }); Tester::test("make_tuple", []() { auto c1 = make_copy_counter<boq_tuple>(); auto c2 = make_copy_counter<std_tuple>(); [[maybe_unused]] auto &&dummy1 = make_tuple(8, c1, 1.1); [[maybe_unused]] auto &&dummy2 = std::make_tuple(8, c2, 1.1); ASSERT_EQ(c1, c2); }); TesterWithBuilder<1>::test("get", [](auto &&builder) { auto c1 = make_copy_counter<boq_tuple>(); auto c2 = make_copy_counter<std_tuple>(); auto &&tuple1 = builder.build(boq::Tuple{42, c1, true}); auto &&tuple2 = builder.build(std::tuple{42, c2, true}); auto v1 = get<1>(std::forward<decltype(tuple1)>(tuple1)); auto v2 = get<1>(std::forward<decltype(tuple2)>(tuple2)); auto v3 = get<0>(std::forward<decltype(tuple1)>(tuple1)); auto v4 = get<0>(std::forward<decltype(tuple2)>(tuple2)); ASSERT_EQ(v1, v2); ASSERT_EQ(v3, v4); }); TesterWithBuilder<2>::test("tuple_cat with 2 args", [](auto &&builder) { auto c1 = make_copy_counter<boq_tuple>(); auto c2 = make_copy_counter<std_tuple>(); auto &&[boq_tuple1, boq_tuple2] = builder.build(boq::Tuple{42, c1, true}, boq::Tuple{false, c1, 1.2}); auto &&[std_tuple1, std_tuple2] = builder.build(std::tuple{42, c2, true}, std::tuple{false, c2, 1.2}); auto boq_t1_2 = boq::tuple_cat(std::forward<decltype(boq_tuple1)>(boq_tuple1), std::forward<decltype(boq_tuple2)>(boq_tuple2)); auto std_t1_2 = std::tuple_cat(std::forward<decltype(std_tuple1)>(std_tuple1), std::forward<decltype(std_tuple2)>(std_tuple2)); static_for<0, tuple_size_v<decltype(boq_t1_2)>>( [&](auto i) { ASSERT_EQ(get<i.value>(boq_t1_2), get<i.value>(std_t1_2)); }); }); TesterWithBuilder<2>::test("tuple_cat", [](auto &&builder) { auto c1 = make_copy_counter<boq_tuple>(); auto c2 = make_copy_counter<std_tuple>(); // varying value category of first and last tuple by constructing them with the builder auto &&[boq_tuple1, boq_tuple3] = builder.build(boq::Tuple{42, c1, true}, boq::Tuple{7, 'c'}); boq::Tuple boq_tuple2{false, c1, 1.2}; auto &&[std_tuple1, std_tuple3] = builder.build(std::tuple{42, c2, true}, std::tuple{7, 'c'}); std::tuple std_tuple2{false, c2, 1.2}; auto boq_t1_2_3 = boq::tuple_cat(std::forward<decltype(boq_tuple1)>(boq_tuple1), std::move(boq_tuple2), std::forward<decltype(boq_tuple3)>(boq_tuple3)); auto std_t1_2_3 = std::tuple_cat(std::forward<decltype(std_tuple1)>(std_tuple1), std::move(std_tuple2), std::forward<decltype(std_tuple3)>(std_tuple3)); static_for<0, tuple_size_v<decltype(boq_t1_2_3)>>( [&](auto i) { ASSERT_EQ(get<i.value>(boq_t1_2_3), get<i.value>(std_t1_2_3)); }); }); static_assert(tuple_size_v<Tuple<int, bool>> == 2); static_assert(tuple_size_v<Tuple<int, bool, float, double>> == 4); TesterWithBuilder<1>::test("tuple_transform", [](auto &&builder) { auto c = make_copy_counter<boq_tuple>(); auto &&tup = builder.build(Tuple{42, c, 12U}); c.reset(); auto tup2 = transform(std::forward<decltype(tup)>(tup), []<typename T>(T &&t) { constexpr bool is_integral = std::is_integral_v<std::remove_cvref_t<T>>; if constexpr (is_integral) { return int(t) + 2; } else { return t.stats; } }); // Tuple<int, CopyCounter, unsigned int> => Tuple<int, CopyStats, int> // Tuple{42, c, 12U} => Tuple{44, c.stats, 14} static_assert(std::is_same_v<std::remove_cvref_t<decltype(tup2)>, Tuple<int, CopyStats, int>>); ASSERT_EQ(get<0>(tup2), 44); ASSERT_EQ(get<1>(tup2), (CopyStats{0, 0, 0})); ASSERT_EQ(get<2>(tup2), 14); }); TesterWithBuilder<1>::test("tuple_filter", [](auto &&builder) { auto c = make_copy_counter<boq_tuple>(); auto &&tup = builder.build(Tuple{42, 2.3F, c, 3.4, 12U}); c.reset(); auto tup2 = filter<std::is_integral>(std::forward<decltype(tup)>(tup)); static_assert(std::is_same_v<std::remove_cvref_t<decltype(tup2)>, Tuple<int, unsigned int>>); ASSERT_EQ(get<0>(tup2), 42); ASSERT_EQ(get<1>(tup2), 12); ASSERT_EQ(c.stats, (CopyStats{0, 0, 0})); }); TesterWithBuilder<1>::test("tuple_filter2", [](auto &&builder) { auto c = make_copy_counter<boq_tuple>(); static constexpr size_t ref_tuple = 3; auto c2 = make_copy_counter<ref_tuple>(); auto &&tup = builder.build(Tuple{42, 2.3F, c, 3.4, 12U}); auto &&ref_tup = builder.build(Tuple{42, 2.3F, c2, 3.4, 12U}); auto tup2 = filter<boq::not_<std::is_integral>::type>(std::forward<decltype(tup)>(tup)); auto ref_tup2 = std::forward<decltype(ref_tup)>(ref_tup); static_assert( std::is_same_v<std::remove_cvref_t<decltype(tup2)>, Tuple<float, IndexedCopyCounter<boq_tuple>, double>>); ASSERT_EQ(get<0>(tup2), 2.3F); ASSERT_EQ(get<1>(tup2), get<2>(ref_tup2)); ASSERT_EQ(get<2>(tup2), 3.4); }); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // // Homework exercise: Update filter to make it work correctly with references! (solution available on github). // // It is recommended to make the tests below pass one by one, they will guide you through the needed changes. // // // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Homework step 1: Update filter so the predicate is executed with the correct type. // In the current implementation we use the transform function to pass the elements to a lambda. This has the inherent // problem that the lambda is unable to distinguish whether the element type is a value or a lvalue reference. // // Hint: add a tuple_element_t alias using the at function from Metaprogramming.h. Instead of using transform, create // a similar function that executes the predicate on the tuple_element_t at each index instead of using the decltype // of the passed element. Tester::test("tuple_filter_pred_passed_correct_types", []() { int i = 10; Tuple<int, int &, int> tup{4, i, 11}; auto tup2 = filter<boq::not_<std::is_reference>::type>(std::forward<decltype(tup)>(tup)); // static_assert(std::is_same_v<decltype(tup2), Tuple<int, int>>); ASSERT((std::is_same_v<decltype(tup2), Tuple<int, int>>)); }); // Homework: step 2. Create a tuple_cat_result_t metafunction in the detail namespace to help to determine the // expected output type of a tuple_cat operation on two tuples // Hint: This is similar to the push_back operation from Metaprogramming.h, only difference is that we "push_back" the // elements of the second tuple, not the whole tuple Tester::test("tuple_cat_result_2_inputs", []() { // static_assert(std::is_same_v<detail::tuple_cat_result_t<Tuple<int, int &, int>, Tuple<int &&>>, // Tuple<int, int &, int, int &&>>); }); // Homework: step 3. Update tuple_cat_result_t metafunction to handle more than 2 inputs // Hint: Recursion should do the trick Tester::test("tuple_cat_result", []() { // static_assert( // std::is_same_v<detail::tuple_cat_result_t<Tuple<double &, double>, Tuple<int, int &, int>, Tuple<int &&>>, // Tuple<double &, double, int, int &, int, int &&>>); }); // Homework: step 4. Make tuple_cat work with references. // The test below tests the concatenation of tuples with lvalue and rvalue references. Current implementation // ignores these references and will create an output tuple with normal integers. // std::tuple_cat is included for reference so you can compare the expected outcome. // Hint: use the tuple_cat_result_t metafunction to ensure the return type of make_tuple_from_fwd_tuple is correct // Note: some filter tests may start failing after updating tuple_cat to correctly handle references. This is expected // as the current filter implementation implicitly assumes that tuple_cat strips references from the element type. // You may want to temporarily comment out the failing filter tests. We will re-enable them in step 5 Tester::test("tuple_cat_with_refs", []() { int i = 10; int j = 11; Tuple<int, int &, int> tup{4, i, 11}; Tuple<int &&> tup2{std::move(j)}; int j2 = 11; std::tuple<int, int &, int> stup{4, i, 11}; std::tuple<int &&> stup2{std::move(j2)}; auto t1_2 = tuple_cat(std::move(tup), std::move(tup2)); auto st1_2 = std::tuple_cat(std::move(stup), std::move(stup2)); // static_assert(std::is_same_v<decltype(t1_2), Tuple<int, int &, int, int &&>>); // static_assert(std::is_same_v<decltype(st1_2), std::tuple<int, int &, int, int &&>>); ASSERT((std::is_same_v<decltype(t1_2), Tuple<int, int &, int, int &&>>)); ASSERT((std::is_same_v<decltype(st1_2), std::tuple<int, int &, int, int &&>>)); }); // Homework step5: // In order to make filter work correctly with reference type elements, introduce a tuple_result_t metafunction in the // detail namespace earlier changes to execute predicate on correct type. // Hint: you can use a similar approach as in the current filter implementation when building the result type: // Wrapping element types that pass the filter into a tuple type and inserting empty tuples for those that don't (use // if_ from Metaprogramming.h). Then pass that type to the tuple_cat_result_t metafunction created in step 2. Tester::test("filter_result", []() { // static_assert( // std::is_same_v<detail::filter_result_t<Tuple<int, double, unsigned>, std::is_integral>, Tuple<int, // unsigned>>); // static_assert( // std::is_same_v<detail::filter_result_t<Tuple<int, int &, int &&>, std::is_reference>, Tuple<int &, int &&>>); }); // Homework step6: Make filter compatible with refences using the now reference-compatible tuple_cat function and // the filter_result_t metafunction from step 5. // Hint: Update detail::tuple_cat_content to directly use tuple_cat_impl with the correct result tuple type. // Note: if you commented out some of the filter tests in step 4, make sure to re-enable them. They should now pass. Tester::test("tuple_filter_with_refs", []() { int i = 10; Tuple<int, int &, int> tup{4, i, 11}; auto tup2 = filter<boq::not_<std::is_reference>::type>(std::forward<decltype(tup)>(tup)); // static_assert(std::is_same_v<decltype(tup2), Tuple<int, int>>); ASSERT((std::is_same_v<decltype(tup2), Tuple<int, int>>)); auto tup3 = filter<std::is_reference>(std::forward<decltype(tup)>(tup)); // static_assert(std::is_same_v<decltype(tup3), Tuple<int &>>); ASSERT((std::is_same_v<decltype(tup3), Tuple<int &>>)); }); return 0; }
44.779359
119
0.65668
QBouts
17378af081eee1a60bbc3f2183d502b3ffc7d31b
6,245
cc
C++
cplusplus_primer_files/17/bits.cc
cbracb/cplusplus-primer-answers
1c4009c1a770e038638f00add8320c5ca9640bcc
[ "MIT" ]
34
2016-09-23T06:22:35.000Z
2021-12-09T14:01:14.000Z
cplusplus_primer_files/17/bits.cc
cbracb/cplusplus-primer-answers
1c4009c1a770e038638f00add8320c5ca9640bcc
[ "MIT" ]
null
null
null
cplusplus_primer_files/17/bits.cc
cbracb/cplusplus-primer-answers
1c4009c1a770e038638f00add8320c5ca9640bcc
[ "MIT" ]
10
2018-05-14T01:35:18.000Z
2021-06-14T02:44:53.000Z
/* * This file contains code from "C++ Primer, Fifth Edition", by Stanley B. * Lippman, Josee Lajoie, and Barbara E. Moo, and is covered under the * copyright and warranty notices given in that book: * * "Copyright (c) 2013 by Objectwrite, Inc., Josee Lajoie, and Barbara E. Moo." * * * "The authors and publisher have taken care in the preparation of this book, * but make no expressed or implied warranty of any kind and assume no * responsibility for errors or omissions. No liability is assumed for * incidental or consequential damages in connection with or arising out of the * use of the information or programs contained herein." * * Permission is granted for this code to be used for educational purposes in * association with the book, given proper citation if and when posted or * reproduced.Any commercial use of this code requires the explicit written * permission of the publisher, Addison-Wesley Professional, a division of * Pearson Education, Inc. Send your request for permission, stating clearly * what code you would like to use, and in what specific way, to the following * address: * * Pearson Education, Inc. * Rights and Permissions Department * One Lake Street * Upper Saddle River, NJ 07458 * Fax: (201) 236-3290 */ #include <cstddef> #include <iostream> #include <string> using std::cout; using std::cin; using std::endl; using std::string; using std::size_t; #include <bitset> using std::bitset; int main() { bitset<32> bitvec(1U); // 32 bits; low-order bit is 1, // remaining bits are 0 bool is_set = bitvec.any(); // true, one bit is set bool is_not_set = bitvec.none(); // false, one bit is set bool all_set = bitvec.all(); // false, only one bit is set size_t onBits = bitvec.count(); // returns 1 size_t sz = bitvec.size(); // returns 32 bitvec.flip(); // reverses the value of all the bits in bitvec bitvec.reset(); // sets all the bits to 0 bitvec.set(); // sets all the bits to 1 cout << "bitvec: " << bitvec << endl; sz = bitvec.size(); // returns 32 onBits = bitvec.count(); // returns 1, // i.e., the number of bits that are on // assign 1 to even numbered bits for (int index = 0; index != 32; index += 2) bitvec[index] = 1; // equivalent loop using set operation for (int index = 0; index != 32; index += 2) bitvec.set(index); // bitvec is unchanged auto b2 = ~bitvec; // b2 is a copy of bitvec with every bit flipped // assign value of last bit in bitvec to the first bit in b2 b2[0] = bitvec[bitvec.size() - 1]; bitvec[0] = 0; // turn off the bit at position 0 bitvec[31] = bitvec[0]; // give last bit the same value as the first bitvec[0].flip(); // flip the value of the bit at position 0 ~bitvec[0]; // equivalent; flips the bit at position 0 bool b = bitvec[0]; // convert the value of bitvec[0] to bool b2[0] = ~bitvec[0]; // first bit in b2 has the opposite value // of the first bit in bitvec unsigned i = 0; if (bitvec.test(i)) // bitvec[i] is on ; //equivalent test using subscript if (bitvec[i]) // bitvec[i] is on ; cout << "bitvec: positions turned on:\n\t"; for (int index = 0; index != 32; ++index) if (bitvec[index]) cout << index << " "; cout << endl; // equivalent; turn off first bit bitvec.flip(0); // reverses the value of the first bit bitvec.set(bitvec.size() - 1); // turns on the last bit bitvec.set(0, 0); // turns off the first bit bitvec.reset(i); // turns off the ith bit bitvec.test(0); // returns false because the first bit is off bitvec[0] = 0; bitvec.flip(0); // reverses value of first bit bitvec[0].flip(); // also reverses the first bit cout << "new inits" <<endl; // bits13 is smaller than the initializer; // high-order bits from the initializer are discarded bitset<13> bits13(0xbeef); // bits are 1111011101111 // bits20 is larger than the initializer; // high-order bits in bits20 are set to zero bitset<20> bits20(0xbeef); // bits are 00001011111011101111 // on machines with 64-bit long long 0ULL is 64 bits of 0, // so ~0ULL is 64 ones, so 0 ... 63 are one, and 64 ... 127 are zero // if long long has 32 bits, 0 ... 32 are one, 33 ... 127 are zero bitset<128> bits128(~0ULL); cout << "bits13: " << bits13 << endl; cout << "bits20: " << bits20 << endl; cout << "bits128: " << bits128 << endl; cout << "bits20[0] " << bits20[0] << endl; cout << "bits20[19] " << bits20[19] << endl; // bitvec1 is smaller than the initializer bitset<32> bitvec1(0xffff); // bits 0 ... 15 are set to 1; // 16 ... 31 are 0 // bitvec2 same size as initializer bitset<64> bitvec2(0xffff); // bits 0 ... 15 are set to 1; // 16 ... 63 are 0 // assuming 64-bit long long, bits 0 to 63 initialized from 0xffff bitset<128> bitvec3(0xffff); // bits 32 through 127 are zero cout << "bitvec1: " << bitvec1 << endl; cout << "bitvec2: " << bitvec2 << endl; cout << "bitvec2[0] " << bitvec2[0] << endl; cout << "bitvec2[31] " << bitvec2[31] << endl; cout << "bitvec3: " << bitvec3 << endl; bitset<32> bitvec4("1100"); // bits 2 and 3 are 1, all others are 0 cout << "strval: " << "1100" << endl; cout << "bitvec4: " << bitvec4 << endl; string str("1111111000000011001101"); bitset<32> bitvec5(str, 5, 4); // four bits starting at str[5], 1100 bitset<32> bitvec6(str, str.size()-4); // use last four characters cout << "str: " << str << endl; cout << "bitvec5: " << bitvec5 << endl; cout << "str: " << str << endl; cout << "bitvec6: " << bitvec6 << endl; unsigned long ulong = bitvec3.to_ulong(); cout << "ulong = " << ulong << endl; bitset<32> bitvec7 = bitvec1 & bitvec4; cout << "bitvec7: " << bitvec7 << endl; bitset<32> bitvec8 = bitvec1 | bitvec4; cout << "bitvec8: " << bitvec8 << endl; bitset<16> chk("111100110011001100000"); cout << "chk: " << chk << endl; bitset<16> bits; cin >> bits; // read up to 16 1 or 0 characters from cin cout << "bits: " << bits << endl; // print what we just read return 0; }
34.313187
79
0.626261
cbracb
173b566563ccaa10b290d62104cb8f2e0a0d6646
666
cpp
C++
src/ns_thread.cpp
kingpeter2015/libovmatting
8d2a6b855f7d3aa7a53b6b107072a8619b26cf67
[ "MIT" ]
37
2021-01-29T13:58:20.000Z
2022-03-29T06:57:40.000Z
src/ns_thread.cpp
positive666/libovmatting
8d2a6b855f7d3aa7a53b6b107072a8619b26cf67
[ "MIT" ]
9
2021-04-17T02:57:27.000Z
2022-03-21T12:21:00.000Z
src/ns_thread.cpp
positive666/libovmatting
8d2a6b855f7d3aa7a53b6b107072a8619b26cf67
[ "MIT" ]
7
2021-02-01T03:51:01.000Z
2022-01-20T08:10:06.000Z
#include "ns_thread.hpp" ov_simple_thread::ov_simple_thread() { _interript = false; } ov_simple_thread::~ov_simple_thread() { if (!this->isInterrupted()) { this->interrupt(); } if (_thread.joinable()) { _thread.join(); } } void ov_simple_thread::start() { _interript = false; std::thread thr(std::bind(&ov_simple_thread::run, this)); _thread = std::move(thr); } std::thread::id ov_simple_thread::getId() { return _thread.get_id(); } void ov_simple_thread::interrupt() { _interript = true; } bool ov_simple_thread::isInterrupted() { return _interript; } void ov_simple_thread::join() { _thread.join(); } void ov_simple_thread::run() { }
12.333333
58
0.687688
kingpeter2015
173c4ddd5afa35a316ed37bcaff65c18ffb83198
2,283
cpp
C++
ndn-cxx/interest-filter.cpp
Pesa/ndn-cxx
0249d71d97b2f1f5313f24cec7c84450a795f2ca
[ "OpenSSL" ]
106
2015-01-06T10:08:29.000Z
2022-02-27T13:40:16.000Z
ndn-cxx/interest-filter.cpp
Pesa/ndn-cxx
0249d71d97b2f1f5313f24cec7c84450a795f2ca
[ "OpenSSL" ]
11
2020-12-27T23:02:56.000Z
2021-10-18T08:00:50.000Z
ndn-cxx/interest-filter.cpp
Pesa/ndn-cxx
0249d71d97b2f1f5313f24cec7c84450a795f2ca
[ "OpenSSL" ]
147
2015-01-15T15:07:29.000Z
2022-02-03T13:08:43.000Z
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2013-2019 Regents of the University of California. * * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions). * * ndn-cxx library is free software: you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later version. * * ndn-cxx 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 Lesser General Public License for more details. * * You should have received copies of the GNU General Public License and GNU Lesser * General Public License along with ndn-cxx, e.g., in COPYING.md file. If not, see * <http://www.gnu.org/licenses/>. * * See AUTHORS.md for complete list of ndn-cxx authors and contributors. */ #include "ndn-cxx/interest-filter.hpp" #include "ndn-cxx/util/regex/regex-pattern-list-matcher.hpp" namespace ndn { InterestFilter::InterestFilter(const Name& prefix) : m_prefix(prefix) { } InterestFilter::InterestFilter(const char* prefixUri) : m_prefix(prefixUri) { } InterestFilter::InterestFilter(const std::string& prefixUri) : m_prefix(prefixUri) { } InterestFilter::InterestFilter(const Name& prefix, const std::string& regexFilter) : m_prefix(prefix) , m_regexFilter(make_shared<RegexPatternListMatcher>(regexFilter, nullptr)) { } InterestFilter::operator const Name&() const { if (hasRegexFilter()) { NDN_THROW(Error("Please update InterestCallback to accept `const InterestFilter&'" " (non-trivial InterestFilter is being used)")); } return m_prefix; } bool InterestFilter::doesMatch(const Name& name) const { return m_prefix.isPrefixOf(name) && (!hasRegexFilter() || m_regexFilter->match(name, m_prefix.size(), name.size() - m_prefix.size())); } std::ostream& operator<<(std::ostream& os, const InterestFilter& filter) { os << filter.getPrefix(); if (filter.hasRegexFilter()) { os << "?regex=" << filter.getRegexFilter(); } return os; } } // namespace ndn
30.039474
87
0.715725
Pesa
173df60f3c80d420a17bfd4e55c9c6e113b08dfd
470
cpp
C++
problems/acmicpc_7568.cpp
qawbecrdtey/BOJ-sol
e3f410e8f4e3a6ade51b68ce2024529870edac64
[ "MIT" ]
null
null
null
problems/acmicpc_7568.cpp
qawbecrdtey/BOJ-sol
e3f410e8f4e3a6ade51b68ce2024529870edac64
[ "MIT" ]
null
null
null
problems/acmicpc_7568.cpp
qawbecrdtey/BOJ-sol
e3f410e8f4e3a6ade51b68ce2024529870edac64
[ "MIT" ]
null
null
null
#include <stdio.h> #include <utility> int main() { int n; scanf("%d", &n); auto a = new std::pair<int, int>[n]; auto b = new int[n](); for(int i = 0; i < n; i++) { scanf("%d%d", &a[i].first, &a[i].second); for(int j = 0; j < i; j++) { if(a[j].first < a[i].first && a[j].second < a[i].second) { b[j]++; } if(a[j].first > a[i].first && a[j].second > a[i].second) { b[i]++; } } } for(int i = 0; i < n; i++) { printf("%d ", b[i] + 1); } }
21.363636
61
0.451064
qawbecrdtey
1742888a91f3acec5239447cc80f075577cf1ecb
1,549
cpp
C++
Chapter_13/gallery-desktop/PictureDelegate.cpp
vivekpala/Mastering-Qt-5
51b1589a234b2178a3597fe74483e2992847f69c
[ "MIT" ]
198
2016-12-18T06:34:41.000Z
2022-03-29T13:35:43.000Z
Chapter_13/gallery-desktop/PictureDelegate.cpp
vivekpala/Mastering-Qt-5
51b1589a234b2178a3597fe74483e2992847f69c
[ "MIT" ]
11
2017-04-20T17:03:40.000Z
2021-11-25T09:43:57.000Z
Chapter_13/gallery-desktop/PictureDelegate.cpp
vivekpala/Mastering-Qt-5
51b1589a234b2178a3597fe74483e2992847f69c
[ "MIT" ]
89
2016-12-20T14:47:29.000Z
2022-02-15T00:20:50.000Z
#include "PictureDelegate.h" #include <QPainter> const unsigned int BANNER_HEIGHT = 20; const unsigned int BANNER_COLOR = 0x303030; const unsigned int BANNER_ALPHA = 200; const unsigned int BANNER_TEXT_COLOR = 0xffffff; const unsigned int HIGHLIGHT_ALPHA = 100; PictureDelegate::PictureDelegate(QObject* parent) : QStyledItemDelegate(parent) { } void PictureDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { painter->save(); QPixmap pixmap = index.model()->data(index, Qt::DecorationRole).value<QPixmap>(); painter->drawPixmap(option.rect.x(), option.rect.y(), pixmap); QRect bannerRect = QRect(option.rect.x(), option.rect.y(), pixmap.width(), BANNER_HEIGHT); QColor bannerColor = QColor(BANNER_COLOR); bannerColor.setAlpha(BANNER_ALPHA); painter->fillRect(bannerRect, bannerColor); QString filename = index.model()->data(index, Qt::DisplayRole).toString(); painter->setPen(BANNER_TEXT_COLOR); painter->drawText(bannerRect, Qt::AlignCenter, filename); if (option.state.testFlag(QStyle::State_Selected)) { QColor selectedColor = option.palette.highlight().color(); selectedColor.setAlpha(HIGHLIGHT_ALPHA); painter->fillRect(option.rect, selectedColor); } painter->restore(); } QSize PictureDelegate::sizeHint(const QStyleOptionViewItem& /*option*/, const QModelIndex& index) const { const QPixmap& pixmap = index.model()->data(index, Qt::DecorationRole).value<QPixmap>(); return pixmap.size(); }
33.673913
114
0.730148
vivekpala
1746c0b79c8f0044bc3f8ec83e1da6604e3bd573
840
cpp
C++
src/git/Blob.cpp
mmahmoudian/Gittyup
96702f3b96160fff540886722f7f195163c4e41b
[ "MIT" ]
127
2021-10-29T19:01:32.000Z
2022-03-31T18:23:56.000Z
src/git/Blob.cpp
mmahmoudian/Gittyup
96702f3b96160fff540886722f7f195163c4e41b
[ "MIT" ]
90
2021-11-05T13:03:58.000Z
2022-03-30T16:42:49.000Z
src/git/Blob.cpp
mmahmoudian/Gittyup
96702f3b96160fff540886722f7f195163c4e41b
[ "MIT" ]
20
2021-10-30T12:25:33.000Z
2022-02-18T03:08:21.000Z
// // Copyright (c) 2016, Scientific Toolworks, Inc. // // This software is licensed under the MIT License. The LICENSE.md file // describes the conditions under which this software may be distributed. // // Author: Jason Haslam // #include "Blob.h" namespace git { Blob::Blob() : Object() {} Blob::Blob(const Object &rhs) : Object(rhs) { if (isValid() && type() != GIT_OBJECT_BLOB) d.clear(); } Blob::Blob(git_blob *blob) : Object(reinterpret_cast<git_object *>(blob)) {} Blob::operator git_blob *() const { return reinterpret_cast<git_blob *>(d.data()); } bool Blob::isBinary() const { return git_blob_is_binary(*this); } QByteArray Blob::content() const { const char *content = static_cast<const char *>(git_blob_rawcontent(*this)); return QByteArray(content, git_blob_rawsize(*this)); } } // namespace git
24
78
0.686905
mmahmoudian
1747b7bfd4970fb8f467d8bd8a3d62eb364d9f35
3,788
c++
C++
tests/core/value_ptr.test.c++
1094387012/SKUI
c85dd7fb9d30ff15d5d6de184670cb47e46df6de
[ "MIT" ]
309
2017-05-06T02:15:43.000Z
2022-03-23T08:27:05.000Z
tests/core/value_ptr.test.c++
qdtroy/skui
201707d06bd29c9ec4b05350b25b777493d5362e
[ "MIT" ]
20
2018-05-11T20:56:45.000Z
2022-03-11T06:10:12.000Z
tests/core/value_ptr.test.c++
qdtroy/skui
201707d06bd29c9ec4b05350b25b777493d5362e
[ "MIT" ]
48
2017-06-27T06:04:15.000Z
2022-03-01T12:56:32.000Z
/** * The MIT License (MIT) * * Copyright © 2017-2020 Ruben Van Boxem * * 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 "test.h++" #include "core/value_ptr.h++" namespace { using skui::test::check; struct Base { Base() = default; virtual ~Base() = default; Base(const Base&) = default; }; struct Derived : Base {}; void test_smart_copy() { skui::core::smart_copy<Base> base_copy; skui::core::smart_copy<Derived> derived_copy; base_copy = derived_copy; check(base_copy.get_copy_function() == derived_copy.get_copy_function(), ""); } void test_value_ptr_constructors_get() { { auto* derived = new Derived; skui::core::value_ptr<Derived> derived_ptr(derived); check(derived_ptr.get() == derived, "constructor stores pointer"); } { auto* derived = new Derived; skui::core::value_ptr<Base> base_ptr(derived); check(base_ptr.get() == derived, "value_ptr<Base> correctly constructed from derived"); } } void test_value_ptr_copy() { skui::core::value_ptr<Base, skui::core::smart_copy<Derived>> base_ptr(new Derived); skui::core::value_ptr<Base> base_ptr_copy(base_ptr); check(base_ptr.get() != nullptr, "copied-from value_ptr is not nullptr"); check(base_ptr_copy.get() != nullptr, "copied-to value_ptr is not nullptr"); check(base_ptr_copy.get() != base_ptr.get(), "value_ptr copy constructor copies"); check(dynamic_cast<Derived*>(base_ptr_copy.get()) != nullptr, "value_ptr copy constructor maintains dynamic type"); } void test_value_ptr_move() { skui::core::value_ptr<Base, skui::core::smart_copy<Derived>> base_ptr(new Derived); skui::core::value_ptr<Base> base_ptr_move = std::move(base_ptr); check(base_ptr.get() == nullptr, "moved-from value_ptr is nullptr"); check(base_ptr_move.get() != nullptr, "moved-to value_ptr is not nullptr"); check(dynamic_cast<Derived*>(base_ptr_move.get()) != nullptr, "value_ptr move maintains dynamic type"); } void test_value_ptr_make_value() { skui::core::value_ptr<Base> ptr = skui::core::make_value<Derived>(); skui::core::value_ptr<Base> ptr_copy(ptr); skui::core::value_ptr<Base> ptr_copy2(ptr_copy); check(dynamic_cast<Derived*>(ptr.get()) != nullptr, "make_value maintains dynamic type"); check(dynamic_cast<Derived*>(ptr_copy.get()) != nullptr, "copy of make_value maintains dynamic type"); check(dynamic_cast<Derived*>(ptr_copy2.get()) != nullptr, "copy of of copy of make_value maintains dynamic type"); } } int main() { test_smart_copy(); test_value_ptr_constructors_get(); test_value_ptr_copy(); test_value_ptr_move(); test_value_ptr_make_value(); return skui::test::exit_code; }
33.522124
119
0.708025
1094387012
174853dfadf486708858bbf6a4f7106bb71200d7
3,834
cpp
C++
yampt.tests/tests.dictcreator.cpp
raffll/yampt
d3f97502b2979f0b189c312a255666950af74232
[ "MIT" ]
19
2016-10-23T12:24:12.000Z
2022-01-30T22:44:22.000Z
yampt.tests/tests.dictcreator.cpp
raffll/yampt
d3f97502b2979f0b189c312a255666950af74232
[ "MIT" ]
16
2018-12-15T11:56:39.000Z
2021-06-08T14:48:07.000Z
yampt.tests/tests.dictcreator.cpp
raffll/yampt
d3f97502b2979f0b189c312a255666950af74232
[ "MIT" ]
1
2021-05-30T12:27:42.000Z
2021-05-30T12:27:42.000Z
#include "catch.hpp" #include "../yampt/tools.hpp" #include "../yampt/esmreader.hpp" #include "../yampt/dictcreator.hpp" TEST_CASE("create raw", "[i]") { DictCreator esm("master/en/Morrowind.esm"); REQUIRE(esm.getDict().at(Tools::RecType::CELL).begin()->first == "Abaelun Mine"); REQUIRE(esm.getDict().at(Tools::RecType::CELL).begin()->second == "Abaelun Mine"); REQUIRE(esm.getDict().at(Tools::RecType::DIAL).begin()->first == "1000-drake pledge"); REQUIRE(esm.getDict().at(Tools::RecType::DIAL).begin()->second == "1000-drake pledge"); REQUIRE(esm.getDict().at(Tools::RecType::INDX).begin()->first == "MGEF^000"); REQUIRE(esm.getDict().at(Tools::RecType::INDX).begin()->second == "This effect permits the subject to breathe underwater for the duration."); REQUIRE(esm.getDict().at(Tools::RecType::RNAM).begin()->first == "Ashlanders^0"); REQUIRE(esm.getDict().at(Tools::RecType::RNAM).begin()->second == "Clanfriend"); REQUIRE(esm.getDict().at(Tools::RecType::DESC).begin()->first == "BSGN^Beggar's Nose"); REQUIRE(esm.getDict().at(Tools::RecType::DESC).begin()->second == "Constellation of The Tower with a Prime Aspect of Secunda."); REQUIRE(esm.getDict().at(Tools::RecType::GMST).begin()->first == "s3dAudio"); REQUIRE(esm.getDict().at(Tools::RecType::GMST).begin()->second == "3D Audio"); REQUIRE(esm.getDict().at(Tools::RecType::FNAM).begin()->first == "ACTI^A_Ex_De_Oar"); REQUIRE(esm.getDict().at(Tools::RecType::FNAM).begin()->second == "Oar"); REQUIRE(esm.getDict().at(Tools::RecType::INFO).begin()->first == "G^Greeting 0^1046442603030210731"); REQUIRE(esm.getDict().at(Tools::RecType::INFO).begin()->second == "I've heard you've got a price on your head, %PCRank. For a small fee, I can take care of that."); REQUIRE(esm.getDict().at(Tools::RecType::TEXT).begin()->first == "BookSkill_Acrobatics2"); REQUIRE(esm.getDict().at(Tools::RecType::TEXT).begin()->second.size() == 10305); REQUIRE(esm.getDict().at(Tools::RecType::BNAM).begin()->first == esm.getDict().at(Tools::RecType::BNAM).begin()->second); REQUIRE(esm.getDict().at(Tools::RecType::SCTX).begin()->first == esm.getDict().at(Tools::RecType::SCTX).begin()->second); } TEST_CASE("create base, same record order", "[i]") { DictCreator esm("master/pl/Morrowind.esm", "master/en/Morrowind.esm"); auto search = esm.getDict().at(Tools::RecType::CELL).find("Abaelun Mine"); REQUIRE(search != esm.getDict().at(Tools::RecType::CELL).end()); REQUIRE(search->second == "Kopalnia Abaelun"); search = esm.getDict().at(Tools::RecType::DIAL).find("Abebaal Egg Mine"); REQUIRE(search != esm.getDict().at(Tools::RecType::DIAL).end()); REQUIRE(search->second == "kopalnia jaj Abebaal"); search = esm.getDict().at(Tools::RecType::INFO).find("T^kopalnia jaj Abebaal^3253555431180022526"); REQUIRE(search != esm.getDict().at(Tools::RecType::INFO).end()); search = esm.getDict().at(Tools::RecType::INFO).find("T^Abebaal Egg Mine^3253555431180022526"); REQUIRE(search == esm.getDict().at(Tools::RecType::INFO).end()); } TEST_CASE("create base, different record order", "[i]") { DictCreator esm("master/de/Morrowind.esm", "master/en/Morrowind.esm"); auto search = esm.getDict().at(Tools::RecType::CELL).find("Abaelun Mine"); REQUIRE(search != esm.getDict().at(Tools::RecType::CELL).end()); REQUIRE(search->second == "Abaelun-Mine"); search = esm.getDict().at(Tools::RecType::CELL).find("Aharunartus"); REQUIRE(search != esm.getDict().at(Tools::RecType::CELL).end()); REQUIRE(search->second == "<err name=\"MISSING\"/>"); search = esm.getDict().at(Tools::RecType::DIAL).find("Abebaal Egg Mine"); REQUIRE(search != esm.getDict().at(Tools::RecType::DIAL).end()); REQUIRE(search->second == "Eiermine Abebaal"); }
58.984615
168
0.666145
raffll
174dcb53c569ab01ef712200e09054dbe0f9e9fc
633
cpp
C++
common/MessageQueue.cpp
lucabello/kangaroo-docs
1d4b6ac044250457a9957ed3ec1ee8b89a99e456
[ "MIT" ]
1
2020-04-11T14:18:54.000Z
2020-04-11T14:18:54.000Z
common/MessageQueue.cpp
lucabello/kangaroo-docs
1d4b6ac044250457a9957ed3ec1ee8b89a99e456
[ "MIT" ]
null
null
null
common/MessageQueue.cpp
lucabello/kangaroo-docs
1d4b6ac044250457a9957ed3ec1ee8b89a99e456
[ "MIT" ]
null
null
null
#include "MessageQueue.h" int MessageQueue::count(){ QMutexLocker locker(&mutex); int count = queue.count(); return count; } bool MessageQueue::isEmpty(){ QMutexLocker locker(&mutex); bool empty = queue.isEmpty(); return empty; } void MessageQueue::clear(){ QMutexLocker locker(&mutex); queue.clear(); } void MessageQueue::push(const Message& m){ QMutexLocker locker(&mutex); queue.enqueue(m); cv.notify_all(); } Message MessageQueue::pop(){ QMutexLocker locker(&mutex); while(queue.isEmpty()) cv.wait(locker.mutex()); Message m = queue.dequeue(); return m; }
19.181818
42
0.649289
lucabello
174e0f0f344dafe9204933c6819d28e72d6fef21
3,662
cpp
C++
tests/TestDataScalar.cpp
Glebanister/spla
6951af369e359827729fd12b08f5df0ba3dac8ef
[ "MIT" ]
10
2021-09-24T03:48:31.000Z
2022-02-07T09:09:01.000Z
tests/TestDataScalar.cpp
Glebanister/spla
6951af369e359827729fd12b08f5df0ba3dac8ef
[ "MIT" ]
78
2021-09-11T09:39:04.000Z
2022-02-11T19:50:07.000Z
tests/TestDataScalar.cpp
Glebanister/spla
6951af369e359827729fd12b08f5df0ba3dac8ef
[ "MIT" ]
3
2021-09-20T15:43:54.000Z
2022-02-15T11:29:52.000Z
/**********************************************************************************/ /* This file is part of spla project */ /* https://github.com/JetBrains-Research/spla */ /**********************************************************************************/ /* MIT License */ /* */ /* Copyright (c) 2021 JetBrains-Research */ /* */ /* 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 <Testing.hpp> template<typename T, typename Gen> void test(std::size_t iterations, std::size_t seed, const spla::RefPtr<spla::Type> &spT, spla::Library &library) { Gen generator(seed); auto spDataWrite = spla::DataScalar::Make(library); auto spDataRead = spla::DataScalar::Make(library); ASSERT_EQ(sizeof(T), spT->GetByteSize()); for (std::size_t k = 0; k < iterations; k++) { T value = generator(); std::vector<T> result(1); spDataWrite->SetValue(&value); spDataRead->SetValue(result.data()); auto spScalar = spla::Scalar::Make(spT, library); auto spExpr = spla::Expression::Make(library); auto spWrite = spExpr->MakeDataWrite(spScalar, spDataWrite); auto spRead = spExpr->MakeDataRead(spScalar, spDataRead); spExpr->Dependency(spWrite, spRead); spExpr->Submit(); spExpr->Wait(); ASSERT_EQ(spExpr->GetState(), spla::Expression::State::Evaluated); ASSERT_EQ(value, result.front()); } } TEST(DataScalar, Float) { spla::Library library; spla::RefPtr<spla::Type> type = spla::Types::Float32(library); test<float, utils::UniformRealGenerator<float>>(10, 0, type, library); } TEST(DataScalar, Int) { spla::Library library; spla::RefPtr<spla::Type> type = spla::Types::Int32(library); test<std::int32_t, utils::UniformIntGenerator<std::int32_t>>(10, 0, type, library); } SPLA_GTEST_MAIN
51.577465
114
0.512288
Glebanister
1757e4a4d9dd18d774b0353d885f694afac4249f
460
cpp
C++
lib/service/Service.cpp
p0thi/ARDUINO
ed06934163c5ccfc75f95b74210217a406ede793
[ "MIT" ]
314
2018-09-07T18:30:29.000Z
2022-03-27T05:25:45.000Z
lib/service/Service.cpp
p0thi/ARDUINO
ed06934163c5ccfc75f95b74210217a406ede793
[ "MIT" ]
89
2018-09-07T02:29:20.000Z
2022-03-15T20:55:24.000Z
lib/service/Service.cpp
p0thi/ARDUINO
ed06934163c5ccfc75f95b74210217a406ede793
[ "MIT" ]
64
2018-09-07T02:32:52.000Z
2022-03-31T13:34:28.000Z
#include "Service.h" #define LOG_MAX_LEN 64 static Print *stream = nullptr; void __log_init__(Print *printer) { stream = printer; } void __log__(const __FlashStringHelper *fmt, ...) { if (!stream) return; char buf[LOG_MAX_LEN]; sprintf_P(buf, (PGM_P) F("%010ld | "), millis()); stream->print(buf); va_list args; va_start(args, fmt); vsnprintf_P(buf, LOG_MAX_LEN, (PGM_P) fmt, args); va_end(args); stream->println(buf); }
24.210526
55
0.654348
p0thi
1758bb03ad62a86f9e758ea23cee19423fcdca3a
350
cpp
C++
codeforces/800/732A-BuyaShovel.cpp
thesaravanakumar/competative-programming
828b9973bbd90945d6edf3719dc2d29213acc3a5
[ "MIT" ]
null
null
null
codeforces/800/732A-BuyaShovel.cpp
thesaravanakumar/competative-programming
828b9973bbd90945d6edf3719dc2d29213acc3a5
[ "MIT" ]
null
null
null
codeforces/800/732A-BuyaShovel.cpp
thesaravanakumar/competative-programming
828b9973bbd90945d6edf3719dc2d29213acc3a5
[ "MIT" ]
null
null
null
/*●▬▬▬▬▬๑۩۩๑▬▬▬▬●●▬▬▬▬▬๑۩۩๑▬▬▬▬●🆀🆄🅰🅺🅴●▬▬▬▬▬๑۩۩๑▬▬▬▬●●▬▬▬▬▬๑۩۩๑▬▬▬▬●*/ #include <bits/stdc++.h> #define ll long long int using namespace std; int main() { int k,r; cin>>k>>r; int a=k,i; for(i=1;k%10!=r&&k%10!=0;i++){ k+=a; } cout<<i; return 0; } /*●▬▬▬▬▬๑۩۩๑▬▬▬▬●●▬▬▬▬▬๑۩۩๑▬▬▬▬●🆀🆄🅰🅺🅴●▬▬▬▬▬๑۩۩๑▬▬▬▬●●▬▬▬▬▬๑۩۩๑▬▬▬▬●*/
21.875
69
0.34
thesaravanakumar
175fb259a78b86c120b09ef2ef23d63ddbde8f7a
43,073
hpp
C++
include/ginkgo/core/base/range.hpp
kliegeois/ginkgo
4defcc07f77828393cc5b4a735a00e50da2cbab0
[ "BSD-3-Clause" ]
null
null
null
include/ginkgo/core/base/range.hpp
kliegeois/ginkgo
4defcc07f77828393cc5b4a735a00e50da2cbab0
[ "BSD-3-Clause" ]
null
null
null
include/ginkgo/core/base/range.hpp
kliegeois/ginkgo
4defcc07f77828393cc5b4a735a00e50da2cbab0
[ "BSD-3-Clause" ]
null
null
null
/*******************************<GINKGO LICENSE>****************************** Copyright (c) 2017-2022, the Ginkgo authors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************<GINKGO LICENSE>*******************************/ #ifndef GKO_PUBLIC_CORE_BASE_RANGE_HPP_ #define GKO_PUBLIC_CORE_BASE_RANGE_HPP_ #include <type_traits> #include <ginkgo/core/base/math.hpp> #include <ginkgo/core/base/types.hpp> #include <ginkgo/core/base/utils.hpp> namespace gko { /** * A span is a lightweight structure used to create sub-ranges from other * ranges. * * A `span s` represents a contiguous set of indexes in one dimension of the * range, starting on index `s.begin` (inclusive) and ending at index `s.end` * (exclusive). A span is only valid if its starting index is smaller than its * ending index. * * Spans can be compared using the `==` and `!=` operators. Two spans are * identical if both their `begin` and `end` values are identical. * * Spans also have two distinct partial orders defined on them: * 1. `x < y` (`y > x`) if and only if `x.end < y.begin` * 2. `x <= y` (`y >= x`) if and only if `x.end <= y.begin` * * Note that the orders are in fact partial - there are spans `x` and `y` for * which none of the following inequalities holds: * `x < y`, `x > y`, `x == y`, `x <= y`, `x >= y`. * An example are spans `span{0, 2}` and `span{1, 3}`. * * In addition, `<=` is a distinct order from `<`, and not just an extension * of the strict order to its weak equivalent. Thus, `x <= y` is not equivalent * to `x < y || x == y`. * * @ingroup ranges */ struct span { /** * Creates a span representing a point `point`. * * The `begin` of this span is set to `point`, and the `end` to `point + 1`. * * @param point the point which the span represents */ GKO_ATTRIBUTES constexpr span(size_type point) noexcept : span{point, point + 1} {} /** * Creates a span. * * @param begin the beginning of the span * @param end the end of the span */ GKO_ATTRIBUTES constexpr span(size_type begin, size_type end) noexcept : begin{begin}, end{end} {} /** * Checks if a span is valid. * * @return true if and only if `this->begin < this->end` */ GKO_ATTRIBUTES constexpr bool is_valid() const { return begin < end; } /** * Returns the length of a span. * * @return `this->end - this->begin` */ GKO_ATTRIBUTES constexpr size_type length() const { return end - begin; } /** * Beginning of the span. */ const size_type begin; /** * End of the span. */ const size_type end; }; GKO_ATTRIBUTES GKO_INLINE constexpr bool operator<(const span& first, const span& second) { return first.end < second.begin; } GKO_ATTRIBUTES GKO_INLINE constexpr bool operator<=(const span& first, const span& second) { return first.end <= second.begin; } GKO_ATTRIBUTES GKO_INLINE constexpr bool operator>(const span& first, const span& second) { return second < first; } GKO_ATTRIBUTES GKO_INLINE constexpr bool operator>=(const span& first, const span& second) { return second <= first; } GKO_ATTRIBUTES GKO_INLINE constexpr bool operator==(const span& first, const span& second) { return first.begin == second.begin && first.end == second.end; } GKO_ATTRIBUTES GKO_INLINE constexpr bool operator!=(const span& first, const span& second) { return !(first == second); } namespace detail { template <size_type CurrentDimension = 0, typename FirstRange, typename SecondRange> GKO_ATTRIBUTES constexpr GKO_INLINE std::enable_if_t<(CurrentDimension >= max(FirstRange::dimensionality, SecondRange::dimensionality)), bool> equal_dimensions(const FirstRange&, const SecondRange&) { return true; } template <size_type CurrentDimension = 0, typename FirstRange, typename SecondRange> GKO_ATTRIBUTES constexpr GKO_INLINE std::enable_if_t<(CurrentDimension < max(FirstRange::dimensionality, SecondRange::dimensionality)), bool> equal_dimensions(const FirstRange& first, const SecondRange& second) { return first.length(CurrentDimension) == second.length(CurrentDimension) && equal_dimensions<CurrentDimension + 1>(first, second); } } // namespace detail /** * A range is a multidimensional view of the memory. * * The range does not store any of its values by itself. Instead, it obtains the * values through an accessor (e.g. accessor::row_major) which describes how the * indexes of the range map to physical locations in memory. * * There are several advantages of using ranges instead of plain memory * pointers: * * 1. Code using ranges is easier to read and write, as there is no need for * index linearizations. * 2. Code using ranges is safer, as it is impossible to accidentally * miscalculate an index or step out of bounds, since range accessors * perform bounds checking in debug builds. For performance, this can be * disabled in release builds by defining the `NDEBUG` flag. * 3. Ranges enable generalized code, as algorithms can be written independent * of the memory layout. This does not impede various optimizations based * on memory layout, as it is always possible to specialize algorithms for * ranges with specific memory layouts. * 4. Ranges have various pointwise operations predefined, which reduces the * amount of loops that need to be written. * * Range operations * ---------------- * * Ranges define a complete set of pointwise unary and binary operators which * extend the basic arithmetic operators in C++, as well as a few pointwise * operations and mathematical functions useful in ginkgo, and a couple of * non-pointwise operations. Compound assignment (`+=`, `*=`, etc.) is not yet * supported at this moment. Here is a complete list of operations: * * - standard unary operations: `+`, `-`, `!`, `~` * - standard binary operations: `+`, `*` (this is pointwise, not * matrix multiplication), `/`, `%`, `<`, `>`, `<=`, `>=`, `==`, `!=`, * `||`, `&&`, `|`, `&`, `^`, `<<`, `>>` * - useful unary functions: `zero`, `one`, `abs`, `real`, `imag`, `conj`, * `squared_norm` * - useful binary functions: `min`, `max` * * All binary pointwise operations also work as expected if one of the operands * is a scalar and the other is a range. The scalar operand will have the effect * as if it was a range of the same size as the other operand, filled with * the specified scalar. * * Two "global" functions `transpose` and `mmul` are also supported. * `transpose` transposes the first two dimensions of the range (i.e. * `transpose(r)(i, j, ...) == r(j, i, ...)`). * `mmul` performs a (batched) matrix multiply of the ranges - the first two * dimensions represent the matrices, while the rest represent the batch. * For example, given the ranges `r1` and `r2` of dimensions `(3, 2, 3)` and * `(2, 4, 3)`, respectively, `mmul(r1, r2)` will return a range of dimensions * `(3, 4, 3)`, obtained by multiplying the 3 frontal slices of the range, and * stacking the result back vertically. * * Compound operations * ------------------- * * Multiple range operations can be combined into a single expression. For * example, an "axpy" operation can be obtained using `y = alpha * x + y`, where * `x` an `y` are ranges, and `alpha` is a scalar. * Range operations are optimized for memory access, and the above code does not * allocate additional storage for intermediate ranges `alpha * x` * or `aplha * x + y`. In fact, the entire computation is done during the * assignment, and the results of operations `+` and `*` only register the data, * and the types of operations that will be computed once the results are * needed. * * It is possible to store and reuse these intermediate expressions. The * following example will overwrite the range `x` with it's 4th power: * * ```c++ * auto square = x * x; // this is range constructor, not range assignment! * x = square; // overwrites x with x*x (this is range assignment) * x = square; // overwrites new x (x*x) with (x*x)*(x*x) (as is this) * ``` * * Caveats * ------- * * __`mmul` is not a highly-optimized BLAS-3 version of the matrix * multiplication.__ The current design of ranges and accessors prevents that, * so if you need a high-perfromance matrix multiplication, you should use one * of the libraries that provide that, or implement your own * (you can use pointwise range operations to help simplify that). However, * range design might get improved in the future to allow efficient * implementations of BLAS-3 kernels. * * Aliasing the result range in `mmul` and `transpose` is not allowed. * Constructs like `A = transpose(A)`, `A = mmul(A, A)`, or `A = mmul(A, A) + C` * lead to undefined behavior. * However, aliasing input arguments is allowed: `C = mmul(A, A)`, and even * `C = mmul(A, A) + C` is valid code (in the last example, only pointwise * operations are aliased). `C = mmul(A, A + C)` is not valid though. * * Examples * -------- * * The range unit tests in core/test/base/range.cpp contain lots of simple * 1-line examples of range operations. The accessor unit tests in * core/test/base/range.cpp show how to use ranges with concrete accessors, * and how to use range slices using `span`s as arguments to range function call * operator. Finally, examples/range contains a complete example where ranges * are used to implement a simple version of the right-looking LU factorization. * * @tparam Accessor underlying accessor of the range * * @ingroup ranges */ template <typename Accessor> class range { public: /** * The type of the underlying accessor. */ using accessor = Accessor; /** * The number of dimensions of the range. */ static constexpr size_type dimensionality = accessor::dimensionality; /** * Use the default destructor. */ ~range() = default; /** * Creates a new range. * * @tparam AccessorParam types of parameters forwarded to the accessor * constructor * * @param params parameters forwarded to Accessor constructor. */ template <typename... AccessorParams> GKO_ATTRIBUTES constexpr explicit range(AccessorParams&&... params) : accessor_{std::forward<AccessorParams>(params)...} {} /** * Returns a value (or a sub-range) with the specified indexes. * * @tparam DimensionTypes The types of indexes. Supported types depend on * the underlying accessor, but are usually either * integer types or spans. If at least one index is * a span, the returned value will be a sub-range. * * @param dimensions the indexes of the values. * * @return a value on position `(dimensions...)`. */ template <typename... DimensionTypes> GKO_ATTRIBUTES constexpr auto operator()(DimensionTypes&&... dimensions) const -> decltype(std::declval<accessor>()( std::forward<DimensionTypes>(dimensions)...)) { static_assert(sizeof...(DimensionTypes) <= dimensionality, "Too many dimensions in range call"); return accessor_(std::forward<DimensionTypes>(dimensions)...); } /** * @copydoc operator=(const range &other) * * This is a version of the function which allows to copy between ranges * of different accessors. * * @tparam OtherAccessor accessor of the other range */ template <typename OtherAccessor> GKO_ATTRIBUTES const range& operator=( const range<OtherAccessor>& other) const { GKO_ASSERT(detail::equal_dimensions(*this, other)); accessor_.copy_from(other); return *this; } /** * Assigns another range to this range. * * The order of assignment is defined by the accessor of this range, thus * the memory access will be optimized for the resulting range, and not for * the other range. If the sizes of two ranges do not match, the result is * undefined. Sizes of the ranges are checked at runtime in debug builds. * * @note Temporary accessors are allowed to define the implementation of * the assignment as deleted, so do not expect `r1 * r2 = r2` to work. * * @param other the range to copy the data from */ GKO_ATTRIBUTES const range& operator=(const range& other) const { GKO_ASSERT(detail::equal_dimensions(*this, other)); accessor_.copy_from(other.get_accessor()); return *this; } range(const range& other) = default; /** * Returns the length of the specified dimension of the range. * * @param dimension the dimensions whose length is returned * * @return the length of the `dimension`-th dimension of the range */ GKO_ATTRIBUTES constexpr size_type length(size_type dimension) const { return accessor_.length(dimension); } /** * Returns a pointer to the accessor. * * Can be used to access data and functions of a specific accessor. * * @return pointer to the accessor */ GKO_ATTRIBUTES constexpr const accessor* operator->() const noexcept { return &accessor_; } /** * `Returns a reference to the accessor. * * @return reference to the accessor */ GKO_ATTRIBUTES constexpr const accessor& get_accessor() const noexcept { return accessor_; } private: accessor accessor_; }; // implementation of range operations follows // (you probably should not have to look at this unless you're interested in the // gory details) namespace detail { enum class operation_kind { range_by_range, scalar_by_range, range_by_scalar }; template <typename Accessor, typename Operation> struct implement_unary_operation { using accessor = Accessor; static constexpr size_type dimensionality = accessor::dimensionality; GKO_ATTRIBUTES constexpr explicit implement_unary_operation( const Accessor& operand) : operand{operand} {} template <typename... DimensionTypes> GKO_ATTRIBUTES constexpr auto operator()( const DimensionTypes&... dimensions) const -> decltype(Operation::evaluate(std::declval<accessor>(), dimensions...)) { return Operation::evaluate(operand, dimensions...); } GKO_ATTRIBUTES constexpr size_type length(size_type dimension) const { return operand.length(dimension); } template <typename OtherAccessor> GKO_ATTRIBUTES void copy_from(const OtherAccessor& other) const = delete; const accessor operand; }; template <operation_kind Kind, typename FirstOperand, typename SecondOperand, typename Operation> struct implement_binary_operation {}; template <typename FirstAccessor, typename SecondAccessor, typename Operation> struct implement_binary_operation<operation_kind::range_by_range, FirstAccessor, SecondAccessor, Operation> { using first_accessor = FirstAccessor; using second_accessor = SecondAccessor; static_assert(first_accessor::dimensionality == second_accessor::dimensionality, "Both ranges need to have the same number of dimensions"); static constexpr size_type dimensionality = first_accessor::dimensionality; GKO_ATTRIBUTES explicit implement_binary_operation( const FirstAccessor& first, const SecondAccessor& second) : first{first}, second{second} { GKO_ASSERT(gko::detail::equal_dimensions(first, second)); } template <typename... DimensionTypes> GKO_ATTRIBUTES constexpr auto operator()( const DimensionTypes&... dimensions) const -> decltype(Operation::evaluate_range_by_range( std::declval<first_accessor>(), std::declval<second_accessor>(), dimensions...)) { return Operation::evaluate_range_by_range(first, second, dimensions...); } GKO_ATTRIBUTES constexpr size_type length(size_type dimension) const { return first.length(dimension); } template <typename OtherAccessor> GKO_ATTRIBUTES void copy_from(const OtherAccessor& other) const = delete; const first_accessor first; const second_accessor second; }; template <typename FirstOperand, typename SecondAccessor, typename Operation> struct implement_binary_operation<operation_kind::scalar_by_range, FirstOperand, SecondAccessor, Operation> { using second_accessor = SecondAccessor; static constexpr size_type dimensionality = second_accessor::dimensionality; GKO_ATTRIBUTES constexpr explicit implement_binary_operation( const FirstOperand& first, const SecondAccessor& second) : first{first}, second{second} {} template <typename... DimensionTypes> GKO_ATTRIBUTES constexpr auto operator()( const DimensionTypes&... dimensions) const -> decltype(Operation::evaluate_scalar_by_range( std::declval<FirstOperand>(), std::declval<second_accessor>(), dimensions...)) { return Operation::evaluate_scalar_by_range(first, second, dimensions...); } GKO_ATTRIBUTES constexpr size_type length(size_type dimension) const { return second.length(dimension); } template <typename OtherAccessor> GKO_ATTRIBUTES void copy_from(const OtherAccessor& other) const = delete; const FirstOperand first; const second_accessor second; }; template <typename FirstAccessor, typename SecondOperand, typename Operation> struct implement_binary_operation<operation_kind::range_by_scalar, FirstAccessor, SecondOperand, Operation> { using first_accessor = FirstAccessor; static constexpr size_type dimensionality = first_accessor::dimensionality; GKO_ATTRIBUTES constexpr explicit implement_binary_operation( const FirstAccessor& first, const SecondOperand& second) : first{first}, second{second} {} template <typename... DimensionTypes> GKO_ATTRIBUTES constexpr auto operator()( const DimensionTypes&... dimensions) const -> decltype(Operation::evaluate_range_by_scalar( std::declval<first_accessor>(), std::declval<SecondOperand>(), dimensions...)) { return Operation::evaluate_range_by_scalar(first, second, dimensions...); } GKO_ATTRIBUTES constexpr size_type length(size_type dimension) const { return first.length(dimension); } template <typename OtherAccessor> GKO_ATTRIBUTES void copy_from(const OtherAccessor& other) const = delete; const first_accessor first; const SecondOperand second; }; } // namespace detail #define GKO_ENABLE_UNARY_RANGE_OPERATION(_operation_name, _operator_name, \ _operator) \ namespace accessor { \ template <typename Operand> \ struct _operation_name \ : ::gko::detail::implement_unary_operation<Operand, \ ::gko::_operator> { \ using ::gko::detail::implement_unary_operation< \ Operand, ::gko::_operator>::implement_unary_operation; \ }; \ } \ GKO_BIND_UNARY_RANGE_OPERATION_TO_OPERATOR(_operation_name, _operator_name) #define GKO_BIND_UNARY_RANGE_OPERATION_TO_OPERATOR(_operation_name, \ _operator_name) \ template <typename Accessor> \ GKO_ATTRIBUTES constexpr GKO_INLINE \ range<accessor::_operation_name<Accessor>> \ _operator_name(const range<Accessor>& operand) \ { \ return range<accessor::_operation_name<Accessor>>( \ operand.get_accessor()); \ } \ static_assert(true, \ "This assert is used to counter the false positive extra " \ "semi-colon warnings") #define GKO_DEFINE_SIMPLE_UNARY_OPERATION(_name, ...) \ struct _name { \ private: \ template <typename Operand> \ GKO_ATTRIBUTES static constexpr auto simple_evaluate_impl( \ const Operand& operand) -> decltype(__VA_ARGS__) \ { \ return __VA_ARGS__; \ } \ \ public: \ template <typename AccessorType, typename... DimensionTypes> \ GKO_ATTRIBUTES static constexpr auto evaluate( \ const AccessorType& accessor, const DimensionTypes&... dimensions) \ -> decltype(simple_evaluate_impl(accessor(dimensions...))) \ { \ return simple_evaluate_impl(accessor(dimensions...)); \ } \ } namespace accessor { namespace detail { // unary arithmetic GKO_DEFINE_SIMPLE_UNARY_OPERATION(unary_plus, +operand); GKO_DEFINE_SIMPLE_UNARY_OPERATION(unary_minus, -operand); // unary logical GKO_DEFINE_SIMPLE_UNARY_OPERATION(logical_not, !operand); // unary bitwise GKO_DEFINE_SIMPLE_UNARY_OPERATION(bitwise_not, ~(operand)); // common functions GKO_DEFINE_SIMPLE_UNARY_OPERATION(zero_operation, zero(operand)); GKO_DEFINE_SIMPLE_UNARY_OPERATION(one_operation, one(operand)); GKO_DEFINE_SIMPLE_UNARY_OPERATION(abs_operation, abs(operand)); GKO_DEFINE_SIMPLE_UNARY_OPERATION(real_operation, real(operand)); GKO_DEFINE_SIMPLE_UNARY_OPERATION(imag_operation, imag(operand)); GKO_DEFINE_SIMPLE_UNARY_OPERATION(conj_operation, conj(operand)); GKO_DEFINE_SIMPLE_UNARY_OPERATION(squared_norm_operation, squared_norm(operand)); } // namespace detail } // namespace accessor // unary arithmetic GKO_ENABLE_UNARY_RANGE_OPERATION(unary_plus, operator+, accessor::detail::unary_plus); GKO_ENABLE_UNARY_RANGE_OPERATION(unary_minus, operator-, accessor::detail::unary_minus); // unary logical GKO_ENABLE_UNARY_RANGE_OPERATION(logical_not, operator!, accessor::detail::logical_not); // unary bitwise GKO_ENABLE_UNARY_RANGE_OPERATION(bitwise_not, operator~, accessor::detail::bitwise_not); // common unary functions GKO_ENABLE_UNARY_RANGE_OPERATION(zero_operation, zero, accessor::detail::zero_operation); GKO_ENABLE_UNARY_RANGE_OPERATION(one_operaton, one, accessor::detail::one_operation); GKO_ENABLE_UNARY_RANGE_OPERATION(abs_operaton, abs, accessor::detail::abs_operation); GKO_ENABLE_UNARY_RANGE_OPERATION(real_operaton, real, accessor::detail::real_operation); GKO_ENABLE_UNARY_RANGE_OPERATION(imag_operaton, imag, accessor::detail::imag_operation); GKO_ENABLE_UNARY_RANGE_OPERATION(conj_operaton, conj, accessor::detail::conj_operation); GKO_ENABLE_UNARY_RANGE_OPERATION(squared_norm_operaton, squared_norm, accessor::detail::squared_norm_operation); namespace accessor { template <typename Accessor> struct transpose_operation { using accessor = Accessor; static constexpr size_type dimensionality = accessor::dimensionality; GKO_ATTRIBUTES constexpr explicit transpose_operation( const Accessor& operand) : operand{operand} {} template <typename FirstDimensionType, typename SecondDimensionType, typename... DimensionTypes> GKO_ATTRIBUTES constexpr auto operator()( const FirstDimensionType& first_dim, const SecondDimensionType& second_dim, const DimensionTypes&... dims) const -> decltype(std::declval<accessor>()(second_dim, first_dim, dims...)) { return operand(second_dim, first_dim, dims...); } GKO_ATTRIBUTES constexpr size_type length(size_type dimension) const { return dimension < 2 ? operand.length(dimension ^ 1) : operand.length(dimension); } template <typename OtherAccessor> GKO_ATTRIBUTES void copy_from(const OtherAccessor& other) const = delete; const accessor operand; }; } // namespace accessor GKO_BIND_UNARY_RANGE_OPERATION_TO_OPERATOR(transpose_operation, transpose); #undef GKO_DEFINE_SIMPLE_UNARY_OPERATION #undef GKO_ENABLE_UNARY_RANGE_OPERATION #define GKO_ENABLE_BINARY_RANGE_OPERATION(_operation_name, _operator_name, \ _operator) \ namespace accessor { \ template <::gko::detail::operation_kind Kind, typename FirstOperand, \ typename SecondOperand> \ struct _operation_name \ : ::gko::detail::implement_binary_operation< \ Kind, FirstOperand, SecondOperand, ::gko::_operator> { \ using ::gko::detail::implement_binary_operation< \ Kind, FirstOperand, SecondOperand, \ ::gko::_operator>::implement_binary_operation; \ }; \ } \ GKO_BIND_RANGE_OPERATION_TO_OPERATOR(_operation_name, _operator_name); \ static_assert(true, \ "This assert is used to counter the false positive extra " \ "semi-colon warnings") #define GKO_BIND_RANGE_OPERATION_TO_OPERATOR(_operation_name, _operator_name) \ template <typename Accessor> \ GKO_ATTRIBUTES constexpr GKO_INLINE range<accessor::_operation_name< \ ::gko::detail::operation_kind::range_by_range, Accessor, Accessor>> \ _operator_name(const range<Accessor>& first, \ const range<Accessor>& second) \ { \ return range<accessor::_operation_name< \ ::gko::detail::operation_kind::range_by_range, Accessor, \ Accessor>>(first.get_accessor(), second.get_accessor()); \ } \ \ template <typename FirstAccessor, typename SecondAccessor> \ GKO_ATTRIBUTES constexpr GKO_INLINE range<accessor::_operation_name< \ ::gko::detail::operation_kind::range_by_range, FirstAccessor, \ SecondAccessor>> \ _operator_name(const range<FirstAccessor>& first, \ const range<SecondAccessor>& second) \ { \ return range<accessor::_operation_name< \ ::gko::detail::operation_kind::range_by_range, FirstAccessor, \ SecondAccessor>>(first.get_accessor(), second.get_accessor()); \ } \ \ template <typename FirstAccessor, typename SecondOperand> \ GKO_ATTRIBUTES constexpr GKO_INLINE range<accessor::_operation_name< \ ::gko::detail::operation_kind::range_by_scalar, FirstAccessor, \ SecondOperand>> \ _operator_name(const range<FirstAccessor>& first, \ const SecondOperand& second) \ { \ return range<accessor::_operation_name< \ ::gko::detail::operation_kind::range_by_scalar, FirstAccessor, \ SecondOperand>>(first.get_accessor(), second); \ } \ \ template <typename FirstOperand, typename SecondAccessor> \ GKO_ATTRIBUTES constexpr GKO_INLINE range<accessor::_operation_name< \ ::gko::detail::operation_kind::scalar_by_range, FirstOperand, \ SecondAccessor>> \ _operator_name(const FirstOperand& first, \ const range<SecondAccessor>& second) \ { \ return range<accessor::_operation_name< \ ::gko::detail::operation_kind::scalar_by_range, FirstOperand, \ SecondAccessor>>(first, second.get_accessor()); \ } \ static_assert(true, \ "This assert is used to counter the false positive extra " \ "semi-colon warnings") #define GKO_DEFINE_SIMPLE_BINARY_OPERATION(_name, ...) \ struct _name { \ private: \ template <typename FirstOperand, typename SecondOperand> \ GKO_ATTRIBUTES constexpr static auto simple_evaluate_impl( \ const FirstOperand& first, const SecondOperand& second) \ -> decltype(__VA_ARGS__) \ { \ return __VA_ARGS__; \ } \ \ public: \ template <typename FirstAccessor, typename SecondAccessor, \ typename... DimensionTypes> \ GKO_ATTRIBUTES static constexpr auto evaluate_range_by_range( \ const FirstAccessor& first, const SecondAccessor& second, \ const DimensionTypes&... dims) \ -> decltype(simple_evaluate_impl(first(dims...), second(dims...))) \ { \ return simple_evaluate_impl(first(dims...), second(dims...)); \ } \ \ template <typename FirstOperand, typename SecondAccessor, \ typename... DimensionTypes> \ GKO_ATTRIBUTES static constexpr auto evaluate_scalar_by_range( \ const FirstOperand& first, const SecondAccessor& second, \ const DimensionTypes&... dims) \ -> decltype(simple_evaluate_impl(first, second(dims...))) \ { \ return simple_evaluate_impl(first, second(dims...)); \ } \ \ template <typename FirstAccessor, typename SecondOperand, \ typename... DimensionTypes> \ GKO_ATTRIBUTES static constexpr auto evaluate_range_by_scalar( \ const FirstAccessor& first, const SecondOperand& second, \ const DimensionTypes&... dims) \ -> decltype(simple_evaluate_impl(first(dims...), second)) \ { \ return simple_evaluate_impl(first(dims...), second); \ } \ } namespace accessor { namespace detail { // binary arithmetic GKO_DEFINE_SIMPLE_BINARY_OPERATION(add, first + second); GKO_DEFINE_SIMPLE_BINARY_OPERATION(sub, first - second); GKO_DEFINE_SIMPLE_BINARY_OPERATION(mul, first* second); GKO_DEFINE_SIMPLE_BINARY_OPERATION(div, first / second); GKO_DEFINE_SIMPLE_BINARY_OPERATION(mod, first % second); // relational GKO_DEFINE_SIMPLE_BINARY_OPERATION(less, first < second); GKO_DEFINE_SIMPLE_BINARY_OPERATION(greater, first > second); GKO_DEFINE_SIMPLE_BINARY_OPERATION(less_or_equal, first <= second); GKO_DEFINE_SIMPLE_BINARY_OPERATION(greater_or_equal, first >= second); GKO_DEFINE_SIMPLE_BINARY_OPERATION(equal, first == second); GKO_DEFINE_SIMPLE_BINARY_OPERATION(not_equal, first != second); // binary logical GKO_DEFINE_SIMPLE_BINARY_OPERATION(logical_or, first || second); GKO_DEFINE_SIMPLE_BINARY_OPERATION(logical_and, first&& second); // binary bitwise GKO_DEFINE_SIMPLE_BINARY_OPERATION(bitwise_or, first | second); GKO_DEFINE_SIMPLE_BINARY_OPERATION(bitwise_and, first& second); GKO_DEFINE_SIMPLE_BINARY_OPERATION(bitwise_xor, first ^ second); GKO_DEFINE_SIMPLE_BINARY_OPERATION(left_shift, first << second); GKO_DEFINE_SIMPLE_BINARY_OPERATION(right_shift, first >> second); // common binary functions GKO_DEFINE_SIMPLE_BINARY_OPERATION(max_operation, max(first, second)); GKO_DEFINE_SIMPLE_BINARY_OPERATION(min_operation, min(first, second)); } // namespace detail } // namespace accessor // binary arithmetic GKO_ENABLE_BINARY_RANGE_OPERATION(add, operator+, accessor::detail::add); GKO_ENABLE_BINARY_RANGE_OPERATION(sub, operator-, accessor::detail::sub); GKO_ENABLE_BINARY_RANGE_OPERATION(mul, operator*, accessor::detail::mul); GKO_ENABLE_BINARY_RANGE_OPERATION(div, operator/, accessor::detail::div); GKO_ENABLE_BINARY_RANGE_OPERATION(mod, operator%, accessor::detail::mod); // relational GKO_ENABLE_BINARY_RANGE_OPERATION(less, operator<, accessor::detail::less); GKO_ENABLE_BINARY_RANGE_OPERATION(greater, operator>, accessor::detail::greater); GKO_ENABLE_BINARY_RANGE_OPERATION(less_or_equal, operator<=, accessor::detail::less_or_equal); GKO_ENABLE_BINARY_RANGE_OPERATION(greater_or_equal, operator>=, accessor::detail::greater_or_equal); GKO_ENABLE_BINARY_RANGE_OPERATION(equal, operator==, accessor::detail::equal); GKO_ENABLE_BINARY_RANGE_OPERATION(not_equal, operator!=, accessor::detail::not_equal); // binary logical GKO_ENABLE_BINARY_RANGE_OPERATION(logical_or, operator||, accessor::detail::logical_or); GKO_ENABLE_BINARY_RANGE_OPERATION(logical_and, operator&&, accessor::detail::logical_and); // binary bitwise GKO_ENABLE_BINARY_RANGE_OPERATION(bitwise_or, operator|, accessor::detail::bitwise_or); GKO_ENABLE_BINARY_RANGE_OPERATION(bitwise_and, operator&, accessor::detail::bitwise_and); GKO_ENABLE_BINARY_RANGE_OPERATION(bitwise_xor, operator^, accessor::detail::bitwise_xor); GKO_ENABLE_BINARY_RANGE_OPERATION(left_shift, operator<<, accessor::detail::left_shift); GKO_ENABLE_BINARY_RANGE_OPERATION(right_shift, operator>>, accessor::detail::right_shift); // common binary functions GKO_ENABLE_BINARY_RANGE_OPERATION(max_operaton, max, accessor::detail::max_operation); GKO_ENABLE_BINARY_RANGE_OPERATION(min_operaton, min, accessor::detail::min_operation); // special binary range functions namespace accessor { template <gko::detail::operation_kind Kind, typename FirstAccessor, typename SecondAccessor> struct mmul_operation { static_assert(Kind == gko::detail::operation_kind::range_by_range, "Matrix multiplication expects both operands to be ranges"); using first_accessor = FirstAccessor; using second_accessor = SecondAccessor; static_assert(first_accessor::dimensionality == second_accessor::dimensionality, "Both ranges need to have the same number of dimensions"); static constexpr size_type dimensionality = first_accessor::dimensionality; GKO_ATTRIBUTES explicit mmul_operation(const FirstAccessor& first, const SecondAccessor& second) : first{first}, second{second} { GKO_ASSERT(first.length(1) == second.length(0)); GKO_ASSERT(gko::detail::equal_dimensions<2>(first, second)); } template <typename FirstDimension, typename SecondDimension, typename... DimensionTypes> GKO_ATTRIBUTES auto operator()(const FirstDimension& row, const SecondDimension& col, const DimensionTypes&... rest) const -> decltype(std::declval<FirstAccessor>()(row, 0, rest...) * std::declval<SecondAccessor>()(0, col, rest...) + std::declval<FirstAccessor>()(row, 1, rest...) * std::declval<SecondAccessor>()(1, col, rest...)) { using result_type = decltype(first(row, 0, rest...) * second(0, col, rest...) + first(row, 1, rest...) * second(1, col, rest...)); GKO_ASSERT(first.length(1) == second.length(0)); auto result = zero<result_type>(); const auto size = first.length(1); for (auto i = zero(size); i < size; ++i) { result += first(row, i, rest...) * second(i, col, rest...); } return result; } GKO_ATTRIBUTES constexpr size_type length(size_type dimension) const { return dimension == 1 ? second.length(1) : first.length(dimension); } template <typename OtherAccessor> GKO_ATTRIBUTES void copy_from(const OtherAccessor& other) const = delete; const first_accessor first; const second_accessor second; }; } // namespace accessor GKO_BIND_RANGE_OPERATION_TO_OPERATOR(mmul_operation, mmul); #undef GKO_DEFINE_SIMPLE_BINARY_OPERATION #undef GKO_ENABLE_BINARY_RANGE_OPERATION } // namespace gko #endif // GKO_PUBLIC_CORE_BASE_RANGE_HPP_
42.352999
80
0.58568
kliegeois
17612e414b3af0406344bbe6b1958cf5e96b5f2b
1,262
cpp
C++
aws-cpp-sdk-securityhub/source/model/PortRangeFromTo.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-securityhub/source/model/PortRangeFromTo.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-securityhub/source/model/PortRangeFromTo.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/securityhub/model/PortRangeFromTo.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace SecurityHub { namespace Model { PortRangeFromTo::PortRangeFromTo() : m_from(0), m_fromHasBeenSet(false), m_to(0), m_toHasBeenSet(false) { } PortRangeFromTo::PortRangeFromTo(JsonView jsonValue) : m_from(0), m_fromHasBeenSet(false), m_to(0), m_toHasBeenSet(false) { *this = jsonValue; } PortRangeFromTo& PortRangeFromTo::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("From")) { m_from = jsonValue.GetInteger("From"); m_fromHasBeenSet = true; } if(jsonValue.ValueExists("To")) { m_to = jsonValue.GetInteger("To"); m_toHasBeenSet = true; } return *this; } JsonValue PortRangeFromTo::Jsonize() const { JsonValue payload; if(m_fromHasBeenSet) { payload.WithInteger("From", m_from); } if(m_toHasBeenSet) { payload.WithInteger("To", m_to); } return payload; } } // namespace Model } // namespace SecurityHub } // namespace Aws
15.974684
69
0.687797
perfectrecall
1765d50e30a5884a527504a253371aed193dcc88
18,521
cpp
C++
tests/src/MpTestAutoResendEngine.cpp
lgrigoriu/end-to-end-smkex
ffe4582247dd6435e5ac01166022ded6d26babac
[ "BSD-3-Clause" ]
null
null
null
tests/src/MpTestAutoResendEngine.cpp
lgrigoriu/end-to-end-smkex
ffe4582247dd6435e5ac01166022ded6d26babac
[ "BSD-3-Clause" ]
null
null
null
tests/src/MpTestAutoResendEngine.cpp
lgrigoriu/end-to-end-smkex
ffe4582247dd6435e5ac01166022ded6d26babac
[ "BSD-3-Clause" ]
null
null
null
#include "MpTestAutoResendEngine.h" #include "MpMsgPayload.h" #include "MpDBConnectorMock.h" #include "MpAutoResendEngine.h" #include "MpMsgTransportMock.h" #include "MpPresenceListMock.h" #include "MpSIPStackMock.h" #include <iostream> MpTestAutoResendEngine::MpTestAutoResendEngine() { testSuite = new MpTestSuiteData(); testSuite->testSuiteName = "TEST Auto Resend Engine"; MpTestsUtils::addTest(*testSuite, "DB sync with connectors 1", testSyncWithDBConnectors1); MpTestsUtils::addTest(*testSuite, "DB sync with connectors 2", testSyncWithDBConnectors2); MpTestsUtils::addTest(*testSuite, "DB sync with connectors 3", testSyncWithDBConnectors3); MpTestsUtils::addTest(*testSuite, "DB sync with connectors 4", testSyncWithDBConnectors4); MpTestsUtils::addTest(*testSuite, "DB sync with connectors 5", testSyncWithDBConnectors5); MpTestsUtils::addTest(*testSuite, "DB sync with connectors 6", testSyncWithDBConnectors6); MpTestsUtils::addTest(*testSuite, "DB sync with connectors 7", testSyncWithDBConnectors7); } int MpTestAutoResendEngine::testSyncWithDBConnectors1() { MpDBConnectorMock dbConn; MpMsgTransportMock transport; MpBuddy buddy0("User0"); MpBuddy buddy1("User1"); MpBuddy buddy2("User2"); MpBuddy buddy3("User3"); MpBuddy buddy4("User4"); MpPresenceListMock presList; for (int i = 0; i < 4; i++) { MpString user = ""; if (i % 4 == 0) { user = "User0"; } else if (i % 4 == 1) { user = "User1"; } else if (i % 4 == 2) { user = "User2"; } else if (i % 4 == 3) { user = "User3"; } char msgPayload[] = "Content"; MpBuffer msgPayloadBuf((uint8_t*) msgPayload, strlen(msgPayload)); dbConn.pushMessage(user, MpMsgPayload(user, msgPayloadBuf, i, 3, i, MP_TYPE_MESSAGE, false)); } MpAutoResendEngine arEngine; MpSIPStackMock sipStackMock; arEngine.setSIPStack(&sipStackMock); arEngine.setAutoResendEnabled(true); arEngine.setMsgTransport(&transport); arEngine.addDBConnector(&dbConn); arEngine.setPresList(&presList); arEngine.syncWithDBConnectors(); /*========================================*/ /*========================================*/ buddy4.setState(MP_BUDDY_ONLINE); presList.insertUser("User4"); arEngine.buddy_state2(buddy4); /*========================================*/ buddy3.setState(MP_BUDDY_ONLINE); presList.insertUser("User3"); arEngine.buddy_state2(buddy3); MP_ASSERT_EQ(transport.lastMsg_.getUserSerial(), "User3"); /*========================================*/ buddy2.setState(MP_BUDDY_ONLINE); presList.insertUser("User2"); arEngine.buddy_state2(buddy2); MP_ASSERT_EQ(transport.lastMsg_.getUserSerial(), "User3"); /*========================================*/ arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_NOT_SENT); // User3 removed MP_ASSERT_EQ(transport.lastMsg_.getUserSerial(), "User2"); /*========================================*/ arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_NOT_SENT); // User2 removed /*========================================*/ arEngine.buddy_state2(buddy3); MP_ASSERT_EQ(transport.lastMsg_.getUserSerial(), "User0"); /*========================================*/ buddy1.setState(MP_BUDDY_ONLINE); presList.insertUser("User1"); arEngine.buddy_state2(buddy1); MP_ASSERT_EQ(transport.lastMsg_.getUserSerial(), "User0"); /*========================================*/ arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_NOT_SENT); // User0 removed MP_ASSERT_EQ(transport.lastMsg_.getUserSerial(), "User1"); /*========================================*/ arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_NOT_SENT); // User1 removed MP_ASSERT_EQ(transport.lastMsg_.getUserSerial(), "User3"); /*========================================*/ arEngine.buddy_state2(buddy2); MP_ASSERT_EQ(transport.lastMsg_.getUserSerial(), "User3"); /*========================================*/ arEngine.buddy_state2(buddy1); arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_NOT_SENT); //User2 removed MP_ASSERT_EQ(transport.lastMsg_.getUserSerial(), "User1"); /*========================================*/ arEngine.buddy_state2(buddy3); arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_NOT_SENT); //User1 removed MP_ASSERT_EQ(transport.lastMsg_.getUserSerial(), "User2"); /*========================================*/ buddy0.setState(MP_BUDDY_ONLINE); arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_NOT_SENT); presList.insertUser("User0"); arEngine.buddy_state2(buddy0); arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_NOT_SENT); MP_ASSERT_EQ(transport.lastMsg_.getUserSerial(), "User0"); return 0; } int MpTestAutoResendEngine::testSyncWithDBConnectors2() { MpDBConnectorMock dbConn; MpMsgTransportMock transport; MpPresenceListMock presList; MpBuddy buddy0("User0"); MpBuddy buddy1("User1"); char msgPayload[] = "Content"; MpBuffer msgPayloadBuf((uint8_t*) msgPayload, strlen(msgPayload)); dbConn.pushMessage("User0", MpMsgPayload(MpString("User0"), msgPayloadBuf, 0, 3, 10, MP_TYPE_MESSAGE, true)); dbConn.pushMessage("User1", MpMsgPayload(MpString("User1"), msgPayloadBuf, 1, 3, 10, MP_TYPE_MESSAGE, true)); MpAutoResendEngine arEngine; MpSIPStackMock sipStackMock; arEngine.setSIPStack(&sipStackMock); arEngine.setAutoResendEnabled(true); arEngine.setMsgTransport(&transport); arEngine.addDBConnector(&dbConn); arEngine.setPresList(&presList); arEngine.syncWithDBConnectors(); buddy0.setState(MP_BUDDY_ONLINE); presList.insertUser("User0"); arEngine.buddy_state2(buddy0); MP_ASSERT_EQ(transport.lastMsg_.getUserSerial(), "User0"); /*========================================*/ buddy1.setState(MP_BUDDY_ONLINE); presList.insertUser("User1"); arEngine.buddy_state2(buddy1); arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_NOT_SENT); //User0 removed MP_ASSERT_EQ(transport.lastMsg_.getUserSerial(), "User1"); /*========================================*/ arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_SENT); // Message for User1 deleted arEngine.buddy_state2(buddy0); MP_ASSERT_EQ(transport.lastMsg_.getUserSerial(), "User0"); /*========================================*/ arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_NOT_SENT); // User0 removed MP_ASSERT_EQ(transport.lastMsg_.getUserSerial(), "User0"); return 0; } int MpTestAutoResendEngine::testSyncWithDBConnectors3() { MpDBConnectorMock dbConn; MpMsgTransportMock transport; MpPresenceListMock presList; MpBuddy buddy0("User0"); MpMsgPayload* messages[2000]; for (int i = 0; i < 1000; i++) { char msgPayload[100]; sprintf(msgPayload, "Msg %d", i); MpBuffer msgPayloadBuf((uint8_t*) msgPayload, strlen(msgPayload)); messages[i] = new MpMsgPayload(MpString("User0"), msgPayloadBuf, i, 3, 10, MP_TYPE_MESSAGE, true); dbConn.pushMessage("User 0", *(messages[i])); } MpAutoResendEngine arEngine; MpSIPStackMock sipStackMock; arEngine.setSIPStack(&sipStackMock); arEngine.setAutoResendEnabled(true); arEngine.setMsgTransport(&transport); arEngine.addDBConnector(&dbConn); arEngine.setPresList(&presList); /*Load messages into engine*/ arEngine.syncWithDBConnectors(); /*Send some messages*/ presList.insertUser("User0"); buddy0.setState(MP_BUDDY_ONLINE); arEngine.buddy_state2(buddy0); MP_ASSERT_EQ(transport.lastMsg_.getUID(), 0); MP_ASSERT_EQ(transport.lastMsg_.getPayload(), messages[0]->getPayload()); /*Confirm first message*/ arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_SENT); MP_ASSERT_EQ(transport.lastMsg_.getPayload(), messages[1]->getPayload()); /*Confirm second message*/ arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_SENT); MP_ASSERT_EQ(transport.lastMsg_.getPayload(), messages[2]->getPayload()); /*Confirm third message*/ arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_SENT); MP_ASSERT_EQ(transport.lastMsg_.getPayload(), messages[3]->getPayload()); /*Put the user online again*/ buddy0.setState(MP_BUDDY_ONLINE); arEngine.buddy_state2(buddy0); MP_ASSERT_EQ(transport.lastMsg_.getPayload(), messages[3]->getPayload()); /*Put the user offline*/ buddy0.setState(MP_BUDDY_OFFLINE); arEngine.buddy_state2(buddy0); /*Wait and send some messages*/ for (int i = 0; i < 1000; i++) { char msgPayload[100]; sprintf(msgPayload, "Msg %d", i + 1000); MpBuffer msgPayloadBuf((uint8_t*) msgPayload, strlen(msgPayload)); messages[i + 1000] = new MpMsgPayload(MpString("User0"), msgPayloadBuf, 0, 3, 10, MP_TYPE_MESSAGE, true); arEngine.addMessage(*(messages[i + 1000])); } /*Put the user online again*/ buddy0.setState(MP_BUDDY_ONLINE); arEngine.buddy_state2(buddy0); MP_ASSERT_EQ(transport.lastMsg_.getPayload(), messages[3]->getPayload()); for (int i = 4; i < 2000; i++) { /*Confirm last message*/ arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_SENT); MP_ASSERT_EQ(transport.lastMsg_.getPayload(), messages[i]->getPayload()); } return 0; } int MpTestAutoResendEngine::testSyncWithDBConnectors4() { MpDBConnectorMock dbConn; MpMsgTransportMock transport; MpPresenceListMock presList; MpBuddy buddy0("user0"); MpBuddy buddy1("user1"); MpMsgPayload* messages[20]; for (int i = 0; i < 10; i++) { char msgPayload[100]; sprintf(msgPayload, "Msg %d", i); MpBuffer msgPayloadBuf((uint8_t*) msgPayload, strlen(msgPayload)); messages[i] = new MpMsgPayload(MpString("user0"), msgPayloadBuf, i, 3, 10, MP_TYPE_MESSAGE, true); dbConn.pushMessage("user0", *(messages[i])); } for (int i = 10; i < 20; i++) { char msgPayload[100]; sprintf(msgPayload, "Msg %d", i); MpBuffer msgPayloadBuf((uint8_t*) msgPayload, strlen(msgPayload)); messages[i] = new MpMsgPayload(MpString("user1"), msgPayloadBuf, i, 3, 10, MP_TYPE_MESSAGE, true); dbConn.pushMessage("user1", *(messages[i])); } MpAutoResendEngine arEngine; MpSIPStackMock sipStackMock; arEngine.setSIPStack(&sipStackMock); arEngine.setAutoResendEnabled(true); arEngine.setMsgTransport(&transport); arEngine.addDBConnector(&dbConn); arEngine.setPresList(&presList); /*Load messages into engine*/ arEngine.syncWithDBConnectors(); /*Send some messages*/ presList.insertUser("user0"); buddy0.setState(MP_BUDDY_OFFLINE); presList.insertUser("user1"); buddy1.setState(MP_BUDDY_ONLINE); arEngine.buddy_state2(buddy0); arEngine.buddy_state2(buddy1); MP_ASSERT_EQ(transport.lastMsg_.getUID(), 10); MP_ASSERT_EQ(transport.lastMsg_.getPayload(), messages[10]->getPayload()); /*Confirm message*/ arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_SENT); MP_ASSERT_EQ(transport.lastMsg_.getPayload(), messages[11]->getPayload()); arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_SENT); MP_ASSERT_EQ(transport.lastMsg_.getPayload(), messages[0]->getPayload()); arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_SENT); MP_ASSERT_EQ(transport.lastMsg_.getPayload(), messages[1]->getPayload()); arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_SENT); MP_ASSERT_EQ(transport.lastMsg_.getPayload(), messages[12]->getPayload()); buddy0.setState(MP_BUDDY_ONLINE); arEngine.buddy_state2(buddy0); arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_SENT); MP_ASSERT_EQ(transport.lastMsg_.getUID(), 2); MP_ASSERT_EQ(transport.lastMsg_.getPayload(), messages[2]->getPayload()); arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_SENT); MP_ASSERT_EQ(transport.lastMsg_.getPayload(), messages[3]->getPayload()); arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_SENT); MP_ASSERT_EQ(transport.lastMsg_.getPayload(), messages[4]->getPayload()); arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_SENT); MP_ASSERT_EQ(transport.lastMsg_.getPayload(), messages[5]->getPayload()); arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_SENT); MP_ASSERT_EQ(transport.lastMsg_.getPayload(), messages[13]->getPayload()); arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_SENT); MP_ASSERT_EQ(transport.lastMsg_.getPayload(), messages[14]->getPayload()); arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_SENT); MP_ASSERT_EQ(transport.lastMsg_.getPayload(), messages[6]->getPayload()); arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_SENT); MP_ASSERT_EQ(transport.lastMsg_.getPayload(), messages[7]->getPayload()); arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_SENT); MP_ASSERT_EQ(transport.lastMsg_.getPayload(), messages[15]->getPayload()); arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_SENT); MP_ASSERT_EQ(transport.lastMsg_.getPayload(), messages[16]->getPayload()); arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_SENT); MP_ASSERT_EQ(transport.lastMsg_.getPayload(), messages[8]->getPayload()); arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_SENT); MP_ASSERT_EQ(transport.lastMsg_.getPayload(), messages[9]->getPayload()); arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_SENT); MP_ASSERT_EQ(transport.lastMsg_.getPayload(), messages[17]->getPayload()); arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_SENT); MP_ASSERT_EQ(transport.lastMsg_.getPayload(), messages[18]->getPayload()); arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_SENT); MP_ASSERT_EQ(transport.lastMsg_.getPayload(), messages[19]->getPayload()); return 0; } int MpTestAutoResendEngine::testSyncWithDBConnectors5() { MpDBConnectorMock dbConn; MpMsgTransportMock transport; MpPresenceListMock presList; MpBuddy buddy0("user0"); MpBuddy buddy1("user1"); char msgPayload[100]; sprintf(msgPayload, "Msg %d", 1); MpBuffer msgPayloadBuf((uint8_t*) msgPayload, strlen(msgPayload)); dbConn.pushMessage("user0", MpMsgPayload(MpString("user0"), msgPayloadBuf, 999, 3, 10, MP_TYPE_MESSAGE, true)); MpAutoResendEngine arEngine; MpSIPStackMock sipStackMock; arEngine.setSIPStack(&sipStackMock); arEngine.setAutoResendEnabled(true); arEngine.setMsgTransport(&transport); arEngine.addDBConnector(&dbConn); arEngine.setPresList(&presList); /*Load messages into engine*/ arEngine.syncWithDBConnectors(); /*Send some messages*/ presList.insertUser("user0"); buddy0.setState(MP_BUDDY_OFFLINE); presList.insertUser("user1"); buddy1.setState(MP_BUDDY_ONLINE); arEngine.buddy_state2(buddy0); arEngine.buddy_state2(buddy1); buddy0.setState(MP_BUDDY_ONLINE); arEngine.buddy_state2(buddy0); MP_ASSERT_EQ(transport.lastMsg_.getUserSerial(), "user0"); MP_ASSERT_EQ(arEngine.isMessageProcessing("user5", 1), false); MP_ASSERT_EQ(arEngine.isMessageProcessing("user5", 999), false); MP_ASSERT_EQ(arEngine.isMessageProcessing("user0", 1), true); MP_ASSERT_EQ(arEngine.isMessageProcessing("user0", 999), true); return 0; } int MpTestAutoResendEngine::testSyncWithDBConnectors6() { MpDBConnectorMock dbConn; MpMsgTransportMock transport; MpPresenceListMock presList; MpBuddy buddy0("user0"); MpBuddy buddy1("user1"); MpBuddy buddy2("user2"); char msgPayload[100]; sprintf(msgPayload, "Msg %d", 1); MpBuffer msgPayloadBuf((uint8_t*) msgPayload, strlen(msgPayload)); dbConn.pushMessage("user0", MpMsgPayload(MpString("user0"), msgPayloadBuf, 999, 3, 10, MP_TYPE_MESSAGE, true)); dbConn.pushMessage("user1", MpMsgPayload(MpString("user1"), msgPayloadBuf, 1000, 3, 10, MP_TYPE_MESSAGE, true)); dbConn.pushMessage("user2", MpMsgPayload(MpString("user2"), msgPayloadBuf, 1001, 3, 10, MP_TYPE_MESSAGE, true)); MpAutoResendEngine arEngine; MpSIPStackMock sipStackMock; arEngine.setSIPStack(&sipStackMock); arEngine.setAutoResendEnabled(true); arEngine.setMsgTransport(&transport); arEngine.addDBConnector(&dbConn); arEngine.setPresList(&presList); /*Load messages into engine*/ arEngine.syncWithDBConnectors(); /*Send some messages*/ presList.insertUser("user0"); buddy0.setState(MP_BUDDY_OFFLINE); presList.insertUser("user1"); buddy1.setState(MP_BUDDY_ONLINE); presList.insertUser("user2"); buddy2.setState(MP_BUDDY_ONLINE); arEngine.buddy_state2(buddy0); arEngine.buddy_state2(buddy1); buddy0.setState(MP_BUDDY_ONLINE); arEngine.buddy_state2(buddy0); MP_ASSERT_EQ(transport.lastMsg_.getUserSerial(), "user1"); arEngine.removeMessagesForSerial("user99"); arEngine.removeMessagesForSerial("user1"); arEngine.removeMessagesForSerial("user0"); arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_SENT); MP_ASSERT_EQ(transport.lastMsg_.getUserSerial(), "user2"); return 0; } int MpTestAutoResendEngine::testSyncWithDBConnectors7() { MpDBConnectorMock dbConn; MpMsgTransportMock transport; MpPresenceListMock presList; MpBuddy buddy0("user0"); MpBuddy buddy1("user1"); char msgPayload[100]; sprintf(msgPayload, "Msg %d", 1); MpBuffer msgPayloadBuf((uint8_t*) msgPayload, strlen(msgPayload)); dbConn.pushMessage("user0", MpMsgPayload(MpString("user0"), msgPayloadBuf, 1, 3, 10, MP_TYPE_MESSAGE, true)); dbConn.pushMessage("user0", MpMsgPayload(MpString("user0"), msgPayloadBuf, 999, 3, 10, MP_TYPE_MESSAGE, true)); dbConn.pushMessage("user0", MpMsgPayload(MpString("user0"), msgPayloadBuf, 1000, 3, 10, MP_TYPE_MESSAGE, true)); dbConn.pushMessage("user1", MpMsgPayload(MpString("user1"), msgPayloadBuf, 1001, 3, 10, MP_TYPE_MESSAGE, true)); dbConn.pushMessage("user1", MpMsgPayload(MpString("user1"), msgPayloadBuf, 1002, 3, 10, MP_TYPE_MESSAGE, true)); dbConn.pushMessage("user1", MpMsgPayload(MpString("user1"), msgPayloadBuf, 1003, 3, 10, MP_TYPE_MESSAGE, true)); MpAutoResendEngine arEngine; MpSIPStackMock sipStackMock; arEngine.setSIPStack(&sipStackMock); arEngine.setAutoResendEnabled(true); arEngine.setMsgTransport(&transport); arEngine.addDBConnector(&dbConn); arEngine.setPresList(&presList); /*Load messages into engine*/ arEngine.syncWithDBConnectors(); /*Send some messages*/ presList.insertUser("user0"); buddy0.setState(MP_BUDDY_ONLINE); presList.insertUser("user1"); buddy1.setState(MP_BUDDY_ONLINE); arEngine.buddy_state2(buddy0); arEngine.buddy_state2(buddy1); MP_ASSERT_EQ(transport.lastMsg_.getUserSerial(), "user0"); arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_NOT_SENT); MP_ASSERT_EQ(transport.lastMsg_.getUserSerial(), "user1"); arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_SENT); MP_ASSERT_EQ(transport.lastMsg_.getUserSerial(), "user1"); arEngine.resendMessage("user0", 999); arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_SENT); MP_ASSERT_EQ(transport.lastMsg_.getUserSerial(), "user0"); arEngine.messageStatus(transport.lastMsg_, MP_MESSAGE_SENT); MP_ASSERT_EQ(transport.lastMsg_.getUserSerial(), "user0"); return 0; }
34.298148
90
0.737055
lgrigoriu
17669517dca681f35fa5614e293900598cf9e248
4,113
cpp
C++
src/TRSSINCOS.cpp
starlingcode/StarlingTRS
a9031bb24481c3e7f12af73b2736ff2449eb3822
[ "MIT" ]
2
2021-10-21T05:50:39.000Z
2022-03-17T23:47:45.000Z
src/TRSSINCOS.cpp
starlingcode/StarlingTRS
a9031bb24481c3e7f12af73b2736ff2449eb3822
[ "MIT" ]
null
null
null
src/TRSSINCOS.cpp
starlingcode/StarlingTRS
a9031bb24481c3e7f12af73b2736ff2449eb3822
[ "MIT" ]
null
null
null
#include "trs.hpp" struct TRSSINCOS : Module { enum ParamIds { DEPTH_PARAM, BIAS_PARAM, NUM_PARAMS }; enum InputIds { MONO_INPUT, STEREO_INPUT, DEPTH_INPUT, NUM_INPUTS }; enum OutputIds { OUT_OUTPUT, NUM_OUTPUTS }; enum LightIds { NUM_LIGHTS }; StereoInHandler mono; StereoInHandler stereo; StereoInHandler depthCV; StereoOutHandler output; // // phase 0 - pi // float_4 bhaskaraSine(float_4 phase) { // float_4 pi = float_4(M_PI); // return (float_4(16.f) * phase * (pi - phase)) / (float_4(5.f) * pi * pi - float_4(4.f) * phase * (pi - phase)); // } #define SINCOS_OVERSAMPLE 4 UpsamplePow2<SINCOS_OVERSAMPLE, float_4> upsamplers[2][2]; DecimatePow2<SINCOS_OVERSAMPLE, float_4> decimators[2][2]; float_4 work[SINCOS_OVERSAMPLE]; TRSSINCOS() { config(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS); configParam(DEPTH_PARAM, 0.f, 1.f, 0.f, ""); configParam(BIAS_PARAM, 0.f, 5.f, 0.f, ""); mono.configure(&inputs[MONO_INPUT]); stereo.configure(&inputs[STEREO_INPUT]); depthCV.configure(&inputs[DEPTH_INPUT]); output.configure(&outputs[OUT_OUTPUT]); } void process(const ProcessArgs &args) override { outputs[OUT_OUTPUT].setChannels(16); for (int polyChunk = 0; polyChunk < 2; polyChunk ++) { float_4 depth = clamp((depthCV.getLeft(polyChunk) / float_4(10.f)) + params[DEPTH_PARAM].getValue(), 0.f, 1.f); float_4 in = mono.getLeft(polyChunk) + stereo.getLeft(polyChunk) + params[BIAS_PARAM].getValue(); in *= depth; // scale -5 to -5 to -2 to -2 in *= float_4(2.f / 5.f); upsamplers[0][polyChunk].process(in); for (int i = 0; i < SINCOS_OVERSAMPLE; i++) { in = upsamplers[0][polyChunk].output[i]; work[i] = bhaskaraSine<float_4, int32_4>(in); } float_4 out = decimators[0][polyChunk].process(work); output.setLeft(out * float_4(5.f), polyChunk); depth = clamp((depthCV.getRight(polyChunk) / float_4(5.f)) + params[DEPTH_PARAM].getValue(), 0.f, 1.f); in = mono.getLeft(polyChunk) + stereo.getRight(polyChunk) + params[BIAS_PARAM].getValue(); in *= depth; // scale -5 to -5 to -2 to -2 in *= float_4(2.f / 5.f); // cos in += float_4(.5f); upsamplers[1][polyChunk].process(in); for (int i = 0; i < SINCOS_OVERSAMPLE; i++) { in = upsamplers[1][polyChunk].output[i]; work[i] = bhaskaraSine<float_4, int32_4>(in); } out = decimators[1][polyChunk].process(work); output.setRight(out * float_4(5.f), polyChunk); } } }; struct TRSSINCOSWidget : ModuleWidget { TRSSINCOSWidget(TRSSINCOS *module) { setModule(module); setPanel(APP->window->loadSvg(asset::plugin(pluginInstance, "res/TRSSINCOS.svg"))); addChild(createWidget<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, 0))); addChild(createWidget<ScrewSilver>(Vec(box.size.x - 2 * RACK_GRID_WIDTH, RACK_GRID_HEIGHT - RACK_GRID_WIDTH))); addParam(createParamCentered<SifamGrey>(mm2px(Vec(10.731, 17.609)), module, TRSSINCOS::DEPTH_PARAM)); addParam(createParamCentered<SifamBlack>(mm2px(Vec(10.789, 38.717)), module, TRSSINCOS::BIAS_PARAM)); addInput(createInputCentered<HexJack>(mm2px(Vec(10.127, 71.508)), module, TRSSINCOS::MONO_INPUT)); addInput(createInputCentered<HexJack>(mm2px(Vec(10.16, 85.504)), module, TRSSINCOS::STEREO_INPUT)); addInput(createInputCentered<HexJack>(mm2px(Vec(10.16, 99.499)), module, TRSSINCOS::DEPTH_INPUT)); addOutput(createOutputCentered<HexJack>(mm2px(Vec(10.16, 113.501)), module, TRSSINCOS::OUT_OUTPUT)); } }; Model *modelTRSSINCOS = createModel<TRSSINCOS, TRSSINCOSWidget>("TRSSINCOS");
33.713115
123
0.599562
starlingcode
1769e9328e857e0e73c06fed7ae6251792875e25
291
cpp
C++
unix/take.cpp
kybr/MAT240C-2018
a888e9175022b90c442f0abddf49a836ef56693f
[ "MIT" ]
null
null
null
unix/take.cpp
kybr/MAT240C-2018
a888e9175022b90c442f0abddf49a836ef56693f
[ "MIT" ]
null
null
null
unix/take.cpp
kybr/MAT240C-2018
a888e9175022b90c442f0abddf49a836ef56693f
[ "MIT" ]
null
null
null
#include "everything.h" // accept and pass on only so many inputs int main(int argc, char* argv[]) { unsigned many = strtoul(argv[1], nullptr, 0); if (many <= 0) return 0; char buffer[256]; while (many > 0) { many--; scanf("%s", buffer); printf("%s\n", buffer); } }
18.1875
47
0.584192
kybr
176a8c9728693eecbba7ec1a391de112b4afde16
18,612
cc
C++
Modules/Image/test/irtkDisplacementToVelocityFieldTest.cc
kevin-keraudren/IRTK
ce329b7f58270b6c34665dcfe9a6e941649f3b94
[ "Apache-2.0" ]
3
2018-10-04T19:32:36.000Z
2021-09-02T07:37:30.000Z
Modules/Image/test/irtkDisplacementToVelocityFieldTest.cc
kevin-keraudren/IRTK
ce329b7f58270b6c34665dcfe9a6e941649f3b94
[ "Apache-2.0" ]
null
null
null
Modules/Image/test/irtkDisplacementToVelocityFieldTest.cc
kevin-keraudren/IRTK
ce329b7f58270b6c34665dcfe9a6e941649f3b94
[ "Apache-2.0" ]
4
2016-03-17T02:55:00.000Z
2018-02-03T05:40:05.000Z
/* The Image Registration Toolkit (IRTK) * * Copyright 2008-2015 Imperial College London * * 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 <irtkImage.h> #include <irtkTransformation.h> #include <irtkNoise.h> #include <irtkGaussianBlurring.h> #include <irtkGaussianBlurring2D.h> #include <irtkConvolutionWithGaussianDerivative.h> #include <irtkConvolutionWithGaussianDerivative2.h> #include <irtkDisplacementToVelocityField.h> #include <irtkVelocityToDisplacementFieldEuler.h> // =========================================================================== // Initialization // =========================================================================== // --------------------------------------------------------------------------- void init(char *name_in, irtkImageAttributes &grid, double sigma, double max, double *&x, double *&y, double *&z, double *&dx, double *&dy, double *&dz) { irtkGenericImage<irtkRealPixel> disp; if (name_in == NULL) { // create zero displacement field irtkImageAttributes attr = grid; attr._t = 3; disp.Initialize(attr); // add random noise to displacement field irtkGaussianNoise<irtkRealPixel> noise(0.0, sigma, -fabs(max), +fabs(max)); noise.SetInput (&disp); noise.SetOutput(&disp); noise.irtkImageToImage<irtkRealPixel>::Run(); // smooth displacements if (grid._z > 1) { irtkGaussianBlurring<irtkRealPixel> blur(1.25); blur.SetInput (&disp); blur.SetOutput(&disp); blur.Run(); } else { irtkGaussianBlurring2D<irtkRealPixel> blur(1.25); blur.SetInput (&disp); blur.SetOutput(&disp); blur.Run(); } } else if (strstr(name_in, ".dof") != NULL) { // read transformation from file irtkTransformation *t = irtkTransformation::New(name_in); irtkMultiLevelTransformation *mffd = dynamic_cast<irtkMultiLevelTransformation *>(t); irtkFreeFormTransformation *ffd = dynamic_cast<irtkFreeFormTransformation *>(t); if (mffd != NULL && mffd->NumberOfLevels() > 0) { ffd = mffd->GetLocalTransformation(mffd->NumberOfLevels() - 1); } if (ffd != NULL) grid = ffd->Attributes(); irtkImageAttributes attr = grid; attr._t = 3; disp.Initialize(attr); t->Displacement(disp); } else { // read displacements from file disp.Read(name_in); if (disp.GetT() != 3) { cerr << "Invalid input displacement field: " << name_in << endl; exit(1); } grid = disp.GetImageAttributes(); grid._t = 1; } // copy to output arrays const int n = grid._x * grid._y * grid._z; x = new double[n]; y = new double[n]; z = new double[n]; dx = new double[n]; dy = new double[n]; dz = new double[n]; int p = 0; for (int k = 0; k < grid._z; k++) { for (int j = 0; j < grid._y; j++) { for (int i = 0; i < grid._x; i++) { x[p] = i; y[p] = j; z[p] = k; disp.ImageToWorld(x[p], y[p], z[p]); dx[p] = disp(i, j, k, 0); dy[p] = disp(i, j, k, 1); dz[p] = disp(i, j, k, 2); p++; } } } } // =========================================================================== // Auxiliary functions // =========================================================================== // --------------------------------------------------------------------------- inline void jac(irtkMatrix &J, irtkGenericImage<double> &img, int i, int j, int k) { J.Initialize(3, 3); double sx = 1.0 / img.GetXSize(); double sy = 1.0 / img.GetYSize(); double sz = 1.0 / img.GetZSize(); if (i <= 0 || i >= img.GetX() - 1) { J(0, 0) = 0; J(0, 1) = 0; J(0, 2) = 0; } else { // central difference J(0, 0) = 0.5 * sx * (img(i + 1, j, k, 0) - img(i - 1, j, k, 0)); J(0, 1) = 0.5 * sx * (img(i + 1, j, k, 1) - img(i - 1, j, k, 1)); J(0, 2) = 0.5 * sx * (img(i + 1, j, k, 2) - img(i - 1, j, k, 2)); } if (j <= 0 || j >= img.GetY() - 1) { J(1, 0) = 0; J(1, 1) = 0; J(1, 2) = 0; } else { // central difference J(1, 0) = 0.5 * sy * (img(i, j + 1, k, 0) - img(i, j - 1, k, 0)); J(1, 1) = 0.5 * sy * (img(i, j + 1, k, 1) - img(i, j - 1, k, 1)); J(1, 2) = 0.5 * sy * (img(i, j + 1, k, 2) - img(i, j - 1, k, 2)); } if (k <= 0 || k >= img.GetZ() - 1) { J(2, 0) = 0; J(2, 1) = 0; J(2, 2) = 0; } else { // central difference J(2, 0) = 0.5 * sz * (img(i, j, k + 1, 0) - img(i, j, k - 1, 0)); J(2, 1) = 0.5 * sz * (img(i, j, k + 1, 1) - img(i, j, k - 1, 1)); J(2, 2) = 0.5 * sz * (img(i, j, k + 1, 2) - img(i, j, k - 1, 2)); } } // =========================================================================== // Exponential map // =========================================================================== // --------------------------------------------------------------------------- inline void expEuler(irtkGenericImage<double> &v, double &x, double &y, double &z, bool inv) { const int NumberOfSteps = 100; // Vercauteren et al. use 500 Euler steps for log() const double dt = (inv ? -1.0 : 1.0) / static_cast<double>(NumberOfSteps); irtkLinearInterpolateImageFunction vf; vf.SetInput(&v); vf.Initialize(); for (int s = 0; s < NumberOfSteps; s++) { double i = x; double j = y; double k = z; v.WorldToImage(i, j, k); x += vf.Evaluate(i, j, k, 0) * dt; y += vf.Evaluate(i, j, k, 1) * dt; z += vf.Evaluate(i, j, k, 2) * dt; } } // =========================================================================== // Logarithmic map // =========================================================================== // --------------------------------------------------------------------------- void testLogWithExpEuler(const irtkImageAttributes &grid, const double *x, const double *y, const double *z, const double *dx, const double *dy, const double *dz) { const int nsteps = 5; const int n = grid._x * grid._y * grid._z; double x1, y1, z1; double x2, y2, z2; double lx, ly, lz; double vx, vy, vz; double dvx, dvy, dvz; irtkMatrix Jv, Jdv; double error, avg_error, max_error; int p; irtkImageAttributes attr = grid; attr._t = 3; irtkGenericImage<double> phi(attr); // displacement field irtkGenericImage<double> v (attr); // current velocity field irtkGenericImage<double> vn (attr); // next velocity field irtkGenericImage<double> dv (attr); // dv = exp(-vp) ° Phi(x) - x // Initialize: // v_0 = 0 // v_1 = exp(-v_0) ° Phi(x) - x = Phi(x) - x p = 0; for (int k = 0; k < grid._z; k++) { for (int j = 0; j < grid._y; j++) { for (int i = 0; i < grid._x; i++) { phi(i, j, k, 0) = dx[p]; phi(i, j, k, 1) = dy[p]; phi(i, j, k, 2) = dz[p]; v (i, j, k, 0) = dx[p]; v (i, j, k, 1) = dy[p]; v (i, j, k, 2) = dz[p]; p++; } } } for (int s = 0; s < nsteps; s++) { // Compute dv = exp(-v) ° Phi(x) - x for (int k = 0; k < grid._z; k++) { for (int j = 0; j < grid._y; j++) { for (int i = 0; i < grid._x; i++) { // Convert to world coordinates x1 = i; y1 = j; z1 = k; phi.ImageToWorld(x1, y1, z1); // Transform by Phi x2 = x1 + phi(i, j, k, 0); y2 = y1 + phi(i, j, k, 1); z2 = z1 + phi(i, j, k, 2); // Transform by inverse of current transformation [= exp(-v)] expEuler(v, x2, y2, z2, true); // Compute delta values dv(i, j, k, 0) = x2 - x1; dv(i, j, k, 1) = y2 - y1; dv(i, j, k, 2) = z2 - z1; } } } // Smooth dv to stabilize computation (see Vercauteren et al. ITK filter) irtkGaussianBlurring2D<double> blur(2.0 * (grid._dx > grid._dy ? grid._dx : grid._dy)); blur.SetInput (&dv); blur.SetOutput(&dv); blur.Run(); // Update velocities using the Baker-Campbell-Hausdorff (BCH) formula for (int k = 0; k < grid._z; k++) { for (int j = 0; j < grid._y; j++) { for (int i = 0; i < grid._x; i++) { vx = v (i, j, k, 0); vy = v (i, j, k, 1); vz = v (i, j, k, 2); dvx = dv(i, j, k, 0); dvy = dv(i, j, k, 1); dvz = dv(i, j, k, 2); // Lie bracket [v, dv] #if 1 jac(Jv, v, i, j, k); jac(Jdv, dv, i, j, k); lx = dvx * Jv(0, 0) - vx * Jdv(0, 0) + dvy * Jv(0, 1) - vy * Jdv(0, 1) + dvz * Jv(0, 2) - vz * Jdv(0, 2); ly = dvx * Jv(1, 0) - vx * Jdv(1, 0) + dvy * Jv(1, 1) - vy * Jdv(1, 1) + dvz * Jv(1, 2) - vz * Jdv(1, 2); lz = dvx * Jv(2, 0) - vx * Jdv(2, 0) + dvy * Jv(2, 1) - vy * Jdv(2, 1) + dvz * Jv(2, 2) - vz * Jdv(2, 2); dvx += 0.5 * lx; dvy += 0.5 * ly; dvz += 0.5 * lz; #endif // BCH update step vn(i, j, k, 0) = vx + dvx; vn(i, j, k, 1) = vy + dvy; vn(i, j, k, 2) = vz + dvz; } } } // Set velocities to updated ones v = vn; } // The stationary velocity field v = log(Phi) is now computed. // In the following, the dense vector field is approximated/interpolated // by a 3D B-spline FFD with a control point at each grid point (voxel). // Store integrated displacements in [rx, ry, rz] while also calculating // the RMS error of the resulting (dense) displacement field. double *rx = new double[n]; double *ry = new double[n]; double *rz = new double[n]; avg_error = 0; max_error = 0; p = 0; for (int k = 0; k < grid._z; k++) { for (int j = 0; j < grid._y; j++) { for (int i = 0; i < grid._x; i++) { x1 = i; y1 = j; z1 = k; v.ImageToWorld(x1, y1, z1); x2 = x1; y2 = y1; z2 = z1; expEuler(v, x2, y2, z2, false); rx[p] = x2 - x1; ry[p] = y2 - y1; rz[p] = z2 - z1; error = sqrt(pow(rx[p] - phi(i, j, k, 0), 2) + pow(ry[p] - phi(i, j, k, 1), 2) + pow(rz[p] - phi(i, j, k, 2), 2)); if (max_error < error) max_error = error; avg_error += error; p++; } } } avg_error /= static_cast<double>(n); cout << "Average RMS error SV (grid, expEuler): " << avg_error << endl; cout << "Maximum RMS error SV (grid, expEuler): " << max_error << endl; cout.flush(); // Now approximate a B-spline FFD from the given displacements irtkBSplineFreeFormTransformation3D ffd(const_cast<irtkImageAttributes&>(grid), grid._dx, grid._dy, grid._dz); double *tmpx = new double[n]; double *tmpy = new double[n]; double *tmpz = new double[n]; memcpy(tmpx, rx, sizeof(double) * n); memcpy(tmpy, ry, sizeof(double) * n); memcpy(tmpz, rz, sizeof(double) * n); ffd.ApproximateAsNew(x, y, z, tmpx, tmpy, tmpz, n); ffd.irtkTransformation::Write("test1-vffd1.dof.gz"); // Error of the approximation, thus compare FFD displacement to // displacement [rx, ry, rz] which was used as input to ApproximateAsNew() avg_error = 0; max_error = 0; for (int k = 2; k < grid._z - 2; k++) { for (int j = 2; j < grid._y - 2; j++) { for (int i = 2; i < grid._x - 2; i++) { x1 = i; y1 = j; z1 = k; v.ImageToWorld(x1, y1, z1); x2 = x1; y2 = y1; z2 = z1; ffd.Transform(x2, y2, z2); p = k * grid._x * grid._y + j * grid._x + i; error = sqrt(pow((x2 - x1) - rx[p], 2) + pow((y2 - y1) - ry[p], 2) + pow((z2 - z1) - rz[p], 2)); if (max_error < error) max_error = error; avg_error += error; p++; } } } avg_error /= static_cast<double>(n); cout << "Average RMS error SV (grid, approx. FFD): " << avg_error << endl; cout << "Maximum RMS error SV (grid, approx. FFD): " << max_error << endl; cout.flush(); // Error of the approximated FFD relative to the initial displacement Phi avg_error = 0; max_error = 0; for (int k = 2; k < grid._z - 2; k++) { for (int j = 2; j < grid._y - 2; j++) { for (int i = 2; i < grid._x - 2; i++) { x1 = i; y1 = j; z1 = k; v.ImageToWorld(x1, y1, z1); x2 = x1; y2 = y1; z2 = z1; ffd.Transform(x2, y2, z2); error = sqrt(pow((x2 - x1) - phi(i, j, k, 0), 2) + pow((y2 - y1) - phi(i, j, k, 1), 2) + pow((z2 - z1) - phi(i, j, k, 2), 2)); if (max_error < error) max_error = error; avg_error += error; p++; } } } avg_error /= static_cast<double>(n); cout << "Average RMS error SV (grid, expEuler, approx. FFD): " << avg_error << endl; cout << "Maximum RMS error SV (grid, expEuler, approx. FFD): " << max_error << endl; cout.flush(); memcpy(tmpx, rx, sizeof(double) * n); memcpy(tmpy, ry, sizeof(double) * n); memcpy(tmpz, rz, sizeof(double) * n); // Now do the same using the B-spline interpolation instead ffd.Interpolate(tmpx, tmpy, tmpz); ffd.irtkTransformation::Write("test1-vffd2.dof.gz"); avg_error = 0; max_error = 0; for (int k = 2; k < grid._z - 2; k++) { for (int j = 2; j < grid._y - 2; j++) { for (int i = 2; i < grid._x - 2; i++) { x1 = i; y1 = j; z1 = k; v.ImageToWorld(x1, y1, z1); x2 = x1; y2 = y1; z2 = z1; ffd.Transform(x2, y2, z2); p = k * grid._x * grid._y + j * grid._x + i; error = sqrt(pow((x2 - x1) - rx[p], 2) + pow((y2 - y1) - ry[p], 2) + pow((z2 - z1) - rz[p], 2)); if (max_error < error) max_error = error; avg_error += error; p++; } } } avg_error /= static_cast<double>(n); cout << "Average RMS error SV (grid, interp. FFD): " << avg_error << endl; cout << "Maximum RMS error SV (grid, interp. FFD): " << max_error << endl; cout.flush(); avg_error = 0; max_error = 0; for (int k = 2; k < grid._z - 2; k++) { for (int j = 2; j < grid._y - 2; j++) { for (int i = 2; i < grid._x - 2; i++) { x1 = i; y1 = j; z1 = k; v.ImageToWorld(x1, y1, z1); x2 = x1; y2 = y1; z2 = z1; ffd.Transform(x2, y2, z2); error = sqrt(pow((x2 - x1) - phi(i, j, k, 0), 2) + pow((y2 - y1) - phi(i, j, k, 1), 2) + pow((z2 - z1) - phi(i, j, k, 2), 2)); if (max_error < error) max_error = error; avg_error += error; p++; } } } avg_error /= static_cast<double>(n); cout << "Average RMS error SV (grid, expEuler, interp. FFD): " << avg_error << endl; cout << "Maximum RMS error SV (grid, expEuler, interp. FFD): " << max_error << endl; cout.flush(); delete[] tmpx; delete[] tmpy; delete[] tmpz; delete[] rx; delete[] ry; delete[] rz; } // =========================================================================== // Main // =========================================================================== int irtkDisplacementToVelocityFieldTest(int ac, char *av[]) { // extract/discard program name ac--; av++; // parse arguments char *dofin = NULL; char *dofout = NULL; double std = 2.0; double max = 5.0; irtkImageAttributes grid; grid._x = 64; grid._y = 64; grid._z = 1; grid._dx = 1.0; grid._dy = 1.0; grid._dz = 1.0; for (int i = 0; i < ac; i++) { char *opt = av[i]; // option/flag name char *arg = av[i+1]; // argument for option bool flag = false; // whether option has no argument if (strcmp(opt, "-dofin") == 0) { dofin = arg; } else if (strcmp(opt, "-dofout") == 0) { dofout = arg; } else if (strcmp(opt, "-std") == 0) { std = atof(arg); } else if (strcmp(opt, "-max") == 0) { max = atof(arg); } else if (strcmp(opt, "-x") == 0) { grid._x = atoi(arg); } else if (strcmp(opt, "-y") == 0) { grid._y = atoi(arg); } else if (strcmp(opt, "-z") == 0) { grid._z = atoi(arg); } else if (strcmp(opt, "-dx") == 0) { grid._dx = atoi(arg); } else if (strcmp(opt, "-dy") == 0) { grid._dy = atoi(arg); } else if (strcmp(opt, "-dz") == 0) { grid._dz = atoi(arg); } else { cerr << "Unknown option: " << opt << endl; exit(1); } if (!flag) i++; // skip option argument } // initial displacement field double *x, *y, *z, *dx, *dy, *dz; init(dofin, grid, std, max, x, y, z, dx, dy, dz); irtkImageAttributes attr = grid; attr._t = 3; irtkGenericImage<double> din(attr); int p = 0; for (int k = 0; k < grid._z; k++) { for (int j = 0; j < grid._y; j++) { for (int i = 0; i < grid._x; i++) { din(i, j, k, 0) = dx[p]; din(i, j, k, 1) = dy[p]; din(i, j, k, 2) = dz[p]; p++; } } } irtkDisplacementToVelocityFieldBCH<double> dtov; irtkGenericImage<double> v; dtov.SetInput (&din); dtov.SetOutput(&v); dtov.Run(); irtkVelocityToDisplacementFieldEuler<double> vtod; irtkGenericImage<double> dout; vtod.SetInput (&v); vtod.SetOutput(&dout); vtod.Run(); if (dofout != NULL) { if (strstr(dofout, ".dof") != NULL) { irtkMultiLevelFreeFormTransformation mffd; irtkFreeFormTransformation3D *ffd = new irtkLinearFreeFormTransformation(dout, grid._dx, grid._dy, grid._dz); ffd->Interpolate(dout.GetPointerToVoxels(0, 0, 0, 0), dout.GetPointerToVoxels(0, 0, 0, 1), dout.GetPointerToVoxels(0, 0, 0, 2)); mffd.PushLocalTransformation(ffd); mffd.Write(dofout); } else { dout.Write(dofout); } } // perform tests //testLogWithExpEuler(grid, x, y, z, dx, dy, dz); // clean up delete[] x; delete[] y; delete[] z; delete[] dx; delete[] dy; delete[] dz; exit(0); }
30.561576
115
0.483666
kevin-keraudren
176aa0bf518fa08631ca83c002e61b6014fbb287
4,441
cpp
C++
Lib-Engine/src/sfz/math/MathPrimitiveToStrings.cpp
PetorSFZ/sfz_tech
0d4027ad2c2bb444b83e78f009b649478cb97a73
[ "Zlib" ]
2
2020-09-04T16:52:47.000Z
2021-04-21T18:30:25.000Z
Lib-Engine/src/sfz/math/MathPrimitiveToStrings.cpp
PetorSFZ/sfz_tech
0d4027ad2c2bb444b83e78f009b649478cb97a73
[ "Zlib" ]
null
null
null
Lib-Engine/src/sfz/math/MathPrimitiveToStrings.cpp
PetorSFZ/sfz_tech
0d4027ad2c2bb444b83e78f009b649478cb97a73
[ "Zlib" ]
null
null
null
// Copyright (c) Peter Hillerström (skipifzero.com, peter@hstroem.se) // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. #include "sfz/math/MathPrimitiveToStrings.hpp" namespace sfz { // Vector toString() // ------------------------------------------------------------------------------------------------ str96 toString(const f32x2& vector, u32 numDecimals) noexcept { str96 tmp; toString(vector, tmp, numDecimals); return tmp; } str96 toString(const f32x3& vector, u32 numDecimals) noexcept { str96 tmp; toString(vector, tmp, numDecimals); return tmp; } str96 toString(const f32x4& vector, u32 numDecimals) noexcept { str96 tmp; toString(vector, tmp, numDecimals); return tmp; } void toString(const f32x2& vector, str96& string, u32 numDecimals) noexcept { str32 formatStr; formatStr.appendf("[%%.%uf, %%.%uf]", numDecimals, numDecimals); string.appendf(formatStr.str(), vector.x, vector.y); } void toString(const f32x3& vector, str96& string, u32 numDecimals) noexcept { str32 formatStr; formatStr.appendf("[%%.%uf, %%.%uf, %%.%uf]", numDecimals, numDecimals, numDecimals); string.appendf(formatStr.str(), vector.x, vector.y, vector.z); } void toString(const f32x4& vector, str96& string, u32 numDecimals) noexcept { str32 formatStr; formatStr.appendf("[%%.%uf, %%.%uf, %%.%uf, %%.%uf]", numDecimals, numDecimals, numDecimals, numDecimals); string.appendf(formatStr.str(), vector.x, vector.y, vector.z, vector.w); } str96 toString(const i32x2& vector) noexcept { str96 tmp; toString(vector, tmp); return tmp; } str96 toString(const i32x3& vector) noexcept { str96 tmp; toString(vector, tmp); return tmp; } str96 toString(const i32x4& vector) noexcept { str96 tmp; toString(vector, tmp); return tmp; } void toString(const i32x2& vector, str96& string) noexcept { string.appendf("[%i, %i]", vector.x, vector.y); } void toString(const i32x3& vector, str96& string) noexcept { string.appendf("[%i, %i, %i]", vector.x, vector.y, vector.z); } void toString(const i32x4& vector, str96& string) noexcept { string.appendf("[%i, %i, %i, %i]", vector.x, vector.y, vector.z, vector.w); } // Matrix toString() // ------------------------------------------------------------------------------------------------ str256 toString(const mat22& matrix, bool rowBreak, u32 numDecimals) noexcept { str256 tmp; toString(matrix, tmp, rowBreak, numDecimals); return tmp; } str256 toString(const mat33& matrix, bool rowBreak, u32 numDecimals) noexcept { str256 tmp; toString(matrix, tmp, rowBreak, numDecimals); return tmp; } str256 toString(const mat44& matrix, bool rowBreak, u32 numDecimals) noexcept { str256 tmp; toString(matrix, tmp, rowBreak, numDecimals); return tmp; } template<u32 H, u32 W> void toStringImpl(const Mat<H,W>& matrix, str256& string, bool rowBreak, u32 numDecimals) noexcept { string.clear(); string.appendf("["); str96 tmp; for (u32 y = 0; y < H; y++) { tmp.clear(); toString(matrix.row(y), tmp, numDecimals); string.appendf("%s", tmp.str()); if (y < (H-1)) { if (rowBreak) { string.appendf(",\n "); } else { string.appendf(", "); } } } string.appendf("]"); } void toString(const mat22& matrix, str256& string, bool rowBreak, u32 numDecimals) noexcept { toStringImpl(matrix, string, rowBreak, numDecimals); } void toString(const mat33& matrix, str256& string, bool rowBreak, u32 numDecimals) noexcept { toStringImpl(matrix, string, rowBreak, numDecimals); } void toString(const mat44& matrix, str256& string, bool rowBreak, u32 numDecimals) noexcept { toStringImpl(matrix, string, rowBreak, numDecimals); } } // namespace sfz
26.915152
107
0.68408
PetorSFZ
176c0478cb042b829515982555817b101582615b
1,713
cpp
C++
libraries/ine-vm/tests/implementation_limits_tests.cpp
inery-blockchain/inery
2823539f76a0debae22b6783781b1374c63a59d8
[ "MIT" ]
null
null
null
libraries/ine-vm/tests/implementation_limits_tests.cpp
inery-blockchain/inery
2823539f76a0debae22b6783781b1374c63a59d8
[ "MIT" ]
null
null
null
libraries/ine-vm/tests/implementation_limits_tests.cpp
inery-blockchain/inery
2823539f76a0debae22b6783781b1374c63a59d8
[ "MIT" ]
null
null
null
#include <algorithm> #include <vector> #include <iterator> #include <cstdlib> #include <fstream> #include <string> #include <catch2/catch.hpp> #include <inery/vm/backend.hpp> #include "wasm_config.hpp" #include "utils.hpp" using namespace inery; using namespace inery::vm; void host_call() {} #include "implementation_limits.hpp" wasm_code implementation_limits_wasm_code{ implementation_limits_wasm + 0, implementation_limits_wasm + sizeof(implementation_limits_wasm)}; BACKEND_TEST_CASE( "Test call depth", "[call_depth]") { wasm_allocator wa; using backend_t = inery::vm::backend<nullptr_t, TestType>; using rhf_t = inery::vm::registered_host_functions<nullptr_t>; rhf_t::add<nullptr_t, &host_call, wasm_allocator>("env", "host.call"); backend_t bkend(implementation_limits_wasm_code); bkend.set_wasm_allocator(&wa); bkend.initialize(nullptr); rhf_t::resolve(bkend.get_module()); CHECK(!bkend.call_with_return(nullptr, "env", "call", (uint32_t)250)); CHECK_THROWS_AS(bkend.call(nullptr, "env", "call", (uint32_t)251), std::exception); CHECK(!bkend.call_with_return(nullptr, "env", "call.indirect", (uint32_t)250)); CHECK_THROWS_AS(bkend.call(nullptr, "env", "call.indirect", (uint32_t)251), std::exception); // The host call is added to the recursive function, so we have one fewer frames CHECK(!bkend.call_with_return(nullptr, "env", "call.host", (uint32_t)249)); CHECK_THROWS_AS(bkend.call(nullptr, "env", "call.host", (uint32_t)250), std::exception); CHECK(!bkend.call_with_return(nullptr, "env", "call.indirect.host", (uint32_t)249)); CHECK_THROWS_AS(bkend.call(nullptr, "env", "call.indirect.host", (uint32_t)250), std::exception); }
36.446809
100
0.732633
inery-blockchain
17765af0221ec095ee20d3032b435fd4854cbb08
27,137
cpp
C++
src/plugProjectEbisawaU/ebiP2TitleUnit.cpp
projectPiki/pikmin2
a431d992acde856d092889a515ecca0e07a3ea7c
[ "Unlicense" ]
33
2021-12-08T11:10:59.000Z
2022-03-26T19:59:37.000Z
src/plugProjectEbisawaU/ebiP2TitleUnit.cpp
projectPiki/pikmin2
a431d992acde856d092889a515ecca0e07a3ea7c
[ "Unlicense" ]
6
2021-12-22T17:54:31.000Z
2022-01-07T21:43:18.000Z
src/plugProjectEbisawaU/ebiP2TitleUnit.cpp
projectPiki/pikmin2
a431d992acde856d092889a515ecca0e07a3ea7c
[ "Unlicense" ]
2
2022-01-04T06:00:49.000Z
2022-01-26T07:27:28.000Z
#include "types.h" /* Generated from dpostproc .section .ctors, "wa" # 0x80472F00 - 0x804732C0 .4byte __sinit_ebiP2TitleUnit_cpp .section .rodata # 0x804732E0 - 0x8049E220 .global lbl_804961D8 lbl_804961D8: .4byte 0x00000000 .4byte 0x00000000 .4byte 0x00000000 .4byte 0x65626950 .4byte 0x32546974 .4byte 0x6C65556E .4byte 0x69740000 .4byte 0x6F70656E .4byte 0x696E672E .4byte 0x626D6400 .global lbl_80496200 lbl_80496200: .4byte 0x65626950 .4byte 0x32546974 .4byte 0x6C65556E .4byte 0x69742E63 .4byte 0x70700000 .global lbl_80496214 lbl_80496214: .asciz "P2Assert" .skip 3 .4byte 0x6F70656E .4byte 0x696E675F .4byte 0x77616974 .4byte 0x2E62636B .4byte 0x00000000 .4byte 0x6F70656E .4byte 0x696E675F .4byte 0x6B617A65 .4byte 0x2E62636B .4byte 0x00000000 .4byte 0x656E656D .4byte 0x792E626D .4byte 0x64000000 .4byte 0x656E656D .4byte 0x792E6263 .4byte 0x6B000000 .global lbl_80496260 lbl_80496260: .4byte 0x626C6163 .4byte 0x6B5F706C .4byte 0x616E6500 .4byte 0x00000000 .section .data, "wa" # 0x8049E220 - 0x804EFC20 .global lbl_804E79B8 lbl_804E79B8: .4byte 0x00000000 .4byte 0x00000000 .4byte 0x00000000 .4byte 0x00000000 .section .sbss # 0x80514D80 - 0x80516360 .global lbl_805160B8 lbl_805160B8: .skip 0x4 .global lbl_805160BC lbl_805160BC: .skip 0x4 .section .sdata2, "a" # 0x80516360 - 0x80520E40 .global lbl_8051F838 lbl_8051F838: .float 1.0 .global lbl_8051F83C lbl_8051F83C: .4byte 0x00000000 .global lbl_8051F840 lbl_8051F840: .float 0.5 .global lbl_8051F844 lbl_8051F844: .4byte 0x42700000 .global lbl_8051F848 lbl_8051F848: .4byte 0x3E4CCCCD .global lbl_8051F84C lbl_8051F84C: .4byte 0x3F4CCCCD .global lbl_8051F850 lbl_8051F850: .4byte 0xC0A00001 .4byte 0x00000000 .global lbl_8051F858 lbl_8051F858: .4byte 0x43300000 .4byte 0x00000000 .global lbl_8051F860 lbl_8051F860: .4byte 0x63616D2E .4byte 0x626D6400 .global lbl_8051F868 lbl_8051F868: .4byte 0x63616D2E .4byte 0x62636B00 .global lbl_8051F870 lbl_8051F870: .4byte 0x63616D2E .4byte 0x62726B00 .global lbl_8051F878 lbl_8051F878: .4byte 0x43300000 .4byte 0x80000000 */ /* * --INFO-- * Address: ........ * Size: 0000A8 */ void E3DModel_set2DCoordToBaseTRMatrix__Q23ebi5titleFP8J3DModelR10Vector2<float> R10Vector2<float> f(void) { // UNUSED FUNCTION } namespace ebi { namespace title { /* * --INFO-- * Address: 803C0AF8 * Size: 000088 */ void TParamBase::loadSettingFile(JKRArchive*, char*) { /* stwu r1, -0x430(r1) mflr r0 stw r0, 0x434(r1) stw r31, 0x42c(r1) mr r31, r3 mr r3, r4 lwz r12, 0(r4) mr r4, r5 lwz r12, 0x14(r12) mtctr r12 bctrl cmplwi r3, 0 beq lbl_803C0B68 mr r4, r3 addi r3, r1, 8 li r5, -1 bl __ct__9RamStreamFPvi li r0, 1 cmpwi r0, 1 stw r0, 0x14(r1) bne lbl_803C0B54 li r0, 0 stw r0, 0x41c(r1) lbl_803C0B54: mr r3, r31 addi r4, r1, 8 bl read__10ParametersFR6Stream li r3, 1 b lbl_803C0B6C lbl_803C0B68: li r3, 0 lbl_803C0B6C: lwz r0, 0x434(r1) lwz r31, 0x42c(r1) mtlr r0 addi r1, r1, 0x430 blr */ } /* * --INFO-- * Address: 803C0B80 * Size: 0000B0 */ void TObjBase::calcModelBaseMtx_(void) { /* stwu r1, -0x40(r1) mflr r0 lfs f6, lbl_8051F83C@sda21(r2) stw r0, 0x44(r1) lfs f7, lbl_8051F838@sda21(r2) stw r31, 0x3c(r1) lfs f0, 0x10(r3) lfs f1, 0x18(r3) fneg f8, f0 lwz r4, 0x28(r3) lfs f5, 0xc(r3) fmr f2, f1 addi r31, r4, 0x24 fmsubs f3, f7, f8, f6 fmuls f4, f6, f8 fnmsubs f0, f7, f5, f6 stfs f3, 0x24(r4) fmr f3, f1 fmsubs f4, f6, f5, f4 stfs f6, 0x28(r4) stfs f5, 0x2c(r4) lfs f5, 4(r3) stfs f5, 0x30(r4) stfs f4, 0x34(r4) stfs f7, 0x38(r4) stfs f6, 0x3c(r4) stfs f6, 0x40(r4) stfs f0, 0x44(r4) stfs f6, 0x48(r4) stfs f8, 0x4c(r4) lfs f0, 8(r3) addi r3, r1, 8 fneg f0, f0 stfs f0, 0x50(r4) bl PSMTXScale mr r3, r31 mr r5, r31 addi r4, r1, 8 bl PSMTXConcat lwz r0, 0x44(r1) lwz r31, 0x3c(r1) mtlr r0 addi r1, r1, 0x40 blr */ } } // namespace title } // namespace ebi /* * --INFO-- * Address: ........ * Size: 000040 */ void pushOut___Q33ebi5title8TObjBaseFP10Vector2<float> f(void) { // UNUSED FUNCTION } namespace ebi { namespace title { /* * --INFO-- * Address: 803C0C30 * Size: 000094 */ void TObjBase::pushOut(ebi::title::TObjBase*) { /* stwu r1, -0x20(r1) mflr r0 stw r0, 0x24(r1) stw r31, 0x1c(r1) mr r31, r4 stw r30, 0x18(r1) mr r30, r3 lwz r12, 0(r3) lwz r12, 0xc(r12) mtctr r12 bctrl clrlwi. r0, r3, 0x18 beq lbl_803C0CAC mr r3, r31 lwz r12, 0(r31) lwz r12, 0xc(r12) mtctr r12 bctrl clrlwi. r0, r3, 0x18 beq lbl_803C0CAC lfs f1, 0x1c(r30) addi r3, r1, 8 lfs f0, 0x1c(r31) addi r4, r31, 4 fadds f0, f1, f0 stfs f0, 0x10(r1) lfs f0, 4(r30) stfs f0, 8(r1) lfs f0, 8(r30) stfs f0, 0xc(r1) bl "out__Q23ebi11EGECircle2fFP10Vector2<f>" lbl_803C0CAC: lwz r0, 0x24(r1) lwz r31, 0x1c(r1) lwz r30, 0x18(r1) mtlr r0 addi r1, r1, 0x20 blr */ } /* * --INFO-- * Address: 803C0CC4 * Size: 000220 */ void TMapBase::setArchive(JKRArchive*) { /* stwu r1, -0x20(r1) mflr r0 stw r0, 0x24(r1) stw r31, 0x1c(r1) mr r31, r3 stw r30, 0x18(r1) stw r29, 0x14(r1) stw r28, 0x10(r1) mr r28, r4 lis r4, lbl_804961D8@ha lwz r12, 0(r28) addi r30, r4, lbl_804961D8@l mr r3, r28 lwz r12, 0x14(r12) addi r4, r30, 0x1c mtctr r12 bctrl or. r29, r3, r3 bne lbl_803C0D24 addi r3, r30, 0x28 addi r5, r30, 0x3c li r4, 0x60 crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_803C0D24: mr r3, r29 lis r4, 0x2010 bl load__22J3DModelLoaderDataBaseFPCvUl stw r3, 0x30(r31) mr r3, r28 addi r4, r30, 0x48 lwz r12, 0(r28) lwz r12, 0x14(r12) mtctr r12 bctrl or. r29, r3, r3 bne lbl_803C0D68 addi r3, r30, 0x28 addi r5, r30, 0x3c li r4, 0x6a crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_803C0D68: mr r3, r29 bl load__20J3DAnmLoaderDataBaseFPCv stw r3, 0x48(r31) mr r3, r28 addi r4, r30, 0x5c lwz r12, 0(r28) lwz r12, 0x14(r12) mtctr r12 bctrl or. r29, r3, r3 bne lbl_803C0DA8 addi r3, r30, 0x28 addi r5, r30, 0x3c li r4, 0x6f crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_803C0DA8: mr r3, r29 bl load__20J3DAnmLoaderDataBaseFPCv stw r3, 0x64(r31) lis r4, 4 lwz r3, 0x30(r31) bl newSharedDisplayList__12J3DModelDataFUl lwz r3, 0x30(r31) bl makeSharedDL__12J3DModelDataFv lwz r3, 0x30(r31) lwz r4, 0x48(r31) lwz r0, 0x18(r3) clrlwi r3, r0, 0x1c bl J3DNewMtxCalcAnm__FUlP15J3DAnmTransform stw r3, 0x4c(r31) li r6, 0 li r7, 0 li r8, 0 lwz r3, 0x30(r31) lwz r4, 0x48(r31) lwz r0, 0x18(r3) lwz r5, 0x64(r31) clrlwi r3, r0, 0x1c bl J3DUNewMtxCalcAnm__FUlP15J3DAnmTransformP15J3DAnmTransformP15J3DAnmTransformP15J3DAnmTransform14J3DMtxCalcFlag stw r3, 0x68(r31) li r3, 0xdc lfs f0, lbl_8051F83C@sda21(r2) stfs f0, 0x14(r31) bl __nw__FUl or. r30, r3, r3 beq lbl_803C0E58 lis r3, __vt__8J3DModel@ha lwz r29, 0x30(r31) addi r0, r3, __vt__8J3DModel@l mr r28, r30 stw r0, 0(r30) addi r3, r28, 0x88 bl init__15J3DVertexBufferFv mr r3, r28 bl initialize__8J3DModelFv mr r3, r28 mr r4, r29 lis r5, 2 li r6, 1 bl entryModelData__8J3DModelFP12J3DModelDataUlUl lbl_803C0E58: stw r30, 0x28(r31) addi r3, r31, 0x34 lwz r4, 0x48(r31) lha r4, 6(r4) bl init__12J3DFrameCtrlFs li r0, 2 lfs f1, lbl_8051F844@sda21(r2) stb r0, 0x38(r31) addi r3, r31, 0x50 lfs f2, lbl_8051F840@sda21(r2) lwz r4, sys@sda21(r13) lfs f0, 0x54(r4) fmuls f0, f1, f0 fmuls f0, f2, f0 stfs f0, 0x40(r31) lwz r4, 0x64(r31) lha r4, 6(r4) bl init__12J3DFrameCtrlFs li r0, 2 lfs f1, lbl_8051F844@sda21(r2) stb r0, 0x54(r31) lfs f2, lbl_8051F840@sda21(r2) lwz r3, sys@sda21(r13) lfs f0, 0x54(r3) fmuls f0, f1, f0 fmuls f0, f2, f0 stfs f0, 0x5c(r31) lwz r31, 0x1c(r1) lwz r30, 0x18(r1) lwz r29, 0x14(r1) lwz r28, 0x10(r1) lwz r0, 0x24(r1) mtlr r0 addi r1, r1, 0x20 blr */ } /* * --INFO-- * Address: 803C0EE4 * Size: 000048 */ void TMapBase::startWind(float) { /* stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) li r0, 1 stw r31, 0xc(r1) mr r31, r3 stw r0, 0x2c(r3) lwz r3, sys@sda21(r13) lfs f0, 0x54(r3) fdivs f1, f1, f0 bl __cvt_fp2unsigned stw r3, 0x6c(r31) stw r3, 0x70(r31) lwz r0, 0x14(r1) lwz r31, 0xc(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 803C0F2C * Size: 00027C */ void TMapBase::update(void) { /* stwu r1, -0x60(r1) mflr r0 stw r0, 0x64(r1) stfd f31, 0x50(r1) psq_st f31, 88(r1), 0, qr0 stw r31, 0x4c(r1) stw r30, 0x48(r1) lfs f0, 0x10(r3) mr r31, r3 lfs f1, 0x18(r31) addi r3, r1, 8 fneg f8, f0 lfs f6, lbl_8051F83C@sda21(r2) lfs f7, lbl_8051F838@sda21(r2) fmr f2, f1 lwz r4, 0x28(r31) fmsubs f3, f7, f8, f6 lfs f5, 0xc(r31) fmuls f4, f6, f8 addi r30, r4, 0x24 stfs f3, 0x24(r4) fnmsubs f0, f7, f5, f6 fmsubs f4, f6, f5, f4 stfs f6, 0x28(r4) fmr f3, f1 stfs f5, 0x2c(r4) lfs f5, 4(r31) stfs f5, 0x30(r4) stfs f4, 0x34(r4) stfs f7, 0x38(r4) stfs f6, 0x3c(r4) stfs f6, 0x40(r4) stfs f0, 0x44(r4) stfs f6, 0x48(r4) stfs f8, 0x4c(r4) lfs f0, 8(r31) fneg f0, f0 stfs f0, 0x50(r4) bl PSMTXScale mr r3, r30 mr r5, r30 addi r4, r1, 8 bl PSMTXConcat lwz r0, 0x6c(r31) cmplwi r0, 0 bne lbl_803C0FEC li r0, 0 stw r0, 0x2c(r31) lbl_803C0FEC: lwz r0, 0x2c(r31) cmpwi r0, 1 beq lbl_803C1038 bge lbl_803C114C cmpwi r0, 0 bge lbl_803C1008 b lbl_803C114C lbl_803C1008: addi r3, r31, 0x34 bl update__12J3DFrameCtrlFv lfs f0, 0x44(r31) lwz r3, 0x48(r31) stfs f0, 8(r3) lwz r3, 0x28(r31) lwz r0, 0x4c(r31) lwz r3, 4(r3) lwz r3, 0x28(r3) lwz r3, 0(r3) stw r0, 0x54(r3) b lbl_803C114C lbl_803C1038: addi r3, r31, 0x34 bl update__12J3DFrameCtrlFv addi r3, r31, 0x50 bl update__12J3DFrameCtrlFv lfs f0, 0x44(r31) lwz r3, 0x48(r31) stfs f0, 8(r3) lfs f0, 0x60(r31) lwz r3, 0x64(r31) stfs f0, 8(r3) lwz r3, 0x6c(r31) lwz r30, 0x68(r31) cmplwi r3, 0 beq lbl_803C1078 addi r0, r3, -1 stw r0, 0x6c(r31) lbl_803C1078: lwz r4, 0x70(r31) cmplwi r4, 0 beq lbl_803C10B8 lwz r3, 0x6c(r31) lis r0, 0x4330 stw r0, 0x38(r1) lfd f2, lbl_8051F858@sda21(r2) stw r3, 0x3c(r1) lfd f0, 0x38(r1) stw r4, 0x44(r1) fsubs f1, f0, f2 stw r0, 0x40(r1) lfd f0, 0x40(r1) fsubs f0, f0, f2 fdivs f1, f1, f0 b lbl_803C10BC lbl_803C10B8: lfs f1, lbl_8051F83C@sda21(r2) lbl_803C10BC: lfs f31, lbl_8051F838@sda21(r2) lfs f0, lbl_8051F848@sda21(r2) fsubs f2, f31, f1 fcmpo cr0, f2, f0 cror 2, 0, 2 bne lbl_803C10DC fdivs f31, f2, f0 b lbl_803C10FC lbl_803C10DC: lfs f0, lbl_8051F84C@sda21(r2) fcmpo cr0, f2, f0 cror 2, 0, 2 bne lbl_803C10F0 b lbl_803C10FC lbl_803C10F0: lfs f1, lbl_8051F850@sda21(r2) fneg f0, f1 fmadds f31, f1, f2, f0 lbl_803C10FC: mr r3, r30 lfs f0, lbl_8051F838@sda21(r2) lwz r12, 0(r30) li r4, 0 fsubs f1, f0, f31 lwz r12, 0x1c(r12) mtctr r12 bctrl mr r3, r30 fmr f1, f31 lwz r12, 0(r30) li r4, 1 lwz r12, 0x1c(r12) mtctr r12 bctrl lwz r3, 0x28(r31) lwz r3, 4(r3) lwz r3, 0x28(r3) lwz r3, 0(r3) stw r30, 0x54(r3) lbl_803C114C: lwz r3, 0x28(r31) lwz r12, 0(r3) lwz r12, 0x10(r12) mtctr r12 bctrl lwz r3, 0x28(r31) lwz r12, 0(r3) lwz r12, 0xc(r12) mtctr r12 bctrl lwz r3, 0x28(r31) lwz r12, 0(r3) lwz r12, 0x1c(r12) mtctr r12 bctrl psq_l f31, 88(r1), 0, qr0 lwz r0, 0x64(r1) lfd f31, 0x50(r1) lwz r31, 0x4c(r1) lwz r30, 0x48(r1) mtlr r0 addi r1, r1, 0x60 blr */ } /* * --INFO-- * Address: 803C11A8 * Size: 000150 */ void TBGEnemyBase::setArchive(JKRArchive*) { /* stwu r1, -0x20(r1) mflr r0 stw r0, 0x24(r1) stw r31, 0x1c(r1) stw r30, 0x18(r1) stw r29, 0x14(r1) mr r29, r4 lis r4, lbl_804961D8@ha stw r28, 0x10(r1) addi r31, r4, lbl_804961D8@l mr r28, r3 mr r3, r29 lwz r12, 0(r29) addi r4, r31, 0x70 lwz r12, 0x14(r12) mtctr r12 bctrl or. r30, r3, r3 bne lbl_803C1208 addi r3, r31, 0x28 addi r5, r31, 0x3c li r4, 0xc7 crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_803C1208: mr r3, r30 lis r4, 0x2010 bl load__22J3DModelLoaderDataBaseFPCvUl stw r3, 0x2c(r28) mr r3, r29 addi r4, r31, 0x7c lwz r12, 0(r29) lwz r12, 0x14(r12) mtctr r12 bctrl or. r30, r3, r3 bne lbl_803C124C addi r3, r31, 0x28 addi r5, r31, 0x3c li r4, 0xd1 crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_803C124C: mr r3, r30 bl load__20J3DAnmLoaderDataBaseFPCv stw r3, 0x44(r28) lis r4, 4 lwz r3, 0x2c(r28) bl newSharedDisplayList__12J3DModelDataFUl lwz r3, 0x2c(r28) bl makeSharedDL__12J3DModelDataFv lwz r3, 0x2c(r28) lwz r4, 0x44(r28) lwz r0, 0x18(r3) clrlwi r3, r0, 0x1c bl J3DNewMtxCalcAnm__FUlP15J3DAnmTransform stw r3, 0x48(r28) li r3, 0xdc lfs f0, lbl_8051F83C@sda21(r2) stfs f0, 0x14(r28) bl __nw__FUl or. r31, r3, r3 beq lbl_803C12D4 lis r3, __vt__8J3DModel@ha lwz r30, 0x2c(r28) addi r0, r3, __vt__8J3DModel@l mr r29, r31 stw r0, 0(r31) addi r3, r29, 0x88 bl init__15J3DVertexBufferFv mr r3, r29 bl initialize__8J3DModelFv mr r3, r29 mr r4, r30 lis r5, 2 li r6, 1 bl entryModelData__8J3DModelFP12J3DModelDataUlUl lbl_803C12D4: stw r31, 0x28(r28) lwz r0, 0x24(r1) lwz r31, 0x1c(r1) lwz r30, 0x18(r1) lwz r29, 0x14(r1) lwz r28, 0x10(r1) mtlr r0 addi r1, r1, 0x20 blr */ } /* * --INFO-- * Address: 803C12F8 * Size: 00005C */ void TBGEnemyBase::start(void) { /* stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) stw r31, 0xc(r1) mr r31, r3 lwz r4, 0x44(r3) addi r3, r31, 0x30 lha r4, 6(r4) bl init__12J3DFrameCtrlFs li r0, 0 lfs f1, lbl_8051F844@sda21(r2) stb r0, 0x34(r31) lfs f2, lbl_8051F840@sda21(r2) lwz r3, sys@sda21(r13) lfs f0, 0x54(r3) fmuls f0, f1, f0 fmuls f0, f2, f0 stfs f0, 0x3c(r31) lwz r31, 0xc(r1) lwz r0, 0x14(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 803C1354 * Size: 000124 */ void TBGEnemyBase::update(void) { /* stwu r1, -0x40(r1) mflr r0 lfs f7, lbl_8051F838@sda21(r2) stw r0, 0x44(r1) lfs f6, lbl_8051F83C@sda21(r2) stw r31, 0x3c(r1) stw r30, 0x38(r1) mr r30, r3 lfs f0, 0x10(r3) addi r3, r1, 8 lfs f1, 0x18(r30) fneg f8, f0 lwz r4, 0x28(r30) lfs f5, 0xc(r30) fmr f2, f1 addi r31, r4, 0x24 fmsubs f3, f7, f8, f6 fmuls f4, f6, f8 fnmsubs f0, f7, f5, f6 stfs f3, 0x24(r4) fmr f3, f1 fmsubs f4, f6, f5, f4 stfs f6, 0x28(r4) stfs f5, 0x2c(r4) lfs f5, 4(r30) stfs f5, 0x30(r4) stfs f4, 0x34(r4) stfs f7, 0x38(r4) stfs f6, 0x3c(r4) stfs f6, 0x40(r4) stfs f0, 0x44(r4) stfs f6, 0x48(r4) stfs f8, 0x4c(r4) lfs f0, 8(r30) fneg f0, f0 stfs f0, 0x50(r4) bl PSMTXScale mr r3, r31 mr r5, r31 addi r4, r1, 8 bl PSMTXConcat addi r3, r30, 0x30 bl update__12J3DFrameCtrlFv lfs f0, 0x40(r30) lwz r3, 0x44(r30) stfs f0, 8(r3) lwz r3, 0x28(r30) lwz r0, 0x48(r30) lwz r3, 4(r3) lwz r3, 0x28(r3) lwz r3, 0(r3) stw r0, 0x54(r3) lwz r3, 0x28(r30) lwz r12, 0(r3) lwz r12, 0x10(r12) mtctr r12 bctrl lwz r3, 0x28(r30) lwz r12, 0(r3) lwz r12, 0xc(r12) mtctr r12 bctrl lwz r3, 0x28(r30) lwz r12, 0(r3) lwz r12, 0x1c(r12) mtctr r12 bctrl lwz r0, 0x44(r1) lwz r31, 0x3c(r1) lwz r30, 0x38(r1) mtlr r0 addi r1, r1, 0x40 blr */ } /* * --INFO-- * Address: 803C1478 * Size: 0002D8 */ void TBlackPlane::setArchive(JKRArchive*) { /* stwu r1, -0x20(r1) mflr r0 stw r0, 0x24(r1) stw r31, 0x1c(r1) mr r31, r3 stw r30, 0x18(r1) stw r29, 0x14(r1) mr r29, r4 mr r3, r29 addi r4, r2, lbl_8051F860@sda21 stw r28, 0x10(r1) lwz r12, 0(r29) lwz r12, 0x14(r12) mtctr r12 bctrl or. r28, r3, r3 bne lbl_803C14D8 lis r3, lbl_80496200@ha lis r5, lbl_80496214@ha addi r3, r3, lbl_80496200@l li r4, 0x102 addi r5, r5, lbl_80496214@l crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_803C14D8: mr r3, r28 lis r4, 0x1010 bl load__22J3DModelLoaderDataBaseFPCvUl stw r3, 0x2c(r31) mr r3, r29 addi r4, r2, lbl_8051F868@sda21 lwz r12, 0(r29) lwz r12, 0x14(r12) mtctr r12 bctrl or. r28, r3, r3 bne lbl_803C1524 lis r3, lbl_80496200@ha lis r5, lbl_80496214@ha addi r3, r3, lbl_80496200@l li r4, 0x10c addi r5, r5, lbl_80496214@l crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_803C1524: mr r3, r28 bl load__20J3DAnmLoaderDataBaseFPCv stw r3, 0x44(r31) mr r3, r29 addi r4, r2, lbl_8051F870@sda21 lwz r12, 0(r29) lwz r12, 0x14(r12) mtctr r12 bctrl or. r28, r3, r3 bne lbl_803C156C lis r3, lbl_80496200@ha lis r5, lbl_80496214@ha addi r3, r3, lbl_80496200@l li r4, 0x111 addi r5, r5, lbl_80496214@l crclr 6 bl panic_f__12JUTExceptionFPCciPCce lbl_803C156C: mr r3, r28 bl load__20J3DAnmLoaderDataBaseFPCv stw r3, 0x60(r31) lwz r3, 0x2c(r31) lwz r4, 0x44(r31) lwz r0, 0x18(r3) clrlwi r3, r0, 0x1c bl J3DNewMtxCalcAnm__FUlP15J3DAnmTransform stw r3, 0x48(r31) li r3, 0xdc lfs f0, lbl_8051F83C@sda21(r2) stfs f0, 0x14(r31) bl __nw__FUl or. r29, r3, r3 beq lbl_803C15E0 lis r3, __vt__8J3DModel@ha lwz r30, 0x2c(r31) addi r0, r3, __vt__8J3DModel@l mr r28, r29 stw r0, 0(r29) addi r3, r28, 0x88 bl init__15J3DVertexBufferFv mr r3, r28 bl initialize__8J3DModelFv mr r3, r28 mr r4, r30 lis r5, 2 li r6, 1 bl entryModelData__8J3DModelFP12J3DModelDataUlUl lbl_803C15E0: stw r29, 0x28(r31) lwz r4, 0x28(r31) lwz r3, 0x60(r31) lwz r4, 4(r4) bl searchUpdateMaterialID__15J3DAnmTevRegKeyFP12J3DModelData li r29, 0 b lbl_803C16FC lbl_803C15FC: li r3, 0xf4 bl __nw__FUl or. r30, r3, r3 beq lbl_803C16C0 lis r3, __vt__14J3DMaterialAnm@ha lis r4, __ct__14J3DMatColorAnmFv@ha addi r0, r3, __vt__14J3DMaterialAnm@l li r6, 8 lis r3, __dt__14J3DMatColorAnmFv@ha stw r0, 0(r30) addi r5, r3, __dt__14J3DMatColorAnmFv@l addi r4, r4, __ct__14J3DMatColorAnmFv@l addi r3, r30, 4 li r7, 2 bl __construct_array lis r3, __ct__12J3DTexMtxAnmFv@ha lis r5, __dt__12J3DTexMtxAnmFv@ha addi r4, r3, __ct__12J3DTexMtxAnmFv@l li r6, 8 addi r3, r30, 0x14 addi r5, r5, __dt__12J3DTexMtxAnmFv@l li r7, 8 bl __construct_array lis r3, __ct__11J3DTexNoAnmFv@ha lis r5, __dt__11J3DTexNoAnmFv@ha addi r4, r3, __ct__11J3DTexNoAnmFv@l li r6, 0xc addi r3, r30, 0x54 addi r5, r5, __dt__11J3DTexNoAnmFv@l li r7, 8 bl __construct_array lis r3, __ct__14J3DTevColorAnmFv@ha lis r5, __dt__14J3DTevColorAnmFv@ha addi r4, r3, __ct__14J3DTevColorAnmFv@l li r6, 8 addi r3, r30, 0xb4 addi r5, r5, __dt__14J3DTevColorAnmFv@l li r7, 4 bl __construct_array lis r3, __ct__15J3DTevKColorAnmFv@ha lis r5, __dt__15J3DTevKColorAnmFv@ha addi r4, r3, __ct__15J3DTevKColorAnmFv@l li r6, 8 addi r3, r30, 0xd4 addi r5, r5, __dt__15J3DTevKColorAnmFv@l li r7, 4 bl __construct_array mr r3, r30 bl initialize__14J3DMaterialAnmFv lbl_803C16C0: lwz r3, 0x28(r31) rlwinm r28, r29, 2, 0xe, 0x1d lwz r3, 4(r3) lwz r3, 0x60(r3) lwzx r3, r3, r28 lwz r12, 0(r3) lwz r12, 0x2c(r12) mtctr r12 bctrl lwz r3, 0x28(r31) addi r29, r29, 1 lwz r3, 4(r3) lwz r3, 0x60(r3) lwzx r3, r3, r28 stw r30, 0x3c(r3) lbl_803C16FC: lwz r4, 0x28(r31) clrlwi r3, r29, 0x10 lwz r5, 4(r4) lhz r0, 0x5c(r5) cmplw r3, r0 blt lbl_803C15FC lwz r4, 0x60(r31) addi r3, r5, 0x58 bl entryTevRegAnimator__16J3DMaterialTableFP15J3DAnmTevRegKey lis r5, j3dSys@ha mr r4, r3 addi r3, r5, j3dSys@l bl ErrorReport__6J3DSysCF10J3DErrType lwz r0, 0x24(r1) lwz r31, 0x1c(r1) lwz r30, 0x18(r1) lwz r29, 0x14(r1) lwz r28, 0x10(r1) mtlr r0 addi r1, r1, 0x20 blr */ } /* * --INFO-- * Address: 803C1750 * Size: 0000A0 */ void TBlackPlane::start(void) { /* stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) stw r31, 0xc(r1) mr r31, r3 lwz r4, 0x44(r3) addi r3, r31, 0x30 lha r4, 6(r4) addi r0, r4, -2 extsh r4, r0 bl init__12J3DFrameCtrlFs li r0, 0 lfs f1, lbl_8051F844@sda21(r2) stb r0, 0x34(r31) addi r3, r31, 0x4c lfs f2, lbl_8051F840@sda21(r2) lwz r4, sys@sda21(r13) lfs f0, 0x54(r4) fmuls f0, f1, f0 fmuls f0, f2, f0 stfs f0, 0x3c(r31) lwz r4, 0x60(r31) lha r4, 6(r4) addi r0, r4, -2 extsh r4, r0 bl init__12J3DFrameCtrlFs li r0, 0 lfs f1, lbl_8051F844@sda21(r2) stb r0, 0x50(r31) lfs f2, lbl_8051F840@sda21(r2) lwz r3, sys@sda21(r13) lfs f0, 0x54(r3) fmuls f0, f1, f0 fmuls f0, f2, f0 stfs f0, 0x58(r31) lwz r31, 0xc(r1) lwz r0, 0x14(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 803C17F0 * Size: 000110 */ void TBlackPlane::updateBeforeCamera(void) { /* stwu r1, -0x40(r1) mflr r0 lfs f7, lbl_8051F838@sda21(r2) stw r0, 0x44(r1) lfs f6, lbl_8051F83C@sda21(r2) stw r31, 0x3c(r1) stw r30, 0x38(r1) mr r30, r3 lfs f0, 0x10(r3) addi r3, r1, 8 lfs f1, 0x18(r30) fneg f8, f0 lwz r4, 0x28(r30) lfs f5, 0xc(r30) fmr f2, f1 addi r31, r4, 0x24 fmsubs f3, f7, f8, f6 fmuls f4, f6, f8 fnmsubs f0, f7, f5, f6 stfs f3, 0x24(r4) fmr f3, f1 fmsubs f4, f6, f5, f4 stfs f6, 0x28(r4) stfs f5, 0x2c(r4) lfs f5, 4(r30) stfs f5, 0x30(r4) stfs f4, 0x34(r4) stfs f7, 0x38(r4) stfs f6, 0x3c(r4) stfs f6, 0x40(r4) stfs f0, 0x44(r4) stfs f6, 0x48(r4) stfs f8, 0x4c(r4) lfs f0, 8(r30) fneg f0, f0 stfs f0, 0x50(r4) bl PSMTXScale mr r3, r31 mr r5, r31 addi r4, r1, 8 bl PSMTXConcat addi r3, r30, 0x30 bl update__12J3DFrameCtrlFv addi r3, r30, 0x4c bl update__12J3DFrameCtrlFv lfs f0, 0x5c(r30) lwz r3, 0x60(r30) stfs f0, 8(r3) lfs f0, 0x40(r30) lwz r3, 0x44(r30) stfs f0, 8(r3) lwz r3, 0x28(r30) lwz r0, 0x48(r30) lwz r3, 4(r3) lwz r3, 0x28(r3) lwz r3, 0(r3) stw r0, 0x54(r3) lwz r3, 0x28(r30) lwz r12, 0(r3) lwz r12, 0x10(r12) mtctr r12 bctrl lwz r0, 0x44(r1) lwz r31, 0x3c(r1) lwz r30, 0x38(r1) mtlr r0 addi r1, r1, 0x40 blr */ } /* * --INFO-- * Address: 803C1900 * Size: 000050 */ void TBlackPlane::updateAfterCamera(void) { /* stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) stw r31, 0xc(r1) mr r31, r3 lwz r3, 0x28(r3) lwz r12, 0(r3) lwz r12, 0xc(r12) mtctr r12 bctrl lwz r3, 0x28(r31) lwz r12, 0(r3) lwz r12, 0x1c(r12) mtctr r12 bctrl lwz r0, 0x14(r1) lwz r31, 0xc(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * --INFO-- * Address: 803C1950 * Size: 00004C */ void TBlackPlane::setLogo(void) { /* stwu r1, -0x20(r1) lis r0, 0x4330 lfd f1, lbl_8051F878@sda21(r2) lha r4, 0x38(r3) stw r0, 8(r1) xoris r4, r4, 0x8000 stw r4, 0xc(r1) lfd f0, 8(r1) stw r0, 0x10(r1) fsubs f0, f0, f1 stfs f0, 0x40(r3) lha r0, 0x54(r3) xoris r0, r0, 0x8000 stw r0, 0x14(r1) lfd f0, 0x10(r1) fsubs f0, f0, f1 stfs f0, 0x5c(r3) addi r1, r1, 0x20 blr */ } /* * --INFO-- * Address: 803C199C * Size: 000078 */ void TBlackPlane::getCameraPos(void) { /* stwu r1, -0x10(r1) mflr r0 stw r0, 0x14(r1) stw r31, 0xc(r1) mr r31, r4 lis r4, lbl_80496260@ha stw r30, 8(r1) mr r30, r3 addi r4, r4, lbl_80496260@l lwz r5, 0x28(r31) lwz r3, 4(r5) lwz r3, 0x54(r3) bl getIndex__10JUTNameTabCFPCc lwz r4, 0x28(r31) mulli r0, r3, 0x30 lwz r3, 0x84(r4) lwz r3, 0xc(r3) add r3, r3, r0 lfs f2, 0x2c(r3) lfs f1, 0x1c(r3) lfs f0, 0xc(r3) stfs f0, 0(r30) stfs f1, 4(r30) stfs f2, 8(r30) lwz r31, 0xc(r1) lwz r30, 8(r1) lwz r0, 0x14(r1) mtlr r0 addi r1, r1, 0x10 blr */ } } // namespace title } // namespace ebi /* * --INFO-- * Address: 803C1A14 * Size: 000028 */ void __sinit_ebiP2TitleUnit_cpp(void) { /* lis r4, __float_nan@ha li r0, -1 lfs f0, __float_nan@l(r4) lis r3, lbl_804E79B8@ha stw r0, lbl_805160B8@sda21(r13) stfsu f0, lbl_804E79B8@l(r3) stfs f0, lbl_805160BC@sda21(r13) stfs f0, 4(r3) stfs f0, 8(r3) blr */ }
19.924376
110
0.582673
projectPiki
177be2392c44caefcf3e2ee55055d2ffeb2362d8
131
hxx
C++
remove_cv_t.hxx
mojo-runtime/lib-std
35178964db5b51184f35447f33c379de9768b534
[ "MIT" ]
null
null
null
remove_cv_t.hxx
mojo-runtime/lib-std
35178964db5b51184f35447f33c379de9768b534
[ "MIT" ]
null
null
null
remove_cv_t.hxx
mojo-runtime/lib-std
35178964db5b51184f35447f33c379de9768b534
[ "MIT" ]
null
null
null
#pragma once #include "remove_cv.hxx" namespace std { template <typename T> using remove_cv_t = typename remove_cv<T>::type; }
11.909091
48
0.732824
mojo-runtime
ed0ccabbe97c98ba2ffa749027d8143f19ead76c
6,136
hpp
C++
tools/quickbook/src/grammar_impl.hpp
lijgame/boost
ec2214a19cdddd1048058321a8105dd0231dac47
[ "BSL-1.0" ]
85
2015-02-08T20:36:17.000Z
2021-11-14T20:38:31.000Z
libs/boost/tools/quickbook/src/grammar_impl.hpp
flingone/frameworks_base_cmds_remoted
4509d9f0468137ed7fd8d100179160d167e7d943
[ "Apache-2.0" ]
9
2015-01-28T16:33:19.000Z
2020-04-12T23:03:28.000Z
libs/boost/tools/quickbook/src/grammar_impl.hpp
flingone/frameworks_base_cmds_remoted
4509d9f0468137ed7fd8d100179160d167e7d943
[ "Apache-2.0" ]
27
2015-01-28T16:33:30.000Z
2021-08-12T05:04:39.000Z
/*============================================================================= Copyright (c) 2002 2004 2006 Joel de Guzman Copyright (c) 2004 Eric Niebler Copyright (c) 2010 Daniel James http://spirit.sourceforge.net/ Use, modification and distribution is subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #if !defined(BOOST_SPIRIT_QUICKBOOK_GRAMMARS_IMPL_HPP) #define BOOST_SPIRIT_QUICKBOOK_GRAMMARS_IMPL_HPP #include "grammar.hpp" #include "cleanup.hpp" #include "values.hpp" #include <boost/spirit/include/classic_symbols.hpp> namespace quickbook { namespace cl = boost::spirit::classic; // Information about a square bracket element (e.g. [* word]). // // TODO: The naming is a bit confused as element is also sometimes used for // syntactic/implicit elements (such as lists and horizontal rules). Maybe // should use entity as a more general name instead of element. Or it might // be better to use 'tag' for square bracket elements, although that is // currently used for the type of entities. struct element_info { // Types of elements. // // Used to determine: // // - where they can be used. // - whether they end a paragraph // - how following newlines are interpreted by the grammar. // - and possibly other things..... enum type_enum { // Used when there's no element. nothing = 0, // A section tag. These can't be nested. section_block = 1, // Block elements that can be used in conditional phrases and lists, // but not nested. (TODO: not a good name). conditional_or_block = 2, // Block elements that can be nested in other elements. nested_block = 4, // Phrase elements. phrase = 8, // Depending on the context this can be a block or phrase. // // Currently this is only used for elements that don't actually // generate output (e.g. anchors, source mode tags). The main // reason is so that lists can be preceeded by the element, e.g. // // [#anchor] // * list item. // // If the anchor was considered to be a phrase element, then the // list wouldn't be recognised. maybe_block = 16 }; // Masks to determine which context elements can be used in (in_*), and // whether they are consided to be a block element (is_*). enum context { // At the top level we allow everything. in_top_level = phrase | maybe_block | nested_block | conditional_or_block | section_block, // In conditional phrases and list blocks we everything but section // elements. in_conditional = phrase | maybe_block | nested_block | conditional_or_block, in_list_block = phrase | maybe_block | nested_block | conditional_or_block, // In nested blocks we allow a more limited range of elements. in_nested_block = phrase | maybe_block | nested_block, // In a phrase we only allow phrase elements, ('maybe_block' // elements are treated as phrase elements in this context) in_phrase = phrase | maybe_block, // At the start of a block these are all block elements. is_contextual_block = maybe_block | nested_block | conditional_or_block | section_block, // These are all block elements in all other contexts. is_block = nested_block | conditional_or_block | section_block, }; element_info() : type(nothing), rule(), tag(0) {} element_info( type_enum t, cl::rule<scanner>* r, value::tag_type tag = value::default_tag, unsigned int v = 0) : type(t), rule(r), tag(tag), qbk_version(v) {} type_enum type; cl::rule<scanner>* rule; value::tag_type tag; unsigned int qbk_version; }; struct quickbook_grammar::impl { quickbook::state& state; cleanup cleanup_; // Main Grammar cl::rule<scanner> block_start; cl::rule<scanner> phrase_start; cl::rule<scanner> nested_phrase; cl::rule<scanner> inline_phrase; cl::rule<scanner> paragraph_phrase; cl::rule<scanner> extended_phrase; cl::rule<scanner> table_title_phrase; cl::rule<scanner> inside_preformatted; cl::rule<scanner> inside_paragraph; cl::rule<scanner> command_line; cl::rule<scanner> attribute_template_body; cl::rule<scanner> attribute_value_1_7; cl::rule<scanner> escape; cl::rule<scanner> raw_escape; cl::rule<scanner> skip_entity; // Miscellaneous stuff cl::rule<scanner> hard_space; cl::rule<scanner> space; cl::rule<scanner> blank; cl::rule<scanner> eol; cl::rule<scanner> phrase_end; cl::rule<scanner> comment; cl::rule<scanner> line_comment; cl::rule<scanner> macro_identifier; // Element Symbols cl::symbols<element_info> elements; // Source mode cl::symbols<source_mode_type> source_modes; // Doc Info cl::rule<scanner> doc_info_details; impl(quickbook::state&); private: void init_main(); void init_block_elements(); void init_phrase_elements(); void init_doc_info(); }; } #endif // BOOST_SPIRIT_QUICKBOOK_GRAMMARS_HPP
36.307692
81
0.564863
lijgame
ed0e061bb0185dea1a6ded2ddf8661d18a59dbeb
135
hh
C++
SDLApp/include/system/Base.hh
gleko/lazysdl
83957530c6e141fc85bbe0a2e765d89d2e697a3e
[ "MIT" ]
null
null
null
SDLApp/include/system/Base.hh
gleko/lazysdl
83957530c6e141fc85bbe0a2e765d89d2e697a3e
[ "MIT" ]
null
null
null
SDLApp/include/system/Base.hh
gleko/lazysdl
83957530c6e141fc85bbe0a2e765d89d2e697a3e
[ "MIT" ]
null
null
null
#pragma once #ifdef __linux__ #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #else #include <SDL.h> #include <SDL_image.h> #endif
12.272727
27
0.718519
gleko
ed118c2c4af7663502fd373a7e58bfffd7385a96
735
cpp
C++
tests/domain/linkpositiontest.cpp
hcmarchezi/manipulator-robot-api
6ec50278496b10d3b31557f92f62d1521edefa2a
[ "MIT" ]
null
null
null
tests/domain/linkpositiontest.cpp
hcmarchezi/manipulator-robot-api
6ec50278496b10d3b31557f92f62d1521edefa2a
[ "MIT" ]
null
null
null
tests/domain/linkpositiontest.cpp
hcmarchezi/manipulator-robot-api
6ec50278496b10d3b31557f92f62d1521edefa2a
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include "LinkPosition.h" class LinkPositionTest : public ::testing::Test { }; TEST_F(LinkPositionTest,objectInstanciatedWithDefaultValues) { PDC::LinkPosition linkPosition(1.2,0.3); ASSERT_DOUBLE_EQ(1.2, linkPosition.GetJointPosition()); ASSERT_DOUBLE_EQ(0.3, linkPosition.GetJointVelocity()); } TEST_F(LinkPositionTest,getAndSetJointPosition) { PDC::LinkPosition linkPosition(0.0,0.0); linkPosition.SetJointPosition(1.25); ASSERT_DOUBLE_EQ(1.25, linkPosition.GetJointPosition()); } TEST_F(LinkPositionTest,getAndSetJointVelocity) { PDC::LinkPosition linkPosition(0.0,0.0); linkPosition.SetJointVelocity(0.2); ASSERT_DOUBLE_EQ(0.2, linkPosition.GetJointVelocity()); }
25.344828
60
0.761905
hcmarchezi
ed194aa657cf07f439dbe36b82f4733dfde426e4
199
cpp
C++
problems/acmicpc_3474.cpp
qawbecrdtey/BOJ-sol
e3f410e8f4e3a6ade51b68ce2024529870edac64
[ "MIT" ]
null
null
null
problems/acmicpc_3474.cpp
qawbecrdtey/BOJ-sol
e3f410e8f4e3a6ade51b68ce2024529870edac64
[ "MIT" ]
null
null
null
problems/acmicpc_3474.cpp
qawbecrdtey/BOJ-sol
e3f410e8f4e3a6ade51b68ce2024529870edac64
[ "MIT" ]
null
null
null
#include <stdio.h> int main() { int t; scanf("%d", &t); while(t--) { long long n, sum = 0; scanf("%lld", &n); for(long long i = 5; i <= n; i *= 5) sum += n / i; printf("%lld\n", sum); } }
18.090909
52
0.472362
qawbecrdtey
ed1aa844287016e5e38a3a036829fa12e8b14273
2,895
cpp
C++
system/jlib/jiface.cpp
emuharemagic/HPCC-Platform
bbd5423b25f6ba2d675521c8917f9ecfa97dace5
[ "Apache-2.0" ]
1
2020-08-01T19:54:56.000Z
2020-08-01T19:54:56.000Z
system/jlib/jiface.cpp
emuharemagic/HPCC-Platform
bbd5423b25f6ba2d675521c8917f9ecfa97dace5
[ "Apache-2.0" ]
null
null
null
system/jlib/jiface.cpp
emuharemagic/HPCC-Platform
bbd5423b25f6ba2d675521c8917f9ecfa97dace5
[ "Apache-2.0" ]
null
null
null
/*############################################################################## HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems. 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 "jiface.hpp" #include "jlib.hpp" #include <assert.h> #include "jmutex.hpp" //=========================================================================== void CInterface::beforeDispose() { } //=========================================================================== #if !defined(_WIN32) && !defined(__GNUC__) static CriticalSection *ICrit; MODULE_INIT(INIT_PRIORITY_JIFACE) { ICrit = new CriticalSection(); return true; } MODULE_EXIT() { // delete ICrit; - need to make sure this is deleted after anything that uses it } int poor_atomic_dec_and_read(atomic_t * v) { ICrit->enter(); int ret = --(*v); ICrit->leave(); return ret; } bool poor_atomic_inc_and_test(atomic_t * v) { ICrit->enter(); bool ret = (++(*v) == 0); ICrit->leave(); return ret; } int poor_atomic_xchg(int i, atomic_t * v) { ICrit->enter(); int prev = (*v); (*v)=i; ICrit->leave(); return prev; } void poor_atomic_add(atomic_t * v, int i) { ICrit->enter(); (*v) += i; ICrit->leave(); } int poor_atomic_add_and_read(atomic_t * v, int i) { ICrit->enter(); (*v) += i; int ret = (*v); ICrit->leave(); return ret; } int poor_atomic_add_exchange(atomic_t * v, int i) { ICrit->enter(); int prev = (*v); (*v)=prev+i; ICrit->leave(); return prev; } bool poor_atomic_cas(atomic_t * v, int newvalue, int expectedvalue) { ICrit->enter(); bool ret = false; if ((*v)==expectedvalue) { *v=newvalue; ret = true; } ICrit->leave(); return ret; } void *poor_atomic_xchg_ptr(void *p, void** v) { ICrit->enter(); void * prev = (*v); (*v)=p; ICrit->leave(); return prev; } bool poor_atomic_cas_ptr(void ** v, void * newvalue, void * expectedvalue) { ICrit->enter(); bool ret = false; if ((*v)==expectedvalue) { *v=newvalue; ret = true; } ICrit->leave(); return ret; } //Hopefully the function call will be enough to stop the compiler reordering any operations void poor_compiler_memory_barrier() { } #endif
20.978261
91
0.559585
emuharemagic
ed1ff8534f7c0de92aa159767b18bd04a1508c4f
3,570
cpp
C++
mlir/tools/mlir-reduce/ReductionNode.cpp
jazgarewal/llvm-project
f8fb30933d1804a47241a61289ab04a995eabbe7
[ "Apache-2.0" ]
null
null
null
mlir/tools/mlir-reduce/ReductionNode.cpp
jazgarewal/llvm-project
f8fb30933d1804a47241a61289ab04a995eabbe7
[ "Apache-2.0" ]
null
null
null
mlir/tools/mlir-reduce/ReductionNode.cpp
jazgarewal/llvm-project
f8fb30933d1804a47241a61289ab04a995eabbe7
[ "Apache-2.0" ]
null
null
null
//===- ReductionNode.cpp - Reduction Node Implementation -----------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file defines the reduction nodes which are used to track of the // metadata for a specific generated variant within a reduction pass and are the // building blocks of the reduction tree structure. A reduction tree is used to // keep track of the different generated variants throughout a reduction pass in // the MLIR Reduce tool. // //===----------------------------------------------------------------------===// #include "mlir/Reducer/ReductionNode.h" using namespace mlir; /// Sets up the metadata and links the node to its parent. ReductionNode::ReductionNode(ModuleOp module, ReductionNode *parent) : module(module), evaluated(false) { if (parent != nullptr) parent->linkVariant(this); } /// Calculates and updates the size and interesting values of the module. void ReductionNode::measureAndTest(const Tester *test) { SmallString<128> filepath; int fd; // Print module to temprary file. std::error_code ec = llvm::sys::fs::createTemporaryFile("mlir-reduce", "mlir", fd, filepath); if (ec) llvm::report_fatal_error("Error making unique filename: " + ec.message()); llvm::ToolOutputFile out(filepath, fd); module.print(out.os()); out.os().close(); if (out.os().has_error()) llvm::report_fatal_error("Error emitting bitcode to file '" + filepath); size = out.os().tell(); interesting = test->isInteresting(filepath); evaluated = true; } /// Returns true if the size and interestingness have been calculated. bool ReductionNode::isEvaluated() const { return evaluated; } /// Returns the size in bytes of the module. int ReductionNode::getSize() const { return size; } /// Returns true if the module exhibits the interesting behavior. bool ReductionNode::isInteresting() const { return interesting; } /// Returns the pointers to the child variants. ReductionNode *ReductionNode::getVariant(unsigned long index) const { if (index < variants.size()) return variants[index].get(); return nullptr; } /// Returns true if the child variants vector is empty. bool ReductionNode::variantsEmpty() const { return variants.empty(); } /// Link a child variant node. void ReductionNode::linkVariant(ReductionNode *newVariant) { std::unique_ptr<ReductionNode> ptrVariant(newVariant); variants.push_back(std::move(ptrVariant)); } /// Sort the child variants and remove the uninteresting ones. void ReductionNode::organizeVariants(const Tester *test) { // Ensure all variants are evaluated. for (auto &var : variants) if (!var->isEvaluated()) var->measureAndTest(test); // Sort variants by interestingness and size. llvm::array_pod_sort( variants.begin(), variants.end(), [](const auto *lhs, const auto *rhs) { if (lhs->get()->isInteresting() && !rhs->get()->isInteresting()) return 0; if (!lhs->get()->isInteresting() && rhs->get()->isInteresting()) return 1; return (lhs->get()->getSize(), rhs->get()->getSize()); }); int interestingCount = 0; for (auto &var : variants) { if (var->isInteresting()) { ++interestingCount; } else { break; } } // Remove uninteresting variants. variants.resize(interestingCount); }
32.454545
80
0.664706
jazgarewal
ed29db46b513dba02f36e1e17d3c6c2a692d482b
924
cc
C++
programs/spiral-to-polyhedron.cc
jamesavery/spiralcode-reference
bb2f02e01447c3f3772eb5f2d7bad4d06c8ce29b
[ "BSD-2-Clause" ]
null
null
null
programs/spiral-to-polyhedron.cc
jamesavery/spiralcode-reference
bb2f02e01447c3f3772eb5f2d7bad4d06c8ce29b
[ "BSD-2-Clause" ]
null
null
null
programs/spiral-to-polyhedron.cc
jamesavery/spiralcode-reference
bb2f02e01447c3f3772eb5f2d7bad4d06c8ce29b
[ "BSD-2-Clause" ]
1
2021-08-04T22:44:06.000Z
2021-08-04T22:44:06.000Z
#include <string> #include "libgraph/triangulation.hh" #include "libgraph/spiral.hh" #include "libgraph/polyhedron.hh" using namespace std; int main(int ac, char **av) { if(ac<=1 || string(av[1]) == "help"){ fprintf(stderr,"Syntax: %s \"<spiral code>\" [output-file]\n" "Graph-file formats: %s.\n", av[0], to_string(PlanarGraph::output_formats).c_str()); return -1; } string spiral_name = av[1]; string filename = ac>2? av[2] : "-"; spiral_nomenclature sn(spiral_name); PlanarGraph g(sn); g.layout2d = g.tutte_layout(); Polyhedron P(g,g.zero_order_geometry()); P.optimize(); // cout << "spiralcode = \"" << spiral_name << "\";\n" // << "fullname = " << sn << ";\n" // << "g = " << g << ";\n" // << "P = " << P << ";\n"; FILE *file = filename=="-"? stdout : fopen(filename.c_str(),"wb"); Polyhedron::to_mol2(P, file); fclose(file); return 0; }
23.692308
68
0.570346
jamesavery
ed319960a4da1f014d124f9eceb2020f26f7abce
1,112
cpp
C++
Ejercicios/Tarea_9/dadosss.cpp
Sabrego02/cpp
0e023b3f71b8669f8854372f9a5794144bcd82e8
[ "MIT" ]
null
null
null
Ejercicios/Tarea_9/dadosss.cpp
Sabrego02/cpp
0e023b3f71b8669f8854372f9a5794144bcd82e8
[ "MIT" ]
null
null
null
Ejercicios/Tarea_9/dadosss.cpp
Sabrego02/cpp
0e023b3f71b8669f8854372f9a5794144bcd82e8
[ "MIT" ]
null
null
null
#include <iostream> #include <stdlib.h> #include <time.h> using namespace std; int dado1,dado2; string lanzar; int main() { while (true) { cout<<"En este juego se gana con los numeros 4 , 6 , 8 y se pierden con los numeros 2 y 12 ---"<<endl<<endl; cout<<"Presione cualquier tecla para lanzar los dados: "<<endl; cin>>lanzar; system ("cls"); for (int i=0;i<=1;i++) { srand (time (0)); dado1=rand()%(6)+1; dado2=rand()%(6)+1; } cout<<"Dado 1 ["<<dado1<<"]"; cout<<" Dado 2 ["<<dado2<<"]"<<endl; cout<<"La suma de los dados es: ["<<dado1+dado2<<"]"<<endl; if (dado1+dado2 == 4 or dado1+dado2 == 6 or dado1+dado2 == 8) { cout<<"El jugador gana, la casa pierde "<<endl; break; } if (dado1+dado2 == 2 or dado1+dado2 == 12) { cout<<" La casa gana, el jugador pierde "<<endl; break; } cout<<"\n--- Vuelve a lanzar ---"<<endl; system("pause"); system ("cls"); } }
25.272727
116
0.478417
Sabrego02
ed39d1da482ef14dcef2da26a6c1bc790bf97af8
2,894
cpp
C++
build/dependencies/image_tools/source/win32/wic.cpp
GPUPeople/cuRE
ccba6a29bba4445300cbb630befe57e31f0d80cb
[ "MIT" ]
55
2018-07-11T23:40:06.000Z
2022-03-18T05:34:44.000Z
visualizer/build/dependencies/image_tools/source/win32/wic.cpp
GPUPeople/vertex_batch_optimization
46332cd9f576eb6a464a96d5214cbce7d0319a6b
[ "MIT" ]
1
2020-08-19T12:39:17.000Z
2020-08-19T12:39:17.000Z
visualizer/build/dependencies/image_tools/source/win32/wic.cpp
GPUPeople/vertex_batch_optimization
46332cd9f576eb6a464a96d5214cbce7d0319a6b
[ "MIT" ]
13
2018-08-16T17:00:36.000Z
2022-01-17T08:33:57.000Z
#include <COM/init.h> #include <COM/error.h> #include "wic.h" namespace { COM::unique_ptr<IWICImagingFactory> createWICFactory() { IWICImagingFactory* factory; COM::throw_error(CoCreateInstance(CLSID_WICImagingFactory, nullptr, CLSCTX_INPROC_SERVER, IID_IWICImagingFactory, reinterpret_cast<void**>(&factory))); return COM::make_unique_ptr(factory); } } namespace WIC { IWICImagingFactory* getFactory() { static COM::scope com_init; static auto factory = createWICFactory(); return factory; } COM::unique_ptr<IWICStream> createStream(IWICImagingFactory* factory) { IWICStream* stream; COM::throw_error(factory->CreateStream(&stream)); return COM::make_unique_ptr(stream); } COM::unique_ptr<IWICBitmapEncoder> createEncoder(IWICImagingFactory* factory, REFGUID container_format) { IWICBitmapEncoder* encoder; COM::throw_error(factory->CreateEncoder(container_format, nullptr, &encoder)); return COM::make_unique_ptr(encoder); } COM::unique_ptr<IWICBitmapFrameEncode> createEncoderFrame(IWICBitmapEncoder* encoder) { IWICBitmapFrameEncode* frame; COM::throw_error(encoder->CreateNewFrame(&frame, nullptr)); return COM::make_unique_ptr(frame); } COM::unique_ptr<IWICBitmapDecoder> createDecoder(IWICImagingFactory* factory, REFGUID container_format) { IWICBitmapDecoder* decoder; COM::throw_error(factory->CreateDecoder(container_format, nullptr, &decoder)); return COM::make_unique_ptr(decoder); } COM::unique_ptr<IWICBitmapDecoder> createDecoder(IWICImagingFactory* factory, REFGUID container_format, IStream* stream, WICDecodeOptions options) { auto decoder = createDecoder(factory, container_format); decoder->Initialize(stream, options); return decoder; } COM::unique_ptr<IWICBitmapDecoder> createDecoder(IWICImagingFactory* factory, IStream* stream) { IWICBitmapDecoder* decoder; COM::throw_error(factory->CreateDecoderFromStream(stream, nullptr, WICDecodeMetadataCacheOnDemand, &decoder)); return COM::make_unique_ptr(decoder); } COM::unique_ptr<IWICBitmapFrameDecode> createDecoderFrame(IWICBitmapDecoder* decoder, UINT index) { IWICBitmapFrameDecode* frame; COM::throw_error(decoder->GetFrame(index, &frame)); return COM::make_unique_ptr(frame); } COM::unique_ptr<IWICBitmap> createBitmap(IWICImagingFactory* factory, const GUID& format, UINT width, UINT height, BYTE* data, UINT pitch) { IWICBitmap* bitmap; COM::throw_error(factory->CreateBitmapFromMemory(width, height, format, pitch, pitch * height, data, &bitmap)); return COM::make_unique_ptr(bitmap); } COM::unique_ptr<IWICFormatConverter> createConverter(IWICImagingFactory* factory) { IWICFormatConverter* converter; COM::throw_error(factory->CreateFormatConverter(&converter)); return COM::make_unique_ptr(converter); } }
31.456522
154
0.755701
GPUPeople
ed3a49394729c9ff3390862669c1363f81c93e3f
1,647
hpp
C++
flexcore/pure/pure_node.hpp
vacing/flexcore
08c08e98556f92d1993e2738cbcb975b3764fa2d
[ "Apache-2.0" ]
47
2016-09-23T10:27:17.000Z
2021-12-14T07:31:40.000Z
flexcore/pure/pure_node.hpp
vacing/flexcore
08c08e98556f92d1993e2738cbcb975b3764fa2d
[ "Apache-2.0" ]
10
2016-12-04T16:40:29.000Z
2020-04-28T08:46:50.000Z
flexcore/pure/pure_node.hpp
vacing/flexcore
08c08e98556f92d1993e2738cbcb975b3764fa2d
[ "Apache-2.0" ]
20
2016-09-23T17:14:41.000Z
2021-10-09T18:24:47.000Z
#ifndef SRC_NODES_PURE_NODE_HPP_ #define SRC_NODES_PURE_NODE_HPP_ #include <flexcore/pure/pure_ports.hpp> namespace fc { namespace pure { class pure_node; /** * \brief port mixin which does nothing and leaves the port as pure. * * pure_port_mixin is used for metaprogramming code which applies mixins * which are given as template parameters to ports. */ template<class port> struct pure_port_mixin : port { /** * \brief forwards constructor arguments to port * * takes pointer to pure_node and ignores that. * This means that ports with this mixin have the same signature * as ports with the graph_connectable<node_aware> mixin. */ template<class... base_args> pure_port_mixin(pure_node*, base_args&&... args) : port(std::forward<base_args>(args)...) { } }; /** * \brief pure base class for generic nodes which are templates over node types * * pure_node defines the pure port types and is otherwise an empty class. */ class pure_node { public: template<class data_t> using event_sink = pure_port_mixin<event_sink<data_t>>; template<class data_t> using state_sink = pure_port_mixin<state_sink<data_t>>; template<class data_t> using event_source = pure_port_mixin<event_source<data_t>>; template<class data_t> using state_source = pure_port_mixin<state_source<data_t>>; template<class port_t> using mixin = pure_port_mixin<port_t>; }; } // namespace pure template<class T> struct is_active_sink<pure::pure_port_mixin<T>> : is_active_sink<T> {}; template<class T> struct is_active_source<pure::pure_port_mixin<T>> : is_active_source<T> {}; } // namespace fc #endif /* SRC_NODES_PURE_NODE_HPP_ */
25.338462
93
0.75167
vacing
ed3fa7e28cbf42e9610efa1cadf47ee2ada7af04
33,872
hxx
C++
src/util/image.hxx
lejeunel/glia
24b763a230627951139010cd07b0d0ff2356a365
[ "MIT" ]
null
null
null
src/util/image.hxx
lejeunel/glia
24b763a230627951139010cd07b0d0ff2356a365
[ "MIT" ]
null
null
null
src/util/image.hxx
lejeunel/glia
24b763a230627951139010cd07b0d0ff2356a365
[ "MIT" ]
null
null
null
#ifndef _glia_util_image_hxx_ #define _glia_util_image_hxx_ #include "glia_image.hxx" #include "type/neighbor.hxx" #include "util/struct.hxx" #include "util/container.hxx" #include "itkCastImageFilter.h" #include "itkVectorImageToImageAdaptor.h" #include "itkBinaryThresholdImageFilter.h" #include "itkConnectedComponentImageFilter.h" #include "itkRelabelComponentImageFilter.h" #include "itkScalarConnectedComponentImageFilter.h" #include "itkResampleImageFilter.h" #include "itkShrinkImageFilter.h" #include "itkNearestNeighborInterpolateImageFunction.h" #include "itkVectorNearestNeighborInterpolateImageFunction.h" #include "itkRescaleIntensityImageFilter.h" #include "itkDiscreteGaussianImageFilter.h" #include "itkAddImageFilter.h" #include "itkMultiplyImageFilter.h" #include "itkBinaryThinningImageFilter.h" #include "itkImageDuplicator.h" #include "itkSliceBySliceImageFilter.h" #include "itkLabelImageToLabelMapFilter.h" #include "itkLabelMapOverlayImageFilter.h" #include "itkTileImageFilter.h" #include "itkExtractImageFilter.h" namespace glia { template <typename TImagePtr> UInt getImagePixelNumber (TImagePtr const& image) { auto size = image->GetRequestedRegion().GetSize(); UInt ret = 1; for (int i = 0; i < size.GetSizeDimension(); ++i) { ret *= size[i]; } return ret; } template <typename TSize0, typename TSize1> bool compareSize (TSize0 const& sz0, TSize1 const& sz1, int D) { bool ret = true; int cnt = 0; for (int i = 0; i < D; ++i) { if (sz1[i] > sz0[i]) { return false; } else if (sz1[i] == sz0[i]) { ++cnt; } } if (cnt == D) { return false; } return ret; } template <UInt D> inline itk::ImageRegion<D> createItkImageRegion (std::initializer_list<UInt> const& size) { assert("Error: incorrect size dimension..." && size.size() == D); itk::Index<D> _index; _index.Fill(0); itk::Size<D> _size; std::copy(size.begin(), size.begin() + D, _size.m_InternalArray); return itk::ImageRegion<D>(_index, _size); } template <UInt D> inline itk::ImageRegion<D> createItkImageRegion (std::vector<UInt> const& size) { assert("Error: incorrect size dimension..." && size.size() == D); itk::Index<D> _index; _index.Fill(0); itk::Size<D> _size; std::copy(size.begin(), size.begin() + D, _size.m_InternalArray); return itk::ImageRegion<D>(_index, _size); } template <UInt D> inline itk::ImageRegion<D> createItkImageRegion ( std::vector<int> const& startIndex, std::vector<UInt> const& size) { assert("Error: incorrect index dimension..." && startIndex.size() == D); assert("Error: incorrect size dimension..." && size.size() == D); itk::Index<D> _index; for (int i = 0; i < D; ++i) { _index[i] = startIndex[i]; } itk::Size<D> _size; std::copy(size.begin(), size.begin() + D, _size.m_InternalArray); return itk::ImageRegion<D>(_index, _size); } template <typename TImage> typename TImage::Pointer createImage (itk::ImageRegion<TImage::ImageDimension> const& region) { auto ret = TImage::New(); ret->SetRegions(region); ret->Allocate(); return ret; } template <typename TImage> typename TImage::Pointer createImage (itk::ImageRegion<TImage::ImageDimension> const& region, typename TImage::PixelType val) { auto ret = createImage<TImage>(region); ret->FillBuffer(val); return ret; } template <typename TImage> typename TImage::Pointer createImage (std::initializer_list<UInt> const& size) { return createImage<TImage> (createItkImageRegion<TImage::ImageDimension>(size)); } template <typename TImage> typename TImage::Pointer createImage (std::initializer_list<UInt> const& size, typename TImage::PixelType val) { auto ret = createImage<TImage>(size); ret->FillBuffer(val); return ret; } template <typename TVecImage> typename TVecImage::Pointer createVectorImage (itk::ImageRegion<TVecImage::ImageDimension> const& region, UInt depth) { auto ret = TVecImage::New(); ret->SetRegions(region); ret->SetVectorLength(depth); ret->Allocate(); return ret; } template <typename TImageOut, typename TImagePtrIn> typename TImageOut::Pointer castImage (TImagePtrIn const& image) { typedef itk::CastImageFilter<TImage<TImagePtrIn>, TImageOut> Caster; auto caster = Caster::New(); caster->SetInput(image); caster->Update(); return caster->GetOutput(); } template <typename TImagePtr> inline UInt getImageSize (TImagePtr const& image) { UInt ret = 1; for (int i = 0; i < TImage<TImagePtr>::ImageDimension; ++i) { ret *= image->GetRequestedRegion().GetSize()[i]; } return ret; } template <typename TImagePtr> inline UInt getImageSize (TImagePtr const& image, int dimension) { return image->GetRequestedRegion().GetSize()[dimension]; } template <typename TImagePtr> UInt getImageVolume (TImagePtr const& image) { UInt ret = 1.0; for (int i = 0; i < TImage<TImagePtr>::ImageDimension; ++i) { ret *= getImageSize(image, i); } return ret; } template <typename TImagePtr> double getImageDiagonal (TImagePtr const& image) { double ret = 0.0; for (int i = 0; i < TImage<TImagePtr>::ImageDimension; ++i) { double l = getImageSize(image, i); ret += l * l; } return std::sqrt(ret); } template <typename TVecImagePtr> inline typename itk::VectorImageToImageAdaptor <TVecImageVal<TVecImagePtr>, TImage<TVecImagePtr>::ImageDimension> ::Pointer getImageComponent (TVecImagePtr const& image, UInt component) { auto ret = itk::VectorImageToImageAdaptor <TVecImageVal<TVecImagePtr>, TImage<TVecImagePtr>::ImageDimension> ::New(); ret->SetExtractComponentIndex(component); ret->SetImage(image); return ret; } // Every orignal value has to have correspondence template <typename TImagePtr, typename TMaskPtr> void transformImage ( TImagePtr& image, std::unordered_map<TImageVal<TImagePtr>, TImageVal<TImagePtr>> const& lmap, TMaskPtr const& mask) { for (TImageIIt<TImagePtr> iit(image, image->GetRequestedRegion()); !iit.IsAtEnd(); ++iit) { if (mask.IsNull() || mask->GetPixel(iit.GetIndex()) != MASK_OUT_VAL) { iit.Set(lmap.find(iit.Get())->second); } } } // If fillMissing == true, use fill pixels that miss label mappings // with BG_VAL template <typename TImagePtr, typename TMaskPtr> void transformImage ( TImagePtr& image, std::unordered_map<TImageVal<TImagePtr>, TImageVal<TImagePtr>> const& lmap, TMaskPtr const& mask, bool fillMissing) { for (TImageIIt<TImagePtr> iit(image, image->GetRequestedRegion()); !iit.IsAtEnd(); ++iit) { if (mask.IsNull() || mask->GetPixel(iit.GetIndex()) != MASK_OUT_VAL) { auto lit = lmap.find(iit.Get()); if (lit != lmap.end()) { iit.Set(lit->second); } else if (fillMissing) { iit.Set(BG_VAL); } } } } // Every orignal value must have correspondence template <typename TImagePtr, typename TRegionMap> void transformImage (TImagePtr& image, TRegionMap const& rmap, std::unordered_map<TImageVal<TImagePtr>, TImageVal<TImagePtr>> const& lmap) { for (auto const& lp: lmap) { auto rit = rmap.find(lp.first); if (rit != rmap.end()) { rit->second.traverse ([&image, &lp](typename TRegionMap::Region::Point const& p) { image->SetPixel(p, lp.second); }); } } } template <typename TImageOut, typename TImagePtrIn> typename TImageOut::Pointer thresholdImage (TImagePtrIn const& image, TImageVal<TImagePtrIn> const& lowerThreshold, TImageVal<TImagePtrIn> const& upperThreshold, typename TImageOut::PixelType const& insideVal, typename TImageOut::PixelType const& outsideVal) { auto filter = itk::BinaryThresholdImageFilter <TImage<TImagePtrIn>, TImageOut>::New(); filter->SetInput(image); filter->SetLowerThreshold(lowerThreshold); filter->SetUpperThreshold(upperThreshold); filter->SetInsideValue(insideVal); filter->SetOutsideValue(outsideVal); filter->Update(); return filter->GetOutput(); } template <typename TImagePtr> void thresholdImageInPlace (TImagePtr& image, TImageVal<TImagePtr> const& lowerThreshold, TImageVal<TImagePtr> const& upperThreshold, TImageVal<TImagePtr> const& insideVal, TImageVal<TImagePtr> const& outsideVal) { auto thresholder = itk::BinaryThresholdImageFilter <TImage<TImagePtr>, TImage<TImagePtr>>::New(); thresholder->SetInput(image); thresholder->InPlaceOn(); thresholder->SetLowerThreshold(lowerThreshold); thresholder->SetUpperThreshold(upperThreshold); thresholder->SetInsideValue(insideVal); thresholder->SetOutsideValue(outsideVal); thresholder->Update(); image = thresholder->GetOutput(); } template <typename TImageOut, typename TImagePtrIn> typename TImageOut::Pointer labelConnectedComponents (TImagePtrIn const& image) { auto labeler = itk::ConnectedComponentImageFilter <TImage<TImagePtrIn>, TImageOut>::New(); labeler->SetInput(image); labeler->SetBackgroundValue(BG_VAL); labeler->SetFullyConnected(false); labeler->Update(); return labeler->GetOutput(); } // Does not work for label images? template <typename TImageOut, typename TImagePtrIn> typename TImageOut::Pointer labelScalarConnectedComponents (TImagePtrIn const& image, TImageVal<TImagePtrIn> const& diffThreshold) { auto filter = itk::ScalarConnectedComponentImageFilter <TImage<TImagePtrIn>, TImageOut>::New(); filter->SetDistanceThreshold(diffThreshold); filter->SetInput(image); filter->Update(); return filter->GetOutput(); } // Relabel connected components of label image // Used to relabel 3D label sub-volume cut from bigger volume template <typename TImageOut, typename TImagePtrIn, typename TMaskPtr> typename TImageOut::Pointer labelIdentityConnectedComponents (TImagePtrIn const& image, TMaskPtr const& mask, TImageVal<TImagePtrIn> bgVal) { const UInt D = TImageOut::ImageDimension; auto ret = createImage<TImageOut>(image->GetRequestedRegion(), bgVal); TImageCIIt<TImagePtrIn> iit(image, image->GetRequestedRegion()); TImageIt<typename TImageOut::Pointer> oit(ret, ret->GetRequestedRegion()); auto valToAssign = bgVal + 1; std::queue<itk::Index<D>> iq; while (!iit.IsAtEnd()) { auto val = iit.Value(); auto idx = iit.GetIndex(); if ((mask.IsNull() || mask->GetPixel(idx) != MASK_OUT_VAL) && val != bgVal && oit.Get() == bgVal) { iq.push(idx); while (!iq.empty()) { auto const& i = iq.front(); ret->SetPixel(i, valToAssign); traverseNeighbors(i, image->GetRequestedRegion(), mask, [&iq, &image, &ret, val, valToAssign, bgVal] (itk::Index<D> const& p) { if (image->GetPixel(p) == val && ret->GetPixel(p) == bgVal) { iq.push(p); ret->SetPixel(p, valToAssign); } }); iq.pop(); } ++valToAssign; } ++iit; ++oit; } return ret; } template <typename TImagePtr> TImagePtr blurImage (TImagePtr const& image, double sigma, int kernelWidth) { typedef TImage<TImagePtr> Image; auto g = itk::DiscreteGaussianImageFilter<Image, Image>::New(); g->SetInput(image); g->SetVariance(sigma * sigma); g->SetMaximumKernelWidth(kernelWidth); g->Update(); return g->GetOutput(); } // Blur image slice by slice along specified dimension template <typename TImagePtr> TImagePtr blurImage (TImagePtr const& image, double sigma, int kernelWidth, int dim) { typedef TImage<TImagePtr> ImageHD; typedef itk::Image<TImageVal<TImagePtr>, ImageHD::ImageDimension - 1> ImageLD; auto blurrer = itk::DiscreteGaussianImageFilter<ImageLD, ImageLD>::New(); blurrer->SetVariance(sigma * sigma); blurrer->SetMaximumKernelWidth(kernelWidth); auto slicer = itk::SliceBySliceImageFilter<ImageHD, ImageHD>::New(); slicer->SetFilter(blurrer); slicer->SetDimension(dim); slicer->SetInput(image); slicer->Update(); return slicer->GetOutput(); } template <typename TImageOut, typename TImagePtrIn> typename TImageOut::Pointer shrinkImage (TImagePtrIn const& image, std::vector<int> const& factors) { auto filter = itk::ShrinkImageFilter<TImage<TImagePtrIn>, TImageOut>::New(); filter->SetInput(image); for (int i = 0; i < TImage<TImagePtrIn>::ImageDimension; ++i) { filter->SetShrinkFactor(i, factors[i]); } filter->Update(); return filter->GetOutput(); } template <typename TImageOut, typename TImagePtrIn> typename TImageOut::Pointer resampleImage (TImagePtrIn image, typename TImageOut::SizeType const& size, typename TImageOut::SpacingType const& spacing, bool nearestNeighborInterpolation) { const uint D = TImage<TImagePtrIn>::ImageDimension; auto resampler = itk::ResampleImageFilter<TImage<TImagePtrIn>, TImageOut>::New(); resampler->SetInput(image); resampler->SetSize(size); resampler->SetOutputSpacing(spacing); resampler->SetTransform(itk::IdentityTransform<double, D>::New()); if (nearestNeighborInterpolation) { resampler->SetInterpolator (itk::NearestNeighborInterpolateImageFunction <TImage<TImagePtrIn>, double>::New()); } resampler->Update(); return resampler->GetOutput(); } template <typename TImageOut, typename TImagePtrIn> typename TImageOut::Pointer resampleImage (TImagePtrIn const& image, double factor, bool nearestNeighborInterpolation) { const uint D = TImage<TImagePtrIn>::ImageDimension; auto size = image->GetRequestedRegion().GetSize(); auto spacing = image->GetSpacing(); for (int i = 0; i < D; ++i) { size[i] = std::ceil(size[i] * factor); spacing[i] /= factor; } return resampleImage<TImageOut> (image, size, spacing, nearestNeighborInterpolation); } template <typename TImageOut, typename TImagePtrIn> typename TImageOut::Pointer resampleImage (TImagePtrIn const& image, typename TImageOut::SizeType const& size, bool nearestNeighborInterpolation) { const uint D = TImage<TImagePtrIn>::ImageDimension; auto sizeIn = image->GetRequestedRegion().GetSize(); auto spacing = image->GetSpacing(); for (int i = 0; i < D; ++i) { spacing[i] /= (double)size[i] / sizeIn[i]; } return resampleImage<TImageOut> (image, size, spacing, nearestNeighborInterpolation); } template <typename TVecImageOut, typename TVecImagePtrIn> typename TVecImageOut::Pointer resampleVectorImage (TVecImagePtrIn const& image, typename TVecImageOut::SizeType const& size, typename TVecImageOut::SpacingType const& spacing, bool nearestNeighborInterpolation) { const uint D = TImage<TVecImagePtrIn>::ImageDimension; auto resampler = itk::ResampleImageFilter <TImage<TVecImagePtrIn>, TVecImageOut>::New(); resampler->SetInput(image); resampler->SetSize(size); resampler->SetOutputSpacing(spacing); resampler->SetTransform(itk::IdentityTransform<double, D>::New()); if (nearestNeighborInterpolation) { resampler->SetInterpolator (itk::NearestNeighborInterpolateImageFunction <TImage<TVecImagePtrIn>, double>::New()); } resampler->Update(); return resampler->GetOutput(); } template <typename TVecImageOut, typename TVecImagePtrIn> typename TVecImageOut::Pointer resampleVectorImage (TVecImagePtrIn const& image, double factor, bool nearestNeighborInterpolation) { const uint D = TImage<TVecImagePtrIn>::ImageDimension; auto size = image->GetRequestedRegion().GetSize(); auto spacing = image->GetSpacing(); for (int i = 0; i < D; ++i) { size[i] = std::ceil(size[i] * factor); spacing[i] /= factor; } return resampleVectorImage<TVecImageOut> (image, size, spacing, nearestNeighborInterpolation); } template <typename TVecImageOut, typename TVecImagePtrIn> typename TVecImageOut::Pointer resampleVectorImage (TVecImagePtrIn const& image, typename TVecImageOut::SizeType const& size, bool nearestNeighborInterpolation) { const uint D = TImage<TVecImagePtrIn>::ImageDimension; auto sizeIn = image->GetRequestedRegion().GetSize(); auto spacing = image->GetSpacing(); for (int i = 0; i < D; ++i) { spacing[i] /= (double)size[i] / sizeIn[i]; } return resampleVectorImage<TVecImageOut> (image, size, spacing, nearestNeighborInterpolation); } template <typename TImagePtr> void rescaleImage (TImagePtr& image, TImageVal<TImagePtr> const& outputMin, TImageVal<TImagePtr> const& outputMax) { auto filter = itk::RescaleIntensityImageFilter<TImage<TImagePtr>>::New(); filter->SetInput(image); filter->SetOutputMinimum(outputMin); filter->SetOutputMaximum(outputMax); filter->Update(); image = filter->GetOutput(); } template <typename TImagePtr> TImagePtr maxPoolImage (TImagePtr const& image, std::unordered_set<Int> const& skipDims) { const UInt D = TImage<TImagePtr>::ImageDimension; auto reg0 = image->GetRequestedRegion(); itk::ImageRegion<D> reg1; reg1.GetModifiableIndex().Fill(0); for (int i = 0; i < D; ++i) { reg1.GetModifiableSize()[i] = skipDims.count(i) > 0? reg0.GetSize()[i]: std::ceil(reg0.GetSize()[i] / 2.0); } TImagePtr image1 = createImage<TImage<TImagePtr>>(reg1); auto idx0 = reg0.GetIndex(); std::array<Int, D> delta, sizes; delta.fill(0); for (int i = 0; i < D; ++i) { sizes[i] = getImageSize(image, i); } for (TImageIt<TImagePtr> iit1(image1, reg1); !iit1.IsAtEnd(); ++iit1) { reg0.SetIndex(idx0); int carry = 1; for (int i = 0; i < D; ++i) { int step; if (skipDims.count(i) > 0) { step = 1; delta[i] += carry; carry = delta[i] / sizes[i]; } else { delta[i] += (carry << 1); carry = delta[i] / sizes[i]; if (idx0[i] < sizes[i] - 1) { step = 2; } else { step = 1; --delta[i]; } } delta[i] %= sizes[i]; reg0.GetModifiableSize()[i] = step; idx0[i] = image->GetRequestedRegion().GetIndex()[i] + delta[i]; } TImageCIt<TImagePtr> iit0(image, reg0); TImageVal<TImagePtr> maxi = iit0.Get(); while (!(++iit0).IsAtEnd()) { maxi = std::max(maxi, iit0.Get()); } iit1.Set(maxi); } return image1; } // In-place: image0 += image1 template <typename TImagePtr> void addImage (TImagePtr& image0, TImagePtr const& image1) { // auto adder = itk::AddImageFilter<TImage<TImagePtr>>::New(); // adder->SetInput(image0); // adder->InPlaceOn(); // adder->SetInput2(image1); // adder->Update(); // image0 = adder->GetOutput(); TImageIt<TImagePtr> iit0(image0, image0->GetRequestedRegion()); TImageCIt<TImagePtr> iit1(image1, image1->GetRequestedRegion()); while (!iit0.IsAtEnd()) { iit0.Value() += iit1.Value(); ++iit0; ++iit1; } } // In-place: image *= multiplier template <typename TImagePtr> void multiplyImage (TImagePtr& image, double multiplier) { auto filter = itk::MultiplyImageFilter<TImage<TImagePtr>>::New(); filter->SetInput(image); filter->InPlaceOn(); filter->SetConstant(multiplier); filter->Update(); image = filter->GetOutput(); } template <typename TImagePtr> TImagePtr averageImages (std::vector<TImagePtr> const& images) { TImagePtr ret = createImage<TImage<TImagePtr>> (images.front()->GetRequestedRegion(), 0.0); for (auto const& image: images) { addImage(ret, image); } multiplyImage(ret, 1.0 / images.size()); return ret; } template <typename TImageOut, typename TImagePtrIn> typename TImageOut::Pointer skeletonizeImage (TImagePtrIn const& image) { auto filter = itk::BinaryThinningImageFilter <TImage<TImagePtrIn>, TImageOut>::New(); filter->SetInput(image); filter->Update(); return filter->GetOutput(); } template <typename TImagePtr> TImagePtr cloneImage (TImagePtr const& image) { auto duplicator = itk::ImageDuplicator<TImage<TImagePtr>>::New(); duplicator->SetInputImage(image); duplicator->Update(); return duplicator->GetOutput(); } template <typename TImagePtr> void copyImage (TImagePtr& dstImage, TImagePtr const& srcImage, typename TImage<TImagePtr>::RegionType const& srcRegion, typename TImage<TImagePtr>::IndexType const& dstIndex) { typename TImage<TImagePtr>::RegionType dstRegion; dstRegion.SetIndex(dstIndex); dstRegion.SetSize(srcRegion.GetSize()); TImageCIt<TImagePtr> sit(srcImage, srcRegion); TImageIt<TImagePtr> dit(dstImage, dstRegion); while (!dit.IsAtEnd()) { dit.Set(sit.Get()); ++dit; ++sit; } } // Only works in 2D for now template <typename TImagePtr> void sampleImage (TImagePtr& outputImage, TImagePtr const& inputImage, std::vector<Int> const& offsets, std::vector<int> const& strides) { const UInt D = TImage<TImagePtr>::ImageDimension; TImageLIIt<TImagePtr> iit(inputImage, inputImage->GetRequestedRegion()), oit(outputImage, outputImage->GetRequestedRegion()); iit.SetDirection(0); oit.SetDirection(0); itk::Index<D> startIndex; for (int i = 0; i < D; ++i) { startIndex[i] = offsets[i]; } iit.SetIndex(startIndex); while (!oit.IsAtEnd()) { while (!oit.IsAtEndOfLine()) { oit.Value() = iit.Value(); ++oit; for (int i = 0; i < strides[0]; ++i) { ++iit; } } oit.NextLine(); for (int i = 0; i < strides[1]; ++i) { iit.NextLine(); } } } template <typename TImagePtr> TImagePtr sampleImage (TImagePtr const& image, std::vector<Int> const& offsets, std::vector<int> const& strides) { if (TImage<TImagePtr>::ImageDimension != 2) { perr("Error: image sampling only supports 2D..."); } auto reg = image->GetRequestedRegion(); reg.GetModifiableIndex().Fill(0); for (int i = 0; i < TImage<TImagePtr>::ImageDimension; ++i) { reg.GetModifiableSize()[i] = std::ceil((reg.GetSize()[i] - offsets[i]) / (double)strides[i]); } auto ret = createImage<TImage<TImagePtr>>(reg); sampleImage(ret, image, offsets, strides); return ret; } // Generate boundary image (double-sized) of region segmentation // Only works in 2D for now // See BSDS/seg2bdry for reference // f (TImageCLIIt<TImagePtr> const& viit0, // TImageCLIIt<TImagePtr> const& viit1) template <typename TBImagePtr, typename TImagePtr, typename Func> void genBoundaryImage (TBImagePtr& bImage, TImagePtr const& segImage, Func f) { bImage->FillBuffer(0); // Horizontal edges computed vertically TImageCLIIt<TImagePtr> viit0(segImage, segImage->GetRequestedRegion()), viit1(segImage, segImage->GetRequestedRegion()); viit0.SetDirection(0); viit1.SetDirection(0); viit1.NextLine(); while (!viit1.IsAtEnd()) { while (!viit1.IsAtEndOfLine()) { if (viit0.Get() != viit1.Get()) { auto index = viit0.GetIndex(); index[0] = index[0] * 2 + 1; index[1] = index[1] * 2 + 2; bImage->SetPixel(index, f(viit0, viit1)); } ++viit0; ++viit1; } viit0.NextLine(); viit1.NextLine(); } // Vertical edges computed horizontally TImageCLIIt<TImagePtr> hiit0(segImage, segImage->GetRequestedRegion()), hiit1(segImage, segImage->GetRequestedRegion()); hiit0.SetDirection(1); hiit1.SetDirection(1); hiit1.NextLine(); while (!hiit1.IsAtEnd()) { while (!hiit1.IsAtEndOfLine()) { if (hiit0.Get() != hiit1.Get()) { auto index = hiit0.GetIndex(); index[0] = index[0] * 2 + 2; index[1] = index[1] * 2 + 1; bImage->SetPixel(index, f(hiit0, hiit1)); } ++hiit0; ++hiit1; } hiit0.NextLine(); hiit1.NextLine(); } // Fill in non-border odd (x, y) boundary pixels TImageLIIt<TBImagePtr> oiit(bImage, bImage->GetRequestedRegion()); oiit.SetDirection(0); oiit.NextLine(); oiit.NextLine(); ++(++oiit); TImageCLIIt<TBImagePtr> oiit0(bImage, bImage->GetRequestedRegion()), oiit1(bImage, bImage->GetRequestedRegion()), oiit2(bImage, bImage->GetRequestedRegion()), oiit3(bImage, bImage->GetRequestedRegion()); oiit0.SetDirection(0); oiit1.SetDirection(0); oiit2.SetDirection(0); oiit3.SetDirection(0); oiit0.NextLine(); ++(++oiit0); oiit1.NextLine(); oiit1.NextLine(); ++(++(++oiit1)); oiit2.NextLine(); oiit2.NextLine(); oiit2.NextLine(); ++(++oiit2); oiit3.NextLine(); oiit3.NextLine(); ++oiit3; while (!oiit2.IsAtEnd()) { while (!oiit1.IsAtEndOfLine()) { oiit.Set(std::max(std::max(oiit0.Get(), oiit2.Get()), std::max(oiit1.Get(), oiit3.Get()))); ++oiit1; if (oiit1.IsAtEndOfLine()) { break; } ++oiit1; ++(++oiit); ++(++oiit0); ++(++oiit2); ++(++oiit3); } oiit2.NextLine(); if (oiit2.IsAtEnd()) { break; } oiit2.NextLine(); oiit.NextLine(); oiit.NextLine(); oiit0.NextLine(); oiit0.NextLine(); oiit1.NextLine(); oiit1.NextLine(); oiit3.NextLine(); oiit3.NextLine(); ++(++oiit); ++(++oiit0); ++(++(++oiit1)); ++(++oiit2); ++oiit3; } // Fill in border pixels auto width = getImageSize(bImage, 0); auto height = getImageSize(bImage, 1); auto _reg = bImage->GetRequestedRegion(); auto _index = _reg.GetIndex(); _reg.GetModifiableIndex()[1] = 1; _reg.GetModifiableSize()[1] = 1; copyImage(bImage, bImage, _reg, _index); // Top _reg.GetModifiableIndex()[1] = height - 2; _index[1] = height - 1; copyImage(bImage, bImage, _reg, _index); // Bottom _reg.GetModifiableIndex()[0] = 1; _reg.GetModifiableIndex()[1] = 0; _reg.GetModifiableSize()[0] = 1; _reg.GetModifiableSize()[1] = height; _index.Fill(0); copyImage(bImage, bImage, _reg, _index); // Left _reg.GetModifiableIndex()[0] = width - 2; _index[0] = width - 1; copyImage(bImage, bImage, _reg, _index); // Right } // Generate boundary image of region segmentation // If doubleSize == false, use original size // Only works in 2D for now // See BSDS/seg2bdry for reference // f (TImageCLIIt<TImagePtr> const& viit0, // TImageCLIIt<TImagePtr> const& viit1) template <typename TImageOut, typename TImagePtr, typename Func> typename TImageOut::Pointer genBoundaryImage (TImagePtr const& segImage, Func f) { if (TImage<TImagePtr>::ImageDimension != 2) { perr("Error: boundary image generation only supports 2D..."); } auto reg = segImage->GetRequestedRegion(); reg.GetModifiableIndex().Fill(0); for (int i = 0; i < TImage<TImagePtr>::ImageDimension; ++i) { reg.GetModifiableSize()[i] = reg.GetSize()[i] * 2 + 1; } auto bImage = createImage<TImageOut>(reg); genBoundaryImage(bImage, segImage, f); return bImage; } // Relabel BG_VAL pixels to nearest smallest region template <typename TImagePtr, typename TMaskPtr> void dilateImage (TImagePtr& image, TMaskPtr const& mask) { const uint D = TImage<TImagePtr>::ImageDimension; typedef TImageVal<TImagePtr> TKey; std::unordered_map<TKey, uint> cmap; genCountMap(cmap, image, mask); auto bgcit = cmap.find(BG_VAL); if (bgcit == cmap.end()) { return; } std::vector<itk::Index<D>> openSet; openSet.reserve(bgcit->second); std::vector<int> changeIndices; std::vector<TKey> changeKeys; changeIndices.reserve(bgcit->second); changeKeys.reserve(bgcit->second); cmap.erase(bgcit); for (TImageCIIt<TImagePtr> iit(image, image->GetRequestedRegion()); !iit.IsAtEnd(); ++iit) { if (iit.Value() == BG_VAL) { openSet.push_back(iit.GetIndex()); } } std::vector<TKey> nvals; nvals.reserve(D * 2); int n = openSet.size(); while (n > 0) { changeIndices.clear(); changeKeys.clear(); for (int i = 0; i < n; ++i) { nvals.clear(); traverseNeighbors(openSet[i], image->GetRequestedRegion(), mask, [&nvals, &image](itk::Index<D> const& idx) { auto val = image->GetPixel(idx); if (val != BG_VAL) { nvals.push_back(val); } }); if (!nvals.empty()) { uint minSize = UINT_MAX; TKey minKey = BG_VAL; for (auto v: nvals) { auto sz = cmap.find(v)->second; if (sz < minSize) { minSize = sz; minKey = v; } } changeIndices.push_back(i); changeKeys.push_back(minKey); } } int m = changeIndices.size(); for (int i = 0; i < m; ++i) { image->SetPixel(openSet[changeIndices[i]], changeKeys[i]); } remove(openSet, changeIndices); n = openSet.size(); } } template <typename TImagePtr, typename TMaskPtr> RgbImage::Pointer overlayImage (TImagePtr const& labelImage, typename UInt8Image<TImage<TImagePtr>::ImageDimension> ::Pointer const& bgImage, TMaskPtr const& mask, double opacity) { const UInt D = TImage<TImagePtr>::ImageDimension; typedef itk::LabelImageToLabelMapFilter<TImage<TImagePtr>> LMF; auto lmf = LMF::New(); lmf->SetInput(labelImage); auto lmof = itk::LabelMapOverlayImageFilter <typename LMF::OutputImageType, UInt8Image<D>, RgbImage>::New(); lmof->SetInput(lmf->GetOutput()); lmof->SetFeatureImage (bgImage.IsNotNull()? bgImage: createImage<UInt8Image<D>>(labelImage->GetRequestedRegion(), 255)); lmof->SetOpacity(opacity); lmof->Update(); return lmof->GetOutput(); } template <typename T, typename TImagePtr, typename TMaskPtr> void getImagePatches (std::vector<std::vector<T>>& patches, TImagePtr const& image, TMaskPtr const& mask, std::vector<int> const& patchRadius) { const UInt D = TImage<TImagePtr>::ImageDimension; UInt n = getImageSize(image); patches.reserve(n); itk::Size<D> radius; uint np = 1; for (int i = 0; i < D; ++i) { radius[i] = patchRadius[i]; np *= patchRadius[i] * 2 + 1; } for (itk::ConstNeighborhoodIterator<TImage<TImagePtr>> iit(radius, image, image->GetRequestedRegion()); !iit.IsAtEnd(); ++iit) { if (mask.IsNull() || mask->GetPixel(iit.GetIndex()) != MASK_OUT_VAL) { patches.emplace_back(); patches.back().reserve(np); for (int i = 0; i < np; ++i) { patches.back().push_back(iit.GetPixel(i)); } } } } template <typename TImagePtr> void relabelImage (TImagePtr& image, int minSize) { typedef TImage<TImagePtr> Image; auto relabeler = itk::RelabelComponentImageFilter<Image, Image>::New(); relabeler->InPlaceOn(); relabeler->SetInput(image); if (minSize > 0) { relabeler->SetMinimumObjectSize(minSize); } relabeler->Update(); image = relabeler->GetOutput(); } template <typename TImagePtr, typename TMaskPtr> void relabelImages ( std::vector<TImagePtr>& images, std::vector<TMaskPtr> const& masks, int minSize) { typedef TImageVal<TImagePtr> TVal; std::unordered_map<TVal, uint> cmap; int n = images.size(); for (int i = 0; i < n; ++i) { genCountMap(cmap, images[i], masks[i]); } std::vector<std::pair<uint, TVal>> ckeys; ckeys.reserve(cmap.size()); for (auto const& cp : cmap) { ckeys.push_back(std::make_pair(cp.second, cp.first)); } std::sort(ckeys.begin(), ckeys.end(), inv_comp<std::pair<uint, TVal>>); std::unordered_map<TVal, TVal> lmap; TVal newKey = 1; for (auto const& ck : ckeys) { lmap[ck.second] = ck.first >= minSize ? newKey++ : BG_VAL; } for (int i = 0; i < n; ++i) { transformImage(images[i], lmap, masks[i]); } } // layout: e.g. use {1, 1, 0} to stack 2D into 3D // See: https://itk.org/ITKExamples/src/Filtering/ImageGrid" // "/Create3DVolume/Documentation.html template <UInt DOut, typename TImagePtr> typename itk::Image<TImageVal<TImagePtr>, DOut>::Pointer tileImages ( std::vector<TImagePtr> const& images, std::array<int, DOut> const& layout) { typedef TImageVal<TImagePtr> TVal; typedef itk::Image<TVal, TImage<TImagePtr>::ImageDimension> InputImage; typedef itk::Image<TVal, DOut> OutputImage; typedef itk::TileImageFilter<InputImage, OutputImage> TF; auto tf = TF::New(); itk::FixedArray<uint, DOut> _layout; for (int i = 0; i < DOut; ++i) { _layout[i] = layout[i]; } tf->SetLayout(_layout); for (int i = 0; i < images.size(); ++i) { tf->SetInput(i, images[i]); } tf->SetDefaultPixelValue(BG_VAL); tf->Update(); return tf->GetOutput(); } // Shortcut for simply stacking images template <typename TImagePtr> typename itk::Image< TImageVal<TImagePtr>, TImage<TImagePtr>::ImageDimension + 1>::Pointer stackImages (std::vector<TImagePtr> const& images) { const UInt DOut = TImage<TImagePtr>::ImageDimension + 1; std::array<int, DOut> layout; layout.fill(1); layout.back() = 0; return tileImages(images, layout); } // E.g., to get 4x4x4 3D subvolume at [x, y, z, 2] from 4x4x4x4 4D volume // Use start = {0, 0, 0, 2} and size = {4, 4, 4, 0} // See: https://itk.org/Doxygen/html/classitk_1_1ExtractImageFilter.html template <UInt DOut, typename TImagePtr> typename itk::Image<TImageVal<TImagePtr>, DOut>::Pointer extractImage ( TImagePtr const& image, std::vector<int> const& start, std::vector<int> const& size) { typedef TImage<TImagePtr> InputImage; typedef itk::Image<TImageVal<TImagePtr>, DOut> OutputImage; typename InputImage::IndexType _start; for (int i = 0; i < start.size(); ++i) { _start[i] = start[i]; } typename InputImage::SizeType _size; for (int i = 0; i < size.size(); ++i) { _size[i] = size[i]; } typename InputImage::RegionType region(_start, _size); auto ef = itk::ExtractImageFilter<InputImage, OutputImage>::New(); ef->SetExtractionRegion(region); ef->SetInput(image); ef->SetDirectionCollapseToIdentity(); ef->Update(); return ef->GetOutput(); } }; #endif
31.018315
74
0.668015
lejeunel
ed4061f4f8f122df260cdbea24fbdfceddc9f368
6,956
cpp
C++
ros2_workspace/src/app_cue/src/SerialMonitor.cpp
MaSiRo-Project-OSS/TWELITE_for_ROS
dae7f38b1a71ab2756776ed93b8eb09dddeeaf4e
[ "MIT" ]
null
null
null
ros2_workspace/src/app_cue/src/SerialMonitor.cpp
MaSiRo-Project-OSS/TWELITE_for_ROS
dae7f38b1a71ab2756776ed93b8eb09dddeeaf4e
[ "MIT" ]
4
2022-01-10T08:51:39.000Z
2022-01-10T10:31:15.000Z
ros2_workspace/src/app_cue/src/SerialMonitor.cpp
MaSiRo-Project-OSS/TWELITE_for_ROS
dae7f38b1a71ab2756776ed93b8eb09dddeeaf4e
[ "MIT" ]
null
null
null
/** * @file SerialMonitor.cpp * @brief SerialMonitor for Linux * @date 2022-01-08 * * @copyright Copyright (c) 2022-. * MaSiRo Project. * */ #include "SerialMonitor.h" #include <fcntl.h> #include <unistd.h> // ==================================================== // #define SERIALMONITOR_DEBUG 0 /* **************************************************** */ #if SERIALMONITOR_DEBUG #define debug_printf(...) printf(__VA_ARGS__) #else #define debug_printf(...) #endif #define log_printf(...) printf(__VA_ARGS__) // ==================================================== // SerialMonitor::SerialMonitor(std::string name, Baudrate baud, int bits, Parity parity, int stop_bits) { this->set_device_name(name); this->set_baud(baud); this->set_format(bits, parity, stop_bits); } ////////////////////////////////////////////////////////// // 設定 API ////////////////////////////////////////////////////////// #pragma region SETTING_API void SerialMonitor::set_device_name(std::string name) { if (name.size() > 0) { this->dev_name = name; } } void SerialMonitor::set_baud(Baudrate baud) { this->dev_baud = baud; } void SerialMonitor::set_format(int bits, Parity parity, int stop_bits) { this->dev_bits = bits; this->dev_parity = parity; this->dev_stop_bits = stop_bits; } std::string SerialMonitor::get_device_name() { return this->dev_name; } #pragma endregion ////////////////////////////////////////////////////////// // デバイス接続 API ////////////////////////////////////////////////////////// #pragma region CONNECT_API int SerialMonitor::device_open(void) { int result = -1; if (-1 == this->dev_fd) { this->dev_fd = open(this->dev_name.c_str(), O_RDWR | O_NOCTTY | O_NONBLOCK); if (this->dev_fd >= 0) { fcntl(this->dev_fd, F_SETFL, 0); //load configuration struct termios conf_tio; tcgetattr(this->dev_fd, &conf_tio); //set baudrate speed_t BAUDRATE = this->dev_baud; cfsetispeed(&conf_tio, BAUDRATE); //non canonical, non echo back conf_tio.c_lflag &= ~(ECHO | ICANON); //non blocking conf_tio.c_cc[VMIN] = 0; conf_tio.c_cc[VTIME] = 0; //store configuration tcsetattr(this->dev_fd, TCSANOW, &conf_tio); debug_printf("%s()\n", __func__); log_printf("open device : \"%s\" %s/bps/data %d bit/%s/stop %d bit\n", this->dev_name.c_str(), this->textBaudrate(this->dev_baud).c_str(), this->dev_bits, this->textParity(this->dev_parity).c_str(), this->dev_stop_bits); this->dev_connected = true; result = 0; } else { this->dev_connected = false; } } return result; } bool SerialMonitor::is_connected(void) { return this->dev_connected; } void SerialMonitor::device_close(void) { if (this->dev_fd >= 0) { close(this->dev_fd); this->dev_fd = -1; } debug_printf("%s()\n", __func__); this->dev_connected = false; } #pragma endregion ////////////////////////////////////////////////////////// // 操作 API ////////////////////////////////////////////////////////// #pragma region OPERATION_API int SerialMonitor::device_write(std::string data) { int result = 0; if (this->dev_connected) { result = write(this->dev_fd, data.c_str(), data.size()); if (result < 0) { this->dev_connected = false; } } return result; } bool SerialMonitor::device_read(std::string *outdata, bool *one_sentence) { bool result = false; const int BUFFER_SIZE = 4096; char buf[BUFFER_SIZE] = { 0 }; static char refill[BUFFER_SIZE] = { 0 }; static int read_size = 0; bool flag_repeat = true; int counter = 2; *outdata = ""; if (true == this->dev_connected) { do { int recv_data = read(this->dev_fd, buf, sizeof(buf)); if (recv_data <= 0) { if (0 >= counter) { flag_repeat = false; } counter--; break; } else { for (int i = 0; i < recv_data; i++) { if ((BUFFER_SIZE - 2) <= read_size) { flag_repeat = false; *one_sentence = false; break; } else if ('\n' == buf[i]) { flag_repeat = false; *one_sentence = true; break; } else if ('\r' == buf[i]) { flag_repeat = false; *one_sentence = true; break; } else { refill[read_size++] = buf[i]; } } if (false == flag_repeat) { if (0 != read_size) { refill[read_size++] = '\n'; refill[read_size] = '\0'; *outdata = refill; result = true; } if (false == *one_sentence) { flag_repeat = true; } read_size = 0; } else { usleep(1000); } } } while (true == flag_repeat); } return result; } #pragma endregion /* **************************************************** */ // /* **************************************************** */ #pragma region PRIVATE_API std::string SerialMonitor::textParity(Parity parity) { switch (parity) { case Parity::None: return "None"; case Parity::Odd: return "Odd"; case Parity::Even: return "Even"; case Parity::Forced1: return "Forced1"; case Parity::Forced0: return "Forced0"; default: return "unknow"; } } std::string SerialMonitor::textBaudrate(Baudrate baud) { switch (baud) { case Baudrate::BaudRate_57600: return "57,600"; case Baudrate::BaudRate_115200: return "115,200"; case Baudrate::BaudRate_230400: return "230,400"; case Baudrate::BaudRate_460800: return "460,800"; case Baudrate::BaudRate_500000: return "500,000"; case Baudrate::BaudRate_576000: return "576,000"; case Baudrate::BaudRate_921600: return "921,600"; default: return "---"; } } #pragma endregion
29.104603
101
0.45069
MaSiRo-Project-OSS
ed41eadaf12a3374bd832ef2058094679082e39f
743
cpp
C++
src/mesh/meshGlobalIds.cpp
Nek5000/nekrs
7a55f459cd9b42129d0d3312dac8dd614cdb50d0
[ "BSD-3-Clause" ]
2
2021-09-07T03:00:53.000Z
2021-12-06T18:08:27.000Z
src/mesh/meshGlobalIds.cpp
yhaomin2007/nekRS
a416c98ed00d48d1bd9722dcca781a1859fc37f4
[ "BSD-3-Clause" ]
2
2021-06-27T02:07:27.000Z
2021-08-24T04:47:42.000Z
src/mesh/meshGlobalIds.cpp
yhaomin2007/nekRS
a416c98ed00d48d1bd9722dcca781a1859fc37f4
[ "BSD-3-Clause" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <stddef.h> #include "mesh.h" #include "nekInterfaceAdapter.hpp" struct parallelNode_t { int baseRank; hlong baseId; }; // uniquely label each node with a global index, used for gatherScatter void meshNekParallelConnectNodes(mesh_t* mesh) { int rank, size; rank = platform->comm.mpiRank; size = platform->comm.mpiCommSize; dlong localNodeCount = mesh->Np * mesh->Nelements; mesh->globalIds = (hlong*) calloc(localNodeCount, sizeof(hlong)); hlong ngv = nek::set_glo_num(mesh->N + 1, mesh->cht); for(dlong id = 0; id < localNodeCount; ++id) mesh->globalIds[id] = nekData.glo_num[id]; } void meshGlobalIds(mesh_t* mesh) { meshNekParallelConnectNodes(mesh); return; }
21.852941
71
0.711978
Nek5000
ed43b83db56198766706922f061cba47b1f0e0e5
819
cpp
C++
source/383.cpp
narikbi/LeetCode
835215c21d1bd6820b20c253026bcb6f889ed3fc
[ "MIT" ]
2
2017-02-28T11:39:13.000Z
2019-12-07T17:23:20.000Z
source/383.cpp
narikbi/LeetCode
835215c21d1bd6820b20c253026bcb6f889ed3fc
[ "MIT" ]
null
null
null
source/383.cpp
narikbi/LeetCode
835215c21d1bd6820b20c253026bcb6f889ed3fc
[ "MIT" ]
null
null
null
// // 383.cpp // LeetCode // // Created by Narikbi on 18.02.17. // Copyright © 2017 app.leetcode.kz. All rights reserved. // #include <stdio.h> #include <iostream> #include <vector> #include <string> #include <algorithm> #include <deque> #include <queue> #include <set> #include <map> #include <stack> #include <cmath> using namespace std; bool canConstruct(string ransomNote, string magazine) { map <char, int> m; for (char c : magazine) m[c]++; for (int i = 0; i < ransomNote.size(); i++) { if (m.count(ransomNote[i]) && m[ransomNote[i]] > 0) { m[ransomNote[i]]--; } else { return false; } } return true; } //int main(int argc, const char * argv[]) { // // cout << canConstruct("aa", "ab"); // // return 0; //}
17.804348
61
0.559219
narikbi
ed45a8f97f758cc7e55fa0abe242a1d30f090308
16,641
cpp
C++
src/realm/object-store/impl/collection_notifier.cpp
DominicFrei/realm-core
731d4deff603fcbd76de0d70e670b945cae58238
[ "Apache-2.0" ]
null
null
null
src/realm/object-store/impl/collection_notifier.cpp
DominicFrei/realm-core
731d4deff603fcbd76de0d70e670b945cae58238
[ "Apache-2.0" ]
null
null
null
src/realm/object-store/impl/collection_notifier.cpp
DominicFrei/realm-core
731d4deff603fcbd76de0d70e670b945cae58238
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////// // // Copyright 2016 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// #include <realm/object-store/impl/collection_notifier.hpp> #include <realm/object-store/impl/realm_coordinator.hpp> #include <realm/object-store/shared_realm.hpp> #include <realm/db.hpp> #include <realm/list.hpp> using namespace realm; using namespace realm::_impl; bool CollectionNotifier::all_related_tables_covered(const TableVersions& versions) { if (m_related_tables.size() > versions.size()) { return false; } auto first = versions.begin(); auto last = versions.end(); for (auto& it : m_related_tables) { TableKey tk{it.table_key}; auto match = std::find_if(first, last, [tk](auto& elem) { return elem.first == tk; }); if (match == last) { // tk not found in versions return false; } } return true; } std::function<bool(ObjectChangeSet::ObjectKeyType)> CollectionNotifier::get_modification_checker(TransactionChangeInfo const& info, ConstTableRef root_table) { if (info.schema_changed) set_table(root_table); // First check if any of the tables accessible from the root table were // actually modified. This can be false if there were only insertions, or // deletions which were not linked to by any row in the linking table auto table_modified = [&](auto& tbl) { auto it = info.tables.find(tbl.table_key.value); return it != info.tables.end() && !it->second.modifications_empty(); }; if (!any_of(begin(m_related_tables), end(m_related_tables), table_modified)) { return [](ObjectChangeSet::ObjectKeyType) { return false; }; } if (m_related_tables.size() == 1) { auto& object_set = info.tables.find(m_related_tables[0].table_key.value)->second; return [&](ObjectChangeSet::ObjectKeyType object_key) { return object_set.modifications_contains(object_key); }; } return DeepChangeChecker(info, *root_table, m_related_tables); } void DeepChangeChecker::find_related_tables(std::vector<RelatedTable>& out, Table const& table) { auto table_key = table.get_key(); if (any_of(begin(out), end(out), [=](auto& tbl) { return tbl.table_key == table_key; })) return; // We need to add this table to `out` before recurring so that the check // above works, but we can't store a pointer to the thing being populated // because the recursive calls may resize `out`, so instead look it up by // index every time size_t out_index = out.size(); out.push_back({table_key, {}}); for (auto col_key : table.get_column_keys()) { auto type = table.get_column_type(col_key); if (type == type_Link || type == type_LinkList) { out[out_index].links.push_back({col_key.value, type == type_LinkList}); find_related_tables(out, *table.get_link_target(col_key)); } } } DeepChangeChecker::DeepChangeChecker(TransactionChangeInfo const& info, Table const& root_table, std::vector<RelatedTable> const& related_tables) : m_info(info) , m_root_table(root_table) , m_root_table_key(root_table.get_key().value) , m_root_object_changes([&] { auto it = info.tables.find(m_root_table_key.value); return it != info.tables.end() ? &it->second : nullptr; }()) , m_related_tables(related_tables) { } bool DeepChangeChecker::check_outgoing_links(TableKey table_key, Table const& table, int64_t obj_key, size_t depth) { auto it = find_if(begin(m_related_tables), end(m_related_tables), [&](auto&& tbl) { return tbl.table_key == table_key; }); if (it == m_related_tables.end()) return false; if (it->links.empty()) return false; // Check if we're already checking if the destination of the link is // modified, and if not add it to the stack auto already_checking = [&](int64_t col) { auto end = m_current_path.begin() + depth; auto match = std::find_if(m_current_path.begin(), end, [&](auto& p) { return p.obj_key == obj_key && p.col_key == col; }); if (match != end) { for (; match < end; ++match) match->depth_exceeded = true; return true; } m_current_path[depth] = {obj_key, col, false}; return false; }; const Obj obj = table.get_object(ObjKey(obj_key)); auto linked_object_changed = [&](OutgoingLink const& link) { if (already_checking(link.col_key)) return false; if (!link.is_list) { if (obj.is_null(ColKey(link.col_key))) return false; auto dst = obj.get<ObjKey>(ColKey(link.col_key)).value; return check_row(*table.get_link_target(ColKey(link.col_key)), dst, depth + 1); } auto& target = *table.get_link_target(ColKey(link.col_key)); auto lvr = obj.get_linklist(ColKey(link.col_key)); return std::any_of(lvr.begin(), lvr.end(), [&, this](auto key) { return this->check_row(target, key.value, depth + 1); }); }; return std::any_of(begin(it->links), end(it->links), linked_object_changed); } bool DeepChangeChecker::check_row(Table const& table, ObjKeyType key, size_t depth) { // Arbitrary upper limit on the maximum depth to search if (depth >= m_current_path.size()) { // Don't mark any of the intermediate rows checked along the path as // not modified, as a search starting from them might hit a modification for (size_t i = 0; i < m_current_path.size(); ++i) m_current_path[i].depth_exceeded = true; return false; } TableKey table_key = table.get_key(); if (depth > 0) { auto it = m_info.tables.find(table_key.value); if (it != m_info.tables.end() && it->second.modifications_contains(key)) return true; } auto& not_modified = m_not_modified[table_key.value]; auto it = not_modified.find(key); if (it != not_modified.end()) return false; bool ret = check_outgoing_links(table_key, table, key, depth); if (!ret && (depth == 0 || !m_current_path[depth - 1].depth_exceeded)) not_modified.insert(key); return ret; } bool DeepChangeChecker::operator()(ObjKeyType key) { if (m_root_object_changes && m_root_object_changes->modifications_contains(key)) return true; return check_row(m_root_table, key, 0); } CollectionNotifier::CollectionNotifier(std::shared_ptr<Realm> realm) : m_realm(std::move(realm)) , m_sg_version(Realm::Internal::get_transaction(*m_realm).get_version_of_current_transaction()) { } CollectionNotifier::~CollectionNotifier() { // Need to do this explicitly to ensure m_realm is destroyed with the mutex // held to avoid potential double-deletion unregister(); } void CollectionNotifier::release_data() noexcept { m_sg = nullptr; } uint64_t CollectionNotifier::add_callback(CollectionChangeCallback callback) { m_realm->verify_thread(); util::CheckedLockGuard lock(m_callback_mutex); auto token = m_next_token++; m_callbacks.push_back({std::move(callback), {}, {}, token, false, false}); if (m_callback_index == npos) { // Don't need to wake up if we're already sending notifications Realm::Internal::get_coordinator(*m_realm).wake_up_notifier_worker(); m_have_callbacks = true; } return token; } void CollectionNotifier::remove_callback(uint64_t token) { // the callback needs to be destroyed after releasing the lock as destroying // it could cause user code to be called Callback old; { util::CheckedLockGuard lock(m_callback_mutex); auto it = find_callback(token); if (it == end(m_callbacks)) { return; } size_t idx = distance(begin(m_callbacks), it); if (m_callback_index != npos) { if (m_callback_index >= idx) --m_callback_index; } --m_callback_count; old = std::move(*it); m_callbacks.erase(it); m_have_callbacks = !m_callbacks.empty(); } } void CollectionNotifier::suppress_next_notification(uint64_t token) { { std::lock_guard<std::mutex> lock(m_realm_mutex); REALM_ASSERT(m_realm); m_realm->verify_thread(); m_realm->verify_in_write(); } util::CheckedLockGuard lock(m_callback_mutex); auto it = find_callback(token); if (it != end(m_callbacks)) { it->skip_next = true; } } std::vector<CollectionNotifier::Callback>::iterator CollectionNotifier::find_callback(uint64_t token) { REALM_ASSERT(m_error || m_callbacks.size() > 0); auto it = find_if(begin(m_callbacks), end(m_callbacks), [=](const auto& c) { return c.token == token; }); // We should only fail to find the callback if it was removed due to an error REALM_ASSERT(m_error || it != end(m_callbacks)); return it; } void CollectionNotifier::unregister() noexcept { std::lock_guard<std::mutex> lock(m_realm_mutex); m_realm = nullptr; } bool CollectionNotifier::is_alive() const noexcept { std::lock_guard<std::mutex> lock(m_realm_mutex); return m_realm != nullptr; } std::unique_lock<std::mutex> CollectionNotifier::lock_target() { return std::unique_lock<std::mutex>{m_realm_mutex}; } void CollectionNotifier::set_table(ConstTableRef table) { m_related_tables.clear(); DeepChangeChecker::find_related_tables(m_related_tables, *table); } void CollectionNotifier::add_required_change_info(TransactionChangeInfo& info) { if (!do_add_required_change_info(info) || m_related_tables.empty()) { return; } info.tables.reserve(m_related_tables.size()); for (auto& tbl : m_related_tables) info.tables[tbl.table_key.value]; } void CollectionNotifier::prepare_handover() { REALM_ASSERT(m_sg); m_sg_version = m_sg->get_version_of_current_transaction(); do_prepare_handover(*m_sg); add_changes(std::move(m_change)); REALM_ASSERT(m_change.empty()); m_has_run = true; #ifdef REALM_DEBUG util::CheckedLockGuard lock(m_callback_mutex); for (auto& callback : m_callbacks) REALM_ASSERT(!callback.skip_next); #endif } void CollectionNotifier::before_advance() { for_each_callback([&](auto& lock, auto& callback) { if (callback.changes_to_deliver.empty()) { return; } auto changes = callback.changes_to_deliver; // acquire a local reference to the callback so that removing the // callback from within it can't result in a dangling pointer auto cb = callback.fn; lock.unlock_unchecked(); cb.before(changes); }); } void CollectionNotifier::after_advance() { for_each_callback([&](auto& lock, auto& callback) { if (callback.initial_delivered && callback.changes_to_deliver.empty()) { return; } callback.initial_delivered = true; auto changes = std::move(callback.changes_to_deliver); // acquire a local reference to the callback so that removing the // callback from within it can't result in a dangling pointer auto cb = callback.fn; lock.unlock_unchecked(); cb.after(changes); }); } void CollectionNotifier::deliver_error(std::exception_ptr error) { // Don't complain about double-unregistering callbacks m_error = true; m_callback_count = m_callbacks.size(); for_each_callback([this, &error](auto& lock, auto& callback) { // acquire a local reference to the callback so that removing the // callback from within it can't result in a dangling pointer auto cb = std::move(callback.fn); auto token = callback.token; lock.unlock_unchecked(); cb.error(error); // We never want to call the callback again after this, so just remove it this->remove_callback(token); }); } bool CollectionNotifier::is_for_realm(Realm& realm) const noexcept { std::lock_guard<std::mutex> lock(m_realm_mutex); return m_realm.get() == &realm; } bool CollectionNotifier::package_for_delivery() { if (!prepare_to_deliver()) return false; util::CheckedLockGuard lock(m_callback_mutex); for (auto& callback : m_callbacks) callback.changes_to_deliver = std::move(callback.accumulated_changes).finalize(); m_callback_count = m_callbacks.size(); return true; } template <typename Fn> void CollectionNotifier::for_each_callback(Fn&& fn) { util::CheckedUniqueLock callback_lock(m_callback_mutex); REALM_ASSERT_DEBUG(m_callback_count <= m_callbacks.size()); for (++m_callback_index; m_callback_index < m_callback_count; ++m_callback_index) { fn(callback_lock, m_callbacks[m_callback_index]); if (!callback_lock.owns_lock()) callback_lock.lock_unchecked(); } m_callback_index = npos; } void CollectionNotifier::attach_to(std::shared_ptr<Transaction> sg) { do_attach_to(*sg); m_sg = std::move(sg); } Transaction& CollectionNotifier::source_shared_group() { return Realm::Internal::get_transaction(*m_realm); } void CollectionNotifier::add_changes(CollectionChangeBuilder change) { util::CheckedLockGuard lock(m_callback_mutex); for (auto& callback : m_callbacks) { if (callback.skip_next) { REALM_ASSERT_DEBUG(callback.accumulated_changes.empty()); callback.skip_next = false; } else { if (&callback == &m_callbacks.back()) callback.accumulated_changes.merge(std::move(change)); else callback.accumulated_changes.merge(CollectionChangeBuilder(change)); } } } NotifierPackage::NotifierPackage(std::exception_ptr error, std::vector<std::shared_ptr<CollectionNotifier>> notifiers, RealmCoordinator* coordinator) : m_notifiers(std::move(notifiers)) , m_coordinator(coordinator) , m_error(std::move(error)) { } // Clang TSE seems to not like returning a unique_lock from a function void NotifierPackage::package_and_wait(util::Optional<VersionID::version_type> target_version) NO_THREAD_SAFETY_ANALYSIS { if (!m_coordinator || m_error || !*this) return; auto lock = m_coordinator->wait_for_notifiers([&] { if (!target_version) return true; return std::all_of(begin(m_notifiers), end(m_notifiers), [&](auto const& n) { return !n->have_callbacks() || (n->has_run() && n->version().version >= *target_version); }); }); // Package the notifiers for delivery and remove any which don't have anything to deliver auto package = [&](auto& notifier) { if (notifier->has_run() && notifier->package_for_delivery()) { m_version = notifier->version(); return false; } return true; }; m_notifiers.erase(std::remove_if(begin(m_notifiers), end(m_notifiers), package), end(m_notifiers)); if (m_version && target_version && m_version->version < *target_version) { m_notifiers.clear(); m_version = util::none; } REALM_ASSERT(m_version || m_notifiers.empty()); m_coordinator = nullptr; } void NotifierPackage::before_advance() { if (m_error) return; for (auto& notifier : m_notifiers) notifier->before_advance(); } void NotifierPackage::after_advance() { if (m_error) { for (auto& notifier : m_notifiers) notifier->deliver_error(m_error); return; } for (auto& notifier : m_notifiers) notifier->after_advance(); } void NotifierPackage::add_notifier(std::shared_ptr<CollectionNotifier> notifier) { m_notifiers.push_back(notifier); m_coordinator->register_notifier(notifier); }
32.693517
118
0.654708
DominicFrei
ed499b15101ba2b1a5abf2be1ade7941a8dee122
194
hpp
C++
src/util/mediancut.hpp
TricksterGuy/PicrossPuzzleExporter
ceda25561906b8f78163bb43775b1be87e905ed3
[ "MIT" ]
8
2018-10-29T15:55:59.000Z
2021-11-26T07:20:35.000Z
src/util/mediancut.hpp
TricksterGuy/PicrossPuzzleExporter
ceda25561906b8f78163bb43775b1be87e905ed3
[ "MIT" ]
6
2020-06-02T04:11:39.000Z
2020-07-20T07:48:19.000Z
src/util/mediancut.hpp
TricksterGuy/PicrossPuzzleExporter
ceda25561906b8f78163bb43775b1be87e905ed3
[ "MIT" ]
1
2020-03-16T18:19:15.000Z
2020-03-16T18:19:15.000Z
#ifndef MEDIAN_CUT_HPP #define MEDIAN_CUT_HPP #include "color.hpp" #include "reductionhelper.hpp" void GetPalette(const Image16Bpp& image, unsigned int num_colors, Palette& palette); #endif
17.636364
84
0.793814
TricksterGuy
ed4d914cf55659b7649564e5342bc4221b8d5d67
1,212
cpp
C++
src/Node.cpp
blinknet/bolt-simulation
f3718c345ee037ad3b69a0772f55177973e7ff8c
[ "Unlicense" ]
3
2018-02-18T18:28:38.000Z
2018-08-22T22:07:40.000Z
src/Node.cpp
blinknet/bolt-simulation
f3718c345ee037ad3b69a0772f55177973e7ff8c
[ "Unlicense" ]
null
null
null
src/Node.cpp
blinknet/bolt-simulation
f3718c345ee037ad3b69a0772f55177973e7ff8c
[ "Unlicense" ]
null
null
null
#include "Node.hpp" #include "Globals.hpp" #include "Utils.hpp" #include "third_party/cpp-base/src/cppbase/Random.hpp" Node::Node() { this->init(0); } Node::Node(int index) { this->init(index); } void Node::init(int index) { const auto city = RandomCity(); this->longitude = DegToRad(city.second.first); this->latitude = DegToRad(city.second.second); this->setCorrupt(corruptionChance); this->index = index; } void Node::reset(const double &corruptionChance) { const auto city = RandomCity(); this->longitude = DegToRad(city.second.first); this->latitude = DegToRad(city.second.second); this->setCorrupt(corruptionChance); } bool Node::isCorrupt() const { return this->corrupt; } void Node::setCorrupt(const double &chance) { this->corrupt = (base::RandFloat64() < chance); } double Node::sphereDistance(const Node &other) const { return acos(sin(longitude) * sin(other.longitude) + cos(longitude) * cos(other.longitude) * cos(fabs(latitude - other.latitude))); } double Node::broadcastDuration(const Node &other) const { const double dist = this->sphereDistance(other); return (computingTime + latency * dist) * LatencyDistribution(); }
25.787234
134
0.691419
blinknet
ed4ec6cff2e60e81fc06327f96affc1c98963cb0
3,803
cpp
C++
samples/snippets/cpp/VS_Snippets_Remoting/SoapBodyBinding_Parts/CPP/soapbodybinding_parts.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
421
2018-04-01T01:57:50.000Z
2022-03-28T15:24:42.000Z
samples/snippets/cpp/VS_Snippets_Remoting/SoapBodyBinding_Parts/CPP/soapbodybinding_parts.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
5,797
2018-04-02T21:12:23.000Z
2022-03-31T23:54:38.000Z
samples/snippets/cpp/VS_Snippets_Remoting/SoapBodyBinding_Parts/CPP/soapbodybinding_parts.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
1,482
2018-03-31T11:26:20.000Z
2022-03-30T22:36:45.000Z
// System.Web.Services.Description.SoapBinding.Namespace // System.Web.Services.Description.SoapBodyBinding.Parts /* The following example demonstrates the 'Namespace' field of 'SoapBinding' class and 'parts' property of 'SoapBodyBinding' class. It takes a wsdl file which supports two protocols 'HttpGet' and 'HttpPost' as input. By using the 'Read' method of 'ServiceDescription' class it gets the 'ServiceDescription' object. It uses the SOAP protocol related classes to create 'Binding' elements of 'SOAP' protocol. It adds all the elements to the 'ServiceDescription' object. The 'ServiceDescription' object creates another wsdl file which supports 'SOAP' protocol also. This wsdl file is used to generate a proxy which is used by the .aspx file. */ #using <System.Xml.dll> #using <System.Web.Services.dll> #using <System.dll> using namespace System; using namespace System::Web::Services::Description; using namespace System::Collections; using namespace System::Xml; int main() { ServiceDescription^ myDescription = ServiceDescription::Read( "AddNumbersInput_cs.wsdl" ); // Create a 'Binding' object for the 'SOAP' protocol. Binding^ myBinding = gcnew Binding; myBinding->Name = "Service1Soap"; XmlQualifiedName^ qualifiedName = gcnew XmlQualifiedName( "s0:Service1Soap" ); myBinding->Type = qualifiedName; // <Snippet1> SoapBinding^ mySoapBinding = gcnew SoapBinding; mySoapBinding->Transport = "http://schemas.xmlsoap.org/soap/http"; mySoapBinding->Style = SoapBindingStyle::Document; // Get the URI for XML namespace of the SoapBinding class. String^ myNameSpace = SoapBinding::Namespace; Console::WriteLine( "The URI of the XML Namespace is :{0}", myNameSpace ); // </Snippet1> // Add the 'SoapBinding' object to the 'Binding' object. myBinding->Extensions->Add( mySoapBinding ); // Create the 'OperationBinding' object for the 'SOAP' protocol. OperationBinding^ myOperationBinding = gcnew OperationBinding; myOperationBinding->Name = "AddNumbers"; // Create the 'SoapOperationBinding' object for the 'SOAP' protocol. SoapOperationBinding^ mySoapOperationBinding = gcnew SoapOperationBinding; mySoapOperationBinding->SoapAction = "http://tempuri.org/AddNumbers"; mySoapOperationBinding->Style = SoapBindingStyle::Document; // Add the 'SoapOperationBinding' object to 'OperationBinding' object. myOperationBinding->Extensions->Add( mySoapOperationBinding ); // <Snippet2> // Create the 'InputBinding' object for the 'SOAP' protocol. InputBinding^ myInput = gcnew InputBinding; SoapBodyBinding^ mySoapBinding1 = gcnew SoapBodyBinding; mySoapBinding1->Use = SoapBindingUse::Literal; array<String^>^ myParts = gcnew array<String^>(1); myParts[ 0 ] = "parameters"; // Set the names of the message parts to appear in the SOAP body. mySoapBinding1->Parts = myParts; myInput->Extensions->Add( mySoapBinding1 ); // Add the 'InputBinding' object to 'OperationBinding' object. myOperationBinding->Input = myInput; // Create the 'OutputBinding' object'. OutputBinding^ myOutput = gcnew OutputBinding; myOutput->Extensions->Add( mySoapBinding1 ); // Add the 'OutPutBinding' to 'OperationBinding'. myOperationBinding->Output = myOutput; // </Snippet2> // Add the 'OperationBinding' to 'Binding'. myBinding->Operations->Add( myOperationBinding ); // Add the 'Binding' to 'BindingCollection' of 'ServiceDescription'. myDescription->Bindings->Add( myBinding ); // Write the 'ServiceDescription' as a WSDL file. myDescription->Write( "AddNumbersOut_cs.wsdl" ); Console::WriteLine( " 'AddNumbersOut_cs.Wsdl' file was generated" ); }
42.255556
88
0.722062
hamarb123
ed51bdba18e0deca9058c03a1eb20b78462331d0
1,690
hpp
C++
src/tests/generator.hpp
bosley/vtitan
b56d715637f72792ae70ab5b28009d129c00ff71
[ "MIT" ]
null
null
null
src/tests/generator.hpp
bosley/vtitan
b56d715637f72792ae70ab5b28009d129c00ff71
[ "MIT" ]
null
null
null
src/tests/generator.hpp
bosley/vtitan
b56d715637f72792ae70ab5b28009d129c00ff71
[ "MIT" ]
null
null
null
#ifndef GENERATOR_TESTS_HPP #define GENERATOR_TESTS_HPP #include "lang/instructions.hpp" #include <random> #include <string> namespace gen { template<typename T> class GenerateRandom { public: explicit GenerateRandom() : eng(rd()) { } T get_range(T min, T max) { std::uniform_int_distribution<T> dist(min, max); return dist(eng); } private: std::random_device rd; std::default_random_engine eng; }; template<class T> class RandomEntry { public: explicit RandomEntry(std::vector<T> values) : _values(values) { } T get_value() { GenerateRandom<int64_t> r; auto idx = r.get_range(0, _values.size()-1); return _values[idx]; } private: std::vector<T> _values; }; static titan::instructions::variable* random_built_in_variable(const std::string& name) { GenerateRandom<uint64_t> g; uint64_t depth = g.get_range(0, 10); uint64_t num_segments = g.get_range(0, 5); std::vector<uint64_t> segments; for(auto i = 0; i < num_segments; i++) { segments.push_back(g.get_range(1, 5)); } RandomEntry<titan::instructions::variable_types> vt_entry({ titan::instructions::variable_types::U8, titan::instructions::variable_types::U16, titan::instructions::variable_types::U32, titan::instructions::variable_types::U64, titan::instructions::variable_types::I8, titan::instructions::variable_types::I16, titan::instructions::variable_types::I32, titan::instructions::variable_types::I64, titan::instructions::variable_types::FLOAT, }); return new titan::instructions::built_in_variable( name, vt_entry.get_value(), depth, segments); } } #endif
21.666667
69
0.685799
bosley
ed549ce1d9c62882bd5787c6ef3fefd1841a56ad
9,350
hpp
C++
include/upcore/up/prolog/msvc.hpp
upcaste/upcaste
8174a2f40e7fde022806f8d1565bb4a415ecb210
[ "MIT" ]
1
2018-09-17T20:50:14.000Z
2018-09-17T20:50:14.000Z
include/upcore/up/prolog/msvc.hpp
jwtowner/upcaste
8174a2f40e7fde022806f8d1565bb4a415ecb210
[ "MIT" ]
null
null
null
include/upcore/up/prolog/msvc.hpp
jwtowner/upcaste
8174a2f40e7fde022806f8d1565bb4a415ecb210
[ "MIT" ]
null
null
null
// // Upcaste Performance Libraries // Copyright (C) 2012-2013 Jesse W. Towner // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // #ifndef UP_PROLOG_MSVC_HPP #define UP_PROLOG_MSVC_HPP // // versions check // #if (_MSC_VER < 1400) # error "MSVC++ versions prior to MSVC++ 2008 are not supported." #elif (_MSC_VER > 1700) # error "Unknown MSVC++ compiler version" #endif #define UP_COMPILER UP_COMPILER_MSVC // // ignored warnings // #if (_MSC_VER <= 1700) # pragma warning(disable:4231) // nonstandard extension used : 'extern' before template explicit instantiation # pragma warning(disable:4530) // C++ exception handler used, but unwind semantics are not enabled. Specify /EHsc #endif // // dependencies // #include <intrin.h> // // C++11 feature detection // #if (_MSC_VER < 1700) # define UP_NO_RANGE_BASED_FOR # define UP_NO_FORWARD_DECLARED_ENUMS # define UP_NO_SCOPED_ENUMS #endif #if (_MSC_VER < 1600) # define UP_NO_AUTO_DECLARATIONS # define UP_NO_AUTO_MULTIDECLARATIONS # define UP_NO_DECLTYPE # define UP_NO_LAMBDAS # define UP_NO_NULLPTR # define UP_NO_RVALUE_REFERENCES # define UP_NO_STATIC_ASSERT #endif #define UP_NO_ALIGNAS #define UP_NO_ALIGNOF #define UP_NO_CONSTEXPR #define UP_NO_DEFAULTED_FUNCTIONS #define UP_NO_DELEGATING_CONSTRUCTORS #define UP_NO_DELETED_FUNCTIONS #define UP_NO_EXPLICIT_CONVERSION_OPERATORS #define UP_NO_SPECIALIZED_EXTERN_TEMPLATES #define UP_NO_FUNCTION_TEMPLATE_DEFAULT_ARGS #define UP_NO_INCONSISTENT_EXPLICIT_INSTANTIATIONS #define UP_NO_INHERITING_CONSTRUCTORS #define UP_NO_INITIALIZER_LISTS #define UP_NO_NATIVE_CHAR16_T #define UP_NO_NATIVE_CHAR32_T #define UP_NO_NOEXCEPT #define UP_NO_NOEXCEPT_FUNCTION_PTR #define UP_NO_RAW_LITERALS #define UP_NO_REFERENCE_QUALIFIED_FUNCTIONS #define UP_NO_SFINAE_EXPR #define UP_NO_TEMPLATE_ALIASES #define UP_NO_THREAD_LOCAL #define UP_NO_UNICODE_LITERALS #define UP_NO_VARIADIC_TEMPLATES #ifdef UP_NO_ALIGNAS # define alignas(expression) __declspec(align(expression)) #endif #ifdef UP_NO_ALIGNOF # define alignof __alignof #endif #ifdef UP_NO_CONSTEXPR # define constexpr const #endif #ifdef UP_NO_NOEXCEPT # define noexcept #endif #ifdef UP_NO_THREAD_LOCAL # define thread_local __declspec(thread) #endif // // C++98 feature detection // #ifndef _CPPUNWIND # define UP_NO_EXCEPTIONS #endif #ifndef _CPPRTTI # define UP_NO_RTTI #endif #ifndef _NATIVE_WCHAR_T_DEFINED # define UP_NO_NATIVE_WCHAR_T #endif // // library feature detection // #if _MSC_VER >= 1600 # define UP_HAS_MSVC_XTHREADS # define UP_HAS_MSVC_XTIME #endif #if _MSC_VER >= 1700 # define UP_HAS_STDCXX_ATOMIC # define UP_HAS_STDCXX_TYPE_TRAITS #endif #undef UP_HAS_STDC_FENV #undef UP_HAS_STDC_INTTYPES #define UP_HAS_STDC_LOCALE #undef UP_HAS_STDC_MATH_C99 #undef UP_HAS_STDC_THREADS #define UP_HAS_STDC_TIME #undef UP_HAS_STDC_UCHAR #define UP_HAS_STDC_WCHAR #define UP_HAS_STDC_ALLOCA #undef UP_HAS_STDC_ALIGNED_ALLOC #undef UP_HAS_STDC_MAX_ALIGN #undef UP_HAS_STDC_SNPRINTF #undef UP_HAS_STDC_STRTOF #undef UP_HAS_STDC_STRTOD #undef UP_HAS_STDC_STRTOLD #undef UP_HAS_STDC_STRTOLL #undef UP_HAS_STDC_STRTOULL #undef UP_HAS_STDC_QUICK_EXIT #undef UP_HAS_STDC_TIMESPEC_GET #undef UP_HAS_STDC_UNSAFE_EXIT #undef UP_HAS_STDC_WCSTOF #undef UP_HAS_STDC_WCSTOD #undef UP_HAS_STDC_WCSTOLD #undef UP_HAS_STDC_WCSTOLL #undef UP_HAS_STDC_WCSTOULL #undef UP_HAS_STDC_VFSCANF #undef UP_HAS_STDC_VSCANF #define UP_HAS_STDC_VSNPRINTF #undef UP_HAS_STDC_VSSCANF #undef UP_HAS_POSIX_THREADS #undef UP_HAS_POSIX_PTHREAD_MUTEX_TIMEDLOCK #undef UP_HAS_POSIX_PTHREAD_MUTEX_ADAPTIVE_NP #undef UP_HAS_POSIX_PTHREAD_MUTEX_ERRORCHECK #undef UP_HAS_POSIX_PTHREAD_MUTEX_TIMED_NP #undef UP_HAS_POSIX_ASPRINTF #undef UP_HAS_POSIX_VASPRINTF #define UP_HAS_POSIX_FSEEKO #define UP_HAS_POSIX_FTELLO #undef UP_HAS_POSIX_GETDELIM #undef UP_HAS_POSIX_GETLINE #undef UP_HAS_POSIX_GETWDELIM #undef UP_HAS_POSIX_GETWLINE #define UP_HAS_POSIX_LOCALE #undef UP_HAS_POSIX_MEMALIGN #undef UP_HAS_POSIX_MEMSTREAM #define UP_HAS_POSIX_MEMCCPY #undef UP_HAS_POSIX_WMEMCCPY #undef UP_HAS_POSIX_STPCPY #undef UP_HAS_POSIX_STPNCPY #define UP_HAS_POSIX_STRCASECMP #define UP_HAS_POSIX_STRNCASECMP #define UP_HAS_POSIX_STRDUP #define UP_HAS_POSIX_STRNLEN #define UP_HAS_POSIX_STRTOK_R #undef UP_HAS_POSIX_MBSNRTOWCS #undef UP_HAS_POSIX_WCSNRTOMBS #undef UP_HAS_POSIX_WCPCPY #undef UP_HAS_POSIX_WCPNCPY #define UP_HAS_POSIX_WCSCASECMP #define UP_HAS_POSIX_WCSNCASECMP #define UP_HAS_POSIX_WCSDUP #define UP_HAS_POSIX_WCSNLEN #undef UP_HAS_GNU_MEMPCPY #undef UP_HAS_GNU_WMEMPCPY #undef UP_HAS_GNU_STRNDUP #undef UP_HAS_GNU_WCSNDUP #undef UP_HAS_BSD_MEMSET_PATTERN // // compiler type-traits // #if (_MSC_VER >= 1400) # define UP_TT_IS_TRIVIALLY_DEFAULT_CONSTRUCTIBLE(T) __has_trivial_constructor(T) # define UP_TT_IS_TRIVIALLY_COPY_CONSTRUCTIBLE(T) __has_trivial_copy(T) # define UP_TT_IS_TRIVIALLY_COPY_ASSIGNABLE(T) __has_trivial_assign(T) # define UP_TT_IS_TRIVIALLY_MOVE_CONSTRUCTIBLE(T) __has_trivial_copy(T) # define UP_TT_IS_TRIVIALLY_MOVE_ASSIGNABLE(T) __has_trivial_assign(T) # define UP_TT_IS_TRIVIALLY_DESTRUCTIBLE(T) __has_trivial_destructor(T) # define UP_TT_IS_NOTHROW_DEFAULT_CONSTRUCTIBLE(T) __has_nothrow_constructor(T) # define UP_TT_IS_NOTHROW_COPY_CONSTRUCTIBLE(T) __has_nothrow_copy(T) # define UP_TT_IS_NOTHROW_COPY_ASSIGNABLE(T) __has_nothrow_assign(T) # define UP_TT_IS_NOTHROW_MOVE_CONSTRUCTIBLE(T) __has_nothrow_copy(T) # define UP_TT_IS_NOTHROW_MOVE_ASSIGNABLE(T) __has_nothrow_assign(T) # define UP_TT_HAS_VIRTUAL_DESTRUCTOR(T) __has_virtual_destructor(T) # define UP_TT_IS_ABSTRACT(T) __is_abstract(T) # define UP_TT_IS_BASE_OF(T,U) __is_base_of(T,U) # define UP_TT_IS_CLASS(T) __is_class(T) # define UP_TT_IS_CONVERTIBLE_TO(T, U) __is_convertible_to(T, U) # define UP_TT_IS_EMPTY(T) __is_empty(T) # define UP_TT_IS_ENUM(T) __is_enum(T) # define UP_TT_IS_POD(T) __is_pod(T) # define UP_TT_IS_POLYMORPHIC(T) __is_polymorphic(T) # define UP_TT_IS_UNION(T) __is_union(T) #endif // // compiler language pragmas // #define UP_DETAIL_STDC_FENV_ACCESS_ON \ __pragma(float_control(push)) \ __pragma(float_control(precise, on)) \ __pragma(float_control(except, on)) \ __pragma(fenv_access(on)) #define UP_DETAIL_STDC_FENV_ACCESS_OFF \ __pragma(fenv_access(off)) \ __pragma(float_control(pop)) #define UP_STDC_FENV_ACCESS(arg) \ UP_DETAIL_STDC_FENV_ACCESS_##arg #define UP_DETAIL_STDC_FP_CONTRACT_ON \ __pragma(fp_contract(on)) #define UP_DETAIL_STDC_FP_CONTRACT_OFF \ __pragma(fp_contract(off)) #define UP_STDC_FP_CONTRACT(arg) \ UP_DETAIL_STDC_FP_CONTRACT_##arg // // compiler built-ins // #define UPABORT __debugbreak #define UPASSUME(expr) __assume(expr) #define UPLIKELY(expr) (expr) #define UPUNLIKELY(expr) (expr) #define UPPREFETCH(address, rw, locality) _mm_prefetch((address), (locality)) #define UPIGNORE(expr) ((void)(expr)) // // function and parameter attributes // #define UPALLOC __declspec(restrict) #define UPCOLD #define UPDEPRECATED(msg) __declspec(deprecated(msg)) #define UPALWAYSINLINE __forceinline #define UPHIDDENINLINE #define UPHOT #define UPNOINLINE __declspec(noinline) #define UPNONNULLALL #define UPNONNULL(...) #define UPNORETURN __declspec(noreturn) #define UPPRINTF(format, args) #define UPPURE __declspec(noalias) #define UPRESTRICT __restrict #define UPSCANF(format, args) #define UPUSED #define UPWARNRESULT #ifndef UP_NO_NOEXCEPT # define UPEXCEPTNOTHROW noexcept #else # define UPEXCEPTNOTHROW throw() #endif // // calling conventions // #define UPCDECL __cdecl #define UPFASTCALL __fastcall #define UPSTDCALL __stdcall #define UPTHISCALL __thiscall // // shared/static library visibility // #define UPEXPORT __declspec(dllexport) #define UPIMPORT __declspec(dllimport) #define UPVISIBLE #define UPHIDDEN #define UPEXPORTEXTERN #define UPIMPORTEXTERN extern #define UPEXPORTEXCEPT #define UPIMPORTEXCEPT #endif
30.064309
116
0.782032
upcaste
ed555addbc226b9a09e15691e32b9a5004dcdafa
2,416
cpp
C++
src/gui/highlighting/FontPicker.cpp
tomvodi/QTail
2e7acf31664969e6890edede6b60e02b20f33eb2
[ "MIT" ]
1
2017-04-29T12:17:59.000Z
2017-04-29T12:17:59.000Z
src/gui/highlighting/FontPicker.cpp
tomvodi/QTail
2e7acf31664969e6890edede6b60e02b20f33eb2
[ "MIT" ]
25
2016-06-11T17:35:42.000Z
2017-07-19T04:19:08.000Z
src/gui/highlighting/FontPicker.cpp
tomvodi/QTail
2e7acf31664969e6890edede6b60e02b20f33eb2
[ "MIT" ]
null
null
null
/** * @author Thomas Baumann <teebaum@ymail.com> * * @section LICENSE * See LICENSE for more informations. * */ #include "FontPicker.h" #include "ui_FontPicker.h" FontPicker::FontPicker(QWidget *parent) : QFrame(parent), ui(new Ui::FontPicker) { ui->setupUi(this); // Init to default font size QFont font; ui->fontSizeSpinBox->setValue(font.pointSize()); createConnections(); } void FontPicker::createConnections() { connect(ui->fontComboBox, &QFontComboBox::currentFontChanged, [this] { emit currentFontChanged(currentFont()); }); connect(ui->boldButton, &QToolButton::toggled, [this] { emit currentFontChanged(currentFont()); }); connect(ui->italicButton, &QToolButton::toggled, [this] { emit currentFontChanged(currentFont()); }); connect(ui->underlineButton, &QToolButton::toggled, [this] { emit currentFontChanged(currentFont()); }); connect(ui->strikeoutButton, &QToolButton::toggled, [this] { emit currentFontChanged(currentFont()); }); connect(ui->fontSizeSpinBox, static_cast<void (QSpinBox::*)(int)>(&QSpinBox::valueChanged), [this] { emit currentFontChanged(currentFont()); }); } FontPicker::~FontPicker() { delete ui; } QFont FontPicker::currentFont() const { QFont font(ui->fontComboBox->currentFont()); font.setBold(ui->boldButton->isChecked()); font.setItalic(ui->italicButton->isChecked()); font.setUnderline(ui->underlineButton->isChecked()); font.setStrikeOut(ui->strikeoutButton->isChecked()); font.setPointSize(ui->fontSizeSpinBox->value()); return font; } void FontPicker::setCurrentFont(const QFont &font) { ui->fontComboBox->setCurrentFont(font); ui->fontSizeSpinBox->setValue(font.pointSize()); ui->boldButton->setChecked(font.bold()); ui->italicButton->setChecked(font.italic()); ui->underlineButton->setChecked(font.underline()); ui->strikeoutButton->setChecked(font.strikeOut()); emit currentFontChanged(currentFont()); } QFontComboBox::FontFilters FontPicker::fontFilters() const { return ui->fontComboBox->fontFilters(); } void FontPicker::setFontFilters(QFontComboBox::FontFilters fontFilters) { ui->fontComboBox->setFontFilters(fontFilters); } void FontPicker::changeEvent(QEvent *event) { if (event->type() == QEvent::LanguageChange) { ui->retranslateUi(this); } QFrame::changeEvent(event); }
27.770115
94
0.69702
tomvodi
ed596431769819eec4b2b8c8e196ae3587c69cb0
7,739
cpp
C++
src/InputBox.cpp
gmalysa/gui2d
0675d396b3f1e28073b77903026c3c797cd445b9
[ "BSD-3-Clause" ]
null
null
null
src/InputBox.cpp
gmalysa/gui2d
0675d396b3f1e28073b77903026c3c797cd445b9
[ "BSD-3-Clause" ]
null
null
null
src/InputBox.cpp
gmalysa/gui2d
0675d396b3f1e28073b77903026c3c797cd445b9
[ "BSD-3-Clause" ]
null
null
null
/** * @file 2dgui/InputBox.cpp * @todo License/copyright statement */ // Standard headers #include <gl/glew.h> #include <glm/glm.hpp> #include <glm/gtc/type_precision.hpp> #include <glm/gtc/type_ptr.hpp> #include <iostream> #include <string> #include <algorithm> // Project definitions #include "2dgui/gui2d.h" #include "2dgui/iUntexturedQuadRenderable.h" #include "2dgui/Manager.h" #include "2dgui/String.h" #include "2dgui/InputBox.h" #include "input/Manager.h" /** * This constructor initializes all of the resources used to draw this input box. * @param m The Manager that controls this input box * @param f The Font to use to draw the text inside this input box. */ gui2d::InputBox::InputBox(gui2d::Manager* m, gui2d::Font* f) : iUntexturedQuadRenderable(2) { init(); _w = 0.3f; _m = m; _string = m->createString(f->getId(), ""); _string->setZ(_z - 5.0f); setInnerHeight(_string->getHeightf()); _m->showQuads(this); } /** * Initialization routine just sets sane values for everything. Most needs * to be customized by the user eventually. */ void gui2d::InputBox::init(void) { _m = NULL; _string = NULL; _x = _y = _h = _w = 0.0f; _margin[0] = _margin[1] = _margin[2] = _margin[3] = 0.0f; _z = 100; _cursor = 0; _inSelection = false; _selectStart = 0; _activeColor = glm::vec4(1.0); _inactiveColor = glm::vec4(0.5, 0.5, 0.5, 1.0); _visible = true; _active = true; } /** * Destructor simply deallocates our string */ gui2d::InputBox::~InputBox(void) { delete _string; } /** * Set the text for the underlying String, and update our cursor to the end of the string. * @param text The string to assign to the input */ void gui2d::InputBox::setText(const std::string& text) { _string->drawText(text); _cursor = text.length(); _inSelection = false; } /** * Clears the underlying string, done for convenience */ void gui2d::InputBox::clearText(void) { _string->remove(0); _cursor = 0; _inSelection = false; } /** * Set the margin for the input box. Note that this margin applies to all four * edges, when set with this method. * @param margin The value of margin, in normalized units */ void gui2d::InputBox::setMargin(float margin) { _margin[0] = _margin[1] = _margin[2] = _margin[3] = margin; _string->setPosition(_x+margin, _y+margin); } /** * Set the inner height of this input box, that is the height excluding margins * @param h The height to use for the inner area of the input box */ void gui2d::InputBox::setInnerHeight(float h) { _h = h + _margin[MARGIN_BOTTOM] + _margin[MARGIN_TOP]; _string->setPosition(_x + _margin[MARGIN_LEFT], _y + _margin[MARGIN_BOTTOM]); setQuadXY(0, _x, _y, _w, _h); } /** * Changes the background color for the input box * @param color The color to use */ void gui2d::InputBox::setBackgroundColor(const glm::vec4& color) { setQuadColor(0, color); } /** * Set the color used by the underlying string in active mode * @param color The color of active input text */ void gui2d::InputBox::setActiveColor(const glm::vec4& color) { _activeColor = color; if (_active) { _string->setColor(color); } } /** * Set the color, but this time for inactive mode * @param color The color of inactive input text */ void gui2d::InputBox::setInactiveColor(const glm::vec4& color) { _inactiveColor = color; if (!_active) { _string->setColor(color); } } /** * Update our position as well as that of the underlying string. * @param normX The normalized x screen coordinate (-1, 1) * @param normY The normalized y screen coordiante (-1, 1) */ void gui2d::InputBox::setPosition(float normX, float normY) { _string->setPosition(normX + _margin[MARGIN_LEFT], normY + _margin[MARGIN_BOTTOM]); _x = normX; _y = normY; setQuadXY(0, _x, _y, _w, _h); } /** * Update the Z-coordinates for the input box, etc. to make it overlap with text properly * @param z New Z coordinate, in a non-normalized float (i.e. not 0-1). */ void gui2d::InputBox::setZ(float z) { _string->setZ(z - 5.0f); setQuadsZ(static_cast<GLshort>(z)); _z = z; } /** * Set this input box to be active, changing the font color */ void gui2d::InputBox::activate(void) { _active = true; _string->setColor(_activeColor); } /** * Set this input box to be inactive, changing the font color */ void gui2d::InputBox::deactivate(void) { _active = false; _string->setColor(_inactiveColor); } /** * Show this input box; this is independent from being active or not */ void gui2d::InputBox::show(void) { _visible = true; _string->show(); _m->showQuads(this); } /** * Hide this input box, this is independent from being active or not */ void gui2d::InputBox::hide(void) { _visible = false; _string->hide(); _m->hideQuads(this); } /** * Handle an input event from input::KeyEvent by either adding characters or modifying our cursor position * @param e The input::KeyEvent keyboard event that has information about what happened */ void gui2d::InputBox::keyPressed(const input::KeyEvent &e) { std::string str; // If we're not active, why are we receiving events? if (!_active) { return; } // Backspace key deletes characters, as does the delete key if (e.ois.key == OIS::KC_BACK || e.ois.key == OIS::KC_DELETE) { if (_inSelection) { _inSelection = false; if (_cursor < _selectStart) { _string->remove(_cursor, _selectStart - _cursor); } else { _string->remove(_selectStart, _cursor - _selectStart); _cursor = _selectStart; } } else { if (e.ois.key == OIS::KC_BACK && _cursor > 0) { _string->remove(_cursor-1, 1); _cursor -= 1; } else if (e.ois.key == OIS::KC_DELETE) { _string->remove(_cursor, 1); } } } else if (e.ois.key == OIS::KC_LEFT) { if (input::Manager::getSingleton().Keyboard().isKeyDown(OIS::KC_LSHIFT)) { if (!_inSelection) { _selectStart = _cursor; _inSelection = true; } else { if (_selectStart == _cursor-1) { _inSelection = false; } } } else { _inSelection = false; } if (_cursor > 0) { _cursor -= 1; } } else if (e.ois.key == OIS::KC_RIGHT) { if (input::Manager::getSingleton().Keyboard().isKeyDown(OIS::KC_LSHIFT)) { if (!_inSelection) { _selectStart = _cursor; _inSelection = true; } else { if (_selectStart == _cursor+1) { _inSelection = false; } } } else { _inSelection = false; } if (_cursor < _string->length()) { _cursor += 1; } } else if ((e.ois.key >= OIS::KC_1 && e.ois.key <= OIS::KC_EQUALS) || (e.ois.key >= OIS::KC_Q && e.ois.key <= OIS::KC_RBRACKET) || (e.ois.key >= OIS::KC_A && e.ois.key <= OIS::KC_GRAVE) || (e.ois.key >= OIS::KC_BACKSLASH && e.ois.key <= OIS::KC_SLASH)) { // Prepare the insertion string if (e.ois.key == OIS::KC_SPACE) { str = " "; } else { str = std::string(input::Manager::getSingleton().Keyboard().getAsString(e.ois.key)); if (!input::Manager::getSingleton().Keyboard().isKeyDown(OIS::KC_LSHIFT)) { std::transform(str.begin(), str.end(), str.begin(), ::tolower); } } // If there's a selection, delete it because we overwrite in that case if (_inSelection) { _inSelection = false; if (_cursor < _selectStart) { _string->remove(_cursor, _selectStart - _cursor); } else { _string->remove(_selectStart, _cursor - _selectStart); _cursor = _selectStart; } } // Insert the string wherever we end up _string->insert(str, _cursor); _cursor += 1; } }
25.969799
107
0.639747
gmalysa
ed5d6d3c3cf244c475c7329d78f12378088cc01c
1,529
hpp
C++
include/xdb/connection.hpp
malasiot/xdb
c9a74401242e614a8185dee1023a9cbab23596d8
[ "MIT" ]
1
2021-12-30T08:41:18.000Z
2021-12-30T08:41:18.000Z
include/xdb/connection.hpp
malasiot/xdb
c9a74401242e614a8185dee1023a9cbab23596d8
[ "MIT" ]
null
null
null
include/xdb/connection.hpp
malasiot/xdb
c9a74401242e614a8185dee1023a9cbab23596d8
[ "MIT" ]
null
null
null
#ifndef XDB_CONNECTION_HPP #define XDB_CONNECTION_HPP #include <sqlite3.h> #include <string> #include <xdb/query.hpp> #include <xdb/connection_handle.hpp> #include <xdb/transaction.hpp> namespace xdb { class Statement ; class Query ; class Connection { public: Connection(); Connection(const std::string &dsn); Connection(const Connection &other) = delete ; Connection &operator = ( const Connection &other) = delete ; // open connection to database withe given params void open(const std::string &dsn); void close() ; operator int () { return (bool)handle_ ; } uint64_t last_insert_rowid() { return handle_->last_insert_rowid() ; } // sqlite3_int64 last_insert_rowid() { // return sqlite3_last_insert_rowid(handle_); // } // int changes() { // return sqlite3_changes(handle_); // } ConnectionHandlePtr handle() const { return handle_ ; } Statement prepareStatement(const std::string &sql) ; Query prepareQuery(const std::string &sql) ; // helper for creating a connection and binding parameters template<typename ...Args> QueryResult query(const std::string & sql, Args... args) { return Query(*this, sql)(args...) ; } template<typename ...Args> void execute(const std::string &sql, Args... args) { Statement(*this, sql)(args...) ; } Transaction transaction() ; void check() ; protected: std::shared_ptr<ConnectionHandle> handle_ ; }; } // namespace xdb #endif
20.118421
64
0.656638
malasiot
ed5f307a664cd48051b5e75472d38d7fa22d191f
1,206
hh
C++
inc/EProtocolDecoderOutput.hh
developkits/CxxMina
705734fccc5ef87c7faa385b77cd1e67c46c5c75
[ "Apache-2.0" ]
7
2016-08-25T14:22:36.000Z
2020-05-25T17:27:51.000Z
inc/EProtocolDecoderOutput.hh
developkits/CxxMina
705734fccc5ef87c7faa385b77cd1e67c46c5c75
[ "Apache-2.0" ]
1
2018-07-11T12:37:55.000Z
2018-07-12T00:05:33.000Z
inc/EProtocolDecoderOutput.hh
developkits/CxxMina
705734fccc5ef87c7faa385b77cd1e67c46c5c75
[ "Apache-2.0" ]
2
2017-06-09T01:22:36.000Z
2021-09-29T16:27:58.000Z
/* * EProtocolDecoderOutput.hh * * Created on: 2016-5-20 * Author: cxxjava@163.com */ #ifndef EPROTOCOLDECODEROUTPUT_HH_ #define EPROTOCOLDECODEROUTPUT_HH_ #include "./EIoSession.hh" #include "./EIoFilter.hh" namespace efc { namespace eio { /** * Callback for {@link ProtocolDecoder} to generate decoded messages. * {@link ProtocolDecoder} must call {@link #write(Object)} for each decoded * messages. * * @author <a href="http://mina.apache.org">Apache MINA Project</a> */ interface EProtocolDecoderOutput: virtual public EObject { virtual ~EProtocolDecoderOutput(){} /** * Callback for {@link ProtocolDecoder} to generate decoded messages. * {@link ProtocolDecoder} must call {@link #write(Object)} for each * decoded messages. * * @param message the decoded message */ virtual void write(sp<EObject> message) = 0; /** * Flushes all messages you wrote via {@link #write(Object)} to * the next filter. * * @param nextFilter the next Filter * @param session The current Session */ virtual void flush(EIoFilter::NextFilter* nextFilter, sp<EIoSession>& session) = 0; }; } /* namespace eio */ } /* namespace efc */ #endif /* EPROTOCOLDECODEROUTPUT_HH_ */
24.12
84
0.701493
developkits
ed65dadfe60d1c88f05de7463272e97192075e41
258
hpp
C++
include/code_generator/Return.hpp
czhj/code_generator
f56382ae851ead5594a5f8772230eee33ea6e747
[ "MIT" ]
1
2022-02-21T02:06:37.000Z
2022-02-21T02:06:37.000Z
include/code_generator/Return.hpp
czhj/code_generator
f56382ae851ead5594a5f8772230eee33ea6e747
[ "MIT" ]
null
null
null
include/code_generator/Return.hpp
czhj/code_generator
f56382ae851ead5594a5f8772230eee33ea6e747
[ "MIT" ]
null
null
null
/** * @file Return.hpp * @author huangjian * @date 2022-03-08 * @version 1.0 * @copyright huangjian **/ #ifndef RETURNS_HPP #define RETURNS_HPP #include "Evaluate.hpp" #define return_(code) Evaluate::create("return {};", code) #endif // RETURNS_HPP
16.125
58
0.682171
czhj
ed6633969d04a81ef88e93d105227761f540d110
136
cpp
C++
config_tests/member_begin.cpp
queertypes/matrix-n
5b7fe52dc32bed67cd50bb1e664e92892b5d1178
[ "BSD-3-Clause" ]
1
2018-03-08T08:43:04.000Z
2018-03-08T08:43:04.000Z
config_tests/member_begin.cpp
queertypes/matrix-n
5b7fe52dc32bed67cd50bb1e664e92892b5d1178
[ "BSD-3-Clause" ]
null
null
null
config_tests/member_begin.cpp
queertypes/matrix-n
5b7fe52dc32bed67cd50bb1e664e92892b5d1178
[ "BSD-3-Clause" ]
null
null
null
#include <vector> int main() { std::vector<int> x = {1,2,3,4}; for (auto i = std::begin(x), end = std::end(x); i != end; ++i); }
13.6
65
0.507353
queertypes
ed66ffcfeb9da892d07bfd94710c59f8a6908d5b
1,978
hpp
C++
ChaosGLTest/geom_list.hpp
chaosarts/ChaosGL.cpp
7d851a404824609547fb9261790b87cee7699d5c
[ "Apache-2.0" ]
null
null
null
ChaosGLTest/geom_list.hpp
chaosarts/ChaosGL.cpp
7d851a404824609547fb9261790b87cee7699d5c
[ "Apache-2.0" ]
null
null
null
ChaosGLTest/geom_list.hpp
chaosarts/ChaosGL.cpp
7d851a404824609547fb9261790b87cee7699d5c
[ "Apache-2.0" ]
null
null
null
// // geom_list.hpp // ChaosGL // // Created by Fu Lam Diep on 15.04.16. // Copyright © 2016 Fu Lam Diep. All rights reserved. // #ifndef ChaosGLTest_geom_list_hpp #define ChaosGLTest_geom_list_hpp #include <ChaosGL/geom.hpp> #include <glm/glm.hpp> #include <gtest/gtest.h> class geom_list: public virtual testing::Test { public: chaosgl::geom pyramide; void SetUp () { pyramide.addValue(glm::vec3(-1, 0, -1)); pyramide.addValue(glm::vec3(0, 0, 1)); pyramide.addValue(glm::vec3(1, 0, -1)); pyramide.addValue(glm::vec3(-1, 0, -1)); pyramide.addValue(glm::vec3(0, 0, 1)); pyramide.addValue(glm::vec3(0, 1, 0)); pyramide.addValue(glm::vec3(0, 0, 1)); pyramide.addValue(glm::vec3(1, 0, -1)); pyramide.addValue(glm::vec3(0, 1, 0)); pyramide.addValue(glm::vec3(1, 0, -1)); pyramide.addValue(glm::vec3(-1, 0, -1)); pyramide.addValue(glm::vec3(0, 1, 0)); } void TearDown () { } virtual ~geom_list () { } }; TEST_F (geom_list, base) { ASSERT_EQ(12, pyramide.count(GL_ARRAY_BUFFER)); ASSERT_EQ(4, pyramide.count(GL_ELEMENT_ARRAY_BUFFER)); } TEST_F (geom_list, primitve) { ASSERT_EQ(4, pyramide.getTriangleCount()); const std::vector<chaosgl::triangle3> triangles = pyramide.getTriangles(glm::vec3(0, 1, 0)); ASSERT_EQ(3, triangles.size()); ASSERT_EQ(glm::vec3(-1, 0, -1), triangles[0].a); ASSERT_EQ(glm::vec3(0, 0, 1), triangles[0].b); ASSERT_EQ(glm::vec3(0, 1, 0), triangles[0].c); ASSERT_EQ(glm::vec3(0, 0, 1), triangles[1].a); ASSERT_EQ(glm::vec3(1, 0, -1), triangles[1].b); ASSERT_EQ(glm::vec3(0, 1, 0), triangles[1].c); ASSERT_EQ(glm::vec3(1, 0, -1), triangles[2].a); ASSERT_EQ(glm::vec3(-1, 0, -1), triangles[2].b); ASSERT_EQ(glm::vec3(0, 1, 0), triangles[2].c); const chaosgl::triangle3 triangle = pyramide.getTriangle(0); ASSERT_EQ(glm::vec3(-1, 0, -1), triangle.a); ASSERT_EQ(glm::vec3(0, 0, 1), triangle.b); ASSERT_EQ(glm::vec3(1, 0, -1), triangle.c); } #endif /* geom_list_h */
22.735632
93
0.649646
chaosarts
ed69c8f6250c77c9594af1ea0d14b40eb36e6e58
714
cpp
C++
common/src/utils/files.cpp
sathyamvellal/learnopengl
54e9fd6193c6dc970b0802bc31c5b558c46586d5
[ "MIT" ]
null
null
null
common/src/utils/files.cpp
sathyamvellal/learnopengl
54e9fd6193c6dc970b0802bc31c5b558c46586d5
[ "MIT" ]
null
null
null
common/src/utils/files.cpp
sathyamvellal/learnopengl
54e9fd6193c6dc970b0802bc31c5b558c46586d5
[ "MIT" ]
null
null
null
// // Created by Sathyam Vellal on 10/03/2018. // #include <string> #include <fstream> #include <sstream> #include "utils/logger.h" #include "utils/files.h" void extract(std::string& contents, const std::string& filename) { log<LOG_VERBOSE>("Opening file %1% ...") % filename.c_str(); std::ifstream fileInput; fileInput.exceptions (std::ifstream::failbit | std::ifstream::badbit); fileInput.open(filename); log<LOG_VERBOSE>("Reading file to buffer ..."); std::stringstream buffer; buffer << fileInput.rdbuf(); log<LOG_VERBOSE>("Writing buffer to string ..."); contents = buffer.str(); log<LOG_VERBOSE>("Closing file %1% ...") % filename.c_str(); fileInput.close(); }
27.461538
74
0.662465
sathyamvellal
ed6bc00089b69a84ce39c8c1c4a25936880e537e
990
cpp
C++
Source/Utility.cpp
Cos8o/GDCrypto
2d75646475a752e93c8b2a829033e2350ecc862c
[ "MIT" ]
16
2018-08-31T13:16:30.000Z
2021-03-07T15:14:14.000Z
Source/Utility.cpp
cos8oih/GDCrypto
2d75646475a752e93c8b2a829033e2350ecc862c
[ "MIT" ]
8
2020-01-21T15:05:19.000Z
2020-11-11T20:05:34.000Z
Source/Utility.cpp
Cos8o/GDCrypto
2d75646475a752e93c8b2a829033e2350ecc862c
[ "MIT" ]
2
2019-01-12T14:37:40.000Z
2020-01-22T03:34:51.000Z
#include "CAPI.hpp" #include "GDCrypto/Utility.hpp" using namespace gdcrypto; //C Bindings extern "C" { GDCRYPTO_API void gdcrypto_xorWithKey( uint8_t* buffer, size_t const bufferSize, uint8_t const* key, size_t const keySize) { if (buffer && bufferSize && key && keySize) { if (!(keySize == 1 && key[0] == '\0')) { for (auto i = 0u; i < bufferSize; ++i) buffer[i] ^= key[i % keySize]; } } } GDCRYPTO_API uint8_t* gdcrypto_levelSeed( uint8_t* levelString, size_t const levelStringSize, size_t* seedOut) { if (levelString && levelStringSize) { std::string s( reinterpret_cast<char*>(levelString), levelStringSize); if (seedOut) *seedOut = s.size(); return gdcrypto_createBuffer(s.c_str(), s.size()); } return nullptr; } GDCRYPTO_API int32_t gdcrypto_levelscoreSeed( uint32_t const jumps, uint32_t const percentage, uint32_t const seconds) { return levelscoreSeed(jumps, percentage, seconds); } }
18
53
0.663636
Cos8o
ed6f409e90bbc8432089fed02a04a3ab945c90f9
295
cpp
C++
src/editorLib/Objects/EnvironmentObject.cpp
AluminiumRat/mtt
3052f8ad0ffabead05a1033e1d714a61e77d0aa8
[ "MIT" ]
null
null
null
src/editorLib/Objects/EnvironmentObject.cpp
AluminiumRat/mtt
3052f8ad0ffabead05a1033e1d714a61e77d0aa8
[ "MIT" ]
null
null
null
src/editorLib/Objects/EnvironmentObject.cpp
AluminiumRat/mtt
3052f8ad0ffabead05a1033e1d714a61e77d0aa8
[ "MIT" ]
null
null
null
#include <mtt/editorLib/Objects/EnvironmentObject.h> using namespace mtt; EnvironmentObject::EnvironmentObject( const QString& name, bool canBeRenamed, const UID theId) : MovableObject(name, canBeRenamed, theId) { }
29.5
58
0.589831
AluminiumRat
ed6f7447eba8cb7c529c724a084e4b1a5913c1b8
2,867
cpp
C++
GraphLayoutLibrary/HierarchicalLayoutGenerator/ReducedNestingTreeNode.cpp
persistentsystems/LayoutLibrary
e299ac0073225c88f488dd9c2615ec786f8e2897
[ "MIT" ]
26
2016-09-13T08:50:09.000Z
2022-02-14T15:14:54.000Z
GraphLayoutLibrary/HierarchicalLayoutGenerator/ReducedNestingTreeNode.cpp
hotpeperoncino/GraphLayoutLibrary
2dec062f6cdbbaa4b791bdd9c7cc54fe90adbc13
[ "MIT" ]
3
2017-06-21T04:18:58.000Z
2018-01-17T13:27:42.000Z
GraphLayoutLibrary/HierarchicalLayoutGenerator/ReducedNestingTreeNode.cpp
hotpeperoncino/GraphLayoutLibrary
2dec062f6cdbbaa4b791bdd9c7cc54fe90adbc13
[ "MIT" ]
4
2017-12-08T09:08:34.000Z
2021-07-22T06:42:31.000Z
#include "ReducedNestingTreeNode.h" ReducedNestingTreeNode::ReducedNestingTreeNode() { m_layerNode = NULL; m_nestingTreeNode = NULL; m_dAveragePosition = 0.0; } bool ReducedNestingTreeNode::isLayerNode() { return m_constBIsLayerNode; } void ReducedNestingTreeNode::addChildNode(double dAvgPosition, ReducedNestingTreeNode *reducedNestingTreeNodeRef) { m_mapChildrenRNTNodes.insert(dAvgPosition , reducedNestingTreeNodeRef); } void ReducedNestingTreeNode::setLayerNode(LayerNode *layerNode) { LAYOUT_ASSERT(m_nestingTreeNode == NULL && layerNode != NULL, LayoutException(__FUNCTION__ ,LayoutExceptionEnum::REQUIRED_PARAMETER_NOT_SET ,"m_nestingTreeNode and layerNode" ,"ReducedNestingTreeNode")); m_layerNode = layerNode; m_constBIsLayerNode = true; } LayerNode *ReducedNestingTreeNode::getLayerNode() { Q_ASSERT_X(m_layerNode != NULL , "ReducedNestingTree Get LayerNode" , "Layer Node is not set"); return m_layerNode; } void ReducedNestingTreeNode::setNestingTreeNode(NestingTreeSubgraphNode *nestingTreeNode) { LAYOUT_ASSERT(m_layerNode == NULL && nestingTreeNode != NULL, LayoutException(__FUNCTION__ ,LayoutExceptionEnum::REQUIRED_PARAMETER_NOT_SET ,"m_nestingTreeNode and layerNode" ,"ReducedNestingTreeNode")); m_nestingTreeNode = nestingTreeNode; m_constBIsLayerNode = false; } NestingTreeSubgraphNode *ReducedNestingTreeNode::getNestingTreeNode() { LAYOUT_ASSERT(m_nestingTreeNode != NULL , LayoutException(__FUNCTION__ ,LayoutExceptionEnum::REQUIRED_PARAMETER_NOT_SET ,"Nesting Tree Node" ,"ReducedNestingTreeNode")); return m_nestingTreeNode; } double ReducedNestingTreeNode::getAveragePosition() { return m_dAveragePosition; } void ReducedNestingTreeNode::setAveragePosition(double dAveragePosition) { m_dAveragePosition = dAveragePosition; } int ReducedNestingTreeNode::getChildLayerNodeCount() { return m_iLayerNodeCount; } void ReducedNestingTreeNode::setChildLayerNodeCount(int iLayerNodeCount) { LAYOUT_ASSERT(iLayerNodeCount >= 0 , LayoutException(__FUNCTION__ ,LayoutExceptionEnum::INVALID_PARAMETER ,QString::number(iLayerNodeCount) ,"iLayerNodeCount")); m_iLayerNodeCount = iLayerNodeCount; } ReducedNestingTreeNode::IteratorMapAvgPosToChildRNTNode ReducedNestingTreeNode::getChildNodesIterator() { IteratorMapAvgPosToChildRNTNode iterChildNodes(m_mapChildrenRNTNodes); return iterChildNodes; }
28.67
113
0.680851
persistentsystems
ed7381bc5d77b985f38212cbd526b9ad415efacc
4,685
hpp
C++
include/matchers/contain.hpp
toroidal-code/cppspec
189a94a7adb32656089da2ba5d8af2f2f0f67767
[ "MIT" ]
11
2015-06-02T23:45:20.000Z
2018-06-27T12:35:19.000Z
include/matchers/contain.hpp
toroidal-code/cppspec
189a94a7adb32656089da2ba5d8af2f2f0f67767
[ "MIT" ]
7
2016-03-17T04:14:38.000Z
2016-05-02T07:51:10.000Z
include/matchers/contain.hpp
toroidal-code/cppspec
189a94a7adb32656089da2ba5d8af2f2f0f67767
[ "MIT" ]
3
2016-10-20T09:31:46.000Z
2017-12-15T02:36:07.000Z
/** @file */ #ifndef CPPSPEC_MATCHERS_INCLUDE_HPP #define CPPSPEC_MATCHERS_INCLUDE_HPP #include "matcher_base.hpp" namespace CppSpec { namespace Matchers { /** * The abstract base class for the Include matcher. * See template specializations below. */ template <typename A, typename E, typename U> class ContainBase : public MatcherBase<A, E> { A actual; public: virtual std::string description() override; virtual std::string failure_message() override; virtual std::string failure_message_when_negated() override; virtual bool diffable() { return true; } protected: bool actual_collection_includes(U expected_item); ContainBase(Expectation<A> &expectation, std::initializer_list<U> expected) : MatcherBase<A, std::vector<U>>(expectation, std::vector<U>(expected)), actual(this->get_actual()){}; ContainBase(Expectation<A> &expectation, U expected) : MatcherBase<A, U>(expectation, expected), actual(this->get_actual()){}; }; template <typename A, typename E, typename U> std::string ContainBase<A, E, U>::description() { // std::vector<E> described_items; return Pretty::improve_hash_formatting( "contain" + Pretty::to_sentance(this->get_expected())); } template <typename A, typename E, typename U> std::string ContainBase<A, E, U>::failure_message() { return Pretty::improve_hash_formatting(MatcherBase<A, E>::failure_message()); } template <typename A, typename E, typename U> std::string ContainBase<A, E, U>::failure_message_when_negated() { return Pretty::improve_hash_formatting( MatcherBase<A, E>::failure_message_when_negated()); } template <typename A, typename E, typename U> bool ContainBase<A, E, U>::actual_collection_includes(U expected_item) { auto actual = this->get_actual(); auto last = *(actual.begin()); static_assert( Util::verbose_assert<std::is_same<decltype(last), U>>::value, "Expected item is not the same type as what is inside container."); return std::find(actual.begin(), actual.end(), expected_item) != actual.end(); } /** * The template specialization of Include that permits matching * against a list of elements (i.e. expected({1,2,3,4}).to_include({1,4}) ) */ template <typename A, typename E, typename U> class Contain : public ContainBase<A, E, U> { enum class Predicate { any, all, none }; public: bool match() override; bool negated_match() override; Contain(Expectation<A> &expectation, std::initializer_list<U> expected) : ContainBase<A, E, U>(expectation, expected){}; protected: bool perform_match(Predicate predicate, Predicate hash_subset_predicate); }; template <typename A, typename E, typename U> bool Contain<A, E, U>::match() { return perform_match(Predicate::all, Predicate::all); } template <typename A, typename E, typename U> bool Contain<A, E, U>::negated_match() { return perform_match(Predicate::none, Predicate::any); } // TODO: support std::map<E,_> template <typename A, typename E, typename U> bool Contain<A, E, U>::perform_match(Predicate predicate, Predicate /*hash_subset_predicate*/) { bool retval = true; // start off true for (U expected_item : this->get_expected()) { retval = retval && this->actual_collection_includes(expected_item); // Based on our main predicate switch (predicate) { case Predicate::all: if (retval) { // if the collection includes the item, continue; // continue the loop } else { // otherwise return false; // immediately return false } case Predicate::none: if (retval) { // if the collection includes the item return false; // immediately return false } else { // otherwise continue; // continue the loop } case Predicate::any: if (retval) { // if the collection includes the item return true; // immediately return true } else { // otherwise continue; // continue the loop } } } return true; } /** * The template specialization of Include that permits matching * of a single element (i.e. expected({1,2,3,4}).to_include(4) ) */ template <typename A, typename U> class Contain<A, U, U> : public ContainBase<A, U, U> { public: Contain(Expectation<A> &expectation, U expected) : ContainBase<A, U, U>(expectation, expected){}; bool match() override; }; template <typename A, typename U> bool Contain<A, U, U>::match() { return this->actual_collection_includes(this->get_expected()); } } // ::Matchers } // namespace CppSpec #endif // CPPSPEC_MATCHERS_INCLUDE_HPP
32.534722
80
0.674493
toroidal-code
ed753499e2c042c0238241c6654343f0ceeca3ac
18,840
cpp
C++
export/release/windows/obj/src/MusicBeatState.cpp
TheSlithyGamer4evr/Friend-Trouble-Source
a540ec9cf4cf3033e0c340e5e4f50d647b94d4a3
[ "Apache-2.0" ]
null
null
null
export/release/windows/obj/src/MusicBeatState.cpp
TheSlithyGamer4evr/Friend-Trouble-Source
a540ec9cf4cf3033e0c340e5e4f50d647b94d4a3
[ "Apache-2.0" ]
null
null
null
export/release/windows/obj/src/MusicBeatState.cpp
TheSlithyGamer4evr/Friend-Trouble-Source
a540ec9cf4cf3033e0c340e5e4f50d647b94d4a3
[ "Apache-2.0" ]
null
null
null
#include <hxcpp.h> #ifndef INCLUDED_95f339a1d026d52c #define INCLUDED_95f339a1d026d52c #include "hxMath.h" #endif #ifndef INCLUDED_ClientPrefs #include <ClientPrefs.h> #endif #ifndef INCLUDED_Conductor #include <Conductor.h> #endif #ifndef INCLUDED_Controls #include <Controls.h> #endif #ifndef INCLUDED_CustomFadeTransition #include <CustomFadeTransition.h> #endif #ifndef INCLUDED_FlxVideo #include <FlxVideo.h> #endif #ifndef INCLUDED_MusicBeatState #include <MusicBeatState.h> #endif #ifndef INCLUDED_MusicBeatSubstate #include <MusicBeatSubstate.h> #endif #ifndef INCLUDED_PlayerSettings #include <PlayerSettings.h> #endif #ifndef INCLUDED_Type #include <Type.h> #endif #ifndef INCLUDED_flixel_FlxBasic #include <flixel/FlxBasic.h> #endif #ifndef INCLUDED_flixel_FlxG #include <flixel/FlxG.h> #endif #ifndef INCLUDED_flixel_FlxGame #include <flixel/FlxGame.h> #endif #ifndef INCLUDED_flixel_FlxState #include <flixel/FlxState.h> #endif #ifndef INCLUDED_flixel_FlxSubState #include <flixel/FlxSubState.h> #endif #ifndef INCLUDED_flixel_addons_transition_FlxTransitionableState #include <flixel/addons/transition/FlxTransitionableState.h> #endif #ifndef INCLUDED_flixel_addons_transition_TransitionData #include <flixel/addons/transition/TransitionData.h> #endif #ifndef INCLUDED_flixel_addons_ui_FlxUIState #include <flixel/addons/ui/FlxUIState.h> #endif #ifndef INCLUDED_flixel_addons_ui_interfaces_IEventGetter #include <flixel/addons/ui/interfaces/IEventGetter.h> #endif #ifndef INCLUDED_flixel_addons_ui_interfaces_IFlxUIState #include <flixel/addons/ui/interfaces/IFlxUIState.h> #endif #ifndef INCLUDED_flixel_group_FlxTypedGroup #include <flixel/group/FlxTypedGroup.h> #endif #ifndef INCLUDED_flixel_input_actions_FlxActionSet #include <flixel/input/actions/FlxActionSet.h> #endif #ifndef INCLUDED_flixel_util_IFlxDestroyable #include <flixel/util/IFlxDestroyable.h> #endif #ifndef INCLUDED_openfl_display_DisplayObject #include <openfl/display/DisplayObject.h> #endif #ifndef INCLUDED_openfl_display_DisplayObjectContainer #include <openfl/display/DisplayObjectContainer.h> #endif #ifndef INCLUDED_openfl_display_IBitmapDrawable #include <openfl/display/IBitmapDrawable.h> #endif #ifndef INCLUDED_openfl_display_InteractiveObject #include <openfl/display/InteractiveObject.h> #endif #ifndef INCLUDED_openfl_display_Sprite #include <openfl/display/Sprite.h> #endif #ifndef INCLUDED_openfl_events_EventDispatcher #include <openfl/events/EventDispatcher.h> #endif #ifndef INCLUDED_openfl_events_IEventDispatcher #include <openfl/events/IEventDispatcher.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_495f89d9d0902be3_17_new,"MusicBeatState","new",0xdae47368,"MusicBeatState.new","MusicBeatState.hx",17,0xa1b2f108) HX_LOCAL_STACK_FRAME(_hx_pos_495f89d9d0902be3_27_get_controls,"MusicBeatState","get_controls",0xacecf677,"MusicBeatState.get_controls","MusicBeatState.hx",27,0xa1b2f108) HX_LOCAL_STACK_FRAME(_hx_pos_495f89d9d0902be3_29_create,"MusicBeatState","create",0x5e9058f4,"MusicBeatState.create","MusicBeatState.hx",29,0xa1b2f108) HX_LOCAL_STACK_FRAME(_hx_pos_495f89d9d0902be3_42_onFocus,"MusicBeatState","onFocus",0xe919c541,"MusicBeatState.onFocus","MusicBeatState.hx",42,0xa1b2f108) HX_LOCAL_STACK_FRAME(_hx_pos_495f89d9d0902be3_48_onFocusLost,"MusicBeatState","onFocusLost",0x797ccfc5,"MusicBeatState.onFocusLost","MusicBeatState.hx",48,0xa1b2f108) HX_LOCAL_STACK_FRAME(_hx_pos_495f89d9d0902be3_55_update,"MusicBeatState","update",0x69867801,"MusicBeatState.update","MusicBeatState.hx",55,0xa1b2f108) HX_LOCAL_STACK_FRAME(_hx_pos_495f89d9d0902be3_70_updateBeat,"MusicBeatState","updateBeat",0x79761a17,"MusicBeatState.updateBeat","MusicBeatState.hx",70,0xa1b2f108) HX_LOCAL_STACK_FRAME(_hx_pos_495f89d9d0902be3_74_updateCurStep,"MusicBeatState","updateCurStep",0xd6ad7aeb,"MusicBeatState.updateCurStep","MusicBeatState.hx",74,0xa1b2f108) HX_LOCAL_STACK_FRAME(_hx_pos_495f89d9d0902be3_124_stepHit,"MusicBeatState","stepHit",0xcf94756f,"MusicBeatState.stepHit","MusicBeatState.hx",124,0xa1b2f108) HX_LOCAL_STACK_FRAME(_hx_pos_495f89d9d0902be3_129_beatHit,"MusicBeatState","beatHit",0xc257b185,"MusicBeatState.beatHit","MusicBeatState.hx",129,0xa1b2f108) HX_LOCAL_STACK_FRAME(_hx_pos_495f89d9d0902be3_89_switchState,"MusicBeatState","switchState",0xaf81f285,"MusicBeatState.switchState","MusicBeatState.hx",89,0xa1b2f108) HX_LOCAL_STACK_FRAME(_hx_pos_495f89d9d0902be3_97_switchState,"MusicBeatState","switchState",0xaf81f285,"MusicBeatState.switchState","MusicBeatState.hx",97,0xa1b2f108) HX_LOCAL_STACK_FRAME(_hx_pos_495f89d9d0902be3_102_switchState,"MusicBeatState","switchState",0xaf81f285,"MusicBeatState.switchState","MusicBeatState.hx",102,0xa1b2f108) HX_LOCAL_STACK_FRAME(_hx_pos_495f89d9d0902be3_113_resetState,"MusicBeatState","resetState",0xec54fbba,"MusicBeatState.resetState","MusicBeatState.hx",113,0xa1b2f108) HX_LOCAL_STACK_FRAME(_hx_pos_495f89d9d0902be3_116_getState,"MusicBeatState","getState",0x1dfde593,"MusicBeatState.getState","MusicBeatState.hx",116,0xa1b2f108) void MusicBeatState_obj::__construct( ::flixel::addons::transition::TransitionData TransIn, ::flixel::addons::transition::TransitionData TransOut){ HX_STACKFRAME(&_hx_pos_495f89d9d0902be3_17_new) HXLINE( 23) this->curBeat = 0; HXLINE( 22) this->curStep = 0; HXLINE( 20) this->lastStep = ((Float)0); HXLINE( 19) this->lastBeat = ((Float)0); HXLINE( 17) super::__construct(TransIn,TransOut); } Dynamic MusicBeatState_obj::__CreateEmpty() { return new MusicBeatState_obj; } void *MusicBeatState_obj::_hx_vtable = 0; Dynamic MusicBeatState_obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< MusicBeatState_obj > _hx_result = new MusicBeatState_obj(); _hx_result->__construct(inArgs[0],inArgs[1]); return _hx_result; } bool MusicBeatState_obj::_hx_isInstanceOf(int inClassId) { if (inClassId<=(int)0x3f706236) { if (inClassId<=(int)0x2f064378) { if (inClassId<=(int)0x23a57bae) { return inClassId==(int)0x00000001 || inClassId==(int)0x23a57bae; } else { return inClassId==(int)0x2f064378; } } else { return inClassId==(int)0x3f706236; } } else { if (inClassId<=(int)0x7c795c9f) { return inClassId==(int)0x62817b24 || inClassId==(int)0x7c795c9f; } else { return inClassId==(int)0x7ccf8994; } } } ::Controls MusicBeatState_obj::get_controls(){ HX_STACKFRAME(&_hx_pos_495f89d9d0902be3_27_get_controls) HXDLIN( 27) return ::PlayerSettings_obj::player1->controls; } HX_DEFINE_DYNAMIC_FUNC0(MusicBeatState_obj,get_controls,return ) void MusicBeatState_obj::create(){ HX_GC_STACKFRAME(&_hx_pos_495f89d9d0902be3_29_create) HXLINE( 30) bool skip = ::flixel::addons::transition::FlxTransitionableState_obj::skipNextTransOut; HXLINE( 31) this->super::create(); HXLINE( 34) if (!(skip)) { HXLINE( 35) this->openSubState( ::CustomFadeTransition_obj::__alloc( HX_CTX ,( (Float)(1) ),true)); } HXLINE( 37) ::flixel::addons::transition::FlxTransitionableState_obj::skipNextTransOut = false; } void MusicBeatState_obj::onFocus(){ HX_STACKFRAME(&_hx_pos_495f89d9d0902be3_42_onFocus) HXLINE( 43) ::FlxVideo_obj::onFocus(); HXLINE( 44) this->super::onFocus(); } void MusicBeatState_obj::onFocusLost(){ HX_STACKFRAME(&_hx_pos_495f89d9d0902be3_48_onFocusLost) HXLINE( 49) ::FlxVideo_obj::onFocusLost(); HXLINE( 50) this->super::onFocusLost(); } void MusicBeatState_obj::update(Float elapsed){ HX_STACKFRAME(&_hx_pos_495f89d9d0902be3_55_update) HXLINE( 57) int oldStep = this->curStep; HXLINE( 59) this->updateCurStep(); HXLINE( 60) this->updateBeat(); HXLINE( 62) bool _hx_tmp; HXDLIN( 62) if ((oldStep != this->curStep)) { HXLINE( 62) _hx_tmp = (this->curStep > 0); } else { HXLINE( 62) _hx_tmp = false; } HXDLIN( 62) if (_hx_tmp) { HXLINE( 63) this->stepHit(); } HXLINE( 65) this->super::update(elapsed); } void MusicBeatState_obj::updateBeat(){ HX_STACKFRAME(&_hx_pos_495f89d9d0902be3_70_updateBeat) HXDLIN( 70) this->curBeat = ::Math_obj::floor((( (Float)(this->curStep) ) / ( (Float)(4) ))); } HX_DEFINE_DYNAMIC_FUNC0(MusicBeatState_obj,updateBeat,(void)) void MusicBeatState_obj::updateCurStep(){ HX_STACKFRAME(&_hx_pos_495f89d9d0902be3_74_updateCurStep) HXLINE( 75) ::Dynamic lastChange = ::Dynamic(::hx::Anon_obj::Create(3) ->setFixed(0,HX_("stepTime",79,75,25,a0),0) ->setFixed(1,HX_("bpm",df,be,4a,00),( (Float)(0) )) ->setFixed(2,HX_("songTime",82,2a,d5,3a),( (Float)(0) ))); HXLINE( 80) { HXLINE( 80) int _g = 0; HXDLIN( 80) int _g1 = ::Conductor_obj::bpmChangeMap->length; HXDLIN( 80) while((_g < _g1)){ HXLINE( 80) _g = (_g + 1); HXDLIN( 80) int i = (_g - 1); HXLINE( 82) if (::hx::IsGreaterEq( ::Conductor_obj::songPosition,::Conductor_obj::bpmChangeMap->__get(i)->__Field(HX_("songTime",82,2a,d5,3a),::hx::paccDynamic) )) { HXLINE( 83) lastChange = ::Conductor_obj::bpmChangeMap->__get(i); } } } HXLINE( 86) this->curStep = ( (int)((lastChange->__Field(HX_("stepTime",79,75,25,a0),::hx::paccDynamic) + ::Math_obj::floor((((::Conductor_obj::songPosition - ( (Float)(::ClientPrefs_obj::noteOffset) )) - ( (Float)(lastChange->__Field(HX_("songTime",82,2a,d5,3a),::hx::paccDynamic)) )) / ::Conductor_obj::stepCrochet)))) ); } HX_DEFINE_DYNAMIC_FUNC0(MusicBeatState_obj,updateCurStep,(void)) void MusicBeatState_obj::stepHit(){ HX_STACKFRAME(&_hx_pos_495f89d9d0902be3_124_stepHit) HXDLIN( 124) if ((::hx::Mod(this->curStep,4) == 0)) { HXLINE( 125) this->beatHit(); } } HX_DEFINE_DYNAMIC_FUNC0(MusicBeatState_obj,stepHit,(void)) void MusicBeatState_obj::beatHit(){ HX_STACKFRAME(&_hx_pos_495f89d9d0902be3_129_beatHit) } HX_DEFINE_DYNAMIC_FUNC0(MusicBeatState_obj,beatHit,(void)) void MusicBeatState_obj::switchState( ::flixel::FlxState nextState){ HX_GC_STACKFRAME(&_hx_pos_495f89d9d0902be3_89_switchState) HXLINE( 91) ::Dynamic curState = ::flixel::FlxG_obj::game->_state; HXLINE( 92) ::MusicBeatState leState = ( ( ::MusicBeatState)(curState) ); HXLINE( 93) if (!(::flixel::addons::transition::FlxTransitionableState_obj::skipNextTransIn)) { HXLINE( 94) leState->openSubState( ::CustomFadeTransition_obj::__alloc( HX_CTX ,((Float)0.7),false)); HXLINE( 95) if (::hx::IsInstanceEq( nextState,::flixel::FlxG_obj::game->_state )) { HX_BEGIN_LOCAL_FUNC_S0(::hx::LocalFunc,_hx_Closure_0) HXARGC(0) void _hx_run(){ HX_GC_STACKFRAME(&_hx_pos_495f89d9d0902be3_97_switchState) HXLINE( 97) ::flixel::FlxState nextState = ( ( ::flixel::FlxState)(::Type_obj::createInstance(::Type_obj::getClass(::flixel::FlxG_obj::game->_state),::cpp::VirtualArray_obj::__new(0))) ); HXDLIN( 97) if (::flixel::FlxG_obj::game->_state->switchTo(nextState)) { HXLINE( 97) ::flixel::FlxG_obj::game->_requestedState = nextState; } } HX_END_LOCAL_FUNC0((void)) HXLINE( 96) ::CustomFadeTransition_obj::finishCallback = ::Dynamic(new _hx_Closure_0()); } else { HX_BEGIN_LOCAL_FUNC_S1(::hx::LocalFunc,_hx_Closure_1, ::flixel::FlxState,nextState) HXARGC(0) void _hx_run(){ HX_GC_STACKFRAME(&_hx_pos_495f89d9d0902be3_102_switchState) HXLINE( 102) if (::flixel::FlxG_obj::game->_state->switchTo(nextState)) { HXLINE( 102) ::flixel::FlxG_obj::game->_requestedState = nextState; } } HX_END_LOCAL_FUNC0((void)) HXLINE( 101) ::CustomFadeTransition_obj::finishCallback = ::Dynamic(new _hx_Closure_1(nextState)); } HXLINE( 106) return; } HXLINE( 108) ::flixel::addons::transition::FlxTransitionableState_obj::skipNextTransIn = false; HXLINE( 109) if (::flixel::FlxG_obj::game->_state->switchTo(nextState)) { HXLINE( 109) ::flixel::FlxG_obj::game->_requestedState = nextState; } } STATIC_HX_DEFINE_DYNAMIC_FUNC1(MusicBeatState_obj,switchState,(void)) void MusicBeatState_obj::resetState(){ HX_STACKFRAME(&_hx_pos_495f89d9d0902be3_113_resetState) HXDLIN( 113) ::MusicBeatState_obj::switchState(::flixel::FlxG_obj::game->_state); } STATIC_HX_DEFINE_DYNAMIC_FUNC0(MusicBeatState_obj,resetState,(void)) ::MusicBeatState MusicBeatState_obj::getState(){ HX_STACKFRAME(&_hx_pos_495f89d9d0902be3_116_getState) HXLINE( 117) ::Dynamic curState = ::flixel::FlxG_obj::game->_state; HXLINE( 118) ::MusicBeatState leState = ( ( ::MusicBeatState)(curState) ); HXLINE( 119) return leState; } STATIC_HX_DEFINE_DYNAMIC_FUNC0(MusicBeatState_obj,getState,return ) ::hx::ObjectPtr< MusicBeatState_obj > MusicBeatState_obj::__new( ::flixel::addons::transition::TransitionData TransIn, ::flixel::addons::transition::TransitionData TransOut) { ::hx::ObjectPtr< MusicBeatState_obj > __this = new MusicBeatState_obj(); __this->__construct(TransIn,TransOut); return __this; } ::hx::ObjectPtr< MusicBeatState_obj > MusicBeatState_obj::__alloc(::hx::Ctx *_hx_ctx, ::flixel::addons::transition::TransitionData TransIn, ::flixel::addons::transition::TransitionData TransOut) { MusicBeatState_obj *__this = (MusicBeatState_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(MusicBeatState_obj), true, "MusicBeatState")); *(void **)__this = MusicBeatState_obj::_hx_vtable; __this->__construct(TransIn,TransOut); return __this; } MusicBeatState_obj::MusicBeatState_obj() { } ::hx::Val MusicBeatState_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 6: if (HX_FIELD_EQ(inName,"create") ) { return ::hx::Val( create_dyn() ); } if (HX_FIELD_EQ(inName,"update") ) { return ::hx::Val( update_dyn() ); } break; case 7: if (HX_FIELD_EQ(inName,"curStep") ) { return ::hx::Val( curStep ); } if (HX_FIELD_EQ(inName,"curBeat") ) { return ::hx::Val( curBeat ); } if (HX_FIELD_EQ(inName,"onFocus") ) { return ::hx::Val( onFocus_dyn() ); } if (HX_FIELD_EQ(inName,"stepHit") ) { return ::hx::Val( stepHit_dyn() ); } if (HX_FIELD_EQ(inName,"beatHit") ) { return ::hx::Val( beatHit_dyn() ); } break; case 8: if (HX_FIELD_EQ(inName,"lastBeat") ) { return ::hx::Val( lastBeat ); } if (HX_FIELD_EQ(inName,"lastStep") ) { return ::hx::Val( lastStep ); } if (HX_FIELD_EQ(inName,"controls") ) { if (inCallProp == ::hx::paccAlways) return ::hx::Val( get_controls() ); } break; case 10: if (HX_FIELD_EQ(inName,"updateBeat") ) { return ::hx::Val( updateBeat_dyn() ); } break; case 11: if (HX_FIELD_EQ(inName,"onFocusLost") ) { return ::hx::Val( onFocusLost_dyn() ); } break; case 12: if (HX_FIELD_EQ(inName,"get_controls") ) { return ::hx::Val( get_controls_dyn() ); } break; case 13: if (HX_FIELD_EQ(inName,"updateCurStep") ) { return ::hx::Val( updateCurStep_dyn() ); } } return super::__Field(inName,inCallProp); } bool MusicBeatState_obj::__GetStatic(const ::String &inName, Dynamic &outValue, ::hx::PropertyAccess inCallProp) { switch(inName.length) { case 8: if (HX_FIELD_EQ(inName,"getState") ) { outValue = getState_dyn(); return true; } break; case 10: if (HX_FIELD_EQ(inName,"resetState") ) { outValue = resetState_dyn(); return true; } break; case 11: if (HX_FIELD_EQ(inName,"switchState") ) { outValue = switchState_dyn(); return true; } } return false; } ::hx::Val MusicBeatState_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 7: if (HX_FIELD_EQ(inName,"curStep") ) { curStep=inValue.Cast< int >(); return inValue; } if (HX_FIELD_EQ(inName,"curBeat") ) { curBeat=inValue.Cast< int >(); return inValue; } break; case 8: if (HX_FIELD_EQ(inName,"lastBeat") ) { lastBeat=inValue.Cast< Float >(); return inValue; } if (HX_FIELD_EQ(inName,"lastStep") ) { lastStep=inValue.Cast< Float >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void MusicBeatState_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_("lastBeat",ec,fa,5c,d4)); outFields->push(HX_("lastStep",c2,00,a5,df)); outFields->push(HX_("curStep",ec,58,71,b7)); outFields->push(HX_("curBeat",16,53,29,ac)); outFields->push(HX_("controls",76,86,bc,37)); super::__GetFields(outFields); }; #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo MusicBeatState_obj_sMemberStorageInfo[] = { {::hx::fsFloat,(int)offsetof(MusicBeatState_obj,lastBeat),HX_("lastBeat",ec,fa,5c,d4)}, {::hx::fsFloat,(int)offsetof(MusicBeatState_obj,lastStep),HX_("lastStep",c2,00,a5,df)}, {::hx::fsInt,(int)offsetof(MusicBeatState_obj,curStep),HX_("curStep",ec,58,71,b7)}, {::hx::fsInt,(int)offsetof(MusicBeatState_obj,curBeat),HX_("curBeat",16,53,29,ac)}, { ::hx::fsUnknown, 0, null()} }; static ::hx::StaticInfo *MusicBeatState_obj_sStaticStorageInfo = 0; #endif static ::String MusicBeatState_obj_sMemberFields[] = { HX_("lastBeat",ec,fa,5c,d4), HX_("lastStep",c2,00,a5,df), HX_("curStep",ec,58,71,b7), HX_("curBeat",16,53,29,ac), HX_("get_controls",7f,3a,d6,ec), HX_("create",fc,66,0f,7c), HX_("onFocus",39,fe,c6,9a), HX_("onFocusLost",bd,e4,85,41), HX_("update",09,86,05,87), HX_("updateBeat",1f,cc,c8,f9), HX_("updateCurStep",e3,bd,df,82), HX_("stepHit",67,ae,41,81), HX_("beatHit",7d,ea,04,74), ::String(null()) }; ::hx::Class MusicBeatState_obj::__mClass; static ::String MusicBeatState_obj_sStaticFields[] = { HX_("switchState",7d,07,8b,77), HX_("resetState",c2,ad,a7,6c), HX_("getState",9b,85,e2,e3), ::String(null()) }; void MusicBeatState_obj::__register() { MusicBeatState_obj _hx_dummy; MusicBeatState_obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("MusicBeatState",76,df,84,5d); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &MusicBeatState_obj::__GetStatic; __mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField; __mClass->mStatics = ::hx::Class_obj::dupFunctions(MusicBeatState_obj_sStaticFields); __mClass->mMembers = ::hx::Class_obj::dupFunctions(MusicBeatState_obj_sMemberFields); __mClass->mCanCast = ::hx::TCanCast< MusicBeatState_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = MusicBeatState_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = MusicBeatState_obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); }
40.867679
325
0.728344
TheSlithyGamer4evr
ed761e95d2b732f832880a71984e0ae2bf438768
30,528
cpp
C++
src/updatework.cpp
CCTV-1/XmageLauncher
d6166f9e54f4401ccd97e960e38b313eccf1557a
[ "MIT" ]
null
null
null
src/updatework.cpp
CCTV-1/XmageLauncher
d6166f9e54f4401ccd97e960e38b313eccf1557a
[ "MIT" ]
null
null
null
src/updatework.cpp
CCTV-1/XmageLauncher
d6166f9e54f4401ccd97e960e38b313eccf1557a
[ "MIT" ]
null
null
null
#include <cstdio> #include <cstdlib> #include <cstring> #include <functional> #include <memory> #include <set> #include <thread> #include <zip.h> #include <json-glib/json-glib.h> #include <giomm/file.h> #include <glibmm/i18n.h> #include "updatework.h" #include "launcherconfig.h" class ReceiveBuff { public: ReceiveBuff() { constexpr const size_t presize = 1024; this->buff = ( char * )malloc( sizeof( char )*presize ); this->allocate_size = presize; this->used_size = 0; } ~ReceiveBuff() { free( this->buff ); } ReceiveBuff( const ReceiveBuff& rhs ) { this->buff = ( char * )malloc( sizeof( char )*(rhs.allocate_size) ); if ( this->buff == nullptr ) { throw std::bad_alloc(); } memccpy( this->buff , rhs.buff , sizeof( char ) , rhs.allocate_size ); this->allocate_size = rhs.allocate_size; this->used_size = rhs.used_size; } ReceiveBuff& operator=( const ReceiveBuff& rhs ) { if ( this == &rhs ) { return *this; } free( this->buff ); this->buff = ( char * )malloc( sizeof( char )*(rhs.allocate_size) ); if ( this->buff == nullptr ) { throw std::bad_alloc(); } memccpy( this->buff , rhs.buff , sizeof( char ) , rhs.allocate_size ); this->allocate_size = rhs.allocate_size; this->used_size = rhs.used_size; } ReceiveBuff( ReceiveBuff&& rhs ) noexcept( true ): buff( std::move(rhs.buff) ), allocate_size( std::move(rhs.allocate_size) ), used_size( std::move(rhs.used_size) ) { ; } ReceiveBuff& operator=( ReceiveBuff&& rhs ) noexcept( true ) { if ( this == &rhs ) { return *this; } free( this->buff ); this->buff = std::move( rhs.buff ); this->allocate_size = std::move( rhs.allocate_size ); this->used_size = std::move( rhs.used_size ); } const char * get_buff( void ) { return this->buff; } std::size_t get_used( void ) { return this->used_size; } void append_data( const char * data , std::size_t data_size ) { std::size_t need_size = used_size + data_size; if ( need_size > this->allocate_size ) { while ( need_size > this->allocate_size ) { this->allocate_size *= 2; } char * new_buff = static_cast<char *>( realloc( this->buff , this->allocate_size ) ); if ( new_buff == nullptr ) { //keep old buff content throw std::bad_alloc(); } this->buff = new_buff; } memccpy( this->buff + used_size , data , sizeof( char ) , data_size ); this->used_size += data_size; } private: char * buff; std::size_t allocate_size; std::size_t used_size; }; static Glib::ustring _proxy_desc; static void common_curl_opt_set( std::shared_ptr<CURL> curl_handle ) { constexpr char user_agent[] = "XmageLauncher"; curl_easy_setopt( curl_handle.get() , CURLOPT_USERAGENT , user_agent ); curl_easy_setopt( curl_handle.get() , CURLOPT_VERBOSE , 0L ); curl_easy_setopt( curl_handle.get() , CURLOPT_FOLLOWLOCATION , 1L ); curl_easy_setopt( curl_handle.get() , CURLOPT_USE_SSL , 1L ); if ( _proxy_desc.empty() == false ) { curl_easy_setopt( curl_handle.get() , CURLOPT_PROXY , _proxy_desc.c_str() ); } } static int download_description_callback( void * client_ptr , curl_off_t dltotal , curl_off_t dlnow , curl_off_t , curl_off_t ) { progress_t * progress = static_cast<progress_t *>( client_ptr ); if ( progress == nullptr || progress->work == nullptr ) { return false; } //notify progress update { std::lock_guard<std::mutex> lock( progress->work->update_mutex ); progress->work->prog_now = dlnow; progress->work->prog_total = dltotal; } progress->dispatcher.emit(); return 0; } static std::size_t get_json_callback( char * content , std::size_t size , std::size_t element_number , void * save_ptr ) { std::size_t realsize = size*element_number; ReceiveBuff * ptr = static_cast<ReceiveBuff *>( save_ptr ); try { ptr->append_data( content , realsize ); } catch(const std::bad_alloc& e) { return 0; } return realsize; } static std::shared_ptr<JsonParser> get_json( Glib::ustring url ) noexcept( false ) { std::string except_message( __func__ ); std::int8_t re_try = 4; long default_timeout = 30L; ReceiveBuff json_buff; char error_buff[CURL_ERROR_SIZE]; //c str* safe error_buff[0] = '\0'; CURLcode res = CURLE_OK; std::shared_ptr<CURL> curl_handle( curl_easy_init() , curl_easy_cleanup ); if ( curl_handle.get() == nullptr ) { except_message += ":libcurl easy initial failure"; throw std::runtime_error( except_message ); } do { common_curl_opt_set( curl_handle ); curl_easy_setopt( curl_handle.get() , CURLOPT_URL , url.c_str() ); curl_easy_setopt( curl_handle.get() , CURLOPT_NOPROGRESS , 1L ); curl_easy_setopt( curl_handle.get() , CURLOPT_TIMEOUT , default_timeout ); curl_easy_setopt( curl_handle.get() , CURLOPT_WRITEFUNCTION , get_json_callback ); curl_easy_setopt( curl_handle.get() , CURLOPT_WRITEDATA , &json_buff ); curl_easy_setopt( curl_handle.get() , CURLOPT_ERRORBUFFER , error_buff ); res = curl_easy_perform( curl_handle.get() ); if ( res != CURLE_OK ) { if ( re_try == 0 ) { except_message += ":get '" + url + "' json failure,libcurl error message:"; except_message += error_buff; throw std::runtime_error( except_message ); } default_timeout += 10L; re_try--; } } while ( res != CURLE_OK ); std::shared_ptr<JsonParser> root( json_parser_new() , g_object_unref ); if ( !json_parser_load_from_data( root.get() , json_buff.get_buff() , json_buff.get_used() , nullptr ) ) { except_message += ":network json:'"; except_message += json_buff.get_buff(); except_message += "' format does not meet expectations"; throw std::invalid_argument( except_message ); } return root; } static xmage_desc_t get_update_desc( const char * api_url , const char * url_jsonpath , const char * ver_jsonpath , std::function<void(xmage_desc_t&)> formatter = nullptr ) { std::shared_ptr<JsonParser> root = get_json( api_url ); JsonNode * root_node = json_parser_get_root( root.get() ); std::shared_ptr<JsonNode> urls_node( json_path_query( url_jsonpath , root_node , nullptr ), json_node_unref ); if ( json_node_get_node_type( urls_node.get() ) != JsonNodeType::JSON_NODE_ARRAY ) { throw std::runtime_error( std::string( "url json path" ) + url_jsonpath + "can't find" ); } JsonArray * urls_arr = json_node_get_array( urls_node.get() ); JsonNode * url_node = json_array_get_element( urls_arr , 0 ); std::shared_ptr<JsonNode> vers_node( json_path_query( ver_jsonpath , root_node , nullptr ), json_node_unref ); if ( json_node_get_node_type( vers_node.get() ) != JsonNodeType::JSON_NODE_ARRAY ) { throw std::runtime_error( std::string( "version json path" ) + ver_jsonpath + "can't find" ); } JsonArray * vers_arr = json_node_get_array( vers_node.get() ); JsonNode * ver_node = json_array_get_element( vers_arr , 0 ); xmage_desc_t raw_desc = { json_node_get_string( ver_node ) , json_node_get_string( url_node ) }; if ( formatter != nullptr ) { formatter( raw_desc ); } return raw_desc; } static Glib::ustring get_installation_package_name( const xmage_desc_t& version_desc ) { return version_desc.version_name + ".zip"; } static Glib::ustring get_download_temp_name( const xmage_desc_t& version_desc ) { return version_desc.version_name + ".dl"; } static bool download_update_callback( xmage_desc_t version_desc , progress_t * download_desc ) { std::shared_ptr<CURL> curl_handle( curl_easy_init() , curl_easy_cleanup ); //output temp file,download success,rename to version.zip,to support check local zip continue download. Glib::ustring temp_name = get_download_temp_name( version_desc ); std::shared_ptr<FILE> download_file( fopen( temp_name.c_str() , "wb+" ) , fclose ); if ( download_file.get() == nullptr ) { g_log( __func__ , G_LOG_LEVEL_WARNING , "open file:\'%s\' failure." , temp_name.c_str() ); return false; } char error_buff[CURL_ERROR_SIZE]; common_curl_opt_set( curl_handle ); curl_easy_setopt( curl_handle.get() , CURLOPT_URL , version_desc.download_url.c_str() ); curl_easy_setopt( curl_handle.get() , CURLOPT_NOPROGRESS , 0L ); curl_easy_setopt( curl_handle.get() , CURLOPT_XFERINFOFUNCTION , download_description_callback ); curl_easy_setopt( curl_handle.get() , CURLOPT_XFERINFODATA , download_desc ); curl_easy_setopt( curl_handle.get() , CURLOPT_WRITEFUNCTION , fwrite ); curl_easy_setopt( curl_handle.get() , CURLOPT_ERRORBUFFER , error_buff ); curl_easy_setopt( curl_handle.get() , CURLOPT_WRITEDATA , download_file.get() ); std::shared_ptr<CURLM> curlmulti_handle( [ curl_handle ]() -> CURLM * { CURLM * handle = curl_multi_init(); curl_multi_add_handle( handle , curl_handle.get() ); return handle; }(), [ curl_handle ]( CURLM * handle ) -> void { curl_multi_remove_handle( handle , curl_handle.get() ); curl_multi_cleanup( handle ); } ); int running_handles; int repeats = 0; CURLMcode status_code = curl_multi_perform( curlmulti_handle.get() , &running_handles ); if ( ( status_code != CURLM_OK ) && ( status_code != CURLM_CALL_MULTI_PERFORM ) ) { g_log( __func__ , G_LOG_LEVEL_MESSAGE , "download url:\'%s\',error type:\'%s\',error message:\'%s\'" , version_desc.download_url.c_str() , curl_multi_strerror( status_code ) , error_buff ); return false; } while( running_handles ) { int numfds; status_code = curl_multi_wait( curlmulti_handle.get() , nullptr , 0 , 100 , &numfds ); if ( status_code != CURLM_OK ) { g_log( __func__ , G_LOG_LEVEL_MESSAGE , "download url:\'%s\',error type:\'%s\',error message:\'%s\'" , version_desc.download_url.c_str() , curl_multi_strerror( status_code ) , error_buff ); return false; } bool do_return; { std::lock_guard<std::mutex> lock( download_desc->work->update_mutex ); do_return = !( download_desc->work->updating ); } if ( do_return ) { //stop update,update failure. return false; } if ( numfds == 0 ) { repeats++; if ( repeats > 1 ) g_usleep( 100 ); //todo:add setting to launcher if ( repeats > 5*600 ) //600*100ms = 1min { g_log( __func__ , G_LOG_LEVEL_MESSAGE , "too long time not receiving data,disconnect,download failure." ); return false; } } else { repeats = 0; } status_code = curl_multi_perform( curlmulti_handle.get() , &running_handles ); if ( ( status_code != CURLM_OK ) && ( status_code != CURLM_CALL_MULTI_PERFORM ) ) { g_log( __func__ , G_LOG_LEVEL_MESSAGE , "download url:\'%s\',error type:\'%s\',error message:\'%s\'" , version_desc.download_url.c_str() , curl_multi_strerror( status_code ) , error_buff ); return false; } } CURLMsg * message = nullptr; do { int msgs_queue = 0; message = curl_multi_info_read( curlmulti_handle.get() , &msgs_queue ); if ( ( message != nullptr ) && ( message->msg == CURLMSG_DONE ) ) { if ( message->data.result != CURLE_OK ) { g_log( __func__ , G_LOG_LEVEL_MESSAGE , "download url:\'%s\',error content:\'%s\',error code:\'%d\'" , version_desc.download_url.c_str() , curl_easy_strerror( message->data.result ) , message->data.result ); return false; } } }while( message != nullptr ); return true; } static bool install_update_callback( Glib::ustring install_packge_name , Glib::ustring install_dir_path , progress_t * progress ) noexcept( false ) { if ( progress == nullptr || progress->work == nullptr ) { return false; } auto install_packge = Gio::File::create_for_path( install_packge_name ); auto install_dir = Gio::File::create_for_path( install_dir_path ); if ( install_packge->query_exists() == false ) { return false; } if ( install_dir->query_exists() == false ) { install_dir->make_directory_with_parents(); } std::shared_ptr<zip_t> zip_ptr( zip_open( install_packge_name.c_str() , ZIP_RDONLY , nullptr ) , zip_close ); zip_int64_t file_number = zip_get_num_entries( zip_ptr.get() , ZIP_FL_UNCHANGED ); { std::lock_guard<std::mutex> lock( progress->work->update_mutex ); progress->work->prog_total = file_number; } progress->dispatcher.emit(); zip_uint64_t buff_size = 1024 * 8 * sizeof( char ); std::shared_ptr<char> data_buff( static_cast<char *>( calloc( buff_size , sizeof( char ) ) ) , free ); for( zip_int64_t i = 0 ; i < file_number ; i++ ) { struct zip_stat file_stat; zip_stat_init( &file_stat ); zip_stat_index( zip_ptr.get() , i , ZIP_FL_ENC_GUESS , &file_stat ); if ( file_stat.size > buff_size ) { buff_size = file_stat.size; //discard old data data_buff = std::shared_ptr<char>( static_cast<char *>( calloc( buff_size , sizeof( char ) ) ) , free ); } std::shared_ptr<zip_file_t> file_ptr( zip_fopen_index( zip_ptr.get() , i , ZIP_FL_UNCHANGED ) , zip_fclose ); zip_fread( file_ptr.get() , data_buff.get() , file_stat.size ); Glib::ustring unzip_path( file_stat.name ); auto target_path = Gio::File::create_for_path( install_dir_path + "/" + unzip_path ); if ( unzip_path[unzip_path.size()-1] == '/' ) { //avoid file_set_contents() write root/dir/ to root/dir //if write to root/dir,block write root/dir/file exception handler mkdir(root/dir/) failure. Gio::FileType type = target_path->query_file_type(); if ( type == Gio::FileType::FILE_TYPE_NOT_KNOWN ) { target_path->make_directory_with_parents(); } //if exists root/dir remove it. else if ( type != Gio::FileType::FILE_TYPE_DIRECTORY ) { target_path->remove(); target_path->make_directory_with_parents(); } //update progress { std::lock_guard<std::mutex> lock( progress->work->update_mutex ); progress->work->prog_now = i + 1; } progress->dispatcher.emit(); continue; } try { Glib::file_set_contents( target_path->get_path() , data_buff.get() , file_stat.size ); } catch ( const Glib::FileError& e ) { auto code = e.code(); if ( code == Glib::FileError::Code::ACCESS_DENIED ) { if ( target_path->query_file_type() != Gio::FileType::FILE_TYPE_DIRECTORY ) g_log( __func__ , G_LOG_LEVEL_MESSAGE , "access file:'%s failure',Glib::FileError code:%d" , target_path->get_path().c_str() , code ); } else if ( code == Glib::FileError::Code::NO_SUCH_ENTITY ) { auto parent_dir = target_path->get_parent(); //zip_get_num_entries ->exists Gio::FileType type = parent_dir->query_file_type(); if ( type == Gio::FileType::FILE_TYPE_NOT_KNOWN ) { parent_dir->make_directory_with_parents(); } try { Glib::file_set_contents( target_path->get_path() , data_buff.get() , file_stat.size ); } catch ( const Glib::FileError& e ) { g_log( __func__ , G_LOG_LEVEL_MESSAGE , "retry unzip file:'%s' failure,Glib::FileError code:%d" , target_path->get_path().c_str() , code ); } } else { g_log( __func__ , G_LOG_LEVEL_MESSAGE , "unzip file:'%s failure',Glib::FileError code:%d" , target_path->get_path().c_str() , code ); } } { std::lock_guard<std::mutex> lock( progress->work->update_mutex ); progress->work->prog_now = i + 1; } progress->dispatcher.emit(); } return true; } bool set_proxy( Glib::ustring scheme , Glib::ustring hostname , std::uint32_t port ) { Glib::ustring proxy_desc; Glib::ustring diff_scheme = scheme.lowercase(); const std::set<Glib::ustring> scheme_map({ "http" , "https" , "socks4" , "socks4a", "socks5" , "socks5h", }); if ( scheme_map.find( diff_scheme ) == scheme_map.end() ) { return false; } proxy_desc += scheme; proxy_desc += "://"; if ( hostname.empty() ) return false; proxy_desc += hostname; if ( port >= 65535 ) return false; proxy_desc += ":"; proxy_desc += std::to_string( port ); _proxy_desc = std::move( proxy_desc ); return true; } static std::shared_future<xmage_desc_t> get_last_version( XmageType type ) { config_t& config = config_t::get_config(); bool using_mirror = config.get_using_mirror(); std::function<xmage_desc_t()> get_version_func; if ( type == XmageType::Release ) { if ( using_mirror ) { //{ // "java" : { // "version": "1.8.0_201", // "old_location": "http://download.oracle.com/otn-pub/java/jdk/8u201-b09/42970487e3af4f5aa5bca3f542482c60/jre-8u201-", // "location": "http://xmage.today/java/jre-8u201-" // }, // "XMage" : { // "version": "1.4.35V1 (2019-04-24)", // "location": "https://github.com/magefree/mage/releases/download/xmage_1.4.35V1/xmage_1.4.35V1.zip", // "locations": ["http://xmage.de/files/xmage_1.4.35V1.zip"], // "torrent": "", // "images": "", // "Launcher" : { // "version": "0.3.8", // "location": "http://bit.ly/xmageLauncher038" // } // } //} get_version_func = std::bind( get_update_desc , "http://xmage.de/xmage/config.json" , "$.XMage.locations[0]" , "$.XMage.version", []( xmage_desc_t& raw ) { //"1.4.35V1 (2019-04-24)", Glib::ustring version_time = raw.version_name; std::size_t space_index = 0; for ( std::size_t i = 0 ; i < version_time.size() ; i++ ) { if ( version_time[i] == ' ' ) { space_index = i; break; } } //1.4.35V1 raw.version_name = version_time.substr( 0 , space_index ); } ); } else { //{ // ... unimportant ... // "assets": [ // { // "name": "mage_1.4.35V0.zip" // ... unimportant ... // "browser_download_url": "https://github.com/magefree/mage/releases/download/xmage_1.4.35V0/xmage_1.4.35V0.zip" // } // { // "name": "mage_1.4.35V0a.zip" // ... unimportant ... // "browser_download_url": "https://github.com/magefree/mage/releases/download/xmage_1.4.35V0/xmage_1.4.35V0a.zip" // } // ], // ... unimportant ... //} get_version_func = std::bind( get_update_desc , "https://api.github.com/repos/magefree/mage/releases/latest" , "$.assets[0].browser_download_url" , "$.assets[0].name", []( xmage_desc_t& raw ) { if ( Glib::str_has_prefix( raw.version_name , "xmage_" ) ) { //"xmage_" exists NUL sizeof 6 raw.version_name = raw.version_name.substr( sizeof( "xmage_" ) - 1 , raw.version_name.size() ); } if ( Glib::str_has_suffix( raw.version_name , ".zip" ) ) { //".zip" exists NUL sizeof 5 raw.version_name = raw.version_name.substr( 0 , raw.version_name.size() - ( sizeof( ".zip" ) - 1 ) ); } } ); } } else { //{ // "java": { // "version": "1.8.0_201", // "location": "http://xmage.today/java/jre-8u201-" // }, // "XMage": { // "version": "1.4.48-dev (2021-05-05 14-05)", // "location": "http://beta.xmage.today/files/mage-update_1.4.48-dev_2021-05-05_14-05.zip", // "locations": [], // "full": "http://beta.xmage.today/files/mage-full_1.4.48-dev_2021-05-05_14-05.zip", // "torrent": "", // "images": "", // "Launcher": { // "version": "0.3.8", // "location": "http://bit.ly/xmageLauncher038" // } // } //} get_version_func = std::bind( get_update_desc , "http://xmage.today//config.json" , "$.XMage.full" , "$.XMage.version" , nullptr ); } std::packaged_task<xmage_desc_t()> task( get_version_func ); std::shared_future<xmage_desc_t> version_future = task.get_future(); std::thread( std::move(task) ).detach(); return version_future; } static std::shared_future<bool> download_update( xmage_desc_t version_desc , progress_t * download_desc ) { std::packaged_task<bool()> task( std::bind( download_update_callback , version_desc , download_desc ) ); std::shared_future<bool> download_future = task.get_future(); std::thread( std::move(task) ).detach(); return download_future; } static std::shared_future<bool> install_update( Glib::ustring install_packge_name , Glib::ustring install_dir_path , progress_t * progress ) { std::packaged_task<bool()> task( std::bind( install_update_callback , install_packge_name , install_dir_path , progress ) ); std::shared_future<bool> unzip_future = task.get_future(); std::thread( std::move(task) ).detach(); return unzip_future; } Glib::ustring xmagetype_to_string( const XmageType& type ) { Glib::ustring str; switch ( type ) { default: case XmageType::Release: str = _( "Release" ); break; case XmageType::Beta: str = _( "Beta" ); break; } return str; } UpdateWork::UpdateWork(): update_mutex(), updating( false ), prog_now(), prog_total(), prog_info() { ; } void UpdateWork::do_update( Glib::Dispatcher& dispatcher ) { //start update,disable launch button { std::lock_guard<std::mutex> lock( this->update_mutex ); this->prog_info = _( "check for updates" ); } //return ; call deconstruct,don't need call dispatcher.emit(); std::shared_ptr<void> lock_launch( [ this , &dispatcher ]() { { std::lock_guard<std::mutex> lock( this->update_mutex ); this->updating = true; } dispatcher.emit(); return nullptr; }(), [ this , &dispatcher ]( void * ) { { std::lock_guard<std::mutex> lock( this->update_mutex ); this->prog_total = 0; this->updating = false; } dispatcher.emit(); } ); config_t& config = config_t::get_config(); XmageType type = config.get_active_xmage(); progress_t progress = { dispatcher , this }; auto update_future = get_last_version( type ); xmage_desc_t update_desc; while ( update_future.wait_for( std::chrono::microseconds( 200 ) ) != std::future_status::ready ) { bool do_return = false; { std::lock_guard<std::mutex> lock( this->update_mutex ); do_return = !( this->updating ); } if ( do_return ) { return ; } } try { update_desc = update_future.get(); } catch ( const std::exception& e ) { //get update information failure g_log( __func__ , G_LOG_LEVEL_MESSAGE , "%s" , e.what() ); //don't need stop request,check update failure,to return end update. { std::lock_guard<std::mutex> lock( this->update_mutex ); this->prog_info = _( "check update failure" ); } return ; } Glib::ustring version; if ( type == XmageType::Release ) { version = config.get_release_version(); } else { version = config.get_beta_version(); } g_log( __func__ , G_LOG_LEVEL_MESSAGE , _( "last xmage version:'%s',download url:'%s'." ) , update_desc.version_name.c_str() , update_desc.download_url.c_str() ); if ( update_desc.version_name.compare( version ) > 0 ) { g_log( __func__ , G_LOG_LEVEL_MESSAGE , "%s" , _( "exist new xmage,now download." ) ); } else { { std::lock_guard<std::mutex> lock( this->update_mutex ); this->prog_info = _( "no need to update" ); } return ; } std::shared_future<bool> download_future; //if exists auto install_package = Gio::File::create_for_path( get_installation_package_name( update_desc ) ); if ( install_package->query_exists() == false ) { download_future = download_update( update_desc , &progress ); { std::lock_guard<std::mutex> lock( this->update_mutex ); this->prog_info = _( "download update" ); } dispatcher.emit(); while ( download_future.wait_for( std::chrono::microseconds( 200 ) ) != std::future_status::ready ) { bool do_return = false; { std::lock_guard<std::mutex> lock( this->update_mutex ); do_return = !( this->updating ); } if ( do_return ) { //wait download thread exit download_future.wait(); return ; } } if ( download_future.get() ) { { std::lock_guard<std::mutex> lock( this->update_mutex ); this->prog_now = 0; this->prog_total = 0; this->prog_info = _( "download success" ); } dispatcher.emit(); auto download_temp_file = Gio::File::create_for_path( get_download_temp_name( update_desc ) ); download_temp_file->move( install_package ); } else { { std::lock_guard<std::mutex> lock( this->update_mutex ); this->prog_now = 0; this->prog_total = 0; this->prog_info = _( "download failure" ); } return ; } } else { g_log( __func__ , G_LOG_LEVEL_MESSAGE , _( "using local installation package" ) ); } Glib::ustring install_path; if ( type == XmageType::Release ) { install_path = config.get_release_path(); } else { install_path = config.get_beta_path(); } { std::lock_guard<std::mutex> lock( this->update_mutex ); this->prog_info = _( "install update" ); } auto install_future = install_update( get_installation_package_name( update_desc ) , install_path , &progress ); dispatcher.emit(); while ( install_future.wait_for( std::chrono::microseconds( 200 ) ) != std::future_status::ready ) { bool do_return = false; { std::lock_guard<std::mutex> lock( this->update_mutex ); do_return = !( this->updating ); } if ( do_return ) { return ; } } if ( install_future.get() == false ) { { std::lock_guard<std::mutex> lock( this->update_mutex ); this->prog_now = 0; this->prog_total = 0; this->prog_info = _( "install failure" ); } return ; } { std::lock_guard<std::mutex> lock( this->update_mutex ); this->prog_now = 0; this->prog_total = 0; this->prog_info = _( "install success" ); } dispatcher.emit(); if ( type == XmageType::Release ) { config.set_release_version( update_desc.version_name ); } else { config.set_beta_version( update_desc.version_name ); } install_package->remove(); } void UpdateWork::stop_update( void ) { std::lock_guard<std::mutex> lock( this->update_mutex ); this->updating = false; } void UpdateWork::get_data( bool& update_end , std::int64_t& now , std::int64_t& total , Glib::ustring& info ) { std::lock_guard<std::mutex> lock( this->update_mutex ); update_end = !this->updating; now = this->prog_now; total = this->prog_total; info = this->prog_info; }
34.262626
179
0.556833
CCTV-1
ed77941bf7a80452c10b2823902fba4f196d1fd7
88
hpp
C++
Kernel/header/interruptExceptionHandler.hpp
NudelErde/Kernel
875a0635b5bbd910680970a9446cb86b96b62323
[ "MIT" ]
null
null
null
Kernel/header/interruptExceptionHandler.hpp
NudelErde/Kernel
875a0635b5bbd910680970a9446cb86b96b62323
[ "MIT" ]
null
null
null
Kernel/header/interruptExceptionHandler.hpp
NudelErde/Kernel
875a0635b5bbd910680970a9446cb86b96b62323
[ "MIT" ]
1
2021-04-28T10:13:53.000Z
2021-04-28T10:13:53.000Z
#pragma once #include <stdint.h> namespace Kernel { void initExceptionHandlers(); }
8.8
29
0.727273
NudelErde