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
d016f0b1044b6e6dca3486f07fb52fd71862cea4
4,463
hpp
C++
Genesis/include/Genesis/LegacyBackend/LegacyBackend.hpp
JoshuaMasci/Genesis
761060626a92e3df7b860a97209fca341cdda240
[ "MIT" ]
2
2020-01-22T05:57:12.000Z
2020-04-06T01:15:30.000Z
Genesis/include/Genesis/LegacyBackend/LegacyBackend.hpp
JoshuaMasci/Genesis
761060626a92e3df7b860a97209fca341cdda240
[ "MIT" ]
null
null
null
Genesis/include/Genesis/LegacyBackend/LegacyBackend.hpp
JoshuaMasci/Genesis
761060626a92e3df7b860a97209fca341cdda240
[ "MIT" ]
null
null
null
#pragma once #include "Genesis/RenderingBackend/VertexInputDescription.hpp" #include "Genesis/RenderingBackend/RenderingTypes.hpp" #include "Genesis/RenderingBackend/PipelineSettings.hpp" namespace Genesis { enum class DepthFormat { depth_16, depth_24, depth_32, depth_32f, }; enum class TextureWrapMode { Repeat, Mirrored_Repeat, Clamp_Edge, Clamp_Border }; enum class TextureFilterMode { Nearest, Linear }; struct TextureCreateInfo { vector2U size; ImageFormat format; TextureWrapMode wrap_mode; TextureFilterMode filter_mode; }; enum class MultisampleCount { Sample_1 = 1, Sample_2 = 2, Sample_4 = 4, Sample_8 = 8, Sample_16 = 16, Sample_32 = 32, Sample_64 = 64 }; struct FramebufferAttachmentInfo { ImageFormat format; MultisampleCount samples; }; struct FramebufferDepthInfo { DepthFormat format; MultisampleCount samples; }; struct FramebufferCreateInfo { vector2U size; FramebufferAttachmentInfo* attachments; uint32_t attachment_count; FramebufferDepthInfo* depth_attachment; }; typedef void* Framebuffer; typedef void* ShaderProgram; struct FrameStats { uint64_t draw_calls; uint64_t triangles_count; }; class LegacyBackend { public: virtual ~LegacyBackend() {}; virtual vector2U getScreenSize() = 0; virtual void startFrame() = 0; virtual void endFrame() = 0; virtual VertexBuffer createVertexBuffer(void* data, uint64_t data_size, const VertexInputDescriptionCreateInfo& vertex_description) = 0; virtual void destoryVertexBuffer(VertexBuffer buffer) = 0; virtual IndexBuffer createIndexBuffer(void* data, uint64_t data_size, IndexType type) = 0; virtual void destoryIndexBuffer(IndexBuffer buffer) = 0; virtual Texture2D createTexture(const TextureCreateInfo& create_info, void* data) = 0; virtual void destoryTexture(Texture2D texture) = 0; virtual ShaderProgram createShaderProgram(const char* vert_data, uint32_t vert_size, const char* frag_data, uint32_t frag_size) = 0; virtual ShaderProgram createComputeShader(const char* data, uint32_t size) = 0; virtual void destoryShaderProgram(ShaderProgram program) = 0; virtual Framebuffer createFramebuffer(const FramebufferCreateInfo& create_info) = 0; virtual void destoryFramebuffer(Framebuffer framebuffer) = 0; virtual Texture2D getFramebufferColorAttachment(Framebuffer framebuffer, uint32_t index) = 0; virtual Texture2D getFramebufferDepthAttachment(Framebuffer framebuffer) = 0; //Commands virtual void bindFramebuffer(Framebuffer framebuffer) = 0; virtual void clearFramebuffer(bool color, bool depth, vector4F* clear_color = nullptr, float* clear_depth = nullptr) = 0; virtual void setPipelineState(const PipelineSettings& pipeline_state) = 0; virtual void bindShaderProgram(ShaderProgram program) = 0; virtual void setUniform1i(const string& name, const int32_t& value) = 0; virtual void setUniform1u(const string& name, const uint32_t& value) = 0; virtual void setUniform2u(const string& name, const vector2U& value) = 0; virtual void setUniform3u(const string& name, const vector3U& value) = 0; virtual void setUniform4u(const string& name, const vector4U& value) = 0; virtual void setUniform1f(const string& name, const float& value) = 0; virtual void setUniform2f(const string& name, const vector2F& value) = 0; virtual void setUniform3f(const string& name, const vector3F& value) = 0; virtual void setUniform4f(const string& name, const vector4F& value) = 0; virtual void setUniformMat3f(const string& name, const matrix3F& value) = 0; virtual void setUniformMat4f(const string& name, const matrix4F& value) = 0; virtual void setUniformTexture(const string& name, const uint32_t texture_slot, Texture2D value) = 0; virtual void setUniformTextureImage(const string& name, const uint32_t texture_slot, Texture2D value) = 0; virtual void setScissor(vector2I offset, vector2U extent) = 0; virtual void clearScissor() = 0; virtual void bindVertexBuffer(VertexBuffer buffer) = 0; virtual void bindIndexBuffer(IndexBuffer buffer) = 0; virtual void drawIndex(uint32_t index_count, uint32_t index_offset = 0) = 0; virtual void draw(VertexBuffer vertex_buffer, IndexBuffer index_buffer, uint32_t triangle_count) = 0; virtual void dispatchCompute(uint32_t groups_x = 1, uint32_t groups_y = 1, uint32_t groups_z = 1) = 0; //Stats virtual FrameStats getLastFrameStats() = 0; }; }
30.568493
138
0.766077
JoshuaMasci
d01efa51e1883ccdcd82c4418fbaf02af8fea6f1
861
cpp
C++
TouchBarConfig.cpp
RPBCACUEAIIBH/HexaLib-Arduino
0f61cb0c1fd560df5a6395749376e1123ba0a8f5
[ "BSD-3-Clause" ]
3
2020-09-10T18:36:25.000Z
2020-12-18T03:34:08.000Z
TouchBarConfig.cpp
RPBCACUEAIIBH/TouchBar
96378d143a57e1a0e5e32b2577d94ee717c5c6cf
[ "BSD-3-Clause" ]
null
null
null
TouchBarConfig.cpp
RPBCACUEAIIBH/TouchBar
96378d143a57e1a0e5e32b2577d94ee717c5c6cf
[ "BSD-3-Clause" ]
null
null
null
#include "TouchBar.h" /* Configure Private */ void TouchBarConfig::SetFlags (boolean SpringBackFlag, boolean SnapFlag, boolean RampFlag, boolean FlipFlag) { Flags = 0; bitWrite(Flags, 6, SpringBackFlag); bitWrite(Flags, 5, SnapFlag); bitWrite(Flags, 4, RampFlag); bitWrite(Flags, 3, FlipFlag); } void TouchBarConfig::SetFlags (boolean RollOverFlag, boolean FlipFlag) { Flags = 0; bitWrite(Flags, 7, RollOverFlag); bitWrite(Flags, 3, FlipFlag); } /* Get Private */ boolean TouchBarConfig::GetRollOverFlag () { return bitRead (Flags, 7); } boolean TouchBarConfig::GetSpringBackFlag () { return bitRead (Flags, 6); } boolean TouchBarConfig::GetSnapFlag () { return bitRead (Flags, 5); } boolean TouchBarConfig::GetRampFlag () { return bitRead (Flags, 4); } boolean TouchBarConfig::GetFlipFlag () { return bitRead (Flags, 3); }
17.571429
108
0.711963
RPBCACUEAIIBH
d02248a925b2e191b000ae89b231c53d74468938
17,691
cc
C++
protocal/guardian/guardian.pb.cc
racestart/g2r
d115ebaab13829d716750eab2ebdcc51d79ff32e
[ "Apache-2.0" ]
1
2020-03-05T12:49:21.000Z
2020-03-05T12:49:21.000Z
protocal/guardian/guardian.pb.cc
gA4ss/g2r
a6e2ee5758ab59fd95704e3c3090dd234fbfb2c9
[ "Apache-2.0" ]
null
null
null
protocal/guardian/guardian.pb.cc
gA4ss/g2r
a6e2ee5758ab59fd95704e3c3090dd234fbfb2c9
[ "Apache-2.0" ]
1
2020-03-25T15:06:39.000Z
2020-03-25T15:06:39.000Z
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: guardian/guardian.proto #define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION #include "guardian/guardian.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> #include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.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) namespace apollo { namespace guardian { namespace { const ::google::protobuf::Descriptor* GuardianCommand_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* GuardianCommand_reflection_ = NULL; } // namespace void protobuf_AssignDesc_guardian_2fguardian_2eproto() GOOGLE_ATTRIBUTE_COLD; void protobuf_AssignDesc_guardian_2fguardian_2eproto() { protobuf_AddDesc_guardian_2fguardian_2eproto(); const ::google::protobuf::FileDescriptor* file = ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName( "guardian/guardian.proto"); GOOGLE_CHECK(file != NULL); GuardianCommand_descriptor_ = file->message_type(0); static const int GuardianCommand_offsets_[2] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GuardianCommand, header_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GuardianCommand, control_command_), }; GuardianCommand_reflection_ = ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( GuardianCommand_descriptor_, GuardianCommand::default_instance_, GuardianCommand_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GuardianCommand, _has_bits_[0]), -1, -1, sizeof(GuardianCommand), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(GuardianCommand, _internal_metadata_), -1); } namespace { GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_); inline void protobuf_AssignDescriptorsOnce() { ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_, &protobuf_AssignDesc_guardian_2fguardian_2eproto); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD; void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( GuardianCommand_descriptor_, &GuardianCommand::default_instance()); } } // namespace void protobuf_ShutdownFile_guardian_2fguardian_2eproto() { delete GuardianCommand::default_instance_; delete GuardianCommand_reflection_; } void protobuf_AddDesc_guardian_2fguardian_2eproto() GOOGLE_ATTRIBUTE_COLD; void protobuf_AddDesc_guardian_2fguardian_2eproto() { static bool already_here = false; if (already_here) return; already_here = true; GOOGLE_PROTOBUF_VERIFY_VERSION; ::apollo::common::protobuf_AddDesc_common_2fheader_2eproto(); ::apollo::control::protobuf_AddDesc_control_2fcontrol_5fcmd_2eproto(); ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( "\n\027guardian/guardian.proto\022\017apollo.guardi" "an\032\023common/header.proto\032\031control/control" "_cmd.proto\"q\n\017GuardianCommand\022%\n\006header\030" "\001 \001(\0132\025.apollo.common.Header\0227\n\017control_" "command\030\002 \001(\0132\036.apollo.control.ControlCo" "mmand", 205); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "guardian/guardian.proto", &protobuf_RegisterTypes); GuardianCommand::default_instance_ = new GuardianCommand(); GuardianCommand::default_instance_->InitAsDefaultInstance(); ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_guardian_2fguardian_2eproto); } // Force AddDescriptors() to be called at static initialization time. struct StaticDescriptorInitializer_guardian_2fguardian_2eproto { StaticDescriptorInitializer_guardian_2fguardian_2eproto() { protobuf_AddDesc_guardian_2fguardian_2eproto(); } } static_descriptor_initializer_guardian_2fguardian_2eproto_; // =================================================================== #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int GuardianCommand::kHeaderFieldNumber; const int GuardianCommand::kControlCommandFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 GuardianCommand::GuardianCommand() : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); // @@protoc_insertion_point(constructor:apollo.guardian.GuardianCommand) } void GuardianCommand::InitAsDefaultInstance() { header_ = const_cast< ::apollo::common::Header*>(&::apollo::common::Header::default_instance()); control_command_ = const_cast< ::apollo::control::ControlCommand*>(&::apollo::control::ControlCommand::default_instance()); } GuardianCommand::GuardianCommand(const GuardianCommand& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:apollo.guardian.GuardianCommand) } void GuardianCommand::SharedCtor() { _cached_size_ = 0; header_ = NULL; control_command_ = NULL; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } GuardianCommand::~GuardianCommand() { // @@protoc_insertion_point(destructor:apollo.guardian.GuardianCommand) SharedDtor(); } void GuardianCommand::SharedDtor() { if (this != default_instance_) { delete header_; delete control_command_; } } void GuardianCommand::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* GuardianCommand::descriptor() { protobuf_AssignDescriptorsOnce(); return GuardianCommand_descriptor_; } const GuardianCommand& GuardianCommand::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_guardian_2fguardian_2eproto(); return *default_instance_; } GuardianCommand* GuardianCommand::default_instance_ = NULL; GuardianCommand* GuardianCommand::New(::google::protobuf::Arena* arena) const { GuardianCommand* n = new GuardianCommand; if (arena != NULL) { arena->Own(n); } return n; } void GuardianCommand::Clear() { // @@protoc_insertion_point(message_clear_start:apollo.guardian.GuardianCommand) if (_has_bits_[0 / 32] & 3u) { if (has_header()) { if (header_ != NULL) header_->::apollo::common::Header::Clear(); } if (has_control_command()) { if (control_command_ != NULL) control_command_->::apollo::control::ControlCommand::Clear(); } } ::memset(_has_bits_, 0, sizeof(_has_bits_)); if (_internal_metadata_.have_unknown_fields()) { mutable_unknown_fields()->Clear(); } } bool GuardianCommand::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:apollo.guardian.GuardianCommand) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional .apollo.common.Header header = 1; case 1: { if (tag == 10) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_header())); } else { goto handle_unusual; } if (input->ExpectTag(18)) goto parse_control_command; break; } // optional .apollo.control.ControlCommand control_command = 2; case 2: { if (tag == 18) { parse_control_command: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_control_command())); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:apollo.guardian.GuardianCommand) return true; failure: // @@protoc_insertion_point(parse_failure:apollo.guardian.GuardianCommand) return false; #undef DO_ } void GuardianCommand::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:apollo.guardian.GuardianCommand) // optional .apollo.common.Header header = 1; if (has_header()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, *this->header_, output); } // optional .apollo.control.ControlCommand control_command = 2; if (has_control_command()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, *this->control_command_, output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:apollo.guardian.GuardianCommand) } ::google::protobuf::uint8* GuardianCommand::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:apollo.guardian.GuardianCommand) // optional .apollo.common.Header header = 1; if (has_header()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 1, *this->header_, false, target); } // optional .apollo.control.ControlCommand control_command = 2; if (has_control_command()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 2, *this->control_command_, false, target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:apollo.guardian.GuardianCommand) return target; } int GuardianCommand::ByteSize() const { // @@protoc_insertion_point(message_byte_size_start:apollo.guardian.GuardianCommand) int total_size = 0; if (_has_bits_[0 / 32] & 3u) { // optional .apollo.common.Header header = 1; if (has_header()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->header_); } // optional .apollo.control.ControlCommand control_command = 2; if (has_control_command()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->control_command_); } } if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void GuardianCommand::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:apollo.guardian.GuardianCommand) if (GOOGLE_PREDICT_FALSE(&from == this)) { ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__); } const GuardianCommand* source = ::google::protobuf::internal::DynamicCastToGenerated<const GuardianCommand>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:apollo.guardian.GuardianCommand) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:apollo.guardian.GuardianCommand) MergeFrom(*source); } } void GuardianCommand::MergeFrom(const GuardianCommand& from) { // @@protoc_insertion_point(class_specific_merge_from_start:apollo.guardian.GuardianCommand) if (GOOGLE_PREDICT_FALSE(&from == this)) { ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__); } if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_header()) { mutable_header()->::apollo::common::Header::MergeFrom(from.header()); } if (from.has_control_command()) { mutable_control_command()->::apollo::control::ControlCommand::MergeFrom(from.control_command()); } } if (from._internal_metadata_.have_unknown_fields()) { mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } } void GuardianCommand::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:apollo.guardian.GuardianCommand) if (&from == this) return; Clear(); MergeFrom(from); } void GuardianCommand::CopyFrom(const GuardianCommand& from) { // @@protoc_insertion_point(class_specific_copy_from_start:apollo.guardian.GuardianCommand) if (&from == this) return; Clear(); MergeFrom(from); } bool GuardianCommand::IsInitialized() const { return true; } void GuardianCommand::Swap(GuardianCommand* other) { if (other == this) return; InternalSwap(other); } void GuardianCommand::InternalSwap(GuardianCommand* other) { std::swap(header_, other->header_); std::swap(control_command_, other->control_command_); std::swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata GuardianCommand::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = GuardianCommand_descriptor_; metadata.reflection = GuardianCommand_reflection_; return metadata; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // GuardianCommand // optional .apollo.common.Header header = 1; bool GuardianCommand::has_header() const { return (_has_bits_[0] & 0x00000001u) != 0; } void GuardianCommand::set_has_header() { _has_bits_[0] |= 0x00000001u; } void GuardianCommand::clear_has_header() { _has_bits_[0] &= ~0x00000001u; } void GuardianCommand::clear_header() { if (header_ != NULL) header_->::apollo::common::Header::Clear(); clear_has_header(); } const ::apollo::common::Header& GuardianCommand::header() const { // @@protoc_insertion_point(field_get:apollo.guardian.GuardianCommand.header) return header_ != NULL ? *header_ : *default_instance_->header_; } ::apollo::common::Header* GuardianCommand::mutable_header() { set_has_header(); if (header_ == NULL) { header_ = new ::apollo::common::Header; } // @@protoc_insertion_point(field_mutable:apollo.guardian.GuardianCommand.header) return header_; } ::apollo::common::Header* GuardianCommand::release_header() { // @@protoc_insertion_point(field_release:apollo.guardian.GuardianCommand.header) clear_has_header(); ::apollo::common::Header* temp = header_; header_ = NULL; return temp; } void GuardianCommand::set_allocated_header(::apollo::common::Header* header) { delete header_; header_ = header; if (header) { set_has_header(); } else { clear_has_header(); } // @@protoc_insertion_point(field_set_allocated:apollo.guardian.GuardianCommand.header) } // optional .apollo.control.ControlCommand control_command = 2; bool GuardianCommand::has_control_command() const { return (_has_bits_[0] & 0x00000002u) != 0; } void GuardianCommand::set_has_control_command() { _has_bits_[0] |= 0x00000002u; } void GuardianCommand::clear_has_control_command() { _has_bits_[0] &= ~0x00000002u; } void GuardianCommand::clear_control_command() { if (control_command_ != NULL) control_command_->::apollo::control::ControlCommand::Clear(); clear_has_control_command(); } const ::apollo::control::ControlCommand& GuardianCommand::control_command() const { // @@protoc_insertion_point(field_get:apollo.guardian.GuardianCommand.control_command) return control_command_ != NULL ? *control_command_ : *default_instance_->control_command_; } ::apollo::control::ControlCommand* GuardianCommand::mutable_control_command() { set_has_control_command(); if (control_command_ == NULL) { control_command_ = new ::apollo::control::ControlCommand; } // @@protoc_insertion_point(field_mutable:apollo.guardian.GuardianCommand.control_command) return control_command_; } ::apollo::control::ControlCommand* GuardianCommand::release_control_command() { // @@protoc_insertion_point(field_release:apollo.guardian.GuardianCommand.control_command) clear_has_control_command(); ::apollo::control::ControlCommand* temp = control_command_; control_command_ = NULL; return temp; } void GuardianCommand::set_allocated_control_command(::apollo::control::ControlCommand* control_command) { delete control_command_; control_command_ = control_command; if (control_command) { set_has_control_command(); } else { clear_has_control_command(); } // @@protoc_insertion_point(field_set_allocated:apollo.guardian.GuardianCommand.control_command) } #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // @@protoc_insertion_point(namespace_scope) } // namespace guardian } // namespace apollo // @@protoc_insertion_point(global_scope)
35.170974
125
0.738907
racestart
d02270a485173a1eff99d741d0d39f556f84faa4
1,046
cpp
C++
code/cpp/NumberOfSymbolsCommonInaSetOfStrings.cpp
analgorithmaday/analgorithmaday.github.io
d43f98803bc673f61334bff54eed381426ee902e
[ "MIT" ]
null
null
null
code/cpp/NumberOfSymbolsCommonInaSetOfStrings.cpp
analgorithmaday/analgorithmaday.github.io
d43f98803bc673f61334bff54eed381426ee902e
[ "MIT" ]
null
null
null
code/cpp/NumberOfSymbolsCommonInaSetOfStrings.cpp
analgorithmaday/analgorithmaday.github.io
d43f98803bc673f61334bff54eed381426ee902e
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <map> #include <vector> using namespace std; void remove_dup(string& gems) { map<char, bool> visited; int len = gems.length(); int i = 0; while(i < len) { if(visited[gems[i]]) { gems.erase(i, 1); len--; continue; } visited[gems[i]] = true; ++i; } } int commons(vector<string>& stones) { map<char, int> element_map; int commons = 0; for(int i = 0; i < stones.size(); ++i) { for(int j = 0; j < stones[i].length(); ++j) { element_map[stones[i][j]]++; } } for(map<char, int>::iterator it = element_map.begin(); it != element_map.end(); ++it ) { if(it->second == stones.size()) commons++; } return commons; } int main() { int N; vector<string> stones; cin>>N; for(int i=0; i < N; i++) { string gem; cin>>gem; remove_dup(gem); stones.push_back(gem); } cout<<commons(stones)<<endl; }
20.509804
92
0.5
analgorithmaday
d022d9f43f19a76814e537c7f00d33fcfa32a76e
12,745
cpp
C++
test/err/id/System.main.cpp
AnantaYudica/basic
dcbf8c9eebb42a4e6a66b3c56ebc3a7e30626950
[ "MIT" ]
null
null
null
test/err/id/System.main.cpp
AnantaYudica/basic
dcbf8c9eebb42a4e6a66b3c56ebc3a7e30626950
[ "MIT" ]
178
2018-08-08T04:04:27.000Z
2019-12-15T01:47:58.000Z
test/err/id/System.main.cpp
AnantaYudica/basic
dcbf8c9eebb42a4e6a66b3c56ebc3a7e30626950
[ "MIT" ]
null
null
null
#include "Test.h" #include "test/Message.h" #include "test/Variable.h" #include "test/Case.h" #include "test/var/At.h" #include "err/id/System.h" #include "err/id/rec/ToBytes.h" #include <type_traits> #include <utility> BASIC_TEST_CONSTRUCT; #define BUFFER_FORMAT_CSTRING 256 basic::test::CString<char> IdentificationToString(basic::err::Identification * && id) { typedef typename basic::err::Identification::RecordType RecordType; constexpr std::size_t max_allocation = RecordType::MaximumAllocation(); std::uint8_t block[max_allocation]; std::size_t size_block = basic::err::id::rec:: ToBytes((const RecordType &)*id, block, max_allocation); const std::size_t size = (size_block * 2); char * tmp = new char[size + 1]; for(std::size_t i = 0, j = 0; i < size; i += 2, ++j) { std::uint8_t hex0 = block[j] >> 4; std::uint8_t hex1 = block[j] & std::uint8_t(0x0F); char ch0 = '0', ch1 = '0'; ch0 += (hex0 <= 9 ? hex0 : (hex0 + 7)); ch1 += (hex1 <= 9 ? hex1 : (hex1 + 7)); tmp[i] = ch0; tmp[i + 1] = ch1; } tmp[size] = '\0'; auto ret = basic::test::cstr::Format(BUFFER_FORMAT_CSTRING, "{Size : %d, Block : 0x%s}", size_block, tmp); delete[] tmp; return std::move(ret); } struct TestAliasSystemCategoryValueType {}; struct TestAliasSystemCodeValueType {}; struct TestBaseOfIdentification {}; struct TestCastToIdentification {}; template<typename TObj> using VariableTestIdSystem = basic::test::Variable< basic::err::defn::type::code::Value, basic::err::defn::type::sys::categ::Value, basic::err::defn::type::sys::code::Value, basic::err::Identification, TObj, basic::test::Value<const char *>, basic::test::Value<TObj *>, basic::test::Value<basic::err::Identification *>, basic::test::type::Function<basic::test::CString<char>(basic::err:: Identification * &&), &IdentificationToString>>; constexpr std::size_t ICodeValueType = 0; constexpr std::size_t ISystemCategoryValueType = 1; constexpr std::size_t ISystemCodeValueType = 2; constexpr std::size_t IIdentificationType = 3; constexpr std::size_t IObjType = 4; constexpr std::size_t IObjName = 5; constexpr std::size_t IObjValue = 6; constexpr std::size_t IIdentificationValue = 7; constexpr std::size_t IIdentificationToStringFunc = 8; typedef basic::test::msg::Argument<TestAliasSystemCategoryValueType, basic::test::msg::arg::type::Name<IObjType>, basic::test::msg::arg::Value<IObjName>, basic::test::msg::arg::type::Name<ISystemCategoryValueType>> ArgTestAliasSystemCategoryValueType; typedef basic::test::msg::Base<TestAliasSystemCategoryValueType, char, ArgTestAliasSystemCategoryValueType, ArgTestAliasSystemCategoryValueType, ArgTestAliasSystemCategoryValueType> MessageBaseTestAliasSystemCategoryValueType; typedef basic::test::msg::Argument<TestAliasSystemCodeValueType, basic::test::msg::arg::type::Name<IObjType>, basic::test::msg::arg::Value<IObjName>, basic::test::msg::arg::type::Name<ISystemCodeValueType>> ArgTestAliasSystemCodeValueType; typedef basic::test::msg::Base<TestAliasSystemCodeValueType, char, ArgTestAliasSystemCodeValueType, ArgTestAliasSystemCodeValueType, ArgTestAliasSystemCodeValueType> MessageBaseTestAliasSystemCodeValueType; typedef basic::test::msg::Argument<TestBaseOfIdentification, basic::test::msg::arg::type::Name<IObjType>, basic::test::msg::arg::Value<IObjName>, basic::test::msg::arg::type::Name<IIdentificationType>> ArgTestBaseOfIdentification; typedef basic::test::msg::Base<TestBaseOfIdentification, char, ArgTestBaseOfIdentification, ArgTestBaseOfIdentification, ArgTestBaseOfIdentification> MessageBaseTestBaseOfIdentification; typedef basic::test::msg::Argument<TestCastToIdentification, basic::test::msg::arg::type::Name<IObjType>, basic::test::msg::arg::Value<IObjName>, basic::test::msg::arg::type::Name<IIdentificationType>, basic::test::msg::arg::type::Function<IIdentificationToStringFunc, basic::test::msg::arg::Value<IIdentificationValue>>> ArgTestCastToIdentification; typedef basic::test::msg::Base<TestCastToIdentification, char, ArgTestCastToIdentification, ArgTestCastToIdentification, ArgTestCastToIdentification> MessageBaseTestCastToIdentification; template<typename TCases, typename... TVariables> struct TestIdSystem : public basic::test::Message<BASIC_TEST, TestIdSystem<TCases, TVariables...>>, public basic::test::Case<TestIdSystem<TCases, TVariables...>, TCases>, public basic::test::Base<TestIdSystem<TCases, TVariables...>, TVariables...>, public MessageBaseTestAliasSystemCategoryValueType, public MessageBaseTestAliasSystemCodeValueType, public MessageBaseTestBaseOfIdentification, public MessageBaseTestCastToIdentification { public: using MessageBaseTestAliasSystemCategoryValueType::Format; using MessageBaseTestAliasSystemCategoryValueType::SetFormat; using MessageBaseTestAliasSystemCategoryValueType::Argument; using MessageBaseTestAliasSystemCodeValueType::Format; using MessageBaseTestAliasSystemCodeValueType::SetFormat; using MessageBaseTestAliasSystemCodeValueType::Argument; using MessageBaseTestBaseOfIdentification::Format; using MessageBaseTestBaseOfIdentification::SetFormat; using MessageBaseTestBaseOfIdentification::Argument; using MessageBaseTestCastToIdentification::Format; using MessageBaseTestCastToIdentification::SetFormat; using MessageBaseTestCastToIdentification::Argument; using basic::test::Case<TestIdSystem<TCases, TVariables...>, TCases>::Run; using basic::test::Base<TestIdSystem<TCases, TVariables...>, TVariables...>::Run; public: TestIdSystem(TVariables & ... var) : basic::test::Message<BASIC_TEST, TestIdSystem<TCases, TVariables...>>(*this), basic::test::Case<TestIdSystem<TCases, TVariables...>, TCases>(*this), basic::test::Base<TestIdSystem<TCases, TVariables...>, TVariables...>(*this, var...) { basic::test::msg::base::Info info; basic::test::msg::base::Debug debug; basic::test::msg::base::Error err; TestAliasSystemCategoryValueType testAliasSystemCategoryValueType; SetFormat(info, testAliasSystemCategoryValueType, "Test alias type " "%s::SystemCategoryValueType {%s} is same with %s\n"); SetFormat(debug, testAliasSystemCategoryValueType, "Test alias type " "%s::SystemCategoryValueType {%s} is same with %s\n"); SetFormat(err, testAliasSystemCategoryValueType, "Error alias type " "%s::SystemCategoryValueType {%s} is not same with %s\n"); TestAliasSystemCodeValueType testAliasSystemCodeValueType; SetFormat(info, testAliasSystemCodeValueType, "Test alias type " "%s::SystemCodeValueType {%s} is same with %s\n"); SetFormat(debug, testAliasSystemCodeValueType, "Test alias type " "%s::SystemCodeValueType {%s} is same with %s\n"); SetFormat(err, testAliasSystemCodeValueType, "Error alias type " "%s::SystemCodeValueType {%s} is not same with %s\n"); TestBaseOfIdentification testBaseOfIdentification; SetFormat(info, testBaseOfIdentification, "Test %s {%s} is base of " "%s\n"); SetFormat(debug, testBaseOfIdentification, "Test %s {%s} is base of " "%s\n"); SetFormat(err, testBaseOfIdentification, "Error %s {%s} is not " "base of %s\n"); TestCastToIdentification testCastToIdentification; SetFormat(info, testCastToIdentification, "Test %s {%s} is same with " "%s %s\n"); SetFormat(debug, testCastToIdentification, "Test %s {%s} is same with " "%s %s\n"); SetFormat(err, testCastToIdentification, "Error %s {%s} is not " "same with %s %s\n"); } template<typename TObj> bool Result(const TestAliasSystemCategoryValueType &, VariableTestIdSystem<TObj> & var) { return typeid(typename basic::err::id::System:: SystemCategoryValueType).hash_code() == typeid(basic::err:: defn::type::sys::categ::Value).hash_code(); } template<typename TObj> bool Result(const TestAliasSystemCodeValueType &, VariableTestIdSystem<TObj> & var) { return typeid(typename basic::err::id::System:: SystemCodeValueType).hash_code() == typeid(basic::err:: defn::type::sys::code::Value).hash_code(); } template<typename TObj> bool Result(const TestBaseOfIdentification &, VariableTestIdSystem<TObj> & var) { return std::is_base_of<basic::err::Identification, TObj>::value; } template<typename TObj> bool Result(const TestCastToIdentification &, VariableTestIdSystem<TObj> & var) { const auto & id_sys = *basic::test::var::At<IObjValue>(var). Get().Get(); const auto & id = *basic::test::var::At<IIdentificationValue>(var). Get().Get(); const bool check_err = id_sys.IsSystem() ? true : (id_sys.Error().Code() == id.Error().Code()); const bool check_err_sys = !id_sys.IsSystem() ? true : (id_sys.ErrorSystem().Code() == id.ErrorSystem().Code() && id_sys.ErrorSystem().Category() == id.ErrorSystem().Category()); return id_sys.IsDefault() == id.IsDefault() && id_sys.IsBad() == id.IsBad() && id_sys.IsStandard() == id.IsStandard() && id_sys.IsCatch() == id.IsCatch() && id_sys.IsSystem() == id.IsSystem() && check_err && check_err_sys; } }; using Case1 = basic::test::type::Parameter<TestAliasSystemCategoryValueType, TestAliasSystemCodeValueType, TestBaseOfIdentification, TestCastToIdentification>; BASIC_TEST_TYPE_NAME("signed char", signed char); BASIC_TEST_TYPE_NAME("char", char); BASIC_TEST_TYPE_NAME("unsigned char", unsigned char); BASIC_TEST_TYPE_NAME("short", short); BASIC_TEST_TYPE_NAME("unsigned short", unsigned short); BASIC_TEST_TYPE_NAME("int", int); BASIC_TEST_TYPE_NAME("unsigned int", unsigned int); BASIC_TEST_TYPE_NAME("long", long); BASIC_TEST_TYPE_NAME("unsigned long", unsigned long); BASIC_TEST_TYPE_NAME("long long", long long); BASIC_TEST_TYPE_NAME("unsigned long long", unsigned long long); BASIC_TEST_TYPE_NAME("basic::err::id::System", basic::err::id::System); BASIC_TEST_TYPE_NAME("basic::err::Identification", basic::err::Identification); typedef VariableTestIdSystem<basic::err::id::System> T1Var1; constexpr typename basic::err::id::System::CodeValueType code_value1 = 4; constexpr typename basic::err::id::System::CategoryValueType categ_value1 = 0xB; basic::err::id::System obj1_1; basic::err::id::System obj1_2{categ_value1, code_value1}; basic::err::id::System obj1_3{basic::err::id::flag::Standard{}, categ_value1, code_value1}; basic::err::Identification id1_1; basic::err::Identification id1_2{basic::err::id::flag::System{}, categ_value1, code_value1}; basic::err::Identification id1_3{basic::err::id::flag::System{}, basic::err::id::flag::Standard{}, categ_value1, code_value1}; T1Var1 t1_var1{"obj1_1", &obj1_1, &id1_1}; T1Var1 t1_var2{"obj1_2", &obj1_2, &id1_2}; T1Var1 t1_var3{"obj1_3", &obj1_3, &id1_3}; REGISTER_TEST(t1, new TestIdSystem<Case1, T1Var1, T1Var1, T1Var1>(t1_var1, t1_var2, t1_var3)); basic::err::id::System obj2_1{obj1_1}; basic::err::id::System obj2_2{obj1_2}; basic::err::id::System obj2_3{obj1_3}; T1Var1 t2_var1{"obj2_1", &obj2_1, &id1_1}; T1Var1 t2_var2{"obj2_2", &obj2_2, &id1_2}; T1Var1 t2_var3{"obj2_3", &obj2_3, &id1_3}; REGISTER_TEST(t2, new TestIdSystem<Case1, T1Var1, T1Var1, T1Var1>(t2_var1, t2_var2, t2_var3)); basic::err::id::System obj2_1_c{obj2_1}; basic::err::id::System obj2_2_c{obj2_2}; basic::err::id::System obj2_3_c{obj2_3}; basic::err::id::System obj3_1{std::move(obj2_1_c)}; basic::err::id::System obj3_2{std::move(obj2_2_c)}; basic::err::id::System obj3_3{std::move(obj2_3_c)}; T1Var1 t3_var1{"obj3_1", &obj3_1, &id1_1}; T1Var1 t3_var2{"obj3_2", &obj3_2, &id1_2}; T1Var1 t3_var3{"obj3_3", &obj3_3, &id1_3}; T1Var1 t3_var4{"obj3_1_c", &obj2_1_c, &id1_1}; T1Var1 t3_var5{"obj3_2_c", &obj2_2_c, &id1_1}; T1Var1 t3_var6{"obj3_3_c", &obj2_3_c, &id1_1}; REGISTER_TEST(t3, new TestIdSystem<Case1, T1Var1, T1Var1, T1Var1, T1Var1, T1Var1, T1Var1>(t3_var1, t3_var2, t3_var3, t3_var4,t3_var5, t3_var6)); int main() { return RUN_TEST(); }
40.332278
79
0.691487
AnantaYudica
d0247ebaf87e6150cd5095f285103e5820f9b090
1,686
hpp
C++
plansys2_problem_expert/include/plansys2_problem_expert/ProblemExpertInterface.hpp
mjcarroll/ros2_planning_system
676d0d3a9629446cdc0797df8daa808e75728cf3
[ "Apache-2.0" ]
null
null
null
plansys2_problem_expert/include/plansys2_problem_expert/ProblemExpertInterface.hpp
mjcarroll/ros2_planning_system
676d0d3a9629446cdc0797df8daa808e75728cf3
[ "Apache-2.0" ]
null
null
null
plansys2_problem_expert/include/plansys2_problem_expert/ProblemExpertInterface.hpp
mjcarroll/ros2_planning_system
676d0d3a9629446cdc0797df8daa808e75728cf3
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 Intelligent Robotics Lab // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef PLANSYS2_PROBLEM_EXPERT__PROBLEMEXPERTINTERFACE_HPP_ #define PLANSYS2_PROBLEM_EXPERT__PROBLEMEXPERTINTERFACE_HPP_ #include <string> #include <vector> #include "plansys2_domain_expert/Types.hpp" #include "plansys2_problem_expert/Types.hpp" namespace plansys2 { class ProblemExpertInterface { public: ProblemExpertInterface() {} virtual std::vector<Instance> getInstances() = 0; virtual bool addInstance(const Instance & instance) = 0; virtual bool removeInstance(const std::string & name) = 0; virtual boost::optional<Instance> getInstance(const std::string & name) = 0; virtual std::vector<Predicate> getPredicates() = 0; virtual bool addPredicate(const Predicate & predicate) = 0; virtual bool removePredicate(const Predicate & predicate) = 0; virtual bool existPredicate(const Predicate & predicate) = 0; virtual Goal getGoal() = 0; virtual bool setGoal(const Goal & goal) = 0; virtual bool clearGoal() = 0; virtual std::string getProblem() = 0; }; } // namespace plansys2 #endif // PLANSYS2_PROBLEM_EXPERT__PROBLEMEXPERTINTERFACE_HPP_
32.423077
78
0.759786
mjcarroll
d02544ddd1be1a6bf3b41d3a07d7085e57b7c2f1
739
cpp
C++
UVa Online Judge (UVa)/Volume 102/10226 - Hardwood Species.cpp
sreejonK19/online-judge-solutions
da65d635cc488c8f305e48b49727ad62649f5671
[ "MIT" ]
null
null
null
UVa Online Judge (UVa)/Volume 102/10226 - Hardwood Species.cpp
sreejonK19/online-judge-solutions
da65d635cc488c8f305e48b49727ad62649f5671
[ "MIT" ]
null
null
null
UVa Online Judge (UVa)/Volume 102/10226 - Hardwood Species.cpp
sreejonK19/online-judge-solutions
da65d635cc488c8f305e48b49727ad62649f5671
[ "MIT" ]
2
2018-11-06T19:37:56.000Z
2018-11-09T19:05:46.000Z
#include <bits/stdc++.h> using namespace std; string name; map <string, int> msi; map <string, int> :: iterator mit; int main( int argc, char ** argv ) { // freopen( "in.txt", "r", stdin ); int tc; scanf( "%d ", &tc ); for( int nCase = 1 ; nCase <= tc ; ++nCase ) { msi.clear(); int total = 0; while( getline( cin, name ) && name.size() ) { ++msi[name]; ++total; } if( nCase > 1 ) puts( "" ); for( mit = msi.begin() ; mit != msi.end() ; ++mit ) { double result = ((double) (mit->second * 100) ) / ((double) total); cout << mit->first << " " << fixed << setprecision( 4 ) << result << endl; } } return 0; }
24.633333
86
0.460081
sreejonK19
d0283ea2630da8f55c697dd4ced02391d4f5681d
4,951
cpp
C++
tasks/FrameFilter.cpp
PhischDotOrg/stm32f4-common
4b6b9c436018c89d3668c6ee107e97abb930bae2
[ "MIT" ]
1
2022-01-31T01:59:52.000Z
2022-01-31T01:59:52.000Z
tasks/FrameFilter.cpp
PhischDotOrg/stm32-common
4b6b9c436018c89d3668c6ee107e97abb930bae2
[ "MIT" ]
5
2020-04-13T21:55:12.000Z
2020-06-27T17:44:44.000Z
tasks/FrameFilter.cpp
PhischDotOrg/stm32f4-common
4b6b9c436018c89d3668c6ee107e97abb930bae2
[ "MIT" ]
null
null
null
/*- * $Copyright$ -*/ #include "tasks/FrameSampler.hpp" #ifndef _FRAME_FILTER_CPP_4085c3de_7e34_4002_a351_d24c2cd81aff #define _FRAME_FILTER_CPP_4085c3de_7e34_4002_a351_d24c2cd81aff #if defined(__cplusplus) extern "C" { #endif /* defined(__cplusplus) */ #include "FreeRTOS/FreeRTOS.h" #include "FreeRTOS/task.h" #include "FreeRTOS/queue.h" #include "FreeRTOS/semphr.h" #if defined(__cplusplus) } /* extern "C" */ #endif /* defined(__cplusplus) */ namespace tasks { /******************************************************************************* * ******************************************************************************/ template<typename InputBufferT, typename OutputBufferT, size_t N, typename FilterT, typename PinT, typename UartT> FrameFilterT<InputBufferT, OutputBufferT, N, FilterT, PinT, UartT>::FrameFilterT(const char * const p_name, const unsigned p_priority, UartT &p_uart, OutputBufferT (&p_frames)[N], FilterT &p_filter) : Task(p_name, p_priority, configMINIMAL_STACK_SIZE * 2), m_uart(p_uart), m_frames(p_frames), m_filter(p_filter), m_activeIndicationPin(NULL), m_current(0), m_rxQueue(NULL), m_txQueue(NULL) { } /******************************************************************************* * ******************************************************************************/ template<typename InputBufferT, typename OutputBufferT, size_t N, typename FilterChainT, typename PinT, typename UartT> FrameFilterT<InputBufferT, OutputBufferT, N, FilterChainT, PinT, UartT>::~FrameFilterT() { } /******************************************************************************* * ******************************************************************************/ template<typename InputBufferT, typename OutputBufferT, size_t N, typename FilterChainT, typename PinT, typename UartT> void FrameFilterT<InputBufferT, OutputBufferT, N, FilterChainT, PinT, UartT>::run(void) { this->m_uart.printf("Task '%s' starting...\r\n", this->m_name); InputBufferT *rxBuffer; int rc = 0; /* Can't do this in the constructor; FreeRTOS must be running */ for (unsigned i = 0; i < N; i++) { this->m_frames[i].unlock(); } for (OutputBufferT *txBuffer = &this->m_frames[0]; ; txBuffer = &this->m_frames[++this->m_current % N]) { if (xQueueReceive(*this->m_rxQueue, &rxBuffer, portMAX_DELAY) != pdTRUE) { this->m_uart.printf("%s(): Failed to receive buffer from queue. Aborting!\r\n", this->m_name); break; } #if defined(WITH_PROFILING) if (this->m_activeIndicationPin != NULL) this->m_activeIndicationPin->set(gpio::Pin::On); #endif /* defined(WITH_PROFILING) */ if (rxBuffer->lock() != 0) { this->m_uart.printf("%s(): Failed to lock Rx Buffer. Aborting!\r\n", this->m_name); break; }; if (txBuffer->lock() != 0) { this->m_uart.printf("%s(): Failed to lock Buffer %u. Aborting!\r\n", this->m_name, this->m_current); break; }; this->m_filter.filter(*rxBuffer, *txBuffer); #if defined(DEBUG_FRAME_FILTER) unsigned idx = 0; for (typename OutputBufferT::const_iterator iter = txBuffer->begin(); iter != txBuffer->end(); iter++, idx++) { volatile unsigned value = ((*iter) * 1000); m_uart.printf("%s(): %d: %d\r\n", this->m_name, idx, (value + 500) / 1000); } #endif /* defined(DEBUG_FRAME_FILTER) */ if (txBuffer->unlock() != 0) { this->m_uart.printf("%s(): Failed to unlock Buffer %u. Aborting!\r\n", this->m_name, this->m_current); break; }; if (rxBuffer->unlock() != 0) { this->m_uart.printf("%s(): Failed to unlock Rx Buffer. Aborting!\r\n", this->m_name); break; } if (rc == 0) { /* * This copies n bytes from &buffer into the queue. The value n is * configured as sizeof(OutputBufferT*) when the queue was created). So * basically, this copies the contents of the buffer pointer to the * queue which, in effect, writes a OutputBufferT * to the queue. */ if (xQueueSend(*this->m_txQueue, &txBuffer, 0) != pdTRUE) { this->m_uart.printf("%s(): Failed to post buffer %d to queue. Aborting!\r\n", this->m_name, this->m_current % N); break; } } else { this->m_uart.printf("%s(): Failed to fill frame buffer with samples!\r\n", this->m_name); } #if defined(WITH_PROFILING) if (this->m_activeIndicationPin != NULL) this->m_activeIndicationPin->set(gpio::Pin::Off); #endif /* defined(WITH_PROFILING) */ } this->m_uart.printf("%s() ended!\r\n", this->m_name); halt(__FILE__, __LINE__); } } /* namespace tasks */ #endif /* _FRAME_FILTER_CPP_4085c3de_7e34_4002_a351_d24c2cd81aff */
40.252033
146
0.565946
PhischDotOrg
d02d99d2d8fdc4ae9ca2b31e5ac7d74a8c51bd3e
3,321
cpp
C++
src/menustate.cpp
jumpmanmv/pixeltetris
4a40543e5919b3ca3b35c2310da258a6cf5d224f
[ "MIT" ]
2
2021-05-07T15:05:56.000Z
2021-11-16T17:33:46.000Z
src/menustate.cpp
jumpmanmv/pixeltetris
4a40543e5919b3ca3b35c2310da258a6cf5d224f
[ "MIT" ]
null
null
null
src/menustate.cpp
jumpmanmv/pixeltetris
4a40543e5919b3ca3b35c2310da258a6cf5d224f
[ "MIT" ]
null
null
null
#include "menustate.hpp" #include <iostream> //debug #include <vector> #include <SDL2/SDL.h> #include "config.hpp" #include "inputmanager.hpp" #include "renderer.hpp" #include "state.hpp" /* * ==================================== * Public methods start here * ==================================== */ MenuState::MenuState (InputManager *manager) : State (manager) {} MenuState::~MenuState () { exit(); } void MenuState::initialize () { index = 0; title_text = new Texture(); title_text->loadFromText ("Pixeltetris!", Game::getInstance()->mRenderer->bigFont, config::default_text_color); #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__) mButtons.push_back(new Button ("../../assets/button-play.png", &Game::pushNewGame, (config::logical_window_width-80)/2, 130)); mButtons.push_back(new Button ("../../assets/button-options.png", &Game::pushOptions, (config::logical_window_width-80)/2, 180)); mButtons.push_back(new Button ("../../assets/button-exit.png", &Game::goBack, (config::logical_window_width-80)/2, 230)); #else mButtons.push_back(new Button ("../assets/button-play.png", &Game::pushNewGame, (config::logical_window_width-80)/2, 130)); mButtons.push_back(new Button ("../assets/button-options.png", &Game::pushOptions, (config::logical_window_width-80)/2, 180)); mButtons.push_back(new Button ("../assets/button-exit.png", &Game::goBack, (config::logical_window_width-80)/2, 230)); #endif } void MenuState::exit () { for (auto i : mButtons) { delete i; } } void MenuState::run () { update(); draw(); } void MenuState::update () { while (mInputManager->pollAction() != 0) { if (mInputManager->isGameExiting()) { nextStateID = STATE_EXIT; break; } switch (mInputManager->getAction()) { case Action::select: { mButtons[index]->callbackFunction(); break; } case Action::move_up: { if (index > 0) { --index; } break; } case Action::move_down: { if (index < mButtons.size()-1) { ++index; } break; } } } } void MenuState::draw () { Game::getInstance()->mRenderer->clearScreen(); for (auto i : mButtons) { i->draw(); } title_text->renderCentered(config::logical_window_width/2, 50); SDL_Rect highlight_box = {mButtons[index]->getX(), mButtons[index]->getY(), mButtons[index]->getWidth(), mButtons[index]->getHeight()}; SDL_SetRenderDrawBlendMode (Game::getInstance()->mRenderer->mSDLRenderer, SDL_BLENDMODE_BLEND); SDL_SetRenderDrawColor (Game::getInstance()->mRenderer->mSDLRenderer, 255, 255, 255, config::transparency_alpha-20); SDL_RenderFillRect(Game::getInstance()->mRenderer->mSDLRenderer, &highlight_box); SDL_SetRenderDrawBlendMode (Game::getInstance()->mRenderer->mSDLRenderer, SDL_BLENDMODE_NONE); Game::getInstance()->mRenderer->updateScreen(); } void MenuState::addButton (Button *button) { mButtons.push_back(button); }
28.878261
139
0.586871
jumpmanmv
d02e2fef6086d606dee2b2a510ff67a73450e2b3
175
cpp
C++
applications/sandbox/systems/gui_test.cpp
Rythe-Interactive/Rythe-Engine.rythe-legacy
c119c494524b069a73100b12dc3d8b898347830d
[ "MIT" ]
2
2022-03-08T09:46:17.000Z
2022-03-28T08:07:05.000Z
applications/sandbox/systems/gui_test.cpp
Rythe-Interactive/Rythe-Engine.rythe-legacy
c119c494524b069a73100b12dc3d8b898347830d
[ "MIT" ]
3
2022-03-02T13:49:10.000Z
2022-03-22T11:54:06.000Z
applications/sandbox/systems/gui_test.cpp
Rythe-Interactive/Rythe-Engine.rythe-legacy
c119c494524b069a73100b12dc3d8b898347830d
[ "MIT" ]
null
null
null
#include "gui_test.hpp" bool legion::GuiTestSystem::captured = false; bool legion::GuiTestSystem::isEditingText = false; legion::ecs::entity legion::GuiTestSystem::selected;
29.166667
52
0.782857
Rythe-Interactive
d0317bfdeb24757d771b5c209eff14e2866e5de9
736
cpp
C++
source.cpp
IshaySela/lightningPlusPlus
bdd81921c6f112b7ed51bb3297ffc213d256e178
[ "MIT" ]
1
2022-01-20T15:51:04.000Z
2022-01-20T15:51:04.000Z
source.cpp
IshaySela/lightningPlusPlus
bdd81921c6f112b7ed51bb3297ffc213d256e178
[ "MIT" ]
1
2022-01-30T10:15:29.000Z
2022-01-30T10:15:29.000Z
source.cpp
IshaySela/lightningPlusPlus
bdd81921c6f112b7ed51bb3297ffc213d256e178
[ "MIT" ]
null
null
null
#include <iostream> #include <lightning/httpServer/ServerBuilder.hpp> constexpr const char *PublicKeyPath = "/home/ishaysela/projects/lightningPlusPlus/tests/localhost.cert"; constexpr const char *PrivateKeyPath = "/home/ishaysela/projects/lightningPlusPlus/tests/localhost.key"; auto main() -> int { auto server = lightning::ServerBuilder::createNew(8080) .withSsl(PublicKeyPath, PrivateKeyPath) .withThreads(1) .build(); auto getForcast = [](lightning::HttpRequest request) { int x; return lightning::HttpResponseBuilder::create() .build(); }; server.get("/forcast", getForcast); server.start(); return 0; }
29.44
104
0.641304
IshaySela
d036ee1170c75bf67a68afdc072618208fbac472
867
cpp
C++
src/tuw_geometry/polar2d.cpp
baluke/tuw_geometry
eaa03386d91f38f70a11dac242ff92eca24906e5
[ "BSD-2-Clause" ]
null
null
null
src/tuw_geometry/polar2d.cpp
baluke/tuw_geometry
eaa03386d91f38f70a11dac242ff92eca24906e5
[ "BSD-2-Clause" ]
null
null
null
src/tuw_geometry/polar2d.cpp
baluke/tuw_geometry
eaa03386d91f38f70a11dac242ff92eca24906e5
[ "BSD-2-Clause" ]
null
null
null
#include <memory> #include <tuw_geometry/polar2d.h> using namespace tuw; Polar2D::Polar2D () : Point2D ( 0,0 ) {}; Polar2D::Polar2D ( const Point2D &p ) : Point2D ( atan2( p.y(), p.x()), sqrt( p.x() * p.x() + p.y()* p.y() ), 1 ) {}; Polar2D::Polar2D ( double alpha, double rho ) : Point2D ( alpha,rho ) {}; Polar2D::Polar2D ( double alpha, double rho, double h ) : Point2D ( alpha, rho, h ) {}; /** * @return alpha **/ const double &Polar2D::alpha () const { return x(); } /** * @return alpha **/ double &Polar2D::alpha () { return x(); } /** * @return rho component **/ const double &Polar2D::rho () const { return y(); } /** * @return rho component **/ double &Polar2D::rho () { return y(); } /** * @return point in cartesian space **/ Point2D Polar2D::point () const { return Point2D(cos(alpha()) * rho(), sin(alpha()) * rho()); }
21.146341
117
0.579008
baluke
d038351d3a364558234f3d429eb9cc35c15e8c5b
1,606
hpp
C++
Header Files/Game.hpp
zhihanLin/text-based-RPG
1d4919a3d9569739ea924a5aa4699a3995dab043
[ "FSFAP" ]
null
null
null
Header Files/Game.hpp
zhihanLin/text-based-RPG
1d4919a3d9569739ea924a5aa4699a3995dab043
[ "FSFAP" ]
null
null
null
Header Files/Game.hpp
zhihanLin/text-based-RPG
1d4919a3d9569739ea924a5aa4699a3995dab043
[ "FSFAP" ]
null
null
null
// // Game.hpp // idleRPG // // Created by ZHIHAN LIN on 4/17/20. // Copyright © 2020 ZHIHAN LIN. All rights reserved. // #ifndef Game_hpp #define Game_hpp #include <stdio.h> #include <iterator> #include <algorithm> #include <ctime> #include <string> #include <vector> #include <deque> #include <fstream> #include "Inventory.hpp" #include "Dungeon.hpp" #include "InvalidMenuChoice.hpp" #include "Shop.hpp" using namespace std; class Game{ private: // for menu int choice; bool tryAgain = false; bool ifPlaying = true; bool lv15Recruitment = true; bool lv30Recruitment = true; protected: vector<Hero> heros; vector<Hero> newHeros; vector<Hero>::iterator it; // for save and load ofstream herosOut; ifstream herosIn; // temporarily store record in queue, // 10 records of heros are allowed, // the latest record will push out the oldest one string record; deque<string> herosRecords; public: Inventory backPack; Game(); ~Game(); // function void menu(); void choiceBetween(const int &begin, const int &end); void menu_inventory(); void menu_applyWeapon(const int &index, string &itemName, int &itemLevel); void menu_applyArmor(const int &index, string &itemName, int &itemLevel); void createHero(); void save(); // 10 records are allowed void load(); void pause(); // setter void setPlaying(bool tf) { this->ifPlaying = tf; } // gettet bool getPlaying() { return this->ifPlaying; } }; #endif /* Game_hpp */
21.131579
78
0.640722
zhihanLin
d03d4d9b0eac61733880aa3f0b3d4c7062f0312f
692
cpp
C++
Codeforces/1005C - Summarize to the Power of Two.cpp
naimulcsx/online-judge-solutions
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
[ "MIT" ]
null
null
null
Codeforces/1005C - Summarize to the Power of Two.cpp
naimulcsx/online-judge-solutions
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
[ "MIT" ]
null
null
null
Codeforces/1005C - Summarize to the Power of Two.cpp
naimulcsx/online-judge-solutions
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; vector<int> val; int n, arr[120100]; unordered_map<int, int> freq; int main() { cin >> n; for (int i = 1; i <= 30; ++i) val.push_back(pow(2, i)); for (int i = 0; i < n; ++i) cin >> arr[i], freq[arr[i]]++; int cnt = 0; for (int i = 0; i < n; ++i) { bool flag = false; freq[arr[i]]--; for ( auto el: val ) { if (el <= arr[i]) continue; int left = el - arr[i]; if (freq[left] > 0) { flag = true; break; } } freq[arr[i]]++; if (!flag) cnt++; } cout << cnt << endl; return 0; }
20.352941
62
0.413295
naimulcsx
d041fe83c7009ef6a47479db78296e97b3170338
887
hpp
C++
src/network/server.hpp
leezhenghui/Mushroom
8aed2bdd80453d856145925d067bef5ed9d10ee0
[ "BSD-3-Clause" ]
351
2016-10-12T14:06:09.000Z
2022-03-24T14:53:54.000Z
src/network/server.hpp
leezhenghui/Mushroom
8aed2bdd80453d856145925d067bef5ed9d10ee0
[ "BSD-3-Clause" ]
7
2017-03-07T01:49:16.000Z
2018-07-27T08:51:54.000Z
src/network/server.hpp
UncP/Mushroom
8aed2bdd80453d856145925d067bef5ed9d10ee0
[ "BSD-3-Clause" ]
62
2016-10-31T12:46:45.000Z
2021-12-28T11:25:26.000Z
/** * > Author: UncP * > Github: www.github.com/UncP/Mushroom * > License: BSD-3 * > Time: 2017-04-23 10:50:39 **/ #ifndef _SERVER_HPP_ #define _SERVER_HPP_ #include <vector> #include "../include/utility.hpp" #include "callback.hpp" #include "socket.hpp" namespace Mushroom { class Channel; class EventBase; class Server : private NoCopy { public: Server(EventBase *event_base, uint16_t port); virtual ~Server(); void Start(); void Close(); void OnConnect(const ConnectCallBack &connectcb); std::vector<Connection *>& Connections(); uint16_t Port() const; protected: uint16_t port_; EventBase *event_base_; Socket socket_; Channel *listen_; std::vector<Connection *> connections_; ConnectCallBack connectcb_; private: void HandleAccept(); }; } // namespace Mushroom #endif /* _SERVER_HPP_ */
16.425926
51
0.662909
leezhenghui
d0467369531d2e1f3dd01fea8c395f1a8a034d25
6,751
cpp
C++
source/ashes/renderer/D3D11Renderer/Miscellaneous/D3D11QueryPool.cpp
DragonJoker/Ashes
a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e
[ "MIT" ]
227
2018-09-17T16:03:35.000Z
2022-03-19T02:02:45.000Z
source/ashes/renderer/D3D11Renderer/Miscellaneous/D3D11QueryPool.cpp
DragonJoker/RendererLib
0f8ad8edec1b0929ebd10247d3dd0a9ee8f8c91a
[ "MIT" ]
39
2018-02-06T22:22:24.000Z
2018-08-29T07:11:06.000Z
source/ashes/renderer/D3D11Renderer/Miscellaneous/D3D11QueryPool.cpp
DragonJoker/Ashes
a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e
[ "MIT" ]
8
2019-05-04T10:33:32.000Z
2021-04-05T13:19:27.000Z
#include "Miscellaneous/D3D11QueryPool.hpp" #include "Core/D3D11Device.hpp" #include "ashesd3d11_api.hpp" namespace ashes::d3d11 { namespace { D3D11_QUERY convert( VkQueryType type ) { switch ( type ) { case VK_QUERY_TYPE_OCCLUSION: return D3D11_QUERY_OCCLUSION; case VK_QUERY_TYPE_PIPELINE_STATISTICS: return D3D11_QUERY_PIPELINE_STATISTICS; case VK_QUERY_TYPE_TIMESTAMP: return D3D11_QUERY_TIMESTAMP; default: assert( false ); return D3D11_QUERY_TIMESTAMP; } } UINT64 getPipelineStatistic( uint32_t index , D3D11_QUERY_DATA_PIPELINE_STATISTICS const & stats ) { switch ( index ) { case 0: return stats.IAVertices; case 1: return stats.IAPrimitives; case 2: return stats.VSInvocations; case 3: return stats.CInvocations; case 4: return stats.CPrimitives; case 5: return stats.PSInvocations; case 6: return stats.GSPrimitives; case 7: return stats.GSInvocations; case 8: return stats.HSInvocations; case 9: return stats.DSInvocations; case 10: return stats.CSInvocations; } return 0ull; } uint32_t adjustQueryCount( uint32_t count , VkQueryType type , VkQueryPipelineStatisticFlags pipelineStatistics ) { if ( type != VK_QUERY_TYPE_PIPELINE_STATISTICS ) { return count; } return 1u; } } QueryPool::QueryPool( VkDevice device , VkQueryPoolCreateInfo createInfo ) : m_device{ device } , m_createInfo{ std::move( createInfo ) } { D3D11_QUERY_DESC desc; desc.MiscFlags = 0u; desc.Query = convert( m_createInfo.queryType ); m_queries.resize( adjustQueryCount( m_createInfo.queryCount, m_createInfo.queryType, m_createInfo.pipelineStatistics ) ); for ( auto & query : m_queries ) { auto hr = get( m_device )->getDevice()->CreateQuery( &desc, &query ); if ( checkError( m_device, hr, "CreateQuery" ) ) { dxDebugName( query, Query ); } } switch ( m_createInfo.queryType ) { case VK_QUERY_TYPE_OCCLUSION: m_data.resize( sizeof( uint64_t ) ); getUint32 = [this]( uint32_t index ) { return uint32_t( *reinterpret_cast< uint64_t * >( m_data.data() ) ); }; getUint64 = [this]( uint32_t index ) { return *reinterpret_cast< uint64_t * >( m_data.data() ); }; break; case VK_QUERY_TYPE_PIPELINE_STATISTICS: m_data.resize( sizeof( D3D11_QUERY_DATA_PIPELINE_STATISTICS ) ); getUint32 = [this]( uint32_t index ) { D3D11_QUERY_DATA_PIPELINE_STATISTICS data = *reinterpret_cast< D3D11_QUERY_DATA_PIPELINE_STATISTICS * >( m_data.data() ); return uint32_t( getPipelineStatistic( index, data ) ); }; getUint64 = [this]( uint32_t index ) { D3D11_QUERY_DATA_PIPELINE_STATISTICS data = *reinterpret_cast< D3D11_QUERY_DATA_PIPELINE_STATISTICS * >( m_data.data() ); return getPipelineStatistic( index, data ); }; break; case VK_QUERY_TYPE_TIMESTAMP: m_data.resize( sizeof( uint64_t ) ); getUint32 = [this]( uint32_t index ) { return uint32_t( *reinterpret_cast< uint64_t * >( m_data.data() ) ); }; getUint64 = [this]( uint32_t index ) { return *reinterpret_cast< uint64_t * >( m_data.data() ); }; break; default: break; } } QueryPool::~QueryPool() { for ( auto & query : m_queries ) { safeRelease( query ); } } VkResult QueryPool::getResults( uint32_t firstQuery , uint32_t queryCount , VkDeviceSize stride , VkQueryResultFlags flags , VkDeviceSize dataSize , void * data )const { if ( m_createInfo.queryType == VK_QUERY_TYPE_PIPELINE_STATISTICS ) { return getPipelineStatisticsResults( firstQuery , queryCount , stride , flags , dataSize , data ); } return getOtherResults( firstQuery , queryCount , stride , flags , dataSize , data ); } VkResult QueryPool::getPipelineStatisticsResults( uint32_t firstQuery , uint32_t queryCount , VkDeviceSize stride , VkQueryResultFlags flags , VkDeviceSize dataSize , void * data )const { auto max = firstQuery + queryCount; assert( max <= m_queries.size() ); auto context{ get( m_device )->getImmediateContext() }; VkResult result = VK_SUCCESS; for ( auto i = firstQuery; i < max; ++i ) { HRESULT hr; do { hr = context->GetData( m_queries[i] , m_data.data() , UINT( m_data.size() ) , 0u ); } while ( hr == S_FALSE ); if ( hr == S_FALSE ) { result = VK_INCOMPLETE; } else if ( checkError( m_device, hr, "GetData" ) ) { auto buffer = reinterpret_cast< uint8_t * >( data ); size_t size = 0u; if ( checkFlag( flags, VK_QUERY_RESULT_64_BIT ) ) { auto resmax = ( m_createInfo.queryType == VK_QUERY_TYPE_PIPELINE_STATISTICS ? uint32_t( m_data.size() / sizeof( uint64_t ) ) : queryCount ); stride = stride ? stride : sizeof( uint64_t ); for ( uint32_t resi = 0; resi < resmax && size < dataSize; ++resi ) { *reinterpret_cast< uint64_t * >( buffer ) = getUint64( resi ); buffer += stride; size += stride; } } else { auto resmax = ( m_createInfo.queryType == VK_QUERY_TYPE_PIPELINE_STATISTICS ? uint32_t( m_data.size() / sizeof( uint32_t ) ) : queryCount ); stride = stride ? stride : sizeof( uint32_t ); for ( uint32_t resi = 0; resi < resmax && size < dataSize; ++resi ) { *reinterpret_cast< uint32_t * >( buffer ) = getUint32( resi ); buffer += stride; size += stride; } } } } return result; } VkResult QueryPool::getOtherResults( uint32_t firstQuery , uint32_t queryCount , VkDeviceSize stride , VkQueryResultFlags flags , VkDeviceSize dataSize , void * data )const { auto max = firstQuery + queryCount; assert( max <= m_queries.size() ); auto context{ get( m_device )->getImmediateContext() }; VkResult result = VK_SUCCESS; stride = stride ? stride : ( checkFlag( flags, VK_QUERY_RESULT_64_BIT ) ? sizeof( uint64_t ) : sizeof( uint32_t ) ); auto buffer = reinterpret_cast< uint8_t * >( data ); for ( auto i = firstQuery; i < max; ++i ) { HRESULT hr; do { hr = context->GetData( m_queries[i] , m_data.data() , UINT( m_data.size() ) , 0u ); } while ( hr == S_FALSE ); if ( hr == S_FALSE ) { result = VK_INCOMPLETE; } else if ( checkError( m_device, hr, "GetData" ) ) { if ( checkFlag( flags, VK_QUERY_RESULT_64_BIT ) ) { *reinterpret_cast< uint64_t * >( buffer ) = getUint64( 0 ); buffer += stride; } else { *reinterpret_cast< uint32_t * >( buffer ) = getUint32( 0 ); buffer += stride; } } } return result; } }
22.654362
125
0.642423
DragonJoker
d0539e7bca2dd480d666f8f4e02fbec4a66ea861
27,036
hpp
C++
include/ResourceState.hpp
procedural/d3d12_translation_layer
fc07d09db68e304b1210a7c4d7793c944dd8151f
[ "MIT" ]
1
2020-04-08T03:12:17.000Z
2020-04-08T03:12:17.000Z
include/ResourceState.hpp
procedural/d3d12_translation_layer
fc07d09db68e304b1210a7c4d7793c944dd8151f
[ "MIT" ]
null
null
null
include/ResourceState.hpp
procedural/d3d12_translation_layer
fc07d09db68e304b1210a7c4d7793c944dd8151f
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once namespace D3D12TranslationLayer { class CommandListManager; // These are defined in the private d3d12 header #define UNKNOWN_RESOURCE_STATE (D3D12_RESOURCE_STATES)0x8000u #define RESOURCE_STATE_VALID_BITS 0x2f3fff #define RESOURCE_STATE_VALID_INTERNAL_BITS 0x2fffff constexpr D3D12_RESOURCE_STATES RESOURCE_STATE_ALL_WRITE_BITS = D3D12_RESOURCE_STATE_RENDER_TARGET | D3D12_RESOURCE_STATE_UNORDERED_ACCESS | D3D12_RESOURCE_STATE_DEPTH_WRITE | D3D12_RESOURCE_STATE_STREAM_OUT | D3D12_RESOURCE_STATE_COPY_DEST | D3D12_RESOURCE_STATE_RESOLVE_DEST | D3D12_RESOURCE_STATE_VIDEO_DECODE_WRITE | D3D12_RESOURCE_STATE_VIDEO_PROCESS_WRITE; enum class SubresourceTransitionFlags { None = 0, TransitionPreDraw = 1, NoBindingTransitions = 2, StateMatchExact = 4, ForceExclusiveState = 8, NotUsedInCommandListIfNoStateChange = 0x10, }; DEFINE_ENUM_FLAG_OPERATORS(SubresourceTransitionFlags); inline bool IsD3D12WriteState(UINT State, SubresourceTransitionFlags Flags) { return (State & RESOURCE_STATE_ALL_WRITE_BITS) != 0 || (Flags & SubresourceTransitionFlags::ForceExclusiveState) != SubresourceTransitionFlags::None; } //================================================================================================================================== // CDesiredResourceState // Stores the current desired state of either an entire resource, or each subresource. //================================================================================================================================== class CDesiredResourceState { public: struct SubresourceInfo { D3D12_RESOURCE_STATES State = UNKNOWN_RESOURCE_STATE; COMMAND_LIST_TYPE CommandListType = COMMAND_LIST_TYPE::UNKNOWN; SubresourceTransitionFlags Flags = SubresourceTransitionFlags::None; }; private: bool m_bAllSubresourcesSame = true; PreallocatedArray<SubresourceInfo> m_spSubresourceInfo; public: static size_t CalcPreallocationSize(UINT SubresourceCount) { return sizeof(SubresourceInfo) * SubresourceCount; } CDesiredResourceState(UINT SubresourceCount, void*& pPreallocatedMemory) noexcept : m_spSubresourceInfo(SubresourceCount, pPreallocatedMemory) // throw( bad_alloc ) { } bool AreAllSubresourcesSame() const noexcept { return m_bAllSubresourcesSame; } SubresourceInfo const& GetSubresourceInfo(UINT SubresourceIndex) const noexcept; void SetResourceState(SubresourceInfo const& Info) noexcept; void SetSubresourceState(UINT SubresourceIndex, SubresourceInfo const& Info) noexcept; void Reset() noexcept; }; //================================================================================================================================== // CCurrentResourceState // Stores the current state of either an entire resource, or each subresource. // Current state can either be shared read across multiple queues, or exclusive on a single queue. //================================================================================================================================== class CCurrentResourceState { public: static constexpr unsigned NumCommandListTypes = static_cast<UINT>(COMMAND_LIST_TYPE::MAX_VALID); struct ExclusiveState { UINT64 FenceValue = 0; D3D12_RESOURCE_STATES State = D3D12_RESOURCE_STATE_COMMON; COMMAND_LIST_TYPE CommandListType = COMMAND_LIST_TYPE::UNKNOWN; // There are cases where we want to synchronize against last write, instead // of last access. Therefore the exclusive state of a (sub)resource is not // overwritten when transitioning to shared state, simply marked as stale. // So Map(READ) always synchronizes against the most recent exclusive state, // while Map(WRITE) always synchronizes against the most recent state, whether // it's exclusive or shared. bool IsMostRecentlyExclusiveState = true; }; struct SharedState { UINT64 FenceValues[NumCommandListTypes] = {}; D3D12_RESOURCE_STATES State[NumCommandListTypes] = {}; }; private: const bool m_bSimultaneousAccess; bool m_bAllSubresourcesSame = true; // Note: As a (minor) memory optimization, using a contiguous block of memory for exclusive + shared state. // The memory is owned by the exclusive state pointer. The shared state pointer is non-owning and possibly null. PreallocatedArray<ExclusiveState> m_spExclusiveState; PreallocatedArray<SharedState> m_pSharedState; void ConvertToSubresourceTracking() noexcept; public: static size_t CalcPreallocationSize(UINT SubresourceCount, bool bSimultaneousAccess) { return (sizeof(ExclusiveState) + (bSimultaneousAccess ? sizeof(SharedState) : 0u)) * SubresourceCount; } CCurrentResourceState(UINT SubresourceCount, bool bSimultaneousAccess, void*& pPreallocatedMemory) noexcept; bool SupportsSimultaneousAccess() const noexcept { return m_bSimultaneousAccess; } bool AreAllSubresourcesSame() const noexcept { return m_bAllSubresourcesSame; } bool IsExclusiveState(UINT SubresourceIndex) const noexcept; void SetExclusiveResourceState(ExclusiveState const& State) noexcept; void SetSharedResourceState(COMMAND_LIST_TYPE Type, UINT64 FenceValue, D3D12_RESOURCE_STATES State) noexcept; void SetExclusiveSubresourceState(UINT SubresourceIndex, ExclusiveState const& State) noexcept; void SetSharedSubresourceState(UINT SubresourceIndex, COMMAND_LIST_TYPE Type, UINT64 FenceValue, D3D12_RESOURCE_STATES State) noexcept; ExclusiveState const& GetExclusiveSubresourceState(UINT SubresourceIndex) const noexcept; SharedState const& GetSharedSubresourceState(UINT SubresourceIndex) const noexcept; UINT GetCommandListTypeMask() const noexcept; UINT GetCommandListTypeMask(CViewSubresourceSubset const& Subresources) const noexcept; UINT GetCommandListTypeMask(UINT Subresource) const noexcept; void Reset() noexcept; }; //================================================================================================================================== // DeferredWait //================================================================================================================================== struct DeferredWait { std::shared_ptr<Fence> fence; UINT64 value; }; //================================================================================================================================== // TransitionableResourceBase // A base class that transitionable resources should inherit from. //================================================================================================================================== struct TransitionableResourceBase { LIST_ENTRY m_TransitionListEntry; CDesiredResourceState m_DesiredState; const bool m_bTriggersDeferredWaits; std::vector<DeferredWait> m_DeferredWaits; static size_t CalcPreallocationSize(UINT NumSubresources) { return CDesiredResourceState::CalcPreallocationSize(NumSubresources); } TransitionableResourceBase(UINT NumSubresources, bool bTriggersDeferredWaits, void*& pPreallocatedMemory) noexcept : m_DesiredState(NumSubresources, pPreallocatedMemory) , m_bTriggersDeferredWaits(bTriggersDeferredWaits) { D3D12TranslationLayer::InitializeListHead(&m_TransitionListEntry); } ~TransitionableResourceBase() noexcept { if (IsTransitionPending()) { D3D12TranslationLayer::RemoveEntryList(&m_TransitionListEntry); } } bool IsTransitionPending() const noexcept { return !D3D12TranslationLayer::IsListEmpty(&m_TransitionListEntry); } void AddDeferredWaits(const std::vector<DeferredWait>& DeferredWaits) noexcept(false) { m_DeferredWaits.insert(m_DeferredWaits.end(), DeferredWaits.begin(), DeferredWaits.end()); // throw( bad_alloc ) } }; //================================================================================================================================== // ResourceStateManagerBase // The main business logic for handling resource transitions, including multi-queue sync and shared/exclusive state changes. // // Requesting a resource to transition simply updates destination state, and ensures it's in a list to be processed later. // // When processing ApplyAllResourceTransitions, we build up sets of vectors. // There's a source one for each command list type, and a single one for the dest because we are applying // the resource transitions for a single operation. // There's also a vector for "tentative" barriers, which are merged into the destination vector if // no flushing occurs as a result of submitting the final barrier operation. // 99% of the time, there will only be the source being populated, but sometimes there will be a destination as well. // If the source and dest of a transition require different types, we put a (source->COMMON) in the approriate source vector, // and a (COMMON->dest) in the destination vector. // // Once all resources are processed, we: // 1. Submit all source barriers, except ones belonging to the destination queue. // 2. Flush all source command lists, except ones belonging to the destination queue. // 3. Determine if the destination queue is going to be flushed. // If so: Submit source barriers on that command list first, then flush it. // If not: Accumulate source, dest, and tentative barriers so they can be sent to D3D12 in a single API call. // 4. Insert waits on the destination queue - deferred waits, and waits for work on other queues. // 5. Insert destination barriers. // // Only once all of this has been done do we update the "current" state of resources, // because this is the only way that we know whether or not the destination queue has been flushed, // and therefore, we can get the correct fence values to store in the subresources. //================================================================================================================================== class ResourceStateManagerBase { protected: LIST_ENTRY m_TransitionListHead; std::vector<DeferredWait> m_DeferredWaits; // State that is reset during the preamble, accumulated during resource traversal, // and applied during the submission phase. enum class PostApplyExclusiveState { Exclusive, Shared, SharedIfFlushed }; struct PostApplyUpdate { TransitionableResourceBase& AffectedResource; CCurrentResourceState& CurrentState; UINT SubresourceIndex; D3D12_RESOURCE_STATES NewState; PostApplyExclusiveState ExclusiveState; bool WasTransitioningToDestinationType; }; std::vector<D3D12_RESOURCE_BARRIER> m_vSrcResourceBarriers[(UINT)COMMAND_LIST_TYPE::MAX_VALID]; std::vector<D3D12_RESOURCE_BARRIER> m_vDstResourceBarriers; std::vector<D3D12_RESOURCE_BARRIER> m_vTentativeResourceBarriers; std::vector<PostApplyUpdate> m_vPostApplyUpdates; COMMAND_LIST_TYPE m_DestinationCommandListType; bool m_bApplyDeferredWaits; bool m_bFlushQueues[(UINT)COMMAND_LIST_TYPE::MAX_VALID]; UINT64 m_QueueFenceValuesToWaitOn[(UINT)COMMAND_LIST_TYPE::MAX_VALID]; ResourceStateManagerBase() noexcept(false); ~ResourceStateManagerBase() noexcept { // All resources should be gone by this point, and each resource ensures it is no longer in this list. assert(D3D12TranslationLayer::IsListEmpty(&m_TransitionListHead)); } // These methods set the destination state of the resource/subresources and ensure it's in the transition list. void TransitionResource(TransitionableResourceBase& Resource, CDesiredResourceState::SubresourceInfo const& State) noexcept; void TransitionSubresources(TransitionableResourceBase& Resource, CViewSubresourceSubset const& Subresources, CDesiredResourceState::SubresourceInfo const& State) noexcept; void TransitionSubresource(TransitionableResourceBase& Resource, UINT SubresourceIndex, CDesiredResourceState::SubresourceInfo const& State) noexcept; // Deferred waits are inserted when a transition is processing that puts applicable resources // into a write state. The command list is flushed, and these waits are inserted before the barriers. void AddDeferredWait(std::shared_ptr<Fence> const& spFence, UINT64 Value) noexcept(false); // Clear out any state from previous iterations. void ApplyResourceTransitionsPreamble() noexcept; // What to do with the resource, in the context of the transition list, after processing it. enum class TransitionResult { // There are no more pending transitions that may be processed at a later time (i.e. draw time), // so remove it from the pending transition list. Remove, // There are more transitions to be done, so keep it in the list. Keep }; // For every entry in the transition list, call a routine. // This routine must return a TransitionResult which indicates what to do with the list. template <typename TFunc> void ForEachTransitioningResource(TFunc&& func) noexcept(noexcept(func(std::declval<TransitionableResourceBase&>()))) { for (LIST_ENTRY *pListEntry = m_TransitionListHead.Flink; pListEntry != &m_TransitionListHead;) { TransitionableResourceBase* pResource = CONTAINING_RECORD(pListEntry, TransitionableResourceBase, m_TransitionListEntry); TransitionResult result = func(*pResource); auto pNextListEntry = pListEntry->Flink; if (result == TransitionResult::Remove) { D3D12TranslationLayer::RemoveEntryList(pListEntry); D3D12TranslationLayer::InitializeListHead(pListEntry); } pListEntry = pNextListEntry; } } // Updates vectors with the operations that should be applied to the requested resource. // May update the destination state of the resource. TransitionResult ProcessTransitioningResource(ID3D12Resource* pTransitioningResource, TransitionableResourceBase& TransitionableResource, CCurrentResourceState& CurrentState, CResourceBindings& BindingState, UINT NumTotalSubresources, _In_reads_((UINT)COMMAND_LIST_TYPE::MAX_VALID) const UINT64* CurrentFenceValues, bool bIsPreDraw) noexcept(false); // This method is templated so that it can have the same code for two implementations without copy/paste. // It is not intended to be completely exstensible. One implementation is leveraged by the translation layer // itself using lambdas that can be inlined. The other uses std::functions which cannot and is intended for tests. template < typename TSubmitBarriersImpl, typename TSubmitCmdListImpl, typename THasCommandsImpl, typename TGetCurrentFenceImpl, typename TInsertDeferredWaitsImpl, typename TInsertQueueWaitImpl > void SubmitResourceTransitionsImpl(TSubmitBarriersImpl&&, TSubmitCmdListImpl&&, THasCommandsImpl&&, TGetCurrentFenceImpl&&, TInsertDeferredWaitsImpl&&, TInsertQueueWaitImpl&&); // Call the D3D12 APIs to perform the resource barriers, command list submission, and command queue sync // that was determined by previous calls to ProcessTransitioningResource. void SubmitResourceTransitions(_In_reads_((UINT)COMMAND_LIST_TYPE::MAX_VALID) CommandListManager** ppManagers) noexcept(false); // Call the callbacks provided to allow tests to inspect what D3D12 APIs would've been called // as part of finalizing a set of barrier operations. void SimulateSubmitResourceTransitions(std::function<void(std::vector<D3D12_RESOURCE_BARRIER>&, COMMAND_LIST_TYPE)> SubmitBarriers, std::function<void(COMMAND_LIST_TYPE)> SubmitCmdList, std::function<bool(COMMAND_LIST_TYPE)> HasCommands, std::function<UINT64(COMMAND_LIST_TYPE)> GetCurrentFenceImpl, std::function<void(COMMAND_LIST_TYPE)> InsertDeferredWaits, std::function<void(UINT64, COMMAND_LIST_TYPE Src, COMMAND_LIST_TYPE Dst)> InsertQueueWait); // Update the current state of resources now that all barriers and sync have been done. // Callback provided to allow this information to be used by concrete implementation as well. template <typename TFunc> void PostSubmitUpdateState(TFunc&& callback, _In_reads_((UINT)COMMAND_LIST_TYPE::MAX_VALID) const UINT64* PreviousFenceValues, UINT64 NewFenceValue) { for (auto& update : m_vPostApplyUpdates) { COMMAND_LIST_TYPE UpdateCmdListType = m_DestinationCommandListType; UINT64 UpdateFenceValue = NewFenceValue; bool Flushed = m_DestinationCommandListType != COMMAND_LIST_TYPE::UNKNOWN && NewFenceValue != PreviousFenceValues[(UINT)m_DestinationCommandListType]; if (update.ExclusiveState == PostApplyExclusiveState::Exclusive || (update.ExclusiveState == PostApplyExclusiveState::SharedIfFlushed && !Flushed)) { CCurrentResourceState::ExclusiveState NewExclusiveState = {}; if (update.WasTransitioningToDestinationType) { NewExclusiveState.CommandListType = m_DestinationCommandListType; NewExclusiveState.FenceValue = NewFenceValue; } else { auto& OldExclusiveState = update.CurrentState.GetExclusiveSubresourceState(update.SubresourceIndex); UpdateCmdListType = NewExclusiveState.CommandListType = OldExclusiveState.CommandListType; UpdateFenceValue = NewExclusiveState.FenceValue = PreviousFenceValues[(UINT)OldExclusiveState.CommandListType]; } NewExclusiveState.State = update.NewState; if (update.SubresourceIndex == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES) { update.CurrentState.SetExclusiveResourceState(NewExclusiveState); } else { update.CurrentState.SetExclusiveSubresourceState(update.SubresourceIndex, NewExclusiveState); } } else if (update.WasTransitioningToDestinationType) { if (update.SubresourceIndex == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES) { update.CurrentState.SetSharedResourceState(m_DestinationCommandListType, NewFenceValue, update.NewState); } else { update.CurrentState.SetSharedSubresourceState(update.SubresourceIndex, m_DestinationCommandListType, NewFenceValue, update.NewState); } } else { continue; } callback(update, UpdateCmdListType, UpdateFenceValue); } } private: // Helpers static bool TransitionRequired(D3D12_RESOURCE_STATES CurrentState, D3D12_RESOURCE_STATES& DestinationState, SubresourceTransitionFlags Flags) noexcept; void AddCurrentStateUpdate(TransitionableResourceBase& Resource, CCurrentResourceState& CurrentState, UINT SubresourceIndex, D3D12_RESOURCE_STATES NewState, PostApplyExclusiveState ExclusiveState, bool IsGoingToDestinationType) noexcept(false); void ProcessTransitioningSubresourceExclusive(CCurrentResourceState& CurrentState, UINT i, COMMAND_LIST_TYPE curCmdListType, _In_reads_((UINT)COMMAND_LIST_TYPE::MAX_VALID) const UINT64* CurrentFenceValues, CDesiredResourceState::SubresourceInfo& SubresourceDestinationInfo, D3D12_RESOURCE_STATES after, TransitionableResourceBase& TransitionableResource, D3D12_RESOURCE_BARRIER& TransitionDesc, SubresourceTransitionFlags Flags) noexcept(false); void ProcessTransitioningSubresourceShared(CCurrentResourceState& CurrentState, UINT i, D3D12_RESOURCE_STATES after, SubresourceTransitionFlags Flags, _In_reads_((UINT)COMMAND_LIST_TYPE::MAX_VALID) const UINT64* CurrentFenceValues, COMMAND_LIST_TYPE curCmdListType, D3D12_RESOURCE_BARRIER& TransitionDesc, TransitionableResourceBase& TransitionableResource) noexcept(false); void SubmitResourceBarriers(_In_reads_(Count) D3D12_RESOURCE_BARRIER const* pBarriers, UINT Count, _In_ CommandListManager* pManager) noexcept; }; //================================================================================================================================== // ResourceStateManager // The implementation of state management tailored to the ImmediateContext and Resource classes. //================================================================================================================================== class ResourceStateManager : public ResourceStateManagerBase { private: ImmediateContext& m_ImmCtx; public: ResourceStateManager(ImmediateContext& ImmCtx) : m_ImmCtx(ImmCtx) { } // *** NOTE: DEFAULT DESTINATION IS GRAPHICS, NOT INFERRED FROM STATE BITS. *** // Transition the entire resource to a particular destination state on a particular command list. void TransitionResource(Resource* pResource, D3D12_RESOURCE_STATES State, COMMAND_LIST_TYPE DestinationCommandListType = COMMAND_LIST_TYPE::GRAPHICS, SubresourceTransitionFlags Flags = SubresourceTransitionFlags::None) noexcept; // Transition a set of subresources to a particular destination state. Fast-path provided when subset covers entire resource. void TransitionSubresources(Resource* pResource, CViewSubresourceSubset const& Subresources, D3D12_RESOURCE_STATES State, COMMAND_LIST_TYPE DestinationCommandListType = COMMAND_LIST_TYPE::GRAPHICS, SubresourceTransitionFlags Flags = SubresourceTransitionFlags::None) noexcept; // Transition a single subresource to a particular destination state. void TransitionSubresource(Resource* pResource, UINT SubresourceIndex, D3D12_RESOURCE_STATES State, COMMAND_LIST_TYPE DestinationCommandListType = COMMAND_LIST_TYPE::GRAPHICS, SubresourceTransitionFlags Flags = SubresourceTransitionFlags::None) noexcept; // Update destination state of a resource to correspond to the resource's bind points. void TransitionResourceForBindings(Resource* pResource) noexcept; // Update destination state of specified subresources to correspond to the resource's bind points. void TransitionSubresourcesForBindings(Resource* pResource, CViewSubresourceSubset const& Subresources) noexcept; // Submit all barriers and queue sync. void ApplyAllResourceTransitions(bool bIsPreDraw = false) noexcept(false); using ResourceStateManagerBase::AddDeferredWait; }; };
57.892934
160
0.593579
procedural
d05c0e47dfcfbf4580a6c245ee181ec570c96dd5
811
cpp
C++
test/MeLikeyCode-QtGameEngine-2a3d47c/qge/RangedWeapon.cpp
JamesMBallard/qmake-unity
cf5006a83e7fb1bbd173a9506771693a673d387f
[ "MIT" ]
16
2019-05-23T08:10:39.000Z
2021-12-21T11:20:37.000Z
test/MeLikeyCode-QtGameEngine-2a3d47c/qge/RangedWeapon.cpp
JamesMBallard/qmake-unity
cf5006a83e7fb1bbd173a9506771693a673d387f
[ "MIT" ]
null
null
null
test/MeLikeyCode-QtGameEngine-2a3d47c/qge/RangedWeapon.cpp
JamesMBallard/qmake-unity
cf5006a83e7fb1bbd173a9506771693a673d387f
[ "MIT" ]
2
2019-05-23T18:37:43.000Z
2021-08-24T21:29:40.000Z
#include "RangedWeapon.h" #include "Sprite.h" #include "EntitySprite.h" using namespace qge; /// Returns the point at which projectiles will be spawn. /// This point is in local coordinates (relative to the RangedWeapon itself). QPointF RangedWeapon::projectileSpawnPoint() { return this->projectileSpawnPoint_; } void RangedWeapon::setProjectileSpawnPoint(QPointF point) { this->projectileSpawnPoint_ = point; } /// Resets the projectile spawn point to be at the very center of the RangedWeapon's sprite. void RangedWeapon::resetProjectileSpawnPoint() { double length = sprite()->currentlyDisplayedFrame().width(); double width = sprite()->currentlyDisplayedFrame().height(); QPointF center; center.setX(length/2); center.setY(width/2); setProjectileSpawnPoint(center); }
26.16129
92
0.747226
JamesMBallard
d05e3e0d3573e3c438f91f523f2f6aea7cd28bd5
231
hpp
C++
chaine/src/mesh/mesh/create_triangle.hpp
the-last-willy/id3d
dc0d22e7247ac39fbc1fd8433acae378b7610109
[ "MIT" ]
null
null
null
chaine/src/mesh/mesh/create_triangle.hpp
the-last-willy/id3d
dc0d22e7247ac39fbc1fd8433acae378b7610109
[ "MIT" ]
null
null
null
chaine/src/mesh/mesh/create_triangle.hpp
the-last-willy/id3d
dc0d22e7247ac39fbc1fd8433acae378b7610109
[ "MIT" ]
null
null
null
#pragma once #include "mesh.hpp" #include "topology.hpp" #include "mesh/triangle/proxy.hpp" namespace face_vertex { inline TriangleProxy create_triangle(Mesh& m) { return proxy(m, index(create_triangle(topology(m)))); } }
14.4375
57
0.731602
the-last-willy
d05fd6b7b0023145cccda237ec0572e8b738aa7b
1,550
hpp
C++
ufora/FORA/TypedFora/ABI/ArbitraryNativeConstantForCSTValue.hpp
ufora/ufora
04db96ab049b8499d6d6526445f4f9857f1b6c7e
[ "Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause" ]
571
2015-11-05T20:07:07.000Z
2022-01-24T22:31:09.000Z
ufora/FORA/TypedFora/ABI/ArbitraryNativeConstantForCSTValue.hpp
timgates42/ufora
04db96ab049b8499d6d6526445f4f9857f1b6c7e
[ "Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause" ]
218
2015-11-05T20:37:55.000Z
2021-05-30T03:53:50.000Z
ufora/FORA/TypedFora/ABI/ArbitraryNativeConstantForCSTValue.hpp
timgates42/ufora
04db96ab049b8499d6d6526445f4f9857f1b6c7e
[ "Apache-2.0", "CC0-1.0", "MIT", "BSL-1.0", "BSD-3-Clause" ]
40
2015-11-07T21:42:19.000Z
2021-05-23T03:48:19.000Z
/*************************************************************************** Copyright 2015 Ufora Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ****************************************************************************/ #pragma once #include "../../Native/NativeCode.hppml" #include "../../Native/ArbitraryNativeConstant.hpp" #include "../../Core/CSTValue.hppml" namespace TypedFora { namespace Abi { class ArbitraryNativeConstantForCSTValueType; class ArbitraryNativeConstantForCSTValue : public ArbitraryNativeConstant { public: ArbitraryNativeConstantForCSTValue(const CSTValue& in, bool asImplval); ArbitraryNativeConstantType* type(); NativeType nativeType(); void* pointerToData(); std::string description(); hash_type hash(); static NativeExpression expressionForCSTValueTyped(const CSTValue& in); static NativeExpression expressionForCSTValueAsImplval(const CSTValue& in); private: friend class ArbitraryNativeConstantForCSTValueType; ImplVal mReference; CSTValue mValue; bool mAsImplval; }; } }
26.271186
77
0.696129
ufora
d0620f145594274dab3e17380e893ce23bf4a984
2,440
cpp
C++
src/ui/contacts/VKUContactsPanel.cpp
igorglotov/tizen-vk-client
de213ede7185818285f78abad36592bc864f76cc
[ "Unlicense" ]
null
null
null
src/ui/contacts/VKUContactsPanel.cpp
igorglotov/tizen-vk-client
de213ede7185818285f78abad36592bc864f76cc
[ "Unlicense" ]
null
null
null
src/ui/contacts/VKUContactsPanel.cpp
igorglotov/tizen-vk-client
de213ede7185818285f78abad36592bc864f76cc
[ "Unlicense" ]
null
null
null
#include "AppResourceId.h" #include "VKUContactsPanel.h" #include "VKUApi.h" #include "UsersPanel.h" #include "SceneRegister.h" #include "ObjectCounter.h" using namespace Tizen::Base; using namespace Tizen::Ui; using namespace Tizen::Ui::Controls; using namespace Tizen::Ui::Scenes; using namespace Tizen::Base::Collection; using namespace Tizen::Web::Json; VKUContactsPanel::VKUContactsPanel(void) { CONSTRUCT(L"VKUContactsPanel"); // pProvider = new ContactsTableProvider(); } VKUContactsPanel::~VKUContactsPanel(void) { DESTRUCT(L"VKUContactsPanel"); // delete pProvider; } bool VKUContactsPanel::Initialize() { Panel::Construct(IDC_PANEL_CONTACTS); return true; } result VKUContactsPanel::OnInitializing(void) { result r = E_SUCCESS; Integer userIdInt = Integer(VKUAuthConfig::GetUserId()); _usersPanel = new UsersPanel(); _usersPanel->Construct(GetBounds()); r = AddControl(_usersPanel); _usersPanel->AddUserSelectedListener(this); Form * form = dynamic_cast<Form *>(GetParent()); RelativeLayout * layout = dynamic_cast<RelativeLayout *>(form->GetLayoutN()); layout->SetVerticalFitPolicy(*this, FIT_POLICY_PARENT); return r; } result VKUContactsPanel::OnTerminating(void) { result r = E_SUCCESS; // TODO: Add your termination code here return r; } void VKUContactsPanel::ClearItems() { AppLog("CONTACTSEVENT: scene deactivated"); // GroupedTableView* pTable = static_cast<GroupedTableView*>(GetControl(IDC_GROUPEDTABLEVIEW1)); // pTable->Invalidate(true); } void VKUContactsPanel::OnSceneActivatedN(const Tizen::Ui::Scenes::SceneId& previousSceneId, const Tizen::Ui::Scenes::SceneId& currentSceneId, Tizen::Base::Collection::IList* pArgs) { AppLog("contacts activated"); _usersPanel->RequestModel(MODEL_TYPE_FRIENDS_ALPHA); } void VKUContactsPanel::OnSceneDeactivated(const Tizen::Ui::Scenes::SceneId& currentSceneId, const Tizen::Ui::Scenes::SceneId& nextSceneId) { AppLog("contacts deactivated"); _usersPanel->ClearModel(); } void VKUContactsPanel::OnUserSelected(const Tizen::Web::Json::JsonObject * userJson) { SceneManager* pSceneManager = SceneManager::GetInstance(); AppAssert(pSceneManager); ArrayList* pList = new (std::nothrow) ArrayList(SingleObjectDeleter); pList->Construct(1); pList->Add(userJson->CloneN()); pSceneManager->GoForward(ForwardSceneTransition(SCENE_USER, SCENE_TRANSITION_ANIMATION_TYPE_LEFT, SCENE_HISTORY_OPTION_ADD_HISTORY), pList); }
27.727273
141
0.766803
igorglotov
d0622848b7eb8afef2a3a200338bcddad81d9cca
19,655
cpp
C++
pwiz/analysis/spectrum_processing/SpectrumList_FilterTest.cpp
shze/pwizard-deb
4822829196e915525029a808470f02d24b8b8043
[ "Apache-2.0" ]
2
2019-12-28T21:24:36.000Z
2020-04-18T03:52:05.000Z
pwiz/analysis/spectrum_processing/SpectrumList_FilterTest.cpp
shze/pwizard-deb
4822829196e915525029a808470f02d24b8b8043
[ "Apache-2.0" ]
null
null
null
pwiz/analysis/spectrum_processing/SpectrumList_FilterTest.cpp
shze/pwizard-deb
4822829196e915525029a808470f02d24b8b8043
[ "Apache-2.0" ]
null
null
null
// // $Id: SpectrumList_FilterTest.cpp 10462 2017-02-10 17:52:32Z chambm $ // // // Original author: Darren Kessner <darren@proteowizard.org> // // Copyright 2008 Spielberg Family Center for Applied Proteomics // Cedars-Sinai Medical Center, Los Angeles, California 90048 // // 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 "SpectrumList_Filter.hpp" #include "pwiz/utility/misc/unit.hpp" #include "pwiz/utility/misc/IntegerSet.hpp" #include "pwiz/utility/misc/Std.hpp" #include "pwiz/data/msdata/examples.hpp" #include "pwiz/data/msdata/Serializer_mzML.hpp" #include <cstring> using namespace pwiz; using namespace pwiz::msdata; using namespace pwiz::analysis; using namespace pwiz::util; using boost::logic::tribool; ostream* os_ = 0; void printSpectrumList(const SpectrumList& sl, ostream& os) { os << "size: " << sl.size() << endl; for (size_t i=0, end=sl.size(); i<end; i++) { SpectrumPtr spectrum = sl.spectrum(i, false); os << spectrum->index << " " << spectrum->id << " " << "ms" << spectrum->cvParam(MS_ms_level).value << " " << "scanEvent:" << spectrum->scanList.scans[0].cvParam(MS_preset_scan_configuration).value << " " << "scanTime:" << spectrum->scanList.scans[0].cvParam(MS_scan_start_time).timeInSeconds() << " " << endl; } } SpectrumListPtr createSpectrumList() { SpectrumListSimplePtr sl(new SpectrumListSimple); for (size_t i=0; i<10; ++i) { SpectrumPtr spectrum(new Spectrum); spectrum->index = i; spectrum->id = "scan=" + lexical_cast<string>(100+i); spectrum->setMZIntensityPairs(vector<MZIntensityPair>(i), MS_number_of_detector_counts); // add mz/intensity to the spectra for mzPresent filter vector<MZIntensityPair> mzint(i*2); for (size_t j=1.0; j<i*2; ++j) { mzint.insert(mzint.end(), MZIntensityPair(j*100, j*j)); } spectrum->setMZIntensityPairs(mzint, MS_number_of_detector_counts); bool isMS1 = i%3==0; spectrum->set(MS_ms_level, isMS1 ? 1 : 2); spectrum->set(isMS1 ? MS_MS1_spectrum : MS_MSn_spectrum); // outfit the spectra with mass analyzer definitions to test the massAnalyzer filter spectrum->scanList.scans.push_back(Scan()); spectrum->scanList.scans[0].instrumentConfigurationPtr = InstrumentConfigurationPtr(new InstrumentConfiguration()); InstrumentConfigurationPtr p = spectrum->scanList.scans[0].instrumentConfigurationPtr; if (i%3 == 0) { p->componentList.push_back(Component(MS_orbitrap, 0/*order*/)); } else { if (i%2) p->componentList.push_back(Component(MS_orbitrap, 0/*order*/)); else p->componentList.push_back(Component(MS_radial_ejection_linear_ion_trap, 0/*order*/)); } if (i%3 != 0) spectrum->precursors.push_back(Precursor(500, 3)); // add precursors and activation types to the MS2 spectra if (i==1 || i ==5) // ETD { spectrum->precursors[0].activation.set(MS_electron_transfer_dissociation); } else if (i==2) // CID { spectrum->precursors[0].activation.set(MS_collision_induced_dissociation); } else if (i==4) // HCD { spectrum->precursors[0].activation.set(MS_HCD); } else if (i==8) // IRMPD { spectrum->precursors[0].activation.set(MS_IRMPD); } else if (i==7) // ETD + SA { spectrum->precursors[0].activation.set(MS_electron_transfer_dissociation); spectrum->precursors[0].activation.set(MS_collision_induced_dissociation); } spectrum->scanList.scans.push_back(Scan()); spectrum->scanList.scans[0].set(MS_preset_scan_configuration, i%4); spectrum->scanList.scans[0].set(MS_scan_start_time, 420+i, UO_second); sl->spectra.push_back(spectrum); } if (os_) { *os_ << "original spectrum list:\n"; printSpectrumList(*sl, *os_); *os_ << endl; } return sl; } struct EvenPredicate : public SpectrumList_Filter::Predicate { virtual tribool accept(const SpectrumIdentity& spectrumIdentity) const { return spectrumIdentity.index%2 == 0; } }; void testEven(SpectrumListPtr sl) { if (os_) *os_ << "testEven:\n"; SpectrumList_Filter filter(sl, EvenPredicate()); if (os_) { printSpectrumList(filter, *os_); *os_ << endl; } unit_assert(filter.size() == 5); for (size_t i=0, end=filter.size(); i<end; i++) { const SpectrumIdentity& id = filter.spectrumIdentity(i); unit_assert(id.index == i); unit_assert(id.id == "scan=" + lexical_cast<string>(100+i*2)); SpectrumPtr spectrum = filter.spectrum(i); unit_assert(spectrum->index == i); unit_assert(spectrum->id == "scan=" + lexical_cast<string>(100+i*2)); } } struct EvenMS2Predicate : public SpectrumList_Filter::Predicate { virtual tribool accept(const SpectrumIdentity& spectrumIdentity) const { if (spectrumIdentity.index%2 != 0) return false; return boost::logic::indeterminate; } virtual tribool accept(const Spectrum& spectrum) const { CVParam param = spectrum.cvParamChild(MS_spectrum_type); if (param.cvid == CVID_Unknown) return boost::logic::indeterminate; if (!cvIsA(param.cvid, MS_mass_spectrum)) return true; // MS level filter doesn't affect non-MS spectra param = spectrum.cvParam(MS_ms_level); if (param.cvid == CVID_Unknown) return boost::logic::indeterminate; return (param.valueAs<int>() == 2); } }; void testEvenMS2(SpectrumListPtr sl) { if (os_) *os_ << "testEvenMS2:\n"; SpectrumList_Filter filter(sl, EvenMS2Predicate()); if (os_) { printSpectrumList(filter, *os_); *os_ << endl; } unit_assert(filter.size() == 3); unit_assert(filter.spectrumIdentity(0).id == "scan=102"); unit_assert(filter.spectrumIdentity(1).id == "scan=104"); unit_assert(filter.spectrumIdentity(2).id == "scan=108"); } struct SelectedIndexPredicate : public SpectrumList_Filter::Predicate { mutable bool pastMaxIndex; SelectedIndexPredicate() : pastMaxIndex(false) {} virtual tribool accept(const SpectrumIdentity& spectrumIdentity) const { if (spectrumIdentity.index>5) pastMaxIndex = true; return (spectrumIdentity.index==1 || spectrumIdentity.index==3 || spectrumIdentity.index==5); } virtual bool done() const { return pastMaxIndex; } }; void testSelectedIndices(SpectrumListPtr sl) { if (os_) *os_ << "testSelectedIndices:\n"; SpectrumList_Filter filter(sl, SelectedIndexPredicate()); if (os_) { printSpectrumList(filter, *os_); *os_ << endl; } unit_assert(filter.size() == 3); unit_assert(filter.spectrumIdentity(0).id == "scan=101"); unit_assert(filter.spectrumIdentity(1).id == "scan=103"); unit_assert(filter.spectrumIdentity(2).id == "scan=105"); } struct HasBinaryDataPredicate : public SpectrumList_Filter::Predicate { HasBinaryDataPredicate(DetailLevel suggestedDetailLevel) : detailLevel_(suggestedDetailLevel) {} DetailLevel detailLevel_; virtual DetailLevel suggestedDetailLevel() const {return detailLevel_;} virtual tribool accept(const msdata::SpectrumIdentity& spectrumIdentity) const { return boost::logic::indeterminate; } virtual tribool accept(const Spectrum& spectrum) const { if (spectrum.binaryDataArrayPtrs.empty()) return boost::logic::indeterminate; return !spectrum.binaryDataArrayPtrs[0]->data.empty(); } }; void testHasBinaryData(SpectrumListPtr sl) { if (os_) *os_ << "testHasBinaryData:\n"; MSData msd; examples::initializeTiny(msd); shared_ptr<stringstream> ss(new stringstream); Serializer_mzML serializer; serializer.write(*ss, msd); MSData msd2; serializer.read(ss, msd2); sl = msd2.run.spectrumListPtr; { SpectrumList_Filter filter(sl, HasBinaryDataPredicate(DetailLevel_FullMetadata)); unit_assert(filter.empty()); } { SpectrumList_Filter filter(sl, HasBinaryDataPredicate(DetailLevel_FullData)); if (os_) { printSpectrumList(filter, *os_); *os_ << endl; } unit_assert_operator_equal(4, filter.size()); } } void testIndexSet(SpectrumListPtr sl) { if (os_) *os_ << "testIndexSet:\n"; IntegerSet indexSet; indexSet.insert(3,5); indexSet.insert(7); indexSet.insert(9); SpectrumList_Filter filter(sl, SpectrumList_FilterPredicate_IndexSet(indexSet)); if (os_) { printSpectrumList(filter, *os_); *os_ << endl; } unit_assert(filter.size() == 5); unit_assert(filter.spectrumIdentity(0).id == "scan=103"); unit_assert(filter.spectrumIdentity(1).id == "scan=104"); unit_assert(filter.spectrumIdentity(2).id == "scan=105"); unit_assert(filter.spectrumIdentity(3).id == "scan=107"); unit_assert(filter.spectrumIdentity(4).id == "scan=109"); } void testScanNumberSet(SpectrumListPtr sl) { if (os_) *os_ << "testScanNumberSet:\n"; IntegerSet scanNumberSet; scanNumberSet.insert(102,104); scanNumberSet.insert(107); SpectrumList_Filter filter(sl, SpectrumList_FilterPredicate_ScanNumberSet(scanNumberSet)); if (os_) { printSpectrumList(filter, *os_); *os_ << endl; } unit_assert(filter.size() == 4); unit_assert(filter.spectrumIdentity(0).id == "scan=102"); unit_assert(filter.spectrumIdentity(1).id == "scan=103"); unit_assert(filter.spectrumIdentity(2).id == "scan=104"); unit_assert(filter.spectrumIdentity(3).id == "scan=107"); } void testScanEventSet(SpectrumListPtr sl) { if (os_) *os_ << "testScanEventSet:\n"; IntegerSet scanEventSet; scanEventSet.insert(0,0); scanEventSet.insert(2,3); SpectrumList_Filter filter(sl, SpectrumList_FilterPredicate_ScanEventSet(scanEventSet)); if (os_) { printSpectrumList(filter, *os_); *os_ << endl; } unit_assert(filter.size() == 7); unit_assert(filter.spectrumIdentity(0).id == "scan=100"); unit_assert(filter.spectrumIdentity(1).id == "scan=102"); unit_assert(filter.spectrumIdentity(2).id == "scan=103"); unit_assert(filter.spectrumIdentity(3).id == "scan=104"); unit_assert(filter.spectrumIdentity(4).id == "scan=106"); unit_assert(filter.spectrumIdentity(5).id == "scan=107"); unit_assert(filter.spectrumIdentity(6).id == "scan=108"); } void testScanTimeRange(SpectrumListPtr sl) { if (os_) *os_ << "testScanTimeRange:\n"; const double low = 422.5; const double high = 427.5; SpectrumList_Filter filter(sl, SpectrumList_FilterPredicate_ScanTimeRange(low, high)); if (os_) { printSpectrumList(filter, *os_); *os_ << endl; } unit_assert(filter.size() == 5); unit_assert(filter.spectrumIdentity(0).id == "scan=103"); unit_assert(filter.spectrumIdentity(1).id == "scan=104"); unit_assert(filter.spectrumIdentity(2).id == "scan=105"); unit_assert(filter.spectrumIdentity(3).id == "scan=106"); unit_assert(filter.spectrumIdentity(4).id == "scan=107"); } void testMSLevelSet(SpectrumListPtr sl) { if (os_) *os_ << "testMSLevelSet:\n"; IntegerSet msLevelSet; msLevelSet.insert(1); SpectrumList_Filter filter(sl, SpectrumList_FilterPredicate_MSLevelSet(msLevelSet)); if (os_) { printSpectrumList(filter, *os_); *os_ << endl; } unit_assert(filter.size() == 4); unit_assert(filter.spectrumIdentity(0).id == "scan=100"); unit_assert(filter.spectrumIdentity(1).id == "scan=103"); unit_assert(filter.spectrumIdentity(2).id == "scan=106"); unit_assert(filter.spectrumIdentity(3).id == "scan=109"); IntegerSet msLevelSet2; msLevelSet2.insert(2); SpectrumList_Filter filter2(sl, SpectrumList_FilterPredicate_MSLevelSet(msLevelSet2)); if (os_) { printSpectrumList(filter2, *os_); *os_ << endl; } unit_assert(filter2.size() == 6); unit_assert(filter2.spectrumIdentity(0).id == "scan=101"); unit_assert(filter2.spectrumIdentity(1).id == "scan=102"); unit_assert(filter2.spectrumIdentity(2).id == "scan=104"); unit_assert(filter2.spectrumIdentity(3).id == "scan=105"); unit_assert(filter2.spectrumIdentity(4).id == "scan=107"); unit_assert(filter2.spectrumIdentity(5).id == "scan=108"); } void testMS2Activation(SpectrumListPtr sl) { if (os_) *os_ << "testMS2Activation:\n"; SpectrumListPtr ms2filter(new SpectrumList_Filter(sl, SpectrumList_FilterPredicate_MSLevelSet(IntegerSet(2)))); set<CVID> cvIDs; // CID cvIDs.insert(MS_electron_transfer_dissociation); cvIDs.insert(MS_HCD); cvIDs.insert(MS_IRMPD); SpectrumList_Filter filter(ms2filter, SpectrumList_FilterPredicate_ActivationType(cvIDs, true)); if (os_) { printSpectrumList(filter, *os_); *os_ << endl; } unit_assert(filter.size() == 1); unit_assert(filter.spectrumIdentity(0).id == "scan=102"); // ETD + SA cvIDs.clear(); cvIDs.insert(MS_electron_transfer_dissociation); cvIDs.insert(MS_collision_induced_dissociation); SpectrumList_Filter filter1(ms2filter, SpectrumList_FilterPredicate_ActivationType(cvIDs, false)); if (os_) { printSpectrumList(filter1, *os_); *os_ << endl; } unit_assert(filter1.size() == 1); unit_assert(filter1.spectrumIdentity(0).id == "scan=107"); // ETD cvIDs.clear(); cvIDs.insert(MS_electron_transfer_dissociation); SpectrumList_Filter filter2(ms2filter, SpectrumList_FilterPredicate_ActivationType(cvIDs, false)); if (os_) { printSpectrumList(filter2, *os_); *os_ << endl; } unit_assert(filter2.size() == 3); unit_assert(filter2.spectrumIdentity(0).id == "scan=101"); unit_assert(filter2.spectrumIdentity(1).id == "scan=105"); unit_assert(filter2.spectrumIdentity(2).id == "scan=107"); // HCD cvIDs.clear(); cvIDs.insert(MS_HCD); SpectrumList_Filter filter3(ms2filter, SpectrumList_FilterPredicate_ActivationType(cvIDs, false)); if (os_) { printSpectrumList(filter3, *os_); *os_ << endl; } unit_assert(filter3.size() == 1); unit_assert(filter3.spectrumIdentity(0).id == "scan=104"); // IRMPD cvIDs.clear(); cvIDs.insert(MS_IRMPD); SpectrumList_Filter filter4(ms2filter, SpectrumList_FilterPredicate_ActivationType(cvIDs, false)); if (os_) { printSpectrumList(filter4, *os_); *os_ << endl; } unit_assert(filter4.size() == 1); unit_assert(filter4.spectrumIdentity(0).id == "scan=108"); } void testMassAnalyzerFilter(SpectrumListPtr sl) { if (os_) *os_ << "testMassAnalyzerFilter:\n"; set<CVID> cvIDs; // msconvert mass analyzer filter FTMS option cvIDs.insert(MS_orbitrap); cvIDs.insert(MS_fourier_transform_ion_cyclotron_resonance_mass_spectrometer); SpectrumList_Filter filter(sl, SpectrumList_FilterPredicate_AnalyzerType(cvIDs)); if (os_) { printSpectrumList(filter, *os_); *os_ << endl; } unit_assert(filter.size() == 7); unit_assert(filter.spectrumIdentity(0).id == "scan=100"); cvIDs.clear(); // msconvert mass analyzer filter ITMS option cvIDs.insert(MS_ion_trap); SpectrumList_Filter filter1(sl, SpectrumList_FilterPredicate_AnalyzerType(cvIDs)); if (os_) { printSpectrumList(filter1, *os_); *os_ << endl; } unit_assert(filter1.size() == 3); unit_assert(filter1.spectrumIdentity(0).id == "scan=102"); } void testMZPresentFilter(SpectrumListPtr sl) { if (os_) *os_ << "testMZPresentFilter:\n"; // test mzpresent on MS level 2 (include test) SpectrumListPtr ms2filter(new SpectrumList_Filter(sl, SpectrumList_FilterPredicate_MSLevelSet(IntegerSet(2)))); chemistry::MZTolerance mzt(3.0); std::set<double> mzSet; mzSet.insert(200.0); mzSet.insert(300.0); mzSet.insert(400.0); double threshold = 10; IntegerSet msLevels(1, INT_MAX); ThresholdFilter tf(ThresholdFilter::ThresholdingBy_Count, threshold, ThresholdFilter::Orientation_MostIntense, msLevels); SpectrumList_Filter filter(ms2filter, SpectrumList_FilterPredicate_MzPresent(mzt, mzSet, tf, SpectrumList_Filter::Predicate::FilterMode_Include)); if (os_) { printSpectrumList(filter, *os_); *os_ << endl; } unit_assert_operator_equal(4, filter.size()); unit_assert_operator_equal("scan=102", filter.spectrumIdentity(0).id); unit_assert_operator_equal("scan=104", filter.spectrumIdentity(1).id); unit_assert_operator_equal("scan=105", filter.spectrumIdentity(2).id); unit_assert_operator_equal("scan=107", filter.spectrumIdentity(3).id); // test mz present on MS level 1 (exclude test) SpectrumListPtr ms1filter(new SpectrumList_Filter(sl, SpectrumList_FilterPredicate_MSLevelSet(IntegerSet(1)))); chemistry::MZTolerance mzt1(3.0); std::set<double> mzSet1; mzSet1.insert(200.0); mzSet1.insert(300.0); double threshold1 = 5; ThresholdFilter tf1(ThresholdFilter::ThresholdingBy_Count, threshold1, ThresholdFilter::Orientation_MostIntense, msLevels); SpectrumList_Filter filter1(ms1filter, SpectrumList_FilterPredicate_MzPresent(mzt1, mzSet1, tf1, SpectrumList_Filter::Predicate::FilterMode_Exclude)); if (os_) { printSpectrumList(filter1, *os_); *os_ << endl; } unit_assert_operator_equal(3, filter1.size()); unit_assert_operator_equal("scan=100", filter1.spectrumIdentity(0).id); unit_assert_operator_equal("scan=106", filter1.spectrumIdentity(1).id); unit_assert_operator_equal("scan=109", filter1.spectrumIdentity(2).id); } void test() { SpectrumListPtr sl = createSpectrumList(); testEven(sl); testEvenMS2(sl); testSelectedIndices(sl); testHasBinaryData(sl); testIndexSet(sl); testScanNumberSet(sl); testScanEventSet(sl); testScanTimeRange(sl); testMSLevelSet(sl); testMS2Activation(sl); testMassAnalyzerFilter(sl); testMZPresentFilter(sl); } int main(int argc, char* argv[]) { TEST_PROLOG(argc, argv) try { if (argc>1 && !strcmp(argv[1],"-v")) os_ = &cout; test(); } catch (exception& e) { TEST_FAILED(e.what()) } catch (...) { TEST_FAILED("Caught unknown exception.") } TEST_EPILOG }
29.379671
154
0.654846
shze
d06472c7490413f30aa3bc094faa073afb2a4f1d
14,820
cpp
C++
src/mruntime/GlobalEventReceiver.cpp
0of/WebOS-Magna
a0fe2c9708fd4dd07928c11fcb03fb29fdd2d511
[ "Apache-2.0" ]
1
2016-03-26T13:25:08.000Z
2016-03-26T13:25:08.000Z
src/mruntime/GlobalEventReceiver.cpp
0of/WebOS-Magna
a0fe2c9708fd4dd07928c11fcb03fb29fdd2d511
[ "Apache-2.0" ]
null
null
null
src/mruntime/GlobalEventReceiver.cpp
0of/WebOS-Magna
a0fe2c9708fd4dd07928c11fcb03fb29fdd2d511
[ "Apache-2.0" ]
null
null
null
#include "GlobalEventReceiver.h" #include "OSRenderBehaviourNotifier.h" #include "OSAttachControllersBehaviourNotifier.h" #include "OSDetachControllersBehaviourNotifier.h" #include "OSScriptRunBehaviourNotifier.h" #include "OSWindowCloseBehaviourNotifier.h" #include "OSStartWindowBehaviourNotifier.h" #include "OSStartApplicationBehaviourNotifier.h" #include "OSQtWidgetInitBehaviourNotifier.h" #include "RuntimeScript.h" #include "ApplicationLoader.h" #include "WindowManager.h" #include "SystemComObjectManager.h" using namespace Magna::SystemComponent; #include <QApplication> namespace Magna{ namespace Runtime{ GlobalEventReceiver& GlobalEventReceiver::getGlobalEventReceiver(){ OSBehaviourNotifierHandler & _handler = OSBehaviourNotifierHandler::getOSBehaviourNotifierHandler(); static SharedPtr<GlobalEventReceiver> eventReceiver = new GlobalEventReceiver( &_handler ); return *eventReceiver; } GlobalEventReceiver::GlobalEventReceiver(OSBehaviourNotifierHandler *handler ) :m_mutex() ,m_handler( handler ){ } GlobalEventReceiver::~GlobalEventReceiver(){ } void GlobalEventReceiver::requestWindowMoved(const unicode_char *id, const IntegerDyadCoordinate& coord ){ QString _movedScript = QString( RuntimeScript::shared_JavaScript_Service_Provider_Window ); _movedScript.append( RuntimeScript::shared_JavaScript_Service_set_window_pos ) .append( "(" ) #ifdef _MSC_VER .append( QString::fromUtf16( reinterpret_cast<const ushort *>( id ) ) ) #else .append( QString::fromStdWString( id ) ) #endif .append( "," ) .append( QString::number( coord.getX() ) ) .append( "," ) .append( QString::number( coord.getY() ) ) .append( ");" ); OSScriptRunBehaviourNotifier *notifier = new OSScriptRunBehaviourNotifier( _movedScript ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); } void GlobalEventReceiver::requestDraggableWindowMove( const unicode_char *id, const IntegerDyadCoordinate& trigger_coord, const IntegerDyadCoordinate& offset ){ QString _movedScript = QString( RuntimeScript::shared_JavaScript_Functionality_Window_Rubber_Band ); _movedScript.append( RuntimeScript::shared_JavaScript_Functionality_trigger_translate ) .append( "(" ) #ifdef _MSC_VER .append( QString::fromUtf16( reinterpret_cast<const ushort *>( id ) ) ) #else .append( QString::fromStdWString( id ) ) #endif .append( "," ) .append( QString::number( trigger_coord.getX() ) ) .append( "," ) .append( QString::number( trigger_coord.getY() ) ) .append( "," ) .append( QString::number( offset.getX()) ) .append( "," ) .append( QString::number( offset.getY() ) ) .append( ");" ); OSScriptRunBehaviourNotifier *notifier = new OSScriptRunBehaviourNotifier( _movedScript ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); } void GlobalEventReceiver::requestWindowResized( const unicode_char *id, const IntegerSize& size){ QString _resizedScript = QString( RuntimeScript::shared_JavaScript_Service_Provider_Window ); _resizedScript.append( RuntimeScript::shared_JavaScript_Service_set_window_size ) .append( "(" ) #ifdef _MSC_VER .append( QString::fromUtf16( reinterpret_cast<const ushort *>( id ) ) ) #else .append( QString::fromStdWString( id ) ) #endif .append( "," ) .append( QString::number( size.getWidth() ) ) .append( "," ) .append( QString::number( size.getHeight() ) ) .append( ");" ); OSScriptRunBehaviourNotifier *notifier = new OSScriptRunBehaviourNotifier( _resizedScript ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); } void GlobalEventReceiver::requestWindowRendering( ManipulateEngine& engine ){ OSRenderBehaviourNotifier *notifier = new OSRenderBehaviourNotifier( engine ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); } void GlobalEventReceiver::requestControllersAttached( std::vector<SharedPtr<Controller::ControllerRoot> > & ctrls ,RunnableContext * context){ OSAttachControllersBehaviourNotifier *notifier = new OSAttachControllersBehaviourNotifier( context, ctrls ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); } void GlobalEventReceiver::requestControllersDetached( const std::vector< uint64 > & ids) { OSDetachControllersBehaviourNotifier *notifier = new OSDetachControllersBehaviourNotifier( ids ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); } void GlobalEventReceiver::requestWindowClose( uint32 id) { OSWindowCloseBehaviourNotifier *notifier = new OSWindowCloseBehaviourNotifier( id ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); } void GlobalEventReceiver::requestWindowVisibilityChanged( const unicode_char *id, bool isVisible) { QString visibScript = QString( RuntimeScript::shared_JavaScript_Service_Provider_Window ); if( isVisible ){ visibScript.append( RuntimeScript::shared_JavaScript_Service_set_window_visible ) .append( "(" ) #ifdef _MSC_VER .append( QString::fromUtf16( reinterpret_cast<const ushort *>( id ) ) ) #else .append( QString::fromStdWString( id ) ) #endif .append( ");" ); } else{ visibScript.append( RuntimeScript::shared_JavaScript_Service_set_window_hidden ) .append( "(" ) #ifdef _MSC_VER .append( QString::fromUtf16( reinterpret_cast<const ushort *>( id ) ) ) #else .append( QString::fromStdWString( id ) ) #endif .append( ");" ); } OSScriptRunBehaviourNotifier *notifier = new OSScriptRunBehaviourNotifier( visibScript ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); } void GlobalEventReceiver::requestWindowFocusChanged( const unicode_char * _id, uint32 _int_id, bool isFocusIn ) { //focus script QString focusScript = QString( RuntimeScript::shared_JavaScript_Service_Provider_Window ); if( isFocusIn ){ focusScript.append( RuntimeScript::shared_JavaScript_Service_window_focus_in ) .append( "(" ) #ifdef _MSC_VER .append( QString::fromUtf16( reinterpret_cast<const ushort *>( _id ) ) ) #else .append( QString::fromStdWString( _id ) ) #endif .append( ");" ); } else{ focusScript.append( RuntimeScript::shared_JavaScript_Service_window_focus_out ) .append( "(" ) #ifdef _MSC_VER .append( QString::fromUtf16( reinterpret_cast<const ushort *>( _id ) ) ) #else .append( QString::fromStdWString( _id ) ) #endif .append( ");" ); } OSScriptRunBehaviourNotifier *notifier = new OSScriptRunBehaviourNotifier( focusScript ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); auto & _coms_manager = SystemComObjectManager::getSystemComObjectManager(); _coms_manager.getDesktopObject().actDispatchWindowFocusChanged( _int_id, isFocusIn ); } void GlobalEventReceiver::requestStartPopOutWindow( const SharedPtr<Window::WindowRoot>& w) { if( !w.isNull() && w->m_requester != Nullptr && w->m_RunnableContext != Nullptr ){ OSStartWindowBehaviourNotifier*notifier = new OSStartWindowBehaviourNotifier( w, WindowManager::WindowType_PopOut ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); } } void GlobalEventReceiver::requestStartNewWindow( const SharedPtr<Window::WindowRoot>& w ) { if( !w.isNull() && w->m_requester != Nullptr && w->m_RunnableContext != Nullptr ){ OSStartWindowBehaviourNotifier*notifier = new OSStartWindowBehaviourNotifier( w, WindowManager::WindowType_Normal ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); } } void GlobalEventReceiver::requestStartNewApplication( const String& p, RunnableContext * r ) { OSStartApplicationBehaviourNotifier *notifier = new OSStartApplicationBehaviourNotifier( false, p, r ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); } void GlobalEventReceiver::requestScriptEval( const String& sc ){ if( !sc.empty() ){ #ifdef _MSC_VER QString _sc = QString::fromUtf16( reinterpret_cast<const ushort *>( sc.c_str() ), sc.size() ) ; #else QString _sc = QString::fromStdWString( sc ) ; #endif OSScriptRunBehaviourNotifier *notifier = new OSScriptRunBehaviourNotifier( _sc ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); } } void GlobalEventReceiver::askObtainApplicationInfo( const String& a1, String& a2, String& a3){ auto &_loader = ApplicationLoader::obtainLoader(); _loader.loadApplicationExpInfo( a1, a2, a3 ); } void GlobalEventReceiver::requestStartNewApplicationWithDialog( const String& p, RunnableContext * r ) { OSStartApplicationBehaviourNotifier *notifier = new OSStartApplicationBehaviourNotifier( !false, p, r ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); } void GlobalEventReceiver::requestControllerResized( const unicode_char *id, const IntegerSize& size ) { QString resized_sc = QString( RuntimeScript::shared_JavaScript_Service_Provider_Controller ); resized_sc.append( RuntimeScript::shared_JavaScript_Service_controller_resize ) .append( "(" ) #ifdef _MSC_VER .append( QString::fromUtf16( reinterpret_cast<const ushort *>( id ) ) ) #else .append( QString::fromStdWString( id ) ) #endif .append( "," ) .append( QString::number( size.getWidth() ) ) .append( "," ) .append( QString::number( size.getHeight() ) ) .append( ");" ); OSScriptRunBehaviourNotifier *notifier = new OSScriptRunBehaviourNotifier( resized_sc ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); } void GlobalEventReceiver::requestControllerMoved( const unicode_char *id, const IntegerDyadCoordinate& coord ) { QString moved_sc = QString( RuntimeScript::shared_JavaScript_Service_Provider_Controller ); moved_sc.append( RuntimeScript::shared_JavaScript_Service_controller_move ) .append( "(" ) #ifdef _MSC_VER .append( QString::fromUtf16( reinterpret_cast<const ushort *>( id ) ) ) #else .append( QString::fromStdWString( id ) ) #endif .append( "," ) .append( QString::number( coord.getX() ) ) .append( "," ) .append( QString::number( coord.getY() ) ) .append( ");" ); OSScriptRunBehaviourNotifier *notifier = new OSScriptRunBehaviourNotifier( moved_sc ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); } void GlobalEventReceiver::requestContentResized( const unicode_char *id, const IntegerSize& size ) { QString resized_sc = QString( RuntimeScript::shared_JavaScript_Service_Provider_Controller ); resized_sc.append( RuntimeScript::shared_JavaScript_Service_content_resize ) .append( "(" ) #ifdef _MSC_VER .append( QString::fromUtf16( reinterpret_cast<const ushort *>( id ) ) ) #else .append( QString::fromStdWString( id ) ) #endif .append( "," ) .append( QString::number( size.getWidth() ) ) .append( "," ) .append( QString::number( size.getHeight() ) ) .append( ");" ); OSScriptRunBehaviourNotifier *notifier = new OSScriptRunBehaviourNotifier( resized_sc ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); } void GlobalEventReceiver::requestWrapperResized( const unicode_char *id, const IntegerSize& size) { QString resized_sc = QString( RuntimeScript::shared_JavaScript_Service_Provider_Controller ); resized_sc.append( RuntimeScript::shared_JavaScript_Service_wrapper_resize ) .append( "(" ) #ifdef _MSC_VER .append( QString::fromUtf16( reinterpret_cast<const ushort *>( id ) ) ) #else .append( QString::fromStdWString( id ) ) #endif .append( "," ) .append( QString::number( size.getWidth() ) ) .append( "," ) .append( QString::number( size.getHeight() ) ) .append( ");" ); OSScriptRunBehaviourNotifier *notifier = new OSScriptRunBehaviourNotifier( resized_sc ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); } void GlobalEventReceiver::requestQtWidgetInit( QtWidgetInitializer *init ) { OSQtWidgetInitBehaviourNotifier*notifier = new OSQtWidgetInitBehaviourNotifier( init ); m_mutex.acquires(); QApplication::postEvent( m_handler, notifier ); m_mutex.releases(); } void GlobalEventReceiver::requestNotifierRunOnCore( const SharedPtr<AbstractedNotifier>& n ) { } } }//namespace Magna
38.493506
167
0.631242
0of
d0671748b70bb83cf7a659a55423e7f4ff7865ef
1,399
cpp
C++
src/Matrix4.cpp
ianmurfinxyz/software_renderer
1feef4754509d99013dc4bbe51006d858bc27561
[ "Unlicense" ]
null
null
null
src/Matrix4.cpp
ianmurfinxyz/software_renderer
1feef4754509d99013dc4bbe51006d858bc27561
[ "Unlicense" ]
null
null
null
src/Matrix4.cpp
ianmurfinxyz/software_renderer
1feef4754509d99013dc4bbe51006d858bc27561
[ "Unlicense" ]
null
null
null
#include "Matrix4.h" using namespace gr; Matrix4::Matrix4(){ this->e[0][0] = 0.f; this->e[0][1] = 0.f; this->e[0][2] = 0.f; this->e[0][3] = 0.f; this->e[1][0] = 0.f; this->e[1][1] = 0.f; this->e[1][2] = 0.f; this->e[1][3] = 0.f; this->e[2][0] = 0.f; this->e[2][1] = 0.f; this->e[2][2] = 0.f; this->e[2][3] = 0.f; this->e[3][0] = 0.f; this->e[3][1] = 0.f; this->e[3][2] = 0.f; this->e[3][3] = 0.f; } Matrix4::Matrix4(float e00, float e01, float e02, float e03, float e10, float e11, float e12, float e13, float e20, float e21, float e22, float e23, float e30, float e31, float e32, float e33){ this->e[0][0] = e00; this->e[0][1] = e01; this->e[0][2] = e02; this->e[0][3] = e03; this->e[1][0] = e10; this->e[1][1] = e11; this->e[1][2] = e12; this->e[1][3] = e13; this->e[2][0] = e20; this->e[2][1] = e21; this->e[2][2] = e22; this->e[2][3] = e23; this->e[3][0] = e30; this->e[3][1] = e31; this->e[3][2] = e32; this->e[3][3] = e33; } Matrix4 Matrix4::mul(const Matrix4& m) const{ Matrix4 tmp; for(int k = 0; k <= 3; k++){ for(int j = 0; j <= 3; j++){ for(int i = 0; i <= 3; i++){ tmp.e[k][j] += this->e[k][i] * m.e[i][j]; } } } return tmp; }
22.564516
61
0.425304
ianmurfinxyz
d0695eaf6fa81759dadae3c3475dd9bcf0ed247b
35,813
cpp
C++
Underlight/Interface.cpp
christyganger/ULClient
bc008ab3042ff9b74d47cdda47ce2318311a51db
[ "BSD-3-Clause" ]
5
2018-08-17T17:17:01.000Z
2020-11-14T05:41:31.000Z
Underlight/Interface.cpp
christyganger/ULClient
bc008ab3042ff9b74d47cdda47ce2318311a51db
[ "BSD-3-Clause" ]
16
2018-08-16T15:37:04.000Z
2019-12-24T19:09:19.000Z
Underlight/Interface.cpp
christyganger/ULClient
bc008ab3042ff9b74d47cdda47ce2318311a51db
[ "BSD-3-Clause" ]
5
2018-08-16T15:34:41.000Z
2019-03-04T04:06:11.000Z
// Interface: utility functions for making the interface pretty // Copyright Lyra LLC, 1997. All rights reserved. #define STRICT #define OEMRESOURCE // to get defines for windows cursor id's #include "Central.h" #include <windows.h> #include <windowsx.h> #include "Utils.h" #include "Resource.h" #include "cGameServer.h" #include "Options.h" #include "SharedConstants.h" #include "cPlayer.h" #include "cDDraw.h" #include "cDSound.h" #include "Realm.h" #include "cChat.h" #include "Dialogs.h" #include "cOutput.h" #include "cKeymap.h" #include "Mouse.h" #include "cArts.h" #include "Interface.h" #include "cEffects.h" ///////////////////////////////////////////////// // External Global Variables extern cGameServer *gs; extern HINSTANCE hInstance; extern cPlayer *player; extern cDDraw *cDD; extern cDSound *cDS; extern cArts *arts; extern cEffects *effects; extern bool ready; extern options_t options; extern cKeymap *keymap; extern cChat *display; extern HFONT display_font[MAX_RESOLUTIONS]; extern float scale_x; extern float scale_y; //const unsigned long lyra_colors[9] = {BLUE, LTBLUE, DKBLUE, LTBLUE, ORANGE, BLUE, // ORANGE, BLACK, ORANGE}; ////////////////////////////////////////////////////////////////// // Constant Structures // Pointers to functions for subclassing static WNDPROC lpfnPushButtonProc; static WNDPROC lpfnStateButtonProc; // radio,check buttons static WNDPROC lpfnStaticTextProc; static WNDPROC lpfnListBoxProc; static WNDPROC lpfnComboBoxProc; static WNDPROC lpfnTrackBarProc; static WNDPROC lpfnEditProc; static WNDPROC lpfnGenericProc; static HBRUSH blueBrush = NULL; static HBRUSH blackBrush = NULL; // pointer to handles for check and radio button state indicator bitmaps // i.e the checkbox and round radio button. These are created once on start up // and deleted at shutdown. static HBITMAP *hRadioButtons = NULL; static HBITMAP *hCheckButtons = NULL; static HBITMAP hBackground = NULL; static HBITMAP hGoldBackground = NULL; static HBITMAP hListBoxArrow = NULL; //////////////////////////////////////////////////////////////////////////////////////////////////// // Lyra Dialog Manager // Blits bitmap to dc at the co-ord in region //void BlitBitmap(HDC dc, HBITMAP bitmap, RECT *region, const window_pos_t& srcregion, int mask) void BlitBitmap(HDC dc, HBITMAP bitmap, RECT *region, int stretch, int mask) { HGDIOBJ old_object; HDC bitmap_dc; bitmap_dc = CreateCompatibleDC(dc); old_object = SelectObject(bitmap_dc, bitmap); //RECT src; //PrepareSrcRect(&src, region, stretch); BitBlt(dc, region->left, region->top, (region->right - region->left), (region->bottom - region->top), bitmap_dc, 0, 0, mask); //StretchBlt(dc, region->left, region->top, (region->right - region->left), //(region->bottom - region->top), bitmap_dc, //src.left, src.top, (src.right - src.left), (src.bottom - src.top), mask); //0, 0, (src.right - src.left), (src.bottom - src.top), mask); SelectObject(bitmap_dc, old_object); DeleteDC(bitmap_dc); return; } void TransparentBlitBitmap(HDC dc, int bitmap_id, RECT *region, int stretch, int mask) { HBITMAP hBitmap; if (effects->EffectWidth(bitmap_id) == 0 ) return ; effects->LoadEffectBitmaps(bitmap_id, 1); hBitmap = effects->CreateBitmap(bitmap_id); BlitBitmap(dc, hBitmap, region, stretch, mask); DeleteObject(hBitmap); effects->FreeEffectBitmaps(bitmap_id); } HCURSOR __cdecl BitmapToCursor(HBITMAP bmp, HCURSOR cursor) { HDC hDC = GetDC(NULL); HDC hMainDC = CreateCompatibleDC(hDC); HDC hAndMaskDC = CreateCompatibleDC(hDC); HDC hXorMaskDC = CreateCompatibleDC(hDC); HBITMAP cursorandmask = NULL; HBITMAP cursorxormask = NULL; //Get the dimensions of the source bitmap BITMAP bm; GetObject(bmp, sizeof(BITMAP), &bm); cursorandmask = CreateCompatibleBitmap(hDC, bm.bmWidth,bm.bmHeight); cursorxormask = CreateCompatibleBitmap(hDC, bm.bmWidth,bm.bmHeight); //Select the bitmaps to DC HBITMAP hOldMainBitmap = (HBITMAP)::SelectObject(hMainDC, bmp); HBITMAP hOldAndMaskBitmap = (HBITMAP)::SelectObject(hAndMaskDC, cursorandmask); HBITMAP hOldXorMaskBitmap = (HBITMAP)::SelectObject(hXorMaskDC, cursorxormask); //Scan each pixel of the souce bitmap and create the masks COLORREF MainBitPixel; for(int x=0;x<bm.bmWidth;++x) { for(int y=0;y<bm.bmHeight;++y) { MainBitPixel = ::GetPixel(hMainDC,x,y); if(MainBitPixel == 0) { SetPixel(hAndMaskDC,x,y,RGB(255,255,255)); SetPixel(hXorMaskDC,x,y,RGB(0,0,0)); } else { SetPixel(hAndMaskDC,x,y,RGB(0,0,0)); SetPixel(hXorMaskDC,x,y,MainBitPixel); } } } SelectObject(hMainDC,hOldMainBitmap); SelectObject(hAndMaskDC,hOldAndMaskBitmap); SelectObject(hXorMaskDC,hOldXorMaskBitmap); DeleteDC(hXorMaskDC); DeleteDC(hAndMaskDC); DeleteDC(hMainDC); ReleaseDC(NULL,hDC); ICONINFO iconinfo = {0}; iconinfo.fIcon = FALSE; iconinfo.xHotspot = 0; iconinfo.yHotspot = 0; iconinfo.hbmMask = cursorandmask; iconinfo.hbmColor = cursorxormask; cursor = CreateIconIndirect(&iconinfo); return cursor; } // Creates a windows bitmap from an effects bitmap with given bitmap ID HBITMAP CreateWindowsBitmap(int bitmap_id) { HBITMAP hBitmap; if (effects->EffectWidth(bitmap_id) == 0 ) return NULL; effects->LoadEffectBitmaps(bitmap_id, 2); hBitmap = effects->CreateBitmap(bitmap_id); effects->FreeEffectBitmaps(bitmap_id); return hBitmap; } // Creates a windows bitmap, and a grayed version of that,from a game bitmap with given bitmap ID // Bitmap handles are returned in hBitmaps array, normal first, grayed second void CreateWindowsBitmaps(int bitmap_id, HBITMAP hBitmaps[] ) { if (effects->EffectWidth(bitmap_id ) != 0 ) { effects->LoadEffectBitmaps(bitmap_id, 3); int size = effects->EffectWidth(bitmap_id)* effects->EffectHeight(bitmap_id); PIXEL *src = (PIXEL *)effects->EffectBitmap(bitmap_id)->address; // Normal Version hBitmaps[0] = effects->Create16bppBitmapFromBits((unsigned char *)src, effects->EffectWidth(bitmap_id), effects->EffectHeight(bitmap_id)); // Grayed Version PIXEL *buffer = new PIXEL[size]; // Go thru bitmap and create new 'grayed' bitmap for (int i = 0; i < size; i++) { //extract colors int red = (src[i] & 0xF800) >> 11; int green = (src[i] & 0x03E0) >> 5; int blue = (src[i] & 0x001F); // average the colors and set each color to this PIXEL average = ((red+blue+green)/3) & 0x1F; buffer[i] = (average << 11) | (average<< 6) | average; } hBitmaps[1] = effects->Create16bppBitmapFromBits((unsigned char *)buffer, effects->EffectWidth(bitmap_id), effects->EffectHeight(bitmap_id)); delete [] buffer; effects->FreeEffectBitmaps(bitmap_id); } else { hBitmaps[0] = NULL; hBitmaps[1] = NULL; } } // Create Windows bitmaps for a dialog control from effects bitmaps // If the control has more than one state e.g a radio button, then is // assumed there are two effects , one for each state, and that the second effect ID is // one more than the first. const int NUM_CONTROL_BITMAPS = 4; HBITMAP *CreateControlBitmaps( int effect_id, int num_states) { HBITMAP *bitmaps = new HBITMAP [NUM_CONTROL_BITMAPS]; memset(bitmaps,0, sizeof HBITMAP * NUM_CONTROL_BITMAPS); for (int i = 0; i < num_states; i++) CreateWindowsBitmaps(effect_id+i, &bitmaps[i*2]); // if no bitmaps were actually created, return NULL bool success = false; for (int i = 0; i < num_states; i++) if (bitmaps[i] != NULL) success = true; if (!success) { delete bitmaps; bitmaps = NULL; } return bitmaps; } // Deletes bitmaps created above void DeleteControlBitmaps(HBITMAP *bitmaps) { if (!bitmaps) return; for (int i = 0; (i < NUM_CONTROL_BITMAPS); i++) if (bitmaps[i]) DeleteObject(bitmaps[i]); delete bitmaps; } // Resizes a Button Window (Should have been in Windows) void ResizeButton(HWND hWnd, int new_width, int new_height) { RECT r; // determine size of button borders int border_x = GetSystemMetrics(SM_CXBORDER) + GetSystemMetrics(SM_CXEDGE); int border_y = GetSystemMetrics(SM_CYBORDER) + GetSystemMetrics(SM_CYEDGE); GetWindowRect(hWnd,&r); MapWindowPoints(NULL,GetParent(hWnd),LPPOINT(&r),2); MoveWindow(hWnd, r.left, r.top, new_width + border_x, new_height + border_y,0); } // Resizes a Label Window (Should have been in Windows) void ResizeLabel(HWND hWnd, int new_width, int new_height) { RECT r; GetWindowRect(hWnd,&r); MapWindowPoints(NULL,GetParent(hWnd),LPPOINT(&r),2); MoveWindow(hWnd, r.left, r.top, new_width, new_height, 0); } // Callback for push buttons BOOL CALLBACK PushButtonProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam) { // Extract pointer to handle array of button text HBITMAP *hButtonText = (HBITMAP *)GetWindowLong(hWnd,GWL_USERDATA); switch (Message) { case WM_SETFOCUS: // Ensures that the focus is never on a button case WM_KILLFOCUS: // and that the annoying focus rectangle is not displayed return 0; case WM_KEYUP: case WM_KEYDOWN: case WM_CHAR: // pass on keyboard messages to parent PostMessage(GetParent(hWnd), Message, wParam, lParam); return 0; case WM_ENABLE: { if ((BOOL)wParam) // If window is being enabled SendMessage(hWnd, BM_SETIMAGE, WPARAM (IMAGE_BITMAP), LPARAM (hButtonText[0])); else SendMessage(hWnd, BM_SETIMAGE, WPARAM (IMAGE_BITMAP), LPARAM (hButtonText[1])); } break; case WM_CAPTURECHANGED: SendMessage(GetParent(hWnd),WM_CAPTURECHANGED, wParam, lParam); // Allows parent to set focus to another window break; case WM_DESTROY: DeleteControlBitmaps(hButtonText); break; } return CallWindowProc(lpfnPushButtonProc,hWnd, Message, wParam, lParam) ; } // Callback for radio and check boxes BOOL CALLBACK StateButtonProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam) { // Extract pointer to handle array of button text HBITMAP *hButtonText = (HBITMAP *)GetWindowLong(hWnd,GWL_USERDATA); switch (Message) { case WM_DESTROY: { DeleteControlBitmaps(hButtonText); break; } case WM_SETFOCUS: // Ensures that the focus is never on a button case WM_KILLFOCUS: // and that the annoying focus rectangle is not displayed return 0; case WM_KEYUP: case WM_KEYDOWN: case WM_CHAR: // pass on keyboard messages to parent PostMessage(GetParent(hWnd), Message, wParam, lParam); return 0; case WM_PAINT: if (hButtonText) { HBITMAP *hButtons; // Determine which bitmaps to used based on button's style int style =GetWindowStyle(hWnd); switch (style & 0x000F) // styles are any integer from 0..16 { case BS_AUTORADIOBUTTON: hButtons = hRadioButtons; break; case BS_AUTOCHECKBOX: hButtons = hCheckButtons; break; } if (!IsWindowEnabled(hWnd)) // If window is disabled hButtons+=1; // Use grayed out bitmaps PAINTSTRUCT Paint; HDC dc= BeginPaint(hWnd,&Paint); RECT button_rect, text_rect; GetClientRect(hWnd, &button_rect); GetClientRect(hWnd, &text_rect); //Determine size of state indicator bitmap int size; BITMAP bm; GetObject(hButtons[0],sizeof BITMAP, &bm); size = bm.bmWidth; // Determine where button and text go depending on button style if (style & BS_LEFTTEXT) button_rect.left = button_rect.right - size; else text_rect.left += size; // Blit button depending on check state BlitBitmap(dc, hButtons[(Button_GetCheck(hWnd)) ? 0 : 2], &button_rect, NOSTRETCH); // Blit button text if (hButtonText) BlitBitmap(dc, hButtonText[IsWindowEnabled(hWnd)?0:1], &text_rect, NOSTRETCH); EndPaint(hWnd,&Paint); return 0; } else break; case BM_SETCHECK: case BM_SETSTATE: // State of button has changed CallWindowProc(lpfnStateButtonProc,hWnd, Message, wParam, lParam); // Windows paints its own stuff during above call so we MUST repaint InvalidateRect(hWnd,NULL,0); UpdateWindow(hWnd); // Repaint return 0; case WM_CAPTURECHANGED: // Tell parent we no logner have the focuse SendMessage(GetParent(hWnd),WM_CAPTURECHANGED, wParam, lParam); } return CallWindowProc(lpfnStateButtonProc,hWnd, Message, wParam, lParam) ; } // Callback for static text BOOL CALLBACK StaticTextProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam) { // Extract pointer to handle array of text HBITMAP *hBitmaps = (HBITMAP *)GetWindowLong(hWnd,GWL_USERDATA); switch (Message) { case WM_DESTROY: { DeleteControlBitmaps(hBitmaps); break; } case WM_SETFOCUS: // Ensures that the focus is never on a button case WM_KILLFOCUS: // and that the annoying focus rectangle is not displayed return 0; case WM_KEYUP: case WM_KEYDOWN: case WM_CHAR: // pass on keyboard messages to parent PostMessage(GetParent(hWnd), Message, wParam, lParam); return 0; case WM_PAINT: if (hBitmaps) { PAINTSTRUCT Paint; HDC dc= BeginPaint(hWnd,&Paint); RECT r; GetClientRect(hWnd, &r); if (hBitmaps) BlitBitmap(dc, hBitmaps[IsWindowEnabled(hWnd)?0:1], &r, NOSTRETCH); EndPaint(hWnd,&Paint); return 0; }; // pass on to normal handler if no bitmaps break; } return CallWindowProc(lpfnStaticTextProc,hWnd, Message, wParam, lParam) ; } // returns true if we're dealing with a "special" list box that doesn't // get normal processing below bool IsSpecialListBox(HWND hWnd) { if ((GetDlgCtrlID(hWnd) == IDC_KEY_EFFECT_COMBO) || (GetDlgCtrlID(hWnd) == IDC_GUILDS) || (GetDlgCtrlID(hWnd) == IDC_IGNORE_LIST) || (GetDlgCtrlID(hWnd) == IDC_WATCH_LIST)) return true; else return false; } void DrawListBoxArrow(HWND hWnd, HDC dc, RECT r) //### { HDC bitmap_dc = CreateCompatibleDC(dc); HGDIOBJ old_object = SelectObject(bitmap_dc, hListBoxArrow); BitBlt(dc, r.left, 0, effects->EffectWidth(LyraBitmap::LISTBOX_ARROWS), effects->EffectHeight(LyraBitmap::LISTBOX_ARROWS), bitmap_dc, 0, 0, SRCCOPY); SelectObject(bitmap_dc, old_object); DeleteDC(bitmap_dc); } // Callback for list boxes BOOL CALLBACK ListBoxProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam) { switch (Message) { case WM_KEYUP: case WM_CHAR: // pass on keyboard messages to parent PostMessage(GetParent(hWnd), Message, wParam, lParam); break; case WM_KEYDOWN: { PostMessage(GetParent(hWnd), Message, wParam, lParam); int old_sel = ListBox_GetCurSel(hWnd); int sel = old_sel; if (wParam == VK_UP && sel == 0) sel = ListBox_GetCount(hWnd) - 1; else if (wParam == VK_DOWN && sel == (ListBox_GetCount(hWnd) - 1)) sel = 0; if (old_sel != sel) { ListBox_SetCurSel(hWnd, sel); InvalidateRect(hWnd, NULL, TRUE); //..since Windows does its own painting in SetCurSel... PostMessage(GetParent(hWnd), WM_COMMAND, (WPARAM)MAKEWPARAM(GetDlgCtrlID(hWnd), LBN_SELCHANGE), (LPARAM)hWnd); // Windows should send LBN_SELCHANGE out in SetCurSel but does not return 0; } } break; case LB_SETCURSEL: if (IsSpecialListBox(hWnd)) break; InvalidateRect(hWnd, NULL, TRUE); break; case WM_MOUSEMOVE: if (IsSpecialListBox(hWnd)) break; return 0; case WM_SETFOCUS: case WM_KILLFOCUS: if (IsSpecialListBox(hWnd)) break; InvalidateRect(hWnd, NULL, TRUE); InvalidateRect(hWnd, NULL, TRUE); return 0; case WM_LBUTTONDOWN: { if (IsSpecialListBox(hWnd)) break; int x = (int)(short)LOWORD(lParam); int y = (int)(short)HIWORD(lParam); RECT r; GetWindowRect(hWnd, &r); // if within the up/down arrow... if (x >= (r.right - r.left - effects->EffectWidth(LyraBitmap::LISTBOX_ARROWS))) { //generate corrosponding keyboard message if (y < (effects->EffectHeight(LyraBitmap::LISTBOX_ARROWS)/2)) SendMessage(hWnd,WM_KEYDOWN, VK_UP,0); // in up arrow else SendMessage(hWnd,WM_KEYDOWN, VK_DOWN,0); // in down arrow } break; } case WM_PAINT: { // important - do NOT custom paint the keyboard config or // select guild listboxes - they are different! if (IsSpecialListBox(hWnd)) break; TCHAR buffer[DEFAULT_MESSAGE_SIZE]; HFONT pOldFont; PAINTSTRUCT Paint; HDC dc= BeginPaint(hWnd,&Paint); SetTextColor(dc, ORANGE); SetBkMode(dc, OPAQUE); SetBkColor(dc, DKBLUE); int curr_selection = ListBox_GetCurSel(hWnd); if (curr_selection != -1) { TEXTMETRIC tm; RECT text_region; pOldFont = (HFONT)SelectObject(dc, display_font[0]); GetTextMetrics(dc, &tm); GetWindowRect(hWnd, &text_region); ListBox_GetText(hWnd, curr_selection, buffer); int clip_width = text_region.right - text_region.left; // EITHER /* int counter = 0; int text_width = 0; int char_width; while (buffer[counter] != '\0') { GetCharWidth(dc, buffer[counter], buffer[counter], &char_width); text_width += char_width; if (text_width + tm.tmAveCharWidth > clip_width) { buffer[counter] = '\0'; break; } counter++; } */ // OR buffer[(int)((clip_width-(4*tm.tmAveCharWidth)) / tm.tmAveCharWidth)]='\0'; TextOut(dc, 0, 0, buffer, _tcslen(buffer)); SelectObject(dc, pOldFont); } RECT r; GetClientRect(hWnd, &r); r.left = r.right - effects->EffectWidth(LyraBitmap::LISTBOX_ARROWS); DrawListBoxArrow(hWnd, dc, r); // ensure the focus rect is painted consistently GetClientRect(hWnd, &r); r.top = 1; r.bottom = effects->EffectHeight(LyraBitmap::LISTBOX_ARROWS) - 1; if (GetFocus() == hWnd) DrawFocusRect(dc, &r); EndPaint(hWnd,&Paint); return 0; }; // pass on to normal handler if no bitmaps break; } return CallWindowProc(lpfnListBoxProc,hWnd, Message, wParam, lParam) ; } // Callback for combo boxes BOOL CALLBACK ComboBoxProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam) { switch (Message) { case WM_KEYUP: case WM_KEYDOWN: case WM_CHAR: // pass on keyboard messages to parent PostMessage(GetParent(hWnd), Message, wParam, lParam); break; } return CallWindowProc(lpfnComboBoxProc, hWnd, Message, wParam, lParam) ; } // Callback for trackbars BOOL CALLBACK TrackBarProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam) { switch (Message) { case WM_KEYUP: case WM_KEYDOWN: case WM_CHAR: // pass on keyboard messages to parent PostMessage(GetParent(hWnd), Message, wParam, lParam); break; } return CallWindowProc(lpfnTrackBarProc, hWnd, Message, wParam, lParam) ; } // Callback for all other controls BOOL CALLBACK EditProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam) { switch (Message) { case WM_KEYUP: switch (LOWORD(wParam)) { case VK_ESCAPE: case VK_RETURN: PostMessage(GetParent(hWnd), Message, wParam, lParam); break; } case WM_RBUTTONDOWN: return 0; break; } return CallWindowProc(lpfnEditProc, hWnd, Message, wParam, lParam) ; } // Callback for all other controls BOOL CALLBACK GenericProc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam) { switch (Message) { case WM_KEYUP: case WM_KEYDOWN: case WM_CHAR: // pass on keyboard messages to parent PostMessage(GetParent(hWnd), Message, wParam, lParam); break; } return CallWindowProc(lpfnGenericProc, hWnd, Message, wParam, lParam) ; } void ResizeDlg(HWND hDlg) { int w,h; RECT rect; if ((scale_x == 0.0f) || (!ready)) return; // now resize appropriately, based on fonts GetWindowRect(hDlg, &rect); w = rect.right - rect.left; h = rect.bottom - rect.top; MoveWindow(hDlg, rect.left, rect.top, w, h, TRUE); // and resize all child windows appropriately EnumChildWindows(hDlg, EnumChildProcSize, NULL); } // callback to set size of child windows BOOL CALLBACK EnumChildProcSize( HWND hChild, LPARAM lParam ) { int w,h,x,y; RECT rect1, rect2; // now resize appropriately, based on fonts GetWindowRect(GetParent(hChild), &rect1); GetWindowRect(hChild, &rect2); x = rect2.left - rect1.left; y = rect2.top - rect1.top; w = rect2.right - rect2.left; h = rect2.bottom - rect2.top; MoveWindow(hChild, x, y, w, h, TRUE); return TRUE; } // Callback to enumerate through all controls of a dialog and set up // apropriate callbacks and bitmaps BOOL CALLBACK EnumChildProcSetup( HWND hChild, LPARAM lParam ) { TCHAR class_name[30]; int effect_id = GetDlgCtrlID(hChild); SendMessage(hChild, WM_SETFONT, WPARAM(display_font[0]), 0); GetClassName(hChild, class_name, sizeof class_name); if(_tcscmp(class_name, _T("Edit")) && _tcscmp(class_name, _T("ComboBox"))&& _tcscmp(class_name, _T("ListBox")) ) // These controls won't have their TABSTOP style unset, so they can receive the focus // All others cannot receive focus { int style = GetWindowLong(hChild, GWL_STYLE); style &= ~WS_TABSTOP; SetWindowLong(hChild, GWL_STYLE, style); } if (_tcscmp(class_name, _T("Static")) == 0) // if window is a static text control { // bitmaps will be null if this is drawn as text HBITMAP *hBitmaps = CreateControlBitmaps(effect_id,1); SetWindowLong(hChild, GWL_USERDATA, LONG(hBitmaps)); if (hBitmaps) { BITMAP bm; GetObject(hBitmaps[0],sizeof BITMAP, &bm); ResizeButton(hChild,bm.bmWidth,bm.bmHeight); } lpfnStaticTextProc = SubclassWindow(hChild, StaticTextProc); return TRUE; } //if (_tcscmp(class_name, "ComboBox") == 0) //{ // if window is a combo box // lpfnComboBoxProc = SubclassWindow(hChild, ComboBoxProc); // return TRUE; //} if (_tcscmp(class_name, _T("ListBox")) == 0) { lpfnListBoxProc = SubclassWindow(hChild, ListBoxProc); return TRUE; } if (_tcscmp(class_name, _T("ComboBox")) == 0) { // if window is a list box lpfnComboBoxProc = SubclassWindow(hChild, ComboBoxProc); return TRUE; } if (_tcscmp(class_name, _T("msctls_trackbar32")) == 0) { // track bar lpfnTrackBarProc = SubclassWindow(hChild, TrackBarProc); return TRUE; } if (_tcscmp(class_name, _T("Edit")) == 0) { // edit lpfnEditProc = SubclassWindow(hChild, EditProc); return TRUE; } if (_tcscmp(class_name, _T("Button"))) // if window is not a button type { // use generic proc lpfnGenericProc = SubclassWindow(hChild, GenericProc); return TRUE; } int style =GetWindowStyle(hChild); switch (style & 0x000F) // styles are any integer from 0..16 { // window data for radio & checkboxes is the bitmap handle case BS_AUTORADIOBUTTON: case BS_AUTOCHECKBOX: { HBITMAP *hBitmaps = CreateControlBitmaps(effect_id,1); if (hBitmaps) { SetWindowLong(hChild,GWL_USERDATA ,LONG(hBitmaps)); //BITMAP bm; //GetObject(hBitmaps[0], sizeof BITMAP, &bm); //ResizeButton(hChild,bm.bmWidth,bm.bmHeight); } lpfnStateButtonProc = SubclassWindow(hChild, StateButtonProc); } break; case BS_PUSHBUTTON: case BS_DEFPUSHBUTTON: { switch (effect_id) { case IDC_OK: effect_id = LyraBitmap::OK; break; case IDC_CANCEL: effect_id = LyraBitmap::CANCEL; break; } // Use standard IDS for common buttons // window data for buttons is the bitmap handle HBITMAP *hBitmaps = CreateControlBitmaps(effect_id,1); if (hBitmaps) { int style = GetWindowLong(hChild, GWL_STYLE); style |= BS_BITMAP; SetWindowLong(hChild, GWL_STYLE, style); SetWindowLong(hChild, GWL_USERDATA, LONG(hBitmaps)); SendMessage(hChild, BM_SETIMAGE,WPARAM (IMAGE_BITMAP), LPARAM (hBitmaps[0])); BITMAP bm; GetObject(hBitmaps[0], sizeof BITMAP, &bm); ResizeButton(hChild,bm.bmWidth,bm.bmHeight); ResizeButton(hChild,bm.bmWidth,bm.bmHeight); } lpfnPushButtonProc = SubclassWindow(hChild, PushButtonProc); } break; } return TRUE; // Continue enumeration } // Callback for master dialog proc. Sets up child controls,paints background,etc BOOL CALLBACK LyraDialogProc(HWND hDlg, UINT Message, WPARAM wParam, LPARAM lParam) { DLGPROC windowProc; switch(Message) { case WM_INITDIALOG: SetWindowLong(hDlg, GWL_USERDATA, lParam); SendMessage(hDlg, WM_SETFONT, WPARAM(display_font[0]), 0); ResizeDlg(hDlg); EnumChildWindows(hDlg, EnumChildProcSetup, NULL); break; } windowProc = DLGPROC(GetWindowLong(hDlg, GWL_USERDATA)); if (windowProc) return windowProc(hDlg, Message, wParam, lParam); else return 0; } static HWND hCurrentDlg; // modeless version of dlg box proc to call HWND __cdecl CreateLyraDialog( HINSTANCE hInstance, int dialog, HWND hWndParent, DLGPROC lpDialogFunc) { hCurrentDlg = CreateDialogParam(hInstance,MAKEINTRESOURCE(dialog),hWndParent,LyraDialogProc, LPARAM(lpDialogFunc)); cDS->PlaySound(LyraSound::MESSAGE_ALERT); return hCurrentDlg; } bool IsLyraDialogMessage(MSG *msg) { if (msg->message == WM_KEYDOWN && msg->wParam == VK_TAB) // tabs are used to move in dialog return IsDialogMessage(hCurrentDlg, msg); // Seems that Windows checks if hCurrent is valid,returns false if not else return false; } // modal version of dlg box proc to call int __cdecl LyraDialogBox( HINSTANCE hInstance, int dialog, HWND hWndParent, DLGPROC lpDialogFunc) { DLGPROC lpDialogProc = lpDialogFunc; if (cDS) cDS->PlaySound(LyraSound::MESSAGE_ALERT); if (!ready) // use plain dialogs for startup error messages to avoid weird color combinations return DialogBox (hInstance, MAKEINTRESOURCE(dialog), hWndParent, lpDialogFunc); else return DialogBoxParam(hInstance, MAKEINTRESOURCE(dialog), hWndParent, LyraDialogProc, LPARAM(lpDialogFunc)); } // Creates cursor from bitmap in effects.rlm: first creates windows bitmap, creates windows // bitmap mask from this, creates windows cursor from these, and sets the system cursor to this. static void SetupLyraCursor(void) { /* int bitmap_id = LyraBitmap::CURSOR; if (effects->EffectWidth(bitmap_id ) == 0 ) return; effects->LoadEffectBitmaps(bitmap_id); int width = effects->EffectWidth(bitmap_id); int height= effects->EffectHeight(bitmap_id); HBITMAP hCursorBitmap = CreateBitmap(width, height, 1, BITS_PER_PIXEL, effects->EffectBitmap(bitmap_id)->address); // Create cursor mask bitmap from cursor. int size = width*height/8; // its a 1 bit per pixel bitmap UCHAR *maskbits = new UCHAR [size]; UCHAR *dest = maskbits; PIXEL *src = (PIXEL*)effects->EffectBitmap(bitmap_id)->address; memset(maskbits,0,size); for (int i = 0; i < size; i++) { int j = 8; while (j--) if (!*src++) // if the source pixel is black *dest |= 1 << j; // set the mask bit on (which makes black transparent) *dest++ ; } HBITMAP hCursorMask = CreateBitmap(width, height, 1, 1, maskbits); delete [] maskbits; effects->FreeEffectBitmaps(bitmap_id); // Create Windows cursor ICONINFO ii; ii.fIcon = false ; // cursor (false) or icon (true) ii.xHotspot = 0; ii.yHotspot = 0; ii.hbmMask = hCursorMask; ii.hbmColor = hCursorBitmap; HCURSOR hCursor = CreateIconIndirect(&ii); DeleteObject(hCursorMask); // CreateIconIdirect makes copies of these so DeleteObject(hCursorBitmap); // they can be deleted here */ // Set system cursor to Lyra cursor HCURSOR hCursor = LoadCursor(NULL,IDC_ARROW); SetCursor(hCursor); SetSystemCursor(hCursor,OCR_NORMAL ); } // Restores the system cursor by accessing the registry for the previous (software)cursor's filename static void RestoreSystemCursor(void) { HKEY reg_key = NULL; DWORD reg_type; TCHAR cursor_file[DEFAULT_MESSAGE_SIZE] = _T(""); DWORD size = sizeof cursor_file; RegOpenKeyEx(HKEY_CURRENT_USER, _T("Control Panel\\Cursors"),0,KEY_ALL_ACCESS ,&reg_key); if (reg_key) { // Get name of file of the regular arrow cursor RegQueryValueEx(reg_key,_T("Arrow"),NULL,&reg_type, (LPBYTE)cursor_file, &size); // Load cursor and set system cursor to it HCURSOR hCursor; if (_tcslen(cursor_file)) hCursor = LoadCursorFromFile(cursor_file);// software cursor else hCursor = LoadCursor(NULL,IDC_ARROW); // hardware cursor (or registry calls failed) SetSystemCursor(hCursor, OCR_NORMAL); RegCloseKey(reg_key); } } void __cdecl InitLyraDialogController(void) { hRadioButtons = CreateControlBitmaps(LyraBitmap::BULLET,2); hCheckButtons = CreateControlBitmaps(LyraBitmap::CHECK_BUTTON, 2); hBackground = CreateWindowsBitmap(LyraBitmap::DLG_BACKGROUND); hGoldBackground = CreateWindowsBitmap(LyraBitmap::DLG_BACKGROUND2); hListBoxArrow = CreateWindowsBitmap(LyraBitmap::LISTBOX_ARROWS); blueBrush = CreateSolidBrush(DKBLUE); blackBrush = CreateSolidBrush(BLACK); SetupLyraCursor(); } void __cdecl DeInitLyraDialogController(void) { RestoreSystemCursor(); if (hRadioButtons) DeleteControlBitmaps(hRadioButtons); if (hCheckButtons) DeleteControlBitmaps(hCheckButtons); if (hBackground) DeleteObject(hBackground); if (hGoldBackground) DeleteObject(hGoldBackground); if (hListBoxArrow) DeleteObject(hListBoxArrow); if (blueBrush) DeleteObject(blueBrush); if (blackBrush) DeleteObject(blackBrush); } bool TileBackground(HWND hWnd, int which_bitmap) { RECT r; BITMAP bm; GetClientRect(hWnd,&r); int bytes; if (!ready) // no coloration before game starts return false; if (which_bitmap == 0) bytes = GetObject(hBackground,sizeof(BITMAP),&bm); else bytes = GetObject(hGoldBackground,sizeof(BITMAP),&bm); if (!bytes || (&bm == NULL)) return false; PAINTSTRUCT Paint; HDC dc= BeginPaint(hWnd,&Paint); SetTextColor(dc, ORANGE); int repeat_x = (r.right/bm.bmWidth) + 1; int repeat_y = (r.bottom/bm.bmHeight) + 1; // Tile background bitmap for (int x= 0; x < repeat_x; x++) for (int y= 0; y < repeat_y; y++) { r.left = x*bm.bmWidth; r.top = y*bm.bmHeight; r.right = r.left + bm.bmWidth; r.bottom = r.top + bm.bmHeight; if (which_bitmap == 0) BlitBitmap(dc,hBackground,&r, NOSTRETCH); else BlitBitmap(dc,hGoldBackground,&r, NOSTRETCH); } EndPaint(hWnd,&Paint); return true; } // sets standard colors for controls; returns true if the message is handled HBRUSH SetControlColors(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam, bool goalposting) { if (!ready) // no coloration before game starts return NULL; TCHAR class_name[30]; switch(Message) { case WM_CTLCOLORSTATIC: // set color of Static controls { GetClassName((HWND)lParam, class_name, sizeof class_name); if (_tcscmp(class_name, _T("msctls_trackbar32")) == 0) { HDC dc = (HDC)wParam; SetTextColor(dc, ORANGE); SetBkMode(dc, OPAQUE); SetBkColor(dc, BLACK); return blackBrush; } else { HDC dc = (HDC)wParam; SetTextColor(dc, ORANGE); if (goalposting) { SetBkMode(dc, OPAQUE); SetBkColor(dc, BLACK); return blackBrush; } else { SetBkMode(dc, TRANSPARENT); return ((HBRUSH)GetStockObject(NULL_BRUSH)); } } } case WM_CTLCOLOREDIT: // set color of edit controls case WM_CTLCOLORLISTBOX: // set color of listbox controls case WM_CTLCOLORBTN: // set color of button controls { HDC dc = (HDC)wParam; SetTextColor(dc, ORANGE); SetBkMode(dc, OPAQUE); if (goalposting) { SetBkColor(dc, BLACK); return blackBrush; } else { SetBkColor(dc, DKBLUE); return blueBrush; } } default: return NULL; } } /* // code for custom painting combo boxes SIZE size; PAINTSTRUCT Paint; HDC dc= BeginPaint(hWnd,&Paint); RECT rc, rcTab, rcFocus; // draw border GetClientRect( hWnd, &rc ); Draw3DRect( dc, &rc, lyra_colors[COLOR_HIGHLIGHT], lyra_colors[COLOR_BTNSHADOW] ); DeflateRect( &rc, 2, 2 ); // draw tab rcTab = rc; rcTab.left = rc.right = rcTab.right - GetSystemMetrics( SM_CXHTHUMB ); RECT rcTab2 = rcTab; bool m_dropDown = SendMessage(hWnd, CB_GETDROPPEDSTATE, 0, 0); if( m_dropDown ) { Draw3DRect( dc, &rcTab, lyra_colors[COLOR_HIGHLIGHT], lyra_colors[COLOR_BTNSHADOW] ); rcTab.top++; rcTab.left++; // last param was m_crThumbDn Draw3DRect( dc, &rcTab, lyra_colors[COLOR_BTNSHADOW], lyra_colors[COLOR_3DLIGHT]); DeflateRect( &rcTab, 1, 1 ); // last param was m_crThumbDn HBRUSH thumbDnBrush = CreateSolidBrush(lyra_colors[COLOR_3DLIGHT]); FillRect( dc, &rcTab, thumbDnBrush); DeleteObject(thumbDnBrush); } else { Draw3DRect( dc, &rcTab, lyra_colors[COLOR_HIGHLIGHT], lyra_colors[COLOR_BTNSHADOW] ); DeflateRect( &rcTab, 2, 2 ); rcTab.right++; rcTab.bottom++; // last param was m_crThumbUp HBRUSH thumbUpBrush = CreateSolidBrush(lyra_colors[COLOR_3DLIGHT]); FillRect( dc, &rcTab, thumbUpBrush ); DeleteObject(thumbUpBrush); } rcTab = rcTab2; // draw arrow HPEN darkpen = CreatePen( PS_SOLID, 1, lyra_colors[COLOR_BTNSHADOW] ); HPEN lightpen = CreatePen( PS_SOLID, 1, lyra_colors[COLOR_HIGHLIGHT] ); POINT topleft = {rcTab.left + ( (rcTab.right - rcTab.left) / 3 ) + m_dropDown, rcTab.top + ( (rcTab.bottom - rcTab.top) / 3 ) + m_dropDown }; POINT topright = { rcTab.right - ( (rcTab.right - rcTab.left) / 3 ) + m_dropDown, rcTab.top + ( (rcTab.bottom - rcTab.top) / 3 ) + m_dropDown }; POINT bottom = { rcTab.left + ( (rcTab.right - rcTab.left) / 2 ) + m_dropDown, rcTab.bottom - ( (rcTab.bottom - rcTab.top) / 3 ) + m_dropDown }; HPEN OldPen = (HPEN)SelectObject(dc, lightpen); MoveToEx( dc, topright.x, topright.y, NULL ); LineTo( dc, bottom.x, bottom.y ); SelectObject(dc, darkpen ); LineTo( dc, topleft.x, topleft.y ); LineTo( dc, topright.x, topright.y ); SelectObject(dc, OldPen ); // draw background rc.bottom++; // BOGON - ALIGNMENT FIX HBRUSH bgbrush = CreateSolidBrush(DKBLUE); FrameRect( dc, &rc, bgbrush ); DeflateRect( &rc, 1, 1 ); HBRUSH focbrush = CreateSolidBrush(lyra_colors[COLOR_3DLIGHT]); if( GetFocus() == hWnd ) FillRect( dc, &rc, focbrush ); else FillRect( dc, &rc, bgbrush ) ; DeleteObject(bgbrush); DeleteObject(focbrush); // draw text TCHAR text[64]; HFONT pOldFont; //pOldFont = dc.SelectObject( GetFont() ); SetTextColor(dc, lyra_colors[COLOR_WINDOWTEXT]); SetBkMode( dc, TRANSPARENT ); _tcscpy(text, "W"); GetTextExtentPoint(dc, text, 1, &size); rc.left += size.cx; GetWindowText( hWnd, text, sizeof(text) ); DrawText( dc, text, _tcslen(text), &rc, DT_LEFT|DT_SINGLELINE|DT_VCENTER ); //dc.SelectObject( pOldFont ); EndPaint(hWnd,&Paint); return 0; */ /* // following are functions ripped off from MFC to ease porting of // the combo box drawing code void Draw3DRect(HDC dc, RECT *lpRect, COLORREF clrTopLeft, COLORREF clrBottomRight) { Draw3DRect(dc, lpRect->left, lpRect->top, lpRect->right - lpRect->left, lpRect->bottom - lpRect->top, clrTopLeft, clrBottomRight); } void Draw3DRect(HDC dc, int x, int y, int cx, int cy, COLORREF clrTopLeft, COLORREF clrBottomRight) { FillSolidRect(dc, x, y, cx - 1, 1, clrTopLeft); FillSolidRect(dc, x, y, 1, cy - 1, clrTopLeft); FillSolidRect(dc, x + cx, y, -1, cy, clrBottomRight); FillSolidRect(dc, x, y + cy, cx, -1, clrBottomRight); } void FillSolidRect(HDC dc, int x, int y, int cx, int cy, COLORREF clr) { SetBkColor(dc, clr); RECT rect = {x, y, x + cx, y + cy}; ExtTextOut(dc, 0, 0, ETO_OPAQUE, &rect, NULL, 0, NULL); } void DeflateRect(RECT *rect, int x, int y) { rect->left += x; rect->top += y; rect->right -= x; rect->bottom -= y; } */ // Disables options for GM invisible avatars void DisableTalkDialogOptionsForInvisAvatar(HWND hWindow) { LmAvatar tempavatar = player->Avatar(); if (tempavatar.Hidden()) { Button_SetCheck(GetDlgItem(hWindow, IDC_RAW_EMOTE), 1); Button_SetCheck(GetDlgItem(hWindow, IDC_EMOTE), 0); Button_SetCheck(GetDlgItem(hWindow, IDC_TALK), 0); Button_SetCheck(GetDlgItem(hWindow, IDC_SHOUT), 0); ShowWindow(GetDlgItem(hWindow, IDC_TALK), SW_HIDE); ShowWindow(GetDlgItem(hWindow, IDC_SHOUT), SW_HIDE); ShowWindow(GetDlgItem(hWindow, IDC_EMOTE), SW_HIDE); } }
27.172231
147
0.699578
christyganger
d06af26600b503a2b881f5ff5f8e9a08460cf32d
1,452
cpp
C++
examples/multistep/main.cpp
Pan-Maciek/iga-ads
4744829c98cba4e9505c5c996070119e73ba18fa
[ "MIT" ]
7
2018-01-19T00:19:19.000Z
2021-06-22T00:53:00.000Z
examples/multistep/main.cpp
Pan-Maciek/iga-ads
4744829c98cba4e9505c5c996070119e73ba18fa
[ "MIT" ]
66
2021-06-22T22:44:21.000Z
2022-03-16T15:18:00.000Z
examples/multistep/main.cpp
Pan-Maciek/iga-ads
4744829c98cba4e9505c5c996070119e73ba18fa
[ "MIT" ]
6
2017-04-13T19:42:27.000Z
2022-03-26T18:46:24.000Z
// SPDX-FileCopyrightText: 2015 - 2021 Marcin Łoś <marcin.los.91@gmail.com> // SPDX-License-Identifier: MIT #include <cstdlib> #include <exception> #include <iostream> #include "multistep2d.hpp" #include "multistep3d.hpp" #include "scheme.hpp" int main(int argc, char* argv[]) { if (argc < 8) { std::cerr << "Usage: multistep <dim> <p> <n> <scheme> <order> <steps> <dt>" << std::endl; std::cerr << "Scheme format: \"s | a(s-1) ... a(0) | b(s) b(s-1) ... b(0) \"" << std::endl; return 0; } auto D = std::atoi(argv[1]); auto p = std::atoi(argv[2]); auto n = std::atoi(argv[3]); auto scheme_name = std::string{argv[4]}; auto order = std::atoi(argv[5]); auto nsteps = std::atoi(argv[6]); auto dt = std::atof(argv[7]); ads::dim_config dim{p, n}; ads::timesteps_config steps{nsteps, dt}; int ders = 1; try { auto scm = ads::get_scheme(scheme_name); // std::cout << "Scheme: " << scm << std::endl; if (D == 2) { ads::config_2d c{dim, dim, steps, ders}; ads::problems::multistep2d sim{c, scm, order}; sim.run(); } else if (D == 3) { ads::config_3d c{dim, dim, dim, steps, ders}; ads::problems::multistep3d sim{c, scm, order}; sim.run(); } } catch (std::exception const& e) { std::cerr << "Error: " << e.what() << std::endl; std::exit(1); } }
30.25
99
0.53168
Pan-Maciek
d06b3400af1c40f7f62a8edba47d77dba695b222
7,281
cpp
C++
Source/DreamPlace/DreamPlaceCharacter.cpp
YuanweiZHANG/DreamPlace
b005c22e2353e674a0596c078083b82efe9ae733
[ "MIT" ]
null
null
null
Source/DreamPlace/DreamPlaceCharacter.cpp
YuanweiZHANG/DreamPlace
b005c22e2353e674a0596c078083b82efe9ae733
[ "MIT" ]
null
null
null
Source/DreamPlace/DreamPlaceCharacter.cpp
YuanweiZHANG/DreamPlace
b005c22e2353e674a0596c078083b82efe9ae733
[ "MIT" ]
null
null
null
// Copyright Epic Games, Inc. All Rights Reserved. #include "DreamPlaceCharacter.h" #include "HeadMountedDisplayFunctionLibrary.h" #include "Camera/CameraComponent.h" #include "Components/CapsuleComponent.h" #include "Components/InputComponent.h" #include "GameFramework/CharacterMovementComponent.h" #include "GameFramework/Controller.h" #include "GameFramework/SpringArmComponent.h" #include "DreamPlacePlayerState.h" #include "Bullet.h" ////////////////////////////////////////////////////////////////////////// // ADreamPlaceCharacter ADreamPlaceCharacter::ADreamPlaceCharacter() { // Set size for collision capsule GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f); // set our turn rates for input BaseTurnRate = 45.f; BaseLookUpRate = 45.f; // Don't rotate when the controller rotates. Let that just affect the camera. bUseControllerRotationPitch = false; bUseControllerRotationYaw = false; bUseControllerRotationRoll = false; // Configure character movement GetCharacterMovement()->bOrientRotationToMovement = true; // Character moves in the direction of input... GetCharacterMovement()->RotationRate = FRotator(0.0f, 540.0f, 0.0f); // ...at this rotation rate GetCharacterMovement()->JumpZVelocity = 600.f; GetCharacterMovement()->AirControl = 0.2f; // Create a camera boom (pulls in towards the player if there is a collision) CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom")); CameraBoom->SetupAttachment(RootComponent); CameraBoom->TargetArmLength = 300.0f; // The camera follows at this distance behind the character CameraBoom->bUsePawnControlRotation = true; // Rotate the arm based on the controller // Create a follow camera FollowCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("FollowCamera")); FollowCamera->SetupAttachment(CameraBoom, USpringArmComponent::SocketName); // Attach the camera to the end of the boom and let the boom adjust to match the controller orientation FollowCamera->bUsePawnControlRotation = false; // Camera does not rotate relative to arm // Note: The skeletal mesh and anim blueprint references on the Mesh component (inherited from Character) // are set in the derived blueprint asset named MyCharacter (to avoid direct content references in C++) } ////////////////////////////////////////////////////////////////////////// // Input void ADreamPlaceCharacter::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) { // Set up gameplay key bindings check(PlayerInputComponent); PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &ACharacter::Jump); PlayerInputComponent->BindAction("Jump", IE_Released, this, &ACharacter::StopJumping); PlayerInputComponent->BindAxis("MoveForward", this, &ADreamPlaceCharacter::MoveForward); PlayerInputComponent->BindAxis("MoveRight", this, &ADreamPlaceCharacter::MoveRight); // We have 2 versions of the rotation bindings to handle different kinds of devices differently // "turn" handles devices that provide an absolute delta, such as a mouse. // "turnrate" is for devices that we choose to treat as a rate of change, such as an analog joystick PlayerInputComponent->BindAxis("Turn", this, &APawn::AddControllerYawInput); PlayerInputComponent->BindAxis("TurnRate", this, &ADreamPlaceCharacter::TurnAtRate); PlayerInputComponent->BindAxis("LookUp", this, &APawn::AddControllerPitchInput); PlayerInputComponent->BindAxis("LookUpRate", this, &ADreamPlaceCharacter::LookUpAtRate); // Shoot PlayerInputComponent->BindAction("Shoot", IE_Pressed, this, &ADreamPlaceCharacter::Shoot); PlayerInputComponent->BindAction("Shoot", IE_Released, this, &ADreamPlaceCharacter::StopShooting); // Fire PlayerInputComponent->BindAction("Fire", IE_Pressed, this, &ADreamPlaceCharacter::Fire); // handle touch devices PlayerInputComponent->BindTouch(IE_Pressed, this, &ADreamPlaceCharacter::TouchStarted); PlayerInputComponent->BindTouch(IE_Released, this, &ADreamPlaceCharacter::TouchStopped); // VR headset functionality PlayerInputComponent->BindAction("ResetVR", IE_Pressed, this, &ADreamPlaceCharacter::OnResetVR); } void ADreamPlaceCharacter::OnResetVR() { UHeadMountedDisplayFunctionLibrary::ResetOrientationAndPosition(); } void ADreamPlaceCharacter::TouchStarted(ETouchIndex::Type FingerIndex, FVector Location) { Jump(); } void ADreamPlaceCharacter::TouchStopped(ETouchIndex::Type FingerIndex, FVector Location) { StopJumping(); } void ADreamPlaceCharacter::TurnAtRate(float Rate) { // calculate delta for this frame from the rate information AddControllerYawInput(Rate * BaseTurnRate * GetWorld()->GetDeltaSeconds()); } void ADreamPlaceCharacter::LookUpAtRate(float Rate) { // calculate delta for this frame from the rate information AddControllerPitchInput(Rate * BaseLookUpRate * GetWorld()->GetDeltaSeconds()); } void ADreamPlaceCharacter::MoveForward(float Value) { if ((Controller != NULL) && (Value != 0.0f)) { // find out which way is forward const FRotator Rotation = Controller->GetControlRotation(); const FRotator YawRotation(0, Rotation.Yaw, 0); // get forward vector const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X); AddMovementInput(Direction, Value); } } void ADreamPlaceCharacter::MoveRight(float Value) { if ( (Controller != NULL) && (Value != 0.0f) ) { // find out which way is right const FRotator Rotation = Controller->GetControlRotation(); const FRotator YawRotation(0, Rotation.Yaw, 0); // get right vector const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y); // add movement in that direction AddMovementInput(Direction, Value); } } void ADreamPlaceCharacter::Shoot() { IsInShooting = true; } void ADreamPlaceCharacter::StopShooting() { IsInShooting = false; } void ADreamPlaceCharacter::Fire() { if (ProjectileClass) { // Get camera position FVector CharacterLocation; FRotator CharacterRotation; //USkeletalMeshComponent *GunMeshComponent = GetMesh(); //GunMeshComponent->GetSocketWorldLocationAndRotation(TEXT("gun_Socket"), CharacterLocation, CharacterRotation); CharacterLocation = GetActorLocation(); // Adjuct to the gun's location CharacterLocation += FVector(0.0f, 0.0f, 65.0f); CharacterRotation = GetActorRotation(); //GetActorEyesViewPoint(CameraLocation, CameraRotation); // Change muzzle offset from camera space to world space FVector MuzzleLocation = CharacterLocation + FTransform(CharacterRotation).TransformVector(MuzzleOffset); FRotator MuzzleRotation = CharacterRotation; MuzzleRotation.Pitch += 0.0f; UWorld* World = GetWorld(); if (World) { FActorSpawnParameters SpawnParams; SpawnParams.Owner = this; SpawnParams.Instigator = GetInstigator(); // Instigater is private // Generate the bullet ABullet* Bullet = World->SpawnActor<ABullet>(ProjectileClass, MuzzleLocation, MuzzleRotation, SpawnParams); if (Bullet) { // Set bullet's initial direction FVector LaunchDirection = MuzzleRotation.Vector(); Bullet->FireInDirection(LaunchDirection); } } } } void ADreamPlaceCharacter::AddScore() { GetPlayerState()->SetScore(GetPlayerState()->GetScore() + 1); } int ADreamPlaceCharacter::GetScore() { return (int)GetPlayerState()->GetScore(); }
35.691176
180
0.757039
YuanweiZHANG
d072835d11b23cf20363c92f5d5a2a057f3a7b3c
4,631
cpp
C++
LeapMotion/src/leap/LeapListener.cpp
kondrak/oculusvr_samples
553c2f6f6c1dcf5071aa3c423436d92449eb2038
[ "MIT" ]
64
2015-06-16T18:39:34.000Z
2022-03-22T14:13:23.000Z
LeapMotion/src/leap/LeapListener.cpp
kondrak/oculusvr_samples
553c2f6f6c1dcf5071aa3c423436d92449eb2038
[ "MIT" ]
null
null
null
LeapMotion/src/leap/LeapListener.cpp
kondrak/oculusvr_samples
553c2f6f6c1dcf5071aa3c423436d92449eb2038
[ "MIT" ]
13
2015-07-01T09:20:37.000Z
2020-11-06T17:12:36.000Z
#include "leap/LeapListener.hpp" #include "leap/LeapLogger.hpp" #ifdef _DEBUG #define LEAP_DEBUG_ENABLED #endif void LeapListener::onInit(const Leap::Controller& controller) { LOG_MESSAGE("[LeapMotion] Initialized"); } void LeapListener::onConnect(const Leap::Controller& controller) { LOG_MESSAGE("[LeapMotion] Device Connected"); // track all the gestures controller.enableGesture(Leap::Gesture::TYPE_CIRCLE); controller.enableGesture(Leap::Gesture::TYPE_KEY_TAP); controller.enableGesture(Leap::Gesture::TYPE_SCREEN_TAP); controller.enableGesture(Leap::Gesture::TYPE_SWIPE); // allow processing images + optimize for HMD controller.setPolicy(static_cast<Leap::Controller::PolicyFlag>(Leap::Controller::POLICY_IMAGES | Leap::Controller::POLICY_OPTIMIZE_HMD)); } void LeapListener::onDisconnect(const Leap::Controller& controller) { // Note: not dispatched when running in a debugger. LOG_MESSAGE("[LeapMotion] Device Disconnected"); } void LeapListener::onExit(const Leap::Controller& controller) { LOG_MESSAGE("[LeapMotion] Exited"); } void LeapListener::onFrame(const Leap::Controller& controller) { // Get the most recent frame and report some basic information const Leap::Frame frame = controller.frame(); #ifdef LEAP_DEBUG_ENABLED debugFrameInfo(frame); #endif Leap::HandList hands = frame.hands(); for (Leap::HandList::const_iterator hl = hands.begin(); hl != hands.end(); ++hl) { // Get the first hand const Leap::Hand hand = *hl; // Get the Arm bone Leap::Arm arm = hand.arm(); #ifdef LEAP_DEBUG_ENABLED debugHandInfo(hand); debugArmInfo(arm); #endif // Get fingers const Leap::FingerList fingers = hand.fingers(); for (Leap::FingerList::const_iterator fl = fingers.begin(); fl != fingers.end(); ++fl) { const Leap::Finger finger = *fl; #ifdef LEAP_DEBUG_ENABLED debugFingerInfo(finger); #endif // Get finger bones for (int b = 0; b < 4; ++b) { Leap::Bone::Type boneType = static_cast<Leap::Bone::Type>(b); Leap::Bone bone = finger.bone(boneType); #ifdef LEAP_DEBUG_ENABLED debugBoneInfo(bone, boneType); #endif } } } // Get tools const Leap::ToolList tools = frame.tools(); for (Leap::ToolList::const_iterator tl = tools.begin(); tl != tools.end(); ++tl) { const Leap::Tool tool = *tl; #ifdef LEAP_DEBUG_ENABLED debugToolInfo(tool); #endif } // Get gestures const Leap::GestureList gestures = frame.gestures(); for (int g = 0; g < gestures.count(); ++g) { Leap::Gesture gesture = gestures[g]; switch (gesture.type()) { case Leap::Gesture::TYPE_CIRCLE: { Leap::CircleGesture circle = gesture; #ifdef LEAP_DEBUG_ENABLED debugCircleGestureInfo(circle, controller); #endif break; } case Leap::Gesture::TYPE_SWIPE: { Leap::SwipeGesture swipe = gesture; #ifdef LEAP_DEBUG_ENABLED debugSwipeGestureInfo(swipe); #endif break; } case Leap::Gesture::TYPE_KEY_TAP: { Leap::KeyTapGesture tap = gesture; #ifdef LEAP_DEBUG_ENABLED debugKeyTapGestureInfo(tap); #endif break; } case Leap::Gesture::TYPE_SCREEN_TAP: { Leap::ScreenTapGesture screentap = gesture; #ifdef LEAP_DEBUG_ENABLED debugScreenTapGestureInfo(screentap); #endif break; } default: LOG_MESSAGE_ASSERT(false, "Unknown gesture type."); break; } } } void LeapListener::onFocusGained(const Leap::Controller& controller) { LOG_MESSAGE("[LeapMotion] Focus Gained"); } void LeapListener::onFocusLost(const Leap::Controller& controller) { LOG_MESSAGE("[LeapMotion] Focus Lost"); } void LeapListener::onDeviceChange(const Leap::Controller& controller) { LOG_MESSAGE("[LeapMotion] Device Changed"); const Leap::DeviceList devices = controller.devices(); for (int i = 0; i < devices.count(); ++i) { #ifdef LEAP_DEBUG_ENABLED debugDeviceInfo(devices[i]); #endif } } void LeapListener::onServiceConnect(const Leap::Controller& controller) { LOG_MESSAGE("[LeapMotion] Service Connected"); } void LeapListener::onServiceDisconnect(const Leap::Controller& controller) { LOG_MESSAGE("[LeapMotion] Service Disconnected"); }
26.3125
141
0.635932
kondrak
d072ddb0cb8f3cc8a41af4c90db3edac8f827734
549
cpp
C++
test/src/gl/GLDemo.cpp
tjakway/pyramid-scheme-simulator
4de02ac120b39185342f433999c2d360a7ccbf7e
[ "MIT" ]
null
null
null
test/src/gl/GLDemo.cpp
tjakway/pyramid-scheme-simulator
4de02ac120b39185342f433999c2d360a7ccbf7e
[ "MIT" ]
null
null
null
test/src/gl/GLDemo.cpp
tjakway/pyramid-scheme-simulator
4de02ac120b39185342f433999c2d360a7ccbf7e
[ "MIT" ]
null
null
null
#include "gl/GLBackend.hpp" #include "PopulationGraph.hpp" #include "TestConfig.hpp" #include "BasicGraphSetup.hpp" namespace pyramid_scheme_simulator { TEST_F(BasicGraphSetup, gldemo) { gl::GLBackend backend( Config::Defaults::defaultGraphLayoutOptions, Config::Defaults::defaultWindowOptions); backend.exportData( std::make_shared<Simulation::Backend::Data>( std::shared_ptr<PopulationGraph>(tinyGraph->clone()), 0, nullptr, nullptr, nullptr)); backend.join(); } }
22.875
69
0.672131
tjakway
d07a4198198787828a7b5b9c0a702f82fb336dbf
8,746
cpp
C++
src/Network/msgitem.cpp
COPS-Projects/COPS-v7-Emulator
ccf377023b0399dc55675577c713ca7440000a80
[ "BSD-2-Clause" ]
2
2019-02-09T20:55:32.000Z
2021-08-12T12:15:03.000Z
src/Network/msgitem.cpp
COPS-Projects/COPS-v7-Emulator
ccf377023b0399dc55675577c713ca7440000a80
[ "BSD-2-Clause" ]
null
null
null
src/Network/msgitem.cpp
COPS-Projects/COPS-v7-Emulator
ccf377023b0399dc55675577c713ca7440000a80
[ "BSD-2-Clause" ]
5
2016-06-27T04:17:38.000Z
2021-08-12T12:15:04.000Z
/** * ****** COPS v7 Emulator - Open Source ****** * Copyright (C) 2012 - 2014 Jean-Philippe Boivin * * Please read the WARNING, DISCLAIMER and PATENTS * sections in the LICENSE file. */ #include "msgitem.h" #include "client.h" #include "entity.h" #include "player.h" #include "npc.h" #include "item.h" #include "gamemap.h" #include "world.h" #include "database.h" #include "msgiteminfo.h" #include <algorithm> // max using namespace std; MsgItem :: MsgItem(uint32_t aUID, Action aAction) : Msg(sizeof(MsgInfo)), mInfo((MsgInfo*)mBuf) { create(aUID, 0, 0, aAction); } MsgItem :: MsgItem(uint32_t aUID, uint32_t aData, Action aAction) : Msg(sizeof(MsgInfo)), mInfo((MsgInfo*)mBuf) { create(aUID, aData, 0, aAction); } MsgItem :: MsgItem(uint8_t** aBuf, size_t aLen) : Msg(aBuf, aLen), mInfo((MsgInfo*)mBuf) { ASSERT(aLen >= sizeof(MsgInfo)); #if BYTE_ORDER == BIG_ENDIAN swap(mBuf); #endif } MsgItem :: ~MsgItem() { } void MsgItem :: create(uint32_t aUID, uint32_t aData, uint32_t aTargetUID, Action aAction) { mInfo->Header.Length = mLen; mInfo->Header.Type = MSG_ITEM; mInfo->UniqId = aUID; mInfo->Data = aData; mInfo->Action = (uint16_t)aAction; mInfo->Timestamp = timeGetTime(); mInfo->TargetUID = aTargetUID; } void MsgItem :: process(Client* aClient) { ASSERT(aClient != nullptr); ASSERT(aClient->getPlayer() != nullptr); static const World& world = World::getInstance(); // singleton static const Database& db = Database::getInstance(); // singleton // Client& client = *aClient; Player& player = *aClient->getPlayer(); switch (mInfo->Action) { case ACTION_BUY: { Npc* npc = nullptr; if (!world.queryNpc(&npc, mInfo->UniqId)) return; if (!npc->isShopNpc()) return; if (player.getMapId() != npc->getMapId()) return; if (GameMap::distance(player.getPosX(), player.getPosY(), npc->getPosX(), npc->getPosY()) > Entity::CELLS_PER_VIEW) return; // TODO ? shop instead of query ? const Item::Info* info = nullptr; uint8_t moneytype = 0; if (IS_SUCCESS(db.getItemFromShop(&info, moneytype, mInfo->UniqId, mInfo->Data))) { switch (moneytype) { case 0: // money { uint32_t price = info->Price; if (player.getMoney() < price) { player.sendSysMsg(STR_NOT_SO_MUCH_MONEY); return; } if (player.awardItem(*info, true)) ASSERT(player.spendMoney(price, true)); break; } case 1: // CPs { uint32_t price = info->CPs; if (player.getCPs() < price) { player.sendSysMsg(STR_NOT_SO_MUCH_MONEY); return; } if (player.awardItem(*info, true)) ASSERT(player.spendMoney(price, true)); break; } default: ASSERT(false); break; } } break; } case ACTION_SELL: { Npc* npc = nullptr; if (!world.queryNpc(&npc, mInfo->UniqId)) return; if (!npc->isShopNpc()) return; if (player.getMapId() != npc->getMapId()) return; if (GameMap::distance(player.getPosX(), player.getPosY(), npc->getPosX(), npc->getPosY()) > Entity::CELLS_PER_VIEW) return; Item* item = player.getItem(mInfo->Data); if (item == nullptr) { player.sendSysMsg(STR_ITEM_NOT_FOUND); return; } if (!item->isSellEnable()) { player.sendSysMsg(STR_NOT_SELL_ENABLE); return; } uint32_t money = item->getSellPrice(); if (!player.eraseItem(mInfo->Data, true)) { player.sendSysMsg(STR_ITEM_INEXIST); return; } if (!player.gainMoney(money, true)) player.sendSysMsg(STR_MONEYBAG_FULL); break; } case ACTION_USE: { if (mInfo->TargetUID == 0 || mInfo->TargetUID == player.getUID()) { Item* item = player.getItem(mInfo->UniqId); if (item != nullptr) { if (!player.useItem(*item, (Item::Position)mInfo->Data, true)) player.sendSysMsg(STR_UNABLE_USE_ITEM); } else player.sendSysMsg(STR_ITEM_INEXIST); } else { printf("MsgItem::use() -> useItemTo(%u, %u)\n", mInfo->TargetUID, mInfo->UniqId); ASSERT(false); } break; } case ACTION_EQUIP: { ASSERT(false); break; } case ACTION_REPAIR: { Item* item = player.getItem(mInfo->UniqId); if (item == nullptr) { player.sendSysMsg(STR_ITEM_NOT_FOUND); return; } if (!item->isRepairEnable() || item->getAmount() > item->getAmountLimit()) { player.sendSysMsg(STR_REPAIR_FAILED); return; } uint32_t money = item->getRepairCost(); int32_t repair = item->getAmountLimit() - item->getAmount(); if (money == 0 || repair <= 0) return; if (!player.spendMoney(money, true)) { player.sendSysMsg(STR_REPAIR_NO_MONEY, money); return; // not enough money } // max durability changed if (item->isEquipment()) { if (item->getAmount() < item->getAmountLimit() / 2) { if (random(0, 100) < 5) item->setAmountLimit(max(1, item->getAmountLimit() - 1)); } else if (item->getAmount() < item->getAmountLimit() / 10) { if (random(0, 100) < 10) item->setAmountLimit(max(1, item->getAmountLimit() - 1)); } else { if (random(0, 100) < 80) item->setAmountLimit(max(1, item->getAmountLimit() - 1)); } } item->setAmount(item->getAmountLimit(), true); MsgItemInfo msg(*item, MsgItemInfo::ACTION_UPDATE); player.send(&msg); break; } case ACTION_REPAIRALL: { ASSERT(false); break; } case ACTION_COMPLETE_TASK: { player.send(this); break; } default: { fprintf(stdout, "Unknown action[%04u], data=[%d]\n", mInfo->Action, mInfo->Data); break; } } } void MsgItem :: swap(uint8_t* aBuf) const { ASSERT(aBuf != nullptr); MsgInfo* info = (MsgInfo*)aBuf; info->UniqId = bswap32(info->UniqId); info->Data = bswap32(info->Data); info->Action = bswap32(info->Action); info->Timestamp = bswap32(info->Timestamp); info->TargetUID = bswap32(info->TargetUID); }
30.58042
101
0.424194
COPS-Projects
4edc6303ac53d563e269047ebedbb45641bebf87
4,704
cpp
C++
Examples/Basics/Particles/Combined/ParticlesCombined.cpp
SuperflyJon/VulkanPlayground
891b88227b66fc1e933ff77c1603e5d685d89047
[ "MIT" ]
2
2021-01-25T16:59:56.000Z
2021-02-14T21:11:05.000Z
Examples/Basics/Particles/Combined/ParticlesCombined.cpp
SuperflyJon/VulkanPlayground
891b88227b66fc1e933ff77c1603e5d685d89047
[ "MIT" ]
null
null
null
Examples/Basics/Particles/Combined/ParticlesCombined.cpp
SuperflyJon/VulkanPlayground
891b88227b66fc1e933ff77c1603e5d685d89047
[ "MIT" ]
1
2021-04-23T10:20:53.000Z
2021-04-23T10:20:53.000Z
#include <VulkanPlayground\Includes.h> #include <random> #include "..\ParticleSystem.h" class ParticlesCombinedApp : public VulkanApplication3DLight { struct VertInfo { glm::vec3 lightPos; float pad1; glm::vec3 viewPos; }; public: ParticlesCombinedApp() { TidyObjectOnExit(particles); } void ResetScene() override { CalcPositionMatrix({ 0.0f, 0.0f, 0.0f }, { -70.0f, -45.0f, 0 }, 0, 30); SetupLighting({ 0.0f, -35.0f, 0.0f }, 0.0f, 0.5f, 0.1f, 32.0f, model.GetModelSize()); } glm::vec4 GetClearColour() const override { return { 0, 0, 0, 1 }; } void SetupObjects(VulkanSystem& system, RenderPass& renderPass, VkExtent2D workingExtent) override { model.CorrectDodgyModelOnLoad(); model.LoadToGpu(system, VulkanPlayground::GetModelFile("Basics", "fireplace.obj"), Attribs::PosNormTexTanBitan); descriptor.AddUniformBuffer(system, 0, mvpUBO, "MVP"); descriptor.AddUniformBuffer(system, 1, vertInfo, "vertInfo"); descriptor.AddTexture(system, 3, texture, VulkanPlayground::GetModelFile("Basics", "fireplace_colormap_bc3_unorm.ktx"), VK_FORMAT_BC3_UNORM_BLOCK); descriptor.AddTexture(system, 4, normalMap, VulkanPlayground::GetModelFile("Basics", "fireplace_normalmap_bc3_unorm.ktx"), VK_FORMAT_BC3_UNORM_BLOCK); descriptor.AddUniformBuffer(system, 2, lightUBO, "Lighting", VK_SHADER_STAGE_FRAGMENT_BIT); CreateDescriptor(system, descriptor, "Draw"); pipeline.SetupVertexDescription(Attribs::PosNormTexTanBitan); pipeline.LoadShader(system, "NormalMap"); CreatePipeline(system, renderPass, pipeline, descriptor, workingExtent, "Main"); smoke.SetAddressMode(VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER); // Avoid edges bleeding over flame.SetAddressMode(VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER); fireDescriptor.AddUniformBuffer(system, 0, fireUniformBuffer, "Fire"); fireDescriptor.AddUniformBuffer(system, 3, viewport, "size"); fireDescriptor.AddTexture(system, 1, flame, VulkanPlayground::GetModelFile("Basics", "particle_flame.ktx")); fireDescriptor.AddTexture(system, 2, smoke, VulkanPlayground::GetModelFile("Basics", "particle_smoke.ktx")); CreateDescriptor(system, fireDescriptor, "Fire"); std::vector<Attribs::Attrib> fireAttribs{ {0, Attribs::Type::Position, VK_FORMAT_R32G32B32_SFLOAT}, {1, Attribs::Type::Misc, VK_FORMAT_R32_SFLOAT}, // Alpha {2, Attribs::Type::Misc, VK_FORMAT_R32_SFLOAT}, // Size {3, Attribs::Type::Misc, VK_FORMAT_R32_SFLOAT}, // Rotation {4, Attribs::Type::Misc, VK_FORMAT_R32_SINT} // Type }; fireGraphicsPipeline.SetupVertexDescription(fireAttribs); fireGraphicsPipeline.AddPushConstant(system, sizeof(int), VK_SHADER_STAGE_FRAGMENT_BIT); fireGraphicsPipeline.SetTopology(VK_PRIMITIVE_TOPOLOGY_POINT_LIST); fireGraphicsPipeline.SetDepthWriteEnabled(false); fireGraphicsPipeline.EnableBlending(VK_BLEND_FACTOR_DST_ALPHA, VK_BLEND_FACTOR_ONE); fireGraphicsPipeline.LoadShaderDiffNames(system, "Particles", "Fire"); CreatePipeline(system, renderPass, fireGraphicsPipeline, fireDescriptor, workingExtent, "Fire"); constexpr auto PARTICLE_COUNT = 500; particles.Prepare(system, PARTICLE_COUNT); viewport().X = (float)windowWidth; viewport.CopyToDevice(system); }; void DrawScene(VkCommandBuffer commandBuffer) override { pipeline.Bind(commandBuffer, descriptor); model.Draw(commandBuffer); // Draw fire in 2 passes to get the blending okay fireGraphicsPipeline.Bind(commandBuffer, fireDescriptor.GetDescriptorSet()); int draw = FLAME_PARTICLE; fireGraphicsPipeline.PushConstant(commandBuffer, &draw); particles.Draw(commandBuffer); draw = SMOKE_PARTICLE; fireGraphicsPipeline.PushConstant(commandBuffer, &draw); particles.Draw(commandBuffer); } void UpdateScene(VulkanSystem& system, float frameTime) override { fireUniformBuffer() = mvpUBO(); fireUniformBuffer().model = glm::translate(fireUniformBuffer().model, glm::vec3(-1.4f, 5.0f, 0.4f)); // Center fire on logs fireUniformBuffer.CopyToDevice(system); mvpUBO().model = glm::scale(mvpUBO().model, glm::vec3(10.0f)); particles.Update(frameTime); vertInfo().lightPos = lightUBO().lightPos; vertInfo().lightPos.x += jitterX.Vary(frameTime) * 25.0f; vertInfo().lightPos.z += jitterZ.Vary(frameTime) * 25.0f; vertInfo().viewPos = lightUBO().viewPos; vertInfo.CopyToDevice(system); } private: Descriptor descriptor; Pipeline pipeline; Model model; Texture texture, normalMap; UBO<VertInfo> vertInfo; UBO<MVP> fireUniformBuffer; Texture flame, smoke; Particles particles; Pipeline fireGraphicsPipeline; Descriptor fireDescriptor; struct Viewport { float X; }; UBO<Viewport> viewport; Jitter jitterX, jitterZ; }; DECLARE_APP(ParticlesCombined)
35.636364
152
0.764456
SuperflyJon
4edc78cd9acce413332ebc186c7039492aaece2a
1,038
cc
C++
src/congestion/util.cc
codefan-byte/supersim
38bd445dcd21fdb78fd28819e0d4dfaa6d1fd651
[ "Apache-2.0" ]
17
2017-05-09T07:08:41.000Z
2021-08-03T01:22:09.000Z
src/congestion/util.cc
codefan-byte/supersim
38bd445dcd21fdb78fd28819e0d4dfaa6d1fd651
[ "Apache-2.0" ]
32
2020-02-26T00:02:29.000Z
2022-01-20T23:23:55.000Z
src/congestion/util.cc
codefan-byte/supersim
38bd445dcd21fdb78fd28819e0d4dfaa6d1fd651
[ "Apache-2.0" ]
13
2016-12-02T22:01:04.000Z
2020-03-23T16:44:04.000Z
/* * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. 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 "congestion/util.h" #include <cmath> bool congestionEqualTo(f64 _cong1, f64 _cong2) { return std::abs(_cong1 - _cong2) < CONGESTION_TOLERANCE; } bool congestionLessThan(f64 _cong1, f64 _cong2) { return (_cong2 - _cong1) >= CONGESTION_TOLERANCE; } bool congestionGreaterThan(f64 _cong1, f64 _cong2) { return (_cong1 - _cong2) >= CONGESTION_TOLERANCE; }
34.6
76
0.753372
codefan-byte
4ede4bf6a196bc6187236dd980b7e27d12b5a8a3
329
hpp
C++
src/Game.hpp
rainstormstudio/Rainstorm-Engine
f27ead834d93343aff22d8fc304cc8e91b19ac6e
[ "MIT" ]
1
2020-05-03T16:26:32.000Z
2020-05-03T16:26:32.000Z
src/Game.hpp
rainstormstudio/Rainstorm-Engine
f27ead834d93343aff22d8fc304cc8e91b19ac6e
[ "MIT" ]
null
null
null
src/Game.hpp
rainstormstudio/Rainstorm-Engine
f27ead834d93343aff22d8fc304cc8e91b19ac6e
[ "MIT" ]
null
null
null
#pragma once #include "Timer.hpp" #include "WindowManager.hpp" class Game { private: bool mIsRunning; Timer *timer; WindowManager mainWindow; public: Game(); bool isRunning(); void initialize(int initWidth, int initHeight); void processEvent(); void update(); void render(); void destroy(); ~Game(); };
14.304348
49
0.680851
rainstormstudio
4ee2e694d6fd1e5aacae17acd46f3528def3fd0e
587
hpp
C++
src/net/Serialize.hpp
kochol/ari2
ca185191531acc1954cd4acfec2137e32fdb5c2d
[ "MIT" ]
81
2018-12-11T20:48:41.000Z
2022-03-18T22:24:11.000Z
src/net/Serialize.hpp
kochol/ari2
ca185191531acc1954cd4acfec2137e32fdb5c2d
[ "MIT" ]
7
2020-04-19T11:50:39.000Z
2021-11-12T16:08:53.000Z
src/net/Serialize.hpp
kochol/ari2
ca185191531acc1954cd4acfec2137e32fdb5c2d
[ "MIT" ]
4
2019-04-24T11:51:29.000Z
2021-03-10T05:26:33.000Z
#pragma once #include <Meta.h> namespace ari::net { template<typename Class, typename Stream, typename = std::enable_if_t <meta::isRegistered<Class>()>> bool Serialize(Stream & stream, Class & obj, const int& member_index = -1); template <typename Class, typename Stream, typename = std::enable_if_t <!meta::isRegistered<Class>()>, typename = void> bool Serialize(Stream & stream, Class & obj, const int& member_index = -1); template <typename Class, typename Stream> bool SerializeBasic(Stream& stream, Class& obj); } // namespace ari::net #include "Serialize.inl"
25.521739
76
0.715503
kochol
4ee3a6be0ead88efed4827d7f6c00783b1e9a1f0
3,171
hpp
C++
Core/History/HistoryTreeView.hpp
Feldrise/SieloNavigateurBeta
faa5fc785271b49d26237a5e9985d6fa22565076
[ "MIT" ]
89
2018-04-26T14:28:13.000Z
2019-07-03T03:58:17.000Z
Core/History/HistoryTreeView.hpp
inviu/webBrowser
37b24eded2e168e43b3f9c9ccc0487ee59410332
[ "MIT" ]
51
2018-04-26T12:43:00.000Z
2019-04-24T20:39:59.000Z
Core/History/HistoryTreeView.hpp
inviu/webBrowser
37b24eded2e168e43b3f9c9ccc0487ee59410332
[ "MIT" ]
34
2018-05-11T07:09:36.000Z
2019-04-19T08:12:40.000Z
/*********************************************************************************** ** MIT License ** ** ** ** Copyright (c) 2018 Victor DENIS (victordenis01@gmail.com) ** ** ** ** Permission is hereby granted, free of charge, to any person obtaining a copy ** ** of this software and associated documentation files (the "Software"), to deal ** ** in the Software without restriction, including without limitation the rights ** ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ** ** copies of the Software, and to permit persons to whom the Software is ** ** furnished to do so, subject to the following conditions: ** ** ** ** The above copyright notice and this permission notice shall be included in all ** ** copies or substantial portions of the Software. ** ** ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ** ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ** ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ** ** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ** ** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ** ** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ** ** SOFTWARE. ** ***********************************************************************************/ #pragma once #ifndef SIELOBROWSER_HistoryTreeView_HPP #define SIELOBROWSER_HistoryTreeView_HPP #include "SharedDefines.hpp" #include <QWidget> #include <QTreeView> #include <QMouseEvent> namespace Sn { class History; class HistoryFilterModel; class SIELO_SHAREDLIB HistoryTreeView: public QTreeView { Q_OBJECT public: HistoryTreeView(QWidget* parent = nullptr); QUrl selectedUrl() const; signals: // Open url in current tab void urlActivated(const QUrl& url); // Open url in new tab void urlCtrlActivated(const QUrl& url); // Open url in new window void urlShiftActivated(const QUrl& url); // Context menu signal with point mapped to global void contextMenuRequested(const QPoint& point); public slots: void search(const QString& string); void removeSelectedItems(); protected: void contextMenuEvent(QContextMenuEvent* event); void mousePressEvent(QMouseEvent* event); void mouseDoubleClickEvent(QMouseEvent* event); void keyPressEvent(QKeyEvent* event); void drawRow(QPainter* painter, const QStyleOptionViewItem& options, const QModelIndex& index) const; private: History* m_history{nullptr}; HistoryFilterModel* m_filter{nullptr}; }; } #endif //SIELOBROWSER_HistoryTreeView_HPP
40.139241
102
0.580259
Feldrise
4eec2ad0bc960df37cf3eb7f215f5205e6109939
1,846
cpp
C++
ParticlePlay/IMS/Format/EmptyFormat.cpp
spywhere/Legacy-ParticlePlay
0c1ec6e4706f72b64e0408cc79cdeffce535b484
[ "BSD-3-Clause" ]
null
null
null
ParticlePlay/IMS/Format/EmptyFormat.cpp
spywhere/Legacy-ParticlePlay
0c1ec6e4706f72b64e0408cc79cdeffce535b484
[ "BSD-3-Clause" ]
null
null
null
ParticlePlay/IMS/Format/EmptyFormat.cpp
spywhere/Legacy-ParticlePlay
0c1ec6e4706f72b64e0408cc79cdeffce535b484
[ "BSD-3-Clause" ]
null
null
null
#include "EmptyFormat.hpp" ppEmptyFormat::ppEmptyFormat(ppIMS* ims, Sint64 length, ppFormat* audioFormat) : ppFormat(ims){ this->length = length; this->sourceAudioFormat = audioFormat; } int ppEmptyFormat::Init(const char *filename, bool stereo){ int status = ppFormat::Init(filename, stereo); if(status>0){ return status; } this->audioChannels = (stereo?2:1); this->audioTracks = 1; this->bitPerSample = 16; this->audioFormat = (stereo?AL_FORMAT_STEREO16:AL_FORMAT_MONO16); return 0; } Sint64 ppEmptyFormat::Read(char *bufferData, Sint64 position, Sint64 size, int track){ for(Sint64 i=0;i<size;i++){ bufferData[i] = 0; } return size; } Sint64 ppEmptyFormat::ActualPosition(Sint64 relativePosition){ return this->sourceAudioFormat->ActualPosition(relativePosition); // return relativePosition*this->audioChannels/(this->stereo?2:1); } Sint64 ppEmptyFormat::RelativePosition(Sint64 actualPosition){ return this->sourceAudioFormat->RelativePosition(actualPosition); // return actualPosition/this->audioChannels*(this->stereo?2:1); } Sint64 ppEmptyFormat::GetPositionLength(){ return this->length; } float ppEmptyFormat::PositionToTime(Sint64 position){ return this->sourceAudioFormat->PositionToTime(position); // float sampleLength = position * 8 / (this->audioChannels * this->bitPerSample); // return sampleLength / this->sourceAudioFormat->GetSampleRate(); } Sint64 ppEmptyFormat::TimeToPosition(float time){ return this->sourceAudioFormat->TimeToPosition(time); float sampleLength = time * this->sourceAudioFormat->GetSampleRate(); return sampleLength * this->audioChannels * this->bitPerSample / 8; } int ppEmptyFormat::GetSampleRate(){ return this->sourceAudioFormat->GetSampleRate(); } ALuint ppEmptyFormat::GetFormat(){ return this->audioFormat; } int ppEmptyFormat::GetTotalTrack(){ return 1; }
28.84375
95
0.762189
spywhere
4efd58df76a0570e6c33bcf2ae94ba2bb45c1684
1,183
hpp
C++
include/gbVk/config.hpp
ComicSansMS/GhulbusVulkan
b24ffb892a7573c957aed443a3fbd7ec281556e7
[ "MIT" ]
null
null
null
include/gbVk/config.hpp
ComicSansMS/GhulbusVulkan
b24ffb892a7573c957aed443a3fbd7ec281556e7
[ "MIT" ]
null
null
null
include/gbVk/config.hpp
ComicSansMS/GhulbusVulkan
b24ffb892a7573c957aed443a3fbd7ec281556e7
[ "MIT" ]
null
null
null
#ifndef GHULBUS_LIBRARY_INCLUDE_GUARD_VULKAN_GBVK_CONFIG_HPP #define GHULBUS_LIBRARY_INCLUDE_GUARD_VULKAN_GBVK_CONFIG_HPP /** @file * * @brief General configuration for Vulkan. * @author Andreas Weis (der_ghulbus@ghulbus-inc.de) */ #include <gbVk/gbVk_Export.hpp> /** Specifies the API for a function declaration. * When building as a dynamic library, this is used to mark the functions that will be exported by the library. */ #define GHULBUS_VULKAN_API GHULBUS_LIBRARY_GBVK_EXPORT /** \namespace GhulbusVulkan Namespace for the GhulbusVulkan library. * The implementation internally always uses this macro `GHULBUS_VULKAN_NAMESPACE` to refer to the namespace. * When building GhulbusVulkan yourself, you can globally redefine this macro to move to a different namespace. */ #ifndef GHULBUS_VULKAN_NAMESPACE # define GHULBUS_VULKAN_NAMESPACE GhulbusVulkan #endif // Vulkan SDK 1.2.154.1 #define GHULBUS_VULKAN_EXPECTED_VK_HEADER_VERSION 154 #ifdef GHULBUS_CONFIG_VULKAN_PLATFORM_WIN32 # define VK_USE_PLATFORM_WIN32_KHR # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN # endif # ifndef NOMINMAX # define NOMINMAX # endif #endif #endif
30.333333
111
0.800507
ComicSansMS
f60127fab3d565dccf2af1994d07743f9b972a1e
6,346
cpp
C++
ramp_14890.cpp
goongg/SamSung
d07f8ca06fa21c2c26f63f89978b79a204373262
[ "CECILL-B" ]
null
null
null
ramp_14890.cpp
goongg/SamSung
d07f8ca06fa21c2c26f63f89978b79a204373262
[ "CECILL-B" ]
null
null
null
ramp_14890.cpp
goongg/SamSung
d07f8ca06fa21c2c26f63f89978b79a204373262
[ "CECILL-B" ]
null
null
null
// 7시 32분 #include <iostream> #include <vector> #include <queue> using namespace std; #define debug 0 class ramp { int n, l; vector<int> t; vector<bool> poss_r;// 가능 행 조사 vector<bool> poss_c;// 가능 열 조사 vector<bool> v; public: void input() { cin>>n >>l; t = vector<int>(n*n); poss_r = vector<bool>(n); poss_c = vector<bool>(n); v = vector<bool>(n); for(int i=0; i<n*n; i++) cin>>t[i]; } int check() { int ret=0; vector<bool> visit ; for(int i=0; i<n; i++) { poss_r[i] =1; visit = v; //행 조사 for(int j=0; j<n-1; j++) { int cur= t[i*n+j]; int next= t[i*n+j+1]; if(cur == next) { //do noting } else if( cur == next -1) { if(l==n) { poss_r[i] =0; break; } if(visit[j]) { poss_r[i] =0; break; } visit[j]=1; for(int k =1 ; k<l; k++) { if( j-k >=0 && visit[j-k]) { poss_r[i] =0; break; } if( !(j-k >=0 && cur == t[i*n +j-k]) ) { poss_r[i] =0; break; } visit[j-k]=1; } } else if( cur == next +1){ if(l==n) { poss_r[i] =0; break; } if(visit[j+1]) { poss_r[i] =0; break; } visit[j+1]=1; for(int k =1 ; k<l; k++) { if( j+1+k < n && visit[j+1+k]) { poss_r[i] =0; break; } if( !(j+1+k < n && next == t[i*n +j+1+k])) { poss_r[i] =0; break; } visit[j+1+k]=1; } } else { poss_r[i] =0; break; } } if(poss_r[i]) ret++; #if debug cout<<i<<"행:"<<poss_r[i]<<endl; #endif } #if debug cout<<endl; #endif //열 조사 for(int j=0; j<n; j++) { poss_c[j] =1; visit = v; for(int i=0; i<n-1; i++) { int cur= t[i*n+j]; int next= t[(i+1)*n+j]; if(cur == next) { //do noting } else if( cur == next -1) { if(l==n) { poss_c[j] =0; break; } if(visit[i]) { poss_c[j] =0; break; } visit[i]=1; for(int k =1 ; k<l; k++){ if( i-k >=0 && visit[i-k ]) { poss_c[j] =0; break; } if( !(i-k >=0 && cur == t[(i-k)*n +j])) { poss_c[j] =0; break; } visit[i-k ]=1; } } else if( cur == next +1) { if(l==n) { poss_c[j] =0; break; } if(visit[i+1]) { poss_c[j] =0; break; } visit[i+1]=1; for(int k =1 ; k<l; k++){ if( i+1+k <n && visit[i+1+k ]) { poss_c[i] =0; break; } if( !(i+1+k < n && next == t[(i+1+k)*n +j])) { poss_c[j] =0; break; } visit[i+1+k ]=1; } } else { poss_c[j] =0; break; } } if(poss_c[j]) ret++; #if debug cout<<j<<"열:"<<poss_c[j]<<endl; #endif } return ret; } }; int main() { ramp r; r.input(); cout<<r.check(); return 0; }
29.793427
73
0.180586
goongg
f601c002dc84eb5f812cf6abd865d61c25b26fd4
4,725
hpp
C++
src/lib/include/black/internal/formula/alphabet.hpp
black-sat/black
80902240987312fb0e6f00227a06e9f9c9728a67
[ "MIT" ]
4
2020-09-30T15:16:22.000Z
2021-09-20T15:02:39.000Z
src/lib/include/black/internal/formula/alphabet.hpp
teodorov/black
4de280ded5e99cc515141b4acc35137ba32c2469
[ "MIT" ]
42
2020-07-15T13:46:11.000Z
2022-03-10T09:42:43.000Z
src/lib/include/black/internal/formula/alphabet.hpp
teodorov/black
4de280ded5e99cc515141b4acc35137ba32c2469
[ "MIT" ]
3
2020-03-30T14:39:17.000Z
2022-03-18T14:05:33.000Z
// // BLACK - Bounded Ltl sAtisfiability ChecKer // // (C) 2019 Nicola Gigante // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #ifndef BLACK_ALPHABET_IMPL_HPP #define BLACK_ALPHABET_IMPL_HPP #include <black/support/meta.hpp> #include <black/logic/formula.hpp> namespace black::internal { // // Out-of-line definitions of methods of class `alphabet` // template<typename T, REQUIRES_OUT_OF_LINE(internal::is_hashable<T>)> inline atom alphabet::var(T&& label) { if constexpr(std::is_constructible_v<std::string,T>) { return atom{this, allocate_atom(std::string{FWD(label)})}; } else { return atom{this, allocate_atom(FWD(label))}; } } // Out-of-line implementations from the handle_base class in formula.hpp, // placed here to have a complete alphabet type template<typename H, typename F> template<typename FType, typename Arg> std::pair<alphabet *, unary_t *> handle_base<H, F>::allocate_unary(FType type, Arg const&arg) { // The type is templated only because of circularity problems static_assert(std::is_same_v<FType, unary::type>); // Get the alphabet from the argument class alphabet *sigma = arg._alphabet; // Ask the alphabet to actually allocate the formula unary_t *object = sigma->allocate_unary(type, arg._formula); return {sigma, object}; } template<typename H, typename F> template<typename FType, typename Arg1, typename Arg2> std::pair<alphabet *, binary_t *> handle_base<H, F>::allocate_binary(FType type, Arg1 const&arg1, Arg2 const&arg2) { // The type is templated only because of circularity problems static_assert(std::is_same_v<FType, binary::type>); // Check that both arguments come from the same alphabet black_assert(arg1._alphabet == arg2._alphabet); // Get the alphabet from the first argument (same as the second, by now) class alphabet *sigma = arg1._alphabet; // Ask the alphabet to actually allocate the formula binary_t *object = sigma->allocate_binary( type, arg1._formula, arg2._formula ); return {sigma, object}; } } // namespace black::internal /* * Functions from formula.hpp that need the alphabet class */ namespace black::internal { // Conjunct multiple formulas generated from a range, // avoiding useless true formulas at the beginning of the fold template<typename Iterator, typename EndIterator, typename F> formula big_and(alphabet &sigma, Iterator b, EndIterator e, F&& f) { formula acc = sigma.top(); while(b != e) { formula elem = std::forward<F>(f)(*b++); if(elem == sigma.top()) continue; else if(acc == sigma.top()) acc = elem; else acc = acc && elem; } return acc; } template<typename Range, typename F> formula big_and(alphabet &sigma, Range r, F&& f) { return big_and(sigma, begin(r), end(r), std::forward<F>(f)); } // Disjunct multiple formulas generated from a range, // avoiding useless true formulas at the beginning of the fold template<typename Iterator, typename EndIterator, typename F> formula big_or(alphabet &sigma, Iterator b, EndIterator e, F&& f) { formula acc = sigma.bottom(); while(b != e) { formula elem = std::forward<F>(f)(*b++); if(elem == sigma.bottom()) continue; else if(acc == sigma.bottom()) acc = elem; else acc = acc || elem; } return acc; } template<typename Range, typename F> formula big_or(alphabet &sigma, Range r, F&& f) { return big_or(sigma, begin(r), end(r), std::forward<F>(f)); } } #endif // BLACK_ALPHABET_IMPL_HPP
32.363014
80
0.685714
black-sat
f6051e9c65fa8d7bd0a127758e0a25fb0e44b0f4
15,312
cc
C++
src/core/analysis/rnn_scorer_gbeam.cc
5003/jumanpp
9f50ee3d62591936a079ade18c6e1d1e8a6d3463
[ "Apache-2.0" ]
1
2018-03-18T15:53:27.000Z
2018-03-18T15:53:27.000Z
src/core/analysis/rnn_scorer_gbeam.cc
5003/jumanpp
9f50ee3d62591936a079ade18c6e1d1e8a6d3463
[ "Apache-2.0" ]
null
null
null
src/core/analysis/rnn_scorer_gbeam.cc
5003/jumanpp
9f50ee3d62591936a079ade18c6e1d1e8a6d3463
[ "Apache-2.0" ]
null
null
null
// // Created by Arseny Tolmachev on 2017/11/20. // #include "rnn_scorer_gbeam.h" #include "rnn/mikolov_rnn.h" #include "rnn_id_resolver.h" #include "util/stl_util.h" namespace jumanpp { namespace core { namespace analysis { struct GbeamRnnFactoryState { rnn::RnnIdResolver resolver; jumanpp::rnn::mikolov::MikolovRnn rnn; util::ConstSliceable<float> embeddings; util::ConstSliceable<float> nceEmbeddings; rnn::RnnInferenceConfig config; jumanpp::rnn::mikolov::MikolovModelReader rnnReader; util::CodedBuffer codedBuf_; u32 embedSize() const { return rnn.modelHeader().layerSize; } util::ArraySlice<float> embedOf(size_t idx) const { return embeddings.row(idx); } util::ArraySlice<float> nceEmbedOf(size_t idx) const { return nceEmbeddings.row(idx); } util::memory::Manager mgr{64 * 1024}; util::Sliceable<float> bosState{}; void computeBosState(i32 bosId) { auto alloc = mgr.core(); auto zeros = alloc->allocate2d<float>(1, embedSize(), 64); util::fill(zeros, 0); bosState = alloc->allocate2d<float>(1, embedSize(), 64); auto embed = embeddings.row(bosId); util::ConstSliceable<float> embedSlice{embed, embedSize(), 1}; jumanpp::rnn::mikolov::ParallelContextData pcd{zeros, embedSlice, bosState}; rnn.computeNewParCtx(&pcd); } StringPiece rnnMatrix() const { return rnn.matrixAsStringpiece(); } StringPiece embeddingData() const { return StringPiece{ reinterpret_cast<StringPiece::pointer_t>(embeddings.begin()), embeddings.size() * sizeof(float)}; } StringPiece nceEmbedData() const { return StringPiece{ reinterpret_cast<StringPiece::pointer_t>(nceEmbeddings.begin()), nceEmbeddings.size() * sizeof(float)}; } StringPiece maxentWeightData() const { return rnn.maxentWeightsAsStringpiece(); } }; struct GbeamRnnState { const GbeamRnnFactoryState* shared; util::memory::Manager manager{2 * 1024 * 1024}; // 2M std::unique_ptr<util::memory::PoolAlloc> alloc{manager.core()}; rnn::RnnIdContainer container{alloc.get()}; Lattice* lat; const ExtraNodesContext* xtra; u32 scorerIdx; util::Sliceable<i32> ctxIdBuf; util::MutableArraySlice<i32> rightIdBuf; util::Sliceable<float> contextBuf; util::Sliceable<float> embBuf; util::MutableArraySlice<float> scoreBuf; util::MutableArraySlice<util::Sliceable<float>> contexts; void allocateState() { auto numBnd = lat->createdBoundaryCount(); auto gbeamSize = lat->config().globalBeamSize; auto embedSize = shared->rnn.modelHeader().layerSize; contexts = alloc->allocateBuf<util::Sliceable<float>>(numBnd); ctxIdBuf = alloc->allocate2d<i32>( gbeamSize, shared->rnn.modelHeader().maxentOrder - 1); rightIdBuf = alloc->allocateBuf<i32>(gbeamSize); contextBuf = alloc->allocate2d<float>(gbeamSize, embedSize, 64); embBuf = alloc->allocate2d<float>(gbeamSize, embedSize, 64); scoreBuf = alloc->allocateBuf<float>(gbeamSize, 64); contexts.at(1) = shared->bosState; } util::ArraySlice<i32> gatherIds(const rnn::RnnBoundary& rbnd) { size_t nodeCnt = static_cast<size_t>(rbnd.nodeCnt); util::MutableArraySlice<i32> subset{rightIdBuf, 0, nodeCnt}; JPP_INDEBUG(int count = rbnd.nodeCnt); for (auto node = rbnd.node; node != nullptr; node = node->nextInBnd) { subset.at(node->idx) = node->id; JPP_INDEBUG(--count); } JPP_DCHECK_EQ(count, 0); return subset; } util::ConstSliceable<float> gatherContext(const rnn::RnnBoundary& rbnd) { auto subset = contextBuf.topRows(rbnd.nodeCnt); for (auto node = rbnd.node; node != nullptr; node = node->nextInBnd) { auto prev = node->prev; JPP_DCHECK_NE(prev, nullptr); auto ctxRow = subset.row(node->idx); auto present = contexts.at(prev->boundary).row(prev->idx); util::copy_buffer(present, ctxRow); } return subset; } util::ConstSliceable<float> gatherLeftEmbeds(util::ArraySlice<i32> ids) { auto subset = embBuf.topRows(ids.size()); for (int i = 0; i < ids.size(); ++i) { auto embedId = ids[i]; if (embedId == -1) { embedId = 0; } auto embed = shared->embedOf(embedId); auto target = subset.row(i); util::copy_buffer(embed, target); } return subset; } util::Sliceable<float> allocContext(u32 bndIdx, size_t size) { auto buf = alloc->allocate2d<float>(size, shared->embedSize(), 64); contexts.at(bndIdx) = buf; return buf; } Status computeContext(u32 bndIdx) { auto& rbnd = container.rnnBoundary(bndIdx); if (rbnd.nodeCnt == 0) { return Status::Ok(); } auto rnnIds = gatherIds(rbnd); auto inCtx = gatherContext(rbnd); auto embs = gatherLeftEmbeds(rnnIds); auto outCtx = allocContext(bndIdx, rnnIds.size()); jumanpp::rnn::mikolov::ParallelContextData pcd{inCtx, embs, outCtx}; shared->rnn.computeNewParCtx(&pcd); return Status::Ok(); } util::ArraySlice<i32> gatherScoreIds(const rnn::RnnBoundary& rbnd) { size_t scoreCnt = static_cast<size_t>(rbnd.scoreCnt); util::MutableArraySlice<i32> subset{rightIdBuf, 0, scoreCnt}; u32 scoreIdx = 0; for (auto sc = rbnd.scores; sc != nullptr; sc = sc->next) { auto node = sc->rnn; subset.at(scoreIdx) = node->id; scoreIdx += 1; } JPP_DCHECK_EQ(scoreIdx, scoreCnt); return subset; } util::ConstSliceable<i32> gatherPrevStateIds(const rnn::RnnBoundary& rbnd) { auto subset = ctxIdBuf.topRows(rbnd.scoreCnt); auto cnt = ctxIdBuf.rowSize(); u32 scoreIdx = 0; for (auto sc = rbnd.scores; sc != nullptr; sc = sc->next) { auto node = sc->rnn; int idx = 0; auto row = subset.row(scoreIdx); auto prev = node->prev; for (; idx < cnt; ++idx) { JPP_DCHECK_NE(prev, nullptr); row.at(idx) = prev->id; } scoreIdx += 1; } JPP_DCHECK_EQ(scoreIdx, rbnd.scoreCnt); return subset; } util::ConstSliceable<float> gatherScoreContext(const rnn::RnnBoundary& rbnd) { auto subset = contextBuf.topRows(rbnd.scoreCnt); u32 idx = 0; for (auto sc = rbnd.scores; sc != nullptr; sc = sc->next) { auto node = sc->rnn; auto prev = node->prev; JPP_DCHECK_NE(prev, nullptr); auto ctxRow = subset.row(idx); auto present = contexts.at(prev->boundary).row(prev->idx); util::copy_buffer(present, ctxRow); idx += 1; } JPP_DCHECK_EQ(idx, rbnd.scoreCnt); return subset; } util::ConstSliceable<float> gatherNceEmbeds(util::ArraySlice<i32> ids) { auto subset = embBuf.topRows(ids.size()); for (int i = 0; i < ids.size(); ++i) { auto embedId = ids[i]; if (embedId == -1) { embedId = 0; } auto embed = shared->nceEmbedOf(embedId); auto target = subset.row(i); util::copy_buffer(embed, target); } return subset; } util::MutableArraySlice<float> resizeScores(i32 size) { size_t sz = static_cast<size_t>(size); util::MutableArraySlice<float> res{scoreBuf, 0, sz}; return res; } void copyScoresToLattice(util::MutableArraySlice<float> slice, const rnn::RnnBoundary& rbnd, u32 bndIdx) { auto bnd = lat->boundary(bndIdx); auto scoreStorage = bnd->scores(); u32 scoreIdx = 0; for (auto sc = rbnd.scores; sc != nullptr; sc = sc->next) { auto ptr = sc->latPtr; JPP_DCHECK_EQ(bndIdx, ptr->boundary); auto nodeScores = scoreStorage->nodeScores(ptr->right); float score; auto rnnId = sc->rnn->id; if (rnnId == shared->resolver.unkId()) { auto& cfg = shared->config; score = cfg.unkConstantTerm + cfg.unkLengthPenalty * sc->rnn->length; } else { score = slice.at(scoreIdx); } scoreIdx += 1; nodeScores.beamLeft(ptr->beam, ptr->left).at(scorerIdx) = score; } JPP_DCHECK_EQ(scoreIdx, rbnd.scoreCnt); } Status scoreBoundary(u32 bndIdx) { auto& rbnd = container.rnnBoundary(bndIdx); if (rbnd.nodeCnt == 0) { return Status::Ok(); } auto rnnIds = gatherScoreIds(rbnd); auto scores = resizeScores(rbnd.scoreCnt); jumanpp::rnn::mikolov::ParallelStepData psd{ gatherPrevStateIds(rbnd), rnnIds, gatherScoreContext(rbnd), gatherNceEmbeds(rnnIds), scores}; shared->rnn.applyParallel(&psd); copyScoresToLattice(scores, rbnd, bndIdx); return Status::Ok(); } Status scoreLattice(Lattice* l, const ExtraNodesContext* xtra) { this->lat = l; this->xtra = xtra; manager.reset(); alloc->reset(); auto numBnd = l->createdBoundaryCount() - 1; allocateState(); JPP_RETURN_IF_ERROR( shared->resolver.resolveIdsAtGbeam(&container, l, xtra)); for (u32 bndIdx = 2; bndIdx < numBnd; ++bndIdx) { JPP_RIE_MSG(computeContext(bndIdx), "bnd=" << bndIdx); } for (u32 bndIdx = 2; bndIdx <= numBnd; ++bndIdx) { JPP_RIE_MSG(scoreBoundary(bndIdx), "bnd=" << bndIdx); } return Status::Ok(); } }; RnnScorerGbeam::RnnScorerGbeam() = default; Status RnnScorerGbeam::scoreLattice(Lattice* l, const ExtraNodesContext* xtra, u32 scorerIdx) { state_->scorerIdx = scorerIdx; return state_->scoreLattice(l, xtra); } RnnScorerGbeam::~RnnScorerGbeam() = default; RnnScorerGbeamFactory::RnnScorerGbeamFactory() = default; Status RnnScorerGbeamFactory::makeInstance( std::unique_ptr<ScoreComputer>* result) { auto ptr = new RnnScorerGbeam; result->reset(ptr); ptr->state_.reset(new GbeamRnnState); ptr->state_->shared = state_.get(); return Status::Ok(); } Status RnnScorerGbeamFactory::make(StringPiece rnnModelPath, const dic::DictionaryHolder& dic, const rnn::RnnInferenceConfig& config) { state_.reset(new GbeamRnnFactoryState); JPP_RETURN_IF_ERROR(state_->rnnReader.open(rnnModelPath)); JPP_RETURN_IF_ERROR(state_->rnnReader.parse()); JPP_RETURN_IF_ERROR(state_->rnn.init(state_->rnnReader.header(), state_->rnnReader.rnnMatrix(), state_->rnnReader.maxentWeights())); setConfig(config); JPP_RETURN_IF_ERROR( state_->resolver.build(dic, state_->config, state_->rnnReader.words())); auto& h = state_->rnnReader.header(); state_->embeddings = {state_->rnnReader.embeddings(), h.layerSize, h.vocabSize}; state_->nceEmbeddings = {state_->rnnReader.nceEmbeddings(), h.layerSize, h.vocabSize}; if (h.layerSize > 64 * 1024) { return JPPS_NOT_IMPLEMENTED << "we don't support embed sizes > 64k"; } state_->computeBosState(0); return Status::Ok(); } const rnn::RnnInferenceConfig& RnnScorerGbeamFactory::config() const { return state_->config; } void RnnScorerGbeamFactory::setConfig(const rnn::RnnInferenceConfig& config) { JPP_DCHECK(state_); state_->config.mergeWith(config); if (!state_->config.nceBias.isDefault()) { state_->rnn.setNceConstant(state_->config.nceBias); } } struct RnnModelHeader { rnn::RnnInferenceConfig& config; i32 unkIdx; std::vector<u32> fields; jumanpp::rnn::mikolov::MikolovRnnModelHeader rnnHeader; }; template <typename Arch> void Serialize(Arch& a, RnnModelHeader& o) { a& o.config.nceBias; a& o.config.unkConstantTerm; a& o.config.unkLengthPenalty; a& o.config.perceptronWeight; a& o.config.rnnWeight; a& o.config.eosSymbol; a& o.config.unkSymbol; a& o.config.rnnFields; a& o.config.fieldSeparator; a& o.unkIdx; a& o.fields; a& o.rnnHeader.layerSize; a& o.rnnHeader.maxentOrder; a& o.rnnHeader.maxentSize; a& o.rnnHeader.vocabSize; a& o.rnnHeader.nceLnz; } Status RnnScorerGbeamFactory::makeInfo(model::ModelInfo* info, StringPiece comment) { if (!state_) { return JPPS_INVALID_STATE << "RnnScorerGbeamFactory was not initialized"; } RnnModelHeader header{ state_->config, state_->resolver.unkId(), {}, state_->rnn.modelHeader()}; util::copy_insert(state_->resolver.targets(), header.fields); util::serialization::Saver s{&state_->codedBuf_}; s.save(header); info->parts.emplace_back(); auto& part = info->parts.back(); part.comment = comment.str(); part.kind = model::ModelPartKind::Rnn; part.data.push_back(s.result()); part.data.push_back(state_->resolver.knownIndex()); part.data.push_back(state_->resolver.unkIndex()); part.data.push_back(state_->rnnMatrix()); part.data.push_back(state_->embeddingData()); part.data.push_back(state_->nceEmbedData()); part.data.push_back(state_->maxentWeightData()); return Status::Ok(); } Status arr2d(StringPiece data, size_t nrows, size_t ncols, util::ConstSliceable<float>* result) { if (nrows * ncols * sizeof(float) < data.size()) { return JPPS_INVALID_PARAMETER << "failed to create ConstSliceable from memory buffer of " << data.size() << " need at least " << nrows * ncols * sizeof(float); } util::ArraySlice<float> wrap{reinterpret_cast<const float*>(data.data()), nrows * ncols}; *result = util::ConstSliceable<float>{wrap, ncols, nrows}; return Status::Ok(); } Status arr1d(StringPiece data, size_t expected, util::ArraySlice<float>* result) { if (expected * sizeof(float) < data.size()) { return JPPS_INVALID_PARAMETER << "failed to create ConstSliceable from memory buffer of " << data.size() << " need at least " << expected * sizeof(float); } *result = util::ArraySlice<float>{reinterpret_cast<const float*>(data.data()), expected}; return Status::Ok(); } Status RnnScorerGbeamFactory::load(const model::ModelInfo& model) { state_.reset(new GbeamRnnFactoryState); auto p = model.firstPartOf(model::ModelPartKind::Rnn); if (p == nullptr) { return JPPS_INVALID_PARAMETER << "model file did not contain RNN"; } RnnModelHeader header{state_->config, {}, {}, {}}; util::serialization::Loader l{p->data[0]}; if (!l.load(&header)) { return JPPS_INVALID_PARAMETER << "failed to read RNN header"; } JPP_RETURN_IF_ERROR(state_->resolver.setState(header.fields, p->data[1], p->data[2], header.unkIdx)); auto& rnnhdr = header.rnnHeader; util::ArraySlice<float> rnnMatrix; util::ArraySlice<float> maxentWeights; JPP_RIE_MSG( arr1d(p->data[3], rnnhdr.layerSize * rnnhdr.vocabSize, &rnnMatrix), "failed to read matrix"); JPP_RIE_MSG(arr2d(p->data[4], rnnhdr.vocabSize, rnnhdr.layerSize, &state_->embeddings), "failed to read embeddings"); JPP_RIE_MSG(arr2d(p->data[5], rnnhdr.vocabSize, rnnhdr.layerSize, &state_->nceEmbeddings), "failed to read NCE embeddings"); JPP_RIE_MSG(arr1d(p->data[6], rnnhdr.maxentSize, &maxentWeights), "failed to read NCE embeddings"); JPP_RETURN_IF_ERROR(state_->rnn.init(rnnhdr, rnnMatrix, maxentWeights)); state_->computeBosState(0); return Status::Ok(); } RnnScorerGbeamFactory::~RnnScorerGbeamFactory() = default; } // namespace analysis } // namespace core } // namespace jumanpp
32.929032
80
0.655499
5003
f60bc96391cc2c3004599c52dec37ec03c42b482
11,188
hpp
C++
mjolnir/forcefield/external/RectangularBoxInteraction.hpp
yutakasi634/Mjolnir
ab7a29a47f994111e8b889311c44487463f02116
[ "MIT" ]
12
2017-02-01T08:28:38.000Z
2018-08-25T15:47:51.000Z
mjolnir/forcefield/external/RectangularBoxInteraction.hpp
Mjolnir-MD/Mjolnir
043df4080720837042c6b67a5495ecae198bc2b3
[ "MIT" ]
60
2019-01-14T08:11:33.000Z
2021-07-29T08:26:36.000Z
mjolnir/forcefield/external/RectangularBoxInteraction.hpp
yutakasi634/Mjolnir
ab7a29a47f994111e8b889311c44487463f02116
[ "MIT" ]
8
2019-01-13T11:03:31.000Z
2021-08-01T11:38:00.000Z
#ifndef MJOLNIR_INTERACTION_EXTERNAL_RECTANGULAR_BOX_INTERACTION_HPP #define MJOLNIR_INTERACTION_EXTERNAL_RECTANGULAR_BOX_INTERACTION_HPP #include <mjolnir/core/ExternalForceInteractionBase.hpp> #include <mjolnir/core/BoundaryCondition.hpp> #include <mjolnir/core/SimulatorTraits.hpp> #include <mjolnir/math/math.hpp> #include <mjolnir/util/format_nth.hpp> namespace mjolnir { /*! @brief Interaction between particle and a box. */ template<typename traitsT, typename potentialT> class RectangularBoxInteraction final : public ExternalForceInteractionBase<traitsT> { public: using traits_type = traitsT; using potential_type = potentialT; using base_type = ExternalForceInteractionBase<traitsT>; using real_type = typename base_type::real_type; using coordinate_type = typename base_type::coordinate_type; using system_type = typename base_type::system_type; using boundary_type = typename base_type::boundary_type; public: RectangularBoxInteraction( const coordinate_type& lower, const coordinate_type& upper, const real_type margin, potential_type&& pot) : cutoff_(-1), margin_(margin), current_margin_(-1), lower_(lower), upper_(upper), neighbors_{}, potential_(std::move(pot)) { MJOLNIR_GET_DEFAULT_LOGGER(); if(!is_unlimited_boundary<boundary_type>::value) { const auto msg = "RectangularBox cannot be used under the periodic " "boundary condition. Use unlimited boundary."; MJOLNIR_LOG_ERROR(msg); throw std::runtime_error(msg); } assert(math::X(lower_) < math::X(upper_)); assert(math::Y(lower_) < math::Y(upper_)); assert(math::Z(lower_) < math::Z(upper_)); } ~RectangularBoxInteraction() override {} // calculate force, update spatial partition (reduce margin) inside. void calc_force (system_type&) const noexcept override; real_type calc_energy(system_type const&) const noexcept override; real_type calc_force_and_energy(system_type&) const noexcept override; /*! @brief initialize spatial partition (e.g. CellList) * * @details before calling `calc_(force|energy)`, this should be called. */ void initialize(const system_type& sys) override { this->potential_.update(sys); // update system parameters this->cutoff_ = this->potential_.max_cutoff_length(); this->make(sys); // update neighbor list return; } /*! @brief update parameters (e.g. temperature, ionic strength, ...) * * @details A method that change system parameters (e.g. Annealing), * * the method is bound to call this function after changing * * parameters. */ void update(const system_type& sys) override { this->potential_.update(sys); // update system parameters this->make(sys); // update neighbor list } void reduce_margin(const real_type dmargin, const system_type& sys) override { this->current_margin_ -= dmargin; if(this->current_margin_ < 0) { this->make(sys); } return; } void scale_margin(const real_type scale, const system_type& sys) override { this->current_margin_ = (cutoff_ + current_margin_) * scale - cutoff_; if(this->current_margin_ < 0) { this->make(sys); } return; } std::string name() const override {return "RectangularBox:"_s + potential_.name();} base_type* clone() const override { return new RectangularBoxInteraction(lower_, upper_, margin_, potential_type(potential_)); } // for tests coordinate_type const& upper() const noexcept {return upper_;} coordinate_type const& lower() const noexcept {return lower_;} potential_type const& potential() const noexcept {return potential_;} private: // construct a neighbor-list. // Also, check if all the particles are inside of the box. void make(const system_type& sys) { MJOLNIR_GET_DEFAULT_LOGGER(); const real_type threshold = this->cutoff_ * (1 + this->margin_); this->neighbors_.clear(); for(std::size_t i : this->potential_.participants()) { const auto& pos = sys.position(i); // Assuming that PBC and Box interaction will not be used together const auto dr_u = this->upper_ - pos; const auto dr_l = pos - this->lower_; // check if all the particles are inside of the box. if(math::X(dr_u) < 0 || math::Y(dr_u) < 0 || math::Z(dr_u) < 0) { MJOLNIR_LOG_ERROR(format_nth(i), " particle, ", pos, " exceeds the upper bound, ", this->upper_); throw_exception<std::runtime_error>(format_nth(i), " particle ", pos, " exceeds the upper bound, ", this->upper_); } if(math::X(dr_l) < 0 || math::Y(dr_l) < 0 || math::Z(dr_l) < 0) { MJOLNIR_LOG_ERROR(format_nth(i), " particle, ", pos, " exceeds the lower bound, ", this->lower_); throw_exception<std::runtime_error>(format_nth(i), " particle ", pos, " exceeds the lower bound, ", this->lower_); } // assign particles that are within the cutoff range. if(math::X(dr_u) <= threshold || math::X(dr_l) <= threshold || math::Y(dr_u) <= threshold || math::Y(dr_l) <= threshold || math::Z(dr_u) <= threshold || math::Z(dr_l) <= threshold) { neighbors_.push_back(i); } } this->current_margin_ = this->cutoff_ * this->margin_; return; } private: real_type cutoff_, margin_, current_margin_; coordinate_type lower_, upper_; std::vector<std::size_t> neighbors_; potential_type potential_; // #ifdef MJOLNIR_WITH_OPENMP // // OpenMP implementation uses its own implementation to run it in parallel. // // So this implementation should not be instanciated with OpenMP Traits. // static_assert(!is_openmp_simulator_traits<traits_type>::value, // "this is the default implementation, not for OpenMP"); // #endif }; template<typename traitsT, typename potT> void RectangularBoxInteraction<traitsT, potT>::calc_force( system_type& sys) const noexcept { // Here we assume that all the particles are inside of the box. // Also we assume that no boundary condition is applied. for(const std::size_t i : this->neighbors_) { const auto& pos = sys.position(i); const auto dr_u = this->upper_ - pos; const auto dr_l = pos - this->lower_; const auto dx_u = this->potential_.derivative(i, math::X(dr_u)); const auto dx_l = this->potential_.derivative(i, math::X(dr_l)); const auto dy_u = this->potential_.derivative(i, math::Y(dr_u)); const auto dy_l = this->potential_.derivative(i, math::Y(dr_l)); const auto dz_u = this->potential_.derivative(i, math::Z(dr_u)); const auto dz_l = this->potential_.derivative(i, math::Z(dr_l)); sys.force(i) += math::make_coordinate<coordinate_type>( dx_u - dx_l, dy_u - dy_l, dz_u - dz_l); } return ; } template<typename traitsT, typename potT> typename RectangularBoxInteraction<traitsT, potT>::real_type RectangularBoxInteraction<traitsT, potT>::calc_energy( const system_type& sys) const noexcept { real_type E = 0.0; for(const std::size_t i : this->neighbors_) { const auto& pos = sys.position(i); const auto dr_u = this->upper_ - pos; const auto dr_l = pos - this->lower_; E += this->potential_.potential(i, math::X(dr_u)) + this->potential_.potential(i, math::X(dr_l)) + this->potential_.potential(i, math::Y(dr_u)) + this->potential_.potential(i, math::Y(dr_l)) + this->potential_.potential(i, math::Z(dr_u)) + this->potential_.potential(i, math::Z(dr_l)); } return E; } template<typename traitsT, typename potT> typename RectangularBoxInteraction<traitsT, potT>::real_type RectangularBoxInteraction<traitsT, potT>::calc_force_and_energy( system_type& sys) const noexcept { real_type E = 0.0; for(const std::size_t i : this->neighbors_) { const auto& pos = sys.position(i); const auto dr_u = this->upper_ - pos; const auto dr_l = pos - this->lower_; const auto dx_u = this->potential_.derivative(i, math::X(dr_u)); const auto dx_l = this->potential_.derivative(i, math::X(dr_l)); const auto dy_u = this->potential_.derivative(i, math::Y(dr_u)); const auto dy_l = this->potential_.derivative(i, math::Y(dr_l)); const auto dz_u = this->potential_.derivative(i, math::Z(dr_u)); const auto dz_l = this->potential_.derivative(i, math::Z(dr_l)); sys.force(i) += math::make_coordinate<coordinate_type>( dx_u - dx_l, dy_u - dy_l, dz_u - dz_l); E += this->potential_.potential(i, math::X(dr_u)) + this->potential_.potential(i, math::X(dr_l)) + this->potential_.potential(i, math::Y(dr_u)) + this->potential_.potential(i, math::Y(dr_l)) + this->potential_.potential(i, math::Z(dr_u)) + this->potential_.potential(i, math::Z(dr_l)); } return E; } } // mjolnir #ifdef MJOLNIR_SEPARATE_BUILD #include <mjolnir/forcefield/external/ExcludedVolumeWallPotential.hpp> #include <mjolnir/forcefield/external/LennardJonesWallPotential.hpp> namespace mjolnir { extern template class RectangularBoxInteraction<SimulatorTraits<double, UnlimitedBoundary>, ExcludedVolumeWallPotential<double>>; extern template class RectangularBoxInteraction<SimulatorTraits<float, UnlimitedBoundary>, ExcludedVolumeWallPotential<float >>; extern template class RectangularBoxInteraction<SimulatorTraits<double, CuboidalPeriodicBoundary>, ExcludedVolumeWallPotential<double>>; extern template class RectangularBoxInteraction<SimulatorTraits<float, CuboidalPeriodicBoundary>, ExcludedVolumeWallPotential<float >>; extern template class RectangularBoxInteraction<SimulatorTraits<double, UnlimitedBoundary>, LennardJonesWallPotential<double>>; extern template class RectangularBoxInteraction<SimulatorTraits<float, UnlimitedBoundary>, LennardJonesWallPotential<float >>; extern template class RectangularBoxInteraction<SimulatorTraits<double, CuboidalPeriodicBoundary>, LennardJonesWallPotential<double>>; extern template class RectangularBoxInteraction<SimulatorTraits<float, CuboidalPeriodicBoundary>, LennardJonesWallPotential<float >>; } // mjolnir #endif // MJOLNIR_SEPARATE_BUILD #endif//MJOLNIR_BOX_INTEARACTION_BASE
41.437037
136
0.642653
yutakasi634
f60d8f801c3ac8ed0863421791d74c5702f9b223
1,836
hpp
C++
src/bwt.hpp
SebWouters/aiss4
f46ea04e573b77abec74459f018d32bd0bdc8865
[ "BSD-3-Clause" ]
null
null
null
src/bwt.hpp
SebWouters/aiss4
f46ea04e573b77abec74459f018d32bd0bdc8865
[ "BSD-3-Clause" ]
null
null
null
src/bwt.hpp
SebWouters/aiss4
f46ea04e573b77abec74459f018d32bd0bdc8865
[ "BSD-3-Clause" ]
null
null
null
/* aiss4: suffix array via induced sorting Copyright (c) 2020, Sebastian Wouters All rights reserved. This file is part of aiss4, licensed under the BSD 3-Clause License. A copy of the License can be found in the file LICENSE in the root folder of this project. */ #pragma once #include <stdint.h> #include <stdlib.h> namespace aiss4 { void decode(const int32_t pointer, const uint8_t * encoded, uint8_t * decoded, const int32_t size) { if (pointer < 0 || size < 1 || encoded == NULL || decoded == NULL) return; int32_t * map = new int32_t[size]; int32_t * head = new int32_t[256]; for (int32_t sym = 0; sym < 256; ++sym) head[sym] = 0; for (int32_t idx = 0; idx < size; ++idx) map[idx] = head[encoded[idx]]++; int32_t total = 1; // Sentinel '$' for (int32_t sym = 0; sym < 256; ++sym) { int32_t tmp = head[sym]; head[sym] = total; total += tmp; } int32_t idx = 0; // map[pointer] + head[$] = 0 for (int32_t cnt = 0; cnt < size; ++cnt) { idx = idx < pointer ? idx : idx - 1; // Sentinel '$' not represented in encoded uint8_t sym = encoded[idx]; decoded[size - 1 - cnt] = sym; idx = map[idx] + head[sym]; } delete [] map; delete [] head; } int32_t encode(const uint8_t * orig, const int32_t * suffix, uint8_t * encoded, const int32_t size) { if (size < 1 || orig == NULL || suffix == NULL || encoded == NULL) return -1; encoded[0] = orig[size - 1]; int32_t target = 1; int32_t pointer = -1; for (int32_t idx = 0; idx < size; ++idx) { if (suffix[idx] == 0) pointer = idx + 1; else encoded[target++] = orig[suffix[idx] - 1]; } return pointer; } } // End of namespace aiss4
23.844156
99
0.562092
SebWouters
f610e7915dfa37bc2766ed278f867b9770dbb6dd
8,779
inl
C++
include/hfsm/detail/machine_composite_methods.inl
kgreenek/HFSM
4a6f5bf6fb868c05ea797f1b8d33073eee461a0b
[ "MIT" ]
74
2017-04-11T20:54:20.000Z
2021-09-01T06:31:01.000Z
include/hfsm/detail/machine_composite_methods.inl
kgreenek/HFSM
4a6f5bf6fb868c05ea797f1b8d33073eee461a0b
[ "MIT" ]
14
2018-01-04T03:54:00.000Z
2018-07-02T22:34:12.000Z
include/hfsm/detail/machine_composite_methods.inl
kgreenek/HFSM
4a6f5bf6fb868c05ea797f1b8d33073eee461a0b
[ "MIT" ]
33
2017-04-12T13:11:37.000Z
2022-01-06T02:06:07.000Z
namespace hfsm { //////////////////////////////////////////////////////////////////////////////// template <typename TC, unsigned TMS> template <typename TH, typename... TS> M<TC, TMS>::_C<TH, TS...>::_C(StateRegistry& stateRegistry, const Parent parent, Parents& stateParents, Parents& forkParents, ForkPointers& forkPointers) : _fork(static_cast<Index>(forkPointers << &_fork), parent, forkParents) , _state(stateRegistry, parent, stateParents, forkParents, forkPointers) , _subStates(stateRegistry, _fork.self, stateParents, forkParents, forkPointers) {} //------------------------------------------------------------------------------ template <typename TC, unsigned TMS> template <typename TH, typename... TS> void M<TC, TMS>::_C<TH, TS...>::deepForwardSubstitute(Control& control, Context& context, LoggerInterface* const logger) { assert(_fork.requested != INVALID_INDEX); if (_fork.requested == _fork.active) _subStates.wideForwardSubstitute(_fork.requested, control, context, logger); else _subStates.wideSubstitute (_fork.requested, control, context, logger); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <typename TC, unsigned TMS> template <typename TH, typename... TS> void M<TC, TMS>::_C<TH, TS...>::deepSubstitute(Control& control, Context& context, LoggerInterface* const logger) { assert(_fork.active == INVALID_INDEX && _fork.requested != INVALID_INDEX); if (!_state .deepSubstitute( control, context, logger)) _subStates.wideSubstitute(_fork.requested, control, context, logger); } //------------------------------------------------------------------------------ template <typename TC, unsigned TMS> template <typename TH, typename... TS> void M<TC, TMS>::_C<TH, TS...>::deepEnterInitial(Context& context, LoggerInterface* const logger) { assert(_fork.active == INVALID_INDEX && _fork.resumable == INVALID_INDEX && _fork.requested == INVALID_INDEX); HSFM_IF_DEBUG(_fork.activeType = TypeInfo::get<typename SubStates::Initial::Head>()); _fork.active = 0; _state .deepEnter (context, logger); _subStates.wideEnterInitial(context, logger); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <typename TC, unsigned TMS> template <typename TH, typename... TS> void M<TC, TMS>::_C<TH, TS...>::deepEnter(Context& context, LoggerInterface* const logger) { assert(_fork.active == INVALID_INDEX && _fork.requested != INVALID_INDEX); HSFM_IF_DEBUG(_fork.activeType = _fork.requestedType); _fork.active = _fork.requested; HSFM_IF_DEBUG(_fork.requestedType.clear()); _fork.requested = INVALID_INDEX; _state .deepEnter( context, logger); _subStates.wideEnter(_fork.active, context, logger); } //------------------------------------------------------------------------------ template <typename TC, unsigned TMS> template <typename TH, typename... TS> bool M<TC, TMS>::_C<TH, TS...>::deepUpdateAndTransition(Control& control, Context& context, LoggerInterface* const logger) { assert(_fork.active != INVALID_INDEX); if (_state.deepUpdateAndTransition(control, context, logger)) { _subStates.wideUpdate(_fork.active, context, logger); return true; } else return _subStates.wideUpdateAndTransition(_fork.active, control, context, logger); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <typename TC, unsigned TMS> template <typename TH, typename... TS> void M<TC, TMS>::_C<TH, TS...>::deepUpdate(Context& context, LoggerInterface* const logger) { assert(_fork.active != INVALID_INDEX); _state .deepUpdate( context, logger); _subStates.wideUpdate(_fork.active, context, logger); } //------------------------------------------------------------------------------ template <typename TC, unsigned TMS> template <typename TH, typename... TS> template <typename TEvent> void M<TC, TMS>::_C<TH, TS...>::deepReact(const TEvent& event, Control& control, Context& context, LoggerInterface* const logger) { assert(_fork.active != INVALID_INDEX); _state .deepReact( event, control, context, logger); _subStates.wideReact(_fork.active, event, control, context, logger); } //------------------------------------------------------------------------------ template <typename TC, unsigned TMS> template <typename TH, typename... TS> void M<TC, TMS>::_C<TH, TS...>::deepLeave(Context& context, LoggerInterface* const logger) { assert(_fork.active != INVALID_INDEX); _subStates.wideLeave(_fork.active, context, logger); _state .deepLeave( context, logger); HSFM_IF_DEBUG(_fork.resumableType = _fork.activeType); _fork.resumable = _fork.active; HSFM_IF_DEBUG(_fork.activeType.clear()); _fork.active = INVALID_INDEX; } //------------------------------------------------------------------------------ template <typename TC, unsigned TMS> template <typename TH, typename... TS> void M<TC, TMS>::_C<TH, TS...>::deepForwardRequest(const enum Transition::Type transition) { if (_fork.requested != INVALID_INDEX) _subStates.wideForwardRequest(_fork.requested, transition); else switch (transition) { case Transition::Remain: deepRequestRemain(); break; case Transition::Restart: deepRequestRestart(); break; case Transition::Resume: deepRequestResume(); break; default: assert(false); } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <typename TC, unsigned TMS> template <typename TH, typename... TS> void M<TC, TMS>::_C<TH, TS...>::deepRequestRemain() { if (_fork.active == INVALID_INDEX) { HSFM_IF_DEBUG(_fork.requestedType = TypeInfo::get<typename SubStates::Initial::Head>()); _fork.requested = 0; } _subStates.wideRequestRemain(); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <typename TC, unsigned TMS> template <typename TH, typename... TS> void M<TC, TMS>::_C<TH, TS...>::deepRequestRestart() { HSFM_IF_DEBUG(_fork.requestedType = TypeInfo::get<typename SubStates::Initial::Head>()); _fork.requested = 0; _subStates.wideRequestRestart(); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <typename TC, unsigned TMS> template <typename TH, typename... TS> void M<TC, TMS>::_C<TH, TS...>::deepRequestResume() { if (_fork.resumable != INVALID_INDEX) { HSFM_IF_DEBUG(_fork.requestedType = _fork.resumableType); _fork.requested = _fork.resumable; } else { HSFM_IF_DEBUG(_fork.requestedType = TypeInfo::get<typename SubStates::Initial::Head>()); _fork.requested = 0; } _subStates.wideRequestResume(_fork.requested); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <typename TC, unsigned TMS> template <typename TH, typename... TS> void M<TC, TMS>::_C<TH, TS...>::deepChangeToRequested(Context& context, LoggerInterface* const logger) { assert(_fork.active != INVALID_INDEX); if (_fork.requested == _fork.active) _subStates.wideChangeToRequested(_fork.requested, context, logger); else if (_fork.requested != INVALID_INDEX) { _subStates.wideLeave(_fork.active, context, logger); HSFM_IF_DEBUG(_fork.resumableType = _fork.activeType); _fork.resumable = _fork.active; HSFM_IF_DEBUG(_fork.activeType = _fork.requestedType); _fork.active = _fork.requested; HSFM_IF_DEBUG(_fork.requestedType.clear()); _fork.requested = INVALID_INDEX; _subStates.wideEnter(_fork.active, context, logger); } } //------------------------------------------------------------------------------ #ifdef HFSM_ENABLE_STRUCTURE_REPORT template <typename TC, unsigned TMS> template <typename TH, typename... TS> void M<TC, TMS>::_C<TH, TS...>::deepGetNames(const unsigned parent, const enum StateInfo::RegionType region, const unsigned depth, StateInfos& _stateInfos) const { _state.deepGetNames(parent, region, depth, _stateInfos); _subStates.wideGetNames(_stateInfos.count() - 1, depth + 1, _stateInfos); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <typename TC, unsigned TMS> template <typename TH, typename... TS> void M<TC, TMS>::_C<TH, TS...>::deepIsActive(const bool isActive, unsigned& index, MachineStructure& structure) const { _state.deepIsActive(isActive, index, structure); _subStates.wideIsActive(isActive ? _fork.active : INVALID_INDEX, index, structure); } #endif //////////////////////////////////////////////////////////////////////////////// }
30.065068
90
0.598929
kgreenek
f61211199fcc49d95fc860f04c824dacf4dbf7e4
1,033
cpp
C++
src/system/boot/platform/next_m68k/devices.cpp
Yn0ga/haiku
74e271b2a286c239e60f0ec261f4f197f4727eee
[ "MIT" ]
1,338
2015-01-03T20:06:56.000Z
2022-03-26T13:49:54.000Z
src/system/boot/platform/next_m68k/devices.cpp
Yn0ga/haiku
74e271b2a286c239e60f0ec261f4f197f4727eee
[ "MIT" ]
15
2015-01-17T22:19:32.000Z
2021-12-20T12:35:00.000Z
src/system/boot/platform/next_m68k/devices.cpp
Yn0ga/haiku
74e271b2a286c239e60f0ec261f4f197f4727eee
[ "MIT" ]
350
2015-01-08T14:15:27.000Z
2022-03-21T18:14:35.000Z
/* * Copyright 2008-2010, François Revol, revol@free.fr. All rights reserved. * Copyright 2003-2006, Axel Dörfler, axeld@pinc-software.de. * Distributed under the terms of the MIT License. */ #include <KernelExport.h> #include <boot/platform.h> #include <boot/partitions.h> #include <boot/stdio.h> #include <boot/stage2.h> #include <string.h> #include "nextrom.h" //#define TRACE_DEVICES #ifdef TRACE_DEVICES # define TRACE(x) dprintf x #else # define TRACE(x) ; #endif static bool sBlockDevicesAdded = false; // #pragma mark - status_t platform_add_boot_device(struct stage2_args *args, NodeList *devicesList) { return B_UNSUPPORTED; } status_t platform_get_boot_partitions(struct stage2_args *args, Node *device, NodeList *list, NodeList *partitionList) { return B_ENTRY_NOT_FOUND; } status_t platform_add_block_devices(stage2_args *args, NodeList *devicesList) { return B_UNSUPPORTED; } status_t platform_register_boot_device(Node *device) { return B_UNSUPPORTED; } void platform_cleanup_devices() { }
15.892308
75
0.760891
Yn0ga
f61a2e86ccbfdb9510471373060b43b0ef035805
1,778
cpp
C++
modules/fsio/tests/src/disk_device.cpp
hfarrow/Fissura
0ccc319b55f8dc99af712c95580342430444bc29
[ "MIT" ]
null
null
null
modules/fsio/tests/src/disk_device.cpp
hfarrow/Fissura
0ccc319b55f8dc99af712c95580342430444bc29
[ "MIT" ]
null
null
null
modules/fsio/tests/src/disk_device.cpp
hfarrow/Fissura
0ccc319b55f8dc99af712c95580342430444bc29
[ "MIT" ]
null
null
null
#include <cstdio> #include <boost/test/unit_test.hpp> #include "global_fixture.h" #include "fstest.h" #include "fscore.h" #include "fsmem.h" #include "fsio.h" using namespace fs; using FileArena = MemoryArena<Allocator<HeapAllocator, AllocationHeaderU32>, MultiThread<MutexPrimitive>, SimpleBoundsChecking, FullMemoryTracking, MemoryTagging>; struct DiskDeviceFixture { DiskDeviceFixture() : area(FS_SIZE_OF_MB * 4), arena(area, "FileArena"), gf(GlobalFixture::instance()) { } ~DiskDeviceFixture() { } HeapArea area; FileArena arena; GlobalFixture* gf; }; BOOST_AUTO_TEST_SUITE(io) BOOST_FIXTURE_TEST_SUITE(disk_device, DiskDeviceFixture) BOOST_AUTO_TEST_CASE(create_device) { FileSystem<FileArena> filesys(&arena); DiskDevice device; BOOST_CHECK(device.getType() == "disk"); } BOOST_AUTO_TEST_CASE(open_file_and_close) { FileSystem<FileArena> filesys(&arena); DiskDevice device; auto file = device.open(&filesys, nullptr, gf->path("content/empty.bin"), IFileSystem::Mode::READ); BOOST_REQUIRE(file); BOOST_REQUIRE(file->opened()); BOOST_CHECK(strcmp(file->getName(), gf->path("content/empty.bin")) == 0); filesys.close(file); BOOST_REQUIRE(!file->opened()); } BOOST_AUTO_TEST_CASE(open_with_invalid_device_list) { FileSystem<FileArena> filesys(&arena); DiskDevice device; auto lambda = [&]() { auto file = device.open(&filesys, "some:other:devices", gf->path("content/empty.bin"), IFileSystem::Mode::READ); }; FS_REQUIRE_ASSERT(lambda); } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END()
22.794872
120
0.652981
hfarrow
f61d2dfd00d13a3a9778cff498e45fc067422dad
20,005
hpp
C++
modules/cudafeatures2d/include/opencv2/cudafeatures2d.hpp
liuhuanjim013/opencv
ac5e5adb6fbefa16bb48257cf534f1d55811603e
[ "BSD-3-Clause" ]
1
2020-11-12T03:37:51.000Z
2020-11-12T03:37:51.000Z
modules/cudafeatures2d/include/opencv2/cudafeatures2d.hpp
liuhuanjim013/opencv
ac5e5adb6fbefa16bb48257cf534f1d55811603e
[ "BSD-3-Clause" ]
null
null
null
modules/cudafeatures2d/include/opencv2/cudafeatures2d.hpp
liuhuanjim013/opencv
ac5e5adb6fbefa16bb48257cf534f1d55811603e
[ "BSD-3-Clause" ]
null
null
null
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #ifndef __OPENCV_CUDAFEATURES2D_HPP__ #define __OPENCV_CUDAFEATURES2D_HPP__ #ifndef __cplusplus # error cudafeatures2d.hpp header must be compiled as C++ #endif #include "opencv2/core/cuda.hpp" #include "opencv2/cudafilters.hpp" /** @addtogroup cuda @{ @defgroup cudafeatures2d Feature Detection and Description @} */ namespace cv { namespace cuda { //! @addtogroup cudafeatures2d //! @{ /** @brief Brute-force descriptor matcher. For each descriptor in the first set, this matcher finds the closest descriptor in the second set by trying each one. This descriptor matcher supports masking permissible matches between descriptor sets. The class BFMatcher_CUDA has an interface similar to the class DescriptorMatcher. It has two groups of match methods: for matching descriptors of one image with another image or with an image set. Also, all functions have an alternative to save results either to the GPU memory or to the CPU memory. @sa DescriptorMatcher, BFMatcher */ class CV_EXPORTS BFMatcher_CUDA { public: explicit BFMatcher_CUDA(int norm = cv::NORM_L2); //! Add descriptors to train descriptor collection void add(const std::vector<GpuMat>& descCollection); //! Get train descriptors collection const std::vector<GpuMat>& getTrainDescriptors() const; //! Clear train descriptors collection void clear(); //! Return true if there are not train descriptors in collection bool empty() const; //! Return true if the matcher supports mask in match methods bool isMaskSupported() const; //! Find one best match for each query descriptor void matchSingle(const GpuMat& query, const GpuMat& train, GpuMat& trainIdx, GpuMat& distance, const GpuMat& mask = GpuMat(), Stream& stream = Stream::Null()); //! Download trainIdx and distance and convert it to CPU vector with DMatch static void matchDownload(const GpuMat& trainIdx, const GpuMat& distance, std::vector<DMatch>& matches); //! Convert trainIdx and distance to vector with DMatch static void matchConvert(const Mat& trainIdx, const Mat& distance, std::vector<DMatch>& matches); //! Find one best match for each query descriptor void match(const GpuMat& query, const GpuMat& train, std::vector<DMatch>& matches, const GpuMat& mask = GpuMat()); //! Make gpu collection of trains and masks in suitable format for matchCollection function void makeGpuCollection(GpuMat& trainCollection, GpuMat& maskCollection, const std::vector<GpuMat>& masks = std::vector<GpuMat>()); //! Find one best match from train collection for each query descriptor void matchCollection(const GpuMat& query, const GpuMat& trainCollection, GpuMat& trainIdx, GpuMat& imgIdx, GpuMat& distance, const GpuMat& masks = GpuMat(), Stream& stream = Stream::Null()); //! Download trainIdx, imgIdx and distance and convert it to vector with DMatch static void matchDownload(const GpuMat& trainIdx, const GpuMat& imgIdx, const GpuMat& distance, std::vector<DMatch>& matches); //! Convert trainIdx, imgIdx and distance to vector with DMatch static void matchConvert(const Mat& trainIdx, const Mat& imgIdx, const Mat& distance, std::vector<DMatch>& matches); //! Find one best match from train collection for each query descriptor. void match(const GpuMat& query, std::vector<DMatch>& matches, const std::vector<GpuMat>& masks = std::vector<GpuMat>()); //! Find k best matches for each query descriptor (in increasing order of distances) void knnMatchSingle(const GpuMat& query, const GpuMat& train, GpuMat& trainIdx, GpuMat& distance, GpuMat& allDist, int k, const GpuMat& mask = GpuMat(), Stream& stream = Stream::Null()); //! Download trainIdx and distance and convert it to vector with DMatch //! compactResult is used when mask is not empty. If compactResult is false matches //! vector will have the same size as queryDescriptors rows. If compactResult is true //! matches vector will not contain matches for fully masked out query descriptors. static void knnMatchDownload(const GpuMat& trainIdx, const GpuMat& distance, std::vector< std::vector<DMatch> >& matches, bool compactResult = false); //! Convert trainIdx and distance to vector with DMatch static void knnMatchConvert(const Mat& trainIdx, const Mat& distance, std::vector< std::vector<DMatch> >& matches, bool compactResult = false); //! Find k best matches for each query descriptor (in increasing order of distances). //! compactResult is used when mask is not empty. If compactResult is false matches //! vector will have the same size as queryDescriptors rows. If compactResult is true //! matches vector will not contain matches for fully masked out query descriptors. void knnMatch(const GpuMat& query, const GpuMat& train, std::vector< std::vector<DMatch> >& matches, int k, const GpuMat& mask = GpuMat(), bool compactResult = false); //! Find k best matches from train collection for each query descriptor (in increasing order of distances) void knnMatch2Collection(const GpuMat& query, const GpuMat& trainCollection, GpuMat& trainIdx, GpuMat& imgIdx, GpuMat& distance, const GpuMat& maskCollection = GpuMat(), Stream& stream = Stream::Null()); //! Download trainIdx and distance and convert it to vector with DMatch //! compactResult is used when mask is not empty. If compactResult is false matches //! vector will have the same size as queryDescriptors rows. If compactResult is true //! matches vector will not contain matches for fully masked out query descriptors. //! @see BFMatcher_CUDA::knnMatchDownload static void knnMatch2Download(const GpuMat& trainIdx, const GpuMat& imgIdx, const GpuMat& distance, std::vector< std::vector<DMatch> >& matches, bool compactResult = false); //! Convert trainIdx and distance to vector with DMatch //! @see BFMatcher_CUDA::knnMatchConvert static void knnMatch2Convert(const Mat& trainIdx, const Mat& imgIdx, const Mat& distance, std::vector< std::vector<DMatch> >& matches, bool compactResult = false); //! Find k best matches for each query descriptor (in increasing order of distances). //! compactResult is used when mask is not empty. If compactResult is false matches //! vector will have the same size as queryDescriptors rows. If compactResult is true //! matches vector will not contain matches for fully masked out query descriptors. void knnMatch(const GpuMat& query, std::vector< std::vector<DMatch> >& matches, int k, const std::vector<GpuMat>& masks = std::vector<GpuMat>(), bool compactResult = false); //! Find best matches for each query descriptor which have distance less than maxDistance. //! nMatches.at<int>(0, queryIdx) will contain matches count for queryIdx. //! carefully nMatches can be greater than trainIdx.cols - it means that matcher didn't find all matches, //! because it didn't have enough memory. //! If trainIdx is empty, then trainIdx and distance will be created with size nQuery x max((nTrain / 100), 10), //! otherwize user can pass own allocated trainIdx and distance with size nQuery x nMaxMatches //! Matches doesn't sorted. void radiusMatchSingle(const GpuMat& query, const GpuMat& train, GpuMat& trainIdx, GpuMat& distance, GpuMat& nMatches, float maxDistance, const GpuMat& mask = GpuMat(), Stream& stream = Stream::Null()); //! Download trainIdx, nMatches and distance and convert it to vector with DMatch. //! matches will be sorted in increasing order of distances. //! compactResult is used when mask is not empty. If compactResult is false matches //! vector will have the same size as queryDescriptors rows. If compactResult is true //! matches vector will not contain matches for fully masked out query descriptors. static void radiusMatchDownload(const GpuMat& trainIdx, const GpuMat& distance, const GpuMat& nMatches, std::vector< std::vector<DMatch> >& matches, bool compactResult = false); //! Convert trainIdx, nMatches and distance to vector with DMatch. static void radiusMatchConvert(const Mat& trainIdx, const Mat& distance, const Mat& nMatches, std::vector< std::vector<DMatch> >& matches, bool compactResult = false); //! Find best matches for each query descriptor which have distance less than maxDistance //! in increasing order of distances). void radiusMatch(const GpuMat& query, const GpuMat& train, std::vector< std::vector<DMatch> >& matches, float maxDistance, const GpuMat& mask = GpuMat(), bool compactResult = false); //! Find best matches for each query descriptor which have distance less than maxDistance. //! If trainIdx is empty, then trainIdx and distance will be created with size nQuery x max((nQuery / 100), 10), //! otherwize user can pass own allocated trainIdx and distance with size nQuery x nMaxMatches //! Matches doesn't sorted. void radiusMatchCollection(const GpuMat& query, GpuMat& trainIdx, GpuMat& imgIdx, GpuMat& distance, GpuMat& nMatches, float maxDistance, const std::vector<GpuMat>& masks = std::vector<GpuMat>(), Stream& stream = Stream::Null()); //! Download trainIdx, imgIdx, nMatches and distance and convert it to vector with DMatch. //! matches will be sorted in increasing order of distances. //! compactResult is used when mask is not empty. If compactResult is false matches //! vector will have the same size as queryDescriptors rows. If compactResult is true //! matches vector will not contain matches for fully masked out query descriptors. static void radiusMatchDownload(const GpuMat& trainIdx, const GpuMat& imgIdx, const GpuMat& distance, const GpuMat& nMatches, std::vector< std::vector<DMatch> >& matches, bool compactResult = false); //! Convert trainIdx, nMatches and distance to vector with DMatch. static void radiusMatchConvert(const Mat& trainIdx, const Mat& imgIdx, const Mat& distance, const Mat& nMatches, std::vector< std::vector<DMatch> >& matches, bool compactResult = false); //! Find best matches from train collection for each query descriptor which have distance less than //! maxDistance (in increasing order of distances). void radiusMatch(const GpuMat& query, std::vector< std::vector<DMatch> >& matches, float maxDistance, const std::vector<GpuMat>& masks = std::vector<GpuMat>(), bool compactResult = false); int norm; private: std::vector<GpuMat> trainDescCollection; }; /** @brief Class used for corner detection using the FAST algorithm. : */ class CV_EXPORTS FAST_CUDA { public: enum { LOCATION_ROW = 0, RESPONSE_ROW, ROWS_COUNT }; //! all features have same size static const int FEATURE_SIZE = 7; /** @brief Constructor. @param threshold Threshold on difference between intensity of the central pixel and pixels on a circle around this pixel. @param nonmaxSuppression If it is true, non-maximum suppression is applied to detected corners (keypoints). @param keypointsRatio Inner buffer size for keypoints store is determined as (keypointsRatio \* image_width \* image_height). */ explicit FAST_CUDA(int threshold, bool nonmaxSuppression = true, double keypointsRatio = 0.05); /** @brief Finds the keypoints using FAST detector. @param image Image where keypoints (corners) are detected. Only 8-bit grayscale images are supported. @param mask Optional input mask that marks the regions where we should detect features. @param keypoints The output vector of keypoints. Can be stored both in CPU and GPU memory. For GPU memory: - keypoints.ptr\<Vec2s\>(LOCATION_ROW)[i] will contain location of i'th point - keypoints.ptr\<float\>(RESPONSE_ROW)[i] will contain response of i'th point (if non-maximum suppression is applied) */ void operator ()(const GpuMat& image, const GpuMat& mask, GpuMat& keypoints); /** @overload */ void operator ()(const GpuMat& image, const GpuMat& mask, std::vector<KeyPoint>& keypoints); /** @brief Download keypoints from GPU to CPU memory. */ static void downloadKeypoints(const GpuMat& d_keypoints, std::vector<KeyPoint>& keypoints); /** @brief Converts keypoints from CUDA representation to vector of KeyPoint. */ static void convertKeypoints(const Mat& h_keypoints, std::vector<KeyPoint>& keypoints); /** @brief Releases inner buffer memory. */ void release(); bool nonmaxSuppression; int threshold; //! max keypoints = keypointsRatio * img.size().area() double keypointsRatio; /** @brief Find keypoints and compute it's response if nonmaxSuppression is true. @param image Image where keypoints (corners) are detected. Only 8-bit grayscale images are supported. @param mask Optional input mask that marks the regions where we should detect features. The function returns count of detected keypoints. */ int calcKeyPointsLocation(const GpuMat& image, const GpuMat& mask); /** @brief Gets final array of keypoints. @param keypoints The output vector of keypoints. The function performs non-max suppression if needed and returns final count of keypoints. */ int getKeyPoints(GpuMat& keypoints); private: GpuMat kpLoc_; int count_; GpuMat score_; GpuMat d_keypoints_; }; /** @brief Class for extracting ORB features and descriptors from an image. : */ class CV_EXPORTS ORB_CUDA { public: enum { X_ROW = 0, Y_ROW, RESPONSE_ROW, ANGLE_ROW, OCTAVE_ROW, SIZE_ROW, ROWS_COUNT }; enum { DEFAULT_FAST_THRESHOLD = 20 }; /** @brief Constructor. @param nFeatures The number of desired features. @param scaleFactor Coefficient by which we divide the dimensions from one scale pyramid level to the next. @param nLevels The number of levels in the scale pyramid. @param edgeThreshold How far from the boundary the points should be. @param firstLevel The level at which the image is given. If 1, that means we will also look at the image scaleFactor times bigger. @param WTA_K @param scoreType @param patchSize */ explicit ORB_CUDA(int nFeatures = 500, float scaleFactor = 1.2f, int nLevels = 8, int edgeThreshold = 31, int firstLevel = 0, int WTA_K = 2, int scoreType = 0, int patchSize = 31); /** @overload */ void operator()(const GpuMat& image, const GpuMat& mask, std::vector<KeyPoint>& keypoints); /** @overload */ void operator()(const GpuMat& image, const GpuMat& mask, GpuMat& keypoints); /** @brief Detects keypoints and computes descriptors for them. @param image Input 8-bit grayscale image. @param mask Optional input mask that marks the regions where we should detect features. @param keypoints The input/output vector of keypoints. Can be stored both in CPU and GPU memory. For GPU memory: - keypoints.ptr\<float\>(X_ROW)[i] contains x coordinate of the i'th feature. - keypoints.ptr\<float\>(Y_ROW)[i] contains y coordinate of the i'th feature. - keypoints.ptr\<float\>(RESPONSE_ROW)[i] contains the response of the i'th feature. - keypoints.ptr\<float\>(ANGLE_ROW)[i] contains orientation of the i'th feature. - keypoints.ptr\<float\>(OCTAVE_ROW)[i] contains the octave of the i'th feature. - keypoints.ptr\<float\>(SIZE_ROW)[i] contains the size of the i'th feature. @param descriptors Computed descriptors. if blurForDescriptor is true, image will be blurred before descriptors calculation. */ void operator()(const GpuMat& image, const GpuMat& mask, std::vector<KeyPoint>& keypoints, GpuMat& descriptors); /** @overload */ void operator()(const GpuMat& image, const GpuMat& mask, GpuMat& keypoints, GpuMat& descriptors); /** @brief Download keypoints from GPU to CPU memory. */ static void downloadKeyPoints(const GpuMat& d_keypoints, std::vector<KeyPoint>& keypoints); /** @brief Converts keypoints from CUDA representation to vector of KeyPoint. */ static void convertKeyPoints(const Mat& d_keypoints, std::vector<KeyPoint>& keypoints); //! returns the descriptor size in bytes inline int descriptorSize() const { return kBytes; } inline void setFastParams(int threshold, bool nonmaxSuppression = true) { fastDetector_.threshold = threshold; fastDetector_.nonmaxSuppression = nonmaxSuppression; } /** @brief Releases inner buffer memory. */ void release(); //! if true, image will be blurred before descriptors calculation bool blurForDescriptor; private: enum { kBytes = 32 }; void buildScalePyramids(const GpuMat& image, const GpuMat& mask); void computeKeyPointsPyramid(); void computeDescriptors(GpuMat& descriptors); void mergeKeyPoints(GpuMat& keypoints); int nFeatures_; float scaleFactor_; int nLevels_; int edgeThreshold_; int firstLevel_; int WTA_K_; int scoreType_; int patchSize_; //! The number of desired features per scale std::vector<size_t> n_features_per_level_; //! Points to compute BRIEF descriptors from GpuMat pattern_; std::vector<GpuMat> imagePyr_; std::vector<GpuMat> maskPyr_; GpuMat buf_; std::vector<GpuMat> keyPointsPyr_; std::vector<int> keyPointsCount_; FAST_CUDA fastDetector_; Ptr<cuda::Filter> blurFilter; GpuMat d_keypoints_; }; //! @} }} // namespace cv { namespace cuda { #endif /* __OPENCV_CUDAFEATURES2D_HPP__ */
44.654018
140
0.713322
liuhuanjim013
f61f0fb6f3804c88c2d74049dd4488714d94af28
547
cpp
C++
0119 Pascals Triangle II/solution.cpp
Aden-Tao/LeetCode
c34019520b5808c4251cb76f69ca2befa820401d
[ "MIT" ]
1
2019-12-19T04:13:15.000Z
2019-12-19T04:13:15.000Z
0119 Pascals Triangle II/solution.cpp
Aden-Tao/LeetCode
c34019520b5808c4251cb76f69ca2befa820401d
[ "MIT" ]
null
null
null
0119 Pascals Triangle II/solution.cpp
Aden-Tao/LeetCode
c34019520b5808c4251cb76f69ca2befa820401d
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; class Solution { public: vector<int> getRow(int rowIndex) { //The basic idea is to iteratively update the array from the end to the beginning. vector<int> res(rowIndex+1, 0); res[0] = 1; for(int i = 1; i<=rowIndex; i++){ for(int j = i; j>=1; j--){ res[j] = res[j] + res[j-1]; } } return res; } }; int main(){ vector<int> res = Solution().getRow(5); for (int n : res) cout << n << " "; }
22.791667
90
0.493601
Aden-Tao
f61f4fac644e64b9beeecde0907d014d6c7cb7ae
1,174
cpp
C++
IntroductionToCpp/Arrays/main.cpp
Trey0303/IntroToCpp
6aea72df60a1dfa80dbeb0d4f90a37fdaf3721b7
[ "MIT" ]
null
null
null
IntroductionToCpp/Arrays/main.cpp
Trey0303/IntroToCpp
6aea72df60a1dfa80dbeb0d4f90a37fdaf3721b7
[ "MIT" ]
null
null
null
IntroductionToCpp/Arrays/main.cpp
Trey0303/IntroToCpp
6aea72df60a1dfa80dbeb0d4f90a37fdaf3721b7
[ "MIT" ]
null
null
null
#include <cstdlib> #include <iostream> #include "arrayh.h" int main() { //create array //index 0 ,1,2 ,3,4 ,5, 6,7,8,9 //array size: 1 ,2,3 ,4,5 ,6, 7,8,9,10 int array[10]{10,1,25,4,33,4,26,7,6,9}; //get size of array int size = 0; for (int i : array) { size++; } //add first 5 numbers in array int result = sum(array, 5); //print full array printNumbers(array, size); //print sum of array int sum = sumNumbers(array, size); std::cout << std::endl << sum; //print largest num in array int largestNumFinal = largestValue(array, size); std::cout << std::endl << largestNumFinal; //find value in array, return index of value // array[],size,value,start int returnValue = findIndex(array, size, 6, 2); std::cout << std::endl << returnValue; //count number of times value is found in array from starting point // array[],size,value,start int count = countElement(array, size, 4, 2); std::cout << std::endl << count; //if array has two or more of the same number say no to being unique, else yes ArrayUniqueness(array, size); //Reverse reverse(array, size, 1, 10); return 0; }
22.150943
79
0.623509
Trey0303
f621ad6f82b11b939ba955b08fe55e539277e5dd
7,326
cpp
C++
packages/geometry/legacy/src/Geometry_SurfaceInputValidatorHelpers.cpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
packages/geometry/legacy/src/Geometry_SurfaceInputValidatorHelpers.cpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
packages/geometry/legacy/src/Geometry_SurfaceInputValidatorHelpers.cpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
//---------------------------------------------------------------------------// //! //! \file Geometry_SurfaceInputValidatorHelpers.cpp //! \author Alex Robinson //! \brief Surface input validator helper function definitions. //! //---------------------------------------------------------------------------// // Std Lib Includes #include <stdexcept> // Trilinos Includes #include <Teuchos_ParameterListExceptions.hpp> // FRENSIE Includes #include "Geometry_SurfaceInputValidatorHelpers.hpp" namespace Geometry{ // Validate the surface name /*! \details No empty spaces, (, ) or - characters are allowed in surface * names. If one is found, a std::invalid_argument exception is thrown. In * addition, the surface cannot be named "n" or "u". A * std::invalid_argument exception will be thrown if so. */ void validateSurfaceName( const std::string& surface_name ) { std::string error_message; // No empty spaces are allowed in surface names std::string::size_type empty_space_pos = surface_name.find( " " ); if( empty_space_pos < surface_name.size() ) { error_message += "Error in surface \""; error_message += surface_name; error_message += "\": spaces are not allowed in surface names.\n"; } // No ( or ) characters are allowed in surface names std::string::size_type left_paren_pos = surface_name.find( "(" ); std::string::size_type right_paren_pos = surface_name.find( ")" ); if( left_paren_pos < surface_name.size() ) { error_message += "Error in surface \""; error_message += surface_name; error_message += "\": ( characters are not allowed in surface names.\n"; } if( right_paren_pos < surface_name.size() ) { error_message += "Error in surface \""; error_message += surface_name; error_message += "\": ) characters are not allowed in surface names.\n"; } // No - characters are allowed in surface names std::string::size_type minus_pos = surface_name.find( "-" ); if( minus_pos < surface_name.size() ) { error_message += "Error in surface \""; error_message += surface_name; error_message += "\": - characters are not allowed in surface names.\n"; } // The name cannot be "n" or "u" if( surface_name.compare( "n" ) == 0 || surface_name.compare( "u" ) == 0 ) { error_message += "Error in surface \""; error_message += surface_name; error_message += "\": the name is reserved.\n"; } // If any errors have occured, throw if( error_message.size() > 0 ) { throw std::invalid_argument( error_message ); } } // Validate the surface type /*! \details Only the following surface types are valid: * <ul> * <li> x plane * <li> y plane * <li> z plane * <li> general plane * <li> x cylinder * <li> y cylinder * <li> z cylinder * <li> sphere * <li> general surface * </ul> * If any other type is specified, a std::invalid_argument excpetion is thrown. */ void validateSurfaceType( const std::string& surface_type, const std::string& surface_name ) { bool valid_surface_type = false; if( surface_type.compare( "x plane" ) == 0 ) valid_surface_type = true; else if( surface_type.compare( "y plane" ) == 0 ) valid_surface_type = true; else if( surface_type.compare( "z plane" ) == 0 ) valid_surface_type = true; else if( surface_type.compare( "general plane" ) == 0 ) valid_surface_type = true; else if( surface_type.compare( "x cylinder" ) == 0 ) valid_surface_type = true; else if( surface_type.compare( "y cylinder" ) == 0 ) valid_surface_type = true; else if( surface_type.compare( "z cylinder" ) == 0 ) valid_surface_type = true; else if( surface_type.compare( "sphere" ) == 0 ) valid_surface_type = true; else if( surface_type.compare( "general surface" ) == 0 ) valid_surface_type = true; // The surface type specified is invalid if( !valid_surface_type ) { std::string error_message = "Error in surface \""; error_message += surface_name.c_str(); error_message += "\": \""; error_message += surface_type.c_str(); error_message += "\" does not name a surface type.\n"; throw std::invalid_argument( error_message ); } } // Validate the surface definition /*! \details This function does not check if the surface is physically * reasonable - only that the correct number of arguments are specified for * the particular surface type. The required number of arguments are as * follows: * <ul> * <li> x plane: 1 * <li> y plane: 1 * <li> z plane: 1 * <li> general plane: 4 * <li> x cylinder: 3 * <li> y cylinder: 3 * <li> z cylinder: 3 * <li> sphere: 4 * <li> general surface: 10 * </ul> * If the number of parameters is not correct, a std::invalid_argument * exception is thrown. */ void validateSurfaceDefinition( const Teuchos::Array<double>& surface_definition, const std::string& surface_type, const std::string& surface_name ) { // Create the potential error message template std::string error_message = "Error in surface \""; error_message += surface_name.c_str(); error_message += "\": \""; error_message += surface_type.c_str(); error_message += "\" "; // axis aligned planes only require a single input value if( surface_type.compare( "x plane" ) == 0 || surface_type.compare( "y plane" ) == 0 || surface_type.compare( "z plane" ) == 0 ) { if( surface_definition.size() != 1 ) { error_message += "requires 1 argument.\n"; throw std::invalid_argument( error_message ); } } else if( surface_type.compare( "x cylinder" ) == 0 || surface_type.compare( "y cylinder" ) == 0 || surface_type.compare( "z cylinder" ) == 0 ) { if( surface_definition.size() != 3 ) { error_message += "requires 3 arguments.\n"; throw std::invalid_argument( error_message ); } } else if( surface_type.compare( "general plane" ) == 0 || surface_type.compare( "sphere" ) == 0 ) { if( surface_definition.size() != 4 ) { error_message += "requires 4 arguments.\n"; throw std::invalid_argument( error_message ); } } else if( surface_type.compare( "general surface" ) == 0 ) { if( surface_definition.size() != 10 ) { error_message += "requires 10 arguments.\n"; throw std::invalid_argument( error_message ); } } } // Validate the surface special attribute /*! \details Only one special attribute is currently accepted: reflecting. * Anything else will cause a std::invalid_argument exception to be thrown. */ void validateSurfaceSpecialAttribute( const std::string& surface_attribute, const std::string& surface_name ) { if( surface_attribute.compare( "reflecting" ) != 0) { std::string error_message = "Error in surface \""; error_message += surface_name.c_str(); error_message += "\": \""; error_message += surface_attribute.c_str(); error_message += "\" is not a valid special attribute.\n"; throw std::invalid_argument( error_message ); } } } // end Geometry namespace //---------------------------------------------------------------------------// // end Geometry_SurfaceInputValidatorHelpers.cpp //---------------------------------------------------------------------------//
31.307692
79
0.627355
lkersting
f62686765a2bf341306311cfa01096943efba6ad
6,362
cpp
C++
Meitner/Application/Example/Testbench/ProcessorTest/main.cpp
testdrive-profiling-master/profiles
6e3854874366530f4e7ae130000000812eda5ff7
[ "BSD-3-Clause" ]
null
null
null
Meitner/Application/Example/Testbench/ProcessorTest/main.cpp
testdrive-profiling-master/profiles
6e3854874366530f4e7ae130000000812eda5ff7
[ "BSD-3-Clause" ]
null
null
null
Meitner/Application/Example/Testbench/ProcessorTest/main.cpp
testdrive-profiling-master/profiles
6e3854874366530f4e7ae130000000812eda5ff7
[ "BSD-3-Clause" ]
null
null
null
//================================================================================ // Copyright (c) 2013 ~ 2021. HyungKi Jeong(clonextop@gmail.com) // Freely available under the terms of the 3-Clause BSD License // (https://opensource.org/licenses/BSD-3-Clause) // // Redistribution and use in source and binary forms, // with or without modification, are permitted provided // that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS // BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE // GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY // OF SUCH DAMAGE. // // Title : Testbench // Rev. : 12/28/2021 Tue (clonextop@gmail.com) //================================================================================ #include "Testbench.h" #include "hw/DUT.h" class Testbench : public TestbenchFramework { DUT* m_pDUT; // Processor (Design Under Testing) DDKMemory* m_pBuff; virtual bool OnInitialize(int argc, char** argv) { m_pDUT = NULL; m_pBuff = NULL; // H/W system equality check if(!CheckSimulation("Processor axi wrapper")) return false; m_pDUT = new DUT(m_pDDK); m_pDUT->SetClock(300.f); // set processor clock to 300MHz (High speed.) for performance m_pBuff = CreateDDKMemory(1024 * 8, 32); // 8KB, 256bit alignment MemoryLog(m_pBuff, "Test buffer memory"); return true; } virtual void OnRelease(void) { if(m_pDUT) m_pDUT->SetClock(50.f); // set processor clock to 50MHz (Low speed.) for IDLE status SAFE_RELEASE(m_pBuff); SAFE_DELETE(m_pDUT); } virtual bool OnTestBench(void) { //----------------------------------------------------- // slave R/W test //----------------------------------------------------- printf("\nAsynchronous slave FIFO R/W test...\n"); printf("\tDUT_CLOCK_GEN STATUS : 0x%X\n", m_pDDK->RegRead(DUT_CLOCKGEN_BASE)); printf("\tWrite slave fifo 5 times...\n"); for(int i = 0; i < 5; i++) { DWORD dwData = 0xABCD0000 | i; printf("\tWrite : 0x%X\n", dwData); m_pDDK->RegWrite(DUT_BASE | (3 << 2), dwData); } printf("\tDUT_CLOCK_GEN STATUS : 0x%X\n", m_pDDK->RegRead(DUT_CLOCKGEN_BASE)); printf("\tRead slave fifo 5 times...\n"); for(int i = 0; i < 5; i++) printf("\tRead : 0x%X\n", m_pDDK->RegRead(DUT_BASE)); //----------------------------------------------------- // master R/W test //----------------------------------------------------- //// ***** write test ***** printf("\nAsynchronous master write test...\n"); // clear memory printf("\tClear memory...\n"); memset(m_pBuff->Virtual(), 0xCC, m_pBuff->ByteSize()); // write to system memory m_pBuff->Flush(); // write m_pDDK->RegWrite(DUT_BASE | (0 << 2), m_pBuff->Physical()); // set target memory address m_pDDK->RegWrite(DUT_BASE | (1 << 2), 8); // set transfer size = 8 m_pDDK->RegWrite(DUT_BASE | (2 << 2), 1); // do write // wait for master bus write done // s/w is too fast in the h/w simulation mode, so we will wait a while. for(int i = 0; i < 20; i++) m_pDDK->RegRead(DUT_BASE); // read from system memory m_pBuff->Flush(FALSE); { DWORD* pData = (DWORD*)m_pBuff->Virtual(); for(int i = 0; i < 20; i++) printf("\tRead : [%d] %08X %08X %08X %08X %08X %08X %08X %08X\n", i, pData[i * 8], pData[i * 8 + 1], pData[i * 8 + 2], pData[i * 8 + 3], pData[i * 8 + 4], pData[i * 8 + 5], pData[i * 8 + 6], pData[i * 8 + 7]); } //// ***** read test ***** printf("\nAsynchronous master read test...\n"); { printf("\tInitiailze memory : 0x%X\n", m_pBuff->Physical()); DWORD* pData = (DWORD*)m_pBuff->Virtual(); for(int i = 0; i < 16; i++) { pData[i * 8] = 0xABC00000 | (i * 8 + 0); pData[i * 8 + 1] = 0xABC10000 | (i * 8 + 1); pData[i * 8 + 2] = 0xABC20000 | (i * 8 + 2); pData[i * 8 + 3] = 0xABC30000 | (i * 8 + 3); pData[i * 8 + 4] = 0xABC40000 | (i * 8 + 4); pData[i * 8 + 5] = 0xABC50000 | (i * 8 + 5); pData[i * 8 + 6] = 0xABC60000 | (i * 8 + 6); pData[i * 8 + 7] = 0xABC70000 | (i * 8 + 7); } // write to system memory m_pBuff->Flush(TRUE); } m_pDDK->RegWrite(DUT_BASE | (0 << 2), m_pBuff->Physical()); // set target memory address m_pDDK->RegWrite(DUT_BASE | (1 << 2), 8); // set transfer size = 8 m_pDDK->RegWrite(DUT_BASE | (2 << 2), 0); // do read // wait for master bus read done // s/w is too fast in the h/w simulation mode, so we will wait a while. for(int i = 0; i < 20; i++) m_pDDK->RegRead(DUT_BASE); // check out~~ printf("\tCheck out processor's valid read operation from simulation's waveform...\n"); //// ***** interrupt test ***** printf("\nInterrupt test...\n"); m_pDDK->RegWrite((DUT_BASE | (4 << 2)), 1); m_pDDK->WaitInterruptDone(); printf("\tInterrupt Counted = 0x%X\n", (m_pDDK->RegRead((DUT_CLOCKGEN_BASE | (4 << 2))) >> 18) & 0x3FF); // clear & get interrupt counter printf("process is done!\n"); return true; } }; int main(int argc, char** argv) { Testbench tb; if(tb.Initialize(argc, argv)) { if(!tb.DoTestbench()) printf("Testbench is failed.\n"); } else { printf("Initialization is failed.\n"); } }
36.774566
139
0.602012
testdrive-profiling-master
f626edbdcefd3f42a5ebe6d3b779ad4cc955d7da
19,938
hpp
C++
src/core/tb2clause.hpp
nrousse/toulbar2
ae79b8b05d7a57d7563ed6d497107b2e77cdd49c
[ "MIT" ]
33
2018-08-16T18:14:35.000Z
2022-03-14T10:26:18.000Z
src/core/tb2clause.hpp
nrousse/toulbar2
ae79b8b05d7a57d7563ed6d497107b2e77cdd49c
[ "MIT" ]
13
2018-08-09T06:53:08.000Z
2022-03-28T10:26:24.000Z
src/core/tb2clause.hpp
nrousse/toulbar2
ae79b8b05d7a57d7563ed6d497107b2e77cdd49c
[ "MIT" ]
12
2018-06-06T15:19:46.000Z
2022-02-11T17:09:27.000Z
#ifndef TB2WCLAUSE_HPP_ #define TB2WCLAUSE_HPP_ #include "tb2abstractconstr.hpp" #include "tb2ternaryconstr.hpp" #include "tb2enumvar.hpp" #include "tb2wcsp.hpp" #include <numeric> //TODO: avoid enumeration on all variables if they are already assigned and removed (using backtrackable domain data structure). //in order to speed-up propagate function if the support variable has a zero unary cost // warning! we assume binary variables class WeightedClause : public AbstractNaryConstraint { Cost cost; // clause weight Tuple tuple; // forbidden assignment corresponding to the negation of the clause StoreCost lb; // projected cost to problem lower bound (if it is zero then all deltaCosts must be zero) vector<StoreCost> deltaCosts; // extended costs from unary costs to the cost function int support; // index of a variable in the scope with a zero unary cost on its value which satisfies the clause StoreInt nonassigned; // number of non-assigned variables during search, must be backtrackable! vector<Long> conflictWeights; // used by weighted degree heuristics bool zeros; // true if all deltaCosts are zero (temporally used by first/next) bool done; // should be true after one call to next Value getTuple(int i) { return scope[i]->toValue(tuple[i]); } Value getClause(int i) { return scope[i]->toValue(!(tuple[i])); } void projectLB(Cost c) { lb += c; assert(lb <= cost); Constraint::projectLB(c); } void extend(Cost c) { for (int i = 0; i < arity_; i++) { EnumeratedVariable* x = scope[i]; if (x->unassigned()) { deltaCosts[i] += c; Value v = getClause(i); TreeDecomposition* td = wcsp->getTreeDec(); if (td) td->addDelta(cluster, x, v, -c); x->extend(v, c); } else assert(x->getValue() == getTuple(i)); } projectLB(c); } void satisfied(int varIndex) { nonassigned = 0; assert(scope[varIndex]->assigned()); assert(scope[varIndex]->getValue() == getClause(varIndex)); assert(deltaCosts[varIndex] == lb); for (int i = 0; i < arity_; i++) { EnumeratedVariable* x = scope[i]; assert(deconnected(i)); if (i != varIndex) { Cost c = deltaCosts[i]; Value v = getClause(i); if (c > MIN_COST) { deltaCosts[i] = MIN_COST; if (x->unassigned()) { if (!CUT(c + wcsp->getLb(), wcsp->getUb())) { TreeDecomposition* td = wcsp->getTreeDec(); if (td) td->addDelta(cluster, x, v, c); } x->project(v, c, true); x->findSupport(); } else { if (x->canbe(v)) { Constraint::projectLB(c); } } } } } } public: // warning! give the negation of the clause as input WeightedClause(WCSP* wcsp, EnumeratedVariable** scope_in, int arity_in, Cost cost_in = MIN_COST, Tuple tuple_in = Tuple()) : AbstractNaryConstraint(wcsp, scope_in, arity_in) , cost(cost_in) , tuple(tuple_in) , lb(MIN_COST) , support(0) , nonassigned(arity_in) , zeros(true) , done(false) { if (tuple_in.empty() && arity_in > 0) tuple = Tuple(arity_in, 0); deltaCosts = vector<StoreCost>(arity_in, StoreCost(MIN_COST)); for (int i = 0; i < arity_in; i++) { assert(scope_in[i]->getDomainInitSize() == 2); conflictWeights.push_back(0); } } virtual ~WeightedClause() {} void setTuple(const Tuple& tin, Cost c) FINAL { cost = c; tuple = tin; } bool extension() const FINAL { return false; } // TODO: allows functional variable elimination but not other preprocessing Long size() const FINAL { Cost sumdelta = ((lb > MIN_COST) ? accumulate(deltaCosts.begin(), deltaCosts.end(), -lb) : MIN_COST); if (sumdelta == MIN_COST) return 1; return getDomainSizeProduct(); } void reconnect() { if (deconnected()) { nonassigned = arity_; AbstractNaryConstraint::reconnect(); } } int getNonAssigned() const { return nonassigned; } Long getConflictWeight() const { return Constraint::getConflictWeight(); } Long getConflictWeight(int varIndex) const { assert(varIndex >= 0); assert(varIndex < arity_); return conflictWeights[varIndex] + Constraint::getConflictWeight(); } void incConflictWeight(Constraint* from) { assert(from!=NULL); if (from == this) { if (deconnected() || nonassigned==arity_) { Constraint::incConflictWeight(1); } else { for (int i = 0; i < arity_; i++) { if (connected(i)) { conflictWeights[i]++; } } } } else if (deconnected()) { for (int i = 0; i < from->arity(); i++) { int index = getIndex(from->getVar(i)); if (index >= 0) { // the last conflict constraint may be derived from two binary constraints (boosting search), each one derived from an n-ary constraint with a scope which does not include parameter constraint from assert(index < arity_); conflictWeights[index]++; } } } } void resetConflictWeight() { conflictWeights.assign(conflictWeights.size(), 0); Constraint::resetConflictWeight(); } bool universal() { if (cost != MIN_COST || lb != MIN_COST) return false; for (int i = 0; i < arity_; i++) if (deltaCosts[i] != MIN_COST) return false; return true; } Cost eval(const Tuple& s) { if (lb == MIN_COST && tuple[support] != s[support]) { assert(accumulate(deltaCosts.begin(), deltaCosts.end(), -lb) == MIN_COST); return MIN_COST; } else { Cost res = -lb; bool istuple = true; for (int i = 0; i < arity_; i++) { if (tuple[i] != s[i]) { res += deltaCosts[i]; istuple = false; } } if (istuple) res += cost; assert(res >= MIN_COST); return res; } } Cost evalsubstr(const Tuple& s, Constraint* ctr) FINAL { return evalsubstrAny(s, ctr); } Cost evalsubstr(const Tuple& s, NaryConstraint* ctr) FINAL { return evalsubstrAny(s, ctr); } template <class T> Cost evalsubstrAny(const Tuple& s, T* ctr) { int count = 0; for (int i = 0; i < arity_; i++) { int ind = ctr->getIndex(getVar(i)); if (ind >= 0) { evalTuple[i] = s[ind]; count++; } } assert(count <= arity_); Cost cost; if (count == arity_) cost = eval(evalTuple); else cost = MIN_COST; return cost; } Cost getCost() FINAL { for (int i = 0; i < arity_; i++) { EnumeratedVariable* var = (EnumeratedVariable*)getVar(i); evalTuple[i] = var->toIndex(var->getValue()); } return eval(evalTuple); } double computeTightness() { return 1.0 * cost / getDomainSizeProduct(); } pair<pair<Cost, Cost>, pair<Cost, Cost>> getMaxCost(int index, Value a, Value b) { Cost sumdelta = ((lb > MIN_COST) ? accumulate(deltaCosts.begin(), deltaCosts.end(), -lb) : MIN_COST); bool supporta = (getClause(index) == a); Cost maxcosta = max((supporta) ? MIN_COST : (cost - lb), sumdelta - ((supporta) ? MIN_COST : (Cost)deltaCosts[index])); Cost maxcostb = max((supporta) ? (cost - lb) : MIN_COST, sumdelta - ((supporta) ? (Cost)deltaCosts[index] : MIN_COST)); return make_pair(make_pair(maxcosta, maxcosta), make_pair(maxcostb, maxcostb)); } void first() { zeros = all_of(deltaCosts.begin(), deltaCosts.end(), [](Cost c) { return c == MIN_COST; }); done = false; if (!zeros) firstlex(); } bool next(Tuple& t, Cost& c) { if (!zeros) return nextlex(t, c); if (done) return false; t = tuple; c = cost - lb; done = true; return true; } Cost getMaxFiniteCost() { Cost sumdelta = ((lb > MIN_COST) ? accumulate(deltaCosts.begin(), deltaCosts.end(), -lb) : MIN_COST); if (CUT(sumdelta, wcsp->getUb())) return MAX_COST; if (CUT(cost, wcsp->getUb())) return sumdelta; else return max(sumdelta, cost - lb); } void setInfiniteCost(Cost ub) { Cost mult_ub = ((ub < (MAX_COST / MEDIUM_COST)) ? (max(LARGE_COST, ub * MEDIUM_COST)) : ub); if (CUT(cost, ub)) cost = mult_ub; } void assign(int varIndex) { if (connected(varIndex)) { deconnect(varIndex); nonassigned = nonassigned - 1; assert(nonassigned >= 0); if (scope[varIndex]->getValue() == getClause(varIndex)) { deconnect(); satisfied(varIndex); return; } if (nonassigned <= 3) { deconnect(); projectNary(); } else { if (ToulBar2::FullEAC) reviseEACGreedySolution(); } } } // propagates the minimum between the remaining clause weight and unary costs of all literals to the problem lower bound void propagate() { Cost mincost = (connected() && scope[support]->unassigned()) ? scope[support]->getCost(getClause(support)) : MAX_COST; for (int i = 0; connected() && i < arity_; i++) { EnumeratedVariable* x = scope[i]; if (x->assigned()) { assign(i); } else if (mincost > MIN_COST) { Cost ucost = x->getCost(getClause(i)); if (ucost < mincost) { mincost = ucost; support = i; } } } if (connected() && mincost < MAX_COST && mincost > MIN_COST && cost > lb) { extend(min(cost - lb, mincost)); } }; bool verify() { Tuple t; Cost c; firstlex(); while (nextlex(t, c)) { if (c == MIN_COST) return true; } return false; } void increase(int index) {} void decrease(int index) {} void remove(int index) {} void projectFromZero(int index) { if (index == support && cost > lb) propagate(); } bool checkEACGreedySolution(int index = -1, Value supportValue = 0) FINAL { bool zerolb = (lb == MIN_COST); if (zerolb && getTuple(support) != ((support == index) ? supportValue : getVar(support)->getSupport())) { assert(accumulate(deltaCosts.begin(), deltaCosts.end(), -lb) == MIN_COST); return true; } else { Cost res = -lb; bool istuple = true; for (int i = 0; i < arity_; i++) { if (getTuple(i) != ((i == index) ? supportValue : getVar(i)->getSupport())) { res += deltaCosts[i]; istuple = false; if (zerolb) { assert(res == MIN_COST); assert(accumulate(deltaCosts.begin(), deltaCosts.end(), -lb) == MIN_COST); return true; } } } if (istuple) res += cost; assert(res >= MIN_COST); return (res == MIN_COST); } } bool reviseEACGreedySolution(int index = -1, Value supportValue = 0) FINAL { bool result = checkEACGreedySolution(index, supportValue); if (!result) { if (index >= 0) { getVar(index)->unsetFullEAC(); } else { int a = arity(); for (int i = 0; i < a; i++) { getVar(i)->unsetFullEAC(); } } } return result; } void print(ostream& os) { os << endl << this << " clause("; int unassigned_ = 0; for (int i = 0; i < arity_; i++) { if (scope[i]->unassigned()) unassigned_++; if (getClause(i) == 0) os << "-"; os << wcsp->getName(scope[i]->wcspIndex); if (i < arity_ - 1) os << ","; } os << ") s:" << support << " / " << cost << " - " << lb << " ("; for (int i = 0; i < arity_; i++) { os << deltaCosts[i]; if (i < arity_ - 1) os << ","; } os << ") "; if (ToulBar2::weightedDegree) { os << "/" << getConflictWeight(); for (int i = 0; i < arity_; i++) { os << "," << conflictWeights[i]; } } os << " arity: " << arity_; os << " unassigned: " << (int)nonassigned << "/" << unassigned_ << endl; } void dump(ostream& os, bool original = true) { Cost maxdelta = MIN_COST; for (vector<StoreCost>::iterator it = deltaCosts.begin(); it != deltaCosts.end(); ++it) { Cost d = (*it); if (d > maxdelta) maxdelta = d; } if (original) { os << arity_; for (int i = 0; i < arity_; i++) os << " " << scope[i]->wcspIndex; if (maxdelta == MIN_COST) { os << " " << 0 << " " << 1 << endl; for (int i = 0; i < arity_; i++) { os << scope[i]->toValue(tuple[i]) << " "; } os << cost << endl; } else { os << " " << 0 << " " << getDomainSizeProduct() << endl; Tuple t; Cost c; firstlex(); while (nextlex(t, c)) { for (int i = 0; i < arity_; i++) { os << scope[i]->toValue(t[i]) << " "; } os << c << endl; } } } else { os << nonassigned; for (int i = 0; i < arity_; i++) if (scope[i]->unassigned()) os << " " << scope[i]->getCurrentVarId(); if (maxdelta == MIN_COST) { os << " " << 0 << " " << 1 << endl; for (int i = 0; i < arity_; i++) { if (scope[i]->unassigned()) os << scope[i]->toCurrentIndex(scope[i]->toValue(tuple[i])) << " "; } os << min(wcsp->getUb(), cost) << endl; } else { os << " " << 0 << " " << getDomainSizeProduct() << endl; Tuple t; Cost c; firstlex(); while (nextlex(t, c)) { for (int i = 0; i < arity_; i++) { if (scope[i]->unassigned()) os << scope[i]->toCurrentIndex(scope[i]->toValue(t[i])) << " "; } os << min(wcsp->getUb(), c) << endl; } } } } void dump_CFN(ostream& os, bool original = true) { bool printed = false; os << "\"F_"; Cost maxdelta = MIN_COST; for (vector<StoreCost>::iterator it = deltaCosts.begin(); it != deltaCosts.end(); ++it) { Cost d = (*it); if (d > maxdelta) maxdelta = d; } if (original) { printed = false; for (int i = 0; i < arity_; i++) { if (printed) os << "_"; os << scope[i]->wcspIndex; printed = true; } os << "\":{\"scope\":["; printed = false; for (int i = 0; i < arity_; i++) { if (printed) os << ","; os << "\"" << scope[i]->getName() << "\""; printed = true; } os << "],\"defaultcost\":" << wcsp->Cost2RDCost(MIN_COST) << ",\n\"costs\":["; if (maxdelta == MIN_COST) { printed = false; for (int i = 0; i < arity_; i++) { if (printed) os << ","; os << tuple[i]; printed = true; } os << "," << wcsp->Cost2RDCost(cost); } else { Tuple t; Cost c; printed = false; firstlex(); while (nextlex(t, c)) { os << endl; for (int i = 0; i < arity_; i++) { if (printed) os << ","; os << t[i]; printed = true; } os << "," << wcsp->Cost2RDCost(c); } } } else { for (int i = 0; i < arity_; i++) if (scope[i]->unassigned()) { if (printed) os << "_"; os << scope[i]->getCurrentVarId(); printed = true; } os << "\":{\"scope\":["; printed = false; for (int i = 0; i < arity_; i++) if (scope[i]->unassigned()) { if (printed) os << ","; os << "\"" << scope[i]->getName() << "\""; printed = true; } os << "],\"defaultcost\":" << wcsp->Cost2RDCost(MIN_COST) << ",\n\"costs\":["; if (maxdelta == MIN_COST) { printed = false; for (int i = 0; i < arity_; i++) { if (scope[i]->unassigned()) { if (printed) os << ","; os << scope[i]->toCurrentIndex(scope[i]->toValue(tuple[i])); printed = true; } } os << "," << wcsp->Cost2RDCost(min(wcsp->getUb(), cost)); } else { Tuple t; Cost c; printed = false; firstlex(); while (nextlex(t, c)) { os << endl; for (int i = 0; i < arity_; i++) { if (scope[i]->unassigned()) { if (printed) os << ","; os << scope[i]->toCurrentIndex(scope[i]->toValue(t[i])); printed = true; } } os << "," << wcsp->Cost2RDCost(min(wcsp->getUb(), c)); } } } os << "]},\n"; } }; #endif /*TB2WCLAUSE_HPP_*/ /* Local Variables: */ /* c-basic-offset: 4 */ /* tab-width: 4 */ /* indent-tabs-mode: nil */ /* c-default-style: "k&r" */ /* End: */
34.023891
231
0.440716
nrousse
f628fb8cbac669d14b03e8cca499eb4e042514e0
1,870
cpp
C++
src/light_effects.cpp
ljmerza/mqtt-msgeq7-led-strip
cd7574efbb1c4a2ba465cba51abe6fbeef5ac875
[ "MIT" ]
1
2019-05-16T01:49:14.000Z
2019-05-16T01:49:14.000Z
src/light_effects.cpp
ljmerza/mqtt-msgeq7-led-strip
cd7574efbb1c4a2ba465cba51abe6fbeef5ac875
[ "MIT" ]
1
2019-01-24T02:04:06.000Z
2019-01-28T17:51:22.000Z
src/light_effects.cpp
ljmerza/mqtt-msgeq7-led-strip
cd7574efbb1c4a2ba465cba51abe6fbeef5ac875
[ "MIT" ]
null
null
null
#include "common.h" #include "config.h" void fill_led_colors(CRGBPalette16 current_palette){ for(int i=0; i<NUM_LEDS; i++) { leds[i] = ColorFromPalette(current_palette, 0, brightness, LINEARBLEND); } } CRGBPalette16 lamp_light(uint8_t red, uint8_t green, uint8_t blue){ CRGB rgb = CRGB(red, green, blue); CRGBPalette16 current_palette = CRGBPalette16( rgb, rgb, rgb, rgb, rgb, rgb, rgb, rgb, rgb, rgb, rgb, rgb, rgb, rgb, rgb, rgb ); return current_palette; } void lamp_candle(){ CRGBPalette16 current_palette = lamp_light(255, 147, 41); fill_led_colors(current_palette); } void lamp_tungsten_40w(){ CRGBPalette16 current_palette = lamp_light(255, 197, 143); fill_led_colors(current_palette); } void lamp_tungsten_100w(){ CRGBPalette16 current_palette = lamp_light(255, 214, 170); fill_led_colors(current_palette); } void lamp_high_pressure_sodium() { CRGBPalette16 current_palette = lamp_light(255, 183, 76); fill_led_colors(current_palette); } void cloudColors_p() { CRGBPalette16 current_palette = CloudColors_p; fill_led_colors(current_palette); } void oceanColors_p() { CRGBPalette16 current_palette = OceanColors_p; fill_led_colors(current_palette); } void forestColors_p() { CRGBPalette16 current_palette = ForestColors_p; fill_led_colors(current_palette); } void lavaColors_p() { CRGBPalette16 current_palette = LavaColors_p; fill_led_colors(current_palette); } void rainbowStripeColors_p() { CRGBPalette16 current_palette = RainbowStripeColors_p; fill_led_colors(current_palette); } void partyColors_p() { CRGBPalette16 current_palette = PartyColors_p; fill_led_colors(current_palette); } void heatColors_p() { CRGBPalette16 current_palette = HeatColors_p; fill_led_colors(current_palette); }
24.605263
80
0.728877
ljmerza
f62b9446cb6a8084b843648adfd65d222d4df16f
5,861
cpp
C++
IP.cpp
keewon/winter-source-beta-3
6fb5d1f524119344785b3587ecb71dff74120b91
[ "FSFAP" ]
null
null
null
IP.cpp
keewon/winter-source-beta-3
6fb5d1f524119344785b3587ecb71dff74120b91
[ "FSFAP" ]
null
null
null
IP.cpp
keewon/winter-source-beta-3
6fb5d1f524119344785b3587ecb71dff74120b91
[ "FSFAP" ]
null
null
null
#include "IP.h" #include <set> #define LOG_ERR 3 unsigned int IP::counter(0); SOCKET IP:: UDP(int (*const function)(const SOCKET), const u_short port) { struct sockaddr_in address; size_t length(sizeof(struct sockaddr)); SOCKET socketID(socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)); if (socketID == INVALID_SOCKET) { syslog(LOG_ERR, "socket in IP::UDP\n"); return INVALID_SOCKET; } memset((void *) & address, 0, length); address.sin_family = AF_INET; address.sin_addr.s_addr = htonl(INADDR_ANY); address.sin_port = htons(port); if (bind(socketID, (struct sockaddr *) & address, length) == SOCKET_ERROR) { syslog(LOG_ERR, "bind in IP::UDP\n"); closesocket(socketID); return INVALID_SOCKET; } client[socketID] = function; return socketID; } SOCKET IP:: TCP(int (*const function)(const SOCKET), const u_short port) { struct sockaddr_in address; size_t length(sizeof(struct sockaddr)); SOCKET socketID(socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)); if (socketID == INVALID_SOCKET) { syslog(LOG_ERR, "socket in IP::TCP\n"); return INVALID_SOCKET; } memset((void *) & address, 0, length); address.sin_family = AF_INET; address.sin_addr.s_addr = htonl(INADDR_ANY); address.sin_port = htons(port); if (bind(socketID, (struct sockaddr *) & address, length) == SOCKET_ERROR) { syslog(LOG_ERR, "bind in IP::TCP\n"); closesocket(socketID); return INVALID_SOCKET; } if (listen(socketID, SOMAXCONN) == SOCKET_ERROR) { syslog(LOG_ERR, "listen in IP::TCP\n"); closesocket(socketID); return INVALID_SOCKET; } server[socketID] = function; return socketID; } SOCKET IP:: TCP(int (*const function)(const SOCKET), const u_short port, const char *const server) { struct sockaddr_in address; size_t length(sizeof(struct sockaddr)); SOCKET socketID(socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)); if (socketID == INVALID_SOCKET) { syslog(LOG_ERR, "socket in IP::TCP\n"); return INVALID_SOCKET; } memset((void *) & address, 0, length); address.sin_family = AF_INET; address.sin_addr.s_addr = inet_addr(server); address.sin_port = htons(port); if (connect(socketID, (struct sockaddr *) & address, length) == SOCKET_ERROR) { syslog(LOG_ERR, "connect in IP::TCP\n"); closesocket(socketID); return INVALID_SOCKET; } client[socketID] = function; return socketID; } bool IP:: empty(void) { if (client.find(INVALID_SOCKET) != client.end()) client.erase(INVALID_SOCKET); return server.empty() && client.empty(); } void IP:: erase(const SOCKET socketID) { if (server.find(socketID) != server.end()) server.erase(socketID); if (client.find(socketID) != client.end()) client.erase(socketID); closesocket(socketID); } int IP:: operator ()(const struct timeval *const timeout) { SOCKET maxID(0); fd_set FileDescriptors; FD_ZERO(& FileDescriptors); if (client.find(INVALID_SOCKET) != client.end()) client.erase(INVALID_SOCKET); for (map::const_iterator i(server.begin()); i != server.end(); ++i) { FD_SET(i->first, & FileDescriptors); if (maxID < i->first) maxID = i->first; } for (map::const_iterator i(client.begin()); i != client.end(); ++i) { FD_SET(i->first, & FileDescriptors); if (maxID < i->first) maxID = i->first; } if (select(maxID + 1, & FileDescriptors, 0, 0, const_cast <struct timeval *>(timeout)) == SOCKET_ERROR) { syslog(LOG_ERR, "select in IP::operator ()\n"); return SOCKET_ERROR; } std::set <SOCKET> sockets; for (map::const_iterator i(client.begin()); i != client.end(); ++i) if (FD_ISSET(i->first, & FileDescriptors) && i->second != 0) if ((* i->second)(i->first) == SOCKET_ERROR) sockets.insert(i->first); for (map::const_iterator i(server.begin()); i != server.end(); ++i) if (FD_ISSET(i->first, & FileDescriptors)) { struct sockaddr_in address; size_t length(sizeof(address)); SOCKET socketID(accept(i->first, (struct sockaddr *) & address, (int *) & length)); if (socketID == INVALID_SOCKET) { syslog(LOG_ERR, "accept in IP::operator ()\n"); continue; } if (maxID < socketID) maxID = socketID; client[socketID] = i->second; if (i->second != 0 && (* i->second)(socketID) == SOCKET_ERROR) sockets.insert(socketID); } for (std::set <SOCKET>::const_iterator i(sockets.begin()); i != sockets.end(); ++i) erase(* i); FD_ZERO(& FileDescriptors); return 0; } IP::map::referent_type & IP:: operator [](const SOCKET socketID) { if (server.find(socketID) != server.end()) return server[socketID]; if (client.find(socketID) != client.end()) return client[socketID]; return client[INVALID_SOCKET]; } IP:: IP(HWND hWnd) { if (counter++ == 0) { WSADATA wsaData; if (WSAStartup(MAKEWORD(2, 2), &wsaData) == SOCKET_ERROR) { if (hWnd != 0) MessageBox(hWnd, "WSAStartup", "Winsock", MB_OK); WSACleanup(); } } } IP:: ~IP(void) { std::set <SOCKET> sockets; for (map::const_iterator i(server.begin()); i != server.end(); ++i) { closesocket(i->first); sockets.insert(i->first); } for (std::set <SOCKET>::const_iterator i(sockets.begin()); i != sockets.end(); ++i) server.erase(* i); sockets.clear(); for (map::const_iterator i(client.begin()); i != client.end(); ++i) { closesocket(i->first); sockets.insert(i->first); } for (std::set <SOCKET>::const_iterator i(sockets.begin()); i != sockets.end(); ++i) client.erase(* i); if (--counter == 0) WSACleanup(); }
25.819383
108
0.615765
keewon
f62d44c9ae61529633378a66943811cb0edbad84
1,239
cpp
C++
Sources/common/erm/rendering/data_structs/RenderConfigs.cpp
JALB91/ERM
5d2c56db6330efc7d662c24796fdc49e43d26e40
[ "MIT" ]
5
2019-02-26T18:46:52.000Z
2022-01-27T23:48:26.000Z
Sources/common/erm/rendering/data_structs/RenderConfigs.cpp
JALB91/ERM
5d2c56db6330efc7d662c24796fdc49e43d26e40
[ "MIT" ]
1
2020-06-07T23:44:29.000Z
2021-04-03T18:49:54.000Z
Sources/common/erm/rendering/data_structs/RenderConfigs.cpp
JALB91/ERM
5d2c56db6330efc7d662c24796fdc49e43d26e40
[ "MIT" ]
null
null
null
#include "erm/rendering/data_structs/RenderConfigs.h" namespace erm { const RenderConfigs RenderConfigs::DEFAULT_RENDER_CONFIGS { SubpassData { AttachmentData( AttachmentLoadOp::CLEAR, AttachmentStoreOp::STORE, ImageLayout::UNDEFINED, #ifdef ERM_RAY_TRACING_ENABLED ImageLayout::GENERAL #else ImageLayout::COLOR_ATTACHMENT_OPTIMAL #endif ), AttachmentData( AttachmentLoadOp::CLEAR, #ifdef ERM_RAY_TRACING_ENABLED AttachmentStoreOp::STORE, #else AttachmentStoreOp::DONT_CARE, #endif ImageLayout::UNDEFINED, #ifdef ERM_RAY_TRACING_ENABLED ImageLayout::GENERAL #else ImageLayout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL #endif )}}; RenderConfigs::RenderConfigs(const SubpassData& subpassData) : mSubpassData(subpassData) {} bool RenderConfigs::operator==(const RenderConfigs& other) const { return IsRenderPassLevelCompatible(other); } bool RenderConfigs::operator!=(const RenderConfigs& other) const { return !(*this == other); } bool RenderConfigs::IsRenderPassLevelCompatible(const RenderConfigs& other) const { return IsSubpassCompatible(other); } bool RenderConfigs::IsSubpassCompatible(const RenderConfigs& other) const { return mSubpassData == other.mSubpassData; } } // namespace erm
21.736842
81
0.786118
JALB91
f62dbe57b051d83e747c9fba74632255747eb9a1
1,045
cpp
C++
Bit Manipulation/AND Product.cpp
StavrosChryselis/hackerrank
42a3e393231e237a99a9e54522ce3ec954bf614f
[ "MIT" ]
null
null
null
Bit Manipulation/AND Product.cpp
StavrosChryselis/hackerrank
42a3e393231e237a99a9e54522ce3ec954bf614f
[ "MIT" ]
null
null
null
Bit Manipulation/AND Product.cpp
StavrosChryselis/hackerrank
42a3e393231e237a99a9e54522ce3ec954bf614f
[ "MIT" ]
null
null
null
/* **************************************************************** **************************************************************** -> Coded by Stavros Chryselis -> Visit my github for more solved problems over multiple sites -> https://github.com/StavrosChryselis -> Feel free to email me at stavrikios@gmail.com **************************************************************** **************************************************************** */ #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; long long A, B; inline long long solve() { long long sum = 0; long long AA = A, BB = B; long long val = 1; while(A || B) { if(A % 2 && B % 2 && BB - AA < val) sum += val; val *= 2; A /= 2; B /= 2; } return sum; } int main() { int T; scanf("%d", &T); while(T--) { scanf("%lld %lld", &A, &B); printf("%lld\n", solve()); } return 0; }
20.490196
64
0.378947
StavrosChryselis
f6301d5a4bed812c45991e5f220e2e92de000a7d
1,663
cpp
C++
modules/params-triangle/test/test_params_triangle.cpp
gurylev-nikita/devtools-course-practice
bab6ba4e39f04940e27c9ac148505eb152c05d17
[ "CC-BY-4.0" ]
null
null
null
modules/params-triangle/test/test_params_triangle.cpp
gurylev-nikita/devtools-course-practice
bab6ba4e39f04940e27c9ac148505eb152c05d17
[ "CC-BY-4.0" ]
3
2021-04-22T17:12:19.000Z
2021-05-14T12:16:25.000Z
modules/params-triangle/test/test_params_triangle.cpp
taktaev-artyom/devtools-course-practice
7cf19defe061c07cfb3ebb71579456e807430a5d
[ "CC-BY-4.0" ]
null
null
null
// Copyright 2021 Paranicheva Alyona #include <gtest/gtest.h> #include <cmath> #include <iostream> #include <utility> #include "include/triangle.h" TEST(Params_Triangle, Create_Triangle) { std::pair<double, double> a(2.5, 0); std::pair<double, double> b(0, 4.5); std::pair<double, double> c(-1.5, 0); ASSERT_NO_THROW(Triangle(a, b, c)); } TEST(Params_Triangle, Calculate_SideAB) { std::pair<double, double> a(0, 0); std::pair<double, double> b(0, 4); std::pair<double, double> c(3, 0); Triangle tr(a, b, c); double sideAB = tr.SideAB(); ASSERT_DOUBLE_EQ(4.0, sideAB); } TEST(Params_Triangle, Calculate_SideBC) { std::pair<double, double> a(0, 0); std::pair<double, double> b(0, 4); std::pair<double, double> c(3, 0); Triangle tr(a, b, c); double sideBC = tr.SideBC(); ASSERT_DOUBLE_EQ(5.0, sideBC); } TEST(Params_Triangle, Calculate_SideAC) { std::pair<double, double> a(0, 0); std::pair<double, double> b(0, 4); std::pair<double, double> c(3, 0); Triangle tr(a, b, c); double sideAC = tr.SideAC(); ASSERT_DOUBLE_EQ(3.0, sideAC); } TEST(Params_Triangle, Calculate_Perimeter) { std::pair<double, double> a(0, 0); std::pair<double, double> b(0, 4); std::pair<double, double> c(3, 0); Triangle tr(a, b, c); double Perimeter = tr.Perimeter(); ASSERT_DOUBLE_EQ(12.0, Perimeter); } TEST(Params_Triangle, Calculate_Area) { std::pair<double, double> a(0, 0); std::pair<double, double> b(0, 4); std::pair<double, double> c(3, 0); Triangle tr(a, b, c); double Area = tr.Area(); ASSERT_DOUBLE_EQ(6.0, Area); }
26.396825
44
0.622971
gurylev-nikita
f63098e2ca87affc55081c3ae5b7011a1cf55a89
4,490
cpp
C++
HN_Path/HN_File.cpp
Jusdetalent/JT_Utility
2dec8ff0e8a0263a589f0829d63cf01dcae46d79
[ "MIT" ]
null
null
null
HN_Path/HN_File.cpp
Jusdetalent/JT_Utility
2dec8ff0e8a0263a589f0829d63cf01dcae46d79
[ "MIT" ]
null
null
null
HN_Path/HN_File.cpp
Jusdetalent/JT_Utility
2dec8ff0e8a0263a589f0829d63cf01dcae46d79
[ "MIT" ]
null
null
null
/* * File source file * By Henock @ Comedac * 07/ 12/ 2016 :: 13:03 */ #include "HN_File.hpp" #include <cstring> #include <cstdio> #include <sys/stat.h> using namespace hnapi::path; // Static methods bool hnapi::path::isFileExist(std::string &dirname) { // Obtain file statistics struct stat fileStat; int i = stat(dirname.c_str(), &fileStat); /* printf("%d %d %d %d %d %d %ld [%ld] %ld %ld %d\n", fileStat.st_mode, fileStat.st_ino, fileStat.st_dev, fileStat.st_nlink, fileStat.st_uid, fileStat.st_gid, fileStat.st_size, fileStat.st_atime, fileStat.st_mtime, fileStat.st_ctime, i); */ if(i == -1 || !S_ISREG(fileStat.st_mode)) return false; // Can arrive here only with success return true; } bool hnapi::path::isFileAbsolutePath(std::string &path) { // Data pointers const char *buffer = path.c_str(); int b_len = strlen(buffer), li = 0; // Analyze if root if(buffer[0] == '\\' || buffer[0] == '/') return true; // If driver for(int i = 0; i < b_len; i++) { switch(buffer[i]) { case '\\': case '/': { if(li == ':'){return true;} } break; } li = buffer[i]; } // Can not arrive here return false; } bool hnapi::path::deleteFileFirstDirName(std::string &path) { return true; } bool hnapi::path::deleteFileFolderName(std::string &path) { return true; } bool hnapi::path::deleteFileFileName(std::string &path, int id) { return true; } std::string hnapi::path::getFileFileName(std::string &path) { // Generate pointers const char *buffer = path.c_str(); int b_len = strlen(buffer), i_len = b_len; bool breaked = false; // Point on separator for(; b_len >= 0; b_len--) { if(buffer[b_len] == '\\' || buffer[b_len] == '/') { breaked = true; break; } } if(b_len == 0 && !breaked) return buffer; // Build data to return char filename[260]; int j = 0; memset(filename, 0, 260 * sizeof(char)); for(b_len++; b_len < i_len; b_len++) { filename[j] = buffer[b_len]; j++; } // Return filename return filename; } std::string hnapi::path::getFileFolderName(std::string &path) { // Generate pointers const char *buffer = path.c_str(); int b_len = strlen(buffer); bool breaked = false; // Point on separator for(; b_len >= 0; b_len--) { if(buffer[b_len] == '\\' || buffer[b_len] == '/') { breaked = true; break; } } if(b_len == 0 && !breaked) return buffer; // Build data to return char filename[260]; int j = 0; for(; j <= b_len; j++){ filename[j] = buffer[j]; }filename[j] = '\0'; // Return filename return filename; } std::string hnapi::path::getFileExtension(std::string &path) { // Build data pointers const char *buffer = path.c_str(); int b_len = strlen(buffer), i; std::string extension; // Place cursor for(i = b_len; i >= 0; i--) { if(buffer[i] == '.') { break; } } // Loop for getting file extension for(i++; i < b_len; i++) { extension+= buffer[i]; } return extension; } bool hnapi::path::isLocalFilePath(std::string &path) { // Verify if file exist if(hnapi::path::isFileExist(path)) return true; // Get file root std::string root = hnapi::path::getFileRoot(path); if(root == "file:") return true; // Unable to find it on local return false; } std::string hnapi::path::getFileRoot(std::string &path) { // Build data pointers const char *buffer = path.c_str(); int b_len = strlen(buffer), i; std::string root; // Loop for getting file root for(i = 0; i < b_len; i++) { root+= buffer[i]; if(buffer[i] == ':') break; } // Return root return root; }
20.883721
64
0.493318
Jusdetalent
f6341801ae9d29d0e6d9cc0f105e1878ad239e9f
9,079
cpp
C++
oaz/neural_network/nn_evaluator.cpp
ameroueh/oaz
7cf192b02adaa373b7b93bedae3ef67886ea53af
[ "MIT" ]
8
2021-03-18T16:06:42.000Z
2022-03-09T10:42:44.000Z
oaz/neural_network/nn_evaluator.cpp
ameroueh/oaz
7cf192b02adaa373b7b93bedae3ef67886ea53af
[ "MIT" ]
null
null
null
oaz/neural_network/nn_evaluator.cpp
ameroueh/oaz
7cf192b02adaa373b7b93bedae3ef67886ea53af
[ "MIT" ]
null
null
null
#include "oaz/neural_network/nn_evaluator.hpp" #include <stdint.h> #include <functional> #include <future> #include <iostream> #include <memory> #include <queue> #include <string> #include <thread> #include <utility> #include "boost/multi_array.hpp" #include "oaz/utils/time.hpp" #include "tensorflow/core/framework/tensor.h" oaz::nn::EvaluationBatch::EvaluationBatch( const std::vector<int>& element_dimensions, size_t size) : m_current_index(0), m_n_reads(0), m_size(size), m_element_size(std::accumulate(element_dimensions.cbegin(), element_dimensions.cend(), 1, std::multiplies<int>())), m_games(boost::extents[size]), m_values(boost::extents[size]), m_policies(boost::extents[size]), m_tasks(boost::extents[size]), m_statistics(std::make_unique<oaz::nn::EvaluationBatchStatistics>()) { std::vector<tensorflow::int64> tensor_dimensions = { static_cast<tensorflow::int64>(size)}; tensor_dimensions.insert(tensor_dimensions.end(), element_dimensions.begin(), element_dimensions.end()); m_batch = tensorflow::Tensor(tensorflow::DT_FLOAT, tensorflow::TensorShape(tensor_dimensions)); GetStatistics().time_created = oaz::utils::time_now_ns(); GetStatistics().size = GetSize(); } oaz::nn::EvaluationBatchStatistics& oaz::nn::EvaluationBatch::GetStatistics() { return *m_statistics; } void oaz::nn::EvaluationBatch::InitialiseElement( size_t index, oaz::games::Game* game, float* value, const boost::multi_array_ref<float, 1>& policy, oaz::thread_pool::Task* task) { float* destination = m_batch.flat<float>().data() + index * GetElementSize(); game->WriteCanonicalStateToTensorMemory(destination); m_games[index] = game; m_values[index] = value; m_policies[index] = std::move(std::make_unique<boost::multi_array_ref<float, 1>>(policy)); m_tasks[index] = task; ++m_n_reads; } bool oaz::nn::EvaluationBatch::IsAvailableForEvaluation() const { return m_current_index == m_n_reads; } size_t oaz::nn::EvaluationBatch::AcquireIndex() { size_t index = m_current_index; ++m_current_index; return index; } boost::multi_array_ref<oaz::games::Game*, 1> oaz::nn::EvaluationBatch::GetGames() { return boost::multi_array_ref<oaz::games::Game*, 1>( m_games.origin(), boost::extents[GetSize()]); } boost::multi_array_ref<float*, 1> oaz::nn::EvaluationBatch::GetValues() { return boost::multi_array_ref<float*, 1>(m_values.origin(), boost::extents[GetSize()]); } boost::multi_array_ref<std::unique_ptr<boost::multi_array_ref<float, 1>>, 1> oaz::nn::EvaluationBatch::GetPolicies() { return boost::multi_array_ref< std::unique_ptr<boost::multi_array_ref<float, 1>>, 1>( m_policies.origin(), boost::extents[GetSize()]); } size_t oaz::nn::EvaluationBatch::GetSize() const { return m_size; } size_t oaz::nn::EvaluationBatch::GetElementSize() const { return m_element_size; } tensorflow::Tensor& oaz::nn::EvaluationBatch::GetBatchTensor() { return m_batch; } float* oaz::nn::EvaluationBatch::GetValue(size_t index) { return m_values[index]; } boost::multi_array_ref<float, 1> oaz::nn::EvaluationBatch::GetPolicy( size_t index) { return *(m_policies[index]); } void oaz::nn::EvaluationBatch::Lock() { m_lock.Lock(); } void oaz::nn::EvaluationBatch::Unlock() { m_lock.Unlock(); } bool oaz::nn::EvaluationBatch::IsFull() const { return m_current_index >= GetSize(); } size_t oaz::nn::EvaluationBatch::GetNumberOfElements() const { return m_current_index; } oaz::thread_pool::Task* oaz::nn::EvaluationBatch::GetTask(size_t index) { return m_tasks[index]; } oaz::nn::NNEvaluator::NNEvaluator( std::shared_ptr<Model> model, std::shared_ptr<oaz::cache::Cache> cache, std::shared_ptr<oaz::thread_pool::ThreadPool> thread_pool, const std::vector<int>& element_dimensions, size_t batch_size) : m_batch_size(batch_size), m_model(std::move(model)), m_cache(std::move(cache)), m_n_evaluation_requests(0), m_n_evaluations(0), m_thread_pool(std::move(thread_pool)), m_element_dimensions(element_dimensions) { StartMonitor(); } oaz::nn::NNEvaluator::~NNEvaluator() { m_exit_signal.set_value(); m_worker.join(); } void oaz::nn::NNEvaluator::Monitor(std::future<void> future_exit_signal) { while (future_exit_signal.wait_for(std::chrono::milliseconds( WAIT_BEFORE_FORCED_EVAL_MS)) == std::future_status::timeout) { ForceEvaluation(); } } void oaz::nn::NNEvaluator::StartMonitor() { std::future<void> future_exit_signal = m_exit_signal.get_future(); m_worker = std::thread(&oaz::nn::NNEvaluator::Monitor, this, std::move(future_exit_signal)); } void oaz::nn::NNEvaluator::AddNewBatch() { std::shared_ptr<oaz::nn::EvaluationBatch> batch = std::make_shared<oaz::nn::EvaluationBatch>(GetElementDimensions(), GetBatchSize()); m_batches.push_back(std::move(batch)); } const std::vector<int>& oaz::nn::NNEvaluator::GetElementDimensions() const { return m_element_dimensions; } size_t oaz::nn::NNEvaluator::GetBatchSize() const { return m_batch_size; } void oaz::nn::NNEvaluator::RequestEvaluation( oaz::games::Game* game, float* value, boost::multi_array_ref<float, 1> policy, oaz::thread_pool::Task* task) { if (m_cache && EvaluateFromCache(game, value, policy, task)) { return; } EvaluateFromNN(game, value, policy, task); } bool oaz::nn::NNEvaluator::EvaluateFromCache( oaz::games::Game* game, float* value, const boost::multi_array_ref<float, 1>& policy, oaz::thread_pool::Task* task) { bool success = m_cache->Evaluate(*game, value, policy); if (success) { m_thread_pool->enqueue(task); } return success; } void oaz::nn::NNEvaluator::EvaluateFromNN( oaz::games::Game* game, float* value, const boost::multi_array_ref<float, 1>& policy, oaz::thread_pool::Task* task) { m_batches.Lock(); if (!m_batches.empty()) { auto current_batch = m_batches.back(); current_batch->Lock(); size_t index = current_batch->AcquireIndex(); bool evaluate_batch = current_batch->IsFull(); if (evaluate_batch) { m_batches.pop_back(); } current_batch->Unlock(); m_batches.Unlock(); current_batch->InitialiseElement(index, game, value, policy, task); if (evaluate_batch) { while (!current_batch->IsAvailableForEvaluation()) { } EvaluateBatch(current_batch.get()); } } else { AddNewBatch(); m_batches.Unlock(); EvaluateFromNN(game, value, policy, task); } } void oaz::nn::NNEvaluator::EvaluateBatch(oaz::nn::EvaluationBatch* batch) { batch->GetStatistics().time_evaluation_start = oaz::utils::time_now_ns(); batch->GetStatistics().n_elements = batch->GetNumberOfElements(); std::vector<tensorflow::Tensor> outputs; m_n_evaluation_requests++; m_model->Run( {{m_model->GetInputNodeName(), batch->GetBatchTensor().Slice(0, batch->GetNumberOfElements())}}, {m_model->GetValueNodeName(), m_model->GetPolicyNodeName()}, {}, &outputs); m_n_evaluations++; auto values_map = outputs[0].template tensor<float, 2>(); auto policies_map = outputs[1].template tensor<float, 2>(); for (size_t i = 0; i != batch->GetNumberOfElements(); ++i) { std::memcpy(batch->GetValue(i), &values_map(i, 0), 1 * sizeof(float)); auto policy = batch->GetPolicy(i); std::memcpy(policy.origin(), &policies_map(i, 0), policy.num_elements() * sizeof(float)); } if (m_cache) { m_cache->BatchInsert(batch->GetGames(), batch->GetValues(), batch->GetPolicies(), batch->GetNumberOfElements()); } for (size_t i = 0; i != batch->GetNumberOfElements(); ++i) { m_thread_pool->enqueue(batch->GetTask(i)); } batch->GetStatistics().time_evaluation_end = oaz::utils::time_now_ns(); ArchiveBatchStatistics(batch->GetStatistics()); } void oaz::nn::NNEvaluator::ArchiveBatchStatistics( const oaz::nn::EvaluationBatchStatistics& stats) { m_archive_lock.Lock(); m_archive.push_back(stats); m_archive_lock.Unlock(); } std::vector<oaz::nn::EvaluationBatchStatistics> oaz::nn::NNEvaluator::GetStatistics() { m_archive_lock.Lock(); std::vector<oaz::nn::EvaluationBatchStatistics> archive(m_archive); m_archive_lock.Unlock(); return archive; } void oaz::nn::NNEvaluator::ForceEvaluation() { m_batches.Lock(); if (!m_batches.empty()) { auto earliest_batch = m_batches.front(); earliest_batch->Lock(); if (earliest_batch->IsAvailableForEvaluation()) { m_batches.pop_front(); earliest_batch->Unlock(); m_batches.Unlock(); earliest_batch->GetStatistics().evaluation_forced = true; EvaluateBatch(earliest_batch.get()); } else { earliest_batch->Unlock(); m_batches.Unlock(); } } else { m_batches.Unlock(); } }
30.672297
79
0.677498
ameroueh
f635d45278e501fdec73c98f216e76c01eda55b0
564
cc
C++
code/foundation/math/xnamath/xna_plane.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
67
2015-03-30T19:56:16.000Z
2022-03-11T13:52:17.000Z
code/foundation/math/xnamath/xna_plane.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
5
2015-04-15T17:17:33.000Z
2016-02-11T00:40:17.000Z
code/foundation/math/xnamath/xna_plane.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
34
2015-03-30T15:08:00.000Z
2021-09-23T05:55:10.000Z
//------------------------------------------------------------------------------ // plane.cc // (C) 2007 Radon Labs GmbH // (C) 2013-2014 Individual contributors, see AUTHORS file //------------------------------------------------------------------------------ #include "stdneb.h" #include "math/plane.h" #include "math/matrix44.h" namespace Math { //------------------------------------------------------------------------------ /** */ plane plane::transform(__PlaneArg p, const matrix44& m) { return XMPlaneTransform(p.vec, m.mx); } } // namespace Math
25.636364
80
0.390071
gscept
f6360a9405234cc744e6a1e93bd3f75e5f6d1266
1,743
cc
C++
src/document_fragment.cc
knocknote/libhtml5
46e18a9122097b4d681c91f0747aa78a20611cab
[ "MIT" ]
7
2019-08-29T05:22:05.000Z
2020-07-07T15:35:50.000Z
src/document_fragment.cc
blastrain/libhtml5
46e18a9122097b4d681c91f0747aa78a20611cab
[ "MIT" ]
3
2019-07-12T09:43:31.000Z
2019-09-10T03:36:45.000Z
src/document_fragment.cc
blastrain/libhtml5
46e18a9122097b4d681c91f0747aa78a20611cab
[ "MIT" ]
3
2019-10-25T05:35:30.000Z
2020-07-21T21:40:52.000Z
#include "element.h" #include "node_list.h" #include "html_collection.h" #include "document_fragment.h" USING_NAMESPACE_HTML5; DocumentFragment::DocumentFragment(emscripten::val v) : Node(v) { } DocumentFragment::~DocumentFragment() { } DocumentFragment *DocumentFragment::create(emscripten::val v) { auto frag = new DocumentFragment(v); frag->autorelease(); return frag; } void DocumentFragment::append(std::vector<Node *> nodes) { for (Node *node : nodes) { HTML5_CALL(this->v, append, node->v); } } Element *DocumentFragment::getElementById(std::string elementId) { return Element::create(HTML5_CALLv(this->v, getElementById, elementId)); } void DocumentFragment::prepend(std::vector<Node *> nodes) { for (Node *node : nodes) { HTML5_CALL(this->v, prepend, node->v); } } Element *DocumentFragment::query(std::string relativeSelectors) { return Element::create(HTML5_CALLv(this->v, query, relativeSelectors)); } std::vector<Element *> DocumentFragment::queryAll(std::string relativeSelectors) { return toObjectArray<Element>(HTML5_CALLv(this->v, queryAll, relativeSelectors)); } Element *DocumentFragment::querySelector(std::string selectors) { return Element::create(HTML5_CALLv(this->v, querySelector, selectors)); } NodeList *DocumentFragment::querySelectorAll(std::string selectors) { return NodeList::create(HTML5_CALLv(this->v, querySelectorAll, selectors)); } HTML5_PROPERTY_IMPL(DocumentFragment, unsigned long, childElementCount); HTML5_PROPERTY_OBJECT_IMPL(DocumentFragment, HTMLCollection, children); HTML5_PROPERTY_OBJECT_IMPL(DocumentFragment, Element, firstElementChild); HTML5_PROPERTY_OBJECT_IMPL(DocumentFragment, Element, lastElementChild);
25.26087
85
0.751004
knocknote
f63653480e4f570d7a3274c77308b46d5f20756a
66
cpp
C++
Src/AppsDev/Logger/logger.cpp
zc110747/embed_manage_system
f7ec87277405ac380d5d5cb3e20240afcd505740
[ "MIT" ]
null
null
null
Src/AppsDev/Logger/logger.cpp
zc110747/embed_manage_system
f7ec87277405ac380d5d5cb3e20240afcd505740
[ "MIT" ]
null
null
null
Src/AppsDev/Logger/logger.cpp
zc110747/embed_manage_system
f7ec87277405ac380d5d5cb3e20240afcd505740
[ "MIT" ]
null
null
null
/* * logger.cpp * * Created on: 2021 Dec 11 15:08:05 */
11
37
0.5
zc110747
f636a43d1f6a3a83f344ac571b6f2310aa1df6b2
1,336
cpp
C++
test/containers/sequences/list/list.cons/size_type.pass.cpp
caiohamamura/libcxx
27c836ff3a9c505deb9fd1616012924de8ff9279
[ "MIT" ]
187
2015-02-28T11:50:45.000Z
2022-02-20T12:51:00.000Z
test/containers/sequences/list/list.cons/size_type.pass.cpp
caiohamamura/libcxx
27c836ff3a9c505deb9fd1616012924de8ff9279
[ "MIT" ]
2
2019-06-24T20:44:59.000Z
2020-06-17T18:41:35.000Z
test/containers/sequences/list/list.cons/size_type.pass.cpp
caiohamamura/libcxx
27c836ff3a9c505deb9fd1616012924de8ff9279
[ "MIT" ]
80
2015-01-02T12:44:41.000Z
2022-01-20T15:37:54.000Z
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <list> // explicit list(size_type n); #include <list> #include <cassert> #include "../../../DefaultOnly.h" #include "../../../stack_allocator.h" int main() { { std::list<int> l(3); assert(l.size() == 3); assert(std::distance(l.begin(), l.end()) == 3); std::list<int>::const_iterator i = l.begin(); assert(*i == 0); ++i; assert(*i == 0); ++i; assert(*i == 0); } { std::list<int, stack_allocator<int, 3> > l(3); assert(l.size() == 3); assert(std::distance(l.begin(), l.end()) == 3); std::list<int>::const_iterator i = l.begin(); assert(*i == 0); ++i; assert(*i == 0); ++i; assert(*i == 0); } #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES { std::list<DefaultOnly> l(3); assert(l.size() == 3); assert(std::distance(l.begin(), l.end()) == 3); } #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES }
26.196078
80
0.44985
caiohamamura
f639c0e1f43704acdb6e3a958d76153e65bb75f1
9,350
cpp
C++
src/clientcommands.cpp
burnedram/csgo-plugin-color-say
64adc99eefa5edfd44c0716e3b0c0d5983a99ee8
[ "MIT" ]
5
2017-10-17T03:26:24.000Z
2021-07-08T23:24:05.000Z
src/clientcommands.cpp
burnedram/csgo-plugin-color-say
64adc99eefa5edfd44c0716e3b0c0d5983a99ee8
[ "MIT" ]
1
2016-10-29T12:59:12.000Z
2017-04-23T18:45:07.000Z
src/clientcommands.cpp
burnedram/csgo-plugin-color-say
64adc99eefa5edfd44c0716e3b0c0d5983a99ee8
[ "MIT" ]
5
2016-09-15T10:11:55.000Z
2022-02-15T16:58:25.000Z
#include "clientcommands.h" #include "globals.h" #include "constants.h" #include "chatcolor.h" #include "chat.h" #include "console.h" #include <unordered_map> #include <sstream> #include <algorithm> using namespace std; namespace colorsay { namespace clientcommands { static unordered_map<string, ColorCommand *> _commands; bool exists(const string &name) { string lowername = name; std::transform(lowername.begin(), lowername.end(), lowername.begin(), ::tolower); return _commands.count(lowername); } PLUGIN_RESULT invoke(edict_t *pEdict, const string &name, const string &args, const vector<string> &argv) { string lowername(name); std::transform(lowername.begin(), lowername.end(), lowername.begin(), ::tolower); return _commands.at(lowername)->invoke(pEdict, args, argv); } } class HelpCommand : public ColorCommand { public: virtual const string get_name() const { return "help"; } virtual const string get_description() const { return "Prints a list of available commands, or more specific help on a command"; } virtual const string get_usage() const { return "help <command>"; } virtual const string get_help() const { return "Prints a list of available commands, or more specific help on a command"; } virtual PLUGIN_RESULT invoke(edict_t *pEdict, const string &args, const vector<string> &argv) const { ostringstream ss; if (argv.size() == 2) { const string &name = argv[1]; if(!clientcommands::exists(name)) { ss << "Unknown command \"" << name << "\"\n"; console::println(pEdict, ss.str()); } else { const ColorCommand *cmd = clientcommands::_commands.at(name); ss << "Usage: " << cmd->get_usage() << "\n\n" << cmd->get_help() << "\n"; console::println(pEdict, ss.str()); } } else if (argv.size() == 1) { console::println(pEdict, "GitHub: github.com/burnedram/csgo-plugin-color-say\nAvailable commands:\n"); for (auto &pair : clientcommands::_commands) { auto &cc = pair.second; console::print(pEdict, cc->get_usage()); console::print(pEdict, "\n\t"); console::println(pEdict, cc->get_description()); } } else { ss << "Usage: " << get_usage() << "\n"; console::println(pEdict, ss.str().c_str()); } return PLUGIN_STOP; } }; class VersionCommand : public ColorCommand { public: virtual const string get_name() const { return "version"; } virtual const string get_description() const { return "Prints the version of this plugin"; } virtual const string get_usage() const { return "version"; } virtual const string get_help() const { return "Prints the version of this plugin"; } virtual PLUGIN_RESULT invoke(edict_t *pEdict, const string &args, const vector<string> &argv) const { console::println(pEdict, "Plugin version " PLUGIN_VERSION); ostringstream ss; ss << "[" << chatcolor::random() << PLUGIN_NAME << chatcolor::ID::WHITE << "] Plugin version " PLUGIN_VERSION; string str = ss.str(); chatcolor::parse_colors(str); chat::say(pEdict, str); return PLUGIN_STOP; } }; class AvailableColorsCommand : public ColorCommand { public: virtual const string get_name() const { return "list"; } virtual const string get_description() const { return "Lists all available colors"; } virtual const string get_usage() const { return "list"; } virtual const string get_help() const { return "Lists all available colors"; } virtual PLUGIN_RESULT invoke(edict_t *pEdict, const string &args, const vector<string> &argv) const { ostringstream ss; ostringstream ss2; string chat_text, console_text; chatcolor::RGB rgb; chatcolor::ID color; ss << "[" << chatcolor::random() << PLUGIN_NAME << "] Available colors"; chat_text = ss.str(); chatcolor::parse_colors(chat_text); chat::say(pEdict, chat_text); console::println(pEdict, "Available colors"); ss.str(""); for (color = chatcolor::min; color <= chatcolor::max; color++) { ss2 << "(" << (int)color << ") {#" << (int)color << "}" << chatcolor::name(color); if(color < chatcolor::max) ss2 << "{#1}, "; ss << ss2.str(); if(color == chatcolor::max) ss2 << ", "; rgb = chatcolor::rgb(color); ss2 << "r" << (int)rgb.r; ss2 << " g" << (int)rgb.g; ss2 << " b" << (int)rgb.b; console_text = ss2.str(); chatcolor::strip_colors(console_text); console::println(pEdict, console_text); ss2.str(""); if ((color - chatcolor::min) % 2 == 1 || color == chatcolor::max) { chat_text = ss.str(); chatcolor::parse_colors(chat_text); chat::say(pEdict, chat_text); ss.str(""); } } return PLUGIN_STOP; } }; class EchoCommand : public ColorCommand { public: virtual const string get_name() const { return "echo"; } virtual const string get_description() const { return "Prints colored text for you (and only you)"; } virtual const string get_usage() const { return "echo <message>"; } virtual const string get_help() const { return "Prints <message> in your chat window. Color tags are enabled.\nFor more info see \"list\""; } virtual PLUGIN_RESULT invoke(edict_t *pEdict, const string &args, const vector<string> &argv) const { if(argv.size() < 2) { console::println(pEdict, "Missing arg"); return PLUGIN_STOP; } string parsed(args); if (!chatcolor::parse_colors(parsed)) console::println(pEdict, "Message contains bad tags"); chat::say(pEdict, parsed); return PLUGIN_STOP; } }; class SayCommand : public ColorCommand { public: virtual const string get_name() const { return "say"; } virtual const string get_description() const { return "Chat in color"; } virtual const string get_usage() const { return "say <message>"; } virtual const string get_help() const { return "Sends <message> to everyone in the server. Color tags are enabled.\nFor more info see \"list\""; } virtual PLUGIN_RESULT invoke(edict_t *pEdict, const string &args, const vector<string> &argv) const { if(argv.size() < 2) { console::println(pEdict, "Missing arg"); return PLUGIN_STOP; } string parsed(args); if (!chatcolor::parse_colors(parsed)) console::println(pEdict, "Message contains bad tags"); chat::say_all(parsed); return PLUGIN_STOP; } }; class SayTeamCommand : public ColorCommand { virtual const string get_name() const { return "say_team"; } virtual const string get_description() const { return "Teamchat in color"; } virtual const string get_usage() const { return "say_team <message>"; } virtual const string get_help() const { return "Sends <message> to everyone on your team. Color tags are enabled.\nFor more info see \"list\""; } virtual PLUGIN_RESULT invoke(edict_t *pEdict, const string &args, const vector<string> &argv) const { if(argv.size() < 2) { console::println(pEdict, "Missing arg"); return PLUGIN_STOP; } string parsed(args); if (!chatcolor::parse_colors(parsed)) console::println(pEdict, "Message contains bad tags"); chat::say_team(pEdict, parsed); return PLUGIN_STOP; } }; namespace clientcommands { void register_commands() { for (auto cc : initializer_list<ColorCommand *>({ new HelpCommand(), new VersionCommand(), new AvailableColorsCommand(), new EchoCommand(), new SayCommand(), new SayTeamCommand()})) _commands[cc->get_name()] = cc; } } }
34.249084
122
0.529198
burnedram
f63e7a16af6aac1e453b3f06341326570eee555b
400
cpp
C++
Source/NetPhysSync/Private/NPSPrediction/FBufferInfo.cpp
i3oi3o/NetPhysSync
267d1858d2f960933a699e725c14d8a4b4713f96
[ "BSD-3-Clause" ]
1
2018-09-22T20:35:49.000Z
2018-09-22T20:35:49.000Z
Source/NetPhysSync/Private/NPSPrediction/FBufferInfo.cpp
i3oi3o/NetPhysSync
267d1858d2f960933a699e725c14d8a4b4713f96
[ "BSD-3-Clause" ]
null
null
null
Source/NetPhysSync/Private/NPSPrediction/FBufferInfo.cpp
i3oi3o/NetPhysSync
267d1858d2f960933a699e725c14d8a4b4713f96
[ "BSD-3-Clause" ]
1
2019-04-17T05:37:51.000Z
2019-04-17T05:37:51.000Z
// This is licensed under the BSD License 2.0 found in the LICENSE file in project's root directory. #include "FBufferInfo.h" FBufferInfo::FBufferInfo(uint32 BufferStartTickIndexParam, int32 BufferNumParam) : BufferStartTickIndex(BufferStartTickIndexParam) , BufferNum(BufferNumParam) , BufferLastTickIndex(BufferStartTickIndexParam + BufferNumParam - 1) { } FBufferInfo::~FBufferInfo() { }
22.222222
100
0.795
i3oi3o
f641c1cbefc7cb47cc8fb566c0540e14efaffc07
6,495
hh
C++
src/cxx/include/data/FileReader.hh
sbooeshaghi/bcl2fastq
3f39a24cd743fa71fba9b7dcf62e5d33cea8272d
[ "BSD-3-Clause" ]
5
2021-06-07T12:36:11.000Z
2022-02-08T09:49:02.000Z
src/cxx/include/data/FileReader.hh
sbooeshaghi/bcl2fastq
3f39a24cd743fa71fba9b7dcf62e5d33cea8272d
[ "BSD-3-Clause" ]
1
2022-03-01T23:55:57.000Z
2022-03-01T23:57:15.000Z
src/cxx/include/data/FileReader.hh
sbooeshaghi/bcl2fastq
3f39a24cd743fa71fba9b7dcf62e5d33cea8272d
[ "BSD-3-Clause" ]
null
null
null
/** * BCL to FASTQ file converter * Copyright (c) 2007-2017 Illumina, Inc. * * This software is covered by the accompanying EULA * and certain third party copyright/licenses, and any user of this * source file is bound by the terms therein. * * \file FileReader.hh * * \brief Declaration of FileReader file. * * \author Aaron Day */ #ifndef BCL2FASTQ_DATA_FILEREADER_HH #define BCL2FASTQ_DATA_FILEREADER_HH #include "common/Types.hh" #include "common/Exceptions.hh" #include "io/SyncFile.hh" #include <boost/noncopyable.hpp> #include <boost/filesystem/path.hpp> #include <boost/format.hpp> #include <boost/iostreams/stream.hpp> #include <boost/iostreams/device/array.hpp> namespace bcl2fastq { namespace data { /// \brief Base class for all file readers class FileReaderBase { public: /// \brief Constructor /// \param data Raw data from file. /// \param ignoreErrors /// \param defaultClustersCount Default number of clusters FileReaderBase(const common::RawDataBuffer& data, bool ignoreErrors, common::ClustersCount defaultClustersCount = 0); /// \brief Destructor virtual ~FileReaderBase() = 0; /// \brief Get file path. /// \return File path. /// \pre <tt>this->isOpen() == true</tt> virtual const boost::filesystem::path& getPath() const; /// \brief Get number of clusters. /// \return Number of clusters in the file. /// \pre <tt>this->isOpen() == true</tt> virtual common::ClustersCount getClustersCount() const; /// \brief Check whether the file is open. /// \retval true File is open. /// \retval false File is not open. virtual bool isOpen() const { return !data_->path_.empty(); } protected: /// \brief Validate the condition is true. /// \param warningMsg The warning message to use if condition is false /// \retval condition bool validateCondition(bool condition, const std::string& warningMsg) const; /// \brief Raw data const common::RawDataBuffer* data_; /// \brief Ignore errors opening file and/or reading its header. bool ignoreErrors_; /// \brief Number of clusters. common::ClustersCount clustersCount_; boost::iostreams::basic_array_source<char> inputSrc_; boost::iostreams::stream<boost::iostreams::basic_array_source<char>> istr_; }; /// \brief File reading class. Virtual inheritance because of diamond inheritance. class FileReader : public virtual FileReaderBase, private boost::noncopyable { public: /// \brief Constructor. Resource acquisition is initialization. /// \param data Raw data from file. /// \param ignoreErrors Supress errors opening file and/or reading its header. /// \param defaultClustersCount Number of clusters to assume in case of error opening the file /// and/or reading its header. FileReader(const common::RawDataBuffer& data, bool ignoreErrors, common::ClustersCount defaultClustersCount = 0); /// \brief Destructor virtual ~FileReader() = 0; protected: /// \brief Return the file type string. Used for logging message purposes. virtual std::string getFileTypeStr() const = 0; /// \brief Log an error message on file io failure. /// \param bytesRead Number of bytes read from file. /// \param bytesExpected Number of bytes expected to be read from file. virtual void logError(std::streamsize bytesRead, std::streamsize bytesExpected) const; std::streamsize readBytes(char* buffer, uint32_t bytes); }; /// \brief Binary File Reader. Base class for reading binary files. class BinaryFileReader : public FileReader { public: /// \brief Constructor. Resource acquisition is initialization. /// \param data Raw data from file. /// \param ignoreErrors Supress errors opening file and/or reading its header. /// \param defaultClustersCount Number of clusters to assume in case of error opening the file /// and/or reading its header. BinaryFileReader(const common::RawDataBuffer& data, bool ignoreErrors, common::ClustersCount defaultClustersCount =0); /// \brief Destructor virtual ~BinaryFileReader() = 0; protected: /// \brief Read bytes from file to buffer. /// \param targetBuffer Target buffer to read to. /// \param targetSize Maximum number of bytes to be read. /// \return Number of bytes read. virtual std::streamsize read(char* targetBuffer, std::streamsize targetSize); /// \brief Read the header. Template allows derived classes to implement their own header /// class without inheritance, which would increase the size of an instance. /// \param header Header to read. template<typename HEADER> bool readHeader(HEADER& header); /// \brief Read the header. The template readHeader method only loads the data from file /// into the HEADER instance. This method is implemented by derived classes to validate /// and do something with the data. virtual bool readHeader() { return true; } }; /// \brief Binary file class that reads all clusters from the file on initialization. class BinaryAllClustersFileReader : public BinaryFileReader { public: /// \brief Constructor /// \param data Raw data from file /// \param ignoreErrors Supress errors opening file and/or reading its header. BinaryAllClustersFileReader(const common::RawDataBuffer& data, bool ignoreErrors); protected: /// \brief Read the clusters from file /// \param buffer Buffer to read data into /// \param clustersCount Number of clusters to read (size of buffer) /// \retval true on success, false on failure. virtual bool readClusters(std::vector<char>& buffer, common::ClustersCount clustersCount); /// \brief Validate the header. Throw an exception on failure. virtual void validateHeader(); /// \brief Return the number of bytes in a record. virtual std::size_t getRecordBytes() const = 0; /// \brief Read all records in the file. virtual void readRecords() { } }; } // namespace data } // namespace bcl2fastq #include "data/FileReader.hpp" #endif // BCL2FASTQ_DATA_FILEREADER_HH
33.828125
98
0.668668
sbooeshaghi
f6432f00dd84fdc63c993624b4fb8ae89272e701
3,274
hpp
C++
Firmware/Drivers/STM32/stm32_timer.hpp
deafloo/ODrive
bae459bb71b39c0169f4b8a322b7371eada58112
[ "MIT" ]
1,068
2016-05-31T22:39:08.000Z
2020-12-20T22:13:01.000Z
Firmware/Drivers/STM32/stm32_timer.hpp
deafloo/ODrive
bae459bb71b39c0169f4b8a322b7371eada58112
[ "MIT" ]
389
2017-10-16T09:44:20.000Z
2020-12-21T14:19:38.000Z
Firmware/Drivers/STM32/stm32_timer.hpp
deafloo/ODrive
bae459bb71b39c0169f4b8a322b7371eada58112
[ "MIT" ]
681
2016-06-12T01:41:00.000Z
2020-12-21T12:49:32.000Z
#ifndef __STM32_TIMER_HPP #define __STM32_TIMER_HPP #include "stm32_system.h" #include <tim.h> #include <array> class Stm32Timer { public: /** * @brief Starts multiple timers deterministically and synchronously from the * specified offset. * * All timers are atomically (*) put into the following state (regardless of * their previous state/configuration): * - TIMx_CNT will be initialized according to the corresponding counter[i] parameter. * - If the timer is in center-aligned mode, it will be set to up-counting direction. * - The update repetition counter is reset to TIMx_RCR (if applicable). * - The prescaler counter is reset. * - Update interrupts are disabled. * - The counter put into running state. * * This function is implemented by generating an update event on all selected timers. * That means as a side effect all things that are connected to the update event * except the interrupt routine itself (i.e. ADCs, DMAs, slave timers, etc) will * be triggered. * * Also you probably want to disable any connected PWM outputs to prevent glitches. * * (*) Best-effort atomically. There will be skew of a handful of clock cycles * but it's always the same given the compiler version and configuration. */ template<size_t I> static void start_synchronously(std::array<TIM_HandleTypeDef*, I> timers, std::array<size_t, I> counters) { start_synchronously_impl(timers, counters, std::make_index_sequence<I>()); } private: #pragma GCC push_options #pragma GCC optimize (3) template<size_t I, size_t ... Is> static void start_synchronously_impl(std::array<TIM_HandleTypeDef*, I> timers, std::array<size_t, I> counters, std::index_sequence<Is...>) { for (size_t i = 0; i < I; ++i) { TIM_HandleTypeDef* htim = timers[i]; // Stop the timer so we can start all of them later more atomically. htim->Instance->CR1 &= ~TIM_CR1_CEN; // Generate update event to force all of the timer's registers into // a known state. __HAL_TIM_DISABLE_IT(htim, TIM_IT_UPDATE); htim->Instance->EGR |= TIM_EGR_UG; __HAL_TIM_CLEAR_IT(htim, TIM_IT_UPDATE); // Load counter with the desired value. htim->Instance->CNT = counters[i]; } register volatile uint32_t* cr_addr[I]; register uint32_t cr_val[I]; for (size_t i = 0; i < I; ++i) { cr_addr[i] = &timers[i]->Instance->CR1; cr_val[i] = timers[i]->Instance->CR1 | TIM_CR1_CEN; } // Restart all timers as atomically as possible. // By inspection we find that this is compiled to the following code: // f7ff faa0 bl 800bdd0 <cpu_enter_critical()> // f8c9 6000 str.w r6, [r9] // f8c8 5000 str.w r5, [r8] // 603c str r4, [r7, #0] // f7ff fa9d bl 800bdd8 <cpu_exit_critical(unsigned long)> uint32_t mask = cpu_enter_critical(); int dummy[I] = {(*cr_addr[Is] = cr_val[Is], 0)...}; (void)dummy; cpu_exit_critical(mask); } #pragma GCC pop_options }; #endif // __STM32_TIMER_HPP
39.445783
144
0.635919
deafloo
f64495f89a4b93117e666c31a395d42bcfa79438
490
hpp
C++
addons/#disabled/TBMod_liveMonitor/configs/CfgFunctions.hpp
Braincrushy/TBMod
785f11cd9cd0defb0d01a6d2861beb6c207eb8a3
[ "MIT" ]
null
null
null
addons/#disabled/TBMod_liveMonitor/configs/CfgFunctions.hpp
Braincrushy/TBMod
785f11cd9cd0defb0d01a6d2861beb6c207eb8a3
[ "MIT" ]
4
2018-12-21T06:57:25.000Z
2020-07-09T09:06:38.000Z
addons/#disabled/TBMod_liveMonitor/configs/CfgFunctions.hpp
Braincrushy/TBMod
785f11cd9cd0defb0d01a6d2861beb6c207eb8a3
[ "MIT" ]
null
null
null
/* Part of the TBMod ( https://github.com/TacticalBaconDevs/TBMod ) Developed by http://tacticalbacon.de Author: Chris 'Taranis' */ class CfgFunctions { class TBMod_liveMonitor { tag = "TB_liveMonitor"; class functions { file = "\TBMod_liveMonitor\functions"; class animated {}; class canShow {}; class initialize {}; class loop {}; class remove {}; }; }; };
19.6
68
0.526531
Braincrushy
f646c7099880bfe83fc9cae96c511f414d38634a
15,397
hpp
C++
p1788/flavor/infsup/setbased/mpfr_bin_ieee754_flavor_class_impl.hpp
nehmeier/libieeep1788
1f10b896ff532e95818856614ab3073189e81199
[ "Apache-2.0" ]
41
2015-01-23T07:52:27.000Z
2022-02-28T03:15:21.000Z
p1788/flavor/infsup/setbased/mpfr_bin_ieee754_flavor_class_impl.hpp
nehmeier/libieeep1788
1f10b896ff532e95818856614ab3073189e81199
[ "Apache-2.0" ]
25
2015-01-25T16:13:35.000Z
2022-02-14T12:05:08.000Z
p1788/flavor/infsup/setbased/mpfr_bin_ieee754_flavor_class_impl.hpp
nehmeier/libieeep1788
1f10b896ff532e95818856614ab3073189e81199
[ "Apache-2.0" ]
8
2015-02-22T11:06:19.000Z
2021-05-23T09:57:32.000Z
// // libieeep1788 // // An implementation of the preliminary IEEE P1788 standard for // interval arithmetic // // // Copyright 2013 - 2015 // // Marco Nehmeier (nehmeier@informatik.uni-wuerzburg.de) // Department of Computer Science, // University of Wuerzburg, Germany // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef LIBIEEEP1788_P1788_FLAVOR_INFSUP_SETBASED_MPFR_BIN_IEEE754_FLAVOR_CLASS_IMPL_HPP #define LIBIEEEP1788_P1788_FLAVOR_INFSUP_SETBASED_MPFR_BIN_IEEE754_FLAVOR_CLASS_IMPL_HPP namespace p1788 { namespace flavor { namespace infsup { namespace setbased { // ----------------------------------------------------------------------------- // Interval constants // ----------------------------------------------------------------------------- // empty bare interval template<typename T> typename mpfr_bin_ieee754_flavor<T>::representation mpfr_bin_ieee754_flavor<T>::empty() { return representation(std::numeric_limits<T>::quiet_NaN(), std::numeric_limits<T>::quiet_NaN()); } // empty decorated interval template<typename T> typename mpfr_bin_ieee754_flavor<T>::representation_dec mpfr_bin_ieee754_flavor<T>::empty_dec() { return representation_dec(representation(std::numeric_limits<T>::quiet_NaN(), std::numeric_limits<T>::quiet_NaN()), p1788::decoration::decoration::trv); } // entire bare interval template<typename T> typename mpfr_bin_ieee754_flavor<T>::representation mpfr_bin_ieee754_flavor<T>::entire() { return representation(-std::numeric_limits<T>::infinity(), std::numeric_limits<T>::infinity()); } // entire decorated interval template<typename T> typename mpfr_bin_ieee754_flavor<T>::representation_dec mpfr_bin_ieee754_flavor<T>::entire_dec() { return representation_dec(representation(-std::numeric_limits<T>::infinity(), std::numeric_limits<T>::infinity()), p1788::decoration::decoration::dac); } // nai decorated interval template<typename T> typename mpfr_bin_ieee754_flavor<T>::representation_dec mpfr_bin_ieee754_flavor<T>::nai() { return representation_dec(representation(std::numeric_limits<T>::quiet_NaN(), std::numeric_limits<T>::quiet_NaN()), p1788::decoration::decoration::ill); } // ----------------------------------------------------------------------------- // Constructors // ----------------------------------------------------------------------------- // bare inf-sup interval template<typename T> typename mpfr_bin_ieee754_flavor<T>::representation mpfr_bin_ieee754_flavor<T>::nums_to_interval(T lower, T upper) { // Comparison with NaN is always false! if (lower <= upper && lower != std::numeric_limits<T>::infinity() && upper != -std::numeric_limits<T>::infinity()) { return representation(lower, upper); } else { p1788::exception::signal_undefined_operation(); return empty(); } } // decorated inf-sup interval template<typename T> typename mpfr_bin_ieee754_flavor<T>::representation_dec mpfr_bin_ieee754_flavor<T>::nums_to_decorated_interval(T lower, T upper) { // Comparison with NaN is always false! if (lower <= upper && lower != std::numeric_limits<T>::infinity() && upper != -std::numeric_limits<T>::infinity()) { return new_dec(representation(lower,upper)); } else { p1788::exception::signal_undefined_operation(); return nai(); } } // bare inf-sup interval mixed type template<typename T> template<typename L_, typename U_> typename mpfr_bin_ieee754_flavor<T>::representation mpfr_bin_ieee754_flavor<T>::nums_to_interval(L_ lower, U_ upper) { static_assert(std::numeric_limits<L_>::is_iec559, "Only IEEE 754 binary compliant types are supported!"); static_assert(std::numeric_limits<U_>::is_iec559, "Only IEEE 754 binary compliant types are supported!"); // Comparison with NaN is always false! if (lower <= upper && lower != std::numeric_limits<L_>::infinity() && upper != -std::numeric_limits<U_>::infinity()) { return representation(convert_rndd(lower), convert_rndu(upper)); } else { p1788::exception::signal_undefined_operation(); return empty(); } } // decorated inf-sup interval mixed type template<typename T> template<typename L_, typename U_> typename mpfr_bin_ieee754_flavor<T>::representation_dec mpfr_bin_ieee754_flavor<T>::nums_to_decorated_interval(L_ lower, U_ upper) { static_assert(std::numeric_limits<L_>::is_iec559, "Only IEEE 754 binary compliant types are supported!"); static_assert(std::numeric_limits<U_>::is_iec559, "Only IEEE 754 binary compliant types are supported!"); // Comparison with NaN is always false! if (lower <= upper && lower != std::numeric_limits<L_>::infinity() && upper != -std::numeric_limits<U_>::infinity()) { return new_dec(representation(convert_rndd(lower), convert_rndu(upper))); } else { p1788::exception::signal_undefined_operation(); return nai(); } } // decorated inf-sup-dec interval template<typename T> typename mpfr_bin_ieee754_flavor<T>::representation_dec mpfr_bin_ieee754_flavor<T>::nums_dec_to_decorated_interval(T lower, T upper, p1788::decoration::decoration dec) { if (p1788::decoration::is_valid(dec)) { // Comparison with NaN is always false! if (dec != p1788::decoration::decoration::ill && (lower <= upper && lower != std::numeric_limits<T>::infinity() && upper != -std::numeric_limits<T>::infinity() && (dec != p1788::decoration::decoration::com || (lower != -std::numeric_limits<T>::infinity() && upper != std::numeric_limits<T>::infinity())) ) ) { return representation_dec(representation(lower,upper), dec); } else { p1788::exception::signal_undefined_operation(); } } return nai(); } // decorated inf-sup-dec interval mixed type template<typename T> template<typename L_, typename U_> typename mpfr_bin_ieee754_flavor<T>::representation_dec mpfr_bin_ieee754_flavor<T>::nums_dec_to_decorated_interval(L_ lower, U_ upper, p1788::decoration::decoration dec) { static_assert(std::numeric_limits<L_>::is_iec559, "Only IEEE 754 binary compliant types are supported!"); static_assert(std::numeric_limits<U_>::is_iec559, "Only IEEE 754 binary compliant types are supported!"); if (p1788::decoration::is_valid(dec)) { // Comparison with NaN is always false! if (dec != p1788::decoration::decoration::ill && (lower <= upper && lower != std::numeric_limits<L_>::infinity() && upper != -std::numeric_limits<U_>::infinity() && (dec != p1788::decoration::decoration::com || (lower != -std::numeric_limits<L_>::infinity() && upper != std::numeric_limits<U_>::infinity())) ) ) { representation tmp(convert_rndd(lower), convert_rndu(upper)); return representation_dec(tmp, std::min(dec, std::isinf(tmp.first) || std::isinf(tmp.second) ? p1788::decoration::decoration::dac : p1788::decoration::decoration::com )); } else { p1788::exception::signal_undefined_operation(); } } return nai(); } // string literal bare interval template<typename T> typename mpfr_bin_ieee754_flavor<T>::representation mpfr_bin_ieee754_flavor<T>::text_to_interval(std::string const& str) { representation rep; std::istringstream s(str); operator_text_to_interval(s, rep); if (!s) { p1788::exception::signal_undefined_operation(); return empty(); } char c; while(s.get(c)) if (!std::isspace(c)) { p1788::exception::signal_undefined_operation(); return empty(); } return rep; } // string literal decorated interval template<typename T> typename mpfr_bin_ieee754_flavor<T>::representation_dec mpfr_bin_ieee754_flavor<T>::text_to_decorated_interval(std::string const& str) { representation_dec rep; std::istringstream s(str); operator_text_to_interval(s, rep); if (!s) { p1788::exception::signal_undefined_operation(); return nai(); } char c; while(s.get(c)) if (!std::isspace(c)) { p1788::exception::signal_undefined_operation(); return nai(); } return rep; } // copy constructor bare interval template<typename T> typename mpfr_bin_ieee754_flavor<T>::representation mpfr_bin_ieee754_flavor<T>::copy(representation const& other) { if (!is_valid(other)) { return empty(); } return other; } // copy constructor decorated interval template<typename T> typename mpfr_bin_ieee754_flavor<T>::representation_dec mpfr_bin_ieee754_flavor<T>::copy(representation_dec const& other) { if (!is_valid(other)) { return nai(); } return other; } // ----------------------------------------------------------------------------- // Convert // ----------------------------------------------------------------------------- // convert bare interval mixed type template<typename T> template<typename T_> typename mpfr_bin_ieee754_flavor<T>::representation mpfr_bin_ieee754_flavor<T>::convert_type(representation_type<T_> const& other) { static_assert(std::numeric_limits<T_>::is_iec559, "Only IEEE 754 binary compliant types are supported!"); if (!mpfr_bin_ieee754_flavor<T_>::is_valid(other)) { return empty(); } return convert_hull(other); } // convert decorated interval mixed type template<typename T> template<typename T_> typename mpfr_bin_ieee754_flavor<T>::representation_dec mpfr_bin_ieee754_flavor<T>::convert_type(representation_dec_type<T_> const& other) { static_assert(std::numeric_limits<T_>::is_iec559, "Only IEEE 754 binary compliant types are supported!"); if (!mpfr_bin_ieee754_flavor<T_>::is_valid(other)) { return nai(); } return convert_hull(other); } // convert decorated interval -> bare interval template<typename T> typename mpfr_bin_ieee754_flavor<T>::representation mpfr_bin_ieee754_flavor<T>::interval_part(representation_dec const& other) { if (!is_valid(other)) { return empty(); } else if (is_nai(other)) { p1788::exception::signal_interval_part_of_nai(); return empty(); } return other.first; } // convert decorated interval -> bare interval mixed type template<typename T> template<typename T_> typename mpfr_bin_ieee754_flavor<T>::representation mpfr_bin_ieee754_flavor<T>::interval_part(representation_dec_type<T_> const& other) { static_assert(std::numeric_limits<T_>::is_iec559, "Only IEEE 754 binary compliant types are supported!"); if (!mpfr_bin_ieee754_flavor<T_>::is_valid(other)) { return empty(); } else if (mpfr_bin_ieee754_flavor<T_>::is_nai(other)) { p1788::exception::signal_interval_part_of_nai(); return empty(); } return convert_hull(other.first); } // convert bare interval -> decorated interval template<typename T> typename mpfr_bin_ieee754_flavor<T>::representation_dec mpfr_bin_ieee754_flavor<T>::new_dec(representation const& other) { if (!is_valid(other)) { return nai(); } else if (is_empty(other)) { return representation_dec(other, p1788::decoration::decoration::trv); } else if (other.first == -std::numeric_limits<T>::infinity() || other.second == std::numeric_limits<T>::infinity()) { return representation_dec(other, p1788::decoration::decoration::dac); } else { return representation_dec(other, p1788::decoration::decoration::com); } } // convert bare interval -> decorated interval mixed type template<typename T> template<typename T_> typename mpfr_bin_ieee754_flavor<T>::representation_dec mpfr_bin_ieee754_flavor<T>::new_dec(representation_type<T_> const& other) { static_assert(std::numeric_limits<T_>::is_iec559, "Only IEEE 754 binary compliant types are supported!"); if (!mpfr_bin_ieee754_flavor<T_>::is_valid(other)) { return nai(); } representation r = convert_hull(other); if (is_empty(r)) { return representation_dec(r, p1788::decoration::decoration::trv); } else if (r.first == -std::numeric_limits<T>::infinity() || r.second == std::numeric_limits<T>::infinity()) { return representation_dec(r, p1788::decoration::decoration::dac); } else { return representation_dec(r, p1788::decoration::decoration::com); } } // set decoration constructor template<typename T> typename mpfr_bin_ieee754_flavor<T>::representation_dec mpfr_bin_ieee754_flavor<T>::set_dec(representation const& other, p1788::decoration::decoration dec) { if (!p1788::decoration::is_valid(dec) || !is_valid(other) || dec == p1788::decoration::decoration::ill) { return nai(); } if (is_empty(other)) { return empty_dec(); } if (dec == p1788::decoration::decoration::com && (other.first == -std::numeric_limits<T>::infinity() || other.second == +std::numeric_limits<T>::infinity())) { return representation_dec(other, p1788::decoration::decoration::dac); } return representation_dec(other, dec); } // set decoration constructor mixed type template<typename T> template<typename T_> typename mpfr_bin_ieee754_flavor<T>::representation_dec mpfr_bin_ieee754_flavor<T>::set_dec(representation_type<T_> const& other, p1788::decoration::decoration dec) { static_assert(std::numeric_limits<T_>::is_iec559, "Only IEEE 754 binary compliant types are supported!"); return convert_hull(mpfr_bin_ieee754_flavor<T_>::set_dec(other, dec)); } // get decoration template<typename T> p1788::decoration::decoration mpfr_bin_ieee754_flavor<T>::decoration_part(representation_dec const& other) { if (!is_valid(other)) { return p1788::decoration::decoration::ill; } return other.second; } } // namespace setbased } // namespace infsup } // namespace flavor } // namespace p1788 #endif // LIBIEEEP1788_P1788_FLAVOR_INFSUP_SETBASED_MPFR_BIN_IEEE754_FLAVOR_CLASS_IMPL_HPP
29.216319
123
0.644541
nehmeier
f646dce818a2567323190f6ea2bc22130e46745a
1,725
cc
C++
elements/standard/checkpaint.cc
MacWR/Click-changed-for-ParaGraph
18285e5da578fbb7285d10380836146e738dee6e
[ "Apache-2.0" ]
129
2015-10-08T14:38:35.000Z
2022-03-06T14:54:44.000Z
elements/standard/checkpaint.cc
MacWR/Click-changed-for-ParaGraph
18285e5da578fbb7285d10380836146e738dee6e
[ "Apache-2.0" ]
241
2016-02-17T16:17:58.000Z
2022-03-15T09:08:33.000Z
elements/standard/checkpaint.cc
MacWR/Click-changed-for-ParaGraph
18285e5da578fbb7285d10380836146e738dee6e
[ "Apache-2.0" ]
61
2015-12-17T01:46:58.000Z
2022-02-07T22:25:19.000Z
/* * checkpaint.{cc,hh} -- element checks paint annotation * Eddie Kohler, Robert Morris * * Copyright (c) 1999-2000 Massachusetts Institute of Technology * Copyright (c) 2008 Meraki, Inc. * * 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, subject to the conditions * listed in the Click LICENSE file. These conditions include: you must * preserve this copyright notice, and you cannot mention the copyright * holders in advertising related to the Software without their permission. * The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This * notice is a summary of the Click LICENSE file; the license in that file is * legally binding. */ #include <click/config.h> #include "checkpaint.hh" #include <click/args.hh> #include <click/error.hh> #include <click/packet_anno.hh> CLICK_DECLS CheckPaint::CheckPaint() { } int CheckPaint::configure(Vector<String> &conf, ErrorHandler *errh) { int anno = PAINT_ANNO_OFFSET; if (Args(conf, this, errh) .read_mp("COLOR", _color) .read_p("ANNO", AnnoArg(1), anno) .complete() < 0) return -1; _anno = anno; return 0; } void CheckPaint::push(int, Packet *p) { if (p->anno_u8(_anno) != _color) checked_output_push(1, p); else output(0).push(p); } Packet * CheckPaint::pull(int) { Packet *p = input(0).pull(); if (p && p->anno_u8(_anno) != _color) { checked_output_push(1, p); p = 0; } return p; } void CheckPaint::add_handlers() { add_data_handlers("color", Handler::OP_READ | Handler::OP_WRITE, &_color); } CLICK_ENDDECLS EXPORT_ELEMENT(CheckPaint)
24.295775
78
0.708986
MacWR
f648900f3836270aafc74e829eed9d3565b0677d
860
cpp
C++
Ch 05/5.14.cpp
Felon03/CppPrimer
7dc2daf59f0ae7ec5670def15cb5fab174fe9780
[ "Apache-2.0" ]
null
null
null
Ch 05/5.14.cpp
Felon03/CppPrimer
7dc2daf59f0ae7ec5670def15cb5fab174fe9780
[ "Apache-2.0" ]
null
null
null
Ch 05/5.14.cpp
Felon03/CppPrimer
7dc2daf59f0ae7ec5670def15cb5fab174fe9780
[ "Apache-2.0" ]
null
null
null
/*编写一段程序,从标准输入中读取若干string对象并查找连续重复出现的单词。*/ #include<iostream> #include<string> #include<vector> using namespace std; int main() { vector<string> st; string st1, prestr; unsigned int wordCnt = 1; bool flag = false; while (cin >> st1) { st.push_back(st1); } auto beg = st.begin(); while (beg != st.end()) { if (prestr == *beg) { ++wordCnt; prestr = *beg; ++beg; } else { if (wordCnt > 1) { cout << prestr << " occurs " << wordCnt << " times" << endl; wordCnt = 1; flag = true; } prestr = *beg; ++beg; } if (beg == st.end()) // 统计最后可能连续的单词 if (wordCnt > 1) { cout << prestr << " occurs " << wordCnt << " times" << endl; flag = true; //wordCnt = 1; // 重置计数器 } } /*判断是否有重复的单词 flag 为 true即有重复的单词*/ if (!flag) cout << "No word occurs more than 2 times." << endl; return 0; }
16.538462
64
0.552326
Felon03
f64a4a21f24b00080d2680d2251d39a4c4e14d67
598
cpp
C++
Classes/Log/AceLog.cpp
DahamChoi/cocos_mygui_debugSystem
f716d99b1babdc8dfe84535033505b936a84a055
[ "MIT" ]
null
null
null
Classes/Log/AceLog.cpp
DahamChoi/cocos_mygui_debugSystem
f716d99b1babdc8dfe84535033505b936a84a055
[ "MIT" ]
null
null
null
Classes/Log/AceLog.cpp
DahamChoi/cocos_mygui_debugSystem
f716d99b1babdc8dfe84535033505b936a84a055
[ "MIT" ]
null
null
null
#include "AceLog.h" #include "LogData.h" #include <ctime> USING_NS_ACE; void AceLog::log(const std::string& msg, Type type) { AceLogPtr pAceLog = std::make_shared<AceLog>(); pAceLog->msg = msg; pAceLog->type = type; time_t curTime = std::time(NULL); tm* pLocal = std::localtime(&curTime); pAceLog->time = (long long)curTime; char str[100]; sprintf(str, "%02d-%02d %02d:%02d:%02d", pLocal->tm_mon + 1, pLocal->tm_mday, pLocal->tm_hour, pLocal->tm_min, pLocal->tm_sec); pAceLog->strTime = str; LogData::getInstance()->addLog(pAceLog); }
23.92
131
0.632107
DahamChoi
f64da81defb3c247ef8d238ae61e13665484af93
1,607
cc
C++
FTPD_cmd.cc
shuLhan/libvos
831491b197fa8f267fd94966d406596896e6f25c
[ "BSD-3-Clause" ]
1
2017-09-14T13:31:16.000Z
2017-09-14T13:31:16.000Z
FTPD_cmd.cc
shuLhan/libvos
831491b197fa8f267fd94966d406596896e6f25c
[ "BSD-3-Clause" ]
null
null
null
FTPD_cmd.cc
shuLhan/libvos
831491b197fa8f267fd94966d406596896e6f25c
[ "BSD-3-Clause" ]
5
2015-04-11T02:59:06.000Z
2021-03-03T19:45:39.000Z
// // Copyright 2009-2016 M. Shulhan (ms@kilabit.info). All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // #include "FTPD_cmd.hh" namespace vos { const char* FTPD_cmd::__cname = "FTPD_cmd"; FTPD_cmd::FTPD_cmd() : _code(0) , _name() , _parm() , _callback(NULL) {} FTPD_cmd::~FTPD_cmd() { reset(); } /** * @method : FTPD_cmd::reset * @desc : reset all attribute. */ void FTPD_cmd::reset() { _code = 0; _name.reset(); _parm.reset(); _callback = 0; } /** * @method : FTPD_cmd::set * @param : * > cmd : pointer to FTPD_cmd object. * @desc : set content of this object using data from 'cmd' object. */ void FTPD_cmd::set(FTPD_cmd *cmd) { _code = cmd->_code; _name.copy(&cmd->_name); _parm.copy(&cmd->_parm); _callback = cmd->_callback; } /** * @method : FTPD_cmd::dump * @desc : Dump content of FTPD_cmd object. */ void FTPD_cmd::dump() { printf( "[vos::FTPD_cmd__] dump:\n" " command : %s\n" " parameter : %s\n", _name.chars(), _parm.chars()); } /** * @method : FTPD_cmd::INIT * @param : * > name : name of new command. * @return : pointer to function. * < !NULL : success, pointer to new FTPD_cmd object. * < NULL : fail. * @desc : Create and initialize a new FTPD_cmd object. */ FTPD_cmd* FTPD_cmd::INIT(const int code, const char* name , void (*callback)(const void*, const void*)) { FTPD_cmd* cmd = new FTPD_cmd(); if (cmd) { cmd->_code = code; cmd->_callback = callback; cmd->_name.copy_raw(name); } return cmd; } } /* namespace::vos */ // vi: ts=8 sw=8 tw=78:
18.686047
73
0.6285
shuLhan
f651e7c2b998d73d94d9609835fcc40c7299cf37
1,556
cpp
C++
6. Heaps/HeapSort.cpp
suraj0803/DSA
6ea21e452d7662e2351ee2a7b0415722e1bbf094
[ "MIT" ]
null
null
null
6. Heaps/HeapSort.cpp
suraj0803/DSA
6ea21e452d7662e2351ee2a7b0415722e1bbf094
[ "MIT" ]
null
null
null
6. Heaps/HeapSort.cpp
suraj0803/DSA
6ea21e452d7662e2351ee2a7b0415722e1bbf094
[ "MIT" ]
null
null
null
#include<iostream> #include<vector> using namespace std; void print(vector<int> v){ for(int x:v){ cout<<x<<" "; } cout<<endl; } bool minHeap = false; bool compare(int a, int b){ if(minHeap){ return a<b; } else{ return a>b; } } void heapify(vector<int> &v, int index, int size) { int left = 2*index; int right = 2*index+1; int min_index = index; int last = size-1; if(left <= last and compare(v[left],v[index])){ min_index = left; } if(right <= last and compare(v[right],v[index])){ min_index = right; } if(min_index!=index){ swap(v[index],v[min_index]); heapify(v,min_index,size); } } void buildHeap(vector<int> &v) { for(int i=(v.size()-1/2); i>=1; i--){// start from 1st non leaves and then heapify // root node is fixed heapify(v,i,v.size()); } } void heapsort(vector<int> &arr){ buildHeap(arr); int n = arr.size(); //remove n-1 elements from the top while(n>1){ swap(arr[1],arr[n-1]); // remove that element from the heap n--;// here we are just shrinking the size and we actually popping the element. heapify(arr,1,n); } } int main() { vector<int> v; v.push_back(-1); int n; cin>>n; int temp; for(int i=0; i<n; i++){ cin>>temp; v.push_back(temp); } heapsort(v); print(v); return 0; }
18.093023
88
0.503856
suraj0803
f654cefc5761d245701e3300ccf8a6ba5973615f
3,990
cpp
C++
Source/ArgsPasserModule/Private/Views/SLauncherWidget.cpp
lpestl/ArgsPasser
e7dc26ccfccd160ca8ed2eee10633a89d88c066a
[ "MIT" ]
null
null
null
Source/ArgsPasserModule/Private/Views/SLauncherWidget.cpp
lpestl/ArgsPasser
e7dc26ccfccd160ca8ed2eee10633a89d88c066a
[ "MIT" ]
null
null
null
Source/ArgsPasserModule/Private/Views/SLauncherWidget.cpp
lpestl/ArgsPasser
e7dc26ccfccd160ca8ed2eee10633a89d88c066a
[ "MIT" ]
null
null
null
#include "SLauncherWidget.h" #include "DesktopPlatform/Public/DesktopPlatformModule.h" #include "DesktopPlatform/Public/IDesktopPlatform.h" #include "Editor/MainFrame/Public/Interfaces/IMainFrameModule.h" #define LOCTEXT_NAMESPACE "LauncherWidget" void SLauncherWidget::Construct(const FArguments& InArgs) { ChildSlot [ SNew( SVerticalBox ) +SVerticalBox::Slot() .AutoHeight() .Padding( 5.f ) [ SNew( SHorizontalBox ) +SHorizontalBox::Slot() .AutoWidth() .VAlign( VAlign_Center ) .Padding(FMargin(0.f, 0.f, 3.f, 0.f) ) [ SNew( STextBlock ) .Text( NSLOCTEXT( "Launcher", "ExecutableText", "Executable:" ) ) ] +SHorizontalBox::Slot() .FillWidth( 1.f ) [ SNew( SEditableTextBox ) .HintText( NSLOCTEXT( "Launcher", "PleaseEnterPath", "Please enter the path to the file") ) .Text(this, &SLauncherWidget::GetExecutablePath) .OnTextCommitted(this, &SLauncherWidget::OnExecutablePathCommited) ] +SHorizontalBox::Slot() .AutoWidth() .Padding( FMargin( 0.f, -1.f ) ) [ SNew( SButton ) .Text( NSLOCTEXT( "Launcher", "Browse", "Browse...") ) .OnClicked(this, &SLauncherWidget::OnBrowseExecutableClicked) .ContentPadding(FCoreStyle::Get().GetMargin("StandardDialog.ContentPadding")) ] ] +SVerticalBox::Slot() .FillHeight( 1.f ) .Padding( 5.f ) +SVerticalBox::Slot() .AutoHeight() .Padding( 5.f ) .HAlign( HAlign_Right ) [ SNew( SHorizontalBox ) +SHorizontalBox::Slot() .Padding( FMargin( 3.f, 0.f, 0.f, 0.f ) ) [ SNew( SBox ) .WidthOverride( 100.f ) [ SNew( SButton ) .HAlign(HAlign_Center) .Text( NSLOCTEXT( "Launcher", "ExecuteText", "Execute" ) ) .IsEnabled(this, &SLauncherWidget::IsExecutablePathExist) ] ] ] ]; } bool SLauncherWidget::ShowOpenFileDialog( const FString& DefaultFolder, const FString& FileDescription, const FString& FileExtension, TArray<FString>& OutFileNames) { // Prompt the user for the filenames IDesktopPlatform* DesktopPlatform = FDesktopPlatformModule::Get(); const FString FileTypes = FString::Printf( TEXT("%s (%s)|%s"), *FileDescription, *FileExtension, *FileExtension ); bool bOpened = false; if ( DesktopPlatform ) { void* ParentWindowWindowHandle = nullptr; const TSharedPtr<SWindow>& MainFrameParentWindow = FSlateApplicationBase::Get().GetActiveTopLevelWindow(); if ( MainFrameParentWindow.IsValid() && MainFrameParentWindow->GetNativeWindow().IsValid() ) { ParentWindowWindowHandle = MainFrameParentWindow->GetNativeWindow()->GetOSWindowHandle(); } bOpened = DesktopPlatform->OpenFileDialog( ParentWindowWindowHandle, LOCTEXT("OpenProjectBrowseTitle", "Open Project").ToString(), DefaultFolder, TEXT(""), FileTypes, EFileDialogFlags::None, OutFileNames ); } return bOpened; } FReply SLauncherWidget::OnBrowseExecutableClicked() { const FString FileDescription = LOCTEXT( "FileTypeDescription", "All files" ).ToString(); const FString FileExtension = FString::Printf(TEXT("*.*")); const FString DefaultFolder = FString(); TArray< FString > FileNames; if (ShowOpenFileDialog(DefaultFolder, FileDescription, FileExtension, FileNames)) { if (FileNames.Num() > 0) { ExecutablePath = FPaths::ConvertRelativePathToFull(FileNames[0]); bIsExecutablePathExist = CheckPathExist(ExecutablePath); } } return FReply::Handled(); } FText SLauncherWidget::GetExecutablePath() const { return FText::FromString( ExecutablePath ); } void SLauncherWidget::OnExecutablePathCommited(const FText& InText, ETextCommit::Type Type) { ExecutablePath = InText.ToString(); bIsExecutablePathExist = CheckPathExist(ExecutablePath); } bool SLauncherWidget::IsExecutablePathExist() const { return bIsExecutablePathExist; } bool SLauncherWidget::CheckPathExist(const FString& InPath) { IPlatformFile& FileManager = FPlatformFileManager::Get().GetPlatformFile(); return FileManager.FileExists(*InPath); } #undef LOCTEXT_NAMESPACE
27.328767
115
0.717043
lpestl
2cf1c405f8068029edc7f14e62ebb7f99aab97b3
2,712
cpp
C++
pausedialog.cpp
williamwu88/Flying-Stickman
d11c05e87bde481200ed1f3aaf5a0f4e4982d9ae
[ "MIT" ]
null
null
null
pausedialog.cpp
williamwu88/Flying-Stickman
d11c05e87bde481200ed1f3aaf5a0f4e4982d9ae
[ "MIT" ]
null
null
null
pausedialog.cpp
williamwu88/Flying-Stickman
d11c05e87bde481200ed1f3aaf5a0f4e4982d9ae
[ "MIT" ]
null
null
null
#include "pausedialog.h" #include "ui_pausedialog.h" PauseDialog::PauseDialog(bool *paused, QWidget *parent) : QDialog(parent), ui(new Ui::PauseDialog), paused(paused) { ui->setupUi(this); //this->setStyleSheet("background-color: #FFFFFF;"); //White this->setFixedSize(this->width(), this->height()); setUpUI(); } PauseDialog::~PauseDialog() { delete ui; } //Sets up the pause screen with the values from the config screen void PauseDialog::setUpUI() { std::string stickman_size = Config::config()->getStickman()->getSize(); int stickman_x_position = Config::config()->getStickman()->getXPosition(); if (stickman_size == "tiny") { ui->tiny_radio->setChecked(true); } else if (stickman_size == "normal") { ui->normal_radio->setChecked(true); } else if (stickman_size == "large") { ui->large_radio->setChecked(true); } else if (stickman_size == "giant") { ui->giant_radio->setChecked(true); } ui->position_slider->setMaximum(Config::config()->getWorldWidth()); ui->position_slider->setValue(stickman_x_position); } void PauseDialog::on_buttonBox_clicked(QAbstractButton *button) { // See what radio button is pressed if ((QPushButton *)button == ui->buttonBox->button(QDialogButtonBox::Close)) { if (ui->tiny_radio->isChecked()) { ui->tiny_radio->setChecked(true); } else if (ui->normal_radio->isChecked()) { ui->normal_radio->setChecked(true); } else if (ui->large_radio->isChecked()) { ui->large_radio->setChecked(true); } else if (ui->giant_radio->isChecked()) { ui->giant_radio->setChecked(true); } *this->paused = false; } } //Real-time update of the x position of the stickman void PauseDialog::on_position_slider_actionTriggered(int /*action*/) { Config::config()->getStickman()->changeXPosition(ui->position_slider->value()); } //Following methods update in real-time the size of the stickman void PauseDialog::on_tiny_radio_clicked() { Config::config()->getStickman()->changeSize("tiny"); Config::config()->getStickman()->updateStickman(); } void PauseDialog::on_normal_radio_clicked() { Config::config()->getStickman()->changeSize("normal"); Config::config()->getStickman()->updateStickman(); } void PauseDialog::on_large_radio_clicked() { Config::config()->getStickman()->changeSize("large"); Config::config()->getStickman()->updateStickman(); } void PauseDialog::on_giant_radio_clicked() { Config::config()->getStickman()->changeSize("giant"); Config::config()->getStickman()->updateStickman(); }
27.673469
83
0.65118
williamwu88
2cf4381bb3482283e4c2c84af071694678e219a1
203
cpp
C++
Fellz/RaknetGlobals.cpp
digitalhoax/fellz
cacf5cd57f00121bcb2a795021aed24c4164c418
[ "Zlib", "libtiff", "BSD-2-Clause", "Apache-2.0", "MIT", "Libpng", "curl", "BSD-3-Clause" ]
1
2017-09-25T09:32:22.000Z
2017-09-25T09:32:22.000Z
Fellz/RaknetGlobals.cpp
digitalhoax/fellz
cacf5cd57f00121bcb2a795021aed24c4164c418
[ "Zlib", "libtiff", "BSD-2-Clause", "Apache-2.0", "MIT", "Libpng", "curl", "BSD-3-Clause" ]
null
null
null
Fellz/RaknetGlobals.cpp
digitalhoax/fellz
cacf5cd57f00121bcb2a795021aed24c4164c418
[ "Zlib", "libtiff", "BSD-2-Clause", "Apache-2.0", "MIT", "Libpng", "curl", "BSD-3-Clause" ]
null
null
null
#include "RaknetGlobals.h" // for documentation, see RaknetGlobals.h RakNet::RakPeerInterface* player2; RakNet::SystemAddress player2Adress; bool isServer; bool isConnected; bool otherGameOver;
22.555556
42
0.783251
digitalhoax
2cf898eb30b312384af57b0be63943dfc1e3cacc
45
hpp
C++
src/boost_mpl_aux__config_has_xxx.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_mpl_aux__config_has_xxx.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_mpl_aux__config_has_xxx.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/mpl/aux_/config/has_xxx.hpp>
22.5
44
0.777778
miathedev
2cf89ab55f7193b92900ab50122c466e126f0a5e
9,234
cpp
C++
src/Daggy/CConsoleDaggy.cpp
milovidov/dataagregator
1150f66fc2ef2bbcf62c0174ef147109185cad98
[ "MIT" ]
135
2019-06-23T20:32:33.000Z
2022-02-06T15:41:41.000Z
src/Daggy/CConsoleDaggy.cpp
milovidov/dataagregator
1150f66fc2ef2bbcf62c0174ef147109185cad98
[ "MIT" ]
2
2020-10-16T17:31:44.000Z
2022-01-02T22:02:04.000Z
src/Daggy/CConsoleDaggy.cpp
milovidov/dataagregator
1150f66fc2ef2bbcf62c0174ef147109185cad98
[ "MIT" ]
11
2019-12-26T14:36:44.000Z
2022-02-23T02:14:41.000Z
/* MIT License Copyright (c) 2020 Mikhail Milovidov 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 "Precompiled.hpp" #include "CConsoleDaggy.hpp" #include <DaggyCore/Core.hpp> #include <DaggyCore/aggregators/CConsole.hpp> #include <DaggyCore/aggregators/CFile.hpp> #include <DaggyCore/Types.hpp> #include <DaggyCore/Errors.hpp> using namespace daggy; CConsoleDaggy::CConsoleDaggy(QObject* parent) : QObject(parent) , daggy_core_(nullptr) , need_hard_stop_(false) { qApp->setApplicationName(DAGGY_NAME); qApp->setApplicationVersion(DAGGY_VERSION_FULL); qApp->setOrganizationName(DAGGY_VENDOR); qApp->setOrganizationDomain(DAGGY_HOMEPAGE_URL); connect(this, &CConsoleDaggy::interrupt, this, &CConsoleDaggy::stop, Qt::QueuedConnection); } std::error_code CConsoleDaggy::prepare() { if (daggy_core_) return errors::success; const auto settings = parse(); Sources sources; switch (settings.data_source_text_type) { case Json: sources = std::move(*sources::convertors::json(settings.data_source_text)); break; case Yaml: sources = std::move(*sources::convertors::yaml(settings.data_source_text)); break; } const QString& session = QDateTime::currentDateTime().toString("dd-MM-yy_hh-mm-ss-zzz") + "_" + settings.data_sources_name; daggy_core_ = new Core(session, std::move(sources), this); connect(daggy_core_, &Core::stateChanged, this, &CConsoleDaggy::onDaggyCoreStateChanged); auto file_aggregator = new aggregators::CFile(settings.output_folder); file_aggregator->moveToThread(&file_thread_); connect(this, &CConsoleDaggy::destroyed, file_aggregator, &aggregators::CFile::deleteLater); auto console_aggregator = new aggregators::CConsole(session, daggy_core_); daggy_core_->connectAggregator(file_aggregator); daggy_core_->connectAggregator(console_aggregator); return daggy_core_->prepare();; } std::error_code CConsoleDaggy::start() { file_thread_.start(); return daggy_core_->start(); } void CConsoleDaggy::stop() { if (need_hard_stop_) { qWarning() << "HARD STOP"; qApp->exit(); } else { daggy_core_->stop(); need_hard_stop_ = true; } file_thread_.quit(); file_thread_.wait(); } bool CConsoleDaggy::handleSystemSignal(const int signal) { if (signal & DEFAULT_SIGNALS) { emit interrupt(signal); return true; } return false; } const QVector<QString>& CConsoleDaggy::supportedConvertors() const { static thread_local QVector<QString> formats = { "json", #ifdef YAML_SUPPORT "yaml" #endif }; return formats; } DaggySourcesTextTypes CConsoleDaggy::textFormatType(const QString& file_name) const { DaggySourcesTextTypes result = Json; const QString& extension = QFileInfo(file_name).suffix(); if (extension == "yml" || extension == "yaml") result = Yaml; return result; } bool CConsoleDaggy::isError() const { return !error_message_.isEmpty(); } const QString& CConsoleDaggy::errorMessage() const { return error_message_; } CConsoleDaggy::Settings CConsoleDaggy::parse() const { Settings result; const QCommandLineOption output_folder_option({"o", "output"}, "Set output folder", "folder", ""); const QCommandLineOption input_format_option({"f", "format"}, "Source format", supportedConvertors().join("|"), supportedConvertors()[0]); const QCommandLineOption auto_complete_timeout({"t", "timeout"}, "Auto complete timeout", "time in ms", 0 ); const QCommandLineOption input_from_stdin_option({"i", "stdin"}, "Read data aggregation sources from stdin"); QCommandLineParser command_line_parser; command_line_parser.addOption(output_folder_option); command_line_parser.addOption(input_format_option); command_line_parser.addOption(input_from_stdin_option); command_line_parser.addOption(auto_complete_timeout); command_line_parser.addHelpOption(); command_line_parser.addVersionOption(); command_line_parser.addPositionalArgument("file", "data aggregation sources file", "*.yaml|*.yml|*.json"); command_line_parser.process(*qApp); const QStringList positional_arguments = command_line_parser.positionalArguments(); if (positional_arguments.isEmpty()) { command_line_parser.showHelp(-1); } const QString& source_file_name = positional_arguments.first(); if (command_line_parser.isSet(input_from_stdin_option)) { result.data_source_text = QTextStream(stdin).readAll(); result.data_sources_name = "stdin"; } else { result.data_source_text = getTextFromFile(source_file_name); result.data_sources_name = QFileInfo(source_file_name).baseName(); } if (command_line_parser.isSet(output_folder_option)) result.output_folder = command_line_parser.value(output_folder_option); else result.output_folder = QString(); if (command_line_parser.isSet(input_format_option)) { const QString& format = command_line_parser.value(input_format_option); if (!supportedConvertors().contains(format.toLower())) { command_line_parser.showHelp(-1); } else { result.data_source_text_type = textFormatType(format); } } else { result.data_source_text_type = textFormatType(source_file_name); } if (command_line_parser.isSet(auto_complete_timeout)) { result.timeout = command_line_parser.value(auto_complete_timeout).toUInt(); } if (result.output_folder.isEmpty()) result.output_folder = QDir::currentPath(); result.data_source_text = mustache(result.data_source_text, result.output_folder); return result; } daggy::Core* CConsoleDaggy::daggyCore() const { return findChild<daggy::Core*>(); } QCoreApplication* CConsoleDaggy::application() const { return qobject_cast<QCoreApplication*>(parent()); } QString CConsoleDaggy::getTextFromFile(QString file_path) const { QString result; if (!QFileInfo::exists(file_path)) { file_path = homeFolder() + file_path; } QFile source_file(file_path); if (source_file.open(QIODevice::ReadOnly | QIODevice::Text)) result = source_file.readAll(); else throw std::invalid_argument(QString("Cann't open %1 file for read: %2") .arg(file_path, source_file.errorString()) .toStdString()); if (result.isEmpty()) throw std::invalid_argument(QString("%1 file is empty") .arg(file_path) .toStdString()); return result; } QString CConsoleDaggy::homeFolder() const { return QStandardPaths::writableLocation(QStandardPaths::AppDataLocation); } QString CConsoleDaggy::mustache(const QString& text, const QString& output_folder) const { QProcessEnvironment process_environment = QProcessEnvironment::systemEnvironment(); kainjow::mustache::mustache tmpl(qUtf8Printable(text)); kainjow::mustache::data variables; for (const auto& key : process_environment.keys()) { variables.set(qPrintable(QString("env_%1").arg(key)), qUtf8Printable(process_environment.value(key))); } variables.set("output_folder", qUtf8Printable(output_folder)); return QString::fromStdString(tmpl.render(variables)); } void CConsoleDaggy::onDaggyCoreStateChanged(DaggyStates state) { switch (state) { case DaggyNotStarted: break; case DaggyStarted: break; case DaggyFinishing: break; case DaggyFinished: qApp->exit(); break; } }
33.33574
127
0.668075
milovidov
2cf95fa4d1af26fa57d13569b320577a31d79785
453
cpp
C++
src/armnn/Exceptions.cpp
KevinRodrigues05/armnn_caffe2_parser
c577f2c6a3b4ddb6ba87a882723c53a248afbeba
[ "MIT" ]
1
2019-03-19T08:44:28.000Z
2019-03-19T08:44:28.000Z
src/armnn/Exceptions.cpp
KevinRodrigues05/armnn_caffe2_parser
c577f2c6a3b4ddb6ba87a882723c53a248afbeba
[ "MIT" ]
null
null
null
src/armnn/Exceptions.cpp
KevinRodrigues05/armnn_caffe2_parser
c577f2c6a3b4ddb6ba87a882723c53a248afbeba
[ "MIT" ]
1
2019-10-11T05:58:56.000Z
2019-10-11T05:58:56.000Z
// // Copyright © 2017 Arm Ltd. All rights reserved. // See LICENSE file in the project root for full license information. // #include "armnn/Exceptions.hpp" #include <string> namespace armnn { Exception::Exception(const std::string& message) : m_Message(message) { } const char* Exception::what() const noexcept { return m_Message.c_str(); } UnimplementedException::UnimplementedException() : Exception("Function not yet implemented") { } }
16.178571
69
0.730684
KevinRodrigues05
2cfea314db777fdd1478eddb86659a125232716f
2,083
cpp
C++
tests/nostdlib/llvm_passes/SimplifyCFG/MergeConditionalStores/mergecondstores.cpp
jmorse/dexter
79cefa890d041dfc927aea2a84737aa704ddd35c
[ "MIT" ]
null
null
null
tests/nostdlib/llvm_passes/SimplifyCFG/MergeConditionalStores/mergecondstores.cpp
jmorse/dexter
79cefa890d041dfc927aea2a84737aa704ddd35c
[ "MIT" ]
null
null
null
tests/nostdlib/llvm_passes/SimplifyCFG/MergeConditionalStores/mergecondstores.cpp
jmorse/dexter
79cefa890d041dfc927aea2a84737aa704ddd35c
[ "MIT" ]
null
null
null
// RUN: %dexter int global = 0; int foo(int bar) // DexWatch('bar', 'global') { int lolret = 0; // DexWatch('bar', 'global', 'lolret') if (bar & 1) { // DexWatch('bar', 'global', 'lolret') bar += 1; // DexUnreachable() lolret += 1; // DexUnreachable() } else { // DexWatch('bar', 'global', 'lolret') global = 2; // DexWatch('bar', 'global', 'lolret') lolret += 2; // DexWatch('bar', 'global', 'lolret') } // DexWatch('bar', 'global', 'lolret') if (bar & 2) { // DexWatch('bar', 'global', 'lolret') bar += 2; // DexUnreachable() lolret += 3; // DexUnreachable() } else { // DexWatch('bar', 'global', 'lolret') global = 5; // DexWatch('bar', 'global', 'lolret') lolret += 4; // DexWatch('bar', 'global', 'lolret') } // DexWatch('bar', 'global', 'lolret') return lolret; // DexWatch('bar', 'global', 'lolret') } int main() { volatile int baz = 4; int read = baz; // DexWatch('global') int lolret2 = foo(read); // DexWatch('global', 'read') return global + lolret2; // DexWatch('global', 'read', 'lolret2') } // Here, mergeConditionalStores merges the two accesses to global into one, // with some kind of select arrangement beforehand. Run in O2, we get a ton // of backwards steps, stepping over unreachable lines, illegal values for // lolret, amoungst other things. // It gets even worse if you just run with opt -mem2reg -simplifycfg. // // Reported: https://bugs.llvm.org/show_bug.cgi?id=38756 // As of 2018-10-8, the illegal value is fixed, but we still step on // unreachable lines. // DexExpectWatchValue('bar', '4', from_line=1, to_line=50) // DexExpectWatchValue('lolret', '0', '2', '6', from_line=1, to_line=50) // DexExpectWatchValue('global', '0', '2', '5', from_line=1, to_line=50) // DexExpectWatchValue('lolret2', '6', from_line=1, to_line=50) // DexExpectWatchValue('read', '4', from_line=1, to_line=50) // DexExpectStepKind('BACKWARD', 0) // DexExpectStepKind('FUNC', 3) // DexExpectStepKind('FUNC_EXTERNAL', 0)
38.574074
75
0.606337
jmorse
2cffd33eed22de0c010509c4afebb3fbd1612541
303
hpp
C++
development/CppDB/libCppDb/include/CppDb/ManagerFwd.hpp
AntonPoturaev/CppDB
034d7feafc438fc585441742472bf4b5ef637eb2
[ "Unlicense" ]
null
null
null
development/CppDB/libCppDb/include/CppDb/ManagerFwd.hpp
AntonPoturaev/CppDB
034d7feafc438fc585441742472bf4b5ef637eb2
[ "Unlicense" ]
null
null
null
development/CppDB/libCppDb/include/CppDb/ManagerFwd.hpp
AntonPoturaev/CppDB
034d7feafc438fc585441742472bf4b5ef637eb2
[ "Unlicense" ]
null
null
null
#if !defined(__CPP_ABSTRACT_DATA_BASE_MANAGER_FORWARD_DECLARATION_HPP__) # define __CPP_ABSTRACT_DATA_BASE_MANAGER_FORWARD_DECLARATION_HPP__ namespace CppAbstractDataBase { class Manager; } /// end namespace CppAbstractDataBase #endif /// !__CPP_ABSTRACT_DATA_BASE_MANAGER_FORWARD_DECLARATION_HPP__
33.666667
72
0.874587
AntonPoturaev
fa07338eccfe31262314f8cc36876a4f175df8c7
1,498
cpp
C++
code-forces/657 Div 2/C2.cpp
ErickJoestar/competitive-programming
76afb766dbc18e16315559c863fbff19a955a569
[ "MIT" ]
1
2020-04-23T00:35:38.000Z
2020-04-23T00:35:38.000Z
code-forces/657 Div 2/C2.cpp
ErickJoestar/competitive-programming
76afb766dbc18e16315559c863fbff19a955a569
[ "MIT" ]
null
null
null
code-forces/657 Div 2/C2.cpp
ErickJoestar/competitive-programming
76afb766dbc18e16315559c863fbff19a955a569
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define ENDL '\n' #define deb(u) cout << #u " : " << (u) << ENDL; #define deba(alias, u) cout << alias << ": " << (u) << ENDL; #define debp(u, v) cout << u << " : " << v << ENDL; #define pb push_back #define F first #define S second #define lli long long #define pii pair<int, int> #define pll pair<lli, lli> #define ALL(a) (a).begin(), (a).end() #define ALLR(a) (a).rbegin(), (a).rend() #define FOR(i, a, n) for (int i = (a); i < (n); ++i) #define FORN(i, a, n) for (int i = (a - 1); i >= n; --i) #define IO \ ios_base::sync_with_stdio(false); \ cin.tie(0); \ cout.tie(0) using namespace std; int main() { IO; int t; cin >> t; while (t--) { lli n, m; cin >> n >> m; pii best = {-1, -1}; vector<lli> v(m); FOR(i, 0, m) { lli a, b; cin >> a >> b; v[i] = a; lli bestVal = best.F + best.S * (n - 1); lli val; if (a >= b) { lli val = b * n; if (val > bestVal) best = {b, b}; } else { lli val = a + b * (n - 1); if (val > bestVal) best = {a, b}; } } sort(v.rbegin(), v.rend()); lli ans = 0; for (auto e : v) { lli val = best.F + best.S * (n - 1); if (e * n > val) { ans += e; } else break; n--; } if (n > 0) ans += best.F + best.S * (n - 1); cout << ans << ENDL; } return 0; }
20.520548
60
0.417223
ErickJoestar
fa0a00bc000fb4492fa205ca3e76cf85f6117e00
1,499
cpp
C++
dynamic programming/70. Climbing Stairs.cpp
Constantine-L01/leetcode
1f1e3a8226fcec036370e75c1d69e823d1323392
[ "MIT" ]
1
2021-04-08T10:33:48.000Z
2021-04-08T10:33:48.000Z
dynamic programming/70. Climbing Stairs.cpp
Constantine-L01/leetcode
1f1e3a8226fcec036370e75c1d69e823d1323392
[ "MIT" ]
null
null
null
dynamic programming/70. Climbing Stairs.cpp
Constantine-L01/leetcode
1f1e3a8226fcec036370e75c1d69e823d1323392
[ "MIT" ]
1
2021-02-23T05:58:58.000Z
2021-02-23T05:58:58.000Z
You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Example 1: Input: n = 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps //better solution with less space used class Solution { public: int climbStairs(int n) { // initially, the currentstep is first stair, oneStep means the move of climbing the stair, twoStep means the move of moving to right and climbing the stair. 1 for oneStep, // 0 for twoStep because it is not possible int oneStepToReachDest = 1; int twoStepToReachDest = 0; int currentStep = 0; // At first iteration, currentStep is 1 because only action oneStep is possible. At second iteration, twoStep = oneStep and oneStep = first iteration's currentStep for(int i = 1; i <= n; i++) { currentStep = oneStepToReachDest + twoStepToReachDest; twoStepToReachDest = oneStepToReachDest; oneStepToReachDest = currentStep; } return currentStep; } }; class Solution { public: int climbStairs(int n) { if(n == 1) return 1; vector<int> steps(n, 0); steps[0] = 1; steps[1] = 2; for(int i = 2; i < n; i++) { steps[i] = steps[i-1] + steps[i-2]; } return steps[n-1]; } };
28.826923
181
0.596398
Constantine-L01
fa0fc5014c590e38f905d7af0ab48bb4b7535324
4,083
hpp
C++
src/utils/timed_events.hpp
norayr/biboumi
805671032d25ee6ce09ed75e8a385c04e9563cdd
[ "Zlib" ]
68
2015-01-29T21:07:37.000Z
2022-03-20T14:48:07.000Z
src/utils/timed_events.hpp
norayr/biboumi
805671032d25ee6ce09ed75e8a385c04e9563cdd
[ "Zlib" ]
5
2016-10-24T18:34:30.000Z
2021-08-31T13:30:37.000Z
src/utils/timed_events.hpp
norayr/biboumi
805671032d25ee6ce09ed75e8a385c04e9563cdd
[ "Zlib" ]
13
2015-12-11T15:19:05.000Z
2021-08-31T13:24:35.000Z
#pragma once #include <functional> #include <string> #include <chrono> #include <vector> using namespace std::literals::chrono_literals; namespace utils { static constexpr std::chrono::milliseconds no_timeout = std::chrono::milliseconds(-1); } class TimedEventsManager; /** * A callback with an associated date. */ class TimedEvent { friend class TimedEventsManager; public: /** * An event the occurs only once, at the given time_point */ explicit TimedEvent(std::chrono::steady_clock::time_point&& time_point, std::function<void()> callback, std::string name=""); explicit TimedEvent(std::chrono::milliseconds&& duration, std::function<void()> callback, std::string name=""); explicit TimedEvent(TimedEvent&&) = default; TimedEvent& operator=(TimedEvent&&) = default; ~TimedEvent() = default; TimedEvent(const TimedEvent&) = delete; TimedEvent& operator=(const TimedEvent&) = delete; /** * Whether or not this event happens after the other one. */ bool is_after(const TimedEvent& other) const; bool is_after(const std::chrono::steady_clock::time_point& time_point) const; /** * Return the duration difference between now and the event time point. * If the difference would be negative (i.e. the event is expired), the * returned value is 0 instead. The value cannot then be negative. */ std::chrono::milliseconds get_timeout() const; void execute() const; const std::string& get_name() const; private: /** * The next time point at which the event is executed. */ std::chrono::steady_clock::time_point time_point; /** * The function to execute. */ std::function<void()> callback; /** * Whether or not this events repeats itself until it is destroyed. */ bool repeat; /** * This value is added to the time_point each time the event is executed, * if repeat is true. Otherwise it is ignored. */ std::chrono::milliseconds repeat_delay; /** * A name that is used to identify that event. If you want to find your * event (for example if you want to cancel it), the name should be * unique. */ std::string name; }; /** * A class managing a list of TimedEvents. * They are sorted, new events can be added, removed, fetch, etc. */ class TimedEventsManager { public: ~TimedEventsManager() = default; TimedEventsManager(const TimedEventsManager&) = delete; TimedEventsManager(TimedEventsManager&&) = delete; TimedEventsManager& operator=(const TimedEventsManager&) = delete; TimedEventsManager& operator=(TimedEventsManager&&) = delete; /** * Return the unique instance of this class */ static TimedEventsManager& instance(); /** * Add an event to the list of managed events. The list is sorted after * this call. */ void add_event(TimedEvent&& event); /** * Returns the duration, in milliseconds, between now and the next * available event. If the event is already expired (the duration is * negative), 0 is returned instead (as in “it's not too late, execute it * now”) * Returns a negative value if no event is available. */ std::chrono::milliseconds get_timeout() const; /** * Execute all the expired events (if their expiration time is exactly * now, or before now). The event is then removed from the list. If the * event does repeat, its expiration time is updated and it is reinserted * in the list at the correct position. * Returns the number of executed events. */ std::size_t execute_expired_events(); /** * Remove (and thus cancel) all the timed events with the given name. * Returns the number of canceled events. */ std::size_t cancel(const std::string& name); /** * Return the number of managed events. */ std::size_t size() const; /** * Return a pointer to the first event with the given name. If none * is found, returns nullptr. */ const TimedEvent* find_event(const std::string& name) const; private: std::vector<TimedEvent> events; explicit TimedEventsManager() = default; };
29.586957
86
0.690914
norayr
fa14c0cd63a0c25a089f5434f3573441a843f9f6
362
cpp
C++
A/1031.cpp
chenjiajia9411/PATest
061c961f5d7bf7b23c3a1b70d3d443cb57263700
[ "Apache-2.0" ]
1
2017-11-24T15:06:29.000Z
2017-11-24T15:06:29.000Z
A/1031.cpp
chenjiajia9411/PAT
061c961f5d7bf7b23c3a1b70d3d443cb57263700
[ "Apache-2.0" ]
null
null
null
A/1031.cpp
chenjiajia9411/PAT
061c961f5d7bf7b23c3a1b70d3d443cb57263700
[ "Apache-2.0" ]
null
null
null
#include <iostream> using namespace std; int main() { string input; cin>>input; int is = input.size(); int n = (is + 2)/3; for(int i = 0;i < n - 1;i++) { cout<<input.front(); input.erase(0,1); for(int j = 0;j < (is - 2*n);j++) cout<<" "; cout<<input.back()<<"\n"; input.pop_back(); } cout<<input<<endl; }
19.052632
52
0.486188
chenjiajia9411
fa17a23c3ce2ce020cd09e3414631fa3e31da150
4,213
cpp
C++
utilities/msmonitor/gui/QMSMFormHeatmapAbstract.cpp
akiml/ampehre
383a863442574ea2e6a6ac853a9b99e153daeccf
[ "BSD-2-Clause" ]
3
2016-01-20T13:41:52.000Z
2018-04-10T17:50:49.000Z
utilities/msmonitor/gui/QMSMFormHeatmapAbstract.cpp
akiml/ampehre
383a863442574ea2e6a6ac853a9b99e153daeccf
[ "BSD-2-Clause" ]
null
null
null
utilities/msmonitor/gui/QMSMFormHeatmapAbstract.cpp
akiml/ampehre
383a863442574ea2e6a6ac853a9b99e153daeccf
[ "BSD-2-Clause" ]
null
null
null
/* * QMSMFormHeatmapAbstract.cpp * * Copyright (C) 2015, Achim Lösch <achim.loesch@upb.de>, Christoph Knorr <cknorr@mail.uni-paderborn.de> * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD license. See the LICENSE file for details. * * encoding: UTF-8 * tab size: 4 * * author: Christoph Knorr (cknorr@mail.uni-paderborn.de) * created: 01/27/16 * version: 0.7.3 - add heatmaps to msmonitor and the enum ipmi_timeout_setting in libmeasure */ #include "QMSMFormHeatmapAbstract.hpp" namespace Ui { uint32_t QMSMFormHeatmapAbstract::sNumberOfImages = 0; QMSMFormHeatmapAbstract::QMSMFormHeatmapAbstract(QWidget *pParent, NData::CDataHandler* pDataHandler) : QMdiSubWindow(pParent), FormHeatmap(), mpFormHeatmapAbstract(new QWidget(pParent)), mpDataHandler(pDataHandler), mTimer(mpDataHandler->getSettings().mGUIRefreshRate, this), mHeatmaps(), mCurrentX(0), mIndexCurrentX(0) { //setAttribute(Qt::WA_DeleteOnClose); setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowCloseButtonHint | Qt::WindowMinimizeButtonHint); setupUi(mpFormHeatmapAbstract); setWidget(mpFormHeatmapAbstract); createActions(); } QMSMFormHeatmapAbstract::~QMSMFormHeatmapAbstract(void) { for(std::vector<Ui::QMSMHeatmap*>::iterator it = mHeatmaps.begin(); it != mHeatmaps.end(); ++it) { delete (*it); } delete mpFormHeatmapAbstract; } void QMSMFormHeatmapAbstract::createActions(void) { connect(pushButtonOK, SIGNAL(clicked(bool)), this, SLOT(close())); connect(pushButtonSave, SIGNAL(clicked(bool)), this, SLOT(saveImage())); connect(this, SIGNAL(signalRefreshGui(void)), this, SLOT(slotRefreshGui())); } QwtText QMSMFormHeatmapAbstract::createTitle(QString title) { QwtText qTitle(title); qTitle.setFont(QFont("Helvetica", 12)); return qTitle; } void QMSMFormHeatmapAbstract::updateCurrentX(void) { uint32_t bufferedSamples = ((mpDataHandler->getSettings().mTimeToBufferData - mpDataHandler->getSettings().mTimeToShowData) / mpDataHandler->getSettings().mDataSamplingRate)-1; uint32_t showSamples = (mpDataHandler->getSettings().mTimeToShowData / mpDataHandler->getSettings().mDataSamplingRate) - 1; double *x = mpDataHandler->getMeasurement().mpX->getDataPtr() + bufferedSamples; //shift x axis every 10 s if(x[showSamples] - mCurrentX > 10) { mCurrentX += 10; } //reset x axis if necessary if(x[showSamples] < mCurrentX) { mCurrentX = 0; } //search the index corresponding to mCurrentX mIndexCurrentX = 0; for (int i = showSamples; i >= 0; i--) { if(x[i] <= (mCurrentX + ((double) mpDataHandler->getSettings().mDataSamplingRate/1000/3))){ mIndexCurrentX = i; break; } } } void QMSMFormHeatmapAbstract::close(void) { hide(); } void QMSMFormHeatmapAbstract::closeEvent(QCloseEvent *pEvent) { hide(); } bool QMSMFormHeatmapAbstract::event(QEvent *pEvent) { if (pEvent->type() == QEvent::ToolTip) { return true; } return QMdiSubWindow::event(pEvent); } void QMSMFormHeatmapAbstract::refreshGui(void) { emit signalRefreshGui(); } void QMSMFormHeatmapAbstract::slotRefreshGui(void) { if(isVisible()) { setupHeatmaps(); for(std::vector<Ui::QMSMHeatmap*>::iterator it = mHeatmaps.begin(); it != mHeatmaps.end(); ++it) { (*it)->refresh(); } } else { updateCurrentX(); } } void QMSMFormHeatmapAbstract::saveImage(void) { //TODO needs to be implemented } void QMSMFormHeatmapAbstract::startTimer(void) { mTimer.startTimer(); } void QMSMFormHeatmapAbstract::stopTimer(void) { mTimer.stopTimer(); } void QMSMFormHeatmapAbstract::joinTimer(void) { mTimer.joinTimer(); } QMSMHeatmap* QMSMFormHeatmapAbstract::addHeatmap(const QString &title) { Ui::QMSMHeatmap *heatmap = new QMSMHeatmap(this); heatmap->setObjectName(title); heatmap->setFrameShape(QFrame::NoFrame); heatmap->setFrameShadow(QFrame::Raised); heatmap->setTitle(title.toStdString()); verticalLayoutMeasurement->insertWidget(mHeatmaps.size(), heatmap); mHeatmaps.push_back(heatmap); resize(650, 50 + 110 * mHeatmaps.size()); return heatmap; } }
27.357143
127
0.711844
akiml
fa18a3ae82592268a345f287ee0a23fec1355601
670
hpp
C++
source/Utilities/Point2D.hpp
hadryansalles/ray-tracing-from-the-ground-up
4ca02fca2cdd458767b4ab3df15b6cd20cb1f413
[ "MIT" ]
5
2021-09-24T12:22:08.000Z
2022-03-23T06:54:02.000Z
source/Utilities/Point2D.hpp
hadryans/ray-tracing-from-the-ground-up
4ca02fca2cdd458767b4ab3df15b6cd20cb1f413
[ "MIT" ]
null
null
null
source/Utilities/Point2D.hpp
hadryans/ray-tracing-from-the-ground-up
4ca02fca2cdd458767b4ab3df15b6cd20cb1f413
[ "MIT" ]
5
2021-08-14T22:26:11.000Z
2022-03-04T09:13:39.000Z
#pragma once #include "Matrix.hpp" #include <math.h> class Point2D { public: double x, y; Point2D(); Point2D(const double a); Point2D(const double a, const double b); Point2D(const Point2D &p); ~Point2D(); Point2D& operator= (const Point2D& p); // assignment operator Point2D operator- (void) const; // unary minus Point2D operator* (const double a) const; // multiplication by a double on the right double d_squared(const Point2D& p) const; // square of distance bertween two points double distance(const Point2D& p) const; // distance bewteen two points }; Point2D operator* (double a, const Point2D& p);
27.916667
89
0.671642
hadryansalles
fa1e92d86a4cfe6bcc31d1ffa3b36128579a55c9
1,401
cpp
C++
Stack & Heap/316. Remove Duplicate Letters/main.cpp
Minecodecraft/LeetCode-Minecode
185fd6efe88d8ffcad94e581915c41502a0361a0
[ "MIT" ]
1
2021-11-19T19:58:33.000Z
2021-11-19T19:58:33.000Z
Stack & Heap/316. Remove Duplicate Letters/main.cpp
Minecodecraft/LeetCode-Minecode
185fd6efe88d8ffcad94e581915c41502a0361a0
[ "MIT" ]
null
null
null
Stack & Heap/316. Remove Duplicate Letters/main.cpp
Minecodecraft/LeetCode-Minecode
185fd6efe88d8ffcad94e581915c41502a0361a0
[ "MIT" ]
2
2021-11-26T12:47:27.000Z
2022-01-13T16:14:46.000Z
// // main.cpp // 316. Remove Duplicate Letters // // Created by 边俊林 on 2019/10/3. // Copyright © 2019 Minecode.Link. All rights reserved. // /* ------------------------------------------------------ *\ https://leetcode.com/problems/remove-duplicate-letters/ \* ------------------------------------------------------ */ #include <map> #include <set> #include <queue> #include <string> #include <stack> #include <vector> #include <cstdio> #include <numeric> #include <cstdlib> #include <utility> #include <iostream> #include <algorithm> #include <unordered_map> #include <unordered_set> using namespace std; /// Solution: // class Solution { public: string removeDuplicateLetters(string s) { vector<int> cnt (26, 0); for (char &ch: s) cnt[ch-'a']++; int idx = 0; for (int i = 0; i < s.length(); ++i) { if (s[i] < s[idx]) idx = i; if (--cnt[s[i] - 'a'] == 0) break; } if (s.empty()) return ""; else { string buffer = s.substr(idx+1); buffer.erase(remove(buffer.begin(), buffer.end(), s[idx]), buffer.end()); return s[idx] + removeDuplicateLetters(buffer); } } }; int main() { Solution sol = Solution(); string s = "bcabc"; // string s = "cbacdcbc"; string res = sol.removeDuplicateLetters(s); cout << res << endl; return 0; }
23.35
85
0.522484
Minecodecraft
fa2380682598c79bfaf0c3f3da04682a49f4ac03
10,020
cpp
C++
Modular Server/modulserv/my_parser.cpp
jancura/modular-server
ef97e7147edb33614d986a514c236f3dd020b513
[ "MIT" ]
1
2018-12-30T11:17:22.000Z
2018-12-30T11:17:22.000Z
Modular Server/modulserv/my_parser.cpp
jancura/modular-server
ef97e7147edb33614d986a514c236f3dd020b513
[ "MIT" ]
null
null
null
Modular Server/modulserv/my_parser.cpp
jancura/modular-server
ef97e7147edb33614d986a514c236f3dd020b513
[ "MIT" ]
null
null
null
//20.05.2005 - implementacia my_parser.cpp /*Pali Jancura - to jest ja :) * 26.05.2005 * - ping prerobeny do dll * - dalsie zmeny, pridany ping, este predtym bol pridany broadcast * 20.05.2005 * add: bool my_parser() */ #include "stdafx.h" #include "my_parser.h" #include "server_thread.h" #include "broadcast_thread.h" #include <string> #include <cctype> #include <winsock.h> #include <iostream> #include <fstream> #define SPRAVA_SIZE 20 using namespace std; typedef string::size_type str_size; typedef size_t (*broadadd_PTR)(char*, size_t, size_t); typedef size_t (*broadcast_PTR)(char*, size_t); typedef int (*GetTimeout_PTR)(); typedef bool (*ping_PTR)(struct in_addr, struct in_addr, DWORD, char *); typedef bool (*newping_PTR)(); broadadd_PTR broadcastadd = NULL; broadcast_PTR GetBroadcastMsg = NULL; GetTimeout_PTR GetTimeOutBroadcast= NULL; ping_PTR ping = NULL; newping_PTR new_ping = NULL; //cesta k suboru pre logovanie pingu char PingLog[MAX_PATH]; /****************************************************************************** * string word(const string& s, str_size& i) * - zo stringu s, vrati jedno slovo od pozicie i, a pozmeni i, tak ze ukazuje * na zaciatok noveho slova alebo koniec stringu s, za predpokladu, ze kazde * slovo je oddelene prave jednym bielym znakom * - v inom pripade vrati prazdny retazec * - v configu pouzivam '=',tento znak zatial preskakujem,mozne vyuzitie neskor ******************************************************************************/ string word(const string& s, str_size& i) { string vysledok = ""; str_size j; if(i < s.size()){ j = i; //dokial nenarazim na biely znak alebo koniec stringu while(j != s.size() && !isspace(s[j])) ++j; //bol tam aspon jeden nebiely znak if(i != j){ vysledok = s.substr(i, j - i); i = ++j; //posuniem sa dalej za biely znak } //preskocim znak '=' if(vysledok == "=") vysledok = word(s, i); } return vysledok; }//string word(string& s, str_size& i) /****************************************************************************** * bool my_parser(const string& conf) * - rozobera konfiguracny string pomocou funkcie word a nastavi konfiguraciu ******************************************************************************/ bool my_parser(const string& conf) { CLog::WriteLog("parser" , "my_parser(): begin"); wchar_t pwcLibrary[MAX_PATH]; char * sprava = new char[SPRAVA_SIZE]; int iNewSize=0; string spr = strcpy(sprava, "modular_server 1.0"); str_size i = 0; string option; int port1, port2; DWORD timeOut = 0; DWORD timeOutBroad = 0; //default hodnoty struct in_addr localhost, subnetmask, broadcastIP; bool old = true, pingOLD = false, pingNEW = false; //pre broadcast a ping bool bBroadcast=false; while(i < conf.size()){ option = word(conf, i); if(option == "port"){ option = word(conf, i); if(option == "telnet"){ option = word(conf, i); port1 = htons(atoi(option.c_str())); }else{ if(option == "broadcast"){ option = word(conf, i); port2 = htons(atoi(option.c_str())); }else{ CLog::WriteLog("parser", "my_parser(): Chyba v nastaveni portov!"); return false; } } }else{ if(option == "localhost"){ option = word(conf, i); localhost.s_addr = inet_addr(option.c_str()); }else{ if(option == "subnetmask"){ option = word(conf, i); subnetmask.s_addr = inet_addr(option.c_str()); }else{ if(option == "broadcast"){ option = word(conf, i); if(option == "Default"){ bBroadcast = true; option = word(conf, i); timeOutBroad = atoi(option.c_str()); if(timeOutBroad<=0) { CLog::WriteLog("parser", "my_parser(): Chyba v nastaveni: Nenastaveny timeout broadcastu!"); return false; } }else{ if(option == "NEW"){ bBroadcast = true; swprintf(pwcLibrary, L"%sLibrary\\broadcast.dll", pwcProgramFolder); HINSTANCE hDll = LoadLibrary(pwcLibrary); if(hDll == NULL){ CLog::WriteLog("parser", "my_parser(): broadcast.dll nie je v library"); bBroadcast = false; }else{ GetBroadcastMsg = (broadcast_PTR)GetProcAddress(hDll,"GetBroadcastMessage"); GetTimeOutBroadcast = (GetTimeout_PTR)GetProcAddress(hDll,"GetTimeOut"); if(GetBroadcastMsg == NULL || GetTimeOutBroadcast==NULL){ CLog::WriteLog("parser", "my_parser(): Nenacitana funkcia z broadcast.dll"); bBroadcast = false; }else{ CLog::WriteLog("parser", "my_parser(): GetBroadcastMessage a GetTimeOutBroadcast uspesne importovane!"); iNewSize = GetBroadcastMsg(sprava, SPRAVA_SIZE); if(iNewSize){ delete [] sprava; sprava = new char [iNewSize+1]; GetBroadcastMsg(sprava, iNewSize); spr = sprava; }else spr = sprava; timeOutBroad = GetTimeOutBroadcast(); CLog::WriteLog("parser", "my_parser(): GetBroadcastMessage a GetTimeOutBroadcast uspesne prebehli!"); } }//if(hDll == NULL) }else{ broadcastIP.s_addr = inet_addr(option.c_str()); }} }else{ if(option == "broadcastadd"){ if(!bBroadcast) CLog::WriteLog("parser", "my_parser(): Broadcastadd neprebehne: Zle nadefinovany broadcast v dll!"); else { swprintf(pwcLibrary, L"%sLibrary\\broadcastadd.dll", pwcProgramFolder); HINSTANCE hDll = LoadLibrary(pwcLibrary); if(hDll == NULL){ CLog::WriteLog("parser", "my_parser(): broadcastadd.dll nie v library!"); }else{ broadcastadd=(broadadd_PTR)GetProcAddress(hDll,"broadcastadd"); if(broadcastadd == NULL){ CLog::WriteLog("parser", "my_parser(): Nenacitana funkcia z broadcastadd.dll!"); }else{ CLog::WriteLog("parser", "my_parser(): Broadcastadd uspesne importovany!"); if(iNewSize) iNewSize = broadcastadd(sprava, iNewSize, spr.size()); else iNewSize = broadcastadd(sprava, SPRAVA_SIZE, spr.size()); if(iNewSize){ char * buf = new char[iNewSize+1]; strcpy(buf, sprava); delete [] sprava; sprava = NULL; broadcastadd(buf, iNewSize, spr.size()); spr = buf; delete [] buf; }else spr = sprava; } }//if(hDll == NULL) } }else{ if(option == "ping"){ option = word(conf, i); if(option == "Default"){ option = word(conf, i); timeOut = atoi(option.c_str()); if(timeOut<=0) { CLog::WriteLog("parser", "my_parser(): Chyba v nastaveni: Nenastaveny timeout pingu!"); return false; } pingOLD = true; }else if(option == "NEW") pingNEW = true; }else{ CLog::WriteLog("parser", "my_parser(): Chyba v nastaveni"); return false; }}}}}} }//while //broadcast CLog::WriteLog("parser", "my_parser(): Inicializacia broadcastu!"); sendBroadcastThread * sendBroad = NULL; recvBroadcastThread * recvBroad = NULL; if(bBroadcast){ recvBroad = new recvBroadcastThread(port2,localhost); sendBroad = new sendBroadcastThread(broadcastIP,port2,spr,timeOutBroad); }else{ } if(sprava) delete [] sprava; //opingujem siet if(pingOLD){ swprintf(pwcLibrary, L"%sLibrary\\ping.dll", pwcProgramFolder); HINSTANCE hDll = LoadLibrary(pwcLibrary); if(hDll == NULL){ CLog::WriteLog("parser", "my_parser(): ping.dll nie v library"); }else{ ping = (ping_PTR)GetProcAddress(hDll,"ping"); if(ping == NULL){ CLog::WriteLog("parser", "my_parser(): Nenacitana funkcia z ping.dll"); }else{ CLog::WriteLog("parser", "my_parser(): ping uspesne importovany!"); sprintf(PingLog, "%sLog\\ping.log", pcProgramFolder); if ( ping(localhost, subnetmask, timeOut, PingLog) ) CLog::WriteLog("parser", "my_parser(): Ping celej siete uspesne prebehol"); else CLog::WriteLog("parser", "my_parser(): Chyba v importovanom ping!"); } }//if(hDll == NULL) } if(pingNEW){ swprintf(pwcLibrary, L"%sLibrary\\new_ping.dll", pwcProgramFolder); HINSTANCE hDll = LoadLibrary(pwcLibrary); if(hDll == NULL){ CLog::WriteLog("parser", "my_parser(): new_ping.dll nie v library"); }else{ new_ping = (newping_PTR)GetProcAddress(hDll,"ping"); if(new_ping == NULL){ CLog::WriteLog("parser", "my_parser(): Nenacitana funkcia z new_ping.dll"); }else{ CLog::WriteLog("parser", "my_parser(): new_ping uspesne importovany!"); if(new_ping()) CLog::WriteLog("parser", "my_parser(): Imporotvany new_ping uspesne prebehol"); else CLog::WriteLog("parser", "my_parser(): Chyba v importovanom new_ping!"); } }//if(hDll == NULL) } //instacionujem triedu pre klientov //spustim vlakno pre prijem spojeni na zadanom porte (samotny server) CLog::WriteLog("parser", "my_parser(): Allocing listenThread!"); listenThread * listen = new listenThread(port1, localhost, &Clients); CLog::WriteLog("parser", "my_parser(): Alloced listenThread!"); //instacionujem triedu pre spracovanie fronty CLog::WriteLog("parser", "my_parser(): Allocing ProcessQueqe!"); CProcessQueqe* ProcessQueqe = new CProcessQueqe(recvBroad, sendBroad, listen, &Clients); CLog::WriteLog("parser", "my_parser(): Alloced ProcessQueqe!"); //vytvorim zamky pre vlakna pre pristup ku globalnym premennym try{ CLog::WriteLog("parser", "my_parser(): ProcessQueqe & listen starting!"); ProcessQueqe->start(); CLog::WriteLog("parser", "my_parser(): ProcessQueqe started!"); listen->start(); CLog::WriteLog("parser", "my_parser(): listen started!"); //zacnem vysielat a prijmat broadcast if(recvBroad) recvBroad->start(); if(sendBroad) sendBroad->start(); CLog::WriteLog("parser", "my_parser(): listen stoping!"); listen->stop(); CLog::WriteLog("parser", "my_parser(): listen stoped!"); if(recvBroad){ recvBroad->stop(); delete recvBroad; CLog::WriteLog("parser", "parser: Uspesne zastaveny recvBroad"); } if(sendBroad){ sendBroad->stop(); delete sendBroad; CLog::WriteLog("parser","parser: Uspesne zastaveny sendBroad"); } ProcessQueqe->stop(); }catch (ThreadException ex) { CLog::WriteLog("parser", (ex.getMessage()).c_str()); } delete listen; delete ProcessQueqe; return true; }
31.809524
110
0.646607
jancura
fa267557bc33f4869f70e21dfcbf5301c9d0d38c
186
hpp
C++
util.hpp
Mnkai/libzku_unitconv
04951b54c255001bceeb484e5ff5754828dfda38
[ "Apache-2.0" ]
null
null
null
util.hpp
Mnkai/libzku_unitconv
04951b54c255001bceeb484e5ff5754828dfda38
[ "Apache-2.0" ]
2
2017-05-29T13:57:39.000Z
2017-06-05T02:21:42.000Z
util.hpp
Mnkai/libzku_unitconv
04951b54c255001bceeb484e5ff5754828dfda38
[ "Apache-2.0" ]
null
null
null
#include <algorithm> #include <functional> #include <cctype> #include <locale> std::string &ltrim(std::string &s); std::string &rtrim(std::string &s); std::string &trim(std::string &s);
23.25
35
0.698925
Mnkai
fa28b20e7e464a27ea215c13f2f5b4e81cac8680
4,319
hpp
C++
esp/platform/espsecurecontext.hpp
miguelvazq/HPCC-Platform
22ad8e5fcb59626abfd8febecbdfccb1e9fb0aa5
[ "Apache-2.0" ]
286
2015-01-03T12:45:17.000Z
2022-03-25T18:12:57.000Z
esp/platform/espsecurecontext.hpp
miguelvazq/HPCC-Platform
22ad8e5fcb59626abfd8febecbdfccb1e9fb0aa5
[ "Apache-2.0" ]
9,034
2015-01-02T08:49:19.000Z
2022-03-31T20:34:44.000Z
esp/platform/espsecurecontext.hpp
cloLN/HPCC-Platform
42ffb763a1cdcf611d3900831973d0a68e722bbe
[ "Apache-2.0" ]
208
2015-01-02T03:27:28.000Z
2022-02-11T05:54:52.000Z
/*############################################################################## HPCC SYSTEMS software Copyright (C) 2016 HPCC Systems®. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ############################################################################## */ #ifndef ESPSECURECONTEXT_HPP #define ESPSECURECONTEXT_HPP #include "jiface.hpp" #include "tokenserialization.hpp" class CTxSummary; // Declares a protocol-independent interface to give security managers read // access to protocol-dependent data values. Subclasses determine the types // of data to which they will provide access. Callers are assumed to know // which data types they may request. // // For example, consider an HTTP request. A caller may need access to HTTP // cookies. In such a case, the caller may call getProtocol() to confirm that // the supported protocol is "http" and then may assume that a property type // of "cookie" will be supported. interface IEspSecureContext : extends IInterface { // Return a protocol-specific identifier. Callers may use this value to // confirm availability of required data types. virtual const char* getProtocol() const = 0; // Returns the TxSummary object to be used for a request. virtual CTxSummary* queryTxSummary() const = 0; // Fetches a data value based on a given type and name. If the requested // value exists it is stored in the supplied value buffer and true is // returned. If the requested value does not exist, the value buffer is // unchanged and false is returned. // // Acceptable values of the 'type' parameter are defined by protocol- // specific subclasses. E.g., an HTTP specific subclass might support // cookie data. // // Acceptable values of the 'name' parameter are dependent on the caller. virtual bool getProp(int type, const char* name, StringBuffer& value) = 0; // Implementation-independent wrapper of the abstract getProp method // providing convenient access to non-string values. Non-string means // numeric (including Boolean) values by default, but callers do have // the option to replace the default deserializer with one capable of // supporting more complex types. // // True is returned if the requested property exists and its value is // convertible to TValue. False is returned in all other cases. The // caller may request the conversion result code to understand why a // request failed. // // Template Parameters // - TValue: a type supported by of TDeserializer // - TDefault[TValue]: a type from which TValue can be initialized // - TDeserializer[TokenDeserializer]: a callback function, lambda, or // functor with signature: // DeserializationResult (*pfn)(const char*, TValue&) template <typename TValue, typename TDefault = TValue, class TDeserializer = TokenDeserializer> bool getProp(int type, const char* name, TValue& value, const TDefault dflt = TDefault(), DeserializationResult* deserializationResult = NULL, TDeserializer& deserializer = TDeserializer()); }; template <typename TValue, typename TDefault, class TDeserializer> inline bool IEspSecureContext::getProp(int type, const char* name, TValue& value, const TDefault dflt, DeserializationResult* deserializationResult, TDeserializer& deserializer) { DeserializationResult result = Deserialization_UNKNOWN; StringBuffer prop; bool found = getProp(type, name, prop); if (found) { result = deserializer(prop, value); found = (Deserialization_SUCCESS == result); } if (!found) { value = TValue(dflt); } if (deserializationResult) { *deserializationResult = result; } return found; } #endif // ESPSECURECONTEXT_HPP
41.133333
194
0.694837
miguelvazq
fa2b1cd9c0e3ad13ff409683d37c865b8020b188
1,609
cpp
C++
breath/cryptography/test/digest_ordering_test.cpp
erez-o/breath
adf197b4e959beffce11e090c5e806d2ff4df38a
[ "BSD-3-Clause" ]
null
null
null
breath/cryptography/test/digest_ordering_test.cpp
erez-o/breath
adf197b4e959beffce11e090c5e806d2ff4df38a
[ "BSD-3-Clause" ]
null
null
null
breath/cryptography/test/digest_ordering_test.cpp
erez-o/breath
adf197b4e959beffce11e090c5e806d2ff4df38a
[ "BSD-3-Clause" ]
null
null
null
// =========================================================================== // This is an open source non-commercial project. // Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++, C#, and Java: // http://www.viva64.com // =========================================================================== // Copyright 2019 Gennaro Prota // // Licensed under the 3-Clause BSD License. // (See accompanying file 3_CLAUSE_BSD_LICENSE.txt or // <https://opensource.org/licenses/BSD-3-Clause>.) // ___________________________________________________________________________ #include "breath/cryptography/digest.hpp" #include "breath/cryptography/sha1_hasher.hpp" #include "breath/testing/testing.hpp" #include <map> #include <string> int test_digest_ordering() ; namespace { void check_usability_with_map() { std::string const s = "test" ; breath::sha1_hasher const hasher( s.cbegin(), s.cend() ) ; breath::sha1_digest const digest( hasher ) ; std::map< breath::sha1_digest, int, breath::sha1_digest::less > m ; m[ digest ] = 1 ; } } int test_digest_ordering() { using namespace breath ; return test_runner::instance().run( "Digest ordering", { check_usability_with_map } ) ; } // Local Variables: // mode: c++ // indent-tabs-mode: nil // c-basic-offset: 4 // End: // vim: set ft=cpp et sts=4 sw=4:
28.732143
78
0.527657
erez-o
fa2b32d34a9ddae71b3b037a4c48e590b07ed49a
525
cpp
C++
chef/aug2020/linchess.cpp
skmorningstar/Competitive-Programming
05ba602d0fe1492d5c36267237980a9ac2f124d6
[ "Apache-2.0" ]
null
null
null
chef/aug2020/linchess.cpp
skmorningstar/Competitive-Programming
05ba602d0fe1492d5c36267237980a9ac2f124d6
[ "Apache-2.0" ]
null
null
null
chef/aug2020/linchess.cpp
skmorningstar/Competitive-Programming
05ba602d0fe1492d5c36267237980a9ac2f124d6
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> #define ll long long int using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); ll t; cin>>t; while(t--) { ll n,k; cin>>n>>k; bool found=false; vector<ll> arr(n); for(ll i{0};i<n;i++) cin>>arr[i]; ll min=INT_MAX; ll mini=0; for(ll i{0};i<n;i++) { if(k%arr[i]==0) { if(k/arr[i]<min) { min=k/arr[i]; mini=arr[i]; } found=true; } } if(found) cout<<mini<<endl; else cout<<-1<<endl; } return 0; }
12.804878
34
0.52
skmorningstar
fa3148e6c41374aa0763f0c4ca79a69d027d60ab
4,245
hpp
C++
include/gem/dimensions_tuple.hpp
RomainBrault/Gem
0eff3cb034a0faaca894316b72f4b005e72e0f5d
[ "MIT" ]
null
null
null
include/gem/dimensions_tuple.hpp
RomainBrault/Gem
0eff3cb034a0faaca894316b72f4b005e72e0f5d
[ "MIT" ]
null
null
null
include/gem/dimensions_tuple.hpp
RomainBrault/Gem
0eff3cb034a0faaca894316b72f4b005e72e0f5d
[ "MIT" ]
null
null
null
#ifndef GEM_DIMENSIONS_TUPLE_HPP_INCLUDED #define GEM_DIMENSIONS_TUPLE_HPP_INCLUDED #define BOOST_HANA_CONFIG_ENABLE_STRING_UDL #include <type_traits> #include <boost/hana/assert.hpp> #include <boost/hana/integral_constant.hpp> #include <boost/hana/minus.hpp> #include <boost/hana/tuple.hpp> #include <boost/hana/transform.hpp> #include <boost/hana/fold.hpp> #include <boost/hana/string.hpp> #include <cereal/cereal.hpp> #include <gem/litterals.hpp> #include <gem/fwd/dimensions_tuple.hpp> namespace gem { gem::concepts::DimensionTuple {T_flag, n_con, n_cov, ...dims} class DimensionTuple : public boost::hana::tuple<dims...> { private: template <gem::concepts::Dimension d1, gem::concepts::Dimension... rd> struct gem_dim_common_type { using type = std::common_type_t<typename d1::dim_t, typename gem_dim_common_type<rd...>::type>; }; // template <gem::concepts::Dimension d1> gem::concepts::Dimension {d1} struct gem_dim_common_type<d1> { using type = typename d1::dim_t; }; public: using type_t = DimensionTuple<T_flag, n_con, n_cov, dims...>; using base_t = boost::hana::tuple<dims...>; using common_t = typename gem_dim_common_type<dims...>::type; friend class cereal::access; public: static constexpr BOOST_HANA_CONSTANT_CHECK_MSG( (boost::hana::ullong_c<0> < boost::hana::ullong_c<sizeof...(dims)>), "At least one dimension must be specified."); using base_t::tuple; constexpr inline auto value(void) const noexcept { constexpr auto _value = [](auto && d) { return d.value(); }; return boost::hana::transform(*this, _value); } static constexpr inline auto get_max(void) noexcept { constexpr auto _max = [](auto && d) { return decltype(+d)::type::get_max(); }; return boost::hana::transform(boost::hana::tuple_t<dims...>, _max); } static constexpr inline auto get_min(void) noexcept { constexpr auto _min = [](auto && d) { return decltype(+d)::type::get_min(); }; return boost::hana::transform(boost::hana::tuple_t<dims...>, _min); } constexpr inline auto size(void) const noexcept { constexpr auto _mult = [](auto && acc, auto && d) { return acc * d; }; return boost::hana::fold(*this, _mult); } constexpr inline auto operator [](const auto & idx) const noexcept -> const std::enable_if_t<T_flag, decltype(base_t::operator[] ( boost::hana::ullong_c<sizeof...(dims)> - idx + GEM_START_IDX - boost::hana::ullong_c<1>))> & { return base_t::operator[] ( boost::hana::ullong_c<sizeof...(dims)> - idx + GEM_START_IDX - boost::hana::ullong_c<1>); } constexpr inline auto operator [](const auto & idx) const noexcept -> const std::enable_if_t<!T_flag, decltype(base_t::operator[] (idx - GEM_START_IDX))> & { return base_t::operator[] (idx - GEM_START_IDX); } private: template<class Archive> auto save(Archive & archive) const -> void { // archive(cereal::make_size_tag(n_con)); boost::hana::ullong_c<n_con>.times.with_index( [this, &archive](auto index) { // TODO: make the string concatenation compile time. archive(cereal::make_nvp("contravariant", this->operator[] (GEM_START_IDX + index))); }); boost::hana::ullong_c<n_cov>.times.with_index( [this, &archive](auto index) { // TODO: make the string concatenation compile time. archive(cereal::make_nvp("covariant", this->operator[] (GEM_START_IDX + boost::hana::ullong_c<n_con> + index))); }); } template<class Archive> auto load(Archive & archive) -> void { } }; } // namespage gem #endif // !GEM_DIMENSIONS_TUPLE_HPP_INCLUDED
29.479167
115
0.582332
RomainBrault
fa3a35933500e9a4c0035de671ededdfc82f1a41
15,054
inl
C++
include/Utopia/Asset/details/Serializer.inl
Justin-sky/Utopia
71912290155a469ad578234a1f5e1695804e04a3
[ "MIT" ]
null
null
null
include/Utopia/Asset/details/Serializer.inl
Justin-sky/Utopia
71912290155a469ad578234a1f5e1695804e04a3
[ "MIT" ]
null
null
null
include/Utopia/Asset/details/Serializer.inl
Justin-sky/Utopia
71912290155a469ad578234a1f5e1695804e04a3
[ "MIT" ]
1
2021-04-24T23:26:09.000Z
2021-04-24T23:26:09.000Z
#pragma once #include "../../Core/Traits.h" #include "../AssetMngr.h" #include "../../Core/Object.h" #include <variant> namespace Ubpa::Utopia::detail { template<typename Value> void WriteVar(const Value& var, Serializer::SerializeContext& ctx); template<typename UserType> void WriteUserType(const UserType* obj, Serializer::SerializeContext& ctx) { if constexpr (HasTypeInfo<UserType>::value) { ctx.writer.StartObject(); Ubpa::USRefl::TypeInfo<UserType>::ForEachVarOf( *obj, [&ctx](auto field, const auto& var) { ctx.writer.Key(field.name.data()); detail::WriteVar(var, ctx); } ); ctx.writer.EndObject(); } else { if (ctx.serializer.IsRegistered(GetID<UserType>())) ctx.serializer.Visit(GetID<UserType>(), obj, ctx); else { assert("not support" && false); ctx.writer.String(Serializer::Key::NOT_SUPPORT); } } } template<size_t Idx, typename Variant> bool WriteVariantAt(const Variant& var, size_t idx, Serializer::SerializeContext& ctx) { if (idx != Idx) return false; ctx.writer.StartObject(); ctx.writer.Key(Serializer::Key::INDEX); ctx.writer.Uint64(var.index()); ctx.writer.Key(Serializer::Key::CONTENT); WriteVar(std::get<std::variant_alternative_t<Idx, Variant>>(var), ctx); ctx.writer.EndObject(); return true; } // TODO : stop template<typename Variant, size_t... Ns> void WriteVariant(const Variant& var, std::index_sequence<Ns...>, Serializer::SerializeContext& ctx) { (WriteVariantAt<Ns>(var, var.index(), ctx), ...); } template<typename Value> void WriteVar(const Value& var, Serializer::SerializeContext& ctx) { if constexpr (std::is_floating_point_v<Value>) ctx.writer.Double(static_cast<double>(var)); else if constexpr (std::is_enum_v<Value>) WriteVar(static_cast<std::underlying_type_t<Value>>(var), ctx); else if constexpr (std::is_integral_v<Value>) { if constexpr (std::is_same_v<Value, bool>) ctx.writer.Bool(var); else { constexpr size_t size = sizeof(Value); if constexpr (std::is_unsigned_v<Value>) { if constexpr (size <= sizeof(unsigned int)) ctx.writer.Uint(static_cast<std::uint32_t>(var)); else ctx.writer.Uint64(static_cast<std::uint64_t>(var)); } else { if constexpr (size <= sizeof(int)) ctx.writer.Int(static_cast<std::int32_t>(var)); else ctx.writer.Int64(static_cast<std::int64_t>(var)); } } } else if constexpr (std::is_same_v<Value, std::string>) ctx.writer.String(var); else if constexpr (std::is_pointer_v<Value>) { if (var == nullptr) ctx.writer.Null(); else { assert("not support" && false); ctx.writer.Null(); } } else if constexpr (is_instance_of_v<Value, std::shared_ptr>) { using Element = typename Value::element_type; if (var == nullptr) ctx.writer.Null(); else { if constexpr (std::is_base_of_v<Object, Element>) { auto& assetMngr = AssetMngr::Instance(); const auto& path = assetMngr.GetAssetPath(*var); if (path.empty()) { ctx.writer.Null(); return; } ctx.writer.String(assetMngr.AssetPathToGUID(path).str()); } else { assert("not support" && false); ctx.writer.Null(); } } } else if constexpr (std::is_same_v<Value, UECS::Entity>) ctx.writer.Uint64(var.Idx()); else if constexpr (ArrayTraits<Value>::isArray) { ctx.writer.StartArray(); for (size_t i = 0; i < ArrayTraits<Value>::size; i++) WriteVar(ArrayTraits_Get(var, i), ctx); ctx.writer.EndArray(); } else if constexpr (OrderContainerTraits<Value>::isOrderContainer) { ctx.writer.StartArray(); auto iter_end = OrderContainerTraits_End(var); for (auto iter = OrderContainerTraits_Begin(var); iter != iter_end; iter++) WriteVar(*iter, ctx); ctx.writer.EndArray(); } else if constexpr (MapTraits<Value>::isMap) { auto iter_end = MapTraits_End(var); if constexpr (std::is_same_v<std::string, MapTraits_KeyType<Value>>) { ctx.writer.StartObject(); for (auto iter = MapTraits_Begin(var); iter != iter_end; ++iter) { const auto& key = MapTraits_Iterator_Key(iter); const auto& mapped = MapTraits_Iterator_Mapped(iter); ctx.writer.Key(key); WriteVar(mapped, ctx); } ctx.writer.EndObject(); } else { ctx.writer.StartArray(); for (auto iter = MapTraits_Begin(var); iter != iter_end; ++iter) { const auto& key = MapTraits_Iterator_Key(iter); const auto& mapped = MapTraits_Iterator_Mapped(iter); ctx.writer.StartObject(); ctx.writer.Key(Serializer::Key::KEY); WriteVar(key, ctx); ctx.writer.Key(Serializer::Key::MAPPED); WriteVar(mapped, ctx); ctx.writer.EndObject(); } ctx.writer.EndArray(); } } else if constexpr (TupleTraits<Value>::isTuple) { ctx.writer.StartArray(); std::apply([&](const auto& ... elements) { (WriteVar(elements, ctx), ...); }, var); ctx.writer.EndArray(); } else if constexpr (is_instance_of_v<Value, std::variant>) { constexpr size_t N = std::variant_size_v<Value>; WriteVariant(var, std::make_index_sequence<N>{}, ctx); } else WriteUserType(&var, ctx); } template<typename Value> void ReadVar(Value& var, const rapidjson::Value& jsonValueField, Serializer::DeserializeContext& ctx); template<size_t Idx, typename Variant> bool ReadVariantAt(Variant& var, size_t idx, const rapidjson::Value& jsonValueContent, Serializer::DeserializeContext& ctx) { if (idx != Idx) return false; std::variant_alternative_t<Idx, Variant> element; ReadVar(element, jsonValueContent, ctx); var = std::move(element); return true; } // TODO : stop template<typename Variant, size_t... Ns> void ReadVariant(Variant& var, std::index_sequence<Ns...>, const rapidjson::Value& jsonValueField, Serializer::DeserializeContext& ctx) { const auto& jsonObject = jsonValueField.GetObject(); size_t idx = jsonObject[Serializer::Key::INDEX].GetUint64(); const auto& jsonValueVariantData = jsonObject[Serializer::Key::CONTENT]; (ReadVariantAt<Ns>(var, idx, jsonValueVariantData, ctx), ...); } template<typename UserType> void ReadUserType(UserType* obj, const rapidjson::Value& jsonValueField, Serializer::DeserializeContext& ctx) { if constexpr (HasTypeInfo<UserType>::value) { const auto& jsonObject = jsonValueField.GetObject(); USRefl::TypeInfo<UserType>::ForEachVarOf( *obj, [&](auto field, auto& var) { auto target = jsonObject.FindMember(field.name.data()); if (target == jsonObject.MemberEnd()) return; ReadVar(var, target->value, ctx); } ); } else { if (ctx.deserializer.IsRegistered(GetID<UserType>())) ctx.deserializer.Visit(GetID<UserType>(), obj, jsonValueField, ctx); else assert("not support" && false); } } template<typename Value> void ReadVar(Value& var, const rapidjson::Value& jsonValueField, Serializer::DeserializeContext& ctx) { if constexpr (std::is_floating_point_v<Value>) var = static_cast<Value>(jsonValueField.GetDouble()); else if constexpr (std::is_enum_v<Value>) { std::underlying_type_t<Value> under; ReadVar(under, jsonValueField, ctx); var = static_cast<Value>(under); } else if constexpr (std::is_integral_v<Value>) { if constexpr (std::is_same_v<Value, bool>) var = jsonValueField.GetBool(); else { constexpr size_t size = sizeof(Value); if constexpr (std::is_unsigned_v<Value>) { if constexpr (size <= sizeof(unsigned int)) var = static_cast<Value>(jsonValueField.GetUint()); else var = static_cast<Value>(jsonValueField.GetUint64()); } else { if constexpr (size <= sizeof(int)) var = static_cast<Value>(jsonValueField.GetInt()); else var = static_cast<Value>(jsonValueField.GetInt64()); } } } else if constexpr (std::is_same_v<Value, std::string>) var = jsonValueField.GetString(); else if constexpr (std::is_pointer_v<Value>) { if (jsonValueField.IsNull()) var = nullptr; else { assert("not support" && false); } } else if constexpr (is_instance_of_v<Value, std::shared_ptr>) { if (jsonValueField.IsNull()) var = nullptr; else if (jsonValueField.IsString()) { using Asset = typename Value::element_type; std::string guid_str = jsonValueField.GetString(); const auto& path = AssetMngr::Instance().GUIDToAssetPath(xg::Guid{ guid_str }); var = AssetMngr::Instance().LoadAsset<Asset>(path); } else assert("not support" && false); } else if constexpr (std::is_same_v<Value, UECS::Entity>) { auto index = jsonValueField.GetUint64(); var = ctx.entityIdxMap.at(index); } else if constexpr (ArrayTraits<Value>::isArray) { const auto& arr = jsonValueField.GetArray(); size_t N = std::min<size_t>(arr.Size(), ArrayTraits<Value>::size); for (size_t i = 0; i < N; i++) ReadVar(ArrayTraits_Get(var, i), arr[static_cast<rapidjson::SizeType>(i)], ctx); } else if constexpr (OrderContainerTraits<Value>::isOrderContainer) { const auto& arr = jsonValueField.GetArray(); for (const auto& jsonValueElement : arr) { OrderContainerTraits_ValueType<Value> element; ReadVar(element, jsonValueElement, ctx); OrderContainerTraits_Add(var, std::move(element)); } OrderContainerTraits_PostProcess(var); } else if constexpr (MapTraits<Value>::isMap) { if constexpr (std::is_same_v<MapTraits_KeyType<Value>, std::string>) { const auto& m = jsonValueField.GetObject(); for (const auto& [val_key, val_mapped] : m) { MapTraits_MappedType<Value> mapped; ReadVar(mapped, val_mapped, ctx); MapTraits_Emplace( var, MapTraits_KeyType<Value>{val_key.GetString()}, std::move(mapped) ); } } else { const auto& m = jsonValueField.GetArray(); for (const auto& val_pair : m) { const auto& pair = val_pair.GetObject(); MapTraits_KeyType<Value> key; MapTraits_MappedType<Value> mapped; ReadVar(key, pair[Serializer::Key::KEY], ctx); ReadVar(mapped, pair[Serializer::Key::MAPPED], ctx); MapTraits_Emplace(var, std::move(key), std::move(mapped)); } } } else if constexpr (TupleTraits<Value>::isTuple) { std::apply([&](auto& ... elements) { const auto& arr = jsonValueField.GetArray(); rapidjson::SizeType i = 0; (ReadVar(elements, arr[i++], ctx), ...); }, var); } else if constexpr (is_instance_of_v<Value, std::variant>) { constexpr size_t N = std::variant_size_v<Value>; ReadVariant(var, std::make_index_sequence<N>{}, jsonValueField, ctx); } else ReadUserType(&var, jsonValueField, ctx); }; } namespace Ubpa::Utopia { template<typename Func> void Serializer::RegisterComponentSerializeFunction(Func&& func) { using ArgList = FuncTraits_ArgList<Func>; static_assert(Length_v<ArgList> == 2); static_assert(std::is_same_v<At_t<ArgList, 1>, SerializeContext&>); using ConstCmptPtr = At_t<ArgList, 0>; static_assert(std::is_pointer_v<ConstCmptPtr>); using ConstCmpt = std::remove_pointer_t<ConstCmptPtr>; static_assert(std::is_const_v<ConstCmpt>); using Cmpt = std::remove_const_t<ConstCmpt>; RegisterComponentSerializeFunction( UECS::CmptType::Of<Cmpt>, [f = std::forward<Func>(func)](const void* p, SerializeContext& ctx) { f(reinterpret_cast<const Cmpt*>(p), ctx); } ); } template<typename Func> void Serializer::RegisterComponentDeserializeFunction(Func&& func) { using ArgList = FuncTraits_ArgList<Func>; static_assert(Length_v<ArgList> == 3); static_assert(std::is_same_v<At_t<ArgList, 1>, const rapidjson::Value&>); static_assert(std::is_same_v<At_t<ArgList, 2>, DeserializeContext&>); using CmptPtr = At_t<ArgList, 0>; static_assert(std::is_pointer_v<CmptPtr>); using Cmpt = std::remove_pointer_t<CmptPtr>; static_assert(!std::is_const_v<Cmpt>); RegisterComponentDeserializeFunction( UECS::CmptType::Of<Cmpt>, [f = std::forward<Func>(func)](void* p, const rapidjson::Value& jsonValueCmpt, DeserializeContext& ctx) { f(reinterpret_cast<Cmpt*>(p), jsonValueCmpt, ctx); } ); } template<typename Func> void Serializer::RegisterUserTypeSerializeFunction(Func&& func) { using ArgList = FuncTraits_ArgList<Func>; static_assert(Length_v<ArgList> == 2); static_assert(std::is_same_v<At_t<ArgList, 1>, SerializeContext&>); using ConstUserTypePtr = At_t<ArgList, 0>; static_assert(std::is_pointer_v<ConstUserTypePtr>); using ConstUserType = std::remove_pointer_t<ConstUserTypePtr>; static_assert(std::is_const_v<ConstUserType>); using UserType = std::remove_const_t<ConstUserType>; RegisterUserTypeSerializeFunction( GetID<UserType>(), [f = std::forward<Func>(func)](const void* p, SerializeContext& ctx) { f(reinterpret_cast<const UserType*>(p), ctx); } ); } template<typename Func> void Serializer::RegisterUserTypeDeserializeFunction(Func&& func) { using ArgList = FuncTraits_ArgList<Func>; static_assert(Length_v<ArgList> == 3); static_assert(std::is_same_v<At_t<ArgList, 1>, const rapidjson::Value&>); static_assert(std::is_same_v<At_t<ArgList, 2>, DeserializeContext&>); using UserTypePtr = At_t<ArgList, 0>; static_assert(std::is_pointer_v<UserTypePtr>); using UserType = std::remove_pointer_t<UserTypePtr>; static_assert(!std::is_const_v<UserType>); RegisterUserTypeDeserializeFunction( GetID<UserType>(), [f = std::forward<Func>(func)](void* p, const rapidjson::Value& jsonValueCmpt, DeserializeContext& ctx) { f(reinterpret_cast<UserType*>(p), jsonValueCmpt, ctx); } ); } template<typename... Cmpts> void Serializer::RegisterComponentSerializeFunction() { (RegisterComponentSerializeFunction(&detail::WriteUserType<Cmpts>), ...); } template<typename... Cmpts> void Serializer::RegisterComponentDeserializeFunction() { (RegisterComponentDeserializeFunction(&detail::ReadUserType<Cmpts>), ...); } template<typename... UserTypes> void Serializer::RegisterUserTypeSerializeFunction() { (RegisterUserTypeSerializeFunction(&detail::WriteUserType<UserTypes>), ...); } template<typename... UserTypes> void Serializer::RegisterUserTypeDeserializeFunction() { (RegisterUserTypeDeserializeFunction(&detail::ReadUserType<UserTypes>), ...); } template<typename... Cmpts> void Serializer::RegisterComponents() { RegisterComponentSerializeFunction<Cmpts...>(); RegisterComponentDeserializeFunction<Cmpts...>(); } // register UserTypes' serialize and deserialize function template<typename... UserTypes> void Serializer::RegisterUserTypes() { RegisterUserTypeSerializeFunction<UserTypes...>(); RegisterUserTypeDeserializeFunction<UserTypes...>(); } template<typename UserType> std::string Serializer::ToJSON(const UserType* obj) { static_assert(!std::is_void_v<UserType>); return ToJSON(GetID<UserType>(), obj); } template<typename UserType> bool Serializer::ToUserType(std::string_view json, UserType* obj) { static_assert(!std::is_void_v<UserType>); return ToUserType(json, GetID<UserType>(), obj); } }
33.905405
138
0.692906
Justin-sky
fa3dc17feac4ff12716e3254a9915d340fb8893f
6,913
cxx
C++
test/core/communication/BeaconSendingCaptureOffStateTest.cxx
stefaneberl/openkit-native
1dc042141f4990508742a89aacafda9b2a29aaaf
[ "Apache-2.0" ]
null
null
null
test/core/communication/BeaconSendingCaptureOffStateTest.cxx
stefaneberl/openkit-native
1dc042141f4990508742a89aacafda9b2a29aaaf
[ "Apache-2.0" ]
null
null
null
test/core/communication/BeaconSendingCaptureOffStateTest.cxx
stefaneberl/openkit-native
1dc042141f4990508742a89aacafda9b2a29aaaf
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2018-2020 Dynatrace LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "CustomMatchers.h" #include "mock/MockIBeaconSendingContext.h" #include "../../protocol/mock/MockIHTTPClient.h" #include "../../protocol/mock/MockIStatusResponse.h" #include "core/communication/IBeaconSendingState.h" #include "core/communication/BeaconSendingCaptureOffState.h" #include "gtest/gtest.h" #include "gmock/gmock.h" using namespace test; using BeaconSendingCaptureOffState_t = core::communication::BeaconSendingCaptureOffState; using IBeaconSendingState_t = core::communication::IBeaconSendingState; using IBeaconSendingState_sp = std::shared_ptr<IBeaconSendingState_t>; using IStatusResponse_t = protocol::IStatusResponse; using MockNiceIBeaconSendingContext_sp = std::shared_ptr<testing::NiceMock<MockIBeaconSendingContext>>; using MockNiceIHttpClient_sp = std::shared_ptr<testing::NiceMock<MockIHTTPClient>>; class BeaconSendingCaptureOffStateTest : public testing::Test { protected: MockNiceIBeaconSendingContext_sp mockContext; MockNiceIHttpClient_sp mockHTTPClient; void SetUp() override { mockHTTPClient = MockIHTTPClient::createNice(); ON_CALL(*mockHTTPClient, sendStatusRequest()) .WillByDefault(testing::Return(MockIStatusResponse::createNice())); mockContext = MockIBeaconSendingContext::createNice(); ON_CALL(*mockContext, getHTTPClient()) .WillByDefault(testing::Return(mockHTTPClient)); } }; TEST_F(BeaconSendingCaptureOffStateTest, aBeaconSendingCaptureOffStateIsNotATerminalState) { // given BeaconSendingCaptureOffState_t target; // when auto obtained = target.isTerminalState(); // then ASSERT_THAT(obtained, testing::Eq(false)); } TEST_F(BeaconSendingCaptureOffStateTest, getStateNameGivesStatesName) { // given auto target = BeaconSendingCaptureOffState_t(); // when auto obtained = target.getStateName(); // then ASSERT_THAT(obtained, testing::StrEq("CaptureOff")); } TEST_F(BeaconSendingCaptureOffStateTest, aBeaconSendingCaptureOffStateHasTerminalStateBeaconSendingFlushSessions) { // given BeaconSendingCaptureOffState_t target; // when auto obtained = target.getShutdownState(); // then ASSERT_THAT(obtained, testing::NotNull()); ASSERT_THAT(obtained->getStateType(), testing::Eq(IBeaconSendingState_t::StateType::BEACON_SENDING_FLUSH_SESSIONS_STATE)); } TEST_F(BeaconSendingCaptureOffStateTest, aBeaconSendingCaptureOffStateTransitionsToCaptureOnStateWhenCapturingActive) { // given ON_CALL(*mockContext, isCaptureOn()) .WillByDefault(testing::Return(true)); auto target = BeaconSendingCaptureOffState_t(); // expect EXPECT_CALL(*mockContext, disableCaptureAndClear()) .Times(::testing::Exactly(1)); EXPECT_CALL(*mockContext, setLastStatusCheckTime(testing::_)) .Times(testing::Exactly(1)); EXPECT_CALL(*mockContext, setNextState(IsABeaconSendingCaptureOnState())) .Times(testing::Exactly(1)); // when target.execute(*mockContext); } TEST_F(BeaconSendingCaptureOffStateTest, getSleepTimeInMillisecondsReturnsMinusOneForDefaultConstructor) { // given auto target = BeaconSendingCaptureOffState_t(); // when auto obtained = target.getSleepTimeInMilliseconds(); // then ASSERT_EQ(int64_t(-1), obtained); } TEST_F(BeaconSendingCaptureOffStateTest, getSleepTimeInMillisecondsReturnsSleepTimeSetInConstructor) { // given int64_t sleepTime = 654321; auto target = BeaconSendingCaptureOffState_t(sleepTime); // when auto obtained = target.getSleepTimeInMilliseconds(); // then ASSERT_THAT(obtained, testing::Eq(sleepTime)); } TEST_F(BeaconSendingCaptureOffStateTest, aBeaconSendingCaptureOffStateWaitsForGivenTime) { // with int64_t sleepTime = 1234; ON_CALL(*mockContext, isCaptureOn()) .WillByDefault(testing::Return(true)); // expect EXPECT_CALL(*mockContext, sleep(testing::Eq(sleepTime))) .Times(testing::Exactly(1)); // given BeaconSendingCaptureOffState_t target(sleepTime); // when target.execute(*mockContext); } TEST_F(BeaconSendingCaptureOffStateTest, aBeaconSendingCaptureOffStateStaysInOffStateWhenServerRespondsWithTooManyRequests) { // with int64_t sleepTime = 1234; auto statusResponse = MockIStatusResponse::createNice(); ON_CALL(*statusResponse, getResponseCode()) .WillByDefault(testing::Return(429)); ON_CALL(*statusResponse, isTooManyRequestsResponse()) .WillByDefault(testing::Return(true)); ON_CALL(*statusResponse, isErroneousResponse()) .WillByDefault(testing::Return(true)); ON_CALL(*statusResponse, getRetryAfterInMilliseconds()) .WillByDefault(testing::Return(sleepTime)); ON_CALL(*mockHTTPClient, sendStatusRequest()) .WillByDefault(testing::Return(statusResponse)); ON_CALL(*mockContext, isCaptureOn()) .WillByDefault(testing::Return(false)); // expect IBeaconSendingState_sp savedNextState = nullptr; EXPECT_CALL(*mockContext, setNextState(IsABeaconSendingCaptureOffState())) .Times(testing::Exactly(1)) .WillOnce(testing::SaveArg<0>(&savedNextState)); // given auto target = BeaconSendingCaptureOffState_t(int64_t(12345)); // when calling execute target.execute(*mockContext); // verify captured state ASSERT_THAT(savedNextState, testing::NotNull()); ASSERT_THAT( std::static_pointer_cast<BeaconSendingCaptureOffState_t>(savedNextState)->getSleepTimeInMilliseconds(), testing::Eq(sleepTime) ); } TEST_F(BeaconSendingCaptureOffStateTest, aBeaconSendingCaptureOffStateDoesDoesNotExecuteStatusRequestWhenInterruptedDuringSleep) { // with ON_CALL(*mockContext, isCaptureOn()) .WillByDefault(testing::Return(false)); EXPECT_CALL(*mockContext, isShutdownRequested()) .WillOnce(testing::Return(false)) .WillRepeatedly(testing::Return(true)); // expect EXPECT_CALL(*mockContext, disableCaptureAndClear()) .Times(::testing::Exactly(1)); // also verify that lastStatusCheckTime was updated EXPECT_CALL(*mockContext, setLastStatusCheckTime(testing::_)) .Times(testing::Exactly(0)); // verify the sleep - since this is not multi-threaded, the sleep time is still the full time EXPECT_CALL(*mockContext, sleep(7200000L)) .Times(testing::Exactly(1)); // verify that after sleeping the transition to IsABeaconSendingFlushSessionsState works EXPECT_CALL(*mockContext, setNextState(IsABeaconSendingFlushSessionsState())) .Times(testing::Exactly(1)); // given auto target = BeaconSendingCaptureOffState_t(); // when calling execute target.execute(*mockContext); }
30.861607
128
0.789093
stefaneberl
fa3e29946fa64171c7ebbacb839e3ad604f64dcb
394
hpp
C++
src/random/circle2d.hpp
degarashi/beat
456cc4469067509f0746fbe4eca0d3a0879cb894
[ "MIT" ]
null
null
null
src/random/circle2d.hpp
degarashi/beat
456cc4469067509f0746fbe4eca0d3a0879cb894
[ "MIT" ]
null
null
null
src/random/circle2d.hpp
degarashi/beat
456cc4469067509f0746fbe4eca0d3a0879cb894
[ "MIT" ]
null
null
null
#pragma once #include "../circle2d.hpp" #include "frea/src/random/vector.hpp" namespace beat { namespace g2 { namespace random { template <class RDP, class RDR> Circle GenCircle(RDP&& rdp, RDR&& rdr) { return { frea::random::GenVec<Vec2>(rdp), std::abs(rdr()) }; } template <class RD> Circle GenCircle(RD&& rd) { return GenCircle(rd, rd); } } } }
17.909091
43
0.604061
degarashi
fa46c8fff2cb0b267e223c7e0da5de4bb2d10b5b
5,356
cpp
C++
xCode/OpenGL/MD2 animation/Classes/QR_Engine/QR_3D/QR_Renderer/QR_Renderer_OpenGL.cpp
Jeanmilost/Demos
2b71f6edc85948540660d290183530fd846262ad
[ "MIT" ]
1
2022-03-22T14:41:15.000Z
2022-03-22T14:41:15.000Z
xCode/OpenGL/MD2 animation/Classes/QR_Engine/QR_3D/QR_Renderer/QR_Renderer_OpenGL.cpp
Jeanmilost/Demos
2b71f6edc85948540660d290183530fd846262ad
[ "MIT" ]
null
null
null
xCode/OpenGL/MD2 animation/Classes/QR_Engine/QR_3D/QR_Renderer/QR_Renderer_OpenGL.cpp
Jeanmilost/Demos
2b71f6edc85948540660d290183530fd846262ad
[ "MIT" ]
null
null
null
/****************************************************************************** * ==> QR_Renderer_OpenGL ----------------------------------------------------* ****************************************************************************** * Description : Specialized OpenGL renderer * * Developer : Jean-Milost Reymond * ******************************************************************************/ #include "QR_Renderer_OpenGL.h" // std #include <sstream> #include <cmath> // qr engine #include "QR_Exception.h" // openGL #ifdef _WIN32 #include <gl/gl.h> #elif defined (__APPLE__) #ifdef USE_OPENGL_DIRECT_MODE #include </Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS9.3.sdk/System/Library/Frameworks/OpenGLES.framework/Headers/ES1/gl.h> #else #include <ES2/gl.h> #include <ES2/glext.h> #endif // USE_OPENGL_DIRECT_MODE #endif // _WIN32 / __APPLE__ #ifdef USE_GLFW_LIBRARY #include <gl/glfw.h> #endif // USE_GLFW_LIBRARY //------------------------------------------------------------------------------ // Class QR_Renderer_OpenGL - c++ cross-platform //------------------------------------------------------------------------------ QR_Renderer_OpenGL::QR_Renderer_OpenGL() : QR_Renderer() {} //------------------------------------------------------------------------------ #ifdef _WIN32 QR_Renderer_OpenGL::QR_Renderer_OpenGL(HWND hWnd, ITfOnConfigure fOnConfigure) : QR_Renderer(), m_hWnd(hWnd) #ifndef USE_GLFW_LIBRARY , m_hDC(NULL), m_hRC(NULL) #endif // USE_GLFW_LIBRARY { Initialize(fOnConfigure); } #endif // defined(_WIN32) //------------------------------------------------------------------------------ QR_Renderer_OpenGL::~QR_Renderer_OpenGL() { #if defined(_WIN32) && !defined(USE_GLFW_LIBRARY) // release OpenGL context ::wglMakeCurrent(NULL, NULL); // delete OpenGL context if (m_hRC) wglDeleteContext(m_hRC); // delete device context if (m_hWnd && m_hDC) ::ReleaseDC(m_hWnd, m_hDC); #endif // defined(_WIN32) && !defined(USE_GLFW_LIBRARY) } //------------------------------------------------------------------------------ void QR_Renderer_OpenGL::BeginScene(const QR_Color& color, IESceneFlags flags) const { // begin post-processing effect if (m_pPostProcessingEffect) m_pPostProcessingEffect->Begin(); GLbitfield openGLSceneFlags = 0; // clear background color, if needed if (flags & IE_SF_ClearColor) { glClearColor((GLclampf)color.GetRedF(), (GLclampf)color.GetGreenF(), (GLclampf)color.GetBlueF(), (GLclampf)color.GetAlphaF()); openGLSceneFlags |= GL_COLOR_BUFFER_BIT; } // clear Z buffer, if needed if (flags & IE_SF_ClearDepth) { #ifdef __APPLE__ glClearDepthf(1.0f); #else glClearDepth(1.0f); #endif openGLSceneFlags |= GL_DEPTH_BUFFER_BIT; } // clear scene, fill with background color and set render flags glClear(openGLSceneFlags); } //------------------------------------------------------------------------------ void QR_Renderer_OpenGL::EndScene() const { // end post-processing effect if (m_pPostProcessingEffect) m_pPostProcessingEffect->End(); #if defined(_WIN32) #ifdef USE_GLFW_LIBRARY // swap the display buffers (displays what was just drawn) glfwSwapBuffers(); #else // no device context? if (!m_hDC) return; // present back buffer ::SwapBuffers(m_hDC); #endif // USE_GLFW_LIBRARY #elif defined(__APPLE__) // nothing to do, Apple OpenGLES implementation does everything for us #else #error "Do implement EndScene() for this platform" #endif } //------------------------------------------------------------------------------ void QR_Renderer_OpenGL::Initialize(ITfOnConfigure fOnConfigure) { #if defined(_WIN32) && !defined(USE_GLFW_LIBRARY) ::PIXELFORMATDESCRIPTOR pfd; QR_Int32 iFormat; // get device context m_hDC = ::GetDC(m_hWnd); // set device context pixel format ::ZeroMemory(&pfd, sizeof(pfd)); pfd.nSize = sizeof(pfd); pfd.nVersion = 1; pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 32; pfd.cDepthBits = 32; pfd.cStencilBits = 32; pfd.iLayerType = PFD_MAIN_PLANE; iFormat = ::ChoosePixelFormat(m_hDC, &pfd); ::SetPixelFormat(m_hDC, iFormat, &pfd); // create and enable OpenGL render context m_hRC = ::wglCreateContext(m_hDC); ::wglMakeCurrent(m_hDC, m_hRC); // notify that OpenGL can be configured if (fOnConfigure) fOnConfigure(this); #endif // defined(_WIN32) && !defined(USE_GLFW_LIBRARY) } //------------------------------------------------------------------------------
33.475
182
0.504294
Jeanmilost
fa489af4f8db0e9a17c8f717b03531ecba92e495
5,549
cxx
C++
Plugins/VR/vtkVRActiveObjectManipulationStyle.cxx
XiaoboFu/ParaViewGeo
0089927885fd67a3d70a22a28977a291bed3fcdd
[ "BSD-2-Clause", "BSD-3-Clause" ]
17
2015-02-17T00:30:26.000Z
2022-03-17T06:13:02.000Z
Plugins/VR/vtkVRActiveObjectManipulationStyle.cxx
ObjectivitySRC/ParaViewGeo
0089927885fd67a3d70a22a28977a291bed3fcdd
[ "BSD-2-Clause", "BSD-3-Clause" ]
null
null
null
Plugins/VR/vtkVRActiveObjectManipulationStyle.cxx
ObjectivitySRC/ParaViewGeo
0089927885fd67a3d70a22a28977a291bed3fcdd
[ "BSD-2-Clause", "BSD-3-Clause" ]
10
2015-08-31T18:20:17.000Z
2022-02-02T15:16:21.000Z
#include "vtkVRActiveObjectManipulationStyle.h" #include "pqActiveObjects.h" #include "pqDataRepresentation.h" #include "pqView.h" #include "vtkCamera.h" #include "vtkMath.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkSMDoubleVectorProperty.h" #include "vtkSMPropertyHelper.h" #include "vtkSMRenderViewProxy.h" #include "vtkSMRepresentationProxy.h" #include "vtkVRQueue.h" vtkVRActiveObjectManipulationStyle::vtkVRActiveObjectManipulationStyle(QObject* parentObject) : Superclass(parentObject) { } vtkVRActiveObjectManipulationStyle::~vtkVRActiveObjectManipulationStyle() { } // ---------------------------------------------------------------------------- // This handler currently only get the bool vtkVRActiveObjectManipulationStyle::handleEvent(const vtkVREventData& data) { switch( data.eventType ) { case BUTTON_EVENT: this->HandleButton( data ); break; case ANALOG_EVENT: this->HandleAnalog( data ); break; case TRACKER_EVENT: this->HandleTracker( data ); break; } return false; } // ---------------------------------------------------------------------------- void vtkVRActiveObjectManipulationStyle::HandleTracker( const vtkVREventData& data ) { } // ---------------------------------------------------------------------------- void vtkVRActiveObjectManipulationStyle::HandleButton( const vtkVREventData& data ) { } // ---------------------------------------------------------------------------- void vtkVRActiveObjectManipulationStyle::HandleAnalog( const vtkVREventData& data ) { HandleSpaceNavigatorAnalog(data); } // -------------------------------------------------------------------------fun vtkAnalog AugmentChannelsToRetainLargestMagnitude(const vtkAnalog t) { vtkAnalog at; // Make a list of the magnitudes into at for(int i=0;i<6;++i) { if(t.channel[i] < 0.0) at.channel[i] = t.channel[i]*-1; else at.channel[i]= t.channel[i]; } // Get the max value; int max =0; for(int i=1;i<6;++i) { if(at.channel[i] > at.channel[max]) max = i; } // copy the max value of t into at (rest are 0) for (int i = 0; i < 6; ++i) { (i==max)?at.channel[i]=t.channel[i]:at.channel[i]=0.0; } return at; } void vtkVRActiveObjectManipulationStyle::HandleSpaceNavigatorAnalog( const vtkVREventData& data ) { vtkAnalog at = AugmentChannelsToRetainLargestMagnitude(data.data.analog); pqView *view = 0; pqDataRepresentation *rep =0; view = pqActiveObjects::instance().activeView(); rep = pqActiveObjects::instance().activeRepresentation(); if(rep) { vtkCamera* camera; double pos[3], up[3], dir[3]; double orient[3]; vtkSMRenderViewProxy *viewProxy = 0; vtkSMRepresentationProxy *repProxy = 0; viewProxy = vtkSMRenderViewProxy::SafeDownCast( view->getViewProxy() ); repProxy = vtkSMRepresentationProxy::SafeDownCast(rep->getProxy()); if ( repProxy && viewProxy ) { vtkSMPropertyHelper(repProxy,"Position").Get(pos,3); vtkSMPropertyHelper(repProxy,"Orientation").Get(orient,3); camera = viewProxy->GetActiveCamera(); camera->GetDirectionOfProjection(dir); camera->OrthogonalizeViewUp(); camera->GetViewUp(up); for (int i = 0; i < 3; i++) { double dx = -0.01*at.channel[2]*up[i]; pos[i] += dx; } double r[3]; vtkMath::Cross(dir, up, r); for (int i = 0; i < 3; i++) { double dx = 0.01*at.channel[0]*r[i]; pos[i] += dx; } for(int i=0;i<3;++i) { double dx = -0.01*at.channel[1]*dir[i]; pos[i] +=dx; } // pos[0] += at.channel[0]; // pos[1] += at.channel[1]; // pos[2] += at.channel[2]; orient[0] += 4.0*at.channel[3]; orient[1] += 4.0*at.channel[5]; orient[2] += 4.0*at.channel[4]; vtkSMPropertyHelper(repProxy,"Position").Set(pos,3); vtkSMPropertyHelper(repProxy,"Orientation").Set(orient,3); repProxy->UpdateVTKObjects(); } } else if ( view ) { vtkSMRenderViewProxy *viewProxy = 0; viewProxy = vtkSMRenderViewProxy::SafeDownCast( view->getViewProxy() ); if ( viewProxy ) { vtkCamera* camera; double pos[3], fp[3], up[3], dir[3]; camera = viewProxy->GetActiveCamera(); camera->GetPosition(pos); camera->GetFocalPoint(fp); camera->GetDirectionOfProjection(dir); camera->OrthogonalizeViewUp(); camera->GetViewUp(up); for (int i = 0; i < 3; i++) { double dx = 0.01*at.channel[2]*up[i]; pos[i] += dx; fp[i] += dx; } // Apply right-left motion double r[3]; vtkMath::Cross(dir, up, r); for (int i = 0; i < 3; i++) { double dx = -0.01*at.channel[0]*r[i]; pos[i] += dx; fp[i] += dx; } camera->SetPosition(pos); camera->SetFocalPoint(fp); camera->Dolly(pow(1.01,at.channel[1])); camera->Elevation( 4.0*at.channel[3]); camera->Azimuth( 4.0*at.channel[5]); camera->Roll( 4.0*at.channel[4]); } } } bool vtkVRActiveObjectManipulationStyle::update() { vtkSMRenderViewProxy *proxy =0; pqView *view = 0; view = pqActiveObjects::instance().activeView(); if ( view ) { proxy = vtkSMRenderViewProxy::SafeDownCast( view->getViewProxy() ); if ( proxy ) { proxy->UpdateVTKObjects(); proxy->StillRender(); } } return false; }
25.809302
97
0.575419
XiaoboFu
fa4d36c4a7e221fbcc362d618b503c54efa5f56d
14,096
hpp
C++
include/GlobalNamespace/StandardScoreSyncStateDeltaNetSerializable.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/StandardScoreSyncStateDeltaNetSerializable.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/StandardScoreSyncStateDeltaNetSerializable.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: LiteNetLib.Utils.INetSerializable #include "LiteNetLib/Utils/INetSerializable.hpp" // Including type: IPoolablePacket #include "GlobalNamespace/IPoolablePacket.hpp" // Including type: ISyncStateDeltaSerializable`1 #include "GlobalNamespace/ISyncStateDeltaSerializable_1.hpp" // Including type: StandardScoreSyncState #include "GlobalNamespace/StandardScoreSyncState.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: GlobalNamespace namespace GlobalNamespace { // Forward declaring type: IPacketPool`1<T> template<typename T> class IPacketPool_1; } // Forward declaring namespace: LiteNetLib::Utils namespace LiteNetLib::Utils { // Forward declaring type: NetDataWriter class NetDataWriter; // Forward declaring type: NetDataReader class NetDataReader; } // Completed forward declares // Type namespace: namespace GlobalNamespace { // Forward declaring type: StandardScoreSyncStateDeltaNetSerializable class StandardScoreSyncStateDeltaNetSerializable; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable); DEFINE_IL2CPP_ARG_TYPE(::GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable*, "", "StandardScoreSyncStateDeltaNetSerializable"); // Type namespace: namespace GlobalNamespace { // Size: 0x2C #pragma pack(push, 1) // Autogenerated type: StandardScoreSyncStateDeltaNetSerializable // [TokenAttribute] Offset: FFFFFFFF class StandardScoreSyncStateDeltaNetSerializable : public ::Il2CppObject/*, public ::LiteNetLib::Utils::INetSerializable, public ::GlobalNamespace::IPoolablePacket, public ::GlobalNamespace::ISyncStateDeltaSerializable_1<::GlobalNamespace::StandardScoreSyncState>*/ { public: #ifdef USE_CODEGEN_FIELDS public: #else #ifdef CODEGEN_FIELD_ACCESSIBILITY CODEGEN_FIELD_ACCESSIBILITY: #else protected: #endif #endif // private StandardScoreSyncState _delta // Size: 0x14 // Offset: 0x10 ::GlobalNamespace::StandardScoreSyncState delta; // Field size check static_assert(sizeof(::GlobalNamespace::StandardScoreSyncState) == 0x14); // private SyncStateId <baseId>k__BackingField // Size: 0x1 // Offset: 0x24 ::GlobalNamespace::SyncStateId baseId; // Field size check static_assert(sizeof(::GlobalNamespace::SyncStateId) == 0x1); // Padding between fields: baseId and: timeOffsetMs char __padding1[0x3] = {}; // private System.Int32 <timeOffsetMs>k__BackingField // Size: 0x4 // Offset: 0x28 int timeOffsetMs; // Field size check static_assert(sizeof(int) == 0x4); public: // Creating interface conversion operator: operator ::LiteNetLib::Utils::INetSerializable operator ::LiteNetLib::Utils::INetSerializable() noexcept { return *reinterpret_cast<::LiteNetLib::Utils::INetSerializable*>(this); } // Creating interface conversion operator: operator ::GlobalNamespace::IPoolablePacket operator ::GlobalNamespace::IPoolablePacket() noexcept { return *reinterpret_cast<::GlobalNamespace::IPoolablePacket*>(this); } // Creating interface conversion operator: operator ::GlobalNamespace::ISyncStateDeltaSerializable_1<::GlobalNamespace::StandardScoreSyncState> operator ::GlobalNamespace::ISyncStateDeltaSerializable_1<::GlobalNamespace::StandardScoreSyncState>() noexcept { return *reinterpret_cast<::GlobalNamespace::ISyncStateDeltaSerializable_1<::GlobalNamespace::StandardScoreSyncState>*>(this); } // Get instance field reference: private StandardScoreSyncState _delta ::GlobalNamespace::StandardScoreSyncState& dyn__delta(); // Get instance field reference: private SyncStateId <baseId>k__BackingField ::GlobalNamespace::SyncStateId& dyn_$baseId$k__BackingField(); // Get instance field reference: private System.Int32 <timeOffsetMs>k__BackingField int& dyn_$timeOffsetMs$k__BackingField(); // static public IPacketPool`1<StandardScoreSyncStateDeltaNetSerializable> get_pool() // Offset: 0x25F09E4 static ::GlobalNamespace::IPacketPool_1<::GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable*>* get_pool(); // public SyncStateId get_baseId() // Offset: 0x25F0A2C ::GlobalNamespace::SyncStateId get_baseId(); // public System.Void set_baseId(SyncStateId value) // Offset: 0x25F0A34 void set_baseId(::GlobalNamespace::SyncStateId value); // public System.Int32 get_timeOffsetMs() // Offset: 0x25F0A3C int get_timeOffsetMs(); // public System.Void set_timeOffsetMs(System.Int32 value) // Offset: 0x25F0A44 void set_timeOffsetMs(int value); // public StandardScoreSyncState get_delta() // Offset: 0x25F0A4C ::GlobalNamespace::StandardScoreSyncState get_delta(); // public System.Void set_delta(StandardScoreSyncState value) // Offset: 0x25F0A60 void set_delta(::GlobalNamespace::StandardScoreSyncState value); // public System.Void Serialize(LiteNetLib.Utils.NetDataWriter writer) // Offset: 0x25F0A74 void Serialize(::LiteNetLib::Utils::NetDataWriter* writer); // public System.Void Deserialize(LiteNetLib.Utils.NetDataReader reader) // Offset: 0x25F0B5C void Deserialize(::LiteNetLib::Utils::NetDataReader* reader); // public System.Void Release() // Offset: 0x25F0C00 void Release(); // public System.Void .ctor() // Offset: 0x25F0CBC // Implemented from: System.Object // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static StandardScoreSyncStateDeltaNetSerializable* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<StandardScoreSyncStateDeltaNetSerializable*, creationType>())); } }; // StandardScoreSyncStateDeltaNetSerializable #pragma pack(pop) static check_size<sizeof(StandardScoreSyncStateDeltaNetSerializable), 40 + sizeof(int)> __GlobalNamespace_StandardScoreSyncStateDeltaNetSerializableSizeCheck; static_assert(sizeof(StandardScoreSyncStateDeltaNetSerializable) == 0x2C); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::get_pool // Il2CppName: get_pool template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::GlobalNamespace::IPacketPool_1<::GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable*>* (*)()>(&GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::get_pool)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable*), "get_pool", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::get_baseId // Il2CppName: get_baseId template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::GlobalNamespace::SyncStateId (GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::*)()>(&GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::get_baseId)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable*), "get_baseId", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::set_baseId // Il2CppName: set_baseId template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::*)(::GlobalNamespace::SyncStateId)>(&GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::set_baseId)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("", "SyncStateId")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable*), "set_baseId", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::get_timeOffsetMs // Il2CppName: get_timeOffsetMs template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::*)()>(&GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::get_timeOffsetMs)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable*), "get_timeOffsetMs", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::set_timeOffsetMs // Il2CppName: set_timeOffsetMs template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::*)(int)>(&GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::set_timeOffsetMs)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable*), "set_timeOffsetMs", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::get_delta // Il2CppName: get_delta template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::GlobalNamespace::StandardScoreSyncState (GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::*)()>(&GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::get_delta)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable*), "get_delta", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::set_delta // Il2CppName: set_delta template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::*)(::GlobalNamespace::StandardScoreSyncState)>(&GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::set_delta)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("", "StandardScoreSyncState")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable*), "set_delta", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::Serialize // Il2CppName: Serialize template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::*)(::LiteNetLib::Utils::NetDataWriter*)>(&GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::Serialize)> { static const MethodInfo* get() { static auto* writer = &::il2cpp_utils::GetClassFromName("LiteNetLib.Utils", "NetDataWriter")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable*), "Serialize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{writer}); } }; // Writing MetadataGetter for method: GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::Deserialize // Il2CppName: Deserialize template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::*)(::LiteNetLib::Utils::NetDataReader*)>(&GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::Deserialize)> { static const MethodInfo* get() { static auto* reader = &::il2cpp_utils::GetClassFromName("LiteNetLib.Utils", "NetDataReader")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable*), "Deserialize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{reader}); } }; // Writing MetadataGetter for method: GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::Release // Il2CppName: Release template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::*)()>(&GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::Release)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable*), "Release", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::StandardScoreSyncStateDeltaNetSerializable::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
60.239316
270
0.769154
RedBrumbler