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
7c58e5f186694bb171931cf1d8266e2c31118507
3,303
cpp
C++
tests/test_transpose/test_transpose.cpp
mablanchard/Fastor
f5ca2f608bdfee34833d5008a93a3f82ce42ddef
[ "MIT" ]
424
2017-05-15T14:34:30.000Z
2022-03-29T08:58:22.000Z
tests/test_transpose/test_transpose.cpp
manodeep/Fastor
aefce47955dd118f04e7b36bf5dbb2d86997ff8f
[ "MIT" ]
150
2016-12-23T10:08:12.000Z
2022-01-16T03:53:45.000Z
tests/test_transpose/test_transpose.cpp
manodeep/Fastor
aefce47955dd118f04e7b36bf5dbb2d86997ff8f
[ "MIT" ]
43
2017-09-20T19:47:24.000Z
2022-02-22T21:12:49.000Z
#include <Fastor/Fastor.h> using namespace Fastor; #define Tol 1e-12 #define BigTol 1e-5 #define HugeTol 1e-2 template<typename T, size_t M, size_t N> Tensor<T,N,M> transpose_ref(const Tensor<T,M,N>& a) { Tensor<T,N,M> out; for (size_t i=0; i<M; ++i) { for (size_t j=0; j<N; ++j) { out(j,i) = a(i,j); } } return out; } template<typename T, size_t M, size_t N> void TEST_TRANSPOSE(Tensor<T,M,N>& a) { Tensor<T,N,M> b1 = transpose_ref(a); Tensor<T,N,M> b2 = transpose(a); Tensor<T,N,M> b3 = trans(a); for (size_t i=0; i<N; ++i) { for (size_t j=0; j<M; ++j) { FASTOR_EXIT_ASSERT(std::abs(b1(i,j) - b2(i,j)) < Tol); FASTOR_EXIT_ASSERT(std::abs(b1(i,j) - b3(i,j)) < Tol); } } FASTOR_EXIT_ASSERT(std::abs(norm(transpose(a))-norm(a))< HugeTol); FASTOR_EXIT_ASSERT(std::abs(norm(trans(a))-norm(a))< HugeTol); } template<typename T> void test_transpose() { { Tensor<T,2,2> t1; t1.iota(5); TEST_TRANSPOSE(t1); } { Tensor<T,3,3> t1; t1.iota(5); TEST_TRANSPOSE(t1); } { Tensor<T,4,4> t1; t1.iota(5); TEST_TRANSPOSE(t1); } { Tensor<T,5,5> t1; t1.iota(5); TEST_TRANSPOSE(t1); } { Tensor<T,7,7> t1; t1.iota(5); TEST_TRANSPOSE(t1); } { Tensor<T,8,8> t1; t1.iota(5); TEST_TRANSPOSE(t1); } { Tensor<T,9,9> t1; t1.iota(5); TEST_TRANSPOSE(t1); } { Tensor<T,10,10> t1; t1.iota(5); TEST_TRANSPOSE(t1); } { Tensor<T,12,12> t1; t1.iota(5); TEST_TRANSPOSE(t1); } { Tensor<T,16,16> t1; t1.iota(5); TEST_TRANSPOSE(t1); } { Tensor<T,17,17> t1; t1.iota(5); TEST_TRANSPOSE(t1); } { Tensor<T,20,20> t1; t1.iota(5); TEST_TRANSPOSE(t1); } { Tensor<T,24,24> t1; t1.iota(5); TEST_TRANSPOSE(t1); } { Tensor<T,40,40> t1; t1.iota(5); TEST_TRANSPOSE(t1); } // non-square { Tensor<T,2,3> t1; t1.iota(5); TEST_TRANSPOSE(t1); } { Tensor<T,3,4> t1; t1.iota(5); TEST_TRANSPOSE(t1); } { Tensor<T,4,5> t1; t1.iota(5); TEST_TRANSPOSE(t1); } { Tensor<T,5,6> t1; t1.iota(5); TEST_TRANSPOSE(t1); } { Tensor<T,6,7> t1; t1.iota(5); TEST_TRANSPOSE(t1); } { Tensor<T,17,29> t1; t1.iota(5); TEST_TRANSPOSE(t1); } // transpose expressions { Tensor<T,2,3> t1; t1.iota(5); FASTOR_EXIT_ASSERT(std::abs(sum(transpose(t1 + 0)) - sum(t1)) < BigTol); FASTOR_EXIT_ASSERT(std::abs(sum(trans(t1 + 0)) - sum(t1)) < BigTol); FASTOR_EXIT_ASSERT(std::abs(sum(transpose(t1 + t1*2 - t1 - t1)) - sum(t1)) < BigTol); FASTOR_EXIT_ASSERT(std::abs(sum(trans(t1 + t1*2 - t1 - t1)) - sum(t1)) < BigTol); } print(FGRN(BOLD("All tests passed successfully"))); } int main() { print(FBLU(BOLD("Testing tensor transpose routine: single precision"))); test_transpose<float>(); print(FBLU(BOLD("Testing tensor transpose routine: double precision"))); test_transpose<double>(); return 0; }
22.02
93
0.518619
mablanchard
7c5b8418e332dc639e4c9bc7b60fde9c073c2ce7
204
cpp
C++
src/main.cpp
JoseLuisC99/GraphDB
63735389e0637746333b404583ae8e54ea309497
[ "MIT" ]
null
null
null
src/main.cpp
JoseLuisC99/GraphDB
63735389e0637746333b404583ae8e54ea309497
[ "MIT" ]
null
null
null
src/main.cpp
JoseLuisC99/GraphDB
63735389e0637746333b404583ae8e54ea309497
[ "MIT" ]
null
null
null
#include <iostream> #include "graph/Vertex.hpp" #include "graph/Edge.hpp" #include "graph/Graph.hpp" using namespace std; int main(int argc, char** argv) { cout << "GraphDB" << endl; return 0; }
18.545455
33
0.666667
JoseLuisC99
7c630c5a5847b69203f8ac94a8f6d844da57a24c
528
cpp
C++
chapter-15/Program 1.cpp
JahanzebNawaz/Introduction-to-C-plus-plus-CPP-Chapter-Exercises
dc3cd3a0091686580aa8414f3d021fe5bb7bb513
[ "MIT" ]
null
null
null
chapter-15/Program 1.cpp
JahanzebNawaz/Introduction-to-C-plus-plus-CPP-Chapter-Exercises
dc3cd3a0091686580aa8414f3d021fe5bb7bb513
[ "MIT" ]
null
null
null
chapter-15/Program 1.cpp
JahanzebNawaz/Introduction-to-C-plus-plus-CPP-Chapter-Exercises
dc3cd3a0091686580aa8414f3d021fe5bb7bb513
[ "MIT" ]
null
null
null
/* program of inheritance */ #include<iostream> #include<conio.h> using namespace std; class move { protected: int position; public: move() { position=0; } void forward() { position++; } void show() { cout<<" Position = "<<position<<endl; } }; class move2: public move { public: void backword() { position--; } }; main() { move2 m; m.show(); m.forward(); m.show(); m.backword(); m.show(); getch(); }
11.234043
43
0.486742
JahanzebNawaz
7c637803e72b33ad45f5566aabf2d06ddf7c949e
37,796
cc
C++
Code/BBearEditor/Engine/Serializer/BBMaterial.pb.cc
xiaoxianrouzhiyou/BBearEditor
0f1b779d87c297661f9a1e66d0613df43f5fe46b
[ "MIT" ]
26
2021-06-30T02:19:30.000Z
2021-07-23T08:38:46.000Z
Code/BBearEditor/Engine/Serializer/BBMaterial.pb.cc
xiaoxianrouzhiyou/BBearEditor-2.0
0f1b779d87c297661f9a1e66d0613df43f5fe46b
[ "MIT" ]
null
null
null
Code/BBearEditor/Engine/Serializer/BBMaterial.pb.cc
xiaoxianrouzhiyou/BBearEditor-2.0
0f1b779d87c297661f9a1e66d0613df43f5fe46b
[ "MIT" ]
3
2021-09-01T08:19:30.000Z
2021-12-28T19:06:40.000Z
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: BBMaterial.proto #include "BBMaterial.pb.h" #include <algorithm> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/wire_format_lite.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> PROTOBUF_PRAGMA_INIT_SEG namespace BBSerializer { constexpr BBMaterial::BBMaterial( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : texturename_() , texturepath_() , floatname_() , floatvalue_() , vec4name_() , vec4value_() , shadername_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , vshaderpath_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , fshaderpath_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , cubemapname_(&::PROTOBUF_NAMESPACE_ID::internal::fixed_address_empty_string) , cubemappaths_(nullptr) , srcblendfunc_(0) , blendstate_(false) , cullstate_(false) , dstblendfunc_(0) , cullface_(0){} struct BBMaterialDefaultTypeInternal { constexpr BBMaterialDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~BBMaterialDefaultTypeInternal() {} union { BBMaterial _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT BBMaterialDefaultTypeInternal _BBMaterial_default_instance_; } // namespace BBSerializer static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_BBMaterial_2eproto[1]; static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_BBMaterial_2eproto = nullptr; static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_BBMaterial_2eproto = nullptr; const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_BBMaterial_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, _has_bits_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, shadername_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, vshaderpath_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, fshaderpath_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, texturename_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, texturepath_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, floatname_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, floatvalue_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, vec4name_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, vec4value_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, blendstate_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, srcblendfunc_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, dstblendfunc_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, cullstate_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, cullface_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, cubemapname_), PROTOBUF_FIELD_OFFSET(::BBSerializer::BBMaterial, cubemappaths_), 0, 1, 2, ~0u, ~0u, ~0u, ~0u, ~0u, ~0u, 6, 5, 8, 7, 9, 3, 4, }; static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, 21, sizeof(::BBSerializer::BBMaterial)}, }; static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = { reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::BBSerializer::_BBMaterial_default_instance_), }; const char descriptor_table_protodef_BBMaterial_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = "\n\020BBMaterial.proto\022\014BBSerializer\032\016BBVect" "or.proto\032\017BBCubeMap.proto\"\321\004\n\nBBMaterial" "\022\027\n\nshaderName\030\001 \001(\tH\000\210\001\001\022\030\n\013vShaderPath" "\030\002 \001(\tH\001\210\001\001\022\030\n\013fShaderPath\030\003 \001(\tH\002\210\001\001\022\023\n" "\013textureName\030\004 \003(\t\022\023\n\013texturePath\030\005 \003(\t\022" "\021\n\tfloatName\030\006 \003(\t\022\022\n\nfloatValue\030\007 \003(\002\022\020" "\n\010vec4Name\030\010 \003(\t\022+\n\tvec4Value\030\t \003(\0132\030.BB" "Serializer.BBVector4f\022\027\n\nblendState\030\n \001(" "\010H\003\210\001\001\022\031\n\014SRCBlendFunc\030\013 \001(\005H\004\210\001\001\022\031\n\014DST" "BlendFunc\030\014 \001(\005H\005\210\001\001\022\026\n\tcullState\030\r \001(\010H" "\006\210\001\001\022\025\n\010cullFace\030\016 \001(\005H\007\210\001\001\022\030\n\013cubeMapNa" "me\030\017 \001(\tH\010\210\001\001\0222\n\014cubeMapPaths\030\020 \001(\0132\027.BB" "Serializer.BBCubeMapH\t\210\001\001B\r\n\013_shaderName" "B\016\n\014_vShaderPathB\016\n\014_fShaderPathB\r\n\013_ble" "ndStateB\017\n\r_SRCBlendFuncB\017\n\r_DSTBlendFun" "cB\014\n\n_cullStateB\013\n\t_cullFaceB\016\n\014_cubeMap" "NameB\017\n\r_cubeMapPathsb\006proto3" ; static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_BBMaterial_2eproto_deps[2] = { &::descriptor_table_BBCubeMap_2eproto, &::descriptor_table_BBVector_2eproto, }; static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_BBMaterial_2eproto_once; const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_BBMaterial_2eproto = { false, false, 669, descriptor_table_protodef_BBMaterial_2eproto, "BBMaterial.proto", &descriptor_table_BBMaterial_2eproto_once, descriptor_table_BBMaterial_2eproto_deps, 2, 1, schemas, file_default_instances, TableStruct_BBMaterial_2eproto::offsets, file_level_metadata_BBMaterial_2eproto, file_level_enum_descriptors_BBMaterial_2eproto, file_level_service_descriptors_BBMaterial_2eproto, }; PROTOBUF_ATTRIBUTE_WEAK const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable* descriptor_table_BBMaterial_2eproto_getter() { return &descriptor_table_BBMaterial_2eproto; } // Force running AddDescriptors() at dynamic initialization time. PROTOBUF_ATTRIBUTE_INIT_PRIORITY static ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptorsRunner dynamic_init_dummy_BBMaterial_2eproto(&descriptor_table_BBMaterial_2eproto); namespace BBSerializer { // =================================================================== class BBMaterial::_Internal { public: using HasBits = decltype(std::declval<BBMaterial>()._has_bits_); static void set_has_shadername(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_vshaderpath(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static void set_has_fshaderpath(HasBits* has_bits) { (*has_bits)[0] |= 4u; } static void set_has_blendstate(HasBits* has_bits) { (*has_bits)[0] |= 64u; } static void set_has_srcblendfunc(HasBits* has_bits) { (*has_bits)[0] |= 32u; } static void set_has_dstblendfunc(HasBits* has_bits) { (*has_bits)[0] |= 256u; } static void set_has_cullstate(HasBits* has_bits) { (*has_bits)[0] |= 128u; } static void set_has_cullface(HasBits* has_bits) { (*has_bits)[0] |= 512u; } static void set_has_cubemapname(HasBits* has_bits) { (*has_bits)[0] |= 8u; } static const ::BBSerializer::BBCubeMap& cubemappaths(const BBMaterial* msg); static void set_has_cubemappaths(HasBits* has_bits) { (*has_bits)[0] |= 16u; } }; const ::BBSerializer::BBCubeMap& BBMaterial::_Internal::cubemappaths(const BBMaterial* msg) { return *msg->cubemappaths_; } void BBMaterial::clear_vec4value() { vec4value_.Clear(); } void BBMaterial::clear_cubemappaths() { if (GetArena() == nullptr && cubemappaths_ != nullptr) { delete cubemappaths_; } cubemappaths_ = nullptr; _has_bits_[0] &= ~0x00000010u; } BBMaterial::BBMaterial(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena), texturename_(arena), texturepath_(arena), floatname_(arena), floatvalue_(arena), vec4name_(arena), vec4value_(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:BBSerializer.BBMaterial) } BBMaterial::BBMaterial(const BBMaterial& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_), texturename_(from.texturename_), texturepath_(from.texturepath_), floatname_(from.floatname_), floatvalue_(from.floatvalue_), vec4name_(from.vec4name_), vec4value_(from.vec4value_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); shadername_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_shadername()) { shadername_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_shadername(), GetArena()); } vshaderpath_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_vshaderpath()) { vshaderpath_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_vshaderpath(), GetArena()); } fshaderpath_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_fshaderpath()) { fshaderpath_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_fshaderpath(), GetArena()); } cubemapname_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_cubemapname()) { cubemapname_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_cubemapname(), GetArena()); } if (from._internal_has_cubemappaths()) { cubemappaths_ = new ::BBSerializer::BBCubeMap(*from.cubemappaths_); } else { cubemappaths_ = nullptr; } ::memcpy(&srcblendfunc_, &from.srcblendfunc_, static_cast<size_t>(reinterpret_cast<char*>(&cullface_) - reinterpret_cast<char*>(&srcblendfunc_)) + sizeof(cullface_)); // @@protoc_insertion_point(copy_constructor:BBSerializer.BBMaterial) } void BBMaterial::SharedCtor() { shadername_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); vshaderpath_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); fshaderpath_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); cubemapname_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&cubemappaths_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&cullface_) - reinterpret_cast<char*>(&cubemappaths_)) + sizeof(cullface_)); } BBMaterial::~BBMaterial() { // @@protoc_insertion_point(destructor:BBSerializer.BBMaterial) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void BBMaterial::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); shadername_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); vshaderpath_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); fshaderpath_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); cubemapname_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (this != internal_default_instance()) delete cubemappaths_; } void BBMaterial::ArenaDtor(void* object) { BBMaterial* _this = reinterpret_cast< BBMaterial* >(object); (void)_this; } void BBMaterial::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void BBMaterial::SetCachedSize(int size) const { _cached_size_.Set(size); } void BBMaterial::Clear() { // @@protoc_insertion_point(message_clear_start:BBSerializer.BBMaterial) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; texturename_.Clear(); texturepath_.Clear(); floatname_.Clear(); floatvalue_.Clear(); vec4name_.Clear(); vec4value_.Clear(); cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000001fu) { if (cached_has_bits & 0x00000001u) { shadername_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { vshaderpath_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000004u) { fshaderpath_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000008u) { cubemapname_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000010u) { if (GetArena() == nullptr && cubemappaths_ != nullptr) { delete cubemappaths_; } cubemappaths_ = nullptr; } } if (cached_has_bits & 0x000000e0u) { ::memset(&srcblendfunc_, 0, static_cast<size_t>( reinterpret_cast<char*>(&cullstate_) - reinterpret_cast<char*>(&srcblendfunc_)) + sizeof(cullstate_)); } if (cached_has_bits & 0x00000300u) { ::memset(&dstblendfunc_, 0, static_cast<size_t>( reinterpret_cast<char*>(&cullface_) - reinterpret_cast<char*>(&dstblendfunc_)) + sizeof(cullface_)); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* BBMaterial::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // string shaderName = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { auto str = _internal_mutable_shadername(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "BBSerializer.BBMaterial.shaderName")); CHK_(ptr); } else goto handle_unusual; continue; // string vShaderPath = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { auto str = _internal_mutable_vshaderpath(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "BBSerializer.BBMaterial.vShaderPath")); CHK_(ptr); } else goto handle_unusual; continue; // string fShaderPath = 3; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { auto str = _internal_mutable_fshaderpath(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "BBSerializer.BBMaterial.fShaderPath")); CHK_(ptr); } else goto handle_unusual; continue; // repeated string textureName = 4; case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 34)) { ptr -= 1; do { ptr += 1; auto str = _internal_add_texturename(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "BBSerializer.BBMaterial.textureName")); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<34>(ptr)); } else goto handle_unusual; continue; // repeated string texturePath = 5; case 5: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 42)) { ptr -= 1; do { ptr += 1; auto str = _internal_add_texturepath(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "BBSerializer.BBMaterial.texturePath")); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<42>(ptr)); } else goto handle_unusual; continue; // repeated string floatName = 6; case 6: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 50)) { ptr -= 1; do { ptr += 1; auto str = _internal_add_floatname(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "BBSerializer.BBMaterial.floatName")); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<50>(ptr)); } else goto handle_unusual; continue; // repeated float floatValue = 7; case 7: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedFloatParser(_internal_mutable_floatvalue(), ptr, ctx); CHK_(ptr); } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 61) { _internal_add_floatvalue(::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr)); ptr += sizeof(float); } else goto handle_unusual; continue; // repeated string vec4Name = 8; case 8: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 66)) { ptr -= 1; do { ptr += 1; auto str = _internal_add_vec4name(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "BBSerializer.BBMaterial.vec4Name")); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<66>(ptr)); } else goto handle_unusual; continue; // repeated .BBSerializer.BBVector4f vec4Value = 9; case 9: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 74)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(_internal_add_vec4value(), ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<74>(ptr)); } else goto handle_unusual; continue; // bool blendState = 10; case 10: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 80)) { _Internal::set_has_blendstate(&has_bits); blendstate_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // int32 SRCBlendFunc = 11; case 11: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 88)) { _Internal::set_has_srcblendfunc(&has_bits); srcblendfunc_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // int32 DSTBlendFunc = 12; case 12: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 96)) { _Internal::set_has_dstblendfunc(&has_bits); dstblendfunc_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // bool cullState = 13; case 13: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 104)) { _Internal::set_has_cullstate(&has_bits); cullstate_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // int32 cullFace = 14; case 14: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 112)) { _Internal::set_has_cullface(&has_bits); cullface_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // string cubeMapName = 15; case 15: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 122)) { auto str = _internal_mutable_cubemapname(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(::PROTOBUF_NAMESPACE_ID::internal::VerifyUTF8(str, "BBSerializer.BBMaterial.cubeMapName")); CHK_(ptr); } else goto handle_unusual; continue; // .BBSerializer.BBCubeMap cubeMapPaths = 16; case 16: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 130)) { ptr = ctx->ParseMessage(_internal_mutable_cubemappaths(), ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* BBMaterial::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:BBSerializer.BBMaterial) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // string shaderName = 1; if (_internal_has_shadername()) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->_internal_shadername().data(), static_cast<int>(this->_internal_shadername().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "BBSerializer.BBMaterial.shaderName"); target = stream->WriteStringMaybeAliased( 1, this->_internal_shadername(), target); } // string vShaderPath = 2; if (_internal_has_vshaderpath()) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->_internal_vshaderpath().data(), static_cast<int>(this->_internal_vshaderpath().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "BBSerializer.BBMaterial.vShaderPath"); target = stream->WriteStringMaybeAliased( 2, this->_internal_vshaderpath(), target); } // string fShaderPath = 3; if (_internal_has_fshaderpath()) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->_internal_fshaderpath().data(), static_cast<int>(this->_internal_fshaderpath().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "BBSerializer.BBMaterial.fShaderPath"); target = stream->WriteStringMaybeAliased( 3, this->_internal_fshaderpath(), target); } // repeated string textureName = 4; for (int i = 0, n = this->_internal_texturename_size(); i < n; i++) { const auto& s = this->_internal_texturename(i); ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( s.data(), static_cast<int>(s.length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "BBSerializer.BBMaterial.textureName"); target = stream->WriteString(4, s, target); } // repeated string texturePath = 5; for (int i = 0, n = this->_internal_texturepath_size(); i < n; i++) { const auto& s = this->_internal_texturepath(i); ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( s.data(), static_cast<int>(s.length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "BBSerializer.BBMaterial.texturePath"); target = stream->WriteString(5, s, target); } // repeated string floatName = 6; for (int i = 0, n = this->_internal_floatname_size(); i < n; i++) { const auto& s = this->_internal_floatname(i); ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( s.data(), static_cast<int>(s.length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "BBSerializer.BBMaterial.floatName"); target = stream->WriteString(6, s, target); } // repeated float floatValue = 7; if (this->_internal_floatvalue_size() > 0) { target = stream->WriteFixedPacked(7, _internal_floatvalue(), target); } // repeated string vec4Name = 8; for (int i = 0, n = this->_internal_vec4name_size(); i < n; i++) { const auto& s = this->_internal_vec4name(i); ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( s.data(), static_cast<int>(s.length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "BBSerializer.BBMaterial.vec4Name"); target = stream->WriteString(8, s, target); } // repeated .BBSerializer.BBVector4f vec4Value = 9; for (unsigned int i = 0, n = static_cast<unsigned int>(this->_internal_vec4value_size()); i < n; i++) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage(9, this->_internal_vec4value(i), target, stream); } // bool blendState = 10; if (_internal_has_blendstate()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(10, this->_internal_blendstate(), target); } // int32 SRCBlendFunc = 11; if (_internal_has_srcblendfunc()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(11, this->_internal_srcblendfunc(), target); } // int32 DSTBlendFunc = 12; if (_internal_has_dstblendfunc()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(12, this->_internal_dstblendfunc(), target); } // bool cullState = 13; if (_internal_has_cullstate()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(13, this->_internal_cullstate(), target); } // int32 cullFace = 14; if (_internal_has_cullface()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(14, this->_internal_cullface(), target); } // string cubeMapName = 15; if (_internal_has_cubemapname()) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::VerifyUtf8String( this->_internal_cubemapname().data(), static_cast<int>(this->_internal_cubemapname().length()), ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::SERIALIZE, "BBSerializer.BBMaterial.cubeMapName"); target = stream->WriteStringMaybeAliased( 15, this->_internal_cubemapname(), target); } // .BBSerializer.BBCubeMap cubeMapPaths = 16; if (_internal_has_cubemappaths()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage( 16, _Internal::cubemappaths(this), target, stream); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:BBSerializer.BBMaterial) return target; } size_t BBMaterial::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:BBSerializer.BBMaterial) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated string textureName = 4; total_size += 1 * ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(texturename_.size()); for (int i = 0, n = texturename_.size(); i < n; i++) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( texturename_.Get(i)); } // repeated string texturePath = 5; total_size += 1 * ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(texturepath_.size()); for (int i = 0, n = texturepath_.size(); i < n; i++) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( texturepath_.Get(i)); } // repeated string floatName = 6; total_size += 1 * ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(floatname_.size()); for (int i = 0, n = floatname_.size(); i < n; i++) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( floatname_.Get(i)); } // repeated float floatValue = 7; { unsigned int count = static_cast<unsigned int>(this->_internal_floatvalue_size()); size_t data_size = 4UL * count; if (data_size > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } total_size += data_size; } // repeated string vec4Name = 8; total_size += 1 * ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(vec4name_.size()); for (int i = 0, n = vec4name_.size(); i < n; i++) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( vec4name_.Get(i)); } // repeated .BBSerializer.BBVector4f vec4Value = 9; total_size += 1UL * this->_internal_vec4value_size(); for (const auto& msg : this->vec4value_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x000000ffu) { // string shaderName = 1; if (cached_has_bits & 0x00000001u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_shadername()); } // string vShaderPath = 2; if (cached_has_bits & 0x00000002u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_vshaderpath()); } // string fShaderPath = 3; if (cached_has_bits & 0x00000004u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_fshaderpath()); } // string cubeMapName = 15; if (cached_has_bits & 0x00000008u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_cubemapname()); } // .BBSerializer.BBCubeMap cubeMapPaths = 16; if (cached_has_bits & 0x00000010u) { total_size += 2 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *cubemappaths_); } // int32 SRCBlendFunc = 11; if (cached_has_bits & 0x00000020u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_srcblendfunc()); } // bool blendState = 10; if (cached_has_bits & 0x00000040u) { total_size += 1 + 1; } // bool cullState = 13; if (cached_has_bits & 0x00000080u) { total_size += 1 + 1; } } if (cached_has_bits & 0x00000300u) { // int32 DSTBlendFunc = 12; if (cached_has_bits & 0x00000100u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_dstblendfunc()); } // int32 cullFace = 14; if (cached_has_bits & 0x00000200u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_cullface()); } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void BBMaterial::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:BBSerializer.BBMaterial) GOOGLE_DCHECK_NE(&from, this); const BBMaterial* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<BBMaterial>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:BBSerializer.BBMaterial) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:BBSerializer.BBMaterial) MergeFrom(*source); } } void BBMaterial::MergeFrom(const BBMaterial& from) { // @@protoc_insertion_point(class_specific_merge_from_start:BBSerializer.BBMaterial) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; texturename_.MergeFrom(from.texturename_); texturepath_.MergeFrom(from.texturepath_); floatname_.MergeFrom(from.floatname_); floatvalue_.MergeFrom(from.floatvalue_); vec4name_.MergeFrom(from.vec4name_); vec4value_.MergeFrom(from.vec4value_); cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x000000ffu) { if (cached_has_bits & 0x00000001u) { _internal_set_shadername(from._internal_shadername()); } if (cached_has_bits & 0x00000002u) { _internal_set_vshaderpath(from._internal_vshaderpath()); } if (cached_has_bits & 0x00000004u) { _internal_set_fshaderpath(from._internal_fshaderpath()); } if (cached_has_bits & 0x00000008u) { _internal_set_cubemapname(from._internal_cubemapname()); } if (cached_has_bits & 0x00000010u) { _internal_mutable_cubemappaths()->::BBSerializer::BBCubeMap::MergeFrom(from._internal_cubemappaths()); } if (cached_has_bits & 0x00000020u) { srcblendfunc_ = from.srcblendfunc_; } if (cached_has_bits & 0x00000040u) { blendstate_ = from.blendstate_; } if (cached_has_bits & 0x00000080u) { cullstate_ = from.cullstate_; } _has_bits_[0] |= cached_has_bits; } if (cached_has_bits & 0x00000300u) { if (cached_has_bits & 0x00000100u) { dstblendfunc_ = from.dstblendfunc_; } if (cached_has_bits & 0x00000200u) { cullface_ = from.cullface_; } _has_bits_[0] |= cached_has_bits; } } void BBMaterial::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:BBSerializer.BBMaterial) if (&from == this) return; Clear(); MergeFrom(from); } void BBMaterial::CopyFrom(const BBMaterial& from) { // @@protoc_insertion_point(class_specific_copy_from_start:BBSerializer.BBMaterial) if (&from == this) return; Clear(); MergeFrom(from); } bool BBMaterial::IsInitialized() const { return true; } void BBMaterial::InternalSwap(BBMaterial* other) { using std::swap; _internal_metadata_.Swap<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); texturename_.InternalSwap(&other->texturename_); texturepath_.InternalSwap(&other->texturepath_); floatname_.InternalSwap(&other->floatname_); floatvalue_.InternalSwap(&other->floatvalue_); vec4name_.InternalSwap(&other->vec4name_); vec4value_.InternalSwap(&other->vec4value_); shadername_.Swap(&other->shadername_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); vshaderpath_.Swap(&other->vshaderpath_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); fshaderpath_.Swap(&other->fshaderpath_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); cubemapname_.Swap(&other->cubemapname_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(BBMaterial, cullface_) + sizeof(BBMaterial::cullface_) - PROTOBUF_FIELD_OFFSET(BBMaterial, cubemappaths_)>( reinterpret_cast<char*>(&cubemappaths_), reinterpret_cast<char*>(&other->cubemappaths_)); } ::PROTOBUF_NAMESPACE_ID::Metadata BBMaterial::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_BBMaterial_2eproto_getter, &descriptor_table_BBMaterial_2eproto_once, file_level_metadata_BBMaterial_2eproto[0]); } // @@protoc_insertion_point(namespace_scope) } // namespace BBSerializer PROTOBUF_NAMESPACE_OPEN template<> PROTOBUF_NOINLINE ::BBSerializer::BBMaterial* Arena::CreateMaybeMessage< ::BBSerializer::BBMaterial >(Arena* arena) { return Arena::CreateMessageInternal< ::BBSerializer::BBMaterial >(arena); } PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc>
40.904762
172
0.707324
xiaoxianrouzhiyou
7c65564d6a6d4b54ed3b7a5ababd4394bff7452b
201
cpp
C++
3-C-And-CPlusPlus-Interview/3-6-CPlusPlusTest/3-6-4-Test4.cpp
wuping5719/JustFun
18140dc1ee314ac8b87d7a95271e4ed2ddf7acd5
[ "MIT" ]
6
2016-05-25T05:23:00.000Z
2021-10-04T09:31:28.000Z
3-C-And-CPlusPlus-Interview/3-6-CPlusPlusTest/3-6-4-Test4.cpp
wuping5719/JustFun
18140dc1ee314ac8b87d7a95271e4ed2ddf7acd5
[ "MIT" ]
null
null
null
3-C-And-CPlusPlus-Interview/3-6-CPlusPlusTest/3-6-4-Test4.cpp
wuping5719/JustFun
18140dc1ee314ac8b87d7a95271e4ed2ddf7acd5
[ "MIT" ]
2
2016-10-15T17:59:31.000Z
2018-06-06T09:44:35.000Z
#include "stdafx.h" #include<stdio.h> #include<stdlib.h> void main() { int a=-3; unsigned int b=2; long c=a+b; printf("%ld\n",c); int x=10; int y=10; x=y=++y; printf("%d %d",x,y); }
11.823529
24
0.542289
wuping5719
7c6932698dcd328d5f0ea9a9641c7efacd43d132
2,841
cpp
C++
cpp/recursionAlgorithms.cpp
chaohan/code-samples
0ae7da954a36547362924003d56a8bece845802c
[ "MIT" ]
null
null
null
cpp/recursionAlgorithms.cpp
chaohan/code-samples
0ae7da954a36547362924003d56a8bece845802c
[ "MIT" ]
null
null
null
cpp/recursionAlgorithms.cpp
chaohan/code-samples
0ae7da954a36547362924003d56a8bece845802c
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/assignment.hpp> #include <boost/math/special_functions/binomial.hpp> namespace recursionAlgorithms { using namespace std; using namespace boost::numeric::ublas; /*9.1 count ways to cover N steps by hopping either 1,2 or 3 steps at a time */ int waysToHopSlow(int N) { if (N==1 || N==0) { return 1; } if (N<0) { return 0; } return waysToHopSlow(N-1)+waysToHopSlow(N-2)+waysToHopSlow(N-3); }; int waysToHopFast(int N, std::vector<int> &cache) { if (N==0 || N==1) { return 1; } if (N<0) { return 0; } if (cache[N]>0) { return cache[N]; } cache[N] = waysToHopFast(N-1,cache) + waysToHopFast(N-2,cache) + waysToHopFast(N-3,cache); return cache[N]; }; /*9.2 Return the number of ways connecting the top-left corner of a MxN matrix/grid to the bottom-right corner, going only downward and rightward. Off-limits grid points are allow by specifying a -1 value in the cache input matrix */ int ways2D(int r, int c, matrix<int> &cache) { if (r == cache.size1()-1 && c == cache.size2()-1 ) { return 1;} if (r >= cache.size1() || c >= cache.size2() || cache(r,c) == -1) { return 0; } if (cache(r,c)>0) { return cache(r,c); } cache(r,c) = ways2D(r,c+1,cache) + ways2D(r+1,c,cache); return cache(r,c); }; template <typename dataType> void printMatrix(matrix<dataType> &mat) { for (int row=0;row<mat.size1();row++) { for (int col=0;col<mat.size2()-1;col++) { cout << mat(row,col) << " "; } cout << mat(row,mat.size2()-1) << endl; } }; }; int main() { using namespace recursionAlgorithms; using namespace boost::math; //matrix<int> input(12,1); //input <<= 1,0,1,2,2,1,3,3,3,0,10,11; // test 9.1 //int Nin = 35; //std::vector<int> cache(Nin,0); //cout << waysToHopSlow(Nin) << endl; //cout << waysToHopFast(Nin,cache) << endl; // test 9.2 int M,N; M = 10; N= 10; matrix<int> input(M,N); //input(1,1) = -1; printMatrix(input); cout << "calculated number of ways = "<< ways2D(0,0,input) << endl; cout << "true number of ways = " << binomial_coefficient<double>(M+N-2,M-1) << endl; printMatrix(input); return 0; }
30.548387
91
0.489968
chaohan
7c72de651605385eff7faae5b93f30321a5953b8
7,805
cpp
C++
D&D Wrath of Silumgar/Motor2D/UIBar.cpp
Wilhelman/DD-Shadow-over-Mystara
d4303ad87cc442414c0facb71ce9cd5564b51039
[ "MIT" ]
3
2019-06-21T04:40:16.000Z
2020-07-07T13:09:53.000Z
D&D Wrath of Silumgar/Motor2D/UIBar.cpp
Wilhelman/DD-Shadow-over-Mystara
d4303ad87cc442414c0facb71ce9cd5564b51039
[ "MIT" ]
56
2018-05-07T10:30:08.000Z
2018-05-15T08:27:06.000Z
D&D Wrath of Silumgar/Motor2D/UIBar.cpp
Wilhelman/DD-Shadow-over-Mystara
d4303ad87cc442414c0facb71ce9cd5564b51039
[ "MIT" ]
3
2019-01-03T17:24:57.000Z
2019-05-04T08:49:12.000Z
#include "ctApp.h" #include "UIBar.h" #include "ctLog.h" #include "ctInput.h" #include "ctPerfTimer.h" UIBar::UIBar(int x, int y, int max_capacity, UI_Type type, ctModule* callback, Entity* entity, UIElement* parent) : UIElement(x, y, type, parent) { this->entity = entity; this->callback = callback; bar_type = type; bar_pos.x = x; bar_pos.y = y; this->max_capacity = max_capacity; current_quantity = max_capacity; if (type == LIFEBAR) { max_width = max_player_bar_width; current_width = max_width; previous_width = max_width; bar_height = player_bar_height; lower_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 571,107,max_width,bar_height }); upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 1,107,max_width,bar_height }); } else if (type == MANABAR) { max_width = max_player_bar_width; current_width = max_width; previous_width = max_width; bar_height = player_bar_height; lower_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 0,129,max_width,bar_height }); upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 318,445,max_width,bar_height }); } else if (type == ENEMYLIFEBAR) { max_width = max_enemy_bar_width; current_width = max_width; previous_width = max_width; bar_height = enemy_bar_height; lower_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 571,110,max_width,bar_height }); upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 1,110,max_width,bar_height }); } if (bar_type != ENEMYLIFEBAR) { SetBarNumbers(); } LOG("UIBar created in x:%i, y:%i", x, y); } void UIBar::Update() { //Destroy the yellowbar after 500ms if (yellow_bar != nullptr && yellow_bar_time.ReadMs() > 500) { App->gui->DeleteUIElement(*yellow_bar); yellow_bar = nullptr; } //if (current_quantity <=0 && bar_type == LIFEBAR) { // DeleteElements(); // lower_bar = nullptr; // upper_bar = nullptr; // yellow_bar = nullptr; //} } void UIBar::LowerBar(int quantity) { //Lower width of the bar when losing hp/mana if (lower_bar != nullptr) { if (quantity<0) { if ((current_quantity - quantity) >= 0) { current_width = CalculateBarWidth(quantity); App->gui->DeleteUIElement(*upper_bar); if (bar_type == LIFEBAR) { upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 1,107,current_width,bar_height }); DrawYellowBar(); } else if (bar_type == MANABAR) { upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 317,444,current_width,bar_height }); DrawYellowBar(); } else if (bar_type == ENEMYLIFEBAR) { upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 1,110,current_width,bar_height }); DrawYellowBar(); } } else { current_width = CalculateBarWidth(-current_quantity); App->gui->DeleteUIElement(*upper_bar); if (bar_type == LIFEBAR) { upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 1,107,current_width,bar_height }); DrawYellowBar(); } else if (bar_type == MANABAR) { upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 317,444,current_width,bar_height }); DrawYellowBar(); } else if (bar_type == ENEMYLIFEBAR) { upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 1,110,current_width,bar_height }); DrawYellowBar(); } } } else if (quantity>0){ if (lower_bar != nullptr) { if ((current_quantity + quantity) < max_capacity) { current_width = CalculateBarWidth(quantity); App->gui->DeleteUIElement(*upper_bar); if (bar_type == LIFEBAR) { upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 1,107,current_width,bar_height }); } else if (bar_type == MANABAR) { upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 317,444,current_width,bar_height }); } else if (bar_type == ENEMYLIFEBAR) { upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 1,110,current_width,bar_height }); DrawYellowBar(); } } else { current_width = CalculateBarWidth((max_capacity - current_quantity)); App->gui->DeleteUIElement(*upper_bar); if (bar_type == LIFEBAR) { upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 1,107,current_width,bar_height }); } else if (bar_type == MANABAR) { upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 317,444,current_width,bar_height }); } else if (bar_type == ENEMYLIFEBAR) { upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 1,110,current_width,bar_height }); DrawYellowBar(); } } } } } if (bar_type != ENEMYLIFEBAR) { SetBarNumbers(); } } void UIBar::RecoverBar(int quantity) { //Recover width of the bar when wining hp/mana if (lower_bar != nullptr) { if ((current_quantity + quantity) < max_capacity) { current_width = CalculateBarWidth(quantity); App->gui->DeleteUIElement(*upper_bar); if (bar_type == LIFEBAR) { upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 1,107,current_width,bar_height }); } else if (bar_type == MANABAR) { upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 317,444,current_width,bar_height }); } if (bar_type == ENEMYLIFEBAR) { upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 1,110,current_width,bar_height }); } } else { current_width = CalculateBarWidth((max_capacity - current_quantity)); App->gui->DeleteUIElement(*upper_bar); if (bar_type == LIFEBAR) { upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 1,107,current_width,bar_height }); } else if (bar_type == MANABAR) { upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 317,444,current_width,bar_height }); } if (bar_type == ENEMYLIFEBAR) { upper_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 1,110,current_width,bar_height }); } } } if (bar_type != ENEMYLIFEBAR) { SetBarNumbers(); } } void UIBar::DrawYellowBar() { //Draw a yellow bar showing what you've lost if (yellow_bar != nullptr) { App->gui->DeleteUIElement(*yellow_bar); } if (current_width > 0) { yellow_bar = App->gui->AddUIImage(bar_pos.x + current_width, bar_pos.y, { 583,130,(previous_width - current_width),bar_height }); } else { yellow_bar = App->gui->AddUIImage(bar_pos.x, bar_pos.y, { 583,130,(previous_width),bar_height }); } yellow_bar_time.Start(); } void UIBar::DeleteElements() { App->gui->DeleteUIElement(*lower_bar); lower_bar = nullptr; App->gui->DeleteUIElement(*upper_bar); upper_bar = nullptr; App->gui->DeleteUIElement(*yellow_bar); yellow_bar = nullptr; App->gui->DeleteUIElement(*bar_numbers); bar_numbers = nullptr; } int UIBar::CalculateBarWidth(int quantity) { //Calculate the new bar width when losing/wining hp/mana quantity int new_width = current_width; previous_width = current_width; int new_quantity = (current_quantity + quantity); current_quantity = new_quantity; if(max_capacity != 0) new_width = (new_quantity * max_width) / max_capacity; return new_width; } int UIBar::CurrentQuantity() { return current_quantity; } void UIBar::MakeElementsInvisible() { lower_bar->non_drawable = true; upper_bar->non_drawable = true; if (yellow_bar != nullptr) { yellow_bar->non_drawable = true; } } void UIBar::MakeElementsVisible() { lower_bar->non_drawable = false; upper_bar->non_drawable = false; if (yellow_bar != nullptr) { yellow_bar->non_drawable = false; } } void UIBar::SetBarNumbers() { if (bar_numbers != nullptr) { App->gui->DeleteUIElement(*bar_numbers); } if (current_quantity<0) { current_quantity = 0; } std::string bar_nums_char = std::to_string(current_quantity) + "/" + std::to_string(max_capacity); bar_numbers = App->gui->AddUILabel(bar_pos.x + (max_width/2) - 10 , bar_pos.y + 3, bar_nums_char, { 255,255,255,255 }, 16, nullptr, nullptr, Second_Font); }
31.095618
155
0.678796
Wilhelman
7c72e74f787e49768ff10fe148f2314d278fd7a0
1,991
cpp
C++
src/source/DRV_STATUS.cpp
ManuelMcLure/TMCStepper
c425c40f0adfa24c1c21ce7d6428bcffc2c921ae
[ "MIT" ]
336
2018-03-26T13:51:46.000Z
2022-03-21T21:58:47.000Z
src/source/DRV_STATUS.cpp
ManuelMcLure/TMCStepper
c425c40f0adfa24c1c21ce7d6428bcffc2c921ae
[ "MIT" ]
218
2017-07-28T06:13:53.000Z
2022-03-26T16:41:21.000Z
src/source/DRV_STATUS.cpp
ManuelMcLure/TMCStepper
c425c40f0adfa24c1c21ce7d6428bcffc2c921ae
[ "MIT" ]
176
2018-09-11T22:16:27.000Z
2022-03-26T13:04:03.000Z
#include "TMCStepper.h" #include "TMC_MACROS.h" #define GET_REG(NS, SETTING) NS::DRV_STATUS_t r{0}; r.sr = DRV_STATUS(); return r.SETTING uint32_t TMC2130Stepper::DRV_STATUS() { return read(DRV_STATUS_t::address); } uint16_t TMC2130Stepper::sg_result(){ GET_REG(TMC2130_n, sg_result); } bool TMC2130Stepper::fsactive() { GET_REG(TMC2130_n, fsactive); } uint8_t TMC2130Stepper::cs_actual() { GET_REG(TMC2130_n, cs_actual); } bool TMC2130Stepper::stallguard() { GET_REG(TMC2130_n, stallGuard); } bool TMC2130Stepper::ot() { GET_REG(TMC2130_n, ot); } bool TMC2130Stepper::otpw() { GET_REG(TMC2130_n, otpw); } bool TMC2130Stepper::s2ga() { GET_REG(TMC2130_n, s2ga); } bool TMC2130Stepper::s2gb() { GET_REG(TMC2130_n, s2gb); } bool TMC2130Stepper::ola() { GET_REG(TMC2130_n, ola); } bool TMC2130Stepper::olb() { GET_REG(TMC2130_n, olb); } bool TMC2130Stepper::stst() { GET_REG(TMC2130_n, stst); } uint32_t TMC2208Stepper::DRV_STATUS() { return read(TMC2208_n::DRV_STATUS_t::address); } bool TMC2208Stepper::otpw() { GET_REG(TMC2208_n, otpw); } bool TMC2208Stepper::ot() { GET_REG(TMC2208_n, ot); } bool TMC2208Stepper::s2ga() { GET_REG(TMC2208_n, s2ga); } bool TMC2208Stepper::s2gb() { GET_REG(TMC2208_n, s2gb); } bool TMC2208Stepper::s2vsa() { GET_REG(TMC2208_n, s2vsa); } bool TMC2208Stepper::s2vsb() { GET_REG(TMC2208_n, s2vsb); } bool TMC2208Stepper::ola() { GET_REG(TMC2208_n, ola); } bool TMC2208Stepper::olb() { GET_REG(TMC2208_n, olb); } bool TMC2208Stepper::t120() { GET_REG(TMC2208_n, t120); } bool TMC2208Stepper::t143() { GET_REG(TMC2208_n, t143); } bool TMC2208Stepper::t150() { GET_REG(TMC2208_n, t150); } bool TMC2208Stepper::t157() { GET_REG(TMC2208_n, t157); } uint16_t TMC2208Stepper::cs_actual() { GET_REG(TMC2208_n, cs_actual); } bool TMC2208Stepper::stealth() { GET_REG(TMC2208_n, stealth); } bool TMC2208Stepper::stst() { GET_REG(TMC2208_n, stst); }
51.051282
89
0.692617
ManuelMcLure
7c7472c04ab1ade0a573cefb0c73da8759b41c18
5,786
hpp
C++
utility/common.hpp
joydit/solidframe
0539b0a1e77663ac4c701a88f56723d3e3688e8c
[ "BSL-1.0" ]
null
null
null
utility/common.hpp
joydit/solidframe
0539b0a1e77663ac4c701a88f56723d3e3688e8c
[ "BSL-1.0" ]
null
null
null
utility/common.hpp
joydit/solidframe
0539b0a1e77663ac4c701a88f56723d3e3688e8c
[ "BSL-1.0" ]
null
null
null
// utility/common.hpp // // Copyright (c) 2007, 2008 Valentin Palade (vipalade @ gmail . com) // // This file is part of SolidFrame framework. // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt. // #ifndef UTILITY_COMMON_HPP #define UTILITY_COMMON_HPP #include "system/common.hpp" namespace solid{ template <typename T> inline T tmax(const T &v1, const T &v2){ return (v1 < v2) ? v2 : v1; } template <typename T> inline T tmin(const T &v1, const T &v2){ return (v1 > v2) ? v2 : v1; } //! A fast template inline function for exchanging values template <typename T> void exchange(T &a, T &b, T &tmp){ tmp = a; a = b; b = tmp; } //! A fast template inline function for exchanging values template <typename T> void exchange(T &a, T &b){ T tmp(a); a = b; b = tmp; } #if 0 bool overflow_safe_great(const uint32 _u1, const uint32 _u2){ if(_u1 > _u2){ return (_u1 - _u2) <= (uint32)(0xffffffff/2); }else{ return (_u2 - _u1) > (uint32)(0xffffffff/2); } } #endif inline bool overflow_safe_less(const uint32 &_u1, const uint32 &_u2){ if(_u1 < _u2){ return (_u2 - _u1) <= (uint32)(0xffffffff/2); }else{ return (_u1 - _u2) > (uint32)(0xffffffff/2); } } inline bool overflow_safe_less(const uint64 &_u1, const uint64 &_u2){ if(_u1 < _u2){ return (_u2 - _u1) <= ((uint64)-1)/2; }else{ return (_u1 - _u2) > ((uint64)-1)/2; } } inline uint32 overflow_safe_max(const uint32 &_u1, const uint32 &_u2){ if(overflow_safe_less(_u1, _u2)){ return _u2; }else{ return _u1; } } inline uint64 overflow_safe_max(const uint64 &_u1, const uint64 &_u2){ if(overflow_safe_less(_u1, _u2)){ return _u2; }else{ return _u1; } } template <typename T> inline T circular_distance(const T &_v, const T &_piv, const T& _max){ if(_v >= _piv){ return _v - _piv; }else{ return _max - _piv + _v; } } inline size_t padding_size(const size_t _sz, const size_t _pad){ return ((_sz / _pad) + 1) * _pad; } inline size_t fast_padding_size(const size_t _sz, const size_t _bitpad){ return ((_sz >> _bitpad) + 1) << _bitpad; } uint8 bit_count(const uint8 _v); uint16 bit_count(const uint16 _v); uint32 bit_count(const uint32 _v); uint64 bit_count(const uint64 _v); template <typename T> struct CRCValue; template<> struct CRCValue<uint64>{ static CRCValue<uint64> check_and_create(uint64 _v); static bool check(uint64 _v); static const uint64 maximum(){ return (1ULL << 58) - 1ULL; } CRCValue(uint64 _v); CRCValue(const CRCValue<uint64> &_v):v(_v.v){} bool ok()const{ return v != (uint64)-1; } const uint64 value()const{ return v >> 6; } const uint64 crc()const{ return v & ((1ULL << 6) - 1); } operator uint64()const{ return v; } private: CRCValue(uint64 _v, bool):v(_v){} const uint64 v; }; template<> struct CRCValue<uint32>{ static CRCValue<uint32> check_and_create(uint32 _v); static bool check(uint32 _v); static const uint32 maximum(){ return (1UL << 27) - 1UL; } CRCValue(uint32 _v); CRCValue(const CRCValue<uint32> &_v):v(_v.v){} bool ok()const{ return v != (uint32)-1; } uint32 value()const{ //return v & ((1UL << 27) - 1); return v >> 5; } uint32 crc()const{ //return v >> 27; return v & ((1UL << 5) - 1); } operator uint32()const{ return v; } private: CRCValue(uint32 _v, bool):v(_v){} const uint32 v; }; template<> struct CRCValue<uint16>{ static CRCValue<uint16> check_and_create(uint16 _v); static bool check(uint16 _v); static const uint16 maximum(){ return ((1 << 12) - 1); } CRCValue(uint16 _idx); CRCValue(const CRCValue<uint16> &_v):v(_v.v){} bool ok()const{ return v != (uint16)-1; } uint16 value()const{ //return v & ((1 << 12) - 1); return v >> 4; } uint16 crc()const{ //return v >> 12; return v & ((1 << 4) - 1); } operator uint16()const{ return v; } private: CRCValue(uint16 _v, bool):v(_v){} const uint16 v; }; template<> struct CRCValue<uint8>{ static CRCValue<uint8> check_and_create(uint8 _v); static bool check(uint8 _v); static const uint8 maximum(){ return ((1 << 5) - 1); } CRCValue(uint8 _idx); CRCValue(const CRCValue<uint8> &_v):v(_v.v){} bool ok()const{ return v != (uint8)-1; } uint8 value()const{ //return v & ((1 << 5) - 1); return v >> 3; } uint8 crc()const{ //return v >> 5; return v & ((1 << 3) - 1); } operator uint8()const{ return v; } private: CRCValue(uint8 _v, bool):v(_v){} const uint8 v; }; template <int N> struct NumberType{ enum{ Number = N }; }; inline void pack(uint32 &_v, const uint16 _v1, const uint16 _v2){ _v = _v2; _v <<= 16; _v |= _v1; } inline uint32 pack(const uint16 _v1, const uint16 _v2){ uint32 v; pack(v, _v1, _v2); return v; } inline void unpack(uint16 &_v1, uint16 &_v2, const uint32 _v){ _v1 = _v & 0xffffUL; _v2 = (_v >> 16) & 0xffffUL; } extern const uint8 reverted_chars[]; inline uint32 bit_revert(const uint32 _v){ uint32 r = (((uint32)reverted_chars[_v & 0xff]) << 24); r |= (((uint32)reverted_chars[(_v >> 8) & 0xff]) << 16); r |= (((uint32)reverted_chars[(_v >> 16) & 0xff]) << 8); r |= (((uint32)reverted_chars[(_v >> 24) & 0xff]) << 0); return r; } inline uint64 bit_revert(const uint64 _v){ uint64 r = (((uint64)reverted_chars[_v & 0xff]) << 56); r |= (((uint64)reverted_chars[(_v >> 8) & 0xff]) << 48); r |= (((uint64)reverted_chars[(_v >> 16) & 0xff]) << 40); r |= (((uint64)reverted_chars[(_v >> 24) & 0xff]) << 32); r |= (((uint64)reverted_chars[(_v >> 32) & 0xff]) << 24); r |= (((uint64)reverted_chars[(_v >> 40) & 0xff]) << 16); r |= (((uint64)reverted_chars[(_v >> 48) & 0xff]) << 8); r |= (((uint64)reverted_chars[(_v >> 56) & 0xff]) << 0); return r; } }//namespace solid #endif
20.230769
89
0.636709
joydit
7c7a0027366c78fc4135120f217b0a26563d406d
1,243
hpp
C++
src/details/std_includes.hpp
spanishgum/leetcode-driver
71883bcdca946684133fbf263a1186f1758ef594
[ "MIT" ]
null
null
null
src/details/std_includes.hpp
spanishgum/leetcode-driver
71883bcdca946684133fbf263a1186f1758ef594
[ "MIT" ]
null
null
null
src/details/std_includes.hpp
spanishgum/leetcode-driver
71883bcdca946684133fbf263a1186f1758ef594
[ "MIT" ]
null
null
null
#ifndef LEET_STD_INCLUDES #define LEET_STD_INCLUDES // Utilities #include <any> #include <bitset> #include <chrono> #include <cstddef> #include <cstdlib> #include <ctime> #include <functional> #include <initializer_list> #include <optional> #include <tuple> #include <utility> #include <variant> // Numeric limits #include <cfloat> #include <cinttypes> #include <climits> #include <cstdint> #include <limits> // Strings #include <cctype> #include <cstring> #include <string> #include <string_view> // Containers #include <array> #include <deque> #include <forward_list> #include <list> #include <map> #include <queue> #include <set> #include <stack> #include <unordered_map> #include <unordered_set> #include <vector> // Iterators #include <iterator> // Algorithms #include <algorithm> // Numerics #include <cfenv> #include <cmath> #include <complex> #include <numeric> #include <random> #include <ratio> #include <valarray> // I/O #include <cstdio> #include <iomanip> #include <iostream> #include <sstream> #include <streambuf> // Regex #include <regex> // Atomic #include <atomic> // Threading #include <condition_variable> #include <future> #include <mutex> #include <shared_mutex> #include <thread> using namespace std; #endif
15.345679
29
0.730491
spanishgum
7c7a1d21ea3255ef6f49069dd2d2f724ec0f54d9
474
cpp
C++
Source/Pickup/BodyPickup.cpp
thatguyabass/Kill-O-Byte-Source
0d4dfea226514161bb9799f55359f91da0998256
[ "Apache-2.0" ]
2
2016-12-13T19:13:10.000Z
2017-08-14T04:46:52.000Z
Source/Pickup/BodyPickup.cpp
thatguyabass/Kill-O-Byte-Source
0d4dfea226514161bb9799f55359f91da0998256
[ "Apache-2.0" ]
null
null
null
Source/Pickup/BodyPickup.cpp
thatguyabass/Kill-O-Byte-Source
0d4dfea226514161bb9799f55359f91da0998256
[ "Apache-2.0" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "Snake_Project.h" #include "BodyPickup.h" #include "SnakeCharacter/SnakeLink.h" ABodyPickup::ABodyPickup(const class FObjectInitializer& PCIP) : Super(PCIP) { BodyCount = 1; PrimaryActorTick.bCanEverTick = true; } void ABodyPickup::GiveTo(ASnakeLink* Link) { for (int32 c = 0; c < BodyCount; c++) { //Link->SpawnBody(); } bCollected = true; OnRep_Collected(bCollected); }
19.75
78
0.729958
thatguyabass
75aca9ce130ac4b59f5fa9339df6ad748481735b
1,623
cpp
C++
tests/madoka/topic.cpp
cre-ne-jp/irclog2json
721f9c6f247ae9d972dff8c1b3befa36bb1e062e
[ "MIT" ]
null
null
null
tests/madoka/topic.cpp
cre-ne-jp/irclog2json
721f9c6f247ae9d972dff8c1b3befa36bb1e062e
[ "MIT" ]
8
2019-08-26T22:57:37.000Z
2021-09-11T17:35:50.000Z
tests/madoka/topic.cpp
cre-ne-jp/irclog2json
721f9c6f247ae9d972dff8c1b3befa36bb1e062e
[ "MIT" ]
null
null
null
#define _XOPEN_SOURCE #include <doctest/doctest.h> #include <ctime> #include <picojson.h> #include "message/madoka_line_parser.h" #include "message/message_base.h" #include "tests/test_helper.h" TEST_CASE("Madoka TOPIC") { using irclog2json::message::MadokaLineParser; struct tm tm_date {}; strptime("1999-02-21", "%F", &tm_date); MadokaLineParser parser{"kataribe", tm_date}; const auto m = parser.ToMessage("00:38:04 Topic of channel #kataribe by sf: " "創作TRPG語り部関係雑談:質問者・相談者歓迎(MLに全転送)"); REQUIRE(m); const auto o = m->ToJsonObject(); SUBCASE("type") { CHECK_OBJ_STR_EQ(o, "type", "TOPIC"); } SUBCASE("channel") { CHECK_OBJ_STR_EQ(o, "channel", "kataribe"); } SUBCASE("timestamp") { CHECK_OBJ_STR_EQ(o, "timestamp", "1999-02-21 00:38:04 +0900"); } SUBCASE("nick") { CHECK_OBJ_STR_EQ(o, "nick", "sf"); } SUBCASE("message") { CHECK_OBJ_STR_EQ(o, "message", "創作TRPG語り部関係雑談:質問者・相談者歓迎(MLに全転送)"); } } TEST_CASE("Madoka TOPIC containing mIRC codes") { using irclog2json::message::MadokaLineParser; struct tm tm_date {}; strptime("1999-02-21", "%F", &tm_date); MadokaLineParser parser{"kataribe", tm_date}; const auto m = parser.ToMessage( "00:38:04 Topic of channel #kataribe by sf: " "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0B\x0C\x0E\x0F" "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F" "通常の文字"); REQUIRE(m); const auto o = m->ToJsonObject(); CHECK_OBJ_STR_EQ(o, "message", "\x02\x03\x04\x0F\x11\x16\x1D\x1E\x1F通常の文字"); }
22.232877
72
0.637708
cre-ne-jp
75bbf795200ee302081f4ab835ab59176362c83d
461
hpp
C++
engine/utility/type/Color.hpp
zhec9/nemo
b719b89933ce722a14355e7ed825a76dea680501
[ "MIT" ]
null
null
null
engine/utility/type/Color.hpp
zhec9/nemo
b719b89933ce722a14355e7ed825a76dea680501
[ "MIT" ]
null
null
null
engine/utility/type/Color.hpp
zhec9/nemo
b719b89933ce722a14355e7ed825a76dea680501
[ "MIT" ]
null
null
null
#pragma once #include <SFML/Graphics/Color.hpp> namespace nemo { struct BorderColor { sf::Color v_; }; struct BackgroundColor { sf::Color v_; }; struct TextColor { sf::Color v_; }; struct TextBoxColors { BorderColor border_; BackgroundColor backgnd_; TextColor text_; TextBoxColors(const BorderColor border, const BackgroundColor backgnd, const TextColor text) : border_ (border) , backgnd_(backgnd) , text_ (text) { } }; }
13.171429
72
0.696312
zhec9
75c18c6cd22c7100d9932b21c1e61c08c544bc5d
880
cpp
C++
1SST/7LW/7task_6.cpp
AVAtarMod/University
3c784a1e109b7a6f6ea495278ec3dc126258625a
[ "BSD-3-Clause" ]
1
2021-07-31T06:55:08.000Z
2021-07-31T06:55:08.000Z
1SST/7LW/7task_6.cpp
AVAtarMod/University-C
e516aac99eabbcbe14d897239f08acf6c8e146af
[ "BSD-3-Clause" ]
1
2020-11-25T12:00:11.000Z
2021-01-13T08:51:52.000Z
1SST/7LW/7task_6.cpp
AVAtarMod/University-C
e516aac99eabbcbe14d897239f08acf6c8e146af
[ "BSD-3-Clause" ]
null
null
null
// Даны два натуральных числа A и B (A < B). Написать функцию, выводящую все числа из диапазона [A; B], которые делятся на свою наибольшую цифру. Для поиск наибольшей цифры числа реализовать отдельную функцию #include <iostream> int maxDigitInNumber(int number); int main(){ printf("\n\nВведите А и B через пробел: "); int a,b; scanf("%d %d",&a,&b); printf("Числа, соответсвующие условиям: "); for (; a <= b; a++) if (a%maxDigitInNumber(a) == 0) printf(" %d",a); printf("\n"); return 0; } int maxDigitInNumber(int number){ int maxDigitInNumber; for (int previousDigit=0; number > 0; number /= 10) { int currentDigit = number%10; if (currentDigit > previousDigit){ previousDigit = currentDigit; maxDigitInNumber = currentDigit; } } return maxDigitInNumber; }
27.5
209
0.619318
AVAtarMod
75cff7cc71e9cbc6e1c6da336bd2c926ccbfb761
2,371
cpp
C++
test/dldist_test.cpp
namreeb/string_algorithms
a91ac5752538bd06d02c390a96e831d4b084bf7d
[ "MIT" ]
null
null
null
test/dldist_test.cpp
namreeb/string_algorithms
a91ac5752538bd06d02c390a96e831d4b084bf7d
[ "MIT" ]
null
null
null
test/dldist_test.cpp
namreeb/string_algorithms
a91ac5752538bd06d02c390a96e831d4b084bf7d
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 2019 namreeb (legal@namreeb.org) http://github.com/namreeb/string_algorithms * * 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 "dldist.hpp" #include <iostream> #include <string> const struct { std::string a; std::string b; int expected_score; } tests[] = { { "test", "test", 0}, // trivial case { "test", "et", 2}, // deletion { "test", "thisisateststring", 13}, // insertions { "test", "tEst", 1}, // substitution { "test", "stet", 2}, // transposition }; int main() { auto constexpr num_tests = sizeof(tests) / sizeof(tests[0]); for (auto i = 0u; i < num_tests; ++i) { auto const score1 = nam::damerau_levenshtein_distance(tests[i].a, tests[i].b); auto const score2 = nam::damerau_levenshtein_distance(tests[i].b, tests[i].a); if (score1 != score2) std::cout << "WARNING: commutative property violation" << std::endl; std::cout << "nam::damerau_levenshtein_distance(\"" << tests[i].a << "\", \"" << tests[i].b << "\") = " << score1 << ". Expected " << tests[i].expected_score << std::endl; if (score1 != tests[i].expected_score) return EXIT_FAILURE; } return EXIT_SUCCESS; }
36.476923
111
0.645297
namreeb
75d15718c760e3149f547fc246fb041a3dd0a22c
2,923
hpp
C++
Box2D/Dynamics/JointAtty.hpp
louis-langholtz/Box2D
7c74792bf177cf36640d735de2bba0225bf7f852
[ "Zlib" ]
32
2016-10-20T05:55:04.000Z
2021-11-25T16:34:41.000Z
Box2D/Dynamics/JointAtty.hpp
louis-langholtz/Box2D
7c74792bf177cf36640d735de2bba0225bf7f852
[ "Zlib" ]
50
2017-01-07T21:40:16.000Z
2018-01-31T10:04:05.000Z
Box2D/Dynamics/JointAtty.hpp
louis-langholtz/Box2D
7c74792bf177cf36640d735de2bba0225bf7f852
[ "Zlib" ]
7
2017-02-09T10:02:02.000Z
2020-07-23T22:49:04.000Z
/* * Original work Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * Modified work Copyright (c) 2017 Louis Langholtz https://github.com/louis-langholtz/Box2D * * 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. */ #ifndef JointAtty_hpp #define JointAtty_hpp /// @file /// Declaration of the JointAtty class. #include <Box2D/Dynamics/Joints/Joint.hpp> namespace box2d { /// @brief Joint attorney. /// /// @details This class uses the "attorney-client" idiom to control the granularity of /// friend-based access to the Joint class. This is meant to help preserve and enforce /// the invariants of the Joint class. /// /// @sa https://en.wikibooks.org/wiki/More_C++_Idioms/Friendship_and_the_Attorney-Client /// class JointAtty { private: static Joint* Create(const box2d::JointDef &def) { return Joint::Create(def); } static void Destroy(const Joint* j) { Joint::Destroy(j); } static void InitVelocityConstraints(Joint& j, BodyConstraintsMap &bodies, const box2d::StepConf &step, const ConstraintSolverConf &conf) { j.InitVelocityConstraints(bodies, step, conf); } static bool SolveVelocityConstraints(Joint& j, BodyConstraintsMap &bodies, const box2d::StepConf &conf) { return j.SolveVelocityConstraints(bodies, conf); } static bool SolvePositionConstraints(Joint& j, BodyConstraintsMap &bodies, const ConstraintSolverConf &conf) { return j.SolvePositionConstraints(bodies, conf); } static bool IsIslanded(const Joint& j) noexcept { return j.IsIslanded(); } static void SetIslanded(Joint& j) noexcept { j.SetIslanded(); } static void UnsetIslanded(Joint& j) noexcept { j.UnsetIslanded(); } friend class World; }; } #endif /* JointAtty_hpp */
32.842697
116
0.640096
louis-langholtz
75d6e972d9a4b3e2aa3bcfe07af269cf53758571
2,378
cpp
C++
cpp/module1_prac/main.cpp
FinancialEngineerLab/bootstrappingSwapCurve
2b2e7b92b6a945ecf09c78f53b53227afe580195
[ "MIT" ]
null
null
null
cpp/module1_prac/main.cpp
FinancialEngineerLab/bootstrappingSwapCurve
2b2e7b92b6a945ecf09c78f53b53227afe580195
[ "MIT" ]
null
null
null
cpp/module1_prac/main.cpp
FinancialEngineerLab/bootstrappingSwapCurve
2b2e7b92b6a945ecf09c78f53b53227afe580195
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <vector> #include <iomanip> #include "utilities.hpp" #include "curvebuilder.hpp" using namespace std; int main() { ifstream infile; infile.open("data.txt"); double x; int mark = 1; vector<curveUtils> bondSeries; vector<curveUtils>::iterator bondSeries_iter = bondSeries.begin(); vector<double> parameters; while (mark) { infile >> x; if (infile) { parameters.push_back(x); } else { mark = 0; if (infile.eof()) { cout << endl; cout << '\t' << '\t' << '\t' << " --- *** End of the file ***---" << endl; } else { cout << "Wrong !! " << endl; } } } for (int i = 0, j = 0; i < parameters.size() / 3; i++) { curveUtils temp(parameters[j], parameters[j + 1], parameters[j + 2]); bondSeries.push_back(temp); j += 3; } // Constructing a complete term // for (bondSeries_iter = bondSeries.begin(); bondSeries_iter != bondSeries.end() - 1; bondSeries_iter++) { double m = ((*(bondSeries_iter + 1)).get_maturity() - (*(bondSeries_iter)).get_maturity()) / 0.5 - 1.0; if (m > 0) { double insert_coupon = (*(bondSeries_iter)).get_rawcoupon() + ((*(bondSeries_iter + 1)).get_rawcoupon() - (*(bondSeries_iter)).get_rawcoupon()) / (m + 1); double insert_maturtiy = (*bondSeries_iter).get_maturity() + 0.5; curveUtils insertBond(insert_coupon, 100, insert_maturtiy); bondSeries.insert((bondSeries_iter + 1), insertBond); bondSeries_iter = bondSeries.begin(); } } curveBuilder calculator(bondSeries); calculator.spot_rate(); calculator.discount_factor(); calculator.forward(); vector<double> spot_rate = calculator.get_result(); vector<double> discount = calculator.get_discount(); vector<double> forward = calculator.get_forward(); vector<double>::iterator it_1 = spot_rate.begin(); vector<double>::iterator it_2 = discount.begin(); vector<double>::iterator it_3 = forward.begin(); cout << endl; cout << "Tenor (M)" << "\t" << "Spot_Rate (%) " << "\t" << "\t" << "DF (%) " << "\t " << "Forwad (%) " << endl; int m = 1; for (; it_1 != spot_rate.end(); it_1++, it_2++, it_3++, ++m) { cout << setprecision(5) << m * 6 << "\t" << "\t" << "\t" << (*it_1) * 100 << "\t" << "\t" << "\t" << (*it_2) << "\t" << "\t" << "\t" << (*it_3) << endl; } return 1; }
29.358025
158
0.586207
FinancialEngineerLab
75d7330ef3ae13d656f42931b16afae3e2ee5a5a
4,300
cpp
C++
XsGameEngine/src/Renderer/OpenGL_Renderer/OpenGL_Renderer.cpp
XsAndre-L/XsGameEngine-REF
82bbb6424c9b63e0ccf381bd73c0beabce0da141
[ "Apache-2.0" ]
null
null
null
XsGameEngine/src/Renderer/OpenGL_Renderer/OpenGL_Renderer.cpp
XsAndre-L/XsGameEngine-REF
82bbb6424c9b63e0ccf381bd73c0beabce0da141
[ "Apache-2.0" ]
null
null
null
XsGameEngine/src/Renderer/OpenGL_Renderer/OpenGL_Renderer.cpp
XsAndre-L/XsGameEngine-REF
82bbb6424c9b63e0ccf381bd73c0beabce0da141
[ "Apache-2.0" ]
null
null
null
#include "OpenGL_Renderer.h" #pragma region Public Functions int OpenGL_Renderer::init_OpenGL_Renderer(GLFWwindow* newWindow) { window = newWindow; int gladStatus = gladLoadGLLoader((GLADloadproc)glfwGetProcAddress); if (gladStatus == 0) { printf("Glad initialization failed!"); glfwDestroyWindow(newWindow); return 1; } glEnable(GL_DEPTH_TEST); glEnable(GL_ARB_gl_spirv); //Allows for spir-v Shaders //TODO int width, height; glfwGetWindowSize(newWindow, &width, &height); glViewport(0, 0, width, height); shaders.CompileShaders(); glm::mat4 projection = glm::perspective(45.0f, (GLfloat)width / (GLfloat)height, 0.1f, 100.0f); shaders.SetProjection(projection); glfwSwapInterval(1); #if defined GUI_LAYER && defined OPENGL bool test = true; new_GUI_Renderer = GUI_Renderer(*newWindow, test, AssetManager); new_GUI_Renderer.createImGuiInstance(); #endif /// <summary> std::string Obj1 = "Models/plane.obj"; std::string Obj2 = "Models/basicOBJ.obj"; AssetManager.createAsset(Obj1.c_str()); AssetManager.createAsset(Obj2.c_str()); //AssetManager.addTexture("Textures/plain.png"); //AssetManager.createOpenGL_MeshModel(Obj3.c_str()); return 0; } //AT the moment this function only refreshes the View and Model Matrices void GLMmovements(OpenGL_MeshModel mod, GLuint MVPuniform, int modelIndex, const Shaders& shaders) { glm::mat4 ViewMat = shaders.GetViewMatrix(); glm::mat4 ModelMat = mod.getMatrix(); glBindBuffer(GL_UNIFORM_BUFFER, MVPuniform); glBufferSubData(GL_UNIFORM_BUFFER, 0, 64, &ModelMat); glBufferSubData(GL_UNIFORM_BUFFER, 64, 64, &ViewMat); glBindBuffer(GL_UNIFORM_BUFFER, 0); //glUniformMatrix4fv(uniformModel, 1, GL_FALSE, glm::value_ptr(model)); } void OpenGL_Renderer::draw() { if (AssetManager.Load_Model_Files) { AssetManager.createOpenGL_MeshModel(); } #if defined GUI_LAYER && defined OPENGL glClearColor(new_GUI_Renderer.clearColor.x, new_GUI_Renderer.clearColor.y, new_GUI_Renderer.clearColor.z, 1.0f); #else glClearColor(40.0f, 40.0f, 40.0f, 1.0f); #endif glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(shaders.getProgram()); for (size_t i = 0; i < AssetManager.MeshModelList.size(); i++) // TODO { GLMmovements(AssetManager.MeshModelList[i], shaders.getMvpLocation(), 0, shaders); // This sets the model Uniform //AssetManager.OpenGL_MeshModelList[i].RenderModel(); auto currModel = AssetManager.MeshModelList[i]; for (size_t i = 0; i < currModel.getMeshCount(); i++) { uint32_t materialIndex = currModel.getMeshToTex()->at(i);//meshToTex[i]; if (materialIndex < AssetManager.textureList.size() && &AssetManager.textureList[materialIndex] != nullptr) { AssetManager.textureList[materialIndex].UseTexture(); } //currModel.meshList[i].renderMesh(); currModel.getMesh(i)->renderMesh(); } } //printf("size %i",(modelList.size())); //shaders.SetDirectionalLight(&mainLight); //shaders.SetPointLight(pointLights, pointLightCount); //shinyMaterial.useMaterial(uniformSpecularIntensityLocation, uniformShininessLocation); //shaders.SetSpotLight(spotLights, spotLightCount); //glUniformMatrix4fv(shaders.getUniformView(), 1, GL_FALSE, glm::value_ptr(camera.calculateViewMatrix())); //glUniform3f(shaders.getEyePositionLocation(), camera.getCameraPosition().x, camera.getCameraPosition().y, camera.getCameraPosition().z); glUseProgram(0); #if defined GUI_LAYER && defined OPENGL OpenGL_MeshModel* mesh; if (AssetManager.MeshModelList.size() > 0) { AssetManager.MeshModelList[*AssetManager.SetSelected()].updateMatrix(); mesh = &AssetManager.MeshModelList[*AssetManager.SetSelected()]; } else { mesh = nullptr; } new_GUI_Renderer.RenderMenus<OpenGL_Assets::AllAssets*>(mesh->getTransformType(),mesh->getPosition(),mesh->getRotation(),mesh->getScale(),AssetManager.SetSelected() ,AssetManager.getAssetInfo()); //The ImGUI Function That Renders The GUI if (ImGui::GetCurrentContext()) ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); #endif glfwSwapBuffers(window); } void OpenGL_Renderer::shutdown_Renderer() { printf("Deleting Renderer\n"); #if defined GUI_LAYER && defined OPENGL new_GUI_Renderer.CleanUpGuiComponents(); new_GUI_Renderer.CleanUpGUI(); #endif } #pragma endregion
27.741935
197
0.75093
XsAndre-L
75d7d2c124375ff010f8e56e4f3b08c7be2174a2
849
cpp
C++
src/algorithms/warmup/TimeConversion.cpp
notoes/HackerRankChallenges
95f280334846a57cfc8433662a1ed0de2aacc3e9
[ "MIT" ]
null
null
null
src/algorithms/warmup/TimeConversion.cpp
notoes/HackerRankChallenges
95f280334846a57cfc8433662a1ed0de2aacc3e9
[ "MIT" ]
null
null
null
src/algorithms/warmup/TimeConversion.cpp
notoes/HackerRankChallenges
95f280334846a57cfc8433662a1ed0de2aacc3e9
[ "MIT" ]
null
null
null
/* https://www.hackerrank.com/challenges/time-conversion Given a time in AM/PM format, convert it to military (2424-hour) time. */ #include <iostream> #include <iomanip> #include <sstream> using namespace std; int string_to_int( const string& str ) { stringstream stream(str); int res; return (stream >> res) ? res : 0; } int main() { string timeStr; cin >> timeStr; string hourStr = timeStr.substr(0, 2); string minuteStr = timeStr.substr(3, 2); string secondStr = timeStr.substr(6, 2); string amPmStr = timeStr.substr(8,2); int hour = string_to_int(hourStr); if( amPmStr=="AM" ) hour = hour==12 ? 0 : hour; if( amPmStr=="PM" ) hour = hour==12 ? 12 : hour + 12; cout << setfill('0') << setw(2) << hour << ":" << minuteStr << ":" << secondStr << endl; return 0; }
22.945946
92
0.603062
notoes
75e5d14fbcb52d1ad2af711a5fc2503d16dce2aa
556
cpp
C++
src/examples/06_module/01_bank/atm.cpp
acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-blacksea2003
c3e3c7e5d08cd1b397346d209095f67714f76689
[ "MIT" ]
null
null
null
src/examples/06_module/01_bank/atm.cpp
acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-blacksea2003
c3e3c7e5d08cd1b397346d209095f67714f76689
[ "MIT" ]
null
null
null
src/examples/06_module/01_bank/atm.cpp
acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-blacksea2003
c3e3c7e5d08cd1b397346d209095f67714f76689
[ "MIT" ]
null
null
null
//atm.cpp #include "atm.h" using std::cout; using std::cin; ATM::ATM() { customers.push_back(Customer(1, "john doe")); customers.push_back(Customer(2, "mary doe")); customers.push_back(Customer(3, "john hancock")); customers.push_back(Customer(4, "mary hancock")); } void scan_card() { cout<<"enter 1 for checking 2 for saving: "; cin>>account_index; customer_index = rand() % customers.size()-1 + 1; } void ATM::display_balance() { cout<<"Balance: "<<customers[customer_index].get_account(account_index -1)<<"\n"; }
20.592593
85
0.656475
acc-cosc-1337-fall-2020
75ea5655890fd577b72626602b66c3d853426fa5
616
cpp
C++
src/common/onRead.cpp
LeandreBl/Subprocess
b45320878ca43ae0058676c93222be4a46ac8cd1
[ "Apache-2.0" ]
4
2020-12-10T20:22:53.000Z
2021-11-08T08:24:49.000Z
src/common/onRead.cpp
LeandreBl/Subprocess
b45320878ca43ae0058676c93222be4a46ac8cd1
[ "Apache-2.0" ]
null
null
null
src/common/onRead.cpp
LeandreBl/Subprocess
b45320878ca43ae0058676c93222be4a46ac8cd1
[ "Apache-2.0" ]
1
2021-11-08T08:33:22.000Z
2021-11-08T08:33:22.000Z
#include <assert.h> #include "Process.hpp" namespace lp { void Process::onReadStdout( const std::function<void(Process &process, std::stringstream &stream)> &callback) noexcept { onRead(Stdout, callback); } void Process::onReadStderr( const std::function<void(Process &process, std::stringstream &stream)> &callback) noexcept { onRead(Stderr, callback); } void Process::onRead( enum streamType stream, const std::function<void(Process &process, std::stringstream &stream)> &callback) noexcept { assert(stream != Stdin); _callbacks[stream - 1] = callback; } } // namespace lp
26.782609
98
0.699675
LeandreBl
75efbcc08d8d0e3ee914dc8da19344269d439dca
868
hpp
C++
src/designpattern/Interpret.hpp
brucexia1/DesignPattern
09dab7aaa4e3d72b64467efe3906e4e504e220c4
[ "MIT" ]
null
null
null
src/designpattern/Interpret.hpp
brucexia1/DesignPattern
09dab7aaa4e3d72b64467efe3906e4e504e220c4
[ "MIT" ]
null
null
null
src/designpattern/Interpret.hpp
brucexia1/DesignPattern
09dab7aaa4e3d72b64467efe3906e4e504e220c4
[ "MIT" ]
null
null
null
#pragma once #include <string> using namespace std; class ContextIpt; class AbstractExpression { public: virtual ~AbstractExpression(); virtual void Interpret(const ContextIpt& c) = 0; protected: AbstractExpression(); }; class TerminalExpression:public AbstractExpression { public: TerminalExpression(const string& statement); ~TerminalExpression(); void Interpret(const ContextIpt& c); protected: private: string _statement; }; class NonterminalExpression:public AbstractExpression { public: NonterminalExpression(AbstractExpression* expression,int times); ~ NonterminalExpression(); void Interpret(const ContextIpt& c); protected: private: AbstractExpression* _expression; int _times; }; class ContextIpt { public: ContextIpt(); ~ContextIpt(); void GlobalInfo(); };
18.083333
67
0.708525
brucexia1
75f0e03b43ef4d956d8b7cf47e2e63accf57452e
6,655
hpp
C++
Include/LibYT/GenericFormatter.hpp
MalteDoemer/YeetOS2
82be488ec1ed13e6558af4e248977dad317b3b85
[ "BSD-2-Clause" ]
null
null
null
Include/LibYT/GenericFormatter.hpp
MalteDoemer/YeetOS2
82be488ec1ed13e6558af4e248977dad317b3b85
[ "BSD-2-Clause" ]
null
null
null
Include/LibYT/GenericFormatter.hpp
MalteDoemer/YeetOS2
82be488ec1ed13e6558af4e248977dad317b3b85
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright 2021 Malte Dömer * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #pragma once #include "Types.hpp" #include "Platform.hpp" #include "Concepts.hpp" #include "StdLib.hpp" #include "Functions.hpp" namespace YT { class GenericFormatter { protected: enum FormatOptions { None = 0, ZeroPad = 1, Sign = 2, Plus = 4, Space = 8, Left = 16, Prefix = 32, Lowercase = 64, }; public: using OutputFunction = Function<void(char, char*, size_t, size_t)>; protected: template<IntegralType T, u8 base> requires requires { requires base >= 2 && base <= 36; } void write_integer(T value, int width, int precision, FormatOptions opts) { constexpr size_t max_buffer_size = sizeof(T) * __CHAR_BIT__; char sign, pad; char local_buffer[max_buffer_size]; const char* digits = (opts & Lowercase) ? "0123456789abcdefghjkilmnopqrstuvwxyz" : "0123456789ABCDEFGHJKILMNOPQRSTUVWXYZ"; /* Left aligned cannot be zero padded */ if (opts & Left) { opts = static_cast<FormatOptions>(opts & ~ZeroPad); } if (opts & ZeroPad) { pad = '0'; } else { pad = ' '; } if (opts & Sign) { using SignedT = typename MakeSigned<T>::Type; if (static_cast<SignedT>(value) < 0) { sign = '-'; SignedT s = static_cast<SignedT>(value); s *= -1; value = static_cast<T>(s); } else if (opts & Plus) { sign = '+'; } else if (opts & Space) { sign = ' '; } else { sign = 0; } } else { sign = 0; } /* Decrease the width if we need to display a sign */ if (sign) { width--; } /* Decrease the width if there is a prefix (0x, 0o, 0b) */ if (opts & Prefix) { switch (base) { case 16: case 8: case 2: width -= 2; break; default: break; } } int i = 0; /* Zero is a special case */ if (value == 0) { local_buffer[0] = '0'; i = 1; } for (; value; i++) { local_buffer[i] = digits[value % base]; value /= base; } if (i > precision) { precision = i; } width -= precision; if (!(opts & ZeroPad) && !(opts & Left)) { while (width > 0) { m_out_func(' ', m_buffer, m_index++, m_maxlen); width--; } } if (sign) { m_out_func(sign, m_buffer, m_index++, m_maxlen); } if (opts & Prefix) { if (base == 16) { m_out_func('0', m_buffer, m_index++, m_maxlen); m_out_func('x', m_buffer, m_index++, m_maxlen); } else if (base == 8) { m_out_func('0', m_buffer, m_index++, m_maxlen); m_out_func('o', m_buffer, m_index++, m_maxlen); } else if (base == 2) { m_out_func('0', m_buffer, m_index++, m_maxlen); m_out_func('b', m_buffer, m_index++, m_maxlen); } } if (!(opts & Left)) { while (width > 0) { m_out_func(pad, m_buffer, m_index++, m_maxlen); width--; } } while (i < precision) { m_out_func('0', m_buffer, m_index++, m_maxlen); precision--; } while (i) { m_out_func(local_buffer[--i], m_buffer, m_index++, m_maxlen); } while (width > 0) { m_out_func(' ', m_buffer, m_index++, m_maxlen); width--; } } template<FloatingPointType T> void write_float(T value, int width, int precision, FormatOptions opts) { VERIFY_NOT_REACHED(); } void write_string(const char* str, int width, int precision, FormatOptions opts) { size_t len; if (precision > 0) { len = strnlen(str, precision); } else { len = strlen(str); } width -= len; if (!(opts & Left)) { while (width > 0) { m_out_func(' ', m_buffer, m_index++, m_maxlen); width--; } } while (len--) { m_out_func(*str++, m_buffer, m_index++, m_maxlen); } while (width > 0) { m_out_func(' ', m_buffer, m_index++, m_maxlen); width--; } } void write_char(char c, int width, int precision, FormatOptions opts) { if (!(opts & Left)) { while (width > 0) { m_out_func(' ', m_buffer, m_index++, m_maxlen); width--; } m_out_func(c, m_buffer, m_index++, m_maxlen); while (width > 0) { m_out_func(' ', m_buffer, m_index++, m_maxlen); width--; } } } protected: OutputFunction m_out_func; char* m_buffer { nullptr }; size_t m_index { 0 }; size_t m_maxlen { 0 }; }; } using YT::GenericFormatter;
27.729167
115
0.518407
MalteDoemer
75f1bc7ff426f5f916c96191f9b8b555070793bb
113
cpp
C++
src/ace/ACE_wrappers/ACEXML/common/Element_Def_Builder.cpp
wfnex/OpenBRAS
b8c2cd836ae85d5307f7f5ca87573b964342bb49
[ "BSD-3-Clause" ]
8
2017-06-05T08:56:27.000Z
2020-04-08T16:50:11.000Z
src/ace/ACE_wrappers/ACEXML/common/Element_Def_Builder.cpp
wfnex/OpenBRAS
b8c2cd836ae85d5307f7f5ca87573b964342bb49
[ "BSD-3-Clause" ]
null
null
null
src/ace/ACE_wrappers/ACEXML/common/Element_Def_Builder.cpp
wfnex/OpenBRAS
b8c2cd836ae85d5307f7f5ca87573b964342bb49
[ "BSD-3-Clause" ]
17
2017-06-05T08:54:27.000Z
2021-08-29T14:19:12.000Z
#include "ACEXML/common/Element_Def_Builder.h" ACEXML_Element_Def_Builder::~ACEXML_Element_Def_Builder () { }
14.125
58
0.80531
wfnex
75f867193418ac6fda899f1462b53aaf2c76eb50
316
cpp
C++
Baekjoon Online Judge/1 ~ 9999/2501/boj-2501.cpp
kesakiyo/Competitive-Programming
e42331b28c3d8c10bd4853c8fa0ebbfc58dfa033
[ "MIT" ]
1
2019-05-17T16:16:43.000Z
2019-05-17T16:16:43.000Z
Baekjoon Online Judge/1 ~ 9999/2501/boj-2501.cpp
kesakiyo/Competitive-Programming
e42331b28c3d8c10bd4853c8fa0ebbfc58dfa033
[ "MIT" ]
null
null
null
Baekjoon Online Judge/1 ~ 9999/2501/boj-2501.cpp
kesakiyo/Competitive-Programming
e42331b28c3d8c10bd4853c8fa0ebbfc58dfa033
[ "MIT" ]
null
null
null
/* Copyright(c) 2019. Minho Cheon. All rights reserved. */ #include <iostream> using namespace std; int main() { int n, k; cin >> n >> k; int cnt = 0; for (int i = 1 ; i <= n ; ++i) { if (n % i == 0) { ++cnt; if (cnt == k) { cout << i << endl; return 0; } } } cout << 0 << endl; }
12.64
56
0.46519
kesakiyo
75ff34fbbb9647902584e07132df7b43d76b229a
878
cpp
C++
chapter08/chapter08_ex08.cpp
TingeOGinge/stroustrup_ppp
bb69533fff8a8f1890c8c866bae2030eaca1cf8b
[ "MIT" ]
170
2015-05-02T18:08:38.000Z
2018-07-31T11:35:17.000Z
chapter08/chapter08_ex08.cpp
TingeOGinge/stroustrup_ppp
bb69533fff8a8f1890c8c866bae2030eaca1cf8b
[ "MIT" ]
7
2017-01-16T02:25:20.000Z
2018-07-20T12:57:30.000Z
chapter08/chapter08_ex08.cpp
TingeOGinge/stroustrup_ppp
bb69533fff8a8f1890c8c866bae2030eaca1cf8b
[ "MIT" ]
105
2015-05-28T11:52:19.000Z
2018-07-17T14:11:25.000Z
// Chapter 08, exercise 08: write simple function randint() to produce random // numbers // Exercise 09: write function that produces random number in a given range #include "../lib_files/std_lib_facilities.h" #include<climits> unsigned int X_n = 0; // initialise seed with clock void init_seed() { X_n = 66779; } // produces a pseudo-random number in the range [0:INT_MAX] int randint() { X_n = (48271*X_n) % INT_MAX; return X_n; } // return pseudo-random int between a and b int rand_in_range(int a, int b) { if (b <= a) error("b must be larger than a"); int r = randint(); return a + double(r)/INT_MAX*(b-a); } int main() try { init_seed(); for (int i = 0; i<1000; ++i) cout << rand_in_range(950,1000) << endl; } catch (exception& e) { cerr << "exception: " << e.what() << endl; } catch (...) { cerr << "exception\n"; }
19.511111
77
0.628702
TingeOGinge
2f137773e438c14119bec747174ff6cbb6d7e89e
1,308
cpp
C++
131_Palindrome_Partitioning.cpp
AvadheshChamola/LeetCode
b0edabfa798c4e204b015f4c367bfc5acfbd8277
[ "MIT" ]
null
null
null
131_Palindrome_Partitioning.cpp
AvadheshChamola/LeetCode
b0edabfa798c4e204b015f4c367bfc5acfbd8277
[ "MIT" ]
null
null
null
131_Palindrome_Partitioning.cpp
AvadheshChamola/LeetCode
b0edabfa798c4e204b015f4c367bfc5acfbd8277
[ "MIT" ]
null
null
null
/* 131. Palindrome Partitioning Medium Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s. A palindrome string is a string that reads the same backward as forward. Example 1: Input: s = "aab" Output: [["a","a","b"],["aa","b"]] Example 2: Input: s = "a" Output: [["a"]] Constraints: 1 <= s.length <= 16 s contains only lowercase English letters. */ class Solution { bool isPalindrome(const string &s, int start,int end){ while(start<=end){ if(s[start++]!=s[end--]){ return false; } } return true; } void dfs( vector<vector<string>> &res,vector<string> &path,const string &s,int index){ if(index==s.size()){ res.push_back(path); return; } for(int i=index;i<s.size();i++){ if(isPalindrome(s,index,i)){ path.push_back(s.substr(index,i-index+1)); dfs(res,path,s,i+1); path.pop_back(); } } } public: vector<vector<string>> partition(string s) { vector<vector<string>> res; if(s.size()==0) return res; vector<string> path; dfs(res,path,s,0); return res; } };
25.647059
139
0.552752
AvadheshChamola
2f16d0d651ce51c3da4780057264f884aacf19cc
6,354
cpp
C++
master/core/third/cxxtools/demo/rpcserver.cpp
importlib/klib
a59837857689d0e60d3df6d2ebd12c3160efa794
[ "MIT" ]
4
2017-12-04T08:22:48.000Z
2019-10-26T21:44:59.000Z
master/core/third/cxxtools/demo/rpcserver.cpp
isuhao/klib
a59837857689d0e60d3df6d2ebd12c3160efa794
[ "MIT" ]
null
null
null
master/core/third/cxxtools/demo/rpcserver.cpp
isuhao/klib
a59837857689d0e60d3df6d2ebd12c3160efa794
[ "MIT" ]
4
2017-12-04T08:22:49.000Z
2018-12-27T03:20:31.000Z
/* * Copyright (C) 2009,2011 Tommi Maekitalo * * This 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 2.1 of the License, or (at your option) any later version. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* Cxxtools implements a rpc framework, which can run with 4 protocols. Xmlrpc is a simple xml based standard protocol. The spec can be found at http://www.xmlrpc.org/. Json rpc is a json based standard protocol. The sepc can be found at http://json-rpc.org. Json is less verbose than xml and therefore jsonrpc is a little faster than xmlrpc. Json rpc comes in cxxtools in 2 flavours: raw and http. And last but not least cxxtools has a own non standard binary protocol. It is faster than xmlrpc or jsonrpc but works only with cxxtools. This demo program implements a server, which runs all 4 flavours in a single event loop. */ #include <iostream> #include <cxxtools/arg.h> #include <cxxtools/log.h> #include <cxxtools/xmlrpc/service.h> #include <cxxtools/http/server.h> #include <cxxtools/bin/rpcserver.h> #include <cxxtools/json/rpcserver.h> #include <cxxtools/json/httpservice.h> #include <cxxtools/eventloop.h> //////////////////////////////////////////////////////////////////////// // This defines functions, which we want to be called remotely. // // Parameters and return values of the functions, which can be exported must be // serializable and deserializable with the cxxtools serialization framework. // For all standard types including container classes in the standard library // proper operators are defined in cxxtools. // std::string echo(const std::string& message) { std::cout << message << std::endl; return message; } double add(double a1, double a2) { return a1 + a2; } //////////////////////////////////////////////////////////////////////// // main // int main(int argc, char* argv[]) { try { // initialize logging - this reads the file log.xml from the current directory log_init(); // read the command line options // option -i <ip-address> defines the ip address of the interface, where the // server waits for connections. Default is empty, which tells the server to // listen on all local interfaces cxxtools::Arg<std::string> ip(argc, argv, 'i'); // option -p <number> specifies the port, where http requests are expected. // This port is valid for xmlrpc and json over http. It defaults to 7002. cxxtools::Arg<unsigned short> port(argc, argv, 'p', 7002); // option -b <number> specifies the port, where the binary server waits for // requests. It defaults to port 7003. cxxtools::Arg<unsigned short> bport(argc, argv, 'b', 7003); // option -j <number> specifies the port, where the json server wait for // requests. It defaults to port 7004. cxxtools::Arg<unsigned short> jport(argc, argv, 'j', 7004); std::cout << "run rpcecho server\n" << "http protocol on port "<< port.getValue() << "\n" << "binary protocol on port " << bport.getValue() << "\n" << "json protocol on port " << jport.getValue() << std::endl; // create an event loop cxxtools::EventLoop loop; // the http server is instantiated with an ip address and a port number // It will be used for xmlrpc and json over http on different urls. cxxtools::http::Server httpServer(loop, ip, port); //////////////////////////////////////////////////////////////////////// // Xmlrpc // we create an instance of the service class cxxtools::xmlrpc::Service xmlrpcService; // we register our functions xmlrpcService.registerFunction("echo", echo); xmlrpcService.registerFunction("add", add); // ... and register the service under a url httpServer.addService("/xmlrpc", xmlrpcService); //////////////////////////////////////////////////////////////////////// // Binary rpc // for the binary rpc server we define a binary server cxxtools::bin::RpcServer binServer(loop, ip, bport); // and register the functions in the server binServer.registerFunction("echo", echo); binServer.registerFunction("add", add); //////////////////////////////////////////////////////////////////////// // Json rpc // for the json rpc server we define a json server cxxtools::json::RpcServer jsonServer(loop, ip, jport); // and register the functions in the server jsonServer.registerFunction("echo", echo); jsonServer.registerFunction("add", add); //////////////////////////////////////////////////////////////////////// // Json rpc over http // for json over http we need a service object cxxtools::json::HttpService jsonhttpService; // we register our functions jsonhttpService.registerFunction("echo", echo); jsonhttpService.registerFunction("add", add); // ... and register the service under a url httpServer.addService("/jsonrpc", jsonhttpService); //////////////////////////////////////////////////////////////////////// // Run // now start the servers by running the event loop loop.run(); } catch (const std::exception& e) { std::cerr << e.what() << std::endl; } }
35.497207
82
0.64542
importlib
2f1ea34e1ec57d9bf981a0ff47629286ebdb1b2d
1,010
cpp
C++
src/cpu.cpp
KhaledYassin/CppND-System-Monitor-Project-Updated
9830ca4f7b877151b5c987b23d7682215363abdb
[ "MIT" ]
null
null
null
src/cpu.cpp
KhaledYassin/CppND-System-Monitor-Project-Updated
9830ca4f7b877151b5c987b23d7682215363abdb
[ "MIT" ]
null
null
null
src/cpu.cpp
KhaledYassin/CppND-System-Monitor-Project-Updated
9830ca4f7b877151b5c987b23d7682215363abdb
[ "MIT" ]
null
null
null
#include "cpu.h" #include <algorithm> #include <cstdlib> #include <iterator> #include <map> #include <string> #include <utility> #include <vector> #include "processor.h" const std::string CPU::kProcessesName = "processes"; const std::string CPU::kRunningProcessesName = "procs_running"; CPU::CPU(const std::string name) { this->name_ = name; } std::map<std::string, Processor>& CPU::GetCores() { return cores_; } void CPU::AddCore(const std::string name) { cores_[name] = Processor(name); } bool CPU::CoreExists(const std::string name) { return cores_.find(name) != cores_.end(); } int CPU::GetTotalProcesses() { return total_processes_; } int CPU::GetRunningProcesses() { return procs_running_; } void CPU::UpdateStatistics() { Processor::UpdateStatistics(); std::for_each(cores_.begin(), cores_.end(), [](auto& core) { core.second.UpdateStatistics(); }); total_processes_ = metrics_[kProcessesName].GetValue(); procs_running_ = metrics_[kRunningProcessesName].GetValue(); }
28.857143
77
0.709901
KhaledYassin
2f2094af3f619c1ac5179d0720e71d505601969b
1,134
cpp
C++
C++/merge_sort.cpp
Shubham56-droid/DataStruture-and-algroithms-in-C-
d6e9f7a669bfe35fb05d97150f2e9aaacd4b53a2
[ "MIT" ]
80
2021-10-05T08:30:07.000Z
2022-03-04T19:42:53.000Z
C++/merge_sort.cpp
Shubham56-droid/DataStruture-and-algroithms-in-C-
d6e9f7a669bfe35fb05d97150f2e9aaacd4b53a2
[ "MIT" ]
182
2021-10-05T08:50:50.000Z
2022-01-31T17:53:04.000Z
C++/merge_sort.cpp
Shubham56-droid/DataStruture-and-algroithms-in-C-
d6e9f7a669bfe35fb05d97150f2e9aaacd4b53a2
[ "MIT" ]
104
2021-10-05T08:45:31.000Z
2022-01-24T10:16:37.000Z
#include <bits/stdc++.h> using namespace std; void merge(int *arr, int l, int mid, int r) { int n1 = mid - l + 1, n2 = r - mid; int a[n1], b[n2]; for (int i = 0; i < n1; i++) { a[i] = arr[l + i]; } for (int i = 0; i < n2; i++) { b[i] = arr[mid + 1 + i]; } int i = 0, j = 0, k = l; while (i < n1 && j < n2) { if (a[i] < b[j]) { arr[k] = a[i]; k++, i++; } else { arr[k] = b[j]; k++, j++; } } while (i < n1) { arr[k] = a[i]; k++, i++; } while (j < n2) { arr[k] = b[j]; k++, j++; } } void mergesort(int *arr, int l, int r) { if (l >= r) return; int mid = (l + r) / 2; mergesort(arr, l, mid); mergesort(arr, mid + 1, r); merge(arr, l, mid, r); } int main() { int n; cin >> n; int arr[n]; for (int i = 0; i < n; i++) cin >> arr[i]; mergesort(arr, 0, n - 1); for (int i = 0; i < n; i++) cout << arr[i] << " "; } //Time complexity: T(n)=T(n/2)+n total=nlogn
18.590164
44
0.354497
Shubham56-droid
2f20a05df79a73a1d0c5be0b2c1734c021acba4b
5,479
hh
C++
source/Utilities/shared/CalibrationYaml.hh
DArpinoRobotics/libmultisense
d3ed760c26762eabf3d9875a2379ff435b4f4be3
[ "Unlicense" ]
null
null
null
source/Utilities/shared/CalibrationYaml.hh
DArpinoRobotics/libmultisense
d3ed760c26762eabf3d9875a2379ff435b4f4be3
[ "Unlicense" ]
null
null
null
source/Utilities/shared/CalibrationYaml.hh
DArpinoRobotics/libmultisense
d3ed760c26762eabf3d9875a2379ff435b4f4be3
[ "Unlicense" ]
null
null
null
/** * @file shared/CalibrationYaml.hh * * Copyright 2013 * Carnegie Robotics, LLC * 4501 Hatfield Street, Pittsburgh, PA 15201 * http://www.carnegierobotics.com * * 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 Carnegie Robotics, LLC 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 CARNEGIE ROBOTICS, LLC BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * **/ #ifndef CALIBRATION_YAML_HH #define CALIBRATION_YAML_HH #include <stdint.h> #include <iostream> #include <string> #include <vector> template<typename T> std::ostream& writeMatrix (std::ostream& stream, std::string const& name, uint32_t rows, uint32_t columns, T const* data) { stream << name << ": !!opencv-matrix\n"; stream << " rows: " << rows << "\n"; stream << " cols: " << columns << "\n"; stream << " dt: d\n"; stream << " data: [ "; stream.precision (17); stream << std::scientific; for (uint32_t i = 0; i < rows; i++) { if (i != 0) { stream << ",\n"; stream << " "; } for (uint32_t j = 0; j < columns; j++) { if (j != 0) { stream << ", "; } stream << data[i * columns + j]; } } stream << " ]\n"; return stream; } class Expect { private: std::string m_value; public: Expect (std::string const& value) : m_value (value) { } std::string const& value () const { return this->m_value; } }; std::istream& operator >> (std::istream& stream, Expect const& expect) { stream >> std::ws; for (std::string::const_iterator iter = expect.value ().begin (); iter != expect.value ().end (); ++iter) { if (*iter == ' ') { stream >> std::ws; continue; } if (stream.get () != *iter) { stream.clear (std::ios_base::failbit); break; } } return stream; } template<typename T> std::istream& operator >> (std::istream& stream, std::vector<T>& data) { char input; while (stream.good ()) { input = 0; stream >> input; if (input == '[') { stream >> data; } else { stream.putback (input); T value; stream >> value; data.push_back (value); } input = 0; stream >> input; if (input == ']') { break; } else if (input != ',') { stream.clear (std::ios_base::failbit); break; } } return stream; } std::istream& parseYaml (std::istream& stream, std::map<std::string, std::vector<float> >& data) { char input; while (stream.good ()) { input = 0; stream >> input; if (input == '%') { std::string comment; std::getline (stream, comment); continue; } stream.putback (input); std::string name; stream >> name; if (name.empty ()) { break; } if (name[name.size () - 1] != ':') { stream.clear (std::ios_base::failbit); break; } name.resize (name.size () - 1); std::vector<float> arrayContents; arrayContents.clear (); input = 0; stream >> input; if (input == '[') { stream >> arrayContents; } else { stream.putback (input); uint32_t rows = 0; uint32_t columns = 0; stream >> Expect ("!!opencv-matrix"); stream >> Expect ("rows:") >> rows; stream >> Expect ("cols:") >> columns; stream >> Expect ("dt: d"); stream >> Expect ("data: [") >> arrayContents; } if (stream.good()) { data.insert (std::make_pair(name, arrayContents)); } else { fprintf (stderr, "Error parsing data near array \"%s\"", name.c_str()); } } return stream; } #endif //CALIBRATION_YAML_HH
25.602804
121
0.548275
DArpinoRobotics
2f2116da52f0819186c50970bd8dc5b4ce95ad6b
857
cpp
C++
src/util/os_structs.cpp
dulingzhi/D2RMH
f3c079fb72234bfba84c9c5251f1c82fc8e5cdb2
[ "MIT" ]
125
2021-10-31T05:55:12.000Z
2022-03-30T09:15:29.000Z
src/util/os_structs.cpp
dulingzhi/D2RMH
f3c079fb72234bfba84c9c5251f1c82fc8e5cdb2
[ "MIT" ]
93
2021-10-31T11:19:37.000Z
2022-03-31T13:25:54.000Z
src/util/os_structs.cpp
dulingzhi/D2RMH
f3c079fb72234bfba84c9c5251f1c82fc8e5cdb2
[ "MIT" ]
57
2021-10-30T08:45:05.000Z
2022-03-30T04:11:21.000Z
/* * Copyright (c) 2021 Soar Qin<soarchin@gmail.com> * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE file or at * https://opensource.org/licenses/MIT. */ #include "os_structs.h" extern "C" { #if defined(_M_IX86) NtWow64QueryInformationProcess64Proc NtWow64QueryInformationProcess64; NtWow64ReadVirtualMemory64Proc NtWow64ReadVirtualMemory64; static HMODULE getNtDllMod() { static HMODULE ntdllMod = LoadLibraryA("ntdll.dll"); return ntdllMod; } #endif void osInit() { #if defined(_M_IX86) NtWow64QueryInformationProcess64 = (NtWow64QueryInformationProcess64Proc)GetProcAddress(getNtDllMod(), "NtWow64QueryInformationProcess64"); NtWow64ReadVirtualMemory64 = (NtWow64ReadVirtualMemory64Proc)GetProcAddress(getNtDllMod(), "NtWow64ReadVirtualMemory64"); #endif } }
25.969697
112
0.770128
dulingzhi
2f241a83937550facec49079a4c99c4ee60e0fce
2,451
cpp
C++
cccc/tests/lexer/location_spec.cpp
DasNaCl/old-university-projects
af1c82afec4805ea672e0c353369035b394cb69d
[ "Apache-2.0" ]
null
null
null
cccc/tests/lexer/location_spec.cpp
DasNaCl/old-university-projects
af1c82afec4805ea672e0c353369035b394cb69d
[ "Apache-2.0" ]
null
null
null
cccc/tests/lexer/location_spec.cpp
DasNaCl/old-university-projects
af1c82afec4805ea672e0c353369035b394cb69d
[ "Apache-2.0" ]
null
null
null
#include <test_suite.hpp> #include <gtest/gtest.h> #define MYTEST(Y) TEST(lexer_locations, locations_ ## Y) using namespace mhc4; static const std::string f = "location.c"; const test_suite ts(f); std::ostream& operator<<(std::ostream& os, const token& tok) { return os << tok.to_string(); } MYTEST(lf_0) { auto vec = ts.lex_all("test\na", 6); EXPECT_EQ(ts.get_identifier_token("test", 1, 1), vec[0]); EXPECT_EQ(ts.get_identifier_token("a", 2, 1), vec[1]); } MYTEST(lf_1) { auto vec = ts.lex_all("\n 123", 5); EXPECT_EQ(ts.get_numeric_token("123", 2, 2), vec[0]); } MYTEST(cr_0) { auto vec = ts.lex_all("hi\rho", 5); EXPECT_EQ(ts.get_identifier_token("hi", 1, 1), vec[0]); EXPECT_EQ(ts.get_identifier_token("ho", 2, 1), vec[1]); } MYTEST(cr_1) { auto vec = ts.lex_all("\r 123", 5); EXPECT_EQ(ts.get_numeric_token("123", 2, 2), vec[0]); } MYTEST(crlf_0) { auto vec = ts.lex_all("Welt\r\nHallo", 11); EXPECT_EQ(ts.get_identifier_token("Welt", 1, 1), vec[0]); EXPECT_EQ(ts.get_identifier_token("Hallo", 2, 1), vec[1]); } MYTEST(crlf_1) { auto vec = ts.lex_all("\r\n 123", 6); EXPECT_EQ(ts.get_numeric_token("123", 2, 2), vec[0]); } MYTEST(column) { auto vec = ts.lex_all("ab 12", 5); EXPECT_EQ(ts.get_identifier_token("ab", 1, 1), vec[0]); EXPECT_EQ(ts.get_numeric_token("12", 1, 4), vec[1]); } MYTEST(row_0) { auto vec = ts.lex_all("\nHello", 6); EXPECT_EQ(ts.get_identifier_token("Hello", 2, 1), vec[0]); } MYTEST(row_1) { auto vec = ts.lex_all("\n\nHello\n\n", 8); EXPECT_EQ(ts.get_identifier_token("Hello", 3, 1), vec[0]); } MYTEST(fail_location_0) { try { ts.lex_all("\n''", 3); ASSERT_FALSE(true) << "Expected lexing to fail for \"''\""; } catch(std::invalid_argument& arg) { EXPECT_EQ(f + ":2:2: error: Couldn\'t lex \"''\"", arg.what()); } } MYTEST(fail_location_1) { try { ts.lex_all("Hallo =\n ''", 12); ASSERT_FALSE(true) << "Expected lexing to fail for \"''\""; } catch(std::invalid_argument& arg) { EXPECT_EQ(f + ":2:4: error: Couldn\'t lex \"''\"", arg.what()); } } MYTEST(fail_location_2) { try { ts.lex_all(" ''", 3); ASSERT_FALSE(true) << "Expected lexing to fail for \"''\""; } catch(std::invalid_argument& arg) { EXPECT_EQ(f + ":1:3: error: Couldn\'t lex \"''\"", arg.what()); } }
21.690265
71
0.585883
DasNaCl
2f2c9683ffc93dc586d8d2eb08f1a7fd96ae2473
2,441
cpp
C++
rescan_file_task.cpp
tim77/qt-virustotal-uploader
d616ab0d709ff3be2eeb062d76e2338d8c2d22dd
[ "Apache-2.0" ]
227
2015-04-16T03:23:15.000Z
2022-03-28T15:54:04.000Z
rescan_file_task.cpp
tim77/qt-virustotal-uploader
d616ab0d709ff3be2eeb062d76e2338d8c2d22dd
[ "Apache-2.0" ]
10
2016-04-30T18:19:43.000Z
2021-11-17T01:41:30.000Z
rescan_file_task.cpp
tim77/qt-virustotal-uploader
d616ab0d709ff3be2eeb062d76e2338d8c2d22dd
[ "Apache-2.0" ]
75
2015-03-17T16:29:00.000Z
2022-03-05T09:19:14.000Z
/* Copyright 2014 VirusTotal S.L. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <QDebug> #include <jansson.h> #include "rescan_file_task.h" #include "VtFile.h" #include "VtResponse.h" #include "qvtfile.h" #include "vt-log.h" RescanFileTask::RescanFileTask(QVtFile *f) { file = f; } #define RESP_BUF_SIZE 255 void RescanFileTask::run(void) { int ret; struct VtFile *api = VtFile_new(); struct VtResponse *response; char *str = NULL; char buf[RESP_BUF_SIZE+1] = { 0, }; int response_code; // connect(this, SIGNAL(LogMsg(int,int,QString)),file, SLOT(RelayLogMsg(int,int,QString))); VtFile_setApiKey(api, file->GetApiKey().toStdString().c_str()); ret = VtFile_rescanHash(api, QString(file->GetSha256().toHex()).toStdString().c_str(), 0, 0, 0, NULL, false); if (ret) { qDebug() << "Error opening fetching report " << QString(file->GetSha256().toHex()) << " " << ret; file->SetState(kWaitForReport); emit LogMsg(VT_LOG_ERR, ret, "Error fetching report"); } else { response = VtFile_getResponse(api); str = VtResponse_toJSONstr(response, VT_JSON_FLAG_INDENT); if (str) { qDebug() << "report Response: " << str; free(str); } VtResponse_getVerboseMsg(response, buf, RESP_BUF_SIZE); qDebug() << "Buff: " << buf; file->SetVerboseMsg(buf); ret = VtResponse_getResponseCode(response, &response_code); if (!ret) { qDebug() << "report response code: " << response_code; if (response_code == 0) { file->SetState(kError); goto free_response; } } str = VtResponse_getString(response, "permalink"); if (str) { file->SetPermalink(str); free(str); } str = VtResponse_getString(response, "scan_id"); if (str) { file->SetScanId(str); free(str); } file->SetState(kWaitForReport); free_response: VtResponse_put(&response); } VtFile_put(&api); }
26.824176
103
0.671856
tim77
2f377ec0c59dcc50e6f5c659ac7ef33dcd8d4643
2,835
cpp
C++
JTS/CF-B/SPOJ-TOE1/test.cpp
rahulsrma26/ol_codes
dc599f5b70c14229a001c5239c366ba1b990f68b
[ "MIT" ]
2
2019-03-18T16:06:10.000Z
2019-04-07T23:17:06.000Z
JTS/CF-B/SPOJ-TOE1/test.cpp
rahulsrma26/ol_codes
dc599f5b70c14229a001c5239c366ba1b990f68b
[ "MIT" ]
null
null
null
JTS/CF-B/SPOJ-TOE1/test.cpp
rahulsrma26/ol_codes
dc599f5b70c14229a001c5239c366ba1b990f68b
[ "MIT" ]
1
2019-03-18T16:06:52.000Z
2019-03-18T16:06:52.000Z
// Date : 2019-03-27 // Author : Rahul Sharma // Problem : https://www.spoj.com/problems/TOE1/ #include <iostream> #include <string> #include <cmath> #include <unordered_set> #include <vector> using namespace std; unordered_set<string> bs; void gen(string& b, int m = 9) { if (!m) { bs.insert(b); return; } char t = (m & 1) ? 'X' : 'O'; for (int i = 0; i < 9; i++) { if (b[i] == '.') { b[i] = t; bs.insert(b); int r = 3 * (i / 3), c = i % 3; bool win = (b[r] == t && b[r + 1] == t && b[r + 2] == t) || (b[c] == t && b[c + 3] == t && b[c + 6] == t) || (b[0] == t && b[4] == t && b[8] == t) || (b[2] == t && b[4] == t && b[6] == t); if (!win) gen(b, m - 1); b[i] = '.'; } } } bool is_ttt(vector<string> m) { int nx = 0, no = 0; for (auto& r : m) { for (auto& c : r) if (c == 'X') nx++; else if (c == 'O') no++; } if (no < nx - 1 || no > nx) return false; bool wx = false, wo = false; for (int i = 0; i < 3; i++) { if (m[i][0] == m[i][1] && m[i][1] == m[i][2]) { if (m[i][0] == 'X') wx = true; else if (m[i][0] == 'O') wo = true; } if (m[0][i] == m[1][i] && m[1][i] == m[2][i]) { if (m[0][i] == 'X') wx = true; else if (m[0][i] == 'O') wo = true; } } if (m[0][0] == m[1][1] && m[1][1] == m[2][2]) { if (m[1][1] == 'X') wx = true; else if (m[1][1] == 'O') wo = true; } if (m[2][0] == m[1][1] && m[1][1] == m[0][2]) { if (m[1][1] == 'X') wx = true; else if (m[1][1] == 'O') wo = true; } if ((wx && wo) || (wx && nx != no + 1) || (wo && nx != no)) return false; return true; } void test() { const char* s = ".XO"; int comb = pow(3, 9); for (int i = 0; i < comb; i++) { string b = "........."; for (int j = i, k = 0; k < 9; k++, j /= 3) b[k] = s[j % 3]; vector<string> m; m.push_back(b.substr(0, 3)); m.push_back(b.substr(3, 3)); m.push_back(b.substr(6, 3)); bool res1 = bs.find(b) != bs.end(); bool res2 = is_ttt(m); if (res1 != res2) { cout << b << ' ' << res1 << " != " << res2 << '\n'; for (auto& r : m) cout << r << '\n'; break; } } } int main() { ios_base::sync_with_stdio(false); cin.tie(0); string s(9, '.'); bs.insert(s); gen(s); cout << bs.size() << '\n'; test(); }
25.088496
71
0.332275
rahulsrma26
2f3a585f8c11acc29e89a9df2c33acfef6177282
3,328
cpp
C++
Kiwano/base/Object.cpp
nomango96/Kiwano
51b4078624fcd6370aa9c30eb5048a538cd1877c
[ "MIT" ]
1
2019-07-17T03:25:52.000Z
2019-07-17T03:25:52.000Z
Kiwano/base/Object.cpp
nomango96/Kiwano
51b4078624fcd6370aa9c30eb5048a538cd1877c
[ "MIT" ]
null
null
null
Kiwano/base/Object.cpp
nomango96/Kiwano
51b4078624fcd6370aa9c30eb5048a538cd1877c
[ "MIT" ]
null
null
null
// Copyright (c) 2016-2018 Kiwano - Nomango // // 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 "Object.h" #include "logs.h" #include <typeinfo> namespace kiwano { namespace { bool tracing_leaks = false; Array<Object*> tracing_objects; } unsigned int Object::last_object_id = 0; Object::Object() : tracing_leak_(false) , user_data_(nullptr) , name_(nullptr) , id_(++last_object_id) { #ifdef KGE_DEBUG Object::__AddObjectToTracingList(this); #endif } Object::~Object() { if (name_) delete name_; #ifdef KGE_DEBUG Object::__RemoveObjectFromTracingList(this); #endif } void * Object::GetUserData() const { return user_data_; } void Object::SetUserData(void * data) { user_data_ = data; } void Object::SetName(String const & name) { if (IsName(name)) return; if (name.empty()) { if (name_) name_->clear(); return; } if (!name_) { name_ = new (std::nothrow) String(name); return; } *name_ = name; } String Object::DumpObject() { String name = typeid(*this).name(); return String::format(L"{ class=\"%s\" id=%d refcount=%d name=\"%s\" }", name.c_str(), GetObjectID(), GetRefCount(), GetName().c_str()); } void Object::StartTracingLeaks() { tracing_leaks = true; } void Object::StopTracingLeaks() { tracing_leaks = false; } void Object::DumpTracingObjects() { KGE_LOG(L"-------------------------- All Objects --------------------------"); for (const auto object : tracing_objects) { KGE_LOG(L"%s", object->DumpObject().c_str()); } KGE_LOG(L"------------------------- Total size: %d -------------------------", tracing_objects.size()); } Array<Object*>& kiwano::Object::__GetTracingObjects() { return tracing_objects; } void Object::__AddObjectToTracingList(Object * obj) { #ifdef KGE_DEBUG if (tracing_leaks && !obj->tracing_leak_) { obj->tracing_leak_ = true; tracing_objects.push_back(obj); } #endif } void Object::__RemoveObjectFromTracingList(Object * obj) { #ifdef KGE_DEBUG if (tracing_leaks && obj->tracing_leak_) { obj->tracing_leak_ = false; auto iter = std::find(tracing_objects.begin(), tracing_objects.end(), obj); if (iter != tracing_objects.end()) { tracing_objects.erase(iter); } } #endif } }
21.470968
105
0.669772
nomango96
2f458e81dce4bc144b554479b1386b6fc5291401
2,124
cpp
C++
Game/Game.cpp
dwarfcrank/FantasyQuest
e5a35a8631dc056db8ffbc114354244b1530eaa6
[ "MIT" ]
1
2020-05-09T20:03:04.000Z
2020-05-09T20:03:04.000Z
Game/Game.cpp
dwarfcrank/FantasyQuest
e5a35a8631dc056db8ffbc114354244b1530eaa6
[ "MIT" ]
null
null
null
Game/Game.cpp
dwarfcrank/FantasyQuest
e5a35a8631dc056db8ffbc114354244b1530eaa6
[ "MIT" ]
null
null
null
#include "pch.h" #include "Game.h" #include "Common.h" #include "InputMap.h" #include "Renderer.h" #include "Transform.h" #include "Mesh.h" #include "File.h" #include "Scene.h" #include "Camera.h" #include "Math.h" #include <SDL2/SDL.h> #include <fmt/format.h> #include <type_traits> #include <d3d11.h> #include <DirectXMath.h> #include <d3dcompiler.h> #include <wrl.h> #include <chrono> using namespace math; GameBase::GameBase(InputMap& inputs) : m_inputs(inputs) { } Game::Game(Scene& scene, InputMap& inputs) : GameBase(inputs), scene(scene) { auto doBind = [this](SDL_Keycode k, float& target, float value) { m_inputs.key(k) .down([&target, value] { target = value; }) .up([&target] { target = 0.0f; }); }; doBind(SDLK_q, angle, -turnSpeed); doBind(SDLK_e, angle, turnSpeed); doBind(SDLK_d, velocity.x, moveSpeed); doBind(SDLK_a, velocity.x, -moveSpeed); doBind(SDLK_w, velocity.z, moveSpeed); doBind(SDLK_s, velocity.z, -moveSpeed); doBind(SDLK_LEFT, lightVelocity.x, -moveSpeed); doBind(SDLK_RIGHT, lightVelocity.x, moveSpeed); doBind(SDLK_UP, lightVelocity.z, moveSpeed); doBind(SDLK_DOWN, lightVelocity.z, -moveSpeed); doBind(SDLK_r, lightVelocity.y, moveSpeed); doBind(SDLK_f, lightVelocity.y, -moveSpeed); m_inputs.onMouseMove([this](const SDL_MouseMotionEvent& event) { if ((event.state & SDL_BUTTON_RMASK) || (SDL_GetModState() & KMOD_LCTRL)) { auto x = static_cast<float>(event.xrel) / 450.0f; auto y = static_cast<float>(event.yrel) / 450.0f; m_camera.rotate(y, x); } }); } bool Game::update(float dt) { bool running = true; m_camera.move(Vector<View>(velocity.x, velocity.y, velocity.z) * dt); m_camera.move(Vector<World>(lightVelocity.x, lightVelocity.y, lightVelocity.z) * dt); m_camera.rotate(0.0f, angle * dt); return running; } void Game::render(IRenderer* r) { } const Camera& Game::getCamera() const { return m_camera; }
25.285714
90
0.629473
dwarfcrank
2f466dd0f7ac366d24718c6c25d6899f434d4072
8,206
cpp
C++
Tissue/ias_TissueIO.cpp
torressancheza/ias
a63cbf4798ce3c91d4282ac25808970c1f272a5a
[ "MIT" ]
2
2021-04-08T06:24:31.000Z
2022-03-31T10:07:15.000Z
Tissue/ias_TissueIO.cpp
torressancheza/ias
a63cbf4798ce3c91d4282ac25808970c1f272a5a
[ "MIT" ]
null
null
null
Tissue/ias_TissueIO.cpp
torressancheza/ias
a63cbf4798ce3c91d4282ac25808970c1f272a5a
[ "MIT" ]
null
null
null
// ************************************************************************************************** // ias - Interacting Active Surfaces // Project homepage: https://github.com/torressancheza/ias // Copyright (c) 2020 Alejandro Torres-Sanchez, Max Kerr Winter and Guillaume Salbreux // ************************************************************************************************** // ias is licenced under the MIT licence: // https://github.com/torressancheza/ias/blob/master/licence.txt // ************************************************************************************************** #include <fstream> #include <thread> #include "ias_Tissue.h" namespace ias { void Tissue::saveVTK(std::string prefix,std::string suffix) { using namespace std; #pragma omp parallel for for(int i = 0; i < int(_cells.size()); i++) _cells[i]->saveVTK(prefix+std::to_string(int(_cells[i]->getCellField("cellId")+0.5))+suffix+".vtu"); vector<int> cellLabels; for(auto c: _cells) cellLabels.push_back(int(c->getCellField("cellId")+0.5)); vector<int> glo_cellLbls(_nCells); MPI_Gatherv(cellLabels.data(), cellLabels.size(), MPI_INT, glo_cellLbls.data(), _nCellPart.data(), _offsetPart.data(), MPI_INT, 0, _comm); if (_myPart == 0) { string vtmname = prefix+suffix + ".vtm"; ofstream file; file.open(vtmname); file << "<VTKFile type=\"vtkMultiBlockDataSet\" version=\"1.0\"" << endl; file << "byte_order=\"LittleEndian\" header_type=\"UInt64\">" << endl; file << "<vtkMultiBlockDataSet>"<< endl; for(int i = 0; i < _nCells; i++) { file << "<DataSet index=\"" << glo_cellLbls[i] << "\" "; file << "name=\"" << glo_cellLbls[i] << "\" "; file << "file=\"" << prefix+std::to_string(glo_cellLbls[i])+suffix+".vtu"; file << "\"></DataSet>" << endl; } file << "</vtkMultiBlockDataSet>" << endl; file <<"<FieldData>" << endl; for(int i = 0; i < _tissFields.size(); i++) { file <<"<DataArray type=\"Float64\" Name=\"" << _tissFieldNames[i] <<"\" NumberOfTuples=\"1\" format=\"ascii\" RangeMin=\"" << _tissFields(i) << "\" RangeMax=\"" << _tissFields(i) << "\">" << endl; file << _tissFields(i) << endl; file << "</DataArray>" << endl; } file << "</FieldData>" << endl; file << "</VTKFile>" << endl; file.close(); } MPI_Barrier(_comm); } void Tissue::loadVTK(std::string location,std::string filename, BasisFunctionType bfType) { using namespace std; using Teuchos::RCP; using Teuchos::rcp; int nCells = 0; vector<string> fileNames; vector<double> fieldValues; if (_myPart == 0) { string name = location+filename + ".vtm"; ifstream file; string line; file.open(name); if (! file.is_open()) throw runtime_error("Could not open file "+name+"."); string errormsg = "Tissue::loadVTK: the file " + name + " is not in a format accepted by ias."; //Read first line getline(file,line); if(line != "<VTKFile type=\"vtkMultiBlockDataSet\" version=\"1.0\"") throw runtime_error(errormsg); getline(file,line); if(line != "byte_order=\"LittleEndian\" header_type=\"UInt64\">") throw runtime_error(errormsg); getline(file,line); if(line != "<vtkMultiBlockDataSet>") throw runtime_error(errormsg); while(getline (file,line)) { if(line.find("<DataSet", 0) == 0) { size_t first = line.find("file=\""); size_t last = line.find("\"><"); string file = line.substr(first+6,last-(first+6)); fileNames.push_back(file); nCells++; } else { break; } } if(line != "</vtkMultiBlockDataSet>") throw runtime_error(errormsg); getline (file,line); if(line != "<FieldData>") throw runtime_error(errormsg); while(getline (file,line)) { if(line.find("<DataArray", 0) == 0) { size_t first = line.find("Name=\""); size_t last = line.find("\" NumberOfTuples"); string name = line.substr(first+6,last-(first+6)); _tissFieldNames.push_back(name); getline (file,line); double value{}; std::istringstream s( line ); s >> value; fieldValues.push_back(value); getline (file,line); if(line != "</DataArray>") throw runtime_error(errormsg); } else { break; } } file.close(); } MPI_Bcast(&nCells, 1, MPI_INT, 0, _comm); int nTissFields{}; nTissFields = _tissFieldNames.size(); MPI_Bcast(&nTissFields, 1, MPI_INT, 0, _comm); string tissFieldNames{}; vector<char> v_tissFieldNames; if(_myPart == 0) { for(auto s: _tissFieldNames) tissFieldNames += s + ","; v_tissFieldNames = vector<char>(tissFieldNames.begin(),tissFieldNames.end()); } int sizeTissFieldNames = v_tissFieldNames.size(); MPI_Bcast(&sizeTissFieldNames, 1, MPI_INT, 0, _comm); v_tissFieldNames.resize(sizeTissFieldNames); MPI_Bcast(v_tissFieldNames.data(), sizeTissFieldNames, MPI_CHAR, 0, _comm); tissFieldNames = string(v_tissFieldNames.begin(),v_tissFieldNames.end()); _tissFieldNames.clear(); std::istringstream ss(tissFieldNames); std::string token; while(std::getline(ss, token, ',')) _tissFieldNames.push_back(token); fieldValues.resize(nTissFields); MPI_Bcast(fieldValues.data(), nTissFields, MPI_DOUBLE, 0, _comm); _tissFields.resize(nTissFields); for(int i = 0; i < nTissFields; i++) _tissFields(i) = fieldValues[i]; fileNames.resize(nCells); for(int i = 0; i < nCells; i++) { int fnamesize = fileNames[i].size(); MPI_Bcast(&fnamesize, 1, MPI_INT, 0, _comm); if (_myPart != 0) fileNames[i].resize(fnamesize); MPI_Bcast(const_cast<char*>(fileNames[i].data()), fnamesize, MPI_CHAR, 0, _comm); } _nCells = nCells; int baseLocItem = _nCells / _nParts; int remain_nItem = _nCells - baseLocItem * _nParts; int currOffs = 0; for (int p = 0; p < _nParts; p++) { int p_locnitem = (p < remain_nItem) ? (baseLocItem + 1) : (baseLocItem); _nCellPart[p] = p_locnitem; _offsetPart[p] = currOffs; currOffs += p_locnitem; } _offsetPart[_nParts] = _nCells; int loc_nCells = _nCellPart[_myPart]; for(int i = 0; i < loc_nCells; i++) { RCP<Cell> cell = rcp(new Cell()); cell->loadVTK(location+fileNames[getGlobalIdx(i)]); cell->setBasisFunctionType(bfType); cell->Update(); _cells.emplace_back(cell); } MPI_Barrier(_comm); } }
35.991228
213
0.469413
torressancheza
2f492448200f371994c36eebc26cdc03494638b8
1,284
cpp
C++
src/tMain.cpp
veljkolazic17/DOS_threads
0f5c065850143469862f1f5cb69d076a4dbd986c
[ "MIT" ]
null
null
null
src/tMain.cpp
veljkolazic17/DOS_threads
0f5c065850143469862f1f5cb69d076a4dbd986c
[ "MIT" ]
null
null
null
src/tMain.cpp
veljkolazic17/DOS_threads
0f5c065850143469862f1f5cb69d076a4dbd986c
[ "MIT" ]
null
null
null
/* * tMain.cpp * * Created on: Jul 1, 2021 * Author: OS1 */ #include "../h/tMain.h" #include "../h/ttools.h" #include "../h/IVTEntry.h" #include "../h/Iterator.h" unsigned tMain::started = 0; int userMain(int args,char* argv[]); void tMain::run(){ this->retback = userMain(args,argv); } tMain::tMain(int args,char** argv){ this->args = args; this->argv = argv; this->retback = -1; } tMain::~tMain(){ this->waitToComplete(); } Thread* tMain::clone() const{ tMain* klon = new tMain(this->args,this->argv); klon->retback = this->retback; return klon; } int tMain::getRetback()const{ return this->retback; } int tMain::execute(int args,char**argv){ if(!started){ initDefaultWrapper(); inic(); tMain tmain(args,argv); tmain.start(); tmain.waitToComplete(); int retback = tmain.getRetback(); restore(); tMain::started = 1; return retback; } //TODO pitanje da li linija ispod treba da stoji tMain::restoreIVT(); return -1; } void tMain::restoreIVT(){ Iterator* iterator = new Iterator((List*)Shared::IVTEntries); IVTEntry* entry = NULL; while((entry = (IVTEntry*)iterator->iterateNext()) != NULL){ delete entry; } Shared::IVTEntries->purge(); delete iterator; }
18.882353
63
0.61838
veljkolazic17
2f4f64ca40b575480983d6d30bc1ac115aee7c6e
5,563
hpp
C++
cpp/include/eop/intrinsics.hpp
asefahmed56/elements-of-programming
2176d4a086ad52d73f1dc3c0cd7a97351766efd7
[ "MIT" ]
1
2020-04-09T06:16:48.000Z
2020-04-09T06:16:48.000Z
cpp/include/eop/intrinsics.hpp
asefahmed56/elements-of-programming
2176d4a086ad52d73f1dc3c0cd7a97351766efd7
[ "MIT" ]
null
null
null
cpp/include/eop/intrinsics.hpp
asefahmed56/elements-of-programming
2176d4a086ad52d73f1dc3c0cd7a97351766efd7
[ "MIT" ]
null
null
null
#ifndef EOP_INTRINSICS_HPP #define EOP_INTRINSICS_HPP #include "concepts.hpp" namespace eop { /** * @brief Method for construction * * Precondition: $v$ refers to raw memory, not an object * Postcondition: $v$ is in a partially-formed state * * @tparam ContainerType A container to store heterogeneous * constructible types * @tparam _Tp A constructible type * @tparam Args Other constructible types * @param p The container, passed by constant lvalue reference */ template < template< typename, typename... > class ContainerType, constructible _Tp, constructible... Args > void construct(const ContainerType<_Tp, Args...>& p) { static_assert(std::is_constructible_v<_Tp> && std::is_constructible_v<Args...>); for (const auto& v : p) { new (&v) _Tp(); } } /** * @brief Method for construction, with an initializer for * members * * Precondition: $v$ refers to raw memory, not an object * Postcondition: Default makes $v = initializer$ * Override $\func{construct}$ to specialize construction * of part of a container * * @tparam ContainerType A container to store heterogeneous * constructible types * @tparam _Tp A constructible type * @tparam Args Other constructible types * @tparam U An * @param p The container, passed by constant lvalue reference * @param initializer The initializer, passed by constant lvalue * reference */ template < template< typename, typename... > class ContainerType, constructible _Tp, constructible... Args, constructible U > void construct(const ContainerType<_Tp, Args...>& p, const U& initializer) { static_assert(std::is_constructible_v<_Tp> && std::is_constructible_v<Args...>); for (const auto& v : p) { new (&v) _Tp(initializer); } } /** * @brief Method for destruction * * Precondition: $v$ is in a partially-formed state * Postcondition: $v$ refers to raw memory, not an object * * @tparam ContainerType A container to store heterogeneous * destructible types * @tparam _Tp A destructible type * @tparam Args Other destructible types * @param p The container, passed by constant lvalue reference */ template < template< typename, typename... > class ContainerType, destructible _Tp, destructible... Args > void destruct(const ContainerType<_Tp, Args...>& p) { static_assert(std::is_destructible_v<_Tp> && std::is_destructible_v<Args...>); for (const auto& v : p) { v.~_Tp(); } } /** * @brief Method for destruction, with a finalizer for members * * Precondition: $v$ is in a partially-formed state * Postcondition: $v$ refers to raw memory, not an object * Override $\func{destruct}$ to specialize destruction of * part of a container * * @tparam ContainerType A container to store heterogeneous * destructible types * @tparam _Tp A destructible type * @tparam Args Other destructible types * @tparam U A finalizer * @param p The container, passed by constant lvalue reference * @param finalizer The finalizer, passed by lvalue reference */ template< template< typename, typename... > class ContainerType, destructible _Tp, destructible... Args, destructible U > void destruct(const ContainerType<_Tp, Args...>& p, U& finalizer) { static_assert(std::is_destructible_v<_Tp> && std::is_destructible_v<Args...>); for (const auto& v : p) { destruct(v); } } /** * @brief Prefix notation for a raw pointer * */ template< typename _Tp > using raw_ptr = _Tp*; /** * @brief Address method to construct a raw * pointer from a memory location * * @tparam _Tp An object type for a partially formed object * from which a pointer type is constructed */ template< partially_formed _Tp > eop::raw_ptr<_Tp> ptr_construct(_Tp&& x) { static_assert(eop::is_partially_formed_v<_Tp>); return &x; } /** * @brief Forwarding method to construct a unique * pointer * * @tparam _Tp An object type for a partially formed object * from which a unique pointer is constructed * @tparam Args Argument types * @param args Arguments * @return std::unique_ptr<_Tp> */ template< partially_formed _Tp, partially_formed... Args > std::unique_ptr<_Tp> ptr_construct(Args&&... args) { static_assert(eop::is_partially_formed_v<_Tp>); return std::unique_ptr<_Tp>(construct(_Tp(std::forward<Args>(args)...))); } /** * @brief Forwarding method to construct a shared * pointer * * @tparam _Tp An object type for a partially formed object from * which a shared pointer is constructed * @tparam Args Argument types * @param args Arguments * @return std::shared_ptr<_Tp> */ template< partially_formed _Tp, partially_formed... Args > std::shared_ptr<_Tp> ptr_construct(Args&&... args) { static_assert(eop::is_partially_formed_v<_Tp>); return std::shared_ptr<_Tp>(construct(_Tp(std::forward<Args>(args)...))); } } // namespace eop #endif // !EOP_IMTRINSICS_HPP
32.723529
81
0.621967
asefahmed56
016c679fcde0745331f83466ad7d22c792f30040
2,678
cpp
C++
frequency.cpp
scross99/cryptanalysis-gui
a3149972f1877889172bee9e969f3dc8b243e6ae
[ "MIT" ]
null
null
null
frequency.cpp
scross99/cryptanalysis-gui
a3149972f1877889172bee9e969f3dc8b243e6ae
[ "MIT" ]
null
null
null
frequency.cpp
scross99/cryptanalysis-gui
a3149972f1877889172bee9e969f3dc8b243e6ae
[ "MIT" ]
null
null
null
#include <wx/wx.h> #include <wx/listctrl.h> #include <cstdlib> #include <iostream> #include "frequency.h" #include "ids.h" #include "english.h" BEGIN_EVENT_TABLE(WA_Frequency, wxPanel) EVT_TEXT(frequency_txt, WA_Frequency::on_txt_changed) END_EVENT_TABLE() WA_Frequency::WA_Frequency(wxWindow * parent) : wxPanel(parent, wxID_ANY){ txt = new wxTextCtrl(this, frequency_txt, wxT(""), wxDefaultPosition, wxDefaultSize, wxTE_MULTILINE); list = new wxListCtrl(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLC_REPORT); list->InsertColumn(0, wxT("Char"), wxLIST_FORMAT_CENTER); list->InsertColumn(1, wxT("Freq"), wxLIST_FORMAT_CENTER); list->InsertColumn(2, wxT("Match"), wxLIST_FORMAT_CENTER); main_sizer = new wxBoxSizer(wxHORIZONTAL); main_sizer->Add(txt, 2, wxEXPAND | wxALL, 3); main_sizer->Add(list, 1, wxEXPAND | wxALL, 3); SetAutoLayout(TRUE); SetSizer(main_sizer); } static int wxCALLBACK freq_comp(long item1, long item2, long sortData){ if(item1 > item2){ return -1; }else if(item1 < item2){ return 1; }else{ return 0; } return 0; } void WA_Frequency::on_txt_changed(wxCommandEvent& event){ unsigned int freq[256]; wxString data = txt->GetValue(); unsigned int len = data.Len(); unsigned int next_id = 0; unsigned int total_freq = 0; //char a, b; /*double eng_freq[] = {0.12702, 0.09056, 0.08167, 0.07507, 0.06966, 0.06749, 0.06327, 0.06094, 0.05987, 0.04253, 0.04025, 0.02782, 0.02758, 0.02406, 0.02360, 0.02228, 0.02015, 0.01974, 0.01929, 0.01492, 0.00978, 0.00772, 0.00153, 0.00150, 0.00095, 0.00074};*/ char eng_cfreq[] = {'e', 't', 'a', 'o', 'i', 'n', 's', 'h', 'r', 'd', 'l', 'c', 'u', 'm', 'w', 'f', 'g', 'y', 'p', 'b', 'v', 'k', 'j', 'x', 'q', 'z'}; list->DeleteAllItems(); //initialise frequency array to 0 for(unsigned int p = 0; p < 256; p++){ freq[p] = 0; } //calculate the frequency of each character for(unsigned int i = 0; i < len; i++){ if(!isspace(data[i])){ freq[int(data[i])]++; total_freq++; } } //add frequencies to list for(unsigned int w = 0; w < 256; w++){ if(freq[w] > 0){ list->InsertItem(next_id, wxString::Format(wxT("%c"), char(w))); list->SetItemData(next_id, long(freq[w])); list->SetItem(next_id, 1, wxString::Format(wxT("%.2f%%"), float(100 * freq[w]) / float(total_freq))); list->SetItem(next_id, 2, wxT("?")); next_id++; } } list->SortItems(freq_comp, 0); for(unsigned int q = 0; q < 26; q++){ list->SetItem(q, 2, wxString::Format(wxT("%c"), eng_cfreq[q])); } } WA_Frequency::~WA_Frequency(){ }
27.050505
105
0.616878
scross99
017157ae72a7def5c133dd4127665f444dda75e7
2,625
cpp
C++
src/AppLines/b3CopyProperty.cpp
stmork/blz3
275e24681cb1493319cd0a50e691feb86182f6f0
[ "BSD-3-Clause" ]
null
null
null
src/AppLines/b3CopyProperty.cpp
stmork/blz3
275e24681cb1493319cd0a50e691feb86182f6f0
[ "BSD-3-Clause" ]
null
null
null
src/AppLines/b3CopyProperty.cpp
stmork/blz3
275e24681cb1493319cd0a50e691feb86182f6f0
[ "BSD-3-Clause" ]
1
2022-01-07T15:58:38.000Z
2022-01-07T15:58:38.000Z
/* ** ** $Filename: b3CopyProperty.cpp $ ** $Release: Dortmund 2005 $ ** $Revision$ ** $Date$ ** $Author$ ** $Developer: Steffen A. Mork $ ** ** Blizzard III - Select shape property copy modes ** ** (C) Copyright 2005 Steffen A. Mork ** All Rights Reserved ** ** */ /************************************************************************* ** ** ** Lines III includes ** ** ** *************************************************************************/ #include "AppLinesInclude.h" #include "b3CopyProperty.h" /************************************************************************* ** ** ** DlgCopyProperties implementation ** ** ** *************************************************************************/ void b3CopyPropertyInfo::b3Add( b3Shape *srcShape, b3Shape *dstShape, b3Base<b3Item> *srcBase, b3Base<b3Item> *dstBase) { b3CopyPropertyItem item; srcShape->b3Store(); item.m_Original.b3InitBase(srcBase->b3GetClass()); item.m_Cloned.b3InitBase(srcBase->b3GetClass()); item.m_DstBase = dstBase; item.m_Shape = dstShape; b3World::b3CloneBase(srcBase,&item.m_Cloned); m_Shapes.b3Add(item); } void b3CopyPropertyInfo::b3Undo() { b3_count i,max = m_Shapes.b3GetCount(); for (i = 0;i < max;i++) { b3CopyPropertyItem &item = m_Shapes[i]; item.m_Cloned.b3MoveFrom(item.m_DstBase); item.m_DstBase->b3MoveFrom(&item.m_Original); b3RecomputeShape(item.m_Shape, item.m_DstBase->b3GetClass()); } } void b3CopyPropertyInfo::b3Redo() { b3_count i,max = m_Shapes.b3GetCount(); for (i = 0;i < max;i++) { b3CopyPropertyItem &item = m_Shapes[i]; item.m_Original.b3MoveFrom(item.m_DstBase); item.m_DstBase->b3MoveFrom(&item.m_Cloned); b3RecomputeShape(item.m_Shape, item.m_DstBase->b3GetClass()); } } void b3CopyPropertyInfo::b3Delete(b3_bool done) { b3_count i,max = m_Shapes.b3GetCount(); if (done) { for (i = 0;i < max;i++) { m_Shapes[i].m_Original.b3Free(); } } else { for (i = 0;i < max;i++) { m_Shapes[i].m_Cloned.b3Free(); } } } void b3CopyPropertyInfo::b3RecomputeShape(b3Shape *shape,b3_u32 surface_class) { switch(surface_class) { case CLASS_MATERIAL: shape->b3RecomputeMaterial(); break; case CLASS_CONDITION: shape->b3RecomputeIndices(); break; } }
23.4375
78
0.508571
stmork
017294bdd75e366ade8483a96b4009bdd8b258bd
723
cpp
C++
Train/Sheet/Sheet-B/extra/extra 01 - 15/09.[Decoding].cpp
mohamedGamalAbuGalala/Practice
2a5fa3bdaf995d0c304f04231e1a69e6960f72c8
[ "MIT" ]
1
2019-12-19T06:51:20.000Z
2019-12-19T06:51:20.000Z
Train/Sheet/Sheet-B/extra/extra 01 - 15/09.[Decoding].cpp
mohamedGamalAbuGalala/Practice
2a5fa3bdaf995d0c304f04231e1a69e6960f72c8
[ "MIT" ]
null
null
null
Train/Sheet/Sheet-B/extra/extra 01 - 15/09.[Decoding].cpp
mohamedGamalAbuGalala/Practice
2a5fa3bdaf995d0c304f04231e1a69e6960f72c8
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; void fl() { #ifndef ONLINE_JUDGE freopen("in.txt", "r", stdin); // freopen("ot.txt", "w", stdout); #else // freopen("jumping.in", "r", stdin); // HERE #endif } //////////////////////////////////////////////////////////////////////////////////////////////// // snippet :: dinp , dhelp , dvec , lli , dfor , dcons , dbit int main() { // dfil fl(); //TODO int n, l, r; string a, b; cin >> n >> a, b = a; if (n & 1) l = r = (n / 2); else l = r = ((n - 2) / 2), r++; bool fl = 1; for (auto ch : a) { if ((n & 1) and l == r) b[l] = ch, l--, r++; else if (fl) b[l] = ch, fl ^= 1, l--; else if (!fl) b[r] = ch, fl ^= 1, r++; } cout << b; return 0; }
20.083333
96
0.410788
mohamedGamalAbuGalala
0173df37d6ce5df5d2b00719a7859743b786c0f8
2,393
cpp
C++
src/tibb/src/Modules/UI/BlackBerry/ProgressBar/TiUIProgressBarProxy.cpp
ssaracut/titanium_mobile_blackberry
952a8100086dcc625584e33abc2dc03340cbb219
[ "Apache-2.0" ]
3
2015-03-07T15:41:18.000Z
2015-11-05T05:07:45.000Z
src/tibb/src/Modules/UI/BlackBerry/ProgressBar/TiUIProgressBarProxy.cpp
ssaracut/titanium_mobile_blackberry
952a8100086dcc625584e33abc2dc03340cbb219
[ "Apache-2.0" ]
1
2015-04-12T11:50:33.000Z
2015-04-12T21:13:19.000Z
src/tibb/src/Modules/UI/BlackBerry/ProgressBar/TiUIProgressBarProxy.cpp
ssaracut/titanium_mobile_blackberry
952a8100086dcc625584e33abc2dc03340cbb219
[ "Apache-2.0" ]
5
2015-01-13T17:14:41.000Z
2015-05-25T16:54:26.000Z
/** * Appcelerator Titanium Mobile * Copyright (c) 2014 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ #include "TiUIProgressBarProxy.h" #include "TiUIProgressBar.h" namespace TiUI { TiUIProgressBarProxy::TiUIProgressBarProxy(const char* name) : Ti::TiViewProxy(name) { createPropertySetterGetter("color", _setColor, _getColor); createPropertySetterGetter("font", _setFont, _getFont); createPropertySetterGetter("max", _setMax, _getMax); createPropertySetterGetter("message", _setMessage, _getMessage); createPropertySetterGetter("min", _setMin, _getMin); createPropertySetterGetter("style", _setStyle, _getStyle); createPropertySetterGetter("value", _setValue, _getValue); _progressBar = new TiUIProgressBar(this); setView(_progressBar); } TiUIProgressBarProxy::~TiUIProgressBarProxy() { } void TiUIProgressBarProxy::setColor(Ti::TiValue) { // Not supported } void TiUIProgressBarProxy::setFont(Ti::TiValue) { // Not supported } void TiUIProgressBarProxy::setMax(Ti::TiValue val) { _progressBar->setMaxValue((float)val.toNumber()); } void TiUIProgressBarProxy::setMessage(Ti::TiValue) { // Not supported } void TiUIProgressBarProxy::setMin(Ti::TiValue val) { _progressBar->setMinValue((float)val.toNumber()); } void TiUIProgressBarProxy::setStyle(Ti::TiValue) { } void TiUIProgressBarProxy::setValue(Ti::TiValue val) { _progressBar->setValue((float)val.toNumber()); } Ti::TiValue TiUIProgressBarProxy::getColor() { // Not supported Ti::TiValue val; val.setUndefined(); return val; } Ti::TiValue TiUIProgressBarProxy::getFont() { // Not supported Ti::TiValue val; val.setUndefined(); return val; } Ti::TiValue TiUIProgressBarProxy::getMax() { Ti::TiValue val; val.setNumber(_progressBar->getMaxValue()); return val; } Ti::TiValue TiUIProgressBarProxy::getMessage() { // Not supported Ti::TiValue val; val.setUndefined(); return val; } Ti::TiValue TiUIProgressBarProxy::getMin() { // Not supported Ti::TiValue val; val.setNumber(_progressBar->getMinValue()); return val; } Ti::TiValue TiUIProgressBarProxy::getStyle() { // Not supported Ti::TiValue val; val.setUndefined(); return val; } Ti::TiValue TiUIProgressBarProxy::getValue() { Ti::TiValue val; val.setNumber(_progressBar->getValue()); return val; } }
22.364486
84
0.754283
ssaracut
01749a8cb48abff3e178b53309c6b048c7c420eb
10,913
cpp
C++
test/quantile_bai_unittest.cpp
gostevehoward/quantile-cs
12bad0fe9843e1a7263f667f95933c3d28825d87
[ "MIT" ]
1
2019-11-27T18:40:38.000Z
2019-11-27T18:40:38.000Z
test/quantile_bai_unittest.cpp
gostevehoward/quantilecs
12bad0fe9843e1a7263f667f95933c3d28825d87
[ "MIT" ]
null
null
null
test/quantile_bai_unittest.cpp
gostevehoward/quantilecs
12bad0fe9843e1a7263f667f95933c3d28825d87
[ "MIT" ]
null
null
null
#include <random> #include "quantile_bai.h" #include "gtest/gtest.h" namespace { TEST(BanditModelTest, Bernoulli) { std::mt19937_64 rng(123); auto model = BanditModel::NITHBernoulli(2, .5, .1); double draw = model.sample_arm(0, rng); EXPECT_TRUE(draw == 0.0 || draw == 1.0); } TEST(BanditModelTest, Uniform) { std::mt19937_64 rng(123); auto model = BanditModel::NITHUniform(2, 1); double draw1 = model.sample_arm(0, rng); EXPECT_LE(1, draw1); EXPECT_LE(draw1, 2); double draw2 = model.sample_arm(0, rng); EXPECT_NE(draw1, draw2); double draw3 = model.sample_arm(1, rng); EXPECT_LE(0, draw3); EXPECT_LE(draw3, 1); } TEST(BanditModelTest, Cauchy) { std::mt19937_64 rng(123); auto model = BanditModel::NITHCauchy(2, 2e6); double draw1 = model.sample_arm(0, rng); EXPECT_LE(1e6, draw1); double draw2 = model.sample_arm(0, rng); EXPECT_NE(draw1, draw2); double draw3 = model.sample_arm(1, rng); EXPECT_LE(draw3, 1e6); } TEST(SzorenyiCITest, Radius) { SzorenyiCI ci; EXPECT_NEAR(ci.radius(100, .05), 0.2588138, 1e-5); } TEST(BetaBinomialCITest, Radius) { // expected values based on R confseq package // beta_binomial_mixture_bound(100*.5*.5, .05, 10*.5*.5, .5, .5) / 100 BetaBinomialCI ci(0.5, 10, .05); EXPECT_NEAR(ci.radius(100, .05), 0.1599309, 1e-5); // beta_binomial_mixture_bound(100*.9*.1, .05, 10*.9*.1, .9, .1) / 100 BetaBinomialCI ci2(0.9, 10, .05); EXPECT_NEAR(ci2.radius(100, .05), 0.08109037, 1e-5); } TEST(StitchedCITest, Radius) { // expected values based on R confseq package // poly_stitching_bound(100*.5*.5, .05, 10*.5*.5, c=(1 - 2 * .5) / 3, // eta=2.04) / 100 StitchedCI ci(0.5, 10, 2.04, 1.4); EXPECT_NEAR(ci.radius(100, .05), 0.178119, 1e-5); // poly_stitching_bound(100*.9*.1, .05, 10*.9*.1, c=(1 - 2 * .9) / 3, // eta=2.04) / 100 StitchedCI ci2(0.9, 10, 2.04, 1.4); EXPECT_NEAR(ci2.radius(100, .05), 0.0888042, 1e-5); } TEST(TreeTrackerTest, BasicUse) { TreeTracker tracker; EXPECT_EQ(tracker.size(), 0); tracker.insert(1); EXPECT_EQ(tracker.size(), 1); tracker.insert(2); EXPECT_EQ(tracker.get_order_statistic(1), 1); EXPECT_EQ(tracker.get_order_statistic(2), 2); for (int i = 3; i <= 50; i++) { tracker.insert(i); } for (int i = 100; i >= 51; i--) { tracker.insert(i); } for (int i = 3; i <= 100; i++) { EXPECT_EQ(tracker.get_order_statistic(i), i); EXPECT_EQ(tracker.count_less_or_equal(i), i); EXPECT_EQ(tracker.count_less(i), i - 1); } } TEST(TreeTrackerTest, TieHandling) { TreeTracker tracker; tracker.insert(0); tracker.insert(1); tracker.insert(0); EXPECT_EQ(tracker.get_order_statistic(1), 0); EXPECT_EQ(tracker.get_order_statistic(2), 0); EXPECT_EQ(tracker.count_less(0), 0); EXPECT_EQ(tracker.count_less_or_equal(0), 2); EXPECT_EQ(tracker.get_order_statistic(3), 1); EXPECT_EQ(tracker.count_less(1), 2); EXPECT_EQ(tracker.count_less_or_equal(1), 3); } class TestCI : public ConfidenceInterval { double radius(const int, const double) const override { return 0.1; } }; TEST(QuantileCITrackerTest, BasicUse) { auto make_os_tracker = []() {return std::make_unique<TreeTracker>();}; QuantileCITracker tracker(2, 0.59, 0.1, make_os_tracker, std::make_unique<TestCI>(), std::make_unique<TestCI>(), std::make_unique<TestCI>(), std::make_unique<TestCI>()); EXPECT_EQ(tracker.num_arms(), 2); for (int i = 1; i <= 10; i++) { tracker.insert(0, i); } EXPECT_EQ(tracker.point_estimate(0, false), 6); EXPECT_EQ(tracker.upper_bound(0, .05, false), 7); EXPECT_EQ(tracker.lower_bound(0, .05, false), 5); EXPECT_EQ(tracker.point_estimate(0, true), 7); EXPECT_EQ(tracker.upper_bound(0, .05, true), 8); EXPECT_EQ(tracker.lower_bound(0, .05, true), 6); for (int i = 11; i <= 100; i++) { tracker.insert(0, i); } EXPECT_EQ(tracker.point_estimate(0, false), 60); EXPECT_EQ(tracker.upper_bound(0, .05, false), 70); EXPECT_EQ(tracker.point_estimate(0, true), 70); } struct CIValues { double point_estimate = 0; double lower_bound = -1; double upper_bound = 1; }; class FakeCITracker : public QuantileCIInterface { public: void insert(const int arm_index, const double value) override { values_[arm_index].push_back(value); } double lower_bound(const int arm_index, const double error_rate, const bool add_epsilon) const override { return (add_epsilon ? p_epsilon_ci_values : p_ci_values)[arm_index] .lower_bound; } double upper_bound(const int arm_index, const double error_rate, const bool add_epsilon) const override { return (add_epsilon ? p_epsilon_ci_values : p_ci_values)[arm_index] .upper_bound; } double point_estimate(const int arm_index, const bool add_epsilon) const override { return (add_epsilon ? p_epsilon_ci_values : p_ci_values)[arm_index] .point_estimate; } int num_arms() const override {return 3;} std::vector<double> values_[3]; CIValues p_ci_values[3]; CIValues p_epsilon_ci_values[3]; }; TEST(QpacAgent, BasicUse) { auto tracker_unique_ptr = std::make_unique<FakeCITracker>(); FakeCITracker* tracker = tracker_unique_ptr.get(); QpacAgent agent(0.05, std::move(tracker_unique_ptr)); for (int i = 0; i < 3; i++) { int arm = agent.get_arm_to_sample(); EXPECT_EQ(agent.update(arm, arm), Agent::NO_ARM_SELECTED); } for (int arm = 0; arm < 3; arm++) { EXPECT_EQ(tracker->values_[arm].size(), 1); EXPECT_EQ(tracker->values_[arm][0], arm); } // eliminate arm 0 tracker->p_epsilon_ci_values[0].upper_bound = -2; for (int i = 0; i < 3; i++) { int arm = agent.get_arm_to_sample(); EXPECT_EQ(agent.update(arm, arm), Agent::NO_ARM_SELECTED); } EXPECT_EQ(tracker->values_[0].size(), 2); for (int i = 0; i < 4; i++) { int arm = agent.get_arm_to_sample(); EXPECT_EQ(agent.update(arm, arm), Agent::NO_ARM_SELECTED); } EXPECT_EQ(tracker->values_[0].size(), 2); EXPECT_EQ(tracker->values_[1].size(), 4); EXPECT_EQ(tracker->values_[2].size(), 4); // choose arm 2 tracker->p_epsilon_ci_values[2].lower_bound = 2; int arm = agent.get_arm_to_sample(); EXPECT_EQ(agent.update(arm, arm), Agent::NO_ARM_SELECTED); arm = agent.get_arm_to_sample(); EXPECT_EQ(agent.update(arm, arm), 2); } class FakeOrderStatisticTracker : public OrderStatisticTracker { public: void insert(const double value) override { inserted_values_.push_back(value); } double get_order_statistic(const int order_index) const override { auto search = order_stats_.find(order_index); if (search != order_stats_.end()) { return search->second; } else { return 0; } } int count_less_or_equal(const double value) const override { assert(false); return -1; } int count_less(const double value) const override { assert(false); return -1; } int size() const override { return inserted_values_.size(); } std::vector<double> inserted_values_; std::unordered_map<int,double> order_stats_; }; int m_k(int num_samples) { return floor(.5 * num_samples - sqrt(3 * .5 * num_samples * 24.26684)) + 1; } TEST(DoubledMaxQAgent, BasicUse) { std::vector<FakeOrderStatisticTracker*> trackers; auto make_os_tracker = [&trackers]() { auto tracker_unique_ptr = std::make_unique<FakeOrderStatisticTracker>(); trackers.push_back(tracker_unique_ptr.get()); return tracker_unique_ptr; }; DoubledMaxQAgent agent(3, 0.05, 0.1, 0.5, make_os_tracker); // 6*log(3*log(-20*.5*log(.05)/.1^2, 2)) - log(.05) // L_D = 24.26684 // floor(3*24.26684 / .5) + 1 const int N_0 = 146; // 10 * .5 * 24.26684 / .1^2 // stopping sample size = 12133.42 // make arm 2 the highest after the initial round trackers[2]->order_stats_[N_0 - m_k(N_0) + 1] = 1; // initial sampling N_0 times from each arm for (int i = 0; i < N_0 * 3; i++) { int arm = agent.get_arm_to_sample(); EXPECT_EQ(agent.update(arm, arm), Agent::NO_ARM_SELECTED); } for (int arm = 0; arm < 3; arm++) { EXPECT_EQ(trackers[arm]->size(), N_0); EXPECT_EQ(trackers[arm]->inserted_values_[0], arm); } EXPECT_EQ(agent.get_arm_to_sample(), 2); // another N_0 samples from arm 2 trackers[2]->order_stats_[2 * N_0 - m_k(2 * N_0) + 1] = 1; for (int i = 0; i < N_0; i++) { EXPECT_EQ(agent.get_arm_to_sample(), 2); EXPECT_EQ(agent.update(2, 0), Agent::NO_ARM_SELECTED); } EXPECT_EQ(trackers[2]->size(), 2 * N_0); EXPECT_EQ(agent.get_arm_to_sample(), 2); // another 2*N_0 samples from arm 2, then switch to arm 1 trackers[1]->order_stats_[N_0 - m_k(N_0) + 1] = 2; for (int i = 0; i < 2 * N_0; i++) { EXPECT_EQ(agent.get_arm_to_sample(), 2); EXPECT_EQ(agent.update(2, 0), Agent::NO_ARM_SELECTED); } EXPECT_EQ(agent.get_arm_to_sample(), 1); // take N_0 samples from arm 1 trackers[1]->order_stats_[2 * N_0 - m_k(2*N_0) + 1] = 2; for (int i = 0; i < N_0; i++) { EXPECT_EQ(agent.get_arm_to_sample(), 1); EXPECT_EQ(agent.update(1, 0), Agent::NO_ARM_SELECTED); } EXPECT_EQ(trackers[2]->size(), 4 * N_0); EXPECT_EQ(trackers[1]->size(), 2 * N_0); // log(12134 / 146, 2) = 6.4 // so sample seven rounds total from arm 1, hence 2^7 * 146 = 18688 samples // before stopping for (int k = 2; k <= 7; k++) { trackers[1]->order_stats_[pow(2, k) * N_0 - m_k(pow(2, k) * N_0) + 1] = 2; } for (int i = 0; i < 18688 - 2 * N_0 - 1; i++) { EXPECT_EQ(agent.get_arm_to_sample(), 1); EXPECT_EQ(agent.update(1, 0), Agent::NO_ARM_SELECTED); } EXPECT_EQ(agent.get_arm_to_sample(), 1); EXPECT_EQ(agent.update(1, 0), 1); } TEST(LucbAgent, BasicUse) { auto tracker_unique_ptr = std::make_unique<FakeCITracker>(); FakeCITracker* tracker = tracker_unique_ptr.get(); LucbAgent agent(0.05, std::move(tracker_unique_ptr)); for (int i = 0; i < 3; i++) { int arm = agent.get_arm_to_sample(); EXPECT_EQ(agent.update(arm, arm), Agent::NO_ARM_SELECTED); } for (int arm = 0; arm < 3; arm++) { EXPECT_EQ(tracker->values_[arm].size(), 1); EXPECT_EQ(tracker->values_[arm][0], arm); } // best arm = 1, best competitor = 2 tracker->p_epsilon_ci_values[1].lower_bound = 2; tracker->p_ci_values[2].upper_bound = 3; for (int i = 0; i < 2; i++) { int arm = agent.get_arm_to_sample(); EXPECT_EQ(agent.update(arm, 0), Agent::NO_ARM_SELECTED); } EXPECT_EQ(tracker->values_[0].size(), 1); EXPECT_EQ(tracker->values_[1].size(), 2); EXPECT_EQ(tracker->values_[2].size(), 2); // now stop with best arm 2 tracker->p_epsilon_ci_values[2].lower_bound = 4; tracker->p_ci_values[1].upper_bound = 3; int arm = agent.get_arm_to_sample(); EXPECT_TRUE(arm == 1 || arm == 2); EXPECT_EQ(agent.update(arm, 0), 2); } } // namespace
30.313889
78
0.652525
gostevehoward
017749506f9ca6e648e0c0787bacc0178bd9e649
14,148
cpp
C++
opt/nomad/src/Algos/Mads/Poll.cpp
scikit-quant/scikit-quant
397ab0b6287f3815e9bcadbfadbe200edbee5a23
[ "BSD-3-Clause-LBNL" ]
31
2019-02-05T16:39:18.000Z
2022-03-11T23:14:11.000Z
opt/nomad/src/Algos/Mads/Poll.cpp
scikit-quant/scikit-quant
397ab0b6287f3815e9bcadbfadbe200edbee5a23
[ "BSD-3-Clause-LBNL" ]
20
2020-04-13T09:22:53.000Z
2021-08-16T16:14:13.000Z
opt/nomad/src/Algos/Mads/Poll.cpp
scikit-quant/scikit-quant
397ab0b6287f3815e9bcadbfadbe200edbee5a23
[ "BSD-3-Clause-LBNL" ]
6
2020-04-21T17:43:47.000Z
2021-03-10T04:12:34.000Z
/*---------------------------------------------------------------------------------*/ /* NOMAD - Nonlinear Optimization by Mesh Adaptive Direct Search - */ /* */ /* NOMAD - Version 4 has been created by */ /* Viviane Rochon Montplaisir - Polytechnique Montreal */ /* Christophe Tribes - Polytechnique Montreal */ /* */ /* The copyright of NOMAD - version 4 is owned by */ /* Charles Audet - Polytechnique Montreal */ /* Sebastien Le Digabel - Polytechnique Montreal */ /* Viviane Rochon Montplaisir - Polytechnique Montreal */ /* Christophe Tribes - Polytechnique Montreal */ /* */ /* NOMAD 4 has been funded by Rio Tinto, Hydro-Québec, Huawei-Canada, */ /* NSERC (Natural Sciences and Engineering Research Council of Canada), */ /* InnovÉÉ (Innovation en Énergie Électrique) and IVADO (The Institute */ /* for Data Valorization) */ /* */ /* NOMAD v3 was created and developed by Charles Audet, Sebastien Le Digabel, */ /* Christophe Tribes and Viviane Rochon Montplaisir and was funded by AFOSR */ /* and Exxon Mobil. */ /* */ /* NOMAD v1 and v2 were created and developed by Mark Abramson, Charles Audet, */ /* Gilles Couture, and John E. Dennis Jr., and were funded by AFOSR and */ /* Exxon Mobil. */ /* */ /* Contact information: */ /* Polytechnique Montreal - GERAD */ /* C.P. 6079, Succ. Centre-ville, Montreal (Quebec) H3C 3A7 Canada */ /* e-mail: nomad@gerad.ca */ /* */ /* This program 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. */ /* */ /* This program is distributed in the hope that it will be useful, but WITHOUT */ /* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or */ /* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License */ /* for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* */ /* You can find information on the NOMAD software at www.gerad.ca/nomad */ /*---------------------------------------------------------------------------------*/ #include "../../Algos/AlgoStopReasons.hpp" #include "../../Algos/Mads/DoublePollMethod.hpp" #include "../../Algos/Mads/NP1UniPollMethod.hpp" #include "../../Algos/Mads/Ortho2NPollMethod.hpp" #include "../../Algos/Mads/OrthoNPlus1NegPollMethod.hpp" #include "../../Algos/Mads/Poll.hpp" #include "../../Algos/Mads/SinglePollMethod.hpp" #include "../../Algos/SubproblemManager.hpp" #include "../../Output/OutputQueue.hpp" #include "../../Type/DirectionType.hpp" #ifdef TIME_STATS #include "../../Util/Clock.hpp" // Initialize static variables double NOMAD::Poll::_pollTime; double NOMAD::Poll::_pollEvalTime; #endif // TIME_STATS void NOMAD::Poll::init() { setStepType(NOMAD::StepType::POLL); verifyParentNotNull(); // Compute primary and secondary poll centers std::vector<NOMAD::EvalPoint> primaryCenters, secondaryCenters; computePrimarySecondaryPollCenters(primaryCenters, secondaryCenters); // Add poll methods for primary polls for (auto pollCenter : primaryCenters) { for (auto pollMethod : createPollMethods(true, pollCenter)) { _pollMethods.push_back(pollMethod); } } // Add poll methods for secondary polls for (auto pollCenter : secondaryCenters) { for (auto pollMethod : createPollMethods(false, pollCenter)) { _pollMethods.push_back(pollMethod); } } } void NOMAD::Poll::startImp() { // Sanity check. verifyGenerateAllPointsBeforeEval(NOMAD_PRETTY_FUNCTION, false); } bool NOMAD::Poll::runImp() { bool pollSuccessful = false; std::string s; // Sanity check. The runImp function should be called only when trial points are generated and evaluated for each search method separately. verifyGenerateAllPointsBeforeEval(NOMAD_PRETTY_FUNCTION, false); // Go through all poll methods to generate points. OUTPUT_DEBUG_START s = "Generate points for " + getName(); AddOutputDebug(s); OUTPUT_DEBUG_END #ifdef TIME_STATS double pollStartTime = NOMAD::Clock::getCPUTime(); double pollEvalStartTime = NOMAD::EvcInterface::getEvaluatorControl()->getEvalTime(); #endif // TIME_STATS // 1- Generate points for all poll methods generateTrialPoints(); // 2- Evaluate points bool isOrthoNP1 = false; for (auto dirType : _runParams->getAttributeValue<NOMAD::DirectionTypeList>("DIRECTION_TYPE")) { if ( NOMAD::DirectionType::ORTHO_NP1_NEG == dirType || NOMAD::DirectionType::ORTHO_NP1_QUAD == dirType) { isOrthoNP1 = true; } } if ( ! _stopReasons->checkTerminate() ) { size_t keepN = NOMAD::INF_SIZE_T; if (isOrthoNP1) { // Keep only N points on the 2N points generated. keepN = _pbParams->getAttributeValue<size_t>("DIMENSION"); } // The StepType argument ensures that all points from secondary poll will // kept, since they were generated with a POLL_METHOD_DOUBLE StepType. evalTrialPoints(this, keepN, NOMAD::StepType::POLL_METHOD_ORTHO_NPLUS1_NEG); pollSuccessful = (getSuccessType() >= NOMAD::SuccessType::FULL_SUCCESS); } // 3- Second evaluation pass: Ortho N+1 if (!_stopReasons->checkTerminate() && !pollSuccessful && isOrthoNP1) { // Generate point for N+1th direction. // Provide evaluated trial points, then erase them to ensure that they // are not re-evaluated, then put them back for postProcessing(). auto evaluatedTrialPoints = getTrialPoints(); clearTrialPoints(); // We only want to use points that were generated by step POLL_METHOD_ORTHO_NPLUS1_NEG. NOMAD::EvalPointSet inputTrialPoints; for (auto trialPoint: evaluatedTrialPoints) { if (NOMAD::StepType::POLL_METHOD_ORTHO_NPLUS1_NEG == trialPoint.getGenStep()) { inputTrialPoints.insert(trialPoint); } } generateTrialPointsNPlus1(inputTrialPoints); // Evaluate point. if (getTrialPointsCount() > 0) { evalTrialPoints(this); pollSuccessful = (getSuccessType() >= NOMAD::SuccessType::FULL_SUCCESS); } // Add back trial points that are already evaluated. for (auto trialPoint: evaluatedTrialPoints) { insertTrialPoint(trialPoint); } } #ifdef TIME_STATS _pollTime += NOMAD::Clock::getCPUTime() - pollStartTime; _pollEvalTime += NOMAD::EvcInterface::getEvaluatorControl()->getEvalTime() - pollEvalStartTime; #endif // TIME_STATS OUTPUT_INFO_START s = getName(); s += (pollSuccessful) ? " is successful" : " is not successful"; s += ". Stop reason: "; s += _stopReasons->getStopReasonAsString() ; AddOutputInfo(s); OUTPUT_INFO_END return pollSuccessful; } void NOMAD::Poll::endImp() { // Sanity check. The endImp function should be called only when trial points are generated and evaluated for each search method separately. verifyGenerateAllPointsBeforeEval(NOMAD_PRETTY_FUNCTION, false); // Compute hMax and update Barrier. postProcessing(); } // Generate new points to evaluate // Note: Used whether MEGA_SEARCH_POLL is true or false. void NOMAD::Poll::generateTrialPoints() { for (auto pollMethod : _pollMethods) { if (_stopReasons->checkTerminate()) { break; } pollMethod->generateTrialPoints(); // Pass the points from Poll method to Poll for later evaluation auto pollMethodPoints = pollMethod->getTrialPoints(); for (auto point : pollMethodPoints) { insertTrialPoint(point); } } // Stopping criterion if (0 == getTrialPointsCount()) { auto madsStopReasons = NOMAD::AlgoStopReasons<NOMAD::MadsStopType>::get(_stopReasons); madsStopReasons->set(NOMAD::MadsStopType::MESH_PREC_REACHED); } } void NOMAD::Poll::generateTrialPointsNPlus1(const NOMAD::EvalPointSet& inputTrialPoints) { for (auto pollMethod : _pollMethods) { if (_stopReasons->checkTerminate()) { break; } if (!pollMethod->hasNPlus1()) { continue; } // Provide the evaluated trial // points to the PollMethod for n+1th point generation. pollMethod->generateTrialPointsNPlus1(inputTrialPoints); // Add the n+1th point to trial points. for (auto point : pollMethod->getTrialPoints()) { insertTrialPoint(point); } } } void NOMAD::Poll::computePrimarySecondaryPollCenters( std::vector<NOMAD::EvalPoint> &primaryCenters, std::vector<NOMAD::EvalPoint> &secondaryCenters) const { auto barrier = getMegaIterationBarrier(); if (nullptr != barrier) { auto firstXFeas = barrier->getFirstXFeas(); auto firstXInf = barrier->getFirstXInf(); bool primaryIsInf = false; NOMAD::Double rho = _runParams->getAttributeValue<NOMAD::Double>("RHO"); // Negative rho means make no distinction between primary and secondary polls. bool usePrimarySecondary = (rho >= 0) && (nullptr != firstXFeas) && (nullptr != firstXInf); if (usePrimarySecondary) { auto evc = NOMAD::EvcInterface::getEvaluatorControl(); auto evalType = evc->getEvalType(); auto computeType = evc->getComputeType(); NOMAD::Double fFeas = firstXFeas->getF(evalType, computeType); NOMAD::Double fInf = firstXInf->getF(evalType, computeType); if (fFeas.isDefined() && fInf.isDefined() && (fFeas - rho) > fInf) { // xFeas' f is too large, use xInf as primary poll instead. primaryIsInf = true; } } if (usePrimarySecondary) { if (primaryIsInf) { primaryCenters = barrier->getAllXInf(); secondaryCenters = barrier->getAllXFeas(); } else { primaryCenters = barrier->getAllXFeas(); secondaryCenters = barrier->getAllXInf(); } } else { // All points are primary centers. primaryCenters = barrier->getAllPoints(); } } } std::vector<std::shared_ptr<NOMAD::PollMethodBase>> NOMAD::Poll::createPollMethods(const bool isPrimary, const NOMAD::EvalPoint& frameCenter) const { std::vector<std::shared_ptr<NOMAD::PollMethodBase>> pollMethods; // Select the poll methods to be executed NOMAD::DirectionTypeList dirTypes; if (isPrimary) { dirTypes = _runParams->getAttributeValue<DirectionTypeList>("DIRECTION_TYPE"); } else { dirTypes = _runParams->getAttributeValue<DirectionTypeList>("DIRECTION_TYPE_SECONDARY_POLL"); } for (auto dirType : dirTypes) { std::shared_ptr<NOMAD::PollMethodBase> pollMethod; switch (dirType) { case DirectionType::ORTHO_2N: pollMethod = std::make_shared<NOMAD::Ortho2NPollMethod>(this, frameCenter); break; case DirectionType::ORTHO_NP1_NEG: pollMethod = std::make_shared<NOMAD::OrthoNPlus1NegPollMethod>(this, frameCenter); break; case DirectionType::NP1_UNI: pollMethod = std::make_shared<NOMAD::NP1UniPollMethod>(this, frameCenter); break; case DirectionType::DOUBLE: pollMethod = std::make_shared<NOMAD::DoublePollMethod>(this, frameCenter); break; case DirectionType::SINGLE: pollMethod = std::make_shared<NOMAD::SinglePollMethod>(this, frameCenter); break; default: throw NOMAD::Exception(__FILE__, __LINE__,"Poll method" + directionTypeToString(dirType) + " is not available."); break; } pollMethods.push_back(pollMethod); } return pollMethods; }
39.741573
147
0.556192
scikit-quant
0177b1a5e739a0eef4cbf6ab6f8e3cbcd699183c
4,671
cpp
C++
tests/filemanager/copy.cpp
sugawaray/filemanager
3dcb908d4c1e0c36de0c60e1b2e1291eec986cb1
[ "MIT" ]
null
null
null
tests/filemanager/copy.cpp
sugawaray/filemanager
3dcb908d4c1e0c36de0c60e1b2e1291eec986cb1
[ "MIT" ]
null
null
null
tests/filemanager/copy.cpp
sugawaray/filemanager
3dcb908d4c1e0c36de0c60e1b2e1291eec986cb1
[ "MIT" ]
null
null
null
#include <iostream> #include <nomagic.h> #include "move_copy_test.h" #include "copy.h" using fm::filemanager::test::Copy_test; START_TEST(should_copy_a_file_to_a_file) { Copy_test test; test.test_should_move_or_copy_a_file_to_a_file(); } END_TEST START_TEST(should_copy_a_file_to_a_filepath) { Copy_test test; test.test_should_move_a_file_to_a_filepath(); } END_TEST START_TEST(should_copy_a_file_to_a_directory) { Copy_test test; test.test_should_move_a_file_to_a_directory(); } END_TEST START_TEST(should_copy_a_directory_to_a_directory) { Copy_test test(true); test.test_should_move_a_directory_to_a_directory(); } END_TEST START_TEST(should_not_copy_similar_files) { Copy_test test; test.test_should_not_move_similar_files(); } END_TEST START_TEST(should_not_copy_a_file_to_a_dir_when_a_dir_exists) { Copy_test test; test.test_should_not_move_a_file_to_a_dir_when_a_dir_exists(); } END_TEST START_TEST(should_not_copy_a_file_to_an_impossible_path) { Copy_test test; test.test_should_not_move_a_file_to_an_impossible_path(); } END_TEST START_TEST(should_copy_a_directory_to_a_directory_path) { Copy_test test(true); test.test_should_move_a_directory_to_a_directory_path(); } END_TEST START_TEST(should_not_copy_a_directory_to_an_impossible_path) { Copy_test test(true); test.test_should_not_move_a_directory_to_an_impossible_path(); } END_TEST START_TEST(should_not_copy_a_directory_to_its_an_ancestor) { Copy_test test(true); test.test_should_not_move_a_directory_to_its_an_ancestor(); } END_TEST START_TEST(should_not_copy_a_file_when_it_looks_like_a_dir) { Copy_test test; test.test_should_not_move_a_file_when_it_looks_like_a_dir(); } END_TEST START_TEST(should_not_copy_a_dir_when_it_looks_like_a_file) { Copy_test test(true); test.test_should_not_move_a_dir_when_it_looks_like_a_file(); } END_TEST START_TEST(copy_a_file_mapping_without_its_real_file) { Copy_test test; test.test_move_a_file_mapping_without_its_real_file(); } END_TEST START_TEST(copy_a_dir_mapping_without_its_real_dir) { Copy_test test(true); test.test_move_a_dir_mapping_without_its_real_dir(); } END_TEST START_TEST(should_not_copy_a_dir_to_a_dir_which_does_not_exist) { Copy_test test(true); test.test_should_not_move_a_dir_to_a_dir_which_does_not_exist(); } END_TEST START_TEST(copy_a_dir_to_a_dirpath_where_there_is_a_dir) { Copy_test test(true); test.test_move_a_dir_to_a_dirpath_where_there_is_a_dir(); } END_TEST START_TEST(should_not_copy_a_file_to_a_dest_file_which_does_not_exist) { Copy_test test; test.test_should_not_move_a_file_to_a_dest_file_which_does_not_exist(); } END_TEST START_TEST(copy_a_file_to_a_path_where_there_is_a_file) { Copy_test test; test.test_move_a_file_to_a_path_where_there_is_a_file(); } END_TEST START_TEST(should_not_copy_a_file_to_a_dir_which_does_not_exist) { Copy_test test; test.test_should_not_move_a_file_to_a_dir_which_does_not_exist(); } END_TEST START_TEST(copy_a_file_to_a_dir_which_does_not_have_any_mappings) { Copy_test test; test.test_move_a_file_to_a_dir_which_does_not_have_any_mappings(); } END_TEST namespace fm { namespace filemanager { namespace test { TCase* create_copy_tcase() { TCase* tcase(tcase_create("copy")); tcase_add_test(tcase, should_copy_a_file_to_a_file); tcase_add_test(tcase, should_copy_a_file_to_a_filepath); tcase_add_test(tcase, should_copy_a_file_to_a_directory); tcase_add_test(tcase, should_copy_a_directory_to_a_directory); tcase_add_test(tcase, should_not_copy_similar_files); tcase_add_test(tcase, should_not_copy_a_file_to_a_dir_when_a_dir_exists); tcase_add_test(tcase, should_not_copy_a_file_to_an_impossible_path); tcase_add_test(tcase, should_copy_a_directory_to_a_directory_path); tcase_add_test(tcase, should_not_copy_a_directory_to_an_impossible_path); tcase_add_test(tcase, should_not_copy_a_directory_to_its_an_ancestor); tcase_add_test(tcase, should_not_copy_a_file_when_it_looks_like_a_dir); tcase_add_test(tcase, should_not_copy_a_dir_when_it_looks_like_a_file); tcase_add_test(tcase, copy_a_file_mapping_without_its_real_file); tcase_add_test(tcase, copy_a_dir_mapping_without_its_real_dir); tcase_add_test(tcase, should_not_copy_a_dir_to_a_dir_which_does_not_exist); tcase_add_test(tcase, copy_a_dir_to_a_dirpath_where_there_is_a_dir); tcase_add_test(tcase, should_not_copy_a_file_to_a_dest_file_which_does_not_exist); tcase_add_test(tcase, copy_a_file_to_a_path_where_there_is_a_file); tcase_add_test(tcase, should_not_copy_a_file_to_a_dir_which_does_not_exist); tcase_add_test(tcase, copy_a_file_to_a_dir_which_does_not_have_any_mappings); return tcase; } } // test } // filemanager } // fm
24.97861
72
0.863413
sugawaray
018e76deee8bdabaf65f1b68d555a51946186eaa
1,508
cpp
C++
paxos/acceptor.cpp
plsmaop/SLOG
bcf5775fdb756d73e56265835020517f6f7b79a7
[ "MIT" ]
26
2020-01-31T18:12:44.000Z
2022-02-07T01:46:07.000Z
paxos/acceptor.cpp
plsmaop/SLOG
bcf5775fdb756d73e56265835020517f6f7b79a7
[ "MIT" ]
17
2020-01-30T20:40:35.000Z
2021-12-22T18:43:21.000Z
paxos/acceptor.cpp
plsmaop/SLOG
bcf5775fdb756d73e56265835020517f6f7b79a7
[ "MIT" ]
6
2019-12-24T15:30:45.000Z
2021-07-06T19:47:30.000Z
#include "paxos/acceptor.h" #include "paxos/simulated_multi_paxos.h" namespace slog { using internal::Envelope; using internal::Request; using internal::Response; Acceptor::Acceptor(SimulatedMultiPaxos& sender) : sender_(sender), ballot_(0) {} void Acceptor::HandleRequest(const internal::Envelope& req) { switch (req.request().type_case()) { case Request::TypeCase::kPaxosAccept: ProcessAcceptRequest(req.request().paxos_accept(), req.from()); break; case Request::TypeCase::kPaxosCommit: ProcessCommitRequest(req.request().paxos_commit(), req.from()); break; default: break; } } void Acceptor::ProcessAcceptRequest(const internal::PaxosAcceptRequest& req, MachineId from_machine_id) { if (req.ballot() < ballot_) { return; } ballot_ = req.ballot(); auto env = sender_.NewEnvelope(); auto accept_response = env->mutable_response()->mutable_paxos_accept(); accept_response->set_ballot(ballot_); accept_response->set_slot(req.slot()); sender_.SendSameChannel(move(env), from_machine_id); } void Acceptor::ProcessCommitRequest(const internal::PaxosCommitRequest& req, MachineId from_machine_id) { // TODO: If leader election is implemented, this is where we erase // memory about an accepted value auto env = sender_.NewEnvelope(); auto commit_response = env->mutable_response()->mutable_paxos_commit(); commit_response->set_slot(req.slot()); sender_.SendSameChannel(move(env), from_machine_id); } } // namespace slog
32.085106
105
0.732095
plsmaop
018f628d208b152da9e47284a479d912d22f2f03
453
cpp
C++
src/platform.cpp
matias310396/sonic
0bfbdd02ad1f1bff04b74b913199b9b7bc45c343
[ "MIT" ]
null
null
null
src/platform.cpp
matias310396/sonic
0bfbdd02ad1f1bff04b74b913199b9b7bc45c343
[ "MIT" ]
null
null
null
src/platform.cpp
matias310396/sonic
0bfbdd02ad1f1bff04b74b913199b9b7bc45c343
[ "MIT" ]
null
null
null
#include "../include/platform.hpp" using namespace engine; void Platform::on_event(GameEvent game_event){ std::string event_name = game_event.game_event_name; Image* platform_image = dynamic_cast<Image*>(images[0]); if(event_name == "MOVE_LEFT" && !GameObject::on_limit_of_level){ position.first += 10; }else if(event_name == "MOVE_RIGHT" && !GameObject::on_limit_of_level){ position.first -= 10; } } void Platform::update(){}
23.842105
73
0.706402
matias310396
019228dfe8b5d4b0bb0029b7bcac44bbf217b8af
893
cpp
C++
1237/src.cpp
sabingoyek/uva-online-judge
78be271d440ff3b9b1b038fb83343ba46ea60843
[ "MIT" ]
null
null
null
1237/src.cpp
sabingoyek/uva-online-judge
78be271d440ff3b9b1b038fb83343ba46ea60843
[ "MIT" ]
null
null
null
1237/src.cpp
sabingoyek/uva-online-judge
78be271d440ff3b9b1b038fb83343ba46ea60843
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { // your code goes here int T; scanf("%d", &T); while(T--){ int D, Q, L, H; string M; vector<pair<string, pair<int, int>>> db; scanf("%d", &D); while(D--){ cin >> M >> L >> H; db.push_back(make_pair(M, make_pair(L,H))); } /*for(int i = 0; i < db.size(); i++){ cout << db[i].first << " " << db[i].second.first << " " << db[i].second.second << "\n"; }*/ scanf("%d", &Q); int q; while(Q--){ int ans, ans_count = 0; scanf("%d", &q); for(int i = 0; i < db.size(); i++){ if((q >= db[i].second.first) && (q <= db[i].second.second)){ ans_count++; ans = i; if(ans_count > 1) break; } } if(ans_count == 1){ printf("%s\n", db[ans].first.c_str()); } else{ printf("UNDETERMINED\n"); } } if(T != 0) printf("\n"); } return 0; }
16.537037
91
0.469205
sabingoyek
0194c378e1a5adc0f8e2c33bc437e8560f28e74b
314
hpp
C++
include/chip8/memory/stack.hpp
lance21/chip8
6797755845b73ee1a6be5c7b3970cb1c271a114b
[ "MIT" ]
null
null
null
include/chip8/memory/stack.hpp
lance21/chip8
6797755845b73ee1a6be5c7b3970cb1c271a114b
[ "MIT" ]
null
null
null
include/chip8/memory/stack.hpp
lance21/chip8
6797755845b73ee1a6be5c7b3970cb1c271a114b
[ "MIT" ]
null
null
null
#ifndef STACK_HPP #define STACK_HPP #include <cstdint> namespace chip8 { namespace memory { class Stack { private: uint8_t stack_pointer_; uint16_t stack_[16]; public: Stack(); uint8_t getStackPointer() const; uint16_t pop(); void push( const uint16_t return_address); }; } } #endif
12.076923
46
0.687898
lance21
019585181381bdc8accf87cc69e80e64ac949e34
1,069
hpp
C++
Lib/Chip/ATSAM3N0B.hpp
operativeF/Kvasir
dfbcbdc9993d326ef8cc73d99129e78459c561fd
[ "Apache-2.0" ]
null
null
null
Lib/Chip/ATSAM3N0B.hpp
operativeF/Kvasir
dfbcbdc9993d326ef8cc73d99129e78459c561fd
[ "Apache-2.0" ]
null
null
null
Lib/Chip/ATSAM3N0B.hpp
operativeF/Kvasir
dfbcbdc9993d326ef8cc73d99129e78459c561fd
[ "Apache-2.0" ]
null
null
null
#pragma once #include <cstdint> #include <Chip/CM3/Atmel/ATSAM3N0B/SPI.hpp> #include <Chip/CM3/Atmel/ATSAM3N0B/TC0.hpp> #include <Chip/CM3/Atmel/ATSAM3N0B/TWI0.hpp> #include <Chip/CM3/Atmel/ATSAM3N0B/TWI1.hpp> #include <Chip/CM3/Atmel/ATSAM3N0B/PWM.hpp> #include <Chip/CM3/Atmel/ATSAM3N0B/USART0.hpp> #include <Chip/CM3/Atmel/ATSAM3N0B/USART1.hpp> #include <Chip/CM3/Atmel/ATSAM3N0B/ADC.hpp> #include <Chip/CM3/Atmel/ATSAM3N0B/DACC.hpp> #include <Chip/CM3/Atmel/ATSAM3N0B/MATRIX.hpp> #include <Chip/CM3/Atmel/ATSAM3N0B/PMC.hpp> #include <Chip/CM3/Atmel/ATSAM3N0B/UART0.hpp> #include <Chip/CM3/Atmel/ATSAM3N0B/CHIPID.hpp> #include <Chip/CM3/Atmel/ATSAM3N0B/UART1.hpp> #include <Chip/CM3/Atmel/ATSAM3N0B/EFC.hpp> #include <Chip/CM3/Atmel/ATSAM3N0B/PIOA.hpp> #include <Chip/CM3/Atmel/ATSAM3N0B/PIOB.hpp> #include <Chip/CM3/Atmel/ATSAM3N0B/RSTC.hpp> #include <Chip/CM3/Atmel/ATSAM3N0B/SUPC.hpp> #include <Chip/CM3/Atmel/ATSAM3N0B/RTT.hpp> #include <Chip/CM3/Atmel/ATSAM3N0B/WDT.hpp> #include <Chip/CM3/Atmel/ATSAM3N0B/RTC.hpp> #include <Chip/CM3/Atmel/ATSAM3N0B/GPBR.hpp>
41.115385
46
0.776427
operativeF
01a1e24acf88e53592372de597bff526883fba94
15,802
hpp
C++
SDK/ARKSurvivalEvolved_Deathworm_AnimBlueprint_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_Deathworm_AnimBlueprint_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_Deathworm_AnimBlueprint_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_Deathworm_AnimBlueprint_structs.hpp" namespace sdk { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // AnimBlueprintGeneratedClass Deathworm_AnimBlueprint.Deathworm_AnimBlueprint_C // 0x0628 (0x0968 - 0x0340) class UDeathworm_AnimBlueprint_C : public UAnimInstance { public: struct FAnimNode_Root AnimGraphNode_Root_CFF4A96944B38C20EDC066BC94E1B628; // 0x0340(0x0028) struct FAnimNode_TransitionResult AnimGraphNode_TransitionResult_E7146F694055C55380B001AE63B41257;// 0x0368(0x0018) struct FAnimNode_TransitionResult AnimGraphNode_TransitionResult_96F8291C41157B73A8AC088C90822FC3;// 0x0380(0x0018) struct FAnimNode_TransitionResult AnimGraphNode_TransitionResult_A9E899CC48521880815FB3B7877D0742;// 0x0398(0x0018) struct FAnimNode_TransitionResult AnimGraphNode_TransitionResult_9EBD37104522759DFF931D95455F88F9;// 0x03B0(0x0018) struct FAnimNode_TransitionResult AnimGraphNode_TransitionResult_399D803B4896CBDB7046B08FCDA1C387;// 0x03C8(0x0018) struct FAnimNode_TransitionResult AnimGraphNode_TransitionResult_F2AD59AE49B82A3361FE04B3A84705F1;// 0x03E0(0x0018) struct FAnimNode_SequencePlayer AnimGraphNode_SequencePlayer_4B4E4832493212299A9477AFECEEFB61;// 0x03F8(0x0030) struct FAnimNode_Root AnimGraphNode_StateResult_47081A314FF2E60BCE1F5FB7EDB9CD3A;// 0x0428(0x0028) struct FAnimNode_SequencePlayer AnimGraphNode_SequencePlayer_C4D91D7B4021DD0E1549D79C4B5E5573;// 0x0450(0x0030) struct FAnimNode_Root AnimGraphNode_StateResult_314750614B6C27F1EB1EDE81E9736224;// 0x0480(0x0028) struct FAnimNode_SequencePlayer AnimGraphNode_SequencePlayer_0E8E130240F31222C619F39B5D0A0CDE;// 0x04A8(0x0030) struct FAnimNode_Root AnimGraphNode_StateResult_51AE0A424EDCC223F1BC6885CF6E682D;// 0x04D8(0x0028) struct FAnimNode_SequencePlayer AnimGraphNode_SequencePlayer_C18A56A64B5B3673FE7802BDC3B545DA;// 0x0500(0x0030) struct FAnimNode_Root AnimGraphNode_StateResult_D063D6CD41C9FC0E94E5FCBBCA43DBC6;// 0x0530(0x0028) struct FAnimNode_SequencePlayer AnimGraphNode_SequencePlayer_0B1F9D9E48D03E816115DDB638E47754;// 0x0558(0x0030) struct FAnimNode_Root AnimGraphNode_StateResult_AFFD668343AA995AB5D2E39C39BA8D97;// 0x0588(0x0028) struct FAnimNode_StateMachine AnimGraphNode_StateMachine_A81CFC5D460FCD67115E908E42AC62E0;// 0x05B0(0x0060) struct FAnimNode_Slot AnimGraphNode_Slot_B368E5AF43AD0F656248FE8C8D11260E; // 0x0610(0x0038) struct FAnimNode_Slot AnimGraphNode_Slot_CE55327E41443ED752B5FF9F20E338A9; // 0x0648(0x0038) struct FAnimNode_ModifyBone AnimGraphNode_ModifyBone_3753B438428D02A6D7BEAD8631918275;// 0x0680(0x00B0) struct FAnimNode_ConvertLocalToComponentSpace AnimGraphNode_LocalToComponentSpace_4AEF33F54406DA03A703DEB5A3D293CE;// 0x0730(0x0028) struct FAnimNode_ConvertComponentToLocalSpace AnimGraphNode_ComponentToLocalSpace_D563D4BE4EF47EDA4E429E8885891D3D;// 0x0758(0x0028) struct FAnimNode_RotationOffsetBlendSpace AnimGraphNode_RotationOffsetBlendSpace_F716FD4C42C6EEFDA55329A375324A6C;// 0x0780(0x00F8) bool bIsUnderground; // 0x0878(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) bool bIsDead; // 0x0879(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) unsigned char UnknownData00[0x2]; // 0x087A(0x0002) MISSED OFFSET struct FRotator RootRotationOffset; // 0x087C(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) struct FVector RootLocationOffset; // 0x0888(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) struct FRotator TargetRotation; // 0x0894(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float AimYaw; // 0x08A0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float AimPitch; // 0x08A4(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float AimOffsetYawScale; // 0x08A8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float AimOffsetPitchScale; // 0x08AC(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float PopUpPlayRate; // 0x08B0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float CallFunc_GetAnimAssetPlayerTimeFromEnd_ReturnValue; // 0x08B4(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool CallFunc_LessEqual_FloatFloat_ReturnValue; // 0x08B8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool CallFunc_Not_PreBool_ReturnValue; // 0x08B9(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool CallFunc_Not_PreBool_ReturnValue2; // 0x08BA(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool CallFunc_BooleanAND_ReturnValue; // 0x08BB(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool CallFunc_BooleanAND_ReturnValue2; // 0x08BC(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) unsigned char UnknownData01[0x3]; // 0x08BD(0x0003) MISSED OFFSET double CallFunc_GetGameTimeInSeconds_ReturnValue; // 0x08C0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) class APawn* CallFunc_TryGetPawnOwner_ReturnValue; // 0x08C8(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) double CallFunc_Subtract_DoubleDouble_ReturnValue; // 0x08D0(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool CallFunc_Not_PreBool_ReturnValue3; // 0x08D8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) unsigned char UnknownData02[0x3]; // 0x08D9(0x0003) MISSED OFFSET float CallFunc_Conv_DoubleToFloat_ReturnValue; // 0x08DC(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool CallFunc_BooleanOR_ReturnValue; // 0x08E0(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool CallFunc_Less_FloatFloat_ReturnValue; // 0x08E1(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) unsigned char UnknownData03[0x2]; // 0x08E2(0x0002) MISSED OFFSET float K2Node_Select_ReturnValue; // 0x08E4(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool K2Node_Select_CmpSuccess; // 0x08E8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) unsigned char UnknownData04[0x3]; // 0x08E9(0x0003) MISSED OFFSET float CallFunc_GetAnimAssetPlayerTimeFromEnd_ReturnValue2; // 0x08EC(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool CallFunc_LessEqual_FloatFloat_ReturnValue2; // 0x08F0(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) unsigned char UnknownData05[0x3]; // 0x08F1(0x0003) MISSED OFFSET float CallFunc_GetAnimAssetPlayerTimeFromEnd_ReturnValue3; // 0x08F4(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool CallFunc_BooleanAND_ReturnValue3; // 0x08F8(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool CallFunc_LessEqual_FloatFloat_ReturnValue3; // 0x08F9(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) unsigned char UnknownData06[0x2]; // 0x08FA(0x0002) MISSED OFFSET float K2Node_Event_DeltaTimeX; // 0x08FC(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) class APawn* CallFunc_TryGetPawnOwner_ReturnValue2; // 0x0900(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) class ADeathworm_Character_BP_C* K2Node_DynamicCast_AsDeathworm_Character_BP_C; // 0x0908(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool K2Node_DynamicCast_CastSuccess; // 0x0910(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) unsigned char UnknownData07[0x3]; // 0x0911(0x0003) MISSED OFFSET struct FRotator CallFunc_GetAimOffsets_RootRotOffset; // 0x0914(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) float CallFunc_GetAimOffsets_TheRootYawSpeed; // 0x0920(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) struct FVector CallFunc_GetAimOffsets_RootLocOffset; // 0x0924(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) struct FRotator CallFunc_GetAimOffsets_ReturnValue; // 0x0930(0x000C) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) float CallFunc_BreakRot_Pitch; // 0x093C(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) float CallFunc_BreakRot_Yaw; // 0x0940(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) float CallFunc_BreakRot_Roll; // 0x0944(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) float CallFunc_Divide_FloatFloat_ReturnValue; // 0x0948(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) float CallFunc_Divide_FloatFloat_ReturnValue2; // 0x094C(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) float CallFunc_Multiply_FloatFloat_ReturnValue; // 0x0950(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) float CallFunc_Add_FloatFloat_ReturnValue; // 0x0954(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) float CallFunc_FClamp_ReturnValue; // 0x0958(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) float CallFunc_Multiply_FloatFloat_ReturnValue2; // 0x095C(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) float CallFunc_Add_FloatFloat_ReturnValue2; // 0x0960(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) float CallFunc_FClamp_ReturnValue2; // 0x0964(0x0004) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindClass("AnimBlueprintGeneratedClass Deathworm_AnimBlueprint.Deathworm_AnimBlueprint_C"); return ptr; } void EvaluateGraphExposedInputs_ExecuteUbergraph_Deathworm_AnimBlueprint_AnimGraphNode_TransitionResult_3462(); void EvaluateGraphExposedInputs_ExecuteUbergraph_Deathworm_AnimBlueprint_AnimGraphNode_TransitionResult_3461(); void EvaluateGraphExposedInputs_ExecuteUbergraph_Deathworm_AnimBlueprint_AnimGraphNode_TransitionResult_3460(); void EvaluateGraphExposedInputs_ExecuteUbergraph_Deathworm_AnimBlueprint_AnimGraphNode_TransitionResult_3459(); void EvaluateGraphExposedInputs_ExecuteUbergraph_Deathworm_AnimBlueprint_AnimGraphNode_TransitionResult_3458(); void EvaluateGraphExposedInputs_ExecuteUbergraph_Deathworm_AnimBlueprint_AnimGraphNode_TransitionResult_3457(); void EvaluateGraphExposedInputs_ExecuteUbergraph_Deathworm_AnimBlueprint_AnimGraphNode_SequencePlayer_7942(); void EvaluateGraphExposedInputs_ExecuteUbergraph_Deathworm_AnimBlueprint_AnimGraphNode_ModifyBone_1080(); void EvaluateGraphExposedInputs_ExecuteUbergraph_Deathworm_AnimBlueprint_AnimGraphNode_RotationOffsetBlendSpace_390(); void BlueprintUpdateAnimation(float* DeltaTimeX); void ExecuteUbergraph_Deathworm_AnimBlueprint(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
121.553846
208
0.611378
2bite
01a80cbbc25aa7a4dd190bfaf3af3a6b5f94bf54
5,543
cpp
C++
test_apps/STM32Cube_FW_F4_V1.24.0/Projects/STM32F429I-Discovery/Demonstrations/TouchGFX/Gui/gui/src/live_data_display_screen/CityInfo.cpp
hwiwonl/ACES
9b9a6766a177c531384b863854459a7e016dbdcc
[ "NCSA" ]
null
null
null
test_apps/STM32Cube_FW_F4_V1.24.0/Projects/STM32F429I-Discovery/Demonstrations/TouchGFX/Gui/gui/src/live_data_display_screen/CityInfo.cpp
hwiwonl/ACES
9b9a6766a177c531384b863854459a7e016dbdcc
[ "NCSA" ]
null
null
null
test_apps/STM32Cube_FW_F4_V1.24.0/Projects/STM32F429I-Discovery/Demonstrations/TouchGFX/Gui/gui/src/live_data_display_screen/CityInfo.cpp
hwiwonl/ACES
9b9a6766a177c531384b863854459a7e016dbdcc
[ "NCSA" ]
null
null
null
/** ****************************************************************************** * This file is part of the TouchGFX 4.10.0 distribution. * * <h2><center>&copy; Copyright (c) 2018 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** */ #include <gui/live_data_display_screen/CityInfo.hpp> #include "BitmapDatabase.hpp" #include <texts/TextKeysAndLanguages.hpp> #include <touchgfx/Color.hpp> #include <stdlib.h> CityInfo::CityInfo() { textColor = 0x0; background.setXY(0, 0); cityName.setColor(Color::getColorFrom24BitRGB(0xFF, 0xFF, 0xFF)); cityName.setTypedText(TypedText(T_WEATHER_CITY_0)); cityName.setPosition(16, 10, 130, 24); cityNameDropShadow.setColor(Color::getColorFrom24BitRGB(0x0, 0x0, 0x0)); cityNameDropShadow.setTypedText(TypedText(T_WEATHER_CITY_0)); cityNameDropShadow.setPosition(cityName.getX() + 1, cityName.getY() + 1, cityName.getWidth(), cityName.getHeight()); cityNameDropShadow.setAlpha(128); timeAndDate.setColor(Color::getColorFrom24BitRGB(0xFF, 0xFF, 0xFF)); timeAndDate.setTypedText(TypedText(T_WEATHER_TIME_INFO_0)); timeAndDate.setPosition(16, 14 + cityName.getTextHeight(), 150, 20); timeAndDateDropShadow.setColor(Color::getColorFrom24BitRGB(0x0, 0x0, 0x0)); timeAndDateDropShadow.setTypedText(TypedText(T_WEATHER_TIME_INFO_0)); timeAndDateDropShadow.setPosition(timeAndDate.getX() + 1, timeAndDate.getY() + 1, timeAndDate.getWidth(), timeAndDate.getHeight()); timeAndDateDropShadow.setAlpha(128); largeTemperature.setColor(Color::getColorFrom24BitRGB(0xFF, 0xFF, 0xFF)); largeTemperature.setTypedText(TypedText(T_WEATHER_LARGE_TEMPERATURE)); largeTemperature.setPosition(66, 46, 150, 110); Unicode::snprintf(largeTemperatureBuffer, 4, "%d", 0); largeTemperature.setWildcard(largeTemperatureBuffer); largeTemperatureDropShadow.setColor(Color::getColorFrom24BitRGB(0x00, 0x00, 0x00)); largeTemperatureDropShadow.setTypedText(TypedText(T_WEATHER_LARGE_TEMPERATURE)); largeTemperatureDropShadow.setPosition(largeTemperature.getX() + 1, largeTemperature.getY() + 2, largeTemperature.getWidth(), largeTemperature.getHeight()); largeTemperatureDropShadow.setWildcard(largeTemperatureBuffer); largeTemperatureDropShadow.setAlpha(128); add(background); add(cityNameDropShadow); add(cityName); add(timeAndDateDropShadow); add(timeAndDate); add(largeTemperatureDropShadow); add(largeTemperature); } void CityInfo::setBitmap(BitmapId bg) { background.setBitmap(Bitmap(bg)); setWidth(background.getWidth()); setHeight(background.getHeight()); } /* Setup the CityInfo with some static city information * In a real world example this data would be live updated * and come from the model, but in this demo it is just hard coded. */ void CityInfo::setCity(Cities c) { city = c; switch (city) { case COPENHAGEN: cityName.setTypedText(TypedText(T_WEATHER_CITY_0)); cityNameDropShadow.setTypedText(TypedText(T_WEATHER_CITY_0)); timeAndDate.setTypedText(TypedText(T_WEATHER_TIME_INFO_0)); timeAndDateDropShadow.setTypedText(TypedText(T_WEATHER_TIME_INFO_0)); startTemperature = 12; break; case MUMBAI: cityName.setTypedText(TypedText(T_WEATHER_CITY_1)); cityNameDropShadow.setTypedText(TypedText(T_WEATHER_CITY_1)); timeAndDate.setTypedText(TypedText(T_WEATHER_TIME_INFO_1)); timeAndDateDropShadow.setTypedText(TypedText(T_WEATHER_TIME_INFO_1)); startTemperature = 32; break; case HONG_KONG: cityName.setTypedText(TypedText(T_WEATHER_CITY_2)); cityNameDropShadow.setTypedText(TypedText(T_WEATHER_CITY_2)); timeAndDate.setTypedText(TypedText(T_WEATHER_TIME_INFO_2)); timeAndDateDropShadow.setTypedText(TypedText(T_WEATHER_TIME_INFO_2)); startTemperature = 24; break; case NEW_YORK: cityName.setTypedText(TypedText(T_WEATHER_CITY_3)); cityNameDropShadow.setTypedText(TypedText(T_WEATHER_CITY_3)); timeAndDate.setTypedText(TypedText(T_WEATHER_TIME_INFO_3)); timeAndDateDropShadow.setTypedText(TypedText(T_WEATHER_TIME_INFO_3)); startTemperature = 16; break; default: break; } setTemperature(startTemperature); cityName.invalidate(); cityNameDropShadow.invalidate(); timeAndDate.invalidate(); timeAndDateDropShadow.invalidate(); } void CityInfo::setTemperature(int16_t newTemperature) { currentTemperature = newTemperature; Unicode::snprintf(largeTemperatureBuffer, 4, "%d", currentTemperature); largeTemperature.invalidate(); largeTemperatureDropShadow.invalidate(); } void CityInfo::adjustTemperature() { // Make sure that the temperature does not drift too far from the starting point if (currentTemperature - 2 == startTemperature) { setTemperature(currentTemperature - 1); } else if (currentTemperature + 2 == startTemperature) { setTemperature(currentTemperature + 1); } else { setTemperature(currentTemperature + ((rand() % 2) ? 1 : -1)); } }
35.305732
160
0.707379
hwiwonl
01aa903c12681817cb94b6eee532b1dd17fd3171
660
cpp
C++
test/testRandom.cpp
htran118/MD-MS-CG
80a3104101348d1c599ecc0a1e08aec855fc70a9
[ "MIT" ]
null
null
null
test/testRandom.cpp
htran118/MD-MS-CG
80a3104101348d1c599ecc0a1e08aec855fc70a9
[ "MIT" ]
null
null
null
test/testRandom.cpp
htran118/MD-MS-CG
80a3104101348d1c599ecc0a1e08aec855fc70a9
[ "MIT" ]
null
null
null
#include <iostream> #include <random> #include <cmath> using namespace std; int NUMROL = 10000; int NUMBIN = 100; int BINSZE = 0.1; int main() { default_random_engine ENGINE; normal_distribution<float> norm(0.0, 1.0); int rand[NUMBIN], rSqr[NUMBIN]; float rVal, rSqT = 0; for(int i = 0; i < NUMBIN; ++i) rand[i] = 0; for(int i = 0; i < NUMROL; ++i) { rVal = norm(ENGINE); if(abs(rVal) < (BINSZE * NUMBIN / 2)) ++rand[int(floor((rVal + BINSZE * NUMBIN / 2) / BINSZE))]; rSqT += rVal * rVal; } cout << rSqT / NUMROL << endl; for(int i = 0; i < NUMBIN; ++i) //cout << i << "\t" << rand[i] << endl; return 0; }
20
64
0.566667
htran118
01ab1caa9d18c97066657389a92ab8e27e3a9e95
1,282
cpp
C++
Nidrobb/Unitests/ToolboxTest.cpp
elias-hanna/Nidrobb
9de4b1bd63384a7c5969537be594f3248fd5c41b
[ "MIT" ]
null
null
null
Nidrobb/Unitests/ToolboxTest.cpp
elias-hanna/Nidrobb
9de4b1bd63384a7c5969537be594f3248fd5c41b
[ "MIT" ]
null
null
null
Nidrobb/Unitests/ToolboxTest.cpp
elias-hanna/Nidrobb
9de4b1bd63384a7c5969537be594f3248fd5c41b
[ "MIT" ]
null
null
null
#define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE ToolboxTest #include <boost/test/unit_test.hpp> #include "../Toolbox.hpp" BOOST_AUTO_TEST_SUITE (CreateRect) BOOST_AUTO_TEST_CASE (Positive) { int x = 10, y=20, w = 30, h=40; SDL_Rect* r = createRect(x,y,w,h); BOOST_REQUIRE(r != nullptr); //Bloquant BOOST_REQUIRE(r->x==x); BOOST_REQUIRE(r->y==y); BOOST_REQUIRE(r->w==w); BOOST_REQUIRE(r->h==h); delete r; } BOOST_AUTO_TEST_CASE (Nul) { int x = 0, y=0, w = 0, h=0; SDL_Rect* r = createRect(x,y,w,h); BOOST_REQUIRE(r != nullptr); BOOST_REQUIRE(r->x==x); BOOST_REQUIRE(r->y==y); BOOST_REQUIRE(r->w==w); BOOST_REQUIRE(r->h==h); delete r; } BOOST_AUTO_TEST_CASE (Negative) { int x = -10, y=-20, w = -30, h=-40; SDL_Rect* r = createRect(x,y,w,h); BOOST_REQUIRE(r != nullptr); BOOST_REQUIRE(r->x==x); BOOST_REQUIRE(r->y==y); BOOST_CHECK(r->w>=0); //Devrait pas autoriser w, h <0 BOOST_CHECK(r->h>=0); //Non bloquant delete r; } BOOST_AUTO_TEST_SUITE_END( ) BOOST_AUTO_TEST_SUITE (OperatorPrint) BOOST_AUTO_TEST_CASE (SDLRect) { int x = 10, y=20, w = 30, h=40; SDL_Rect* r = createRect(x,y,w,h); BOOST_REQUIRE(r != nullptr); std::cout<<"Rect : "<<x<<"/"<<y<<" - "<<w<<"/"<<h<<" = "<<*r<<std::endl; delete r; } BOOST_AUTO_TEST_SUITE_END( )
19.424242
73
0.652886
elias-hanna
01aca3435e599ebfcee6deb9b9daeeae63e33674
20,234
cpp
C++
test/rocprim/test_block_reduce.cpp
saadrahim/rocPRIM
4c8bc629b298f33e0c0df07b61f9b30503a84f27
[ "MIT" ]
null
null
null
test/rocprim/test_block_reduce.cpp
saadrahim/rocPRIM
4c8bc629b298f33e0c0df07b61f9b30503a84f27
[ "MIT" ]
null
null
null
test/rocprim/test_block_reduce.cpp
saadrahim/rocPRIM
4c8bc629b298f33e0c0df07b61f9b30503a84f27
[ "MIT" ]
null
null
null
// MIT License // // Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved. // // 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 <vector> // Google Test #include <gtest/gtest.h> // rocPRIM API #include <rocprim/rocprim.hpp> #include "test_utils.hpp" #define HIP_CHECK(error) ASSERT_EQ(static_cast<hipError_t>(error), hipSuccess) namespace rp = rocprim; template<class T, class BinaryOp> T apply(BinaryOp binary_op, const T& a, const T& b) { return binary_op(a, b); } // Params for tests template< class T, unsigned int BlockSize = 256U, unsigned int ItemsPerThread = 1U, rp::block_reduce_algorithm Algorithm = rp::block_reduce_algorithm::using_warp_reduce, class BinaryOp = rocprim::plus<T> > struct params { using type = T; using binary_op_type = BinaryOp; static constexpr rp::block_reduce_algorithm algorithm = Algorithm; static constexpr unsigned int block_size = BlockSize; static constexpr unsigned int items_per_thread = ItemsPerThread; }; // --------------------------------------------------------- // Test for reduce ops taking single input value // --------------------------------------------------------- template<class Params> class RocprimBlockReduceSingleValueTests : public ::testing::Test { public: using type = typename Params::type; using binary_op_type = typename Params::binary_op_type; static constexpr rp::block_reduce_algorithm algorithm = Params::algorithm; static constexpr unsigned int block_size = Params::block_size; }; typedef ::testing::Types< // ----------------------------------------------------------------------- // rocprim::block_reduce_algorithm::using_warp_reduce // ----------------------------------------------------------------------- params<int, 64U>, params<int, 128U>, params<int, 192U>, params<int, 256U>, params<int, 512U>, params<int, 1024U>, params<int, 65U>, params<int, 37U>, params<int, 129U>, params<int, 162U>, params<int, 255U>, // uint tests params<unsigned int, 64U>, params<unsigned int, 256U>, params<unsigned int, 377U>, // char tests params<char, 64U>, params<char, 256U>, params<char, 377U>, // half tests params<rp::half, 64U, 1, rp::block_reduce_algorithm::using_warp_reduce, test_utils::half_maximum>, params<rp::half, 256U, 1, rp::block_reduce_algorithm::using_warp_reduce, test_utils::half_maximum>, params<rp::half, 377U, 1, rp::block_reduce_algorithm::using_warp_reduce, test_utils::half_maximum>, // long tests params<long, 64U>, params<long, 256U>, params<long, 377U>, // ----------------------------------------------------------------------- // rocprim::block_reduce_algorithm::raking_reduce // ----------------------------------------------------------------------- params<int, 64U, 1, rp::block_reduce_algorithm::raking_reduce>, params<int, 128U, 1, rp::block_reduce_algorithm::raking_reduce>, params<int, 192U, 1, rp::block_reduce_algorithm::raking_reduce>, params<int, 256U, 1, rp::block_reduce_algorithm::raking_reduce>, params<int, 512U, 1, rp::block_reduce_algorithm::raking_reduce>, params<int, 1024U, 1, rp::block_reduce_algorithm::raking_reduce>, params<char, 64U, 1, rp::block_reduce_algorithm::raking_reduce>, params<char, 128U, 1, rp::block_reduce_algorithm::raking_reduce>, params<char, 192U, 1, rp::block_reduce_algorithm::raking_reduce>, params<char, 256U, 1, rp::block_reduce_algorithm::raking_reduce>, params<rp::half, 64U, 1, rp::block_reduce_algorithm::raking_reduce, test_utils::half_maximum>, params<rp::half, 128U, 1, rp::block_reduce_algorithm::raking_reduce, test_utils::half_maximum>, params<rp::half, 192U, 1, rp::block_reduce_algorithm::raking_reduce, test_utils::half_maximum>, params<rp::half, 256U, 1, rp::block_reduce_algorithm::raking_reduce, test_utils::half_maximum>, params<unsigned long, 65U, 1, rp::block_reduce_algorithm::raking_reduce>, params<long, 37U, 1, rp::block_reduce_algorithm::raking_reduce>, params<short, 162U, 1, rp::block_reduce_algorithm::raking_reduce>, params<unsigned int, 255U, 1, rp::block_reduce_algorithm::raking_reduce>, params<int, 377U, 1, rp::block_reduce_algorithm::raking_reduce>, params<unsigned char, 377U, 1, rp::block_reduce_algorithm::raking_reduce> > SingleValueTestParams; TYPED_TEST_CASE(RocprimBlockReduceSingleValueTests, SingleValueTestParams); template< unsigned int BlockSize, rocprim::block_reduce_algorithm Algorithm, class T, class BinaryOp > __global__ void reduce_kernel(T* device_output, T* device_output_reductions) { const unsigned int index = (hipBlockIdx_x * BlockSize) + hipThreadIdx_x; T value = device_output[index]; rp::block_reduce<T, BlockSize, Algorithm> breduce; breduce.reduce(value, value, BinaryOp()); if(hipThreadIdx_x == 0) { device_output_reductions[hipBlockIdx_x] = value; } } TYPED_TEST(RocprimBlockReduceSingleValueTests, Reduce) { using T = typename TestFixture::type; using binary_op_type = typename TestFixture::binary_op_type; constexpr auto algorithm = TestFixture::algorithm; constexpr size_t block_size = TestFixture::block_size; // Given block size not supported if(block_size > test_utils::get_max_block_size()) { return; } const size_t size = block_size * 113; const size_t grid_size = size / block_size; // Generate data std::vector<T> output = test_utils::get_random_data<T>(size, 2, 50); std::vector<T> output_reductions(size / block_size); // Calculate expected results on host std::vector<T> expected_reductions(output_reductions.size(), 0); binary_op_type binary_op; for(size_t i = 0; i < output.size() / block_size; i++) { T value = 0; for(size_t j = 0; j < block_size; j++) { auto idx = i * block_size + j; value = apply(binary_op, value, output[idx]); } expected_reductions[i] = value; } // Preparing device T* device_output; HIP_CHECK(hipMalloc(&device_output, output.size() * sizeof(T))); T* device_output_reductions; HIP_CHECK(hipMalloc(&device_output_reductions, output_reductions.size() * sizeof(T))); HIP_CHECK( hipMemcpy( device_output, output.data(), output.size() * sizeof(T), hipMemcpyHostToDevice ) ); // Running kernel hipLaunchKernelGGL( HIP_KERNEL_NAME(reduce_kernel<block_size, algorithm, T, binary_op_type>), dim3(grid_size), dim3(block_size), 0, 0, device_output, device_output_reductions ); // Reading results back HIP_CHECK( hipMemcpy( output_reductions.data(), device_output_reductions, output_reductions.size() * sizeof(T), hipMemcpyDeviceToHost ) ); // Verifying results test_utils::assert_eq(output_reductions, expected_reductions); HIP_CHECK(hipFree(device_output)); HIP_CHECK(hipFree(device_output_reductions)); } template< unsigned int BlockSize, rocprim::block_reduce_algorithm Algorithm, class T > __global__ void reduce_multiplies_kernel(T* device_output, T* device_output_reductions) { const unsigned int index = (hipBlockIdx_x * BlockSize) + hipThreadIdx_x; T value = device_output[index]; rp::block_reduce<T, BlockSize, Algorithm> breduce; breduce.reduce(value, value, rocprim::multiplies<T>()); if(hipThreadIdx_x == 0) { device_output_reductions[hipBlockIdx_x] = value; } } template<class T> T host_multiplies(const T& x, const T& y) { return x * y; } rp::half host_multiplies(const rp::half&, const rp::half&) { // Used to allow compilation of tests with half return rp::half(); // Any value since half is not tested in ReduceMultiplies } TYPED_TEST(RocprimBlockReduceSingleValueTests, ReduceMultiplies) { using T = typename TestFixture::type; constexpr auto algorithm = TestFixture::algorithm; constexpr size_t block_size = TestFixture::block_size; // Half not tested here if(std::is_same<T, rp::half>::value) { return; } // Given block size not supported if(block_size > test_utils::get_max_block_size()) { return; } const size_t size = block_size * 113; const size_t grid_size = size / block_size; // Generate data std::vector<T> output(size, 1); auto two_places = test_utils::get_random_data<unsigned int>(size/32, 0, size-1); for(auto i : two_places) { output[i] = T(2); } std::vector<T> output_reductions(size / block_size); // Calculate expected results on host std::vector<T> expected_reductions(output_reductions.size(), 0); for(size_t i = 0; i < output.size() / block_size; i++) { T value = 1; for(size_t j = 0; j < block_size; j++) { auto idx = i * block_size + j; value = host_multiplies(value, output[idx]); } expected_reductions[i] = value; } // Preparing device T* device_output; HIP_CHECK(hipMalloc(&device_output, output.size() * sizeof(T))); T* device_output_reductions; HIP_CHECK(hipMalloc(&device_output_reductions, output_reductions.size() * sizeof(T))); HIP_CHECK( hipMemcpy( device_output, output.data(), output.size() * sizeof(T), hipMemcpyHostToDevice ) ); // Running kernel hipLaunchKernelGGL( HIP_KERNEL_NAME(reduce_multiplies_kernel<block_size, algorithm, T>), dim3(grid_size), dim3(block_size), 0, 0, device_output, device_output_reductions ); // Reading results back HIP_CHECK( hipMemcpy( output_reductions.data(), device_output_reductions, output_reductions.size() * sizeof(T), hipMemcpyDeviceToHost ) ); // Verifying results test_utils::assert_eq(output_reductions, expected_reductions); HIP_CHECK(hipFree(device_output)); HIP_CHECK(hipFree(device_output_reductions)); } TYPED_TEST_CASE(RocprimBlockReduceSingleValueTests, SingleValueTestParams); template< unsigned int BlockSize, rocprim::block_reduce_algorithm Algorithm, class T, class BinaryOp > __global__ void reduce_valid_kernel(T* device_output, T* device_output_reductions, const unsigned int valid_items) { const unsigned int index = (hipBlockIdx_x * BlockSize) + hipThreadIdx_x; T value = device_output[index]; rp::block_reduce<T, BlockSize, Algorithm> breduce; breduce.reduce(value, value, valid_items, BinaryOp()); if(hipThreadIdx_x == 0) { device_output_reductions[hipBlockIdx_x] = value; } } TYPED_TEST(RocprimBlockReduceSingleValueTests, ReduceValid) { using T = typename TestFixture::type; using binary_op_type = typename TestFixture::binary_op_type; constexpr auto algorithm = TestFixture::algorithm; constexpr size_t block_size = TestFixture::block_size; const unsigned int valid_items = test_utils::get_random_value(block_size - 10, block_size); // Given block size not supported if(block_size > test_utils::get_max_block_size()) { return; } const size_t size = block_size * 113; const size_t grid_size = size / block_size; // Generate data std::vector<T> output = test_utils::get_random_data<T>(size, 2, 50); std::vector<T> output_reductions(size / block_size); // Calculate expected results on host std::vector<T> expected_reductions(output_reductions.size(), 0); binary_op_type binary_op; for(size_t i = 0; i < output.size() / block_size; i++) { T value = 0; for(size_t j = 0; j < valid_items; j++) { auto idx = i * block_size + j; value = apply(binary_op, value, output[idx]); } expected_reductions[i] = value; } // Preparing device T* device_output; HIP_CHECK(hipMalloc(&device_output, output.size() * sizeof(T))); T* device_output_reductions; HIP_CHECK(hipMalloc(&device_output_reductions, output_reductions.size() * sizeof(T))); HIP_CHECK( hipMemcpy( device_output, output.data(), output.size() * sizeof(T), hipMemcpyHostToDevice ) ); // Running kernel hipLaunchKernelGGL( HIP_KERNEL_NAME(reduce_valid_kernel<block_size, algorithm, T, binary_op_type>), dim3(grid_size), dim3(block_size), 0, 0, device_output, device_output_reductions, valid_items ); // Reading results back HIP_CHECK( hipMemcpy( output_reductions.data(), device_output_reductions, output_reductions.size() * sizeof(T), hipMemcpyDeviceToHost ) ); // Verifying results test_utils::assert_eq(output_reductions, expected_reductions); HIP_CHECK(hipFree(device_output)); HIP_CHECK(hipFree(device_output_reductions)); } template<class Params> class RocprimBlockReduceInputArrayTests : public ::testing::Test { public: using type = typename Params::type; using binary_op_type = typename Params::binary_op_type; static constexpr unsigned int block_size = Params::block_size; static constexpr rocprim::block_reduce_algorithm algorithm = Params::algorithm; static constexpr unsigned int items_per_thread = Params::items_per_thread; }; typedef ::testing::Types< // ----------------------------------------------------------------------- // rocprim::block_reduce_algorithm::using_warp_reduce // ----------------------------------------------------------------------- params<float, 6U, 32>, params<float, 32, 2>, params<unsigned int, 256, 3>, params<int, 512, 4>, params<float, 1024, 1>, params<float, 37, 2>, params<float, 65, 5>, params<float, 162, 7>, params<float, 255, 15>, params<char, 1024, 1>, params<char, 37, 2>, params<char, 65, 5>, params<rp::half, 1024, 1, rp::block_reduce_algorithm::using_warp_reduce, test_utils::half_maximum>, params<rp::half, 37, 2, rp::block_reduce_algorithm::using_warp_reduce, test_utils::half_maximum>, params<rp::half, 65, 5, rp::block_reduce_algorithm::using_warp_reduce, test_utils::half_maximum>, // ----------------------------------------------------------------------- // rocprim::block_reduce_algorithm::raking_reduce // ----------------------------------------------------------------------- params<float, 6U, 32, rp::block_reduce_algorithm::raking_reduce>, params<float, 32, 2, rp::block_reduce_algorithm::raking_reduce>, params<int, 256, 3, rp::block_reduce_algorithm::raking_reduce>, params<unsigned int, 512, 4, rp::block_reduce_algorithm::raking_reduce>, params<float, 1024, 1, rp::block_reduce_algorithm::raking_reduce>, params<float, 37, 2, rp::block_reduce_algorithm::raking_reduce>, params<float, 65, 5, rp::block_reduce_algorithm::raking_reduce>, params<float, 162, 7, rp::block_reduce_algorithm::raking_reduce>, params<float, 255, 15, rp::block_reduce_algorithm::raking_reduce>, params<char, 1024, 1, rp::block_reduce_algorithm::raking_reduce>, params<char, 37, 2, rp::block_reduce_algorithm::raking_reduce>, params<char, 65, 5, rp::block_reduce_algorithm::raking_reduce>, params<rp::half, 1024, 1, rp::block_reduce_algorithm::raking_reduce, test_utils::half_maximum>, params<rp::half, 37, 2, rp::block_reduce_algorithm::raking_reduce, test_utils::half_maximum>, params<rp::half, 65, 5, rp::block_reduce_algorithm::raking_reduce, test_utils::half_maximum> > InputArrayTestParams; TYPED_TEST_CASE(RocprimBlockReduceInputArrayTests, InputArrayTestParams); template< unsigned int BlockSize, unsigned int ItemsPerThread, rocprim::block_reduce_algorithm Algorithm, class T, class BinaryOp > __global__ void reduce_array_kernel(T* device_output, T* device_output_reductions) { const unsigned int index = ((hipBlockIdx_x * BlockSize) + hipThreadIdx_x) * ItemsPerThread; // load T in_out[ItemsPerThread]; for(unsigned int j = 0; j < ItemsPerThread; j++) { in_out[j] = device_output[index + j]; } rp::block_reduce<T, BlockSize, Algorithm> breduce; T reduction; breduce.reduce(in_out, reduction, BinaryOp()); if(hipThreadIdx_x == 0) { device_output_reductions[hipBlockIdx_x] = reduction; } } TYPED_TEST(RocprimBlockReduceInputArrayTests, Reduce) { using T = typename TestFixture::type; using binary_op_type = typename TestFixture::binary_op_type; constexpr auto algorithm = TestFixture::algorithm; constexpr size_t block_size = TestFixture::block_size; constexpr size_t items_per_thread = TestFixture::items_per_thread; // Given block size not supported if(block_size > test_utils::get_max_block_size()) { return; } const size_t items_per_block = block_size * items_per_thread; const size_t size = items_per_block * 37; const size_t grid_size = size / items_per_block; // Generate data std::vector<T> output = test_utils::get_random_data<T>(size, 2, 50); // Output reduce results std::vector<T> output_reductions(size / block_size, 0); // Calculate expected results on host std::vector<T> expected_reductions(output_reductions.size(), 0); binary_op_type binary_op; for(size_t i = 0; i < output.size() / items_per_block; i++) { T value = 0; for(size_t j = 0; j < items_per_block; j++) { auto idx = i * items_per_block + j; value = apply(binary_op, value, output[idx]); } expected_reductions[i] = value; } // Preparing device T* device_output; HIP_CHECK(hipMalloc(&device_output, output.size() * sizeof(T))); T* device_output_reductions; HIP_CHECK(hipMalloc(&device_output_reductions, output_reductions.size() * sizeof(T))); HIP_CHECK( hipMemcpy( device_output, output.data(), output.size() * sizeof(T), hipMemcpyHostToDevice ) ); HIP_CHECK( hipMemcpy( device_output_reductions, output_reductions.data(), output_reductions.size() * sizeof(T), hipMemcpyHostToDevice ) ); // Running kernel hipLaunchKernelGGL( HIP_KERNEL_NAME(reduce_array_kernel<block_size, items_per_thread, algorithm, T, binary_op_type>), dim3(grid_size), dim3(block_size), 0, 0, device_output, device_output_reductions ); // Reading results back HIP_CHECK( hipMemcpy( output_reductions.data(), device_output_reductions, output_reductions.size() * sizeof(T), hipMemcpyDeviceToHost ) ); // Verifying results test_utils::assert_near(output_reductions, expected_reductions, 0.05); HIP_CHECK(hipFree(device_output)); HIP_CHECK(hipFree(device_output_reductions)); }
34.64726
105
0.661708
saadrahim
01acc91ff0f87252de65216ec877bd878fbbb682
913
cpp
C++
src/IsoGame/Play/Rooms/ShooterRoom.cpp
Harry09/IsoGame
7320bee14197b66a96f432d4071537b3bb892c13
[ "MIT" ]
null
null
null
src/IsoGame/Play/Rooms/ShooterRoom.cpp
Harry09/IsoGame
7320bee14197b66a96f432d4071537b3bb892c13
[ "MIT" ]
null
null
null
src/IsoGame/Play/Rooms/ShooterRoom.cpp
Harry09/IsoGame
7320bee14197b66a96f432d4071537b3bb892c13
[ "MIT" ]
null
null
null
#include "ShooterRoom.h" #include <Common\Random.h> #include <Play\Objects\Entities\Enemies\Shooter.h> #include <Play\Objects\Rock.h> ShooterRoom::ShooterRoom(Map *parent, const sf::Vector2i &pos) : Room(parent, pos) { m_isRoomClear = false; m_roomType = Room::ENEMY; auto playZone = GetPlayZone(); Random random; for (int i = 0; i < random.Get<int>(1, 3); ++i) { float x = random.Get<float>(playZone.left, playZone.left + playZone.width); float y = random.Get<float>(playZone.top, playZone.top + playZone.height); AddObject(new Shooter(sf::Vector2f(x, y))); } for (int i = 0; i < random.Get<int>(4, 6); ++i) { float x = random.Get<float>(playZone.left, playZone.left + playZone.width); float y = random.Get<float>(playZone.top, playZone.top + playZone.height); AddObject(new Rock(sf::Vector2f(x, y))); } m_roomColor = sf::Color(0x5C6BC0FF); } ShooterRoom::~ShooterRoom() { }
21.738095
77
0.67908
Harry09
01af6663d4e513c5d9e6eb067655257b87986187
2,282
cpp
C++
LeetCodeCPP/212. Word Search II/main.cpp
18600130137/leetcode
fd2dc72c0b85da50269732f0fcf91326c4787d3a
[ "Apache-2.0" ]
1
2019-03-29T03:33:56.000Z
2019-03-29T03:33:56.000Z
LeetCodeCPP/212. Word Search II/main.cpp
18600130137/leetcode
fd2dc72c0b85da50269732f0fcf91326c4787d3a
[ "Apache-2.0" ]
null
null
null
LeetCodeCPP/212. Word Search II/main.cpp
18600130137/leetcode
fd2dc72c0b85da50269732f0fcf91326c4787d3a
[ "Apache-2.0" ]
null
null
null
// // main.cpp // 212. Word Search II // // Created by admin on 2019/6/13. // Copyright © 2019年 liu. All rights reserved. // #include <iostream> #include <vector> #include <string> using namespace std; class TrieNode{ public: TrieNode *next[26]; string word; TrieNode(){ word=""; memset(next,NULL,sizeof(next)); } }; class Solution { private: TrieNode * buildTrieNode(vector<string>& words){ TrieNode* root=new TrieNode(); for(string word:words){ TrieNode* cur=root; for(char c:word){ if(cur->next[c-'a']==NULL){ cur->next[c-'a']=new TrieNode(); } cur=cur->next[c-'a']; } cur->word=word; } return root; } void dfs(vector<vector<char>>& board,int i,int j,TrieNode *cur,vector<string> &ret){ const char c=board[i][j]; if(c=='#' || cur->next[c-'a']==NULL){ return; } cur=cur->next[c-'a']; if(cur->word!=""){ //防止重复 ret.push_back(cur->word); cur->word=""; } board[i][j]='#'; if(i>0) dfs(board,i-1,j,cur,ret); if(j>0) dfs(board,i,j-1,cur,ret); if(i<board.size()-1) dfs(board,i+1,j,cur,ret); if(j<board[0].size()-1) dfs(board,i,j+1,cur,ret); board[i][j]=c; } public: vector<string> findWords(vector<vector<char>>& board,vector<string> &words) { int m=board.size(); if(m==0){ return {}; } int n=board[0].size(); if(n==0){ return {}; } TrieNode* root=buildTrieNode(words); vector<string> ret; for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ dfs(board,i,j,root,ret); } } return ret; } }; int main(int argc, const char * argv[]) { vector<vector<char>> input1={{'o','a','a','n'},{'e','t','a','e'},{'i','h','k','r'},{'i','f','l','v'}}; vector<string> input2={"oath","pea","eat","rain"}; Solution so=Solution(); vector<string> ret=so.findWords(input1, input2); for(auto r:ret){ cout<<r<<" "; } cout<<endl; return 0; }
23.525773
107
0.468449
18600130137
01af913d446d653333760ee24a0a8a473afc85dc
3,400
hpp
C++
include/codegen/include/GlobalNamespace/PlayerHeightSettingsController.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/GlobalNamespace/PlayerHeightSettingsController.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/GlobalNamespace/PlayerHeightSettingsController.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.MonoBehaviour #include "UnityEngine/MonoBehaviour.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: TMPro namespace TMPro { // Forward declaring type: TextMeshProUGUI class TextMeshProUGUI; } // Forward declaring namespace: UnityEngine::UI namespace UnityEngine::UI { // Forward declaring type: Button class Button; } // Forward declaring namespace: GlobalNamespace namespace GlobalNamespace { // Forward declaring type: Vector3SO class Vector3SO; // Forward declaring type: VRPlatformHelper class VRPlatformHelper; // Forward declaring type: PlayerSpecificSettings class PlayerSpecificSettings; } // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: CanvasGroup class CanvasGroup; } // Forward declaring namespace: HMUI namespace HMUI { // Forward declaring type: ButtonBinder class ButtonBinder; } // Completed forward declares // Type namespace: namespace GlobalNamespace { // Autogenerated type: PlayerHeightSettingsController class PlayerHeightSettingsController : public UnityEngine::MonoBehaviour { public: // private TMPro.TextMeshProUGUI _text // Offset: 0x18 TMPro::TextMeshProUGUI* text; // private UnityEngine.UI.Button _setButton // Offset: 0x20 UnityEngine::UI::Button* setButton; // private Vector3SO _roomCenter // Offset: 0x28 GlobalNamespace::Vector3SO* roomCenter; // private UnityEngine.CanvasGroup _canvasGroup // Offset: 0x30 UnityEngine::CanvasGroup* canvasGroup; // private VRPlatformHelper _vrPlatformHelper // Offset: 0x38 GlobalNamespace::VRPlatformHelper* vrPlatformHelper; // private PlayerSpecificSettings _playerSettings // Offset: 0x40 GlobalNamespace::PlayerSpecificSettings* playerSettings; // private HMUI.ButtonBinder _buttonBinder // Offset: 0x48 HMUI::ButtonBinder* buttonBinder; // public System.Void set_interactable(System.Boolean value) // Offset: 0xBDED84 void set_interactable(bool value); // protected System.Void Awake() // Offset: 0xBDEE1C void Awake(); // public System.Void Init(PlayerSpecificSettings playerSettings) // Offset: 0xBDEEE0 void Init(GlobalNamespace::PlayerSpecificSettings* playerSettings); // private System.Void AutoSetHeight() // Offset: 0xBDEFAC void AutoSetHeight(); // private System.Void RefreshUI() // Offset: 0xBDEF08 void RefreshUI(); // public System.Void .ctor() // Offset: 0xBDF058 // Implemented from: UnityEngine.MonoBehaviour // Base method: System.Void MonoBehaviour::.ctor() // Base method: System.Void Behaviour::.ctor() // Base method: System.Void Component::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() static PlayerHeightSettingsController* New_ctor(); }; // PlayerHeightSettingsController } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::PlayerHeightSettingsController*, "", "PlayerHeightSettingsController"); #pragma pack(pop)
35.051546
111
0.726471
Futuremappermydud
01afe0535cfe3ca9df69abddfc03bbfe3764613f
7,739
cpp
C++
tests/src/types/src/types_test.cpp
hymanat/Karabiner-Elements
af955113ee0a5990ba52a467cad43a9f590b2e79
[ "Unlicense" ]
1
2021-11-09T10:28:50.000Z
2021-11-09T10:28:50.000Z
tests/src/types/src/types_test.cpp
bland328/Karabiner-Elements
328df25e09837cd29023def17d552830bf6cdba2
[ "Unlicense" ]
null
null
null
tests/src/types/src/types_test.cpp
bland328/Karabiner-Elements
328df25e09837cd29023def17d552830bf6cdba2
[ "Unlicense" ]
null
null
null
#include <catch2/catch.hpp> #include "types.hpp" TEST_CASE("make_key_code") { REQUIRE(krbn::make_key_code("spacebar") == krbn::key_code::spacebar); REQUIRE(krbn::make_key_code("unknown") == std::nullopt); REQUIRE(krbn::make_key_code_name(krbn::key_code::spacebar) == std::string("spacebar")); REQUIRE(krbn::make_key_code_name(krbn::key_code::left_option) == std::string("left_alt")); REQUIRE(krbn::make_key_code_name(krbn::key_code::extra_) == std::string("(number:65536)")); REQUIRE(krbn::make_hid_usage_page(krbn::key_code(1234)) == krbn::hid_usage_page::keyboard_or_keypad); REQUIRE(krbn::make_hid_usage(krbn::key_code(1234)) == krbn::hid_usage(1234)); { auto actual = krbn::make_key_code(krbn::hid_usage_page(kHIDPage_KeyboardOrKeypad), krbn::hid_usage(kHIDUsage_KeyboardTab)); REQUIRE(*actual == krbn::key_code(kHIDUsage_KeyboardTab)); } { auto actual = krbn::make_key_code(krbn::hid_usage_page(krbn::kHIDPage_AppleVendorTopCase), krbn::hid_usage(krbn::kHIDUsage_AV_TopCase_KeyboardFn)); REQUIRE(*actual == krbn::key_code::fn); } { auto actual = krbn::make_key_code(krbn::hid_usage_page(krbn::kHIDPage_AppleVendorKeyboard), krbn::hid_usage(krbn::kHIDUsage_AppleVendorKeyboard_Function)); REQUIRE(*actual == krbn::key_code::fn); } { auto actual = krbn::make_key_code(krbn::hid_usage_page::keyboard_or_keypad, krbn::hid_usage(1234)); REQUIRE(*actual == krbn::key_code(1234)); } { auto actual = krbn::make_key_code(krbn::hid_usage_page(kHIDPage_Button), krbn::hid_usage(1)); REQUIRE(actual == std::nullopt); } // from_json { nlohmann::json json("escape"); REQUIRE(krbn::key_code(json) == krbn::key_code::escape); } { nlohmann::json json(static_cast<uint32_t>(krbn::key_code::escape)); REQUIRE(krbn::key_code(json) == krbn::key_code::escape); } { nlohmann::json json; REQUIRE_THROWS_AS( krbn::key_code(json), pqrs::json::unmarshal_error); REQUIRE_THROWS_WITH( krbn::key_code(json), "json must be string or number, but is `null`"); } { nlohmann::json json("unknown_value"); REQUIRE_THROWS_AS( krbn::key_code(json), pqrs::json::unmarshal_error); REQUIRE_THROWS_WITH( krbn::key_code(json), "unknown key_code: `\"unknown_value\"`"); } } TEST_CASE("make_key_code (modifier_flag)") { REQUIRE(krbn::make_key_code(krbn::modifier_flag::zero) == std::nullopt); REQUIRE(krbn::make_key_code(krbn::modifier_flag::caps_lock) == krbn::key_code::caps_lock); REQUIRE(krbn::make_key_code(krbn::modifier_flag::left_control) == krbn::key_code::left_control); REQUIRE(krbn::make_key_code(krbn::modifier_flag::left_shift) == krbn::key_code::left_shift); REQUIRE(krbn::make_key_code(krbn::modifier_flag::left_option) == krbn::key_code::left_option); REQUIRE(krbn::make_key_code(krbn::modifier_flag::left_command) == krbn::key_code::left_command); REQUIRE(krbn::make_key_code(krbn::modifier_flag::right_control) == krbn::key_code::right_control); REQUIRE(krbn::make_key_code(krbn::modifier_flag::right_shift) == krbn::key_code::right_shift); REQUIRE(krbn::make_key_code(krbn::modifier_flag::right_option) == krbn::key_code::right_option); REQUIRE(krbn::make_key_code(krbn::modifier_flag::right_command) == krbn::key_code::right_command); REQUIRE(krbn::make_key_code(krbn::modifier_flag::fn) == krbn::key_code::fn); REQUIRE(krbn::make_key_code(krbn::modifier_flag::end_) == std::nullopt); } TEST_CASE("make_modifier_flag") { REQUIRE(krbn::make_modifier_flag(krbn::key_code::caps_lock) == std::nullopt); REQUIRE(krbn::make_modifier_flag(krbn::key_code::left_control) == krbn::modifier_flag::left_control); REQUIRE(krbn::make_modifier_flag(krbn::key_code::left_shift) == krbn::modifier_flag::left_shift); REQUIRE(krbn::make_modifier_flag(krbn::key_code::left_option) == krbn::modifier_flag::left_option); REQUIRE(krbn::make_modifier_flag(krbn::key_code::left_command) == krbn::modifier_flag::left_command); REQUIRE(krbn::make_modifier_flag(krbn::key_code::right_control) == krbn::modifier_flag::right_control); REQUIRE(krbn::make_modifier_flag(krbn::key_code::right_shift) == krbn::modifier_flag::right_shift); REQUIRE(krbn::make_modifier_flag(krbn::key_code::right_option) == krbn::modifier_flag::right_option); REQUIRE(krbn::make_modifier_flag(krbn::key_code::right_command) == krbn::modifier_flag::right_command); REQUIRE(krbn::make_modifier_flag(krbn::key_code::fn) == krbn::modifier_flag::fn); REQUIRE(krbn::make_modifier_flag(krbn::hid_usage_page::keyboard_or_keypad, krbn::hid_usage(kHIDUsage_KeyboardA)) == std::nullopt); REQUIRE(krbn::make_modifier_flag(krbn::hid_usage_page::keyboard_or_keypad, krbn::hid_usage(kHIDUsage_KeyboardErrorRollOver)) == std::nullopt); REQUIRE(krbn::make_modifier_flag(krbn::hid_usage_page::keyboard_or_keypad, krbn::hid_usage(kHIDUsage_KeyboardLeftShift)) == krbn::modifier_flag::left_shift); REQUIRE(krbn::make_modifier_flag(krbn::hid_usage_page::button, krbn::hid_usage(1)) == std::nullopt); } TEST_CASE("make_consumer_key_code") { REQUIRE(krbn::make_consumer_key_code("mute") == krbn::consumer_key_code::mute); REQUIRE(!krbn::make_consumer_key_code("unknown")); REQUIRE(krbn::make_consumer_key_code_name(krbn::consumer_key_code::mute) == std::string("mute")); REQUIRE(krbn::make_consumer_key_code_name(krbn::consumer_key_code(12345)) == std::string("(number:12345)")); REQUIRE(krbn::make_consumer_key_code(krbn::hid_usage_page::consumer, krbn::hid_usage::csmr_mute) == krbn::consumer_key_code::mute); REQUIRE(!krbn::make_consumer_key_code(krbn::hid_usage_page::keyboard_or_keypad, krbn::hid_usage(kHIDUsage_KeyboardA))); REQUIRE(krbn::make_hid_usage_page(krbn::consumer_key_code::mute) == krbn::hid_usage_page::consumer); REQUIRE(krbn::make_hid_usage(krbn::consumer_key_code::mute) == krbn::hid_usage::csmr_mute); // from_json { nlohmann::json json("mute"); REQUIRE(krbn::consumer_key_code(json) == krbn::consumer_key_code::mute); } { nlohmann::json json(static_cast<uint32_t>(krbn::consumer_key_code::mute)); REQUIRE(krbn::consumer_key_code(json) == krbn::consumer_key_code::mute); } { nlohmann::json json; REQUIRE_THROWS_AS( krbn::consumer_key_code(json), pqrs::json::unmarshal_error); REQUIRE_THROWS_WITH( krbn::key_code(json), "json must be string or number, but is `null`"); } { nlohmann::json json("unknown_value"); REQUIRE_THROWS_AS( krbn::consumer_key_code(json), pqrs::json::unmarshal_error); REQUIRE_THROWS_WITH( krbn::consumer_key_code(json), "unknown consumer_key_code: `\"unknown_value\"`"); } } TEST_CASE("make_pointing_button") { REQUIRE(krbn::make_pointing_button("button1") == krbn::pointing_button::button1); REQUIRE(!krbn::make_pointing_button("unknown")); REQUIRE(krbn::make_pointing_button_name(krbn::pointing_button::button1) == std::string("button1")); REQUIRE(krbn::make_pointing_button_name(krbn::pointing_button(12345)) == std::string("(number:12345)")); { auto actual = krbn::make_pointing_button(krbn::hid_usage_page(kHIDPage_Button), krbn::hid_usage(1)); REQUIRE(*actual == krbn::pointing_button::button1); } { auto actual = krbn::make_pointing_button(krbn::hid_usage_page(kHIDPage_KeyboardOrKeypad), krbn::hid_usage(kHIDUsage_KeyboardTab)); REQUIRE(actual == std::nullopt); } }
46.90303
159
0.70513
hymanat
01b1224e96bd6bea7444be3a10d1e36c64bd2b44
168
hpp
C++
lib/language_framework.hpp
s9rA16Bf4/language_framework
231b3a615be88f080329c98bfc46502e9d3777e6
[ "MIT" ]
null
null
null
lib/language_framework.hpp
s9rA16Bf4/language_framework
231b3a615be88f080329c98bfc46502e9d3777e6
[ "MIT" ]
null
null
null
lib/language_framework.hpp
s9rA16Bf4/language_framework
231b3a615be88f080329c98bfc46502e9d3777e6
[ "MIT" ]
null
null
null
#ifndef MAIN_HPP #define MAIN_HPP 1 #define FRAMEWORK_VERSION "1.0" #include "custom.hpp" // Base headers #include "interpreter.hpp" #include "function.hpp" #endif
12.923077
31
0.744048
s9rA16Bf4
01ba0c69d7e84f272c22ff4df5725eef1e7bee88
346
hpp
C++
approach_boost_serialization/bus_group_ser.hpp
noahleft/serialization
731ebcee68339960308a86b25cf3c11ba815043e
[ "MIT" ]
null
null
null
approach_boost_serialization/bus_group_ser.hpp
noahleft/serialization
731ebcee68339960308a86b25cf3c11ba815043e
[ "MIT" ]
null
null
null
approach_boost_serialization/bus_group_ser.hpp
noahleft/serialization
731ebcee68339960308a86b25cf3c11ba815043e
[ "MIT" ]
null
null
null
#ifndef BUS_GROUP_SER_HPP #define BUS_GROUP_SER_HPP #include "bus_group.hpp" #include "bus_route_ser.hpp" #include <boost/serialization/vector.hpp> namespace boost { namespace serialization { template<class Archive> void serialize(Archive & ar, bus_group & obj, const unsigned int version) { ar & obj.groups; } } } #endif
18.210526
79
0.725434
noahleft
01cba97435271210885bf306469f7fe834e61162
1,133
hpp
C++
modules/services/pathfinder_cpp/bld/fsa.hpp
memristor/mep2
bc5cddacba3d740f791f3454b8cb51bda83ce202
[ "MIT" ]
5
2018-11-27T15:15:00.000Z
2022-02-10T21:44:13.000Z
modules/services/pathfinder_cpp/fsa.hpp
memristor/mep2
bc5cddacba3d740f791f3454b8cb51bda83ce202
[ "MIT" ]
2
2018-10-20T15:48:40.000Z
2018-11-20T05:11:33.000Z
modules/services/pathfinder_cpp/fsa.hpp
memristor/mep2
bc5cddacba3d740f791f3454b8cb51bda83ce202
[ "MIT" ]
1
2020-02-07T12:44:47.000Z
2020-02-07T12:44:47.000Z
#ifndef FSA_H #define FSA_H #include <cstring> #include <iostream> template <class T, int N = 100> class FixedSizeAllocator { private: struct FSAElem { T userElement; FSAElem *pNext; }; FSAElem *m_pFirstFree; int m_pMemory[(sizeof(FSAElem) * N) / sizeof(int) + 1]; public: FixedSizeAllocator(bool clear_memory = false) { m_pFirstFree = (FSAElem*)m_pMemory; if(clear_memory) memset( m_pMemory, 0, sizeof(FSAElem) * N ); FSAElem *elem = m_pFirstFree; for(unsigned int i=0; i<N; i++) { elem->pNext = elem+1; elem++; } (elem-1)->pNext = NULL; } template<class... Args> T* alloc(Args&&... args) { FSAElem *pNewNode; if(!m_pFirstFree) { std::cout << "NULLLLL !!!!!!! " << typeid(T).name() << " " << T::ref_count << "\n"; return NULL; } else { pNewNode = m_pFirstFree; new (&pNewNode->userElement) T(args...); m_pFirstFree = m_pFirstFree->pNext; } return reinterpret_cast<T*>(pNewNode); } void free(T *user_data) { FSAElem *pNode = reinterpret_cast<FSAElem*>(user_data); user_data->~T(); pNode->pNext = m_pFirstFree; m_pFirstFree = pNode; } }; #endif
21.377358
86
0.633716
memristor
01d47a71ae639e745b34f274d99721d93d2b7a23
2,900
cpp
C++
Queue/Deque_Using_Circular_Array.cpp
susantabiswas/placementPrep
22a7574206ddc63eba89517f7b68a3d2f4d467f5
[ "MIT" ]
19
2018-12-02T05:59:44.000Z
2021-07-24T14:11:54.000Z
Queue/Deque_Using_Circular_Array.cpp
susantabiswas/placementPrep
22a7574206ddc63eba89517f7b68a3d2f4d467f5
[ "MIT" ]
null
null
null
Queue/Deque_Using_Circular_Array.cpp
susantabiswas/placementPrep
22a7574206ddc63eba89517f7b68a3d2f4d467f5
[ "MIT" ]
13
2019-04-25T16:20:00.000Z
2021-09-06T19:50:04.000Z
//Circular linked list using Array #include<iostream> #include<vector> using namespace std; struct CLL{ vector<int> arr; int rear = -1; int beg = -1; int n = 0; CLL(int n){ arr.resize(n); this->n = n; } }; bool isFull(CLL* head){ if( head->beg == head->rear+1 || head->beg == 0 && head->rear == head->n-1) return true; else return false; } bool isEmpty(CLL *head){ if(head->beg == -1 ) return true; else return false; } //for displaying the elements void disp(CLL *head){ for(int i = 0; i<head->n; i++) cout<<head->arr[i]<<" "; cout<<endl; } //for insertion in End void insertEnd(CLL *head,int data){ cout<<endl<<"*********************PUSH******************\n"; cout<<"Before data:"<<data<<" beg:"<<head->beg<<" rear:"<<head->rear<<endl; if(isFull(head)) return; if(head->beg == -1) head->beg =head->rear = 0; else if(head->rear == head->n - 1) head->rear = 0; else head->rear ++; head->arr[head->rear] = data; cout<<"After data:"<<data<<" beg:"<<head->beg<<" rear:"<<head->rear<<endl; disp(head); } //insertion at Begining void insertBegin(CLL *head,int data){ cout<<endl<<"*********************PUSH******************\n"; cout<<"Before data:"<<data<<" beg:"<<head->beg<<" rear:"<<head->rear<<endl; if(isFull(head)) return; if(head->beg == -1) head->beg =head->rear = 0; //update the writable index for front position else if(head->beg == 0) head->beg = head->n -1; else head->beg --; //push the element head->arr[head->beg] = data; cout<<"After data:"<<data<<" beg:"<<head->beg<<" rear:"<<head->rear<<endl; disp(head); } //for deletion in begining void delBegin(CLL *head){ cout<<endl<<"*********************POP******************\n"; cout<<"Before beg:"<<head->beg<<" rear:"<<head->rear<<endl; if(isEmpty(head)) return; if(head->beg == head->rear) head->beg =head->rear = -1; else if(head->beg == head->n -1) head->beg = 0; else head->beg++; cout<<"After beg:"<<head->beg<<" rear:"<<head->rear<<endl; disp(head); } //deleteion at end void deleteEnd(CLL *head){ cout<<endl<<"*********************POP******************\n"; cout<<"Before beg:"<<head->beg<<" rear:"<<head->rear<<endl; if(isEmpty(head)) return; if(head->beg == head->rear) head->beg = head->rear = -1; else if(head->rear == 0) head->rear = head->n -1 ; else head->rear--; cout<<"After beg:"<<head->beg<<" rear:"<<head->rear<<endl; disp(head); } int main(){ CLL *head = new CLL(5); insertEnd(head,1); insertEnd(head,2); insertEnd(head,3); delBegin(head); delBegin(head); //insertEnd(head,3); insertEnd(head,4); insertEnd(head,5); insertEnd(head,6); insertEnd(head,7); insertEnd(head,8); disp(head); cout<<" **beg:"<<head->beg<<" rear:"<<head->rear<<endl; delBegin(head); delBegin(head); delBegin(head); deleteEnd(head);deleteEnd(head); insertBegin(head,44); insertEnd(head,55); disp(head); return 0; }
20.714286
76
0.574828
susantabiswas
01dcf6d7a7b9d9eb39557865ab2878023d65ec3a
1,931
cpp
C++
src/Engine/UI/ListGUI.cpp
BclEx/h3ml
acfcccbdadcffa7b2c1794393a26359ad7c8479b
[ "MIT" ]
null
null
null
src/Engine/UI/ListGUI.cpp
BclEx/h3ml
acfcccbdadcffa7b2c1794393a26359ad7c8479b
[ "MIT" ]
null
null
null
src/Engine/UI/ListGUI.cpp
BclEx/h3ml
acfcccbdadcffa7b2c1794393a26359ad7c8479b
[ "MIT" ]
null
null
null
#include "ListGUILocal.h" void ListGUILocal::StateChanged() { if (!_stateUpdates) return; int i; for (i = 0; i < Num(); i++) _gui->SetStateString(va("%s_item_%i", _name.c_str(), i), (*this)[i].c_str()); for (i = Num(); i < _water; i++) _gui->SetStateString(va("%s_item_%i", m_name.c_str(), i), ""); _water = Num(); _gui->StateChanged(Sys_Milliseconds()); } int ListGUILocal::GetNumSelections() { return _gui->State().GetInt(va("%s_numsel", _name.c_str())); } int ListGUILocal::GetSelection(char *s, int size, int _sel) const { if (s) s[0] = '\0'; int sel = _gui->State().GetInt(va("%s_sel_%i", _name.c_str(), _sel), "-1"); if (sel == -1 || sel >= _ids.Num()) return -1; if (s) idStr::snPrintf(s, size, _gui->State().GetString(va("%s_item_%i", _name.c_str(), sel), "")); // don't let overflow if (sel >= _ids.Num()) sel = 0; _gui->SetStateInt(va("%s_selid_0", _name.c_str()), _ids[sel]); return m_ids[sel]; } void ListGUILocal::SetSelection(int sel) { _gui->SetStateInt(va("%s_sel_0", _name.c_str()), sel); StateChanged(); } void ListGUILocal::Add(int id, const string &s) { int i = _ids.FindIndex(id); if (i == -1) { Append(s); m_ids.Append(id); } else (*this)[i] = s; StateChanged(); } void ListGUILocal::Push(const string &s) { Append(s); _ids.Append(_ids.Num()); StateChanged(); } bool ListGUILocal::Del(int id) { int i = _ids.FindIndex(id); if (i == -1) return false; _ids.RemoveIndex(i); this->RemoveIndex(i); StateChanged(); return true; } void ListGUILocal::Clear() { _ids.Clear(); vector<string, TAG_OLD_UI>::Clear(); if (_gui) // will clear all the GUI variables and will set m_water back to 0 StateChanged(); } bool ListGUILocal::IsConfigured() const { return (_gui != nullptr); } void ListGUILocal::SetStateChanges(bool enable) { _stateUpdates = enable; StateChanged(); } void ListGUILocal::Shutdown() { _gui = nullptr; _name.Clear(); Clear(); }
20.542553
94
0.640601
BclEx
01dea22851ce7efe9a2305c72028f7b12edadc08
5,978
hpp
C++
src/util/raft/node.hpp
vipinsun/opencbdc-tx
724f307548f92676423e98d7f2c1bfc2c66f79ef
[ "MIT" ]
1
2022-02-07T22:36:36.000Z
2022-02-07T22:36:36.000Z
src/util/raft/node.hpp
vipinsun/opencbdc-tx
724f307548f92676423e98d7f2c1bfc2c66f79ef
[ "MIT" ]
null
null
null
src/util/raft/node.hpp
vipinsun/opencbdc-tx
724f307548f92676423e98d7f2c1bfc2c66f79ef
[ "MIT" ]
null
null
null
// Copyright (c) 2021 MIT Digital Currency Initiative, // Federal Reserve Bank of Boston // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef OPENCBDC_TX_SRC_RAFT_NODE_H_ #define OPENCBDC_TX_SRC_RAFT_NODE_H_ #include "console_logger.hpp" #include "state_manager.hpp" #include "util/common/config.hpp" #include "util/network/connection_manager.hpp" #include <libnuraft/nuraft.hxx> namespace cbdc::raft { /// A NuRaft state machine execution result. using result_type = nuraft::cmd_result<nuraft::ptr<nuraft::buffer>>; /// Function type for raft state machine execution result callbacks. using callback_type = std::function<void(result_type& r, nuraft::ptr<std::exception>& err)>; /// \brief A node in a raft cluster. /// /// Wrapper for replicated state machine functionality using raft from the /// external library NuRaft. Builds a cluster with other raft /// nodes. Uses NuRaft to durably replicate log entries between a quorum of /// raft nodes. Callers provide a state machine to execute the log entries /// and return the execution result. class node { public: node() = delete; node(const node&) = delete; auto operator=(const node&) -> node& = delete; node(node&&) = delete; auto operator=(node&&) -> node& = delete; /// Constructor. /// \param node_id identifier of the node in the raft cluster. Must be /// 0 or greater. /// \param raft_endpoint TCP endpoint upon which to listen for incoming raft /// connections. /// \param node_type name of the raft cluster this node will be part /// of. /// \param blocking true if replication calls should block until the /// state machine makes an execution result available. /// \param sm pointer to the state machine replicated by the cluster. /// \param asio_thread_pool_size number of threads for processing raft /// messages. Set to 0 to use the number /// of cores on the system. /// \param logger log instance NuRaft should use. /// \param raft_cb NuRaft callback to report raft events. node(int node_id, const network::endpoint_t& raft_endpoint, const std::string& node_type, bool blocking, nuraft::ptr<nuraft::state_machine> sm, size_t asio_thread_pool_size, std::shared_ptr<logging::log> logger, nuraft::cb_func::func_type raft_cb); ~node(); /// Initializes the NuRaft instance with the given state machine and /// raft parameters. /// \param raft_params NuRaft-specific parameters for the raft node. /// \return true if the raft node initialized successfully. auto init(const nuraft::raft_params& raft_params) -> bool; /// Connect to each of the given raft nodes and join them to the /// cluster. If this node is not node 0, this method blocks until /// node 0 joins this node to the cluster. /// \param raft_servers node endpoints of the other raft nodes in the /// cluster. /// \return true if adding the nodes to the raft cluster succeeded. auto build_cluster(const std::vector<network::endpoint_t>& raft_servers) -> bool; /// Indicates whether this node is the current raft leader. /// \return true if this node is the leader. [[nodiscard]] auto is_leader() const -> bool; /// Replicates the given log entry in the cluster. Calls the given /// callback with the state machine execution result. /// \param new_log log entry to replicate. /// \param result_fn callback function to call asynchronously with the /// state machine execution result. /// \return true if the log entry was accepted for replication. [[nodiscard]] auto replicate(nuraft::ptr<nuraft::buffer> new_log, const callback_type& result_fn) const -> bool; /// Replicates the provided log entry and returns the results from the /// state machine if the replication was successful. The method will /// block until the result is available or replication has failed. /// \param new_log raft log entry to replicate /// \return result from state machine or empty optional if replication /// failed [[nodiscard]] auto replicate_sync(const nuraft::ptr<nuraft::buffer>& new_log) const -> std::optional<nuraft::ptr<nuraft::buffer>>; /// Returns the last replicated log index. /// \return log index. [[nodiscard]] auto last_log_idx() const -> uint64_t; /// Returns a pointer to the state machine replicated by this raft /// node. /// \return pointer to the state machine. [[nodiscard]] auto get_sm() const -> nuraft::state_machine*; /// Shut down the NuRaft instance. void stop(); private: uint32_t m_node_id; bool m_blocking; int m_port; nuraft::ptr<nuraft::logger> m_raft_logger; nuraft::ptr<state_manager> m_smgr; nuraft::ptr<nuraft::state_machine> m_sm; nuraft::raft_launcher m_launcher; nuraft::ptr<nuraft::raft_server> m_raft_instance; nuraft::asio_service::options m_asio_opt; nuraft::raft_server::init_options m_init_opts; [[nodiscard]] auto add_cluster_nodes( const std::vector<network::endpoint_t>& raft_servers) const -> bool; }; } #endif // OPENCBDC_TX_SRC_RAFT_NODE_H_
43.007194
84
0.620442
vipinsun
01e311d5e32d8ad2ab4cf442fdd81a5f30d2f25c
781
cpp
C++
POINTMEE.cpp
Himanshu1801/codechef
100785c10f49e5200e82e68f10d7a6213b31b821
[ "Apache-2.0" ]
null
null
null
POINTMEE.cpp
Himanshu1801/codechef
100785c10f49e5200e82e68f10d7a6213b31b821
[ "Apache-2.0" ]
null
null
null
POINTMEE.cpp
Himanshu1801/codechef
100785c10f49e5200e82e68f10d7a6213b31b821
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--) { int n; int x[n],y[n]; int count=0,k,a,b; cin>>n; for (int i = 0; i < n; i++) { cin>>x[i]; cin>>y[i]; } for (int i = 0; i < n; i++) { if (/* condition */) { x[i]=x[i]+k; count++; } else if (/* condition */) { y[i]=y[i]+k; count++; } else if (/* condition */) { x[i]=x[i]+k; y[i]=y[i]+k; count++; } else if (/* condition */) { x[i]=x[i]+k; y[i]=y[i]-k; count++; } } } return 0; }
16.617021
36
0.289373
Himanshu1801
5434c523ba9205b5e96f81960fd54474a4ec1f6d
4,893
cpp
C++
cpp/godot-cpp/src/gen/VisualScriptPropertyGet.cpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
1
2021-03-16T09:51:00.000Z
2021-03-16T09:51:00.000Z
cpp/godot-cpp/src/gen/VisualScriptPropertyGet.cpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
null
null
null
cpp/godot-cpp/src/gen/VisualScriptPropertyGet.cpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
null
null
null
#include "VisualScriptPropertyGet.hpp" #include <core/GodotGlobal.hpp> #include <core/CoreTypes.hpp> #include <core/Ref.hpp> #include <core/Godot.hpp> #include "__icalls.hpp" namespace godot { VisualScriptPropertyGet::___method_bindings VisualScriptPropertyGet::___mb = {}; void VisualScriptPropertyGet::___init_method_bindings() { ___mb.mb__get_type_cache = godot::api->godot_method_bind_get_method("VisualScriptPropertyGet", "_get_type_cache"); ___mb.mb__set_type_cache = godot::api->godot_method_bind_get_method("VisualScriptPropertyGet", "_set_type_cache"); ___mb.mb_get_base_path = godot::api->godot_method_bind_get_method("VisualScriptPropertyGet", "get_base_path"); ___mb.mb_get_base_script = godot::api->godot_method_bind_get_method("VisualScriptPropertyGet", "get_base_script"); ___mb.mb_get_base_type = godot::api->godot_method_bind_get_method("VisualScriptPropertyGet", "get_base_type"); ___mb.mb_get_basic_type = godot::api->godot_method_bind_get_method("VisualScriptPropertyGet", "get_basic_type"); ___mb.mb_get_call_mode = godot::api->godot_method_bind_get_method("VisualScriptPropertyGet", "get_call_mode"); ___mb.mb_get_index = godot::api->godot_method_bind_get_method("VisualScriptPropertyGet", "get_index"); ___mb.mb_get_property = godot::api->godot_method_bind_get_method("VisualScriptPropertyGet", "get_property"); ___mb.mb_set_base_path = godot::api->godot_method_bind_get_method("VisualScriptPropertyGet", "set_base_path"); ___mb.mb_set_base_script = godot::api->godot_method_bind_get_method("VisualScriptPropertyGet", "set_base_script"); ___mb.mb_set_base_type = godot::api->godot_method_bind_get_method("VisualScriptPropertyGet", "set_base_type"); ___mb.mb_set_basic_type = godot::api->godot_method_bind_get_method("VisualScriptPropertyGet", "set_basic_type"); ___mb.mb_set_call_mode = godot::api->godot_method_bind_get_method("VisualScriptPropertyGet", "set_call_mode"); ___mb.mb_set_index = godot::api->godot_method_bind_get_method("VisualScriptPropertyGet", "set_index"); ___mb.mb_set_property = godot::api->godot_method_bind_get_method("VisualScriptPropertyGet", "set_property"); } VisualScriptPropertyGet *VisualScriptPropertyGet::_new() { return (VisualScriptPropertyGet *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, godot::api->godot_get_class_constructor((char *)"VisualScriptPropertyGet")()); } Variant::Type VisualScriptPropertyGet::_get_type_cache() const { return (Variant::Type) ___godot_icall_int(___mb.mb__get_type_cache, (const Object *) this); } void VisualScriptPropertyGet::_set_type_cache(const int64_t type_cache) { ___godot_icall_void_int(___mb.mb__set_type_cache, (const Object *) this, type_cache); } NodePath VisualScriptPropertyGet::get_base_path() const { return ___godot_icall_NodePath(___mb.mb_get_base_path, (const Object *) this); } String VisualScriptPropertyGet::get_base_script() const { return ___godot_icall_String(___mb.mb_get_base_script, (const Object *) this); } String VisualScriptPropertyGet::get_base_type() const { return ___godot_icall_String(___mb.mb_get_base_type, (const Object *) this); } Variant::Type VisualScriptPropertyGet::get_basic_type() const { return (Variant::Type) ___godot_icall_int(___mb.mb_get_basic_type, (const Object *) this); } VisualScriptPropertyGet::CallMode VisualScriptPropertyGet::get_call_mode() const { return (VisualScriptPropertyGet::CallMode) ___godot_icall_int(___mb.mb_get_call_mode, (const Object *) this); } String VisualScriptPropertyGet::get_index() const { return ___godot_icall_String(___mb.mb_get_index, (const Object *) this); } String VisualScriptPropertyGet::get_property() const { return ___godot_icall_String(___mb.mb_get_property, (const Object *) this); } void VisualScriptPropertyGet::set_base_path(const NodePath base_path) { ___godot_icall_void_NodePath(___mb.mb_set_base_path, (const Object *) this, base_path); } void VisualScriptPropertyGet::set_base_script(const String base_script) { ___godot_icall_void_String(___mb.mb_set_base_script, (const Object *) this, base_script); } void VisualScriptPropertyGet::set_base_type(const String base_type) { ___godot_icall_void_String(___mb.mb_set_base_type, (const Object *) this, base_type); } void VisualScriptPropertyGet::set_basic_type(const int64_t basic_type) { ___godot_icall_void_int(___mb.mb_set_basic_type, (const Object *) this, basic_type); } void VisualScriptPropertyGet::set_call_mode(const int64_t mode) { ___godot_icall_void_int(___mb.mb_set_call_mode, (const Object *) this, mode); } void VisualScriptPropertyGet::set_index(const String index) { ___godot_icall_void_String(___mb.mb_set_index, (const Object *) this, index); } void VisualScriptPropertyGet::set_property(const String property) { ___godot_icall_void_String(___mb.mb_set_property, (const Object *) this, property); } }
46.160377
227
0.816677
GDNative-Gradle
54351f4440753e19b57f08ecd4efe7a84ee98cb3
1,011
cpp
C++
kakao_test_2017/A.cpp
sjnov11/Coding-Tests
8f98723f842357ee771f3842d46211bc9d92ff29
[ "MIT" ]
null
null
null
kakao_test_2017/A.cpp
sjnov11/Coding-Tests
8f98723f842357ee771f3842d46211bc9d92ff29
[ "MIT" ]
null
null
null
kakao_test_2017/A.cpp
sjnov11/Coding-Tests
8f98723f842357ee771f3842d46211bc9d92ff29
[ "MIT" ]
null
null
null
#include <iostream> #include <cstring> using namespace std; void go(int n, int arr1[], int arr2[]) { int map1[16][16], map2[16][16]; memset(map1, 0, sizeof(int) * 16 * 16); memset(map2, 0, sizeof(int) * 16 * 16); for (int i = 0; i < n; i++) { cout << "row " << i << endl; for (int j = 0; j < n; j++) { cout << n-j-1<< " : " << arr1[i] << " / " << arr1[i] % 2<< endl; map1[i][n - j - 1] = arr1[i] % 2; arr1[i] /= 2; if (arr1[i] == 0) break; } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { map2[i][n - j - 1] = arr2[i] % 2; arr2[i] /= 2; if (arr2[i] == 0) break; } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (map1[i][j] | map2[i][j]) cout << "#"; else cout << " "; } cout << "\n"; } } int main() { /*int n = 5; int arr1[5] = { 9, 20, 28, 18, 11 }; int arr2[5] = { 30, 1, 21, 17, 28 };*/ int n = 6; int arr1[6] = { 46, 33, 33, 22, 31, 50 }; int arr2[6] = { 27, 56, 19, 14, 14, 10 }; go(n, arr1, arr2); }
21.0625
67
0.431256
sjnov11
54426de9ef2b728b2868e7a5316d38c2af5cac61
974
cpp
C++
Engine/Source/Runtime/EcsFramework/Component/Camera/Old/OrthographicCamera.cpp
hebohang/HEngine
82f40797a7cfabaa11aeeb7797fba70551d18017
[ "MIT" ]
null
null
null
Engine/Source/Runtime/EcsFramework/Component/Camera/Old/OrthographicCamera.cpp
hebohang/HEngine
82f40797a7cfabaa11aeeb7797fba70551d18017
[ "MIT" ]
null
null
null
Engine/Source/Runtime/EcsFramework/Component/Camera/Old/OrthographicCamera.cpp
hebohang/HEngine
82f40797a7cfabaa11aeeb7797fba70551d18017
[ "MIT" ]
null
null
null
#include "hepch.h" #include "OrthographicCamera.h" #include <glm/gtc/matrix_transform.hpp> namespace HEngine { OrthographicCamera::OrthographicCamera(float left, float right, float bottom, float top) : mProjectionMatrix(glm::ortho(left, right, bottom, top, -1.0f, 1.0f)), mViewMatrix(1.0f) { mViewProjectionMatrix = mProjectionMatrix * mViewMatrix; } void OrthographicCamera::SetProjection(float left, float right, float bottom, float top) { mProjectionMatrix = glm::ortho(left, right, bottom, top, -1.0f, 1.0f); mViewProjectionMatrix = mProjectionMatrix * mViewMatrix; } void OrthographicCamera::RecalculateViewMatrix() { glm::mat4 transform = glm::translate(glm::mat4(1.0f), mPosition) * glm::rotate(glm::mat4(1.0f), glm::radians(mRotation), glm::vec3(0, 0, 1)); mViewMatrix = glm::inverse(transform); mViewProjectionMatrix = mProjectionMatrix * mViewMatrix; } }
34.785714
97
0.678645
hebohang
5444a52093a712adccddf081f06a8f4564d37db6
12,633
cpp
C++
FrameSkippingFilter.cpp
CSIR-RTVC/FrameSkippingFilter
a907161384b0bbe670dabcf2b78ad57bd348ec1b
[ "BSD-3-Clause" ]
null
null
null
FrameSkippingFilter.cpp
CSIR-RTVC/FrameSkippingFilter
a907161384b0bbe670dabcf2b78ad57bd348ec1b
[ "BSD-3-Clause" ]
null
null
null
FrameSkippingFilter.cpp
CSIR-RTVC/FrameSkippingFilter
a907161384b0bbe670dabcf2b78ad57bd348ec1b
[ "BSD-3-Clause" ]
1
2021-01-08T18:26:49.000Z
2021-01-08T18:26:49.000Z
/** @file MODULE : FrameSkippingFilter FILE NAME : FrameSkippingFilter.cpp DESCRIPTION : This filter skips a specified number of frames depending on the parameter denoted by "skipFrame" LICENSE: Software License Agreement (BSD License) Copyright (c) 2014, CSIR 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 CSIR nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =========================================================================== */ #include "stdafx.h" #include "FrameSkippingFilter.h" #include <cassert> #include <set> #include <dvdmedia.h> // timestamp unit is in 10^-7 const double TIMESTAMP_FACTOR = 10000000.0; FrameSkippingFilter::FrameSkippingFilter(LPUNKNOWN pUnk, HRESULT *pHr) : CTransInPlaceFilter(NAME("CSIR VPP Frame Skipping Filter"), pUnk, CLSID_VPP_FrameSkippingFilter, pHr, false), m_uiSkipFrameNumber(0), m_uiTotalFrames(1), m_uiCurrentFrame(0), m_dSkipRatio(1.0), m_dTargetFrameRate(0.0), m_bIsTimeSet(false), m_dTimeFrame(0.0), m_dTimeCurrent(0.0), m_dTargetTimeFrame(0.0), m_tStart(0), m_tStop(0) { // Init parameters initParameters(); } FrameSkippingFilter::~FrameSkippingFilter() { } CUnknown * WINAPI FrameSkippingFilter::CreateInstance(LPUNKNOWN pUnk, HRESULT *pHr) { FrameSkippingFilter *pFilter = new FrameSkippingFilter(pUnk, pHr); if (pFilter == NULL) { *pHr = E_OUTOFMEMORY; } return pFilter; } STDMETHODIMP FrameSkippingFilter::NonDelegatingQueryInterface(REFIID riid, void **ppv) { if (riid == (IID_ISettingsInterface)) { return GetInterface((ISettingsInterface*) this, ppv); } if (riid == (IID_ISpecifyPropertyPages)) { return GetInterface(static_cast<ISpecifyPropertyPages*>(this), ppv); } else { return CTransInPlaceFilter::NonDelegatingQueryInterface(riid, ppv); } } HRESULT FrameSkippingFilter::Transform(IMediaSample *pSample) { /* Check for other streams and pass them on */ // don't skip control info AM_SAMPLE2_PROPERTIES * const pProps = m_pInput->SampleProps(); if (pProps->dwStreamId != AM_STREAM_MEDIA) { return S_OK; } // select mode if (m_uiFrameSkippingMode == FSKIP_ACHIEVE_TARGET_RATE) { if (m_dTargetFrameRate != 0.0) { assert(m_dTargetFrameRate > 0.0); //set initial time frame m_dTargetTimeFrame = (1 / m_dTargetFrameRate); // timestamp unit is in 10^-7 HRESULT hr = pSample->GetTime(&m_tStart, &m_tStop); if (SUCCEEDED(hr)) { //m_bIsTimeSet runs only once with each rendering to initialize the 1st targetTimeFrame if (!m_bIsTimeSet) { m_dTimeCurrent = m_tStart / TIMESTAMP_FACTOR; m_dTimeFrame = m_dTimeCurrent + m_dTargetTimeFrame; m_bIsTimeSet = true; return S_OK; } else { m_dTimeCurrent = m_tStart / TIMESTAMP_FACTOR; if (m_dTimeCurrent > m_dTimeFrame) { int multiplier = static_cast<int>(ceil((m_dTimeCurrent - m_dTimeFrame) / m_dTargetTimeFrame)); if (multiplier == 0) { multiplier = 1; } m_dTimeFrame += (m_dTargetTimeFrame *multiplier); return S_OK; } else { return S_FALSE; } } } else { return hr; } } else { return S_OK; } } else if (m_uiFrameSkippingMode == FSKIP_SKIP_X_FRAMES_EVERY_Y) { if (m_vFramesToBeSkipped.empty()) return S_OK; int iSkip = m_vFramesToBeSkipped[m_uiCurrentFrame++]; if (m_uiCurrentFrame >= m_vFramesToBeSkipped.size()) { m_uiCurrentFrame = 0; } if (iSkip == 1) { return S_FALSE; } return S_OK; } else { assert(false); return S_OK; } #if 0 // adjust frame duration here? BYTE *pBufferIn, *pBufferOut; HRESULT hr = pSample->GetPointer(&pBufferIn); if (FAILED(hr)) { return hr; } VIDEOINFOHEADER *pVih1 = (VIDEOINFOHEADER*)mtIn->pbFormat; m_dSkipRatio #endif } DEFINE_GUID(MEDIASUBTYPE_I420, 0x30323449, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71); HRESULT FrameSkippingFilter::CheckInputType(const CMediaType* mtIn) { // Check the major type. if (mtIn->majortype != MEDIATYPE_Video) { return VFW_E_TYPE_NOT_ACCEPTED; } if ( (mtIn->subtype != MEDIASUBTYPE_RGB24) && (mtIn->subtype != MEDIASUBTYPE_RGB32) && (mtIn->subtype != MEDIASUBTYPE_I420) ) { return VFW_E_TYPE_NOT_ACCEPTED; } if (mtIn->formattype != FORMAT_VideoInfo) { return VFW_E_TYPE_NOT_ACCEPTED; } return S_OK; } HRESULT FrameSkippingFilter::Run(REFERENCE_TIME tStart) { if (m_uiFrameSkippingMode == FSKIP_SKIP_X_FRAMES_EVERY_Y) { m_vFramesToBeSkipped.clear(); int iSkip = 0, iTotal = 0; bool res = lowestRatio(m_dSourceFrameRate, m_dTargetFrameRate, iSkip, iTotal); if (res) { m_uiSkipFrameNumber = iSkip; m_uiTotalFrames = iTotal; // calculate which frames should be dropped if (m_uiSkipFrameNumber < m_uiTotalFrames && m_uiSkipFrameNumber > 0) { double dRatio = m_uiTotalFrames / static_cast<double>(m_uiSkipFrameNumber); std::set<int> toBeSkipped; std::set<int> toBePlayed; // populate to be skipped: note that this index is 1-indexed for (size_t iCount = 1; iCount <= m_uiSkipFrameNumber; ++iCount) { #if _MSC_VER > 1600 int iToBeSkipped = static_cast<int>(round(iCount * dRatio)); #else int iToBeSkipped = static_cast<int>(floor(iCount * dRatio + 0.5)); #endif toBeSkipped.insert(iToBeSkipped); } // populate to be played for (size_t iCount = 1; iCount <= m_uiTotalFrames; ++iCount) { auto found = toBeSkipped.find(iCount); if (found == toBeSkipped.end()) { toBePlayed.insert(iCount); m_vFramesToBeSkipped.push_back(0); } else { m_vFramesToBeSkipped.push_back(1); } } } else { // invalid input m_vFramesToBeSkipped.clear(); } } } return CTransInPlaceFilter::Run(tStart); } HRESULT FrameSkippingFilter::Stop(void) { m_uiCurrentFrame = 0; m_vFramesToBeSkipped.clear(); m_bIsTimeSet = false; return CTransInPlaceFilter::Stop(); } CBasePin* FrameSkippingFilter::GetPin(int n) { HRESULT hr = S_OK; // Create an input pin if not already done if (m_pInput == NULL) { m_pInput = new CTransInPlaceInputPin(NAME("TransInPlace input pin") , this // Owner filter , &hr // Result code , L"Input" // Pin name ); // Constructor for CTransInPlaceInputPin can't fail ASSERT(SUCCEEDED(hr)); } // Create an output pin if not already done if (m_pInput != NULL && m_pOutput == NULL) { m_pOutput = new FrameSkippingOutputPin(NAME("Frame skipping output pin") , this // Owner filter , &hr // Result code , L"Output" // Pin name ); // a failed return code should delete the object ASSERT(SUCCEEDED(hr)); if (m_pOutput == NULL) { delete m_pInput; m_pInput = NULL; } } // Return the appropriate pin ASSERT(n >= 0 && n <= 1); if (n == 0) { return m_pInput; } else if (n == 1) { return m_pOutput; } else { return NULL; } } // GetPin STDMETHODIMP FrameSkippingFilter::SetParameter(const char* type, const char* value) { HRESULT hr = CSettingsInterface::SetParameter(type, value); if (SUCCEEDED(hr)) { if (m_uiTotalFrames > 0) m_dSkipRatio = m_uiSkipFrameNumber / static_cast<double>(m_uiTotalFrames); else m_dSkipRatio = 0.0; } return hr; } FrameSkippingOutputPin::FrameSkippingOutputPin (__in_opt LPCTSTR pObjectName , __inout CTransInPlaceFilter *pFilter , __inout HRESULT *phr , __in_opt LPCWSTR pName ) : CTransInPlaceOutputPin(pObjectName, pFilter, phr, pName) { } // EnumMediaTypes // - pass through to our downstream filter STDMETHODIMP FrameSkippingOutputPin::EnumMediaTypes(__deref_out IEnumMediaTypes **ppEnum) { HRESULT hr = CTransInPlaceOutputPin::EnumMediaTypes(ppEnum); if (SUCCEEDED(hr)) { // modify frame duration AM_MEDIA_TYPE *pmt = NULL; while (hr = (*ppEnum)->Next(1, &pmt, NULL), hr == S_OK) { adjustAverageTimePerFrameInVideoInfoHeader(pmt); } } return hr; } // EnumMediaTypes HRESULT FrameSkippingOutputPin::SetMediaType(const CMediaType* pmtOut) { const AM_MEDIA_TYPE* pMediaType = pmtOut; adjustAverageTimePerFrameInVideoInfoHeader(const_cast<AM_MEDIA_TYPE*>(pMediaType)); return CTransInPlaceOutputPin::SetMediaType(pmtOut); } inline void FrameSkippingOutputPin::adjustAverageTimePerFrameInVideoInfoHeader(AM_MEDIA_TYPE * pmt) { if (((FrameSkippingFilter*)m_pFilter)->m_dSkipRatio > 0.0) { if ((FORMAT_VideoInfo == pmt->formattype)) { VIDEOINFOHEADER* pV = (VIDEOINFOHEADER*)pmt->pbFormat; REFERENCE_TIME duration = static_cast<REFERENCE_TIME>(pV->AvgTimePerFrame / ((FrameSkippingFilter*)m_pFilter)->m_dSkipRatio); pV->AvgTimePerFrame = duration; } else if ((FORMAT_VideoInfo2 == pmt->formattype)) { VIDEOINFOHEADER2* pV = (VIDEOINFOHEADER2*)pmt->pbFormat; REFERENCE_TIME duration = static_cast<REFERENCE_TIME>(pV->AvgTimePerFrame / ((FrameSkippingFilter*)m_pFilter)->m_dSkipRatio); pV->AvgTimePerFrame = duration; } } } bool FrameSkippingFilter::lowestRatio(double SourceFrameRate, double targetFrameRate, int& iSkipFrame, int& tTotalFrames) { if (targetFrameRate > SourceFrameRate) { return false; } const double EPSILON = 0.0001; if (SourceFrameRate - targetFrameRate < EPSILON) { iSkipFrame = 0; tTotalFrames = 0; return true; } //get rid of the floating point //limited to 1 decimal for now if (fmod(targetFrameRate, 1) != 0 || fmod(SourceFrameRate, 1) != 0) { targetFrameRate = targetFrameRate * 10; SourceFrameRate = SourceFrameRate * 10; } double targetFrameRateTemp(round(targetFrameRate)), SourceFrameRateTemp(round(SourceFrameRate)); //Logic to find the greatest common factor while (true) { (targetFrameRateTemp > SourceFrameRateTemp) ? targetFrameRateTemp = remainder(targetFrameRateTemp, SourceFrameRateTemp) : SourceFrameRateTemp = remainder(SourceFrameRateTemp, targetFrameRateTemp); if (targetFrameRateTemp < 0) { targetFrameRateTemp += SourceFrameRateTemp; } else if (SourceFrameRateTemp < 0) { SourceFrameRateTemp += targetFrameRateTemp; } if (targetFrameRateTemp <= 0 || SourceFrameRateTemp <= 0) { break; } } // Divide by the GCF to get the lowest ratio if (targetFrameRateTemp == 0) { iSkipFrame = (unsigned int)((SourceFrameRate - targetFrameRate) / SourceFrameRateTemp); tTotalFrames = (unsigned int)(SourceFrameRate / SourceFrameRateTemp); } else if (SourceFrameRateTemp == 0) { iSkipFrame = (unsigned int)((SourceFrameRate - targetFrameRate) / targetFrameRateTemp); tTotalFrames = (unsigned int)(SourceFrameRate / targetFrameRateTemp); } else { //The previous loop prevent this from happening } return true; }
27.949115
204
0.675849
CSIR-RTVC
544516bca1bac9c8226de0bed344538bd0577e45
5,681
cpp
C++
Dot_Engine/src/Dot/LevelEditor/LevelEditor.cpp
Bodka0904/Dot_Engine
1db28c56eeecefaed8aa3f1d87932765d5b16dd4
[ "Apache-2.0" ]
null
null
null
Dot_Engine/src/Dot/LevelEditor/LevelEditor.cpp
Bodka0904/Dot_Engine
1db28c56eeecefaed8aa3f1d87932765d5b16dd4
[ "Apache-2.0" ]
7
2019-06-04T06:28:21.000Z
2019-06-05T05:49:55.000Z
Dot_Engine/src/Dot/LevelEditor/LevelEditor.cpp
Bodka0904/Dot_Engine
1db28c56eeecefaed8aa3f1d87932765d5b16dd4
[ "Apache-2.0" ]
null
null
null
#include "stdafx.h" #include "LevelEditor.h" #include "Dot/Renderer/RenderSystem.h" #include "Dot/Core/Input.h" #include "Dot/Core/AssetManager.h" namespace Dot { LevelEditor::LevelEditor() { m_Default = std::make_shared<DefaultUI>(); m_TerrainEditor = std::make_shared<TerrainEditorUI>(); m_DefaultID = GuiApplication::Get()->AddBlock(m_Default); m_Default->m_TerrainEditorID = GuiApplication::Get()->AddBlock(m_TerrainEditor); GuiApplication::Get()->SwitchBlock(m_DefaultID); } LevelEditor::~LevelEditor() { } void LevelEditor::OnUpdate(float ts) { m_Default->m_CamController->OnUpdate(ts * 250.0f); } void LevelEditor::OnRender() { GuiApplication::Get()->GetCurrent()->OnRender(); } void LevelEditor::DefaultUI::OnAttach() { m_StaticShader = AssetManager::Get()->GetShader("StaticShader"); m_CamController = std::make_shared<Dot::CameraController>(glm::perspectiveFov(glm::radians(45.0f), float(Dot::Input::GetWindowSize().first) * 0.72f, float(Dot::Input::GetWindowSize().second) * 0.72f, 0.1f, 10000.0f)); m_Light = std::make_shared<Dot::Light>(); m_Light->position = glm::vec3(0.0f, 30.0f, 0.0f); m_Light->color = glm::vec3(0.7f, 0.7f, 0.7f); m_Light->strength = 1.0f; m_RenderSystem = ECSManager::Get()->GetSystem<RenderSystem>(); Dot::Layout layout{ {glm::vec2(0.0f,0.0f),glm::vec2(0.2f,1.0f),{ {Dot::ElementType::PANEL,0.3f,"Panel"}, {Dot::ElementType::PANEL,0.3f,"Panel1"}, {Dot::ElementType::PANEL,0.4f,"Panel2"} }}, {glm::vec2(0.2f,0.0f),glm::vec2(0.6f,1.0f),{ {Dot::ElementType::PANEL,0.08f,"Panel5"}, {Dot::ElementType::WINDOW,0.72f,"Scene"}, {Dot::ElementType::CONSOLE,0.2f,"Console"}, }}, {glm::vec2(0.8f,0.0f),glm::vec2(0.2f,1.0f),{ {Dot::ElementType::PANEL,0.5f,"Panel3"}, {Dot::ElementType::PANEL,0.7f,"Panel4"}, }} }; SetLayout(layout); GetPanel("Panel")->AddWidget("Button1", Dot::Button::Create("test", glm::vec2(0), glm::vec2(50, 50), glm::vec3(1, 1, 1))); GetPanel("Panel")->AddWidget("Button2", Dot::Button::Create("test", glm::vec2(0), glm::vec2(50, 50), glm::vec3(1, 1, 1))); GetPanel("Panel")->AddWidget("Button3", Dot::Button::Create("test", glm::vec2(0), glm::vec2(50, 50), glm::vec3(1, 1, 1))); GetPanel("Panel")->AddWidget("Slider", Dot::Slider::Create("slider", glm::vec2(0), glm::vec2(200, 30), glm::vec3(1, 1, 1), &m_Value, -10, 20)); GetPanel("Panel")->AddWidget("Checkbox", Dot::CheckBox::Create("checkbox", glm::vec2(0), glm::vec2(50, 50), glm::vec3(1, 1, 1))); GetPanel("Panel")->AddWidget("TextArea", Dot::TextArea::Create("textarea", glm::vec2(0), glm::vec2(200, 20), glm::vec3(1, 1, 1), glm::vec3(0, 0, 0))); GetPanel("Panel")->AddWidget("TextArea1", Dot::TextArea::Create("textarea1", glm::vec2(0), glm::vec2(200, 20), glm::vec3(1, 1, 1), glm::vec3(0, 0, 0))); GetPanel("Panel")->AddWidget("TextArea2", Dot::TextArea::Create("textarea2", glm::vec2(0), glm::vec2(200, 20), glm::vec3(1, 1, 1), glm::vec3(0, 0, 0))); GetPanel("Panel")->AddWidget("TextArea3", Dot::TextArea::Create("textarea3", glm::vec2(0), glm::vec2(200, 20), glm::vec3(1, 1, 1), glm::vec3(0, 0, 0))); GetPanel("Panel")->AddWidget("Dropdown", Dot::Dropdown::Create("drop", glm::vec2(0), glm::vec2(200, 20), glm::vec3(1, 1, 1))); GetPanel("Panel5")->AddWidget("Dropdown1", Dot::Dropdown::Create("drop", glm::vec2(0), glm::vec2(200, 20), glm::vec3(1, 1, 1))); //GetPanel("Panel1")->AddWidget("TextArea3", Dot::TextArea::Create("textarea3", glm::vec2(0), glm::vec2(200, 20), glm::vec3(1, 1, 1), glm::vec3(0, 0, 0))); //GetPanel("Panel1")->AddWidget("TextArea4", Dot::TextArea::Create("textarea3", glm::vec2(0), glm::vec2(200, 20), glm::vec3(1, 1, 1), glm::vec3(0, 0, 0))); //GetPanel("Panel1")->AddWidget("ArrButton", Dot::ArrowButton::Create("arrbutton", glm::vec2(0), glm::vec2(50, 50), glm::vec3(1, 1, 1))); //GetPanel("Panel1")->AddWidget("ArrButton2", Dot::ArrowButton::Create("arrbutton", glm::vec2(0), glm::vec2(50, 50), glm::vec3(1, 1, 1))); Dot::Logger::Get()->ConnectConsole(GetConsole("Console")); GetPanel("Panel")->GetWidget<Dot::Dropdown>("Dropdown").AddBox("Test1"); GetPanel("Panel")->GetWidget<Dot::Dropdown>("Dropdown").AddBox("Test2"); GetPanel("Panel")->GetWidget<Dot::Dropdown>("Dropdown").AddBox("Test3"); GetPanel("Panel")->GetWidget<Dot::Dropdown>("Dropdown").AddBox("Test4"); GetPanel("Panel5")->GetWidget<Dot::Dropdown>("Dropdown1").AddBox("Test1"); GetPanel("Panel5")->GetWidget<Dot::Dropdown>("Dropdown1").AddBox("Test2"); GetPanel("Panel5")->GetWidget<Dot::Dropdown>("Dropdown1").AddBox("Test3"); GetPanel("Panel5")->GetWidget<Dot::Dropdown>("Dropdown1").AddBox("Test4"); GetPanel("Panel5")->GetWidget<Dot::Dropdown>("Dropdown1").AddBox("Test5"); GetPanel("Panel5")->GetWidget<Dot::Dropdown>("Dropdown1").AddBox("Test6"); GetPanel("Panel5")->GetWidget<Dot::Dropdown>("Dropdown1").AddBox("Test7"); GetPanel("Panel5")->GetWidget<Dot::Dropdown>("Dropdown1").AddBox("Test8"); } void LevelEditor::DefaultUI::OnUpdate() { if (GetPanel("Panel5")->GetWidget<Dot::Dropdown>("Dropdown1").Clicked(1)) { GuiApplication::Get()->SwitchBlock(m_TerrainEditorID); } } void LevelEditor::DefaultUI::OnEvent(Event& event) { } void LevelEditor::DefaultUI::OnRender() { for (auto win : m_Window) { win.second->ActivateRenderTarget(); Renderer::Clear(glm::vec4(1, 1, 1, 0)); m_RenderSystem->BeginScene(m_CamController->GetCamera(), m_Light); { m_RenderSystem->Render(); } m_RenderSystem->EndScene(m_StaticShader); //SceneManager::Get()->GetCurretScene()->OnRender(); } RenderCommand::SetDefaultRenderTarget(); } }
45.448
219
0.655694
Bodka0904
5445d64b96580e2ea8b77dda8289c0189275a2f2
3,615
cpp
C++
Arduino/oneM2M/examples/ThingPlug_oneM2M_SDK/src/SRA/GetTime.cpp
SKT-ThingPlug/thingplug-device-sdk-C
fcb12ee172265f882787cc993bd6c5bbe9d876cf
[ "Apache-2.0" ]
9
2017-06-14T11:19:09.000Z
2020-04-11T08:01:06.000Z
Arduino/oneM2M/examples/ThingPlug_oneM2M_SDK/src/SRA/GetTime.cpp
SKT-ThingPlug/thingplug-device-sdk-C
fcb12ee172265f882787cc993bd6c5bbe9d876cf
[ "Apache-2.0" ]
null
null
null
Arduino/oneM2M/examples/ThingPlug_oneM2M_SDK/src/SRA/GetTime.cpp
SKT-ThingPlug/thingplug-device-sdk-C
fcb12ee172265f882787cc993bd6c5bbe9d876cf
[ "Apache-2.0" ]
15
2017-04-17T00:17:20.000Z
2021-06-26T04:12:39.000Z
/** * @file getTime.cpp * * @brief Arduino get Time API * * Copyright (C) 2016. SPTek,All Rights Reserved. * Written 2016,by SPTek */ #include <Arduino.h> #include <SPI.h> #include <Ethernet.h> #include <EthernetUdp.h> #include <TimeLib.h> #include "GetTime.h" EthernetUDP Udp; unsigned int localPort = 8888; // local port to listen for UDP packets IPAddress timeServer(132, 163, 4, 101); const int timeZone = 0; // Central European Time //const int timeZone = -5; // Eastern Standard Time (USA) //const int timeZone = -4; // Eastern Daylight Time (USA) //const int timeZone = -8; // Pacific Standard Time (USA) //const int timeZone = -7; // Pacific Daylight Time (USA) /*-------- NTn coe ----------*/ const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets // send an NTP request to the time server at the given address void sendNTPpacket(IPAddress &address) { // set all bytes in the buffer to 0 memset(packetBuffer, 0, NTP_PACKET_SIZE); // Initialize values needed to form NTP request // (see URL above for details on the packets) packetBuffer[0] = 0b11100011; // LI, Version, Mode packetBuffer[1] = 0; // Stratum, or type of clock packetBuffer[2] = 6; // Polling Interval packetBuffer[3] = 0xEC; // Peer Clock Precision // 8 bytes of zero for Root Delay & Root Dispersion packetBuffer[12] = 49; packetBuffer[13] = 0x4E; packetBuffer[14] = 49; packetBuffer[15] = 52; // all NTP fields have been given values, now // you can send a packet requesting a timestamp: Udp.beginPacket(address, 123); //NTP requests are to port 123 Udp.write(packetBuffer, NTP_PACKET_SIZE); Udp.endPacket(); } time_t getNtpTime() { while (Udp.parsePacket() > 0) ; // discard any previously received packets Serial.println("Transmit NTP Request"); sendNTPpacket(timeServer); uint32_t beginWait = millis(); while (millis() - beginWait < 1500) { int size = Udp.parsePacket(); if (size >= NTP_PACKET_SIZE) { Serial.println("Receive NTP Response"); Udp.read(packetBuffer, NTP_PACKET_SIZE); // read packet into the buffer unsigned long secsSince1900; // convert four bytes starting at location 40 to a long integer secsSince1900 = (unsigned long)packetBuffer[40] << 24; secsSince1900 |= (unsigned long)packetBuffer[41] << 16; secsSince1900 |= (unsigned long)packetBuffer[42] << 8; secsSince1900 |= (unsigned long)packetBuffer[43]; return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR; } } Serial.println("No NTP Response :-("); return 0; // return 0 if unable to get the time } void setNtpTime() { Udp.begin(localPort); Serial.println("waiting for sync"); setSyncProvider(getNtpTime); } int getHour() { return hour(); } int getMinute() { return minute(); } int getSecond() { return second(); } int getYear() { return year(); } int getMonth() { return month(); } int getDay() { return day(); } /*-------- DISPLAY code ----------*/ void digitalClockDisplay() { // digital clock display of the time Serial.print(hour()); Serial.print(" "); Serial.print(minute()); Serial.print(" "); Serial.print(second()); Serial.print(" "); Serial.print(day()); Serial.print(" "); Serial.print(month()); Serial.print(" "); Serial.print(year()); Serial.println(); }
26.386861
84
0.636515
SKT-ThingPlug
544883955e804df11c3ec0c3d75b36934ff48805
3,592
cpp
C++
modules/voting/voting.cpp
Clyde-Beep/sporks-test
c760d68c23a12dcc5c1a48ee0fc5e26c344f5c07
[ "Apache-2.0" ]
null
null
null
modules/voting/voting.cpp
Clyde-Beep/sporks-test
c760d68c23a12dcc5c1a48ee0fc5e26c344f5c07
[ "Apache-2.0" ]
null
null
null
modules/voting/voting.cpp
Clyde-Beep/sporks-test
c760d68c23a12dcc5c1a48ee0fc5e26c344f5c07
[ "Apache-2.0" ]
null
null
null
/************************************************************************************ * * Sporks, the learning, scriptable Discord bot! * * Copyright 2019 Craig Edwards <support@sporks.gg> * * 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 <sporks/bot.h> #include <sporks/modules.h> #include <string> #include <cstdint> #include <fstream> #include <streambuf> #include <sporks/stringops.h> #include <sporks/database.h> /** * Provides a role on the home server when someone votes for the bot on various websites such as top.gg */ class VotingModule : public Module { public: VotingModule(Bot* instigator, ModuleLoader* ml) : Module(instigator, ml) { ml->Attach({ I_OnPresenceUpdate }, this); } virtual ~VotingModule() { } virtual std::string GetVersion() { /* NOTE: This version string below is modified by a pre-commit hook on the git repository */ std::string version = "$ModVer 5$"; return "1.0." + version.substr(8,version.length() - 9); } virtual std::string GetDescription() { return "Awards roles in exchange for votes"; } virtual bool OnPresenceUpdate() { db::resultset rs_votes = db::query("SELECT id, snowflake_id, UNIX_TIMESTAMP(vote_time) AS vote_time, origin, rolegiven FROM infobot_votes", {}); aegis::guild* home = bot->core.find_guild(from_string<int64_t>(Bot::GetConfig("home"), std::dec)); if (home) { /* Process removals first */ for (auto vote = rs_votes.begin(); vote != rs_votes.end(); ++vote) { int64_t member_id = from_string<int64_t>((*vote)["snowflake_id"], std::dec); aegis::user* user = bot->core.find_user(member_id); if (user) { if ((*vote)["rolegiven"] == "1") { /* Role was already given, take away the role and remove the vote IF the date is too far in the past. * Votes last 24 hours. */ uint64_t role_timestamp = from_string<uint64_t>((*vote)["vote_time"], std::dec); if (time(NULL) - role_timestamp > 86400) { db::query("DELETE FROM infobot_votes WHERE id = ?", {(*vote)["id"]}); home->remove_guild_member_role(member_id, from_string<int64_t>(Bot::GetConfig("vote_role"), std::dec)); bot->core.log->info("Removing vanity role from {}", member_id); } } } } /* Now additions, so that if they've re-voted, it doesnt remove it */ for (auto vote = rs_votes.begin(); vote != rs_votes.end(); ++vote) { int64_t member_id = from_string<int64_t>((*vote)["snowflake_id"], std::dec); aegis::user* user = bot->core.find_user(member_id); if (user) { if ((*vote)["rolegiven"] == "0") { /* Role not yet given, give the role and set rolegiven to 1 */ bot->core.log->info("Adding vanity role to {}", member_id); home->add_guild_member_role(member_id, from_string<int64_t>(Bot::GetConfig("vote_role"), std::dec)); db::query("UPDATE infobot_votes SET rolegiven = 1 WHERE snowflake_id = ?", {(*vote)["snowflake_id"]}); } } } } return true; } }; ENTRYPOINT(VotingModule);
35.564356
146
0.639477
Clyde-Beep
544b77d96f7fff2b482d1abc1c2720a9f259ee1c
202
cpp
C++
qtglgame/mainwindow.cpp
Darkness-ua/cube-labyrinth-game
3b0b8971e20dfb17a63fb21e08c61f5d2b4c85b2
[ "Unlicense" ]
null
null
null
qtglgame/mainwindow.cpp
Darkness-ua/cube-labyrinth-game
3b0b8971e20dfb17a63fb21e08c61f5d2b4c85b2
[ "Unlicense" ]
null
null
null
qtglgame/mainwindow.cpp
Darkness-ua/cube-labyrinth-game
3b0b8971e20dfb17a63fb21e08c61f5d2b4c85b2
[ "Unlicense" ]
null
null
null
#include <iostream> #include "mainwindow.h" #include "window.h" using namespace std; MainWindow::MainWindow() { setWindowTitle(tr("QT GLGame")); setCentralWidget(new Window(this)); }
10.631579
39
0.678218
Darkness-ua
544d342b8f19e6d2d4bcc3802decf00f46005130
566
hpp
C++
cannon/utils/class_forward.hpp
cannontwo/cannon
4be79f3a6200d1a3cd26c28c8f2250dbdf08f267
[ "MIT" ]
null
null
null
cannon/utils/class_forward.hpp
cannontwo/cannon
4be79f3a6200d1a3cd26c28c8f2250dbdf08f267
[ "MIT" ]
46
2021-01-12T23:03:52.000Z
2021-10-01T17:29:01.000Z
cannon/utils/class_forward.hpp
cannontwo/cannon
4be79f3a6200d1a3cd26c28c8f2250dbdf08f267
[ "MIT" ]
null
null
null
#pragma once #ifndef CANNON_UTILS_CLASS_FORWARD_H #define CANNON_UTILS_CLASS_FORWARD_H /*! * \file cannon/utils/class_forward.hpp * \brief File containing class forward macro. */ #include <memory> /*! * \def CANNON_CLASS_FORWARD * \brief Macro that forward declares a class, <Class>Ptr, <Class>ConstPtr. */ #define CANNON_CLASS_FORWARD(C) \ class C; \ typedef std::shared_ptr<C> C##Ptr; \ typedef std::shared_ptr<const C> C##ConstPrt; #endif /* ifndef CANNON_UTILS_CLASS_FORWARD_H */
25.727273
75
0.651943
cannontwo
544da4164e82942921678c6efe91b09e5dbe30fc
3,877
cpp
C++
c++/src/algo/winmask/seq_masker_ostat_ascii.cpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
31
2016-12-09T04:56:59.000Z
2021-12-31T17:19:10.000Z
c++/src/algo/winmask/seq_masker_ostat_ascii.cpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
6
2017-03-10T17:25:13.000Z
2021-09-22T15:49:49.000Z
c++/src/algo/winmask/seq_masker_ostat_ascii.cpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
20
2015-01-04T02:15:17.000Z
2021-12-03T02:31:43.000Z
/* $Id: seq_masker_ostat_ascii.cpp 183994 2010-02-23 20:20:11Z morgulis $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: Aleksandr Morgulis * * File Description: * Implementation of CSeqMaskerUStatAscii class. * */ #include <ncbi_pch.hpp> #include <corelib/ncbistd.hpp> #include <algo/winmask/seq_masker_ostat_ascii.hpp> BEGIN_NCBI_SCOPE //------------------------------------------------------------------------------ const char * CSeqMaskerOstatAscii::CSeqMaskerOstatAsciiException::GetErrCodeString() const { switch( GetErrCode() ) { case eBadOrder: return "bad unit order"; default: return CException::GetErrCodeString(); } } //------------------------------------------------------------------------------ CSeqMaskerOstatAscii::CSeqMaskerOstatAscii( const string & name ) : CSeqMaskerOstat( name.empty() ? static_cast<CNcbiOstream&>(NcbiCout) : static_cast<CNcbiOstream&>(*new CNcbiOfstream( name.c_str() )), name.empty() ? false : true ) {} //------------------------------------------------------------------------------ CSeqMaskerOstatAscii::CSeqMaskerOstatAscii( CNcbiOstream & os ) : CSeqMaskerOstat( os, false ) {} //------------------------------------------------------------------------------ CSeqMaskerOstatAscii::~CSeqMaskerOstatAscii() { } //------------------------------------------------------------------------------ void CSeqMaskerOstatAscii::doSetUnitSize( Uint4 us ) { out_stream << us << endl; } //------------------------------------------------------------------------------ void CSeqMaskerOstatAscii::doSetUnitCount( Uint4 unit, Uint4 count ) { static Uint4 punit = 0; if( unit != 0 && unit <= punit ) { CNcbiOstrstream ostr; ostr << "current unit " << hex << unit << "; " << "previous unit " << hex << punit; string s = CNcbiOstrstreamToString(ostr); NCBI_THROW( CSeqMaskerOstatAsciiException, eBadOrder, s ); } out_stream << hex << unit << " " << dec << count << "\n"; punit = unit; } //------------------------------------------------------------------------------ void CSeqMaskerOstatAscii::doSetComment( const string & msg ) { out_stream << "#" << msg << "\n"; } //------------------------------------------------------------------------------ void CSeqMaskerOstatAscii::doSetParam( const string & name, Uint4 value ) { out_stream << ">" << name << " " << value << "\n"; } //------------------------------------------------------------------------------ void CSeqMaskerOstatAscii::doSetBlank() { out_stream << "\n"; } END_NCBI_SCOPE
36.92381
80
0.522569
OpenHero
54516c9b4b8be7b382d990a59303084266303a4e
29,680
cpp
C++
parser/parser.cpp
rdffg/bcaa_importer
f92e0b39673b5c557540154d4567c53a15adadcd
[ "Apache-2.0" ]
null
null
null
parser/parser.cpp
rdffg/bcaa_importer
f92e0b39673b5c557540154d4567c53a15adadcd
[ "Apache-2.0" ]
2
2019-05-07T22:49:31.000Z
2021-08-20T20:03:53.000Z
parser/parser.cpp
rdffg/bcaa_importer
f92e0b39673b5c557540154d4567c53a15adadcd
[ "Apache-2.0" ]
null
null
null
#include <string.h> #include <fstream> #include "parser.h" #include "DataAdvice-pimpl.h" #include "DataAdvice-pskel.h" #include "model/dataadvice.h" #include "runtypeparser.h" #include <QApplication> #include <QFileInfo> #include <QDebug> #include "QDjango.h" #include "saveerror.h" Parser::Parser(QString filePath, QObject *parent): QObject(parent) , filePath(filePath) { m_cancel = std::make_unique<bool>(); } Parser::~Parser() { } std::string Parser::findXsdPath() { QString xsdName = "DataAdvice.xsd"; auto xsdPath = QApplication::applicationDirPath() + "/" + xsdName; QFileInfo check_file(xsdPath); if (check_file.exists() && check_file.isReadable()) { return (QString("file:///") + xsdPath.replace(" ","%20")).toStdString(); } else { QDir dir = QDir(filePath); dir.cdUp(); xsdPath = dir.canonicalPath() + "/" + xsdName; check_file = QFileInfo(xsdPath); if (check_file.exists() && check_file.isReadable()) return (QString("file:///") + xsdPath.replace(" ", "%20")).toStdString(); else throw QString("DataAdvice.xsd was not found."); } } void Parser::import() { *m_cancel = false; if (!QDjango::createTables()) { this->message(QString("Did not create tables (this is okay if the tables already exist)")); } try { if (!QDjango::database().transaction()) throw SaveError("Failed to create transaction."); message("Populating lookup tables..."); model::PropertyClassValueType::populate(); model::minortaxing::JurisdictionType::populate(); message("Done."); message(QString("Importing records from ") + filePath + "..."); std::unique_ptr<model::DataAdvice> dataAdvice; try { dataAdvice = readFile(filePath.toStdString(), findXsdPath(), false); } catch (SaveError &err) { QDjango::database().rollback(); emit message(err.text()); emit finished(false); return; } catch (QString& err) { QDjango::database().rollback(); emit message(err); emit finished(false); return; } catch ( ... ) { QDjango::database().rollback(); qDebug() << "Stopped parsing the file."; emit finished(false); return; } writeMetadata(dataAdvice); emit folioSaved(-1); // set progressbar to indeterminate if (!QDjango::database().commit()) throw SaveError("Failed to commit transaction."); message("Successfully imported the data file."); emit finished(true); } catch (SaveError &err) { this->message(err.text()); emit finished(false); } } void Parser::writeMetadata(const std::unique_ptr<model::DataAdvice> &summary) { model::ImportMeta meta; meta.setImportDate(QDate::currentDate()); meta.setRunDate(summary->runDate()); meta.setRunType(summary->runType()); if (!meta.save()) throw SaveError(meta.lastError().text()); } void Parser::cancel() { *m_cancel = true; } std::unique_ptr<model::DataAdvice> Parser::getFileInfo() { auto xsdPath = findXsdPath(); auto advice = readFile(filePath.toStdString(), findXsdPath(), true); return advice; } std::unique_ptr<model::DataAdvice> Parser::readFile(const std::string& path, const std::string& xsdPath, bool forSummary) { // use a stream so we can calculate progress based on // position in the file stream std::ifstream file; long long size; file.open(path, std::ios::in | std::ios::ate); // open input stream at end of file if (file.is_open()) { size = file.tellg(); file.seekg(0, file.beg); qDebug() << "size of size_t: " << sizeof(size_t); } else { char *errbuf = new char[32]; strerror_s(errbuf, 32, errno); throw(QString("Failed to open file.") + QString(errbuf)); } std::unique_ptr<::dataadvice::DataAdvice_pskel> DataAdvice_p; //auto parser = registerParser(forSummary); ::xml_schema::integerImpl integer_p; ::dataadvice::RunTypeImpl RunType_p; ::xml_schema::dateImpl date_p; ::dataadvice::AssessmentAreaCollectionImpl AssessmentAreaCollection_p; ::dataadvice::AssessmentAreaImpl AssessmentArea_p; ::dataadvice::AssessmentAreaCodeImpl AssessmentAreaCode_p; ::dataadvice::String255Impl String255_p; ::dataadvice::JurisdictionCollectionImpl JurisdictionCollection_p; ::dataadvice::JurisdictionImpl Jurisdiction_p; ::dataadvice::JurisdictionCodeImpl JurisdictionCode_p; ::dataadvice::FolioRecordCollectionImpl FolioRecordCollection_p; ::dataadvice::FolioRecordImpl FolioRecord_p(file, size); ::dataadvice::FolioRollNumberImpl FolioRollNumber_p; ::dataadvice::ActionCodeImpl ActionCode_p; ::dataadvice::String32Impl String32_p; ::dataadvice::FolioLookupCodeItemImpl FolioLookupCodeItem_p; ::dataadvice::LookupCodeImpl LookupCode_p; ::dataadvice::FolioString255ItemImpl FolioString255Item_p; ::dataadvice::FolioActionImpl FolioAction_p; ::dataadvice::FolioAddImpl FolioAdd_p; ::dataadvice::FolioRenumberImpl FolioRenumber_p; ::dataadvice::FolioDeleteImpl FolioDelete_p; ::dataadvice::FolioAddressCollectionImpl FolioAddressCollection_p; ::dataadvice::FolioAddressImpl FolioAddress_p; ::dataadvice::FolioBooleanItemImpl FolioBooleanItem_p; ::xml_schema::booleanImpl boolean_p; ::dataadvice::UniqueIDImpl UniqueID_p; ::dataadvice::OwnershipGroupCollectionImpl OwnershipGroupCollection_p; ::dataadvice::OwnershipGroupImpl OwnershipGroup_p; ::dataadvice::FolioUniqueIDItemImpl FolioUniqueIDItem_p; ::dataadvice::FolioDateItemImpl FolioDateItem_p; ::dataadvice::OwnerCollectionImpl OwnerCollection_p; ::dataadvice::OwnerImpl Owner_p; ::dataadvice::FolioString1ItemImpl FolioString1Item_p; ::dataadvice::String1Impl String1_p; ::dataadvice::FormattedMailingAddressImpl FormattedMailingAddress_p; ::dataadvice::FormattedMailingAddressLineImpl FormattedMailingAddressLine_p; ::dataadvice::String40Impl String40_p; ::dataadvice::MailingAddressImpl MailingAddress_p; ::dataadvice::LegalDescriptionCollectionImpl LegalDescriptionCollection_p; ::dataadvice::LegalDescriptionImpl LegalDescription_p; ::dataadvice::FolioString1024ItemImpl FolioString1024Item_p; ::dataadvice::String1024Impl String1024_p; ::dataadvice::FolioDescriptionImpl FolioDescription_p; ::dataadvice::NeighbourhoodImpl Neighbourhood_p; ::dataadvice::LandMeasurementImpl LandMeasurement_p; ::dataadvice::SpecialDistrictImpl SpecialDistrict_p; ::dataadvice::ManualClassImpl ManualClass_p; ::dataadvice::FolioDecimalItemImpl FolioDecimalItem_p; ::xml_schema::decimalImpl decimal_p; ::dataadvice::SaleCollectionImpl SaleCollection_p; ::dataadvice::SaleImpl Sale_p; ::dataadvice::PropertyValuesImpl PropertyValues_p; ::dataadvice::PropertyClassValuesCollectionImpl PropertyClassValuesCollection_p; ::dataadvice::PropertyClassValuesCollectionImpl PropertyClassValuesSummaryCollection_p; ::dataadvice::PropertyClassValuesImpl PropertyClassValues_p; ::dataadvice::PropertyClassCodeImpl PropertyClassCode_p; ::dataadvice::PropertySubClassCodeImpl PropertySubClassCode_p; ::dataadvice::ValuationImpl Valuation_p; ::dataadvice::ValuationCollectionImpl ValuationCollection_p; ::dataadvice::ValuesByETCImpl ValuesByETC_p; ::dataadvice::FolioAmendmentCollectionImpl FolioAmendmentCollection_p; ::dataadvice::FolioAmendmentImpl FolioAmendment_p; ::dataadvice::MinorTaxingImpl MinorTaxing_p; ::dataadvice::MinorTaxingJurisdictionCollectionImpl MinorTaxingJurisdictionCollection_p; ::dataadvice::MinorTaxingJurisdictionImpl MinorTaxingJurisdiction_p; ::dataadvice::FarmCollectionImpl FarmCollection_p; ::dataadvice::FarmImpl Farm_p; ::dataadvice::ManufacturedHomeCollectionImpl ManufacturedHomeCollection_p; ::dataadvice::ManufacturedHomeImpl ManufacturedHome_p; ::dataadvice::ManagedForestCollectionImpl ManagedForestCollection_p; ::dataadvice::ManagedForestImpl ManagedForest_p; ::dataadvice::OilAndGasCollectionImpl OilAndGasCollection_p; ::dataadvice::OilAndGasImpl OilAndGas_p; ::dataadvice::LandCharacteristicCollectionImpl LandCharacteristicCollection_p; ::dataadvice::LandCharacteristicImpl LandCharacteristic_p; ::dataadvice::DeliverySummaryImpl DeliverySummary_p; ::dataadvice::FolioGroupValuesImpl FolioGroupValues_p; ::dataadvice::AmendmentReasonCountCollectionImpl AmendmentReasonCountCollection_p; ::dataadvice::AmendmentReasonCountImpl AmendmentReasonCount_p; ::dataadvice::DeleteReasonCountCollectionImpl DeleteReasonCountCollection_p; ::dataadvice::DeleteReasonCountImpl DeleteReasonCount_p; ::dataadvice::VersionImpl Version_p; // set the cancel flag FolioRecord_p.setCancelFlag(*m_cancel); // Connect the parsers together. // if (forSummary) { DataAdvice_p = std::make_unique<dataadvice::RunTypeParser>(); DataAdvice_p->RunType_parser(RunType_p); DataAdvice_p->EndDate_parser(date_p); DataAdvice_p->Version_parser(Version_p); DataAdvice_p->StartDate_parser(date_p); DataAdvice_p->RunDate_parser(date_p); //DataAdvice_p->ReportSummary_parser(DeliverySummary_p); } else { DataAdvice_p = std::make_unique<::dataadvice::DataAdviceImpl>(); DataAdvice_p->parsers (integer_p, integer_p, RunType_p, date_p, date_p, AssessmentAreaCollection_p, DeliverySummary_p, Version_p, UniqueID_p, UniqueID_p, date_p); AssessmentAreaCollection_p.parsers (AssessmentArea_p); AssessmentArea_p.parsers (AssessmentAreaCode_p, String255_p, JurisdictionCollection_p, DeliverySummary_p); JurisdictionCollection_p.parsers (Jurisdiction_p); Jurisdiction_p.parsers (JurisdictionCode_p, String255_p, FolioRecordCollection_p, DeliverySummary_p); FolioRecordCollection_p.parsers (FolioRecord_p); FolioRecord_p.parsers (FolioRollNumber_p, FolioLookupCodeItem_p, FolioString255Item_p, FolioAction_p, FolioAddressCollection_p, OwnershipGroupCollection_p, LegalDescriptionCollection_p, FolioDescription_p, SaleCollection_p, PropertyValues_p, FolioAmendmentCollection_p, MinorTaxing_p, FarmCollection_p, ManufacturedHomeCollection_p, ManagedForestCollection_p, OilAndGasCollection_p, LandCharacteristicCollection_p, UniqueID_p); FolioRollNumber_p.parsers (ActionCode_p, String32_p); FolioLookupCodeItem_p.parsers (ActionCode_p, LookupCode_p); FolioString255Item_p.parsers (ActionCode_p, String255_p); FolioAction_p.parsers (FolioAdd_p, FolioDelete_p); FolioAdd_p.parsers (FolioRenumber_p); FolioRenumber_p.parsers (AssessmentAreaCode_p, String255_p, JurisdictionCode_p, String255_p, String32_p); FolioDelete_p.parsers (FolioRenumber_p, LookupCode_p, String255_p); FolioAddressCollection_p.parsers (ActionCode_p, FolioAddress_p); FolioAddress_p.parsers (ActionCode_p, FolioBooleanItem_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, UniqueID_p); FolioBooleanItem_p.parsers (ActionCode_p, boolean_p); OwnershipGroupCollection_p.parsers (ActionCode_p, OwnershipGroup_p); OwnershipGroup_p.parsers (ActionCode_p, FolioUniqueIDItem_p, FolioBooleanItem_p, FolioBooleanItem_p, FolioLookupCodeItem_p, FolioString255Item_p, FolioDateItem_p, FolioLookupCodeItem_p, FolioString255Item_p, OwnerCollection_p, FormattedMailingAddress_p, MailingAddress_p); FolioUniqueIDItem_p.parsers (ActionCode_p, UniqueID_p); FolioDateItem_p.parsers (ActionCode_p, date_p); OwnerCollection_p.parsers (ActionCode_p, Owner_p); Owner_p.parsers (ActionCode_p, FolioString255Item_p, FolioString255Item_p, FolioString1Item_p, FolioString255Item_p, FolioUniqueIDItem_p, FolioLookupCodeItem_p, FolioString255Item_p, UniqueID_p); FolioString1Item_p.parsers (ActionCode_p, String1_p); FormattedMailingAddress_p.parsers (ActionCode_p, FormattedMailingAddressLine_p, FormattedMailingAddressLine_p, FormattedMailingAddressLine_p, FormattedMailingAddressLine_p, FormattedMailingAddressLine_p, FormattedMailingAddressLine_p, UniqueID_p); FormattedMailingAddressLine_p.parsers (ActionCode_p, String40_p); MailingAddress_p.parsers (ActionCode_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, UniqueID_p); LegalDescriptionCollection_p.parsers (ActionCode_p, LegalDescription_p); LegalDescription_p.parsers (ActionCode_p, FolioString1024Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString1024Item_p, UniqueID_p); FolioString1024Item_p.parsers (ActionCode_p, String1024_p); FolioDescription_p.parsers (ActionCode_p, Neighbourhood_p, FolioLookupCodeItem_p, FolioString255Item_p, FolioBooleanItem_p, FolioBooleanItem_p, FolioBooleanItem_p, FolioBooleanItem_p, FolioBooleanItem_p, FolioBooleanItem_p, FolioLookupCodeItem_p, FolioString255Item_p, FolioLookupCodeItem_p, FolioString255Item_p, FolioString255Item_p, LandMeasurement_p, SpecialDistrict_p, SpecialDistrict_p, SpecialDistrict_p, ManualClass_p); Neighbourhood_p.parsers (ActionCode_p, FolioLookupCodeItem_p, FolioString255Item_p); LandMeasurement_p.parsers (ActionCode_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p); SpecialDistrict_p.parsers (ActionCode_p, FolioLookupCodeItem_p, FolioString255Item_p); ManualClass_p.parsers (ActionCode_p, FolioLookupCodeItem_p, FolioString255Item_p, FolioDecimalItem_p); FolioDecimalItem_p.parsers (ActionCode_p, decimal_p); SaleCollection_p.parsers (ActionCode_p, Sale_p); Sale_p.parsers (ActionCode_p, FolioString255Item_p, FolioDateItem_p, FolioDecimalItem_p, FolioLookupCodeItem_p, FolioString255Item_p, FolioDateItem_p, FolioDecimalItem_p, FolioLookupCodeItem_p, FolioString255Item_p, FolioLookupCodeItem_p, FolioString255Item_p, UniqueID_p); PropertyValues_p.parsers (PropertyClassValuesCollection_p, PropertyClassValuesCollection_p, PropertyClassValuesCollection_p, ValuationCollection_p); PropertyClassValuesCollection_p.parsers (PropertyClassValues_p); PropertyClassValues_p.parsers (PropertyClassCode_p, String255_p, PropertySubClassCode_p, String255_p, Valuation_p, Valuation_p, Valuation_p); Valuation_p.parsers (decimal_p, decimal_p); ValuationCollection_p.parsers (ValuesByETC_p); ValuesByETC_p.parsers (LookupCode_p, String255_p, PropertyClassCode_p, String255_p, decimal_p, decimal_p); FolioAmendmentCollection_p.parsers (ActionCode_p, FolioAmendment_p); FolioAmendment_p.parsers (ActionCode_p, FolioLookupCodeItem_p, FolioString255Item_p, FolioLookupCodeItem_p, FolioString255Item_p, FolioDateItem_p, FolioString1Item_p, UniqueID_p); MinorTaxing_p.parsers (ActionCode_p, MinorTaxingJurisdictionCollection_p, MinorTaxingJurisdictionCollection_p, MinorTaxingJurisdictionCollection_p, MinorTaxingJurisdictionCollection_p, MinorTaxingJurisdictionCollection_p, MinorTaxingJurisdictionCollection_p, MinorTaxingJurisdictionCollection_p, MinorTaxingJurisdictionCollection_p, MinorTaxingJurisdictionCollection_p); MinorTaxingJurisdictionCollection_p.parsers (ActionCode_p, MinorTaxingJurisdiction_p); MinorTaxingJurisdiction_p.parsers (ActionCode_p, FolioLookupCodeItem_p, FolioString1Item_p, FolioString255Item_p, UniqueID_p); FarmCollection_p.parsers (ActionCode_p, Farm_p); Farm_p.parsers (ActionCode_p, FolioString255Item_p, UniqueID_p); ManufacturedHomeCollection_p.parsers (ActionCode_p, ManufacturedHome_p); ManufacturedHome_p.parsers (ActionCode_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, FolioString255Item_p, UniqueID_p); ManagedForestCollection_p.parsers (ActionCode_p, ManagedForest_p); ManagedForest_p.parsers (ActionCode_p, FolioString255Item_p, UniqueID_p); OilAndGasCollection_p.parsers (ActionCode_p, OilAndGas_p); OilAndGas_p.parsers (ActionCode_p, FolioString255Item_p, UniqueID_p); LandCharacteristicCollection_p.parsers (ActionCode_p, LandCharacteristic_p); LandCharacteristic_p.parsers (ActionCode_p, FolioLookupCodeItem_p, FolioString255Item_p); DeliverySummary_p.parsers (integer_p, integer_p, integer_p, FolioGroupValues_p, FolioGroupValues_p, FolioGroupValues_p, PropertyClassValuesSummaryCollection_p, PropertyClassValuesSummaryCollection_p, PropertyClassValuesSummaryCollection_p, AmendmentReasonCountCollection_p, DeleteReasonCountCollection_p); FolioGroupValues_p.parsers (decimal_p, decimal_p); AmendmentReasonCountCollection_p.parsers (AmendmentReasonCount_p); AmendmentReasonCount_p.parsers (LookupCode_p, String255_p, integer_p); DeleteReasonCountCollection_p.parsers (DeleteReasonCount_p); DeleteReasonCount_p.parsers (LookupCode_p, String255_p, integer_p); } // connect signals connect(&FolioRecord_p, &dataadvice::FolioRecordImpl::folioSaved, this, &Parser::folioSaved); connect(&FolioRecord_p, &dataadvice::FolioRecordImpl::message, this, &Parser::message); connect(dynamic_cast<dataadvice::DataAdviceImpl *>(DataAdvice_p.get()), &dataadvice::DataAdviceImpl::message, this, &Parser::message); // configure XSD location ::xml_schema::document doc_p (*DataAdvice_p, "http://data.bcassessment.ca/DataAdvice/Formats/DAX/DataAdvice.xsd", "DataAdvice"); ::xml_schema::properties props; props.schema_location( "http://data.bcassessment.ca/DataAdvice/Formats/DAX/DataAdvice.xsd", xsdPath); try { DataAdvice_p->pre(); doc_p.parse(file, 0, props); file.close(); return std::unique_ptr<model::DataAdvice>(DataAdvice_p->post_DataAdvice()); } catch (const ::xml_schema::parsing& e) { file.close(); qDebug() << e.what(); for (auto &&d: e.diagnostics()) { qDebug() << "Parse error on line " << d.line() << ", column " << d.column(); qDebug() << QString::fromStdString(d.message()); emit message(QString("Parse error on line ") + QString::number(d.line()) + ", column " + QString::number(d.column())); emit message(QString::fromStdString(d.message())); } throw QString(*e.what()); } catch (const ::xml_schema::exception& e) { file.close(); qDebug() << e.what(); message(QString("Parse error: ") + QString(*e.what())); throw e.what(); } catch (const std::ios_base::failure&) { file.close(); qDebug() << "IO failue."; emit message(QString("IO Failure")); throw QString("IO Failure"); } catch (dataadvice::StopParsing&) { file.close(); qDebug() << "Stopped parsing"; //this is terrible, and should be refactored if (forSummary) return DataAdvice_p->post_DataAdvice(); else throw; } }
41.980198
138
0.519474
rdffg
5451aa66c0eca9573d252c8fd44441d31c5295f9
1,351
cpp
C++
QtChartsDemo/PieChart/widget.cpp
mahuifa/QMDemo
430844c0167c7374550c6133b38c5e8485f506d6
[ "Apache-2.0" ]
null
null
null
QtChartsDemo/PieChart/widget.cpp
mahuifa/QMDemo
430844c0167c7374550c6133b38c5e8485f506d6
[ "Apache-2.0" ]
null
null
null
QtChartsDemo/PieChart/widget.cpp
mahuifa/QMDemo
430844c0167c7374550c6133b38c5e8485f506d6
[ "Apache-2.0" ]
null
null
null
#include "widget.h" #include <QPieSeries> QT_CHARTS_USE_NAMESPACE // 引入命名空间,必须放在ui_widget.h前 #include "ui_widget.h" Widget::Widget(QWidget *parent) : QWidget(parent) , ui(new Ui::Widget) { ui->setupUi(this); this->setWindowTitle("QtCharts绘图-饼图Demo"); initChart(); } Widget::~Widget() { delete ui; } /** * @brief 初始化绘制饼图,饼图和圆环图的绘制方式基本一样,只是 * 不通过setHoleSize设置大于孔径,默认为0,就是没有孔径 */ void Widget::initChart() { QPieSeries* series = new QPieSeries(); // 创建一个饼图对象(设置孔径就是圆环) series->append("星期一", 1); // 添加饼图切片 series->append("星期二", 2); series->append("星期三", 3); series->append("星期四", 4); series->append("星期五", 5); QPieSlice* slice = series->slices().at(1); // 获取饼图中某一个切片(在绘制圆环图Demo中是通过appent函数获取,这里换一种方式) slice->setExploded(); // 将切片分离饼图 slice->setLabelVisible(); // 显示当前切片的标签 slice->setPen(QPen(Qt::darkGreen, 2)); // 设置画笔颜色和粗细 slice->setBrush(Qt::green); // 设置切片背景色 QChart* chart = ui->chartView->chart(); // 获取QChartView中默认的QChart chart->addSeries(series); // 将创建好的饼图对象添加进QChart chart->setTitle("饼图标题"); // 设置图表标题 ui->chartView->setRenderHint(QPainter::Antialiasing); // 设置抗锯齿 }
30.022222
100
0.571429
mahuifa
54523956a8077c86a3c7c26a0225ee22dcaf5ffb
551
cpp
C++
EquilibriumPointInArray/main.cpp
Kapil706/GeeksForGeeks.Cpp-
3251fe2caf29e485656626d758058bd968e50ae1
[ "MIT" ]
1
2019-07-31T16:47:51.000Z
2019-07-31T16:47:51.000Z
EquilibriumPointInArray/main.cpp
Kapil706/GeeksForGeeks.Cpp-
3251fe2caf29e485656626d758058bd968e50ae1
[ "MIT" ]
null
null
null
EquilibriumPointInArray/main.cpp
Kapil706/GeeksForGeeks.Cpp-
3251fe2caf29e485656626d758058bd968e50ae1
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int EqPoint(int arr[],int n){ int sum=0; for(int i=0;i<n;i++){ sum += arr[i]; } int l_sum=0; for(int i=0;i<n;i++){ if(l_sum==sum-arr[i]){ return i+1; } l_sum += arr[i]; sum -= arr[i]; } return -1; } int main() { int t; cin>>t; while(t--){ int n; cin>>n; int arr[n]; for(int i=0;i<n;i++){cin>>arr[i];} cout<<EqPoint(arr,n); } return 0; }
8.746032
42
0.395644
Kapil706
5454c944abe007f82b0e3871a02707b18b713dd0
457
hpp
C++
core/world/filter/Filter.hpp
PlatformerTeam/mad
8768e3127a0659f1d831dcb6c96ba2bb71c30795
[ "MIT" ]
2
2022-02-21T08:23:02.000Z
2022-03-17T10:01:40.000Z
core/world/filter/Filter.hpp
PlatformerTeam/mad
8768e3127a0659f1d831dcb6c96ba2bb71c30795
[ "MIT" ]
43
2022-02-21T13:07:08.000Z
2022-03-22T11:02:16.000Z
core/world/filter/Filter.hpp
PlatformerTeam/mad
8768e3127a0659f1d831dcb6c96ba2bb71c30795
[ "MIT" ]
null
null
null
#ifndef MAD_CORE_WORLD_FILTER_FILTER_HPP #define MAD_CORE_WORLD_FILTER_FILTER_HPP #include <world/entity/Entity.hpp> #include <memory> #include <vector> namespace mad::core { struct Filter { enum class Type { Id, True }; explicit Filter(Type new_type) : type(new_type) { } virtual ~Filter() = default; const Type type; }; } #endif //MAD_CORE_WORLD_FILTER_FILTER_HPP
15.233333
57
0.621444
PlatformerTeam
5457dd67633d2d84e3c2f7bd495184dbb65e145b
5,683
cpp
C++
addons/support/config.cpp
Krzyciu/A3CS
b7144fc9089b5ded6e37cc1fad79b1c2879521be
[ "MIT" ]
1
2020-06-07T00:45:49.000Z
2020-06-07T00:45:49.000Z
addons/support/config.cpp
Krzyciu/A3CS
b7144fc9089b5ded6e37cc1fad79b1c2879521be
[ "MIT" ]
27
2020-05-24T11:09:56.000Z
2020-05-25T12:28:10.000Z
addons/support/config.cpp
Krzyciu/A3CS
b7144fc9089b5ded6e37cc1fad79b1c2879521be
[ "MIT" ]
2
2020-05-31T08:52:45.000Z
2021-04-16T23:16:37.000Z
#include "script_component.hpp" class CfgPatches { class ADDON { name = COMPONENT_NAME; units[] = {}; weapons[] = {}; requiredVersion = REQUIRED_VERSION; requiredAddons[] = {"a3cs_common", "A3_Ui_F"}; author = ECSTRING(main,Author); authors[] = {"SzwedzikPL"}; url = ECSTRING(main,URL); VERSION_CONFIG; }; }; /* class RscText; class RscTitle; class RscListBox; class RscControlsGroup; class RscMapControl; class RscButtonMenu; class RscButtonMenuCancel; class GVAR(RscSupportPanel) { onLoad = QUOTE(uiNamespace setVariable [ARR_2(QQGVAR(RscSupportPanel), _this select 0)];); onUnload = QUOTE(uiNamespace setVariable [ARR_2(QQGVAR(RscSupportPanel), displayNull)];); idd = -1; movingEnable = 1; enableSimulation = 1; enableDisplay = 1; class controlsBackground { class titleBackground: RscText { idc = IDC_RSCSUPPORTPANEL_TITLEBG; x = "-6.5 * (((safezoneW / safezoneH) min 1.2) / 40) + (safezoneX + (safezoneW - ((safezoneW / safezoneH) min 1.2))/2)"; y = "1 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) + (safezoneY + (safezoneH - (((safezoneW / safezoneH) min 1.2) / 1.2))/2)"; w = "53 * (((safezoneW / safezoneH) min 1.2) / 40)"; h = "1 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)"; colorBackground[] = { "(profilenamespace getvariable ['GUI_BCG_RGB_R', 0.13])", "(profilenamespace getvariable ['GUI_BCG_RGB_G', 0.54])", "(profilenamespace getvariable ['GUI_BCG_RGB_B', 0.21])", "(profilenamespace getvariable ['GUI_BCG_RGB_A', 0.8])" }; }; class mainBackground: RscText { idc = IDC_RSCSUPPORTPANEL_MAINBG; x = "-6.5 * (((safezoneW / safezoneH) min 1.2) / 40) + (safezoneX + (safezoneW - ((safezoneW / safezoneH) min 1.2))/2)"; y = "2.1 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) + (safezoneY + (safezoneH - (((safezoneW / safezoneH) min 1.2) / 1.2))/2)"; w = "53 * (((safezoneW / safezoneH) min 1.2) / 40)"; h = "20.8 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)"; colorBackground[] = {0, 0, 0, 0.69999999}; }; }; class Controls { class title: RscTitle { idc = IDC_RSCSUPPORTPANEL_TITLE; text = CSTRING(Title); x = "-6.5 * (((safezoneW / safezoneH) min 1.2) / 40) + (safezoneX + (safezoneW - ((safezoneW / safezoneH) min 1.2))/2)"; y = "1 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) + (safezoneY + (safezoneH - (((safezoneW / safezoneH) min 1.2) / 1.2))/2)"; w = "15 * (((safezoneW / safezoneH) min 1.2) / 40)"; h = "1 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)"; }; class assetTitle: RscTitle { idc = IDC_RSCSUPPORTPANEL_ASSETTITLE; text = ""; x = "8.5 * (((safezoneW / safezoneH) min 1.2) / 40) + (safezoneX + (safezoneW - ((safezoneW / safezoneH) min 1.2))/2)"; y = "1 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) + (safezoneY + (safezoneH - (((safezoneW / safezoneH) min 1.2) / 1.2))/2)"; w = "24 * (((safezoneW / safezoneH) min 1.2) / 40)"; h = "1 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)"; }; class assetsList: RscListBox { IDC = IDC_RSCSUPPORTPANEL_ASSETS; x = "-6.3 * (((safezoneW / safezoneH) min 1.2) / 40) + (safezoneX + (safezoneW - ((safezoneW / safezoneH) min 1.2))/2)"; y = "2.3 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) + (safezoneY + (safezoneH - (((safezoneW / safezoneH) min 1.2) / 1.2))/2)"; w = "15 * (((safezoneW / safezoneH) min 1.2) / 40)"; h = "20.4 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)"; }; class propertiesGroup: RscControlsGroup { IDC = IDC_RSCSUPPORTPANEL_PROPERTIES; x = "8.5 * (((safezoneW / safezoneH) min 1.2) / 40) + (safezoneX + (safezoneW - ((safezoneW / safezoneH) min 1.2))/2)"; y = "2.3 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) + (safezoneY + (safezoneH - (((safezoneW / safezoneH) min 1.2) / 1.2))/2)"; w = "15 * (((safezoneW / safezoneH) min 1.2) / 40)"; h = "20.4 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)"; }; class positionMap: RscMapControl { idc = IDC_RSCSUPPORTPANEL_MAP; x = "23.7 * (((safezoneW / safezoneH) min 1.2) / 40) + (safezoneX + (safezoneW - ((safezoneW / safezoneH) min 1.2))/2)"; y = "2.3 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) + (safezoneY + (safezoneH - (((safezoneW / safezoneH) min 1.2) / 1.2))/2)"; w = "22.5 * (((safezoneW / safezoneH) min 1.2) / 40)"; h = "20.4 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)"; colorBackground[] = {1, 1, 1, 1}; showCountourInterval = 0; scaleDefault = 0.1; drawObjects = 0; showMarkers = 0; showTacticalPing = 0; }; class sendMission: RscButtonMenu { idc = IDC_RSCSUPPORTPANEL_BUTTONSEND; text = CSTRING(SendMission); x = "38.5 * (((safezoneW / safezoneH) min 1.2) / 40) + (safezoneX + (safezoneW - ((safezoneW / safezoneH) min 1.2))/2)"; y = "23 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) + (safezoneY + (safezoneH - (((safezoneW / safezoneH) min 1.2) / 1.2))/2)"; w = "8 * (((safezoneW / safezoneH) min 1.2) / 40)"; h = "1 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)"; }; class cancelDialog: RscButtonMenuCancel { text = ECSTRING(Common,Close); x = "-6.5 * (((safezoneW / safezoneH) min 1.2) / 40) + (safezoneX + (safezoneW - ((safezoneW / safezoneH) min 1.2))/2)"; y = "23 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) + (safezoneY + (safezoneH - (((safezoneW / safezoneH) min 1.2) / 1.2))/2)"; w = "6.25 * (((safezoneW / safezoneH) min 1.2) / 40)"; h = "1 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)"; }; }; }; */
47.756303
138
0.575224
Krzyciu
54625f75629de7448fb5f77430590b478a8f81b1
1,469
cpp
C++
plugins/d3d9/src/vf/convert/role_visitor.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
plugins/d3d9/src/vf/convert/role_visitor.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
plugins/d3d9/src/vf/convert/role_visitor.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <sge/d3d9/d3dinclude.hpp> #include <sge/d3d9/vf/convert/role_visitor.hpp> #include <sge/renderer/vf/dynamic/color_fwd.hpp> #include <sge/renderer/vf/dynamic/extra_fwd.hpp> #include <sge/renderer/vf/dynamic/normal_fwd.hpp> #include <sge/renderer/vf/dynamic/pos_fwd.hpp> #include <sge/renderer/vf/dynamic/texpos_fwd.hpp> sge::d3d9::vf::convert::role_visitor::result_type sge::d3d9::vf::convert::role_visitor::operator()(sge::renderer::vf::dynamic::pos const &) const { return D3DDECLUSAGE_POSITION; } sge::d3d9::vf::convert::role_visitor::result_type sge::d3d9::vf::convert::role_visitor::operator()(sge::renderer::vf::dynamic::normal const &) const { return D3DDECLUSAGE_NORMAL; } sge::d3d9::vf::convert::role_visitor::result_type sge::d3d9::vf::convert::role_visitor::operator()(sge::renderer::vf::dynamic::color const &) const { return D3DDECLUSAGE_COLOR; } sge::d3d9::vf::convert::role_visitor::result_type sge::d3d9::vf::convert::role_visitor::operator()(sge::renderer::vf::dynamic::texpos const &) const { return D3DDECLUSAGE_TEXCOORD; } sge::d3d9::vf::convert::role_visitor::result_type sge::d3d9::vf::convert::role_visitor::operator()(sge::renderer::vf::dynamic::extra const &) const { return D3DDECLUSAGE_TEXCOORD; }
34.162791
98
0.741321
cpreh
5464f3a43593c2dabe316c95b9d88be08176250f
956
cpp
C++
NewFramework/HelitWing.cpp
lhthang1998/Megaman_X3_DirectX
2c695fefad81c37a7872cc79c78d0de3ff6db9ca
[ "MIT" ]
null
null
null
NewFramework/HelitWing.cpp
lhthang1998/Megaman_X3_DirectX
2c695fefad81c37a7872cc79c78d0de3ff6db9ca
[ "MIT" ]
null
null
null
NewFramework/HelitWing.cpp
lhthang1998/Megaman_X3_DirectX
2c695fefad81c37a7872cc79c78d0de3ff6db9ca
[ "MIT" ]
null
null
null
#include "HelitWing.h" HelitWing::HelitWing() { } HelitWing::HelitWing(MObject* _helit) { helit = _helit; dirRight = helit->dirRight; x = helit->x + OFFSET_X * dirRight; y = helit->y + OFFSET_Y; anim = new Animation(5, 0, 4, ANIM_DELAY); char s[50]; for (int i = 0; i < 5; i++) { sprintf_s(s, "sprites/helit/wing/%d.png", i); anim->sprite[i] = new Sprite(s); } } HelitWing::~HelitWing() { } void HelitWing::Update() { movex = helit->movex; movey = helit->movey; } void HelitWing::Render() { D3DXVECTOR2 translation = D3DXVECTOR2(x + movex, y + movey); D3DXVECTOR2 shift = D3DXVECTOR2(GameGlobal::wndWidth / 2 - GameGlobal::camera->position.x, GameGlobal::wndHeight / 2 - GameGlobal::camera->position.y); D3DXVECTOR2 combined = translation + shift; D3DXVECTOR2 scale = D3DXVECTOR2(1 * dirRight, 1); D3DXMatrixTransformation2D(&matrix, NULL, 0, &scale, NULL, NULL, &combined); x += movex; y += movey; anim->Animate(matrix); }
22.232558
152
0.670502
lhthang1998
546c2676acfcf8921ae40ab6ae1866e2afd2d448
2,512
cpp
C++
development/Common/Utility/source/Logger/YLog.cpp
eglowacki/zloty
9c864ae0beb1ac64137a096795261768b7fc6710
[ "MIT" ]
null
null
null
development/Common/Utility/source/Logger/YLog.cpp
eglowacki/zloty
9c864ae0beb1ac64137a096795261768b7fc6710
[ "MIT" ]
44
2018-06-28T03:01:44.000Z
2022-03-20T19:53:00.000Z
development/Common/Utility/source/Logger/YLog.cpp
eglowacki/zloty
9c864ae0beb1ac64137a096795261768b7fc6710
[ "MIT" ]
null
null
null
#include "Logger/YLog.h" #include "App/AppUtilities.h" #include "StringHelpers.h" #include "Platform/Support.h" #include "Debugging/DevConfiguration.h" #include "Time/GameClock.h" #include <fstream> #include "YagetVersion.h" #if YAGET_LOG_ENABLED == 1 YAGET_COMPILE_GLOBAL_SETTINGS("Log Included") #else YAGET_COMPILE_GLOBAL_SETTINGS("Log NOT Included") #endif // YAGET_LOG_ENABLED namespace { std::set<std::string> GetTagSet() { const auto tags = yaget::ylog::GetRegisteredTags(); std::set<std::string> result(tags.begin(), tags.end());; return result; } } using namespace yaget; void ylog::Initialize(const args::Options& options) { ylog::Config::Vector configList; for (auto&& it : dev::CurrentConfiguration().mDebug.mLogging.Outputs) { ylog::Config::addOutput(configList, it.first.c_str()); for (auto&& o : it.second) { ylog::Config::setOption(configList, o.first.c_str(), o.second.c_str()); } } ylog::Logger& logObject = ylog::Get(); //DBUG, INFO, NOTE, WARN, EROR Log::Level level = ylog::Log::toLevel(dev::CurrentConfiguration().mDebug.mLogging.Level.c_str()); logObject = ylog::Logger(logObject.getName().c_str()); logObject.setLevel(level); // setup filters, which tags will be suppressed from log output Strings filters = dev::CurrentConfiguration().mDebug.mLogging.Filters; for (auto&& it: filters) { if (*it.begin() == '!') { std::string tag(it.begin() + 1, it.end()); ylog::Manager::AddOverrideFilter(Tagger(tag.c_str())); } else { ylog::Manager::AddFilter(Tagger(it.c_str())); } } // Configure the Log Manager (create Output objects) ylog::Manager::configure(configList); // dump file with all registered tags using name and hash values if (options.find<bool>("log_write_tags", false)) { std::string fileName = util::ExpendEnv("$(LogFolder)/LogTags.txt", nullptr); std::ofstream logTagsFile(fileName.c_str()); logTagsFile << "; Currently registered log tags\n"; const auto& tags = GetTagSet(); for (const auto& tag : tags) { logTagsFile << std::setw(4) << std::left << tag << " = " << std::setw(10) << std::right << LOG_TAG(tag.c_str()) << "\n"; } } } ylog::Logger& ylog::Get() { static ylog::Logger ApplicationLogger("yaget"); return ApplicationLogger; }
28.545455
132
0.620223
eglowacki
5471f48d27aadd1d69d1278ad6cb364b8864f37c
31,485
cpp
C++
SU2-Quantum/Common/src/fem/fem_gauss_jacobi_quadrature.cpp
Agony5757/SU2-Quantum
16e7708371a597511e1242f3a7581e8c4187f5b2
[ "Apache-2.0" ]
null
null
null
SU2-Quantum/Common/src/fem/fem_gauss_jacobi_quadrature.cpp
Agony5757/SU2-Quantum
16e7708371a597511e1242f3a7581e8c4187f5b2
[ "Apache-2.0" ]
null
null
null
SU2-Quantum/Common/src/fem/fem_gauss_jacobi_quadrature.cpp
Agony5757/SU2-Quantum
16e7708371a597511e1242f3a7581e8c4187f5b2
[ "Apache-2.0" ]
1
2021-12-03T06:40:08.000Z
2021-12-03T06:40:08.000Z
/*! * \file fem_gauss_jacobi_quadrature.cpp * \brief Functions to compute the points and weights for the Gauss-Jacobi quadrature rules. All the functions in this file are based on the program JACOBI_RULE of John Burkardt. * \author E. van der Weide * \version 7.0.6 "Blackbird" * * SU2 Project Website: https://su2code.github.io * * The SU2 Project is maintained by the SU2 Foundation * (http://su2foundation.org) * * Copyright 2012-2020, SU2 Contributors (cf. AUTHORS.md) * * SU2 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 2.1 of the License, or (at your option) any later version. * * SU2 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 a copy of the GNU Lesser General Public * License along with SU2. If not, see <http://www.gnu.org/licenses/>. */ /* From: "Burkardt, John" <jburkardt@fsu.edu> Subject: Re: Gauss-Jacobi Quadrature Code Date: July 6, 2016 at 4:14:17 AM PDT To: "Thomas D. Economon" <economon@stanford.edu> Cc: Edwin van der Weide <E.T.A.vanderWeide@ctw.utwente.nl> Dear Thomas Economon, Thank you for your note about jacobi_rule.cpp; I am glad you find it of use. You are welcome to use this code in any way you choose. The only reason I put a Gnu LGPL on it was because, from a number of inquiries, it became clear to me that people were hesitant to use a piece of software if there was no license information on it at all. At the time, LGPL seemed the least restrictive. I didn't pay attention to the vexing fact that now there are several versions of LGPL, because I really don't care. If this statement is not enough for you, let me know what would be better. I have no objection to you taking a copy of jacobi_rule.cpp and altering the license to agree with your preferred version of LGPL, for instance. John Burkardt ________________________________________ From: Thomas D. Economon <economon@stanford.edu> Sent: Tuesday, July 5, 2016 11:04:34 PM To: Burkardt, John Cc: Edwin van der Weide Subject: Gauss-Jacobi Quadrature Code Dear John, I am the lead developer for the open-source SU2 suite, which is primarily for computational fluid dynamics, but also for solving other PDE systems (http://su2.stanford.edu, https://github.com/su2code/SU2). Over the past few months, we have been working on a new high-order discontinuous Galerkin fluid solver within the codebase, led by Prof. Edwin van der Weide at the University of Twente (cc’d). We found your attached code to be very helpful in resolving some issues with integration for our pyramid elements, and we would really like to reuse the implementation if possible. First, we would like to check if this is ok with you personally, and ask how we can properly attribute your work in the code? Second, we are curious just what version of the GNU LGPL license you are using to make sure that we don’t have any licensing issues. For SU2, we are using GNU LGPL v2.1. Thanks for the time and take care, Tom */ #include "../../include/fem/fem_gauss_jacobi_quadrature.hpp" void CGaussJacobiQuadrature::GetQuadraturePoints(const passivedouble alpha, const passivedouble beta, const passivedouble a, const passivedouble b, vector<passivedouble> &GJPoints, vector<passivedouble> &GJWeights) { /*--- Determine the number of integration points. Check if the number makes sense. ---*/ unsigned int nIntPoints = (unsigned int)GJPoints.size(); if(nIntPoints < 1 || nIntPoints > 100) SU2_MPI::Error("Invalid number of Gauss Jacobi integration points", CURRENT_FUNCTION); /*--- Call the function cgqf to do the actual work. ---*/ int kind = 4; cgqf(nIntPoints, kind, alpha, beta, a, b, GJPoints.data(), GJWeights.data()); } //****************************************************************************80 void CGaussJacobiQuadrature::cdgqf(int nt, int kind, passivedouble alpha, passivedouble beta, passivedouble t[], passivedouble wts[]) //****************************************************************************80 // // Purpose: // // CDGQF computes a Gauss quadrature formula with default A, B and simple knots. // // Discussion: // // This routine computes all the knots and weights of a Gauss quadrature // formula with a classical weight function with default values for A and B, // and only simple knots. // // There are no moments checks and no printing is done. // // Use routine EIQFS to evaluate a quadrature computed by CGQFS. // // Licensing: // // This code is distributed under the GNU LGPL license. // // Modified: // // 08 January 2010 // // Author: // // Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky. // C++ version by John Burkardt. // // Reference: // // Sylvan Elhay, Jaroslav Kautsky, // Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of // Interpolatory Quadrature, // ACM Transactions on Mathematical Software, // Volume 13, Number 4, December 1987, pages 399-415. // // Parameters: // // Input, int NT, the number of knots. // // Input, int KIND, the rule. // 1, Legendre, (a,b) 1.0 // 2, Chebyshev, (a,b) ((b-x)*(x-a))^(-0.5) // 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha // 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta // 5, Generalized Laguerre, (a,inf) (x-a)^alpha*exp(-b*(x-a)) // 6, Generalized Hermite, (-inf,inf) |x-a|^alpha*exp(-b*(x-a)^2) // 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha // 8, Rational, (a,inf) (x-a)^alpha*(x+b)^beta // // Input, passivedouble ALPHA, the value of Alpha, if needed. // // Input, passivedouble BETA, the value of Beta, if needed. // // Output, passivedouble T[NT], the knots. // // Output, passivedouble WTS[NT], the weights. // { passivedouble *aj; passivedouble *bj; passivedouble zemu; parchk ( kind, 2 * nt, alpha, beta ); // // Get the Jacobi matrix and zero-th moment. // aj = new passivedouble[nt]; bj = new passivedouble[nt]; zemu = class_matrix ( kind, nt, alpha, beta, aj, bj ); // // Compute the knots and weights. // sgqf ( nt, aj, bj, zemu, t, wts ); delete [] aj; delete [] bj; return; } //****************************************************************************80 void CGaussJacobiQuadrature::cgqf(int nt, int kind, passivedouble alpha, passivedouble beta, passivedouble a, passivedouble b, passivedouble t[], passivedouble wts[]) //****************************************************************************80 // // Purpose: // // CGQF computes knots and weights of a Gauss quadrature formula. // // Discussion: // // The user may specify the interval (A,B). // // Only simple knots are produced. // // Use routine EIQFS to evaluate this quadrature formula. // // Licensing: // // This code is distributed under the GNU LGPL license. // // Modified: // // 16 February 2010 // // Author: // // Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky. // C++ version by John Burkardt. // // Reference: // // Sylvan Elhay, Jaroslav Kautsky, // Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of // Interpolatory Quadrature, // ACM Transactions on Mathematical Software, // Volume 13, Number 4, December 1987, pages 399-415. // // Parameters: // // Input, int NT, the number of knots. // // Input, int KIND, the rule. // 1, Legendre, (a,b) 1.0 // 2, Chebyshev Type 1, (a,b) ((b-x)*(x-a))^-0.5) // 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha // 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta // 5, Generalized Laguerre, (a,+oo) (x-a)^alpha*exp(-b*(x-a)) // 6, Generalized Hermite, (-oo,+oo) |x-a|^alpha*exp(-b*(x-a)^2) // 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha // 8, Rational, (a,+oo) (x-a)^alpha*(x+b)^beta // 9, Chebyshev Type 2, (a,b) ((b-x)*(x-a))^(+0.5) // // Input, passivedouble ALPHA, the value of Alpha, if needed. // // Input, passivedouble BETA, the value of Beta, if needed. // // Input, passivedouble A, B, the interval endpoints, or // other parameters. // // Output, passivedouble T[NT], the knots. // // Output, passivedouble WTS[NT], the weights. // { int i; int *mlt; int *ndx; // // Compute the Gauss quadrature formula for default values of A and B. // cdgqf ( nt, kind, alpha, beta, t, wts ); // // Prepare to scale the quadrature formula to other weight function with // valid A and B. // mlt = new int[nt]; for ( i = 0; i < nt; i++ ) { mlt[i] = 1; } ndx = new int[nt]; for ( i = 0; i < nt; i++ ) { ndx[i] = i + 1; } scqf ( nt, t, mlt, wts, nt, ndx, wts, t, kind, alpha, beta, a, b ); delete [] mlt; delete [] ndx; return; } //****************************************************************************80 passivedouble CGaussJacobiQuadrature::class_matrix(int kind, int m, passivedouble alpha, passivedouble beta, passivedouble aj[], passivedouble bj[]) //****************************************************************************80 // // Purpose: // // CLASS_MATRIX computes the Jacobi matrix for a quadrature rule. // // Discussion: // // This routine computes the diagonal AJ and sub-diagonal BJ // elements of the order M tridiagonal symmetric Jacobi matrix // associated with the polynomials orthogonal with respect to // the weight function specified by KIND. // // For weight functions 1-7, M elements are defined in BJ even // though only M-1 are needed. For weight function 8, BJ(M) is // set to zero. // // The zero-th moment of the weight function is returned in ZEMU. // // Licensing: // // This code is distributed under the GNU LGPL license. // // Modified: // // 08 January 2010 // // Author: // // Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky. // C++ version by John Burkardt. // // Reference: // // Sylvan Elhay, Jaroslav Kautsky, // Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of // Interpolatory Quadrature, // ACM Transactions on Mathematical Software, // Volume 13, Number 4, December 1987, pages 399-415. // // Parameters: // // Input, int KIND, the rule. // 1, Legendre, (a,b) 1.0 // 2, Chebyshev, (a,b) ((b-x)*(x-a))^(-0.5) // 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha // 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta // 5, Generalized Laguerre, (a,inf) (x-a)^alpha*exp(-b*(x-a)) // 6, Generalized Hermite, (-inf,inf) |x-a|^alpha*exp(-b*(x-a)^2) // 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha // 8, Rational, (a,inf) (x-a)^alpha*(x+b)^beta // // Input, int M, the order of the Jacobi matrix. // // Input, passivedouble ALPHA, the value of Alpha, if needed. // // Input, passivedouble BETA, the value of Beta, if needed. // // Output, passivedouble AJ[M], BJ[M], the diagonal and subdiagonal // of the Jacobi matrix. // // Output, passivedouble CLASS_MATRIX, the zero-th moment. // { passivedouble a2b2; passivedouble ab; passivedouble aba; passivedouble abi; passivedouble abj; passivedouble abti; passivedouble apone; int i; passivedouble pi = 3.14159265358979323846264338327950; passivedouble temp; passivedouble temp2; passivedouble zemu; temp = r8_epsilon ( ); parchk ( kind, 2 * m - 1, alpha, beta ); temp2 = 0.5; if ( 500.0 * temp < fabs ( pow ( tgamma ( temp2 ), 2 ) - pi ) ) { cout << "\n"; cout << "CLASS_MATRIX - Fatal error!\n"; cout << " Gamma function does not match machine parameters.\n"; exit ( 1 ); } if ( kind == 1 ) { ab = 0.0; zemu = 2.0 / ( ab + 1.0 ); for ( i = 0; i < m; i++ ) { aj[i] = 0.0; } for ( i = 1; i <= m; i++ ) { abi = i + ab * ( i % 2 ); abj = 2 * i + ab; bj[i-1] = sqrt ( abi * abi / ( abj * abj - 1.0 ) ); } } else if ( kind == 2 ) { zemu = pi; for ( i = 0; i < m; i++ ) { aj[i] = 0.0; } bj[0] = sqrt ( 0.5 ); for ( i = 1; i < m; i++ ) { bj[i] = 0.5; } } else if ( kind == 3 ) { ab = alpha * 2.0; zemu = pow ( 2.0, ab + 1.0 ) * pow ( tgamma ( alpha + 1.0 ), 2 ) / tgamma ( ab + 2.0 ); for ( i = 0; i < m; i++ ) { aj[i] = 0.0; } bj[0] = sqrt ( 1.0 / ( 2.0 * alpha + 3.0 ) ); for ( i = 2; i <= m; i++ ) { bj[i-1] = sqrt ( i * ( i + ab ) / ( 4.0 * pow ( i + alpha, 2 ) - 1.0 ) ); } } else if ( kind == 4 ) { ab = alpha + beta; abi = 2.0 + ab; zemu = pow ( 2.0, ab + 1.0 ) * tgamma ( alpha + 1.0 ) * tgamma ( beta + 1.0 ) / tgamma ( abi ); aj[0] = ( beta - alpha ) / abi; bj[0] = sqrt ( 4.0 * ( 1.0 + alpha ) * ( 1.0 + beta ) / ( ( abi + 1.0 ) * abi * abi ) ); a2b2 = beta * beta - alpha * alpha; for ( i = 2; i <= m; i++ ) { abi = 2.0 * i + ab; aj[i-1] = a2b2 / ( ( abi - 2.0 ) * abi ); abi = abi * abi; bj[i-1] = sqrt ( 4.0 * i * ( i + alpha ) * ( i + beta ) * ( i + ab ) / ( ( abi - 1.0 ) * abi ) ); } } else if ( kind == 5 ) { zemu = tgamma ( alpha + 1.0 ); for ( i = 1; i <= m; i++ ) { aj[i-1] = 2.0 * i - 1.0 + alpha; bj[i-1] = sqrt ( i * ( i + alpha ) ); } } else if ( kind == 6 ) { zemu = tgamma ( ( alpha + 1.0 ) / 2.0 ); for ( i = 0; i < m; i++ ) { aj[i] = 0.0; } for ( i = 1; i <= m; i++ ) { bj[i-1] = sqrt ( ( i + alpha * ( i % 2 ) ) / 2.0 ); } } else if ( kind == 7 ) { ab = alpha; zemu = 2.0 / ( ab + 1.0 ); for ( i = 0; i < m; i++ ) { aj[i] = 0.0; } for ( i = 1; i <= m; i++ ) { abi = i + ab * ( i % 2 ); abj = 2 * i + ab; bj[i-1] = sqrt ( abi * abi / ( abj * abj - 1.0 ) ); } } else // if ( kind == 8 ) { ab = alpha + beta; zemu = tgamma ( alpha + 1.0 ) * tgamma ( - ( ab + 1.0 ) ) / tgamma ( - beta ); apone = alpha + 1.0; aba = ab * apone; aj[0] = - apone / ( ab + 2.0 ); bj[0] = - aj[0] * ( beta + 1.0 ) / ( ab + 2.0 ) / ( ab + 3.0 ); for ( i = 2; i <= m; i++ ) { abti = ab + 2.0 * i; aj[i-1] = aba + 2.0 * ( ab + i ) * ( i - 1 ); aj[i-1] = - aj[i-1] / abti / ( abti - 2.0 ); } for ( i = 2; i <= m - 1; i++ ) { abti = ab + 2.0 * i; bj[i-1] = i * ( alpha + i ) / ( abti - 1.0 ) * ( beta + i ) / ( abti * abti ) * ( ab + i ) / ( abti + 1.0 ); } bj[m-1] = 0.0; for ( i = 0; i < m; i++ ) { bj[i] = sqrt ( bj[i] ); } } return zemu; } //****************************************************************************80 void CGaussJacobiQuadrature::imtqlx(int n, passivedouble d[], passivedouble e[], passivedouble z[]) //****************************************************************************80 // // Purpose: // // IMTQLX diagonalizes a symmetric tridiagonal matrix. // // Discussion: // // This routine is a slightly modified version of the EISPACK routine to // perform the implicit QL algorithm on a symmetric tridiagonal matrix. // // The authors thank the authors of EISPACK for permission to use this // routine. // // It has been modified to produce the product Q' * Z, where Z is an input // vector and Q is the orthogonal matrix diagonalizing the input matrix. // The changes consist (essentialy) of applying the orthogonal transformations // directly to Z as they are generated. // // Licensing: // // This code is distributed under the GNU LGPL license. // // Modified: // // 08 January 2010 // // Author: // // Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky. // C++ version by John Burkardt. // // Reference: // // Sylvan Elhay, Jaroslav Kautsky, // Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of // Interpolatory Quadrature, // ACM Transactions on Mathematical Software, // Volume 13, Number 4, December 1987, pages 399-415. // // Roger Martin, James Wilkinson, // The Implicit QL Algorithm, // Numerische Mathematik, // Volume 12, Number 5, December 1968, pages 377-383. // // Parameters: // // Input, int N, the order of the matrix. // // Input/output, passivedouble D(N), the diagonal entries of the matrix. // On output, the information in D has been overwritten. // // Input/output, passivedouble E(N), the subdiagonal entries of the // matrix, in entries E(1) through E(N-1). On output, the information in // E has been overwritten. // // Input/output, passivedouble Z(N). On input, a vector. On output, // the value of Q' * Z, where Q is the matrix that diagonalizes the // input symmetric tridiagonal matrix. // { passivedouble b; passivedouble c; passivedouble f; passivedouble g; int i; int ii; int itn = 30; int j; int k; int l; int m = 0; // To avoid a compiler warning. int mml; passivedouble p; passivedouble prec; passivedouble r; passivedouble s; prec = r8_epsilon ( ); if ( n == 1 ) { return; } e[n-1] = 0.0; for ( l = 1; l <= n; l++ ) { j = 0; for ( ; ; ) { for ( m = l; m <= n; m++ ) { if ( m == n ) { break; } if ( fabs ( e[m-1] ) <= prec * ( fabs ( d[m-1] ) + fabs ( d[m] ) ) ) { break; } } p = d[l-1]; if ( m == l ) { break; } if ( itn <= j ) { cout << "\n"; cout << "IMTQLX - Fatal error!\n"; cout << " Iteration limit exceeded\n"; exit ( 1 ); } j = j + 1; g = ( d[l] - p ) / ( 2.0 * e[l-1] ); r = sqrt ( g * g + 1.0 ); g = d[m-1] - p + e[l-1] / ( g + fabs ( r ) * r8_sign ( g ) ); s = 1.0; c = 1.0; p = 0.0; mml = m - l; for ( ii = 1; ii <= mml; ii++ ) { i = m - ii; f = s * e[i-1]; b = c * e[i-1]; if ( fabs ( g ) <= fabs ( f ) ) { c = g / f; r = sqrt ( c * c + 1.0 ); e[i] = f * r; s = 1.0 / r; c = c * s; } else { s = f / g; r = sqrt ( s * s + 1.0 ); e[i] = g * r; c = 1.0 / r; s = s * c; } g = d[i] - p; r = ( d[i-1] - g ) * s + 2.0 * c * b; p = s * r; d[i] = g + p; g = c * r - b; f = z[i]; z[i] = s * z[i-1] + c * f; z[i-1] = c * z[i-1] - s * f; } d[l-1] = d[l-1] - p; e[l-1] = g; e[m-1] = 0.0; } } // // Sorting. // for ( ii = 2; ii <= m; ii++ ) { i = ii - 1; k = i; p = d[i-1]; for ( j = ii; j <= n; j++ ) { if ( d[j-1] < p ) { k = j; p = d[j-1]; } } if ( k != i ) { d[k-1] = d[i-1]; d[i-1] = p; p = z[i-1]; z[i-1] = z[k-1]; z[k-1] = p; } } return; } //****************************************************************************80 void CGaussJacobiQuadrature::parchk(int kind, int m, passivedouble alpha, passivedouble beta) //****************************************************************************80 // // Purpose: // // PARCHK checks parameters ALPHA and BETA for classical weight functions. // // Licensing: // // This code is distributed under the GNU LGPL license. // // Modified: // // 07 January 2010 // // Author: // // Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky. // C++ version by John Burkardt. // // Reference: // // Sylvan Elhay, Jaroslav Kautsky, // Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of // Interpolatory Quadrature, // ACM Transactions on Mathematical Software, // Volume 13, Number 4, December 1987, pages 399-415. // // Parameters: // // Input, int KIND, the rule. // 1, Legendre, (a,b) 1.0 // 2, Chebyshev, (a,b) ((b-x)*(x-a))^(-0.5) // 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha // 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta // 5, Generalized Laguerre, (a,inf) (x-a)^alpha*exp(-b*(x-a)) // 6, Generalized Hermite, (-inf,inf) |x-a|^alpha*exp(-b*(x-a)^2) // 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha // 8, Rational, (a,inf) (x-a)^alpha*(x+b)^beta // // Input, int M, the order of the highest moment to // be calculated. This value is only needed when KIND = 8. // // Input, passivedouble ALPHA, BETA, the parameters, if required // by the value of KIND. // { passivedouble tmp; if ( kind <= 0 ) { cout << "\n"; cout << "PARCHK - Fatal error!\n"; cout << " KIND <= 0.\n"; exit ( 1 ); } // // Check ALPHA for Gegenbauer, Jacobi, Laguerre, Hermite, Exponential. // if ( 3 <= kind && alpha <= -1.0 ) { cout << "\n"; cout << "PARCHK - Fatal error!\n"; cout << " 3 <= KIND and ALPHA <= -1.\n"; exit ( 1 ); } // // Check BETA for Jacobi. // if ( kind == 4 && beta <= -1.0 ) { cout << "\n"; cout << "PARCHK - Fatal error!\n"; cout << " KIND == 4 and BETA <= -1.0.\n"; exit ( 1 ); } // // Check ALPHA and BETA for rational. // if ( kind == 8 ) { tmp = alpha + beta + m + 1.0; if ( 0.0 <= tmp || tmp <= beta ) { cout << "\n"; cout << "PARCHK - Fatal error!\n"; cout << " KIND == 8 but condition on ALPHA and BETA fails.\n"; exit ( 1 ); } } return; } //****************************************************************************80 passivedouble CGaussJacobiQuadrature::r8_epsilon( ) //****************************************************************************80 // // Purpose: // // R8_EPSILON returns the R8 roundoff unit. // // Discussion: // // The roundoff unit is a number R which is a power of 2 with the // property that, to the precision of the computer's arithmetic, // 1 < 1 + R // but // 1 = ( 1 + R / 2 ) // // Licensing: // // This code is distributed under the GNU LGPL license. // // Modified: // // 01 September 2012 // // Author: // // John Burkardt // // Parameters: // // Output, passivedouble R8_EPSILON, the R8 round-off unit. // { const passivedouble value = 2.220446049250313E-016; return value; } //****************************************************************************80 passivedouble CGaussJacobiQuadrature::r8_sign(passivedouble x) //****************************************************************************80 // // Purpose: // // R8_SIGN returns the sign of an R8. // // Licensing: // // This code is distributed under the GNU LGPL license. // // Modified: // // 18 October 2004 // // Author: // // John Burkardt // // Parameters: // // Input, passivedouble X, the number whose sign is desired. // // Output, passivedouble R8_SIGN, the sign of X. // { passivedouble value; if ( x < 0.0 ) { value = -1.0; } else { value = 1.0; } return value; } //****************************************************************************80 void CGaussJacobiQuadrature::scqf(int nt, const passivedouble t[], const int mlt[], const passivedouble wts[], int nwts, int ndx[], passivedouble swts[], passivedouble st[], int kind, passivedouble alpha, passivedouble beta, passivedouble a, passivedouble b) //****************************************************************************80 // // Purpose: // // SCQF scales a quadrature formula to a nonstandard interval. // // Discussion: // // The arrays WTS and SWTS may coincide. // // The arrays T and ST may coincide. // // Licensing: // // This code is distributed under the GNU LGPL license. // // Modified: // // 16 February 2010 // // Author: // // Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky. // C++ version by John Burkardt. // // Reference: // // Sylvan Elhay, Jaroslav Kautsky, // Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of // Interpolatory Quadrature, // ACM Transactions on Mathematical Software, // Volume 13, Number 4, December 1987, pages 399-415. // // Parameters: // // Input, int NT, the number of knots. // // Input, passivedouble T[NT], the original knots. // // Input, int MLT[NT], the multiplicity of the knots. // // Input, passivedouble WTS[NWTS], the weights. // // Input, int NWTS, the number of weights. // // Input, int NDX[NT], used to index the array WTS. // For more details see the comments in CAWIQ. // // Output, passivedouble SWTS[NWTS], the scaled weights. // // Output, passivedouble ST[NT], the scaled knots. // // Input, int KIND, the rule. // 1, Legendre, (a,b) 1.0 // 2, Chebyshev Type 1, (a,b) ((b-x)*(x-a))^(-0.5) // 3, Gegenbauer, (a,b) ((b-x)*(x-a))^alpha // 4, Jacobi, (a,b) (b-x)^alpha*(x-a)^beta // 5, Generalized Laguerre, (a,+oo) (x-a)^alpha*exp(-b*(x-a)) // 6, Generalized Hermite, (-oo,+oo) |x-a|^alpha*exp(-b*(x-a)^2) // 7, Exponential, (a,b) |x-(a+b)/2.0|^alpha // 8, Rational, (a,+oo) (x-a)^alpha*(x+b)^beta // 9, Chebyshev Type 2, (a,b) ((b-x)*(x-a))^(+0.5) // // Input, passivedouble ALPHA, the value of Alpha, if needed. // // Input, passivedouble BETA, the value of Beta, if needed. // // Input, passivedouble A, B, the interval endpoints. // { passivedouble al; passivedouble be; int i; int k; int l; passivedouble p; passivedouble shft; passivedouble slp; passivedouble temp; passivedouble tmp; temp = r8_epsilon ( ); parchk ( kind, 1, alpha, beta ); if ( kind == 1 ) { al = 0.0; be = 0.0; if ( fabs ( b - a ) <= temp ) { cout << "\n"; cout << "SCQF - Fatal error!\n"; cout << " |B - A| too small.\n"; exit ( 1 ); } shft = ( a + b ) / 2.0; slp = ( b - a ) / 2.0; } else if ( kind == 2 ) { al = -0.5; be = -0.5; if ( fabs ( b - a ) <= temp ) { cout << "\n"; cout << "SCQF - Fatal error!\n"; cout << " |B - A| too small.\n"; exit ( 1 ); } shft = ( a + b ) / 2.0; slp = ( b - a ) / 2.0; } else if ( kind == 3 ) { al = alpha; be = alpha; if ( fabs ( b - a ) <= temp ) { cout << "\n"; cout << "SCQF - Fatal error!\n"; cout << " |B - A| too small.\n"; exit ( 1 ); } shft = ( a + b ) / 2.0; slp = ( b - a ) / 2.0; } else if ( kind == 4 ) { al = alpha; be = beta; if ( fabs ( b - a ) <= temp ) { cout << "\n"; cout << "SCQF - Fatal error!\n"; cout << " |B - A| too small.\n"; exit ( 1 ); } shft = ( a + b ) / 2.0; slp = ( b - a ) / 2.0; } else if ( kind == 5 ) { if ( b <= 0.0 ) { cout << "\n"; cout << "SCQF - Fatal error!\n"; cout << " B <= 0\n"; exit ( 1 ); } shft = a; slp = 1.0 / b; al = alpha; be = 0.0; } else if ( kind == 6 ) { if ( b <= 0.0 ) { cout << "\n"; cout << "SCQF - Fatal error!\n"; cout << " B <= 0.\n"; exit ( 1 ); } shft = a; slp = 1.0 / sqrt ( b ); al = alpha; be = 0.0; } else if ( kind == 7 ) { al = alpha; be = 0.0; if ( fabs ( b - a ) <= temp ) { cout << "\n"; cout << "SCQF - Fatal error!\n"; cout << " |B - A| too small.\n"; exit ( 1 ); } shft = ( a + b ) / 2.0; slp = ( b - a ) / 2.0; } else if ( kind == 8 ) { if ( a + b <= 0.0 ) { cout << "\n"; cout << "SCQF - Fatal error!\n"; cout << " A + B <= 0.\n"; exit ( 1 ); } shft = a; slp = a + b; al = alpha; be = beta; } else // if ( kind == 9 ) { al = 0.5; be = 0.5; if ( fabs ( b - a ) <= temp ) { cout << "\n"; cout << "SCQF - Fatal error!\n"; cout << " |B - A| too small.\n"; exit ( 1 ); } shft = ( a + b ) / 2.0; slp = ( b - a ) / 2.0; } p = pow ( slp, al + be + 1.0 ); for ( k = 0; k < nt; k++ ) { st[k] = shft + slp * t[k]; l = abs ( ndx[k] ); if ( l != 0 ) { tmp = p; for ( i = l - 1; i <= l - 1 + mlt[k] - 1; i++ ) { swts[i] = wts[i] * tmp; tmp = tmp * slp; } } } return; } //****************************************************************************80 void CGaussJacobiQuadrature::sgqf(int nt, const passivedouble aj[], passivedouble bj[], passivedouble zemu, passivedouble t[], passivedouble wts[]) //****************************************************************************80 // // Purpose: // // SGQF computes knots and weights of a Gauss Quadrature formula. // // Discussion: // // This routine computes all the knots and weights of a Gauss quadrature // formula with simple knots from the Jacobi matrix and the zero-th // moment of the weight function, using the Golub-Welsch technique. // // Licensing: // // This code is distributed under the GNU LGPL license. // // Modified: // // 08 January 2010 // // Author: // // Original FORTRAN77 version by Sylvan Elhay, Jaroslav Kautsky. // C++ version by John Burkardt. // // Reference: // // Sylvan Elhay, Jaroslav Kautsky, // Algorithm 655: IQPACK, FORTRAN Subroutines for the Weights of // Interpolatory Quadrature, // ACM Transactions on Mathematical Software, // Volume 13, Number 4, December 1987, pages 399-415. // // Parameters: // // Input, int NT, the number of knots. // // Input, passivedouble AJ[NT], the diagonal of the Jacobi matrix. // // Input/output, passivedouble BJ[NT], the subdiagonal of the Jacobi // matrix, in entries 1 through NT-1. On output, BJ has been overwritten. // // Input, passivedouble ZEMU, the zero-th moment of the weight function. // // Output, passivedouble T[NT], the knots. // // Output, passivedouble WTS[NT], the weights. // { int i; // // Exit if the zero-th moment is not positive. // if ( zemu <= 0.0 ) { cout << "\n"; cout << "SGQF - Fatal error!\n"; cout << " ZEMU <= 0.\n"; exit ( 1 ); } // // Set up vectors for IMTQLX. // for ( i = 0; i < nt; i++ ) { t[i] = aj[i]; } wts[0] = sqrt ( zemu ); for ( i = 1; i < nt; i++ ) { wts[i] = 0.0; } // // Diagonalize the Jacobi matrix. // imtqlx ( nt, t, bj, wts ); for ( i = 0; i < nt; i++ ) { wts[i] = wts[i] * wts[i]; } return; }
25.934926
117
0.512307
Agony5757
547256a644e198048b62b52d9ff88db2097ccb1c
41,567
cpp
C++
src/virtualMachine/VirtualMachine.cpp
Suru-09/Compilation-Tehniques
cbfc5f5a47d786287d7a75e68814de113e3d0375
[ "MIT" ]
null
null
null
src/virtualMachine/VirtualMachine.cpp
Suru-09/Compilation-Tehniques
cbfc5f5a47d786287d7a75e68814de113e3d0375
[ "MIT" ]
null
null
null
src/virtualMachine/VirtualMachine.cpp
Suru-09/Compilation-Tehniques
cbfc5f5a47d786287d7a75e68814de113e3d0375
[ "MIT" ]
null
null
null
#include "VirtualMachine.hpp" VirtualMachine::~VirtualMachine() { // delete stack_ptr; // delete stack_ptr; } VirtualMachine::VirtualMachine() : stack_ptr(nullptr), stack_after(nullptr), n_globals(0), class_name("VirtualMachine") { logger = Logger{class_name}; } void VirtualMachine::push_d(const double& d) { if ( stack_ptr + sizeof(double) > stack_after ) { std::cout << logger << "[PUSH_D] OUT OF STACK!\n"; exit(1); } *(double *)stack_ptr = d; stack_ptr += sizeof(double); } double VirtualMachine::pop_d() { if ( stack_ptr - sizeof(double) < stack ) { std::cout << logger << "[POP_D] NOT ENOUGH BYTES ON STACK!\n"; exit(1); } stack_ptr -= sizeof(double); return *(double *)stack_ptr; } void VirtualMachine::push_i(const long& i) { if ( stack_ptr + sizeof(int) > stack_after ) { std::cout << logger << "[PUSH_I] OUT OF STACK!\n"; exit(1); } *(int *)stack_ptr = i; stack_ptr += sizeof(long); } int VirtualMachine::pop_i() { if ( stack_ptr - sizeof(long) < stack ) { std::cout << logger << "[POP_I] NOT ENOUGH BYTES ON STACK!\n"; exit(1); } stack_ptr -= sizeof(long); return *(long *)stack_ptr; } void VirtualMachine::push_c(const char& c) { if ( stack_ptr + sizeof(char) > stack_after ) { std::cout << logger << "[PUSH_C] OUT OF STACK!\n"; exit(1); } *(char *)stack_ptr = c; stack_ptr += sizeof(char); } char VirtualMachine::pop_c() { if ( stack_ptr - sizeof(char) < stack ) { std::cout << logger << "[POP_C] NOT ENOUGH BYTES ON STACK!\n"; exit(1); } stack_ptr -= sizeof(char); return *(char *)stack_ptr; } void VirtualMachine::push_a(void * a) { if ( stack_ptr + sizeof(void *) > stack_after ) { std::cout << logger << "[PUSH_A] OUT OF STACK!\n"; exit(1); } *(void **)stack_ptr = a; stack_ptr += sizeof(void *); } void * VirtualMachine::pop_a() { if ( stack_ptr - sizeof(void *) < stack ) { std::cout << logger << "[POP_A] NOT ENOUGH BYTES ON STACK!\n"; exit(1); } stack_ptr -= sizeof(void *); return *(void **)stack_ptr; } void* VirtualMachine::alloc_heap(const int& size) { if ( n_globals + size > GLOBAL_SIZE ) { std::cout << logger << "There is not enough memory on the Heap!\n"; exit(2); } void * p = globals + n_globals; n_globals += size; return p; } void VirtualMachine::set_il(const InstructionList& instr_list) { this->instr_list = instr_list; } InstructionList VirtualMachine::get_il() { return instr_list; } void VirtualMachine::run() { long int i_val_1, i_val_2; double d_val_1, d_val_2; char * a_val, * a_val_2; char * frame_ptr = 0, * old_sp; stack_ptr = stack; // we allocated continuouus memory for the stack, use it stack_after = stack + STACK_SIZE; // this should be the first address after // the stack's memory for ( std::list<Instruction>::iterator it = instr_list.instr_list.begin() ; it != instr_list.instr_list.end() ;) { // std::cout << logger << "IP: [" << (int)(*it).op_code << "] SP-stack: [" // << (stack_ptr - stack) << "]\n"; // std::cout << logger << "STACK_PTR: [" << reinterpret_cast<void*> (&stack_ptr) << "]\n"; switch ((*it).op_code) { case 0: // O_HALT std::cout << logger << "[O_HALT_INSTRUCTION]\n"; return; case 1: // O_ADD_C i_val_1 = pop_c(); i_val_2 = pop_c(); std::cout << logger << "[O_ADD_C] Adding: " << i_val_1 << " + " << i_val_2 << " -> " << "[" << i_val_1 + i_val_2 << "]\n"; push_c(i_val_1 + i_val_2); ++it; break; case 2: // O_ADD_D d_val_1 = pop_d(); d_val_2 = pop_d(); std::cout << logger << "[O_ADD_D] Adding: " << d_val_1 << " + " << d_val_2 << " -> " << "[" << d_val_1 + d_val_2 << "]\n"; push_d(d_val_1 + d_val_2); break; case 3: // O_ADD_I i_val_1 = pop_i(); i_val_2 = pop_i(); std::cout << logger << "[O_ADD_I] Adding: " << i_val_1 << " + " << i_val_2 << " -> " << "[" << i_val_1 + i_val_2 << "]\n"; push_i(i_val_1 + i_val_2); ++it; break; case 4: // O_AND_C i_val_1 = pop_c(); i_val_2 = pop_c(); std::cout << logger << "[O_AND_C] AND: " << i_val_1 << " + " << i_val_2 << " -> " << "[" << (i_val_1 && i_val_2) << "]\n"; push_i(i_val_1 && i_val_2); ++it; break; case 5: // O_AND_D d_val_1 = pop_d(); d_val_2 = pop_d(); std::cout << logger << "[O_AND_D] AND: " << d_val_1 << " + " << d_val_2 << " -> " << "[" << (d_val_1 && d_val_2) << "]\n"; push_i(d_val_1 && d_val_2); ++it; break; case 6: // O_AND_I i_val_1 = pop_i(); i_val_2 = pop_i(); std::cout << logger << "[O_AND_I] AND: " << i_val_1 << " + " << i_val_2 << " -> " << "[" << (i_val_1 && i_val_2) << "]\n"; push_i(i_val_1 + i_val_2); ++it; break; case 7: // O_CALL std::cout << logger << "[O_CALL_INSTRUCTION]\n"; if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "void") { auto val = std::get<void *> ((*it).args[0]); auto itr = std::find(instr_list.instr_list.begin(), instr_list.instr_list.end(), (*static_cast<Instruction *> (val))); if ( itr != instr_list.instr_list.end()) { push_a(reinterpret_cast<void *>(&(++it))); it = itr; } else { std::cout << logger << "[O_CALL_INSTRUCTION] Given instruction was wrong!\n"; exit(3); } } else { std::cout << logger << "[O_CALL] Wrong structure called!\n"; exit(2); } break; case 8: // O_CALLEXT std::cout << logger << "[O_CALLEXT_INSTRUCTION]\n"; if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "void") { auto IP = std::get<void *> ((*it).args[0]); (*(void(*)())IP)(); // This is really dangerous } else { std::cout << logger << "[O_CALLEXT] Wrong structure called!\n"; exit(2); } ++it; break; case 9: // O_CAST_C_D i_val_1 = pop_c(); d_val_1 = static_cast<double>(i_val_1); std::cout << logger << "[O_CAST_C_D] char: " << i_val_1 << "to double: " << d_val_1 << "\n"; push_d(d_val_1); it++; break; case 10: // O_CAST_C_I i_val_1 = pop_c(); i_val_2 = static_cast<long>(i_val_1); std::cout << logger << "[O_CAST_C_I] char: " << i_val_1 << "to integer: " << i_val_2 << "\n"; push_i(i_val_2); it++; break; case 11: // O_CAST_D_C d_val_1 = pop_d(); i_val_1 = static_cast<char>(d_val_1); std::cout << logger << "[O_CAST_D_C] double: " << d_val_1 << "to char: " << i_val_1 << "\n"; push_i(i_val_1); it++; break; case 12: // O_CAST_D_I d_val_1 = pop_d(); i_val_1 = static_cast<long>(d_val_1); std::cout << logger << "[O_CAST_D_I] double: " << d_val_1 << "to integer: " << i_val_1 << "\n"; push_i(i_val_1); it++; break; case 13: // O_CAST_I_C i_val_1 = pop_i(); i_val_2 = static_cast<char>(i_val_1); std::cout << logger << "[O_CAST_I_C] integer: " << i_val_1 << "to char: " << i_val_2 << "\n"; push_i(i_val_2); it++; break; case 14: // O_CAST_I_D i_val_1 = pop_i(); d_val_1 = static_cast<double>(i_val_1); std::cout << logger << "[O_CAST_I_D] int: " << i_val_1 << "to double: " << d_val_1 << "\n"; push_d(d_val_1); it++; break; case 15: // O_DIV_C i_val_1 = pop_c(); i_val_2 = pop_c(); std::cout << logger << "[O_DIV_C] DIV: " << i_val_1 << " / " << i_val_2 << " -> [" << i_val_1 / i_val_2 << "]\n"; push_c(i_val_1 / i_val_2); it++; break; case 16: // O_DIV_D d_val_1 = pop_d(); d_val_2 = pop_d(); std::cout << logger << "[O_DIV_D] DIV: " << d_val_1 << " / " << d_val_2 << " -> [" << d_val_1 / d_val_2 << "]\n"; push_d(d_val_1 / d_val_2); it++; break; case 17: // O_DIV_I i_val_1 = pop_i(); i_val_2 = pop_i(); std::cout << logger << "[O_DIV_I] DIV: " << i_val_1 << " / " << i_val_2 << " -> [" << i_val_1 / i_val_2 << "]\n"; push_i(i_val_1 / i_val_2); it++; break; case 18: // O_DROP if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "long" ) { i_val_1 = std::get<long> ((*it).args[0]); std::cout << logger << "[O_DROP] value: " << i_val_1 << "\n"; if (stack_ptr - i_val_1 < stack) { std::cout << logger << "[O_DROP] not enough stack bytes!\n"; exit(3); } stack_ptr -= i_val_1; ++it; } else { std::cout << logger << "[O_DROP] Wrong structure calling!\n"; exit(2); } break; case 19: // O_ENTER if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "long" ) { i_val_1 = std::get<long> ((*it).args[0]); std::cout << logger << "[O_ENTER] ENTER: " << i_val_1 << "\n"; push_a(frame_ptr); frame_ptr = stack_ptr; stack_ptr += i_val_1; ++it; } else { std::cout << logger << "[O_ENTER] Wrong structure calling!\n"; exit(2); } break; case 20: // O_EQ_A a_val = static_cast<char *> (pop_a()); a_val_2 = static_cast<char *> (pop_a()); std::cout << logger << "[O_EQ_A] [" << a_val << "] == [" << a_val_2 << "] -> " << (d_val_1 == d_val_2) << "\n"; push_i(d_val_1 == d_val_2); ++it; break; case 21: // O_EQ_C i_val_1 = pop_c(); i_val_2 = pop_c(); std::cout << logger << "[O_EQ_C] [" << i_val_1 << "] == [" << i_val_2 << "] -> " << (i_val_1 == i_val_2) << "\n"; push_i(i_val_1 == i_val_2); ++it; break; case 22: // O_EQ_D d_val_1 = pop_d(); d_val_2 = pop_d(); std::cout << logger << "[O_EQ_D] [" << d_val_1 << "] == [" << d_val_2 << "] -> " << (d_val_1 == d_val_2) << "\n"; push_i(d_val_1 == d_val_2); ++it; break; case 23: // O_EQ_I i_val_1 = pop_i(); i_val_2 = pop_i(); std::cout << logger << "[O_EQ_I] [" << i_val_1 << "] == [" << i_val_2 << "] -> " << (i_val_1 == i_val_2) << "\n"; push_i(i_val_1 == i_val_2); ++it; break; case 24: // O_GREATER_C i_val_1 = pop_c(); i_val_2 = pop_c(); std::cout << logger << "[O_GREATER_C] [" << i_val_1 << "] > [" << i_val_2 << "] -> " << (i_val_1 > i_val_2) << "\n"; push_i(i_val_1 > i_val_2); ++it; break; case 25: // O_GREATER_D d_val_1 = pop_d(); d_val_2 = pop_d(); std::cout << logger << "[O_GREATER_D] [" << d_val_1 << "] > [" << d_val_2 << "] -> " << (d_val_1 > d_val_2) << "\n"; push_i(d_val_1 > d_val_2); ++it; break; case 26: // O_GREATER_I i_val_1 = pop_i(); i_val_2 = pop_i(); std::cout << logger << "[O_GREATER_I] [" << i_val_1 << "] > [" << i_val_2 << "] -> " << (i_val_1 > i_val_2) << "\n"; push_i(i_val_1 > i_val_2); ++it; break; case 27: // O_GREATEREQ_C i_val_1 = pop_c(); i_val_2 = pop_c(); std::cout << logger << "[O_GREATEREQ_C] [" << i_val_1 << "] >= [" << i_val_2 << "] -> " << (i_val_1 >= i_val_2) << "\n"; push_i(i_val_1 >= i_val_2); ++it; break; case 28: // O_GREATEREQ_D d_val_1 = pop_d(); d_val_2 = pop_d(); std::cout << logger << "[O_GREATEREQ_D] [" << d_val_1 << "] >= [" << d_val_2 << "] -> " << (d_val_1 >= d_val_2) << "\n"; push_i(d_val_1 >= d_val_2); ++it; break; case 29: // O_GREATEREQ_I i_val_1 = pop_i(); i_val_2 = pop_i(); std::cout << logger << "[O_GREATEREQ_I] [" << i_val_1 << "] >= [" << i_val_2 << "] -> " << (i_val_1 >= i_val_2) << "\n"; push_i(i_val_1 >= i_val_2); ++it; break; case 30: // O_INSERT if ( (*it).args.size() == 2 && Instruction::variant_to_type((*it).args[0]) == "long" && Instruction::variant_to_type((*it).args[1]) == "long" ) { i_val_1 = std::get<long> ((*it).args[0]); // Destination i_val_2 = std::get<long> ((*it).args[1]); // No. of bytes std::cout << logger << "[O_INSERT]/t" << i_val_1 << ", " << i_val_2 << "\n"; if ( stack_ptr + i_val_2 > stack_after) { std::cout << logger << "[O_INSERT] OUT of stack!\n"; exit(2); } // make room memmove(stack_ptr - i_val_1 + i_val_2, stack_ptr - i_val_1, i_val_1); memmove(stack_ptr - i_val_1, stack_ptr + i_val_2, i_val_2); stack_ptr += i_val_2; ++it; } else { std::cout << logger << "[O_INSERT] Wrong structure calling!\n"; exit(2); } break; case 31: // O_JF_A if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "void" ) { a_val = static_cast<char *> (pop_a()); auto val = std::get<void *> ((*it).args[0]); std::cout << logger << "[O_JF_A] " << val << " (" << a_val << ")\n"; auto itr = std::find(instr_list.instr_list.begin(), instr_list.instr_list.end(), (*static_cast<Instruction *> (val))); if ( itr != instr_list.instr_list.end()) { it = !a_val ? itr : ++it; } else { std::cout << logger << "[O_JF_A] Given Instruction is not valid!\n"; exit(2); } } else { std::cout << logger << "[O_JF_A] Wrong structure calling!\n"; exit(2); } break; case 32: // O_JF_C if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "void" ) { i_val_1 = pop_c(); auto val = std::get<void *> ((*it).args[0]); std::cout << logger << "[O_JF_C] " << val << " (" << i_val_1 << ")\n"; auto itr = std::find(instr_list.instr_list.begin(), instr_list.instr_list.end(), (*static_cast<Instruction *> (val))); if ( itr != instr_list.instr_list.end()) { it = !i_val_1 ? itr : ++it; } else { std::cout << logger << "[O_JF_C] Given Instruction is not valid!\n"; exit(2); } } else { std::cout << logger << "[O_JF_C] Wrong structure calling!\n"; exit(2); } break; case 33: // O_JF_D if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "void" ) { d_val_1 = pop_d(); auto val = std::get<void *> ((*it).args[0]); std::cout << logger << "[O_JF_D] " << val << " (" << d_val_1 << ")\n"; auto itr = std::find(instr_list.instr_list.begin(), instr_list.instr_list.end(), (*static_cast<Instruction *> (val))); if ( itr != instr_list.instr_list.end()) { it = !d_val_1 ? itr : ++it; } else { std::cout << logger << "[O_JF_D] Given Instruction is not valid!\n"; exit(2); } } else { std::cout << logger << "[O_JF_D] Wrong structure calling!\n"; exit(2); } break; case 34: // O_JF_I if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "void" ) { i_val_1 = pop_i(); auto val = std::get<void *> ((*it).args[0]); std::cout << logger << "[O_JF_I] " << val << " (" << i_val_1 << ")\n"; auto itr = std::find(instr_list.instr_list.begin(), instr_list.instr_list.end(), (*static_cast<Instruction *> (val))); if ( itr != instr_list.instr_list.end()) { it = !i_val_1 ? itr : ++it; } else { std::cout << logger << "[O_JF_I] Given Instruction is not valid!\n"; exit(2); } } else { std::cout << logger << "[O_JF_I] Wrong structure calling!\n"; exit(2); } break; case 35: // O_JMP if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "void" ) { auto val = std::get<void *> ((*it).args[0]); std::cout << logger << "[O_JMP] " << val << "\n"; auto itr = std::find(instr_list.instr_list.begin(), instr_list.instr_list.end(), (*static_cast<Instruction *> (val))); if ( itr != instr_list.instr_list.end()) { it = itr; } else { std::cout << logger << "[O_JMP] Given Instruction is not valid!\n"; exit(2); } } else { std::cout << logger << "[O_JMP] Wrong structure calling!\n"; exit(2); } break; case 36: // O_JT_A if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "void" ) { a_val = static_cast<char *> (pop_a()); auto val = std::get<void *> ((*it).args[0]); std::cout << logger << "[O_JT_A] " << val << " (" << a_val << ")\n"; auto itr = std::find(instr_list.instr_list.begin(), instr_list.instr_list.end(), (*static_cast<Instruction *> (val))); if ( itr != instr_list.instr_list.end()) { it = a_val ? itr : ++it; } else { std::cout << logger << "[O_JT_A] Given Instruction is not valid!\n"; exit(2); } } else { std::cout << logger << "[O_JT_A] Wrong structure calling!\n"; exit(2); } break; case 37: // O_JT_C if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "void" ) { i_val_1 = pop_c(); auto val = std::get<void *> ((*it).args[0]); std::cout << logger << "[O_JT_C] " << val << " (" << i_val_1 << ")\n"; auto itr = std::find(instr_list.instr_list.begin(), instr_list.instr_list.end(), (*static_cast<Instruction *> (val))); if ( itr != instr_list.instr_list.end()) { it = i_val_1 ? itr : ++it; } else { std::cout << logger << "[O_JT_C] Given Instruction is not valid!\n"; exit(2); } } else { std::cout << logger << "[O_JT_C] Wrong structure calling!\n"; exit(2); } break; case 38: // O_JT_D if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "void" ) { d_val_1 = pop_d(); auto val = std::get<void *> ((*it).args[0]); std::cout << logger << "[O_JT_D] " << val << " (" << d_val_1 << ")\n"; auto itr = std::find(instr_list.instr_list.begin(), instr_list.instr_list.end(), (*static_cast<Instruction *> (val))); if ( itr != instr_list.instr_list.end()) { it = d_val_1 ? itr : ++it; } else { std::cout << logger << "[O_JT_D] Given Instruction is not valid!\n"; exit(2); } } else { std::cout << logger << "[O_JT_D] Wrong structure calling!\n"; exit(2); } break; case 39: // O_JT_I if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "void" ) { i_val_1 = pop_i(); auto val = std::get<void *> ((*it).args[0]); std::cout << logger << "[O_JT_I] " << val << " (" << i_val_1 << ")\n"; auto itr = std::find(instr_list.instr_list.begin(), instr_list.instr_list.end(), (*static_cast<Instruction *> (val))); if ( itr != instr_list.instr_list.end()) { it = i_val_1 ? itr : ++it; } else { std::cout << logger << "[O_JT_I] Given Instruction is not valid!\n"; exit(2); } } else { std::cout << logger << "[O_JT_I] Wrong structure calling!\n"; exit(2); } break; case 40: // O_LESS_C i_val_1 = pop_c(); i_val_2 = pop_c(); std::cout << logger << "[O_LESS_C] [" << i_val_1 << "] < [" << i_val_2 << "] -> " << (i_val_1 < i_val_2) << "\n"; push_i(i_val_1 < i_val_2); ++it; break; case 41: // O_LESS_D d_val_1 = pop_d(); d_val_2 = pop_d(); std::cout << logger << "[O_LESS_D] [" << d_val_1 << "] < [" << d_val_2 << "] -> " << (d_val_1 < d_val_2) << "\n"; push_i(d_val_1 < d_val_2); ++it; break; case 42: // O_LESS_I i_val_1 = pop_i(); i_val_2 = pop_i(); std::cout << logger << "[O_LESS_I] [" << i_val_1 << "] < [" << i_val_2 << "] -> " << (i_val_1 < i_val_2) << "\n"; push_i(i_val_1 < i_val_2); ++it; break; case 43: // O_LESSEQ_C i_val_1 = pop_c(); i_val_2 = pop_c(); std::cout << logger << "[O_LESSEQ_C] [" << i_val_1 << "] <= [" << i_val_2 << "] -> " << (i_val_1 <= i_val_2) << "\n"; push_i(i_val_1 <= i_val_2); ++it; break; case 44: // O_LESSEQ_D d_val_1 = pop_d(); d_val_2 = pop_d(); std::cout << logger << "[O_LESSEQ_D] [" << d_val_1 << "] <= [" << d_val_2 << "] -> " << (d_val_1 <= d_val_2) << "\n"; push_i(d_val_1 <= d_val_2); ++it; break; case 45: // O_LESSEQ_I i_val_1 = pop_i(); i_val_2 = pop_i(); std::cout << logger << "[O_LESSEQ_I] [" << i_val_1 << "] <= [" << i_val_2 << "] -> " << (i_val_1 <= i_val_2) << "\n"; push_i(i_val_1 <= i_val_2); ++it; break; case 46: // O_MUL_C i_val_1 = pop_c(); i_val_2 = pop_c(); std::cout << logger << "[O_MUL_C] MUL: " << i_val_1 << " * " << i_val_2 << " -> " << "[" << i_val_1 * i_val_2 << "]\n"; push_c(i_val_1 * i_val_2); ++it; break; case 47: // O_MUL_D d_val_1 = pop_d(); d_val_2 = pop_d(); std::cout << logger << "[O_MUL_D] MUL: " << d_val_1 << " * " << d_val_2 << " -> " << "[" << d_val_1 * d_val_2 << "]\n"; push_c(d_val_1 * d_val_2); ++it; break; case 48: // O_MUL_I i_val_1 = pop_i(); i_val_2 = pop_i(); std::cout << logger << "[O_MUL_I] MUL: " << i_val_1 << " * " << i_val_2 << " -> " << "[" << i_val_1 * i_val_2 << "]\n"; push_c(i_val_1 * i_val_2); ++it; break; case 49: // O_NEG_C i_val_1 = pop_c(); std::cout << logger << "[O_NEG_C] [-" << i_val_1 << "]\n"; push_c(-i_val_1); ++it; break; case 50: // O_NEG_D d_val_1 = pop_d(); std::cout << logger << "[O_NEG_D] [-" << d_val_1 << "]\n"; push_c(-d_val_1); ++it; break; case 51: // O_NEG_I i_val_1 = pop_i(); std::cout << logger << "[O_NEG_I] [-" << i_val_1 << "]\n"; push_i(-i_val_1); ++it; break; case 52: // O_NOP std::cout << logger << "[O_NOP]\n"; ++it; break; case 53: // O_NOT_A a_val = static_cast<char *>(pop_a()); std::cout << logger << "[O_NOT_A] [-" << a_val << "]\n"; push_i(!a_val); ++it; break; case 54: // O_NOT_C i_val_1 = pop_c(); std::cout << logger << "[O_NOT_C] [-" << i_val_1 << "]\n"; push_i(!i_val_1); ++it; break; case 55: // O_NOT_D d_val_1 = pop_d(); std::cout << logger << "[O_NOT_D] [-" << d_val_1 << "]\n"; push_i(!d_val_1); ++it; break; case 56: // O_NOT_I i_val_1 = pop_i(); std::cout << logger << "[O_NOT_I] [-" << i_val_1 << "]\n"; push_i(!i_val_1); ++it; break; case 57: // O_NOTEQ_A a_val = static_cast<char *> (pop_a()); a_val_2 = static_cast<char *> (pop_a()); std::cout << logger << "[O_NOTEQ_A] [" << a_val << "] != [" << a_val_2 << "] -> " << (a_val != a_val_2) << "\n"; push_i(a_val != a_val_2); it++; break; case 58: // O_NOTEQ_C i_val_1 = pop_c(); i_val_2 = pop_c(); std::cout << logger << "[O_NOTEQ_C] [" << i_val_1 << "] != [" << i_val_2 << "] -> " << (i_val_1 != i_val_2) << "\n"; push_i(i_val_1 != i_val_2); it++; break; case 59: // O_NOTEQ_D d_val_1 = pop_d(); d_val_2 = pop_d(); std::cout << logger << "[O_NOTEQ_D] [" << d_val_1 << "] != [" << d_val_2 << "] -> " << (d_val_1 != d_val_2) << "\n"; push_i(d_val_1 != d_val_2); it++; break; case 60: // O_NOTEQ_I i_val_1 = pop_i(); i_val_2 = pop_i(); std::cout << logger << "[O_NOTEQ_I] [" << i_val_1 << "] != [" << i_val_2 << "] -> " << (i_val_1 != i_val_2) << "\n"; push_i(i_val_1 != i_val_2); it++; break; case 61: // O_OFFSET i_val_1 = pop_i(); a_val = static_cast<char *> (pop_a()); std::cout << logger << "[O_OFFSET] " << a_val << " + " << i_val_1 << " -> " << a_val + i_val_1 << "\n"; push_a(a_val + i_val_1); ++it; break; case 62: // O_OR_A a_val = static_cast<char *> (pop_a()); a_val_2 = static_cast<char *> (pop_a()); std::cout << logger << "[O_OR_A] [" << a_val << "] || [" << a_val_2 << "] -> " << (a_val || a_val_2) << "\n"; push_i(a_val || a_val_2); it++; break; case 63: // O_OR_D d_val_1 = pop_d(); d_val_2 = pop_d(); std::cout << logger << "[O_OR_D] [" << d_val_1 << "] || [" << d_val_2 << "] -> " << (d_val_1 || d_val_2) << "\n"; push_i(d_val_1 || d_val_2); it++; break; case 64: // O_OR_I i_val_1 = pop_i(); i_val_2 = pop_i(); std::cout << logger << "[O_OR_I] [" << i_val_1 << "] || [" << i_val_2 << "] -> " << (i_val_1 || i_val_2) << "\n"; push_i(i_val_1 || i_val_2); it++; break; case 65: // O_PUSHFPADDR if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "long" ) { i_val_1 = std::get<long> ((*it).args[0]); std::cout << logger << "[O_PUSHFPADDR] " << i_val_1 << " " << i_val_1 + frame_ptr << "\n"; push_a(frame_ptr + i_val_1); ++it; } else { std::cout << logger << "[O_PUSHFPADDR] Wrong structure calling!\n"; exit(2); } break; case 66: // O_PUSHCT_A if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "void" ) { a_val = static_cast<char * > (std::get<void*> ((*it).args[0])); std::cout << logger << "[O_PUSHCT_A] " << std::hex << a_val << "\n"; push_a(std::get<void*> ((*it).args[0])); ++it; } else { std::cout << logger << "[O_PUSHCT_A] Wrong structure calling!\n"; exit(2); } break; case 67: // O_PUSHCT_C if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "long" ) { i_val_1 = static_cast<char> (std::get<long> ((*it).args[0])); std::cout << logger << "[O_PUSHCT_C] " << std::hex << i_val_1 << "\n"; push_i(std::get<long> ((*it).args[0])); ++it; } else { std::cout << logger << "[O_PUSHCT_C] Wrong structure calling!\n"; exit(2); } break; case 68: // O_PUSHCT_D if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "double" ) { d_val_1 = std::get<double> ((*it).args[0]); std::cout << logger << "[O_PUSHCT_D] " << std::hex << d_val_1 << "\n"; push_i(std::get<double> ((*it).args[0])); ++it; } else { std::cout << logger << "[O_PUSHCT_D] Wrong structure calling!\n"; exit(2); } break; case 69: // O_PUSHCT_I if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "long" ) { i_val_1 = std::get<long> ((*it).args[0]); std::cout << logger << "[O_PUSHCT_I] " << i_val_1 << "\n"; push_i(i_val_1); ++it; } else { std::cout << logger << "[O_PUSHCT_I] Wrong structure calling!\n"; exit(2); } break; break; case 70: // O_RET if ( (*it).args.size() == 2 && Instruction::variant_to_type((*it).args[0]) == "long" && Instruction::variant_to_type((*it).args[1]) == "long" ) { i_val_1 = std::get<long> ((*it).args[0]); // size args i_val_2 = std::get<long> ((*it).args[1]); // sizeof(retType) std::cout << logger << "[O_RET] " << i_val_1 << " " << i_val_2 << "\n"; old_sp = stack_ptr; stack_ptr = frame_ptr; frame_ptr = static_cast<char *> (pop_a()); if ( stack_ptr - i_val_1 < stack ) { std::cout << logger << "[O_RET] Not enough stack!\n"; exit(2); } stack_ptr -= i_val_1; memmove(stack_ptr, old_sp - i_val_2, i_val_2); stack_ptr+= i_val_2; } else { std::cout << logger << "[O_RET] Wrong structure calling!\n"; exit(2); } break; case 71: // O_STORE if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "long" ){ i_val_1 = std::get<long> ((*it).args[0]); if ( stack_ptr - (sizeof(void *) + i_val_1 ) < stack ) { std::cout << logger << "[O_STORE] Not enough stack bytes for SET!\n"; exit(2); } a_val = stack_ptr - sizeof(void *) - i_val_1; std::cout << logger << "[O_STORE] storing " << i_val_1 << " at " << static_cast<void *> (&a_val) << "\n"; memcpy(a_val, stack_ptr - i_val_1, i_val_1); stack_ptr -= sizeof(void *) + i_val_1; // std::cout << logger << "Stack_ptr : " << static_cast<void *> (&stack_ptr) // << " vs " << static_cast<void *> (&stack) << "\n"; ++it; } else { std::cout << logger << "[O_STORE] Wrong structure calling!\n"; exit(2); } break; case 72: // O_SUB_C i_val_1 = pop_c(); i_val_2 = pop_c(); std::cout << logger << "[O_SUB_C] " << i_val_1 << " - " << i_val_2 << " -> " << i_val_1 - i_val_2 << "\n"; push_d(i_val_1 - i_val_2); ++it; break; case 73: // O_SUB_D d_val_1 = pop_d(); d_val_2 = pop_d(); std::cout << logger << "[O_SUB_D] " << d_val_2 << " - " << d_val_1 << " -> " << d_val_2 - d_val_1 << "\n"; push_d(d_val_2 - d_val_1); ++it; break; case 74: // O_SUB_I i_val_1 = pop_i(); i_val_2 = pop_i(); std::cout << logger << "[O_SUB_I] " << i_val_1 << " - " << i_val_2 << " -> " << i_val_1 - i_val_2 << "\n"; push_d(i_val_1 - i_val_2); ++it; break; case 75: // O_LOAD if ( (*it).args.size() == 1 && Instruction::variant_to_type((*it).args[0]) == "long" ) { i_val_1 = std::get<long> ((*it).args[0]); a_val = static_cast<char*> (pop_a()); std::cout << logger << "[O_LOAD]\t" << i_val_1 << " at " << static_cast<void *> (&a_val) << "\n"; if ( stack_ptr + i_val_1 > stack_after ) { std::cout << logger << "[O_LOAD] Out of stack!\n"; exit(2); } memcpy(stack_ptr, a_val, i_val_1); // loading from address a_val [i_val_1] bytes on stack stack_ptr += i_val_1; it++; } else { std::cout << logger << "[O_LOAD] Wrong structure calling!\n"; exit(2); } break; case 76: // O_AND_A a_val = static_cast<char *> (pop_a()); a_val_2 = static_cast<char*> (pop_a()); std::cout << logger << "[O_AND_A] Adding: " << a_val << " + " << a_val_2 << " -> " << "[" << (a_val && a_val_2) << "]\n"; push_i(a_val && a_val_2); ++it; break; case 77: // O_OR_C i_val_1 = pop_c(); i_val_2 = pop_c(); std::cout << logger << "[O_OR_C] [" << i_val_1 << "] || [" << i_val_2 << "] -> " << (i_val_1 || i_val_2) << "\n"; push_i(i_val_1 || i_val_2); it++; break; default: std::cout << logger << "[O_NONE] No instructionm with the given code!\n"; exit(2); } } }
45.083514
139
0.371713
Suru-09
547273f87b4a527486b33e099b397f92371445ba
901
cpp
C++
Code/AutomatedTests/HeaderBlockTokenTest.cpp
ProgramMax/maxGif
de509a1512dd56015c7f044bfc177ae662e57694
[ "BSD-3-Clause" ]
1
2016-11-13T17:50:10.000Z
2016-11-13T17:50:10.000Z
Code/AutomatedTests/HeaderBlockTokenTest.cpp
ProgramMax/maxGif
de509a1512dd56015c7f044bfc177ae662e57694
[ "BSD-3-Clause" ]
23
2016-11-13T18:41:42.000Z
2017-12-27T13:58:07.000Z
Code/AutomatedTests/HeaderBlockTokenTest.cpp
ProgramMax/maxGif
de509a1512dd56015c7f044bfc177ae662e57694
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2016, The maxGif Contributors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <max/Testing/TestSuite.hpp> #include <maxGif/Parsing/Tokens.hpp> #include <vector> int main() { auto TestSuite = max::Testing::TestSuite( "HeaderBlockToken" ); TestSuite.AddTest( max::Testing::Test( "constructor sets the start offset", []( max::Testing::Test & CurrentTest ) { auto const StartOffset = size_t{ 0 }; auto const TestObject = maxGif::Parsing::HeaderBlockToken{ StartOffset }; CurrentTest.MAX_TESTING_ASSERT( TestObject.StartOffset == StartOffset ); } )); TestSuite.AddTest( max::Testing::Test( "size is 6", []( max::Testing::Test & CurrentTest ) { CurrentTest.MAX_TESTING_ASSERT( maxGif::Parsing::HeaderBlockToken::SizeInBytes() == 6 ); } )); TestSuite.RunTests(); return 0; }
30.033333
91
0.711432
ProgramMax
5479ccd289b973d5ace94630955cc67960d6fddd
242
cpp
C++
etc/config/src/EXPORT_KEYWORD.cpp
Hower91/Apache-C-Standard-Library-4.2.x
4d9011d60dbb38b3ff80dcfe54dccd3a4647d9d3
[ "Apache-2.0" ]
null
null
null
etc/config/src/EXPORT_KEYWORD.cpp
Hower91/Apache-C-Standard-Library-4.2.x
4d9011d60dbb38b3ff80dcfe54dccd3a4647d9d3
[ "Apache-2.0" ]
null
null
null
etc/config/src/EXPORT_KEYWORD.cpp
Hower91/Apache-C-Standard-Library-4.2.x
4d9011d60dbb38b3ff80dcfe54dccd3a4647d9d3
[ "Apache-2.0" ]
null
null
null
// checking for the export keyword // NOTE: test EXPORT.cpp links with EXPORT_KEYOWRD.o and expects // to find a definition of the function template below there export template <class T> T exported_function_template (T t) { return t; }
20.166667
64
0.752066
Hower91
548055c5c726bfd5487e71523b054ca6fe96ffb4
768
hpp
C++
libs/gui/impl/include/sge/gui/impl/style/spacing.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/gui/impl/include/sge/gui/impl/style/spacing.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/gui/impl/include/sge/gui/impl/style/spacing.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_GUI_IMPL_STYLE_SPACING_HPP_INCLUDED #define SGE_GUI_IMPL_STYLE_SPACING_HPP_INCLUDED #include <sge/gui/impl/style/inner_border.hpp> #include <sge/gui/impl/style/outer_border.hpp> #include <sge/rucksack/scalar.hpp> #include <fcppt/config/external_begin.hpp> #include <type_traits> #include <fcppt/config/external_end.hpp> namespace sge::gui::impl::style { using spacing = std::integral_constant< sge::rucksack::scalar, (sge::gui::impl::style::inner_border::value + sge::gui::impl::style::outer_border::value) * 2>; } #endif
29.538462
99
0.740885
cpreh
548a79c421b09c5cdcc9aa9c505d904cc625f10e
2,795
cpp
C++
OneCodeTeam/How to create a SDI with Multi-Views in MFC/[C++]-How to create a SDI with Multi-Views in MFC/C++/MFCSDIAppln/MFCSDIApplnView.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
2
2022-01-21T01:40:58.000Z
2022-01-21T01:41:10.000Z
OneCodeTeam/How to create a SDI with Multi-Views in MFC/[C++]-How to create a SDI with Multi-Views in MFC/C++/MFCSDIAppln/MFCSDIApplnView.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
1
2022-03-15T04:21:41.000Z
2022-03-15T04:21:41.000Z
OneCodeTeam/How to create a SDI with Multi-Views in MFC/[C++]-How to create a SDI with Multi-Views in MFC/C++/MFCSDIAppln/MFCSDIApplnView.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
null
null
null
/****************************** Module Header ******************************\ * Module Name: MFCSDIApplnView.cpp * Project: MFCSDIAppln * Copyright (c) Microsoft Corporation. * * This is Main View. * * This source is subject to the Microsoft Public License. * See http://www.microsoft.com/en-us/openness/licenses.aspx#MPL * All other rights reserved. * * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. \***************************************************************************/ #include "stdafx.h" // SHARED_HANDLERS can be defined in an ATL project implementing preview, thumbnail // and search filter handlers and allows sharing of document code with that project. #ifndef SHARED_HANDLERS #include "MFCSDIAppln.h" #endif #include "MFCSDIApplnDoc.h" #include "MFCSDIApplnView.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CMFCSDIApplnView IMPLEMENT_DYNCREATE(CMFCSDIApplnView, CView) BEGIN_MESSAGE_MAP(CMFCSDIApplnView, CView) // Standard printing commands ON_COMMAND(ID_FILE_PRINT, &CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_DIRECT, &CView::OnFilePrint) ON_COMMAND(ID_FILE_PRINT_PREVIEW, &CView::OnFilePrintPreview) END_MESSAGE_MAP() // CMFCSDIApplnView construction/destruction CMFCSDIApplnView::CMFCSDIApplnView() { // TODO: add construction code here } CMFCSDIApplnView::~CMFCSDIApplnView() { } BOOL CMFCSDIApplnView::PreCreateWindow(CREATESTRUCT& cs) { // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs return CView::PreCreateWindow(cs); } // CMFCSDIApplnView drawing void CMFCSDIApplnView::OnDraw(CDC* pDC) { CMFCSDIApplnDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); if (!pDoc) return; CString str = _T("Displaying MainView"); pDC->DrawText(str, CRect(100, 100, 500, 500), DT_CENTER); } // CMFCSDIApplnView printing BOOL CMFCSDIApplnView::OnPreparePrinting(CPrintInfo* pInfo) { // default preparation return DoPreparePrinting(pInfo); } void CMFCSDIApplnView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add extra initialization before printing } void CMFCSDIApplnView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/) { // TODO: add cleanup after printing } // CMFCSDIApplnView diagnostics #ifdef _DEBUG void CMFCSDIApplnView::AssertValid() const { CView::AssertValid(); } void CMFCSDIApplnView::Dump(CDumpContext& dc) const { CView::Dump(dc); } CMFCSDIApplnDoc* CMFCSDIApplnView::GetDocument() const // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CMFCSDIApplnDoc))); return (CMFCSDIApplnDoc*)m_pDocument; } #endif //_DEBUG // CMFCSDIApplnView message handlers
23.487395
85
0.729159
zzgchina888
548dd46e2289357b2682171fe2f3d589bbdefe1c
1,295
cpp
C++
Deitel/Chapter12/exercises/12.09/ex_1209.cpp
SebastianTirado/Cpp-Learning-Archive
fb83379d0cc3f9b2390cef00119464ec946753f4
[ "MIT" ]
19
2019-09-15T12:23:51.000Z
2020-06-18T08:31:26.000Z
Deitel/Chapter12/exercises/12.09/ex_1209.cpp
eirichan/CppLearingArchive
07a4baf63f0765d41eb0cc6d32a4c9d2ae1d5bac
[ "MIT" ]
15
2021-12-07T06:46:03.000Z
2022-01-31T07:55:32.000Z
Deitel/Chapter12/exercises/12.09/ex_1209.cpp
eirichan/CppLearingArchive
07a4baf63f0765d41eb0cc6d32a4c9d2ae1d5bac
[ "MIT" ]
13
2019-06-29T02:58:27.000Z
2020-05-07T08:52:22.000Z
/* * ===================================================================================== * * Filename: * * Description: * * Version: 1.0 * Created: Thanks to github you know it * Revision: none * Compiler: g++ * * Author: Mahmut Erdem ÖZGEN m.erdemozgen@gmail.com * * * ===================================================================================== */ #include <iostream> #include "OvernightPackage.hpp" #include "TwoDayPackage.hpp" #include "Utility.hpp" int main(int argc, const char *argv[]) { OvernightPackage op(Person("Bob", "Bobson", "12 Bob Street", "BobVille", "Bobzone", "B0B-50N"), Person("Sue", "Sueson", "12 Sue Street", "SueVille", "Suezona", "5U3-50N"), 12.0f, 5.0f, 1.0f); TwoDayPackage tdp( Person("Send", "er", "Sender Street", "Send Place", "Snd", "53N-D3R"), Person("Reci", "pient", "Receipient Lane", "Recip Town", "Rpt", "R3C-3NT"), 12.0f, 5.0f, 1.0f); std::cout << "Overnight Package:\n"; op.printDetails(); std::cout << "\n\nTwo day Package:\n"; tdp.printDetails(); std::cout << std::endl; return 0; }
27.553191
88
0.433977
SebastianTirado
5490715eab05b16a29adef8834ad61db35612d76
635
cpp
C++
VC2010Samples/ComTypeLibfor7/dcom/atldraw/preatldr.cpp
alonmm/VCSamples
6aff0b4902f5027164d593540fcaa6601a0407c3
[ "MIT" ]
300
2019-05-09T05:32:33.000Z
2022-03-31T20:23:24.000Z
VC2010Samples/ComTypeLibfor7/dcom/atldraw/preatldr.cpp
JaydenChou/VCSamples
9e1d4475555b76a17a3568369867f1d7b6cc6126
[ "MIT" ]
9
2016-09-19T18:44:26.000Z
2018-10-26T10:20:05.000Z
VC2010Samples/ComTypeLibfor7/dcom/atldraw/preatldr.cpp
JaydenChou/VCSamples
9e1d4475555b76a17a3568369867f1d7b6cc6126
[ "MIT" ]
633
2019-05-08T07:34:12.000Z
2022-03-30T04:38:28.000Z
// preatldr.cpp : source file that includes just the standard includes // ATLDraw.pch will be the pre-compiled header // preatldr.obj will contain the pre-compiled type information #include "preatldr.h" LONG g_cObjCnt; void dump_com_error(_com_error &e) { _tprintf(_T("Oops - hit an error!\n")); _tprintf(_T("\a\tCode = %08lx\n"), e.Error()); _tprintf(_T("\a\tCode meaning = %s\n"), e.ErrorMessage()); _bstr_t bstrSource(e.Source()); _bstr_t bstrDescription(e.Description()); _tprintf(_T("\a\tSource = %s\n"), (LPCTSTR) bstrSource); _tprintf(_T("\a\tDescription = %s\n"), (LPCTSTR) bstrDescription); }
33.421053
70
0.68189
alonmm
549382a8825cf8cd8e0f2d62c6c0c15a4542fbcc
318
inl
C++
node_modules/lzz-gyp/lzz-source/smtc_CreateDtorBaseName.inl
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
3
2019-09-18T16:44:33.000Z
2021-03-29T13:45:27.000Z
node_modules/lzz-gyp/lzz-source/smtc_CreateDtorBaseName.inl
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
null
null
null
node_modules/lzz-gyp/lzz-source/smtc_CreateDtorBaseName.inl
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
2
2019-03-29T01:06:38.000Z
2019-09-18T16:44:34.000Z
// smtc_CreateDtorBaseName.inl // #ifdef LZZ_ENABLE_INLINE #define LZZ_INLINE inline #else #define LZZ_INLINE #endif namespace smtc { LZZ_INLINE BaseNamePtr createDtorBaseName (util::Loc const & loc, util::Ident const & ident) { return createDtorBaseName (loc, util::Ident (), ident); } } #undef LZZ_INLINE
18.705882
94
0.745283
SuperDizor
5499fe18223882ee1792d4083a10b2eac2be9b94
3,521
hpp
C++
argholder.hpp
degarashi/spinner
6c0d5dbdcde962a36de28cdc867478e2a715b689
[ "MIT" ]
null
null
null
argholder.hpp
degarashi/spinner
6c0d5dbdcde962a36de28cdc867478e2a715b689
[ "MIT" ]
null
null
null
argholder.hpp
degarashi/spinner
6c0d5dbdcde962a36de28cdc867478e2a715b689
[ "MIT" ]
null
null
null
#pragma once #include <type_traits> #include <cassert> namespace spn { struct none_t{}; //! rvalue-reference wrapper template <class T> struct _RRef { T& value; _RRef(T& v): value(v) {} _RRef(const _RRef& r): value(r.value) {} int get() { return 0; } operator T& () { return value; } }; template <class T> struct _RRef<T&&> { T&& value; _RRef(const _RRef& r): value(std::move(r.value)) {} _RRef(T&& v): value(std::forward<T>(v)) {} operator T&& () { return std::move(value); } int get() { return 1; } }; template <class T> auto RRef(T&& t) -> _RRef<decltype(std::forward<T>(t))> { return _RRef<T&&>(std::forward<T>(t)); } template <class... Ts> struct ArgHolder { ArgHolder() = default; ArgHolder(ArgHolder&& /*a*/) {} template <class CB, class... TsA> auto reverse(CB cb, TsA&&... tsa) -> decltype(cb(std::forward<TsA>(tsa)...)) { return cb(std::forward<TsA>(tsa)...); } template <class CB, class... TsA> auto inorder(CB cb, TsA&&... tsa) -> decltype(cb(std::forward<TsA>(tsa)...)) { return cb(std::forward<TsA>(tsa)...); } }; //! 引数を一旦とっておいて後で関数に渡す /*! not reference, not pointerな型はrvalue_referenceで渡されるので2回以上呼べない */ template <class T0, class... Ts> struct ArgHolder<T0,Ts...> { T0 _value; using Lower = ArgHolder<Ts...>; Lower _other; // 2度呼び出しチェック #ifdef DEBUG bool _bCall = false; void _check() { if(_bCall) assert(!"Invalid ArgHolder call (called twice)"); _bCall = true; } #else void _check() {} #endif template <class T2> ArgHolder(ArgHolder<T2,Ts...>&& a): _value(std::move(a._value)), _other(std::move(a._other)) #ifdef DEBUG , _bCall(a._bCall) #endif {} template <class T0A, class... TsA> ArgHolder(T0A&& t0, TsA&&... tsa): _value(std::forward<T0A>(t0)), _other(std::forward<TsA>(tsa)...) {} // T0がnot reference, not pointerな時はrvalue referenceで渡す template <class CB, class... TsA, class TT0 = T0, class = typename std::enable_if<std::is_object<TT0>::value>::type> auto reverse(CB cb, TsA&&... tsa) -> decltype(_other.reverse(cb, std::move(_value), std::forward<TsA>(tsa)...)) { _check(); return _other.reverse(cb, std::move(_value), std::forward<TsA>(tsa)...); } // それ以外はそのまま渡す template <class CB, class... TsA, class TT0 = T0, class = typename std::enable_if<!std::is_object<TT0>::value>::type> auto reverse(CB cb, TsA&&... tsa) -> decltype(_other.reverse(cb, _value, std::forward<TsA>(tsa)...)) { return _other.reverse(cb, _value, std::forward<TsA>(tsa)...); } // T0がnot reference, not pointerな時はrvalue referenceで渡す template <class CB, class... TsA, class TT0 = T0, class = typename std::enable_if<std::is_object<TT0>::value>::type> auto inorder(CB cb, TsA&&... tsa) -> decltype(_other.inorder(cb, std::forward<TsA>(tsa)..., std::move(_value))) { _check(); return _other.inorder(cb, std::forward<TsA>(tsa)..., std::move(_value)); } // それ以外はそのまま渡す template <class CB, class... TsA, class TT0 = T0, class = typename std::enable_if<!std::is_object<TT0>::value>::type> auto inorder(CB cb, TsA&&... tsa) -> decltype(_other.inorder(cb, std::forward<TsA>(tsa)..., _value)) { return _other.inorder(cb, std::forward<TsA>(tsa)..., _value); } }; //! 引数の順序を逆にしてコール template <class CB, class... Ts> auto ReversedArg(CB cb, Ts&&... ts) -> decltype(ArgHolder<decltype(std::forward<Ts>(ts))...>(std::forward<Ts>(ts)...).reverse(cb)) { return ArgHolder<decltype(std::forward<Ts>(ts))...>(std::forward<Ts>(ts)...).reverse(cb); } }
33.216981
133
0.628515
degarashi
549b05c7f97acd0d48578db2fee40efd3401dc63
5,660
cpp
C++
csl/cslbase/utf8check.cpp
arthurcnorman/general
5e8fef0cc7999fa8ab75d8fdf79ad5488047282b
[ "BSD-2-Clause" ]
null
null
null
csl/cslbase/utf8check.cpp
arthurcnorman/general
5e8fef0cc7999fa8ab75d8fdf79ad5488047282b
[ "BSD-2-Clause" ]
null
null
null
csl/cslbase/utf8check.cpp
arthurcnorman/general
5e8fef0cc7999fa8ab75d8fdf79ad5488047282b
[ "BSD-2-Clause" ]
null
null
null
// utfcheck.cpp Copyright (C) 2016-2020 Codemist // // This is a pretty silly program! It looks at Unicode characters and tests // when case-folding can change the number of utf-8 bytes needed to encode // them. At least in the default locales I have set up on my own Mac and // Linux systems there is never a change of encoded length, but on Windows // there sometimes is. For instance towlower when applied to a capital letter // "I" with a dot over it gives back a simple lower case "i". A consequence // of this is of course that folding case backwards and forwards can be // lossy. The code here lists the cases I came across on my Windows // system when running under cygwin. A windows version compiled using // i686-w64-mingw32-gcc seems to behave like Linux with no discrepancies // shown. // // There is a real prospect that the concept of "case" and folding will be // locale sensitive and so running this in different locales may be // instructive. // /************************************************************************** * Copyright (C) 2020, Codemist. A C Norman * * * * 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 relevant * * 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. * * * * 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 OWNERS 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. * *************************************************************************/ // $Id: utf8check.cpp 5433 2020-10-15 21:09:02Z arthurcnorman $ #include <cstdio> #include <cwchar> #include <cctype> #include <cwctype> int encode(char *s, int c) { char *s1 = s; if (c <= 0x7f) *s++ = c; else if (c <= 0x7ff) { *s++ = 0xc0 + ((c>>6) & 0x1f); *s++ = 0x80 + (c & 0x3f); } else if (c <= 0xffff) { *s++ = 0xe0 + ((c>>12) & 0x0f); *s++ = 0x80 + ((c>>6) & 0x3f); *s++ = 0x80 + (c & 0x3f); } else { *s++ = 0xf0 + ((c>>16) & 0x07); *s++ = 0x80 + ((c>>12) & 0x3f); *s++ = 0x80 + ((c>>6) & 0x3f); *s++ = 0x80 + (c & 0x3f); } *s = 0; return (s - s1); } int main(int argc, char *argv[]) { int c1, c2, c3, n1, n2, n3, status, flag; char s1[8], s2[8], s3[8]; std::printf(" base upper lower\n"); for (c1 = 0; c1<=0xffff; c1++) { // Skip the surrogate range if (0xd800 <= c1 && c1 <= 0xdfff) continue; c2 = std::towupper(c1); c3 = std::towlower(c1); n1 = encode(s1, c1); n2 = encode(s2, c2); n3 = encode(s3, c3); flag = 1; switch (c1) { // Here are cases I know are sometimes at issue... // about them! case 0x0130: // LATIN CAPITAL I WITH DOT case 0x0131: // LATIN SMALL LETTER DOTLESS I case 0x017f: // LATIN SMALL LETTER LONG S case 0x023a: // LATIN CAPITAL A WITH STROKE case 0x023e: case 0x023f: case 0x0240: case 0x0250: case 0x0251: case 0x0252: case 0x026b: case 0x0271: case 0x027d: case 0x1e9e: case 0x1fbe: case 0x2126: case 0x212a: case 0x212b: case 0x2c62: case 0x2c64: case 0x2c65: case 0x2c66: case 0x2c6d: case 0x2c6e: case 0x2c6f: case 0x2c70: // LATIN CAPITRAL LETTER TURNED ALPHA case 0x2c7e: // LATIN CAPITAL S WITH SWASH TAIL case 0x2c7f: // LATIN CAPITAL Z WITH SWASH TAIL flag = 0; default: break; } status = (n1 == n2 && n1 == n3); // are utf-8 lengths unchanged? if (status && flag) continue; std::printf("%#.4x(%d) %#.4x(%d) %#.4x(%d) %s %s %s %s\n", c1, n1, c2, n2, c3, n3, (status ? "OK " : "bad"), s1, s2, s3); } return 0; } // end of utf8check.cpp
40.428571
82
0.514664
arthurcnorman
549b3ed789af7653d7eadacb42cd9ff98e5605be
4,034
hpp
C++
rmvmath/matrix/affinematrix3x3/operator/TAffineMatrix3x3_operator_mul.hpp
vitali-kurlovich/RMMath
a982b89e5db08e9cd16cb08e92839a315b6198dc
[ "MIT" ]
null
null
null
rmvmath/matrix/affinematrix3x3/operator/TAffineMatrix3x3_operator_mul.hpp
vitali-kurlovich/RMMath
a982b89e5db08e9cd16cb08e92839a315b6198dc
[ "MIT" ]
null
null
null
rmvmath/matrix/affinematrix3x3/operator/TAffineMatrix3x3_operator_mul.hpp
vitali-kurlovich/RMMath
a982b89e5db08e9cd16cb08e92839a315b6198dc
[ "MIT" ]
null
null
null
// // Created by Vitali Kurlovich on 1/13/16. // #ifndef RMVECTORMATH_TAFFINEMATRIX3X3_OPERATOR_MUL_HPP #define RMVECTORMATH_TAFFINEMATRIX3X3_OPERATOR_MUL_HPP #include "../TAffineMatrix3x3_def.hpp" #include "../func/TAffineMatrix3x3_func_mul.hpp" #include "../func/TAffineMatrix3x3_func_mulvec.hpp" namespace rmmath { namespace matrix { // Mul template<typename T> inline TAffineMatrix3x3 <T> operator*(const TAffineMatrix3x3 <T> &a, const TAffineMatrix3x3 <T> &b) { return mul(a, b); } template<typename T> inline TMatrix3x4 <T> operator*(const TAffineMatrix3x3 <T> &a, const TMatrix3x4 <T> &b) { return mul(a, b); } template<typename T> inline TMatrix4x3 <T> operator*(const TMatrix4x3 <T> &a, const TAffineMatrix3x3 <T> &b) { return mul(a, b); } template<typename T> inline TMatrix3x3 <T> operator*(const TAffineMatrix3x3 <T> &a, const TMatrix3x3 <T> &b) { return mul(a, b); } template<typename T> inline TMatrix3x3 <T> operator*(const TMatrix3x3 <T> &a, const TAffineMatrix3x3 <T> &b) { return mul(a, b); } template<typename T> inline TMatrix3x2 <T> operator*(const TAffineMatrix3x3 <T> &a, const TMatrix3x2 <T> &b) { return mul(a, b); } template<typename T> inline TMatrix2x3 <T> operator*(const TMatrix2x3 <T> &a, const TAffineMatrix3x3 <T> &b) { return mul(a, b); } template<typename T> inline TMatrix3x1 <T> operator*(const TAffineMatrix3x3 <T> &a, const TMatrix3x1 <T> &b) { return mul(a, b); } template<typename T> inline TMatrix1x3 <T> operator*(const TMatrix1x3 <T> &a, const TAffineMatrix3x3 <T> &b) { return mul(a, b); } template<typename T> inline TAffineMatrix3x3 <T> &operator*=(TAffineMatrix3x3 <T> &a, const TAffineMatrix3x3 <T> &b) { ___unsafe::_mul(a, b); return a; } template<typename T> inline TMatrix4x3 <T> &operator*=(TMatrix4x3 <T> &a, const TAffineMatrix3x3 <T> &b) { ___unsafe::_mul(a, b); return a; } template<typename T> inline TMatrix3x3 <T> &operator*=(TMatrix3x3 <T> &a, const TAffineMatrix3x3 <T> &b) { ___unsafe::_mul(a, b); return a; } template<typename T> inline TMatrix2x3 <T> &operator*=(TMatrix2x3 <T> &a, const TAffineMatrix3x3 <T> &b) { ___unsafe::_mul(a, b); return a; } template<typename T> inline TMatrix1x3 <T> &operator*=(TMatrix1x3 <T> &a, const TAffineMatrix3x3 <T> &b) { ___unsafe::_mul(a, b); return a; } } template<typename T> inline vector::TVector3 <T> operator * (const matrix::TAffineMatrix3x3 <T> &a, const vector::TVector3<T> &b) { return mul(a, b); } template<typename T> inline vector::TVector3 <T> operator * (const vector::TVector3<T> &a, const matrix::TAffineMatrix3x3 <T> &b) { return mul(a, b); } template<typename T> inline vector::TVector3 <T> &operator *= (vector::TVector3 <T> &a, const matrix::TAffineMatrix3x3 <T> &b) { ___unsafe::_mul(a,b); return a; } template<typename T> inline vector::TVector3 <T> operator * (const matrix::TAffineMatrix3x3 <T> &a, const vector::TAffineVector3<T> &b) { return mul(a, b); } template<typename T> inline vector::TAffineVector3 <T> operator * (const vector::TAffineVector3<T> &a, const matrix::TAffineMatrix3x3 <T> &b) { return mul(a, b); } template<typename T> inline vector::TAffineVector3 <T> &operator *= (vector::TAffineVector3 <T> &a, const matrix::TAffineMatrix3x3 <T> &b) { ___unsafe::_mul(a,b); return a; } } #endif //RMVECTORMATH_TAFFINEMATRIX3X3_OPERATOR_MUL_HPP
29.021583
126
0.587506
vitali-kurlovich
549f7add891c354e05c87513df8fcd43a6c06037
1,957
cpp
C++
algorithms/graph/kruskals_mst_algorithm.cpp
sureshmangs/Code
de91ffc7ef06812a31464fb40358e2436734574c
[ "MIT" ]
16
2020-06-02T19:22:45.000Z
2022-02-05T10:35:28.000Z
algorithms/graph/kruskals_mst_algorithm.cpp
codezoned/Code
de91ffc7ef06812a31464fb40358e2436734574c
[ "MIT" ]
null
null
null
algorithms/graph/kruskals_mst_algorithm.cpp
codezoned/Code
de91ffc7ef06812a31464fb40358e2436734574c
[ "MIT" ]
2
2020-08-27T17:40:06.000Z
2022-02-05T10:33:52.000Z
#include<bits/stdc++.h> using namespace std; struct Edge { int src, dst, weight; }; class DisjointSet { unordered_map<int, int> parent; public: void makeSet(int V){ // create V disjoint sets (one for each vertex) for(int i = 0; i < V; i++) parent[i] = i; } // Find the root of the set in which element k belongs int Find(int k){ // if k is root if (parent[k] == k) return k; // recur for parent until we find root return Find(parent[k]); } void Union(int a, int b){ // find root of the sets in which elements x and y belongs int x = Find(a); int y = Find(b); parent[x] = y; } }; vector<Edge> Kruskals(vector<Edge> edges, int V){ // stores edges present in MST vector<Edge> MST; // initialize DisjointSet class DisjointSet ds; // create singleton set for each element of universe ds.makeSet(V); // MST contains exactly V-1 edges while (MST.size() != V - 1){ // consider next edge with minimum weight from the graph Edge next_edge = edges.back(); edges.pop_back(); // find root of the sets to which two endpoint // vertices of next_edge belongs int x = ds.Find(next_edge.src); int y = ds.Find(next_edge.dst); // if both endpoints have different parents, they belong to // different connected components and can be included in MST if (x != y) { MST.push_back(next_edge); ds.Union(x, y); } } return MST; } bool comp(Edge a, Edge b){ return (a.weight > b.weight); } int main(){ vector<Edge> edges {{ 0, 1, 4 }, { 0, 7, 8 }, { 1, 2, 8 }, { 1, 7, 11 }, { 2, 3, 7 }, { 2, 8, 2 }, { 2, 5, 4 }, { 3, 4, 9 }, { 3, 5, 14 }, { 4, 5, 10 }, { 5, 6, 2 }, {6, 7, 1}, {6, 8, 6}, {7, 8, 7} }; // sort edges by increasing weight sort(edges.begin(), edges.end(), comp); int V = 9; // vertices // construct graph vector<Edge> e = Kruskals(edges, V); for (auto &edge: e) cout << "(" << edge.src << ", " << edge.dst << ", " << edge.weight << ")" << endl; return 0; }
20.819149
201
0.599387
sureshmangs
54a1523fda2e54a274eeb38d617b589861a732e0
1,740
cpp
C++
OJ/LeetCode/leetcode/problems/938.cpp
ONGOING-Z/DataStructure
9099393d1c7dfabc3e2939586ea6d1d254631eb2
[ "MIT" ]
null
null
null
OJ/LeetCode/leetcode/problems/938.cpp
ONGOING-Z/DataStructure
9099393d1c7dfabc3e2939586ea6d1d254631eb2
[ "MIT" ]
2
2021-10-31T10:05:45.000Z
2022-02-12T15:17:53.000Z
OJ/LeetCode/leetcode/938.cpp
ONGOING-Z/Learn-Algorithm-and-DataStructure
3a512bd83cc6ed5035ac4550da2f511298b947c0
[ "MIT" ]
null
null
null
#include <stdio.h> #include <vector> using namespace std; /* Leetcode */ /* 题目信息 */ /* *938. Range Sum of BST Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive). The binary search tree is guaranteed to have unique values. Example 1: Input: root = [10,5,15,3,7,null,18], L = 7, R = 15 Output: 32 Example 2: Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10 Output: 23 Note: The number of nodes in the tree is at most 10000. The final answer is guaranteed to be less than 2^31. */ struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} }; /* my solution */ // none /* better solution */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: int sum = 0; void inorder(TreeNode *root, int L, int R) { if (root->left) inorder(root->left, L, R); if (root->val >= L && root->val <= R) sum += root->val; if (root->right) inorder(root->right, L, R); } int rangeSumBST(TreeNode *root, int L, int R) { inorder(root, L, R); return sum; } }; /* 一些总结 */ // 1. 使用的是中序遍历,这样看来并不难。
23.513514
123
0.584483
ONGOING-Z