hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
fe6bb5ba44173c7c781536096f4236d85dd87044
32,477
cc
C++
content/common/gpu/gpu_channel.cc
nagineni/chromium-crosswalk
5725642f1c67d0f97e8613ec1c3e8107ab53fdf8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
4
2017-04-05T01:51:34.000Z
2018-02-15T03:11:54.000Z
content/common/gpu/gpu_channel.cc
nagineni/chromium-crosswalk
5725642f1c67d0f97e8613ec1c3e8107ab53fdf8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-12-13T19:44:12.000Z
2021-12-13T19:44:12.000Z
content/common/gpu/gpu_channel.cc
nagineni/chromium-crosswalk
5725642f1c67d0f97e8613ec1c3e8107ab53fdf8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
4
2017-04-05T01:52:03.000Z
2022-02-13T17:58:45.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #if defined(OS_WIN) #include <windows.h> #endif #include "content/common/gpu/gpu_channel.h" #include <queue> #include <vector> #include "base/bind.h" #include "base/command_line.h" #include "base/debug/trace_event.h" #include "base/message_loop/message_loop_proxy.h" #include "base/rand_util.h" #include "base/strings/string_util.h" #include "base/timer/timer.h" #include "content/common/gpu/gpu_channel_manager.h" #include "content/common/gpu/gpu_messages.h" #include "content/common/gpu/media/gpu_video_encode_accelerator.h" #include "content/common/gpu/sync_point_manager.h" #include "content/public/common/content_switches.h" #include "crypto/hmac.h" #include "gpu/command_buffer/common/mailbox.h" #include "gpu/command_buffer/service/gpu_scheduler.h" #include "gpu/command_buffer/service/image_manager.h" #include "gpu/command_buffer/service/mailbox_manager.h" #include "ipc/ipc_channel.h" #include "ipc/ipc_channel_proxy.h" #include "ui/gl/gl_context.h" #include "ui/gl/gl_image.h" #include "ui/gl/gl_surface.h" #if defined(OS_POSIX) #include "ipc/ipc_channel_posix.h" #endif #if defined(OS_ANDROID) #include "content/common/gpu/stream_texture_manager_android.h" #endif namespace content { namespace { // Number of milliseconds between successive vsync. Many GL commands block // on vsync, so thresholds for preemption should be multiples of this. const int64 kVsyncIntervalMs = 17; // Amount of time that we will wait for an IPC to be processed before // preempting. After a preemption, we must wait this long before triggering // another preemption. const int64 kPreemptWaitTimeMs = 2 * kVsyncIntervalMs; // Once we trigger a preemption, the maximum duration that we will wait // before clearing the preemption. const int64 kMaxPreemptTimeMs = kVsyncIntervalMs; // Stop the preemption once the time for the longest pending IPC drops // below this threshold. const int64 kStopPreemptThresholdMs = kVsyncIntervalMs; } // anonymous namespace // This filter does three things: // - it counts and timestamps each message forwarded to the channel // so that we can preempt other channels if a message takes too long to // process. To guarantee fairness, we must wait a minimum amount of time // before preempting and we limit the amount of time that we can preempt in // one shot (see constants above). // - it handles the GpuCommandBufferMsg_InsertSyncPoint message on the IO // thread, generating the sync point ID and responding immediately, and then // posting a task to insert the GpuCommandBufferMsg_RetireSyncPoint message // into the channel's queue. // - it generates mailbox names for clients of the GPU process on the IO thread. class GpuChannelMessageFilter : public IPC::ChannelProxy::MessageFilter { public: // Takes ownership of gpu_channel (see below). GpuChannelMessageFilter(const std::string& private_key, base::WeakPtr<GpuChannel>* gpu_channel, scoped_refptr<SyncPointManager> sync_point_manager, scoped_refptr<base::MessageLoopProxy> message_loop) : preemption_state_(IDLE), gpu_channel_(gpu_channel), channel_(NULL), sync_point_manager_(sync_point_manager), message_loop_(message_loop), messages_forwarded_to_channel_(0), a_stub_is_descheduled_(false), hmac_(crypto::HMAC::SHA256) { bool success = hmac_.Init(base::StringPiece(private_key)); DCHECK(success); } virtual void OnFilterAdded(IPC::Channel* channel) OVERRIDE { DCHECK(!channel_); channel_ = channel; } virtual void OnFilterRemoved() OVERRIDE { DCHECK(channel_); channel_ = NULL; } virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE { DCHECK(channel_); bool handled = true; IPC_BEGIN_MESSAGE_MAP(GpuChannelMessageFilter, message) IPC_MESSAGE_HANDLER(GpuChannelMsg_GenerateMailboxNames, OnGenerateMailboxNames) IPC_MESSAGE_HANDLER(GpuChannelMsg_GenerateMailboxNamesAsync, OnGenerateMailboxNamesAsync) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() if (message.type() == GpuCommandBufferMsg_RetireSyncPoint::ID) { // This message should not be sent explicitly by the renderer. NOTREACHED(); handled = true; } // All other messages get processed by the GpuChannel. if (!handled) { messages_forwarded_to_channel_++; if (preempting_flag_.get()) pending_messages_.push(PendingMessage(messages_forwarded_to_channel_)); UpdatePreemptionState(); } if (message.type() == GpuCommandBufferMsg_InsertSyncPoint::ID) { uint32 sync_point = sync_point_manager_->GenerateSyncPoint(); IPC::Message* reply = IPC::SyncMessage::GenerateReply(&message); GpuCommandBufferMsg_InsertSyncPoint::WriteReplyParams(reply, sync_point); Send(reply); message_loop_->PostTask(FROM_HERE, base::Bind( &GpuChannelMessageFilter::InsertSyncPointOnMainThread, gpu_channel_, sync_point_manager_, message.routing_id(), sync_point)); handled = true; } return handled; } void MessageProcessed(uint64 messages_processed) { while (!pending_messages_.empty() && pending_messages_.front().message_number <= messages_processed) pending_messages_.pop(); UpdatePreemptionState(); } void SetPreemptingFlagAndSchedulingState( gpu::PreemptionFlag* preempting_flag, bool a_stub_is_descheduled) { preempting_flag_ = preempting_flag; a_stub_is_descheduled_ = a_stub_is_descheduled; } void UpdateStubSchedulingState(bool a_stub_is_descheduled) { a_stub_is_descheduled_ = a_stub_is_descheduled; UpdatePreemptionState(); } bool Send(IPC::Message* message) { return channel_->Send(message); } protected: virtual ~GpuChannelMessageFilter() { message_loop_->PostTask(FROM_HERE, base::Bind( &GpuChannelMessageFilter::DeleteWeakPtrOnMainThread, gpu_channel_)); } private: // Message handlers. void OnGenerateMailboxNames(unsigned num, std::vector<gpu::Mailbox>* result) { TRACE_EVENT1("gpu", "OnGenerateMailboxNames", "num", num); result->resize(num); for (unsigned i = 0; i < num; ++i) { char name[GL_MAILBOX_SIZE_CHROMIUM]; base::RandBytes(name, sizeof(name) / 2); bool success = hmac_.Sign( base::StringPiece(name, sizeof(name) / 2), reinterpret_cast<unsigned char*>(name) + sizeof(name) / 2, sizeof(name) / 2); DCHECK(success); (*result)[i].SetName(reinterpret_cast<int8*>(name)); } } void OnGenerateMailboxNamesAsync(unsigned num) { std::vector<gpu::Mailbox> names; OnGenerateMailboxNames(num, &names); Send(new GpuChannelMsg_GenerateMailboxNamesReply(names)); } enum PreemptionState { // Either there's no other channel to preempt, there are no messages // pending processing, or we just finished preempting and have to wait // before preempting again. IDLE, // We are waiting kPreemptWaitTimeMs before checking if we should preempt. WAITING, // We can preempt whenever any IPC processing takes more than // kPreemptWaitTimeMs. CHECKING, // We are currently preempting (i.e. no stub is descheduled). PREEMPTING, // We would like to preempt, but some stub is descheduled. WOULD_PREEMPT_DESCHEDULED, }; PreemptionState preemption_state_; // Maximum amount of time that we can spend in PREEMPTING. // It is reset when we transition to IDLE. base::TimeDelta max_preemption_time_; struct PendingMessage { uint64 message_number; base::TimeTicks time_received; explicit PendingMessage(uint64 message_number) : message_number(message_number), time_received(base::TimeTicks::Now()) { } }; void UpdatePreemptionState() { switch (preemption_state_) { case IDLE: if (preempting_flag_.get() && !pending_messages_.empty()) TransitionToWaiting(); break; case WAITING: // A timer will transition us to CHECKING. DCHECK(timer_.IsRunning()); break; case CHECKING: if (!pending_messages_.empty()) { base::TimeDelta time_elapsed = base::TimeTicks::Now() - pending_messages_.front().time_received; if (time_elapsed.InMilliseconds() < kPreemptWaitTimeMs) { // Schedule another check for when the IPC may go long. timer_.Start( FROM_HERE, base::TimeDelta::FromMilliseconds(kPreemptWaitTimeMs) - time_elapsed, this, &GpuChannelMessageFilter::UpdatePreemptionState); } else { if (a_stub_is_descheduled_) TransitionToWouldPreemptDescheduled(); else TransitionToPreempting(); } } break; case PREEMPTING: // A TransitionToIdle() timer should always be running in this state. DCHECK(timer_.IsRunning()); if (a_stub_is_descheduled_) TransitionToWouldPreemptDescheduled(); else TransitionToIdleIfCaughtUp(); break; case WOULD_PREEMPT_DESCHEDULED: // A TransitionToIdle() timer should never be running in this state. DCHECK(!timer_.IsRunning()); if (!a_stub_is_descheduled_) TransitionToPreempting(); else TransitionToIdleIfCaughtUp(); break; default: NOTREACHED(); } } void TransitionToIdleIfCaughtUp() { DCHECK(preemption_state_ == PREEMPTING || preemption_state_ == WOULD_PREEMPT_DESCHEDULED); if (pending_messages_.empty()) { TransitionToIdle(); } else { base::TimeDelta time_elapsed = base::TimeTicks::Now() - pending_messages_.front().time_received; if (time_elapsed.InMilliseconds() < kStopPreemptThresholdMs) TransitionToIdle(); } } void TransitionToIdle() { DCHECK(preemption_state_ == PREEMPTING || preemption_state_ == WOULD_PREEMPT_DESCHEDULED); // Stop any outstanding timer set to force us from PREEMPTING to IDLE. timer_.Stop(); preemption_state_ = IDLE; preempting_flag_->Reset(); TRACE_COUNTER_ID1("gpu", "GpuChannel::Preempting", this, 0); UpdatePreemptionState(); } void TransitionToWaiting() { DCHECK_EQ(preemption_state_, IDLE); DCHECK(!timer_.IsRunning()); preemption_state_ = WAITING; timer_.Start( FROM_HERE, base::TimeDelta::FromMilliseconds(kPreemptWaitTimeMs), this, &GpuChannelMessageFilter::TransitionToChecking); } void TransitionToChecking() { DCHECK_EQ(preemption_state_, WAITING); DCHECK(!timer_.IsRunning()); preemption_state_ = CHECKING; max_preemption_time_ = base::TimeDelta::FromMilliseconds(kMaxPreemptTimeMs); UpdatePreemptionState(); } void TransitionToPreempting() { DCHECK(preemption_state_ == CHECKING || preemption_state_ == WOULD_PREEMPT_DESCHEDULED); DCHECK(!a_stub_is_descheduled_); // Stop any pending state update checks that we may have queued // while CHECKING. if (preemption_state_ == CHECKING) timer_.Stop(); preemption_state_ = PREEMPTING; preempting_flag_->Set(); TRACE_COUNTER_ID1("gpu", "GpuChannel::Preempting", this, 1); timer_.Start( FROM_HERE, max_preemption_time_, this, &GpuChannelMessageFilter::TransitionToIdle); UpdatePreemptionState(); } void TransitionToWouldPreemptDescheduled() { DCHECK(preemption_state_ == CHECKING || preemption_state_ == PREEMPTING); DCHECK(a_stub_is_descheduled_); if (preemption_state_ == CHECKING) { // Stop any pending state update checks that we may have queued // while CHECKING. timer_.Stop(); } else { // Stop any TransitionToIdle() timers that we may have queued // while PREEMPTING. timer_.Stop(); max_preemption_time_ = timer_.desired_run_time() - base::TimeTicks::Now(); if (max_preemption_time_ < base::TimeDelta()) { TransitionToIdle(); return; } } preemption_state_ = WOULD_PREEMPT_DESCHEDULED; preempting_flag_->Reset(); TRACE_COUNTER_ID1("gpu", "GpuChannel::Preempting", this, 0); UpdatePreemptionState(); } static void InsertSyncPointOnMainThread( base::WeakPtr<GpuChannel>* gpu_channel, scoped_refptr<SyncPointManager> manager, int32 routing_id, uint32 sync_point) { // This function must ensure that the sync point will be retired. Normally // we'll find the stub based on the routing ID, and associate the sync point // with it, but if that fails for any reason (channel or stub already // deleted, invalid routing id), we need to retire the sync point // immediately. if (gpu_channel->get()) { GpuCommandBufferStub* stub = gpu_channel->get()->LookupCommandBuffer( routing_id); if (stub) { stub->AddSyncPoint(sync_point); GpuCommandBufferMsg_RetireSyncPoint message(routing_id, sync_point); gpu_channel->get()->OnMessageReceived(message); return; } else { gpu_channel->get()->MessageProcessed(); } } manager->RetireSyncPoint(sync_point); } static void DeleteWeakPtrOnMainThread( base::WeakPtr<GpuChannel>* gpu_channel) { delete gpu_channel; } // NOTE: this is a pointer to a weak pointer. It is never dereferenced on the // IO thread, it's only passed through - therefore the WeakPtr assumptions are // respected. base::WeakPtr<GpuChannel>* gpu_channel_; IPC::Channel* channel_; scoped_refptr<SyncPointManager> sync_point_manager_; scoped_refptr<base::MessageLoopProxy> message_loop_; scoped_refptr<gpu::PreemptionFlag> preempting_flag_; std::queue<PendingMessage> pending_messages_; // Count of the number of IPCs forwarded to the GpuChannel. uint64 messages_forwarded_to_channel_; base::OneShotTimer<GpuChannelMessageFilter> timer_; bool a_stub_is_descheduled_; crypto::HMAC hmac_; }; GpuChannel::GpuChannel(GpuChannelManager* gpu_channel_manager, GpuWatchdog* watchdog, gfx::GLShareGroup* share_group, gpu::gles2::MailboxManager* mailbox, int client_id, bool software) : gpu_channel_manager_(gpu_channel_manager), messages_processed_(0), client_id_(client_id), share_group_(share_group ? share_group : new gfx::GLShareGroup), mailbox_manager_(mailbox ? mailbox : new gpu::gles2::MailboxManager), image_manager_(new gpu::gles2::ImageManager), watchdog_(watchdog), software_(software), handle_messages_scheduled_(false), processed_get_state_fast_(false), currently_processing_message_(NULL), weak_factory_(this), num_stubs_descheduled_(0) { DCHECK(gpu_channel_manager); DCHECK(client_id); channel_id_ = IPC::Channel::GenerateVerifiedChannelID("gpu"); const CommandLine* command_line = CommandLine::ForCurrentProcess(); log_messages_ = command_line->HasSwitch(switches::kLogPluginMessages); disallowed_features_.multisampling = command_line->HasSwitch(switches::kDisableGLMultisampling); #if defined(OS_ANDROID) stream_texture_manager_.reset(new StreamTextureManagerAndroid(this)); #endif } bool GpuChannel::Init(base::MessageLoopProxy* io_message_loop, base::WaitableEvent* shutdown_event) { DCHECK(!channel_.get()); // Map renderer ID to a (single) channel to that process. channel_.reset(new IPC::SyncChannel( channel_id_, IPC::Channel::MODE_SERVER, this, io_message_loop, false, shutdown_event)); base::WeakPtr<GpuChannel>* weak_ptr(new base::WeakPtr<GpuChannel>( weak_factory_.GetWeakPtr())); filter_ = new GpuChannelMessageFilter( mailbox_manager_->private_key(), weak_ptr, gpu_channel_manager_->sync_point_manager(), base::MessageLoopProxy::current()); io_message_loop_ = io_message_loop; channel_->AddFilter(filter_.get()); return true; } std::string GpuChannel::GetChannelName() { return channel_id_; } #if defined(OS_POSIX) int GpuChannel::TakeRendererFileDescriptor() { if (!channel_) { NOTREACHED(); return -1; } return channel_->TakeClientFileDescriptor(); } #endif // defined(OS_POSIX) bool GpuChannel::OnMessageReceived(const IPC::Message& message) { if (log_messages_) { DVLOG(1) << "received message @" << &message << " on channel @" << this << " with type " << message.type(); } if (message.type() == GpuCommandBufferMsg_GetStateFast::ID) { if (processed_get_state_fast_) { // Require a non-GetStateFast message in between two GetStateFast // messages, to ensure progress is made. std::deque<IPC::Message*>::iterator point = deferred_messages_.begin(); while (point != deferred_messages_.end() && (*point)->type() == GpuCommandBufferMsg_GetStateFast::ID) { ++point; } if (point != deferred_messages_.end()) { ++point; } deferred_messages_.insert(point, new IPC::Message(message)); } else { // Move GetStateFast commands to the head of the queue, so the renderer // doesn't have to wait any longer than necessary. deferred_messages_.push_front(new IPC::Message(message)); } } else { deferred_messages_.push_back(new IPC::Message(message)); } OnScheduled(); return true; } void GpuChannel::OnChannelError() { gpu_channel_manager_->RemoveChannel(client_id_); } bool GpuChannel::Send(IPC::Message* message) { // The GPU process must never send a synchronous IPC message to the renderer // process. This could result in deadlock. DCHECK(!message->is_sync()); if (log_messages_) { DVLOG(1) << "sending message @" << message << " on channel @" << this << " with type " << message->type(); } if (!channel_) { delete message; return false; } return channel_->Send(message); } void GpuChannel::RequeueMessage() { DCHECK(currently_processing_message_); deferred_messages_.push_front( new IPC::Message(*currently_processing_message_)); messages_processed_--; currently_processing_message_ = NULL; } void GpuChannel::OnScheduled() { if (handle_messages_scheduled_) return; // Post a task to handle any deferred messages. The deferred message queue is // not emptied here, which ensures that OnMessageReceived will continue to // defer newly received messages until the ones in the queue have all been // handled by HandleMessage. HandleMessage is invoked as a // task to prevent reentrancy. base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&GpuChannel::HandleMessage, weak_factory_.GetWeakPtr())); handle_messages_scheduled_ = true; } void GpuChannel::StubSchedulingChanged(bool scheduled) { bool a_stub_was_descheduled = num_stubs_descheduled_ > 0; if (scheduled) { num_stubs_descheduled_--; OnScheduled(); } else { num_stubs_descheduled_++; } DCHECK_LE(num_stubs_descheduled_, stubs_.size()); bool a_stub_is_descheduled = num_stubs_descheduled_ > 0; if (a_stub_is_descheduled != a_stub_was_descheduled) { if (preempting_flag_.get()) { io_message_loop_->PostTask( FROM_HERE, base::Bind(&GpuChannelMessageFilter::UpdateStubSchedulingState, filter_, a_stub_is_descheduled)); } } } void GpuChannel::CreateViewCommandBuffer( const gfx::GLSurfaceHandle& window, int32 surface_id, const GPUCreateCommandBufferConfig& init_params, int32* route_id) { TRACE_EVENT1("gpu", "GpuChannel::CreateViewCommandBuffer", "surface_id", surface_id); *route_id = MSG_ROUTING_NONE; GpuCommandBufferStub* share_group = stubs_.Lookup(init_params.share_group_id); // Virtualize compositor contexts on OS X to prevent performance regressions // when enabling FCM. // http://crbug.com/180463 bool use_virtualized_gl_context = false; #if defined(OS_MACOSX) use_virtualized_gl_context = true; #endif *route_id = GenerateRouteID(); scoped_ptr<GpuCommandBufferStub> stub( new GpuCommandBufferStub(this, share_group, window, mailbox_manager_.get(), image_manager_.get(), gfx::Size(), disallowed_features_, init_params.attribs, init_params.gpu_preference, use_virtualized_gl_context, *route_id, surface_id, watchdog_, software_, init_params.active_url)); if (preempted_flag_.get()) stub->SetPreemptByFlag(preempted_flag_); router_.AddRoute(*route_id, stub.get()); stubs_.AddWithID(stub.release(), *route_id); } GpuCommandBufferStub* GpuChannel::LookupCommandBuffer(int32 route_id) { return stubs_.Lookup(route_id); } void GpuChannel::CreateImage( gfx::PluginWindowHandle window, int32 image_id, gfx::Size* size) { TRACE_EVENT1("gpu", "GpuChannel::CreateImage", "image_id", image_id); *size = gfx::Size(); if (image_manager_->LookupImage(image_id)) { LOG(ERROR) << "CreateImage failed, image_id already in use."; return; } scoped_refptr<gfx::GLImage> image = gfx::GLImage::CreateGLImage(window); if (!image.get()) return; image_manager_->AddImage(image.get(), image_id); *size = image->GetSize(); } void GpuChannel::DeleteImage(int32 image_id) { TRACE_EVENT1("gpu", "GpuChannel::DeleteImage", "image_id", image_id); image_manager_->RemoveImage(image_id); } void GpuChannel::LoseAllContexts() { gpu_channel_manager_->LoseAllContexts(); } void GpuChannel::MarkAllContextsLost() { for (StubMap::Iterator<GpuCommandBufferStub> it(&stubs_); !it.IsAtEnd(); it.Advance()) { it.GetCurrentValue()->MarkContextLost(); } } void GpuChannel::DestroySoon() { base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&GpuChannel::OnDestroy, this)); } int GpuChannel::GenerateRouteID() { static int last_id = 0; return ++last_id; } void GpuChannel::AddRoute(int32 route_id, IPC::Listener* listener) { router_.AddRoute(route_id, listener); } void GpuChannel::RemoveRoute(int32 route_id) { router_.RemoveRoute(route_id); } gpu::PreemptionFlag* GpuChannel::GetPreemptionFlag() { if (!preempting_flag_.get()) { preempting_flag_ = new gpu::PreemptionFlag; io_message_loop_->PostTask( FROM_HERE, base::Bind( &GpuChannelMessageFilter::SetPreemptingFlagAndSchedulingState, filter_, preempting_flag_, num_stubs_descheduled_ > 0)); } return preempting_flag_.get(); } void GpuChannel::SetPreemptByFlag( scoped_refptr<gpu::PreemptionFlag> preempted_flag) { preempted_flag_ = preempted_flag; for (StubMap::Iterator<GpuCommandBufferStub> it(&stubs_); !it.IsAtEnd(); it.Advance()) { it.GetCurrentValue()->SetPreemptByFlag(preempted_flag_); } } GpuChannel::~GpuChannel() { if (preempting_flag_.get()) preempting_flag_->Reset(); } void GpuChannel::OnDestroy() { TRACE_EVENT0("gpu", "GpuChannel::OnDestroy"); gpu_channel_manager_->RemoveChannel(client_id_); } bool GpuChannel::OnControlMessageReceived(const IPC::Message& msg) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(GpuChannel, msg) IPC_MESSAGE_HANDLER(GpuChannelMsg_CreateOffscreenCommandBuffer, OnCreateOffscreenCommandBuffer) IPC_MESSAGE_HANDLER(GpuChannelMsg_DestroyCommandBuffer, OnDestroyCommandBuffer) IPC_MESSAGE_HANDLER(GpuChannelMsg_CreateVideoEncoder, OnCreateVideoEncoder) IPC_MESSAGE_HANDLER(GpuChannelMsg_DestroyVideoEncoder, OnDestroyVideoEncoder) #if defined(OS_ANDROID) IPC_MESSAGE_HANDLER(GpuChannelMsg_RegisterStreamTextureProxy, OnRegisterStreamTextureProxy) IPC_MESSAGE_HANDLER(GpuChannelMsg_EstablishStreamTexture, OnEstablishStreamTexture) IPC_MESSAGE_HANDLER(GpuChannelMsg_SetStreamTextureSize, OnSetStreamTextureSize) #endif IPC_MESSAGE_HANDLER( GpuChannelMsg_CollectRenderingStatsForSurface, OnCollectRenderingStatsForSurface) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() DCHECK(handled) << msg.type(); return handled; } void GpuChannel::HandleMessage() { handle_messages_scheduled_ = false; if (deferred_messages_.empty()) return; bool should_fast_track_ack = false; IPC::Message* m = deferred_messages_.front(); GpuCommandBufferStub* stub = stubs_.Lookup(m->routing_id()); do { if (stub) { if (!stub->IsScheduled()) return; if (stub->IsPreempted()) { OnScheduled(); return; } } scoped_ptr<IPC::Message> message(m); deferred_messages_.pop_front(); bool message_processed = true; processed_get_state_fast_ = (message->type() == GpuCommandBufferMsg_GetStateFast::ID); currently_processing_message_ = message.get(); bool result; if (message->routing_id() == MSG_ROUTING_CONTROL) result = OnControlMessageReceived(*message); else result = router_.RouteMessage(*message); currently_processing_message_ = NULL; if (!result) { // Respond to sync messages even if router failed to route. if (message->is_sync()) { IPC::Message* reply = IPC::SyncMessage::GenerateReply(&*message); reply->set_reply_error(); Send(reply); } } else { // If the command buffer becomes unscheduled as a result of handling the // message but still has more commands to process, synthesize an IPC // message to flush that command buffer. if (stub) { if (stub->HasUnprocessedCommands()) { deferred_messages_.push_front(new GpuCommandBufferMsg_Rescheduled( stub->route_id())); message_processed = false; } } } if (message_processed) MessageProcessed(); // We want the EchoACK following the SwapBuffers to be sent as close as // possible, avoiding scheduling other channels in the meantime. should_fast_track_ack = false; if (!deferred_messages_.empty()) { m = deferred_messages_.front(); stub = stubs_.Lookup(m->routing_id()); should_fast_track_ack = (m->type() == GpuCommandBufferMsg_Echo::ID) && stub && stub->IsScheduled(); } } while (should_fast_track_ack); if (!deferred_messages_.empty()) { OnScheduled(); } } void GpuChannel::OnCreateOffscreenCommandBuffer( const gfx::Size& size, const GPUCreateCommandBufferConfig& init_params, int32* route_id) { TRACE_EVENT0("gpu", "GpuChannel::OnCreateOffscreenCommandBuffer"); GpuCommandBufferStub* share_group = stubs_.Lookup(init_params.share_group_id); *route_id = GenerateRouteID(); scoped_ptr<GpuCommandBufferStub> stub(new GpuCommandBufferStub( this, share_group, gfx::GLSurfaceHandle(), mailbox_manager_.get(), image_manager_.get(), size, disallowed_features_, init_params.attribs, init_params.gpu_preference, false, *route_id, 0, watchdog_, software_, init_params.active_url)); if (preempted_flag_.get()) stub->SetPreemptByFlag(preempted_flag_); router_.AddRoute(*route_id, stub.get()); stubs_.AddWithID(stub.release(), *route_id); TRACE_EVENT1("gpu", "GpuChannel::OnCreateOffscreenCommandBuffer", "route_id", route_id); } void GpuChannel::OnDestroyCommandBuffer(int32 route_id) { TRACE_EVENT1("gpu", "GpuChannel::OnDestroyCommandBuffer", "route_id", route_id); GpuCommandBufferStub* stub = stubs_.Lookup(route_id); if (!stub) return; bool need_reschedule = (stub && !stub->IsScheduled()); router_.RemoveRoute(route_id); stubs_.Remove(route_id); // In case the renderer is currently blocked waiting for a sync reply from the // stub, we need to make sure to reschedule the GpuChannel here. if (need_reschedule) { // This stub won't get a chance to reschedule, so update the count now. StubSchedulingChanged(true); } } void GpuChannel::OnCreateVideoEncoder(int32* route_id) { TRACE_EVENT0("gpu", "GpuChannel::OnCreateVideoEncoder"); *route_id = GenerateRouteID(); GpuVideoEncodeAccelerator* encoder = new GpuVideoEncodeAccelerator(this, *route_id); router_.AddRoute(*route_id, encoder); video_encoders_.AddWithID(encoder, *route_id); } void GpuChannel::OnDestroyVideoEncoder(int32 route_id) { TRACE_EVENT1( "gpu", "GpuChannel::OnDestroyVideoEncoder", "route_id", route_id); GpuVideoEncodeAccelerator* encoder = video_encoders_.Lookup(route_id); if (!encoder) return; router_.RemoveRoute(route_id); video_encoders_.Remove(route_id); } #if defined(OS_ANDROID) void GpuChannel::OnRegisterStreamTextureProxy( int32 stream_id, int32* route_id) { // Note that route_id is only used for notifications sent out from here. // StreamTextureManager owns all texture objects and for incoming messages // it finds the correct object based on stream_id. *route_id = GenerateRouteID(); stream_texture_manager_->RegisterStreamTextureProxy(stream_id, *route_id); } void GpuChannel::OnEstablishStreamTexture( int32 stream_id, int32 primary_id, int32 secondary_id) { stream_texture_manager_->EstablishStreamTexture( stream_id, primary_id, secondary_id); } void GpuChannel::OnSetStreamTextureSize( int32 stream_id, const gfx::Size& size) { stream_texture_manager_->SetStreamTextureSize(stream_id, size); } #endif void GpuChannel::OnCollectRenderingStatsForSurface( int32 surface_id, GpuRenderingStats* stats) { for (StubMap::Iterator<GpuCommandBufferStub> it(&stubs_); !it.IsAtEnd(); it.Advance()) { int texture_upload_count = it.GetCurrentValue()->decoder()->GetTextureUploadCount(); base::TimeDelta total_texture_upload_time = it.GetCurrentValue()->decoder()->GetTotalTextureUploadTime(); base::TimeDelta total_processing_commands_time = it.GetCurrentValue()->decoder()->GetTotalProcessingCommandsTime(); stats->global_texture_upload_count += texture_upload_count; stats->global_total_texture_upload_time += total_texture_upload_time; stats->global_total_processing_commands_time += total_processing_commands_time; if (it.GetCurrentValue()->surface_id() == surface_id) { stats->texture_upload_count += texture_upload_count; stats->total_texture_upload_time += total_texture_upload_time; stats->total_processing_commands_time += total_processing_commands_time; } } GPUVideoMemoryUsageStats usage_stats; gpu_channel_manager_->gpu_memory_manager()->GetVideoMemoryUsageStats( &usage_stats); stats->global_video_memory_bytes_allocated = usage_stats.bytes_allocated; } void GpuChannel::MessageProcessed() { messages_processed_++; if (preempting_flag_.get()) { io_message_loop_->PostTask( FROM_HERE, base::Bind(&GpuChannelMessageFilter::MessageProcessed, filter_, messages_processed_)); } } void GpuChannel::CacheShader(const std::string& key, const std::string& shader) { gpu_channel_manager_->Send( new GpuHostMsg_CacheShader(client_id_, key, shader)); } void GpuChannel::AddFilter(IPC::ChannelProxy::MessageFilter* filter) { channel_->AddFilter(filter); } void GpuChannel::RemoveFilter(IPC::ChannelProxy::MessageFilter* filter) { channel_->RemoveFilter(filter); } } // namespace content
32.574724
80
0.688857
nagineni
fe6ffd53fd7aa0a845db231dea9364eec7d3bab2
6,289
cc
C++
3rdParty/s2geometry/dfefe0c/src/s2/s2edge_tessellator.cc
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
12,278
2015-01-29T17:11:33.000Z
2022-03-31T21:12:00.000Z
3rdParty/s2geometry/dfefe0c/src/s2/s2edge_tessellator.cc
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
9,469
2015-01-30T05:33:07.000Z
2022-03-31T16:17:21.000Z
3rdParty/s2geometry/dfefe0c/src/s2/s2edge_tessellator.cc
rajeev02101987/arangodb
817e6c04cb82777d266f3b444494140676da98e2
[ "Apache-2.0" ]
892
2015-01-29T16:26:19.000Z
2022-03-20T07:44:30.000Z
// Copyright 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Author: ericv@google.com (Eric Veach) #include "s2/s2edge_tessellator.h" #include <cmath> #include "s2/s2latlng.h" #include "s2/s2pointutil.h" using std::vector; S1Angle S2EdgeTessellator::kMinTolerance() { // This distance is less than 1 micrometer on the Earth's surface, but is // still much larger than the expected projection and interpolation errors. return S1Angle::Radians(1e-13); } S2EdgeTessellator::S2EdgeTessellator(const S2::Projection* projection, S1Angle tolerance) : proj_(*projection), tolerance_(std::max(tolerance, kMinTolerance())), wrap_distance_(projection->wrap_distance()) { if (tolerance < kMinTolerance()) S2_LOG(DFATAL) << "Tolerance too small"; } void S2EdgeTessellator::AppendProjected( const S2Point& a, const S2Point& b, vector<R2Point>* vertices) const { R2Point pa = proj_.Project(a); if (vertices->empty()) { vertices->push_back(pa); } else { pa = WrapDestination(vertices->back(), pa); S2_DCHECK_EQ(vertices->back(), pa) << "Appended edges must form a chain"; } R2Point pb = WrapDestination(pa, proj_.Project(b)); AppendProjected(pa, a, pb, b, vertices); } // Given a geodesic edge AB, split the edge as necessary and append all // projected vertices except the first to "vertices". // // The maximum recursion depth is (M_PI / kMinTolerance()) < 45, and the // frame size is small so stack overflow should not be an issue. void S2EdgeTessellator::AppendProjected(const R2Point& pa, const S2Point& a, const R2Point& pb, const S2Point& b, vector<R2Point>* vertices) const { // It's impossible to robustly test whether a projected edge is close enough // to a geodesic edge without knowing the details of the projection // function, but the following heuristic works well for a wide range of map // projections. The idea is simply to test whether the midpoint of the // projected edge is close enough to the midpoint of the geodesic edge. // // This measures the distance between the two edges by treating them as // parametric curves rather than geometric ones. The problem with // measuring, say, the minimum distance from the projected midpoint to the // geodesic edge is that this is a lower bound on the value we want, because // the maximum separation between the two curves is generally not attained // at the midpoint of the projected edge. The distance between the curve // midpoints is at least an upper bound on the distance from either midpoint // to opposite curve. It's not necessarily an upper bound on the maximum // distance between the two curves, but it is a powerful requirement because // it demands that the two curves stay parametrically close together. This // turns out to be much more robust with respect for projections with // singularities (e.g., the North and South poles in the rectangular and // Mercator projections) because the curve parameterization speed changes // rapidly near such singularities. S2Point mid = (a + b).Normalize(); S2Point test_mid = proj_.Unproject(proj_.Interpolate(0.5, pa, pb)); if (S1ChordAngle(mid, test_mid) < tolerance_) { vertices->push_back(pb); } else { R2Point pmid = WrapDestination(pa, proj_.Project(mid)); AppendProjected(pa, a, pmid, mid, vertices); AppendProjected(pmid, mid, pb, b, vertices); } } void S2EdgeTessellator::AppendUnprojected( const R2Point& pa, const R2Point& pb_in, vector<S2Point>* vertices) const { R2Point pb = WrapDestination(pa, pb_in); S2Point a = proj_.Unproject(pa); S2Point b = proj_.Unproject(pb); if (vertices->empty()) { vertices->push_back(a); } else { // Note that coordinate wrapping can create a small amount of error. For // example in the edge chain "0:-175, 0:179, 0:-177", the first edge is // transformed into "0:-175, 0:-181" while the second is transformed into // "0:179, 0:183". The two coordinate pairs for the middle vertex // ("0:-181" and "0:179") may not yield exactly the same S2Point. S2_DCHECK(S2::ApproxEquals(vertices->back(), a)) << "Appended edges must form a chain"; } AppendUnprojected(pa, a, pb, b, vertices); } // Like AppendProjected, but interpolates a projected edge and appends the // corresponding points on the sphere. void S2EdgeTessellator::AppendUnprojected(const R2Point& pa, const S2Point& a, const R2Point& pb, const S2Point& b, vector<S2Point>* vertices) const { // See notes above regarding measuring the interpolation error. R2Point pmid = proj_.Interpolate(0.5, pa, pb); S2Point mid = proj_.Unproject(pmid); S2Point test_mid = (a + b).Normalize(); if (S1ChordAngle(mid, test_mid) < tolerance_) { vertices->push_back(b); } else { AppendUnprojected(pa, a, pmid, mid, vertices); AppendUnprojected(pmid, mid, pb, b, vertices); } } // Wraps the coordinates of the edge destination if necessary to obtain the // shortest edge. R2Point S2EdgeTessellator::WrapDestination(const R2Point& pa, const R2Point& pb) const { double x = pb.x(), y = pb.y(); // The code below ensures that "pb" is unmodified unless wrapping is required. if (wrap_distance_.x() > 0 && fabs(x - pa.x()) > 0.5 * wrap_distance_.x()) { x = pa.x() + remainder(x - pa.x(), wrap_distance_.x()); } if (wrap_distance_.y() > 0 && fabs(y - pa.y()) > 0.5 * wrap_distance_.y()) { y = pa.y() + remainder(y - pa.y(), wrap_distance_.y()); } return R2Point(x, y); }
44.288732
80
0.685006
rajeev02101987
fe71bebe3277551d644585d06fabee4d87d7ca83
20,442
cxx
C++
HLT/BASE/util/ZMQESDserver.cxx
shahor02/AliRoot
37118c83effe7965a2a24b3b868bf9012727fb7e
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
HLT/BASE/util/ZMQESDserver.cxx
shahor02/AliRoot
37118c83effe7965a2a24b3b868bf9012727fb7e
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
HLT/BASE/util/ZMQESDserver.cxx
shahor02/AliRoot
37118c83effe7965a2a24b3b868bf9012727fb7e
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
#include "AliESDEvent.h" #include "AliESDtrack.h" #include "AliHLTZMQhelpers.h" #include "AliOptionParser.h" #include "TFile.h" #include "TSystem.h" #include "TTree.h" #include "signal.h" #include "zmq.h" #include <iostream> #include <memory> #include <pthread.h> #include <string> #include <sys/time.h> #include <time.h> #include <unistd.h> using namespace AliZMQhelpers; // methods Int_t ProcessOptionString(TString arguments, Bool_t verbose = kFALSE); Int_t InitZMQ(); Int_t Run(); Int_t HandleRequest(aliZMQmsg::iterator block, void* /*socket*/ = NULL); Int_t DoSend(void* socket); Int_t HandleControlSequence(aliZMQmsg::iterator block, void* socket); void SetLastPushBackTime(); template <typename T> class o2vec; template <typename T> void alizmq_deleteArray(void* data, void*); template <typename T> int alizmq_msg_add_array(aliZMQmsg* message, o2vec<T>&& vec); // configuration vars Bool_t fVerbose = kFALSE; TString fZMQconfigOUT = "PUSH"; Int_t fZMQmaxQueueSize = 10; Int_t fZMQtimeout = -1; int fZMQlingerTime = 30000; //30s default linger std::vector<std::string> fFilesIn; std::string fInfo; // cache for the info string std::string fID; // merger ID/name long fPushbackPeriod = -1; // in seconds, -1 means never long fRequestPeriod = -1; // in seconds, -1 means never long fRequestTimeout = 10000; // default 10s aliZMQrootStreamerInfo fSchema; bool fSchemaOnRequest = false; bool fSchemaOnSend = false; int fCompression = 1; bool fgTerminationSignaled = false; bool fOnce = true; unsigned long long fLastPushBackTime = 0; unsigned long long fLastRequestTime = 0; struct timeval fCurrentTimeStruct; uint64_t fBytesOUT = 0; unsigned long fSecondsStart = 0; unsigned long fSecondsStop = 0; unsigned long long fNumberOfMessagesSent = 0; // ZMQ stuff void* fZMQcontext = NULL; // ze zmq context void* fZMQout = NULL; // the monitoring socket, here we publish a copy of the data void* fZMQresetBroadcast = NULL; bool fReconfigureZMQ = true; const char* fUSAGE = "ZMQESDserver options: \n" " -id : some string identifier\n" " -in : comma separated list of input files, e.g. AliESDs.root,../AliESDs.root\n" " -out : data out, format is zmq config string, e.g. PUSH+tcp://localhost:123123 or REP@tcp://*:123123\n" " -once : [0|1] run once, or run forever" " -ZMQlinger : [ms] - how long to wait for socket to send pending data before forcing close" " -Verbose : print some info\n"; //_______________________________________________________________________________________ void sig_handler(int signo) { if (signo == SIGINT) printf(" received SIGINT\n"); fgTerminationSignaled = true; } //_______________________________________________________________________________________ Int_t Run() { // start time (sec) gettimeofday(&fCurrentTimeStruct, NULL); fSecondsStart = fCurrentTimeStruct.tv_sec; // main loop while (!fgTerminationSignaled) { Int_t nSockets = 1; zmq_pollitem_t sockets[] = { { fZMQout, 0, ZMQ_POLLIN | ZMQ_POLLOUT, 0 }, }; Int_t rc = 0; errno = 0; Int_t outType = alizmq_socket_type(fZMQout); // poll sockets for data or conditions rc = zmq_poll(sockets, nSockets, fZMQtimeout); // poll sockets if (rc == -1 && errno == ETERM) { // this can only happen it the context was terminated, one of the sockets are // not valid or operation was interrupted Printf("zmq_poll was interrupted! rc = %i, %s", rc, zmq_strerror(errno)); break; } if (alizmq_socket_type(fZMQout) == ZMQ_REP) { // request waiting if (sockets[0].revents & ZMQ_POLLIN) { printf("request in\n"); aliZMQmsg message; alizmq_msg_recv(&message, fZMQout, 0); for (aliZMQmsg::iterator i = message.begin(); i != message.end(); ++i) { HandleRequest(i, fZMQout); } alizmq_msg_close(&message); } } // socket 0 else if (sockets[0].revents & ZMQ_POLLOUT) { DoSend(fZMQout); } } // main loop // stop time (sec) gettimeofday(&fCurrentTimeStruct, NULL); fSecondsStop = fCurrentTimeStruct.tv_sec; { printf("number of messages sent : %llu\n", fNumberOfMessagesSent); printf("out %lubytes, %.2f MB\n", fBytesOUT, (double)(fBytesOUT) / 1024. / 1024.); } return 0; } //_____________________________________________________________________ Int_t HandleControlSequence(aliZMQmsg::iterator block, void* socket) { // handle control sequences in the request if any return 0; } //_____________________________________________________________________ Int_t HandleRequest(aliZMQmsg::iterator block, void* socket) { printf("HandleRequest\n"); HandleControlSequence(block, socket); return DoSend(socket); } // struct NameHeader: public BaseDataTopic { static constexpr int nameSize{32}; char _name[nameSize]; NameHeader(char const* name, bool more = false): BaseDataTopic(sizeof(NameHeader), CharArr2uint64("NameHead"), CharArr2uint64("NONE"), more), _name{} { strncpy(_name, name, nameSize); //set padding length in last byte uint8_t* lastByte = reinterpret_cast<uint8_t*>(this) + sizeof(NameHeader) - 1; *lastByte = nameSize-strlen(name); }; }; struct Header { DataTopic dataHeader; NameHeader nameHeader; Header(char const* name, const char* id, const char* origin, uint64_t spec=0): dataHeader{id,origin,spec,CharArr2uint64("NONE"),true}, nameHeader{name} {}; }; //______________________________________________________________________________ //this is a really stupid vector, push_back has no bounds checking! //it tries to minimize reallocations and can release the underlying buffer template<typename T> class o2vec { public: o2vec(Header header, size_t capacity=0) : _buf(capacity?new T[capacity]:new T[1]), //don't want to deal with corner cases _capacity{capacity}, _end(_buf.get()), _header(header) {} o2vec(const o2vec&) = delete; o2vec& operator=(const o2vec&) = delete; T* release() { return _buf.release(); } size_t free() { return _buf.get()+_capacity-_end; } size_t size() { return _end-_buf.get(); } size_t capacity() { return _capacity; } T& back() { return *(_end-1); } T* get() const { return _buf.get(); } void push_back(T i) { *_end++=i; } void reserve(size_t elems) { if (elems>_capacity){ T* tmp = new T[elems]; memcpy(tmp,_buf.get(),size()); _end=tmp+size(); _buf.reset(tmp); _capacity=elems; }; } Header* header() {return &_header;} void reserve_free(size_t elems) { if (elems>free()){ reserve(size()+elems); }; } private: std::unique_ptr<T[]> _buf; T* _end{nullptr}; size_t _capacity{0}; Header _header; }; //______________________________________________________________________________ Int_t DoSend(void* socket) { aliZMQmsg message; o2vec<int32_t> feventID(Header{"fEVID", "TRKPAREVID","ESD"}); o2vec<float> fX(Header{"fX", "TRKPARX","ESD"}); o2vec<float> fAlpha(Header{"fAlpha", "TRKPARAlpha","ESD"}); o2vec<float> fY(Header{"fY", "TRKPARY","ESD"}); o2vec<float> fZ(Header{"fZ", "TRKPARZ","ESD"}); o2vec<float> fSnp(Header{"fSnp", "TRKPARSnp","ESD"}); o2vec<float> fTgl(Header{"fTgl", "TRKPARTgl","ESD"}); o2vec<float> fSigned1Pt(Header{"fSigned1Pt", "TRKPARSigned1Pt","ESD"}); o2vec<float> fCYY(Header{"fCYY", "TRKCOVCYY","ESD"}); o2vec<float> fCZY(Header{"fCZY", "TRKCOVCZY","ESD"}); o2vec<float> fCZZ(Header{"fCZZ", "TRKCOVCZZ","ESD"}); o2vec<float> fCSnpY(Header{"fCSnpY", "TRKCOVCSnpY","ESD"}); o2vec<float> fCSnpZ(Header{"fCSnpZ", "TRKCOVCSnpZ","ESD"}); o2vec<float> fCSnpSnp(Header{"fCSnpSnp", "TRKCOVCSnpSnp","ESD"}); o2vec<float> fCTglY(Header{"fCTglY", "TRKCOVCTglY","ESD"}); o2vec<float> fCTglZ(Header{"fCTglZ", "TRKCOVCTglZ","ESD"}); o2vec<float> fCTglSnp(Header{"fCTglSnp", "TRKCOVCTglSnp","ESD"}); o2vec<float> fCTglTgl(Header{"fCTglTgl", "TRKCOVCTglTgl","ESD"}); o2vec<float> fC1PtY(Header{"fC1PtY", "TRKCOVC1PtY","ESD"}); o2vec<float> fC1PtZ(Header{"fC1PtZ", "TRKCOVC1PtZ","ESD"}); o2vec<float> fC1PtSnp(Header{"fC1PtSnp", "TRKCOVC1PtSnp","ESD"}); o2vec<float> fC1PtTgl(Header{"fC1PtTgl", "TRKCOVC1PtTgl","ESD"}); o2vec<float> fC1Pt21Pt2(Header{"fC1Pt21Pt2", "TRKCOVC1Pt21Pt2","ESD"}); o2vec<float> fTPCinnerP(Header{"fTPCinnerP", "TRKEXTTPCinnerP","ESD"}); o2vec<float> fFlags(Header{"fFlags", "TRKEXTFlags","ESD"}); o2vec<float> fITSClusterMap(Header{"fITSClusterMap", "TRKEXTITSClsMap","ESD"}); o2vec<float> fTPCncls(Header{"fTPCncls", "TRKEXTTPCncls","ESD"}); o2vec<float> fTRDntracklets(Header{"fTRDntracklets", "TRKEXTTRDntrklts","ESD"}); o2vec<float> fITSchi2Ncl(Header{"fITSchi2Ncl", "TRKEXTITSchi2Ncl","ESD"}); o2vec<float> fTPCchi2Ncl(Header{"fTPCchi2Ncl", "TRKEXTTPCchi2Ncl","ESD"}); o2vec<float> fTRDchi2(Header{"fTRDchi2", "TRKEXTTRDchi2","ESD"}); o2vec<float> fTOFchi2(Header{"fTOFchi2", "TRKEXTTOFchi2","ESD"}); o2vec<float> fTPCsignal(Header{"fTPCsignal", "TRKEXTTPCsignal","ESD"}); o2vec<float> fTRDsignal(Header{"fTRDsignal", "TRKEXTTRDsignal","ESD"}); o2vec<float> fTOFsignal(Header{"fTOFsignal", "TRKEXTTOFsignal","ESD"}); o2vec<float> fLength(Header{"fLength", "TRKEXTLength","ESD"}); for (std::string filename: fFilesIn) { if (fVerbose) {printf("opening file %si\n",filename.c_str());} TFile file(filename.c_str()); if (file.IsOpen() == false) { printf("ERROR: cannot open %s",filename.c_str()); continue; } TTree* esdTree = (TTree*)file.Get("esdTree"); unique_ptr<AliESDEvent> esd(new AliESDEvent); esd->ReadFromTree(esdTree); size_t nev = esdTree->GetEntries(); if (fVerbose) {printf(" %lu events\n",nev);} for (size_t iev = 0; iev < nev; ++iev) { esd->Reset(); esdTree->GetEntry(iev); esd->ConnectTracks(); // Tracks information size_t ntrk = esd->GetNumberOfTracks(); if (fVerbose) {printf(" event: %lu tracks:%lu\n",iev,ntrk);} //naive preallocation scheme size_t elems = ntrk*nev*fFilesIn.size()+ntrk*nev; feventID.reserve(elems); fX.reserve(elems); fAlpha.reserve(elems); fY.reserve(elems); fZ.reserve(elems); fSnp.reserve(elems); fTgl.reserve(elems); fSigned1Pt.reserve(elems); fCYY.reserve(elems); fCZY.reserve(elems); fCZZ.reserve(elems); fCSnpY.reserve(elems); fCSnpZ.reserve(elems); fCSnpSnp.reserve(elems); fCTglY.reserve(elems); fCTglZ.reserve(elems); fCTglSnp.reserve(elems); fCTglTgl.reserve(elems); fC1PtY.reserve(elems); fC1PtZ.reserve(elems); fC1PtSnp.reserve(elems); fC1PtTgl.reserve(elems); fC1Pt21Pt2.reserve(elems); fTPCinnerP.reserve(elems); fFlags.reserve(elems); fITSClusterMap.reserve(elems); fTPCncls.reserve(elems); fTRDntracklets.reserve(elems); fITSchi2Ncl.reserve(elems); fTPCchi2Ncl.reserve(elems); fTRDchi2.reserve(elems); fTOFchi2.reserve(elems); fTPCsignal.reserve(elems); fTRDsignal.reserve(elems); fTOFsignal.reserve(elems); fLength.reserve(elems); for (size_t itrk = 0; itrk < ntrk; ++itrk) { AliESDtrack* track = esd->GetTrack(itrk); track->SetESDEvent(esd.get()); feventID.push_back(iev); fX.push_back(track->GetX()); fAlpha.push_back(track->GetAlpha()); fY.push_back(track->GetY()); fZ.push_back(track->GetZ()); fSnp.push_back(track->GetSnp()); fTgl.push_back(track->GetTgl()); fSigned1Pt.push_back(track->GetSigned1Pt()); fCYY.push_back(track->GetSigmaY2()); fCZY.push_back(track->GetSigmaZY()); fCZZ.push_back(track->GetSigmaZ2()); fCSnpY.push_back(track->GetSigmaSnpY()); fCSnpZ.push_back(track->GetSigmaSnpZ()); fCSnpSnp.push_back(track->GetSigmaSnp2()); fCTglY.push_back(track->GetSigmaTglY()); fCTglZ.push_back(track->GetSigmaTglZ()); fCTglSnp.push_back(track->GetSigmaTglSnp()); fCTglTgl.push_back(track->GetSigmaTgl2()); fC1PtY.push_back(track->GetSigma1PtY()); fC1PtZ.push_back(track->GetSigma1PtZ()); fC1PtSnp.push_back(track->GetSigma1PtSnp()); fC1PtTgl.push_back(track->GetSigma1PtTgl()); fC1Pt21Pt2.push_back(track->GetSigma1Pt2()); const AliExternalTrackParam* intp = track->GetTPCInnerParam(); fTPCinnerP.push_back(intp ? intp->GetP() : 0); fFlags.push_back(track->GetStatus()); fITSClusterMap.push_back(track->GetITSClusterMap()); fTPCncls.push_back(track->GetTPCNcls()); fTRDntracklets.push_back(track->GetTRDntracklets()); fITSchi2Ncl.push_back(track->GetITSNcls() ? track->GetITSchi2() / track->GetITSNcls() : 0); fTPCchi2Ncl.push_back(track->GetTPCNcls() ? track->GetTPCchi2() / track->GetTPCNcls() : 0); fTRDchi2.push_back(track->GetTRDchi2()); fTOFchi2.push_back(track->GetTOFchi2()); fTPCsignal.push_back(track->GetTPCsignal()); fTRDsignal.push_back(track->GetTRDsignal()); fTOFsignal.push_back(track->GetTOFsignal()); fLength.push_back(track->GetIntegratedLength()); }//track loop }//event loop }//file loop int rc{0}; rc = alizmq_msg_add_array(&message, std::move(feventID)); rc = alizmq_msg_add_array(&message, std::move(fX)); rc = alizmq_msg_add_array(&message, std::move(fAlpha)); rc = alizmq_msg_add_array(&message, std::move(fY)); rc = alizmq_msg_add_array(&message, std::move(fZ)); rc = alizmq_msg_add_array(&message, std::move(fSnp)); rc = alizmq_msg_add_array(&message, std::move(fTgl)); rc = alizmq_msg_add_array(&message, std::move(fSigned1Pt)); rc = alizmq_msg_add_array(&message, std::move(fCYY)); rc = alizmq_msg_add_array(&message, std::move(fCZY)); rc = alizmq_msg_add_array(&message, std::move(fCZZ)); rc = alizmq_msg_add_array(&message, std::move(fCSnpY)); rc = alizmq_msg_add_array(&message, std::move(fCSnpZ)); rc = alizmq_msg_add_array(&message, std::move(fCSnpSnp)); rc = alizmq_msg_add_array(&message, std::move(fCTglY)); rc = alizmq_msg_add_array(&message, std::move(fCTglZ)); rc = alizmq_msg_add_array(&message, std::move(fCTglSnp)); rc = alizmq_msg_add_array(&message, std::move(fCTglTgl)); rc = alizmq_msg_add_array(&message, std::move(fC1PtY)); rc = alizmq_msg_add_array(&message, std::move(fC1PtZ)); rc = alizmq_msg_add_array(&message, std::move(fC1PtSnp)); rc = alizmq_msg_add_array(&message, std::move(fC1PtTgl)); rc = alizmq_msg_add_array(&message, std::move(fC1Pt21Pt2)); rc = alizmq_msg_add_array(&message, std::move(fTPCinnerP)); rc = alizmq_msg_add_array(&message, std::move(fFlags)); rc = alizmq_msg_add_array(&message, std::move(fITSClusterMap)); rc = alizmq_msg_add_array(&message, std::move(fTPCncls)); rc = alizmq_msg_add_array(&message, std::move(fTRDntracklets)); rc = alizmq_msg_add_array(&message, std::move(fITSchi2Ncl)); rc = alizmq_msg_add_array(&message, std::move(fTPCchi2Ncl)); rc = alizmq_msg_add_array(&message, std::move(fTRDchi2)); rc = alizmq_msg_add_array(&message, std::move(fTOFchi2)); rc = alizmq_msg_add_array(&message, std::move(fTPCsignal)); rc = alizmq_msg_add_array(&message, std::move(fTRDsignal)); rc = alizmq_msg_add_array(&message, std::move(fTOFsignal)); rc = alizmq_msg_add_array(&message, std::move(fLength)); fBytesOUT = alizmq_msg_send(&message, socket, 0); if (fBytesOUT<=0) { printf("ERROR sending: %s\n",zmq_strerror(zmq_errno())); } fNumberOfMessagesSent++; SetLastPushBackTime(); alizmq_msg_close(&message); if (fOnce) { fgTerminationSignaled=true; } return fBytesOUT; } //______________________________________________________________________________ void SetLastPushBackTime() { gettimeofday(&fCurrentTimeStruct, NULL); fLastPushBackTime = 1000 * fCurrentTimeStruct.tv_sec + fCurrentTimeStruct.tv_usec / 1000; } //_______________________________________________________________________________________ Int_t InitZMQ() { // init or reinit stuff Int_t rc = 0; rc = alizmq_socket_init(fZMQout, fZMQcontext, fZMQconfigOUT.Data(), fZMQtimeout, fZMQmaxQueueSize, fZMQlingerTime); printf("out: (%s) %s\n", alizmq_socket_name(rc), fZMQconfigOUT.Data()); return 0; } //______________________________________________________________________________ Int_t ProcessOptionString(TString arguments, Bool_t verbose) { // process passed options Int_t nOptions = 0; std::unique_ptr<aliStringVec> options{ AliOptionParser::TokenizeOptionString(arguments) }; for (auto i : *options) { const TString& option = i.first; const TString& value = i.second; if (option.EqualTo("ZMQconfigOUT") || option.EqualTo("out")) { fZMQconfigOUT = value; fReconfigureZMQ = true; } else if (option.EqualTo("in")) { Ssiz_t from{0}; TString token{}; while (value.Tokenize(token,from,",")) { fFilesIn.emplace_back(token.Data()); } } else if (option.EqualTo("Verbose")) { fVerbose = value.EqualTo("0") ? kFALSE : kTRUE; } else if (option.EqualTo("ZMQmaxQueueSize")) { fZMQmaxQueueSize = value.Atoi(); fReconfigureZMQ = true; } else if (option.EqualTo("ZMQtimeout")) { fZMQtimeout = value.Atoi(); fReconfigureZMQ = true; } else if (option.EqualTo("id")) { fID = value.Data(); } else if (option.EqualTo("once")) { fOnce = value.Atoi(); } else if (option.EqualTo("ZMQlinger")) { fZMQlingerTime = value.Atoi(); } else { Printf("unrecognized option |%s|", option.Data()); nOptions = -1; break; } nOptions++; } if (nOptions < 1) fReconfigureZMQ = false; if (fReconfigureZMQ && (InitZMQ() < 0)) { Printf("failed ZMQ init"); return -1; } fReconfigureZMQ = false; if (fRequestTimeout < 100) printf("WARNING: setting the socket timeout to %lu ms can be dagerous,\n" " choose something more realistic or leave the default as it is\n", fRequestTimeout); return nOptions; } //_______________________________________________________________________________________ int main(Int_t argc, char** argv) { Int_t mainReturnCode = 0; // catch signals if (signal(SIGHUP, sig_handler) == SIG_ERR) printf("\ncan't catch SIGHUP\n"); if (signal(SIGINT, sig_handler) == SIG_ERR) printf("\ncan't catch SIGINT\n"); if (signal(SIGQUIT, sig_handler) == SIG_ERR) printf("\ncan't catch SIGQUIT\n"); if (signal(SIGTERM, sig_handler) == SIG_ERR) printf("\ncan't catch SIGTERM\n"); // the context fZMQcontext = alizmq_context(); if (!fZMQcontext) { printf("could not init the ZMQ context\n"); return 1; } // process args TString argString = AliOptionParser::GetFullArgString(argc, argv); if (ProcessOptionString(argString, kTRUE) <= 0) { printf("%s", fUSAGE); return 1; } Run(); // destroy ZMQ sockets zmq_close(fZMQout); zmq_ctx_destroy(fZMQcontext); return mainReturnCode; } //_______________________________________________________________________________________ template <typename T> void alizmq_deleteArray(void* data, void*) { delete [] static_cast<T*>(data); } template <typename T> int alizmq_msg_add_array(aliZMQmsg* message, o2vec<T>&& vec) { //add a frame to the mesage int rc = 0; size_t nelems = vec.size(); T* array = vec.release(); Header* topic = vec.header(); //prepare topic msg zmq_msg_t* topicMsg = new zmq_msg_t; rc = zmq_msg_init_size( topicMsg, sizeof(*topic)); if (rc<0) { zmq_msg_close(topicMsg); delete topicMsg; return -1; } memcpy(zmq_msg_data(topicMsg),topic,sizeof(*topic)); size_t size = nelems*sizeof(T); //prepare data msg zmq_msg_t* dataMsg = new zmq_msg_t; rc = zmq_msg_init_data( dataMsg, array, size, alizmq_deleteArray<T>, nullptr); if (rc<0) { zmq_msg_close(topicMsg); zmq_msg_close(dataMsg); delete topicMsg; delete dataMsg; return -1; } static_cast<DataTopic*>(zmq_msg_data(topicMsg))->SetPayloadSize(size); //add the frame to the message message->push_back(std::make_pair(topicMsg,dataMsg)); return message->size(); }
33.185065
126
0.678994
shahor02
fe72501cc5bc36b6f010dd21fd28d836cc3a160a
10,485
cpp
C++
LibFoundation/Curves/Wm4BezierCurve3.cpp
wjezxujian/WildMagic4
249a17f8c447cf57c6283408e01009039810206a
[ "BSL-1.0" ]
3
2021-08-02T04:03:03.000Z
2022-01-04T07:31:20.000Z
LibFoundation/Curves/Wm4BezierCurve3.cpp
wjezxujian/WildMagic4
249a17f8c447cf57c6283408e01009039810206a
[ "BSL-1.0" ]
null
null
null
LibFoundation/Curves/Wm4BezierCurve3.cpp
wjezxujian/WildMagic4
249a17f8c447cf57c6283408e01009039810206a
[ "BSL-1.0" ]
5
2019-10-13T02:44:19.000Z
2021-08-02T04:03:10.000Z
// Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // The Wild Magic Version 4 Foundation Library source code is supplied // under the terms of the license agreement // http://www.geometrictools.com/License/Wm4FoundationLicense.pdf // and may not be copied or disclosed except in accordance with the terms // of that agreement. #include "Wm4FoundationPCH.h" #include "Wm4BezierCurve3.h" namespace Wm4 { //---------------------------------------------------------------------------- template <class Real> BezierCurve3<Real>::BezierCurve3 (int iDegree, Vector3<Real>* akCtrlPoint) : SingleCurve3<Real>((Real)0.0,(Real)1.0) { assert(iDegree >= 2); int i, j; m_iDegree = iDegree; m_iNumCtrlPoints = m_iDegree + 1; m_akCtrlPoint = akCtrlPoint; // compute first-order differences m_akDer1CtrlPoint = WM4_NEW Vector3<Real>[m_iNumCtrlPoints-1]; for (i = 0; i < m_iNumCtrlPoints-1; i++) { m_akDer1CtrlPoint[i] = m_akCtrlPoint[i+1] - m_akCtrlPoint[i]; } // compute second-order differences m_akDer2CtrlPoint = WM4_NEW Vector3<Real>[m_iNumCtrlPoints-2]; for (i = 0; i < m_iNumCtrlPoints-2; i++) { m_akDer2CtrlPoint[i] = m_akDer1CtrlPoint[i+1] - m_akDer1CtrlPoint[i]; } // compute third-order differences if (iDegree >= 3) { m_akDer3CtrlPoint = WM4_NEW Vector3<Real>[m_iNumCtrlPoints-3]; for (i = 0; i < m_iNumCtrlPoints-3; i++) { m_akDer3CtrlPoint[i] = m_akDer2CtrlPoint[i+1] - m_akDer2CtrlPoint[i]; } } else { m_akDer3CtrlPoint = 0; } // Compute combinatorial values Choose(N,K), store in m_aafChoose[N][K]. // The values m_aafChoose[r][c] are invalid for r < c (use only the // entries for r >= c). m_aafChoose = WM4_NEW Real*[m_iNumCtrlPoints]; m_aafChoose[0] = WM4_NEW Real[m_iNumCtrlPoints*m_iNumCtrlPoints]; for (i = 1; i < m_iNumCtrlPoints; i++) { m_aafChoose[i] = &m_aafChoose[0][i*m_iNumCtrlPoints]; } m_aafChoose[0][0] = (Real)1.0; m_aafChoose[1][0] = (Real)1.0; m_aafChoose[1][1] = (Real)1.0; for (i = 2; i <= m_iDegree; i++) { m_aafChoose[i][0] = (Real)1.0; m_aafChoose[i][i] = (Real)1.0; for (j = 1; j < i; j++) { m_aafChoose[i][j] = m_aafChoose[i-1][j-1] + m_aafChoose[i-1][j]; } } // variation support m_iTwoDegree = 2*m_iDegree; m_iTwoDegreePlusOne = m_iTwoDegree + 1; m_afSigma = WM4_NEW Real[m_iTwoDegreePlusOne]; m_afRecip = WM4_NEW Real[m_iTwoDegreePlusOne]; for (i = 0; i <= m_iTwoDegree; i++) { m_afSigma[i] = (Real)0.0; int iHalf = (i % 2 ? (i+1)/2 : i/2); int iStart = (i <= m_iDegree ? 0 : i - m_iDegree); Real fDot, fProd; for (j = iStart; j < iHalf; j++) { fDot = m_akCtrlPoint[j].Dot(m_akCtrlPoint[i-j]); fProd = m_aafChoose[m_iDegree][j]*m_aafChoose[m_iDegree][i-j]; m_afSigma[i] += fDot*fProd; } m_afSigma[i] *= (Real)2.0; if ((i % 2) == 0) { fDot = m_akCtrlPoint[iHalf].Dot(m_akCtrlPoint[iHalf]); fProd = m_aafChoose[m_iDegree][iHalf]; fProd *= fProd; m_afSigma[i] += fDot*fProd; } m_afRecip[i] = ((Real)1.0)/Real(m_iTwoDegreePlusOne-i); } int iTDp2 = m_iTwoDegreePlusOne+1; m_afPowT0 = WM4_NEW Real[iTDp2]; m_afPowT0[0] = (Real)1.0; m_afPowT1 = WM4_NEW Real[iTDp2]; m_afPowT1[0] = (Real)1.0; m_afPowOmT0 = WM4_NEW Real[iTDp2]; m_afPowOmT0[0] = (Real)1.0; m_afPowOmT1 = WM4_NEW Real[iTDp2]; m_afPowOmT1[0] = (Real)1.0; } //---------------------------------------------------------------------------- template <class Real> BezierCurve3<Real>::~BezierCurve3 () { WM4_DELETE[] m_afPowOmT1; WM4_DELETE[] m_afPowOmT0; WM4_DELETE[] m_afPowT1; WM4_DELETE[] m_afPowT0; WM4_DELETE[] m_afSigma; WM4_DELETE[] m_afRecip; WM4_DELETE[] m_aafChoose[0]; WM4_DELETE[] m_aafChoose; WM4_DELETE[] m_akDer3CtrlPoint; WM4_DELETE[] m_akDer2CtrlPoint; WM4_DELETE[] m_akDer1CtrlPoint; WM4_DELETE[] m_akCtrlPoint; } //---------------------------------------------------------------------------- template <class Real> int BezierCurve3<Real>::GetDegree () const { return m_iDegree; } //---------------------------------------------------------------------------- template <class Real> const Vector3<Real>* BezierCurve3<Real>::GetControlPoints () const { return m_akCtrlPoint; } //---------------------------------------------------------------------------- template <class Real> Vector3<Real> BezierCurve3<Real>::GetPosition (Real fTime) const { Real fOmTime = (Real)1.0 - fTime; Real fPowTime = fTime; Vector3<Real> kResult = fOmTime*m_akCtrlPoint[0]; for (int i = 1; i < m_iDegree; i++) { Real fCoeff = m_aafChoose[m_iDegree][i]*fPowTime; kResult = (kResult+fCoeff*m_akCtrlPoint[i])*fOmTime; fPowTime *= fTime; } kResult += fPowTime*m_akCtrlPoint[m_iDegree]; return kResult; } //---------------------------------------------------------------------------- template <class Real> Vector3<Real> BezierCurve3<Real>::GetFirstDerivative (Real fTime) const { Real fOmTime = (Real)1.0 - fTime; Real fPowTime = fTime; Vector3<Real> kResult = fOmTime*m_akDer1CtrlPoint[0]; int iDegreeM1 = m_iDegree - 1; for (int i = 1; i < iDegreeM1; i++) { Real fCoeff = m_aafChoose[iDegreeM1][i]*fPowTime; kResult = (kResult+fCoeff*m_akDer1CtrlPoint[i])*fOmTime; fPowTime *= fTime; } kResult += fPowTime*m_akDer1CtrlPoint[iDegreeM1]; kResult *= Real(m_iDegree); return kResult; } //---------------------------------------------------------------------------- template <class Real> Vector3<Real> BezierCurve3<Real>::GetSecondDerivative (Real fTime) const { Real fOmTime = (Real)1.0 - fTime; Real fPowTime = fTime; Vector3<Real> kResult = fOmTime*m_akDer2CtrlPoint[0]; int iDegreeM2 = m_iDegree - 2; for (int i = 1; i < iDegreeM2; i++) { Real fCoeff = m_aafChoose[iDegreeM2][i]*fPowTime; kResult = (kResult+fCoeff*m_akDer2CtrlPoint[i])*fOmTime; fPowTime *= fTime; } kResult += fPowTime*m_akDer2CtrlPoint[iDegreeM2]; kResult *= Real(m_iDegree*(m_iDegree-1)); return kResult; } //---------------------------------------------------------------------------- template <class Real> Vector3<Real> BezierCurve3<Real>::GetThirdDerivative (Real fTime) const { if (m_iDegree < 3) { return Vector3<Real>::ZERO; } Real fOmTime = (Real)1.0 - fTime; Real fPowTime = fTime; Vector3<Real> kResult = fOmTime*m_akDer3CtrlPoint[0]; int iDegreeM3 = m_iDegree - 3; for (int i = 1; i < iDegreeM3; i++) { Real fCoeff = m_aafChoose[iDegreeM3][i]*fPowTime; kResult = (kResult+fCoeff*m_akDer3CtrlPoint[i])*fOmTime; fPowTime *= fTime; } kResult += fPowTime*m_akDer3CtrlPoint[iDegreeM3]; kResult *= Real(m_iDegree*(m_iDegree-1)*(m_iDegree-2)); return kResult; } //---------------------------------------------------------------------------- template <class Real> Real BezierCurve3<Real>::GetVariation (Real fT0, Real fT1, const Vector3<Real>* pkP0, const Vector3<Real>* pkP1) const { int i, j, k; Vector3<Real> kP0, kP1; if (!pkP0) { kP0 = GetPosition(fT0); pkP0 = &kP0; } if (!pkP1) { kP1 = GetPosition(fT1); pkP1 = &kP1; } // compute powers of t0, t1, 1-t0, 1-t1 Real fOmT0 = (Real)1.0 - fT0; Real fOmT1 = (Real)1.0 - fT1; for (i = 1, j = 0; i <= m_iTwoDegreePlusOne; i++, j++) { m_afPowT0[i] = fT0*m_afPowT0[j]; m_afPowT1[i] = fT1*m_afPowT1[j]; m_afPowOmT0[i] = fOmT0*m_afPowOmT0[j]; m_afPowOmT1[i] = fOmT1*m_afPowOmT1[j]; } // line segment is L(t) = P0 + ((t-t0)/(t1-t0))*(P1-P0) // var1 = integral(Dot(L,L)) static const Real s_fOneThird = ((Real)1.0)/(Real)3.0; Real fDT = fT1 - fT0; Real fP0P0 = pkP0->Dot(*pkP0); Real fP0P1 = pkP0->Dot(*pkP1); Real fP1P1 = pkP1->Dot(*pkP1); Real fVar1 = s_fOneThird*fDT*(fP0P0 + fP0P1 + fP1P1); // var2 = integral(Dot(X,P0)) // var3 = integral(Dot(X,P1-P0)*(t-t0)/(t1-t0)) Real fVar2 = (Real)0.0; Real fVar3 = (Real)0.0; Vector3<Real> kDir = *pkP1 - *pkP0; Real fIint = (Real)0.0; int iDp2 = m_iDegree+2, iDm1 = m_iDegree-1; Real fJint = (m_afPowOmT0[iDp2] - m_afPowOmT1[iDp2])*m_afRecip[iDm1]; Real fProd0, fProd1, fDot; for (i = 0, j = m_iDegree, k = m_iDegree+1; i <= m_iDegree; i++, j++, k--) { // compute I[i] fProd0 = m_afPowT0[i]*m_afPowOmT0[k]; fProd1 = m_afPowT1[i]*m_afPowOmT1[k]; fIint = (fProd0 - fProd1 + i*fIint)*m_afRecip[j]; // compute J[i] fProd0 = m_afPowT0[i+1]*m_afPowOmT0[k]; fProd1 = m_afPowT1[i+1]*m_afPowOmT1[k]; fJint = (fProd0 - fProd1 + (i+1)*fJint)*m_afRecip[j]; // update partial variations fDot = pkP0->Dot(m_akCtrlPoint[i]); fProd0 = m_aafChoose[m_iDegree][i]*fDot; fVar2 += fProd0*fIint; fDot = kDir.Dot(m_akCtrlPoint[i]); fProd0 = m_aafChoose[m_iDegree][i]*fDot; fVar3 += fProd0*(fJint - fT0*fIint); } fVar3 /= fDT; // var4 = integral(Dot(X,X)) Real fVar4 = (Real)0.0; Real fKint = (Real)0.0; for (i = 0, j = m_iTwoDegreePlusOne; i <= m_iTwoDegree; i++, j--) { // compute K[i] fProd0 = m_afPowT0[i]*m_afPowOmT0[j]; fProd1 = m_afPowT1[i]*m_afPowOmT1[j]; fKint = (fProd0 - fProd1 + i*fKint)*m_afRecip[i]; // update partial variation fVar4 += m_afSigma[i]*fKint; } Real fVar = fVar1 - ((Real)2.0)*(fVar2 + fVar3) + fVar4; return fVar; } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // explicit instantiation //---------------------------------------------------------------------------- template WM4_FOUNDATION_ITEM class BezierCurve3<float>; template WM4_FOUNDATION_ITEM class BezierCurve3<double>; //---------------------------------------------------------------------------- }
30.838235
78
0.548784
wjezxujian
fe7451a36dd2930fea9af116943e8808fa4078d5
1,332
hpp
C++
src/Switch.Core/include/Switch/System/IFormatProvider.hpp
victor-timoshin/Switch
8e8e687a8bdc4f79d482680da3968e9b3e464b8b
[ "MIT" ]
4
2020-02-11T13:22:58.000Z
2022-02-24T00:37:43.000Z
src/Switch.Core/include/Switch/System/IFormatProvider.hpp
sgf/Switch
8e8e687a8bdc4f79d482680da3968e9b3e464b8b
[ "MIT" ]
null
null
null
src/Switch.Core/include/Switch/System/IFormatProvider.hpp
sgf/Switch
8e8e687a8bdc4f79d482680da3968e9b3e464b8b
[ "MIT" ]
2
2020-02-01T02:19:01.000Z
2021-12-30T06:44:00.000Z
/// @file /// @brief Contains Switch::System::IFormatProvider interface. #pragma once #include "../Interface.hpp" #include "Object.hpp" #include "Type.hpp" /// @cond namespace Switch { namespace System { class Type; } } /// @endcond /// @brief The Switch namespace contains all fundamental classes to access Hardware, Os, System, and more. namespace Switch { /// @brief The System namespace contains fundamental classes and base classes that define commonly-used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions. namespace System { /// @interface IFormatProvider /// @brief Provides a mechanism for retrieving an object to control formatting. /// @par Library /// Switch.Core class core_export_ IFormatProvider interface_ { public: /// @brief Returns an object that provides formatting services for the specified type. /// @param type An object that specifies the type of format object to return. /// @return object An instance of the object specified by formatType, if the IFormatProvider implementation can supply that type of object; otherwise, nullNothingnullptra null reference (Nothing in Visual Basic). virtual const Object& GetFormat(const Type& type) const = 0; }; } } using namespace Switch;
37
218
0.731231
victor-timoshin
fe762264675ebe43ba8af74eb4817a0d0bdace63
2,923
cpp
C++
src/example/main.cpp
Blitzman/practica-sistemas-percepcion-mayr
fbee0739b70bceadfc955a36207573fd31ca2e35
[ "MIT" ]
1
2016-01-12T22:10:16.000Z
2016-01-12T22:10:16.000Z
src/example/main.cpp
Blitzman/practica-sistemas-percepcion-mayr
fbee0739b70bceadfc955a36207573fd31ca2e35
[ "MIT" ]
null
null
null
src/example/main.cpp
Blitzman/practica-sistemas-percepcion-mayr
fbee0739b70bceadfc955a36207573fd31ca2e35
[ "MIT" ]
null
null
null
#include "ImageShapeSegmentation.hpp" #include "ImageColorSegmentation.hpp" #include "Shape.hpp" // #include <opencv2/opencv.hpp> #include <opencv2/core/core.hpp> #include <opencv2/imgcodecs.hpp> #include <opencv2/highgui/highgui.hpp> #include <iostream> #include <glob.h> #include <unistd.h> #include <limits.h> std::vector<std::string> globVector(const std::string& pattern){ glob_t glob_result; glob(pattern.c_str(),GLOB_TILDE,NULL,&glob_result); std::vector<std::string> files; for(unsigned int i=0;i<glob_result.gl_pathc;++i){ files.push_back(std::string(glob_result.gl_pathv[i])); } globfree(&glob_result); return files; } void merge_shapes(std::vector<Shape> & rShapesColor, std::vector<Shape> & rShapesShape) { for (unsigned int i = 0; i < rShapesColor.size(); ++i) { unsigned int min_index_ = 0; double min_distance_ = std::numeric_limits<double>::max(); cv::Point c_c_ = rShapesColor[i].getCentroid(); for (unsigned int j = 0; j < rShapesShape.size(); ++j) { cv::Point c_s_ = rShapesShape[j].get_vertex_centroid(); double distance_ = cv::norm(c_c_ - c_s_); if (distance_ < min_distance_) { min_distance_ = distance_; min_index_ = j; } } rShapesShape[min_index_].m_point_list = rShapesColor[i].m_point_list; std::cout << "Color[" << i << "] corresponds to Shape[" << min_index_ << "]...\n"; } } int main(int argc, char** argv ) { std::vector<std::string> files = globVector("../resources/*"); cv::Size size(640, 480); for(int i = 0; i < files.size(); i++) { cv::Mat frame; std::cout << files[i] << std::endl; std::vector<Shape> shapes_color_; ImageColorSegmentation ics(files[i]); ics.setHistogramOutput(false); ics.process(ImageColorSegmentation::HLS, frame, shapes_color_); cv::Mat color_resized; resize(frame, color_resized, size); cv::namedWindow( "DisplayWindow" ); // Create a window for display. cv::imshow("DisplayWindow", color_resized ); cv::Mat frame_shape_; ImageShapeSegmentation iss_(files[i]); iss_.process(frame_shape_); cv::Mat shape_resized_; resize(frame_shape_, shape_resized_, size); cv::namedWindow("DisplayWindow2"); cv::imshow("DisplayWindow2", shape_resized_); cv::Mat final_image_; final_image_ = cv::imread(files[i]); std::vector<Shape> shapes_shape_ = iss_.get_shapes(); merge_shapes(shapes_color_, shapes_shape_); std::cout << "Drawing shapes...\n"; for (Shape s_ : shapes_shape_) { s_.draw_name(final_image_, cv::Scalar(0, 0, 0)); s_.draw_box(final_image_, cv::Scalar(0, 0, 0)); s_.draw_contour(final_image_, cv::Scalar(0, 0, 0)); } std::cout << "Showing image...\n"; cv::Mat final_image_resized_; resize(final_image_, final_image_resized_, size); cv::namedWindow("Semantic Image"); cv::imshow("Semantic Image", final_image_resized_); cv::waitKey(0); } cv::waitKey(0); // */ return 0; }
27.575472
87
0.678413
Blitzman
fe767127bd898fc9ef5f40f66ca6aa7b796d2e8e
187
cc
C++
lib/libfaeris/src/stage/action/FsAction.cc
NosicLin/Faeris
018fddccc875fb63347673edef3ad2ff80c87149
[ "MIT" ]
null
null
null
lib/libfaeris/src/stage/action/FsAction.cc
NosicLin/Faeris
018fddccc875fb63347673edef3ad2ff80c87149
[ "MIT" ]
null
null
null
lib/libfaeris/src/stage/action/FsAction.cc
NosicLin/Faeris
018fddccc875fb63347673edef3ad2ff80c87149
[ "MIT" ]
null
null
null
#include "stage/action/FsAction.h" #include "stage/FsScene.h" #include "mgr/FsObjectMgr.h" NS_FS_BEGIN const char* Action::className() { return FS_ACTION_CLASS_NAME; } NS_FS_END
10.388889
34
0.743316
NosicLin
fe7d985981eb3878d0572909d9dd7bde74176ff3
407
hpp
C++
optionals/police/script_component.hpp
kellerkompanie/kellerkompanie-mods
f15704710f77ba6c018c486d95cac4f7749d33b8
[ "MIT" ]
6
2018-05-05T22:28:57.000Z
2019-07-06T08:46:51.000Z
optionals/police/script_component.hpp
Schwaggot/kellerkompanie-mods
7a389e49e3675866dbde1b317a44892926976e9d
[ "MIT" ]
107
2018-04-11T19:42:27.000Z
2019-09-13T19:05:31.000Z
optionals/police/script_component.hpp
kellerkompanie/kellerkompanie-mods
f15704710f77ba6c018c486d95cac4f7749d33b8
[ "MIT" ]
3
2018-10-03T11:54:46.000Z
2019-02-28T13:30:16.000Z
#define COMPONENT police #define COMPONENT_BEAUTIFIED Police #include "\x\keko\addons\main\script_mod.hpp" // #define DEBUG_MODE_FULL // #define DISABLE_COMPILE_CACHE // #define ENABLE_PERFORMANCE_COUNTERS #ifdef DEBUG_ENABLED_POLICE #define DEBUG_MODE_FULL #endif #ifdef DEBUG_SETTINGS_POLICE #define DEBUG_SETTINGS DEBUG_SETTINGS_POLICE #endif #include "\x\keko\addons\main\script_macros.hpp"
22.611111
48
0.810811
kellerkompanie
fe7f082e879f6de9992cc0d134b84755c45860a0
594
hpp
C++
libs/mpi/include/hpx/mpi/force_linking.hpp
picanumber/hpx
76d6fe0bf4bd7f23e62c170fd8a0c8dbed66ec7d
[ "BSL-1.0" ]
null
null
null
libs/mpi/include/hpx/mpi/force_linking.hpp
picanumber/hpx
76d6fe0bf4bd7f23e62c170fd8a0c8dbed66ec7d
[ "BSL-1.0" ]
null
null
null
libs/mpi/include/hpx/mpi/force_linking.hpp
picanumber/hpx
76d6fe0bf4bd7f23e62c170fd8a0c8dbed66ec7d
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2019-2020 The STE||AR GROUP // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #if !defined(HPX_MPI_FORCE_LINKING_HPP) #define HPX_MPI_FORCE_LINKING_HPP #include <hpx/config.hpp> #include <hpx/mpi/mpi_future.hpp> #include <mpi.h> namespace hpx { namespace mpi { struct force_linking_helper { MPI_Errhandler* mpi_errhandler; }; force_linking_helper& force_linking(); }} // namespace hpx::mpi #endif
22.846154
80
0.718855
picanumber
fe8237956999f51fa4cc7487791f7ede9cc73e07
1,792
cpp
C++
codes/CSES/CSES_1082.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
2
2021-03-07T03:34:02.000Z
2021-03-09T01:22:21.000Z
codes/CSES/CSES_1082.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
1
2021-03-27T15:01:23.000Z
2021-03-27T15:55:34.000Z
codes/CSES/CSES_1082.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
1
2021-03-27T05:02:33.000Z
2021-03-27T05:02:33.000Z
#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <ctime> #include <cmath> #include <cassert> #include <algorithm> #include <vector> #include <string> #include <map> #include <set> #include <sstream> #include <list> #include <queue> #include <stack> //#include <unordered_map> //#include <unordered_set> #include <functional> #define max_v 1100 #define LOGN 50 #define int_max 0x3f3f3f3f #define cont continue #define byte_max 0x3f #define pow_2(n) (1 << (n)) //tree #define lsb(n) ((n)&(-(n))) #define LC(n) (((n) << 1) + 1) #define RC(n) (((n) << 1) + 2) #define LOG2(n) ((int)(ceil(log2((n))))) using namespace std; void setIO(const string& file_name){ freopen((file_name+".in").c_str(), "r", stdin); freopen((file_name+".out").c_str(), "w+", stdout); } const long long mod = (long long)1e9 + 7; long long F(long long a, long long b){// returns sym of all integers [a, b] if(a > b) swap(a, b); long long A = (b + 1ll - a) % mod; long long B = ((a%mod) * A) % mod; long long C = ((b - a) % 2ll) ? b - a : (b - a) / 2ll; long long D = ((b + 1ll - a) % 2ll) ? b + 1ll - a : (b + 1ll- a) / 2ll; C %= mod; D %= mod; return ((C * D) % mod + B) % mod; } int main(){ long long n, tot = 0ll; scanf("%lld", &n); for(long long i = 1ll; n/i>(long long)floor(sqrt(n)); i += 1ll){ (tot += F(n/i, 1ll + (n/(i + 1ll))) * (i%mod)) %= mod; //printf("%lld %lld -> %lld\n", n/i, 1ll + (n/(i + 1ll)), F(n/i, 1ll + (n/(i + 1ll) * i))); } //printf("%lld\n", tot); //for(int i = 0; i<n; i++){ //long long a, b; //scanf("%lld%lld", &a, &b); //printf("%lld\n", F(a, b)); //} for(long long i = 1ll; i<=(long long)floor(sqrt(n)); i += 1ll){ (tot += (i%mod) * (n/i)) %= mod; } printf("%lld\n", tot); return 0; }
24.547945
96
0.551339
chessbot108
fe826b21359e277df6a7733a204f9b7aedcb4108
168
hpp
C++
libng/compiler/src/libng_compiler/json/JSONLexer.hpp
gapry/libng
8fbf927e5bb73f105bddbb618430d3e1bf2cf877
[ "MIT" ]
null
null
null
libng/compiler/src/libng_compiler/json/JSONLexer.hpp
gapry/libng
8fbf927e5bb73f105bddbb618430d3e1bf2cf877
[ "MIT" ]
null
null
null
libng/compiler/src/libng_compiler/json/JSONLexer.hpp
gapry/libng
8fbf927e5bb73f105bddbb618430d3e1bf2cf877
[ "MIT" ]
null
null
null
#pragma once #include <libng_core/types/noncopyable.hpp> namespace libng { class JSONLexer : public NonCopyable { public: void nextChar(); }; } // namespace libng
14
43
0.732143
gapry
fe839e09cdefe36f43533cb0a79f8c91718bac98
1,570
hh
C++
src/opbox/core/Singleton.hh
faodel/faodel
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
[ "MIT" ]
2
2019-01-25T21:21:07.000Z
2021-04-29T17:24:00.000Z
src/opbox/core/Singleton.hh
faodel/faodel
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
[ "MIT" ]
8
2018-10-09T14:35:30.000Z
2020-09-30T20:09:42.000Z
src/opbox/core/Singleton.hh
faodel/faodel
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
[ "MIT" ]
2
2019-04-23T19:01:36.000Z
2021-05-11T07:44:55.000Z
// Copyright 2021 National Technology & Engineering Solutions of Sandia, LLC // (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. // Government retains certain rights in this software. #ifndef OPBOX_SINGLETON_HH #define OPBOX_SINGLETON_HH #include "faodel-common/Common.hh" #include "faodel-common/LoggingInterface.hh" #include "opbox/common/Types.hh" #include "opbox/OpBox.hh" #include "opbox/common/OpRegistry.hh" #include "opbox/core/OpBoxCoreBase.hh" #include "opbox/core/OpBoxCoreUnconfigured.hh" namespace opbox { namespace internal { /** * @brief The actual OpBox singleton, which manages bootstraps * */ class SingletonImpl : public faodel::bootstrap::BootstrapInterface, public faodel::LoggingInterface { public: SingletonImpl(); ~SingletonImpl() override; bool IsUnconfigured(); //Bootstrap API void Init(const faodel::Configuration &config) override; void Start() override; void Finish() override; void GetBootstrapDependencies(std::string &name, std::vector<std::string> &requires, std::vector<std::string> &optional) const override; void whookieInfoRegistry(faodel::ReplyStream &rs) { return registry.whookieInfo(rs); } OpRegistry registry; OpBoxCoreBase *core; private: OpBoxCoreUnconfigured unconfigured; }; /** * @brief A static placeholder for opbox's singleton */ class Singleton { public: static opbox::internal::SingletonImpl impl; }; } // namespace internal } // namespace opbox #endif // OPBOX_OPBOXSINGLETON_HH
21.506849
88
0.724841
faodel
fe866af8d807379922aef9e74916d21abfebe0e2
2,143
cpp
C++
tests/unit/net/collect-netifs.cpp
KITE-2018/kite-ndn-cxx
2a674e2bab42a39d0731b0a30c4d49369b084c1c
[ "OpenSSL" ]
4
2021-04-21T02:48:49.000Z
2021-06-25T06:08:58.000Z
tests/unit/net/collect-netifs.cpp
KITE-2018/kite-ndn-cxx
2a674e2bab42a39d0731b0a30c4d49369b084c1c
[ "OpenSSL" ]
11
2020-12-27T23:02:56.000Z
2021-10-18T08:00:50.000Z
tests/unit/net/collect-netifs.cpp
KITE-2018/kite-ndn-cxx
2a674e2bab42a39d0731b0a30c4d49369b084c1c
[ "OpenSSL" ]
3
2021-02-28T10:04:09.000Z
2021-09-23T05:01:00.000Z
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2013-2018 Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, * Washington University in St. Louis, * Beijing Institute of Technology, * The University of Memphis. * * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions). * * ndn-cxx library is free software: you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later version. * * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received copies of the GNU General Public License and GNU Lesser * General Public License along with ndn-cxx, e.g., in COPYING.md file. If not, see * <http://www.gnu.org/licenses/>. * * See AUTHORS.md for complete list of ndn-cxx authors and contributors. */ #include "tests/unit/net/collect-netifs.hpp" #include "ndn-cxx/net/network-monitor.hpp" #include <boost/asio/io_service.hpp> namespace ndn { namespace net { namespace tests { std::vector<shared_ptr<const NetworkInterface>> collectNetworkInterfaces(bool allowCached) { static optional<std::vector<shared_ptr<const NetworkInterface>>> cached; if (!allowCached || !cached) { boost::asio::io_service io; NetworkMonitor netmon(io); if (netmon.getCapabilities() & NetworkMonitor::CAP_ENUM) { netmon.onEnumerationCompleted.connect([&io] { io.stop(); }); io.run(); io.reset(); } cached = netmon.listNetworkInterfaces(); } return *cached; } } // namespace tests } // namespace net } // namespace ndn
35.716667
87
0.673355
KITE-2018
fe867d89e878f21b412b2d01c662f100e5629058
6,475
hpp
C++
DiligentCore/Graphics/GraphicsEngineD3D12/include/ShaderResourcesD3D12.hpp
JorisSAN/DiligentEngine
5701b916bc2e9fefab1cf5ad0d20d4b6bb0f64c5
[ "Apache-2.0" ]
null
null
null
DiligentCore/Graphics/GraphicsEngineD3D12/include/ShaderResourcesD3D12.hpp
JorisSAN/DiligentEngine
5701b916bc2e9fefab1cf5ad0d20d4b6bb0f64c5
[ "Apache-2.0" ]
null
null
null
DiligentCore/Graphics/GraphicsEngineD3D12/include/ShaderResourcesD3D12.hpp
JorisSAN/DiligentEngine
5701b916bc2e9fefab1cf5ad0d20d4b6bb0f64c5
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019-2020 Diligent Graphics LLC * Copyright 2015-2019 Egor Yusov * * 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. * * In no event and under no legal theory, whether in tort (including negligence), * contract, or otherwise, unless required by applicable law (such as deliberate * and grossly negligent acts) or agreed to in writing, shall any Contributor be * liable for any damages, including any direct, indirect, special, incidental, * or consequential damages of any character arising as a result of this License or * out of the use or inability to use the software (including but not limited to damages * for loss of goodwill, work stoppage, computer failure or malfunction, or any and * all other commercial damages or losses), even if such Contributor has been advised * of the possibility of such damages. */ #pragma once /// \file /// Declaration of Diligent::ShaderResourcesD3D12 class // ShaderResourcesD3D12 are created by ShaderD3D12Impl instances. They are then referenced by ShaderResourceLayoutD3D12 objects, which are in turn // created by instances of PipelineStatesD3D12Impl and ShaderD3D12Impl // // _________________ // | | // | ShaderD3D12Impl | // |_________________| // | // |shared_ptr // ________V_____________ _____________________________________________________________________ // | | unique_ptr | | | | | | | // | ShaderResourcesD3D12 |--------------->| CBs | TexSRVs | TexUAVs | BufSRVs | BufUAVs | Samplers | // |______________________| |________|___________|___________|___________|___________|____________| // A A A A // | \ / \ // |shared_ptr Ref Ref Ref // ________|__________________ ________\________________________/_________________________\_________________________________________ // | | unique_ptr | | | | | | | // | ShaderResourceLayoutD3D12 |--------------->| SRV_CBV_UAV[0] | SRV_CBV_UAV[1] | ... | Sampler[0] | Sampler[1] | ... | // |___________________________| |___________________|_________________|_______________|__________________|_________________|__________| // A | A // | |___________________SamplerId________________________| // | // __________|_____________ // | | // | PipelineStateD3D12Impl | // |________________________| // // // // One ShaderResourcesD3D12 instance can be referenced by multiple objects // // // ________________________ _<m_pShaderResourceLayouts>_ _____<m_pShaderVarMgrs>_____ ________________________________ // | | | | | | | | // | PipelineStateD3D12Impl |========>| ShaderResourceLayoutD3D12 |<-------| ShaderVariableManagerD3D12 |<====| ShaderResourceBindingD3D12Impl | // |________________________| |____________________________| |____________________________| |________________________________| // | A // |shared_ptr \ // _________________ ___________V__________ \ _____<m_pShaderVarMgrs>_____ ________________________________ // | | shared_ptr | | \ | | | | // | ShaderD3D12Impl |---------------->| ShaderResourcesD3D12 | '-------| ShaderVariableManagerD3D12 |<====| ShaderResourceBindingD3D12Impl | // |_________________| |______________________| |____________________________| |________________________________| // | |___________________ A // | | | // V V |shared_ptr // _______<m_StaticVarsMgr>____ ___<m_StaticResLayout>_|___ // | | | | // | ShaderVariableManagerD3D12 |------>| ShaderResourceLayoutD3D12 | // |____________________________| |___________________________| // #include "ShaderResources.hpp" namespace Diligent { /// Diligent::ShaderResourcesD3D12 class class ShaderResourcesD3D12 final : public ShaderResources { public: // Loads shader resources from the compiled shader bytecode ShaderResourcesD3D12(ID3DBlob* pShaderBytecode, const ShaderDesc& ShdrDesc, const char* CombinedSamplerSuffix, class IDXCompiler* pDXCompiler); // clang-format off ShaderResourcesD3D12 (const ShaderResourcesD3D12&) = delete; ShaderResourcesD3D12 ( ShaderResourcesD3D12&&) = delete; ShaderResourcesD3D12& operator = (const ShaderResourcesD3D12&) = delete; ShaderResourcesD3D12& operator = ( ShaderResourcesD3D12&&) = delete; // clang-format on }; } // namespace Diligent
59.40367
156
0.538378
JorisSAN
fe86846b105a5ea4e975a89739dd7b0fce99e98c
5,916
cc
C++
cpp_src/cmd/reindexer_server/winservice.cc
Smolevich/reindexer
139a27a5f07023af40e08b6f9e9b27abb9bc4939
[ "Apache-2.0" ]
null
null
null
cpp_src/cmd/reindexer_server/winservice.cc
Smolevich/reindexer
139a27a5f07023af40e08b6f9e9b27abb9bc4939
[ "Apache-2.0" ]
null
null
null
cpp_src/cmd/reindexer_server/winservice.cc
Smolevich/reindexer
139a27a5f07023af40e08b6f9e9b27abb9bc4939
[ "Apache-2.0" ]
null
null
null
#ifdef _WIN32 #include <assert.h> #include <malloc.h> #include <stdarg.h> #include <stdio.h> #include <string.h> #include "winservice.h" namespace reindexer_server { #define SERVER_STOP_WAIT 5000 #define SERVER_START_WAIT 5000 WinService *g_Service; static std::string GetLastErrorAsString() { // Get the error message, if any. DWORD errorMessageID = ::GetLastError(); if (errorMessageID == 0) return std::string(); // No error message has been recorded LPSTR messageBuffer = nullptr; size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), LPSTR(&messageBuffer), 0, NULL); std::string message(messageBuffer, size); // Free the buffer. LocalFree(messageBuffer); return message; } WinService::WinService(const std::string &name, const std::string &displayName, std::function<void(void)> run, std::function<void(void)> terminate, std::function<bool(void)> status) : name_(name), displayName_(displayName), run_(run), terminate_(terminate), status_(status) { g_Service = this; sshStatusHandle_ = NULL; } WinService::~WinService() { g_Service = 0; } void WinService::Message(bool bError, const char *fmt, ...) { va_list va; va_start(va, fmt); char tempBuf[4096]; vsprintf(tempBuf, fmt, va); MessageBox(NULL, tempBuf, displayName_.c_str(), MB_OK | (bError ? MB_ICONSTOP : MB_ICONINFORMATION)); va_end(va); } static VOID WINAPI ServiceCtrl(DWORD dwCtrlCode) { assert(g_Service); g_Service->ServiceCtrl(dwCtrlCode); } static void WINAPI ServiceMain(DWORD dwArgc, LPTSTR lpszArgv[]) { assert(g_Service); g_Service->MainInternal(dwArgc, lpszArgv); } void WinService::ServiceCtrl(DWORD dwCtrlCode) { switch (dwCtrlCode) { case SERVICE_CONTROL_SHUTDOWN: case SERVICE_CONTROL_STOP: ReportStatusToSCMgr(SERVICE_STOP_PENDING, NO_ERROR, SERVER_STOP_WAIT); terminate_(); while (status_()) { Sleep(1000); ReportStatusToSCMgr(SERVICE_STOP_PENDING, NO_ERROR, SERVER_STOP_WAIT); } ReportStatusToSCMgr(SERVICE_STOPPED, 0, 0); break; default: ReportStatusToSCMgr(ssStatus_.dwCurrentState, NO_ERROR, 0); } } void WinService::MainInternal(DWORD dwArgc, LPTSTR lpszArgv[]) { (void)dwArgc; (void)lpszArgv; if ((sshStatusHandle_ = RegisterServiceCtrlHandler(name_.c_str(), reindexer_server::ServiceCtrl)) != NULL) { memset(&ssStatus_, 0, sizeof(ssStatus_)); ssStatus_.dwServiceType = SERVICE_WIN32_OWN_PROCESS; ssStatus_.dwServiceSpecificExitCode = 0; if (ReportStatusToSCMgr(SERVICE_START_PENDING, NO_ERROR, SERVER_START_WAIT)) { ReportStatusToSCMgr(SERVICE_RUNNING, NO_ERROR, 0); run_(); } ReportStatusToSCMgr(SERVICE_STOPPED, 0, 0); } } bool WinService::ReportStatusToSCMgr(DWORD dwCurrentState, DWORD dwWin32ExitCode, DWORD dwWaitHint) { static DWORD dwCheckPoint = 1; if (dwCurrentState == SERVICE_START_PENDING) ssStatus_.dwControlsAccepted = 0; else ssStatus_.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN; ssStatus_.dwCurrentState = dwCurrentState; ssStatus_.dwWin32ExitCode = dwWin32ExitCode; ssStatus_.dwWaitHint = dwWaitHint; if ((dwCurrentState == SERVICE_RUNNING) || (dwCurrentState == SERVICE_STOPPED)) ssStatus_.dwCheckPoint = 0; else ssStatus_.dwCheckPoint = dwCheckPoint++; return SetServiceStatus(sshStatusHandle_, &ssStatus_); } bool WinService::Install(const char *cmdline) { SC_HANDLE schService = NULL, schSCManager = NULL; Remove(true); if ((schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS)) != NULL) { schService = CreateService(schSCManager, // SCManager database name_.c_str(), // name of service displayName_.c_str(), // name to display SERVICE_ALL_ACCESS, // desired access SERVICE_WIN32_OWN_PROCESS, // service type SERVICE_AUTO_START, // start type SERVICE_ERROR_NORMAL, // error control type cmdline, // service's binary NULL, // no load ordering group NULL, // no tag identifier NULL, // dependencies NULL, // LocalSystem account NULL); // no password if (schService != NULL) { CloseServiceHandle(schService); CloseServiceHandle(schSCManager); return true; } else Message(false, "CreateService failed:\n%s\n", GetLastErrorAsString().c_str()); CloseServiceHandle(schSCManager); } else { Message(true, "OpenSCManager failed:\n%s\n", GetLastErrorAsString().c_str()); } return false; } int WinService::Start() { SERVICE_TABLE_ENTRY DispTable[] = {{const_cast<char *>(name_.c_str()), ServiceMain}, {NULL, NULL}}; StartServiceCtrlDispatcher(DispTable); return 0; } bool WinService::Remove(bool silent) { SC_HANDLE schService = NULL, schSCManager = NULL; if ((schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS)) != NULL) { schService = OpenService(schSCManager, name_.c_str(), SERVICE_ALL_ACCESS); if (schService != NULL) { if (ControlService(schService, SERVICE_CONTROL_STOP, &ssStatus_)) { Sleep(1000); while (QueryServiceStatus(schService, &ssStatus_)) { if (ssStatus_.dwCurrentState == SERVICE_STOP_PENDING) { Sleep(1000); } else break; } } if (DeleteService(schService)) { CloseServiceHandle(schService); CloseServiceHandle(schSCManager); return true; } else if (!silent) Message(true, "DeleteService failed:\n%s\n", GetLastErrorAsString().c_str()); CloseServiceHandle(schService); } else if (!silent) Message(true, "OpenService failed:\n%s\n", GetLastErrorAsString().c_str()); CloseServiceHandle(schSCManager); } else if (!silent) Message(true, "OpenSCManager failed:\n%s\n", GetLastErrorAsString().c_str()); return false; } } // namespace reindexer_server #endif
30.338462
128
0.717039
Smolevich
fe86b335bcfde6ccd185480177f1c4ba55265787
1,808
hpp
C++
Axis/System/Include/Axis/StaticArray.hpp
SimmyPeet/Axis
a58c073d13f74d0224fbfca34a4dcd4b9d0c6726
[ "Apache-2.0" ]
1
2022-01-23T14:51:51.000Z
2022-01-23T14:51:51.000Z
Axis/System/Include/Axis/StaticArray.hpp
SimmyPeet/Axis
a58c073d13f74d0224fbfca34a4dcd4b9d0c6726
[ "Apache-2.0" ]
null
null
null
Axis/System/Include/Axis/StaticArray.hpp
SimmyPeet/Axis
a58c073d13f74d0224fbfca34a4dcd4b9d0c6726
[ "Apache-2.0" ]
1
2022-01-10T21:01:54.000Z
2022-01-10T21:01:54.000Z
/// \copyright Simmypeet - Copyright (C) /// This file is subject to the terms and conditions defined in /// file 'LICENSE', which is part of this source code package. #ifndef AXIS_SYSTEM_STATICARRAY_HPP #define AXIS_SYSTEM_STATICARRAY_HPP #pragma once #include "Config.hpp" #include "Trait.hpp" namespace Axis { namespace System { /// \brief The wrapper over the compile-time known size array. /// /// \warning This class doesn't provide strong exception safety. template <RawType T, Size N> struct StaticArray { public: /// \brief The length of the static array. static constexpr Size Length = N; /// \brief Gets the length of the array. AXIS_NODISCARD constexpr Size GetLength() const noexcept; /// \brief Indexing operator. Gets the reference to the element at the specified index. /// /// \param[in] index The index of the element. /// /// \return The reference to the element at the specified index. AXIS_NODISCARD constexpr T& operator[](Size index); /// \brief Indexing operator. Gets the reference to the element at the specified index. /// AXIS_NODISCARD constexpr const T& operator[](Size index) const; /// \brief Iterator begin AXIS_NODISCARD constexpr T* begin() noexcept; /// \brief Const iterator begin AXIS_NODISCARD constexpr const T* begin() const noexcept; /// \brief Iterator end AXIS_NODISCARD constexpr T* end() noexcept; /// \brief Const iterator end AXIS_NODISCARD constexpr const T* end() const noexcept; /// \brief The internal stack allocated array. T _Elements[N] = {}; // Initializes array with default constructor }; } // namespace System } // namespace Axis #include "../../Private/Axis/StaticArrayImpl.inl" #endif // AXIS_SYSTEM_STATICARRAY_HPP
27.815385
91
0.698009
SimmyPeet
fe87c0963d761c1fffb1b6db7fdf0e1d9250163b
5,605
cc
C++
ggeo/GGeoGLTF.cc
hanswenzel/opticks
b75b5929b6cf36a5eedeffb3031af2920f75f9f0
[ "Apache-2.0" ]
11
2020-07-05T02:39:32.000Z
2022-03-20T18:52:44.000Z
ggeo/GGeoGLTF.cc
hanswenzel/opticks
b75b5929b6cf36a5eedeffb3031af2920f75f9f0
[ "Apache-2.0" ]
null
null
null
ggeo/GGeoGLTF.cc
hanswenzel/opticks
b75b5929b6cf36a5eedeffb3031af2920f75f9f0
[ "Apache-2.0" ]
4
2020-09-03T20:36:32.000Z
2022-01-19T07:42:21.000Z
/* * Copyright (c) 2019 Opticks Team. All Rights Reserved. * * This file is part of Opticks * (see https://bitbucket.org/simoncblyth/opticks). * * 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 "BFile.hh" #include "GGeo.hh" #include "GMesh.hh" #include "GVolume.hh" #include "GMaterialLib.hh" #include "GBndLib.hh" #include "GGeoGLTF.hh" #include "NNode.hpp" #include "NCSG.hpp" #include "YOG.hh" #include "YOGMaker.hh" #include "PLOG.hh" using YOG::Sc ; using YOG::Nd ; using YOG::Mh ; using YOG::Maker ; const plog::Severity GGeoGLTF::LEVEL = debug ; void GGeoGLTF::Save( const GGeo* ggeo, const char* path, int root ) // static { GGeoGLTF tf(ggeo); tf.save(path, root); } GGeoGLTF::GGeoGLTF( const GGeo* ggeo ) : m_ggeo(ggeo), m_mlib(ggeo->getMaterialLib()), m_blib(ggeo->getBndLib()), m_sc(new YOG::Sc(0)), m_maker(NULL) { init(); } void GGeoGLTF::init() { addMaterials(); addMeshes(); addNodes(); } void GGeoGLTF::addMaterials() { unsigned num_materials = m_mlib->getNumMaterials(); for(size_t i=0 ; i < num_materials ; i++) { const char* name = m_mlib->getName(i); int idx = m_sc->add_material(name); assert( idx == int(i) ); } } void GGeoGLTF::addMeshes() { unsigned num_meshes = m_ggeo->getNumMeshes(); for(unsigned i=0 ; i < num_meshes ; i++) { int lvIdx = i ; const GMesh* mesh = m_ggeo->getMesh(lvIdx); const NCSG* csg = mesh->getCSG(); const nnode* root = mesh->getRoot(); const nnode* raw = root->other ; std::string lvname = csg->get_lvname(); // <-- probably wont work postcache : IT DOES NOW VIA METADATA std::string soname = csg->get_soname(); LOG(verbose) << " lvIdx " << lvIdx << " lvname " << lvname << " soname " << soname ; int soIdx = m_sc->add_mesh( lvIdx, lvname.c_str(), soname.c_str() ); assert( soIdx == int(lvIdx) ); Mh* mh = m_sc->meshes[lvIdx] ; mh->mesh = mesh ; mh->csg = csg ; mh->csgnode = root ; mh->vtx = mesh->m_x4src_vtx ; mh->idx = mesh->m_x4src_idx ; GSolidRec rec(raw, root, csg, soIdx, lvIdx ); m_solidrec.push_back( rec ) ; } } void GGeoGLTF::addNodes() { const GVolume* top = m_ggeo->getVolume(0); Nd* parent_nd = NULL ; addNodes_r( top, parent_nd, 0 ) ; } void GGeoGLTF::addNodes_r(const GVolume* volume, YOG::Nd* parent_nd, int depth) { const GMesh* mesh = volume->getMesh(); int lvIdx = mesh->getIndex() ; const nmat4triple* ltriple = volume->getLocalTransform(); unsigned boundary = volume->getBoundary(); std::string boundaryName = m_blib->shortname(boundary); int materialIdx = m_blib->getInnerMaterial(boundary); const char* pvName = volume->getPVName() ; LOG(verbose) << " volume " << volume << " lv " << lvIdx << " boundary " << std::setw(4) << boundary << " materialIdx " << std::setw(4) << materialIdx << " boundaryName " << boundaryName ; int ndIdx = m_sc->add_node( lvIdx, materialIdx, pvName, ltriple, boundaryName, depth, true, // selected: not yet used in YOG machinery parent_nd ); Nd* nd = m_sc->get_node(ndIdx) ; for(unsigned i = 0; i < volume->getNumChildren(); i++) addNodes_r(volume->getChildVolume(i), nd, depth + 1); } void GGeoGLTF::save(const char* path, int root ) { m_sc->root = root ; LOG(info) << " path " << path << " sc.root " << m_sc->root ; bool yzFlip = true ; bool saveNPYToGLTF = false ; BFile::preparePath( path ) ; m_maker = new YOG::Maker(m_sc, yzFlip, saveNPYToGLTF) ; m_maker->convert(); m_maker->save(path); std::string dir = BFile::ParentDir(path); writeSolidRec(dir.c_str()); } void GGeoGLTF::dumpSolidRec(const char* msg) const { LOG(error) << msg ; std::ostream& out = std::cout ; solidRecTable( out ); } void GGeoGLTF::writeSolidRec(const char* dir) const { std::string path = BFile::preparePath( dir, "solids.txt", true ) ; LOG(LEVEL) << " writeSolidRec " << " dir [" << dir << "]" << " path [" << path << "]" ; std::ofstream out(path.c_str()); solidRecTable( out ); } void GGeoGLTF::solidRecTable( std::ostream& out ) const { unsigned num_solid = m_solidrec.size() ; out << "written by GGeoGLTF::solidRecTable " << std::endl ; out << "num_solid " << num_solid << std::endl ; for(unsigned i=0 ; i < num_solid ; i++) { const GSolidRec& rec = m_solidrec[i] ; out << rec.desc() << std::endl ; } }
25.829493
112
0.560928
hanswenzel
fe8862ece5b84bba5feb87d0ef64880e15505055
57,619
cpp
C++
src/tests/class_tests/smartpeak/source/LossFunctionTensor_test.cpp
dmccloskey/EvoNet
8d7fafe1069593024e5b63fd6b81a341a3bf33b5
[ "MIT" ]
3
2020-12-28T11:07:26.000Z
2021-12-30T11:38:13.000Z
src/tests/class_tests/smartpeak/source/LossFunctionTensor_test.cpp
dmccloskey/EvoNet
8d7fafe1069593024e5b63fd6b81a341a3bf33b5
[ "MIT" ]
20
2018-10-03T11:35:23.000Z
2019-10-14T09:17:07.000Z
src/tests/class_tests/smartpeak/source/LossFunctionTensor_test.cpp
dmccloskey/EvoNet
8d7fafe1069593024e5b63fd6b81a341a3bf33b5
[ "MIT" ]
null
null
null
/**TODO: Add copyright*/ #define BOOST_TEST_MODULE LossFunctionTensor test suite #include <boost/test/included/unit_test.hpp> #include <SmartPeak/ml/LossFunctionTensor.h> #include <iostream> using namespace SmartPeak; using namespace std; BOOST_AUTO_TEST_SUITE(lossFunctionTensor) /** ManhattanDistanceLossOp Tests */ BOOST_AUTO_TEST_CASE(constructorManhattanDistanceLossOp) { ManhattanDistanceLossTensorOp<float, Eigen::DefaultDevice>* ptrReLU = nullptr; ManhattanDistanceLossTensorOp<float, Eigen::DefaultDevice>* nullPointerReLU = nullptr; BOOST_CHECK_EQUAL(ptrReLU, nullPointerReLU); } BOOST_AUTO_TEST_CASE(destructorManhattanDistanceLossOp) { ManhattanDistanceLossTensorOp<float, Eigen::DefaultDevice>* ptrReLU = nullptr; ptrReLU = new ManhattanDistanceLossTensorOp<float, Eigen::DefaultDevice>(); delete ptrReLU; } BOOST_AUTO_TEST_CASE(operationfunctionManhattanDistanceLossOp) { ManhattanDistanceLossTensorOp<float, Eigen::DefaultDevice> operation; const int memory_size = 2; const int batch_size = 2; const int layer_size = 2; const int time_step = 0; Eigen::Tensor<float, 2> y_true(batch_size, layer_size); y_true.setValues({ {1, 2}, {1, 2} }); Eigen::Tensor<float, 3> y_pred(batch_size, memory_size, layer_size); y_pred.setValues({ {{1, 1}, {0, 0}}, {{2, 2}, {0, 0}} }); float error_ptr[] = { 0, 0, 0, 0 }; Eigen::DefaultDevice device; operation(y_pred.data(), y_true.data(), error_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 2>> error(error_ptr, batch_size, memory_size); BOOST_CHECK_CLOSE(error(0, 0), 1, 1e-4); BOOST_CHECK_CLOSE(error(1, 0), 1, 1e-4); BOOST_CHECK_CLOSE(error(0, 1), 0, 1e-4); BOOST_CHECK_CLOSE(error(1, 1), 0, 1e-4); } /** ManhattanDistanceLossGradOp Tests */ BOOST_AUTO_TEST_CASE(constructorManhattanDistanceLossGradOp) { ManhattanDistanceLossGradTensorOp<float, Eigen::DefaultDevice>* ptrReLU = nullptr; ManhattanDistanceLossGradTensorOp<float, Eigen::DefaultDevice>* nullPointerReLU = nullptr; BOOST_CHECK_EQUAL(ptrReLU, nullPointerReLU); } BOOST_AUTO_TEST_CASE(destructorManhattanDistanceLossGradOp) { ManhattanDistanceLossGradTensorOp<float, Eigen::DefaultDevice>* ptrReLU = nullptr; ptrReLU = new ManhattanDistanceLossGradTensorOp<float, Eigen::DefaultDevice>(); delete ptrReLU; } BOOST_AUTO_TEST_CASE(operationfunctionManhattanDistanceLossGradOp) { ManhattanDistanceLossGradTensorOp<float, Eigen::DefaultDevice> operation; const int memory_size = 2; const int batch_size = 2; const int layer_size = 2; const int time_step = 0; Eigen::Tensor<float, 2> y_true(batch_size, layer_size); y_true.setValues({ {1, 2}, {1, 2} }); Eigen::Tensor<float, 3> y_pred(batch_size, memory_size, layer_size); y_pred.setValues({ {{1, 1}, {0, 0}}, {{2, 2}, {0, 0}} }); float error_ptr[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; Eigen::DefaultDevice device; operation(y_pred.data(), y_true.data(), error_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 3>> error(error_ptr, batch_size, memory_size, layer_size); BOOST_CHECK_CLOSE(error(0, 0, 0), 0.0, 1e-4); //-nan BOOST_CHECK_CLOSE(error(0, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 0, 0), -1.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(0, 0, 1), 1.0, 1e-4); BOOST_CHECK_CLOSE(error(0, 1, 1), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 0, 1), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 1, 1), 0.0, 1e-4); } /** L2NormLossOp Tests */ BOOST_AUTO_TEST_CASE(constructorL2NormOp) { L2NormLossTensorOp<float, Eigen::DefaultDevice>* ptrL2Norm = nullptr; L2NormLossTensorOp<float, Eigen::DefaultDevice>* nullPointerL2Norm = nullptr; BOOST_CHECK_EQUAL(ptrL2Norm, nullPointerL2Norm); } BOOST_AUTO_TEST_CASE(destructorL2NormOp) { L2NormLossTensorOp<float, Eigen::DefaultDevice>* ptrL2Norm = nullptr; ptrL2Norm = new L2NormLossTensorOp<float, Eigen::DefaultDevice>(); delete ptrL2Norm; } BOOST_AUTO_TEST_CASE(operationfunctionL2NormOp) { L2NormLossTensorOp<float, Eigen::DefaultDevice> operation; const int memory_size = 2; const int batch_size = 2; const int layer_size = 2; const int time_step = 0; Eigen::Tensor<float, 2> y_true(batch_size, layer_size); y_true.setValues({ {1, 2}, {1, 2} }); Eigen::Tensor<float, 3> y_pred(batch_size, memory_size, layer_size); y_pred.setValues({ {{1, 1}, {0, 0}}, {{2, 2}, {0, 0}} }); float error_ptr[] = { 0, 0, 0, 0 }; Eigen::DefaultDevice device; operation(y_pred.data(), y_true.data(), error_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 2>> error(error_ptr, batch_size, memory_size); BOOST_CHECK_CLOSE(error(0, 0), 0.5, 1e-4); //TODO BOOST_CHECK_CLOSE(error(1, 0), -2.5, 1e-4); BOOST_CHECK_CLOSE(error(0, 1), 0, 1e-4); BOOST_CHECK_CLOSE(error(1, 1), 0, 1e-4); } /** L2NormLossGradOp Tests */ BOOST_AUTO_TEST_CASE(constructorL2NormGradOp) { L2NormLossGradTensorOp<float, Eigen::DefaultDevice>* ptrL2Norm = nullptr; L2NormLossGradTensorOp<float, Eigen::DefaultDevice>* nullPointerL2Norm = nullptr; BOOST_CHECK_EQUAL(ptrL2Norm, nullPointerL2Norm); } BOOST_AUTO_TEST_CASE(destructorL2NormGradOp) { L2NormLossGradTensorOp<float, Eigen::DefaultDevice>* ptrL2Norm = nullptr; ptrL2Norm = new L2NormLossGradTensorOp<float, Eigen::DefaultDevice>(); delete ptrL2Norm; } BOOST_AUTO_TEST_CASE(operationfunctionL2NormGradOp) { L2NormLossGradTensorOp<float, Eigen::DefaultDevice> operation; const int memory_size = 2; const int batch_size = 2; const int layer_size = 2; const int time_step = 0; Eigen::Tensor<float, 2> y_true(batch_size, layer_size); y_true.setValues({ {1, 2}, {1, 2} }); Eigen::Tensor<float, 3> y_pred(batch_size, memory_size, layer_size); y_pred.setValues({ {{1, 1}, {0, 0}}, {{2, 2}, {0, 0}} }); float error_ptr[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; Eigen::DefaultDevice device; operation(y_pred.data(), y_true.data(), error_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 3>> error(error_ptr, batch_size, memory_size, layer_size); BOOST_CHECK_CLOSE(error(0, 0, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(0, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 0, 0), -1.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(0, 0, 1), 1.0, 1e-4); BOOST_CHECK_CLOSE(error(0, 1, 1), 0, 1e-4); BOOST_CHECK_CLOSE(error(1, 0, 1), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 1, 1), 0.0, 1e-4); } /** CrossEntropyOp Tests */ BOOST_AUTO_TEST_CASE(constructorCrossEntropyOp) { BCELossTensorOp<float, Eigen::DefaultDevice>* ptrCrossEntropy = nullptr; BCELossTensorOp<float, Eigen::DefaultDevice>* nullPointerCrossEntropy = nullptr; BOOST_CHECK_EQUAL(ptrCrossEntropy, nullPointerCrossEntropy); } BOOST_AUTO_TEST_CASE(destructorCrossEntropyOp) { BCELossTensorOp<float, Eigen::DefaultDevice>* ptrCrossEntropy = nullptr; ptrCrossEntropy = new BCELossTensorOp<float, Eigen::DefaultDevice>(); delete ptrCrossEntropy; } BOOST_AUTO_TEST_CASE(operationfunctionCrossEntropyOp) { BCELossTensorOp<float, Eigen::DefaultDevice> operation; const int memory_size = 2; const int batch_size = 2; const int layer_size = 2; const int time_step = 0; Eigen::Tensor<float, 2> y_true(batch_size, layer_size); y_true.setValues({ {1, 0}, {1, 0} }); Eigen::Tensor<float, 3> y_pred(batch_size, memory_size, layer_size); y_pred.setValues({ {{.1, .9}, {0, 0}}, {{.9, .1}, {0, 0}} }); float error_ptr[] = { 0, 0, 0, 0 }; Eigen::DefaultDevice device; operation(y_pred.data(), y_true.data(), error_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 2>> error(error_ptr, batch_size, memory_size); BOOST_CHECK_CLOSE(error(0, 0), 4.60517025, 1e-4); BOOST_CHECK_CLOSE(error(1, 0), 0.21072109, 1e-4); BOOST_CHECK_CLOSE(error(0, 1), 0, 1e-4); BOOST_CHECK_CLOSE(error(1, 1), 0, 1e-4); } /** CrossEntropyGradOp Tests */ BOOST_AUTO_TEST_CASE(constructorCrossEntropyGradOp) { BCELossGradTensorOp<float, Eigen::DefaultDevice>* ptrCrossEntropy = nullptr; BCELossGradTensorOp<float, Eigen::DefaultDevice>* nullPointerCrossEntropy = nullptr; BOOST_CHECK_EQUAL(ptrCrossEntropy, nullPointerCrossEntropy); } BOOST_AUTO_TEST_CASE(destructorCrossEntropyGradOp) { BCELossGradTensorOp<float, Eigen::DefaultDevice>* ptrCrossEntropy = nullptr; ptrCrossEntropy = new BCELossGradTensorOp<float, Eigen::DefaultDevice>(); delete ptrCrossEntropy; } BOOST_AUTO_TEST_CASE(operationfunctionCrossEntropyGradOp) { BCELossGradTensorOp<float, Eigen::DefaultDevice> operation; const int memory_size = 2; const int batch_size = 2; const int layer_size = 2; const int time_step = 0; Eigen::Tensor<float, 2> y_true(batch_size, layer_size); y_true.setValues({ {1, 0}, {1, 0} }); Eigen::Tensor<float, 3> y_pred(batch_size, memory_size, layer_size); y_pred.setValues({ {{.1, .9}, {0, 0}}, {{.9, .1}, {0, 0}} }); float error_ptr[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; Eigen::DefaultDevice device; operation(y_pred.data(), y_true.data(), error_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 3>> error(error_ptr, batch_size, memory_size, layer_size); BOOST_CHECK_CLOSE(error(0, 0, 0), 10.0000, 1e-4); BOOST_CHECK_CLOSE(error(0, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 0, 0), 1.11111116, 1e-4); BOOST_CHECK_CLOSE(error(1, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(0, 0, 1), -10.0000, 1e-4); BOOST_CHECK_CLOSE(error(0, 1, 1), 0, 1e-4); BOOST_CHECK_CLOSE(error(1, 0, 1), -1.11111116, 1e-4); BOOST_CHECK_CLOSE(error(1, 1, 1), 0.0, 1e-4); } /** NegativeLogLikelihoodLossOp Tests */ BOOST_AUTO_TEST_CASE(constructorNegativeLogLikelihoodOp) { NegativeLogLikelihoodLossTensorOp<float, Eigen::DefaultDevice>* ptrNegativeLogLikelihood = nullptr; NegativeLogLikelihoodLossTensorOp<float, Eigen::DefaultDevice>* nullPointerNegativeLogLikelihood = nullptr; BOOST_CHECK_EQUAL(ptrNegativeLogLikelihood, nullPointerNegativeLogLikelihood); } BOOST_AUTO_TEST_CASE(destructorNegativeLogLikelihoodOp) { NegativeLogLikelihoodLossTensorOp<float, Eigen::DefaultDevice>* ptrNegativeLogLikelihood = nullptr; ptrNegativeLogLikelihood = new NegativeLogLikelihoodLossTensorOp<float, Eigen::DefaultDevice>(); delete ptrNegativeLogLikelihood; } BOOST_AUTO_TEST_CASE(operationfunctionNegativeLogLikelihoodOp) { NegativeLogLikelihoodLossTensorOp<float, Eigen::DefaultDevice> operation; const int memory_size = 2; const int batch_size = 2; const int layer_size = 2; const int time_step = 0; Eigen::Tensor<float, 2> y_true(batch_size, layer_size); y_true.setValues({ {1, 0}, {1, 0} }); Eigen::Tensor<float, 3> y_pred(batch_size, memory_size, layer_size); y_pred.setValues({ {{.1, .9}, {0, 0}}, {{.9, .1}, {0, 0}} }); float error_ptr[] = { 0, 0, 0, 0 }; Eigen::DefaultDevice device; operation(y_pred.data(), y_true.data(), error_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 2>> error(error_ptr, batch_size, memory_size); BOOST_CHECK_CLOSE(error(0, 0), 1.15129256, 1e-4); BOOST_CHECK_CLOSE(error(1, 0), 0.0526802726, 1e-4); BOOST_CHECK_CLOSE(error(0, 1), 0, 1e-4); BOOST_CHECK_CLOSE(error(1, 1), 0, 1e-4); } /** NegativeLogLikelihoodLossGradOp Tests */ BOOST_AUTO_TEST_CASE(constructorNegativeLogLikelihoodGradOp) { NegativeLogLikelihoodLossGradTensorOp<float, Eigen::DefaultDevice>* ptrNegativeLogLikelihood = nullptr; NegativeLogLikelihoodLossGradTensorOp<float, Eigen::DefaultDevice>* nullPointerNegativeLogLikelihood = nullptr; BOOST_CHECK_EQUAL(ptrNegativeLogLikelihood, nullPointerNegativeLogLikelihood); } BOOST_AUTO_TEST_CASE(destructorNegativeLogLikelihoodGradOp) { NegativeLogLikelihoodLossGradTensorOp<float, Eigen::DefaultDevice>* ptrNegativeLogLikelihood = nullptr; ptrNegativeLogLikelihood = new NegativeLogLikelihoodLossGradTensorOp<float, Eigen::DefaultDevice>(); delete ptrNegativeLogLikelihood; } BOOST_AUTO_TEST_CASE(operationfunctionNegativeLogLikelihoodGradOp) { NegativeLogLikelihoodLossGradTensorOp<float, Eigen::DefaultDevice> operation; const int memory_size = 2; const int batch_size = 2; const int layer_size = 2; const int time_step = 0; Eigen::Tensor<float, 2> y_true(batch_size, layer_size); y_true.setValues({ {1, 0}, {1, 0} }); Eigen::Tensor<float, 3> y_pred(batch_size, memory_size, layer_size); y_pred.setValues({ {{.1, .9}, {0, 0}}, {{.9, .1}, {0, 0}} }); float error_ptr[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; Eigen::DefaultDevice device; operation(y_pred.data(), y_true.data(), error_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 3>> error(error_ptr, batch_size, memory_size, layer_size); BOOST_CHECK_CLOSE(error(0, 0, 0), -5.0, 1e-4); BOOST_CHECK_CLOSE(error(0, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 0, 0), -0.555555582, 1e-4); BOOST_CHECK_CLOSE(error(1, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(0, 0, 1), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(0, 1, 1), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 0, 1), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 1, 1), 0.0, 1e-4); } /** MSELossOp Tests */ BOOST_AUTO_TEST_CASE(constructorMSEOp) { MSELossTensorOp<float, Eigen::DefaultDevice>* ptrMSE = nullptr; MSELossTensorOp<float, Eigen::DefaultDevice>* nullPointerMSE = nullptr; BOOST_CHECK_EQUAL(ptrMSE, nullPointerMSE); } BOOST_AUTO_TEST_CASE(destructorMSEOp) { MSELossTensorOp<float, Eigen::DefaultDevice>* ptrMSE = nullptr; ptrMSE = new MSELossTensorOp<float, Eigen::DefaultDevice>(); delete ptrMSE; } BOOST_AUTO_TEST_CASE(operationfunctionMSEOp) { MSELossTensorOp<float, Eigen::DefaultDevice> operation; const int memory_size = 2; const int batch_size = 2; const int layer_size = 2; const int time_step = 0; Eigen::Tensor<float, 2> y_true(batch_size, layer_size); y_true.setValues({ {1, 2}, {1, 2} }); Eigen::Tensor<float, 3> y_pred(batch_size, memory_size, layer_size); y_pred.setValues({ {{1, 1}, {0, 0}}, {{2, 2}, {0, 0}} }); float error_ptr[] = { 0, 0, 0, 0 }; Eigen::DefaultDevice device; operation(y_pred.data(), y_true.data(), error_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 2>> error(error_ptr, batch_size, memory_size); BOOST_CHECK_CLOSE(error(0, 0), 0.25, 1e-4); BOOST_CHECK_CLOSE(error(1, 0), 0.25, 1e-4); BOOST_CHECK_CLOSE(error(0, 1), 0, 1e-4); BOOST_CHECK_CLOSE(error(1, 1), 0, 1e-4); } /** MSELossGradOp Tests */ BOOST_AUTO_TEST_CASE(constructorMSEGradOp) { MSELossGradTensorOp<float, Eigen::DefaultDevice>* ptrMSE = nullptr; MSELossGradTensorOp<float, Eigen::DefaultDevice>* nullPointerMSE = nullptr; BOOST_CHECK_EQUAL(ptrMSE, nullPointerMSE); } BOOST_AUTO_TEST_CASE(destructorMSEGradOp) { MSELossGradTensorOp<float, Eigen::DefaultDevice>* ptrMSE = nullptr; ptrMSE = new MSELossGradTensorOp<float, Eigen::DefaultDevice>(); delete ptrMSE; } BOOST_AUTO_TEST_CASE(operationfunctionMSEGradOp) { MSELossGradTensorOp<float, Eigen::DefaultDevice> operation; const int memory_size = 2; const int batch_size = 2; const int layer_size = 2; const int time_step = 0; Eigen::Tensor<float, 2> y_true(batch_size, layer_size); y_true.setValues({ {1, 2}, {1, 2} }); Eigen::Tensor<float, 3> y_pred(batch_size, memory_size, layer_size); y_pred.setValues({ {{1, 1}, {0, 0}}, {{2, 2}, {0, 0}} }); float error_ptr[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; Eigen::DefaultDevice device; operation(y_pred.data(), y_true.data(), error_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 3>> error(error_ptr, batch_size, memory_size, layer_size); BOOST_CHECK_CLOSE(error(0, 0, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(0, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 0, 0), -0.5, 1e-4); BOOST_CHECK_CLOSE(error(1, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(0, 0, 1), 0.5, 1e-4); BOOST_CHECK_CLOSE(error(0, 1, 1), 0, 1e-4); BOOST_CHECK_CLOSE(error(1, 0, 1), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 1, 1), 0.0, 1e-4); } /** MAELossOp Tests */ BOOST_AUTO_TEST_CASE(constructorMAEOp) { MAELossTensorOp<float, Eigen::DefaultDevice>* ptrMAE = nullptr; MAELossTensorOp<float, Eigen::DefaultDevice>* nullPointerMAE = nullptr; BOOST_CHECK_EQUAL(ptrMAE, nullPointerMAE); } BOOST_AUTO_TEST_CASE(destructorMAEOp) { MAELossTensorOp<float, Eigen::DefaultDevice>* ptrMAE = nullptr; ptrMAE = new MAELossTensorOp<float, Eigen::DefaultDevice>(); delete ptrMAE; } BOOST_AUTO_TEST_CASE(operationfunctionMAEOp) { MAELossTensorOp<float, Eigen::DefaultDevice> operation; const int memory_size = 2; const int batch_size = 2; const int layer_size = 2; const int time_step = 0; Eigen::Tensor<float, 2> y_true(batch_size, layer_size); y_true.setValues({ {1, 2}, {1, 2} }); Eigen::Tensor<float, 3> y_pred(batch_size, memory_size, layer_size); y_pred.setValues({ {{1, 1}, {0, 0}}, {{2, 2}, {0, 0}} }); float error_ptr[] = { 0, 0, 0, 0 }; Eigen::DefaultDevice device; operation(y_pred.data(), y_true.data(), error_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 2>> error(error_ptr, batch_size, memory_size); BOOST_CHECK_CLOSE(error(0, 0), 0.5, 1e-4); BOOST_CHECK_CLOSE(error(1, 0), 0.5, 1e-4); BOOST_CHECK_CLOSE(error(0, 1), 0, 1e-4); BOOST_CHECK_CLOSE(error(1, 1), 0, 1e-4); } /** MAELossGradOp Tests */ BOOST_AUTO_TEST_CASE(constructorMAEGradOp) { MAELossGradTensorOp<float, Eigen::DefaultDevice>* ptrMAE = nullptr; MAELossGradTensorOp<float, Eigen::DefaultDevice>* nullPointerMAE = nullptr; BOOST_CHECK_EQUAL(ptrMAE, nullPointerMAE); } BOOST_AUTO_TEST_CASE(destructorMAEGradOp) { MAELossGradTensorOp<float, Eigen::DefaultDevice>* ptrMAE = nullptr; ptrMAE = new MAELossGradTensorOp<float, Eigen::DefaultDevice>(); delete ptrMAE; } BOOST_AUTO_TEST_CASE(operationfunctionMAEGradOp) { MAELossGradTensorOp<float, Eigen::DefaultDevice> operation; const int memory_size = 2; const int batch_size = 2; const int layer_size = 2; const int time_step = 0; Eigen::Tensor<float, 2> y_true(batch_size, layer_size); y_true.setValues({ {1, 2}, {1, 2} }); Eigen::Tensor<float, 3> y_pred(batch_size, memory_size, layer_size); y_pred.setValues({ {{1, 1}, {0, 0}}, {{2, 2}, {0, 0}} }); float error_ptr[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; Eigen::DefaultDevice device; operation(y_pred.data(), y_true.data(), error_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 3>> error(error_ptr, batch_size, memory_size, layer_size); BOOST_CHECK_CLOSE(error(0, 0, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(0, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 0, 0), -0.499999523, 1e-4); BOOST_CHECK_CLOSE(error(1, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(0, 0, 1), 0.5, 1e-4); BOOST_CHECK_CLOSE(error(0, 1, 1), 0, 1e-4); BOOST_CHECK_CLOSE(error(1, 0, 1), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 1, 1), 0.0, 1e-4); } /** MRSELossOp Tests */ BOOST_AUTO_TEST_CASE(constructorMRSEOp) { MRSELossTensorOp<float, Eigen::DefaultDevice>* ptrMRSE = nullptr; MRSELossTensorOp<float, Eigen::DefaultDevice>* nullPointerMRSE = nullptr; BOOST_CHECK_EQUAL(ptrMRSE, nullPointerMRSE); } BOOST_AUTO_TEST_CASE(destructorMRSEOp) { MRSELossTensorOp<float, Eigen::DefaultDevice>* ptrMRSE = nullptr; ptrMRSE = new MRSELossTensorOp<float, Eigen::DefaultDevice>(); delete ptrMRSE; } BOOST_AUTO_TEST_CASE(operationfunctionMRSEOp) { MRSELossTensorOp<float, Eigen::DefaultDevice> operation; const int memory_size = 2; const int batch_size = 2; const int layer_size = 2; const int time_step = 0; Eigen::Tensor<float, 2> y_true(batch_size, layer_size); y_true.setValues({ {1, 2}, {1, 2} }); Eigen::Tensor<float, 3> y_pred(batch_size, memory_size, layer_size); y_pred.setValues({ {{1, 1}, {0, 0}}, {{2, 2}, {0, 0}} }); float error_ptr[] = { 0, 0, 0, 0 }; Eigen::DefaultDevice device; operation(y_pred.data(), y_true.data(), error_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 2>> error(error_ptr, batch_size, memory_size); BOOST_CHECK_CLOSE(error(0, 0), 1.5, 1e-4); BOOST_CHECK_CLOSE(error(1, 0), 1.5, 1e-4); BOOST_CHECK_CLOSE(error(0, 1), 0, 1e-4); BOOST_CHECK_CLOSE(error(1, 1), 0, 1e-4); } /** MRSELossGradOp Tests */ BOOST_AUTO_TEST_CASE(constructorMRSEGradOp) { MRSELossGradTensorOp<float, Eigen::DefaultDevice>* ptrMRSE = nullptr; MRSELossGradTensorOp<float, Eigen::DefaultDevice>* nullPointerMRSE = nullptr; BOOST_CHECK_EQUAL(ptrMRSE, nullPointerMRSE); } BOOST_AUTO_TEST_CASE(destructorMRSEGradOp) { MRSELossGradTensorOp<float, Eigen::DefaultDevice>* ptrMRSE = nullptr; ptrMRSE = new MRSELossGradTensorOp<float, Eigen::DefaultDevice>(); delete ptrMRSE; } BOOST_AUTO_TEST_CASE(operationfunctionMRSEGradOp) { MRSELossGradTensorOp<float, Eigen::DefaultDevice> operation; const int memory_size = 2; const int batch_size = 2; const int layer_size = 2; const int time_step = 0; Eigen::Tensor<float, 2> y_true(batch_size, layer_size); y_true.setValues({ {1, 2}, {1, 2} }); Eigen::Tensor<float, 3> y_pred(batch_size, memory_size, layer_size); y_pred.setValues({ {{1, 1}, {0, 0}}, {{2, 2}, {0, 0}} }); float error_ptr[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; Eigen::DefaultDevice device; operation(y_pred.data(), y_true.data(), error_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 3>> error(error_ptr, batch_size, memory_size, layer_size); BOOST_CHECK_CLOSE(error(0, 0, 0), -499999.969, 1e-4); BOOST_CHECK_CLOSE(error(0, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 0, 0), -499999.969, 1e-4); BOOST_CHECK_CLOSE(error(1, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(0, 0, 1), -707106.688, 1e-4); BOOST_CHECK_CLOSE(error(0, 1, 1), 0, 1e-4); BOOST_CHECK_CLOSE(error(1, 0, 1), -707106.688, 1e-4); BOOST_CHECK_CLOSE(error(1, 1, 1), 0.0, 1e-4); } /** MLELossOp Tests */ BOOST_AUTO_TEST_CASE(constructorMLEOp) { MLELossTensorOp<float, Eigen::DefaultDevice>* ptrMLE = nullptr; MLELossTensorOp<float, Eigen::DefaultDevice>* nullPointerMLE = nullptr; BOOST_CHECK_EQUAL(ptrMLE, nullPointerMLE); } BOOST_AUTO_TEST_CASE(destructorMLEOp) { MLELossTensorOp<float, Eigen::DefaultDevice>* ptrMLE = nullptr; ptrMLE = new MLELossTensorOp<float, Eigen::DefaultDevice>(); delete ptrMLE; } BOOST_AUTO_TEST_CASE(operationfunctionMLEOp) { MLELossTensorOp<float, Eigen::DefaultDevice> operation; const int memory_size = 2; const int batch_size = 2; const int layer_size = 2; const int time_step = 0; Eigen::Tensor<float, 2> y_true(batch_size, layer_size); y_true.setValues({ {1, 2}, {1, 2} }); Eigen::Tensor<float, 3> y_pred(batch_size, memory_size, layer_size); y_pred.setValues({ {{1, 1}, {0, 0}}, {{2, 2}, {0, 0}} }); float error_ptr[] = { 0, 0, 0, 0 }; Eigen::DefaultDevice device; operation(y_pred.data(), y_true.data(), error_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 2>> error(error_ptr, batch_size, memory_size); BOOST_CHECK_CLOSE(error(0, 0), 0.346573591, 1e-4); BOOST_CHECK_CLOSE(error(1, 0), 0.346573591, 1e-4); BOOST_CHECK_CLOSE(error(0, 1), 0, 1e-4); BOOST_CHECK_CLOSE(error(1, 1), 0, 1e-4); } /** MLELossGradOp Tests */ BOOST_AUTO_TEST_CASE(constructorMLEGradOp) { MLELossGradTensorOp<float, Eigen::DefaultDevice>* ptrMLE = nullptr; MLELossGradTensorOp<float, Eigen::DefaultDevice>* nullPointerMLE = nullptr; BOOST_CHECK_EQUAL(ptrMLE, nullPointerMLE); } BOOST_AUTO_TEST_CASE(destructorMLEGradOp) { MLELossGradTensorOp<float, Eigen::DefaultDevice>* ptrMLE = nullptr; ptrMLE = new MLELossGradTensorOp<float, Eigen::DefaultDevice>(); delete ptrMLE; } BOOST_AUTO_TEST_CASE(operationfunctionMLEGradOp) { MLELossGradTensorOp<float, Eigen::DefaultDevice> operation; const int memory_size = 2; const int batch_size = 2; const int layer_size = 2; const int time_step = 0; Eigen::Tensor<float, 2> y_true(batch_size, layer_size); y_true.setValues({ {1, 2}, {1, 2} }); Eigen::Tensor<float, 3> y_pred(batch_size, memory_size, layer_size); y_pred.setValues({ {{1, 1}, {0, 0}}, {{2, 2}, {0, 0}} }); float error_ptr[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; Eigen::DefaultDevice device; operation(y_pred.data(), y_true.data(), error_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 3>> error(error_ptr, batch_size, memory_size, layer_size); BOOST_CHECK_CLOSE(error(0, 0, 0), -0.5, 1e-4); BOOST_CHECK_CLOSE(error(0, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 0, 0), -0.5, 1e-4); BOOST_CHECK_CLOSE(error(1, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(0, 0, 1), -0.250000119, 1e-4); BOOST_CHECK_CLOSE(error(0, 1, 1), 0, 1e-4); BOOST_CHECK_CLOSE(error(1, 0, 1), -0.250000119, 1e-4); BOOST_CHECK_CLOSE(error(1, 1, 1), 0.0, 1e-4); } /** KLDivergenceMuLossOp Tests */ BOOST_AUTO_TEST_CASE(constructorKLDivergenceMuOp) { KLDivergenceMuLossTensorOp<float, Eigen::DefaultDevice>* ptrKLDivergenceMu = nullptr; KLDivergenceMuLossTensorOp<float, Eigen::DefaultDevice>* nullPointerKLDivergenceMu = nullptr; BOOST_CHECK_EQUAL(ptrKLDivergenceMu, nullPointerKLDivergenceMu); } BOOST_AUTO_TEST_CASE(destructorKLDivergenceMuOp) { KLDivergenceMuLossTensorOp<float, Eigen::DefaultDevice>* ptrKLDivergenceMu = nullptr; ptrKLDivergenceMu = new KLDivergenceMuLossTensorOp<float, Eigen::DefaultDevice>(); delete ptrKLDivergenceMu; } BOOST_AUTO_TEST_CASE(operationfunctionKLDivergenceMuOp) { // Without capacity KLDivergenceMuLossTensorOp<float, Eigen::DefaultDevice> operation; const int memory_size = 2; const int batch_size = 2; const int layer_size = 2; const int time_step = 0; Eigen::Tensor<float, 2> y_true(batch_size, layer_size); y_true.setValues({ {1, 2}, {1, 2} }); Eigen::Tensor<float, 3> y_pred(batch_size, memory_size, layer_size); y_pred.setValues({ {{1, 1}, {0, 0}}, {{2, 2}, {0, 0}} }); float error_ptr[] = { 0, 0, 0, 0 }; Eigen::DefaultDevice device; operation(y_pred.data(), y_true.data(), error_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 2>> error(error_ptr, batch_size, memory_size); BOOST_CHECK_CLOSE(error(0, 0), 0, 1e-4); BOOST_CHECK_CLOSE(error(1, 0), 3, 1e-4); BOOST_CHECK_CLOSE(error(0, 1), 0, 1e-4); BOOST_CHECK_CLOSE(error(1, 1), 0, 1e-4); // With capacity KLDivergenceMuLossTensorOp<float, Eigen::DefaultDevice> operationC(1e-3, 1, 5); float errorC_ptr[] = { 0, 0, 0, 0 }; operationC(y_pred.data(), y_true.data(), errorC_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 2>> errorC(errorC_ptr, batch_size, memory_size); BOOST_CHECK_CLOSE(errorC(0, 0), -5, 1e-4); BOOST_CHECK_CLOSE(errorC(1, 0), -2, 1e-4); BOOST_CHECK_CLOSE(errorC(0, 1), 0, 1e-4); BOOST_CHECK_CLOSE(errorC(1, 1), 0, 1e-4); } /** KLDivergenceMuLossGradOp Tests */ BOOST_AUTO_TEST_CASE(constructorKLDivergenceMuGradOp) { KLDivergenceMuLossGradTensorOp<float, Eigen::DefaultDevice>* ptrKLDivergenceMu = nullptr; KLDivergenceMuLossGradTensorOp<float, Eigen::DefaultDevice>* nullPointerKLDivergenceMu = nullptr; BOOST_CHECK_EQUAL(ptrKLDivergenceMu, nullPointerKLDivergenceMu); } BOOST_AUTO_TEST_CASE(destructorKLDivergenceMuGradOp) { KLDivergenceMuLossGradTensorOp<float, Eigen::DefaultDevice>* ptrKLDivergenceMu = nullptr; ptrKLDivergenceMu = new KLDivergenceMuLossGradTensorOp<float, Eigen::DefaultDevice>(); delete ptrKLDivergenceMu; } BOOST_AUTO_TEST_CASE(operationfunctionKLDivergenceMuGradOp) { // Without capacity KLDivergenceMuLossGradTensorOp<float, Eigen::DefaultDevice> operation; const int memory_size = 2; const int batch_size = 2; const int layer_size = 2; const int time_step = 0; Eigen::Tensor<float, 2> y_true(batch_size, layer_size); y_true.setValues({ {1, 2}, {1, 2} }); Eigen::Tensor<float, 3> y_pred(batch_size, memory_size, layer_size); y_pred.setValues({ {{1, 1}, {0, 0}}, {{2, 2}, {0, 0}} }); float error_ptr[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; Eigen::DefaultDevice device; operation(y_pred.data(), y_true.data(), error_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 3>> error(error_ptr, batch_size, memory_size, layer_size); BOOST_CHECK_CLOSE(error(0, 0, 0), -2.0, 1e-4); BOOST_CHECK_CLOSE(error(0, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 0, 0), -4.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(0, 0, 1), -2.0, 1e-4); BOOST_CHECK_CLOSE(error(0, 1, 1), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 0, 1), -4.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 1, 1), 0.0, 1e-4); // With capacity KLDivergenceMuLossGradTensorOp<float, Eigen::DefaultDevice> operationC(1e-4, 1, 5); float errorC_ptr[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; operationC(y_pred.data(), y_true.data(), errorC_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 3>> errorC(errorC_ptr, batch_size, memory_size, layer_size); BOOST_CHECK_CLOSE(errorC(0, 0, 0), 3.0, 1e-4); BOOST_CHECK_CLOSE(errorC(0, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(errorC(1, 0, 0), 1.0, 1e-4); BOOST_CHECK_CLOSE(errorC(1, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(errorC(0, 0, 1), 3.0, 1e-4); BOOST_CHECK_CLOSE(errorC(0, 1, 1), 0.0, 1e-4); BOOST_CHECK_CLOSE(errorC(1, 0, 1), 1.0, 1e-4); BOOST_CHECK_CLOSE(errorC(1, 1, 1), 0.0, 1e-4); } /** KLDivergenceLogVarLossOp Tests */ BOOST_AUTO_TEST_CASE(constructorKLDivergenceLogVarOp) { KLDivergenceLogVarLossTensorOp<float, Eigen::DefaultDevice>* ptrKLDivergenceLogVar = nullptr; KLDivergenceLogVarLossTensorOp<float, Eigen::DefaultDevice>* nullPointerKLDivergenceLogVar = nullptr; BOOST_CHECK_EQUAL(ptrKLDivergenceLogVar, nullPointerKLDivergenceLogVar); } BOOST_AUTO_TEST_CASE(destructorKLDivergenceLogVarOp) { KLDivergenceLogVarLossTensorOp<float, Eigen::DefaultDevice>* ptrKLDivergenceLogVar = nullptr; ptrKLDivergenceLogVar = new KLDivergenceLogVarLossTensorOp<float, Eigen::DefaultDevice>(); delete ptrKLDivergenceLogVar; } BOOST_AUTO_TEST_CASE(operationfunctionKLDivergenceLogVarOp2) { // Without capacity KLDivergenceLogVarLossTensorOp<float, Eigen::DefaultDevice> operation; const int memory_size = 2; const int batch_size = 2; const int layer_size = 2; const int time_step = 0; Eigen::Tensor<float, 2> y_true(batch_size, layer_size); y_true.setValues({ {1, 2}, {1, 2} }); Eigen::Tensor<float, 3> y_pred(batch_size, memory_size, layer_size); y_pred.setValues({ {{1, 1}, {0, 0}}, {{2, 2}, {0, 0}} }); float error_ptr[] = { 0, 0, 0, 0 }; Eigen::DefaultDevice device; operation(y_pred.data(), y_true.data(), error_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 2>> error(error_ptr, batch_size, memory_size); BOOST_CHECK_CLOSE(error(0, 0), 1.29744244, 1e-4); BOOST_CHECK_CLOSE(error(1, 0), 2.43656349, 1e-4); BOOST_CHECK_CLOSE(error(0, 1), 0, 1e-4); BOOST_CHECK_CLOSE(error(1, 1), 0, 1e-4); // With capacity KLDivergenceLogVarLossTensorOp<float, Eigen::DefaultDevice> operationC(1e-3, 1, 5); float errorC_ptr[] = { 0, 0, 0, 0 }; operationC(y_pred.data(), y_true.data(), errorC_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 2>> errorC(errorC_ptr, batch_size, memory_size); BOOST_CHECK_CLOSE(errorC(0, 0), -3.70255756, 1e-4); BOOST_CHECK_CLOSE(errorC(1, 0), -2.56343651, 1e-4); BOOST_CHECK_CLOSE(errorC(0, 1), 0, 1e-4); BOOST_CHECK_CLOSE(errorC(1, 1), 0, 1e-4); } /** KLDivergenceLogVarLossGradOp Tests */ BOOST_AUTO_TEST_CASE(constructorKLDivergenceLogVarGradOp) { KLDivergenceLogVarLossGradTensorOp<float, Eigen::DefaultDevice>* ptrKLDivergenceLogVar = nullptr; KLDivergenceLogVarLossGradTensorOp<float, Eigen::DefaultDevice>* nullPointerKLDivergenceLogVar = nullptr; BOOST_CHECK_EQUAL(ptrKLDivergenceLogVar, nullPointerKLDivergenceLogVar); } BOOST_AUTO_TEST_CASE(destructorKLDivergenceLogVarGradOp) { KLDivergenceLogVarLossGradTensorOp<float, Eigen::DefaultDevice>* ptrKLDivergenceLogVar = nullptr; ptrKLDivergenceLogVar = new KLDivergenceLogVarLossGradTensorOp<float, Eigen::DefaultDevice>(); delete ptrKLDivergenceLogVar; } BOOST_AUTO_TEST_CASE(operationfunctionKLDivergenceLogVarGradOp) { // Without capacity KLDivergenceLogVarLossGradTensorOp<float, Eigen::DefaultDevice> operation; const int memory_size = 2; const int batch_size = 2; const int layer_size = 2; const int time_step = 0; Eigen::Tensor<float, 2> y_true(batch_size, layer_size); y_true.setValues({ {1, 2}, {1, 2} }); Eigen::Tensor<float, 3> y_pred(batch_size, memory_size, layer_size); y_pred.setValues({ {{1, 1}, {0, 0}}, {{2, 2}, {0, 0}} }); float error_ptr[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; Eigen::DefaultDevice device; operation(y_pred.data(), y_true.data(), error_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 3>> error(error_ptr, batch_size, memory_size, layer_size); BOOST_CHECK_CLOSE(error(0, 0, 0), -1.14872122, 1e-4); BOOST_CHECK_CLOSE(error(0, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 0, 0), -2.21828175, 1e-4); BOOST_CHECK_CLOSE(error(1, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(0, 0, 1), -1.14872122, 1e-4); BOOST_CHECK_CLOSE(error(0, 1, 1), 0, 1e-4); BOOST_CHECK_CLOSE(error(1, 0, 1), -2.21828175, 1e-4); BOOST_CHECK_CLOSE(error(1, 1, 1), 0.0, 1e-4); // With capacity KLDivergenceLogVarLossGradTensorOp<float, Eigen::DefaultDevice> operationC(1e-4, 1, 5); float errorC_ptr[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; operationC(y_pred.data(), y_true.data(), errorC_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 3>> errorC(errorC_ptr, batch_size, memory_size, layer_size); BOOST_CHECK_CLOSE(errorC(0, 0, 0), 3.85127878, 1e-4); BOOST_CHECK_CLOSE(errorC(0, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(errorC(1, 0, 0), 2.78171825, 1e-4); BOOST_CHECK_CLOSE(errorC(1, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(errorC(0, 0, 1), 3.85127878, 1e-4); BOOST_CHECK_CLOSE(errorC(0, 1, 1), 0.0, 1e-4); BOOST_CHECK_CLOSE(errorC(1, 0, 1), 2.78171825, 1e-4); BOOST_CHECK_CLOSE(errorC(1, 1, 1), 0.0, 1e-4); } /** BCEWithLogitsLossOp Tests */ BOOST_AUTO_TEST_CASE(constructorBCEWithLogitsOp) { BCEWithLogitsLossTensorOp<float, Eigen::DefaultDevice>* ptrBCEWithLogits = nullptr; BCEWithLogitsLossTensorOp<float, Eigen::DefaultDevice>* nullPointerBCEWithLogits = nullptr; BOOST_CHECK_EQUAL(ptrBCEWithLogits, nullPointerBCEWithLogits); } BOOST_AUTO_TEST_CASE(destructorBCEWithLogitsOp) { BCEWithLogitsLossTensorOp<float, Eigen::DefaultDevice>* ptrBCEWithLogits = nullptr; ptrBCEWithLogits = new BCEWithLogitsLossTensorOp<float, Eigen::DefaultDevice>(); delete ptrBCEWithLogits; } BOOST_AUTO_TEST_CASE(operationfunctionBCEWithLogitsOp) { BCEWithLogitsLossTensorOp<float, Eigen::DefaultDevice> operation; const int memory_size = 2; const int batch_size = 2; const int layer_size = 2; const int time_step = 0; Eigen::Tensor<float, 2> y_true(batch_size, layer_size); y_true.setValues({ {1, 0},{0, 1} }); Eigen::Tensor<float, 3> y_pred(batch_size, memory_size, layer_size); y_pred.setValues({ {{1, 2}, {0, 0}}, {{1, 2}, {0, 0}} }); float error_ptr[] = { 0, 0, 0, 0 }; Eigen::DefaultDevice device; operation(y_pred.data(), y_true.data(), error_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 2>> error(error_ptr, batch_size, memory_size); BOOST_CHECK_CLOSE(error(0, 0), 2.44018984, 1e-4); BOOST_CHECK_CLOSE(error(1, 0), 1.44018972, 1e-4); BOOST_CHECK_CLOSE(error(0, 1), 0, 1e-4); BOOST_CHECK_CLOSE(error(1, 1), 0, 1e-4); } /** BCEWithLogitsLossGradOp Tests */ BOOST_AUTO_TEST_CASE(constructorBCEWithLogitsGradOp) { BCEWithLogitsLossGradTensorOp<float, Eigen::DefaultDevice>* ptrBCEWithLogits = nullptr; BCEWithLogitsLossGradTensorOp<float, Eigen::DefaultDevice>* nullPointerBCEWithLogits = nullptr; BOOST_CHECK_EQUAL(ptrBCEWithLogits, nullPointerBCEWithLogits); } BOOST_AUTO_TEST_CASE(destructorBCEWithLogitsGradOp) { BCEWithLogitsLossGradTensorOp<float, Eigen::DefaultDevice>* ptrBCEWithLogits = nullptr; ptrBCEWithLogits = new BCEWithLogitsLossGradTensorOp<float, Eigen::DefaultDevice>(); delete ptrBCEWithLogits; } BOOST_AUTO_TEST_CASE(operationfunctionBCEWithLogitsGradOp) { BCEWithLogitsLossGradTensorOp<float, Eigen::DefaultDevice> operation; const int memory_size = 2; const int batch_size = 2; const int layer_size = 2; const int time_step = 0; Eigen::Tensor<float, 2> y_true(batch_size, layer_size); y_true.setValues({ {1, 0},{0, 1} }); Eigen::Tensor<float, 3> y_pred(batch_size, memory_size, layer_size); y_pred.setValues({ {{1, 2}, {0, 0}}, {{1, 2}, {0, 0}} }); float error_ptr[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; Eigen::DefaultDevice device; operation(y_pred.data(), y_true.data(), error_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 3>> error(error_ptr, batch_size, memory_size, layer_size); BOOST_CHECK_CLOSE(error(0, 0, 0), 0.268941402, 1e-4); //0.268941432 BOOST_CHECK_CLOSE(error(0, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 0, 0), -0.731058598, 1e-4); //-0.731058598 BOOST_CHECK_CLOSE(error(1, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(0, 0, 1), -0.880797088, 1e-4); //-0.880797088 BOOST_CHECK_CLOSE(error(0, 1, 1), 0, 1e-4); BOOST_CHECK_CLOSE(error(1, 0, 1), 0.119202971, 1e-4); //0.119202919 BOOST_CHECK_CLOSE(error(1, 1, 1), 0.0, 1e-4); } /** CrossEntropyWithLogitsLossOp Tests */ BOOST_AUTO_TEST_CASE(constructorCrossEntropyWithLogitsOp) { CrossEntropyWithLogitsLossTensorOp<float, Eigen::DefaultDevice>* ptrCrossEntropyWithLogits = nullptr; CrossEntropyWithLogitsLossTensorOp<float, Eigen::DefaultDevice>* nullPointerCrossEntropyWithLogits = nullptr; BOOST_CHECK_EQUAL(ptrCrossEntropyWithLogits, nullPointerCrossEntropyWithLogits); } BOOST_AUTO_TEST_CASE(destructorCrossEntropyWithLogitsOp) { CrossEntropyWithLogitsLossTensorOp<float, Eigen::DefaultDevice>* ptrCrossEntropyWithLogits = nullptr; ptrCrossEntropyWithLogits = new CrossEntropyWithLogitsLossTensorOp<float, Eigen::DefaultDevice>(); delete ptrCrossEntropyWithLogits; } BOOST_AUTO_TEST_CASE(operationfunctionCrossEntropyWithLogitsOp1) { CrossEntropyWithLogitsLossTensorOp<float, Eigen::DefaultDevice> operation; const int memory_size = 2; const int batch_size = 2; const int layer_size = 2; const int time_step = 0; Eigen::Tensor<float, 2> y_true(batch_size, layer_size); y_true.setValues({ //{1, 0},{0, 1} {1, 0}, {1, 0} }); Eigen::Tensor<float, 3> y_pred(batch_size, memory_size, layer_size); y_pred.setValues({ //{{1, 2}, {0, 0}}, //{{1, 2}, {0, 0}} { {0, 2.19722}, {0, 0}}, {{2.19722, 0}, {0, 0}} }); float error_ptr[] = { 0, 0, 0, 0 }; Eigen::DefaultDevice device; operation(y_pred.data(), y_true.data(), error_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 2>> error(error_ptr, batch_size, memory_size); //BOOST_CHECK_CLOSE(error(0, 0), 0.656630814, 1e-4); //BOOST_CHECK_CLOSE(error(1, 0), 0.156630829, 1e-4); //BOOST_CHECK_CLOSE(error(0, 1), 0, 1e-4); //BOOST_CHECK_CLOSE(error(1, 1), 0, 1e-4); BOOST_CHECK_CLOSE(error(0, 0), 1.15129054, 1e-4); BOOST_CHECK_CLOSE(error(1, 0), 0.0526805036, 1e-4); BOOST_CHECK_CLOSE(error(0, 1), 0, 1e-4); BOOST_CHECK_CLOSE(error(1, 1), 0, 1e-4); } /** CrossEntropyWithLogitsLossGradOp Tests */ BOOST_AUTO_TEST_CASE(constructorCrossEntropyWithLogitsGradOp) { CrossEntropyWithLogitsLossGradTensorOp<float, Eigen::DefaultDevice>* ptrCrossEntropyWithLogits = nullptr; CrossEntropyWithLogitsLossGradTensorOp<float, Eigen::DefaultDevice>* nullPointerCrossEntropyWithLogits = nullptr; BOOST_CHECK_EQUAL(ptrCrossEntropyWithLogits, nullPointerCrossEntropyWithLogits); } BOOST_AUTO_TEST_CASE(destructorCrossEntropyWithLogitsGradOp) { CrossEntropyWithLogitsLossGradTensorOp<float, Eigen::DefaultDevice>* ptrCrossEntropyWithLogits = nullptr; ptrCrossEntropyWithLogits = new CrossEntropyWithLogitsLossGradTensorOp<float, Eigen::DefaultDevice>(); delete ptrCrossEntropyWithLogits; } BOOST_AUTO_TEST_CASE(operationfunctionCrossEntropyWithLogitsGradOp1) { CrossEntropyWithLogitsLossGradTensorOp<float, Eigen::DefaultDevice> operation; const int memory_size = 2; const int batch_size = 2; const int layer_size = 2; const int time_step = 0; Eigen::Tensor<float, 2> y_true(batch_size, layer_size); y_true.setValues({ //{1, 0},{0, 1} {1, 0}, {1, 0} }); Eigen::Tensor<float, 3> y_pred(batch_size, memory_size, layer_size); y_pred.setValues({ //{{1, 2}, {0, 0}}, //{{1, 2}, {0, 0}} { {0, 2.19722}, {0, 0}}, {{2.19722, 0}, {0, 0}} }); float error_ptr[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; Eigen::DefaultDevice device; operation(y_pred.data(), y_true.data(), error_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 3>> error(error_ptr, batch_size, memory_size, layer_size); //BOOST_CHECK_CLOSE(error(0, 0, 0), 0.0, 1e-4); //BOOST_CHECK_CLOSE(error(0, 1, 0), 0.0, 1e-4); //BOOST_CHECK_CLOSE(error(1, 0, 0), -0.5, 1e-4); //BOOST_CHECK_CLOSE(error(1, 1, 0), 0.0, 1e-4); //BOOST_CHECK_CLOSE(error(0, 0, 1), -1.0, 1e-4); //BOOST_CHECK_CLOSE(error(0, 1, 1), 0.0, 1e-4); //BOOST_CHECK_CLOSE(error(1, 0, 1), -0.5, 1e-4); //BOOST_CHECK_CLOSE(error(1, 1, 1), 0.0, 1e-4); // Option 1 BOOST_CHECK_CLOSE(error(0, 0, 0), 0.5, 1e-4); // NegLogLiklihoodGrad = -4.99994993 BOOST_CHECK_CLOSE(error(0, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 0, 0), -0.598610044, 1e-4); // NegLogLiklihoodGrad = -0.555554926 BOOST_CHECK_CLOSE(error(1, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(0, 0, 1), -1.09861004, 1e-4); BOOST_CHECK_CLOSE(error(0, 1, 1), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 0, 1), 0, 1e-4); BOOST_CHECK_CLOSE(error(1, 1, 1), 0.0, 1e-4); //// Option 2 //BOOST_CHECK_CLOSE(error(0, 0, 0), -4.9999299, 1e-4); //BOOST_CHECK_CLOSE(error(0, 1, 0), 0.0, 1e-4); //BOOST_CHECK_CLOSE(error(1, 0, 0), -0.555555224, 1e-4); //BOOST_CHECK_CLOSE(error(1, 1, 0), 0.0, 1e-4); //BOOST_CHECK_CLOSE(error(0, 0, 1), 0.0, 1e-4); //BOOST_CHECK_CLOSE(error(0, 1, 1), 0.0, 1e-4); //BOOST_CHECK_CLOSE(error(1, 0, 1), 0.0, 1e-4); //BOOST_CHECK_CLOSE(error(1, 1, 1), 0.0, 1e-4); } /** MSERangeUBLossOp Tests */ BOOST_AUTO_TEST_CASE(constructorMSERangeUBOp) { MSERangeUBLossTensorOp<float, Eigen::DefaultDevice>* ptrMSERangeUB = nullptr; MSERangeUBLossTensorOp<float, Eigen::DefaultDevice>* nullPointerMSERangeUB = nullptr; BOOST_CHECK_EQUAL(ptrMSERangeUB, nullPointerMSERangeUB); } BOOST_AUTO_TEST_CASE(destructorMSERangeUBOp) { MSERangeUBLossTensorOp<float, Eigen::DefaultDevice>* ptrMSERangeUB = nullptr; ptrMSERangeUB = new MSERangeUBLossTensorOp<float, Eigen::DefaultDevice>(); delete ptrMSERangeUB; } BOOST_AUTO_TEST_CASE(operationfunctionMSERangeUBOp) { MSERangeUBLossTensorOp<float, Eigen::DefaultDevice> operation; const int memory_size = 2; const int batch_size = 2; const int layer_size = 2; const int time_step = 0; Eigen::Tensor<float, 2> y_true(batch_size, layer_size); y_true.setValues({ {1, 2}, {1, 2} }); Eigen::Tensor<float, 3> y_pred(batch_size, memory_size, layer_size); y_pred.setValues({ {{1, 3}, {0, 0}}, {{0, 2}, {0, 0}} }); float error_ptr[] = { 0, 0, 0, 0 }; Eigen::DefaultDevice device; operation(y_pred.data(), y_true.data(), error_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 2>> error(error_ptr, batch_size, memory_size); BOOST_CHECK_CLOSE(error(0, 0), 0.25, 1e-4); BOOST_CHECK_CLOSE(error(1, 0), 0, 1e-4); BOOST_CHECK_CLOSE(error(0, 1), 0, 1e-4); BOOST_CHECK_CLOSE(error(1, 1), 0, 1e-4); } /** MSERangeUBLossGradOp Tests */ BOOST_AUTO_TEST_CASE(constructorMSERangeUBGradOp) { MSERangeUBLossGradTensorOp<float, Eigen::DefaultDevice>* ptrMSERangeUB = nullptr; MSERangeUBLossGradTensorOp<float, Eigen::DefaultDevice>* nullPointerMSERangeUB = nullptr; BOOST_CHECK_EQUAL(ptrMSERangeUB, nullPointerMSERangeUB); } BOOST_AUTO_TEST_CASE(destructorMSERangeUBGradOp) { MSERangeUBLossGradTensorOp<float, Eigen::DefaultDevice>* ptrMSERangeUB = nullptr; ptrMSERangeUB = new MSERangeUBLossGradTensorOp<float, Eigen::DefaultDevice>(); delete ptrMSERangeUB; } BOOST_AUTO_TEST_CASE(operationfunctionMSERangeUBGradOp) { MSERangeUBLossGradTensorOp<float, Eigen::DefaultDevice> operation; const int memory_size = 2; const int batch_size = 2; const int layer_size = 2; const int time_step = 0; Eigen::Tensor<float, 2> y_true(batch_size, layer_size); y_true.setValues({ {1, 2}, {1, 2} }); Eigen::Tensor<float, 3> y_pred(batch_size, memory_size, layer_size); y_pred.setValues({ {{1, 3}, {0, 0}}, {{0, 2}, {0, 0}} }); float error_ptr[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; Eigen::DefaultDevice device; operation(y_pred.data(), y_true.data(), error_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 3>> error(error_ptr, batch_size, memory_size, layer_size); BOOST_CHECK_CLOSE(error(0, 0, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(0, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 0, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(0, 0, 1), -0.5, 1e-4); BOOST_CHECK_CLOSE(error(0, 1, 1), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 0, 1), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 1, 1), 0.0, 1e-4); } /** MSERangeLBLossOp Tests */ BOOST_AUTO_TEST_CASE(constructorMSERangeLBOp) { MSERangeLBLossTensorOp<float, Eigen::DefaultDevice>* ptrMSERangeLB = nullptr; MSERangeLBLossTensorOp<float, Eigen::DefaultDevice>* nullPointerMSERangeLB = nullptr; BOOST_CHECK_EQUAL(ptrMSERangeLB, nullPointerMSERangeLB); } BOOST_AUTO_TEST_CASE(destructorMSERangeLBOp) { MSERangeLBLossTensorOp<float, Eigen::DefaultDevice>* ptrMSERangeLB = nullptr; ptrMSERangeLB = new MSERangeLBLossTensorOp<float, Eigen::DefaultDevice>(); delete ptrMSERangeLB; } BOOST_AUTO_TEST_CASE(operationfunctionMSERangeLBOp) { MSERangeLBLossTensorOp<float, Eigen::DefaultDevice> operation; const int memory_size = 2; const int batch_size = 2; const int layer_size = 2; const int time_step = 0; Eigen::Tensor<float, 2> y_true(batch_size, layer_size); y_true.setValues({ {1, 2}, {1, 2} }); Eigen::Tensor<float, 3> y_pred(batch_size, memory_size, layer_size); y_pred.setValues({ {{1, 3}, {0, 0}}, {{0, 2}, {0, 0}} }); float error_ptr[] = { 0, 0, 0, 0 }; Eigen::DefaultDevice device; operation(y_pred.data(), y_true.data(), error_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 2>> error(error_ptr, batch_size, memory_size); BOOST_CHECK_CLOSE(error(0, 0), 0, 1e-4); BOOST_CHECK_CLOSE(error(1, 0), 0.25, 1e-4); BOOST_CHECK_CLOSE(error(0, 1), 0, 1e-4); BOOST_CHECK_CLOSE(error(1, 1), 0, 1e-4); } /** MSERangeLBLossGradOp Tests */ BOOST_AUTO_TEST_CASE(constructorMSERangeLBGradOp) { MSERangeLBLossGradTensorOp<float, Eigen::DefaultDevice>* ptrMSERangeLB = nullptr; MSERangeLBLossGradTensorOp<float, Eigen::DefaultDevice>* nullPointerMSERangeLB = nullptr; BOOST_CHECK_EQUAL(ptrMSERangeLB, nullPointerMSERangeLB); } BOOST_AUTO_TEST_CASE(destructorMSERangeLBGradOp) { MSERangeLBLossGradTensorOp<float, Eigen::DefaultDevice>* ptrMSERangeLB = nullptr; ptrMSERangeLB = new MSERangeLBLossGradTensorOp<float, Eigen::DefaultDevice>(); delete ptrMSERangeLB; } BOOST_AUTO_TEST_CASE(operationfunctionMSERangeLBGradOp) { MSERangeLBLossGradTensorOp<float, Eigen::DefaultDevice> operation; const int memory_size = 2; const int batch_size = 2; const int layer_size = 2; const int time_step = 0; Eigen::Tensor<float, 2> y_true(batch_size, layer_size); y_true.setValues({ {1, 2}, {1, 2} }); Eigen::Tensor<float, 3> y_pred(batch_size, memory_size, layer_size); y_pred.setValues({ {{1, 3}, {0, 0}}, {{0, 2}, {0, 0}} }); float error_ptr[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; Eigen::DefaultDevice device; operation(y_pred.data(), y_true.data(), error_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 3>> error(error_ptr, batch_size, memory_size, layer_size); BOOST_CHECK_CLOSE(error(0, 0, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(0, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 0, 0), 0.5, 1e-4); BOOST_CHECK_CLOSE(error(1, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(0, 0, 1), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(0, 1, 1), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 0, 1), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 1, 1), 0.0, 1e-4); } /** KLDivergenceCatLossOp Tests */ BOOST_AUTO_TEST_CASE(constructorKLDivergenceCatOp) { KLDivergenceCatLossTensorOp<float, Eigen::DefaultDevice>* ptrKLDivergenceCat = nullptr; KLDivergenceCatLossTensorOp<float, Eigen::DefaultDevice>* nullPointerKLDivergenceCat = nullptr; BOOST_CHECK_EQUAL(ptrKLDivergenceCat, nullPointerKLDivergenceCat); } BOOST_AUTO_TEST_CASE(destructorKLDivergenceCatOp) { KLDivergenceCatLossTensorOp<float, Eigen::DefaultDevice>* ptrKLDivergenceCat = nullptr; ptrKLDivergenceCat = new KLDivergenceCatLossTensorOp<float, Eigen::DefaultDevice>(); delete ptrKLDivergenceCat; } BOOST_AUTO_TEST_CASE(operationfunctionKLDivergenceCatOp) { // Without capacity KLDivergenceCatLossTensorOp<float, Eigen::DefaultDevice> operation; const int memory_size = 2; const int batch_size = 2; const int layer_size = 2; const int time_step = 0; Eigen::Tensor<float, 2> y_true(batch_size, layer_size); y_true.setValues({ {1, 2}, {1, 2} }); Eigen::Tensor<float, 3> y_pred(batch_size, memory_size, layer_size); y_pred.setValues({ {{1, 1}, {0, 0}}, {{2, 2}, {0, 0}} }); float error_ptr[] = { 0, 0, 0, 0 }; Eigen::DefaultDevice device; operation(y_pred.data(), y_true.data(), error_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 2>> error(error_ptr, batch_size, memory_size); BOOST_CHECK_CLOSE(error(0, 0), 6.12971067, 1e-4); BOOST_CHECK_CLOSE(error(1, 0), 30.2493725, 1e-4); BOOST_CHECK_CLOSE(error(0, 1), 0, 1e-4); BOOST_CHECK_CLOSE(error(1, 1), 0, 1e-4); // With capacity KLDivergenceCatLossTensorOp<float, Eigen::DefaultDevice> operationC(1e-3, 1, 5); float errorC_ptr[] = { 0, 0, 0, 0 }; operationC(y_pred.data(), y_true.data(), errorC_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 2>> errorC(errorC_ptr, batch_size, memory_size); BOOST_CHECK_CLOSE(errorC(0, 0), 5.43656349, 1e-4); BOOST_CHECK_CLOSE(errorC(1, 0), 29.5562248, 1e-4); BOOST_CHECK_CLOSE(errorC(0, 1), 0, 1e-4); BOOST_CHECK_CLOSE(errorC(1, 1), 0, 1e-4); } /** KLDivergenceCatLossGradOp Tests */ BOOST_AUTO_TEST_CASE(constructorKLDivergenceCatGradOp) { KLDivergenceCatLossGradTensorOp<float, Eigen::DefaultDevice>* ptrKLDivergenceCat = nullptr; KLDivergenceCatLossGradTensorOp<float, Eigen::DefaultDevice>* nullPointerKLDivergenceCat = nullptr; BOOST_CHECK_EQUAL(ptrKLDivergenceCat, nullPointerKLDivergenceCat); } BOOST_AUTO_TEST_CASE(destructorKLDivergenceCatGradOp) { KLDivergenceCatLossGradTensorOp<float, Eigen::DefaultDevice>* ptrKLDivergenceCat = nullptr; ptrKLDivergenceCat = new KLDivergenceCatLossGradTensorOp<float, Eigen::DefaultDevice>(); delete ptrKLDivergenceCat; } BOOST_AUTO_TEST_CASE(operationfunctionKLDivergenceCatGradOp) { // No capacity KLDivergenceCatLossGradTensorOp<float, Eigen::DefaultDevice> operation; const int memory_size = 2; const int batch_size = 2; const int layer_size = 2; const int time_step = 0; Eigen::Tensor<float, 2> y_true(batch_size, layer_size); y_true.setValues({ {1, 2}, {1, 2} }); Eigen::Tensor<float, 3> y_pred(batch_size, memory_size, layer_size); y_pred.setValues({ {{1, 1}, {0, 0}}, {{2, 2}, {0, 0}} }); float error_ptr[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; Eigen::DefaultDevice device; operation(y_pred.data(), y_true.data(), error_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 3>> error(error_ptr, batch_size, memory_size, layer_size); BOOST_CHECK_CLOSE(error(0, 0, 0), -5.43656349, 1e-4); BOOST_CHECK_CLOSE(error(0, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 0, 0), -22.1671677, 1e-4); BOOST_CHECK_CLOSE(error(1, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(0, 0, 1), -5.43656349, 1e-4); BOOST_CHECK_CLOSE(error(0, 1, 1), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 0, 1), -22.1671677, 1e-4); BOOST_CHECK_CLOSE(error(1, 1, 1), 0.0, 1e-4); // With capacity KLDivergenceCatLossGradTensorOp<float, Eigen::DefaultDevice> operationC(1e-4, 1, 5); float errorC_ptr[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; operationC(y_pred.data(), y_true.data(), errorC_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 3>> errorC(errorC_ptr, batch_size, memory_size, layer_size); BOOST_CHECK_CLOSE(errorC(0, 0, 0), -4.74341631, 1e-4); BOOST_CHECK_CLOSE(errorC(0, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(errorC(1, 0, 0), -21.47402, 1e-4); BOOST_CHECK_CLOSE(errorC(1, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(errorC(0, 0, 1), -4.74341631, 1e-4); BOOST_CHECK_CLOSE(errorC(0, 1, 1), 0.0, 1e-4); BOOST_CHECK_CLOSE(errorC(1, 0, 1), -21.47402, 1e-4); BOOST_CHECK_CLOSE(errorC(1, 1, 1), 0.0, 1e-4); } /** MAPELossOp Tests */ BOOST_AUTO_TEST_CASE(constructorMAPELossOp) { MAPELossTensorOp<float, Eigen::DefaultDevice>* ptrMAPELoss = nullptr; MAPELossTensorOp<float, Eigen::DefaultDevice>* nullPointerMAPELoss = nullptr; BOOST_CHECK_EQUAL(ptrMAPELoss, nullPointerMAPELoss); } BOOST_AUTO_TEST_CASE(destructorMAPELossOp) { MAPELossTensorOp<float, Eigen::DefaultDevice>* ptrMAPELoss = nullptr; ptrMAPELoss = new MAPELossTensorOp<float, Eigen::DefaultDevice>(); delete ptrMAPELoss; } BOOST_AUTO_TEST_CASE(operationfunctionMAPELossOp) { MAPELossTensorOp<float, Eigen::DefaultDevice> operation; const int memory_size = 2; const int batch_size = 2; const int layer_size = 2; const int time_step = 0; Eigen::Tensor<float, 2> y_true(batch_size, layer_size); y_true.setValues({ {1, 2}, {1, 2} }); Eigen::Tensor<float, 3> y_pred(batch_size, memory_size, layer_size); y_pred.setValues({ {{1, 1}, {0, 0}}, {{2, 2}, {0, 0}} }); float error_ptr[] = { 0, 0, 0, 0 }; Eigen::DefaultDevice device; operation(y_pred.data(), y_true.data(), error_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 2>> error(error_ptr, batch_size, memory_size); BOOST_CHECK_CLOSE(error(0, 0), 0.249999881, 1e-4); BOOST_CHECK_CLOSE(error(1, 0), 0.499999523, 1e-4); BOOST_CHECK_CLOSE(error(0, 1), 0, 1e-4); BOOST_CHECK_CLOSE(error(1, 1), 0, 1e-4); } /** MAPELossGradOp Tests */ BOOST_AUTO_TEST_CASE(constructorMAPELossGradOp) { MAPELossGradTensorOp<float, Eigen::DefaultDevice>* ptrMAPELoss = nullptr; MAPELossGradTensorOp<float, Eigen::DefaultDevice>* nullPointerMAPELoss = nullptr; BOOST_CHECK_EQUAL(ptrMAPELoss, nullPointerMAPELoss); } BOOST_AUTO_TEST_CASE(destructorMAPELossGradOp) { MAPELossGradTensorOp<float, Eigen::DefaultDevice>* ptrMAPELoss = nullptr; ptrMAPELoss = new MAPELossGradTensorOp<float, Eigen::DefaultDevice>(); delete ptrMAPELoss; } BOOST_AUTO_TEST_CASE(operationfunctionMAPELossGradOp) { MAPELossGradTensorOp<float, Eigen::DefaultDevice> operation; const int memory_size = 2; const int batch_size = 2; const int layer_size = 2; const int time_step = 0; Eigen::Tensor<float, 2> y_true(batch_size, layer_size); y_true.setValues({ {1, 2}, {1, 2} }); Eigen::Tensor<float, 3> y_pred(batch_size, memory_size, layer_size); y_pred.setValues({ {{1, 1}, {0, 0}}, {{2, 2}, {0, 0}} }); float error_ptr[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; Eigen::DefaultDevice device; operation(y_pred.data(), y_true.data(), error_ptr, batch_size, memory_size, layer_size, time_step, device); Eigen::TensorMap<Eigen::Tensor<float, 3>> error(error_ptr, batch_size, memory_size, layer_size); BOOST_CHECK_CLOSE(error(0, 0, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(0, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 0, 0), -0.5, 1e-4); BOOST_CHECK_CLOSE(error(1, 1, 0), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(0, 0, 1), 0.250000149, 1e-4); BOOST_CHECK_CLOSE(error(0, 1, 1), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 0, 1), 0.0, 1e-4); BOOST_CHECK_CLOSE(error(1, 1, 1), 0.0, 1e-4); } BOOST_AUTO_TEST_SUITE_END()
34.543765
115
0.717402
dmccloskey
fe89c3c52039e7d78ec052a975eafa656fa8bc0d
1,964
cpp
C++
modules/core/trigonometric/unit/table/rem_pio2_straight.cpp
pbrunet/nt2
2aeca0f6a315725b335efd5d9dc95d72e10a7fb7
[ "BSL-1.0" ]
null
null
null
modules/core/trigonometric/unit/table/rem_pio2_straight.cpp
pbrunet/nt2
2aeca0f6a315725b335efd5d9dc95d72e10a7fb7
[ "BSL-1.0" ]
null
null
null
modules/core/trigonometric/unit/table/rem_pio2_straight.cpp
pbrunet/nt2
2aeca0f6a315725b335efd5d9dc95d72e10a7fb7
[ "BSL-1.0" ]
null
null
null
//============================================================================== // Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #include <nt2/table.hpp> #include <nt2/include/functions/rem_pio2_straight.hpp> #include <nt2/include/functions/sin.hpp> #include <nt2/include/functions/cos.hpp> #include <nt2/include/functions/linspace.hpp> #include <nt2/include/functions/of_size.hpp> #include <nt2/include/functions/tie.hpp> #include <nt2/include/constants/pi.hpp> #include <nt2/sdk/unit/module.hpp> #include <nt2/sdk/unit/tests/relation.hpp> NT2_TEST_CASE_TPL(rem_pio2_straight_table, NT2_REAL_TYPES) { using nt2::rem_pio2_straight; using nt2::table; typedef typename nt2::meta::as_integer<T>::type iT; typedef table<iT> tabi_t; typedef table<T> tab_t; static const size_t nb = 60; tab_t a = nt2::linspace(T(0), T(10)*nt2::Pi<T>(), nb); tab_t r(nt2::of_size(1, nb)); tabi_t n(nt2::of_size(1, nb)); { rem_pio2_straight(a, n, r); for(size_t i = 1; i <= nb; ++i) { iT n1; T r1; rem_pio2_straight(a(i), n1, r1); NT2_TEST_EQUAL(n(i), n1); NT2_TEST_EQUAL(r(i), r1); } } { n = rem_pio2_straight(a, r); for(size_t i = 1; i <= nb; ++i) { iT n1; T r1; rem_pio2_straight(a(i), n1, r1); NT2_TEST_EQUAL(n(i), n1); NT2_TEST_EQUAL(r(i), r1); } } { nt2::tie(n, r) = rem_pio2_straight(a); for(size_t i = 1; i <= nb; ++i) { iT n1; T r1; rem_pio2_straight(a(i), n1, r1); NT2_TEST_EQUAL(n(i), n1); NT2_TEST_EQUAL(r(i), r1); } } }
28.057143
80
0.559063
pbrunet
fe8c190bbf3e995fbc3f245105767646bdb0822a
7,001
cpp
C++
termsrv/common/license/common/certlib/licecert/licecert.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
termsrv/common/license/common/certlib/licecert/licecert.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
termsrv/common/license/common/certlib/licecert/licecert.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 1998 Microsoft Corporation Module Name: licecert.cpp Abstract: This module contains the APIs for parsing and verifying X509 certificates Author: Frederick Chong (fredch) 6/1/1998 Environment: Win32, WinCE, Win16 Notes: --*/ #include <windows.h> #include "license.h" #include "certcate.h" #include "licecert.h" #define MAX_NUM_CERT_BLOBS 200 //+---------------------------------------------------------------------------- // // Function: // // VerifyCertChain // // Abstract: // // Verifies a chain of X509 certificates // // Parameters: // // pbCert - Points to the certificate chain // cbCert - Size of the certificate chain // pbPublicKey - The memory to store the public key of the subject on output. // If set to NULL on input, the API will return // LICENSE_STATUS_INSUFFICIENT_BUFFER and the size of the // required buffer set in pcbPublicKey. // pcbPublicKey - Size of the allocated memory on input. On output, contains // the actual size of the public key. // pfDates - How the API should check the validity dates in the cert chain. // This flag may be set to the following values: // // CERT_DATE_ERROR_IF_INVALID - The API will return an error if the // dates are invalid. When the API returns, // this flag will be set to CERT_DATE_OK if the // dates are OK or one of CERT_DATE_NOT_BEFORE_INVALID // or CERT_DATE_NOT_AFTER_INVALID. // CERT_DATE_DONT_VALIDATE - Don't validate the dates in the cert chain. The value // in this flag is not changed when the API returns. // CERT_DATE_WARN_IF_INVALID - Don't return an error for invalid cert dates. // When the API returns, this flag will be set to // CERT_DATE_OK if the dates are OK or one of // CERT_DATE_NOT_BEFORE_INVALID or // CERT_DATE_NOT_AFTER_INVALID. // // Return: // // LICENSE_STATUS_OK if the function is successful. // //+---------------------------------------------------------------------------- LICENSE_STATUS VerifyCertChain( LPBYTE pbCert, DWORD cbCert, LPBYTE pbPublicKey, LPDWORD pcbPublicKey, LPDWORD pfDates ) { PCert_Chain pCertChain = ( PCert_Chain )pbCert; UNALIGNED Cert_Blob *pCertificate; BYTE FAR * abCertAligned; LPBYTE lpCertHandles = NULL; LPCERTIFICATEHANDLE phCert; LICENSE_STATUS dwRetCode = LICENSE_STATUS_OK; DWORD dwCertType = CERTYPE_X509, dwIssuerLen, i, cbCertHandles = 0; BOOL fRet; if( ( NULL == pCertChain ) || ( sizeof( Cert_Chain ) >= cbCert ) ) { return( LICENSE_STATUS_INVALID_INPUT ); } // // check cert chain version // if( MAX_CERT_CHAIN_VERSION < GET_CERTIFICATE_VERSION( pCertChain->dwVersion ) ) { return( LICENSE_STATUS_NOT_SUPPORTED ); } // // allocate memory for the certificate handles // // arbitrary limit of blobs, so that cbCertHandles doesn't overflow if (pCertChain->dwNumCertBlobs > MAX_NUM_CERT_BLOBS) { return (LICENSE_STATUS_INVALID_INPUT); } // // Verify input data before actually allocate memory // pCertificate = (PCert_Blob)&(pCertChain->CertBlob[0]); for(i=0; i < pCertChain->dwNumCertBlobs; i++) { if (((PBYTE)pCertificate > (pbCert + (cbCert - sizeof(Cert_Blob)))) || (pCertificate->cbCert == 0) || (pCertificate->cbCert > (DWORD)((pbCert + cbCert) - pCertificate->abCert))) { return (LICENSE_STATUS_INVALID_INPUT); } pCertificate = (PCert_Blob)(pCertificate->abCert + pCertificate->cbCert); } cbCertHandles = sizeof( CERTIFICATEHANDLE ) * pCertChain->dwNumCertBlobs; lpCertHandles = new BYTE[ cbCertHandles ]; if( NULL == lpCertHandles ) { return( LICENSE_STATUS_OUT_OF_MEMORY ); } memset( lpCertHandles, 0, cbCertHandles ); // // Load all the certificates into memory. The certificate chain always // start with the root issuer's certificate // for( i = 0, pCertificate = pCertChain->CertBlob, phCert = ( LPCERTIFICATEHANDLE )lpCertHandles; i < pCertChain->dwNumCertBlobs; i++, phCert++ ) { if (i != 0) { if (pCertificate->abCert == NULL) { abCertAligned = NULL; } else { abCertAligned = new BYTE[pCertificate->cbCert]; if (NULL == abCertAligned) { dwRetCode = LICENSE_STATUS_OUT_OF_MEMORY; goto done; } memcpy(abCertAligned,pCertificate->abCert,pCertificate->cbCert); } } else { // // First item is always aligned // abCertAligned = pCertificate->abCert; } fRet = PkcsCertificateLoadAndVerify( phCert, abCertAligned, pCertificate->cbCert, &dwCertType, CERTSTORE_APPLICATION, CERTTRUST_NOONE, NULL, &dwIssuerLen, NULL, pfDates ); if ((abCertAligned != NULL) && (abCertAligned != pCertificate->abCert)) { delete [] abCertAligned; } if( !fRet ) { dwRetCode = GetLastError(); goto done; } pCertificate = (PCert_Blob )(pCertificate->abCert + pCertificate->cbCert); } // // Get the public key of the last certificate // if( !PkcsCertificateGetPublicKey( *( phCert - 1), pbPublicKey, pcbPublicKey ) ) { dwRetCode = GetLastError(); } done: // // free all the certificate handles // if( lpCertHandles ) { for( i = 0, phCert = ( LPCERTIFICATEHANDLE )lpCertHandles; i < pCertChain->dwNumCertBlobs; i++, phCert++ ) { if( *phCert ) { PkcsCertificateCloseHandle( *phCert ); } } delete [] lpCertHandles; } return( dwRetCode ); }
28.8107
101
0.511927
npocmaka
fe8e9545e56d2416bd3e746e9ef28da09d7fac12
45,458
cc
C++
DQM/CTPPS/plugins/CTPPSDiamondDQMSource.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
DQM/CTPPS/plugins/CTPPSDiamondDQMSource.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
DQM/CTPPS/plugins/CTPPSDiamondDQMSource.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
/**************************************************************************** * * This is a part of CTPPS offline software. * Authors: * Jan Kašpar (jan.kaspar@gmail.com) * Nicola Minafra * Laurent Forthomme * ****************************************************************************/ #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Utilities/interface/InputTag.h" #include "DQMServices/Core/interface/DQMEDAnalyzer.h" #include "DQMServices/Core/interface/DQMStore.h" #include "DQMServices/Core/interface/MonitorElement.h" #include "DataFormats/Provenance/interface/EventRange.h" #include "DataFormats/CTPPSDigi/interface/TotemVFATStatus.h" #include "DataFormats/CTPPSDigi/interface/TotemFEDInfo.h" #include "DataFormats/Common/interface/DetSetVector.h" #include "DataFormats/CTPPSReco/interface/TotemRPLocalTrack.h" #include "DataFormats/CTPPSDetId/interface/CTPPSDiamondDetId.h" #include "DataFormats/CTPPSDigi/interface/CTPPSDiamondDigi.h" #include "DataFormats/CTPPSReco/interface/CTPPSDiamondRecHit.h" #include "DataFormats/CTPPSReco/interface/CTPPSDiamondLocalTrack.h" #include <string> //---------------------------------------------------------------------------------------------------- class CTPPSDiamondDQMSource : public DQMEDAnalyzer { public: CTPPSDiamondDQMSource( const edm::ParameterSet& ); virtual ~CTPPSDiamondDQMSource(); protected: void dqmBeginRun( const edm::Run&, const edm::EventSetup& ) override; void bookHistograms( DQMStore::IBooker&, const edm::Run&, const edm::EventSetup& ) override; void analyze( const edm::Event&, const edm::EventSetup& ); void beginLuminosityBlock( const edm::LuminosityBlock&, const edm::EventSetup& ); void endLuminosityBlock( const edm::LuminosityBlock&, const edm::EventSetup& ); void endRun( const edm::Run&, const edm::EventSetup& ); private: // Constants static const double SEC_PER_LUMI_SECTION; // Number of seconds per lumisection: used to compute hit rates in Hz static const int CHANNEL_OF_VFAT_CLOCK; // Channel ID of the VFAT that contains clock data static const double DISPLAY_RESOLUTION_FOR_HITS_MM; // Bin width of histograms showing hits and tracks (in mm) static const double INV_DISPLAY_RESOLUTION_FOR_HITS_MM; static const double HPTDC_BIN_WIDTH_NS; // ns per HPTDC bin static const int CTPPS_NUM_OF_ARMS; static const int CTPPS_DIAMOND_STATION_ID; static const int CTPPS_DIAMOND_RP_ID; static const int CTPPS_NEAR_RP_ID; static const int CTPPS_FAR_RP_ID; static const int CTPPS_DIAMOND_NUM_OF_PLANES; static const int CTPPS_DIAMOND_NUM_OF_CHANNELS; static const int CTPPS_FED_ID_45; static const int CTPPS_FED_ID_56; edm::EDGetTokenT< edm::DetSetVector<TotemVFATStatus> > tokenStatus_; edm::EDGetTokenT< edm::DetSetVector<TotemRPLocalTrack> > tokenLocalTrack_; edm::EDGetTokenT< edm::DetSetVector<CTPPSDiamondDigi> > tokenDigi_; edm::EDGetTokenT< edm::DetSetVector<CTPPSDiamondRecHit> > tokenDiamondHit_; edm::EDGetTokenT< edm::DetSetVector<CTPPSDiamondLocalTrack> > tokenDiamondTrack_; edm::EDGetTokenT< std::vector<TotemFEDInfo> > tokenFEDInfo_; bool excludeMultipleHits_; double minimumStripAngleForTomography_; double maximumStripAngleForTomography_; std::vector< std::pair<edm::EventRange, int> > runParameters_; int centralOOT_; unsigned int verbosity_; /// plots related to the whole system struct GlobalPlots { MonitorElement* h_trackCorr_hor = NULL; GlobalPlots() {} GlobalPlots( DQMStore::IBooker& ibooker ); }; GlobalPlots globalPlot_; /// plots related to one Diamond detector package struct PotPlots { MonitorElement* activity_per_bx = NULL; MonitorElement* activity_per_bx_plus1 = NULL; MonitorElement* activity_per_bx_minus1 = NULL; MonitorElement* hitDistribution2d = NULL; MonitorElement* hitDistribution2dOOT = NULL; MonitorElement* hitDistribution2dOOT_le = NULL; MonitorElement* hitDistribution2dOOT_te = NULL; MonitorElement* activePlanes = NULL; MonitorElement* trackDistribution = NULL; MonitorElement* trackDistributionOOT = NULL; MonitorElement* stripTomographyAllFar = NULL; MonitorElement* stripTomographyAllFar_plus1 = NULL; MonitorElement* stripTomographyAllFar_minus1 = NULL; MonitorElement* leadingEdgeCumulative_both = NULL, *leadingEdgeCumulative_le = NULL; MonitorElement* timeOverThresholdCumulativePot = NULL, *leadingTrailingCorrelationPot = NULL; MonitorElement* leadingWithoutTrailingCumulativePot = NULL; MonitorElement* ECCheck = NULL; MonitorElement* HPTDCErrorFlags_cumulative = NULL; MonitorElement* clock_Digi1_le = NULL; MonitorElement* clock_Digi1_te = NULL; MonitorElement* clock_Digi3_le = NULL; MonitorElement* clock_Digi3_te = NULL; PotPlots() {}; PotPlots( DQMStore::IBooker& ibooker, unsigned int id ); }; std::unordered_map<unsigned int, PotPlots> potPlots_; int EC_difference_56_, EC_difference_45_; /// plots related to one Diamond plane struct PlanePlots { MonitorElement* digiProfileCumulativePerPlane = NULL; MonitorElement* hitProfile = NULL; MonitorElement* hit_multiplicity = NULL; MonitorElement* stripTomography_far = NULL; PlanePlots() {} PlanePlots( DQMStore::IBooker& ibooker, unsigned int id ); }; std::unordered_map<unsigned int, PlanePlots> planePlots_; /// plots related to one Diamond channel struct ChannelPlots { MonitorElement* activity_per_bx = NULL; MonitorElement* activity_per_bx_plus1 = NULL; MonitorElement* activity_per_bx_minus1 = NULL; MonitorElement* HPTDCErrorFlags = NULL; MonitorElement* leadingEdgeCumulative_both = NULL, *leadingEdgeCumulative_le = NULL; MonitorElement* TimeOverThresholdCumulativePerChannel = NULL; MonitorElement* LeadingTrailingCorrelationPerChannel = NULL; MonitorElement* leadingWithoutTrailing = NULL; MonitorElement* stripTomography_far = NULL; MonitorElement* hit_rate = NULL; MonitorElement* ECCheckPerChannel = NULL; unsigned long hitsCounterPerLumisection; ChannelPlots() : hitsCounterPerLumisection( 0 ) {} ChannelPlots( DQMStore::IBooker &ibooker, unsigned int id ); }; std::unordered_map<unsigned int, ChannelPlots> channelPlots_; }; //---------------------------------------------------------------------------------------------------- // Values for all constants const double CTPPSDiamondDQMSource::SEC_PER_LUMI_SECTION = 23.31; const int CTPPSDiamondDQMSource::CHANNEL_OF_VFAT_CLOCK = 30; const double CTPPSDiamondDQMSource::DISPLAY_RESOLUTION_FOR_HITS_MM = 0.1; const double CTPPSDiamondDQMSource::INV_DISPLAY_RESOLUTION_FOR_HITS_MM = 1./DISPLAY_RESOLUTION_FOR_HITS_MM; const double CTPPSDiamondDQMSource::HPTDC_BIN_WIDTH_NS = 25./1024; const int CTPPSDiamondDQMSource::CTPPS_NUM_OF_ARMS = 2; const int CTPPSDiamondDQMSource::CTPPS_DIAMOND_STATION_ID = 1; const int CTPPSDiamondDQMSource::CTPPS_DIAMOND_RP_ID = 6; const int CTPPSDiamondDQMSource::CTPPS_NEAR_RP_ID = 2; const int CTPPSDiamondDQMSource::CTPPS_FAR_RP_ID = 3; const int CTPPSDiamondDQMSource::CTPPS_DIAMOND_NUM_OF_PLANES = 4; const int CTPPSDiamondDQMSource::CTPPS_DIAMOND_NUM_OF_CHANNELS = 12; const int CTPPSDiamondDQMSource::CTPPS_FED_ID_56 = 582; const int CTPPSDiamondDQMSource::CTPPS_FED_ID_45 = 583; //---------------------------------------------------------------------------------------------------- CTPPSDiamondDQMSource::GlobalPlots::GlobalPlots( DQMStore::IBooker& ibooker ) { ibooker.setCurrentFolder( "CTPPS" ); h_trackCorr_hor = ibooker.book2D( "track correlation all hor", "rp, all, hor", 6, -0.5, 5.5, 6, -0.5, 5.5 ); TH2F* hist = h_trackCorr_hor->getTH2F(); TAxis* xa = hist->GetXaxis(), *ya = hist->GetYaxis(); xa->SetBinLabel( 6, "45, 210, near" ); ya->SetBinLabel( 1, "45, 210, near" ); xa->SetBinLabel( 5, "45, 210, far" ); ya->SetBinLabel( 2, "45, 210, far" ); xa->SetBinLabel( 4, "45, 220, cyl" ); ya->SetBinLabel( 3, "45, 220, cyl" ); xa->SetBinLabel( 3, "56, 210, near" ); ya->SetBinLabel( 4, "56, 210, near" ); xa->SetBinLabel( 2, "56, 210, far" ); ya->SetBinLabel( 5, "56, 210, far" ); xa->SetBinLabel( 1, "56, 220, cyl" ); ya->SetBinLabel( 6, "56, 220, cyl" ); } //---------------------------------------------------------------------------------------------------- CTPPSDiamondDQMSource::PotPlots::PotPlots( DQMStore::IBooker& ibooker, unsigned int id ) { std::string path, title; CTPPSDiamondDetId( id ).rpName( path, CTPPSDiamondDetId::nPath ); ibooker.setCurrentFolder( path ); CTPPSDiamondDetId( id ).rpName( title, CTPPSDiamondDetId::nFull ); activity_per_bx = ibooker.book1D( "activity per BX", title+" activity per BX;Event.BX", 4002, -1.5, 4000. + 0.5 ); activity_per_bx_plus1 = ibooker.book1D( "activity per BX OOT +1", title+" activity per BX OOT +1;Event.BX", 4002, -1.5, 4000. + 0.5 ); activity_per_bx_minus1 = ibooker.book1D( "activity per BX OOT -1", title+" activity per BX OOT -1;Event.BX", 4002, -1.5, 4000. + 0.5 ); hitDistribution2d = ibooker.book2D( "hits in planes", title+" hits in planes;plane number;x (mm)", 10, -0.5, 4.5, 19.*INV_DISPLAY_RESOLUTION_FOR_HITS_MM, -1, 18 ); hitDistribution2dOOT= ibooker.book2D( "hits with OOT in planes", title+" hits with OOT in planes;plane number + 0.1 OOT;x (mm)", 41, -0.1, 4, 19.*INV_DISPLAY_RESOLUTION_FOR_HITS_MM, -1, 18 ); hitDistribution2dOOT_le= ibooker.book2D( "hits with OOT in planes (le only)", title+" hits with OOT in planes (le only);plane number + 0.1 OOT;x (mm)", 41, -0.1, 4, 19.*INV_DISPLAY_RESOLUTION_FOR_HITS_MM, -1, 18 ); hitDistribution2dOOT_te= ibooker.book2D( "hits with OOT in planes (te only)", title+" hits with OOT in planes (te only);plane number + 0.1 OOT;x (mm)", 41, -0.1, 4, 19.*INV_DISPLAY_RESOLUTION_FOR_HITS_MM, -1, 18 ); activePlanes = ibooker.book1D( "active planes", title+" active planes;number of active planes", 6, -0.5, 5.5 ); trackDistribution = ibooker.book1D( "tracks", title+" tracks;x (mm)", 19.*INV_DISPLAY_RESOLUTION_FOR_HITS_MM, -1, 18 ); trackDistributionOOT = ibooker.book2D( "tracks with OOT", title+" tracks with OOT;plane number;x (mm)", 9, -0.5, 4, 19.*INV_DISPLAY_RESOLUTION_FOR_HITS_MM, -1, 18 ); stripTomographyAllFar = ibooker.book2D( "tomography all far", title+" tomography with strips far (all planes);x + 25*plane(mm);y (mm)", 100, 0, 100, 24, -2, 10 ); stripTomographyAllFar_plus1 = ibooker.book2D( "tomography all far OOT +1", title+" tomography with strips far (all planes);x + 25*plane(mm);y (mm)", 100, 0, 100, 24, -2, 10 ); stripTomographyAllFar_minus1 = ibooker.book2D( "tomography all far OOT -1", title+" tomography with strips far (all planes);x + 25*plane(mm);y (mm)", 100, 0, 100, 24, -2, 10 ); leadingEdgeCumulative_both = ibooker.book1D( "leading edge (le and te)", title+" leading edge (le and te); leading edge (ns)", 125, 0, 125 ); leadingEdgeCumulative_le = ibooker.book1D( "leading edge (le only)", title+" leading edge (le only); leading edge (ns)", 125, 0, 125 ); timeOverThresholdCumulativePot = ibooker.book1D( "time over threshold", title+" time over threshold;time over threshold (ns)", 100, -100, 100 ); leadingTrailingCorrelationPot = ibooker.book2D( "leading trailing correlation", title+" leading trailing correlation;leading edge (ns);trailing edge (ns)", 100, 0, 100, 100, 0, 100 ); leadingWithoutTrailingCumulativePot = ibooker.book1D( "leading edges without trailing", title+" leading edges without trailing;leading edges without trailing", 4, 0.5, 4.5 ); leadingWithoutTrailingCumulativePot->getTH1F()->GetXaxis()->SetBinLabel( 1, "Nothing" ); leadingWithoutTrailingCumulativePot->getTH1F()->GetXaxis()->SetBinLabel( 2, "Leading only" ); leadingWithoutTrailingCumulativePot->getTH1F()->GetXaxis()->SetBinLabel( 3, "Trailing only" ); leadingWithoutTrailingCumulativePot->getTH1F()->GetXaxis()->SetBinLabel( 4, "Both" ); ECCheck = ibooker.book1D( "optorxEC(8bit) - vfatEC", title+" EC Error;optorxEC-vfatEC", 512, -256, 256 ); HPTDCErrorFlags_cumulative = ibooker.book1D( "HPTDC Errors", title+" HPTDC Errors", 16, -0.5, 16.5 ); for ( unsigned short error_index=1; error_index<16; ++error_index ) HPTDCErrorFlags_cumulative->getTH1F()->GetXaxis()->SetBinLabel( error_index, HPTDCErrorFlags::getHPTDCErrorName( error_index-1 ).c_str() ); HPTDCErrorFlags_cumulative->getTH1F()->GetXaxis()->SetBinLabel( 16, "MH" ); ibooker.setCurrentFolder( path+"/clock/" ); clock_Digi1_le = ibooker.book1D( "clock1 leading edge", title+" clock1;leading edge (ns)", 125, 0, 125 ); clock_Digi1_te = ibooker.book1D( "clock1 trailing edge", title+" clock1;trailing edge (ns)", 125, 0, 125 ); clock_Digi3_le = ibooker.book1D( "clock3 leading edge", title+" clock3;leading edge (ns)", 1000, 0, 125 ); clock_Digi3_te = ibooker.book1D( "clock3 trailing edge", title+" clock3;trailing edge (ns)", 125, 0, 125 ); } //---------------------------------------------------------------------------------------------------- CTPPSDiamondDQMSource::PlanePlots::PlanePlots( DQMStore::IBooker& ibooker, unsigned int id ) { std::string path, title; CTPPSDiamondDetId( id ).planeName( path, CTPPSDiamondDetId::nPath ); ibooker.setCurrentFolder( path ); CTPPSDiamondDetId( id ).planeName( title, CTPPSDiamondDetId::nFull ); digiProfileCumulativePerPlane = ibooker.book1D( "digi profile", title+" digi profile; ch number", 12, -0.5, 11.5 ); hitProfile = ibooker.book1D( "hit profile", title+" hit profile;x (mm)", 19.*INV_DISPLAY_RESOLUTION_FOR_HITS_MM, -1, 18 ); hit_multiplicity = ibooker.book1D( "channels per plane", title+" channels per plane; ch per plane", 13, -0.5, 12.5 ); stripTomography_far = ibooker.book2D( "tomography far", title+" tomography with strips far;x + 25 OOT (mm);y (mm)", 150, -50, 100, 24, -2, 10 ); } //---------------------------------------------------------------------------------------------------- CTPPSDiamondDQMSource::ChannelPlots::ChannelPlots( DQMStore::IBooker& ibooker, unsigned int id ) : hitsCounterPerLumisection(0) { std::string path, title; CTPPSDiamondDetId( id ).channelName( path, CTPPSDiamondDetId::nPath ); ibooker.setCurrentFolder( path ); CTPPSDiamondDetId( id ).channelName( title, CTPPSDiamondDetId::nFull ); leadingWithoutTrailing = ibooker.book1D( "Leading Edges Without Trailing", title+" leading edges without trailing", 4, 0.5, 4.5 ); leadingWithoutTrailing->getTH1F()->GetXaxis()->SetBinLabel( 1, "Nothing" ); leadingWithoutTrailing->getTH1F()->GetXaxis()->SetBinLabel( 2, "Leading only" ); leadingWithoutTrailing->getTH1F()->GetXaxis()->SetBinLabel( 3, "Trailer only" ); leadingWithoutTrailing->getTH1F()->GetXaxis()->SetBinLabel( 4, "Full" ); activity_per_bx = ibooker.book1D( "activity per BX", title+" activity per BX;Event.BX", 4002, -1.5, 4000. + 0.5 ); activity_per_bx_plus1 = ibooker.book1D( "activity per BX OOT +1", title+" activity per BX OOT +1;Event.BX", 4002, -1.5, 4000. + 0.5 ); activity_per_bx_minus1 = ibooker.book1D( "activity per BX OOT -1", title+" activity per BX OOT -1;Event.BX", 4002, -1.5, 4000. + 0.5 ); HPTDCErrorFlags = ibooker.book1D( "hptdc_Errors", title+" HPTDC Errors", 16, -0.5, 16.5 ); for ( unsigned short error_index=1; error_index<16; ++error_index ) HPTDCErrorFlags->getTH1F()->GetXaxis()->SetBinLabel( error_index, HPTDCErrorFlags::getHPTDCErrorName( error_index-1 ).c_str() ); HPTDCErrorFlags->getTH1F()->GetXaxis()->SetBinLabel( 16, "MH" ); leadingEdgeCumulative_both = ibooker.book1D( "leading edge (le and te)", title+" leading edge; leading edge (ns)", 100, 0, 200 ); leadingEdgeCumulative_le = ibooker.book1D( "leading edge (le only)", title+" leading edge; leading edge (ns)", 200, 0, 200 ); TimeOverThresholdCumulativePerChannel = ibooker.book1D( "time over threshold", title+" time over threshold;time over threshold (ns)", 100, -100, 100 ); LeadingTrailingCorrelationPerChannel = ibooker.book2D( "leading trailing correlation", title+" leading trailing correlation;leading edge (ns);trailing edge (ns)", 100, 0, 100, 100, 0, 100 ); ECCheckPerChannel = ibooker.book1D("optorxEC(8bit) - vfatEC vs optorxEC", title+" EC Error;optorxEC-vfatEC", 512, -256, 256 ); stripTomography_far = ibooker.book2D( "tomography far", "tomography with strips far;x + 25 OOT (mm);y (mm)", 150, -50, 100, 24, -2, 10 ); hit_rate = ibooker.book1D( "hit rate", title+"hit rate;rate (Hz)", 10, 0, 100 ); } //---------------------------------------------------------------------------------------------------- CTPPSDiamondDQMSource::CTPPSDiamondDQMSource( const edm::ParameterSet& ps ) : tokenStatus_ ( consumes< edm::DetSetVector<TotemVFATStatus> > ( ps.getParameter<edm::InputTag>( "tagStatus" ) ) ), tokenLocalTrack_ ( consumes< edm::DetSetVector<TotemRPLocalTrack> > ( ps.getParameter<edm::InputTag>( "tagLocalTrack" ) ) ), tokenDigi_ ( consumes< edm::DetSetVector<CTPPSDiamondDigi> > ( ps.getParameter<edm::InputTag>( "tagDigi" ) ) ), tokenDiamondHit_ ( consumes< edm::DetSetVector<CTPPSDiamondRecHit> > ( ps.getParameter<edm::InputTag>( "tagDiamondRecHits" ) ) ), tokenDiamondTrack_( consumes< edm::DetSetVector<CTPPSDiamondLocalTrack> >( ps.getParameter<edm::InputTag>( "tagDiamondLocalTracks" ) ) ), tokenFEDInfo_ ( consumes< std::vector<TotemFEDInfo> > ( ps.getParameter<edm::InputTag>( "tagFEDInfo" ) ) ), excludeMultipleHits_ ( ps.getParameter<bool>( "excludeMultipleHits" ) ), minimumStripAngleForTomography_( ps.getParameter<double>( "minimumStripAngleForTomography" ) ), maximumStripAngleForTomography_( ps.getParameter<double>( "maximumStripAngleForTomography" ) ), centralOOT_( -999 ), verbosity_ ( ps.getUntrackedParameter<unsigned int>( "verbosity", 0 ) ), EC_difference_56_( -500 ), EC_difference_45_( -500 ) { for ( const auto& pset : ps.getParameter< std::vector<edm::ParameterSet> >( "offsetsOOT" ) ) { runParameters_.emplace_back( std::make_pair( pset.getParameter<edm::EventRange>( "validityRange" ), pset.getParameter<int>( "centralOOT" ) ) ); } } //---------------------------------------------------------------------------------------------------- CTPPSDiamondDQMSource::~CTPPSDiamondDQMSource() {} //---------------------------------------------------------------------------------------------------- void CTPPSDiamondDQMSource::dqmBeginRun( const edm::Run& iRun, const edm::EventSetup& ) { centralOOT_ = -999; for ( const auto& oot : runParameters_ ) { if ( edm::contains( oot.first, edm::EventID( iRun.run(), 0, 1 ) ) ) { centralOOT_ = oot.second; break; } } } //---------------------------------------------------------------------------------------------------- void CTPPSDiamondDQMSource::bookHistograms( DQMStore::IBooker& ibooker, const edm::Run&, const edm::EventSetup& ) { ibooker.cd(); ibooker.setCurrentFolder( "CTPPS" ); globalPlot_= GlobalPlots( ibooker ); for ( unsigned short arm = 0; arm < CTPPS_NUM_OF_ARMS; ++arm ) { const CTPPSDiamondDetId rpId( arm, CTPPS_DIAMOND_STATION_ID, CTPPS_DIAMOND_RP_ID ); potPlots_[rpId] = PotPlots( ibooker, rpId ); for ( unsigned short pl = 0; pl < CTPPS_DIAMOND_NUM_OF_PLANES; ++pl ) { const CTPPSDiamondDetId plId( arm, CTPPS_DIAMOND_STATION_ID, CTPPS_DIAMOND_RP_ID, pl ); planePlots_[plId] = PlanePlots( ibooker, plId); for ( unsigned short ch = 0; ch < CTPPS_DIAMOND_NUM_OF_CHANNELS; ++ch ) { const CTPPSDiamondDetId chId( arm, CTPPS_DIAMOND_STATION_ID, CTPPS_DIAMOND_RP_ID, pl, ch ); channelPlots_[chId] = ChannelPlots( ibooker, chId ); } } } } //---------------------------------------------------------------------------------------------------- void CTPPSDiamondDQMSource::beginLuminosityBlock( const edm::LuminosityBlock&, const edm::EventSetup& ) { for ( auto& plot : channelPlots_ ) { if ( plot.second.hitsCounterPerLumisection != 0 ) { plot.second.hit_rate->Fill( (double) plot.second.hitsCounterPerLumisection / SEC_PER_LUMI_SECTION ); } plot.second.hitsCounterPerLumisection = 0; } } //---------------------------------------------------------------------------------------------------- void CTPPSDiamondDQMSource::analyze( const edm::Event& event, const edm::EventSetup& ) { // get event data edm::Handle< edm::DetSetVector<TotemVFATStatus> > diamondVFATStatus; event.getByToken( tokenStatus_, diamondVFATStatus ); edm::Handle< edm::DetSetVector<TotemRPLocalTrack> > stripTracks; event.getByToken( tokenLocalTrack_, stripTracks ); edm::Handle< edm::DetSetVector<CTPPSDiamondDigi> > diamondDigis; event.getByToken( tokenDigi_, diamondDigis ); edm::Handle< std::vector<TotemFEDInfo> > fedInfo; event.getByToken( tokenFEDInfo_, fedInfo ); edm::Handle< edm::DetSetVector<CTPPSDiamondRecHit> > diamondRecHits; event.getByToken( tokenDiamondHit_, diamondRecHits ); edm::Handle< edm::DetSetVector<CTPPSDiamondLocalTrack> > diamondLocalTracks; event.getByToken( tokenDiamondTrack_, diamondLocalTracks ); // check validity bool valid = true; valid &= diamondVFATStatus.isValid(); valid &= diamondDigis.isValid(); valid &= fedInfo.isValid(); if ( !valid ) { if ( verbosity_ ) { edm::LogProblem("CTPPSDiamondDQMSource") << "ERROR in TotemDQMModuleRP::analyze > some of the required inputs are not valid. Skipping this event.\n" << " diamondVFATStatus.isValid = " << diamondVFATStatus.isValid() << "\n" << " diamondDigis.isValid = " << diamondDigis.isValid() << "\n" << " fedInfo.isValid = " << fedInfo.isValid(); } return; } //------------------------------ // RP Plots //------------------------------ // if (event.bunchCrossing() > 100) return; //------------------------------ // Correlation Plots //------------------------------ for ( const auto& ds1 : *stripTracks ) { for ( const auto& tr1 : ds1 ) { if ( ! tr1.isValid() ) continue; CTPPSDetId rpId1( ds1.detId() ); unsigned int arm1 = rpId1.arm(); unsigned int stNum1 = rpId1.station(); unsigned int rpNum1 = rpId1.rp(); if (stNum1 != 0 || ( rpNum1 != 2 && rpNum1 != 3 ) ) continue; unsigned int idx1 = arm1*3 + rpNum1-2; for ( const auto& ds2 : *stripTracks ) { for ( const auto& tr2 : ds2 ) { if ( ! tr2.isValid() ) continue; CTPPSDetId rpId2(ds2.detId()); unsigned int arm2 = rpId2.arm(); unsigned int stNum2 = rpId2.station(); unsigned int rpNum2 = rpId2.rp(); if (stNum2 != 0 || ( rpNum2 != 2 && rpNum2 != 3 ) ) continue; unsigned int idx2 = arm2*3 + rpNum2-2; if ( idx1 >= idx2 ) globalPlot_.h_trackCorr_hor->Fill( 5-idx1, idx2 ); // strips-strips } } for ( const auto& ds2 : *diamondLocalTracks ) { for ( const auto& tr2 : ds2 ) { if ( ! tr2.isValid() ) continue; if ( centralOOT_ != -999 && tr2.getOOTIndex() != centralOOT_ ) continue; if ( excludeMultipleHits_ && tr2.getMultipleHits() > 0 ) continue; CTPPSDetId diamId2( ds2.detId() ); unsigned int arm2 = diamId2.arm(); if ( idx1 >= arm2*3+2 ) globalPlot_.h_trackCorr_hor->Fill( 5-idx1, arm2*3+2 ); // strips-diamonds else globalPlot_.h_trackCorr_hor->Fill( 5-(arm2*3+2 ),idx1 ); // strips-diamonds } } } } for ( const auto& ds1 : *diamondLocalTracks ) { for ( const auto& tr1 : ds1 ) { if ( ! tr1.isValid() ) continue; if ( excludeMultipleHits_ && tr1.getMultipleHits() > 0 ) continue; if ( centralOOT_ != -999 && tr1.getOOTIndex() != centralOOT_ ) continue; CTPPSDetId diamId1( ds1.detId() ); unsigned int arm1 = diamId1.arm(); globalPlot_.h_trackCorr_hor->Fill( 5-(arm1*3+2), arm1*3+2 ); // diamonds-diamonds for ( const auto& ds2 : *diamondLocalTracks ) { for ( const auto& tr2 : ds2 ) { if ( ! tr2.isValid() ) continue; if ( excludeMultipleHits_ && tr2.getMultipleHits() > 0 ) continue; if ( centralOOT_ != -999 && tr2.getOOTIndex() != centralOOT_ ) continue; CTPPSDetId diamId2( ds2.detId() ); unsigned int arm2 = diamId2.arm(); if ( arm1 > arm2 ) globalPlot_.h_trackCorr_hor->Fill( 5-(arm1*3+2), arm2*3+2 ); // diamonds-diamonds } } } } // Using CTPPSDiamondDigi for ( const auto& digis : *diamondDigis ) { const CTPPSDiamondDetId detId( digis.detId() ); CTPPSDiamondDetId detId_pot( digis.detId() ); for ( const auto& digi : digis ) { detId_pot.setPlane( 0 ); detId_pot.setChannel( 0 ); if ( detId.channel() == CHANNEL_OF_VFAT_CLOCK ) continue; if ( potPlots_.find( detId_pot ) == potPlots_.end() ) continue; //Leading without trailing investigation if ( digi.getLeadingEdge() == 0 && digi.getTrailingEdge() == 0 ) potPlots_[detId_pot].leadingWithoutTrailingCumulativePot->Fill( 1 ); else if ( digi.getLeadingEdge() != 0 && digi.getTrailingEdge() == 0 ) potPlots_[detId_pot].leadingWithoutTrailingCumulativePot->Fill( 2 ); else if ( digi.getLeadingEdge() == 0 && digi.getTrailingEdge() != 0 ) potPlots_[detId_pot].leadingWithoutTrailingCumulativePot->Fill( 3 ); else if ( digi.getLeadingEdge() != 0 && digi.getTrailingEdge() != 0 ) potPlots_[detId_pot].leadingWithoutTrailingCumulativePot->Fill( 4 ); // HPTDC Errors const HPTDCErrorFlags hptdcErrors = digi.getHPTDCErrorFlags(); for ( unsigned short hptdcErrorIndex = 1; hptdcErrorIndex < 16; ++hptdcErrorIndex ) if ( hptdcErrors.getErrorId( hptdcErrorIndex-1 ) ) potPlots_[detId_pot].HPTDCErrorFlags_cumulative->Fill( hptdcErrorIndex ); if ( digi.getMultipleHit() ) potPlots_[detId_pot].HPTDCErrorFlags_cumulative->Fill( 16 ); } } // EC Errors for ( const auto& vfat_status : *diamondVFATStatus ) { const CTPPSDiamondDetId detId( vfat_status.detId() ); CTPPSDiamondDetId detId_pot( vfat_status.detId() ); detId_pot.setPlane( 0 ); detId_pot.setChannel( 0 ); for ( const auto& status : vfat_status ) { if ( !status.isOK() ) continue; if ( potPlots_.find(detId_pot) == potPlots_.end() ) continue; // Check Event Number for ( const auto& optorx : *fedInfo ) { if ( detId.arm() == 1 && optorx.getFEDId() == CTPPS_FED_ID_56 ) { potPlots_[detId_pot].ECCheck->Fill((int)((optorx.getLV1()& 0xFF)-((unsigned int) status.getEC() & 0xFF)) & 0xFF); if ( ( static_cast<int>( ( optorx.getLV1() & 0xFF )-status.getEC() ) != EC_difference_56_ ) && ( static_cast<uint8_t>( ( optorx.getLV1() & 0xFF )-status.getEC() ) < 128 ) ) EC_difference_56_ = static_cast<int>( optorx.getLV1() & 0xFF )-( static_cast<unsigned int>( status.getEC() ) & 0xFF ); if ( EC_difference_56_ != 1 && EC_difference_56_ != -500 && EC_difference_56_ < 128 && EC_difference_56_ > -128 ) if (verbosity_) edm::LogProblem("CTPPSDiamondDQMSource") << "FED " << CTPPS_FED_ID_56 << ": ECError at EV: 0x"<< std::hex << optorx.getLV1() << "\t\tVFAT EC: 0x"<< static_cast<unsigned int>( status.getEC() ) << "\twith ID: " << std::dec << detId << "\tdiff: " << EC_difference_56_; } else if ( detId.arm() == 0 && optorx.getFEDId()== CTPPS_FED_ID_45 ) { potPlots_[detId_pot].ECCheck->Fill((int)((optorx.getLV1()& 0xFF)-status.getEC()) & 0xFF); if ( ( static_cast<int>( ( optorx.getLV1() & 0xFF )-status.getEC() ) != EC_difference_45_ ) && ( static_cast<uint8_t>( ( optorx.getLV1() & 0xFF )-status.getEC() ) < 128 ) ) EC_difference_45_ = static_cast<int>( optorx.getLV1() & 0xFF )-( static_cast<unsigned int>( status.getEC() ) & 0xFF ); if ( EC_difference_45_ != 1 && EC_difference_45_ != -500 && EC_difference_45_ < 128 && EC_difference_45_ > -128 ) if (verbosity_) edm::LogProblem("CTPPSDiamondDQMSource") << "FED " << CTPPS_FED_ID_45 << ": ECError at EV: 0x"<< std::hex << optorx.getLV1() << "\t\tVFAT EC: 0x"<< static_cast<unsigned int>( status.getEC() ) << "\twith ID: " << std::dec << detId << "\tdiff: " << EC_difference_45_; } } } } // Using CTPPSDiamondRecHit std::unordered_map<unsigned int, std::set<unsigned int> > planes; for ( const auto& rechits : *diamondRecHits ) { CTPPSDiamondDetId detId_pot( rechits.detId() ); detId_pot.setPlane( 0 ); detId_pot.setChannel( 0 ); const CTPPSDiamondDetId detId( rechits.detId() ); for ( const auto& rechit : rechits ) { if ( excludeMultipleHits_ && rechit.getMultipleHits() > 0 ) continue; planes[detId_pot].insert( detId.plane() ); if ( potPlots_.find( detId_pot ) == potPlots_.end() ) continue; float UFSDShift = 0.0; if ( rechit.getYWidth() < 3 ) UFSDShift = 0.5; // Display trick for UFSD that have 2 pixels with same X if ( rechit.getToT() != 0 && centralOOT_ != -999 && rechit.getOOTIndex() == centralOOT_ ) { TH2F *hitHistoTmp = potPlots_[detId_pot].hitDistribution2d->getTH2F(); TAxis *hitHistoTmpYAxis = hitHistoTmp->GetYaxis(); int startBin = hitHistoTmpYAxis->FindBin( rechit.getX() - 0.5*rechit.getXWidth() ); int numOfBins = rechit.getXWidth()*INV_DISPLAY_RESOLUTION_FOR_HITS_MM; for ( int i=0; i<numOfBins; ++i) { hitHistoTmp->Fill( detId.plane(), hitHistoTmpYAxis->GetBinCenter(startBin+i) + UFSDShift ); } } if ( rechit.getToT() != 0 ) { // Both potPlots_[detId_pot].leadingEdgeCumulative_both->Fill( rechit.getT() + 25*rechit.getOOTIndex() ); potPlots_[detId_pot].timeOverThresholdCumulativePot->Fill( rechit.getToT() ); TH2F *hitHistoOOTTmp = potPlots_[detId_pot].hitDistribution2dOOT->getTH2F(); TAxis *hitHistoOOTTmpYAxis = hitHistoOOTTmp->GetYaxis(); int startBin = hitHistoOOTTmpYAxis->FindBin( rechit.getX() - 0.5*rechit.getXWidth() ); int numOfBins = rechit.getXWidth()*INV_DISPLAY_RESOLUTION_FOR_HITS_MM; for ( int i=0; i<numOfBins; ++i) { hitHistoOOTTmp->Fill( detId.plane() + 0.1 * rechit.getOOTIndex(), hitHistoOOTTmpYAxis->GetBinCenter(startBin+i) ); } } else { if ( rechit.getT() == 0 ) { // Only trailing TH2F *hitHistoOOTTmp = potPlots_[detId_pot].hitDistribution2dOOT_te->getTH2F(); TAxis *hitHistoOOTTmpYAxis = hitHistoOOTTmp->GetYaxis(); int startBin = hitHistoOOTTmpYAxis->FindBin( rechit.getX() - 0.5*rechit.getXWidth() ); int numOfBins = rechit.getXWidth()*INV_DISPLAY_RESOLUTION_FOR_HITS_MM; for ( int i=0; i<numOfBins; ++i) { hitHistoOOTTmp->Fill( detId.plane() + 0.1 * rechit.getOOTIndex(), hitHistoOOTTmpYAxis->GetBinCenter(startBin+i) ); } } else { // Only leading potPlots_[detId_pot].leadingEdgeCumulative_le->Fill( rechit.getT() + 25*rechit.getOOTIndex() ); TH2F *hitHistoOOTTmp = potPlots_[detId_pot].hitDistribution2dOOT_le->getTH2F(); TAxis *hitHistoOOTTmpYAxis = hitHistoOOTTmp->GetYaxis(); int startBin = hitHistoOOTTmpYAxis->FindBin( rechit.getX() - 0.5*rechit.getXWidth() ); int numOfBins = rechit.getXWidth()*INV_DISPLAY_RESOLUTION_FOR_HITS_MM; for ( int i=0; i<numOfBins; ++i) { hitHistoOOTTmp->Fill( detId.plane() + 0.1 * rechit.getOOTIndex(), hitHistoOOTTmpYAxis->GetBinCenter(startBin+i) ); } } } if ( rechit.getToT() != 0 ) { switch ( rechit.getOOTIndex() - ( ( centralOOT_ != -999 ) ? centralOOT_ : 0 ) ) { case -1: potPlots_[detId_pot].activity_per_bx_minus1->Fill( event.bunchCrossing() ); break; case 0: potPlots_[detId_pot].activity_per_bx->Fill( event.bunchCrossing() ); break; case 1: potPlots_[detId_pot].activity_per_bx_plus1->Fill( event.bunchCrossing() ); break; } } // End if (complete hits) } } for ( const auto& plt : potPlots_ ) { plt.second.activePlanes->Fill( planes[plt.first].size() ); } // Using CTPPSDiamondLocalTrack for ( const auto& tracks : *diamondLocalTracks ) { CTPPSDiamondDetId detId_pot( tracks.detId() ); detId_pot.setPlane( 0 ); detId_pot.setChannel( 0 ); const CTPPSDiamondDetId detId( tracks.detId() ); for ( const auto& track : tracks ) { if ( ! track.isValid() ) continue; if ( excludeMultipleHits_ && track.getMultipleHits() > 0 ) continue; if ( potPlots_.find( detId_pot ) == potPlots_.end() ) continue; TH2F *trackHistoOOTTmp = potPlots_[detId_pot].trackDistributionOOT->getTH2F(); TAxis *trackHistoOOTTmpYAxis = trackHistoOOTTmp->GetYaxis(); int startBin = trackHistoOOTTmpYAxis->FindBin( track.getX0() - track.getX0Sigma() ); int numOfBins = 2*track.getX0Sigma()*INV_DISPLAY_RESOLUTION_FOR_HITS_MM; for ( int i=0; i<numOfBins; ++i) { trackHistoOOTTmp->Fill( track.getOOTIndex(), trackHistoOOTTmpYAxis->GetBinCenter(startBin+i) ); } if ( centralOOT_ != -999 && track.getOOTIndex() == centralOOT_ ) { TH1F *trackHistoInTimeTmp = potPlots_[detId_pot].trackDistribution->getTH1F(); int startBin = trackHistoInTimeTmp->FindBin( track.getX0() - track.getX0Sigma() ); int numOfBins = 2*track.getX0Sigma()*INV_DISPLAY_RESOLUTION_FOR_HITS_MM; for ( int i=0; i<numOfBins; ++i) { trackHistoInTimeTmp->Fill( trackHistoInTimeTmp->GetBinCenter(startBin+i) ); } } } } // Tomography of diamonds using strips for ( const auto& rechits : *diamondRecHits ) { CTPPSDiamondDetId detId_pot( rechits.detId() ); detId_pot.setPlane( 0 ); detId_pot.setChannel( 0 ); const CTPPSDiamondDetId detId( rechits.detId() ); for ( const auto& rechit : rechits ) { if ( excludeMultipleHits_ && rechit.getMultipleHits() > 0 ) continue; if ( rechit.getToT() == 0 ) continue; if ( !stripTracks.isValid() ) continue; if ( potPlots_.find( detId_pot ) == potPlots_.end() ) continue; for ( const auto& ds : *stripTracks ) { const CTPPSDetId stripId( ds.detId() ); for ( const auto& striplt : ds ) { if ( !striplt.isValid() ) continue; if ( stripId.arm() != detId_pot.arm() ) continue; if ( striplt.getTx() > maximumStripAngleForTomography_ || striplt.getTy() > maximumStripAngleForTomography_) continue; if ( striplt.getTx() < minimumStripAngleForTomography_ || striplt.getTy() < minimumStripAngleForTomography_) continue; if ( stripId.rp() == CTPPS_FAR_RP_ID ) { switch ( rechit.getOOTIndex() - ( ( centralOOT_ != -999 ) ? centralOOT_ : 0 ) ) { case -1: { potPlots_[detId_pot].stripTomographyAllFar_minus1->Fill( striplt.getX0() + 25*detId.plane(), striplt.getY0() ); } break; case 0: { potPlots_[detId_pot].stripTomographyAllFar->Fill( striplt.getX0() + 25*detId.plane(), striplt.getY0() ); } break; case 1: { potPlots_[detId_pot].stripTomographyAllFar_plus1->Fill( striplt.getX0() + 25*detId.plane(), striplt.getY0() ); } break; } } } } } } //------------------------------ // Clock Plots //------------------------------ for ( const auto& digis : *diamondDigis ) { const CTPPSDiamondDetId detId( digis.detId() ); CTPPSDiamondDetId detId_pot( digis.detId() ); if ( detId.channel() == CHANNEL_OF_VFAT_CLOCK ) { detId_pot.setPlane( 0 ); detId_pot.setChannel( 0 ); for ( const auto& digi : digis ) { if ( digi.getLeadingEdge() != 0 ) { if ( detId.plane() == 1 ) { potPlots_[detId_pot].clock_Digi1_le->Fill( HPTDC_BIN_WIDTH_NS * digi.getLeadingEdge() ); potPlots_[detId_pot].clock_Digi1_te->Fill( HPTDC_BIN_WIDTH_NS * digi.getTrailingEdge() ); } if ( detId.plane() == 3 ) { potPlots_[detId_pot].clock_Digi3_le->Fill( HPTDC_BIN_WIDTH_NS * digi.getLeadingEdge() ); potPlots_[detId_pot].clock_Digi3_te->Fill( HPTDC_BIN_WIDTH_NS * digi.getTrailingEdge() ); } } } } } //------------------------------ // Plane Plots //------------------------------ // Using CTPPSDiamondDigi std::unordered_map<unsigned int, unsigned int> channelsPerPlane; for ( const auto& digis : *diamondDigis ) { const CTPPSDiamondDetId detId( digis.detId() ); CTPPSDiamondDetId detId_plane( digis.detId() ); for ( const auto& digi : digis ) { detId_plane.setChannel( 0 ); if ( detId.channel() == CHANNEL_OF_VFAT_CLOCK ) continue; if ( planePlots_.find( detId_plane ) == planePlots_.end() ) continue; if ( digi.getLeadingEdge() != 0 ) { planePlots_[detId_plane].digiProfileCumulativePerPlane->Fill( detId.channel() ); if ( channelsPerPlane.find(detId_plane) != channelsPerPlane.end() ) channelsPerPlane[detId_plane]++; else channelsPerPlane[detId_plane] = 0; } } } for ( const auto& plt : channelsPerPlane ) { planePlots_[plt.first].hit_multiplicity->Fill( plt.second ); } // Using CTPPSDiamondRecHit for ( const auto& rechits : *diamondRecHits ) { CTPPSDiamondDetId detId_plane( rechits.detId() ); detId_plane.setChannel( 0 ); for ( const auto& rechit : rechits ) { if ( excludeMultipleHits_ && rechit.getMultipleHits() > 0 ) continue; if ( rechit.getToT() == 0 ) continue; if ( planePlots_.find( detId_plane ) != planePlots_.end() ) { if ( centralOOT_ != -999 && rechit.getOOTIndex() == centralOOT_ ) { TH1F *hitHistoTmp = planePlots_[detId_plane].hitProfile->getTH1F(); int startBin = hitHistoTmp->FindBin( rechit.getX() - 0.5*rechit.getXWidth() ); int numOfBins = rechit.getXWidth()*INV_DISPLAY_RESOLUTION_FOR_HITS_MM; for ( int i=0; i<numOfBins; ++i) { hitHistoTmp->Fill( hitHistoTmp->GetBinCenter(startBin+i) ); } } } } } // Tomography of diamonds using strips for ( const auto& rechits : *diamondRecHits ) { CTPPSDiamondDetId detId_plane( rechits.detId() ); detId_plane.setChannel( 0 ); for ( const auto& rechit : rechits ) { if ( excludeMultipleHits_ && rechit.getMultipleHits() > 0 ) continue; if ( rechit.getToT() == 0 ) continue; if ( !stripTracks.isValid() ) continue; if (planePlots_.find(detId_plane) == planePlots_.end()) continue; for ( const auto& ds : *stripTracks ) { const CTPPSDetId stripId(ds.detId()); for ( const auto& striplt : ds ) { if (! striplt.isValid()) continue; if ( stripId.arm() != detId_plane.arm() ) continue; if ( striplt.getTx() > maximumStripAngleForTomography_ || striplt.getTy() > maximumStripAngleForTomography_) continue; if ( striplt.getTx() < minimumStripAngleForTomography_ || striplt.getTy() < minimumStripAngleForTomography_) continue; if ( stripId.rp() == CTPPS_FAR_RP_ID ) { planePlots_[detId_plane].stripTomography_far->Fill( striplt.getX0() + 25*(rechit.getOOTIndex() - ( ( centralOOT_ != -999 ) ? centralOOT_ : 0 ) +1), striplt.getY0() ); } } } } } //------------------------------ // Channel Plots //------------------------------ //Check Event Number for ( const auto& vfat_status : *diamondVFATStatus ) { const CTPPSDiamondDetId detId( vfat_status.detId() ); for ( const auto& status : vfat_status ) { if ( !status.isOK() ) continue; if ( channelPlots_.find(detId) != channelPlots_.end() ) { for ( const auto& optorx : *fedInfo ) { if ( ( detId.arm() == 1 && optorx.getFEDId() == CTPPS_FED_ID_56 ) || ( detId.arm() == 0 && optorx.getFEDId() == CTPPS_FED_ID_45 ) ) { channelPlots_[detId].ECCheckPerChannel->Fill((int)((optorx.getLV1()& 0xFF)-((unsigned int) status.getEC() & 0xFF)) & 0xFF); } } } } } // digi profile cumulative for ( const auto& digis : *diamondDigis ) { const CTPPSDiamondDetId detId( digis.detId() ); for ( const auto& digi : digis ) { if ( detId.channel() == CHANNEL_OF_VFAT_CLOCK ) continue; if ( channelPlots_.find( detId ) != channelPlots_.end() ) { // HPTDC Errors const HPTDCErrorFlags hptdcErrors = digi.getHPTDCErrorFlags(); for ( unsigned short hptdcErrorIndex = 1; hptdcErrorIndex < 16; ++hptdcErrorIndex ) if ( hptdcErrors.getErrorId( hptdcErrorIndex-1 ) ) channelPlots_[detId].HPTDCErrorFlags->Fill( hptdcErrorIndex ); if ( digi.getMultipleHit() ) channelPlots_[detId].HPTDCErrorFlags->Fill( 16 ); // Check dropped trailing edges if ( digi.getLeadingEdge() == 0 && digi.getTrailingEdge() == 0 ) channelPlots_[detId].leadingWithoutTrailing->Fill( 1 ); else if ( digi.getLeadingEdge() != 0 && digi.getTrailingEdge() == 0 ) channelPlots_[detId].leadingWithoutTrailing->Fill( 2 ); else if ( digi.getLeadingEdge() == 0 && digi.getTrailingEdge() != 0 ) channelPlots_[detId].leadingWithoutTrailing->Fill( 3 ); else if ( digi.getLeadingEdge() != 0 && digi.getTrailingEdge() != 0 ) channelPlots_[detId].leadingWithoutTrailing->Fill( 4 ); } } } // Using CTPPSDiamondRecHit for ( const auto& rechits : *diamondRecHits ) { CTPPSDiamondDetId detId( rechits.detId() ); for ( const auto& rechit : rechits ) { if ( excludeMultipleHits_ && rechit.getMultipleHits() > 0 ) continue; if ( channelPlots_.find( detId ) != channelPlots_.end() ) { if ( rechit.getToT() != 0 ) { channelPlots_[detId].leadingEdgeCumulative_both->Fill( rechit.getT() + 25*rechit.getOOTIndex() ); channelPlots_[detId].TimeOverThresholdCumulativePerChannel->Fill( rechit.getToT() ); } else if ( rechit.getT() != 0 ) channelPlots_[detId].leadingEdgeCumulative_le->Fill( rechit.getT() + 25*rechit.getOOTIndex() ); channelPlots_[detId].LeadingTrailingCorrelationPerChannel->Fill( rechit.getT() + 25*rechit.getOOTIndex(), rechit.getT() + 25*rechit.getOOTIndex() + rechit.getToT() ); ++(channelPlots_[detId].hitsCounterPerLumisection); } if ( rechit.getToT() != 0 ) { switch ( rechit.getOOTIndex() - ( ( centralOOT_ != -999 ) ? centralOOT_ : 0 ) ) { case -1: { channelPlots_[detId].activity_per_bx_minus1->Fill( event.bunchCrossing() ); } break; case 0: { channelPlots_[detId].activity_per_bx->Fill( event.bunchCrossing() ); } break; case 1: { channelPlots_[detId].activity_per_bx_plus1->Fill( event.bunchCrossing() ); } break; } } } } // Tomography of diamonds using strips for ( const auto& rechits : *diamondRecHits ) { const CTPPSDiamondDetId detId( rechits.detId() ); for ( const auto& rechit : rechits ) { if ( excludeMultipleHits_ && rechit.getMultipleHits() > 0 ) continue; if ( stripTracks.isValid() ) { if (channelPlots_.find(detId) == channelPlots_.end()) continue; for ( const auto& ds : *stripTracks ) { for ( const auto& striplt : ds ) { CTPPSDetId stripId(ds.detId()); if ( !striplt.isValid() ) continue; if ( stripId.arm() != detId.arm() ) continue; if ( striplt.getTx() > maximumStripAngleForTomography_ || striplt.getTy() > maximumStripAngleForTomography_) continue; if ( striplt.getTx() < minimumStripAngleForTomography_ || striplt.getTy() < minimumStripAngleForTomography_) continue; if ( stripId.rp() == CTPPS_FAR_RP_ID ) { channelPlots_[detId].stripTomography_far->Fill( striplt.getX0() + 25*(rechit.getOOTIndex() - ( ( centralOOT_ != -999 ) ? centralOOT_ : 0 ) +1), striplt.getY0() ); } } } } } } } //---------------------------------------------------------------------------------------------------- void CTPPSDiamondDQMSource::endLuminosityBlock( const edm::LuminosityBlock&, const edm::EventSetup& ) {} //---------------------------------------------------------------------------------------------------- void CTPPSDiamondDQMSource::endRun( const edm::Run&, const edm::EventSetup& ) {} //---------------------------------------------------------------------------------------------------- DEFINE_FWK_MODULE( CTPPSDiamondDQMSource );
48.462687
216
0.6354
pasmuss
fe8edecc5f2a475ebb57cce4766c38d2ed538db6
15,911
cpp
C++
sycl/source/detail/allowlist.cpp
mgehre-xlx/sycl
2086745509ef4bc298d7bbec402a123dae68f25e
[ "Apache-2.0" ]
61
2019-04-12T18:49:57.000Z
2022-03-19T22:23:16.000Z
sycl/source/detail/allowlist.cpp
mgehre-xlx/sycl
2086745509ef4bc298d7bbec402a123dae68f25e
[ "Apache-2.0" ]
127
2019-04-09T00:55:50.000Z
2022-03-21T15:35:41.000Z
sycl/source/detail/allowlist.cpp
mgehre-xlx/sycl
2086745509ef4bc298d7bbec402a123dae68f25e
[ "Apache-2.0" ]
10
2019-04-02T18:25:40.000Z
2022-02-15T07:11:37.000Z
//==-------------- allowlist.cpp - SYCL_DEVICE_ALLOWLIST -------------------==// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include <detail/allowlist.hpp> #include <detail/config.hpp> #include <detail/device_impl.hpp> #include <detail/platform_info.hpp> #include <algorithm> #include <regex> __SYCL_INLINE_NAMESPACE(cl) { namespace sycl { namespace detail { constexpr char BackendNameKeyName[] = "BackendName"; constexpr char DeviceTypeKeyName[] = "DeviceType"; constexpr char DeviceVendorIdKeyName[] = "DeviceVendorId"; constexpr char DriverVersionKeyName[] = "DriverVersion"; constexpr char PlatformVersionKeyName[] = "PlatformVersion"; constexpr char DeviceNameKeyName[] = "DeviceName"; constexpr char PlatformNameKeyName[] = "PlatformName"; constexpr std::array<const char *, 7> SupportedAllowListKeyNames{ BackendNameKeyName, DeviceTypeKeyName, DeviceVendorIdKeyName, DriverVersionKeyName, PlatformVersionKeyName, DeviceNameKeyName, PlatformNameKeyName}; // Parsing and validating SYCL_DEVICE_ALLOWLIST variable value. // // The value has the following form: // DeviceDesc1|DeviceDesc2|<...>|DeviceDescN // DeviceDescN is the set of descriptions for the device which should be // allowed. The sets of device descriptions are separated by '|' symbol. The set // of descriptions has the following structure: // DeviceDescN = Key1:Value1,Key2:Value2,...,KeyN:ValueN // Device descriptions are separated by ',' symbol. // Key and value of a device description are separated by ":" symbol. // KeyN is the key of a device description, it could be one of the following // from SupportedAllowListKeyNames vector above. // DeviceName and PlatformName device descriptions are deprecated and will be // removed in one of the future releases. // ValueN is the value of a device description, it could be regex and some fixed // string. // Function should return parsed SYCL_DEVICE_ALLOWLIST variable value as // AllowListParsedT type (vector of maps), e.g.: // {{Key1: Value1, Key2: Value2}, ..., {Key1: Value1, ..., KeyN: ValueN}} AllowListParsedT parseAllowList(const std::string &AllowListRaw) { if (AllowListRaw.empty()) return {}; AllowListParsedT AllowListParsed; AllowListParsed.emplace_back(); constexpr std::array<const char *, 3> SupportedKeyNamesHaveFixedValue{ BackendNameKeyName, DeviceTypeKeyName, DeviceVendorIdKeyName}; constexpr std::array<const char *, 4> SupportedKeyNamesRequireRegexValue{ DriverVersionKeyName, PlatformVersionKeyName, DeviceNameKeyName, PlatformNameKeyName}; size_t KeyStart = 0, KeyEnd = 0, ValueStart = 0, ValueEnd = 0, DeviceDescIndex = 0; const char DelimiterBtwKeyAndValue = ':'; const char DelimiterBtwItemsInDeviceDesc = ','; const char DelimiterBtwDeviceDescs = '|'; if (AllowListRaw.find(DelimiterBtwKeyAndValue, KeyStart) == std::string::npos) throw sycl::runtime_error("SYCL_DEVICE_ALLOWLIST has incorrect format. For " "details, please refer to " "https://github.com/intel/llvm/blob/sycl/sycl/" "doc/EnvironmentVariables.md", PI_INVALID_VALUE); while ((KeyEnd = AllowListRaw.find(DelimiterBtwKeyAndValue, KeyStart)) != std::string::npos) { if ((ValueStart = AllowListRaw.find_first_not_of( DelimiterBtwKeyAndValue, KeyEnd)) == std::string::npos) break; const std::string &Key = AllowListRaw.substr(KeyStart, KeyEnd - KeyStart); // check that provided key is supported if (std::find(SupportedAllowListKeyNames.begin(), SupportedAllowListKeyNames.end(), Key) == SupportedAllowListKeyNames.end()) { throw sycl::runtime_error( "Unrecognized key in SYCL_DEVICE_ALLOWLIST. For details, please " "refer to " "https://github.com/intel/llvm/blob/sycl/sycl/doc/" "EnvironmentVariables.md", PI_INVALID_VALUE); } bool ShouldAllocateNewDeviceDescMap = false; std::string Value; auto &DeviceDescMap = AllowListParsed[DeviceDescIndex]; // check if Key is not already defined in DeviceDescMap, e.g., caused by the // following invalid syntax: Key1:Value1,Key2:Value2,Key1:Value3 if (DeviceDescMap.find(Key) == DeviceDescMap.end()) { // calculate and validate value which has fixed format if (std::find(SupportedKeyNamesHaveFixedValue.begin(), SupportedKeyNamesHaveFixedValue.end(), Key) != SupportedKeyNamesHaveFixedValue.end()) { ValueEnd = AllowListRaw.find(DelimiterBtwItemsInDeviceDesc, ValueStart); // check if it is the last Key:Value pair in the device description, and // correct end position of that value if (size_t ValueEndCand = AllowListRaw.find(DelimiterBtwDeviceDescs, ValueStart); (ValueEndCand != std::string::npos) && (ValueEndCand < ValueEnd)) { ValueEnd = ValueEndCand; ShouldAllocateNewDeviceDescMap = true; } if (ValueEnd == std::string::npos) ValueEnd = AllowListRaw.length(); Value = AllowListRaw.substr(ValueStart, ValueEnd - ValueStart); // post-processing checks for some values auto ValidateEnumValues = [&](std::string CheckingKeyName, auto SourceOfSupportedValues) { if (Key == CheckingKeyName) { bool ValueIsValid = false; for (const auto &Item : SourceOfSupportedValues) if (Value == Item.first) { ValueIsValid = true; break; } if (!ValueIsValid) throw sycl::runtime_error( "Value " + Value + " for key " + Key + " is not valid in " "SYCL_DEVICE_ALLOWLIST. For details, please refer to " "https://github.com/intel/llvm/blob/sycl/sycl/doc/" "EnvironmentVariables.md", PI_INVALID_VALUE); } }; // check that values of keys, which should have some fixed format, are // valid. E.g., for BackendName key, the allowed values are only ones // described in SyclBeMap ValidateEnumValues(BackendNameKeyName, getSyclBeMap()); ValidateEnumValues(DeviceTypeKeyName, getSyclDeviceTypeMap()); if (Key == DeviceVendorIdKeyName) { // DeviceVendorId should have hex format if (!std::regex_match(Value, std::regex("0[xX][0-9a-fA-F]+"))) { throw sycl::runtime_error( "Value " + Value + " for key " + Key + " is not valid in " "SYCL_DEVICE_ALLOWLIST. It should have the hex format. For " "details, please refer to " "https://github.com/intel/llvm/blob/sycl/sycl/doc/" "EnvironmentVariables.md", PI_INVALID_VALUE); } } } // calculate and validate value which has regex format else if (std::find(SupportedKeyNamesRequireRegexValue.begin(), SupportedKeyNamesRequireRegexValue.end(), Key) != SupportedKeyNamesRequireRegexValue.end()) { const std::string Prefix("{{"); // TODO: can be changed to string_view::starts_with after switching // DPC++ RT to C++20 if (Prefix != AllowListRaw.substr(ValueStart, Prefix.length())) { throw sycl::runtime_error("Key " + Key + " of SYCL_DEVICE_ALLOWLIST should have " "value which starts with " + Prefix, PI_INVALID_VALUE); } // cut off prefix from the value ValueStart += Prefix.length(); ValueEnd = ValueStart; const std::string Postfix("}}"); for (; ValueEnd < AllowListRaw.length() - Postfix.length() + 1; ++ValueEnd) { if (Postfix == AllowListRaw.substr(ValueEnd, Postfix.length())) break; // if it is the last iteration and next 2 symbols are not a postfix, // throw exception if (ValueEnd == AllowListRaw.length() - Postfix.length()) throw sycl::runtime_error( "Key " + Key + " of SYCL_DEVICE_ALLOWLIST should have " "value which ends with " + Postfix, PI_INVALID_VALUE); } size_t NextExpectedDelimiterPos = ValueEnd + Postfix.length(); // if it is not the end of the string, check that symbol next to a // postfix is a delimiter (, or ;) if ((AllowListRaw.length() != NextExpectedDelimiterPos) && (AllowListRaw[NextExpectedDelimiterPos] != DelimiterBtwItemsInDeviceDesc) && (AllowListRaw[NextExpectedDelimiterPos] != DelimiterBtwDeviceDescs)) throw sycl::runtime_error( "Unexpected symbol on position " + std::to_string(NextExpectedDelimiterPos) + ": " + AllowListRaw[NextExpectedDelimiterPos] + ". Should be either " + DelimiterBtwItemsInDeviceDesc + " or " + DelimiterBtwDeviceDescs, PI_INVALID_VALUE); if (AllowListRaw[NextExpectedDelimiterPos] == DelimiterBtwDeviceDescs) ShouldAllocateNewDeviceDescMap = true; Value = AllowListRaw.substr(ValueStart, ValueEnd - ValueStart); ValueEnd += Postfix.length(); } else assert(false && "Key should be either in SupportedKeyNamesHaveFixedValue " "or SupportedKeyNamesRequireRegexValue"); // add key and value to the map DeviceDescMap.emplace(Key, Value); } else throw sycl::runtime_error("Re-definition of key " + Key + " is not allowed in " "SYCL_DEVICE_ALLOWLIST", PI_INVALID_VALUE); KeyStart = ValueEnd; if (KeyStart != std::string::npos) ++KeyStart; if (ShouldAllocateNewDeviceDescMap) { ++DeviceDescIndex; AllowListParsed.emplace_back(); } } return AllowListParsed; } // Checking if we can allow device with device description DeviceDesc bool deviceIsAllowed(const DeviceDescT &DeviceDesc, const AllowListParsedT &AllowListParsed) { assert(std::all_of(SupportedAllowListKeyNames.begin(), SupportedAllowListKeyNames.end(), [&DeviceDesc](const auto &SupportedKeyName) { return DeviceDesc.find(SupportedKeyName) != DeviceDesc.end(); }) && "DeviceDesc map should have all supported keys for " "SYCL_DEVICE_ALLOWLIST."); auto EqualityComp = [&](const std::string &KeyName, const DeviceDescT &AllowListDeviceDesc) { // change to map::contains after switching DPC++ RT to C++20 if (AllowListDeviceDesc.find(KeyName) != AllowListDeviceDesc.end()) if (AllowListDeviceDesc.at(KeyName) != DeviceDesc.at(KeyName)) return false; return true; }; auto RegexComp = [&](const std::string &KeyName, const DeviceDescT &AllowListDeviceDesc) { if (AllowListDeviceDesc.find(KeyName) != AllowListDeviceDesc.end()) if (!std::regex_match(DeviceDesc.at(KeyName), std::regex(AllowListDeviceDesc.at(KeyName)))) return false; return true; }; bool ShouldDeviceBeAllowed = false; for (const auto &AllowListDeviceDesc : AllowListParsed) { if (!EqualityComp(BackendNameKeyName, AllowListDeviceDesc)) continue; if (!EqualityComp(DeviceTypeKeyName, AllowListDeviceDesc)) continue; if (!EqualityComp(DeviceVendorIdKeyName, AllowListDeviceDesc)) continue; if (!RegexComp(DriverVersionKeyName, AllowListDeviceDesc)) continue; if (!RegexComp(PlatformVersionKeyName, AllowListDeviceDesc)) continue; if (!RegexComp(DeviceNameKeyName, AllowListDeviceDesc)) continue; if (!RegexComp(PlatformNameKeyName, AllowListDeviceDesc)) continue; // no any continue was called on this iteration, so all parameters matched // successfully, so allow this device to use ShouldDeviceBeAllowed = true; break; } return ShouldDeviceBeAllowed; } void applyAllowList(std::vector<RT::PiDevice> &PiDevices, RT::PiPlatform PiPlatform, const plugin &Plugin) { AllowListParsedT AllowListParsed = parseAllowList(SYCLConfig<SYCL_DEVICE_ALLOWLIST>::get()); if (AllowListParsed.empty()) return; DeviceDescT DeviceDesc; // get BackendName value and put it to DeviceDesc sycl::backend Backend = Plugin.getBackend(); for (const auto &SyclBe : getSyclBeMap()) { if (SyclBe.second == Backend) { DeviceDesc.emplace(BackendNameKeyName, SyclBe.first); break; } } // get PlatformVersion value and put it to DeviceDesc DeviceDesc.emplace( PlatformVersionKeyName, sycl::detail::get_platform_info<std::string, info::platform::version>::get(PiPlatform, Plugin)); // get PlatformName value and put it to DeviceDesc DeviceDesc.emplace( PlatformNameKeyName, sycl::detail::get_platform_info<std::string, info::platform::name>::get( PiPlatform, Plugin)); int InsertIDx = 0; for (RT::PiDevice Device : PiDevices) { // get DeviceType value and put it to DeviceDesc RT::PiDeviceType PiDevType; Plugin.call<PiApiKind::piDeviceGetInfo>(Device, PI_DEVICE_INFO_TYPE, sizeof(RT::PiDeviceType), &PiDevType, nullptr); sycl::info::device_type DeviceType = pi::cast<info::device_type>(PiDevType); for (const auto &SyclDeviceType : getSyclDeviceTypeMap()) { if (SyclDeviceType.second == DeviceType) { const auto &DeviceTypeValue = SyclDeviceType.first; DeviceDesc[DeviceTypeKeyName] = DeviceTypeValue; break; } } // get DeviceVendorId value and put it to DeviceDesc uint32_t DeviceVendorIdUInt = sycl::detail::get_device_info<uint32_t, info::device::vendor_id>::get( Device, Plugin); std::stringstream DeviceVendorIdHexStringStream; DeviceVendorIdHexStringStream << "0x" << std::hex << DeviceVendorIdUInt; const auto &DeviceVendorIdValue = DeviceVendorIdHexStringStream.str(); DeviceDesc[DeviceVendorIdKeyName] = DeviceVendorIdValue; // get DriverVersion value and put it to DeviceDesc const auto &DriverVersionValue = sycl::detail::get_device_info< std::string, info::device::driver_version>::get(Device, Plugin); DeviceDesc[DriverVersionKeyName] = DriverVersionValue; // get DeviceName value and put it to DeviceDesc const auto &DeviceNameValue = sycl::detail::get_device_info<std::string, info::device::name>::get( Device, Plugin); DeviceDesc[DeviceNameKeyName] = DeviceNameValue; // check if we can allow device with such device description DeviceDesc if (deviceIsAllowed(DeviceDesc, AllowListParsed)) { PiDevices[InsertIDx++] = Device; } } PiDevices.resize(InsertIDx); } } // namespace detail } // namespace sycl } // __SYCL_INLINE_NAMESPACE(cl)
42.429333
80
0.629816
mgehre-xlx
fe903cdf57086ffd0a4001148614668be10d34b1
452
cpp
C++
0201-0300/0202-Happy Number/0202-Happy Number.cpp
jiadaizhao/LeetCode
4ddea0a532fe7c5d053ffbd6870174ec99fc2d60
[ "MIT" ]
49
2018-05-05T02:53:10.000Z
2022-03-30T12:08:09.000Z
0201-0300/0202-Happy Number/0202-Happy Number.cpp
jolly-fellow/LeetCode
ab20b3ec137ed05fad1edda1c30db04ab355486f
[ "MIT" ]
11
2017-12-15T22:31:44.000Z
2020-10-02T12:42:49.000Z
0201-0300/0202-Happy Number/0202-Happy Number.cpp
jolly-fellow/LeetCode
ab20b3ec137ed05fad1edda1c30db04ab355486f
[ "MIT" ]
28
2017-12-05T10:56:51.000Z
2022-01-26T18:18:27.000Z
class Solution { public: bool isHappy(int n) { unordered_set<int> visited{n}; while (n != 1) { int temp = n; n = 0; while (temp) { int i = temp % 10; n += i * i; temp /= 10; } if (visited.count(n)) { return false; } visited.insert(n); } return true; } };
20.545455
38
0.338496
jiadaizhao
fe910396c9c334cdf140d27bed8721480471526d
722
cpp
C++
testrun/src/testrun.cpp
yappy/ymj
e2e2e48e30f1858e9f6708f681db6070848a2b81
[ "MIT" ]
null
null
null
testrun/src/testrun.cpp
yappy/ymj
e2e2e48e30f1858e9f6708f681db6070848a2b81
[ "MIT" ]
null
null
null
testrun/src/testrun.cpp
yappy/ymj
e2e2e48e30f1858e9f6708f681db6070848a2b81
[ "MIT" ]
null
null
null
#include <ymj.h> #include <array> #include <cstring> #include <cstdio> using Hand = std::array<uint8_t, YMJ_HAND_SIZE>; void callback(const ymj_state *state) { std::printf("(%2d)", state->head); for (int i = 0; i < 4; i++) { std::printf("(%c %d)", state->mentu[i].is_kotu ? 'k' : 's', state->mentu[i].start); } std::putchar('\n'); } void create_state(ymj_state *state, const Hand &hand) { std::memset(state, 0, sizeof(*state)); for (const auto &hai : hand) { state->hai_count[hai]++; } } int main() { ymj_state state; Hand hand {1,1,1,2,2,2,3,3,3,4,4,4,5,5}; create_state(&state, hand); int ret = ymj_for_each_hora(&state, callback); std::printf("ymj_for_each_hora(): %d\n", ret); return 0; }
19
53
0.623269
yappy
fe9175102dd96f3dd986b0bdeef6414eb14da956
12,637
cc
C++
chromeos/services/libassistant/settings_controller_unittest.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
chromeos/services/libassistant/settings_controller_unittest.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
chromeos/services/libassistant/settings_controller_unittest.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromeos/services/libassistant/settings_controller.h" #include "base/test/mock_callback.h" #include "base/test/task_environment.h" #include "chromeos/assistant/internal/test_support/fake_assistant_manager.h" #include "chromeos/assistant/internal/test_support/fake_assistant_manager_internal.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/icu/source/common/unicode/locid.h" namespace chromeos { namespace libassistant { namespace { #define EXPECT_NO_CALLS(args...) EXPECT_CALL(args).Times(0); #define IGNORE_CALLS(args...) EXPECT_CALL(args).Times(testing::AnyNumber()); // The auth tokens are pairs of <user, token> using AuthTokens = std::vector<std::pair<std::string, std::string>>; std::vector<mojom::AuthenticationTokenPtr> ToVector( mojom::AuthenticationTokenPtr token) { std::vector<mojom::AuthenticationTokenPtr> result; result.push_back(std::move(token)); return result; } class AssistantManagerInternalMock : public assistant::FakeAssistantManagerInternal { public: AssistantManagerInternalMock() = default; AssistantManagerInternalMock(const AssistantManagerInternalMock&) = delete; AssistantManagerInternalMock& operator=(const AssistantManagerInternalMock&) = delete; ~AssistantManagerInternalMock() override = default; // assistant::FakeAssistantManagerInternal implementation: MOCK_METHOD(void, SetLocaleOverride, (const std::string& locale)); MOCK_METHOD(void, SetOptions, (const assistant_client::InternalOptions& options, assistant_client::SuccessCallbackInternal on_done)); MOCK_METHOD(void, SendUpdateSettingsUiRequest, (const std::string& s3_request_update_settings_ui_request_proto, const std::string& user_id, assistant_client::VoicelessResponseCallback on_done)); }; class AssistantManagerMock : public assistant::FakeAssistantManager { public: AssistantManagerMock() = default; AssistantManagerMock(const AssistantManagerMock&) = delete; AssistantManagerMock& operator=(const AssistantManagerMock&) = delete; ~AssistantManagerMock() override = default; // assistant::FakeAssistantManager implementation: MOCK_METHOD(void, EnableListening, (bool value)); MOCK_METHOD(void, SetAuthTokens, (const AuthTokens&)); }; } // namespace class AssistantSettingsControllerTest : public testing::Test { public: AssistantSettingsControllerTest() : assistant_manager_(std::make_unique<AssistantManagerMock>()), assistant_manager_internal_( std::make_unique< testing::StrictMock<AssistantManagerInternalMock>>()) {} AssistantSettingsControllerTest(const AssistantSettingsControllerTest&) = delete; AssistantSettingsControllerTest& operator=( const AssistantSettingsControllerTest&) = delete; ~AssistantSettingsControllerTest() override = default; SettingsController& controller() { return controller_; } void CreateLibassistant() { controller().OnAssistantManagerCreated(assistant_manager_.get(), assistant_manager_internal_.get()); } void StartLibassistant() { controller().OnAssistantManagerStarted(assistant_manager_.get(), assistant_manager_internal_.get()); } void DestroyLibassistant() { controller().OnDestroyingAssistantManager( assistant_manager_.get(), assistant_manager_internal_.get()); assistant_manager_ = nullptr; assistant_manager_internal_ = nullptr; assistant_manager_ = std::make_unique<AssistantManagerMock>(); assistant_manager_internal_ = std::make_unique<testing::StrictMock<AssistantManagerInternalMock>>(); } void CreateAndStartLibassistant() { CreateLibassistant(); StartLibassistant(); } AssistantManagerInternalMock& assistant_manager_internal_mock() { return *assistant_manager_internal_; } AssistantManagerMock& assistant_manager_mock() { return *assistant_manager_; } private: base::test::SingleThreadTaskEnvironment environment_; SettingsController controller_; std::unique_ptr<AssistantManagerMock> assistant_manager_; std::unique_ptr<AssistantManagerInternalMock> assistant_manager_internal_; }; TEST_F(AssistantSettingsControllerTest, ShouldNotCrashIfLibassistantIsNotCreated) { controller().SetAuthenticationTokens({}); controller().SetHotwordEnabled(true); controller().SetListeningEnabled(true); controller().SetLocale("locale"); controller().SetSpokenFeedbackEnabled(true); } TEST_F(AssistantSettingsControllerTest, ShouldNotCrashAfterDestroyingLibassistant) { CreateAndStartLibassistant(); DestroyLibassistant(); controller().SetAuthenticationTokens({}); controller().SetHotwordEnabled(true); controller().SetListeningEnabled(true); controller().SetLocale("locale"); controller().SetSpokenFeedbackEnabled(true); } TEST_F(AssistantSettingsControllerTest, ShouldResetAllValuesWhenLibassistantIsDestroyed) { controller().SetAuthenticationTokens({}); controller().SetHotwordEnabled(true); controller().SetLocale("locale"); controller().SetSpokenFeedbackEnabled(true); DestroyLibassistant(); // After destroying Libassistant, the settings should be cleared. // We test this by ensuring they are not applied when Libassistant starts. EXPECT_NO_CALLS(assistant_manager_internal_mock(), SetLocaleOverride); EXPECT_NO_CALLS(assistant_manager_internal_mock(), SetOptions); EXPECT_NO_CALLS(assistant_manager_internal_mock(), SendUpdateSettingsUiRequest); EXPECT_NO_CALLS(assistant_manager_mock(), SetAuthTokens); CreateAndStartLibassistant(); } TEST_F(AssistantSettingsControllerTest, ShouldSetLocale) { CreateLibassistant(); EXPECT_CALL(assistant_manager_internal_mock(), SetLocaleOverride("locale")); controller().SetLocale("locale"); } TEST_F(AssistantSettingsControllerTest, ShouldUseDefaultLocaleIfSettingToEmptyString) { const std::string default_locale = icu::Locale::getDefault().getName(); CreateLibassistant(); EXPECT_CALL(assistant_manager_internal_mock(), SetLocaleOverride(default_locale)); controller().SetLocale(""); } TEST_F(AssistantSettingsControllerTest, ShouldNotSetInternalOptionsWhenLocaleIsNotSet) { CreateLibassistant(); EXPECT_NO_CALLS(assistant_manager_internal_mock(), SetOptions); controller().SetSpokenFeedbackEnabled(true); } TEST_F(AssistantSettingsControllerTest, ShouldNotSetInternalOptionsWhenSpokenFeedbackEnabledIsNotSet) { IGNORE_CALLS(assistant_manager_internal_mock(), SetLocaleOverride); CreateLibassistant(); EXPECT_NO_CALLS(assistant_manager_internal_mock(), SetOptions); controller().SetLocale("locale"); } TEST_F(AssistantSettingsControllerTest, ShouldSetInternalOptionsWhenLocaleIsUpdated) { IGNORE_CALLS(assistant_manager_internal_mock(), SetLocaleOverride); controller().SetSpokenFeedbackEnabled(true); CreateLibassistant(); EXPECT_CALL(assistant_manager_internal_mock(), SetOptions); controller().SetLocale("locale"); } TEST_F(AssistantSettingsControllerTest, ShouldSetInternalOptionsWhenSpokenFeedbackEnabledIsUpdated) { IGNORE_CALLS(assistant_manager_internal_mock(), SetLocaleOverride); controller().SetLocale("locale"); CreateLibassistant(); EXPECT_CALL(assistant_manager_internal_mock(), SetOptions); controller().SetSpokenFeedbackEnabled(true); } TEST_F(AssistantSettingsControllerTest, ShouldSetInternalOptionsAndLocaleWhenLibassistantIsCreated) { controller().SetLocale("locale"); controller().SetSpokenFeedbackEnabled(true); EXPECT_CALL(assistant_manager_internal_mock(), SetLocaleOverride); EXPECT_CALL(assistant_manager_internal_mock(), SetOptions); CreateLibassistant(); } TEST_F(AssistantSettingsControllerTest, ShouldNotSetDeviceOptionsWhenLocaleIsNotSet) { IGNORE_CALLS(assistant_manager_internal_mock(), SetLocaleOverride); CreateAndStartLibassistant(); EXPECT_NO_CALLS(assistant_manager_internal_mock(), SendUpdateSettingsUiRequest); controller().SetHotwordEnabled(true); } TEST_F(AssistantSettingsControllerTest, ShouldNotSetDeviceOptionsWhenHotwordEnabledIsNotSet) { IGNORE_CALLS(assistant_manager_internal_mock(), SetLocaleOverride); CreateAndStartLibassistant(); EXPECT_NO_CALLS(assistant_manager_internal_mock(), SendUpdateSettingsUiRequest); controller().SetLocale("locale"); } TEST_F(AssistantSettingsControllerTest, ShouldSetDeviceOptionsWhenLocaleIsUpdated) { IGNORE_CALLS(assistant_manager_internal_mock(), SetLocaleOverride); CreateAndStartLibassistant(); controller().SetHotwordEnabled(true); EXPECT_CALL(assistant_manager_internal_mock(), SendUpdateSettingsUiRequest); controller().SetLocale("locale"); } TEST_F(AssistantSettingsControllerTest, ShouldSetDeviceOptionsWhenHotwordEnabledIsUpdated) { IGNORE_CALLS(assistant_manager_internal_mock(), SetLocaleOverride); CreateAndStartLibassistant(); controller().SetLocale("locale"); EXPECT_CALL(assistant_manager_internal_mock(), SendUpdateSettingsUiRequest); controller().SetHotwordEnabled(true); } TEST_F(AssistantSettingsControllerTest, ShouldSetDeviceOptionsWhenLibassistantIsStarted) { IGNORE_CALLS(assistant_manager_internal_mock(), SetLocaleOverride); CreateLibassistant(); controller().SetLocale("locale"); controller().SetHotwordEnabled(true); EXPECT_CALL(assistant_manager_internal_mock(), SendUpdateSettingsUiRequest); StartLibassistant(); } TEST_F(AssistantSettingsControllerTest, ShouldSetAuthenticationTokens) { const AuthTokens expected = {{"user", "token"}}; CreateLibassistant(); EXPECT_CALL(assistant_manager_mock(), SetAuthTokens(expected)); controller().SetAuthenticationTokens( ToVector(mojom::AuthenticationToken::New("user", "token"))); } TEST_F(AssistantSettingsControllerTest, ShouldSetAuthenticationTokensWhenLibassistantIsCreated) { const AuthTokens expected = {{"user", "token"}}; controller().SetAuthenticationTokens( ToVector(mojom::AuthenticationToken::New("user", "token"))); EXPECT_CALL(assistant_manager_mock(), SetAuthTokens(expected)); CreateLibassistant(); } TEST_F(AssistantSettingsControllerTest, ShouldSupportEmptyAuthenticationTokenList) { CreateLibassistant(); const AuthTokens expected = {}; EXPECT_CALL(assistant_manager_mock(), SetAuthTokens(expected)); controller().SetAuthenticationTokens({}); } TEST_F(AssistantSettingsControllerTest, ShouldSetListeningEnabled) { CreateLibassistant(); EXPECT_CALL(assistant_manager_mock(), EnableListening(true)); controller().SetListeningEnabled(true); } TEST_F(AssistantSettingsControllerTest, ShouldSetListeningEnabledWhenLibassistantIsCreated) { controller().SetListeningEnabled(false); EXPECT_CALL(assistant_manager_mock(), EnableListening(false)); CreateLibassistant(); } TEST_F(AssistantSettingsControllerTest, GetSettingsShouldCallCallbackEvenIfLibassistantIsNotStarted) { base::MockCallback<SettingsController::GetSettingsCallback> callback; EXPECT_CALL(callback, Run(std::string{})); controller().GetSettings("selector", callback.Get()); } TEST_F(AssistantSettingsControllerTest, GetSettingsShouldCallCallbackIfLibassistantIsStopped) { CreateAndStartLibassistant(); base::MockCallback<SettingsController::GetSettingsCallback> callback; controller().GetSettings("selector", callback.Get()); EXPECT_CALL(callback, Run(std::string{})); DestroyLibassistant(); } TEST_F(AssistantSettingsControllerTest, UpdateSettingsShouldCallCallbackEvenIfLibassistantIsNotStarted) { base::MockCallback<SettingsController::UpdateSettingsCallback> callback; EXPECT_CALL(callback, Run(std::string{})); controller().UpdateSettings("selector", callback.Get()); } TEST_F(AssistantSettingsControllerTest, UpdateSettingsShouldCallCallbackIfLibassistantIsStopped) { IGNORE_CALLS(assistant_manager_internal_mock(), SendUpdateSettingsUiRequest); CreateAndStartLibassistant(); base::MockCallback<SettingsController::UpdateSettingsCallback> callback; controller().UpdateSettings("selector", callback.Get()); EXPECT_CALL(callback, Run(std::string{})); DestroyLibassistant(); } } // namespace libassistant } // namespace chromeos
32.823377
85
0.77827
iridium-browser
fe917698a57854e71cf55aee8f459745e48df9bb
18,727
hpp
C++
modules/clients/cpp/main/include/gridgain/impl/gridclientcomputeprojection.hpp
cybernetics/gridgain
39f3819c9769b04caca62b263581c0458f21c4d6
[ "Apache-2.0" ]
1
2019-04-22T08:48:55.000Z
2019-04-22T08:48:55.000Z
modules/clients/cpp/main/include/gridgain/impl/gridclientcomputeprojection.hpp
cybernetics/gridgain
39f3819c9769b04caca62b263581c0458f21c4d6
[ "Apache-2.0" ]
null
null
null
modules/clients/cpp/main/include/gridgain/impl/gridclientcomputeprojection.hpp
cybernetics/gridgain
39f3819c9769b04caca62b263581c0458f21c4d6
[ "Apache-2.0" ]
null
null
null
/* Copyright (C) GridGain Systems. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* _________ _____ __________________ _____ * __ ____/___________(_)______ /__ ____/______ ____(_)_______ * _ / __ __ ___/__ / _ __ / _ / __ _ __ `/__ / __ __ \ * / /_/ / _ / _ / / /_/ / / /_/ / / /_/ / _ / _ / / / * \____/ /_/ /_/ \_,__/ \____/ \__,_/ /_/ /_/ /_/ */ #ifndef GRID_CLIENT_COMPUTE_PROJECTION_IMP_HPP #define GRID_CLIENT_COMPUTE_PROJECTION_IMP_HPP #include "gridgain/gridclientcompute.hpp" #include "gridgain/impl/gridclientprojection.hpp" #include "gridgain/impl/utils/gridthreadpool.hpp" class GridTopologyRequestCommand; /** * Implementation of GridClientCompute. */ class GridClientComputeProjectionImpl : public GridClientCompute, public GridClientProjectionImpl { public: /** * Constructor. * * @param data Shared data. * @param prjLsnr Projection listener. * @param pFilter Node filter (may be omitted). */ GridClientComputeProjectionImpl(TGridClientSharedDataPtr data, GridClientProjectionListener& prjLsnr, TGridClientNodePredicatePtr pFilter, TGridClientLoadBalancerPtr balancer, TGridThreadPoolPtr& threadPool); /** * Creates a projection that will communicate only with specified remote node. * <p> * If current projection is dynamic projection, then this method will check is passed node is in topology. * If any filters were specified in current topology, this method will check if passed node is accepted by * the filter. If current projection was restricted to any subset of nodes, this method will check if * passed node is in that subset. If any of the checks fails an exception will be thrown. * * @param node Single node to which this projection will be restricted. * @return Resulting static projection that is bound to a given node. * @throw GridClientException If resulting projection is empty. */ virtual TGridClientComputePtr projection(const GridClientNode& node); /** * Creates a projection that will communicate only with specified remote nodes. For any particular call * a node to communicate will be selected with passed balancer.. * <p> * If current projection is dynamic projection, then this method will check is passed nodes are in topology. * If any filters were specified in current topology, this method will check if passed nodes are accepted by * the filter. If current projection was restricted to any subset of nodes, this method will check if * passed nodes are in that subset (i.e. calculate the intersection of two collections). * If any of the checks fails an exception will be thrown. * * @param nodes Collection of nodes to which this projection will be restricted. * @param balancer Balancer that will select nodes in resulting projection. * @return Resulting static projection that is bound to a given nodes. * @throw GridClientException If resulting projection is empty. */ virtual TGridClientComputePtr projection(const TGridClientNodeList& nodes); /** * Creates a projection that will communicate only with nodes that are accepted by the passed filter. * <p> * If current projection is dynamic projection, then filter will be applied to the most relevant * topology snapshot every time a node to communicate is selected. If current projection is a static projection, * then resulting projection will only be restricted to nodes that were in parent projection and were * accepted by the passed filter. If any of the checks fails an exception will be thrown. * * @param filter Filter that will select nodes for projection. * @return Resulting projection (static or dynamic, depending in parent projection type). * @throws GridClientException If resulting projection is empty. */ virtual TGridClientComputePtr projection(TGridClientNodePredicatePtr filter); /** * Creates a projection that will communicate only with nodes that are accepted by the passed filter. * <p> * If current projection is dynamic projection, then filter will be applied to the most relevant * topology snapshot every time a node to communicate is selected. If current projection is a static projection, * then resulting projection will only be restricted to nodes that were in parent projection and were * accepted by the passed filter. If any of the checks fails an exception will be thrown. * * @param filter Filter that will select nodes for projection. * @return Resulting projection (static or dynamic, depending in parent projection type). * @throws GridClientException If resulting projection is empty. */ virtual TGridClientComputePtr projection(std::function<bool (const GridClientNode&)> & filter); /** * Creates a projection that will communicate only with nodes that are accepted by the passed filter. The * balancer passed will override default balancer specified in configuration. * <p> * If current projection is dynamic projection, then filter will be applied to the most relevant * topology snapshot every time a node to communicate is selected. If current projection is a static projection, * then resulting projection will only be restricted to nodes that were in parent projection and were * accepted by the passed filter. If any of the checks fails an exception will be thrown. * * @param filter Filter that will select nodes for projection. * @param balancer Balancer that will select balanced node in resulting projection. * @return Resulting projection (static or dynamic, depending in parent projection type). * @throws GridClientException If resulting projection is empty. */ virtual TGridClientComputePtr projection(TGridClientNodePredicatePtr filter, TGridClientLoadBalancerPtr balancer); /** * Creates a projection that will communicate only with nodes that are accepted by the passed filter. The * balancer passed will override default balancer specified in configuration. * <p> * If current projection is dynamic projection, then filter will be applied to the most relevant * topology snapshot every time a node to communicate is selected. If current projection is a static projection, * then resulting projection will only be restricted to nodes that were in parent projection and were * accepted by the passed filter. If any of the checks fails an exception will be thrown. * * @param filter Filter that will select nodes for projection. * @param balancer Balancer that will select balanced node in resulting projection. * @return Resulting projection (static or dynamic, depending in parent projection type). * @throws GridClientException If resulting projection is empty. */ virtual TGridClientComputePtr projection(std::function<bool (const GridClientNode&)> & filter, TGridClientLoadBalancerPtr balancer); /** * Creates a projection that will communicate only with specified remote nodes. For any particular call * a node to communicate will be selected with passed balancer.. * <p> * If current projection is dynamic projection, then this method will check is passed nodes are in topology. * If any filters were specified in current topology, this method will check if passed nodes are accepted by * the filter. If current projection was restricted to any subset of nodes, this method will check if * passed nodes are in that subset (i.e. calculate the intersection of two collections). * If any of the checks fails an exception will be thrown. * * @param nodes Collection of nodes to which this projection will be restricted. * @param balancer Balancer that will select nodes in resulting projection. * @return Resulting static projection that is bound to a given nodes. * @throws GridClientException If resulting projection is empty. */ virtual TGridClientComputePtr projection(const TGridClientNodeList& nodes, TGridClientLoadBalancerPtr balancer); /** * Gets balancer used by projection. * * @return Instance of {@link GridClientLoadBalancer}. */ virtual TGridClientLoadBalancerPtr balancer() const; /** * Executes task. * * @param taskName Task name or task class name. * @param taskArg Optional task argument. * @return Task execution result. * @throw GridClientException In case of error. * @throw GridServerUnreachableException If none of the servers can be reached. * @throw GridClientClosedException If client was closed manually. */ virtual GridClientVariant execute(const std::string& taskName, const GridClientVariant& taskArg); /** * Asynchronously executes task. * * @param taskName Task name or task class name. * @param taskArg Optional task argument. * @return Future. */ virtual TGridClientFutureVariant executeAsync(const std::string& taskName, const GridClientVariant& taskArg); /** * Executes task using cache affinity key for routing. This way the task will start executing * exactly on the node where this affinity key is cached. * * @param taskName Task name or task class name. * @param cacheName Name of the cache on which affinity should be calculated. * @param affKey Affinity key. * @param taskArg Optional task argument. * @return Task execution result. * @throw GridClientException In case of error. * @throw GridServerUnreachableException If none of the servers can be reached. * @throw GridClientClosedException If client was closed manually. */ virtual GridClientVariant affinityExecute(const std::string& taskName, const std::string& cacheName, const GridClientVariant& affKey, const GridClientVariant& taskArg); /** * Asynchronously executes task using cache affinity key for routing. This way * the task will start executing exactly on the node where this affinity key is cached. * * @param taskName Task name or task class name. * @param cacheName Name of the cache on which affinity should be calculated. * @param affKey Affinity key. * @param taskArg Optional task argument. * @return Future. */ virtual TGridClientFutureVariant affinityExecuteAsync(const std::string& taskName, const std::string& cacheName, const GridClientVariant& affKey, const GridClientVariant& taskArg); /** * Gets node with given id from most recently refreshed topology. * * @param id Node ID. * @return Node for given ID or <tt>null</tt> if node with given id was not found. */ virtual TGridClientNodePtr node(const GridClientUuid& id) const; /** * Gets nodes that pass the filter. If this compute instance is a projection, then only * nodes that pass projection criteria will be passed to the filter. * * @param filter Node filter. * @return Collection of nodes that satisfy provided filter. */ virtual TGridClientNodeList nodes(TGridClientNodePredicatePtr filter) const; /** * Gets nodes that pass the filter. If this compute instance is a projection, then only * nodes that pass projection criteria will be passed to the filter. * * @param filter Node filter. * @return Collection of nodes that satisfy provided filter. */ virtual TGridClientNodeList nodes(std::function<bool (const GridClientNode&)> & filter) const; /** * Gets all nodes in the projection. * * @param filter Node filter. * @return Collection of nodes that satisfy provided filter. */ virtual TGridClientNodeList nodes() const; /** * Gets nodes that passes the filter. If this compute instance is a projection, then only * nodes that passes projection criteria will be passed to the filter. * * @param filter Node filter. * @return Collection of nodes that satisfy provided filter. */ virtual TGridClientNodeList nodes(const std::vector<GridClientUuid>& ids) const; /** * Gets node by its ID. * * @param id Node ID. * @param includeAttrs Whether to include node attributes. * @param includeMetrics Whether to include node metrics. * @return Node descriptor or <tt>null</tt> if node doesn't exist. * @throw GridClientException In case of error. * @throw GridServerUnreachableException If none of the servers can be reached. * @throw GridClientClosedException If client was closed manually. */ virtual TGridClientNodePtr refreshNode(const GridClientUuid& id, bool includeAttrs, bool includeMetrics); /** * Asynchronously gets node by its ID. * * @param id Node ID. * @param includeAttrs Whether to include node attributes. * @param includeMetrics Whether to include node metrics. * @return Future. */ virtual TGridClientNodeFuturePtr refreshNodeAsync(const GridClientUuid& id, bool includeAttrs, bool includeMetrics); /** * Gets node by IP address. * * @param ip IP address. * @param includeAttrs Whether to include node attributes. * @param includeMetrics Whether to include node metrics. * @return Node descriptor or <tt>null</tt> if node doesn't exist. * @throw GridClientException In case of error. * @throw GridServerUnreachableException If none of the servers can be reached. * @throw GridClientClosedException If client was closed manually. */ virtual TGridClientNodePtr refreshNode(const std::string& ip, bool includeAttrs, bool includeMetrics); /** * Asynchronously gets node by IP address. * * @param ip IP address. * @param includeAttrs Whether to include node attributes. * @param includeMetrics Whether to include node metrics. * @return Future. */ virtual TGridClientNodeFuturePtr refreshNodeAsync(const std::string& ip, bool includeAttrs, bool includeMetrics); /** * Gets current topology. * * @param includeAttrs Whether to include node attributes. * @param includeMetrics Whether to include node metrics. * @return Node descriptors. * @throw GridClientException In case of error. * @throw GridServerUnreachableException If none of the servers can be reached. * @throw GridClientClosedException If client was closed manually. */ virtual TGridClientNodeList refreshTopology(bool includeAttrs, bool includeMetrics); /** * Asynchronously gets current topology. * * @param includeAttrs Whether to include node attributes. * @param includeMetrics Whether to include node metrics. * @return Future. */ virtual TGridClientNodeFutureList refreshTopologyAsync(bool includeAttrs, bool includeMetrics); /** * Gets contents of default log file (<tt>GRIDGAIN_HOME/work/log/gridgain.log</tt>). * * @param lineFrom Index of line from which log is get, inclusive (starting from 0). * @param lineTo Index of line to which log is get, inclusive (starting from 0). * @return Log contents. * @throw GridClientException In case of error. * @throw GridServerUnreachableException If none of the servers can be reached. * @throw GridClientClosedException If client was closed manually. */ virtual std::vector<std::string> log(int lineFrom, int lineTo); /** * Asynchronously gets contents of default log file * (<tt>GRIDGAIN_HOME/work/log/gridgain.log</tt>). * * @param lineFrom Index of line from which log is get, inclusive (starting from 0). * @param lineTo Index of line to which log is get, inclusive (starting from 0). * @return Future. */ virtual TGridFutureStringList logAsync(int lineFrom, int lineTo); /** * Gets contents of custom log file. * * @param path Log file path. Can be absolute or relative to GRIDGAIN_HOME. * @param lineFrom Index of line from which log is get, inclusive (starting from 0). * @param lineTo Index of line to which log is get, inclusive (starting from 0). * @return Log contents. * @throw GridClientException In case of error. * @throw GridServerUnreachableException If none of the servers can be reached. * @throw GridClientClosedException If client was closed manually. */ virtual std::vector<std::string> log(const std::string& path, int lineFrom, int lineTo); /** * Asynchronously gets contents of custom log file. * * @param path Log file path. Can be absolute or relative to GRIDGAIN_HOME. * @param lineFrom Index of line from which log is get, inclusive (starting from 0). * @param lineTo Index of line to which log is get, inclusive (starting from 0). * @return Future. */ virtual TGridFutureStringList logAsync(const std::string& path, int lineFrom, int lineTo); /** * Invalidates this data instance. This is done by the client to indicate * that is has been stopped. After this call, all interface methods * will throw GridClientClosedException. */ void invalidate(); protected: /** * Creates subprojection based on node filter and balancer. * * @param filter Node filter. * @param balancer Load balancer. */ TGridClientComputePtr makeProjection(TGridClientNodePredicatePtr filter, TGridClientLoadBalancerPtr balancer); private: /** * Internal refresh topology command. * * @param cmd Topology command to execute. * @return Refreshed nodes. */ TGridClientNodeList refreshTopology(GridTopologyRequestCommand& cmd); /** List of current subprojections. */ std::vector< std::shared_ptr<GridClientCompute> > subProjections; /** Invalidated flag. */ TGridAtomicBool invalidated; /** Thread pool for running async operations. */ TGridThreadPoolPtr threadPool; }; #endif
46.125616
116
0.709617
cybernetics
fe92b689908185c622228255afdfb901b3a25730
1,066
hpp
C++
src/cpp/common/eigenIncluder.hpp
umma-zannat/ginan
a4d1a3bb8696267f23d26e8c6a2f6080b87bb494
[ "Apache-2.0" ]
1
2022-01-12T15:14:55.000Z
2022-01-12T15:14:55.000Z
src/cpp/common/eigenIncluder.hpp
umma-zannat/ginan
a4d1a3bb8696267f23d26e8c6a2f6080b87bb494
[ "Apache-2.0" ]
null
null
null
src/cpp/common/eigenIncluder.hpp
umma-zannat/ginan
a4d1a3bb8696267f23d26e8c6a2f6080b87bb494
[ "Apache-2.0" ]
1
2022-01-12T15:15:12.000Z
2022-01-12T15:15:12.000Z
#ifndef __EIGEN_INCLUDER_HPP__ #define __EIGEN_INCLUDER_HPP__ #include <eigen3/Eigen/Core> #include <eigen3/Eigen/Dense> #include <eigen3/Eigen/Sparse> #include <eigen3/Eigen/SparseCholesky> #include <eigen3/Eigen/SparseQR> #include <eigen3/Eigen/LU> #include <eigen3/Eigen/Cholesky> #include <eigen3/Eigen/Geometry> #include <eigen3/Eigen/OrderingMethods> using Eigen::SimplicialLLT; using Eigen::SimplicialLDLT; using Eigen::COLAMDOrdering; using Eigen::LDLT; using Eigen::LLT; using Eigen::PartialPivLU; using Eigen::Matrix; using Eigen::MatrixXd; using Eigen::Matrix2d; using Eigen::Matrix3d; using Eigen::VectorXd; using Vector6d = Eigen::Vector<double, 6>; using Eigen::Vector3d; using Eigen::Vector2d; using Eigen::MatrixXi; using Eigen::SparseMatrix; using Eigen::SparseVector; using Eigen::SparseQR; using Eigen::Map; using Eigen::Quaterniond; using Eigen::Triplet; using Eigen::ArrayXd; using Eigen::placeholders::all; typedef Eigen::Array<bool,Eigen::Dynamic,1> ArrayXb; template <typename Type, int Size> using Vector = Matrix<Type, Size, 1>; #endif
24.790698
52
0.783302
umma-zannat
fe9342a2cd4e25288f083537775247a1c249697e
1,109
cpp
C++
Eunoia-Engine/Src/Eunoia/Utils/SettingsLoader.cpp
EunoiaGames/Eunoia-Dev
94edea774d1de05dc6a0c24ffdd3bb91b91a3346
[ "Apache-2.0" ]
null
null
null
Eunoia-Engine/Src/Eunoia/Utils/SettingsLoader.cpp
EunoiaGames/Eunoia-Dev
94edea774d1de05dc6a0c24ffdd3bb91b91a3346
[ "Apache-2.0" ]
null
null
null
Eunoia-Engine/Src/Eunoia/Utils/SettingsLoader.cpp
EunoiaGames/Eunoia-Dev
94edea774d1de05dc6a0c24ffdd3bb91b91a3346
[ "Apache-2.0" ]
null
null
null
#include "SettingsLoader.h" #include "../Core/Engine.h" namespace Eunoia { void SettingsLoader::WriteSettingsToFile(const String& path, const EunoiaSettings& settings) { FILE* file = fopen(path.C_Str(), "wb"); if (!file) return; fwrite(&settings, sizeof(EunoiaSettings), 1, file); fclose(file); } void SettingsLoader::LoadSettingsFromFile(const String& path, b32 applySettings) { FILE* file = fopen(path.C_Str(), "rb"); if (!file) return; EunoiaSettings settings; fread(&settings, sizeof(EunoiaSettings), 1, file); fclose(file); if (applySettings) ApplySettings(settings); } void SettingsLoader::ApplySettings(const EunoiaSettings& settings) { Renderer2D* r2D = Engine::GetRenderer()->GetRenderer2D(); Renderer3D* r3D = Engine::GetRenderer()->GetRenderer3D(); r2D->SetProjection(settings.settings2D.projection); r2D->SetSpritePosOrigin(settings.settings2D.origin); r3D->SetAmbient(settings.settings3D.ambient); r3D->SetBloomThreshold(settings.settings3D.bloomThreshold); r3D->SetBloomBlurIterationCount(settings.settings3D.bloomBlurIterCount); } }
25.790698
93
0.737601
EunoiaGames
fe961e6ebc88ebe1d6d69b8458ec40f4381952a7
2,059
cpp
C++
logdevice/test/utils/NodesConfigurationFileUpdater.cpp
YangKian/LogDevice
e5c2168c11e9de867a1bcf519f95016e1c879b5c
[ "BSD-3-Clause" ]
1,831
2018-09-12T15:41:52.000Z
2022-01-05T02:38:03.000Z
logdevice/test/utils/NodesConfigurationFileUpdater.cpp
YangKian/LogDevice
e5c2168c11e9de867a1bcf519f95016e1c879b5c
[ "BSD-3-Clause" ]
183
2018-09-12T16:14:59.000Z
2021-12-07T15:49:43.000Z
logdevice/test/utils/NodesConfigurationFileUpdater.cpp
YangKian/LogDevice
e5c2168c11e9de867a1bcf519f95016e1c879b5c
[ "BSD-3-Clause" ]
228
2018-09-12T15:41:51.000Z
2022-01-05T08:12:09.000Z
/** * Copyright (c) 2017-present, Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include "logdevice/test/utils/NodesConfigurationFileUpdater.h" #include "logdevice/common/configuration/nodes/NodesConfigurationCodec.h" namespace facebook { namespace logdevice { namespace IntegrationTestUtils { namespace { constexpr std::chrono::seconds kPollingInterval{1}; } NodesConfigurationFileUpdater::NodesConfigurationFileUpdater( std::shared_ptr<UpdateableNodesConfiguration> updateable_nodes_config, std::unique_ptr<configuration::nodes::NodesConfigurationStore> store) : updateable_nodes_config_(std::move(updateable_nodes_config)), store_(std::move(store)) {} NodesConfigurationFileUpdater::~NodesConfigurationFileUpdater() { shutdown_signaled = true; polling_thread_.join(); } void NodesConfigurationFileUpdater::start() { polling_thread_ = std::thread(&NodesConfigurationFileUpdater::pollingLoop, this); } void NodesConfigurationFileUpdater::pollingLoop() { while (!shutdown_signaled.load()) { folly::Optional<membership::MembershipVersion::Type> current_version; if (auto current_nc = updateable_nodes_config_->get(); current_nc != nullptr) { current_version = current_nc->getVersion(); } std::string serialized_nc; auto status = store_->getConfigSync(&serialized_nc, current_version); if (status == Status::OK) { auto new_nc = configuration::nodes::NodesConfigurationCodec::deserialize( std::move(serialized_nc)); ld_check(new_nc); updateable_nodes_config_->update(std::move(new_nc)); } else if (status == Status::UPTODATE) { // Do nothing } else { ld_error("Failed reading the nodes configuration from the store: %s", error_name(status)); } std::this_thread::sleep_for(kPollingInterval); } } }}} // namespace facebook::logdevice::IntegrationTestUtils
32.68254
79
0.733851
YangKian
fe96cf6d4cfc691fbdca17d41b7814c1d9ab7076
7,410
cpp
C++
mainwindow.cpp
probonopd/qsshfs
47ff48c0a177a36540b06a1af5b9cd3571f3b292
[ "BSD-3-Clause" ]
10
2017-08-23T20:39:49.000Z
2022-03-05T22:44:25.000Z
mainwindow.cpp
probonopd/qsshfs
47ff48c0a177a36540b06a1af5b9cd3571f3b292
[ "BSD-3-Clause" ]
1
2017-10-19T13:01:03.000Z
2019-09-25T10:25:01.000Z
mainwindow.cpp
probonopd/qsshfs
47ff48c0a177a36540b06a1af5b9cd3571f3b292
[ "BSD-3-Clause" ]
4
2019-01-31T09:08:55.000Z
2020-09-14T11:53:41.000Z
#include "editremotedialog.h" #include "mainwindow.h" #include "ui_mainwindow.h" #include <QDesktopServices> #include <QSettings> #include <dialogmaster.h> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), model(new MountModel(this)), sortModel(new QSortFilterProxyModel(this)), trayIco(new QSystemTrayIcon(windowIcon(), this)) { ui->setupUi(this); ui->treeView->setParent(this); centralWidget()->deleteLater(); setCentralWidget(ui->treeView); sortModel->setSourceModel(model); ui->treeView->setModel(sortModel); auto s = new QAction(this); s->setSeparator(true); ui->treeView->addActions({ ui->actionMount, ui->actionOpen_Folder, s, ui->actionEdit_Host, ui->actionRemove_Host }); trayIco->setToolTip(QApplication::applicationDisplayName()); auto menu = new QMenu(this); menu->addAction(QIcon::fromTheme(QStringLiteral("window-new")), tr("Show main window"), this, &MainWindow::show); menu->addMenu(model->createMountMenu(menu)); menu->addAction(ui->action_Reload_Mounts); menu->addSeparator(); auto runAction = menu->addAction(QIcon::fromTheme(QStringLiteral("games-config-options")), tr("Keep running"), qApp, [](bool triggered){ QApplication::setQuitOnLastWindowClosed(!triggered); }); runAction->setCheckable(true); auto startAction = menu->addAction(QIcon::fromTheme(QStringLiteral("system-run")), tr("Autostart"), this, &MainWindow::updateAutostart); startAction->setCheckable(true); menu->addAction(QIcon::fromTheme(QStringLiteral("gtk-quit")), tr("Quit"), qApp, &QApplication::quit); trayIco->setContextMenu(menu); trayIco->setVisible(true); QSettings settings; settings.beginGroup(QStringLiteral("gui")); restoreGeometry(settings.value(QStringLiteral("geom")).toByteArray()); restoreState(settings.value(QStringLiteral("state")).toByteArray()); ui->treeView->header()->restoreState(settings.value(QStringLiteral("header")).toByteArray()); runAction->setChecked(settings.value(QStringLiteral("background"), true).toBool()); startAction->setChecked(isAutostart()); QApplication::setQuitOnLastWindowClosed(!runAction->isChecked()); settings.endGroup(); connect(ui->actionExit, &QAction::triggered, qApp, &QApplication::quit); connect(ui->actionAbout_Qt, &QAction::triggered, qApp, &QApplication::aboutQt); connect(ui->action_Reload_Mounts, &QAction::triggered, model, &MountModel::reload); connect(model, &MountModel::modelReset, this, [this](){ reloadCurrent(QModelIndex()); }); connect(ui->treeView->selectionModel(), &QItemSelectionModel::currentChanged, this, &MainWindow::reloadCurrent); connect(model->controller(), &MountController::mountError, this, &MainWindow::mountError); connect(qApp, &QApplication::commitDataRequest, this, &MainWindow::commitShutdown); connect(qApp, &QApplication::saveStateRequest, this, &MainWindow::commitShutdown); } MainWindow::~MainWindow() { QSettings settings; settings.beginGroup(QStringLiteral("gui")); settings.setValue(QStringLiteral("geom"), saveGeometry()); settings.setValue(QStringLiteral("state"), saveState()); settings.setValue(QStringLiteral("header"), ui->treeView->header()->saveState()); settings.setValue(QStringLiteral("background"), !QApplication::quitOnLastWindowClosed()); settings.endGroup(); delete ui; } void MainWindow::mountError(const QString &name, const QString &errorLog, int exitCode) { reloadCurrent(ui->treeView->currentIndex()); auto conf = DialogMaster::createCritical(tr("Failed to mount/unmount %1").arg(name)); conf.parent = isVisible() ? this : nullptr; conf.title = conf.text; if(exitCode == -1){ conf.text = tr("The mount or unmount operation failed! Check the details for the " "generated error log"); } else { conf.text = tr("The mount or unmount operation failed with exit code %1! Check the details for the " "generated error log") .arg(exitCode); } conf.details = errorLog; DialogMaster::messageBox(conf); } void MainWindow::reloadCurrent(const QModelIndex &uiIndex) { auto index = sortModel->mapToSource(uiIndex); ui->actionMount->setEnabled(index.isValid()); if(index.isValid()) { auto mounted = model->isMounted(index); ui->actionEdit_Host->setEnabled(!mounted); ui->actionRemove_Host->setEnabled(!mounted); ui->actionMount->setChecked(mounted); } else { ui->actionEdit_Host->setEnabled(false); ui->actionRemove_Host->setEnabled(false); ui->actionMount->setChecked(false); } } void MainWindow::updateAutostart(bool checked) { auto resPath = QStringLiteral("%1/autostart/%2.sh") .arg(QStandardPaths::writableLocation(QStandardPaths::ConfigLocation)) .arg(QCoreApplication::applicationName()); if(checked) { QFile file(resPath); if(file.open(QIODevice::WriteOnly | QIODevice::Text)) { file.write(QStringLiteral("#!/bin/sh\n%1 --hidden") .arg(QCoreApplication::applicationName()) .toUtf8()); file.close(); file.setPermissions(file.permissions() | QFileDevice::ExeUser); } } else QFile::remove(resPath); } void MainWindow::commitShutdown(QSessionManager &sm) { auto args = sm.restartCommand(); if(!isVisible()) { if(!args.contains(QStringLiteral("--hidden"))) args.append(QStringLiteral("--hidden")); } else args.removeAll(QStringLiteral("--hidden")); sm.setRestartCommand(args); sm.setRestartHint(QSessionManager::RestartIfRunning); } void MainWindow::on_actionAdd_Host_triggered() { auto info = EditRemoteDialog::editInfo({}, this); if(info.isValid()) model->addMountInfo(info); } void MainWindow::on_actionEdit_Host_triggered() { auto index = sortModel->mapToSource(ui->treeView->currentIndex()); if(index.isValid()) { auto info = EditRemoteDialog::editInfo(model->mountInfo(index), this); if(info.isValid()) model->updateMountInfo(index, info); } } void MainWindow::on_actionRemove_Host_triggered() { auto index = sortModel->mapToSource(ui->treeView->currentIndex()); if(index.isValid()) { if(DialogMaster::question(this, tr("Do you really want to remove the selected mount?"))) model->removeMountInfo(index); } } void MainWindow::on_actionMount_triggered(bool checked) { auto index = sortModel->mapToSource(ui->treeView->currentIndex()); if(index.isValid()) { if(checked) model->mount(index); else model->unmount(index); } } void MainWindow::on_actionOpen_Folder_triggered() { auto index = sortModel->mapToSource(ui->treeView->currentIndex()); if(index.isValid()) { auto info = model->mountInfo(index); QDesktopServices::openUrl(QUrl::fromLocalFile(info.localPath)); } } void MainWindow::on_actionAbout_triggered() { DialogMaster::about(this, tr("A gui wrapper around sshfs"), true, QUrl(QStringLiteral("https://github.com/Skycoder42"))); } bool MainWindow::isAutostart() { auto resPath = QStringLiteral("%1/autostart/%2.sh") .arg(QStandardPaths::writableLocation(QStandardPaths::ConfigLocation)) .arg(QCoreApplication::applicationName()); return QFile::exists(resPath); } void MainWindow::on_treeView_activated(const QModelIndex &index) { auto srcIndex = sortModel->mapToSource(index); if(srcIndex.isValid()) { if(!model->isMounted(srcIndex)) model->mount(srcIndex); else { auto info = model->mountInfo(srcIndex); QDesktopServices::openUrl(QUrl::fromLocalFile(info.localPath)); } } }
31.134454
111
0.725371
probonopd
fe9794c47477d9a0dbff1ffa746b87ca3e5abcef
3,491
cpp
C++
src/ros_comm/rosbag_storage/src/stream.cpp
jungleni/ros_code_reading
499e98c0b0d309da78060b19b55c420c22110d65
[ "Apache-2.0" ]
742
2017-07-05T02:49:36.000Z
2022-03-30T12:55:43.000Z
src/ros_comm/rosbag_storage/src/stream.cpp
jungleni/ros_code_reading
499e98c0b0d309da78060b19b55c420c22110d65
[ "Apache-2.0" ]
73
2017-07-06T12:50:51.000Z
2022-03-07T08:07:07.000Z
src/ros_comm/rosbag_storage/src/stream.cpp
jungleni/ros_code_reading
499e98c0b0d309da78060b19b55c420c22110d65
[ "Apache-2.0" ]
425
2017-07-04T22:03:29.000Z
2022-03-29T06:59:06.000Z
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. ********************************************************************/ #include "rosbag/stream.h" #include "rosbag/chunked_file.h" //#include <ros/ros.h> using boost::shared_ptr; namespace rosbag { // StreamFactory StreamFactory::StreamFactory(ChunkedFile* file) : uncompressed_stream_(new UncompressedStream(file)), bz2_stream_ (new BZ2Stream(file)), lz4_stream_ (new LZ4Stream(file)) { } shared_ptr<Stream> StreamFactory::getStream(CompressionType type) const { switch (type) { case compression::Uncompressed: return uncompressed_stream_; case compression::BZ2: return bz2_stream_; case compression::LZ4: return lz4_stream_; default: return shared_ptr<Stream>(); } } // Stream Stream::Stream(ChunkedFile* file) : file_(file) { } Stream::~Stream() { } void Stream::startWrite() { } void Stream::stopWrite() { } void Stream::startRead() { } void Stream::stopRead() { } FILE* Stream::getFilePointer() { return file_->file_; } uint64_t Stream::getCompressedIn() { return file_->compressed_in_; } void Stream::setCompressedIn(uint64_t nbytes) { file_->compressed_in_ = nbytes; } void Stream::advanceOffset(uint64_t nbytes) { file_->offset_ += nbytes; } char* Stream::getUnused() { return file_->unused_; } int Stream::getUnusedLength() { return file_->nUnused_; } void Stream::setUnused(char* unused) { file_->unused_ = unused; } void Stream::setUnusedLength(int nUnused) { file_->nUnused_ = nUnused; } void Stream::clearUnused() { file_->clearUnused(); } } // namespace rosbag
41.559524
85
0.656545
jungleni
fe97cb6a65b0d93851d6c915f540518794e624c0
3,295
cpp
C++
C Programming/Leaderboard/main.cpp
NanoCode012/ITStep
21807b6bcd564c9ed490e4af70954bff9a5d698d
[ "MIT" ]
5
2019-10-23T13:22:18.000Z
2022-02-04T18:36:00.000Z
C Programming/Leaderboard/main.cpp
NanoCode012/ITStep
21807b6bcd564c9ed490e4af70954bff9a5d698d
[ "MIT" ]
null
null
null
C Programming/Leaderboard/main.cpp
NanoCode012/ITStep
21807b6bcd564c9ed490e4af70954bff9a5d698d
[ "MIT" ]
3
2018-05-23T04:16:52.000Z
2021-12-19T14:56:00.000Z
#include <iostream> #include "array.h" using namespace std; int SetName(char list[][10], char names[]){ int lastIndex = Count(list); int lastChar = Count(names); for (int i = 0; i < lastChar; i++){ list[lastIndex][i] = names[i]; } return 0; } int ShowName(char names[][10], int index){ int count = Count(names[index]); for (int i = 0; i < count; i++){ cout << names[index][i]; } return 0; } int SetValue(int scores[][2], int score){ int count = Count(scores); scores[count][0] = score; scores[count][1] = count; return 0; } int Swap(int scores[][2], int pos0, int pos1){ int temp = scores[pos0][0]; scores[pos0][0] = scores[pos1][0]; scores[pos1][0] = temp; temp = scores[pos0][1]; scores[pos0][1] = scores[pos1][1]; scores[pos1][1] = temp; return 0; } int BubbleSort(int scores[][2]){ int count = Count(scores); bool hasSwapped; for (int i = 0; i < count; i++){ hasSwapped = false; for (int j = 1; j < count; j++){ if (scores[j - 1][0] < scores[j][0]) { Swap(scores, j - 1, j); hasSwapped = true; } } if (!hasSwapped) break; } return 0; } int ShowLeaderboard(int scores[][2], char names[][10], int numOfParticipants){ int tempScore = 0; int rank = 0; int tempRank = rank; for (int i = 0; i < numOfParticipants; i++) { rank++; if (tempScore == scores[i][0]) { cout << tempRank << "\t"; ShowName(names, scores[i][1]); }else { cout << rank << "\t" ; ShowName(names, scores[i][1]); tempRank = rank; } tempScore = scores[i][0]; cout << "\t" << scores[i][0] << endl; } return 0; } int main(){ int numOfPeople = 5; int scores[numOfPeople][2]; char names[numOfPeople][10]; names[0][0] = '0';//when init a char[], it sets char[0][1] to 'p', bypassing my check //Input int tempScore = 0; char tempName[10]; cout << "Please input amountOfPeople: "; cin >> numOfPeople; for (int i = 0; i < numOfPeople; i++){ cout << "Please input score between 1->100: "; cin >> tempScore; if (0 < tempScore && tempScore <= 100){ cout << "Please set name: "; cin >> tempName; SetValue(scores, tempScore); SetName(names, tempName); cout << "Name added!" << endl; }else { cout << "Score not within range. Please try again." << endl; i--; } } /* //Set scores (score cannot be 0) SetValue(scores, 87); SetValue(scores, 98); SetValue(scores, 50); SetValue(scores, 98); SetValue(scores, 75); //Set names SetName(names, "happy"); // cout << Count(names) << endl; SetName(names, "box"); // cout << Count(names) << endl; SetName(names, "card"); // cout << Count(names) << endl; // ShowName(names, 0); // ShowName(names, 2); // ShowName(names, 0); SetName(names, "eli"); SetName(names, "pox"); */ BubbleSort(scores); cout << "Rank\tName\tScore" << endl; ShowLeaderboard(scores, names, numOfPeople); return 0; }
24.774436
89
0.517147
NanoCode012
fe9881602fb5466a928517ace5c24e466538ffec
818
hpp
C++
include/matrix.hpp
Alan-Kuan/MatrixSpaces
38d490635dbd1c6bc6fbba75bc0128e9820456fc
[ "MIT" ]
null
null
null
include/matrix.hpp
Alan-Kuan/MatrixSpaces
38d490635dbd1c6bc6fbba75bc0128e9820456fc
[ "MIT" ]
null
null
null
include/matrix.hpp
Alan-Kuan/MatrixSpaces
38d490635dbd1c6bc6fbba75bc0128e9820456fc
[ "MIT" ]
null
null
null
#ifndef MATRIX_HPP #define MATRIX_HPP #include "fraction.hpp" #include <cassert> #include <iostream> using namespace std; struct Matrix{ int row_size, col_size; Fraction **rows; // Constructors Matrix(int n); Matrix(int m, int n); // Copy Constructor Matrix(const Matrix &M); // Destructor ~Matrix(); // Operater Overloading Fraction*& operator [] (const int &i); Fraction* operator [] (const int &i) const; // access-only Matrix operator - () const; // unary minus Matrix operator + (const Matrix &M); Matrix operator - (const Matrix &M); Matrix operator * (const Matrix &M); Matrix operator * (const int &x); // scalar multiplication Matrix& operator = (const Matrix &M); // Tranpose Matrix transpose(void) const; }; ostream& operator << (ostream &os, const Matrix &M); #endif
17.041667
60
0.680929
Alan-Kuan
fe9897c0a96bd599ca447f2182733f46fcd4987e
2,034
cpp
C++
src/Thor/Particle.cpp
Shinao/JustAGame
d2683b9a1b33f236e5f87b1cb26444be50a9851a
[ "MIT" ]
null
null
null
src/Thor/Particle.cpp
Shinao/JustAGame
d2683b9a1b33f236e5f87b1cb26444be50a9851a
[ "MIT" ]
null
null
null
src/Thor/Particle.cpp
Shinao/JustAGame
d2683b9a1b33f236e5f87b1cb26444be50a9851a
[ "MIT" ]
null
null
null
///////////////////////////////////////////////////////////////////////////////// // // Thor C++ Library // Copyright (c) 2011-2014 Jan Haller // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // ///////////////////////////////////////////////////////////////////////////////// #include <Thor/Particles/Particle.hpp> namespace thor { Particle::Particle(sf::Time totalLifetime) : position() , velocity() , rotation() , rotationSpeed() , scale(1.f, 1.f) , color(255, 255, 255) , textureIndex(0) , totalLifetime(totalLifetime) , passedLifetime(sf::Time::Zero) { } sf::Time getElapsedLifetime(const Particle& particle) { return particle.passedLifetime; } sf::Time getTotalLifetime(const Particle& particle) { return particle.totalLifetime; } sf::Time getRemainingLifetime(const Particle& particle) { return getTotalLifetime(particle) - getElapsedLifetime(particle); } float getElapsedRatio(const Particle& particle) { return getElapsedLifetime(particle) / getTotalLifetime(particle); } float getRemainingRatio(const Particle& particle) { return getRemainingLifetime(particle) / getTotalLifetime(particle); } } // namespace thor
28.647887
82
0.663717
Shinao
fe999578e94c4e4f47034918b44d493a8870d28f
2,104
cpp
C++
libs/fnd/memory/test/src/unit_test_fnd_memory_addressof.cpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
4
2018-06-10T13:35:32.000Z
2021-06-03T14:27:41.000Z
libs/fnd/memory/test/src/unit_test_fnd_memory_addressof.cpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
566
2017-01-31T05:36:09.000Z
2022-02-09T05:04:37.000Z
libs/fnd/memory/test/src/unit_test_fnd_memory_addressof.cpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
1
2018-07-05T04:40:53.000Z
2018-07-05T04:40:53.000Z
/** * @file unit_test_fnd_memory_addressof.cpp * * @brief addressof のテスト * * @author myoukaku */ #include <bksge/fnd/memory/addressof.hpp> #include <bksge/fnd/config.hpp> #include <gtest/gtest.h> #include "constexpr_test.hpp" namespace bksge_memory_test { namespace addressof_test { struct UselessType {}; // operator&がオーバーロードされていないクラス struct A { }; // operator&がオーバーロードされているクラス struct B { BKSGE_CONSTEXPR UselessType operator&(void) const { return UselessType(); } }; // operator&がグローバル関数としてオーバーロードされているクラス struct C { }; BKSGE_CONSTEXPR UselessType operator&(C const&) { return UselessType(); } BKSGE_CONSTEXPR int func(UselessType) { return 0; } BKSGE_CONSTEXPR int func(A const*) { return 1; } BKSGE_CONSTEXPR int func(B const*) { return 2; } BKSGE_CONSTEXPR int func(C const*) { return 3; } GTEST_TEST(MemoryTest, AddressofTest) { { BKSGE_CONSTEXPR int n1 = 0; BKSGE_CONSTEXPR const int n2 = 0; volatile int n3 = 0; const volatile int n4 = 0; BKSGE_CONSTEXPR_EXPECT_TRUE(&n1 == bksge::addressof(n1)); BKSGE_CONSTEXPR_EXPECT_TRUE(&n2 == bksge::addressof(n2)); EXPECT_TRUE(&n3 == bksge::addressof(n3)); EXPECT_TRUE(&n4 == bksge::addressof(n4)); } { BKSGE_CONSTEXPR A a {}; BKSGE_CONSTEXPR_EXPECT_EQ(1, func(&a)); BKSGE_CONSTEXPR_EXPECT_EQ(1, func(bksge::addressof(a))); } { BKSGE_CONSTEXPR B b {}; BKSGE_CXX17_CONSTEXPR_EXPECT_EQ(0, func(&b)); #if defined(BKSGE_APPLE_CLANG) EXPECT_EQ(2, func(bksge::addressof(b))); #else BKSGE_CXX17_CONSTEXPR_EXPECT_EQ(2, func(bksge::addressof(b))); #endif } { BKSGE_CONSTEXPR C c {}; BKSGE_CXX17_CONSTEXPR_EXPECT_EQ(0, func(&c)); #if defined(BKSGE_APPLE_CLANG) EXPECT_EQ(3, func(bksge::addressof(c))); #else BKSGE_CXX17_CONSTEXPR_EXPECT_EQ(3, func(bksge::addressof(c))); #endif } } } // namespace addressof_test } // namespace bksge_memory_test
19.849057
65
0.637357
myoukaku
fe99db904207e277e3650932910de2a74856ae3e
1,241
cpp
C++
src/02/02.cpp
TrojanerHD/AdventofCode2021
2c378b3bc6545dbab5f6a825ed783a02da4a049e
[ "MIT" ]
1
2021-12-03T17:36:21.000Z
2021-12-03T17:36:21.000Z
src/02/02.cpp
TrojanerHD/AdventofCode2021
2c378b3bc6545dbab5f6a825ed783a02da4a049e
[ "MIT" ]
null
null
null
src/02/02.cpp
TrojanerHD/AdventofCode2021
2c378b3bc6545dbab5f6a825ed783a02da4a049e
[ "MIT" ]
1
2021-12-03T17:34:41.000Z
2021-12-03T17:34:41.000Z
#include <iostream> #include "../common/common.h" int main() { auto inputs = read_inputs(); auto values = split(inputs, "\n"); // Part 1 auto depth = 0; auto horizontal = 0; for (size_t i = 0; i < values.size(); i++) { auto input = values[i]; auto instructions = split(input, " "); if (instructions[0] == "forward") horizontal += stoi(instructions[1]); else if (instructions[0] == "down") depth += stoi(instructions[1]); else if (instructions[0] == "up") depth -= stoi(instructions[1]); } std::cout << "Part 1: " << horizontal * depth << std::endl; // Part 2 depth = 0; horizontal = 0; auto aim = 0; for (size_t i = 0; i < values.size(); i++) { auto input = values[i]; auto instructions = split(input, " "); if (instructions[0] == "forward") { horizontal += stoi(instructions[1]); depth += aim * stoi(instructions[1]); } else if (instructions[0] == "down") aim += stoi(instructions[1]); else if (instructions[0] == "up") aim -= stoi(instructions[1]); } std::cout << "Part 2: " << horizontal * depth << std::endl; }
31.820513
63
0.514102
TrojanerHD
fe9a747b82e472127db0e366216744fd8accae86
132,136
cpp
C++
CarenRengineCodes/Direct2D/CarenD2D1DCRenderTarget.cpp
VictorSantosReis/CarenRengine
8d0291171a6c5c402320ef2c0f6672ff2d412962
[ "Apache-2.0" ]
4
2020-10-19T17:17:11.000Z
2020-10-22T18:12:34.000Z
CarenRengineCodes/Direct2D/CarenD2D1DCRenderTarget.cpp
VictorSantosReis/CarenRengine
8d0291171a6c5c402320ef2c0f6672ff2d412962
[ "Apache-2.0" ]
1
2021-02-07T03:10:26.000Z
2021-02-07T03:10:26.000Z
CarenRengineCodes/Direct2D/CarenD2D1DCRenderTarget.cpp
VictorSantosReis/CarenRengine
8d0291171a6c5c402320ef2c0f6672ff2d412962
[ "Apache-2.0" ]
null
null
null
/* Copyright 2020 Victor Santos Reis 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 "../pch.h" #include "CarenD2D1DCRenderTarget.h" //Destruidor. CarenD2D1DCRenderTarget::~CarenD2D1DCRenderTarget() { //Define que a classe foi descartada Prop_DisposedClasse = true; } //Construtor. CarenD2D1DCRenderTarget::CarenD2D1DCRenderTarget() { //INICIALIZA SEM NENHUM PONTEIRO VINCULADO. } // Métodos da interface ICaren /// <summary> /// (QueryInterface) - Consulta o objeto COM atual para um ponteiro para uma de suas interfaces; identificando a interface por uma /// referência ao identificador de interface (IID). Se o objeto COM implementar a interface, o método retorna um ponteiro para essa /// interface depois de adicionar uma nova referência(AddRef). /// </summary> /// <param name="Param_Guid">O IID(Identificador de Interface) ou GUID para a interface desejada.</param> /// <param name="Param_InterfaceSolicitada">A interface que vai receber o ponteiro nativo. O usuário deve inicializar a interface antes de chamar o método. Libere a interface quando não for mais usá-la.</param> CarenResult CarenD2D1DCRenderTarget::ConsultarInterface(String^ Param_Guid, ICaren^ Param_InterfaceSolicitada) { //Variavel que vai retornar o resultado. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM HRESULT Hr = E_FAIL; //Variaveis a serem utilizadas GUID GuidInterface = GUID_NULL; wchar_t* DadosGuid = NULL; LPVOID* pInterfaceSolcitada = NULL; //Setor onde será criado o GUID para realizar a operação. { //Context Marshal. marshal_context ctx; //Lagrura da string int LarguraString = 0; //Variavel que vai conter os dados da String para o tipo não gerenciado. const char* DadosConvertidos = NULL; //Verifica se a string é valida. if (!String::IsNullOrEmpty(Param_Guid)) { //Obtém a largura da String. LarguraString = Param_Guid->Length + 1; //Converte os dados para um buffer de char. //O Proprio marshal_context destroi o buffer. DadosConvertidos = ctx.marshal_as<const char*>(Param_Guid); //Aloca memoria para o Dados do Guid. DadosGuid = new wchar_t[LarguraString]; //Copia os dados para o OLECHAR. mbstowcs_s(NULL, DadosGuid, LarguraString, DadosConvertidos, LarguraString - 1); //Chama o método que vai criar o CLSID adequado a aparti do guid Hr = CLSIDFromString(DadosGuid, (LPCLSID)&GuidInterface); } else { //Falhou ao criar o GUID Resultado.AdicionarCodigo(ResultCode::ER_GUID_INVALIDO, false); //A string não é valida goto Done; } } //Verifica se o guid foi criado com sucesso. if (GuidInterface == GUID_NULL) { //Falhou ao criar o GUID Resultado.AdicionarCodigo(ResultCode::ER_GUID_INVALIDO, false); //Sai do método goto Done; } //Chama o método para realizara operação Hr = PonteiroTrabalho->QueryInterface(GuidInterface, (LPVOID*)&pInterfaceSolcitada); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Define o ponteiro na interface solicitada. //A interface deve ter sido incializada pelo usuário. Resultado = Param_InterfaceSolicitada->AdicionarPonteiro(pInterfaceSolcitada); //Verifica o resultado da operação. if (Resultado.StatusCode != ResultCode::SS_OK) { //Libera a referência obtida a parti do QueryInterface. ((IUnknown*)pInterfaceSolcitada)->Release(); pInterfaceSolcitada = NULL; } Done:; //Verifica se o OLECHAR é valido e destroi if (ObjetoValido(DadosGuid)) { //Libera os dados. delete[] DadosGuid; } //Retorna o resultado return Resultado; } /// <summary> /// Método responsável por adicionar um novo ponteiro nativo a classe atual. /// Este método não é responsável por adicionar uma nova referência ao objeto COM. /// </summary> /// <param name="Param_PonteiroNativo">Variável (GERENCIADA) para o ponteiro nativo a ser adicionado.</param> CarenResult CarenD2D1DCRenderTarget::AdicionarPonteiro(IntPtr Param_PonteiroNativo) { //Variavel que vai retornar o resultado. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Verifica se o objeto é valido if (Param_PonteiroNativo == IntPtr::Zero) { //O objeto não é valido Resultado.AdicionarCodigo(ResultCode::ER_E_POINTER, false); //Sai do método. goto Done; } //Converte o ponteiro para o tipo especifico da classe. PonteiroTrabalho = reinterpret_cast<ID2D1DCRenderTarget*>(Param_PonteiroNativo.ToPointer()); //Verifica o ponteiro if (ObjetoValido(PonteiroTrabalho)) { //Define que o ponteiro foi definido com sucesso. Resultado.AdicionarCodigo(ResultCode::SS_OK, true); } else { //Define falha na operação Resultado.AdicionarCodigo(ResultCode::ER_E_POINTER, false); } Done:; //Retornao resultado return Resultado; } /// <summary> /// Método responsável por adicionar um novo ponteiro nativo a classe atual. /// Este método não é responsável por adicionar uma nova referência ao objeto COM. /// </summary> /// <param name="Param_PonteiroNativo">Variável (NATIVA) para o ponteiro nativo a ser adicionado.</param> CarenResult CarenD2D1DCRenderTarget::AdicionarPonteiro(LPVOID Param_PonteiroNativo) { //Variavel que vai retornar o resultado. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Verifica se o objeto é valido if (!ObjetoValido(Param_PonteiroNativo)) { //O objeto não é valido Resultado.AdicionarCodigo(ResultCode::ER_E_POINTER, false); //Sai do método goto Done; } //Converte o ponteiro para o tipo especifico da classe. PonteiroTrabalho = reinterpret_cast<ID2D1DCRenderTarget*>(Param_PonteiroNativo); //Verifica se o ponteiro é valido if (ObjetoValido(PonteiroTrabalho)) { //Ponteiro convertido com sucesso! //Define sucesso na operação Resultado.AdicionarCodigo(ResultCode::SS_OK, true); } else { //Falhou ao converter o ponteiro vazio para sua real representação. //Define falha no ponteiro Resultado.AdicionarCodigo(ResultCode::ER_E_POINTER, false); } Done:; //Retornao resultado return Resultado; } /// <summary> /// Método responsável por recuperar o ponteiro atual da classe. Se o ponteiro não for valido, o método retornar ResultCode::ER_PONTEIRO. /// Este método não é responsável por adicionar uma nova referência ao objeto COM. /// </summary> /// <param name="Param_Out_PonteiroNativo">Variável (GERENCIADA) que vai receber o ponteiro nativo.</param> CarenResult CarenD2D1DCRenderTarget::RecuperarPonteiro([Out] IntPtr% Param_Out_PonteiroNativo) { //Variavel que vai retornar o resultado. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Verifica se o ponteiro é valido if (!ObjetoValido(PonteiroTrabalho)) { //O ponteiro de trabalho é invalido. Resultado.AdicionarCodigo(ResultCode::ER_E_POINTER, false); //Sai do método goto Done; } //Cria e define o ponteiro gerenciado no parametro de saida. Param_Out_PonteiroNativo = IntPtr((LPVOID)PonteiroTrabalho); //Define o resultado Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Retorna o resultado return Resultado; } /// <summary> /// Método responsável por recuperar o ponteiro atual da classe. Se o ponteiro não for valido, o método retornar ResultCode::ER_PONTEIRO. /// Este método não é responsável por adicionar uma nova referência ao objeto COM. /// </summary> /// <param name="Param_Out_PonteiroNativo">Variável (NATIVA) que vai receber o ponteiro nativo.</param> CarenResult CarenD2D1DCRenderTarget::RecuperarPonteiro(LPVOID* Param_Out_PonteiroNativo) { //Variavel que vai retornar o resultado. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Verifica se o ponteiro é valido if (!ObjetoValido(PonteiroTrabalho)) { //O ponteiro de trabalho é invalido. Resultado.AdicionarCodigo(ResultCode::ER_E_POINTER, false); //Sai do método goto Done; } //Define o ponteiro de trabalho no parametro de saida. *Param_Out_PonteiroNativo = PonteiroTrabalho; //Define o resultado Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Retorna o resultado return Resultado; } /// <summary> /// Método responsável por retornar a quantidade de referências do objeto COM atual. /// </summary> /// <param name="Param_Out_Referencias">Variável que vai receber a quantidade de referências do objeto.</param> CarenResult CarenD2D1DCRenderTarget::RecuperarReferencias([Out] UInt64% Param_Out_Referencias) { //Variavel que vai retornar o resultado. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Verifica se o ponteiro é valido if (!ObjetoValido(PonteiroTrabalho)) { //O ponteiro de trabalho é invalido. Resultado.AdicionarCodigo(ResultCode::ER_E_POINTER, false); //Sai do método goto Done; } //Adiciona uma referência ao ponteiro ULONG CountRefs = PonteiroTrabalho->AddRef(); //Libera a referência adicional PonteiroTrabalho->Release(); //Decrementa o valor da quantidade de referência retornada em (-1) e define no parametro de saida. Param_Out_Referencias = static_cast<UInt64>(CountRefs - 1); //Define o resultado Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Retorna o resultado return Resultado; } /// <summary> /// Método responsável por indicar se o ponteiro COM atual é válido. /// </summary> CarenResult CarenD2D1DCRenderTarget::StatusPonteiro() { return (ObjetoValido(PonteiroTrabalho) ? CarenResult(ResultCode::SS_OK, true) : CarenResult(ResultCode::ER_E_POINTER, false)); } /// <summary> /// Método responsável por retornar a variável que armazena o último código de erro desconhecido ou não documentado gerado pela classe. /// Esse método não chama o método nativo (GetLastError), apenas retorna o código de erro que foi armazenado na classe. /// </summary> Int32 CarenD2D1DCRenderTarget::ObterCodigoErro() { return Var_Glob_LAST_HRESULT; } /// <summary> /// (AddRef) - Incrementa a contagem de referência para o ponteiro do objeto COM atual. Você deve chamar este método sempre que /// você fazer uma cópia de um ponteiro de interface. /// </summary> void CarenD2D1DCRenderTarget::AdicionarReferencia() { //Adiciona uma referência ao ponteiro PonteiroTrabalho->AddRef(); } /// <summary> /// (Release) - 'Decrementa' a contagem de referência do objeto COM atual. /// </summary> void CarenD2D1DCRenderTarget::LiberarReferencia() { //Libera a referência e obtém a quantidade atual. ULONG RefCount = PonteiroTrabalho->Release(); //Verifica se a quantidade é zero e se o ponteiro ainda é valido. //Se sim, vai deletar o ponteiro. if (RefCount == 0 && ObjetoValido(PonteiroTrabalho)) { //NULA o ponteiro vazio. PonteiroTrabalho = NULL; } } /// <summary> /// Método responsável por chamar o finalizador da interface para realizar a limpeza e descarte de dados pendentes. /// Este método pode ser escrito de forma diferente para cada interface. /// </summary> void CarenD2D1DCRenderTarget::Finalizar() { ////////////////////// //Código de descarte// ////////////////////// //Informa ao GC que a classe já foi limpa e pode ser descartada. GC::SuppressFinalize(this); //Nula o ponteiro de trabalho da classe. PonteiroTrabalho = Nulo; //Chama o finalizador da classe this->~CarenD2D1DCRenderTarget(); } // Métodos da interface proprietária(ICarenD2D1DCRenderTarget) /// <summary> /// Vincula o alvo de renderização ao contexto do dispositivo ao qual ele emite comandos de desenho. /// Antes de renderizar com o alvo de renderização DC, você deve usar seu método BindDC para associá-lo a um GDI DC. Você faz isso cada vez que usa um DC diferente, ou o tamanho da área /// que deseja desenhar para mudanças. /// </summary> /// <param name="Param_Hdc">O contexto do dispositivo para o qual o alvo de renderização emite comandos de desenho.</param> /// <param name="Param_SubRect">As dimensões da Handle(Param_Hdc) para um contexto de dispositivo (HDC) a que o alvo de renderização está vinculado.</param> CarenResult CarenD2D1DCRenderTarget::BindDC( IntPtr Param_Hdc, CA_RECT^ Param_SubRect) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; RECT* pRect = NULL; HDC pHdc = NULL; //Converte a estrutura. pRect = Util.ConverterRECTManagedToUnmanaged(Param_SubRect); //Obtém o HDC(IntPtr) pHdc = Util.ConverterIntPtrTo<HDC>(Param_Hdc); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->BindDC(pHdc, pRect); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } Done:; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pRect); //Retorna o resultado. return Resultado; } // Métodos da interface proprietária(ICarenD2D1RenderTarget) /// <summary> /// Inicia o desenho deste alvo de renderização. /// </summary> void CarenD2D1DCRenderTarget::BeginDraw() { //Chama o método para realizar a operação. PonteiroTrabalho->BeginDraw(); } /// <summary> /// Limpa a área de desenho para a cor especificada. /// </summary> /// <param name="Param_ClearColor"></param> void CarenD2D1DCRenderTarget::Clear(CA_D2D1_COLOR_F^ Param_ClearColor) { //Variaveis a serem utilizadas. Utilidades Util; D2D1_COLOR_F* pColorF = NULL; //Converte a estrutura gerenciada para a nativa. pColorF = Util.ConverterD2D1_COLOR_FManagedToUnmanaged(Param_ClearColor); //Chama o método para realizar a operação. PonteiroTrabalho->Clear(pColorF); //Libera a memória para a estrutura. DeletarEstruturaSafe(&pColorF); } /// <summary> /// Cria um bitmap do Direct2D de um ponteiro para dados de origem na memória. /// </summary> /// <param name="Param_Size">As dimensões em pixels do bitmap a ser criado.</param> /// <param name="Param_DadosOrigem">Um ponteiro para a localização da memória dos dados da imagem ou NULO para criar um bitmap não inicializado.</param> /// <param name="Param_Pitch">A contagem de bytes de cada linha de varredura, que é igual a (a largura da imagem em pixels × o número de bytes por pixel) + preenchimento de memória. Se (Param_DadosOrigem) é NULO, este valor é ignorado. (Note que o tom também é às vezes chamado de pitch.)</param> /// <param name="Param_PropriedadesBitmap">O formato de pixel e pontos por polegada (DPI) do bitmap a ser criado.</param> /// <param name="Param_Out_Bitmap">Retorna a interface (ICarenD2D1Bitmap) que contém um ponteiro para o novo bitmap.</param> CarenResult CarenD2D1DCRenderTarget::CreateBitmap( CA_D2D1_SIZE_U^ Param_Size, ICarenBuffer^ Param_DadosOrigem, UInt32 Param_Pitch, CA_D2D1_BITMAP_PROPERTIES^ Param_PropriedadesBitmap, [Out] ICarenD2D1Bitmap^% Param_Out_Bitmap) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_SIZE_U* pSizeU = NULL; D2D1_BITMAP_PROPERTIES* pBitmapProps = NULL; IntPtr pBufferOrigem = IntPtr::Zero; ID2D1Bitmap* pOutBitmap = NULL; //Converte as estruturas gerenciadas para as nativas. pSizeU = Util.ConverterD2D1_SIZE_UManagedToUnmanaged(Param_Size); pBitmapProps = Util.ConverterD2D1_BITMAP_PROPERTIESManagedToUnmanaged(Param_PropriedadesBitmap); //Obtém o ponteiro para a memória de origem. Resultado = Param_DadosOrigem->GetInternalPointer(pBufferOrigem); //Verifica se não falhou. if (!CarenSucesso(Resultado)) { //Falhou ao recupera o ponteiro. //Sai do método Sair; } //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateBitmap(*pSizeU, pBufferOrigem.ToPointer(), Param_Pitch, pBitmapProps, &pOutBitmap); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface que será retornada Param_Out_Bitmap = gcnew CarenD2D1Bitmap(); //Define o ponteiro na interface de saida. Resultado = Param_Out_Bitmap->AdicionarPonteiro(pOutBitmap); //Verifica se houve erro. if (!CarenSucesso(Resultado)) { //Falhou ao definir o ponteiro. //Libera o ponteiro pOutBitmap->Release(); pOutBitmap = NULL; Param_Out_Bitmap->Finalizar(); Param_Out_Bitmap = nullptr; } Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pSizeU); DeletarEstruturaSafe(&pBitmapProps); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um bitmap do Direct2D não inicializado. /// </summary> /// <param name="Param_Size">As dimensões em pixels do bitmap a ser criado.</param> /// <param name="Param_PropriedadesBitmap">O formato de pixel e pontos por polegada (DPI) do bitmap a ser criado.</param> /// <param name="Param_Out_Bitmap">Retorna a interface (ICarenD2D1Bitmap) que contém um ponteiro para o novo bitmap.</param> CarenResult CarenD2D1DCRenderTarget::CreateBitmap( CA_D2D1_SIZE_U^ Param_Size, CA_D2D1_BITMAP_PROPERTIES^ Param_PropriedadesBitmap, [Out] ICarenD2D1Bitmap^% Param_Out_Bitmap) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_SIZE_U* pSizeU = NULL; D2D1_BITMAP_PROPERTIES* pBitmapProps = NULL; ID2D1Bitmap* pOutBitmap = NULL; //Converte as estruturas gerenciadas para as nativas. pSizeU = Util.ConverterD2D1_SIZE_UManagedToUnmanaged(Param_Size); pBitmapProps = Util.ConverterD2D1_BITMAP_PROPERTIESManagedToUnmanaged(Param_PropriedadesBitmap); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateBitmap(*pSizeU, *pBitmapProps, &pOutBitmap); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface que será retornada Param_Out_Bitmap = gcnew CarenD2D1Bitmap(); //Define o ponteiro na interface de saida. Resultado = Param_Out_Bitmap->AdicionarPonteiro(pOutBitmap); //Verifica se houve erro. if (!CarenSucesso(Resultado)) { //Falhou ao definir o ponteiro. //Libera o ponteiro pOutBitmap->Release(); pOutBitmap = NULL; Param_Out_Bitmap->Finalizar(); Param_Out_Bitmap = nullptr; } Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pSizeU); DeletarEstruturaSafe(&pBitmapProps); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um ICarenD2D1BitmapBrush a partir do bitmap especificado. /// </summary> /// <param name="Param_Bitmap">O conteúdo do bitmap do novo pincel(Brush).</param> /// <param name="Param_PropriedadesBitmapBrush">Os modos de extensão e o modo de interpolação do novo pincel, ou NULO. Se você definir este parâmetro como NULO,a escova padrão para o D2D1_EXTEND_MODE_CLAMP /// modos de extensão horizontal e vertical e o modo de interpolação D2D1_BITMAP_INTERPOLATION_MODE_LINEAR.</param> /// <param name="Param_PropriedadesBrush">Uma estrutura que contenha a opacidade e a transformação do novo pincel, ou NULO. Se você definir este parâmetro como NULO,o pincel define o membro da opacidade /// para 1.0F e o membro de transformação para a matriz de identidade.</param> /// <param name="Param_Out_BitmapBrush">Retorna a interface (ICarenD2D1BitmapBrush) que contém um ponteiro para o novo pincel(Brush).</param> CarenResult CarenD2D1DCRenderTarget::CreateBitmapBrush( ICarenD2D1Bitmap^ Param_Bitmap, CA_D2D1_BITMAP_BRUSH_PROPERTIES^ Param_PropriedadesBitmapBrush, CA_D2D1_BRUSH_PROPERTIES^ Param_PropriedadesBrush, [Out] ICarenD2D1BitmapBrush^% Param_Out_BitmapBrush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; ID2D1Bitmap* pBitmap = NULL; D2D1_BITMAP_BRUSH_PROPERTIES* pBitmapBrushProps = NULL; //Pode ser NULO. D2D1_BRUSH_PROPERTIES* pBrushProps = NULL; //Pode ser NULO. ID2D1BitmapBrush* pOutBrush = NULL; //Recupera o ponteiro para o bitmap. Resultado = Param_Bitmap->RecuperarPonteiro((LPVOID*)&pBitmap); //Verifica se não houve erro. if (!CarenSucesso(Resultado)) { //Falhou. O ponteiro é invalido. //Sai do método Sair; } //Converte as estruturas gerenciadas para a nativa se validas. pBitmapBrushProps = ObjetoGerenciadoValido(Param_PropriedadesBitmapBrush) ? Util.ConverterD2D1_BITMAP_BRUSH_PROPERTIESManagedToUnmanaged(Param_PropriedadesBitmapBrush) : NULL; pBrushProps = ObjetoGerenciadoValido(Param_PropriedadesBrush) ? Util.ConverterD2D1_BRUSH_PROPERTIESManagedToUnmanaged(Param_PropriedadesBrush) : NULL; //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateBitmapBrush(pBitmap, pBitmapBrushProps, pBrushProps, &pOutBrush); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a classe a ser retornada. Param_Out_BitmapBrush = gcnew CarenD2D1BitmapBrush(); //Define o ponteiro da interface. Resultado = Param_Out_BitmapBrush->AdicionarPonteiro(pOutBrush); //Verifica se não houve erro if (!CarenSucesso(Resultado)) { //Falhou ao definir o ponteiro. //Libera os dados. pOutBrush->Release(); pOutBrush = NULL; Param_Out_BitmapBrush->Finalizar(); Param_Out_BitmapBrush = nullptr; } Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pBitmapBrushProps); DeletarEstruturaSafe(&pBrushProps); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um ICarenD2D1BitmapBrush a partir do bitmap especificado. O pincel usa os valores padrão para seu modo de extensão, modo de interpolação, opacidade e transformação. /// </summary> /// <param name="Param_Bitmap">O conteúdo do bitmap do novo pincel.</param> /// <param name="Param_Out_BitmapBrush">Retorna a interface (ICarenD2D1BitmapBrush) que contém um ponteiro para o novo pincel(Brush).</param> CarenResult CarenD2D1DCRenderTarget::CreateBitmapBrush( ICarenD2D1Bitmap^ Param_Bitmap, [Out] ICarenD2D1BitmapBrush^% Param_Out_BitmapBrush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. ID2D1Bitmap* pBitmap = NULL; ID2D1BitmapBrush* pOutBrush = NULL; //Recupera o ponteiro para o bitmap. Resultado = Param_Bitmap->RecuperarPonteiro((LPVOID*)&pBitmap); //Verifica se não houve erro. if (!CarenSucesso(Resultado)) { //Falhou. O ponteiro é invalido. //Sai do método Sair; } //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateBitmapBrush(pBitmap, &pOutBrush); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a classe a ser retornada. Param_Out_BitmapBrush = gcnew CarenD2D1BitmapBrush(); //Define o ponteiro da interface. Resultado = Param_Out_BitmapBrush->AdicionarPonteiro(pOutBrush); //Verifica se não houve erro if (!CarenSucesso(Resultado)) { //Falhou ao definir o ponteiro. //Libera os dados. pOutBrush->Release(); pOutBrush = NULL; Param_Out_BitmapBrush->Finalizar(); Param_Out_BitmapBrush = nullptr; } Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Cria um ID2D1BitmapBrush a partir do bitmap especificado. O pincel usa os valores padrão para sua opacidade e transformação. /// O Brush bitmap criado por este método tem uma opacidade de 1.0f e a matriz de identidade como sua transformação. /// </summary> /// <param name="Param_Bitmap">O conteúdo do bitmap do novo pincel.</param> /// <param name="Param_PropriedadesBitmapBrush">Os modos de extensão e o modo de interpolação do novo pincel.</param> /// <param name="Param_Out_BitmapBrush">Retorna a interface (ICarenD2D1BitmapBrush) que contém um ponteiro para o novo pincel(Brush).</param> CarenResult CarenD2D1DCRenderTarget::CreateBitmapBrush( ICarenD2D1Bitmap^ Param_Bitmap, CA_D2D1_BITMAP_BRUSH_PROPERTIES^ Param_PropriedadesBitmapBrush, [Out] ICarenD2D1BitmapBrush^% Param_Out_BitmapBrush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; ID2D1Bitmap* pBitmap = NULL; ID2D1BitmapBrush* pOutBrush = NULL; D2D1_BITMAP_BRUSH_PROPERTIES* pBitmapBrushProps = NULL; //Recupera o ponteiro para o bitmap. Resultado = Param_Bitmap->RecuperarPonteiro((LPVOID*)&pBitmap); //Verifica se não houve erro. if (!CarenSucesso(Resultado)) { //Falhou. O ponteiro é invalido. //Sai do método Sair; } //Converte as estruturas gerenciadas para a nativa se validas. pBitmapBrushProps = Util.ConverterD2D1_BITMAP_BRUSH_PROPERTIESManagedToUnmanaged(Param_PropriedadesBitmapBrush); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateBitmapBrush(pBitmap, *pBitmapBrushProps, &pOutBrush); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a classe a ser retornada. Param_Out_BitmapBrush = gcnew CarenD2D1BitmapBrush(); //Define o ponteiro da interface. Resultado = Param_Out_BitmapBrush->AdicionarPonteiro(pOutBrush); //Verifica se não houve erro if (!CarenSucesso(Resultado)) { //Falhou ao definir o ponteiro. //Libera os dados. pOutBrush->Release(); pOutBrush = NULL; Param_Out_BitmapBrush->Finalizar(); Param_Out_BitmapBrush = nullptr; } Done:; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pBitmapBrushProps); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um ICarenD2D1Bitmap copiando o bitmap especificado do Microsoft Windows Imaging Component (WIC). /// </summary> /// <param name="Param_WicBitmapSource">Uma interface ICarenWICBitmapSource que contém os dados a serem copiados.</param> /// <param name="Param_PropriedadesBitmap">O formato de pixel e DPI do bitmap para criar. O formato pixel deve corresponder ao formato de pixel do wicBitmapSource, ou o método falhará. Para evitar uma /// incompatibilidade, você pode passar NULO ou passar o valor obtido ligando para a função de ajudante D2D1::PixelFormat sem especificar nenhum valor de parâmetro. Se o dpiX e o dpiY forem 0,0f, o /// DPI padrão, 96, será usado. As informações de DPI incorporadas no (Param_WicBitmapSource) são ignoradas.</param> /// <param name="Param_Out_Bitmap">Retorna a interface ICarenD2D1Bitmap que contém um ponteiro para o novo bitmap.</param> CarenResult CarenD2D1DCRenderTarget::CreateBitmapFromWicBitmap( ICaren^ Param_WicBitmapSource, CA_D2D1_BITMAP_PROPERTIES^ Param_PropriedadesBitmap, [Out] ICarenD2D1Bitmap^% Param_Out_Bitmap) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; IWICBitmapSource* pWicBitmapSource = NULL; D2D1_BITMAP_PROPERTIES* pBitmapProps = NULL; //Pode ser NULO. ID2D1Bitmap* pOutBitmap = NULL; //Recupera o ponteiro para o bitmap. Resultado = Param_WicBitmapSource->RecuperarPonteiro((LPVOID*)&pWicBitmapSource); //Verifica se não houve erro. if (!CarenSucesso(Resultado)) { //Falhou. O ponteiro é invalido. //Sai do método Sair; } //Converte a estrutura gerenciada para a nativa se valida. pBitmapProps = ObjetoGerenciadoValido(Param_PropriedadesBitmap) ? Util.ConverterD2D1_BITMAP_PROPERTIESManagedToUnmanaged(Param_PropriedadesBitmap) : NULL; //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateBitmapFromWicBitmap(pWicBitmapSource, pBitmapProps, &pOutBitmap); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a classe a ser retornada. Param_Out_Bitmap = gcnew CarenD2D1Bitmap(); //Define o ponteiro da interface. Resultado = Param_Out_Bitmap->AdicionarPonteiro(pOutBitmap); //Verifica se não houve erro if (!CarenSucesso(Resultado)) { //Falhou ao definir o ponteiro. //Libera os dados. pOutBitmap->Release(); pOutBitmap = NULL; Param_Out_Bitmap->Finalizar(); Param_Out_Bitmap = nullptr; } Done:; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pBitmapProps); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um ID2D1Bitmap copiando o bitmap especificado do Microsoft Windows Imaging Component (WIC). /// </summary> /// <param name="Param_WicBitmapSource">Uma interface ICarenWICBitmapSource que contém os dados a serem copiados.</param> /// <param name="Param_Out_Bitmap">Retorna a interface ICarenD2D1Bitmap que contém um ponteiro para o novo bitmap.</param> CarenResult CarenD2D1DCRenderTarget::CreateBitmapFromWicBitmap( ICaren^ Param_WicBitmapSource, [Out] ICarenD2D1Bitmap^% Param_Out_Bitmap) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. IWICBitmapSource* pWicBitmapSource = NULL; ID2D1Bitmap* pOutBitmap = NULL; //Recupera o ponteiro para o bitmap. Resultado = Param_WicBitmapSource->RecuperarPonteiro((LPVOID*)&pWicBitmapSource); //Verifica se não houve erro. if (!CarenSucesso(Resultado)) { //Falhou. O ponteiro é invalido. //Sai do método Sair; } //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateBitmapFromWicBitmap(pWicBitmapSource, &pOutBitmap); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a classe a ser retornada. Param_Out_Bitmap = gcnew CarenD2D1Bitmap(); //Define o ponteiro da interface. Resultado = Param_Out_Bitmap->AdicionarPonteiro(pOutBitmap); //Verifica se não houve erro if (!CarenSucesso(Resultado)) { //Falhou ao definir o ponteiro. //Libera os dados. pOutBitmap->Release(); pOutBitmap = NULL; Param_Out_Bitmap->Finalizar(); Param_Out_Bitmap = nullptr; } Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Cria um alvo de renderização bitmap para uso durante o desenho offscreen intermediário compatível com o alvo de renderização atual. /// </summary> /// <param name="Param_DesiredSize">O tamanho desejado do novo alvo de renderização (em pixels independentes do dispositivo), se ele deve ser diferente do alvo de renderização original.</param> /// <param name="Param_DesiredPixelSize">O tamanho desejado do novo alvo de renderização em pixels se ele deve ser diferente do alvo de renderização original.</param> /// <param name="DesiredFormat">O formato de pixel desejado e o modo alfa do novo alvo de renderização. Se o formato do pixel for definido para DXGI_FORMAT_UNKNOWN, o novo alvo de renderização usará /// o mesmo formato de pixel que o alvo original da renderização. Se o modo alfa estiver D2D1_ALPHA_MODE_UNKNOWN,o modo alfa do novo destino renderizante padrão para D2D1_ALPHA_MODE_PREMULTIPLIED.</param> /// <param name="Param_Opcoes">Um valor que especifica se o novo alvo de renderização deve ser compatível com o GDI.</param> /// <param name="Param_Out_BitmapRenderTarget">Retorna a interface (ICarenD2D1BitmapRenderTarget) que contém um ponteiro para um novo alvo de renderização bitmap. O usuário deve inicializar a interface antes de chamar este método.</param> CarenResult CarenD2D1DCRenderTarget::CreateCompatibleRenderTarget( CA_D2D1_SIZE_F^ Param_DesiredSize, CA_D2D1_SIZE_U^ Param_DesiredPixelSize, CA_D2D1_PIXEL_FORMAT^ DesiredFormat, CA_D2D1_COMPATIBLE_RENDER_TARGET_OPTIONS Param_Opcoes, ICaren^ Param_Out_BitmapRenderTarget) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_SIZE_F* pSizeF = NULL; D2D1_SIZE_U* pSizeU = NULL; D2D1_PIXEL_FORMAT* pPixelFormat = NULL; D2D1_COMPATIBLE_RENDER_TARGET_OPTIONS OptonsRender = static_cast<D2D1_COMPATIBLE_RENDER_TARGET_OPTIONS>(Param_Opcoes); ID2D1BitmapRenderTarget* pOutRenderTarget = NULL; //Converte as estruturas. pSizeF = Util.ConverterD2D1_SIZE_FManagedToUnmanaged(Param_DesiredSize); pSizeU = Util.ConverterD2D1_SIZE_UManagedToUnmanaged(Param_DesiredPixelSize); pPixelFormat = Util.ConverterD2D1_PIXEL_FORMATManagedToUnmanaged(DesiredFormat); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateCompatibleRenderTarget(*pSizeF, *pSizeU, *pPixelFormat, &pOutRenderTarget); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Define o ponteiro da interface inicializada pelo usuário. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutRenderTarget, Param_Out_BitmapRenderTarget, true)); Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pSizeF); DeletarEstruturaSafe(&pSizeU); DeletarEstruturaSafe(&pPixelFormat); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um novo alvo de renderização bitmap para uso durante o desenho offscreen intermediário que é compatível com o alvo de renderização atual e tem o mesmo tamanho, DPI e formato de pixel /// (mas não o modo alfa) como o alvo de renderização atual. /// O alvo de renderização bitmap criado por este método não é compatível com o GDI, e tem um modo alfa de D2D1_ALPHA_MODE_PREMULTIPLIED. /// </summary> /// <param name="Param_Out_BitmapRenderTarget">Retorna a interface (ICarenD2D1BitmapRenderTarget) que contém um ponteiro para um novo alvo de renderização bitmap. O usuário deve inicializar a interface antes de chamar este método.</param> CarenResult CarenD2D1DCRenderTarget::CreateCompatibleRenderTarget(ICaren^ Param_Out_BitmapRenderTarget) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. ID2D1BitmapRenderTarget* pOutRenderTarget = NULL; //Chama o método para realizar a operação. PonteiroTrabalho->CreateCompatibleRenderTarget(&pOutRenderTarget); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Define o ponteiro da interface inicializada pelo usuário. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutRenderTarget, Param_Out_BitmapRenderTarget, true)); Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Cria um alvo de renderização bitmap para uso durante o desenho offscreen intermediário compatível com o alvo de renderização atual. /// O alvo de renderização bitmap criado por este método não é compatível com o GDI. /// </summary> /// <param name="Param_DesiredSize">O tamanho desejado do novo destino de renderização em pixels independentes do dispositivo. O tamanho do pixel é calculado a partir do tamanho desejado usando o DPI pai de destino. /// Se o tamanho desejado for mapeado para um tamanho de pixel inteiro, o DPI do destino de renderização compatível será o mesmo que o DPI pai do destino. Se o Tamanho desejado é mapeado para um tamanho de pixel /// fracionário, o tamanho do pixel é arredondado para o número inteiro mais próximo e o DPI para o destino de renderização compatível é um pouco maior que o DPI do destino de renderização pai. Em todos os casos, /// a coordenada (Param_DesiredSize.width, Param_DesiredSize.height) é mapeada para o canto inferior direito do destino de renderização compatível.</param> /// <param name="Param_Out_BitmapRenderTarget">Retorna a interface (ICarenD2D1BitmapRenderTarget) que contém um ponteiro para um novo alvo de renderização bitmap. O usuário deve inicializar a interface antes de chamar este método.</param> CarenResult CarenD2D1DCRenderTarget::CreateCompatibleRenderTarget( CA_D2D1_SIZE_F^ Param_DesiredSize, ICaren^ Param_Out_BitmapRenderTarget) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_SIZE_F* pSizeF = NULL; ID2D1BitmapRenderTarget* pOutRenderTarget = NULL; //Converte a estrutura. pSizeF = Util.ConverterD2D1_SIZE_FManagedToUnmanaged(Param_DesiredSize); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateCompatibleRenderTarget(*pSizeF, &pOutRenderTarget); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Define o ponteiro da interface inicializada pelo usuário. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutRenderTarget, Param_Out_BitmapRenderTarget)); Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pSizeF); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um alvo de renderização bitmap para uso durante o desenho offscreen intermediário compatível com o alvo de renderização atual. /// </summary> /// <param name="Param_DesiredSize">O tamanho desejado do novo alvo de renderização (em pixels independentes do dispositivo), se ele deve ser diferente do alvo de renderização original.</param> /// <param name="Param_DesiredPixelSize">O tamanho desejado do novo alvo de renderização em pixels se ele deve ser diferente do alvo de renderização original.</param> /// <param name="Param_Out_BitmapRenderTarget">Retorna a interface (ICarenD2D1BitmapRenderTarget) que contém um ponteiro para um novo alvo de renderização bitmap. O usuário deve inicializar a interface antes de chamar este método.</param> CarenResult CarenD2D1DCRenderTarget::CreateCompatibleRenderTarget( CA_D2D1_SIZE_F^ Param_DesiredSize, CA_D2D1_SIZE_U^ Param_DesiredPixelSize, ICaren^ Param_Out_BitmapRenderTarget) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_SIZE_F* pSizeF = NULL; D2D1_SIZE_U* pSizeU = NULL; ID2D1BitmapRenderTarget* pOutRenderTarget = NULL; //Converte as estruturas. pSizeF = Util.ConverterD2D1_SIZE_FManagedToUnmanaged(Param_DesiredSize); pSizeU = Util.ConverterD2D1_SIZE_UManagedToUnmanaged(Param_DesiredPixelSize); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateCompatibleRenderTarget(*pSizeF, *pSizeU, &pOutRenderTarget); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Define o ponteiro da interface inicializada pelo usuário. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutRenderTarget, Param_Out_BitmapRenderTarget)); Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pSizeF); DeletarEstruturaSafe(&pSizeU); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um alvo de renderização bitmap para uso durante o desenho offscreen intermediário compatível com o alvo de renderização atual. /// </summary> /// <param name="Param_DesiredSize">O tamanho desejado do novo alvo de renderização (em pixels independentes do dispositivo), se ele deve ser diferente do alvo de renderização original.</param> /// <param name="Param_DesiredPixelSize">O tamanho desejado do novo alvo de renderização em pixels se ele deve ser diferente do alvo de renderização original.</param> /// <param name="DesiredFormat">O formato de pixel desejado e o modo alfa do novo alvo de renderização. Se o formato do pixel for definido para DXGI_FORMAT_UNKNOWN, o novo alvo de renderização usará o mesmo formato de pixel que o alvo original da renderização. Se o modo alfa estiver D2D1_ALPHA_MODE_UNKNOWN,o modo alfa do novo destino renderizante padrão para D2D1_ALPHA_MODE_PREMULTIPLIED.</param> /// <param name="Param_Out_BitmapRenderTarget">Retorna a interface (ICarenD2D1BitmapRenderTarget) que contém um ponteiro para um novo alvo de renderização bitmap. O usuário deve inicializar a interface antes de chamar este método.</param> CarenResult CarenD2D1DCRenderTarget::CreateCompatibleRenderTarget( CA_D2D1_SIZE_F^ Param_DesiredSize, CA_D2D1_SIZE_U^ Param_DesiredPixelSize, CA_D2D1_PIXEL_FORMAT^ DesiredFormat, ICaren^ Param_Out_BitmapRenderTarget) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_SIZE_F* pSizeF = NULL; D2D1_SIZE_U* pSizeU = NULL; D2D1_PIXEL_FORMAT* pPixelFormat = NULL; ID2D1BitmapRenderTarget* pOutRenderTarget = NULL; //Converte as estruturas. pSizeF = Util.ConverterD2D1_SIZE_FManagedToUnmanaged(Param_DesiredSize); pSizeU = Util.ConverterD2D1_SIZE_UManagedToUnmanaged(Param_DesiredPixelSize); pPixelFormat = Util.ConverterD2D1_PIXEL_FORMATManagedToUnmanaged(DesiredFormat); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateCompatibleRenderTarget(*pSizeF, *pSizeU, *pPixelFormat, &pOutRenderTarget); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Define o ponteiro da interface inicializada pelo usuário. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutRenderTarget, Param_Out_BitmapRenderTarget)); Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pSizeF); DeletarEstruturaSafe(&pSizeU); DeletarEstruturaSafe(&pPixelFormat); //Retorna o resultado. return Resultado; } /// <summary> /// Cria uma interface de coleção ICarenD2D1GradientStop a partir do conjunto especificado de estruturas CA_D2D1_GRADIENT_STOP. /// </summary> /// <param name="Param_MatrizGraientStops">Uma matriz de estruturas CA_D2D1_GRADIENT_STOP.</param> /// <param name="Param_QuantidadeGradientes">Um valor maior ou igual a 1 que especifica o número de estruturas(CA_D2D1_GRADIENT_STOP) na matriz (Param_MatrizGraientStops).</param> /// <param name="Param_ColorInterpolationGamma">O espaço em que a interpolação de cores entre as paradas gradientes é realizada.</param> /// <param name="Param_ModoExtendido">O comportamento do gradiente fora da faixa [0,1] normalizada.</param> /// <param name="Param_Out_GradientStopCollection">Retorna a interface ICarenD2D1GradientStopCollection que contém um ponteiro para a nova GradientStopCollection.</param> CarenResult CarenD2D1DCRenderTarget::CreateGradientStopCollection( cli::array<CA_D2D1_GRADIENT_STOP^>^ Param_MatrizGraientStops, UInt32 Param_QuantidadeGradientes, CA_D2D1_GAMMA Param_ColorInterpolationGamma, CA_D2D1_EXTEND_MODE Param_ModoExtendido, [Out] ICarenD2D1GradientStopCollection^% Param_Out_GradientStopCollection) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. D2D1_GRADIENT_STOP* pMatrizGradientes = CriarMatrizEstruturas<D2D1_GRADIENT_STOP>(Param_QuantidadeGradientes); D2D1_GAMMA Gamma = static_cast<D2D1_GAMMA>(Param_ColorInterpolationGamma); D2D1_EXTEND_MODE ExtendMode = static_cast<D2D1_EXTEND_MODE>(Param_ModoExtendido); ID2D1GradientStopCollection* pOutGradientCollection = NULL; //Copia os dados da matriz gerenciada para a nativa. for (UInt32 i = 0; i < Param_QuantidadeGradientes; i++) { //Inicializa a estrutura no index especifico. ZeroMemory(&pMatrizGradientes[i], sizeof(D2D1_GRADIENT_STOP)); //Define os dados. pMatrizGradientes[i].position = Param_MatrizGraientStops[i]->position; //Define os dados ARGB. pMatrizGradientes->color.a = Param_MatrizGraientStops[i]->color->a; pMatrizGradientes->color.r = Param_MatrizGraientStops[i]->color->r; pMatrizGradientes->color.g = Param_MatrizGraientStops[i]->color->g; pMatrizGradientes->color.b = Param_MatrizGraientStops[i]->color->b; } //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateGradientStopCollection(pMatrizGradientes, Param_QuantidadeGradientes, Gamma, ExtendMode, &pOutGradientCollection); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface de saida. Param_Out_GradientStopCollection = gcnew CarenD2D1GradientStopCollection(); //Define o ponteiro da interface. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutGradientCollection, Param_Out_GradientStopCollection)); Done:; //Libera a memória para a matriz de estruturas. DeletarMatrizEstruturasSafe(&pMatrizGradientes); //Retorna o resultado. return Resultado; } /// <summary> /// Cria uma interface de coleção ICarenD2D1GradientStop a partir das estruturas GradientStops especificadas que usa o gama de interpolação de cores D2D1_GAMMA_2_2 e o modo de extensão do Clamp. /// </summary> /// <param name="Param_MatrizGraientStops">Uma matriz de estruturas CA_D2D1_GRADIENT_STOP.</param> /// <param name="Param_QuantidadeGradientes">Um valor maior ou igual a 1 que especifica o número de estruturas(CA_D2D1_GRADIENT_STOP) na matriz (Param_MatrizGraientStops).</param> /// <param name="Param_Out_GradientStopCollection">Retorna a interface ICarenD2D1GradientStopCollection que contém um ponteiro para a nova GradientStopCollection.</param> CarenResult CarenD2D1DCRenderTarget::CreateGradientStopCollection( cli::array<CA_D2D1_GRADIENT_STOP^>^ Param_MatrizGraientStops, UInt32 Param_QuantidadeGradientes, [Out] ICarenD2D1GradientStopCollection^% Param_Out_GradientStopCollection) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_GRADIENT_STOP* pMatrizGradientes = CriarMatrizEstruturas<D2D1_GRADIENT_STOP>(Param_QuantidadeGradientes); ID2D1GradientStopCollection* pOutGradientCollection = NULL; //Copia os dados da matriz gerenciada para a nativa. for (UInt32 i = 0; i < Param_QuantidadeGradientes; i++) { //Inicializa a estrutura no index especifico. ZeroMemory(&pMatrizGradientes[i], sizeof(D2D1_GRADIENT_STOP)); //Define os dados. pMatrizGradientes[i].position = Param_MatrizGraientStops[i]->position; //Define os dados ARGB. pMatrizGradientes->color.a = Param_MatrizGraientStops[i]->color->a; pMatrizGradientes->color.r = Param_MatrizGraientStops[i]->color->r; pMatrizGradientes->color.g = Param_MatrizGraientStops[i]->color->g; pMatrizGradientes->color.b = Param_MatrizGraientStops[i]->color->b; } //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateGradientStopCollection(pMatrizGradientes, Param_QuantidadeGradientes, &pOutGradientCollection); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface de saida. Param_Out_GradientStopCollection = gcnew CarenD2D1GradientStopCollection(); //Define o ponteiro da interface. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutGradientCollection, Param_Out_GradientStopCollection)); Done:; //Libera a memória para a matriz de estruturas. DeletarMatrizEstruturasSafe(&pMatrizGradientes); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um recurso de camada que pode ser usado com este alvo de renderização e seus alvos de renderização compatíveis. /// </summary> /// <param name="Param_Size">Se (0, 0) for especificado, nenhuma loja de backup será criada por trás do recurso de camada. O recurso de camada é alocado para o tamanho mínimo quando o PushLayer é chamado.</param> /// <param name="Param_Out_Layer">Retorna a interface ICarenD2D1Layer que contém um ponteiro para a nova camada(Layer).</param> CarenResult CarenD2D1DCRenderTarget::CreateLayer( CA_D2D1_SIZE_F^ Param_Size, [Out] ICarenD2D1Layer^% Param_Out_Layer) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_SIZE_F* pSizeF = NULL; ID2D1Layer* pOutLayer = NULL; //Converte a estrutura. pSizeF = Util.ConverterD2D1_SIZE_FManagedToUnmanaged(Param_Size); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateLayer(pSizeF, &pOutLayer); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface de saida. Param_Out_Layer = gcnew CarenD2D1Layer(); //Define o ponteiro da interface. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutLayer, Param_Out_Layer)); Done:; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pSizeF); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um recurso de camada que pode ser usado com este alvo de renderização e seus alvos de renderização compatíveis. /// </summary> /// <param name="Param_Out_Layer">Retorna a interface ICarenD2D1Layer que contém um ponteiro para a nova camada(Layer).</param> CarenResult CarenD2D1DCRenderTarget::CreateLayer([Out] ICarenD2D1Layer^% Param_Out_Layer) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. ID2D1Layer* pOutLayer = NULL; //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateLayer(&pOutLayer); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface de saida. Param_Out_Layer = gcnew CarenD2D1Layer(); //Define o ponteiro da interface. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutLayer, Param_Out_Layer)); Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Cria um ICarenD2D1LinearGradientBrush que contém as GradientStops especificadas e tem a opacidade de transformação e base especificada. /// </summary> /// <param name="Param_PropriedadesLinerarGradientBrush">Os pontos de partida e fim do gradiente.</param> /// <param name="Param_PropriedadesBrush">A opacidade de transformação e base do novo pincel.</param> /// <param name="Param_GradientStopCollection">Uma interface que contém uma coleção de estruturas D2D1_GRADIENT_STOP que descrevem as cores no Brush Gradient e suas localizações ao longo da linha gradiente.</param> /// <param name="Param_Out_LinearGradientBrush">Retorna uma interface ICarenD2D1LinearGradientBrush que contém um ponteiro para o novo Pincel(Brush).</param> CarenResult CarenD2D1DCRenderTarget::CreateLinearGradientBrush( CA_D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES^ Param_PropriedadesLinerarGradientBrush, CA_D2D1_BRUSH_PROPERTIES^ Param_PropriedadesBrush, ICarenD2D1GradientStopCollection^ Param_GradientStopCollection, [Out] ICarenD2D1LinearGradientBrush^% Param_Out_LinearGradientBrush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES* pLinearGradientProps = NULL; D2D1_BRUSH_PROPERTIES* pBrushProps = NULL; ID2D1GradientStopCollection* pGradientStopCollection = NULL; ID2D1LinearGradientBrush* pOutLinearGradientBrush = NULL; //Converte as estruturas. pLinearGradientProps = Util.ConverterD2D1_LINEAR_GRADIENT_BRUSH_PROPERTIESManagedToUnmanaged(Param_PropriedadesLinerarGradientBrush); pBrushProps = Util.ConverterD2D1_BRUSH_PROPERTIESManagedToUnmanaged(Param_PropriedadesBrush); //Recupera o ponteiro para a coleção de gradientes. Resultado = RecuperarPonteiroCaren(Param_GradientStopCollection, &pGradientStopCollection); //Sai do método em caso de erro SairOnError(Resultado); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateLinearGradientBrush(pLinearGradientProps, pBrushProps, pGradientStopCollection, &pOutLinearGradientBrush); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface de saida. Param_Out_LinearGradientBrush = gcnew CarenD2D1LinearGradientBrush(); //Define o ponteiro da interface. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutLinearGradientBrush, Param_Out_LinearGradientBrush)); Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pLinearGradientProps); DeletarEstruturaSafe(&pBrushProps); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um ICarenD2D1LinearGradientBrush que contém os GradientStops especificados, não tem transformação e tem uma opacidade base de 1.0. /// </summary> /// <param name="Param_PropriedadesLinerarGradientBrush">Os pontos de partida e fim do gradiente.</param> /// <param name="Param_GradientStopCollection">Uma interface que contém uma coleção de estruturas D2D1_GRADIENT_STOP que descrevem as cores no Brush Gradient e suas localizações ao longo da linha gradiente.</param> /// <param name="Param_Out_LinearGradientBrush">Retorna uma interface ICarenD2D1LinearGradientBrush que contém um ponteiro para o novo Pincel(Brush).</param> CarenResult CarenD2D1DCRenderTarget::CreateLinearGradientBrush( CA_D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES^ Param_PropriedadesLinerarGradientBrush, ICarenD2D1GradientStopCollection^ Param_GradientStopCollection, [Out] ICarenD2D1LinearGradientBrush^% Param_Out_LinearGradientBrush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES* pLinearGradientProps = NULL; ID2D1GradientStopCollection* pGradientStopCollection = NULL; ID2D1LinearGradientBrush* pOutLinearGradientBrush = NULL; //Converte a estrutura. pLinearGradientProps = Util.ConverterD2D1_LINEAR_GRADIENT_BRUSH_PROPERTIESManagedToUnmanaged(Param_PropriedadesLinerarGradientBrush); //Recupera o ponteiro para a coleção de gradientes. Resultado = RecuperarPonteiroCaren(Param_GradientStopCollection, &pGradientStopCollection); //Sai do método em caso de erro SairOnError(Resultado); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateLinearGradientBrush(*pLinearGradientProps, pGradientStopCollection, &pOutLinearGradientBrush); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface de saida. Param_Out_LinearGradientBrush = gcnew CarenD2D1LinearGradientBrush(); //Define o ponteiro da interface. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutLinearGradientBrush, Param_Out_LinearGradientBrush)); Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pLinearGradientProps); //Retorna o resultado. return Resultado; } /// <summary> /// Crie uma malha(Mesh) que usa triângulos para descrever uma forma. /// </summary> /// <param name="Param_Out_Mesh">Retorna uma interface ICarenD2D1Mesh que contém um ponteiro para a nova malha(Mesh).</param> CarenResult CarenD2D1DCRenderTarget::CreateMesh([Out] ICarenD2D1Mesh^% Param_Out_Mesh) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. ID2D1Mesh* pOutMesh = NULL; //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateMesh(&pOutMesh); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface de saida. Param_Out_Mesh = gcnew CarenD2D1Mesh(); //Define o ponteiro da interface. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutMesh, Param_Out_Mesh)); Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Cria um ICarenD2D1RadialGradientBrush que contém os GradientStops especificados e tem a opacidade de transformação e base especificada. /// </summary> /// <param name="Param_PropriedadesRadialGradientBrush">O centro, a origem gradiente compensada, e raio x e raio y do gradiente do Brush.</param> /// <param name="Param_PropriedadesBrush">A opacidade de transformação e base do novo pincel(Brush).</param> /// <param name="Param_GradientStopCollection">Uma interface que contém uma coleção de estruturas D2D1_GRADIENT_STOP que descrevem as cores no Brush Gradient e suas localizações ao longo do gradiente.</param> /// <param name="Param_Out_RadialGradientBrush">Retorna uma interface ICarenD2D1RadialGradientBrush que contém um ponteiro para o novo Pincel(Brush).</param> CarenResult CarenD2D1DCRenderTarget::CreateRadialGradientBrush( CA_D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES^ Param_PropriedadesRadialGradientBrush, CA_D2D1_BRUSH_PROPERTIES^ Param_PropriedadesBrush, ICarenD2D1GradientStopCollection^ Param_GradientStopCollection, [Out] ICarenD2D1RadialGradientBrush^% Param_Out_RadialGradientBrush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES* pRadialGradientProps = NULL; D2D1_BRUSH_PROPERTIES* pBrushProps = NULL; ID2D1GradientStopCollection* pGradientStopCollection = NULL; ID2D1RadialGradientBrush* pOutRadialGradientBrush = NULL; //Converte as estruturas. pRadialGradientProps = Util.ConverterD2D1_RADIAL_GRADIENT_BRUSH_PROPERTIESManagedToUnmanaged(Param_PropriedadesRadialGradientBrush); pBrushProps = Util.ConverterD2D1_BRUSH_PROPERTIESManagedToUnmanaged(Param_PropriedadesBrush); //Recupera o ponteiro para a coleção de gradientes. Resultado = RecuperarPonteiroCaren(Param_GradientStopCollection, &pGradientStopCollection); //Sai do método em caso de erro SairOnError(Resultado); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateRadialGradientBrush(pRadialGradientProps, pBrushProps, pGradientStopCollection, &pOutRadialGradientBrush); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface de saida. Param_Out_RadialGradientBrush = gcnew CarenD2D1RadialGradientBrush(); //Define o ponteiro da interface. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutRadialGradientBrush, Param_Out_RadialGradientBrush)); Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pRadialGradientProps); DeletarEstruturaSafe(&pBrushProps); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um ICarenD2D1RadialGradientBrush que contém os GradientStops especificados, não tem transformação e tem uma opacidade base de 1.0. /// </summary> /// <param name="Param_PropriedadesRadialGradientBrush">O centro, a origem gradiente compensada, e raio x e raio y do gradiente do Brush.</param> /// <param name="Param_GradientStopCollection">Uma interface que contém uma coleção de estruturas D2D1_GRADIENT_STOP que descrevem as cores no Brush Gradient e suas localizações ao longo do gradiente.</param> /// <param name="Param_Out_RadialGradientBrush">Retorna uma interface ICarenD2D1RadialGradientBrush que contém um ponteiro para o novo Pincel(Brush).</param> CarenResult CarenD2D1DCRenderTarget::CreateRadialGradientBrush( CA_D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES^ Param_PropriedadesRadialGradientBrush, ICarenD2D1GradientStopCollection^ Param_GradientStopCollection, [Out] ICarenD2D1RadialGradientBrush^% Param_Out_RadialGradientBrush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES* pRadialGradientProps = NULL; ID2D1GradientStopCollection* pGradientStopCollection = NULL; ID2D1RadialGradientBrush* pOutRadialGradientBrush = NULL; //Converte a estrutura. pRadialGradientProps = Util.ConverterD2D1_RADIAL_GRADIENT_BRUSH_PROPERTIESManagedToUnmanaged(Param_PropriedadesRadialGradientBrush); //Recupera o ponteiro para a coleção de gradientes. Resultado = RecuperarPonteiroCaren(Param_GradientStopCollection, &pGradientStopCollection); //Sai do método em caso de erro SairOnError(Resultado); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateRadialGradientBrush(*pRadialGradientProps, pGradientStopCollection, &pOutRadialGradientBrush); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface de saida. Param_Out_RadialGradientBrush = gcnew CarenD2D1RadialGradientBrush(); //Define o ponteiro da interface. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutRadialGradientBrush, Param_Out_RadialGradientBrush)); Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Cria um ICarenD2D1Bitmap cujos dados são compartilhados com outro recurso. /// </summary> /// <param name="Param_Riid">O ID de interface do objeto que fornece os dados de origem.</param> /// <param name="Param_InterfaceDados">Uma ICarenD2D1Bitmap, ICarenDXGISurface ou uma ICarenWICBitmapLock que contém os dados para compartilhar com o novo ICarenD2D1Bitmap. </param> /// <param name="Param_PropriedadesBitmap">O formato de pixel e DPI do bitmap para criar. A DXGI_FORMAT parte do formato pixel deve corresponder à DXGI_FORMAT de dados ou o método falhará, mas os modos alfa /// não precisam coincidir. Para evitar uma incompatibilidade, você pode passar NULO ou o valor obtido da função auxiliar D2D1::PixelFormat. As configurações de DPI não têm que coincidir com as dos dados. /// Se o dpiX e o dpiY forem 0,0f, o DPI do alvo de renderização será usado.</param> /// <param name="Param_Out_Bitmap">Retorna uma interface ICarenD2D1Bitmap que contém um ponteiro para o novo bitmap.</param> CarenResult CarenD2D1DCRenderTarget::CreateSharedBitmap( String^ Param_Riid, ICaren^ Param_InterfaceDados, CA_D2D1_BITMAP_PROPERTIES^ Param_PropriedadesBitmap, [Out] ICarenD2D1Bitmap^% Param_Out_Bitmap) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; GUID Riid = GUID_NULL; PVOID pInterfaceDados = NULL; D2D1_BITMAP_PROPERTIES* pBitmapProps = NULL; //Poder ser NULO. ID2D1Bitmap* pOutBitmap = NULL; //Cria e converte os dados necessários. Riid = Util.CreateGuidFromString(Param_Riid); pBitmapProps = ObjetoGerenciadoValido(Param_PropriedadesBitmap) ? Util.ConverterD2D1_BITMAP_PROPERTIESManagedToUnmanaged(Param_PropriedadesBitmap) : NULL; //Recupera o ponteiro para a interface de dados. Resultado = RecuperarPonteiroCaren(Param_InterfaceDados, &pInterfaceDados); //Sai do método em caso de erro. SairOnError(Resultado); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateSharedBitmap(Riid, pInterfaceDados, pBitmapProps, &pOutBitmap); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface de saida. Param_Out_Bitmap = gcnew CarenD2D1Bitmap(); //Define o ponteiro da interface. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutBitmap, Param_Out_Bitmap)); Done:; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pBitmapProps); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um novo ICarenD2D1SolidColorBrush que tem a cor e a opacidade especificados. /// </summary> /// <param name="Param_Cor">Os valores vermelho, verde, azul e alfa da cor do pincel.</param> /// <param name="Param_PropriedadesBrush">A opacidade base do pincel.</param> /// <param name="Param_Out_SolidColorBrush">Retorna uma interface ICarenD2D1Bitmap que contém um ponteiro para o novo pincel(Brush).</param> CarenResult CarenD2D1DCRenderTarget::CreateSolidColorBrush( CA_D2D1_COLOR_F^ Param_Cor, CA_D2D1_BRUSH_PROPERTIES^ Param_PropriedadesBrush, [Out] ICarenD2D1SolidColorBrush^% Param_Out_SolidColorBrush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_COLOR_F* pColorF = NULL; D2D1_BRUSH_PROPERTIES* pBrushProps = NULL; ID2D1SolidColorBrush* pOutSolidColorBrush = NULL; //Converte as estruturas. pColorF = Util.ConverterD2D1_COLOR_FManagedToUnmanaged(Param_Cor); pBrushProps = Util.ConverterD2D1_BRUSH_PROPERTIESManagedToUnmanaged(Param_PropriedadesBrush); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateSolidColorBrush(pColorF, pBrushProps, &pOutSolidColorBrush); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface de saida. Param_Out_SolidColorBrush = gcnew CarenD2D1SolidColorBrush(); //Define o ponteiro da interface. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutSolidColorBrush, Param_Out_SolidColorBrush)); Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pColorF); DeletarEstruturaSafe(&pBrushProps); //Retorna o resultado. return Resultado; } /// <summary> /// Cria um novo ICarenD2D1SolidColorBrush que tem a cor especificada e uma opacidade base de 1.0f. /// </summary> /// <param name="Param_Cor">Os valores vermelho, verde, azul e alfa da cor do pincel(Brush).</param> /// <param name="Param_Out_SolidColorBrush">Retorna uma interface ICarenD2D1Bitmap que contém um ponteiro para o novo pincel(Brush).</param> CarenResult CarenD2D1DCRenderTarget::CreateSolidColorBrush( CA_D2D1_COLOR_F^ Param_Cor, [Out] ICarenD2D1SolidColorBrush^% Param_Out_SolidColorBrush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_COLOR_F* pColorF = NULL; ID2D1SolidColorBrush* pOutSolidColorBrush = NULL; //Converte a estrutura. pColorF = Util.ConverterD2D1_COLOR_FManagedToUnmanaged(Param_Cor); //Chama o método para realizar a operação. Hr = PonteiroTrabalho->CreateSolidColorBrush(*pColorF, &pOutSolidColorBrush); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Cria a interface de saida. Param_Out_SolidColorBrush = gcnew CarenD2D1SolidColorBrush(); //Define o ponteiro da interface. Libera a interface nativa em caso de erro. SairOnError(DefinirPonteiroInterface(pOutSolidColorBrush, Param_Out_SolidColorBrush)); Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pColorF); //Retorna o resultado. return Resultado; } /// <summary> /// Desenha o bitmap especificado depois de dimensioná-lo para o tamanho do retângulo especificado. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como DrawBitmap) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_Bitmap">O bitmap para renderizar.</param> /// <param name="Param_RetanguloDestino">O tamanho e a posição, em pixels independentes do dispositivo no espaço de coordenadas do alvo de renderização, da área para a qual o bitmap é desenhado. /// Se o retângulo não for bem ordenado, nada é desenhado, mas o alvo de renderização não entra em um estado de erro.</param> /// <param name="Param_Opacidade">Um valor entre 0,0f e 1,0f, inclusive, que especifica um valor de opacidade para aplicar ao bitmap; este valor é multiplicado em relação aos valores alfa do /// conteúdo do bitmap.</param> /// <param name="Param_InterpolationMode">O modo de interpolação a ser usado se o bitmap for dimensionado ou girado pela operação de desenho.</param> /// <param name="Param_RetanguloOrigem">O tamanho e a posição, em pixels independentes do dispositivo no espaço de coordenadas do bitmap, da área dentro do bitmap para desenhar.</param> CarenResult CarenD2D1DCRenderTarget::DrawBitmap( ICarenD2D1Bitmap^ Param_Bitmap, CA_D2D1_RECT_F^ Param_RetanguloDestino, float Param_Opacidade, CA_D2D1_BITMAP_INTERPOLATION_MODE Param_InterpolationMode, CA_D2D1_RECT_F^ Param_RetanguloOrigem) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; ID2D1Bitmap* pBitmapRender = NULL; D2D1_RECT_F* pRectDestinoF = NULL; D2D1_RECT_F* pRectOrigemF = NULL; D2D1_BITMAP_INTERPOLATION_MODE BitmapInterpolationMode = static_cast<D2D1_BITMAP_INTERPOLATION_MODE>(Param_InterpolationMode); //Recupera o ponteiro para o bitmap Resultado = RecuperarPonteiroCaren(Param_Bitmap, &pBitmapRender); //Sai do método em caso de erro SairOnError(Resultado); //Converte as estruturas. pRectDestinoF = Util.ConverterD2D1_RECT_FManagedToUnmanaged(Param_RetanguloDestino); pRectOrigemF = Util.ConverterD2D1_RECT_FManagedToUnmanaged(Param_RetanguloOrigem); //Chama o método para realizar a operação. PonteiroTrabalho->DrawBitmap(pBitmapRender, pRectDestinoF, Param_Opacidade, BitmapInterpolationMode, pRectOrigemF); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pRectDestinoF); DeletarEstruturaSafe(&pRectOrigemF); //Retorna o resultado. return Resultado; } /// <summary> /// Desenha o contorno(Outline) da elipse especificada usando o estilo de traçado especificado. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como DrawEllipse) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_Ellipse">A posição e o raio da elipse para desenhar, em pixels independentes do dispositivo.</param> /// <param name="Param_Brush">O pincel(Brush) usado para pintar o contorno da elipse.</param> /// <param name="Param_StrokeWidth">A largura do Stroke, em pixels independentes do dispositivo. O valor deve ser maior ou igual a 0,0f. Se este parâmetro não for especificado, ele será padrão /// para 1.0f. O golpe está centrado na linha.</param> /// <param name="Param_StrokeStyle">O estilo do Stroke para aplicar ao contorno(Outline) da elipse, ou NULO para pintar um traço sólido.</param> CarenResult CarenD2D1DCRenderTarget::DrawEllipse( CA_D2D1_ELLIPSE^ Param_Ellipse, ICarenD2D1Brush^ Param_Brush, float Param_StrokeWidth, ICarenD2D1StrokeStyle^ Param_StrokeStyle) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_ELLIPSE* pEllipse = NULL; ID2D1Brush* pBrush = NULL; ID2D1StrokeStyle* pStrokeStyle = NULL; //Pode ser NULO. //Recupera o ponteiro para o Brush. Resultado = RecuperarPonteiroCaren(Param_Brush, &pBrush); //Sai do método em caso de erro. SairOnError(Resultado); //Recupera o ponteiro para o Stroke se informado. if (ObjetoGerenciadoValido(Param_StrokeStyle)) { //Recupera o ponteiro. RecuperarPonteiroCaren(Param_StrokeStyle, &pStrokeStyle); } //Converte a estrutura. pEllipse = Util.ConverterD2D1_ELLIPSEManagedToUnmanaged(Param_Ellipse); //Chama o método para realizar a operação. PonteiroTrabalho->DrawEllipse(pEllipse, pBrush, Param_StrokeWidth, pStrokeStyle); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pEllipse); //Retorna o resultado. return Resultado; } /// <summary> /// Desenha o contorno da geometria especificada usando o estilo de traçado especificado. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como DrawGeometry) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_Geometria">A geometria para desenhar.</param> /// <param name="Param_Brush">O pincel(Brush) para pintar o traço(Stroke) da geometria.</param> /// <param name="Param_StrokeWidth">A largura do traçado, em pixels independentes do dispositivo. O valor deve ser maior ou igual a 0,0f. Se este parâmetro não for especificado, ele será padrão /// para 1.0f. O golpe está centrado na linha.</param> /// <param name="Param_StrokeStyle">O estilo de traçado(Stroke) para aplicar ao contorno(Outline) da geometria, ou NULO para pintar um traço(Stroke) sólido.</param> CarenResult CarenD2D1DCRenderTarget::DrawGeometry( ICarenD2D1Geometry^ Param_Geometria, ICarenD2D1Brush^ Param_Brush, float Param_StrokeWidth, ICarenD2D1StrokeStyle^ Param_StrokeStyle) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; ID2D1Geometry* pGeometryRender = NULL; ID2D1Brush* pBrush = NULL; ID2D1StrokeStyle* pStrokeStyle = NULL; //Pode ser NULO. //Recupera o ponteiro para a gemetria. Resultado = RecuperarPonteiroCaren(Param_Geometria, &pGeometryRender); //Sai do método em caso de erro. SairOnError(Resultado); //Recupera o ponteiro para o Brush. Resultado = RecuperarPonteiroCaren(Param_Brush, &pBrush); //Sai do método em caso de erro. SairOnError(Resultado); //Recupera o ponteiro para o Stroke se informado. if (ObjetoGerenciadoValido(Param_StrokeStyle)) { //Recupera o ponteiro. RecuperarPonteiroCaren(Param_StrokeStyle, &pStrokeStyle); } //Chama o método para realizar a operação. PonteiroTrabalho->DrawGeometry(pGeometryRender, pBrush, Param_StrokeWidth, pStrokeStyle); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Desenha os glifos(Glyph) especificados. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como DrawGlyphRun) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_BaseLineOrigin">A origem, em pixels independentes de dispositivos, da linha de base dos glifos(Glyph).</param> /// <param name="Param_GlyphRun">Os glifos(Glyph) para renderizar.</param> /// <param name="Param_ForegroundBrush">O pincel(Brush) usado para pintar os glifos(Glyph) especificados.</param> /// <param name="Param_MeasuringMode">Um valor que indica como as métricas do glifo(Glyph) são usadas para medir o texto quando ele é formatado. O valor padrão é DWRITE_MEASURING_MODE_NATURAL.</param> CarenResult CarenD2D1DCRenderTarget::DrawGlyphRun( CA_D2D1_POINT_2F^ Param_BaseLineOrigin, CA_DWRITE_GLYPH_RUN^ Param_GlyphRun, ICarenD2D1Brush^ Param_ForegroundBrush, CA_DWRITE_MEASURING_MODE Param_MeasuringMode) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_POINT_2F* pPoint = NULL; DWRITE_GLYPH_RUN* pGlyphRun = NULL; ID2D1Brush* pBrush = NULL; DWRITE_MEASURING_MODE DWriteMeasuringMode = static_cast<DWRITE_MEASURING_MODE>(Param_MeasuringMode); //Converte as estruturas. pPoint = Util.ConverterD2D1_POINT_2FManagedToUnmanaged(Param_BaseLineOrigin); pGlyphRun = Util.ConverterDWRITE_GLYPH_RUNManagedToUnmanaged(Param_GlyphRun); //Recupera o ponteiro para a interface do Brush Resultado = RecuperarPonteiroCaren(Param_ForegroundBrush, &pBrush); //Sai do método em caso de erro SairOnError(Resultado); //Chama o método para realizar a operação. PonteiroTrabalho->DrawGlyphRun(*pPoint, pGlyphRun, pBrush, DWriteMeasuringMode); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Libera a memória para as matrizes. DeletarEstruturaSafe(&pPoint); if (ObjetoValido(pGlyphRun)) { //Libera as matrizes internas da estrutura. DeletarMatrizUnidimensionalSafe(&pGlyphRun->glyphIndices); DeletarMatrizUnidimensionalSafe(&pGlyphRun->glyphAdvances); DeletarMatrizEstruturasSafe(&pGlyphRun->glyphOffsets); } DeletarEstruturaSafe(&pGlyphRun); //Retorna o resultado. return Resultado; } /// <summary> /// Desenha uma linha entre os pontos especificados usando o estilo de traçado especificado. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como DrawLine) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_Point0">O ponto de partida da linha, em pixels independentes de dispositivos.</param> /// <param name="Param_Point1">O ponto final da linha, em pixels independentes de dispositivos.</param> /// <param name="Param_Brush">O pincel(Brush) para pintar o traço da linha.</param> /// <param name="Param_StrokeWidth">A largura do Stroke, em pixels independentes do dispositivo.O valor deve ser maior ou igual a 0, 0f.Se esse parâmetro não for especificado, o padrão será 1.0f. /// O Stroke é centralizado na linha.</param> /// <param name="Param_StrokeStyle">O estilo de Stroke para pintar, ou NULO para pintar uma linha sólida.</param> CarenResult CarenD2D1DCRenderTarget::DrawLine( CA_D2D1_POINT_2F^ Param_Point0, CA_D2D1_POINT_2F^ Param_Point1, ICarenD2D1Brush^ Param_Brush, float Param_StrokeWidth, ICarenD2D1StrokeStyle^ Param_StrokeStyle) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_POINT_2F* pPoint0 = NULL; D2D1_POINT_2F* pPoint1 = NULL; ID2D1Brush* pBrush = NULL; ID2D1StrokeStyle* pStrokeStyle = NULL; //Converte as estruturas. pPoint0 = Util.ConverterD2D1_POINT_2FManagedToUnmanaged(Param_Point0); pPoint1 = Util.ConverterD2D1_POINT_2FManagedToUnmanaged(Param_Point1); //Recupera o ponteiro para a interface do Brush Resultado = RecuperarPonteiroCaren(Param_Brush, &pBrush); //Sai do método em caso de erro SairOnError(Resultado); //Recupera o ponteiro para o Stroke se informado. if (ObjetoGerenciadoValido(Param_StrokeStyle)) { //Recupera o ponteiro. RecuperarPonteiroCaren(Param_StrokeStyle, &pStrokeStyle); } //Chama o método para realizar a operação. PonteiroTrabalho->DrawLine(*pPoint0, *pPoint1, pBrush, Param_StrokeWidth, pStrokeStyle); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pPoint0); DeletarEstruturaSafe(&pPoint1); //Retorna o resultado. return Resultado; } /// <summary> /// Desenha o contorno(Outline) de um retângulo que tem as dimensões especificadas e o estilo de traçado. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como DrawRectangle) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_Rect">As dimensões do retângulo para desenhar, em pixels independentes do dispositivo.</param> /// <param name="Param_Brush">O pincel(Brush) usado para pintar o curso do retângulo.</param> /// <param name="Param_StrokeWidth">A largura do traçado(Stroke), em pixels independentes do dispositivo. O valor deve ser maior ou igual a 0,0f. Se esse parâmetro não for especificado, /// o padrão será 1.0f. O traço(Stroke) é centralizado na linha.</param> /// <param name="Param_StrokeStyle">O estilo do traço(Stroke) para pintar ou NULO para pintar um traçado sólido.</param> CarenResult CarenD2D1DCRenderTarget::DrawRectangle( CA_D2D1_RECT_F^ Param_Rect, ICarenD2D1Brush^ Param_Brush, float Param_StrokeWidth, ICarenD2D1StrokeStyle^ Param_StrokeStyle) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_RECT_F* pRectF = NULL; ID2D1Brush* pBrush = NULL; ID2D1StrokeStyle* pStrokeStyle = NULL; //Converte a estrutura. pRectF = Util.ConverterD2D1_RECT_FManagedToUnmanaged(Param_Rect); //Recupera o ponteiro para a interface do Brush Resultado = RecuperarPonteiroCaren(Param_Brush, &pBrush); //Sai do método em caso de erro SairOnError(Resultado); //Recupera o ponteiro para o Stroke se informado. if (ObjetoGerenciadoValido(Param_StrokeStyle)) { //Recupera o ponteiro. RecuperarPonteiroCaren(Param_StrokeStyle, &pStrokeStyle); } //Chama o método para realizar a operação. PonteiroTrabalho->DrawRectangle(pRectF, pBrush, Param_StrokeWidth, pStrokeStyle); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pRectF); //Retorna o resultado. return Resultado; } /// <summary> /// Desenha o contorno(Outline) do retângulo arredondado especificado usando o estilo de traçado especificado. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como DrawRoundedRectangle) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_RoundedRect">As dimensões do retângulo arredondado para desenhar, em pixels independentes do dispositivo.</param> /// <param name="Param_Brush">O pincel(Brush) usado para pintar o contorno do retângulo arredondado.</param> /// <param name="Param_StrokeWidth">A largura do traçado(Stroke), em pixels independentes do dispositivo. O valor deve ser maior ou igual a 0,0f. Se esse parâmetro não for especificado, o padrão /// será 1.0f. O traço(Stroke) é centralizado na linha.</param> /// <param name="Param_StrokeStyle">O estilo do traçado do retângulo arredondado, ou NULO para pintar um traço sólido. O valor padrão é NULO.</param> CarenResult CarenD2D1DCRenderTarget::DrawRoundedRectangle( CA_D2D1_ROUNDED_RECT^ Param_RoundedRect, ICarenD2D1Brush^ Param_Brush, float Param_StrokeWidth, ICarenD2D1StrokeStyle^ Param_StrokeStyle) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; D2D1_ROUNDED_RECT* pRoundedRect = NULL; ID2D1Brush* pBrush = NULL; ID2D1StrokeStyle* pStrokeStyle = NULL; //Converte a estrutura. pRoundedRect = Util.ConverterD2D1_ROUNDED_RECTManagedToUnmanaged(Param_RoundedRect); //Recupera o ponteiro para a interface do Brush Resultado = RecuperarPonteiroCaren(Param_Brush, &pBrush); //Sai do método em caso de erro SairOnError(Resultado); //Recupera o ponteiro para o Stroke se informado. if (ObjetoGerenciadoValido(Param_StrokeStyle)) { //Recupera o ponteiro. RecuperarPonteiroCaren(Param_StrokeStyle, &pStrokeStyle); } //Chama o método para realizar a operação. PonteiroTrabalho->DrawRoundedRectangle(pRoundedRect, pBrush, Param_StrokeWidth, pStrokeStyle); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pRoundedRect); //Retorna o resultado. return Resultado; } /// <summary> /// Desenha o texto especificado usando as informações de formato fornecidas por um objeto ICarenDWriteTextFormat. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como DrawText) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_Texto">Uma string de caracteres Unicode para desenhar.</param> /// <param name="Param_TamanhoTexto">O número de caracteres em (Param_Texto).</param> /// <param name="Param_TextFormat">Uma interface(ICarenDWriteTextFormat) que descreve a formatação de detalhes do texto para desenhar, como a fonte, o tamanho da fonte e a direção do fluxo.</param> /// <param name="Param_LayoutRect">O tamanho e a posição da área em que o texto é desenhado.</param> /// <param name="Param_DefaultFillBrush">O pincel(Brush) usado para pintar o texto.</param> /// <param name="Param_Opcoes">Um valor que indica se o texto deve ser encaixado nos limites do pixel e se o texto deve ser cortado no retângulo de layout. O valor padrão é D2D1_DRAW_TEXT_OPTIONS_NONE, /// o que indica que o texto deve ser encaixado nos limites do pixel e não deve ser cortado para o retângulo de layout.</param> /// <param name="Param_MeasuringMode">Um valor que indica como as métricas do glifo(Glyph) são usadas para medir o texto quando ele é formatado. O valor padrão é DWRITE_MEASURING_MODE_NATURAL.</param> CarenResult CarenD2D1DCRenderTarget::DrawText( String^ Param_Texto, UInt32 Param_TamanhoTexto, ICaren^ Param_TextFormat, CA_D2D1_RECT_F^ Param_LayoutRect, ICarenD2D1Brush^ Param_DefaultFillBrush, CA_D2D1_DRAW_TEXT_OPTIONS Param_Opcoes, CA_DWRITE_MEASURING_MODE Param_MeasuringMode) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. Utilidades Util; PWCHAR pTexto = NULL; IDWriteTextFormat* pTextFormat = NULL; D2D1_RECT_F* pLayoutRectF = NULL; ID2D1Brush* pBrush = NULL; D2D1_DRAW_TEXT_OPTIONS DrawTextOptions = static_cast<D2D1_DRAW_TEXT_OPTIONS>(Param_Opcoes); DWRITE_MEASURING_MODE MeasuringMode = static_cast<DWRITE_MEASURING_MODE>(Param_MeasuringMode); //Verifica se a string é valida if (!ObjetoGerenciadoValido(Param_Texto)) throw gcnew NullReferenceException("O texto a ser desenhado não pode ser NULO!"); //Converte a string para wchar pTexto = Util.ConverterStringToWCHAR(Param_Texto); //Recupera o ponteiro para a interface de formato do texto. Resultado = RecuperarPonteiroCaren(Param_TextFormat, &pTextFormat); //Sai do método em caso de erro SairOnError(Resultado); //Recupera o ponteiro para a interface do Brush Resultado = RecuperarPonteiroCaren(Param_DefaultFillBrush, &pBrush); //Sai do método em caso de erro SairOnError(Resultado); //Converte a estrutura. pLayoutRectF = Util.ConverterD2D1_RECT_FManagedToUnmanaged(Param_LayoutRect); //Chama o método para realizar a operação. PonteiroTrabalho->DrawText(pTexto, Param_TamanhoTexto, pTextFormat, pLayoutRectF, pBrush, DrawTextOptions, MeasuringMode); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Libera a memória para os dados. DeletarStringAllocatedSafe(&pTexto); DeletarEstruturaSafe(&pLayoutRectF); //Retorna o resultado. return Resultado; } /// <summary> /// Desenha o texto formatado descrito pelo objeto ICarenDWriteTextLayout especificado. /// Ao desenhar o mesmo texto repetidamente, o uso do método DrawTextLayout é mais eficiente do que usar o método DrawText porque o texto não precisa ser formatado e o layout processado a cada chamada. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como DrawTextLayout) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_Origem">O ponto, descrito em pixels independentes do dispositivo, no qual o canto superior esquerdo do texto descrito pelo (Param_TextLayout) é desenhado.</param> /// <param name="Param_TextLayout">Uma interface(ICarenDWriteTextLayout) com o texto formatado para desenhar. Quaisquer efeitos de desenho que não herdem do ID2D1Resource são ignorados. Se houver /// efeitos de desenho que herdam do ICarenD2D1Resource que não são pincéis, este método falhará e o alvo de renderização é colocado em um estado de erro.</param> /// <param name="Param_DefaultFillBrush">O pincel(Brush) usado para pintar qualquer texto no (Param_TextLayout) que ainda não tenha um pincel associado a ele como efeito de desenho (especificado pelo /// método ICarenDWriteTextLayout::SetDrawingEffect).</param> /// <param name="Param_Opcoes">Um valor que indica se o texto deve ser encaixado nos limites do pixel e se o texto deve ser cortado no retângulo de layout. O valor padrão é D2D1_DRAW_TEXT_OPTIONS_NONE, /// o que indica que o texto deve ser encaixado nos limites do pixel e não deve ser cortado para o retângulo de layout.</param> CarenResult CarenD2D1DCRenderTarget::DrawTextLayout( CA_D2D1_POINT_2F^ Param_Origem, ICaren^ Param_TextLayout, ICarenD2D1Brush^ Param_DefaultFillBrush, CA_D2D1_DRAW_TEXT_OPTIONS Param_Opcoes) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Variaveis a serem utilizadas. Utilidades Util; D2D1_POINT_2F* pPointOrigem = NULL; IDWriteTextLayout* pDwriterTextLayout = NULL; ID2D1Brush* pBrush = NULL; D2D1_DRAW_TEXT_OPTIONS DrawTextOptions = static_cast<D2D1_DRAW_TEXT_OPTIONS>(Param_Opcoes); //Recupera o ponteiro para a interface de formato do texto. Resultado = RecuperarPonteiroCaren(Param_TextLayout, &pDwriterTextLayout); //Sai do método em caso de erro SairOnError(Resultado); //Recupera o ponteiro para a interface do Brush Resultado = RecuperarPonteiroCaren(Param_DefaultFillBrush, &pBrush); //Sai do método em caso de erro SairOnError(Resultado); //Converte a estrutura. pPointOrigem = Util.ConverterD2D1_POINT_2FManagedToUnmanaged(Param_Origem); //Chama o método para realizar a operação. PonteiroTrabalho->DrawTextLayout(*pPointOrigem, pDwriterTextLayout, pBrush, DrawTextOptions); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pPointOrigem); //Retorna o resultado. return Resultado; } /// <summary> /// Termina as operações de desenho no alvo de renderização e indica o estado de erro atual e as tags associadas. /// </summary> /// <param name="Param_Out_Tag1">Quando este método retorna, contém a tag para operações de desenho que causaram erros ou 0 se não houver erros.</param> /// <param name="Param_Out_Tag2">Quando este método retorna, contém a tag para operações de desenho que causaram erros ou 0 se não houver erros.</param> CarenResult CarenD2D1DCRenderTarget::EndDraw( [Out] UInt64% Param_Out_Tag1, [Out] UInt64% Param_Out_Tag2) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. UINT64 OutTag1 = 0; UINT64 OutTag2 = 0; //Chama o método para realizar a operação. Hr = PonteiroTrabalho->EndDraw(&OutTag1, &OutTag2); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Define os valores nos parametros de saida. Param_Out_Tag1 = OutTag1; Param_Out_Tag2 = OutTag2; Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Pinta o interior da elipse especificada. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como FillEllipse) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_Ellipse">A posição e o raio, em pixels independentes do dispositivo, da elipse para pintar.</param> /// <param name="Param_Brush">O pincel(Brush) usado para pintar o interior da elipse.</param> CarenResult CarenD2D1DCRenderTarget::FillEllipse( CA_D2D1_ELLIPSE^ Param_Ellipse, ICarenD2D1Brush^ Param_Brush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Variaveis a serem utilizadas. Utilidades Util; D2D1_ELLIPSE* pEllipse = NULL; ID2D1Brush* pBrush = NULL; //Recupera o ponteiro para a interface do Brush Resultado = RecuperarPonteiroCaren(Param_Brush, &pBrush); //Sai do método em caso de erro SairOnError(Resultado); //Converte a estrutura. pEllipse = Util.ConverterD2D1_ELLIPSEManagedToUnmanaged(Param_Ellipse); //Chama o método para realizar a operação. PonteiroTrabalho->FillEllipse(pEllipse, pBrush); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pEllipse); //Retorna o resultado. return Resultado; } /// <summary> /// Pinta o interior da geometria especificada. /// Se o parâmetro (Param_OpacityBrush) não for NULO, o valor alfa de cada pixel da opacidade mapeadaBrush é usado para determinar a opacidade resultante de cada pixel correspondente da geometria. /// Apenas o valor alfa de cada cor no Brush é usado para este processamento; todas as outras informações de cores são ignoradas. /// O valor alfa especificado pelo Brush é multiplicado pelo valor alfa da geometria após a geometria ter sido pintada pelo Brush. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como FillGeometry) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_Geometria">A geometria para pintar.</param> /// <param name="Param_Brush">O pincel(Brush) para pintar o interior da geometria.</param> /// <param name="Param_OpacityBrush">A máscara de opacidade para aplicar à geometria, ou NULO para nenhuma máscara de opacidade. Se uma máscara de opacidade (o parâmetro Param_OpacityBrush) for especificada, /// o (Param_Brush) deve ser um ICarenD2D1BitmapBrush que tem seus modos x e y-extend definidos para D2D1_EXTEND_MODE_CLAMP.</param> CarenResult CarenD2D1DCRenderTarget::FillGeometry( ICarenD2D1Geometry^ Param_Geometria, ICarenD2D1Brush^ Param_Brush, ICarenD2D1Brush^ Param_OpacityBrush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Variaveis a serem utilizadas. ID2D1Geometry* pGeometry = NULL; ID2D1Brush* pBrush = NULL; ID2D1Brush* pOpacityBrush = NULL; //Pode ser NULO. //Recupera o ponteiro para a interface de Geometria. Resultado = RecuperarPonteiroCaren(Param_Geometria, &pGeometry); //Sai do método em caso de erro SairOnError(Resultado); //Recupera o ponteiro para a interface do Brush Resultado = RecuperarPonteiroCaren(Param_Brush, &pBrush); //Sai do método em caso de erro SairOnError(Resultado); //Verifica se forneceu o Brush de opacidade if (ObjetoGerenciadoValido(Param_OpacityBrush)) { //Recupera o ponteiro para a interface do Brush de opacidade. RecuperarPonteiroCaren(Param_OpacityBrush, &pOpacityBrush); } //Chama o método para realizar a operação. PonteiroTrabalho->FillGeometry(pGeometry, pBrush, pOpacityBrush); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Pinta o interior da malha especificada. /// O modo antialias atual do alvo de renderização deve ser D2D1_ANTIALIAS_MODE_ALIASED quando FillMesh é chamado. Para alterar o modo antialias do alvo de renderização, use o método SetAntialiasMode. /// FillMesh não espera uma ordem de enrolamento específica para os triângulos no ID2D1Mesh; tanto no sentido horário quanto no sentido anti-horário funcionará. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como FillMesh) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_Mesh">A malha para pintar.</param> /// <param name="Param_Brush">O pincel(Brush) para pintar a malha.</param> CarenResult CarenD2D1DCRenderTarget::FillMesh( ICarenD2D1Mesh^ Param_Mesh, ICarenD2D1Brush^ Param_Brush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Variaveis a serem utilizadas. ID2D1Mesh* pMesh = NULL; ID2D1Brush* pBrush = NULL; //Recupera o ponteiro para a interface do Mesh Resultado = RecuperarPonteiroCaren(Param_Mesh, &pMesh); //Sai do método em caso de erro SairOnError(Resultado); //Recupera o ponteiro para a interface do Brush Resultado = RecuperarPonteiroCaren(Param_Brush, &pBrush); //Sai do método em caso de erro SairOnError(Resultado); //Chama o método para realizar a operação. PonteiroTrabalho->FillMesh(pMesh, pBrush); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Aplica a máscara de opacidade descrita pelo bitmap especificado em um pincel e usa esse pincel para pintar uma região do alvo de renderização. /// Para que este método funcione corretamente, o alvo de renderização deve estar usando o modo D2D1_ANTIALIAS_MODE_ALIASED antialiasing. Você pode definir o modo antialiasing chamando o método /// ICarenD2D1RenderTarget::SetAntialiasMode método. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como FillOpacityMask) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_OpacityMask">A máscara de opacidade para aplicar no pincel. O valor alfa de cada pixel na região especificado pelo (Param_RetanguloOrigem) é multiplicado com o valor alfa do /// Brush após o pincel(Brush) ter sido mapeado para a área definida pelo (Param_RetanguloDestino).</param> /// <param name="Param_Brush">O pincel(Brush) usado para pintar a região do alvo de render especificado pelo (Param_RetanguloDestino).</param> /// <param name="Param_Content">O tipo de conteúdo que a máscara de opacidade contém. O valor é usado para determinar o espaço de cor no qual a máscara de opacidade é misturada. /// A partir do Windows 8, o D2D1_OPACITY_MASK_CONTENT não é necessário. Consulte o método ICarenD2D1DeviceContext::FillOpacityMask, que não tem parâmetro D2D1_OPACITY_MASK_CONTENT.</param> /// <param name="Param_RetanguloDestino">A região do alvo de renderização para pintar, em pixels independentes do dispositivo.</param> /// <param name="Param_RetanguloOrigem">A região do bitmap para usar como máscara de opacidade, em pixels independentes de dispositivos.</param> CarenResult CarenD2D1DCRenderTarget::FillOpacityMask( ICarenD2D1Bitmap^ Param_OpacityMask, ICarenD2D1Brush^ Param_Brush, CA_D2D1_OPACITY_MASK_CONTENT Param_Content, CA_D2D1_RECT_F^ Param_RetanguloDestino, CA_D2D1_RECT_F^ Param_RetanguloOrigem) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Variaveis a serem utilizadas. Utilidades Util; ID2D1Bitmap* pOpacityMaskBitmap = NULL; ID2D1Brush* pBrush = NULL; D2D1_OPACITY_MASK_CONTENT OpacityMask = static_cast<D2D1_OPACITY_MASK_CONTENT>(Param_Content); D2D1_RECT_F* pRectDestinoF = NULL; D2D1_RECT_F* pRectOrigemF = NULL; //Recupera o ponteiro para a interface do Opacity Mask Resultado = RecuperarPonteiroCaren(Param_OpacityMask, &pOpacityMaskBitmap); //Sai do método em caso de erro SairOnError(Resultado); //Recupera o ponteiro para a interface do Brush Resultado = RecuperarPonteiroCaren(Param_Brush, &pBrush); //Sai do método em caso de erro SairOnError(Resultado); //Converte as estruturas. pRectDestinoF = Util.ConverterD2D1_RECT_FManagedToUnmanaged(Param_RetanguloDestino); pRectOrigemF = Util.ConverterD2D1_RECT_FManagedToUnmanaged(Param_RetanguloOrigem); //Chama o método para realizar a operação. PonteiroTrabalho->FillOpacityMask(pOpacityMaskBitmap, pBrush, OpacityMask, pRectDestinoF, pRectOrigemF); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Libera a memória para as estruturas. DeletarEstruturaSafe(&pRectDestinoF); DeletarEstruturaSafe(&pRectOrigemF); //Retorna o resultado. return Resultado; } /// <summary> /// Pinta o interior do retângulo especificado. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como FillRectangle) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_Rect">A dimensão do retângulo para pintar, em pixels independentes do dispositivo.</param> /// <param name="Param_Brush">O pincel(Brush) usado para pintar o interior do retângulo.</param> CarenResult CarenD2D1DCRenderTarget::FillRectangle( CA_D2D1_RECT_F^ Param_Rect, ICarenD2D1Brush^ Param_Brush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Variaveis a serem utilizadas. Utilidades Util; D2D1_RECT_F* pRectF = NULL; ID2D1Brush* pBrush = NULL; //Recupera o ponteiro para a interface do Brush Resultado = RecuperarPonteiroCaren(Param_Brush, &pBrush); //Sai do método em caso de erro SairOnError(Resultado); //Converte a estrutura. pRectF = Util.ConverterD2D1_RECT_FManagedToUnmanaged(Param_Rect); //Chama o método para realizar a operação. PonteiroTrabalho->FillRectangle(pRectF, pBrush); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pRectF); //Retorna o resultado. return Resultado; } /// <summary> /// Pinta o interior do retângulo arredondado especificado. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como FillRoundedRectangle) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_Rect">As dimensões do retângulo arredondado para pintar, em pixels independentes do dispositivo.</param> /// <param name="Param_Brush">O pincel(Brush) usado para pintar o interior do retângulo arredondado.</param> CarenResult CarenD2D1DCRenderTarget::FillRoundedRectangle( CA_D2D1_ROUNDED_RECT^ Param_Rect, ICarenD2D1Brush^ Param_Brush) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Variaveis a serem utilizadas. Utilidades Util; D2D1_ROUNDED_RECT* pRoundedRectF = NULL; ID2D1Brush* pBrush = NULL; //Recupera o ponteiro para a interface do Brush Resultado = RecuperarPonteiroCaren(Param_Brush, &pBrush); //Sai do método em caso de erro SairOnError(Resultado); //Converte a estrutura. pRoundedRectF = Util.ConverterD2D1_ROUNDED_RECTManagedToUnmanaged(Param_Rect); //Chama o método para realizar a operação. PonteiroTrabalho->FillRoundedRectangle(pRoundedRectF, pBrush); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pRoundedRectF); //Retorna o resultado. return Resultado; } /// <summary> /// Executa todos os comandos de desenho pendentes. /// Este comando não libera o contexto do dispositivo Direct3D que está associado ao alvo de renderização. /// Chamar este método redefine o estado de erro do alvo de renderização. /// Se o método for bem sucedido, ele retorna SS_OK. Caso contrário, ele retorna um código de erro HRESULT e define Tag1 e Tag2 para as tags que estavam ativas quando o erro ocorreu. Se não ocorreu nenhum erro, /// este método define o estado de Tags de erro (0,0). /// </summary> /// <param name="Param_Out_Tag1">Quando este método retorna, contém a tag para operações de desenho que causaram erros ou 0 se não houver erros.</param> /// <param name="Param_Out_Tag2">Quando este método retorna, contém a tag para operações de desenho que causaram erros ou 0 se não houver erros.</param> CarenResult CarenD2D1DCRenderTarget::Flush( [Out] UInt64% Param_Out_Tag1, [Out] UInt64% Param_Out_Tag2) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. UINT64 OutTag1 = 0; UINT64 OutTag2 = 0; //Chama o método para realizar a operação. Hr = PonteiroTrabalho->Flush(&OutTag1, &OutTag2); //Processa o resultado da chamada. Resultado.ProcessarCodigoOperacao(Hr); //Verifica se obteve sucesso na operação. if (!Sucesso(static_cast<HRESULT>(Resultado.HResult))) { //Falhou ao realizar a operação. //Define o código na classe. Var_Glob_LAST_HRESULT = Hr; //Sai do método Sair; } //Define os valores nos parametros de saida. Param_Out_Tag1 = OutTag1; Param_Out_Tag2 = OutTag2; Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Recupera o modo antialiasing atual para operações de desenho sem texto. /// </summary> /// <param name="Param_Out_AntialiasMode">Retorna o modo antialiasing atual para operações de desenho sem texto.</param> void CarenD2D1DCRenderTarget::GetAntialiasMode([Out] CA_D2D1_ANTIALIAS_MODE% Param_Out_AntialiasMode) { //Variaveis a serem utilizadas. D2D1_ANTIALIAS_MODE OutAliasMode; //Chama o método para realizar a operação. OutAliasMode = PonteiroTrabalho->GetAntialiasMode(); //Define no parametro de saida. Param_Out_AntialiasMode = static_cast<CA_D2D1_ANTIALIAS_MODE>(OutAliasMode); } /// <summary> /// Retorne os pontos do alvo de renderização por polegada (DPI). /// </summary> /// <param name="Param_Out_DpiX">Retorna o DPI horizontal do alvo de renderização.</param> /// <param name="Param_Out_DpiY">Retorna o DPI vertical do alvo de renderização. </param> void CarenD2D1DCRenderTarget::GetDpi( [Out] float% Param_Out_DpiX, [Out] float% Param_Out_DpiY) { //Variaveis a serem utilizadas. FLOAT OutDpiX; FLOAT OutDpiY; //Chama o método para realizar a operação. PonteiroTrabalho->GetDpi(&OutDpiX, &OutDpiY); //Define nos parametros de saida. Param_Out_DpiX = OutDpiX; Param_Out_DpiY = OutDpiY; } /// <summary> /// Obtém o tamanho máximo, em unidades dependentes de dispositivos (pixels), de qualquer dimensão de bitmap suportada pelo alvo de renderização. /// Este método retorna o tamanho máximo da textura do dispositivo Direct3D. /// O renderizador de software e os dispositivos WARP retornam o valor de 16 megapixels (16* 1024 * 1024). Você pode criar uma textura Direct2D que é deste tamanho, mas não uma textura Direct3D que /// é deste tamanho. /// </summary> /// <param name="Param_Out_MaximumSize">Retorna o tamanho máximo, em pixels, de qualquer dimensão de bitmap suportada pelo alvo de renderização.</param> void CarenD2D1DCRenderTarget::GetMaximumBitmapSize([Out] UInt32% Param_Out_MaximumSize) { //Chama o método para realizar a operação. Param_Out_MaximumSize = PonteiroTrabalho->GetMaximumBitmapSize(); } /// <summary> /// Recupera o formato de pixel e o modo alfa do alvo de renderização. /// </summary> /// <param name="Param_Out_PixelFormat">Retorna o formato pixel e o modo alfa do alvo de renderização.</param> void CarenD2D1DCRenderTarget::GetPixelFormat([Out] CA_D2D1_PIXEL_FORMAT^% Param_Out_PixelFormat) { //Variaveis a serem utilizadas. Utilidades Util; D2D1_PIXEL_FORMAT OutPixelFormat; //Chama o método para realizar a operação. OutPixelFormat = PonteiroTrabalho->GetPixelFormat(); //Converte e define no parametro de saida. Param_Out_PixelFormat = Util.ConverterD2D1_PIXEL_FORMATUnmanagedToManaged(&OutPixelFormat); } /// <summary> /// Retorna o tamanho do alvo de renderização em pixels do dispositivo. /// </summary> /// <param name="Param_Out_PixelSize">Retorna tamanho do alvo de renderização em pixels do dispositivo.</param> void CarenD2D1DCRenderTarget::GetPixelSize([Out] CA_D2D1_SIZE_U^% Param_Out_PixelSize) { //Variaveis a serem utilizadas. Utilidades Util; D2D1_SIZE_U OutSizeU; //Chama o método para realizar a operação. OutSizeU = PonteiroTrabalho->GetPixelSize(); //Converte e define no parametro de saida. Param_Out_PixelSize = Util.ConverterD2D1_SIZE_UUnmanagedToManaged(&OutSizeU); } /// <summary> /// Retorna o tamanho do alvo de renderização em pixels independentes do dispositivo. /// </summary> /// <param name="Param_Out_Size">Retorna tamanho atual do alvo de renderização em pixels independentes do dispositivo.</param> void CarenD2D1DCRenderTarget::GetSize([Out] CA_D2D1_SIZE_F^% Param_Out_Size) { //Variaveis a serem utilizadas. Utilidades Util; D2D1_SIZE_F OutSizeF; //Chama o método para realizar a operação. OutSizeF = PonteiroTrabalho->GetSize(); //Converte e define no parametro de saida. Param_Out_Size = Util.ConverterD2D1_SIZE_FUnmanagedToManaged(&OutSizeF); } /// <summary> /// Obtém o rótulo(Tags) para operações de desenho subsequentes. /// </summary> /// <param name="Param_Out_Tag1">Retorna o primeiro rótulo para operações de desenho subsequentes.</param> /// <param name="Param_Out_Tag2">Retorna o segundo rótulo para operações de desenho subsequentes.</param> void CarenD2D1DCRenderTarget::GetTags( [Out] UInt64% Param_Out_Tag1, [Out] UInt64% Param_Out_Tag2) { //Variaveis a serem utilizadas. UINT64 OutTag1; UINT64 OutTag2; //Chama o método para realizar a operação. PonteiroTrabalho->GetTags(&OutTag1, &OutTag2); //Define nos parametros de saida. Param_Out_Tag1 = OutTag1; Param_Out_Tag2 = OutTag2; } /// <summary> /// Obtém o modo antialiasing atual para operações de desenho de texto e glifo(Glyph). /// </summary> /// <param name="Param_Out_TextAntialiasMode">Retorna o modo antialiasing atual para operações de desenho de texto e glifo(Glyph).</param> void CarenD2D1DCRenderTarget::GetTextAntialiasMode([Out] CA_D2D1_TEXT_ANTIALIAS_MODE% Param_Out_TextAntialiasMode) { //Variaveis a serem utilizadas. D2D1_TEXT_ANTIALIAS_MODE OutTextAliasMode; //Chama o método para realizar a operação. OutTextAliasMode = PonteiroTrabalho->GetTextAntialiasMode(); //Converte e define no parametro de saida. Param_Out_TextAntialiasMode = static_cast<CA_D2D1_TEXT_ANTIALIAS_MODE>(OutTextAliasMode); } /// <summary> /// Recupera as opções de renderização de texto atual do alvo. /// </summary> /// <param name="Param_Out_TextRenderingParams">Retorna a interface (IDWriteRenderingParams) que contém um ponteiro para as opções de renderização de texto atuais do destino. O usuário deve inicializar a interface antes de chamar este método.</param> void CarenD2D1DCRenderTarget::GetTextRenderingParams(ICaren^ Param_Out_TextRenderingParams) { //Variaveis a serem utilizadas. IDWriteRenderingParams* pDWriteRendParams = NULL; //Chama o método para realizar a operação. PonteiroTrabalho->GetTextRenderingParams(&pDWriteRendParams); //Define na interface de destino no parametro. Param_Out_TextRenderingParams->AdicionarPonteiro(pDWriteRendParams); } /// <summary> /// Obtém a transformação atual do alvo render. /// </summary> /// <param name="Param_Out_Transform">Retorna a transformação atual do alvo de renderização.</param> void CarenD2D1DCRenderTarget::GetTransform([Out] CA_D2D1_MATRIX_3X2_F^% Param_Out_Transform) { //Variaveis a serem utilizadas. Utilidades Util; D2D1_MATRIX_3X2_F OutMatrix = { }; //Chama o método para realizar a operação. PonteiroTrabalho->GetTransform(&OutMatrix); //Converte e define no parametro de saida. Param_Out_Transform = Util.ConverterD2D1_MATRIX_3X2_FUnmanagedToManaged(&OutMatrix); } /// <summary> /// Indica se o alvo de renderização suporta as propriedades especificadas. /// Este método não avalia as configurações de DPI especificadas pelo parâmetro (Param_ProppriedadesRenderTarget). /// </summary> /// <param name="Param_ProppriedadesRenderTarget">As propriedades de destino de renderização para testar.</param> /// <param name="Param_Out_Suporta">Retorna um valor Booleano TRUE se as propriedades de destino de renderização especificadas forem suportadas por este alvo de renderização; caso contrário, FALSO.</param> void CarenD2D1DCRenderTarget::IsSupported( CA_D2D1_RENDER_TARGET_PROPERTIES^ Param_ProppriedadesRenderTarget, [Out] Boolean% Param_Out_Suporta) { //Variaveis a serem utilizadas. Utilidades Util; D2D1_RENDER_TARGET_PROPERTIES* pRenderTargetProps = NULL; BOOL IsSuported = FALSE; //Converte a estrutura. pRenderTargetProps = Util.ConverterD2D1_RENDER_TARGET_PROPERTIESManagedToUnmanaged(Param_ProppriedadesRenderTarget); //Chama o método para realizar a operação. IsSuported = PonteiroTrabalho->IsSupported(pRenderTargetProps); //Define no parametro de saida. Param_Out_Suporta = IsSuported ? true : false; //Libera a memória para a estrutura. DeletarEstruturaSafe(&pRenderTargetProps); } /// <summary> /// Remove o último clipe alinhado ao eixo do alvo de renderização. Depois que este método é chamado, o clipe não é mais aplicado às operações de desenho subsequentes. /// PopAxisAlignedClip deve ser chamado uma vez para cada chamada para PushAxisAlignedClip. /// Um par PushAxisAlignedClip/PopAxisAlignedClip pode ocorrer ao redor ou dentro de um par PushLayer/PopLayer, mas pode não se sobrepor. Por exemplo, uma sequência PushAxisAlignedClip, PushLayer, PopLayer, /// PopAxisAlignedClip é válida, mas uma sequência PushAxisAlignedClip, PushLayer, PopAxisAlignedClip, PopLayer não é. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como PopAxisAlignedClip) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> void CarenD2D1DCRenderTarget::PopAxisAlignedClip() { //Chama o método para realizar a operação. PonteiroTrabalho->PopAxisAlignedClip(); } /// <summary> /// Interrompe o redirecionamento das operações de desenho para a camada especificada pela última chamada do PushLayer. /// Um PopLayer deve corresponder a uma chamada pushlayer anterior. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como PopLayer) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> void CarenD2D1DCRenderTarget::PopLayer() { //Chama o método para realizar a operação. PonteiroTrabalho->PopLayer(); } /// <summary> /// Especifica um retângulo ao qual todas as operações de desenho subsequentes são cortadas. /// O PushAxisAlignedClip e o PopAxisAlignedClip devem coincidir. Caso contrário, o estado de erro está definido. Para que o alvo de renderização continue recebendo novos comandos, você pode chamar /// Flush para limpar o erro. /// Um par PushAxisAlignedClip e PopAxisAlignedClip pode ocorrer em torno ou dentro de um PushLayer e PopLayer, mas não pode se sobrepor. Por exemplo, a sequência de PushAxisAlignedClip, PushLayer, /// PopLayer, PopAxisAlignedClip é válida, mas a sequência de PushAxisAlignedClip, PushLayer, PopAxisAlignedClip, PopLayer é inválida. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como PushAxisAlignedClip) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_ClipRect">O tamanho e a posição da área de recorte, em pixels independentes do dispositivo.</param> /// <param name="Param_AntialiasMode">O modo antialiasing que é usado para desenhar as bordas das retagens de clipe que têm limites de subpixel, e para misturar o clipe com o conteúdo da cena. A mistura /// é realizada uma vez quando o método PopAxisAlignedClip é chamado, e não se aplica a cada primitivo dentro da camada.</param> void CarenD2D1DCRenderTarget::PushAxisAlignedClip( CA_D2D1_RECT_F^ Param_ClipRect, CA_D2D1_ANTIALIAS_MODE Param_AntialiasMode) { //Variaveis a serem utilizadas. Utilidades Util; D2D1_RECT_F* pClipRect = NULL; D2D1_ANTIALIAS_MODE AliasMode = static_cast<D2D1_ANTIALIAS_MODE>(Param_AntialiasMode); //Converte a estrutura. pClipRect = Util.ConverterD2D1_RECT_FManagedToUnmanaged(Param_ClipRect); //Chama o método para realizar a operação. PonteiroTrabalho->PushAxisAlignedClip(pClipRect, AliasMode); //Libera a memória para a estrutura. DeletarEstruturaSafe(&pClipRect); } /// <summary> /// Adicione a camada especificada ao destino renderização para que ela receba todas as operações de desenho subsequentes até que o PopLayer seja chamado. /// O método PushLayer permite que um chamador comece a redirecionar a renderização para uma camada. Todas as operações de renderização são válidas em uma camada. A localização da camada é afetada /// pela transformação mundial definida na meta de renderização. /// Cada PushLayer deve ter uma chamada PopLayer correspondente. Se houver mais chamadas do PopLayer do que chamadas PushLayer, o alvo de renderização será colocado em um estado de erro. Se flush /// for chamado antes de todas as camadas pendentes serem estouradas, o alvo de renderização será colocado em um estado de erro e um erro será retornado. O estado de erro pode ser liberado por uma chamada para EndDraw. /// Este método não retorna um código de erro se falhar. Para determinar se uma operação de desenho (como PushLayer) falhou, verifique o resultado retornado pelo ICarenD2D1RenderTarget::EndDraw /// ou ICarenD2D1RenderTarget::Flush. /// </summary> /// <param name="Param_ParametrosLayer">Os limites de conteúdo, máscara geométrica, opacidade, máscara de opções de opções de opções antialiasing para a camada.</param> /// <param name="Param_Layer">A camada que recebe operações de desenho subsequentes. Começando pelo Windows 8, este parâmetro é opcional. Se uma camada não for especificada, o Direct2D gerencia /// automaticamente o recurso de camada.</param> void CarenD2D1DCRenderTarget::PushLayer( CA_D2D1_LAYER_PARAMETERS^ Param_ParametrosLayer, ICarenD2D1Layer^ Param_Layer) { //Variaveis a serem utilizadas. Utilidades Util; D2D1_LAYER_PARAMETERS* pLayerParams = NULL; ID2D1Layer* pLayer = NULL; //Pode ser NULO. //Converte a estrutura. pLayerParams = Util.ConverterD2D1_LAYER_PARAMETERSManagedToUnmanaged(Param_ParametrosLayer); //Verifica se forneceu a camada if (ObjetoGerenciadoValido(Param_Layer)) { //Recupera o ponteiro para a interface da Layer RecuperarPonteiroCaren(Param_Layer, &pLayer); } //Chama o método para realizar a operação. PonteiroTrabalho->PushLayer(pLayerParams, pLayer); //Libera a memória para a estrutura. DeletarEstruturaSafe(&pLayerParams); } /// <summary> /// Define o estado de desenho do alvo de renderização ao do ID2D1DrawingStateBlock especificado. /// </summary> /// <param name="Param_DrawingStateBlock">O novo estado de desenho do alvo render.</param> CarenResult CarenD2D1DCRenderTarget::RestoreDrawingState(ICarenD2D1DrawingStateBlock^ Param_DrawingStateBlock) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. ID2D1DrawingStateBlock* pStateBlock = NULL; //Recupera o ponteiro para a interface da StateBlock Resultado = RecuperarPonteiroCaren(Param_DrawingStateBlock, &pStateBlock); //Sai do método em caso de erro SairOnError(Resultado); //Chama o método para realizar a operação. PonteiroTrabalho->RestoreDrawingState(pStateBlock); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Salva o estado de desenho atual para o ID2D1DrawingStateBlock especificado. /// </summary> /// <param name="Param_DrawingStateBlock">Retorna uma interface para o estado de desenho atual do alvo de renderização. Este parâmetro deve ser inicializado antes de passá-lo para o método.</param> CarenResult CarenD2D1DCRenderTarget::SaveDrawingState(ICarenD2D1DrawingStateBlock^ Param_DrawingStateBlock) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Resultado COM. ResultadoCOM Hr = E_FAIL; //Variaveis a serem utilizadas. ID2D1DrawingStateBlock* pStateBlock = NULL; //Recupera o ponteiro para a interface da StateBlock Resultado = RecuperarPonteiroCaren(Param_DrawingStateBlock, &pStateBlock); //Sai do método em caso de erro SairOnError(Resultado); //Chama o método para realizar a operação. PonteiroTrabalho->SaveDrawingState(pStateBlock); //Define sucesso Resultado.AdicionarCodigo(ResultCode::SS_OK, true); Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Define o modo de antialiasing do alvo de renderização. O modo antialiasing aplica-se a todas as operações de desenho subsequentes, excluindo as operações de desenho de texto e glifo(Glyph). /// Para especificar o modo antialiasing para operações de texto e glifos(Glyph), use o método SetTextAntialiasMode. /// </summary> /// <param name="Param_AntialiasMode">O modo antialiasing para futuras operações de desenho.</param> void CarenD2D1DCRenderTarget::SetAntialiasMode(CA_D2D1_ANTIALIAS_MODE Param_AntialiasMode) { //Chama o método para realizar a operação. PonteiroTrabalho->SetAntialiasMode(static_cast<D2D1_ANTIALIAS_MODE>(Param_AntialiasMode)); } /// <summary> /// Define os pontos por polegada (DPI) do alvo de renderização. /// Este método especifica o mapeamento do espaço pixel para o espaço independente do dispositivo para o alvo de renderização. Se tanto o DpiX quanto o DpiY forem 0, o DPI do sistema de leitura /// de fábrica será escolhido. Se um parâmetro for zero e o outro não especificado, o DPI não será alterado. /// Para ICarenD2D1HwndRenderTarget, o DPI é padrão para o DPI mais recentemente do sistema de leitura de fábrica. O valor padrão para todas as outras metas de renderização é de 96 DPI. /// </summary> /// <param name="Param_DpiX">Um valor maior ou igual a zero que especifica o DPI horizontal do alvo de renderização.</param> /// <param name="Param_DpiY">Um valor maior ou igual a zero que especifica o DPI vertical do alvo de renderização.</param> void CarenD2D1DCRenderTarget::SetDpi( float Param_DpiX, float Param_DpiY) { //Chama o método para realizar a operação. PonteiroTrabalho->SetDpi(Param_DpiX, Param_DpiY); } /// <summary> /// Especifica um rótulo(Tag) para operações de desenho subsequentes. /// As etiquetas(Tags) especificadas por este método são impressas por mensagens de erro depuração. Se nenhuma tag for definida, o valor padrão de cada tag é 0. /// </summary> /// <param name="Param_Tag1">Um rótulo para aplicar às operações de desenho subsequentes.</param> /// <param name="Param_Tag2">Um rótulo para aplicar às operações de desenho subsequentes.</param> void CarenD2D1DCRenderTarget::SetTags( UInt64 Param_Tag1, UInt64 Param_Tag2) { //Chama o método para realizar a operação. PonteiroTrabalho->SetTags(Param_Tag1, Param_Tag2); } /// <summary> /// Especifica o modo antialiasing a ser usado para operações subsequentes de desenho de texto e glifo(Glyph). /// </summary> /// <param name="Param_TextAntialiasMode">O modo antialiasing para usar para operações subsequentes de desenho de texto e glifo(Glyph).</param> void CarenD2D1DCRenderTarget::SetTextAntialiasMode(CA_D2D1_TEXT_ANTIALIAS_MODE Param_TextAntialiasMode) { //Chama o método para realizar a operação. PonteiroTrabalho->SetTextAntialiasMode(static_cast<D2D1_TEXT_ANTIALIAS_MODE>(Param_TextAntialiasMode)); } /// <summary> /// Especifica as opções de renderização de texto a serem aplicadas a todas as operações subsequentes de desenho de texto e glifo(Glyph). /// Se as configurações especificadas por textRenderingParams forem incompatíveis com o modo antialiasing de texto do alvo de renderização (especificado por SetTextAntialiasMode), as operações /// subsequentes de desenho de texto e glifo(Glyph) falharão e colocarão o alvo de renderização em um estado de erro. /// </summary> /// <param name="Param_TextRenderingParams">Uma interface(IDWriteRenderingParams) para as opções de renderização de texto a serem aplicadas a todas as operações subsequentes de desenho /// de texto e glifoGlyph); NULO para limpar as opções atuais de renderização de texto.</param> CarenResult CarenD2D1DCRenderTarget::SetTextRenderingParams(ICaren^ Param_TextRenderingParams) { //Variavel a ser retornada. CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false); //Variaveis a serem utilizadas. IDWriteRenderingParams* pDwriteParams = NULL; //Recupera o ponteiro para a interface da StateBlock Resultado = RecuperarPonteiroCaren(Param_TextRenderingParams, &pDwriteParams); //Sai do método em caso de erro SairOnError(Resultado); //Chama o método para realizar a operação. PonteiroTrabalho->SetTextRenderingParams(pDwriteParams); Done:; //Retorna o resultado. return Resultado; } /// <summary> /// Aplica a transformação especificada ao alvo de renderização, substituindo a transformação existente. Todas as operações subsequentes de desenho ocorrem no espaço transformado. /// </summary> /// <param name="Param_Transform">A transformação para aplicar ao alvo de renderização.</param> void CarenD2D1DCRenderTarget::SetTransform(CA_D2D1_MATRIX_3X2_F^ Param_Transform) { //Variaveis a serem utilizadas. Utilidades Util; D2D1_MATRIX_3X2_F* pMatrix = NULL; //Converte a estrutura. pMatrix = Util.ConverterD2D1_MATRIX_3X2_FManagedToUnmanaged(Param_Transform); //Chama o método para realizar a operação. PonteiroTrabalho->SetTransform(pMatrix); //Libera a memória para a estrutura DeletarEstruturaSafe(&pMatrix); } // Métodos da interface proprietária(ICarenD2D1Resource) /// <summary> /// Recupera a fábrica associada a este recurso. /// </summary> /// <param name="Param_Out_Factory">Retorna uma interface(ICarenD2D1Factory) que contém um ponteiro para a fabrica que criou esse recurso. O usuário deve inicializar a interface antes de chamar este método.</param> void CarenD2D1DCRenderTarget::GetFactory(ICaren^ Param_Out_Factory) { //Variaveis a serem utilizadas. ID2D1Factory* pFactory = NULL; //Variavel de resultados. CarenResult Resultado; //Chama o método para realizar a operação. PonteiroTrabalho->GetFactory(&pFactory); //Verifica se o ponteiro é válido if (!ObjetoValido(pFactory)) Sair; //Adiciona o ponteiro na interface informada. Resultado = Param_Out_Factory->AdicionarPonteiro(pFactory); //Verifica o resultado da operação. if (Resultado.StatusCode != ResultCode::SS_OK) { //Libera o ponteiro recuperado anteriormente. pFactory->Release(); pFactory = NULL; //Chama uma execeção para indicar o erro. throw gcnew Exception(String::Format("Ocorreu uma falha ao definir o ponteiro nativo na interface gerenciada. Código de erro > {0}", Resultado.StatusCode)); } Done:; }
37.807153
399
0.781127
VictorSantosReis
fe9e31c97b5420d6eed4e7e97897fbb5b33a2e00
11,062
cpp
C++
Mac_M1/DiodeAmplifier/Source/PluginEditor.cpp
landonviator/DiodeAmplifier
c26d9096435dc653687912ca9409888037af4958
[ "MIT" ]
null
null
null
Mac_M1/DiodeAmplifier/Source/PluginEditor.cpp
landonviator/DiodeAmplifier
c26d9096435dc653687912ca9409888037af4958
[ "MIT" ]
null
null
null
Mac_M1/DiodeAmplifier/Source/PluginEditor.cpp
landonviator/DiodeAmplifier
c26d9096435dc653687912ca9409888037af4958
[ "MIT" ]
null
null
null
/* ============================================================================== This file contains the basic framework code for a JUCE plugin editor. ============================================================================== */ #include "PluginProcessor.h" #include "PluginEditor.h" //============================================================================== DiodeAmplifierAudioProcessorEditor::DiodeAmplifierAudioProcessorEditor (DiodeAmplifierAudioProcessor& p) : AudioProcessorEditor (&p), audioProcessor (p) { shadowProperties.radius = 24; shadowProperties.offset = juce::Point<int> (-1, 12); shadowProperties.colour = juce::Colours::black.withAlpha(0.25f); dialShadow.setShadowProperties (shadowProperties); sliders.reserve(6); sliders = { &inputSlider, &driveSlider, &lowSlider, &midSlider, &highSlider, &outputSlider }; labels.reserve(6); labels = { &inputLabel, &driveLabel, &lowLabel, &midLabel, &highLabel, &outputLabel }; labelTexts.reserve(6); labelTexts = { inputSliderLabelText, driveSliderLabelText, lowSliderLabelText, midSliderLabelText, highSliderLabelText, outputSliderLabelText }; inputSlider.setLookAndFeel(&customDial); driveSlider.setLookAndFeel(&customDial); outputSlider.setLookAndFeel(&customDial); lowSlider.setLookAndFeel(&customDial2); midSlider.setLookAndFeel(&customDial2); highSlider.setLookAndFeel(&customDial2); for (auto i = 0; i < sliders.size(); i++) { addAndMakeVisible(sliders[i]); sliders[i]->setSliderStyle(juce::Slider::SliderStyle::RotaryVerticalDrag); sliders[i]->setTextBoxStyle(juce::Slider::TextBoxBelow, false, 64, 32); sliders[i]->setColour(0x1001400, juce::Colour::fromFloatRGBA(1, 1, 1, 0.5f)); sliders[i]->setColour(0x1001700, juce::Colour::fromFloatRGBA(1, 1, 1, 0.0f)); sliders[i]->setColour(0x1001500, juce::Colour::fromFloatRGBA(0, 0, 0, 0.25f)); sliders[i]->setComponentEffect(&dialShadow); sliders[i]->setRange(-24.0, 24.0, 0.25); sliders[i]->setDoubleClickReturnValue(true, 0.0); } driveSlider.setRange(0.0, 10.0, 0.25); lowSlider.setRange(-6.0, 6.0, 0.25); midSlider.setRange(-6.0, 6.0, 0.25); highSlider.setRange(-6.0, 6.0, 0.25); inputSliderAttach = std::make_unique<juce::AudioProcessorValueTreeState::SliderAttachment>(audioProcessor.treeState, inputGainSliderId, inputSlider); driveSliderAttach = std::make_unique<juce::AudioProcessorValueTreeState::SliderAttachment>(audioProcessor.treeState, driveSliderId, driveSlider); lowSliderAttach = std::make_unique<juce::AudioProcessorValueTreeState::SliderAttachment>(audioProcessor.treeState, lowSliderId, lowSlider); midSliderAttach = std::make_unique<juce::AudioProcessorValueTreeState::SliderAttachment>(audioProcessor.treeState, midSliderId, midSlider); highSliderAttach = std::make_unique<juce::AudioProcessorValueTreeState::SliderAttachment>(audioProcessor.treeState, highSliderId, highSlider); outputSliderAttach = std::make_unique<juce::AudioProcessorValueTreeState::SliderAttachment>(audioProcessor.treeState, outputGainSliderId, outputSlider); for (auto i = 0; i < labels.size(); i++) { addAndMakeVisible(labels[i]); labels[i]->setText(labelTexts[i], juce::dontSendNotification); labels[i]->setJustificationType(juce::Justification::centred); labels[i]->setColour(0x1000281, juce::Colour::fromFloatRGBA(1, 1, 1, 0.25f)); labels[i]->attachToComponent(sliders[i], false); } addAndMakeVisible(windowBorder); windowBorder.setText("Ignorant Diode Amplifier"); windowBorder.setColour(0x1005400, juce::Colour::fromFloatRGBA(1, 1, 1, 0.25f)); windowBorder.setColour(0x1005410, juce::Colour::fromFloatRGBA(1, 1, 1, 0.25f)); addAndMakeVisible(&brightButton); brightButton.setButtonText("Bright"); brightButton.setClickingTogglesState(true); brightButtonAttach = std::make_unique<juce::AudioProcessorValueTreeState::ButtonAttachment>(audioProcessor.treeState, brightId, brightButton); brightButton.setColour(0x1000100, juce::Colours::whitesmoke.darker(1.0).withAlpha(1.0f)); brightButton.setColour(0x1000c00, juce::Colour::fromFloatRGBA(0, 0, 0, 0)); brightButton.setColour(0x1000101, juce::Colours::lightgoldenrodyellow.darker(0.2f)); brightButton.setColour(0x1000102, juce::Colours::black.brighter(0.1)); brightButton.setColour(0x1000103, juce::Colours::black.brighter(0.1)); addAndMakeVisible(&cabButton); cabButton.setButtonText("Load IR"); cabButton.setColour(0x1000100, juce::Colours::whitesmoke.darker(1.0).withAlpha(1.0f)); cabButton.setColour(0x1000c00, juce::Colour::fromFloatRGBA(0, 0, 0, 0)); cabButton.setColour(0x1000101, juce::Colours::lightgoldenrodyellow.darker(0.2f)); cabButton.setColour(0x1000102, juce::Colours::black.brighter(0.1)); cabButton.setColour(0x1000103, juce::Colours::black.brighter(0.1)); addAndMakeVisible(&cabToggleButton); cabToggleButton.setClickingTogglesState(true); cabToggleButton.setToggleState(true, juce::dontSendNotification); cabToggleButton.setButtonText("Cab On"); cabToggleAttach = std::make_unique<juce::AudioProcessorValueTreeState::ButtonAttachment>(audioProcessor.treeState, cabId, cabToggleButton); cabToggleButton.setColour(0x1000100, juce::Colours::whitesmoke.darker(1.0).withAlpha(1.0f)); cabToggleButton.setColour(0x1000c00, juce::Colour::fromFloatRGBA(0, 0, 0, 0)); cabToggleButton.setColour(0x1000101, juce::Colours::lightgoldenrodyellow.darker(0.2f)); cabToggleButton.setColour(0x1000102, juce::Colours::black.brighter(0.1)); cabToggleButton.setColour(0x1000103, juce::Colours::black.brighter(0.1)); addAndMakeVisible(&resetIRButton); resetIRButton.setButtonText("Reset IR"); resetIRButton.setColour(0x1000100, juce::Colours::whitesmoke.darker(1.0).withAlpha(1.0f)); resetIRButton.setColour(0x1000c00, juce::Colour::fromFloatRGBA(0, 0, 0, 0)); resetIRButton.setColour(0x1000101, juce::Colours::lightgoldenrodyellow.darker(0.2f)); resetIRButton.setColour(0x1000102, juce::Colours::black.brighter(0.1)); resetIRButton.setColour(0x1000103, juce::Colours::black.brighter(0.1)); setCabButtonProps(); setSize (711, 500); } DiodeAmplifierAudioProcessorEditor::~DiodeAmplifierAudioProcessorEditor() { inputSlider.setLookAndFeel(nullptr); driveSlider.setLookAndFeel(nullptr); lowSlider.setLookAndFeel(nullptr); midSlider.setLookAndFeel(nullptr); highSlider.setLookAndFeel(nullptr); outputSlider.setLookAndFeel(nullptr); } //============================================================================== void DiodeAmplifierAudioProcessorEditor::paint (juce::Graphics& g) { //Image layer from Illustrator pluginBackground = juce::ImageCache::getFromMemory(BinaryData::PluginBackground1_png, BinaryData::PluginBackground1_pngSize); g.drawImageWithin(pluginBackground, 0, 0, AudioProcessorEditor::getWidth(), AudioProcessorEditor::getHeight(), juce::RectanglePlacement::stretchToFit); // Background dark-maker // juce::Rectangle<float> backgroundDarker; // backgroundDarker.setBounds(0, 0, AudioProcessorEditor::getWidth(), AudioProcessorEditor::getHeight()); // g.setColour(juce::Colour::fromFloatRGBA(0.09f, 0.10f, 0.12f, 0.65f)); // g.fillRect(backgroundDarker); // Header rectangle juce::Rectangle<float> header; header.setBounds(0, 0, AudioProcessorEditor::getWidth(), AudioProcessorEditor::getHeight() * 0.13f); g.setColour(juce::Colours::black.withAlpha(0.5f)); g.fillRect(header); // Set header text g.setFont (16.0f); g.setColour (juce::Colours::white.withAlpha(0.25f)); g.drawFittedText ("Algorithms by Landon Viator", 12, AudioProcessorEditor::getHeight() * 0.05, AudioProcessorEditor::getWidth(), AudioProcessorEditor::getHeight(), juce::Justification::topLeft, 1); // Logo mLogo = juce::ImageCache::getFromMemory(BinaryData::landon5504_png, BinaryData::landon5504_pngSize); g.drawImageWithin(mLogo, AudioProcessorEditor::getWidth() * 0.4f, AudioProcessorEditor::getHeight() * 0.025, AudioProcessorEditor::getHeight() * 0.08f * 4.58, AudioProcessorEditor::getHeight() * 0.08f, juce::RectanglePlacement::centred); } void DiodeAmplifierAudioProcessorEditor::resized() { //Master bounds object juce::Rectangle<int> bounds = getLocalBounds(); auto sliderSize {3.5}; //first column of gui juce::FlexBox flexboxColumnOne; flexboxColumnOne.flexDirection = juce::FlexBox::Direction::row; flexboxColumnOne.flexWrap = juce::FlexBox::Wrap::noWrap; flexboxColumnOne.alignContent = juce::FlexBox::AlignContent::center; juce::Array<juce::FlexItem> itemArrayColumnOne; itemArrayColumnOne.add(juce::FlexItem(bounds.getWidth() / sliderSize, bounds.getHeight() / sliderSize, inputSlider).withMargin(juce::FlexItem::Margin(0, 0, 0, 0))); itemArrayColumnOne.add(juce::FlexItem(bounds.getWidth() / sliderSize, bounds.getHeight() / sliderSize, driveSlider).withMargin(juce::FlexItem::Margin(0, 0, 0, 0))); itemArrayColumnOne.add(juce::FlexItem(bounds.getWidth() / sliderSize, bounds.getHeight() / sliderSize, outputSlider).withMargin(juce::FlexItem::Margin(0, 0, 0, 0))); flexboxColumnOne.items = itemArrayColumnOne; flexboxColumnOne.performLayout(bounds.removeFromTop(bounds.getHeight() - 72)); /* ============================================================================ */ lowSlider.setBounds(inputSlider.getX(), inputSlider.getY() + inputSlider.getHeight() + 32, inputSlider.getWidth(), inputSlider.getHeight()); midSlider.setBounds(driveSlider.getX(), driveSlider.getY() + driveSlider.getHeight() + 32, driveSlider.getWidth(), driveSlider.getHeight()); highSlider.setBounds(outputSlider.getX(), outputSlider.getY() + outputSlider.getHeight() + 32, outputSlider.getWidth(), outputSlider.getHeight()); brightButton.setBounds(outputSlider.getX() + outputSlider.getWidth() - 24, outputSlider.getY() * 1.5, 72, 32); cabButton.setBounds(brightButton.getX(), brightButton.getY() + brightButton.getHeight(), 72, 32); cabToggleButton.setBounds(cabButton.getX(), cabButton.getY() + cabButton.getHeight(), 72, 32); resetIRButton.setBounds(cabToggleButton.getX(), cabToggleButton.getY() + cabToggleButton.getHeight(), 72, 32); // Window border bounds windowBorder.setBounds ( 16, AudioProcessorEditor::getHeight() * 0.16, AudioProcessorEditor::getWidth() * 0.95, AudioProcessorEditor::getHeight() * .8 ); }
54.492611
241
0.683782
landonviator
fea407a7ea7b167aa1bbb49a184b5b7bd70a91b5
29,001
ipp
C++
generators/pd/templates/thrift-src/p4_pd_rpc_server.ipp
liusheng198933/PI
124ac3c45df72a4b93eee1664266e923f4b69545
[ "Apache-2.0" ]
1
2019-01-15T10:47:28.000Z
2019-01-15T10:47:28.000Z
generators/pd/templates/thrift-src/p4_pd_rpc_server.ipp
liusheng198933/PI
124ac3c45df72a4b93eee1664266e923f4b69545
[ "Apache-2.0" ]
null
null
null
generators/pd/templates/thrift-src/p4_pd_rpc_server.ipp
liusheng198933/PI
124ac3c45df72a4b93eee1664266e923f4b69545
[ "Apache-2.0" ]
null
null
null
//:: pd_prefix = "p4_pd_" + p4_prefix + "_" //:: api_prefix = p4_prefix + "_" #include "p4_prefix.h" #include <iostream> #include <string.h> #include "pd/pd.h" #include <list> #include <map> #include <mutex> #include <thread> #include <condition_variable> #include <future> using namespace ::p4_pd_rpc; using namespace ::res_pd_rpc; namespace { __attribute__ ((unused)) void bytes_meter_spec_thrift_to_pd( const ${api_prefix}bytes_meter_spec_t &meter_spec, p4_pd_bytes_meter_spec_t *pd_meter_spec) { pd_meter_spec->cir_kbps = meter_spec.cir_kbps; pd_meter_spec->cburst_kbits = meter_spec.cburst_kbits; pd_meter_spec->pir_kbps = meter_spec.pir_kbps; pd_meter_spec->pburst_kbits = meter_spec.pburst_kbits; pd_meter_spec->meter_type = meter_spec.color_aware ? PD_METER_TYPE_COLOR_AWARE : PD_METER_TYPE_COLOR_UNAWARE; } __attribute__ ((unused)) void packets_meter_spec_thrift_to_pd( const ${api_prefix}packets_meter_spec_t &meter_spec, p4_pd_packets_meter_spec_t *pd_meter_spec) { pd_meter_spec->cir_pps = meter_spec.cir_pps; pd_meter_spec->cburst_pkts = meter_spec.cburst_pkts; pd_meter_spec->pir_pps = meter_spec.pir_pps; pd_meter_spec->pburst_pkts = meter_spec.pburst_pkts; pd_meter_spec->meter_type = meter_spec.color_aware ? PD_METER_TYPE_COLOR_AWARE : PD_METER_TYPE_COLOR_UNAWARE; } __attribute__ ((unused)) void bytes_meter_spec_pd_to_thrift( const p4_pd_bytes_meter_spec_t &pd_meter_spec, ${api_prefix}bytes_meter_spec_t *meter_spec) { meter_spec->cir_kbps = pd_meter_spec.cir_kbps; meter_spec->cburst_kbits = pd_meter_spec.cburst_kbits; meter_spec->pir_kbps = pd_meter_spec.pir_kbps; meter_spec->pburst_kbits = pd_meter_spec.pburst_kbits; meter_spec->color_aware = (pd_meter_spec.meter_type == PD_METER_TYPE_COLOR_AWARE); } __attribute__ ((unused)) void packets_meter_spec_pd_to_thrift( const p4_pd_packets_meter_spec_t &pd_meter_spec, ${api_prefix}packets_meter_spec_t *meter_spec) { meter_spec->cir_pps = pd_meter_spec.cir_pps; meter_spec->cburst_pkts = pd_meter_spec.cburst_pkts; meter_spec->pir_pps = pd_meter_spec.pir_pps; meter_spec->pburst_pkts = pd_meter_spec.pburst_pkts; meter_spec->color_aware = (pd_meter_spec.meter_type == PD_METER_TYPE_COLOR_AWARE); } } // namespace //:: def get_direct_parameter_specs(t, api_prefix): //:: specs = [] //:: if t.direct_meters: //:: m = t.direct_meters //:: if m.unit == m.MeterUnit.PACKETS: //:: specs += ["const " + api_prefix + "packets_meter_spec_t &" + m.name + "_spec"] //:: else: //:: specs += ["const " + api_prefix + "bytes_meter_spec_t &" + m.name + "_spec"] //:: #endif //:: #endif //:: return specs //:: #enddef class ${p4_prefix}Handler : virtual public ${p4_prefix}If { private: class CbWrap { CbWrap() {} int wait() { std::unique_lock<std::mutex> lock(cb_mutex); while(cb_status == 0) { cb_condvar.wait(lock); } return 0; } void notify() { std::unique_lock<std::mutex> lock(cb_mutex); assert(cb_status == 0); cb_status = 1; cb_condvar.notify_one(); } static void cb_fn(int device_id, void *cookie) { (void) device_id; CbWrap *inst = static_cast<CbWrap *>(cookie); inst->notify(); } CbWrap(const CbWrap &other) = delete; CbWrap &operator=(const CbWrap &other) = delete; CbWrap(CbWrap &&other) = delete; CbWrap &operator=(CbWrap &&other) = delete; private: std::mutex cb_mutex{}; std::condition_variable cb_condvar{}; int cb_status{0}; }; public: ${p4_prefix}Handler() { } // Table entry add functions //:: for t_name, t in tables.items(): //:: t_type = t.type_ //:: if t_type != TableType.SIMPLE: continue //:: t_name = get_c_name(t_name) //:: match_type = t.match_type //:: has_match_spec = len(t.key) > 0 //:: for a_name, a in t.actions.items(): //:: a_name = get_c_name(a_name) //:: has_action_spec = len(a.runtime_data) > 0 //:: params = ["const SessionHandle_t sess_hdl", //:: "const DevTarget_t &dev_tgt"] //:: if has_match_spec: //:: params += ["const " + api_prefix + t_name + "_match_spec_t &match_spec"] //:: #endif //:: if match_type in {MatchType.TERNARY, MatchType.RANGE}: //:: params += ["const int32_t priority"] //:: #endif //:: if has_action_spec: //:: params += ["const " + api_prefix + a_name + "_action_spec_t &action_spec"] //:: #endif //:: if t.support_timeout: //:: params += ["const int32_t ttl"] //:: #endif //:: params += get_direct_parameter_specs(t, api_prefix) //:: param_str = ", ".join(params) //:: name = t_name + "_table_add_with_" + a_name //:: pd_name = pd_prefix + name EntryHandle_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; //:: if has_match_spec: ${pd_prefix}${t_name}_match_spec_t pd_match_spec; //:: match_params = gen_match_params(t.key) //:: for name, width in match_params: //:: name = get_c_name(name) //:: if width <= 4: pd_match_spec.${name} = match_spec.${name}; //:: else: memcpy(pd_match_spec.${name}, match_spec.${name}.c_str(), ${width}); //:: #endif //:: #endfor //:: #endif //:: if has_action_spec: ${pd_prefix}${a_name}_action_spec_t pd_action_spec; //:: action_params = gen_action_params(a.runtime_data) //:: for name, _, width in action_params: //:: name = get_c_name(name) //:: if width <= 4: pd_action_spec.${name} = action_spec.${name}; //:: else: memcpy(pd_action_spec.${name}, action_spec.${name}.c_str(), ${width}); //:: #endif //:: #endfor //:: #endif p4_pd_entry_hdl_t pd_entry; //:: pd_params = ["sess_hdl", "pd_dev_tgt"] //:: if has_match_spec: //:: pd_params += ["&pd_match_spec"] //:: #endif //:: if match_type in {MatchType.TERNARY, MatchType.RANGE}: //:: pd_params += ["priority"] //:: #endif //:: if has_action_spec: //:: pd_params += ["&pd_action_spec"] //:: #endif //:: if t.support_timeout: //:: pd_params += ["(uint32_t)ttl"] //:: #endif //:: # direct parameter specs //:: if t.direct_meters: //:: m = t.direct_meters //:: unit_name = MeterUnit.to_str(m.unit) p4_pd_${unit_name}_meter_spec_t pd_${m.name}_spec; ${unit_name}_meter_spec_thrift_to_pd(${m.name}_spec, &pd_${m.name}_spec); //:: pd_params += ["&pd_" + m.name + "_spec"] //:: #endif //:: pd_params += ["&pd_entry"] //:: pd_param_str = ", ".join(pd_params) ${pd_name}(${pd_param_str}); return pd_entry; } //:: #endfor //:: #endfor // Table entry modify functions //:: for t_name, t in tables.items(): //:: t_type = t.type_ //:: if t_type != TableType.SIMPLE: continue //:: t_name = get_c_name(t_name) //:: for a_name, a in t.actions.items(): //:: a_name = get_c_name(a_name) //:: has_action_spec = len(a.runtime_data) > 0 //:: params = ["const SessionHandle_t sess_hdl", //:: "const int8_t dev_id", //:: "const EntryHandle_t entry"] //:: if has_action_spec: //:: params += ["const " + api_prefix + a_name + "_action_spec_t &action_spec"] //:: #endif //:: params += get_direct_parameter_specs(t, api_prefix) //:: param_str = ", ".join(params) //:: name = t_name + "_table_modify_with_" + a_name //:: pd_name = pd_prefix + name EntryHandle_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; //:: if has_action_spec: ${pd_prefix}${a_name}_action_spec_t pd_action_spec; //:: action_params = gen_action_params(a.runtime_data) //:: for name, _, width in action_params: //:: name = get_c_name(name) //:: if width <= 4: pd_action_spec.${name} = action_spec.${name}; //:: else: memcpy(pd_action_spec.${name}, action_spec.${name}.c_str(), ${width}); //:: #endif //:: #endfor //:: #endif //:: pd_params = ["sess_hdl", "dev_id", "entry"] //:: if has_action_spec: //:: pd_params += ["&pd_action_spec"] //:: #endif //:: # direct parameter specs //:: if t.direct_meters: //:: m = t.direct_meters //:: unit_name = MeterUnit.to_str(m.unit) p4_pd_${unit_name}_meter_spec_t pd_${m.name}_spec; ${unit_name}_meter_spec_thrift_to_pd(${m.name}_spec, &pd_${m.name}_spec); //:: pd_params += ["&pd_" + m.name + "_spec"] //:: #endif //:: pd_param_str = ", ".join(pd_params) return ${pd_name}(${pd_param_str}); } //:: #endfor //:: #endfor // Table entry delete functions //:: for t_name, t in tables.items(): //:: t_type = t.type_ //:: t_name = get_c_name(t_name) //:: name = t_name + "_table_delete" //:: pd_name = pd_prefix + name //:: params = ["const SessionHandle_t sess_hdl", //:: "const int8_t dev_id", //:: "const EntryHandle_t entry"] //:: param_str = ", ".join(params) int32_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; return ${pd_name}(sess_hdl, dev_id, entry); } //:: #endfor // set default action //:: for t_name, t in tables.items(): //:: t_type = t.type_ //:: if t_type != TableType.SIMPLE: continue //:: t_name = get_c_name(t_name) //:: for a_name, a in t.actions.items(): //:: a_name = get_c_name(a_name) //:: has_action_spec = len(a.runtime_data) > 0 //:: params = ["const SessionHandle_t sess_hdl", //:: "const DevTarget_t &dev_tgt"] //:: if has_action_spec: //:: params += ["const " + api_prefix + a_name + "_action_spec_t &action_spec"] //:: #endif //:: params += get_direct_parameter_specs(t, api_prefix) //:: param_str = ", ".join(params) //:: name = t_name + "_set_default_action_" + a_name //:: pd_name = pd_prefix + name int32_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; //:: if has_action_spec: ${pd_prefix}${a_name}_action_spec_t pd_action_spec; //:: action_params = gen_action_params(a.runtime_data) //:: for name, _, width in action_params: //:: name = get_c_name(name) //:: if width <= 4: pd_action_spec.${name} = action_spec.${name}; //:: else: memcpy(pd_action_spec.${name}, action_spec.${name}.c_str(), ${width}); //:: #endif //:: #endfor //:: #endif p4_pd_entry_hdl_t pd_entry; //:: pd_params = ["sess_hdl", "pd_dev_tgt"] //:: if has_action_spec: //:: pd_params += ["&pd_action_spec"] //:: #endif //:: # direct parameter specs //:: if t.direct_meters: //:: m = t.direct_meters //:: unit_name = MeterUnit.to_str(m.unit) p4_pd_${unit_name}_meter_spec_t pd_${m.name}_spec; ${unit_name}_meter_spec_thrift_to_pd(${m.name}_spec, &pd_${m.name}_spec); //:: pd_params += ["&pd_" + m.name + "_spec"] //:: #endif //:: pd_params += ["&pd_entry"] //:: pd_param_str = ", ".join(pd_params) return ${pd_name}(${pd_param_str}); // return pd_entry; } //:: #endfor //:: #endfor //:: name = "clean_all" //:: pd_name = pd_prefix + name int32_t ${name}(const SessionHandle_t sess_hdl, const DevTarget_t &dev_tgt) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; return ${pd_name}(sess_hdl, pd_dev_tgt); } // INDIRECT ACTION DATA AND MATCH SELECT //:: for act_prof_name, act_prof in act_profs.items(): //:: act_prof_name = get_c_name(act_prof_name) //:: for a_name, a in act_prof.actions.items(): //:: a_name = get_c_name(a_name) //:: has_action_spec = len(a.runtime_data) > 0 //:: params = ["const SessionHandle_t sess_hdl", //:: "const DevTarget_t &dev_tgt"] //:: if has_action_spec: //:: params += ["const " + api_prefix + a_name + "_action_spec_t &action_spec"] //:: #endif //:: param_str = ", ".join(params) //:: name = act_prof_name + "_add_member_with_" + a_name //:: pd_name = pd_prefix + name EntryHandle_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; //:: if has_action_spec: ${pd_prefix}${a_name}_action_spec_t pd_action_spec; //:: action_params = gen_action_params(a.runtime_data) //:: for name, _, width in action_params: //:: name = get_c_name(name) //:: if width <= 4: pd_action_spec.${name} = action_spec.${name}; //:: else: memcpy(pd_action_spec.${name}, action_spec.${name}.c_str(), ${width}); //:: #endif //:: #endfor //:: #endif p4_pd_mbr_hdl_t pd_mbr_hdl; //:: pd_params = ["sess_hdl", "pd_dev_tgt"] //:: if has_action_spec: //:: pd_params += ["&pd_action_spec"] //:: #endif //:: pd_params += ["&pd_mbr_hdl"] //:: pd_param_str = ", ".join(pd_params) ${pd_name}(${pd_param_str}); return pd_mbr_hdl; } //:: params = ["const SessionHandle_t sess_hdl", //:: "const int8_t dev_id", //:: "const MemberHandle_t mbr"] //:: if has_action_spec: //:: params += ["const " + api_prefix + a_name + "_action_spec_t &action_spec"] //:: #endif //:: param_str = ", ".join(params) //:: name = act_prof_name + "_modify_member_with_" + a_name //:: pd_name = pd_prefix + name EntryHandle_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; //:: if has_action_spec: ${pd_prefix}${a_name}_action_spec_t pd_action_spec; //:: action_params = gen_action_params(a.runtime_data) //:: for name, _, width in action_params: //:: name = get_c_name(name) //:: if width <= 4: pd_action_spec.${name} = action_spec.${name}; //:: else: memcpy(pd_action_spec.${name}, action_spec.${name}.c_str(), ${width}); //:: #endif //:: #endfor //:: #endif //:: pd_params = ["sess_hdl", "dev_id", "mbr"] //:: if has_action_spec: //:: pd_params += ["&pd_action_spec"] //:: #endif //:: pd_param_str = ", ".join(pd_params) return ${pd_name}(${pd_param_str}); } //:: #endfor //:: params = ["const SessionHandle_t sess_hdl", //:: "const int8_t dev_id", //:: "const MemberHandle_t mbr"] //:: param_str = ", ".join(params) //:: name = act_prof_name + "_del_member" //:: pd_name = pd_prefix + name int32_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; return ${pd_name}(sess_hdl, dev_id, mbr); } //:: if not act_prof.with_selector: continue //:: //:: params = ["const SessionHandle_t sess_hdl", //:: "const DevTarget_t &dev_tgt", //:: "const int16_t max_grp_size"] //:: param_str = ", ".join(params) //:: name = act_prof_name + "_create_group" //:: pd_name = pd_prefix + name GroupHandle_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; p4_pd_grp_hdl_t pd_grp_hdl; ${pd_name}(sess_hdl, pd_dev_tgt, max_grp_size, &pd_grp_hdl); return pd_grp_hdl; } //:: params = ["const SessionHandle_t sess_hdl", //:: "const int8_t dev_id", //:: "const GroupHandle_t grp"] //:: param_str = ", ".join(params) //:: name = act_prof_name + "_del_group" //:: pd_name = pd_prefix + name int32_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; return ${pd_name}(sess_hdl, dev_id, grp); } //:: params = ["const SessionHandle_t sess_hdl", //:: "const int8_t dev_id", //:: "const GroupHandle_t grp", //:: "const MemberHandle_t mbr"] //:: param_str = ", ".join(params) //:: name = act_prof_name + "_add_member_to_group" //:: pd_name = pd_prefix + name int32_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; return ${pd_name}(sess_hdl, dev_id, grp, mbr); } //:: params = ["const SessionHandle_t sess_hdl", //:: "const int8_t dev_id", //:: "const GroupHandle_t grp", //:: "const MemberHandle_t mbr"] //:: param_str = ", ".join(params) //:: name = act_prof_name + "_del_member_from_group" //:: pd_name = pd_prefix + name int32_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; return ${pd_name}(sess_hdl, dev_id, grp, mbr); } //:: params = ["const SessionHandle_t sess_hdl", //:: "const int8_t dev_id", //:: "const GroupHandle_t grp", //:: "const MemberHandle_t mbr"] //:: param_str = ", ".join(params) //:: name = act_prof_name + "_deactivate_group_member" //:: pd_name = pd_prefix + name int32_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; return 0; } //:: params = ["const SessionHandle_t sess_hdl", //:: "const int8_t dev_id", //:: "const GroupHandle_t grp", //:: "const MemberHandle_t mbr"] //:: param_str = ", ".join(params) //:: name = act_prof_name + "_reactivate_group_member" //:: pd_name = pd_prefix + name int32_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; return 0; } //:: #endfor //:: for t_name, t in tables.items(): //:: t_type = t.type_ //:: if t_type == TableType.SIMPLE: continue //:: t_name = get_c_name(t_name) //:: match_type = t.match_type //:: has_match_spec = len(t.key) > 0 //:: params = ["const SessionHandle_t sess_hdl", //:: "const DevTarget_t &dev_tgt"] //:: if has_match_spec: //:: params += ["const " + api_prefix + t_name + "_match_spec_t &match_spec"] //:: #endif //:: if match_type in {MatchType.TERNARY, MatchType.RANGE}: //:: params += ["const int32_t priority"] //:: #endif //:: params_wo = params + ["const MemberHandle_t mbr"] //:: param_str = ", ".join(params_wo) //:: name = t_name + "_add_entry" //:: pd_name = pd_prefix + name EntryHandle_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; //:: if has_match_spec: ${pd_prefix}${t_name}_match_spec_t pd_match_spec; //:: match_params = gen_match_params(t.key) //:: for name, width in match_params: //:: name = get_c_name(name) //:: if width <= 4: pd_match_spec.${name} = match_spec.${name}; //:: else: memcpy(pd_match_spec.${name}, match_spec.${name}.c_str(), ${width}); //:: #endif //:: #endfor //:: #endif p4_pd_entry_hdl_t pd_entry; //:: pd_params = ["sess_hdl", "pd_dev_tgt"] //:: if has_match_spec: //:: pd_params += ["&pd_match_spec"] //:: #endif //:: if match_type in {MatchType.TERNARY, MatchType.RANGE}: //:: pd_params += ["priority"] //:: #endif //:: pd_params += ["mbr", "&pd_entry"] //:: pd_param_str = ", ".join(pd_params) ${pd_name}(${pd_param_str}); return pd_entry; } //:: if t_type != TableType.INDIRECT_WS: continue //:: params_w = params + ["const GroupHandle_t grp"] //:: param_str = ", ".join(params_w) //:: name = t_name + "_add_entry_with_selector" //:: pd_name = pd_prefix + name EntryHandle_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; //:: if has_match_spec: ${pd_prefix}${t_name}_match_spec_t pd_match_spec; //:: match_params = gen_match_params(t.key) //:: for name, width in match_params: //:: name = get_c_name(name) //:: if width <= 4: pd_match_spec.${name} = match_spec.${name}; //:: else: memcpy(pd_match_spec.${name}, match_spec.${name}.c_str(), ${width}); //:: #endif //:: #endfor //:: #endif p4_pd_entry_hdl_t pd_entry; //:: pd_params = ["sess_hdl", "pd_dev_tgt"] //:: if has_match_spec: //:: pd_params += ["&pd_match_spec"] //:: #endif //:: if match_type in {MatchType.TERNARY, MatchType.RANGE}: //:: pd_params += ["priority"] //:: #endif //:: pd_params += ["grp", "&pd_entry"] //:: pd_param_str = ", ".join(pd_params) ${pd_name}(${pd_param_str}); return pd_entry; } //:: #endfor //:: for t_name, t in tables.items(): //:: t_type = t.type_ //:: if t_type == TableType.SIMPLE: continue //:: t_name = get_c_name(t_name) //:: params = ["const SessionHandle_t sess_hdl", //:: "const DevTarget_t &dev_tgt"] //:: params_wo = params + ["const MemberHandle_t mbr"] //:: param_str = ", ".join(params_wo) //:: name = t_name + "_set_default_entry" //:: pd_name = pd_prefix + name int32_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; p4_pd_entry_hdl_t pd_entry; //:: pd_params = ["sess_hdl", "pd_dev_tgt"] //:: pd_params += ["mbr", "&pd_entry"] //:: pd_param_str = ", ".join(pd_params) ${pd_name}(${pd_param_str}); return pd_entry; } //:: if t_type != TableType.INDIRECT_WS: continue //:: params_w = params + ["const GroupHandle_t grp"] //:: param_str = ", ".join(params_w) //:: name = t_name + "_set_default_entry_with_selector" //:: pd_name = pd_prefix + name int32_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; p4_pd_entry_hdl_t pd_entry; //:: pd_params = ["sess_hdl", "pd_dev_tgt"] //:: pd_params += ["grp", "&pd_entry"] //:: pd_param_str = ", ".join(pd_params) ${pd_name}(${pd_param_str}); return pd_entry; } //:: #endfor // COUNTERS //:: for ca_name, ca in counter_arrays.items(): //:: if ca.is_direct: //:: name = "counter_read_" + ca_name //:: pd_name = pd_prefix + name void ${name}(${api_prefix}counter_value_t &counter_value, const SessionHandle_t sess_hdl, const DevTarget_t &dev_tgt, const EntryHandle_t entry, const ${api_prefix}counter_flags_t &flags) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; int pd_flags = 0; if(flags.read_hw_sync) pd_flags |= COUNTER_READ_HW_SYNC; p4_pd_counter_value_t value = ${pd_name}(sess_hdl, pd_dev_tgt, entry, pd_flags); counter_value.packets = value.packets; counter_value.bytes = value.bytes; } //:: name = "counter_write_" + ca_name //:: pd_name = pd_prefix + name int32_t ${name}(const SessionHandle_t sess_hdl, const DevTarget_t &dev_tgt, const EntryHandle_t entry, const ${api_prefix}counter_value_t &counter_value) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; p4_pd_counter_value_t value; value.packets = counter_value.packets; value.bytes = counter_value.bytes; return ${pd_name}(sess_hdl, pd_dev_tgt, entry, value); } //:: else: //:: name = "counter_read_" + ca_name //:: pd_name = pd_prefix + name void ${name}(${api_prefix}counter_value_t &counter_value, const SessionHandle_t sess_hdl, const DevTarget_t &dev_tgt, const int32_t index, const ${api_prefix}counter_flags_t &flags) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; int pd_flags = 0; if(flags.read_hw_sync) pd_flags |= COUNTER_READ_HW_SYNC; p4_pd_counter_value_t value = ${pd_name}(sess_hdl, pd_dev_tgt, index, pd_flags); counter_value.packets = value.packets; counter_value.bytes = value.bytes; } //:: name = "counter_write_" + ca_name //:: pd_name = pd_prefix + name int32_t ${name}(const SessionHandle_t sess_hdl, const DevTarget_t &dev_tgt, const int32_t index, const ${api_prefix}counter_value_t &counter_value) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; p4_pd_counter_value_t value; value.packets = counter_value.packets; value.bytes = counter_value.bytes; return ${pd_name}(sess_hdl, pd_dev_tgt, index, value); } //:: #endif //:: #endfor //:: for ca_name, ca in counter_arrays.items(): //:: name = "counter_hw_sync_" + ca_name //:: pd_name = pd_prefix + name int32_t ${name}(const SessionHandle_t sess_hdl, const DevTarget_t &dev_tgt) { p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; std::promise<void> promise; auto future = promise.get_future(); struct HwSync { HwSync(std::promise<void> &promise) : promise(promise) { } std::promise<void> &promise; }; // lambda does not capture, so can be used as function pointer auto cb = [](int device_id, void *cookie) { static_cast<HwSync *>(cookie)->promise.set_value(); }; HwSync h(promise); ${pd_name}(sess_hdl, pd_dev_tgt, cb, static_cast<void *>(&h)); future.wait(); return 0; } //:: #endfor // METERS //:: for ma_name, ma in meter_arrays.items(): //:: params = ["const SessionHandle_t sess_hdl", //:: "const DevTarget_t &dev_tgt"] //:: pd_params = ["sess_hdl", "pd_dev_tgt"] //:: if ma.is_direct: //:: params += ["const EntryHandle_t entry"] //:: pd_params += ["entry"] //:: else: //:: params += ["const int32_t index"] //:: pd_params += ["index"] //:: #endif //:: if ma.unit == MeterUnit.PACKETS: //:: params += ["const " + api_prefix + "packets_meter_spec_t &meter_spec"] //:: else: //:: params += ["const " + api_prefix + "bytes_meter_spec_t &meter_spec"] //:: #endif //:: pd_params += ["&pd_meter_spec"] //:: param_str = ", ".join(params) //:: //:: pd_param_str = ", ".join(pd_params) //:: //:: name = "meter_set_" + ma_name //:: pd_name = pd_prefix + name int32_t ${name}(${param_str}) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; //:: if ma.unit == MeterUnit.PACKETS: p4_pd_packets_meter_spec_t pd_meter_spec; packets_meter_spec_thrift_to_pd(meter_spec, &pd_meter_spec); //:: else: p4_pd_bytes_meter_spec_t pd_meter_spec; bytes_meter_spec_thrift_to_pd(meter_spec, &pd_meter_spec); //:: #endif return ${pd_name}(${pd_param_str}); } //:: if ma.unit == MeterUnit.PACKETS: //:: params = [api_prefix + "packets_meter_spec_t &meter_spec"] //:: else: //:: params = [api_prefix + "bytes_meter_spec_t &meter_spec"] //:: #endif //:: params += ["const SessionHandle_t sess_hdl", //:: "const DevTarget_t &dev_tgt"] //:: pd_params = ["sess_hdl", "pd_dev_tgt"] //:: if ma.is_direct: //:: params += ["const EntryHandle_t entry"] //:: pd_params += ["entry"] //:: else: //:: params += ["const int32_t index"] //:: pd_params += ["index"] //:: #endif //:: pd_params += ["&pd_meter_spec"] //:: param_str = ", ".join(params) //:: //:: pd_param_str = ", ".join(pd_params) //:: //:: name = "meter_read_" + ma_name //:: pd_name = pd_prefix + name void ${name}(${param_str}) { std::cerr << "In ${name}\n"; p4_pd_dev_target_t pd_dev_tgt; pd_dev_tgt.device_id = dev_tgt.dev_id; pd_dev_tgt.dev_pipe_id = dev_tgt.dev_pipe_id; //:: if ma.unit == MeterUnit.PACKETS: p4_pd_packets_meter_spec_t pd_meter_spec; //:: else: p4_pd_bytes_meter_spec_t pd_meter_spec; //:: #endif p4_pd_status_t status = ${pd_name}(${pd_param_str}); if (status) return; //:: if ma.unit == MeterUnit.PACKETS: packets_meter_spec_pd_to_thrift(pd_meter_spec, &meter_spec); //:: else: bytes_meter_spec_pd_to_thrift(pd_meter_spec, &meter_spec); //:: #endif } //:: #endfor };
32.658784
193
0.603048
liusheng198933
fea421ffeeed2b9606315aca0ccc3bfc3d563e51
1,444
cc
C++
chrome/browser/ash/login/screens/wrong_hwid_screen.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chrome/browser/ash/login/screens/wrong_hwid_screen.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
chrome/browser/ash/login/screens/wrong_hwid_screen.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ash/login/screens/wrong_hwid_screen.h" #include "chrome/browser/ash/login/wizard_controller.h" #include "chrome/browser/ui/webui/chromeos/login/wrong_hwid_screen_handler.h" namespace ash { namespace { constexpr char kUserActionSkip[] = "skip-screen"; } // namespace WrongHWIDScreen::WrongHWIDScreen(WrongHWIDScreenView* view, const base::RepeatingClosure& exit_callback) : BaseScreen(WrongHWIDScreenView::kScreenId, OobeScreenPriority::SCREEN_HARDWARE_ERROR), view_(view), exit_callback_(exit_callback) { DCHECK(view_); if (view_) view_->Bind(this); } WrongHWIDScreen::~WrongHWIDScreen() { if (view_) view_->Unbind(); } void WrongHWIDScreen::OnExit() { if (is_hidden()) return; exit_callback_.Run(); } void WrongHWIDScreen::OnViewDestroyed(WrongHWIDScreenView* view) { if (view_ == view) view_ = nullptr; } void WrongHWIDScreen::ShowImpl() { if (view_) view_->Show(); } void WrongHWIDScreen::HideImpl() { if (view_) view_->Hide(); } void WrongHWIDScreen::OnUserAction(const std::string& action_id) { if (action_id == kUserActionSkip) { OnExit(); } else { BaseScreen::OnUserAction(action_id); } } } // namespace ash
22.920635
77
0.692521
zealoussnow
fea473307303994bbc460172efce67143587bf36
44,007
cpp
C++
test/adiar/bdd/test_apply.cpp
logsem/adiar
056c62a37eedcc5a9e46ccc8c235b5aacedebe32
[ "MIT" ]
null
null
null
test/adiar/bdd/test_apply.cpp
logsem/adiar
056c62a37eedcc5a9e46ccc8c235b5aacedebe32
[ "MIT" ]
null
null
null
test/adiar/bdd/test_apply.cpp
logsem/adiar
056c62a37eedcc5a9e46ccc8c235b5aacedebe32
[ "MIT" ]
null
null
null
go_bandit([]() { describe("adiar/bdd/apply.cpp", []() { node_file bdd_F; node_file bdd_T; { // Garbage collect writers to free write-lock node_writer nw_F(bdd_F); nw_F << create_sink(false); node_writer nw_T(bdd_T); nw_T << create_sink(true); } ptr_t sink_T = create_sink_ptr(true); ptr_t sink_F = create_sink_ptr(false); node_file bdd_x0; node_file bdd_not_x0; node_file bdd_x1; node_file bdd_x2; { // Garbage collect writers early node_writer nw_x0(bdd_x0); nw_x0 << create_node(0,MAX_ID, sink_F, sink_T); node_writer nw_not_x0(bdd_not_x0); nw_not_x0 << create_node(0,MAX_ID, sink_T, sink_F); node_writer nw_x1(bdd_x1); nw_x1 << create_node(1,MAX_ID, sink_F, sink_T); node_writer nw_x2(bdd_x2); nw_x2 << create_node(2,MAX_ID, sink_F, sink_T); } node_file bdd_1; /* 1 ---- x0 / \ | 2 ---- x1 |/ \ 3 4 ---- x2 / \ / \ F T T 5 ---- x3 / \ F T */ node_t n1_5 = create_node(3,MAX_ID, sink_F, sink_T); node_t n1_4 = create_node(2,MAX_ID, sink_T, n1_5.uid); node_t n1_3 = create_node(2,MAX_ID-1, sink_F, sink_T); node_t n1_2 = create_node(1,MAX_ID, n1_3.uid, n1_4.uid); node_t n1_1 = create_node(0,MAX_ID, n1_3.uid, n1_2.uid); { // Garbage collect early and free write-lock node_writer nw_1(bdd_1); nw_1 << n1_5 << n1_4 << n1_3 << n1_2 << n1_1; } node_file bdd_2; /* ---- x0 1 ---- x1 / \ | T ---- x2 | 2 ---- x3 / \ T F */ node_t n2_2 = create_node(3,MAX_ID, sink_T, sink_F); node_t n2_1 = create_node(1,MAX_ID, n2_2.uid, sink_T); { // Garbage collect early and free write-lock node_writer nw_2(bdd_2); nw_2 << n2_2 << n2_1; } node_file bdd_3; /* 1 ---- x0 / \ 2 3 ---- x1 _/ X \_ | _/ \_ | X X / \ / \ 4 5 6 7 ---- x2 / \/ \/ \/ \ F T 8 T F ---- x3 / \ F T */ node_t n3_8 = create_node(3,MAX_ID, sink_F, sink_T); node_t n3_7 = create_node(2,MAX_ID, sink_T, sink_F); node_t n3_6 = create_node(2,MAX_ID - 1, n3_8.uid, sink_T); node_t n3_5 = create_node(2,MAX_ID - 2, sink_T, n3_8.uid); node_t n3_4 = create_node(2,MAX_ID - 3, sink_F, sink_T); node_t n3_3 = create_node(1,MAX_ID, n3_4.uid, n3_6.uid); node_t n3_2 = create_node(1,MAX_ID - 1, n3_5.uid, n3_7.uid); node_t n3_1 = create_node(0,MAX_ID, n3_2.uid, n3_3.uid); { // Garbage collect early and free write-lock node_writer nw_3(bdd_3); nw_3 << n3_8 << n3_7 << n3_6 << n3_5 << n3_4 << n3_3 << n3_2 << n3_1; } /* The product construction of bbd_1 and bdd_2 above is as follows in sorted order. (1,1) ---- x0 \_ _/ _X_ // Match in fst, but not coordinatewise / \ (3,1) (2,1) ---- x1 / \_ _/ \ / X \ /_______/ \ \ | \ \ (3,2) (3,T) (4,T) ---- x2 \ \ / \ / \ \ \ (F,T) (T,T) / \ \________ ___________/ \________ X________ X_________\ _______ / \ \ / \ \ (5,T) (F,2) (T,2) ---- x3 / \ / \ / \ (F,T) (T,T) (F,T)(F,F) (T,T)(T,F) */ describe("bdd_and(f,g)", [&]() { it("should resolve F /\\ T sink-only BDDs", [&]() { __bdd out = bdd_and(bdd_F, bdd_T); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should resolve T /\\ T sink-only BDDs", [&]() { __bdd out = bdd_and(bdd_T, bdd_T); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should shortcut on irrelevance on x0 /\\ T", [&]() { __bdd out = bdd_and(bdd_x0, bdd_T); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(bdd_x0._file_ptr)); AssertThat(out.negate, Is().False()); }); it("should shortcut F /\\ x0", [&]() { __bdd out = bdd_and(bdd_F, bdd_x0); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should x0 and !x0", [&]() { /* 1 ---- x0 / \ F F */ __bdd out = bdd_and(bdd_x0, bdd_not_x0); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().False()); }); it("should shortcut F /\\ [2]", [&]() { __bdd out = bdd_and(bdd_F, bdd_2); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should compute (and shortcut) BBD 1 /\\ [2]", [&]() { /* 1 ---- x0 X / \ 2 3 ---- x1 / \ / \ / X \ /___/ \ \ / | \ 4 5 6 ---- x2 / \ / \_ _/ \ F 7 F T 8 ---- x3 / \ / \ T F F T */ __bdd out = bdd_and(bdd_1, bdd_2); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(1,0) })); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(1,1) })); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), create_node_ptr(2,0) })); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,1), create_node_ptr(2,0) })); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,1)), create_node_ptr(2,1) })); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), create_node_ptr(2,2) })); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,2)), create_node_ptr(3,0) })); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,0)), create_node_ptr(3,1) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,1), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,1)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,2), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,1), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,1)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,2u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(2,3u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(3,2u))); AssertThat(level_info.can_pull(), Is().False()); }); it("should return input on being given the same BDD twice", [&]() { __bdd out = bdd_and(bdd_1, bdd_1); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(bdd_1._file_ptr)); AssertThat(out.negate, Is().False()); }); it("should group all recursion requests together", [&]() { // This is a counter-example to the prior "break ties on fst() with // snd()" approach. Here we will have three requests to the level of // x2, but in the following order: // // [((2,0),(2,1)), ((2,1),(2,0)), ((2,0),(2,1))] // // which all are tied, and hence the prior version would create // three nodes on this level rather than just two. /* 1 ---- x0 / \ 2 | ---- x1 / \| 3 4 ---- x2 / \\/ \ T F T */ // The second version is the same but has the nodes 3 and 4 mirrored // and the T sinks are replaced with an arc to a node for x3. node_file bdd_group_1, bdd_group_2; { // Garbage collect writers to free write-lock node_writer w1(bdd_group_1); w1 << create_node(2,1, create_sink_ptr(false), create_sink_ptr(true)) << create_node(2,0, create_sink_ptr(true), create_sink_ptr(false)) << create_node(1,0, create_node_ptr(2,0), create_node_ptr(2,1)) << create_node(0,1, create_node_ptr(1,0), create_node_ptr(2,1)); node_writer w2(bdd_group_2); w2 << create_node(3,0, create_sink_ptr(false), create_sink_ptr(true)) << create_node(2,1, create_node_ptr(3,0), create_sink_ptr(false)) << create_node(2,0, create_sink_ptr(false), create_node_ptr(3,0)) << create_node(1,0, create_node_ptr(2,1), create_node_ptr(2,0)) << create_node(0,1, create_node_ptr(1,0), create_node_ptr(2,0)); } __bdd out = bdd_and(bdd_group_1, bdd_group_2); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); // (2,2) AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(1,0) })); AssertThat(node_arcs.can_pull(), Is().True()); // (3,4) AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), create_node_ptr(2,0) })); AssertThat(node_arcs.can_pull(), Is().True()); // (4,3) AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(2,1) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), create_node_ptr(2,1) })); AssertThat(node_arcs.can_pull(), Is().True()); // (T,5) i.e. the added node AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,0), create_node_ptr(3,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,1)), create_node_ptr(3,0) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,0)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,1), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(2,2u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(3,1u))); AssertThat(level_info.can_pull(), Is().False()); }); }); describe("bdd_nand(f,g)", [&]() { it("should shortcut on negating on T and x0", [&]() { __bdd out = bdd_nand(bdd_x0, bdd_T); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(bdd_x0._file_ptr)); AssertThat(out.negate, Is().True()); }); it("should shortcut on negating on T and x0", [&]() { __bdd out = bdd_nand(bdd_x0, bdd_T); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(bdd_x0._file_ptr)); AssertThat(out.negate, Is().True()); }); it("should collapse on the same BDD twice, where one is negated [1]", [&]() { __bdd out = bdd_nand(bdd_2, bdd_not(bdd_2)); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); }); describe("bdd_or(f,g)", [&]() { it("should resolve T \\/ F sink-only BDDs", [&]() { __bdd out = bdd_or(bdd_T, bdd_F); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should resolve T \\/ F sink-only BDDs", [&]() { __bdd out = bdd_or(bdd_F, bdd_F); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should shortcut on irrelevance on x0 \\/ F", [&]() { __bdd out = bdd_or(bdd_x0, bdd_F); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(bdd_x0._file_ptr)); AssertThat(out.negate, Is().False()); }); it("should OR shortcut on irrelevance F \\/ x0", [&]() { __bdd out = bdd_or(bdd_F, bdd_x0); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(bdd_x0._file_ptr)); AssertThat(out.negate, Is().False()); }); it("should shortcut on x0 \\/ x2", [&]() { /* 1 ---- x0 / \ | T | 2 ---- x2 / \ F T */ __bdd out = bdd_or(bdd_x0, bdd_x2); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(2,0) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(2,1u))); AssertThat(level_info.can_pull(), Is().False()); }); it("should shortcut [1] \\/ T", [&]() { __bdd out = bdd_or(bdd_1, bdd_T); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should compute (and shortcut) [2] \\/ T", [&]() { __bdd out = bdd_or(bdd_2, bdd_T); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should compute (and shortcut) [1] \\/ [2]", [&]() { /* 1 ---- x0 / \ 2 3 ---- x1 / \ / \ | T | T \_ _/ 4 ---- x2 / \ 5 T ---- x3 / \ T F */ __bdd out = bdd_or(bdd_1, bdd_2); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(1,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(1,1) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), create_node_ptr(2,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,1), create_node_ptr(2,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,0), create_node_ptr(3,0) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,1)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,0), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,0)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,2u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(2,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(3,1u))); AssertThat(level_info.can_pull(), Is().False()); }); }); describe("bdd_nor(f,g)", [&]() { it("should collapse on the same BDD twice to a sink, where one is negated [2]", [&]() { __bdd out = bdd_nor(bdd_not(bdd_3), bdd_3); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); }); describe("bdd_xor(f,g)", [&]() { it("should resolve F ^ T sink-only BDDs", [&]() { __bdd out = bdd_xor(bdd_F, bdd_T); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should resolve T ^ T sink-only BDDs", [&]() { __bdd out = bdd_xor(bdd_T, bdd_T); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()) ; AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should shortcut on negating on x0 ^ T", [&]() { __bdd out = bdd_xor(bdd_x0, bdd_T); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(bdd_x0._file_ptr)); AssertThat(out.negate, Is().True()); }); it("should shortcut on negating on T ^ x0", [&]() { __bdd out = bdd_xor(bdd_x0, bdd_T); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(bdd_x0._file_ptr)); AssertThat(out.negate, Is().True()); }); it("should compute x0 ^ x1", [&]() { /* The order on the leaves are due to the sorting of sink requests after evaluating x0 1 ---- x0 / \ 2 3 ---- x1 / \ / \ F T T F */ __bdd out = bdd_xor(bdd_x0, bdd_x1); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(1,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(1,1) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,1), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,1)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,2u))); AssertThat(level_info.can_pull(), Is().False()); }); it("should compute [2] ^ x2", [&]() { /* ---- x0 (1,1) ---- x1 / \ (2,1) (T,1) ---- x2 / \ / \ / \ T F | | (2,F) (2,T) ---- x3 / \ / \ T F F T */ __bdd out = bdd_xor(bdd_2, bdd_x2); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), create_node_ptr(2,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), create_node_ptr(2,1) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,0), create_node_ptr(3,0) })); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,0)), create_node_ptr(3,1) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,1), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,1)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,0), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,0)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,1), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,1)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(2,2u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(3,2u))); AssertThat(level_info.can_pull(), Is().False()); }); it("should compute [1] ^ [2]", [&]() { /* There is no shortcutting possible on an XOR, so see the product construction above. */ __bdd out = bdd_xor(bdd_1, bdd_2); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(1,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(1,1) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), create_node_ptr(2,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,1), create_node_ptr(2,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,1)), create_node_ptr(2,1) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), create_node_ptr(2,2) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,2)), create_node_ptr(3,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,0), create_node_ptr(3,1) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,0)), create_node_ptr(3,2) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,1), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,1)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,2), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,0), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,0)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,1), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,1)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,2), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,2)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,2u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(2,3u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(3,3u))); AssertThat(level_info.can_pull(), Is().False()); }); it("should compute [3] ^ [1]", [&]() { /* The queue appD_data is used to forward data across the level. When [1] and 3 are combined, this is needed The product between the [3] and [1] then is (1,1) ---- x0 ________/ \_______ / \ (2,3) (3,2) ---- x1 / \_________ ________/ \ | X | // (5,3) (7,3) (4,3) (6,4) \__ _________/ \__________ / // min: 0 0 0 1 ___X___ X // max: 1 3 0 2 / \ _____/ \ // coord: 2 3 1 4 / \ / \ (4,3) (5,3) (6,4) (7,3) ---- x2 / \ / \ / \ / \ (F,F) (T,T) (T,F) | / \ (T,F) (F,T) | / \ | / | |/ | (8,T) (T,5) ---- x3 / \ / \ (F,T) (T,T) (T,F) (T,T) */ __bdd out = bdd_xor(bdd_3, bdd_1); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); // (2,3) AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), create_node_ptr(1,0) })); AssertThat(node_arcs.can_pull(), Is().True()); // (3,2) AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(1,1) })); AssertThat(node_arcs.can_pull(), Is().True()); // (4,3) AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,1), create_node_ptr(2,0) })); AssertThat(node_arcs.can_pull(), Is().True()); // (5,3) AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), create_node_ptr(2,1) })); AssertThat(node_arcs.can_pull(), Is().True()); // (6,4) AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,1)), create_node_ptr(2,2) })); AssertThat(node_arcs.can_pull(), Is().True()); // (7,3) AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), create_node_ptr(2,3) })); AssertThat(node_arcs.can_pull(), Is().True()); // (8,T) AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,1)), create_node_ptr(3,0) })); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,2), create_node_ptr(3,0) })); AssertThat(node_arcs.can_pull(), Is().True()); // (T,5) AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,2)), create_node_ptr(3,1) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,0)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,1), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(2,3), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(2,3)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,0), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,0)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(3,1), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(3,1)), sink_F })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,2u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(2,4u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(3,2u))); AssertThat(level_info.can_pull(), Is().False()); }); it("should collapse on the same BDD twice", [&]() { __bdd out = bdd_xor(bdd_1, bdd_1); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should collapse on the same BDD twice to a sink, when both are negated", [&]() { __bdd out = bdd_xor(bdd_not(bdd_1), bdd_not(bdd_1)); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); }); describe("bdd_xnor(f,g)", [&]() { // TODO }); describe("bdd_imp(f,g)", [&]() { it("should resolve F -> T sink-only BDDs", [&]() { __bdd out = bdd_imp(bdd_F, bdd_T); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should resolve T -> F sink-only BDDs", [&]() { __bdd out = bdd_imp(bdd_T, bdd_F); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(false))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should resolve T -> T sink-only BDDs", [&]() { __bdd out = bdd_imp(bdd_T, bdd_T); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should shortcut on irrelevance on T -> x0", [&]() { __bdd out = bdd_imp(bdd_T, bdd_x0); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(bdd_x0._file_ptr)); AssertThat(out.negate, Is().False()); }); it("should shortcut on x0 -> x1", [&]() { /* The order on the leaves are due to the sorting of sink requests after evaluating x0 1 ---- x0 / \ T 2 ---- x1 / \ F T */ __bdd out = bdd_imp(bdd_x0, bdd_x1); node_arc_test_stream node_arcs(out); AssertThat(node_arcs.can_pull(), Is().True()); AssertThat(node_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(0,0)), create_node_ptr(1,0) })); AssertThat(node_arcs.can_pull(), Is().False()); sink_arc_test_stream sink_arcs(out); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(0,0), sink_T })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { create_node_ptr(1,0), sink_F })); AssertThat(sink_arcs.can_pull(), Is().True()); AssertThat(sink_arcs.pull(), Is().EqualTo(arc { flag(create_node_ptr(1,0)), sink_T })); AssertThat(sink_arcs.can_pull(), Is().False()); level_info_test_stream<arc_t> level_info(out); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(0,1u))); AssertThat(level_info.can_pull(), Is().True()); AssertThat(level_info.pull(), Is().EqualTo(create_level_info(1,1u))); AssertThat(level_info.can_pull(), Is().False()); }); it("should shortcut F -> [1]", [&]() { __bdd out = bdd_imp(bdd_F, bdd_1); node_test_stream out_nodes(out); AssertThat(out_nodes.can_pull(), Is().True()); AssertThat(out_nodes.pull(), Is().EqualTo(create_sink(true))); AssertThat(out_nodes.can_pull(), Is().False()); AssertThat(out.get<node_file>().meta_size(), Is().EqualTo(0u)); }); it("should return the input when given the same BDD twice, where one is negated [1]", [&]() { __bdd out = bdd_imp(bdd_not(bdd_2), bdd_2); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(bdd_2._file_ptr)); AssertThat(out.negate, Is().False()); // negated the already negated input doubly-negating }); it("should return input when given the same BDD twice, where one is negated [2]", [&]() { __bdd out = bdd_imp(bdd_2, bdd_not(bdd_2)); AssertThat(out.get<node_file>()._file_ptr, Is().EqualTo(bdd_2._file_ptr)); AssertThat(out.negate, Is().True()); // negated the first of the two }); }); describe("bdd_invimp(f,g)", [&]() { // TODO }); describe("bdd_equiv(f,g)", [&]() { // TODO }); describe("bdd_diff(f,g)", [&]() { // TODO }); describe("bdd_less(f,g)", [&]() { // TODO }); }); });
38.101299
111
0.547686
logsem
fea4ae8e6c63cf0b41b62212f9740569d2c8b344
1,382
cpp
C++
MVJ_Engine_base/ComponentLight.cpp
expelthegrace/ThomasTheEngine
d570c9746725e3f8232753799cce90cdc47a4b48
[ "Unlicense" ]
null
null
null
MVJ_Engine_base/ComponentLight.cpp
expelthegrace/ThomasTheEngine
d570c9746725e3f8232753799cce90cdc47a4b48
[ "Unlicense" ]
null
null
null
MVJ_Engine_base/ComponentLight.cpp
expelthegrace/ThomasTheEngine
d570c9746725e3f8232753799cce90cdc47a4b48
[ "Unlicense" ]
null
null
null
#include "ComponentLight.h" #include "GameObject.h" #include "ComponentTransform.h" #include "ModuleScene.h" #include "Application.h" #include "debugdraw.h" #include "JSONManager.h" ComponentLight::ComponentLight(GameObject * my_go) { this->my_go = my_go; this->type = LIGHT; if (App->scene->mainLight == nullptr) App->scene->mainLight = this; } ComponentLight::~ComponentLight() { my_go = nullptr; } update_status ComponentLight::Update() { position = my_go->transform->globalPosition; //direction = (my_go->transform->rotation * initialDirection).Normalized(); colorLight_Intensity = float3(colorLight.x * intensity, colorLight.y * intensity, colorLight.z * intensity); const ddVec3 boxColor = { 0.f, 0.6f, 0.8f }; dd::sphere(position, boxColor, 0.4 * App->GameScale); return UPDATE_CONTINUE; } void ComponentLight::Reset() { colorLight = { 0.5f, 0.5f, 0.5f }; intensity = 1.f; } void ComponentLight::Save(JSON_Value* componentsJSON) { JSON_Value* componentJSON = componentsJSON->createValue(); componentJSON->addInt("Type", type); componentJSON->addVector3("colorLight", colorLight); componentJSON->addFloat("Intensity", intensity); componentsJSON->addValue("Light", componentJSON); } void ComponentLight::Load(JSON_Value* componentJSON) { colorLight = componentJSON->getVector3("colorLight"); intensity = componentJSON->getFloat("Intensity"); }
26.075472
109
0.736614
expelthegrace
fea56f27d43c67c9ccb569e6d805f3364226f565
16,573
cc
C++
quiche/http2/test_tools/http2_frame_decoder_listener_test_util.cc
ktprime/quiche-1
abf85ce22e1409a870b1bf470cb5a68cbdb28e50
[ "BSD-3-Clause" ]
null
null
null
quiche/http2/test_tools/http2_frame_decoder_listener_test_util.cc
ktprime/quiche-1
abf85ce22e1409a870b1bf470cb5a68cbdb28e50
[ "BSD-3-Clause" ]
null
null
null
quiche/http2/test_tools/http2_frame_decoder_listener_test_util.cc
ktprime/quiche-1
abf85ce22e1409a870b1bf470cb5a68cbdb28e50
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "quiche/http2/test_tools/http2_frame_decoder_listener_test_util.h" #include "quiche/http2/decoder/http2_frame_decoder_listener.h" #include "quiche/http2/http2_constants.h" #include "quiche/http2/http2_structures.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { FailingHttp2FrameDecoderListener::FailingHttp2FrameDecoderListener() = default; FailingHttp2FrameDecoderListener::~FailingHttp2FrameDecoderListener() = default; bool FailingHttp2FrameDecoderListener::OnFrameHeader( const Http2FrameHeader& header) { ADD_FAILURE() << "OnFrameHeader: " << header; return false; } void FailingHttp2FrameDecoderListener::OnDataStart( const Http2FrameHeader& header) { FAIL() << "OnDataStart: " << header; } void FailingHttp2FrameDecoderListener::OnDataPayload(const char* /*data*/, size_t len) { FAIL() << "OnDataPayload: len=" << len; } void FailingHttp2FrameDecoderListener::OnDataEnd() { FAIL() << "OnDataEnd"; } void FailingHttp2FrameDecoderListener::OnHeadersStart( const Http2FrameHeader& header) { FAIL() << "OnHeadersStart: " << header; } void FailingHttp2FrameDecoderListener::OnHeadersPriority( const Http2PriorityFields& priority) { FAIL() << "OnHeadersPriority: " << priority; } void FailingHttp2FrameDecoderListener::OnHpackFragment(const char* /*data*/, size_t len) { FAIL() << "OnHpackFragment: len=" << len; } void FailingHttp2FrameDecoderListener::OnHeadersEnd() { FAIL() << "OnHeadersEnd"; } void FailingHttp2FrameDecoderListener::OnPriorityFrame( const Http2FrameHeader& header, const Http2PriorityFields& priority) { FAIL() << "OnPriorityFrame: " << header << "; priority: " << priority; } void FailingHttp2FrameDecoderListener::OnContinuationStart( const Http2FrameHeader& header) { FAIL() << "OnContinuationStart: " << header; } void FailingHttp2FrameDecoderListener::OnContinuationEnd() { FAIL() << "OnContinuationEnd"; } void FailingHttp2FrameDecoderListener::OnPadLength(size_t trailing_length) { FAIL() << "OnPadLength: trailing_length=" << trailing_length; } void FailingHttp2FrameDecoderListener::OnPadding(const char* /*padding*/, size_t skipped_length) { FAIL() << "OnPadding: skipped_length=" << skipped_length; } void FailingHttp2FrameDecoderListener::OnRstStream( const Http2FrameHeader& header, Http2ErrorCode error_code) { FAIL() << "OnRstStream: " << header << "; code=" << error_code; } void FailingHttp2FrameDecoderListener::OnSettingsStart( const Http2FrameHeader& header) { FAIL() << "OnSettingsStart: " << header; } void FailingHttp2FrameDecoderListener::OnSetting( const Http2SettingFields& setting_fields) { FAIL() << "OnSetting: " << setting_fields; } void FailingHttp2FrameDecoderListener::OnSettingsEnd() { FAIL() << "OnSettingsEnd"; } void FailingHttp2FrameDecoderListener::OnSettingsAck( const Http2FrameHeader& header) { FAIL() << "OnSettingsAck: " << header; } void FailingHttp2FrameDecoderListener::OnPushPromiseStart( const Http2FrameHeader& header, const Http2PushPromiseFields& promise, size_t total_padding_length) { FAIL() << "OnPushPromiseStart: " << header << "; promise: " << promise << "; total_padding_length: " << total_padding_length; } void FailingHttp2FrameDecoderListener::OnPushPromiseEnd() { FAIL() << "OnPushPromiseEnd"; } void FailingHttp2FrameDecoderListener::OnPing(const Http2FrameHeader& header, const Http2PingFields& ping) { FAIL() << "OnPing: " << header << "; ping: " << ping; } void FailingHttp2FrameDecoderListener::OnPingAck(const Http2FrameHeader& header, const Http2PingFields& ping) { FAIL() << "OnPingAck: " << header << "; ping: " << ping; } void FailingHttp2FrameDecoderListener::OnGoAwayStart( const Http2FrameHeader& header, const Http2GoAwayFields& goaway) { FAIL() << "OnGoAwayStart: " << header << "; goaway: " << goaway; } void FailingHttp2FrameDecoderListener::OnGoAwayOpaqueData(const char* /*data*/, size_t len) { FAIL() << "OnGoAwayOpaqueData: len=" << len; } void FailingHttp2FrameDecoderListener::OnGoAwayEnd() { FAIL() << "OnGoAwayEnd"; } void FailingHttp2FrameDecoderListener::OnWindowUpdate( const Http2FrameHeader& header, uint32_t increment) { FAIL() << "OnWindowUpdate: " << header << "; increment=" << increment; } void FailingHttp2FrameDecoderListener::OnAltSvcStart( const Http2FrameHeader& header, size_t origin_length, size_t value_length) { FAIL() << "OnAltSvcStart: " << header << "; origin_length: " << origin_length << "; value_length: " << value_length; } void FailingHttp2FrameDecoderListener::OnAltSvcOriginData(const char* /*data*/, size_t len) { FAIL() << "OnAltSvcOriginData: len=" << len; } void FailingHttp2FrameDecoderListener::OnAltSvcValueData(const char* /*data*/, size_t len) { FAIL() << "OnAltSvcValueData: len=" << len; } void FailingHttp2FrameDecoderListener::OnAltSvcEnd() { FAIL() << "OnAltSvcEnd"; } void FailingHttp2FrameDecoderListener::OnPriorityUpdateStart( const Http2FrameHeader& header, const Http2PriorityUpdateFields& priority_update) { FAIL() << "OnPriorityUpdateStart: " << header << "; prioritized_stream_id: " << priority_update.prioritized_stream_id; } void FailingHttp2FrameDecoderListener::OnPriorityUpdatePayload( const char* /*data*/, size_t len) { FAIL() << "OnPriorityUpdatePayload: len=" << len; } void FailingHttp2FrameDecoderListener::OnPriorityUpdateEnd() { FAIL() << "OnPriorityUpdateEnd"; } void FailingHttp2FrameDecoderListener::OnUnknownStart( const Http2FrameHeader& header) { FAIL() << "OnUnknownStart: " << header; } void FailingHttp2FrameDecoderListener::OnUnknownPayload(const char* /*data*/, size_t len) { FAIL() << "OnUnknownPayload: len=" << len; } void FailingHttp2FrameDecoderListener::OnUnknownEnd() { FAIL() << "OnUnknownEnd"; } void FailingHttp2FrameDecoderListener::OnPaddingTooLong( const Http2FrameHeader& header, size_t missing_length) { FAIL() << "OnPaddingTooLong: " << header << "; missing_length: " << missing_length; } void FailingHttp2FrameDecoderListener::OnFrameSizeError( const Http2FrameHeader& header) { FAIL() << "OnFrameSizeError: " << header; } LoggingHttp2FrameDecoderListener::LoggingHttp2FrameDecoderListener() : wrapped_(nullptr) {} LoggingHttp2FrameDecoderListener::LoggingHttp2FrameDecoderListener( Http2FrameDecoderListener* wrapped) : wrapped_(wrapped) {} LoggingHttp2FrameDecoderListener::~LoggingHttp2FrameDecoderListener() = default; bool LoggingHttp2FrameDecoderListener::OnFrameHeader( const Http2FrameHeader& header) { QUICHE_VLOG(1) << "OnFrameHeader: " << header; if (wrapped_ != nullptr) { return wrapped_->OnFrameHeader(header); } return true; } void LoggingHttp2FrameDecoderListener::OnDataStart( const Http2FrameHeader& header) { QUICHE_VLOG(1) << "OnDataStart: " << header; if (wrapped_ != nullptr) { wrapped_->OnDataStart(header); } } void LoggingHttp2FrameDecoderListener::OnDataPayload(const char* data, size_t len) { QUICHE_VLOG(1) << "OnDataPayload: len=" << len; if (wrapped_ != nullptr) { wrapped_->OnDataPayload(data, len); } } void LoggingHttp2FrameDecoderListener::OnDataEnd() { QUICHE_VLOG(1) << "OnDataEnd"; if (wrapped_ != nullptr) { wrapped_->OnDataEnd(); } } void LoggingHttp2FrameDecoderListener::OnHeadersStart( const Http2FrameHeader& header) { QUICHE_VLOG(1) << "OnHeadersStart: " << header; if (wrapped_ != nullptr) { wrapped_->OnHeadersStart(header); } } void LoggingHttp2FrameDecoderListener::OnHeadersPriority( const Http2PriorityFields& priority) { QUICHE_VLOG(1) << "OnHeadersPriority: " << priority; if (wrapped_ != nullptr) { wrapped_->OnHeadersPriority(priority); } } void LoggingHttp2FrameDecoderListener::OnHpackFragment(const char* data, size_t len) { QUICHE_VLOG(1) << "OnHpackFragment: len=" << len; if (wrapped_ != nullptr) { wrapped_->OnHpackFragment(data, len); } } void LoggingHttp2FrameDecoderListener::OnHeadersEnd() { QUICHE_VLOG(1) << "OnHeadersEnd"; if (wrapped_ != nullptr) { wrapped_->OnHeadersEnd(); } } void LoggingHttp2FrameDecoderListener::OnPriorityFrame( const Http2FrameHeader& header, const Http2PriorityFields& priority) { QUICHE_VLOG(1) << "OnPriorityFrame: " << header << "; priority: " << priority; if (wrapped_ != nullptr) { wrapped_->OnPriorityFrame(header, priority); } } void LoggingHttp2FrameDecoderListener::OnContinuationStart( const Http2FrameHeader& header) { QUICHE_VLOG(1) << "OnContinuationStart: " << header; if (wrapped_ != nullptr) { wrapped_->OnContinuationStart(header); } } void LoggingHttp2FrameDecoderListener::OnContinuationEnd() { QUICHE_VLOG(1) << "OnContinuationEnd"; if (wrapped_ != nullptr) { wrapped_->OnContinuationEnd(); } } void LoggingHttp2FrameDecoderListener::OnPadLength(size_t trailing_length) { QUICHE_VLOG(1) << "OnPadLength: trailing_length=" << trailing_length; if (wrapped_ != nullptr) { wrapped_->OnPadLength(trailing_length); } } void LoggingHttp2FrameDecoderListener::OnPadding(const char* padding, size_t skipped_length) { QUICHE_VLOG(1) << "OnPadding: skipped_length=" << skipped_length; if (wrapped_ != nullptr) { wrapped_->OnPadding(padding, skipped_length); } } void LoggingHttp2FrameDecoderListener::OnRstStream( const Http2FrameHeader& header, Http2ErrorCode error_code) { QUICHE_VLOG(1) << "OnRstStream: " << header << "; code=" << error_code; if (wrapped_ != nullptr) { wrapped_->OnRstStream(header, error_code); } } void LoggingHttp2FrameDecoderListener::OnSettingsStart( const Http2FrameHeader& header) { QUICHE_VLOG(1) << "OnSettingsStart: " << header; if (wrapped_ != nullptr) { wrapped_->OnSettingsStart(header); } } void LoggingHttp2FrameDecoderListener::OnSetting( const Http2SettingFields& setting_fields) { QUICHE_VLOG(1) << "OnSetting: " << setting_fields; if (wrapped_ != nullptr) { wrapped_->OnSetting(setting_fields); } } void LoggingHttp2FrameDecoderListener::OnSettingsEnd() { QUICHE_VLOG(1) << "OnSettingsEnd"; if (wrapped_ != nullptr) { wrapped_->OnSettingsEnd(); } } void LoggingHttp2FrameDecoderListener::OnSettingsAck( const Http2FrameHeader& header) { QUICHE_VLOG(1) << "OnSettingsAck: " << header; if (wrapped_ != nullptr) { wrapped_->OnSettingsAck(header); } } void LoggingHttp2FrameDecoderListener::OnPushPromiseStart( const Http2FrameHeader& header, const Http2PushPromiseFields& promise, size_t total_padding_length) { QUICHE_VLOG(1) << "OnPushPromiseStart: " << header << "; promise: " << promise << "; total_padding_length: " << total_padding_length; if (wrapped_ != nullptr) { wrapped_->OnPushPromiseStart(header, promise, total_padding_length); } } void LoggingHttp2FrameDecoderListener::OnPushPromiseEnd() { QUICHE_VLOG(1) << "OnPushPromiseEnd"; if (wrapped_ != nullptr) { wrapped_->OnPushPromiseEnd(); } } void LoggingHttp2FrameDecoderListener::OnPing(const Http2FrameHeader& header, const Http2PingFields& ping) { QUICHE_VLOG(1) << "OnPing: " << header << "; ping: " << ping; if (wrapped_ != nullptr) { wrapped_->OnPing(header, ping); } } void LoggingHttp2FrameDecoderListener::OnPingAck(const Http2FrameHeader& header, const Http2PingFields& ping) { QUICHE_VLOG(1) << "OnPingAck: " << header << "; ping: " << ping; if (wrapped_ != nullptr) { wrapped_->OnPingAck(header, ping); } } void LoggingHttp2FrameDecoderListener::OnGoAwayStart( const Http2FrameHeader& header, const Http2GoAwayFields& goaway) { QUICHE_VLOG(1) << "OnGoAwayStart: " << header << "; goaway: " << goaway; if (wrapped_ != nullptr) { wrapped_->OnGoAwayStart(header, goaway); } } void LoggingHttp2FrameDecoderListener::OnGoAwayOpaqueData(const char* data, size_t len) { QUICHE_VLOG(1) << "OnGoAwayOpaqueData: len=" << len; if (wrapped_ != nullptr) { wrapped_->OnGoAwayOpaqueData(data, len); } } void LoggingHttp2FrameDecoderListener::OnGoAwayEnd() { QUICHE_VLOG(1) << "OnGoAwayEnd"; if (wrapped_ != nullptr) { wrapped_->OnGoAwayEnd(); } } void LoggingHttp2FrameDecoderListener::OnWindowUpdate( const Http2FrameHeader& header, uint32_t increment) { QUICHE_VLOG(1) << "OnWindowUpdate: " << header << "; increment=" << increment; if (wrapped_ != nullptr) { wrapped_->OnWindowUpdate(header, increment); } } void LoggingHttp2FrameDecoderListener::OnAltSvcStart( const Http2FrameHeader& header, size_t origin_length, size_t value_length) { QUICHE_VLOG(1) << "OnAltSvcStart: " << header << "; origin_length: " << origin_length << "; value_length: " << value_length; if (wrapped_ != nullptr) { wrapped_->OnAltSvcStart(header, origin_length, value_length); } } void LoggingHttp2FrameDecoderListener::OnAltSvcOriginData(const char* data, size_t len) { QUICHE_VLOG(1) << "OnAltSvcOriginData: len=" << len; if (wrapped_ != nullptr) { wrapped_->OnAltSvcOriginData(data, len); } } void LoggingHttp2FrameDecoderListener::OnAltSvcValueData(const char* data, size_t len) { QUICHE_VLOG(1) << "OnAltSvcValueData: len=" << len; if (wrapped_ != nullptr) { wrapped_->OnAltSvcValueData(data, len); } } void LoggingHttp2FrameDecoderListener::OnAltSvcEnd() { QUICHE_VLOG(1) << "OnAltSvcEnd"; if (wrapped_ != nullptr) { wrapped_->OnAltSvcEnd(); } } void LoggingHttp2FrameDecoderListener::OnPriorityUpdateStart( const Http2FrameHeader& header, const Http2PriorityUpdateFields& priority_update) { QUICHE_VLOG(1) << "OnPriorityUpdateStart"; if (wrapped_ != nullptr) { wrapped_->OnPriorityUpdateStart(header, priority_update); } } void LoggingHttp2FrameDecoderListener::OnPriorityUpdatePayload(const char* data, size_t len) { QUICHE_VLOG(1) << "OnPriorityUpdatePayload"; if (wrapped_ != nullptr) { wrapped_->OnPriorityUpdatePayload(data, len); } } void LoggingHttp2FrameDecoderListener::OnPriorityUpdateEnd() { QUICHE_VLOG(1) << "OnPriorityUpdateEnd"; if (wrapped_ != nullptr) { wrapped_->OnPriorityUpdateEnd(); } } void LoggingHttp2FrameDecoderListener::OnUnknownStart( const Http2FrameHeader& header) { QUICHE_VLOG(1) << "OnUnknownStart: " << header; if (wrapped_ != nullptr) { wrapped_->OnUnknownStart(header); } } void LoggingHttp2FrameDecoderListener::OnUnknownPayload(const char* data, size_t len) { QUICHE_VLOG(1) << "OnUnknownPayload: len=" << len; if (wrapped_ != nullptr) { wrapped_->OnUnknownPayload(data, len); } } void LoggingHttp2FrameDecoderListener::OnUnknownEnd() { QUICHE_VLOG(1) << "OnUnknownEnd"; if (wrapped_ != nullptr) { wrapped_->OnUnknownEnd(); } } void LoggingHttp2FrameDecoderListener::OnPaddingTooLong( const Http2FrameHeader& header, size_t missing_length) { QUICHE_VLOG(1) << "OnPaddingTooLong: " << header << "; missing_length: " << missing_length; if (wrapped_ != nullptr) { wrapped_->OnPaddingTooLong(header, missing_length); } } void LoggingHttp2FrameDecoderListener::OnFrameSizeError( const Http2FrameHeader& header) { QUICHE_VLOG(1) << "OnFrameSizeError: " << header; if (wrapped_ != nullptr) { wrapped_->OnFrameSizeError(header); } } } // namespace http2
32.369141
80
0.679298
ktprime
feaa372bc87f1b92e044ca48f3f5f99d2b7de9bb
8,646
cc
C++
components/offline_pages/core/prefetch/tasks/metrics_finalization_task_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
components/offline_pages/core/prefetch/tasks/metrics_finalization_task_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
components/offline_pages/core/prefetch/tasks/metrics_finalization_task_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/offline_pages/core/prefetch/tasks/metrics_finalization_task.h" #include <memory> #include <set> #include <vector> #include "base/test/metrics/histogram_tester.h" #include "base/time/time.h" #include "components/offline_pages/core/prefetch/mock_prefetch_item_generator.h" #include "components/offline_pages/core/prefetch/prefetch_item.h" #include "components/offline_pages/core/prefetch/prefetch_types.h" #include "components/offline_pages/core/prefetch/store/prefetch_store_test_util.h" #include "components/offline_pages/core/prefetch/tasks/prefetch_task_test_base.h" #include "components/offline_pages/core/test_scoped_offline_clock.h" #include "testing/gtest/include/gtest/gtest.h" namespace offline_pages { class MetricsFinalizationTaskTest : public PrefetchTaskTestBase { public: MetricsFinalizationTaskTest() = default; ~MetricsFinalizationTaskTest() override = default; void SetUp() override; void TearDown() override; protected: std::unique_ptr<MetricsFinalizationTask> metrics_finalization_task_; }; void MetricsFinalizationTaskTest::SetUp() { PrefetchTaskTestBase::SetUp(); metrics_finalization_task_ = std::make_unique<MetricsFinalizationTask>(store()); } void MetricsFinalizationTaskTest::TearDown() { metrics_finalization_task_.reset(); PrefetchTaskTestBase::TearDown(); } TEST_F(MetricsFinalizationTaskTest, StoreFailure) { store_util()->SimulateInitializationError(); // Execute the metrics task. RunTask(metrics_finalization_task_.get()); } // Tests that the task works correctly with an empty database. TEST_F(MetricsFinalizationTaskTest, EmptyRun) { EXPECT_EQ(0, store_util()->CountPrefetchItems()); // Execute the metrics task. RunTask(metrics_finalization_task_.get()); EXPECT_EQ(0, store_util()->CountPrefetchItems()); } TEST_F(MetricsFinalizationTaskTest, LeavesOtherStatesAlone) { std::vector<PrefetchItemState> all_states_but_finished = GetAllStatesExcept({PrefetchItemState::FINISHED}); for (auto& state : all_states_but_finished) { PrefetchItem item = item_generator()->CreateItem(state); EXPECT_TRUE(store_util()->InsertPrefetchItem(item)) << "Failed inserting item with state " << static_cast<int>(state); } std::set<PrefetchItem> all_inserted_items; EXPECT_EQ(10U, store_util()->GetAllItems(&all_inserted_items)); // Execute the task. RunTask(metrics_finalization_task_.get()); std::set<PrefetchItem> all_items_after_task; EXPECT_EQ(10U, store_util()->GetAllItems(&all_items_after_task)); EXPECT_EQ(all_inserted_items, all_items_after_task); } TEST_F(MetricsFinalizationTaskTest, FinalizesMultipleItems) { base::Time before_insert_time = base::Time::Now(); std::set<PrefetchItem> finished_items = { item_generator()->CreateItem(PrefetchItemState::FINISHED), item_generator()->CreateItem(PrefetchItemState::FINISHED), item_generator()->CreateItem(PrefetchItemState::FINISHED)}; for (auto& item : finished_items) { ASSERT_TRUE(store_util()->InsertPrefetchItem(item)); // Confirms that ItemGenerator did set |freshness_time| with Time::Now(). ASSERT_LE(before_insert_time, item.freshness_time); } PrefetchItem unfinished_item = item_generator()->CreateItem(PrefetchItemState::NEW_REQUEST); ASSERT_TRUE(store_util()->InsertPrefetchItem(unfinished_item)); // Overrides the offline clock and set a current time in the future. TestScopedOfflineClock clock; clock.SetNow(before_insert_time + base::Hours(1)); // Execute the metrics task. RunTask(metrics_finalization_task_.get()); // The finished ones should all have become zombies and the new request should // be untouched. std::set<PrefetchItem> all_items; EXPECT_EQ(4U, store_util()->GetAllItems(&all_items)); EXPECT_EQ(0U, FilterByState(all_items, PrefetchItemState::FINISHED).size()); std::set<PrefetchItem> zombie_items = FilterByState(all_items, PrefetchItemState::ZOMBIE); EXPECT_EQ(3U, zombie_items.size()); for (const PrefetchItem& zombie_item : zombie_items) { EXPECT_EQ(clock.Now(), zombie_item.freshness_time) << "Incorrect freshness_time (not updated?) for item " << zombie_item.client_id; } std::set<PrefetchItem> items_in_new_request_state = FilterByState(all_items, PrefetchItemState::NEW_REQUEST); EXPECT_EQ(1U, items_in_new_request_state.count(unfinished_item)); } TEST_F(MetricsFinalizationTaskTest, MetricsAreReported) { PrefetchItem successful_item = item_generator()->CreateItem(PrefetchItemState::FINISHED); successful_item.generate_bundle_attempts = 1; successful_item.get_operation_attempts = 1; successful_item.download_initiation_attempts = 1; ASSERT_TRUE(store_util()->InsertPrefetchItem(successful_item)); PrefetchItem failed_item = item_generator()->CreateItem(PrefetchItemState::RECEIVED_GCM); failed_item.state = PrefetchItemState::FINISHED; failed_item.error_code = PrefetchItemErrorCode::ARCHIVING_FAILED; ASSERT_TRUE(store_util()->InsertPrefetchItem(failed_item)); PrefetchItem unfinished_item = item_generator()->CreateItem(PrefetchItemState::NEW_REQUEST); ASSERT_TRUE(store_util()->InsertPrefetchItem(unfinished_item)); // Execute the metrics task. base::HistogramTester histogram_tester; RunTask(metrics_finalization_task_.get()); std::set<PrefetchItem> all_items; EXPECT_EQ(3U, store_util()->GetAllItems(&all_items)); EXPECT_EQ(2U, FilterByState(all_items, PrefetchItemState::ZOMBIE).size()); EXPECT_EQ(1U, FilterByState(all_items, PrefetchItemState::NEW_REQUEST).size()); // One successful and one failed samples. histogram_tester.ExpectUniqueSample( "OfflinePages.Prefetching.ItemLifetime.Successful", 0, 1); histogram_tester.ExpectUniqueSample( "OfflinePages.Prefetching.ItemLifetime.Failed", 0, 1); // One sample for each_error code value. histogram_tester.ExpectTotalCount( "OfflinePages.Prefetching.FinishedItemErrorCode", 2); histogram_tester.ExpectBucketCount( "OfflinePages.Prefetching.FinishedItemErrorCode", static_cast<int>(PrefetchItemErrorCode::SUCCESS), 1); histogram_tester.ExpectBucketCount( "OfflinePages.Prefetching.FinishedItemErrorCode", static_cast<int>(PrefetchItemErrorCode::ARCHIVING_FAILED), 1); // Attempt values match what was set above (non set values default to 0). histogram_tester.ExpectTotalCount( "OfflinePages.Prefetching.ActionAttempts.GeneratePageBundle", 2); histogram_tester.ExpectBucketCount( "OfflinePages.Prefetching.ActionAttempts.GeneratePageBundle", 0, 1); histogram_tester.ExpectBucketCount( "OfflinePages.Prefetching.ActionAttempts.GeneratePageBundle", 1, 1); histogram_tester.ExpectTotalCount( "OfflinePages.Prefetching.ActionAttempts.GetOperation", 2); histogram_tester.ExpectBucketCount( "OfflinePages.Prefetching.ActionAttempts.GetOperation", 0, 1); histogram_tester.ExpectBucketCount( "OfflinePages.Prefetching.ActionAttempts.GetOperation", 1, 1); histogram_tester.ExpectTotalCount( "OfflinePages.Prefetching.ActionAttempts.DownloadInitiation", 2); histogram_tester.ExpectBucketCount( "OfflinePages.Prefetching.ActionAttempts.DownloadInitiation", 0, 1); histogram_tester.ExpectBucketCount( "OfflinePages.Prefetching.ActionAttempts.DownloadInitiation", 1, 1); } // Verifies that items from all states are counted properly. TEST_F(MetricsFinalizationTaskTest, CountsItemsInEachStateMetricReportedCorectly) { // Insert a different number of items for each state. for (size_t i = 0; i < kOrderedPrefetchItemStates.size(); ++i) { PrefetchItemState state = kOrderedPrefetchItemStates[i]; for (size_t j = 0; j < i + 1; ++j) { PrefetchItem item = item_generator()->CreateItem(state); EXPECT_TRUE(store_util()->InsertPrefetchItem(item)) << "Failed inserting item with state " << static_cast<int>(state); } } // Execute the task. base::HistogramTester histogram_tester; RunTask(metrics_finalization_task_.get()); histogram_tester.ExpectTotalCount("OfflinePages.Prefetching.StateCounts", 66); // Check that histogram was recorded correctly for items in each state. for (size_t i = 0; i < kOrderedPrefetchItemStates.size(); ++i) { histogram_tester.ExpectBucketCount( "OfflinePages.Prefetching.StateCounts", static_cast<int>(kOrderedPrefetchItemStates[i]), i + 1); } } } // namespace offline_pages
39.479452
83
0.768679
zealoussnow
feac833cbd24d7144743f1757a134c8932f38a2c
64,956
cpp
C++
common/workunit/wujobq.cpp
jeclrsg/HPCC-Platform
c1daafb6060f0c47c95bce98e5431fedc33c592d
[ "Apache-2.0" ]
286
2015-01-03T12:45:17.000Z
2022-03-25T18:12:57.000Z
common/workunit/wujobq.cpp
jeclrsg/HPCC-Platform
c1daafb6060f0c47c95bce98e5431fedc33c592d
[ "Apache-2.0" ]
9,034
2015-01-02T08:49:19.000Z
2022-03-31T20:34:44.000Z
common/workunit/wujobq.cpp
jeclrsg/HPCC-Platform
c1daafb6060f0c47c95bce98e5431fedc33c592d
[ "Apache-2.0" ]
208
2015-01-02T03:27:28.000Z
2022-02-11T05:54:52.000Z
/*############################################################################## HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ############################################################################## */ #include "platform.h" #include <algorithm> #include "limits.h" #include "jlib.hpp" #include "jbuff.hpp" #include "jsecrets.hpp" #include "dasess.hpp" #include "dautils.hpp" #include "portlist.h" #include "dacoven.hpp" #include "daclient.hpp" #include "dasds.hpp" #include "dasess.hpp" #include "daqueue.hpp" #include "workunit.hpp" #include "wujobq.hpp" #include "securesocket.hpp" #ifndef _CONTAINERIZED #include "environment.hpp" #endif #ifdef _MSC_VER #pragma warning (disable : 4355) #endif #if 0 JobQueues JobQueue @name= @count= @state=active|paused|stopped Edition <num> Client @session= @connected= @waiting= -- connections and waiting can be > 1 (multiple threads) Item* @wuid @owner @node @port @priority @session #endif class CJobQueueItem: implements IJobQueueItem, public CInterface { int priority; StringAttr wu; StringAttr owner; SessionId sessid; SocketEndpoint ep; unsigned port; CDateTime enqueuedt; public: IMPLEMENT_IINTERFACE; CJobQueueItem(MemoryBuffer &src) { deserialize(src); } CJobQueueItem(const char *_wu) : wu(_wu) { priority = 0; ep = queryMyNode()->endpoint(); port = 0; sessid = myProcessSession(); } CJobQueueItem(IPropertyTree *item) { const char * wuid = item->queryProp("@wuid"); if (*wuid=='~') wuid++; wu.set(wuid); owner.set(item->queryProp("@owner")); sessid = (SessionId)item->getPropInt64("@session"); priority = item->getPropInt("@priority"); ep.set(item->queryProp("@node")); port = (unsigned)item->getPropInt("@port"); StringBuffer dts; if (item->getProp("@enqueuedt",dts)) enqueuedt.setString(dts.str()); } static void assignBranch(IPropertyTree *item,IJobQueueItem *qi) { item->setPropInt64("@session",qi->getSessionId()); item->setPropInt("@priority",qi->getPriority()); item->setPropInt("@port",qi->getPort()); item->setProp("@wuid",qi->queryWUID()); item->setProp("@owner",qi->queryOwner()); StringBuffer eps; qi->queryEndpoint().getUrlStr(eps); item->setProp("@node",eps.str()); StringBuffer dts; qi->queryEnqueuedTime().getString(dts); if (dts.length()==0) { CDateTime dt; dt.setNow(); dt.getString(dts); qi->setEnqueuedTime(dt); } item->setProp("@enqueuedt",dts.str()); } const char *queryWUID() { return wu.get(); } int getPriority() { return priority; } unsigned getPort() { return port; } SessionId getSessionId() { return sessid; } SocketEndpoint &queryEndpoint() { return ep; } const char *queryOwner() { return owner.get(); } bool equals(IJobQueueItem *other) { // work unit is primary key return strcmp(wu.get(),other->queryWUID())==0; } CDateTime &queryEnqueuedTime() { return enqueuedt; } void setEnqueuedTime(const CDateTime &dt) { enqueuedt.set(dt); } void serialize(MemoryBuffer &tgt) { tgt.append(priority).append(port).append(wu).append(sessid); ep.serialize(tgt); StringBuffer dts; enqueuedt.getString(dts); tgt.append(owner).append(dts); } void deserialize(MemoryBuffer &src) { src.read(priority).read(port).read(wu).read(sessid); ep.deserialize(src); StringBuffer dts; src.read(owner).read(dts); enqueuedt.setString(dts.str()); } IJobQueueItem* clone() { IJobQueueItem* ret = new CJobQueueItem(wu); ret->setPriority(priority); ret->setPriority(port); ret->setEndpoint(ep); ret->setSessionId(sessid); return ret; } void setPriority(int _priority) { priority = _priority; } void setPort(unsigned _port) { port = _port; } void setEndpoint(const SocketEndpoint &_ep) { ep = _ep; } void setSessionId(SessionId _id) { if (_id) sessid = _id; else sessid = myProcessSession(); } void setOwner(const char *_owner) { owner.set(_owner); } bool isValidSession() { Owned<INode> node = createINode(ep); return (querySessionManager().lookupProcessSession(node)==sessid); } }; class CJobQueueIterator: implements IJobQueueIterator, public CInterface { public: CJobQueueContents &items; unsigned idx; IMPLEMENT_IINTERFACE; CJobQueueIterator(CJobQueueContents &_items) : items(_items) { idx = 0; } bool isValid() { return idx<items.ordinality(); } bool first() { idx = 0; return isValid(); } bool next() { idx++; return isValid(); } IJobQueueItem & query() { return items.item(idx); } }; IJobQueueIterator *CJobQueueContents::getIterator() { return new CJobQueueIterator(*this); } IJobQueueItem *createJobQueueItem(const char *wuid) { if (!wuid||!*wuid) throw MakeStringException(-1,"createJobQueueItem empty WUID"); return new CJobQueueItem(wuid);; } IJobQueueItem *deserializeJobQueueItem(MemoryBuffer &mb) { return new CJobQueueItem(mb); } #define ForEachQueue(qd) for (sQueueData *qd = qdata; qd!=NULL; qd=qd->next) #define ForEachQueueIn(parent,qd) for (sQueueData *qd = parent.qdata; qd!=NULL; qd=qd->next) struct sQueueData { sQueueData *next; IRemoteConnection *conn; StringAttr qname; IPropertyTree *root; SubscriptionId subscriberid; unsigned lastWaitEdition; }; class CJobQueueBase: implements IJobQueueConst, public CInterface { class cOrderedIterator { CJobQueueBase &parent; unsigned numqueues; unsigned *queueidx; sQueueData **queues; IPropertyTree **queuet; MemoryAttr ma; unsigned current; public: cOrderedIterator(CJobQueueBase&_parent) : parent(_parent) { numqueues=0; ForEachQueueIn(parent,qd1) if (qd1->root) numqueues++; queueidx = (unsigned *)ma.allocate(numqueues*(sizeof(unsigned)+sizeof(sQueueData *)+sizeof(IPropertyTree *))); queues = (sQueueData **)(queueidx+numqueues); queuet = (IPropertyTree **)(queues+numqueues); unsigned i = 0; ForEachQueueIn(parent,qd2) { if (qd2->root) queues[i++] = qd2; } current = (unsigned)-1; } bool first() { StringBuffer path; parent.getItemPath(path,0U); current = (unsigned)-1; for (unsigned i = 0; i<numqueues;i++) { queueidx[i] = 0; queuet[i] = queues[i]->root->queryPropTree(path.str()); if (queuet[i]) if ((current==(unsigned)-1)||parent.itemOlder(queuet[i],queuet[current])) current = i; } return current!=(unsigned)-1; } bool next() { if (current==(unsigned)-1) return false; queueidx[current]++; StringBuffer path; parent.getItemPath(path,queueidx[current]); queuet[current] = queues[current]->root->queryPropTree(path.str()); current = (unsigned)-1; for (unsigned i = 0; i<numqueues;i++) { if (queuet[i]) if ((current==(unsigned)-1)||parent.itemOlder(queuet[i],queuet[current])) current = i; } return current!=(unsigned)-1; } bool isValid() { return current!=(unsigned)-1; } void item(sQueueData *&qd, IPropertyTree *&t,unsigned &idx) { assertex(current!=(unsigned)-1); qd = queues[current]; t = queuet[current]; idx = queueidx[current]; } sQueueData &queryQueue() { assertex(current!=(unsigned)-1); return *queues[current]; } IPropertyTree &queryTree() { assertex(current!=(unsigned)-1); return *queuet[current]; } }; protected: bool doGetLastDequeuedInfo(sQueueData *qd, StringAttr &wuid, CDateTime &enqueuedt, int &priority) { priority = 0; if (!qd) return false; const char *w = qd->root->queryProp("@prevwuid"); if (!w||!*w) return false; wuid.set(w); StringBuffer dts; if (qd->root->getProp("@prevenqueuedt",dts)) enqueuedt.setString(dts.str()); priority = qd->root->getPropInt("@prevpriority"); return true; } public: sQueueData *qdata; Semaphore notifysem; CriticalSection crit; IMPLEMENT_IINTERFACE; CJobQueueBase(const char *_qname) { StringArray qlist; qlist.appendListUniq(_qname, ","); sQueueData *last = NULL; ForEachItemIn(i,qlist) { sQueueData *qd = new sQueueData; qd->next = NULL; qd->qname.set(qlist.item(i)); qd->conn = NULL; qd->root = NULL; qd->lastWaitEdition = 0; qd->subscriberid = 0; if (last) last->next = qd; else qdata = qd; last = qd; } }; virtual ~CJobQueueBase() { while (qdata) { sQueueData * next = qdata->next; delete qdata; qdata = next; } } StringBuffer &getItemPath(StringBuffer &path,const char *wuid) { if (!wuid||!*wuid) return getItemPath(path,0U); return path.appendf("Item[@wuid=\"%s\"]",wuid); } StringBuffer &getItemPath(StringBuffer &path,unsigned idx) { path.appendf("Item[@num=\"%d\"]",idx+1); return path; } IPropertyTree *queryClientRootIndex(sQueueData &qd, unsigned idx) { VStringBuffer path("Client[%d]", idx+1); return qd.root->queryPropTree(path); } bool itemOlder(IPropertyTree *qt1, IPropertyTree *qt2) { // if this ever becomes time critical thne could cache enqueued values StringBuffer d1s; if (qt1) qt1->getProp("@enqueuedt",d1s); StringBuffer d2s; if (qt2) qt2->getProp("@enqueuedt",d2s); return (strcmp(d1s.str(),d2s.str())<0); } IJobQueueItem *doGetItem(sQueueData &qd,unsigned idx) { if (idx==(unsigned)-1) { idx = qd.root->getPropInt("@count"); if (!idx) return NULL; idx--; } StringBuffer path; IPropertyTree *item = qd.root->queryPropTree(getItemPath(path,idx).str()); if (!item) return NULL; return new CJobQueueItem(item); } IJobQueueItem *getItem(sQueueData &qd,unsigned idx) { return doGetItem(qd, idx); } IJobQueueItem *getHead(sQueueData &qd) { return getItem(qd,0); } unsigned doFindRank(sQueueData &qd,const char *wuid) { StringBuffer path; IPropertyTree *item = qd.root->queryPropTree(getItemPath(path,wuid).str()); if (!item) return (unsigned)-1; return item->getPropInt("@num")-1; } unsigned findRank(sQueueData &qd,const char *wuid) { return doFindRank(qd,wuid); } IJobQueueItem *find(sQueueData &qd,const char *wuid) { StringBuffer path; IPropertyTree *item = qd.root->queryPropTree(getItemPath(path,wuid).str()); if (!item) return NULL; bool cached = item->getPropInt("@num",0)<=0; if (wuid&&cached) return NULL; // don't want cached value unless explicit return new CJobQueueItem(item); } unsigned copyItemsImpl(sQueueData &qd,CJobQueueContents &dest) { unsigned ret=0; StringBuffer path; for (unsigned i=0;;i++) { IPropertyTree *item = qd.root->queryPropTree(getItemPath(path.clear(),i).str()); if (!item) break; ret++; dest.append(*new CJobQueueItem(item)); } return ret; } virtual void copyItemsAndState(CJobQueueContents& contents, StringBuffer& state, StringBuffer& stateDetails) { assertex(qdata); assertex(qdata->root); copyItemsImpl(*qdata,contents); const char *st = qdata->root->queryProp("@state"); if (st&&*st) state.set(st); if (st && (strieq(st, "paused") || strieq(st, "stopped"))) { const char *stDetails = qdata->root->queryProp("@stateDetails"); if (stDetails&&*stDetails) stateDetails.set(stDetails); } } sQueueData *findQD(const char *wuid) { if (wuid&&*wuid) { ForEachQueue(qd) { unsigned idx = doFindRank(*qd,wuid); if (idx!=(unsigned)-1) return qd; } } return NULL; } virtual unsigned waiting() { unsigned ret = 0; ForEachQueue(qd) { for (unsigned i=0;;i++) { IPropertyTree *croot = queryClientRootIndex(*qd,i); if (!croot) break; ret += croot->getPropInt("@waiting"); } } return ret; } virtual unsigned findRank(const char *wuid) { assertex(qdata); if (!qdata->next) return findRank(*qdata,wuid); cOrderedIterator it(*this); unsigned i = 0; ForEach(it) { const char *twuid = it.queryTree().queryProp("@wuid"); if (twuid&&(strcmp(twuid,wuid)==0)) return i; i++; } return (unsigned)-1; } virtual unsigned copyItems(CJobQueueContents &dest) { assertex(qdata); if (!qdata->next) return copyItemsImpl(*qdata,dest); cOrderedIterator it(*this); unsigned ret = 0; ForEach(it) { dest.append(*new CJobQueueItem(&it.queryTree())); ret++; } return ret; } virtual IJobQueueItem *getItem(unsigned idx) { if (!qdata) return NULL; if (!qdata->next) return getItem(*qdata,idx); cOrderedIterator it(*this); unsigned i = 0; IPropertyTree *ret = NULL; ForEach(it) { if (i==idx) { ret = &it.queryTree(); break; } else if (idx==(unsigned)-1) // -1 means return last ret = &it.queryTree(); i++; } if (ret) return new CJobQueueItem(ret); return NULL; } virtual IJobQueueItem *getHead() { if (!qdata) return NULL; if (!qdata->next) return getHead(*qdata); return getItem(0); } virtual IJobQueueItem *getTail() { if (!qdata) return NULL; if (!qdata->next) return getHead(*qdata); return getItem((unsigned)-1); } virtual IJobQueueItem *find(const char *wuid) { if (!qdata) return NULL; sQueueData *qd = qdata->next?findQD(wuid):qdata; if (!qd) return NULL; return find(*qd,wuid); } virtual bool paused() { // true if all paused ForEachQueue(qd) { if (qd->root) { const char *state = qd->root->queryProp("@state"); if (state&&(strcmp(state,"paused")!=0)) return false; } } return true; } virtual bool paused(StringBuffer& info) { // true if all paused ForEachQueue(qd) { if (qd->root) { const char *state = qd->root->queryProp("@state"); if (state&&(strcmp(state,"paused")!=0)) return false; if (state&&!info.length()) { const char *stateDetails = qd->root->queryProp("@stateDetails"); if (stateDetails && *stateDetails) info.set(stateDetails); } } } return true; } virtual bool stopped() { // true if all stopped ForEachQueue(qd) { if (qd->root) { const char *state = qd->root->queryProp("@state"); if (state&&(strcmp(state,"stopped")!=0)) return false; } } return true; } virtual bool stopped(StringBuffer& info) { // true if all stopped ForEachQueue(qd) { if (qd->root) { const char *state = qd->root->queryProp("@state"); if (state&&(strcmp(state,"stopped")!=0)) return false; if (state&&!info.length()) { const char *stateDetails = qd->root->queryProp("@stateDetails"); if (stateDetails && *stateDetails) info.set(stateDetails); } } } return true; } virtual unsigned ordinality() { unsigned ret = 0; ForEachQueue(qd) { if (qd->root) ret += qd->root->getPropInt("@count"); } return ret; } virtual bool getLastDequeuedInfo(StringAttr &wuid, CDateTime &enqueuedt, int &priority) { return doGetLastDequeuedInfo(qdata, wuid, enqueuedt, priority); } //Similar to copyItemsAndState(), this method returns the state information for one queue. virtual void getState(StringBuffer& state, StringBuffer& stateDetails) { if (!qdata->root) return; const char *st = qdata->root->queryProp("@state"); if (!st || !*st) return; state.set(st); if ((strieq(st, "paused") || strieq(st, "stopped"))) stateDetails.set(qdata->root->queryProp("@stateDetails")); } }; class CJobQueueConst: public CJobQueueBase { Owned<IPropertyTree> jobQueueSnapshot; public: CJobQueueConst(const char *_qname, IPropertyTree* _jobQueueSnapshot) : CJobQueueBase(_qname) { if (!_jobQueueSnapshot) throw MakeStringException(-1, "No job queue snapshot"); jobQueueSnapshot.setown(_jobQueueSnapshot); ForEachQueue(qd) { VStringBuffer path("Queue[@name=\"%s\"]", qd->qname.get()); qd->root = jobQueueSnapshot->queryPropTree(path.str()); if (!qd->root) throw MakeStringException(-1, "No job queue found for %s", qd->qname.get()); } }; }; class CJobQueue: public CJobQueueBase, implements IJobQueue { public: sQueueData *activeq; SessionId sessionid; unsigned locknest; bool writemode; bool connected; Owned<IConversation> initiateconv; StringAttr initiatewu; bool dequeuestop; bool cancelwaiting; bool validateitemsessions; class csubs: implements ISDSSubscription, public CInterface { CJobQueue *parent; public: IMPLEMENT_IINTERFACE; csubs(CJobQueue *_parent) { parent = _parent; } void notify(SubscriptionId id, const char *xpath, SDSNotifyFlags flags, unsigned valueLen, const void *valueData) { CriticalBlock block(parent->crit); parent->notifysem.signal(); } } subs; IMPLEMENT_IINTERFACE; CJobQueue(const char *_qname) : CJobQueueBase(_qname), subs(this) { activeq = qdata; sessionid = myProcessSession(); validateitemsessions = false; writemode = false; locknest = 0; connected = false; dequeuestop = false; cancelwaiting = false; Cconnlockblock block(this,false); // this just checks queue exists } virtual ~CJobQueue() { try { while (locknest) connunlock(true); // auto rollback if (connected) disconnect(); } catch (IException *e) { // server error EXCLOG(e, "~CJobQueue"); e->Release(); } try { // must attempt to remove subscription before object destroyed. dounsubscribe(); } catch (IException *e) { EXCLOG(e, "~CJobQueue calling dounsubscribe"); e->Release(); } } void connlock(bool exclusive) { // must be in sect if (locknest++==0) { unsigned wait = qdata&&qdata->next?5000:INFINITE; ForEachQueue(qd) { for (;;) { StringBuffer path; path.appendf("/JobQueues/Queue[@name=\"%s\"]",qd->qname.get()); bool timeout; for (;;) { timeout=false; try { qd->conn = querySDS().connect(path.str(),myProcessSession(),exclusive?RTM_LOCK_WRITE:RTM_LOCK_READ,wait); if (qd->conn) break; } catch (ISDSException *e) { if (SDSExcpt_LockTimeout != e->errorCode()) throw; e->Release(); timeout = true; } // create queue Owned<IRemoteConnection> pconn; try { pconn.setown(querySDS().connect("/JobQueues",myProcessSession(),RTM_LOCK_WRITE|RTM_CREATE_QUERY,wait)); if (!pconn) throw MakeStringException(-1,"CJobQueue could not create JobQueues"); IPropertyTree *proot = pconn->queryRoot(); StringBuffer cpath; cpath.appendf("Queue[@name=\"%s\"]",qd->qname.get()); if (!proot->hasProp(cpath.str())) { IPropertyTree *pt = proot->addPropTree("Queue"); pt->setProp("@name",qd->qname.get()); pt->setProp("@state","active"); pt->setPropInt("@count", 0); pt->setPropInt("Edition", 1); } } catch (ISDSException *e) { if (SDSExcpt_LockTimeout != e->errorCode()) throw; e->Release(); timeout = true; } } if (!timeout) break; sQueueData *qd2 = qdata; do { ::Release(qd2->conn); qd2->conn = NULL; qd2->root = NULL; } while (qd2!=qd); PROGLOG("Job Queue contention - delaying before retrying"); Sleep(getRandom()%5000); // dining philosopher delay wait = getRandom()%4000+3000; // try and prevent sync qd = qdata; } qd->root = qd->conn->queryRoot(); } writemode = exclusive; } else { if (exclusive&&!writemode) { ForEachQueue(qd) { assertex(qd->conn); writemode = exclusive; bool lockreleased; safeChangeModeWrite(qd->conn,qd->qname.get(),lockreleased); qd->root = qd->conn->queryRoot(); } } } } void connunlock(bool rollback=false) { // should be in sect if (--locknest==0) { ForEachQueue(qd) { if (qd->conn) { // can occur if connection to dali threw exception if (writemode) { if (rollback) qd->conn->rollback(); else { qd->root->setPropInt("Edition",qd->root->getPropInt("Edition")+1); qd->conn->commit(); } } qd->conn->Release(); qd->conn = NULL; } qd->root = NULL; } writemode = false; } } void conncommit() // doesn't set edition { // called within sect if (writemode) { ForEachQueue(qd) { if (qd->conn) qd->conn->commit(); } } } class Cconnlockblock: public CriticalBlock { CJobQueue *parent; bool rollback; public: Cconnlockblock(CJobQueue *_parent,bool exclusive) : CriticalBlock(_parent->crit) { parent = _parent; parent->connlock(exclusive); rollback = false; } ~Cconnlockblock() { parent->connunlock(rollback); } void setRollback(bool set=true) { rollback = set; } void commit() { parent->conncommit(); } }; void removeItem(sQueueData &qd,IPropertyTree *item, bool cache) { // does not adjust or use @count unsigned n = item->getPropInt("@num"); if (!n) return; if (cache) { StringBuffer s; item->getProp("@wuid",s.clear()); qd.root->setProp("@prevwuid",s.str()); item->getProp("@enqueuedt",s.clear()); qd.root->setProp("@prevenqueuedt",s.str()); qd.root->setPropInt("@prevpriority",item->getPropInt("@priority")); } item->setPropInt("@num",-1); StringBuffer path; for (;;) { IPropertyTree *item2 = qd.root->queryPropTree(getItemPath(path.clear(),n).str()); if (!item2) break; item2->setPropInt("@num",n); n++; } qd.root->removeTree(item); } IPropertyTree *addItem(sQueueData &qd,IPropertyTree *item,unsigned idx,unsigned count) { // does not set any values other than num StringBuffer path; // first move following up unsigned n=count; while (n>idx) { n--; qd.root->queryPropTree(getItemPath(path.clear(),n).str())->setPropInt("@num",n+2); } item->setPropInt("@num",idx+1); return qd.root->addPropTree("Item",item); } void dosubscribe() { // called in crit section ForEachQueue(qd) { if (qd->subscriberid) { querySDS().unsubscribe(qd->subscriberid); qd->subscriberid = 0; } StringBuffer path; path.appendf("/JobQueues/Queue[@name=\"%s\"]/Edition",qd->qname.get()); qd->subscriberid = querySDS().subscribe(path.str(), subs, false); } } bool haschanged() // returns if any changed { bool changed = false; ForEachQueue(qd) { if (!qd->subscriberid) { StringBuffer path; path.appendf("/JobQueues/Queue[@name=\"%s\"]/Edition",qd->qname.get()); qd->subscriberid = querySDS().subscribe(path.str(), subs, false); } unsigned e = (unsigned)qd->root->getPropInt("Edition", 1); if (e!=qd->lastWaitEdition) { qd->lastWaitEdition = e; changed = true; break; } } return changed; } void dounsubscribe() { // called in crit section ForEachQueue(qd) { if (qd->subscriberid) { querySDS().unsubscribe(qd->subscriberid); qd->subscriberid = 0; } } } IPropertyTree *queryClientRootSession(sQueueData &qd) { VStringBuffer path("Client[@session=\"%" I64F "d\"]", sessionid); IPropertyTree *ret = qd.root->queryPropTree(path.str()); if (!ret) { ret = qd.root->addPropTree("Client"); ret->setPropInt64("@session",sessionid); StringBuffer eps; ret->setProp("@node",queryMyNode()->endpoint().getUrlStr(eps).str()); } return ret; } void connect(bool _validateitemsessions) { Cconnlockblock block(this,true); validateitemsessions = _validateitemsessions; if (connected) disconnect(); dosubscribe(); ForEachQueue(qd) { if (validateitemsessions) { unsigned connected; unsigned waiting; unsigned count; getStats(*qd,connected,waiting,count); // clear any duff clients } IPropertyTree *croot = queryClientRootSession(*qd); croot->setPropInt64("@connected",croot->getPropInt64("@connected",0)+1); } connected = true; } void disconnect() // signal no longer wil be dequeing (optional - done automatically on release) { Cconnlockblock block(this,true); if (connected) { dounsubscribe(); ForEachQueue(qd) { IPropertyTree *croot = queryClientRootSession(*qd); croot->setPropInt64("@connected",croot->getPropInt64("@connected",0)-1); } connected = false; } } sQueueData *findbestqueue(bool useprev,int minprio,unsigned numqueues,sQueueData **queues) { if (numqueues==0) return NULL; if (numqueues==1) return *queues; sQueueData *best = NULL; IPropertyTree *bestt = NULL; for (unsigned i=0;i<numqueues;i++) { sQueueData *qd = queues[i]; unsigned count = qd->root->getPropInt("@count"); if (count) { int mpr = useprev?std::max(qd->root->getPropInt("@prevpriority"),minprio):minprio; if (count&&((minprio==INT_MIN)||checkprio(*qd,mpr))) { StringBuffer path; IPropertyTree *item = qd->root->queryPropTree(getItemPath(path,0U).str()); if (!item) continue; if (item->getPropInt("@num",0)<=0) continue; CDateTime dt; StringBuffer enqueued; if (!best||itemOlder(item,bestt)) { best = qd; bestt = item; } } } } return best; } void setWaiting(unsigned numqueues,sQueueData **queues, bool set) { for (unsigned i=0; i<numqueues; i++) { IPropertyTree *croot = queryClientRootSession(*queues[i]); croot->setPropInt64("@waiting",croot->getPropInt64("@waiting",0)+(set?1:-1)); } } // 'simple' queuing IJobQueueItem *dodequeue(int minprio,unsigned timeout=INFINITE, bool useprev=false, bool *timedout=NULL) { bool hasminprio=(minprio!=INT_MIN); if (timedout) *timedout = false; IJobQueueItem *ret=NULL; bool waitingset = false; while (!dequeuestop) { unsigned t = 0; if (timeout!=(unsigned)INFINITE) t = msTick(); { Cconnlockblock block(this,true); block.setRollback(true); // assume not going to update // now cycle through queues looking at state unsigned total = 0; unsigned stopped = 0; PointerArray active; ForEachQueue(qd) { total++; const char *state = qd->root->queryProp("@state"); if (state) { if (strcmp(state,"stopped")==0) stopped++; else if (strcmp(state,"paused")!=0) active.append(qd); } else active.append(qd); } if (stopped==total) return NULL; // all stopped sQueueData **activeqds = (sQueueData **)active.getArray(); unsigned activenum = active.ordinality(); if (activenum) { sQueueData *bestqd = findbestqueue(useprev,minprio,activenum,activeqds); unsigned count = bestqd?bestqd->root->getPropInt("@count"):0; // load minp from cache if (count) { int mpr = useprev?std::max(bestqd->root->getPropInt("@prevpriority"),minprio):minprio; if (!hasminprio||checkprio(*bestqd,mpr)) { block.setRollback(false); ret = dotake(*bestqd,NULL,true,hasminprio,mpr); if (ret) // think it must be! timeout = 0; // so mark that done else if (!hasminprio) { WARNLOG("Resetting queue %s",bestqd->qname.get()); clear(*bestqd); // reset queue as seems to have become out of sync } } } if (timeout!=0) { // more to do if (!connected) { // if connect already done non-zero connect(validateitemsessions); block.setRollback(false); } if (!waitingset) { setWaiting(activenum,activeqds,true); block.commit(); waitingset = true; } } } if (timeout==0) { if (waitingset) { setWaiting(activenum,activeqds,false); block.commit(); } if (timedout) *timedout = (ret==NULL); break; } } unsigned to = 5*60*1000; // check every 5 mins independant of notify (in case subscription lost for some reason) if (to>timeout) to = timeout; notifysem.wait(to); if (timeout!=(unsigned)INFINITE) { t = msTick()-t; if (t<timeout) timeout -= t; else timeout = 0; } } return ret; } IJobQueueItem *dequeue(unsigned timeout=INFINITE) { return dodequeue(INT_MIN,timeout); } IJobQueueItem *prioDequeue(int minprio,unsigned timeout=INFINITE) // minprio == MAX_INT - used cache priority { return dodequeue(minprio,timeout); } void placeonqueue(sQueueData &qd, IJobQueueItem *qitem,unsigned idx) // takes ownership of qitem { Owned<IJobQueueItem> qi = qitem; remove(qi->queryWUID()); // just in case trying to put on twice! int priority = qi->getPriority(); unsigned count = qd.root->getPropInt("@count"); StringBuffer path; if (count&&(idx!=(unsigned)-1)) { // need to check before and after if (idx) { IPropertyTree *pt = qd.root->queryPropTree(getItemPath(path.clear(),idx-1).str()); if (pt) { int pp = pt->getPropInt("@priority"); if (priority>pp) { qi->setPriority(pp); priority = pp; } } else // what happened here? idx = (unsigned)-1; } if (idx<count) { IPropertyTree *pt = qd.root->queryPropTree(getItemPath(path.clear(),idx).str()); if (pt) { int pp = pt->getPropInt("@priority"); if (priority<pp) { qi->setPriority(pp); priority = pp; } } else // what happened here? idx = (unsigned)-1; } } if (idx==(unsigned)-1) { idx = count; while (idx) { IPropertyTree *previtem = qd.root->queryPropTree(getItemPath(path.clear(),idx-1).str()); if (previtem) { if (previtem->getPropInt("@priority")>=priority) { break; } } else count--; // how did that happen? idx--; } } CJobQueueItem::assignBranch(addItem(qd,createPTree("Item"),idx,count),qi); qd.root->setPropInt("@count",count+1); } void enqueue(sQueueData &qd,IJobQueueItem *qitem) // takes ownership of qitem { Cconnlockblock block(this,true); placeonqueue(qd,qitem,(unsigned)-1); } void enqueueBefore(sQueueData &qd,IJobQueueItem *qitem,const char *wuid) { Cconnlockblock block(this,true); placeonqueue(qd,qitem,doFindRank(qd,wuid)); } void enqueueAfter(sQueueData &qd,IJobQueueItem *qitem,const char *wuid) { Cconnlockblock block(this,true); unsigned idx = doFindRank(qd,wuid); if (idx!=(unsigned)-1) idx++; placeonqueue(qd,qitem,idx); } void enqueueTail(sQueueData &qd,IJobQueueItem *qitem) { Cconnlockblock block(this,true); Owned<IJobQueueItem> qi = getTail(qd); if (qi) enqueueAfter(qd,qitem,qi->queryWUID()); else enqueue(qd,qitem); } void enqueueHead(sQueueData &qd,IJobQueueItem *qitem) { Cconnlockblock block(this,true); Owned<IJobQueueItem> qi = doGetItem(qd, 0); if (qi) enqueueBefore(qd,qitem,qi->queryWUID()); else enqueue(qd,qitem); } unsigned ordinality(sQueueData &qd) { Cconnlockblock block(this,false); return qd.root->getPropInt("@count"); } IJobQueueItem *getTail(sQueueData &qd) { return doGetItem(qd,(unsigned)-1); } IJobQueueItem *loadItem(sQueueData &qd,IJobQueueItem *qi) { Cconnlockblock block(this,false); StringBuffer path; IPropertyTree *item = qd.root->queryPropTree(getItemPath(path,qi->queryWUID()).str()); if (!item) return NULL; bool cached = item->getPropInt("@num",0)<=0; if (cached) return NULL; // don't want cached value return new CJobQueueItem(item); } bool checkprio(sQueueData &qd,int minprio=0) { StringBuffer path; IPropertyTree *item = qd.root->queryPropTree(getItemPath(path,0U).str()); if (!item) return false; return (item->getPropInt("@priority")>=minprio); } IJobQueueItem *dotake(sQueueData &qd,const char *wuid,bool saveitem,bool hasminprio=false,int minprio=0) { StringBuffer path; IPropertyTree *item = qd.root->queryPropTree(getItemPath(path,wuid).str()); if (!item) return NULL; if (item->getPropInt("@num",0)<=0) return NULL; // don't want (old) cached value if (hasminprio&&(item->getPropInt("@priority")<minprio)) return NULL; IJobQueueItem *ret = new CJobQueueItem(item); removeItem(qd,item,saveitem); unsigned count = qd.root->getPropInt("@count"); assertex(count); qd.root->setPropInt("@count",count-1); return ret; } IJobQueueItem *take(sQueueData &qd,const char *wuid) { Cconnlockblock block(this,true); return dotake(qd,wuid,false); } unsigned takeItems(sQueueData &qd,CJobQueueContents &dest) { Cconnlockblock block(this,true); unsigned ret = copyItemsImpl(qd,dest); clear(qd); return ret; } void enqueueItems(sQueueData &qd,CJobQueueContents &items) { unsigned n=items.ordinality(); if (n) { Cconnlockblock block(this,true); for (unsigned i=0;i<n;i++) enqueue(qd,items.item(i).clone()); } } void enqueueBefore(IJobQueueItem *qitem,const char *wuid) { Cconnlockblock block(this,true); sQueueData *qd = qdata->next?findQD(wuid):qdata; enqueueBefore(*qd,qitem,wuid); } void enqueueAfter(IJobQueueItem *qitem,const char *wuid) { Cconnlockblock block(this,true); sQueueData *qd = qdata->next?findQD(wuid):qdata; enqueueAfter(*qd,qitem,wuid); } bool moveBefore(const char *wuid,const char *nextwuid) { if (!qdata) return false; Cconnlockblock block(this,true); sQueueData *qd = qdata->next?findQD(wuid):qdata; if (!qd) return false; IJobQueueItem *qi=take(*qd,wuid); if (!qi) return false; sQueueData *qdd = NULL; if (qdata->next) qdd = findQD(nextwuid); if (!qdd) qdd = qd; enqueueBefore(*qdd,qi,nextwuid); return true; } bool moveAfter(const char *wuid,const char *prevwuid) { if (!qdata) return false; Cconnlockblock block(this,true); sQueueData *qd = qdata->next?findQD(wuid):qdata; if (!qd) return false; IJobQueueItem *qi=take(*qd,wuid); if (!qi) return false; sQueueData *qdd = NULL; if (qdata->next) qdd = findQD(prevwuid); if (!qdd) qdd = qd; enqueueAfter(*qdd,qi,prevwuid); return true; } bool moveToHead(const char *wuid) { if (!qdata) return false; Cconnlockblock block(this,true); sQueueData *qd = qdata->next?findQD(wuid):qdata; if (!qd) return false; IJobQueueItem *qi=take(*qd,wuid); if (!qi) return false; enqueueHead(*qd,qi); return true; } bool moveToTail(const char *wuid) { if (!qdata) return false; Cconnlockblock block(this,true); sQueueData *qd = qdata->next?findQD(wuid):qdata; if (!qd) return false; IJobQueueItem *qi=take(*qd,wuid); if (!qi) return false; enqueueTail(*qd,qi); return true; } bool remove(const char *wuid) { if (!qdata) return false; Cconnlockblock block(this,true); sQueueData *qd = qdata->next?findQD(wuid):qdata; if (!qd) return false; StringBuffer path; IPropertyTree *item = qd->root->queryPropTree(getItemPath(path,wuid).str()); if (!item) return false; bool cached = item->getPropInt("@num",0)<=0; // old cached (bwd compat) removeItem(*qd,item,false); if (!cached) { unsigned count = qd->root->getPropInt("@count"); assertex(count); qd->root->setPropInt("@count",count-1); } return true; } bool changePriority(const char *wuid,int value) { if (!qdata) return false; Cconnlockblock block(this,true); sQueueData *qd = qdata->next?findQD(wuid):qdata; if (!qd) return false; IJobQueueItem *qi=take(*qd,wuid); if (!qi) { StringBuffer ws("~"); // change cached item ws.append(wuid); StringBuffer path; IPropertyTree *item = qd->root->queryPropTree(getItemPath(path,ws.str()).str()); if (item) { item->setPropInt("@priority",value); return true; } return false; } qi->setPriority(value); enqueue(*qd,qi); return true; } void clear(sQueueData &qd) { Cconnlockblock block(this,true); qd.root->setPropInt("@count",0); for (;;) { IPropertyTree *item = qd.root->queryPropTree("Item[1]"); if (!item) break; qd.root->removeTree(item); } } void lock() { connlock(false); // sub functions will change to exclusive if needed } void unlock(bool rollback=false) { connunlock(rollback); } void pause(sQueueData &qd) { Cconnlockblock block(this,true); qd.root->setProp("@state","paused"); } void resume(sQueueData &qd) { Cconnlockblock block(this,true); qd.root->setProp("@state","active"); } bool paused(sQueueData &qd) { Cconnlockblock block(this,false); const char *state = qd.root->queryProp("@state"); return (state&&(strcmp(state,"paused")==0)); } void stop(sQueueData &qd) { Cconnlockblock block(this,true); qd.root->setProp("@state","stopped"); } bool stopped(sQueueData &qd) { Cconnlockblock block(this,false); const char *state = qd.root->queryProp("@state"); return (state&&(strcmp(state,"stopped")==0)); } void doGetStats(sQueueData &qd,unsigned &connected,unsigned &waiting,unsigned &enqueued) { Cconnlockblock block(this,false); connected = 0; waiting = 0; unsigned i=0; for (;;) { IPropertyTree *croot = queryClientRootIndex(qd,i); if (!croot) break; if (validateitemsessions && !validSession(croot)) { Cconnlockblock block(this,true); qd.root->removeTree(croot); } else { waiting += croot->getPropInt("@waiting"); connected += croot->getPropInt("@connected"); i++; } } // now remove any duff queue items unsigned count = qd.root->getPropInt("@count"); if (!validateitemsessions) { enqueued = count; return; } i=0; StringBuffer path; for (;;) { IPropertyTree *item = qd.root->queryPropTree(getItemPath(path.clear(),i).str()); if (!item) break; if (!validSession(item)) { Cconnlockblock block(this,true); item = qd.root->queryPropTree(path.str()); if (!item) break; // PROGLOG("WUJOBQ: Removing %s as session %" I64F "x not active",item->queryProp("@wuid"),item->getPropInt64("@session")); removeItem(qd,item,false); } else i++; } if (count!=i) { Cconnlockblock block(this,true); qd.root->setPropInt("@count",i); } enqueued = i; } void getStats(sQueueData &qd,unsigned &connected,unsigned &waiting,unsigned &enqueued) { Cconnlockblock block(this,false); doGetStats(qd,connected,waiting,enqueued); } void getStats(unsigned &connected,unsigned &waiting,unsigned &enqueued) { // multi queue Cconnlockblock block(this,false); connected=0; waiting=0; enqueued=0; ForEachQueue(qd) { unsigned c; unsigned w; unsigned e; doGetStats(*qd,c,w,e); connected+=c; waiting+=w; enqueued+=e; } } IJobQueueItem *take(const char *wuid) { assertex(qdata); if (!qdata->next) return take(*qdata,wuid); Cconnlockblock block(this,true); ForEachQueue(qd) { IJobQueueItem *ret = dotake(*qd,wuid,false); if (ret) return ret; } return NULL; } unsigned takeItems(CJobQueueContents &dest) { assertex(qdata); if (!qdata->next) return takeItems(*qdata,dest); Cconnlockblock block(this,true); unsigned ret = 0; ForEachQueue(qd) { ret += copyItemsImpl(*qd,dest); clear(*qd); } return ret; } void enqueueItems(CJobQueueContents &items) { // enqueues to firs sub-queue (not sure that useful) assertex(qdata); return enqueueItems(*qdata,items); } void clear() { ForEachQueue(qd) { clear(*qd); } } bool validSession(IPropertyTree *item) { Owned<INode> node = createINode(item->queryProp("@node"),DALI_SERVER_PORT); // port should always be present return (querySessionManager().lookupProcessSession(node)==(SessionId)item->getPropInt64("@session")); } IConversation *initiateConversation(sQueueData &qd,IJobQueueItem *item) { CriticalBlock block(crit); assertex(!initiateconv.get()); SocketEndpoint ep = item->queryEndpoint(); unsigned short port = (unsigned short)item->getPort(); #if defined(_USE_OPENSSL) if (queryMtls()) initiateconv.setown(createSingletonSecureSocketConnection(port)); else #endif initiateconv.setown(createSingletonSocketConnection(port)); if (!port) item->setPort(initiateconv->setRandomPort(WUJOBQ_BASE_PORT,WUJOBQ_PORT_NUM)); initiatewu.set(item->queryWUID()); enqueue(qd,item); bool ok; { CriticalUnblock unblock(crit); ok = initiateconv->accept(INFINITE); } if (!ok) initiateconv.clear(); return initiateconv.getClear(); } IConversation *acceptConversation(IJobQueueItem *&retitem, unsigned prioritytransitiondelay,IDynamicPriority *maxp) { CriticalBlock block(crit); retitem = NULL; assertex(connected); // must be connected int curmp = maxp?maxp->get():0; int nextmp = curmp; for (;;) { bool timedout = false; Owned<IJobQueueItem> item; { CriticalUnblock unblock(crit); // this is a bit complicated with multi-thor if (prioritytransitiondelay||maxp) { item.setown(dodequeue((std::max(curmp,nextmp)/10)*10, // round down to multiple of 10 prioritytransitiondelay?prioritytransitiondelay:60000,prioritytransitiondelay>0,&timedout)); // if dynamic priority check every minute if (!prioritytransitiondelay) { curmp = nextmp; // using max above is a bit devious to allow transition nextmp = maxp->get(); } } else item.setown(dequeue(INFINITE)); } if (item.get()) { if (item->isValidSession()) { SocketEndpoint ep = item->queryEndpoint(); ep.port = item->getPort(); Owned<IConversation> acceptconv; #if defined(_USE_OPENSSL) if (queryMtls()) acceptconv.setown(createSingletonSecureSocketConnection(ep.port,&ep)); else #endif acceptconv.setown(createSingletonSocketConnection(ep.port,&ep)); if (acceptconv->connect(3*60*1000)) { // shouldn't need that long retitem = item.getClear(); return acceptconv.getClear(); } } } else if (prioritytransitiondelay) prioritytransitiondelay = 0; else if (!timedout) break; } return NULL; } void cancelInitiateConversation(sQueueData &qd) { CriticalBlock block(crit); if (initiatewu.get()) remove(initiatewu); if (initiateconv.get()) initiateconv->cancel(); } void cancelAcceptConversation() { CriticalBlock block(crit); dequeuestop = true; notifysem.signal(); } bool cancelInitiateConversation(sQueueData &qd,const char *wuid) { Cconnlockblock block(this,true); for (;;) { Owned<IJobQueueItem> item = dotake(qd,wuid,false); if (!item.get()) break; if (item->isValidSession()) { SocketEndpoint ep = item->queryEndpoint(); ep.port = item->getPort(); Owned<IConversation> acceptconv; #if defined(_USE_OPENSSL) if (queryMtls()) acceptconv.setown(createSingletonSecureSocketConnection(ep.port,&ep)); else #endif acceptconv.setown(createSingletonSocketConnection(ep.port,&ep)); acceptconv->connect(3*60*1000); // connect then close should close other end return true; } } return false; } bool waitStatsChange(unsigned timeout) { assertex(!connected); // not allowed to call this while connected cancelwaiting = false; while(!cancelwaiting) { { Cconnlockblock block(this,false); if (haschanged()) return true; } if (!notifysem.wait(timeout)) break; } return false; } void cancelWaitStatsChange() { CriticalBlock block(crit); cancelwaiting = true; notifysem.signal(); } virtual void enqueue(IJobQueueItem *qitem) { enqueue(*activeq,qitem); } void enqueueHead(IJobQueueItem *qitem) { enqueueHead(*activeq,qitem); } void enqueueTail(IJobQueueItem *qitem) { enqueueTail(*activeq,qitem); } void pause() { Cconnlockblock block(this,true); ForEachQueue(qd) { if (qd->root) qd->root->setProp("@state","paused"); } } void pause(const char* info) { Cconnlockblock block(this,true); ForEachQueue(qd) { if (qd->root) { qd->root->setProp("@state","paused"); if (info && *info) qd->root->setProp("@stateDetails",info); } } } void stop() { Cconnlockblock block(this,true); ForEachQueue(qd) { if (qd->root) qd->root->setProp("@state","stopped"); } } void stop(const char* info) { Cconnlockblock block(this,true); ForEachQueue(qd) { if (qd->root) { qd->root->setProp("@state","stopped"); if (info && *info) qd->root->setProp("@stateDetails",info); } } } void resume() { Cconnlockblock block(this,true); ForEachQueue(qd) { if (qd->root) qd->root->setProp("@state","active"); } } void resume(const char* info) { Cconnlockblock block(this,true); ForEachQueue(qd) { if (qd->root) { qd->root->setProp("@state","active"); if (info && *info) qd->root->setProp("@stateDetails",info); } } } IConversation *initiateConversation(IJobQueueItem *item) { return initiateConversation(*activeq,item); } void cancelInitiateConversation() { return cancelInitiateConversation(*activeq); } bool cancelInitiateConversation(const char *wuid) { return cancelInitiateConversation(*activeq,wuid); } const char * queryActiveQueueName() { return activeq->qname; } void setActiveQueue(const char *name) { ForEachQueue(qd) { if (!name||(strcmp(qd->qname.get(),name)==0)) { activeq = qd; return; } } if (name) throw MakeStringException (-1,"queue %s not found",name); } const char *nextQueueName(const char *last) { ForEachQueue(qd) { if (!last||(strcmp(qd->qname.get(),last)==0)) { if (qd->next) return qd->next->qname.get(); break; } } return NULL; } virtual bool paused() { Cconnlockblock block(this,false); return CJobQueueBase::paused(); } virtual bool paused(StringBuffer& info) { Cconnlockblock block(this,false); return CJobQueueBase::paused(info); } virtual bool stopped() { Cconnlockblock block(this,false); return CJobQueueBase::stopped(); } virtual bool stopped(StringBuffer& info) { Cconnlockblock block(this,false); return CJobQueueBase::stopped(info); } virtual unsigned ordinality() { Cconnlockblock block(this,false); return CJobQueueBase::ordinality(); } virtual unsigned waiting() { Cconnlockblock block(this,false); return CJobQueueBase::waiting(); } virtual IJobQueueItem *getItem(unsigned idx) { Cconnlockblock block(this,false); return CJobQueueBase::getItem(idx); } virtual IJobQueueItem *getHead() { Cconnlockblock block(this,false); return CJobQueueBase::getHead(); } virtual IJobQueueItem *getTail() { Cconnlockblock block(this,false); return CJobQueueBase::getTail(); } virtual IJobQueueItem *find(const char *wuid) { Cconnlockblock block(this,false); return CJobQueueBase::find(wuid); } virtual unsigned findRank(const char *wuid) { Cconnlockblock block(this,false); return CJobQueueBase::findRank(wuid); } virtual unsigned copyItems(CJobQueueContents &dest) { Cconnlockblock block(this,false); return CJobQueueBase::copyItems(dest); } virtual bool getLastDequeuedInfo(StringAttr &wuid, CDateTime &enqueuedt, int &priority) { Cconnlockblock block(this,false); return CJobQueueBase::doGetLastDequeuedInfo(activeq, wuid, enqueuedt, priority); } virtual void copyItemsAndState(CJobQueueContents& contents, StringBuffer& state, StringBuffer& stateDetails) { Cconnlockblock block(this,false); CJobQueueBase::copyItemsAndState(contents, state, stateDetails); } virtual void getState(StringBuffer& state, StringBuffer& stateDetails) { Cconnlockblock block(this,false); CJobQueueBase::getState(state, stateDetails); } }; class CJQSnapshot : public CInterface, implements IJQSnapshot { Owned<IPropertyTree> jobQueueInfo; public: IMPLEMENT_IINTERFACE; CJQSnapshot() { Owned<IRemoteConnection> connJobQueues = querySDS().connect("/JobQueues", myProcessSession(), RTM_LOCK_READ, 30000); if (!connJobQueues) throw MakeStringException(-1, "CJQSnapshot::CJQSnapshot: /JobQueues not found"); jobQueueInfo.setown(createPTreeFromIPT(connJobQueues->queryRoot())); } IJobQueueConst* getJobQueue(const char *name) { if (!jobQueueInfo) return NULL; return new CJobQueueConst(name, jobQueueInfo.getLink()); } }; IJQSnapshot *createJQSnapshot() { return new CJQSnapshot(); } IJobQueue *createJobQueue(const char *name) { if (!name||!*name) throw MakeStringException(-1,"createJobQueue empty name"); return new CJobQueue(name); } extern bool WORKUNIT_API runWorkUnit(const char *wuid, const char *queueName) { #ifdef _CONTAINERIZED StringBuffer agentQueue; getClusterEclAgentQueueName(agentQueue, queueName); #else //NB: In the non-container system the name of the roxie agent queue does not follow the convention for the containerized system Owned<IConstWUClusterInfo> clusterInfo = getTargetClusterInfo(queueName); if (!clusterInfo.get()) return false; SCMStringBuffer agentQueue; clusterInfo->getAgentQueue(agentQueue); if (!agentQueue.length()) return false; #endif Owned<IJobQueue> queue = createJobQueue(agentQueue.str()); if (!queue.get()) throw MakeStringException(-1, "Could not create workunit queue"); IJobQueueItem *item = createJobQueueItem(wuid); queue->enqueue(item); PROGLOG("Agent request '%s' enqueued on '%s'", wuid, agentQueue.str()); return true; } extern bool WORKUNIT_API runWorkUnit(const char *wuid) { Owned<IWorkUnitFactory> factory = getWorkUnitFactory(); Owned<IConstWorkUnit> w = factory->openWorkUnit(wuid); if (w) { StringAttr clusterName = (w->queryClusterName()); w.clear(); return runWorkUnit(wuid, clusterName.str()); } else return false; } extern WORKUNIT_API StringBuffer &getQueuesContainingWorkUnit(const char *wuid, StringBuffer &queueList) { Owned<IRemoteConnection> conn = querySDS().connect("/JobQueues", myProcessSession(), RTM_LOCK_READ, 5000); if (!conn) return queueList; VStringBuffer xpath("Queue[Item/@wuid='%s']", wuid); Owned<IPropertyTreeIterator> it = conn->getElements(xpath.str()); ForEach(*it) { if (queueList.length()) queueList.append(','); queueList.append(it->query().queryProp("@name")); } return queueList; } extern void WORKUNIT_API removeWorkUnitFromAllQueues(const char *wuid) { StringBuffer queueList; if (!getQueuesContainingWorkUnit(wuid, queueList).length()) return; Owned<IJobQueue> q = createJobQueue(queueList.str()); if (q) while(q->remove(wuid)); } extern bool WORKUNIT_API switchWorkUnitQueue(IWorkUnit* wu, const char *cluster) { if (!wu) return false; class cQswitcher: public CInterface, implements IQueueSwitcher { public: IMPLEMENT_IINTERFACE; void * getQ(const char * qname, const char * wuid) { Owned<IJobQueue> q = createJobQueue(qname); return q->take(wuid); } void putQ(const char * qname, const char * wuid, void * qitem) { Owned<IJobQueue> q = createJobQueue(qname); q->enqueue((IJobQueueItem *)qitem); } bool isAuto() { return false; } } switcher; return wu->switchThorQueue(cluster, &switcher); }
29.299053
136
0.518243
jeclrsg
fead0d2dc5afc81cf23e0c10f5d148679cea8263
13,657
cpp
C++
dali-toolkit/public-api/controls/scrollable/scroll-view/scroll-view.cpp
dalihub/dali-toolk
980728a7e35b8ddd28f70c090243e8076e21536e
[ "Apache-2.0", "BSD-3-Clause" ]
7
2016-11-18T10:26:51.000Z
2021-01-28T13:51:59.000Z
dali-toolkit/public-api/controls/scrollable/scroll-view/scroll-view.cpp
dalihub/dali-toolk
980728a7e35b8ddd28f70c090243e8076e21536e
[ "Apache-2.0", "BSD-3-Clause" ]
13
2020-07-15T11:33:03.000Z
2021-04-09T21:29:23.000Z
dali-toolkit/public-api/controls/scrollable/scroll-view/scroll-view.cpp
dalihub/dali-toolk
980728a7e35b8ddd28f70c090243e8076e21536e
[ "Apache-2.0", "BSD-3-Clause" ]
10
2019-05-17T07:15:09.000Z
2021-05-24T07:28:08.000Z
/* * Copyright (c) 2020 Samsung Electronics Co., Ltd. * * 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. * */ // CLASS HEADER #include <dali-toolkit/public-api/controls/scrollable/scroll-view/scroll-view.h> // EXTERNAL INCLUDES #include <dali/integration-api/debug.h> // INTERNAL INCLUDES #include <dali-toolkit/internal/controls/scrollable/scroll-view/scroll-view-impl.h> #include <dali-toolkit/public-api/controls/scrollable/scrollable.h> using namespace Dali; namespace Dali { namespace Toolkit { /////////////////////////////////////////////////////////////////////////////////////////////////// // RulerDomain /////////////////////////////////////////////////////////////////////////////////////////////////// RulerDomain::RulerDomain(float min, float max, bool enabled) : min(min), max(max), enabled(enabled) { } float RulerDomain::Clamp(float x, float length, float scale) const { ClampState clamped; return Clamp(x, length, scale, clamped); } float RulerDomain::Clamp(float x, float length, float scale, ClampState& clamped) const { if(!enabled) { clamped = NOT_CLAMPED; return x; } const float minExtent = min * scale; const float maxExtent = max * scale - length; if(x < minExtent) { clamped = CLAMPED_TO_MIN; return minExtent; } else if(x > maxExtent) { clamped = CLAMPED_TO_MAX; return maxExtent; } clamped = NOT_CLAMPED; return x; } float RulerDomain::GetSize() const { return max - min; } /////////////////////////////////////////////////////////////////////////////////////////////////// // Ruler /////////////////////////////////////////////////////////////////////////////////////////////////// Ruler::Ruler() : mType(FREE), mEnabled(true), mDomain(RulerDomain(0.0f, 1.0f, false)) { } Ruler::~Ruler() { } Ruler::RulerType Ruler::GetType() const { return mType; } bool Ruler::IsEnabled() const { return mEnabled; } void Ruler::Enable() { mEnabled = true; } void Ruler::Disable() { mEnabled = false; } void Ruler::SetDomain(RulerDomain domain) { mDomain = domain; } const RulerDomain& Ruler::GetDomain() const { return mDomain; } void Ruler::DisableDomain() { mDomain = RulerDomain(0.0f, 1.0f, false); } float Ruler::Clamp(float x, float length, float scale) const { return mDomain.Clamp(x, length, scale); } float Ruler::Clamp(float x, float length, float scale, ClampState& clamped) const { return mDomain.Clamp(x, length, scale, clamped); } float Ruler::SnapAndClamp(float x, float bias, float length, float scale) const { return Clamp(Snap(x, bias), length, scale); } float Ruler::SnapAndClamp(float x, float bias, float length, float scale, ClampState& clamped) const { return Clamp(Snap(x, bias), length, scale, clamped); } /////////////////////////////////////////////////////////////////////////////////////////////////// // DefaultRuler /////////////////////////////////////////////////////////////////////////////////////////////////// DefaultRuler::DefaultRuler() { mType = FREE; } float DefaultRuler::Snap(float x, float bias) const { return x; } float DefaultRuler::GetPositionFromPage(unsigned int page, unsigned int& volume, bool wrap) const { volume = 0; return 0.0f; } unsigned int DefaultRuler::GetPageFromPosition(float position, bool wrap) const { return 0; } unsigned int DefaultRuler::GetTotalPages() const { return 1; } /////////////////////////////////////////////////////////////////////////////////////////////////// // FixedRuler /////////////////////////////////////////////////////////////////////////////////////////////////// FixedRuler::FixedRuler(float spacing) : mSpacing(spacing) { if(fabsf(mSpacing) <= Math::MACHINE_EPSILON_1) { DALI_LOG_ERROR("Page spacing too small (%f).\n", double(spacing)); mSpacing = spacing >= 0.0f ? Math::MACHINE_EPSILON_1 : -Math::MACHINE_EPSILON_1; } mType = FIXED; } float FixedRuler::Snap(float x, float bias) const { return floor(x / mSpacing + bias) * mSpacing; } float FixedRuler::GetPositionFromPage(unsigned int page, unsigned int& volume, bool wrap) const { float position = mDomain.min; volume = 0; // spacing must be present. if(mEnabled) { unsigned int column = page; // In carry mode, a volume (carry) is produced when page exceeds limit within domain if(wrap) { unsigned int pagesPerVolume = mDomain.GetSize() / mSpacing; if(pagesPerVolume > 0) { column += pagesPerVolume; column %= pagesPerVolume; volume = page / pagesPerVolume; } } position = mDomain.min + column * mSpacing; } else // Domain (or Spacing) is not present, carry page to volume. { if(wrap) { volume = page; } } return position; } unsigned int FixedRuler::GetPageFromPosition(float position, bool wrap) const { unsigned int page = 0; // spacing must be present. if(mEnabled) { if(wrap) { position = WrapInDomain(position, mDomain.min, mDomain.max); } page = std::max(static_cast<double>(0.0f), static_cast<double>(floor((position - mDomain.min) / mSpacing + 0.5f))); if(wrap) { unsigned int pagesPerVolume = mDomain.GetSize() / mSpacing; // Defensive check to avoid a divide by zero below when the ruler is in an invalid state (entire domain smaller than spacing between pages of it): if(pagesPerVolume < 1u) { pagesPerVolume = 1u; DALI_LOG_ERROR("Ruler domain(%f) is smaller than its spacing(%f).\n", mDomain.GetSize() * 1.0, mSpacing * 1.0); } page %= pagesPerVolume; } } return page; } unsigned int FixedRuler::GetTotalPages() const { unsigned int pagesPerVolume = 1; // spacing must be present. if(mEnabled) { pagesPerVolume = mDomain.GetSize() / mSpacing; } return pagesPerVolume; } /////////////////////////////////////////////////////////////////////////////////////////////////// // ScrollView /////////////////////////////////////////////////////////////////////////////////////////////////// ScrollView::ScrollView() { } ScrollView::ScrollView(Internal::ScrollView& implementation) : Scrollable(implementation) { } ScrollView::ScrollView(Dali::Internal::CustomActor* internal) : Scrollable(internal) { VerifyCustomActorPointer<Internal::ScrollView>(internal); } ScrollView::ScrollView(const ScrollView& handle) = default; ScrollView::ScrollView(ScrollView&& rhs) = default; ScrollView& ScrollView::operator=(const ScrollView& handle) = default; ScrollView& ScrollView::operator=(ScrollView&& rhs) = default; ScrollView ScrollView::New() { return Internal::ScrollView::New(); } ScrollView::~ScrollView() { } ScrollView ScrollView::DownCast(BaseHandle handle) { return Control::DownCast<ScrollView, Internal::ScrollView>(handle); } AlphaFunction ScrollView::GetScrollSnapAlphaFunction() const { return GetImpl(*this).GetScrollSnapAlphaFunction(); } void ScrollView::SetScrollSnapAlphaFunction(AlphaFunction alpha) { GetImpl(*this).SetScrollSnapAlphaFunction(alpha); } AlphaFunction ScrollView::GetScrollFlickAlphaFunction() const { return GetImpl(*this).GetScrollFlickAlphaFunction(); } void ScrollView::SetScrollFlickAlphaFunction(AlphaFunction alpha) { GetImpl(*this).SetScrollFlickAlphaFunction(alpha); } float ScrollView::GetScrollSnapDuration() const { return GetImpl(*this).GetScrollSnapDuration(); } void ScrollView::SetScrollSnapDuration(float time) { GetImpl(*this).SetScrollSnapDuration(time); } float ScrollView::GetScrollFlickDuration() const { return GetImpl(*this).GetScrollFlickDuration(); } void ScrollView::SetScrollFlickDuration(float time) { GetImpl(*this).SetScrollFlickDuration(time); } void ScrollView::SetRulerX(RulerPtr ruler) { GetImpl(*this).SetRulerX(ruler); } void ScrollView::SetRulerY(RulerPtr ruler) { GetImpl(*this).SetRulerY(ruler); } void ScrollView::SetScrollSensitive(bool sensitive) { GetImpl(*this).SetScrollSensitive(sensitive); } void ScrollView::SetMaxOvershoot(float overshootX, float overshootY) { GetImpl(*this).SetMaxOvershoot(overshootX, overshootY); } void ScrollView::SetSnapOvershootAlphaFunction(AlphaFunction alpha) { GetImpl(*this).SetSnapOvershootAlphaFunction(alpha); } void ScrollView::SetSnapOvershootDuration(float duration) { GetImpl(*this).SetSnapOvershootDuration(duration); } void ScrollView::SetActorAutoSnap(bool enable) { GetImpl(*this).SetActorAutoSnap(enable); } void ScrollView::SetWrapMode(bool enable) { GetImpl(*this).SetWrapMode(enable); } int ScrollView::GetScrollUpdateDistance() const { return GetImpl(*this).GetScrollUpdateDistance(); } void ScrollView::SetScrollUpdateDistance(int distance) { GetImpl(*this).SetScrollUpdateDistance(distance); } bool ScrollView::GetAxisAutoLock() const { return GetImpl(*this).GetAxisAutoLock(); } void ScrollView::SetAxisAutoLock(bool enable) { GetImpl(*this).SetAxisAutoLock(enable); } float ScrollView::GetAxisAutoLockGradient() const { return GetImpl(*this).GetAxisAutoLockGradient(); } void ScrollView::SetAxisAutoLockGradient(float gradient) { GetImpl(*this).SetAxisAutoLockGradient(gradient); } float ScrollView::GetFrictionCoefficient() const { return GetImpl(*this).GetFrictionCoefficient(); } void ScrollView::SetFrictionCoefficient(float friction) { GetImpl(*this).SetFrictionCoefficient(friction); } float ScrollView::GetFlickSpeedCoefficient() const { return GetImpl(*this).GetFlickSpeedCoefficient(); } void ScrollView::SetFlickSpeedCoefficient(float speed) { GetImpl(*this).SetFlickSpeedCoefficient(speed); } Vector2 ScrollView::GetMinimumDistanceForFlick() const { return GetImpl(*this).GetMinimumDistanceForFlick(); } void ScrollView::SetMinimumDistanceForFlick(const Vector2& distance) { GetImpl(*this).SetMinimumDistanceForFlick(distance); } float ScrollView::GetMinimumSpeedForFlick() const { return GetImpl(*this).GetMinimumSpeedForFlick(); } void ScrollView::SetMinimumSpeedForFlick(float speed) { GetImpl(*this).SetMinimumSpeedForFlick(speed); } float ScrollView::GetMaxFlickSpeed() const { return GetImpl(*this).GetMaxFlickSpeed(); } void ScrollView::SetMaxFlickSpeed(float speed) { GetImpl(*this).SetMaxFlickSpeed(speed); } Vector2 ScrollView::GetWheelScrollDistanceStep() const { return GetImpl(*this).GetWheelScrollDistanceStep(); } void ScrollView::SetWheelScrollDistanceStep(Vector2 step) { GetImpl(*this).SetWheelScrollDistanceStep(step); } Vector2 ScrollView::GetCurrentScrollPosition() const { return GetImpl(*this).GetCurrentScrollPosition(); } unsigned int ScrollView::GetCurrentPage() const { return GetImpl(*this).GetCurrentPage(); } void ScrollView::ScrollTo(const Vector2& position) { GetImpl(*this).ScrollTo(position); } void ScrollView::ScrollTo(const Vector2& position, float duration) { GetImpl(*this).ScrollTo(position, duration); } void ScrollView::ScrollTo(const Vector2& position, float duration, AlphaFunction alpha) { GetImpl(*this).ScrollTo(position, duration, alpha); } void ScrollView::ScrollTo(const Vector2& position, float duration, DirectionBias horizontalBias, DirectionBias verticalBias) { GetImpl(*this).ScrollTo(position, duration, horizontalBias, verticalBias); } void ScrollView::ScrollTo(const Vector2& position, float duration, AlphaFunction alpha, DirectionBias horizontalBias, DirectionBias verticalBias) { GetImpl(*this).ScrollTo(position, duration, alpha, horizontalBias, verticalBias); } void ScrollView::ScrollTo(unsigned int page) { GetImpl(*this).ScrollTo(page); } void ScrollView::ScrollTo(unsigned int page, float duration) { GetImpl(*this).ScrollTo(page, duration); } void ScrollView::ScrollTo(unsigned int page, float duration, DirectionBias bias) { GetImpl(*this).ScrollTo(page, duration, bias); } void ScrollView::ScrollTo(Actor& actor) { GetImpl(*this).ScrollTo(actor); } void ScrollView::ScrollTo(Actor& actor, float duration) { GetImpl(*this).ScrollTo(actor, duration); } bool ScrollView::ScrollToSnapPoint() { return GetImpl(*this).ScrollToSnapPoint(); } void ScrollView::ApplyConstraintToChildren(Constraint constraint) { GetImpl(*this).ApplyConstraintToChildren(constraint); } void ScrollView::RemoveConstraintsFromChildren() { GetImpl(*this).RemoveConstraintsFromChildren(); } void ScrollView::ApplyEffect(ScrollViewEffect effect) { GetImpl(*this).ApplyEffect(effect); } void ScrollView::RemoveEffect(ScrollViewEffect effect) { GetImpl(*this).RemoveEffect(effect); } void ScrollView::RemoveAllEffects() { GetImpl(*this).RemoveAllEffects(); } void ScrollView::BindActor(Actor child) { GetImpl(*this).BindActor(child); } void ScrollView::UnbindActor(Actor child) { GetImpl(*this).UnbindActor(child); } ScrollView::SnapStartedSignalType& ScrollView::SnapStartedSignal() { return GetImpl(*this).SnapStartedSignal(); } void ScrollView::SetScrollingDirection(Radian direction, Radian threshold) { GetImpl(*this).SetScrollingDirection(direction, threshold); } void ScrollView::RemoveScrollingDirection(Radian direction) { GetImpl(*this).RemoveScrollingDirection(direction); } } // namespace Toolkit } // namespace Dali
22.425287
152
0.684191
dalihub
feafca7c4bc5b9e44743cc2eafae0570f1de9be7
5,972
cc
C++
content/renderer/media/crypto/content_decryption_module_factory.cc
iplo/Chain
8bc8943d66285d5258fffc41bed7c840516c4422
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
231
2015-01-08T09:04:44.000Z
2021-12-30T03:03:10.000Z
content/renderer/media/crypto/content_decryption_module_factory.cc
j4ckfrost/android_external_chromium_org
a1a3dad8b08d1fcf6b6b36c267158ed63217c780
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2017-02-14T21:55:58.000Z
2017-02-14T21:55:58.000Z
content/renderer/media/crypto/content_decryption_module_factory.cc
j4ckfrost/android_external_chromium_org
a1a3dad8b08d1fcf6b6b36c267158ed63217c780
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
268
2015-01-21T05:53:28.000Z
2022-03-25T22:09:01.000Z
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/renderer/media/crypto/content_decryption_module_factory.h" #include "base/logging.h" #include "content/renderer/media/crypto/key_systems.h" #include "media/cdm/aes_decryptor.h" #if defined(ENABLE_PEPPER_CDMS) #include "content/renderer/media/crypto/ppapi_decryptor.h" #include "content/renderer/pepper/pepper_plugin_instance_impl.h" #include "content/renderer/pepper/pepper_webplugin_impl.h" #include "third_party/WebKit/public/platform/WebMediaPlayerClient.h" #include "third_party/WebKit/public/platform/WebString.h" #include "third_party/WebKit/public/web/WebFrame.h" #elif defined(OS_ANDROID) #include "content/renderer/media/android/proxy_media_keys.h" #include "content/renderer/media/android/renderer_media_player_manager.h" #endif // defined(ENABLE_PEPPER_CDMS) namespace content { #if defined(ENABLE_PEPPER_CDMS) // Returns the PepperPluginInstanceImpl associated with the Helper Plugin. // If a non-NULL pointer is returned, the caller must call // closeHelperPluginSoon() when the Helper Plugin is no longer needed. static scoped_refptr<PepperPluginInstanceImpl> CreateHelperPlugin( const std::string& plugin_type, blink::WebMediaPlayerClient* web_media_player_client, blink::WebFrame* web_frame) { DCHECK(web_media_player_client); DCHECK(web_frame); blink::WebPlugin* web_plugin = web_media_player_client->createHelperPlugin( blink::WebString::fromUTF8(plugin_type), web_frame); if (!web_plugin) return NULL; DCHECK(!web_plugin->isPlaceholder()); // Prevented by Blink. // Only Pepper plugins are supported, so it must be a ppapi object. PepperWebPluginImpl* ppapi_plugin = static_cast<PepperWebPluginImpl*>(web_plugin); return ppapi_plugin->instance(); } static scoped_ptr<media::MediaKeys> CreatePpapiDecryptor( const std::string& key_system, const media::SessionCreatedCB& session_created_cb, const media::SessionMessageCB& session_message_cb, const media::SessionReadyCB& session_ready_cb, const media::SessionClosedCB& session_closed_cb, const media::SessionErrorCB& session_error_cb, const base::Closure& destroy_plugin_cb, blink::WebMediaPlayerClient* web_media_player_client, blink::WebFrame* web_frame) { DCHECK(web_media_player_client); DCHECK(web_frame); std::string plugin_type = GetPepperType(key_system); DCHECK(!plugin_type.empty()); const scoped_refptr<PepperPluginInstanceImpl>& plugin_instance = CreateHelperPlugin(plugin_type, web_media_player_client, web_frame); if (!plugin_instance.get()) { DLOG(ERROR) << "Plugin instance creation failed."; return scoped_ptr<media::MediaKeys>(); } scoped_ptr<PpapiDecryptor> decryptor = PpapiDecryptor::Create(key_system, plugin_instance, session_created_cb, session_message_cb, session_ready_cb, session_closed_cb, session_error_cb, destroy_plugin_cb); if (!decryptor) destroy_plugin_cb.Run(); // Else the new object will call destroy_plugin_cb to destroy Helper Plugin. return scoped_ptr<media::MediaKeys>(decryptor.Pass()); } void ContentDecryptionModuleFactory::DestroyHelperPlugin( blink::WebMediaPlayerClient* web_media_player_client, blink::WebFrame* web_frame) { web_media_player_client->closeHelperPluginSoon(web_frame); } #endif // defined(ENABLE_PEPPER_CDMS) scoped_ptr<media::MediaKeys> ContentDecryptionModuleFactory::Create( const std::string& key_system, #if defined(ENABLE_PEPPER_CDMS) blink::WebMediaPlayerClient* web_media_player_client, blink::WebFrame* web_frame, const base::Closure& destroy_plugin_cb, #elif defined(OS_ANDROID) RendererMediaPlayerManager* manager, int media_keys_id, const GURL& frame_url, #endif // defined(ENABLE_PEPPER_CDMS) const media::SessionCreatedCB& session_created_cb, const media::SessionMessageCB& session_message_cb, const media::SessionReadyCB& session_ready_cb, const media::SessionClosedCB& session_closed_cb, const media::SessionErrorCB& session_error_cb) { if (CanUseAesDecryptor(key_system)) { return scoped_ptr<media::MediaKeys>( new media::AesDecryptor(session_created_cb, session_message_cb, session_ready_cb, session_closed_cb, session_error_cb)); } #if defined(ENABLE_PEPPER_CDMS) // TODO(ddorwin): Remove when the WD API implementation supports loading // Pepper-based CDMs: http://crbug.com/250049 if (!web_media_player_client) return scoped_ptr<media::MediaKeys>(); return CreatePpapiDecryptor(key_system, session_created_cb, session_message_cb, session_ready_cb, session_closed_cb, session_error_cb, destroy_plugin_cb, web_media_player_client, web_frame); #elif defined(OS_ANDROID) scoped_ptr<ProxyMediaKeys> proxy_media_keys( new ProxyMediaKeys(manager, media_keys_id, session_created_cb, session_message_cb, session_ready_cb, session_closed_cb, session_error_cb)); proxy_media_keys->InitializeCDM(key_system, frame_url); return proxy_media_keys.PassAs<media::MediaKeys>(); #else return scoped_ptr<media::MediaKeys>(); #endif // defined(ENABLE_PEPPER_CDMS) } } // namespace content
39.549669
78
0.692565
iplo
feb16307bf9150d1ed948e2e001c1f4fbb5a2dea
7,029
cpp
C++
archive/FirstCut/territory.cpp
MangoCats/gomer
2b8059122add2bfab8cb4738cbaeeed0c59e4b58
[ "MIT" ]
null
null
null
archive/FirstCut/territory.cpp
MangoCats/gomer
2b8059122add2bfab8cb4738cbaeeed0c59e4b58
[ "MIT" ]
null
null
null
archive/FirstCut/territory.cpp
MangoCats/gomer
2b8059122add2bfab8cb4738cbaeeed0c59e4b58
[ "MIT" ]
null
null
null
#include "territory.h" Territory::Territory(Board *parent) : QObject(parent) { bp = parent; size = 0.4; show = false; for ( int i = 0; i < bp->Xsize; i++ ) for ( int j = 0; j < bp->Ysize; j++ ) gi.append( -1 ); // -1 == undetermined territory, not yet in a group update(); } void Territory::setScene( BoardScene *scp ) { scene = scp; } /** * @brief Territory::clear - erase existing territory objects * in preparation for a new computation and possible display */ void Territory::clear() { clearDisplay(); foreach( TerritorySquare *tp, squareList ) delete tp; squareList.clear(); foreach( TerritoryGroup *gp, groupList ) delete gp; groupList.clear(); for ( int i = 0; i < bp->Xsize; i++ ) for ( int j = 0; j < bp->Ysize; j++ ) gi.replace( i + j * bp->Xsize, -1 ); } /** * @brief Territory::update - floodfill all empty grid points * and determine their current territory status: black, white or undetermined. */ void Territory::update() { clear(); // Determine how many territory groups there are, and what coordinates they each cover for ( int i = 0; i < bp->Xsize; i++ ) for ( int j = 0; j < bp->Ysize; j++ ) if ( gi.at( i + j * bp->Xsize ) == -1 ) { tFill( i, j, groupList.size() ); groupList.append( new TerritoryGroup(this) ); } // Fill the territory groups with square objects for ( int k = 0; k < groupList.size(); k++ ) { TerritoryGroup *tp = groupList.at(k); for ( int i = 0; i < bp->Xsize; i++ ) for ( int j = 0; j < bp->Ysize; j++ ) { if ( gi.at( i + j * bp->Xsize ) == k ) { TerritorySquare *ts = new TerritorySquare(this); ts->x = i; ts->y = j; ts->g = k; ts->c = -2; // Undetermined, at this time squareList.append(ts); tp->group.append(ts); } } } // Determine the color of each territory group for ( int k = 0; k < groupList.size(); k++ ) { TerritoryGroup *tp = groupList.at(k); int tc = -2; // -2 undeterminmed, -1 determined to be disputed, 0 black, 1 white bool done = ( groupList.size() <= 0 ) || ( tp->group.size() == 0 ); int i = 0; while( !done ) { TerritorySquare *ts = tp->group.at(i); if ( ts->x > 0 ) done |= territoryColor( ts->x-1, ts->y, &tc ); if ( ts->x < (bp->Xsize - 1) ) done |= territoryColor( ts->x+1, ts->y, &tc ); if ( ts->y > 0 ) done |= territoryColor( ts->x, ts->y-1, &tc ); if ( ts->y < (bp->Ysize - 1) ) done |= territoryColor( ts->x, ts->y+1, &tc ); if ( ++i >= tp->group.size() ) done = true; } groupList.at(k)->c = tc; foreach ( TerritorySquare *ts, tp->group ) ts->c = tc; } updateDisplay(); } /** * @brief Territory::territoryColor - judging adjacent squares to a territory and the current color determination * determine the continuing color evaluation of the territory * @param x - coordinate to evaluate * @param y - coordinate to evaluate * @param tc - current color assignment * @return true if the current color assignment has become disputed */ bool Territory::territoryColor( int x, int y, int *tc ) { int ii = x + bp->Xsize * y; if ( bp->board.size() <= ii ) return true; Stone *sp = bp->board.at( ii ); if ( sp == nullptr ) return false; // No info here if ( *tc == -1 ) return true; // Done before we start if ( *tc == -2 ) { *tc = sp->c; return false; } if ( *tc == sp->c ) return false; // Continuing the trend *tc = -1; // Contrasting neighbor found, territory is in dispute return true; } /** * @brief Territory::tFill - floodfill unclaimed territory with group index g * @param x - coordinate to look for unfilled neighbors from * @param y - coordinate to look for unfilled neighbors from * @param g - group index to fill this territory with */ void Territory::tFill( int x, int y, int g ) { int ii = x + y * bp->Xsize; if ( bp->board.size() <= ii ) return; if ( bp->board.at( ii ) != nullptr ) { gi.replace( ii, -2 - bp->board.at( ii )->c ); // -2 for blackstone, -3 for whitestone return; // floodfill search does not pass a stone } gi.replace( ii, g ); if ( x > 0 ) tCheck( x-1, y, g ); if ( x < ( bp->Xsize - 1 ) ) tCheck( x+1, y, g ); if ( y > 0 ) tCheck( x, y-1, g ); if ( y < ( bp->Ysize - 1 ) ) tCheck( x, y+1, g ); } /** * @brief Territory::tCheck * @param x - coordinate to check for stone * @param y - coordinate to check for stone * @param g - group index to mark this territory with */ void Territory::tCheck( int x, int y, int g ) { int ii = x + y * bp->Xsize; if ( bp->board.size() <= ii ) return; // Board is not ready yet, happens at first initialization if ( gi.size() < ii ) { qDebug( "ERROR: gi not ready yet" ); return; } if ( gi.at( ii ) != -1 ) { if (( gi.at( ii ) > -1 ) && ( gi.at( ii ) != g )) { QString msg = QString( "ERROR: tCheck @(%1,%2,%3) encountered another territory index %4" ).arg(x).arg(y).arg(g).arg(gi.at( ii ) ); qDebug( qPrintable( msg ) ); } return; // already marked } if ( bp->board.at( ii ) != nullptr ) { gi.replace( ii, -2 - bp->board.at( ii )->c ); // -2 for blackstone, -3 for whitestone return; // floodfill search does not pass a stone } tFill( x, y, g ); // Continue the floodfill search } /** * @brief Territory::clearDisplay - just clear the displayed * squares' graphics items, not the underlying data objects. */ void Territory::clearDisplay() { if ( scene == nullptr ) return; foreach( TerritorySquare *tp, squareList ) { if ( tp->ri != nullptr ) { tp->ri->setVisible( false ); scene->removeMyItem( tp->ri ); delete( tp->ri ); tp->ri = nullptr; } } } /** * @brief Territory::updateDisplay - just update the display * graphics items, not recalculating territory data objects. */ void Territory::updateDisplay() { clearDisplay(); if ( !show ) return; QPen tPen; QBrush tBrush; foreach( TerritorySquare *tp, squareList ) { // tp->ri == nullptr, done in clearDisplay if ( tp->c < 0 ) { tPen = scene->linePen; tBrush = scene->backBrush; } else if ( tp->c == 0 ) { tPen = Qt::NoPen; tBrush = scene->blackBrush; } else if ( tp->c == 1 ) { tPen = Qt::NoPen; tBrush = scene->whiteBrush; } else { tPen = Qt::NoPen; tBrush = scene->backBrush; qDebug( "Territory::updateDisplay() unknown color" ); } tp->ri = scene->addRect( (qreal)tp->x - size*0.5, (qreal)tp->y - size*0.5, size, size, tPen, tBrush ); // TODO: correct pen and brush for territory color } }
33.15566
141
0.548584
MangoCats
feb2bc4c8288cce2ee9c23f57a16e618adbd52ae
9,826
cpp
C++
tests/unit/Base/TestTimer.cpp
franjgonzalez/Quinoa
411eb8815e92618c563881b784e287e2dd916f89
[ "RSA-MD" ]
null
null
null
tests/unit/Base/TestTimer.cpp
franjgonzalez/Quinoa
411eb8815e92618c563881b784e287e2dd916f89
[ "RSA-MD" ]
null
null
null
tests/unit/Base/TestTimer.cpp
franjgonzalez/Quinoa
411eb8815e92618c563881b784e287e2dd916f89
[ "RSA-MD" ]
null
null
null
// ***************************************************************************** /*! \file tests/unit/Base/TestTimer.cpp \copyright 2012-2015 J. Bakosi, 2016-2018 Los Alamos National Security, LLC., 2019 Triad National Security, LLC. All rights reserved. See the LICENSE file for details. \brief Unit tests for tk::Timer \details Unit tests for tk::Timer */ // ***************************************************************************** #include <unistd.h> #include "NoWarning/tut.hpp" #include "TUTConfig.hpp" #include "Timer.hpp" #include "ContainerUtil.hpp" #include "NoWarning/tutsuite.decl.h" namespace unittest { extern CProxy_TUTSuite g_suiteProxy; } // unittest:: #ifndef DOXYGEN_GENERATING_OUTPUT namespace tut { //! All tests in group inherited from this base struct Timer_common { // cppcheck-suppress unusedStructMember double precision = 1.0e-3; // required precision in seconds for timings }; //! Test group shortcuts using Timer_group = test_group< Timer_common, MAX_TESTS_IN_GROUP >; using Timer_object = Timer_group::object; //! Define test group static Timer_group Timer( "Base/Timer" ); //! Test definitions for group //! Test timing a 0.1s duration as float with given precision template<> template<> void Timer_object::test< 1 >() { double prec = 1.0e-1; // only for this single test (to pass on Mac OS) set_test_name( "measure 0.1s using dsec() with " + std::to_string(prec) + "s prec" ); tk::Timer timer; usleep( 100000 ); // in micro-seconds, sleep for 0.1 second // test if time measured with at least 1/10th of a millisecond prec ensure_equals( "time 0.1s elapsed as float", timer.dsec(), 0.1, prec ); } //! Test timing a 1.0 duration as h:m:s with given precision template<> template<> void Timer_object::test< 2 >() { set_test_name( "measure 1.0s using hms() with " + std::to_string(precision) + "s prec" ); tk::Timer timer; usleep( 1000000 ); // in micro-seconds, sleep for 1.0 second const auto stamp = timer.hms(); // test if time measured with at least 1/10th of a millisecond precision ensure_equals( "time 1.0s elapsed as hrs", static_cast<tk::real>(stamp.hrs.count()), 0.0, precision ); ensure_equals( "time 1.0s elapsed as min", static_cast<tk::real>(stamp.min.count()), 0.0, precision ); ensure_equals( "time 1.0s elapsed as sec", static_cast<tk::real>(stamp.sec.count()), 1.0, precision ); } //! Test estimated time elapsed and to accomplishment triggered by term template<> template<> void Timer_object::test< 3 >() { set_test_name( "ETE and ETA triggered by terminate time" ); // Setup a duration case tk::real term = 5.0; // time at which to terminate time stepping tk::real time = 1.0; // current time uint64_t nstep = 1000; // max number of time steps to take (large) uint64_t it = 1; // current iteration tk::Timer timer; usleep( 1000000 ); // in micro-seconds, sleep for 1.0 second tk::Timer::Watch ete, eta; timer.eta( term, time, nstep, it, ete, eta ); // test estimated time elapsed with given precision ensure_equals( "estimated time elapsed in hrs", static_cast<tk::real>(ete.hrs.count()), 0.0, precision ); ensure_equals( "estimated time elapsed in min", static_cast<tk::real>(ete.min.count()), 0.0, precision ); ensure_equals( "estimated time elapsed in sec", static_cast<tk::real>(ete.sec.count()), 1.0, precision ); // test estimated time to accomplishment with given precision ensure_equals( "estimated time to accomplishment in hrs", static_cast<tk::real>(eta.hrs.count()), 0.0, precision ); ensure_equals( "estimated time to accomplishment in min", static_cast<tk::real>(eta.min.count()), 0.0, precision ); ensure_equals( "estimated time to accomplishment in sec", static_cast<tk::real>(eta.sec.count()), 4.0, precision ); } //! Test estimated time elapsed and to accomplishment triggered by nstep template<> template<> void Timer_object::test< 4 >() { set_test_name( "ETE and ETA triggered by max number of steps" ); // Setup a duration case tk::real term = 500.0; // time at which to terminate time stepping (large) tk::real time = 1.0; // current time uint64_t nstep = 100; // max number of time steps to take uint64_t it = 1; // current iteration tk::Timer timer; usleep( 1000000 ); // in micro-seconds, sleep for 1.0 second tk::Timer::Watch ete, eta; timer.eta( term, time, nstep, it, ete, eta ); // test estimated time elapsed with given precision ensure_equals( "estimated time elapsed in hrs", static_cast<tk::real>(ete.hrs.count()), 0.0, precision ); ensure_equals( "estimated time elapsed in min", static_cast<tk::real>(ete.min.count()), 0.0, precision ); ensure_equals( "estimated time elapsed in sec", static_cast<tk::real>(ete.sec.count()), 1.0, precision ); // test estimated time to accomplishment with given precision ensure_equals( "estimated time to accomplishment in hrs", static_cast<tk::real>(eta.hrs.count()), 0.0, precision ); ensure_equals( "estimated time to accomplishment in min", static_cast<tk::real>(eta.min.count()), 1.0, precision ); ensure_equals( "estimated time to accomplishment in sec", static_cast<tk::real>(eta.sec.count()), 39.0, precision ); } //! Test converting a 1.0s duration timed as a float to Timer::Watch template<> template<> void Timer_object::test< 5 >() { set_test_name( "convert time stamp in float to Watch" ); tk::Timer timer; usleep( 1000000 ); // in micro-seconds, sleep for 1.0 second // convert time stamp in float to Timer::Watch const auto w = tk::hms( timer.dsec() ); // test if time measured with at least 1/10th of a millisecond precision ensure_equals( "time 1.0s elapsed as float represented as Timer::Watch in hrs", static_cast<tk::real>(w.hrs.count()), 0.0, precision ); ensure_equals( "time 1.0s elapsed as float represented as Timer::Watch in min", static_cast<tk::real>(w.min.count()), 0.0, precision ); ensure_equals( "time 1.0s elapsed as float represented as Timer::Watch in sec", static_cast<tk::real>(w.sec.count()), 1.0, precision ); } //! Charm chare having a tk::Timer object class CharmTimer : public CBase_CharmTimer { public: explicit CharmTimer( const tk::Timer& timer ) { // Create test result struct, assume test is ok tut::test_result tr( "Base/Timer", 7, "Charm:migrate tk::Timer 2", tut::test_result::result_type::ok ); // Evaluate test: The incoming timer's time point is queried here that // includes the time elapsed before the Charm++ chare has been created + the // migration time, so tested with a somewhat lose precision that includes // the approximate (guessed) migration time. try { ensure( "timer different after migrated: ", timer.dsec() > 1.0 ); } catch ( const failure& ex ) { tr.result = ex.result(); tr.exception_typeid = ex.type(); tr.message = ex.what(); } // Send back a new test result, with tag "2", signaling the second part. unittest::g_suiteProxy.evaluate( { tr.group, tr.name, std::to_string(tr.result), tr.message, tr.exception_typeid } ); } }; //! Test Charm++ migration of a tk::Timer object across the network //! \details Every Charm++ migration test, such as this one, consists of two //! unit tests: one for send and one for receive. Both triggers a TUT test, //! but the receive side is created manually, i.e., without the awareness of //! the TUT library. Unfortunately thus, there is no good way to count up //! these additional tests, and thus if a test such as this is added to the //! suite this number must be updated in UnitTest/TUTSuite.h in //! unittest::TUTSuite::m_migrations. template<> template<> void Timer_object::test< 6 >() { // This test spawns a new Charm++ chare. The "1" at the end of the test name // signals that this is only the first part of this test: the part up to // firing up an asynchronous Charm++ chare. The second part creates a new test // result, sending it back to the suite if successful. If that chare never // executes, the suite will hang waiting for that chare to call back. set_test_name( "Charm:migrate tk::Timer 1" ); tk::Timer timer; usleep( 1000000 ); // in micro-seconds, sleep for 1.0 second CProxy_CharmTimer::ckNew( timer ); // fire up Charm++ chare } //! Test querying a timer from a std::map template<> template<> void Timer_object::test< 7 >() { double prec = 1.0e-2; // only for this single test (to pass on Mac OS) set_test_name( "query timer from map" ); std::map< std::string, tk::Timer > timer; timer[ "some timer" ];// start timing, assign to label usleep( 1000000 ); // in micro-seconds, sleep for 1.0 second const auto t = tk::ref_find( timer, "some timer" ); ensure_equals( "timer different", t.dsec(), 1.0, prec ); } //! Test that querying timer from a map throws with garbage key template<> template<> void Timer_object::test< 8 >() { set_test_name( "query throws with non-existent key" ); try { std::map< std::string, tk::Timer > timer; timer[ "some timer" ];// start timing, assign to label tk::cref_find( timer, std::string("some non-existent timer") ); fail( "should throw exception" ); } catch ( tk::Exception& ) { // exception thrown, test ok } } } // tut:: #endif // DOXYGEN_GENERATING_OUTPUT #include "NoWarning/charmtimer.def.h"
40.436214
81
0.650926
franjgonzalez
feb39fce496b9d8cc30b3401f1015dbde0ea7ba2
2,148
hpp
C++
src/hotspot/share/prims/universalUpcallHandler.hpp
1690296356/jdk
eaf668d1510c28d51e26c397b582b66ebdf7e263
[ "Apache-2.0" ]
1
2020-12-26T04:52:15.000Z
2020-12-26T04:52:15.000Z
src/hotspot/share/prims/universalUpcallHandler.hpp
1690296356/jdk
eaf668d1510c28d51e26c397b582b66ebdf7e263
[ "Apache-2.0" ]
1
2020-12-26T04:57:19.000Z
2020-12-26T04:57:19.000Z
src/hotspot/share/prims/universalUpcallHandler.hpp
1690296356/jdk
eaf668d1510c28d51e26c397b582b66ebdf7e263
[ "Apache-2.0" ]
1
2021-12-06T01:13:18.000Z
2021-12-06T01:13:18.000Z
/* * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ #ifndef SHARE_VM_PRIMS_UNIVERSALUPCALLHANDLER_HPP #define SHARE_VM_PRIMS_UNIVERSALUPCALLHANDLER_HPP #include "asm/codeBuffer.hpp" #include "prims/foreign_globals.hpp" class JavaThread; class ProgrammableUpcallHandler { private: static constexpr CodeBuffer::csize_t upcall_stub_size = 1024; struct UpcallMethod { Klass* klass; Symbol* name; Symbol* sig; } upcall_method; ProgrammableUpcallHandler(); static const ProgrammableUpcallHandler& instance(); static void upcall_helper(JavaThread* thread, jobject rec, address buff); static void attach_thread_and_do_upcall(jobject rec, address buff); static void handle_uncaught_exception(oop exception); static Thread* maybe_attach_and_get_thread(bool* should_detach); static void detach_thread(Thread* thread); public: static address generate_optimized_upcall_stub(jobject mh, Method* entry, jobject jabi, jobject jconv); static address generate_upcall_stub(jobject rec, jobject abi, jobject buffer_layout); static bool supports_optimized_upcalls(); }; #endif // SHARE_VM_PRIMS_UNIVERSALUPCALLHANDLER_HPP
36.40678
104
0.777467
1690296356
feb42da88f6f4a48cae396ac03a3654e0f7a30f1
32,005
cpp
C++
cplus/libcfint/CFIntMimeTypeTableObj.cpp
msobkow/cfint_2_13
63ff9dfc85647066d0c8d61469ada572362e2b48
[ "Apache-2.0" ]
null
null
null
cplus/libcfint/CFIntMimeTypeTableObj.cpp
msobkow/cfint_2_13
63ff9dfc85647066d0c8d61469ada572362e2b48
[ "Apache-2.0" ]
null
null
null
cplus/libcfint/CFIntMimeTypeTableObj.cpp
msobkow/cfint_2_13
63ff9dfc85647066d0c8d61469ada572362e2b48
[ "Apache-2.0" ]
null
null
null
// Description: C++18 Table Object implementation for CFInt. /* * org.msscf.msscf.CFInt * * Copyright (c) 2020 Mark Stephen Sobkow * * MSS Code Factory CFInt 2.13 Internet Essentials * * Copyright 2020-2021 Mark Stephen Sobkow * * This file is part of MSS Code Factory. * * MSS Code Factory is available under dual commercial license from Mark Stephen * Sobkow, or under the terms of the GNU General Public License, Version 3 * or later. * * MSS Code Factory is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MSS Code Factory is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MSS Code Factory. If not, see <https://www.gnu.org/licenses/>. * * Donations to support MSS Code Factory can be made at * https://www.paypal.com/paypalme2/MarkSobkow * * Please contact Mark Stephen Sobkow at mark.sobkow@gmail.com for commercial licensing. * * Manufactured by MSS Code Factory 2.12 */ #include <cflib/ICFLibPublic.hpp> using namespace std; #include <cfint/ICFIntPublic.hpp> #include <cfintobj/ICFIntObjPublic.hpp> #include <cfintobj/CFIntClusterObj.hpp> #include <cfintobj/CFIntHostNodeObj.hpp> #include <cfintobj/CFIntISOCcyObj.hpp> #include <cfintobj/CFIntISOCtryObj.hpp> #include <cfintobj/CFIntISOCtryCcyObj.hpp> #include <cfintobj/CFIntISOCtryLangObj.hpp> #include <cfintobj/CFIntISOLangObj.hpp> #include <cfintobj/CFIntISOTZoneObj.hpp> #include <cfintobj/CFIntLicenseObj.hpp> #include <cfintobj/CFIntMajorVersionObj.hpp> #include <cfintobj/CFIntMimeTypeObj.hpp> #include <cfintobj/CFIntMinorVersionObj.hpp> #include <cfintobj/CFIntSecAppObj.hpp> #include <cfintobj/CFIntSecDeviceObj.hpp> #include <cfintobj/CFIntSecFormObj.hpp> #include <cfintobj/CFIntSecGroupObj.hpp> #include <cfintobj/CFIntSecGroupFormObj.hpp> #include <cfintobj/CFIntSecGrpIncObj.hpp> #include <cfintobj/CFIntSecGrpMembObj.hpp> #include <cfintobj/CFIntSecSessionObj.hpp> #include <cfintobj/CFIntSecUserObj.hpp> #include <cfintobj/CFIntServiceObj.hpp> #include <cfintobj/CFIntServiceTypeObj.hpp> #include <cfintobj/CFIntSubProjectObj.hpp> #include <cfintobj/CFIntSysClusterObj.hpp> #include <cfintobj/CFIntTSecGroupObj.hpp> #include <cfintobj/CFIntTSecGrpIncObj.hpp> #include <cfintobj/CFIntTSecGrpMembObj.hpp> #include <cfintobj/CFIntTenantObj.hpp> #include <cfintobj/CFIntTldObj.hpp> #include <cfintobj/CFIntTopDomainObj.hpp> #include <cfintobj/CFIntTopProjectObj.hpp> #include <cfintobj/CFIntURLProtocolObj.hpp> #include <cfintobj/CFIntClusterEditObj.hpp> #include <cfintobj/CFIntHostNodeEditObj.hpp> #include <cfintobj/CFIntISOCcyEditObj.hpp> #include <cfintobj/CFIntISOCtryEditObj.hpp> #include <cfintobj/CFIntISOCtryCcyEditObj.hpp> #include <cfintobj/CFIntISOCtryLangEditObj.hpp> #include <cfintobj/CFIntISOLangEditObj.hpp> #include <cfintobj/CFIntISOTZoneEditObj.hpp> #include <cfintobj/CFIntLicenseEditObj.hpp> #include <cfintobj/CFIntMajorVersionEditObj.hpp> #include <cfintobj/CFIntMimeTypeEditObj.hpp> #include <cfintobj/CFIntMinorVersionEditObj.hpp> #include <cfintobj/CFIntSecAppEditObj.hpp> #include <cfintobj/CFIntSecDeviceEditObj.hpp> #include <cfintobj/CFIntSecFormEditObj.hpp> #include <cfintobj/CFIntSecGroupEditObj.hpp> #include <cfintobj/CFIntSecGroupFormEditObj.hpp> #include <cfintobj/CFIntSecGrpIncEditObj.hpp> #include <cfintobj/CFIntSecGrpMembEditObj.hpp> #include <cfintobj/CFIntSecSessionEditObj.hpp> #include <cfintobj/CFIntSecUserEditObj.hpp> #include <cfintobj/CFIntServiceEditObj.hpp> #include <cfintobj/CFIntServiceTypeEditObj.hpp> #include <cfintobj/CFIntSubProjectEditObj.hpp> #include <cfintobj/CFIntSysClusterEditObj.hpp> #include <cfintobj/CFIntTSecGroupEditObj.hpp> #include <cfintobj/CFIntTSecGrpIncEditObj.hpp> #include <cfintobj/CFIntTSecGrpMembEditObj.hpp> #include <cfintobj/CFIntTenantEditObj.hpp> #include <cfintobj/CFIntTldEditObj.hpp> #include <cfintobj/CFIntTopDomainEditObj.hpp> #include <cfintobj/CFIntTopProjectEditObj.hpp> #include <cfintobj/CFIntURLProtocolEditObj.hpp> #include <cfintobj/CFIntClusterTableObj.hpp> #include <cfintobj/CFIntHostNodeTableObj.hpp> #include <cfintobj/CFIntISOCcyTableObj.hpp> #include <cfintobj/CFIntISOCtryTableObj.hpp> #include <cfintobj/CFIntISOCtryCcyTableObj.hpp> #include <cfintobj/CFIntISOCtryLangTableObj.hpp> #include <cfintobj/CFIntISOLangTableObj.hpp> #include <cfintobj/CFIntISOTZoneTableObj.hpp> #include <cfintobj/CFIntLicenseTableObj.hpp> #include <cfintobj/CFIntMajorVersionTableObj.hpp> #include <cfintobj/CFIntMimeTypeTableObj.hpp> #include <cfintobj/CFIntMinorVersionTableObj.hpp> #include <cfintobj/CFIntSecAppTableObj.hpp> #include <cfintobj/CFIntSecDeviceTableObj.hpp> #include <cfintobj/CFIntSecFormTableObj.hpp> #include <cfintobj/CFIntSecGroupTableObj.hpp> #include <cfintobj/CFIntSecGroupFormTableObj.hpp> #include <cfintobj/CFIntSecGrpIncTableObj.hpp> #include <cfintobj/CFIntSecGrpMembTableObj.hpp> #include <cfintobj/CFIntSecSessionTableObj.hpp> #include <cfintobj/CFIntSecUserTableObj.hpp> #include <cfintobj/CFIntServiceTableObj.hpp> #include <cfintobj/CFIntServiceTypeTableObj.hpp> #include <cfintobj/CFIntSubProjectTableObj.hpp> #include <cfintobj/CFIntSysClusterTableObj.hpp> #include <cfintobj/CFIntTSecGroupTableObj.hpp> #include <cfintobj/CFIntTSecGrpIncTableObj.hpp> #include <cfintobj/CFIntTSecGrpMembTableObj.hpp> #include <cfintobj/CFIntTenantTableObj.hpp> #include <cfintobj/CFIntTldTableObj.hpp> #include <cfintobj/CFIntTopDomainTableObj.hpp> #include <cfintobj/CFIntTopProjectTableObj.hpp> #include <cfintobj/CFIntURLProtocolTableObj.hpp> namespace cfint { const std::string CFIntMimeTypeTableObj::CLASS_NAME( "CFIntMimeTypeTableObj" ); const std::string CFIntMimeTypeTableObj::TABLE_NAME( "MimeType" ); const std::string CFIntMimeTypeTableObj::TABLE_DBNAME( "MimeType" ); CFIntMimeTypeTableObj::CFIntMimeTypeTableObj() { schema = NULL; members = new std::map<cfint::CFIntMimeTypePKey, cfint::ICFIntMimeTypeObj*>(); allMimeType = NULL; indexByUNameIdx = new std::map< cfint::CFIntMimeTypeByUNameIdxKey, cfint::ICFIntMimeTypeObj*>(); } CFIntMimeTypeTableObj::CFIntMimeTypeTableObj( cfint::ICFIntSchemaObj* argSchema ) { schema = dynamic_cast<cfint::ICFIntSchemaObj*>( argSchema ); members = new std::map<cfint::CFIntMimeTypePKey, cfint::ICFIntMimeTypeObj*>(); allMimeType = NULL; indexByUNameIdx = new std::map< cfint::CFIntMimeTypeByUNameIdxKey, cfint::ICFIntMimeTypeObj*>(); } CFIntMimeTypeTableObj::~CFIntMimeTypeTableObj() { minimizeMemory(); if( indexByUNameIdx != NULL ) { delete indexByUNameIdx; indexByUNameIdx = NULL; } if( members != NULL ) { cfint::ICFIntMimeTypeObj* curMember; auto membersIter = members->begin(); while( membersIter != members->end() ) { curMember = membersIter->second; if( curMember != NULL ) { delete curMember; } members->erase( membersIter ); membersIter = members->begin(); } delete members; members = NULL; } } cfint::ICFIntSchemaObj* CFIntMimeTypeTableObj::getSchema() { return( schema ); } void CFIntMimeTypeTableObj::setSchema( cfint::ICFIntSchemaObj* value ) { schema = dynamic_cast<cfint::ICFIntSchemaObj*>( value ); } const std::string CFIntMimeTypeTableObj::getTableName() { return( TABLE_NAME ); } const std::string CFIntMimeTypeTableObj::getTableDbName() { return( TABLE_DBNAME ); } const classcode_t* CFIntMimeTypeTableObj::getObjQualifyingClassCode() { return( NULL ); } void CFIntMimeTypeTableObj::minimizeMemory() { if( allMimeType != NULL ) { allMimeType->clear(); delete allMimeType; allMimeType = NULL; } if( indexByUNameIdx != NULL ) { indexByUNameIdx->clear(); } if( members != NULL ) { cfint::ICFIntMimeTypeObj* cur = NULL; cfint::ICFIntMimeTypeEditObj* edit = NULL; auto iter = members->begin(); auto end = members->end(); while( iter != end ) { cur = iter->second; if( cur != NULL ) { iter->second = NULL; edit = cur->getEdit(); if( edit != NULL ) { edit->endEdit(); edit = NULL; } delete cur; cur = NULL; } iter ++; } members->clear(); } } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::newInstance() { cfint::ICFIntMimeTypeObj* inst = dynamic_cast<cfint::ICFIntMimeTypeObj*>( new CFIntMimeTypeObj( schema ) ); return( inst ); } cfint::ICFIntMimeTypeEditObj* CFIntMimeTypeTableObj::newEditInstance( cfint::ICFIntMimeTypeObj* orig ) { cfint::ICFIntMimeTypeEditObj* edit = dynamic_cast<cfint::ICFIntMimeTypeEditObj*>( new CFIntMimeTypeEditObj( orig )); return( edit ); } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::realizeMimeType( cfint::ICFIntMimeTypeObj* Obj ) { static const std::string S_ProcName( "realizeMimeType" ); static const std::string S_ExistingObj( "existingObj" ); static const std::string S_KeepObj( "keepObj" ); static const std::string S_Obj( "Obj" ); if( Obj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 1, S_Obj ); } cfint::ICFIntMimeTypeObj* obj = Obj; cfint::ICFIntMimeTypeObj* existingObj = NULL; cfint::CFIntMimeTypePKey* pkey = obj->getPKey(); cfint::ICFIntMimeTypeObj* keepObj = NULL; auto searchMembers = members->find( *pkey ); if( searchMembers != members->end() ) { existingObj = searchMembers->second; if( existingObj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_ExistingObj ); } keepObj = existingObj; pkey = keepObj->getPKey(); /* * We always rebind the data because if we're being called, some index may have been * updated and is refreshing it's data, which may require binding a different lookup key */ // Detach object from alternate and duplicate indexes, leave PKey alone if( indexByUNameIdx != NULL ) { cfint::CFIntMimeTypeByUNameIdxKey keyUNameIdx; keyUNameIdx.setRequiredName( keepObj->getRequiredName() ); auto removalProbe = indexByUNameIdx->find( keyUNameIdx ); if( removalProbe != indexByUNameIdx->end() ) { indexByUNameIdx->erase( removalProbe ); } } keepObj->setBuff( dynamic_cast<cfint::CFIntMimeTypeBuff*>( Obj->getBuff()->clone() ) ); // Attach new object to alternate and duplicate indexes -- PKey stays stable if( indexByUNameIdx != NULL ) { static const std::string S_AUNameIdxObj( "aUNameIdxObj" ); cfint::ICFIntMimeTypeObj* aUNameIdxObj = dynamic_cast<cfint::ICFIntMimeTypeObj*>( keepObj ); if( aUNameIdxObj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_AUNameIdxObj ); } cfint::CFIntMimeTypeByUNameIdxKey keyUNameIdx; keyUNameIdx.setRequiredName( keepObj->getRequiredName() ); indexByUNameIdx->insert( std::map< cfint::CFIntMimeTypeByUNameIdxKey, cfint::ICFIntMimeTypeObj* >::value_type( keyUNameIdx, aUNameIdxObj ) ); } if( allMimeType != NULL ) { allMimeType->insert( std::map< cfint::CFIntMimeTypePKey, cfint::ICFIntMimeTypeObj* >::value_type( *(keepObj->getPKey()), keepObj ) ); } } else { keepObj = obj; keepObj->setIsNew( false ); pkey = keepObj->getPKey(); // Attach new object to PKey, all, alternate, and duplicate indexes members->insert( std::map< cfint::CFIntMimeTypePKey, cfint::ICFIntMimeTypeObj* >::value_type( *(keepObj->getPKey()), keepObj ) ); // Attach new object to alternate and duplicate indexes -- PKey stay stable if( indexByUNameIdx != NULL ) { static const std::string S_AUNameIdxObj( "aUNameIdxObj" ); cfint::ICFIntMimeTypeObj* aUNameIdxObj = dynamic_cast<cfint::ICFIntMimeTypeObj*>( keepObj ); if( aUNameIdxObj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_AUNameIdxObj ); } cfint::CFIntMimeTypeByUNameIdxKey keyUNameIdx; keyUNameIdx.setRequiredName( keepObj->getRequiredName() ); indexByUNameIdx->insert( std::map< cfint::CFIntMimeTypeByUNameIdxKey, cfint::ICFIntMimeTypeObj* >::value_type( keyUNameIdx, aUNameIdxObj ) ); } if( allMimeType != NULL ) { allMimeType->insert( std::map< cfint::CFIntMimeTypePKey, cfint::ICFIntMimeTypeObj* >::value_type( *(keepObj->getPKey()), keepObj ) ); } } if( keepObj != obj ) { delete obj; obj = NULL; } // Something is leaking, so I've added this paranoid check if( ( keepObj != existingObj ) && ( existingObj != NULL ) ) { delete existingObj; existingObj = NULL; } return( keepObj ); } void CFIntMimeTypeTableObj::deepDisposeByIdIdx( const int32_t MimeTypeId ) { static const std::string S_ProcName( "deepDisposeByIdIdx" ); std::vector<cfint::ICFIntMimeTypeObj*> list; cfint::ICFIntMimeTypeObj* existingObj = readCachedMimeTypeByIdIdx( MimeTypeId ); if( existingObj != NULL ) { list.push_back( existingObj ); } cfint::ICFIntMimeTypeObj* cur = NULL; classcode_t classCode; auto listIter = list.begin(); auto listEnd = list.end(); while( listIter != listEnd ) { cur = *listIter; if( cur != NULL ) { classCode = cur->getClassCode(); if( classCode == cfint::CFIntMimeTypeBuff::CLASS_CODE ) { dynamic_cast<cfint::CFIntMimeTypeTableObj*>( schema->getMimeTypeTableObj() )->reallyDeepDisposeMimeType( dynamic_cast<cfint::ICFIntMimeTypeObj*>( cur ) ); } } listIter ++; } } void CFIntMimeTypeTableObj::deepDisposeByUNameIdx( const std::string& Name ) { static const std::string S_ProcName( "deepDisposeByUNameIdx" ); std::vector<cfint::ICFIntMimeTypeObj*> list; cfint::ICFIntMimeTypeObj* existingObj = readCachedMimeTypeByUNameIdx( Name ); if( existingObj != NULL ) { list.push_back( existingObj ); } cfint::ICFIntMimeTypeObj* cur = NULL; classcode_t classCode; auto listIter = list.begin(); auto listEnd = list.end(); while( listIter != listEnd ) { cur = *listIter; if( cur != NULL ) { classCode = cur->getClassCode(); if( classCode == cfint::CFIntMimeTypeBuff::CLASS_CODE ) { dynamic_cast<cfint::CFIntMimeTypeTableObj*>( schema->getMimeTypeTableObj() )->reallyDeepDisposeMimeType( dynamic_cast<cfint::ICFIntMimeTypeObj*>( cur ) ); } } listIter ++; } } void CFIntMimeTypeTableObj::reallyDeepDisposeMimeType( cfint::ICFIntMimeTypeObj* Obj ) { static const std::string S_ProcName( "reallyDeepDisposeMimeType" ); if( Obj == NULL ) { return; } cfint::ICFIntMimeTypeObj* obj = Obj; classcode_t classCode = obj->getClassCode(); if( classCode == cfint::CFIntMimeTypeBuff::CLASS_CODE ) { dynamic_cast<cfint::CFIntMimeTypeTableObj*>( schema->getMimeTypeTableObj() )->reallyDetachFromIndexesMimeType( dynamic_cast<cfint::ICFIntMimeTypeObj*>( obj ) ); } if( obj->getEdit() != NULL ) { obj->endEdit(); } delete obj; obj = NULL; } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::createMimeType( cfint::ICFIntMimeTypeEditObj* Obj ) { static const std::string S_ProcName( "createMimeType" ); static const std::string S_Obj( "obj" ); static const std::string S_Cloneable( "cloneable" ); static const std::string S_ClonedBuff( "clonedbuff" ); CFLIB_EXCEPTION_DECLINFO cfint::ICFIntMimeTypeObj* obj = dynamic_cast<cfint::ICFIntMimeTypeObj*>( Obj->getOrig() ); try { cfint::CFIntMimeTypeBuff* buff = dynamic_cast<cfint::CFIntMimeTypeBuff*>( Obj->getBuff()->clone() ); // C++18 version of create returns a new buffer instance and takes over ownership of the passed-in buffer // MSS TODO WORKING The xmsg client will need to return the buffer instance created by processing // the response message, while xmsg rqst will have to delete the backing store instance // it receives after preparing the reply message so that memory doesn't leak on every request. cflib::ICFLibCloneableObj* cloneable = dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMimeType()->createMimeType( schema->getAuthorization(), buff ); if( cloneable == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_Cloneable ); } Obj->endEdit(); obj->setBuff( dynamic_cast<cfint::CFIntMimeTypeBuff*>( cloneable ) ); obj = dynamic_cast<cfint::ICFIntMimeTypeObj*>( obj->realize() ); if( obj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_Obj ); } } CFLIB_EXCEPTION_CATCH_FALLTHROUGH if( ! CFLIB_EXCEPTION_EMPTY ) { if( obj->getEdit() != NULL ) { obj->endEdit(); } if( obj->getIsNew() ) { delete obj; obj = NULL; } CFLIB_EXCEPTION_RETHROW_CFLIBEXCEPTION } return( obj ); } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::readMimeType( cfint::CFIntMimeTypePKey* pkey, bool forceRead ) { static const std::string S_Obj( "obj" ); static const std::string S_Realized( "realized" ); static const std::string S_ProcName( "readMimeType" ); cfint::ICFIntMimeTypeObj* obj = NULL; cfint::ICFIntMimeTypeObj* realized = NULL; if( ! forceRead ) { auto searchMembers = members->find( *pkey ); if( searchMembers != members->end() ) { // obj could be NULL if cache misses is enabled obj = searchMembers->second; realized = obj; } } if( forceRead || ( obj == NULL ) ) { cfint::CFIntMimeTypeBuff* readBuff = dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMimeType()->readDerivedByIdIdx( schema->getAuthorization(), pkey->getRequiredMimeTypeId() ); if( readBuff != NULL ) { obj = dynamic_cast<cfint::CFIntMimeTypeTableObj*>( schema->getMimeTypeTableObj() )->newInstance(); obj->setBuff( readBuff ); realized = dynamic_cast<cfint::ICFIntMimeTypeObj*>( obj->realize() ); if( realized == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_Realized ); } // No need to delete obj -- realize() auto-destructs the instance it decided to discard obj = NULL; } } return( realized ); } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::lockMimeType( cfint::CFIntMimeTypePKey* pkey ) { static const std::string S_ProcName( "lockMimeType" ); cfint::ICFIntMimeTypeObj* locked = NULL; cfint::CFIntMimeTypeBuff* lockBuff = dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMimeType()->lockDerived( schema->getAuthorization(), pkey ); if( lockBuff != NULL ) { locked = dynamic_cast<cfint::CFIntMimeTypeTableObj*>( schema->getMimeTypeTableObj() )->newInstance(); locked->setBuff( lockBuff ); locked = dynamic_cast<cfint::ICFIntMimeTypeObj*>( locked->realize() ); } else { return( NULL ); } return( locked ); } std::vector<cfint::ICFIntMimeTypeObj*> CFIntMimeTypeTableObj::readAllMimeType( bool forceRead ) { static const std::string S_ProcName( "readAllMimeType" ); static const std::string S_Idx( "idx" ); static const std::string S_Realized( "realized" ); CFLIB_EXCEPTION_DECLINFO cfint::ICFIntMimeTypeObj* realized = NULL; if( forceRead || ( allMimeType == NULL ) ) { std::map<cfint::CFIntMimeTypePKey, cfint::ICFIntMimeTypeObj*>* map = new std::map<cfint::CFIntMimeTypePKey,cfint::ICFIntMimeTypeObj*>(); allMimeType = map; std::TCFLibOwningVector<cfint::CFIntMimeTypeBuff*> buffList = dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMimeType()->readAllDerived( schema->getAuthorization() ); cfint::CFIntMimeTypeBuff* buff = NULL; cfint::ICFIntMimeTypeObj* obj = NULL; try { for( size_t idx = 0; idx < buffList.size(); idx ++ ) { buff = buffList[ idx ]; buffList[ idx ] = NULL; obj = newInstance(); obj->setBuff( buff ); realized = dynamic_cast<cfint::ICFIntMimeTypeObj*>( obj->realize() ); if( realized == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_Realized ); } allMimeType->insert( std::map< cfint::CFIntMimeTypePKey, cfint::ICFIntMimeTypeObj* >::value_type( *(realized->getPKey()), realized ) ); // No need to delete obj -- realize() auto-destructs the instance it decided to discard obj = NULL; } } CFLIB_EXCEPTION_CATCH_FALLTHROUGH if( ( obj != NULL ) && obj->getIsNew() ) { delete obj; obj = NULL; } CFLIB_EXCEPTION_RETHROW_CFLIBEXCEPTION } size_t len = allMimeType->size(); std::vector<cfint::ICFIntMimeTypeObj*> arr; auto valIter = allMimeType->begin(); size_t idx = 0; while( valIter != allMimeType->end() ) { arr.push_back( valIter->second ); valIter ++; } return( arr ); } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::readMimeTypeByIdIdx( const int32_t MimeTypeId, bool forceRead ) { static const std::string S_ProcName( "readMimeTypeByIdIdx" ); static const std::string S_Realized( "realized" ); cfint::CFIntMimeTypePKey pkey; pkey.setRequiredMimeTypeId( MimeTypeId ); cfint::ICFIntMimeTypeObj* obj = readMimeType( &pkey, forceRead ); return( obj ); } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::readMimeTypeByUNameIdx( const std::string& Name, bool forceRead ) { static const std::string S_ProcName( "readMimeTypeByUNameIdx" ); static const std::string S_Realized( "realized" ); if( indexByUNameIdx == NULL ) { indexByUNameIdx = new std::map< cfint::CFIntMimeTypeByUNameIdxKey, cfint::ICFIntMimeTypeObj*>(); } cfint::CFIntMimeTypeByUNameIdxKey key; key.setRequiredName( Name ); cfint::ICFIntMimeTypeObj* obj = NULL; cfint::ICFIntMimeTypeObj* realized = NULL; if( ! forceRead ) { auto searchIndexByUNameIdx = indexByUNameIdx->find( key ); if( searchIndexByUNameIdx != indexByUNameIdx->end() ) { // Note: obj may be null if cache misses is enabled obj = searchIndexByUNameIdx->second; realized = obj; } } if( forceRead || ( obj == NULL ) ) { cfint::CFIntMimeTypeBuff* buff = dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMimeType()->readDerivedByUNameIdx( schema->getAuthorization(), Name ); if( buff != NULL ) { obj = dynamic_cast<cfint::CFIntMimeTypeTableObj*>( schema->getMimeTypeTableObj() )->newInstance(); obj->setBuff( buff ); realized = dynamic_cast<cfint::ICFIntMimeTypeObj*>( obj->realize() ); if( realized == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_Realized ); } indexByUNameIdx->insert( std::map< cfint::CFIntMimeTypeByUNameIdxKey, cfint::ICFIntMimeTypeObj*>::value_type( key, dynamic_cast<cfint::ICFIntMimeTypeObj*>( realized ) ) ); // No need to delete obj -- realize() auto-destructs the instance it decided to discard obj = realized; } } return( obj ); } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::readMimeTypeByLookupUNameIdx( const std::string& Name, bool forceRead ) { static const std::string S_Realized( "realized" ); static const std::string S_Obj( "obj" ); static const std::string S_ProcName( "readMimeTypeByLookupUNameIdx" ); if( indexByUNameIdx == NULL ) { indexByUNameIdx = new std::map< cfint::CFIntMimeTypeByUNameIdxKey, cfint::ICFIntMimeTypeObj*>(); } cfint::CFIntMimeTypeByUNameIdxKey key; key.setRequiredName( Name ); cfint::ICFIntMimeTypeObj* obj = NULL; cfint::ICFIntMimeTypeObj* realized = NULL; if( ! forceRead ) { auto searchIndexByUNameIdx = indexByUNameIdx->find( key ); if( searchIndexByUNameIdx != indexByUNameIdx->end() ) { obj = searchIndexByUNameIdx->second; } } if( forceRead || ( obj == NULL ) ) { cfint::CFIntMimeTypeBuff* buff = dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMimeType()->readDerivedByLookupUNameIdx( schema->getAuthorization(), Name ); if( buff != NULL ) { obj = dynamic_cast<cfint::ICFIntMimeTypeObj*>( dynamic_cast<cfint::CFIntMimeTypeTableObj*>( schema->getMimeTypeTableObj() )->newInstance() ); obj->setBuff( buff ); realized = dynamic_cast<cfint::ICFIntMimeTypeObj*>( obj->realize() ); if( realized == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_Realized ); } indexByUNameIdx->insert( std::map< cfint::CFIntMimeTypeByUNameIdxKey, cfint::ICFIntMimeTypeObj*>::value_type( key, dynamic_cast<cfint::ICFIntMimeTypeObj*>( realized ) ) ); // No need to delete obj -- realize() auto-destructs the instance it decided to discard obj = realized; } } return( obj ); } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::readCachedMimeType( cfint::CFIntMimeTypePKey* pkey ) { static const std::string S_Obj( "obj" ); static const std::string S_Realized( "realized" ); static const std::string S_ProcName( "readMimeType" ); cfint::ICFIntMimeTypeObj* obj = NULL; cfint::ICFIntMimeTypeObj* realized = NULL; auto searchMembers = members->find( *pkey ); if( searchMembers != members->end() ) { // obj could be NULL if cache misses is enabled obj = searchMembers->second; realized = obj; } return( realized ); } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::readCachedMimeTypeByIdIdx( const int32_t MimeTypeId ) { static const std::string S_ProcName( "readCachedMimeTypeByIdIdx" ); static const std::string S_Realized( "realized" ); cfint::CFIntMimeTypePKey pkey; pkey.setRequiredMimeTypeId( MimeTypeId ); cfint::ICFIntMimeTypeObj* obj = readCachedMimeType( &pkey ); return( obj ); } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::readCachedMimeTypeByUNameIdx( const std::string& Name ) { static const std::string S_ProcName( "readCachedMimeTypeByUNameIdx" ); static const std::string S_Realized( "realized" ); if( indexByUNameIdx == NULL ) { indexByUNameIdx = new std::map< cfint::CFIntMimeTypeByUNameIdxKey, cfint::ICFIntMimeTypeObj*>(); } cfint::CFIntMimeTypeByUNameIdxKey key; key.setRequiredName( Name ); cfint::ICFIntMimeTypeObj* obj = NULL; auto searchIndexByUNameIdx = indexByUNameIdx->find( key ); if( searchIndexByUNameIdx != indexByUNameIdx->end() ) { // Note: obj may be null if cache misses is enabled obj = searchIndexByUNameIdx->second; } else { for( auto iterMembers = members->begin(); ( obj == NULL ) && ( iterMembers != members->end() ); iterMembers ++ ) { obj = iterMembers->second; if( obj != NULL ) { if( *(dynamic_cast<cfint::CFIntMimeTypeBuff*>( obj->getBuff() ) ) != key ) { obj = NULL; } } } } return( obj ); } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::readCachedMimeTypeByLookupUNameIdx( const std::string& Name ) { static const std::string S_Realized( "realized" ); static const std::string S_Obj( "obj" ); static const std::string S_ProcName( "readCachedMimeTypeByLookupUNameIdx" ); if( indexByUNameIdx == NULL ) { indexByUNameIdx = new std::map< cfint::CFIntMimeTypeByUNameIdxKey, cfint::ICFIntMimeTypeObj*>(); } cfint::CFIntMimeTypeByUNameIdxKey key; key.setRequiredName( Name ); cfint::ICFIntMimeTypeObj* obj = NULL; cfint::ICFIntMimeTypeObj* realized = NULL; auto searchIndexByUNameIdx = indexByUNameIdx->find( key ); if( searchIndexByUNameIdx != indexByUNameIdx->end() ) { obj = searchIndexByUNameIdx->second; } else { for( auto iterMembers = members->begin(); ( obj == NULL ) && ( iterMembers != members->end() ); iterMembers ++ ) { obj = iterMembers->second; if( obj != NULL ) { if( *(dynamic_cast<cfint::CFIntMimeTypeBuff*>( obj->getBuff() ) ) != key ) { obj = NULL; } } } } return( obj ); } cfint::ICFIntMimeTypeObj* CFIntMimeTypeTableObj::updateMimeType( cfint::ICFIntMimeTypeEditObj* Obj ) { static const std::string S_ProcName( "updateMimeType" ); static const std::string S_Obj( "obj" ); static const std::string S_Updated( "updated" ); CFLIB_EXCEPTION_DECLINFO cfint::ICFIntMimeTypeObj* obj = dynamic_cast<cfint::ICFIntMimeTypeObj*>( Obj->getOrig() ); try { cfint::CFIntMimeTypeBuff* updated = dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMimeType()->updateMimeType( schema->getAuthorization(), dynamic_cast<cfint::CFIntMimeTypeBuff*>( Obj->getMimeTypeBuff()->clone() ) ); if( updated == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_Updated ); } obj = dynamic_cast<cfint::ICFIntMimeTypeObj*>( dynamic_cast<cfint::CFIntMimeTypeTableObj*>( schema->getMimeTypeTableObj() )->newInstance() ); obj->setBuff( updated ); obj = dynamic_cast<cfint::ICFIntMimeTypeObj*>( obj->realize() ); if( obj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_Obj ); } if( obj->getEdit() != NULL ) { obj->endEdit(); } } CFLIB_EXCEPTION_CATCH_FALLTHROUGH if( ! CFLIB_EXCEPTION_EMPTY ) { if( obj->getEdit() != NULL ) { obj->endEdit(); } CFLIB_EXCEPTION_RETHROW_CFLIBEXCEPTION } return( obj ); } void CFIntMimeTypeTableObj::deleteMimeType( cfint::ICFIntMimeTypeEditObj* Obj ) { cfint::ICFIntMimeTypeObj* obj = Obj; dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMimeType()->deleteMimeType( schema->getAuthorization(), obj->getMimeTypeBuff() ); deepDisposeByIdIdx( obj->getRequiredMimeTypeId() ); } void CFIntMimeTypeTableObj::deleteMimeTypeByIdIdx( const int32_t MimeTypeId ) { cfint::CFIntMimeTypePKey pkey; pkey.setRequiredMimeTypeId( MimeTypeId ); cfint::ICFIntMimeTypeObj* obj = readMimeType( &pkey, true ); if( obj != NULL ) { cfint::ICFIntMimeTypeEditObj* editObj = dynamic_cast<cfint::ICFIntMimeTypeEditObj*>( obj->getEdit() ); if( editObj == NULL ) { editObj = dynamic_cast<cfint::ICFIntMimeTypeEditObj*>( obj->beginEdit() ); } if( editObj != NULL ) { editObj->deleteInstance(); editObj = NULL; } } } void CFIntMimeTypeTableObj::deleteMimeTypeByUNameIdx( const std::string& Name ) { if( indexByUNameIdx == NULL ) { indexByUNameIdx = new std::map< cfint::CFIntMimeTypeByUNameIdxKey, cfint::ICFIntMimeTypeObj*>(); } cfint::CFIntMimeTypeByUNameIdxKey key; key.setRequiredName( Name ); cfint::ICFIntMimeTypeObj* obj = NULL; auto searchIndexByUNameIdx = indexByUNameIdx->find( key ); if( searchIndexByUNameIdx != indexByUNameIdx->end() ) { dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMimeType()->deleteMimeTypeByUNameIdx( schema->getAuthorization(), Name ); } else { dynamic_cast<ICFIntSchema*>( schema->getBackingStore() )->getTableMimeType()->deleteMimeTypeByUNameIdx( schema->getAuthorization(), Name ); } deepDisposeByUNameIdx( Name ); } void CFIntMimeTypeTableObj::reallyDetachFromIndexesMimeType( cfint::ICFIntMimeTypeObj* Obj ) { static const std::string S_ProcName( "reallyDetachFromIndexesMimeType" ); static const std::string S_Obj( "Obj" ); static const std::string S_ExistingObj( "ExistingObj" ); if( Obj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 1, S_Obj ); } cfint::ICFIntMimeTypeObj* obj = Obj; cfint::CFIntMimeTypePKey* pkey = obj->getPKey(); auto searchMembers = members->find( *pkey ); if( searchMembers != members->end() ) { cfint::ICFIntMimeTypeObj* existingObj = searchMembers->second; if( existingObj == NULL ) { throw cflib::CFLibNullArgumentException( CLASS_NAME, S_ProcName, 0, S_ExistingObj ); } if( indexByUNameIdx != NULL ) { cfint::CFIntMimeTypeByUNameIdxKey keyUNameIdx; keyUNameIdx.setRequiredName( obj->getRequiredName() ); auto removalProbe = indexByUNameIdx->find( keyUNameIdx ); if( removalProbe != indexByUNameIdx->end() ) { indexByUNameIdx->erase( removalProbe ); } } members->erase( searchMembers ); } } }
37.389019
188
0.716732
msobkow
feb62b058d2646a7bba9f74e3efa21e9785d546e
5,352
cc
C++
src/core/heap.cc
upscalesoftware/swoole-src
c99796171a5f9bb90450b570a400e2496490c44b
[ "Apache-2.0" ]
2
2020-08-16T01:24:24.000Z
2021-07-02T03:13:31.000Z
src/core/heap.cc
sunnyMlon/swoole-src
c99796171a5f9bb90450b570a400e2496490c44b
[ "Apache-2.0" ]
null
null
null
src/core/heap.cc
sunnyMlon/swoole-src
c99796171a5f9bb90450b570a400e2496490c44b
[ "Apache-2.0" ]
null
null
null
/* +----------------------------------------------------------------------+ | Swoole | +----------------------------------------------------------------------+ | This source file is subject to version 2.0 of the Apache license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.apache.org/licenses/LICENSE-2.0.html | | If you did not receive a copy of the Apache2.0 license and are unable| | to obtain it through the world-wide-web, please send a note to | | license@swoole.com so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Tianfeng Han <mikan.tenny@gmail.com> | +----------------------------------------------------------------------+ */ #include "swoole.h" #include "heap.h" #define left(i) ((i) << 1) #define right(i) (((i) << 1) + 1) #define parent(i) ((i) >> 1) static void swHeap_bubble_up(swHeap *heap, uint32_t i); static uint32_t swHeap_maxchild(swHeap *heap, uint32_t i); static void swHeap_percolate_down(swHeap *heap, uint32_t i); swHeap *swHeap_new(size_t n, uint8_t type) { swHeap *heap = (swHeap *) sw_malloc(sizeof(swHeap)); if (!heap) { return nullptr; } if (!(heap->nodes = (swHeap_node **) sw_malloc((n + 1) * sizeof(void *)))) { sw_free(heap); return nullptr; } heap->num = 1; heap->size = (n + 1); heap->type = type; return heap; } void swHeap_free(swHeap *heap) { sw_free(heap->nodes); sw_free(heap); } static sw_inline int swHeap_compare(uint8_t type, uint64_t a, uint64_t b) { if (type == SW_MIN_HEAP) { return a > b; } else { return a < b; } } uint32_t swHeap_size(swHeap *q) { return (q->num - 1); } static uint32_t swHeap_maxchild(swHeap *heap, uint32_t i) { uint32_t child_i = left(i); if (child_i >= heap->num) { return 0; } swHeap_node *child_node = heap->nodes[child_i]; if ((child_i + 1) < heap->num && swHeap_compare(heap->type, child_node->priority, heap->nodes[child_i + 1]->priority)) { child_i++; } return child_i; } static void swHeap_bubble_up(swHeap *heap, uint32_t i) { swHeap_node *moving_node = heap->nodes[i]; uint32_t parent_i; for (parent_i = parent(i); (i > 1) && swHeap_compare(heap->type, heap->nodes[parent_i]->priority, moving_node->priority); i = parent_i, parent_i = parent(i)) { heap->nodes[i] = heap->nodes[parent_i]; heap->nodes[i]->position = i; } heap->nodes[i] = moving_node; moving_node->position = i; } static void swHeap_percolate_down(swHeap *heap, uint32_t i) { uint32_t child_i; swHeap_node *moving_node = heap->nodes[i]; while ((child_i = swHeap_maxchild(heap, i)) && swHeap_compare(heap->type, moving_node->priority, heap->nodes[child_i]->priority)) { heap->nodes[i] = heap->nodes[child_i]; heap->nodes[i]->position = i; i = child_i; } heap->nodes[i] = moving_node; moving_node->position = i; } swHeap_node *swHeap_push(swHeap *heap, uint64_t priority, void *data) { void *tmp; uint32_t i; uint32_t newsize; if (heap->num >= heap->size) { newsize = heap->size * 2; if (!(tmp = sw_realloc(heap->nodes, sizeof(void *) * newsize))) { return nullptr; } heap->nodes = (swHeap_node **) tmp; heap->size = newsize; } swHeap_node *node = (swHeap_node *) sw_malloc(sizeof(swHeap_node)); if (!node) { return nullptr; } node->priority = priority; node->data = data; i = heap->num++; heap->nodes[i] = node; swHeap_bubble_up(heap, i); return node; } void swHeap_change_priority(swHeap *heap, uint64_t new_priority, void *ptr) { swHeap_node *node = (swHeap_node *) ptr; uint32_t pos = node->position; uint64_t old_pri = node->priority; node->priority = new_priority; if (swHeap_compare(heap->type, old_pri, new_priority)) { swHeap_bubble_up(heap, pos); } else { swHeap_percolate_down(heap, pos); } } void swHeap_remove(swHeap *heap, swHeap_node *node) { uint32_t pos = node->position; heap->nodes[pos] = heap->nodes[--heap->num]; if (swHeap_compare(heap->type, node->priority, heap->nodes[pos]->priority)) { swHeap_bubble_up(heap, pos); } else { swHeap_percolate_down(heap, pos); } } void *swHeap_pop(swHeap *heap) { swHeap_node *head; if (!heap || heap->num == 1) { return nullptr; } head = heap->nodes[1]; heap->nodes[1] = heap->nodes[--heap->num]; swHeap_percolate_down(heap, 1); void *data = head->data; sw_free(head); return data; } void *swHeap_peek(swHeap *heap) { if (heap->num == 1) { return nullptr; } swHeap_node *node = heap->nodes[1]; if (!node) { return nullptr; } return node->data; } void swHeap_print(swHeap *heap) { for (uint32_t i = 1; i < heap->num; i++) { printf("#%d\tpriority=%ld, data=%p\n", i, (long) heap->nodes[i]->priority, heap->nodes[i]->data); } }
29.086957
105
0.560725
upscalesoftware
feb6e5965a4dcbd3a8ec03fe55e54d8f251289d5
14,666
cpp
C++
src/parse.cpp
Phildo/expandpass
7e4a5ac77e6b194dcbcb26284b1201ba841fee77
[ "MIT" ]
165
2018-03-19T15:06:33.000Z
2021-11-15T15:44:39.000Z
src/parse.cpp
Phildo/expandpass
7e4a5ac77e6b194dcbcb26284b1201ba841fee77
[ "MIT" ]
3
2021-01-05T05:04:10.000Z
2021-12-24T03:18:57.000Z
src/parse.cpp
Phildo/expandpass
7e4a5ac77e6b194dcbcb26284b1201ba841fee77
[ "MIT" ]
11
2018-04-30T17:51:21.000Z
2021-05-01T03:37:54.000Z
#include "parse.h" #include "util.h" int parse_child(FILE *fp, int unquoted, int *line_n, char *buff, char **b, group *g, group *prev_g, int depth, parse_error *er) { g->countable = 1; //until proven otherwise int n_chars = 0; while(buff[n_chars] != '\0') n_chars++; size_t line_buff_len = max_read_line_len; char *s = *b; while(g->type == GROUP_TYPE_NULL) { if(*s == '\0') { n_chars = getline(&buff, &line_buff_len, fp); *line_n = *line_n+1; if(n_chars <= 0) { *buff = '\0'; er->error = ERROR_EOF; safe_sprintf(er->txt,"ERROR: EOF\nline %d\n",*line_n); return 0; } s = buff; } while(*s == ' ' || *s == '\t') s++; if(*s == '<' ) { g->type = GROUP_TYPE_SEQUENCE; s++; } else if(*s == '{' ) { g->type = GROUP_TYPE_OPTION; s++; } else if(*s == '(' ) { g->type = GROUP_TYPE_PERMUTE; s++; } else if(*s == '"' ) { g->type = GROUP_TYPE_CHARS; s++; } else if(*s == '[' ) { g->type = GROUP_TYPE_MODIFICATION; s++; } else if(*s == '#' ) { g->type = GROUP_TYPE_NULL; s++; *s = '\0'; } else if(*s == '\n') { g->type = GROUP_TYPE_NULL; s++; *s = '\0'; } else if(*s == '\0') { g->type = GROUP_TYPE_NULL; s++; *s = '\0'; } else if(*s == '-') { char *c; g->type = GROUP_TYPE_CHARS; g->n = 0; g->chars = (char *)safe_malloc(sizeof(char)*g->n+1); c = g->chars; s++; *c = '\0'; *b = s; return 1; } else if(unquoted && *s != '>' && *s != '}' && *s != ')' && *s != ']') { char *c; g->type = GROUP_TYPE_CHARS; if(*s == '\\') s++; g->n = 1; g->chars = (char *)safe_malloc(sizeof(char)*g->n+1); c = g->chars; *c = *s; c++; s++; *c = '\0'; *b = s; return 1; } else { *b = s; er->error = ERROR_INVALID_LINE; if(buff[n_chars-1] == '\n') n_chars--; buff[n_chars] = '\0'; safe_sprintf(er->txt,"ERROR: Invalid line\nline %d ( %s )\n",*line_n,buff); return 0; } if(g->type != GROUP_TYPE_CHARS) { while(*s == ' ' || *s == '\t') s++; } char *c; if(g->type == GROUP_TYPE_OPTION) g->countable = 0; //TODO: this limitation renders "countability" a farce switch(g->type) { case GROUP_TYPE_SEQUENCE: case GROUP_TYPE_OPTION: case GROUP_TYPE_PERMUTE: g->n = 0; *b = s; if(g->type == GROUP_TYPE_SEQUENCE) { if(!parse_tag(fp, line_n, buff, b, &g->tag_u, 1, er)) return 0; if(!parse_tag(fp, line_n, buff, b, &g->tag_g, 0, er)) return 0; if(g->tag_u) g->countable = 0; if(g->tag_g) g->countable = 0; } return parse_childs(fp, unquoted, line_n, buff, b, g, depth+1, er); break; case GROUP_TYPE_CHARS: c = s; while(*c != '"' && *c != '\n' && *c != '\0') { if(*c == '\\') c++; c++; } if(*c == '"') { g->n = (c-s); g->chars = (char *)safe_malloc(sizeof(char)*g->n+1); c = g->chars; while(*s != '"' && *s != '\n' && *s != '\0') { if(*s == '\\') { s++; g->n--; } *c = *s; c++; s++; } if(*s != '"') { er->error = ERROR_UNTERMINATED_STRING; if(buff[n_chars-1] == '\n') n_chars--; buff[n_chars] = '\0'; safe_sprintf(er->txt,"ERROR: Unterminated string\nline %d ( %s )\n",*line_n,buff); return 0; } s++; *c = '\0'; } else { er->error = ERROR_INVALID_STRING; if(buff[n_chars-1] == '\n') n_chars--; buff[n_chars] = '\0'; safe_sprintf(er->txt,"ERROR: Invalid characters after begining string\nline %d ( %s )\n",*line_n,buff); return 0; } break; case GROUP_TYPE_MODIFICATION: //special case if(!prev_g) { er->error = ERROR_UNPARENTED_MODIFICATION; if(buff[n_chars-1] == '\n') n_chars--; buff[n_chars] = '\0'; safe_sprintf(er->txt,"ERROR: Modification with no previous group\nline %d ( %s )\n",*line_n,buff); return 0; } *b = s; return parse_modifications(fp, line_n, buff, b, prev_g, er); break; case GROUP_TYPE_NULL: ; break; default: //appease compiler break; } } *b = s; return 1; } int parse_tag(FILE *fp, int *line_n, char *buff, char **b, tag *t, int u, parse_error *er) { assert(!*t); int n_chars = 0; while(buff[n_chars] != '\0') n_chars++; size_t line_buff_len = max_read_line_len; char *s = *b; while(1) { if(*s == '\0') { n_chars = getline(&buff, &line_buff_len, fp); *line_n = *line_n+1; if(n_chars <= 0) { *buff = '\0'; er->error = ERROR_BADEOF; safe_sprintf(er->txt,"ERROR: EOF parsing tag\nline %d\n",*line_n); return 0; } s = buff; } else if(*s == ' ' || *s == '\t') s++; else break; } int parsed = 0; int d; if((u && *s == 'U') || (!u && *s == 'G')) { s++; while((d = parse_number(s,&parsed)) != -1) { if(parsed < 1 || parsed >= max_tag_count) { er->error = ERROR_TAG_RANGE; if(u) safe_sprintf(er->txt,"ERROR: unique tag outside of valid range [1-%d]\nline %d\n",max_tag_count-1,*line_n); else safe_sprintf(er->txt,"ERROR: group tag outside of valid range [1-%d]\nline %d\n",max_tag_count-1,*line_n); return 0; } s += d; *t |= 1 << (parsed-1); if(*s == ',') s++; } if(!*t) { er->error = ERROR_TAG_SPECIFY; if(u) safe_sprintf(er->txt,"ERROR: unique tag not specified\nline %d\n",*line_n); else safe_sprintf(er->txt,"ERROR: group tag not specified\nline %d\n",*line_n); return 0; } } *b = s; return 1; } int parse_modification(FILE *fp, int *line_n, char *buff, char **b, modification *m, parse_error *er) { int n_chars = 0; while(buff[n_chars] != '\0') n_chars++; size_t line_buff_len = max_read_line_len; char *s = *b; int found = 0; while(!found) { if(*s == '\0') { n_chars = getline(&buff, &line_buff_len, fp); *line_n = *line_n+1; if(n_chars <= 0) { *buff = '\0'; er->error = ERROR_BADEOF; safe_sprintf(er->txt,"ERROR: EOF parsing modification\nline %d\n",*line_n); return 0; } s = buff; } int d = 1; while(d > 0) { while(*s == ' ' || *s == '\t') s++; if(*s == 'c' ) { s++; d = parse_number(s,&m->n_copys); m->n_copys -= 1; } //m->n_copys = 0 means "just do it once" (ie default) else if(*s == 'd' ) { s++; d = parse_number(s,&m->n_deletions); } else if(*s == 's' ) { s++; d = parse_number(s,&m->n_substitutions); } else if(*s == 'i' ) { s++; d = parse_number(s,&m->n_injections); } else if(*s == 'm' ) { s++; d = parse_number(s,&m->n_smart_substitutions); } else if(*s == '-' ) { s++; *b = s; if(m->n_injections+m->n_smart_substitutions+m->n_substitutions+m->n_deletions+m->n_copys == 0) return 1; else d = -1; } else break; if(d < 0) { er->error = ERROR_INVALID_NULL_MODIFICATION; if(buff[n_chars-1] == '\n') n_chars--; buff[n_chars] = '\0'; safe_sprintf(er->txt,"ERROR: Invalid null modification\nline %d ( %s )\n",*line_n,buff); return 0; } else { s += d; found = 1; } } if(!found) { if(*s == '#' ) { s++; *s = '\0'; } else if(*s == '\n') { s++; *s = '\0'; } else if(*s == '\0') { s++; *s = '\0'; } else { *b = s; er->error = ERROR_INVALID_MODIFICATION; if(buff[n_chars-1] == '\n') n_chars--; buff[n_chars] = '\0'; safe_sprintf(er->txt,"ERROR: Invalid line in modification\nline %d ( %s )\n",*line_n,buff); return 0; } } else { if(*s == '#' ) { s++; *s = '\0'; } else if(*s == '\n') { s++; *s = '\0'; } else if(*s == '\0') { s++; *s = '\0'; } else if(*s == '"' ) //get chars { s++; char *c = s; while(*c != '"' && *c != '\n' && *c != '\0') { if(*c == '\\') c++; c++; } if(*c == '"') { m->n = (c-s); m->chars = (char *)safe_malloc(sizeof(char)*m->n+1); c = m->chars; while(*s != '"' && *s != '\n' && *s != '\0') { if(*s == '\\') { s++; m->n--; } *c = *s; c++; s++; } if(*s != '"') { er->error = ERROR_UNTERMINATED_STRING; if(buff[n_chars-1] == '\n') n_chars--; buff[n_chars] = '\0'; safe_sprintf(er->txt,"ERROR: Unterminated modification gamut\nline %d ( %s )\n",*line_n,buff); return 0; } s++; *c = '\0'; } else { er->error = ERROR_INVALID_STRING; if(buff[n_chars-1] == '\n') n_chars--; buff[n_chars] = '\0'; safe_sprintf(er->txt,"ERROR: Invalid characters after begining gamut\nline %d ( %s )\n",*line_n,buff); return 0; } } } if(m->n_substitutions+m->n_injections > 0 && !m->n) { er->error = ERROR_MODIFICATION_EMPTY_GAMUT; if(buff[n_chars-1] == '\n') n_chars--; buff[n_chars] = '\0'; safe_sprintf(er->txt,"ERROR: gamut required with substitution or injection\nline %d ( %s )\n",*line_n,buff); return 0; } } *b = s; return 1; } int parse_modifications(FILE *fp, int *line_n, char *buff, char **b, group *g, parse_error *er) { char *s; int valid_modification = 1; modification *m = (modification *)safe_malloc(sizeof(modification)); while(valid_modification) { zero_modification(m); valid_modification = parse_modification(fp,line_n,buff,b,m,er); if(valid_modification) { if(m->n_smart_substitutions) g->countable = 0; g->n_mods++; if(g->n_mods == 1) g->mods = (modification *)safe_malloc(sizeof(modification)); else g->mods = (modification *)safe_realloc(g->mods,sizeof(modification)*g->n_mods); g->mods[g->n_mods-1] = *m; } } free(m); if(er->error == ERROR_BADEOF) return 0; //close everything if(er->error != ERROR_INVALID_MODIFICATION) return 0; //let "invalid modification" attempt parse as "end modification" if(er->force) return 0; //if error force, don't allow passthrough ("unexpected parse" should only bubble up one level) s = *b; if(*s != ']') { //er->error; //retain error from stack int n_chars = 0; while(buff[n_chars] != '\0') n_chars++; if(buff[n_chars-1] == '\n') n_chars--; buff[n_chars] = '\0'; safe_sprintf(er->txt,"ERROR: Invalid characters within modifiers\nline %d ( %s )\n",*line_n,buff); er->force = 1; return 0; } s++; *b = s; return 1; } int parse_childs(FILE *fp, int unquoted, int *line_n, char *buff, char **b, group *g, int depth, parse_error *er) { char *s; int valid_kid = 1; group *prev_c = 0; group *c = (group *)safe_malloc(sizeof(group)); while(valid_kid) { zero_group(c); valid_kid = parse_child(fp, unquoted, line_n, buff, b, c, prev_c, depth+1, er); if(valid_kid) { if(c->type == GROUP_TYPE_MODIFICATION) { //ok } else if(c->type == GROUP_TYPE_NULL) { er->error = ERROR_NULL_CHILD; int n_chars = 0; while(buff[n_chars] != '\0') n_chars++; if(buff[n_chars-1] == '\n') n_chars--; buff[n_chars] = '\0'; safe_sprintf(er->txt,"Null child type found\nline %d ( %s )\n",*line_n,buff); } else { g->n++; if(g->n == 1) g->childs = (group *)safe_malloc(sizeof(group)); else g->childs = (group *)safe_realloc(g->childs,sizeof(group)*g->n); g->childs[g->n-1] = *c; prev_c = &g->childs[g->n-1]; } } } free(c); if(er->error == ERROR_EOF) { if(depth == 0) return 1; //close everything else { er->error = ERROR_BADEOF; //upgrade error switch(g->type) { case GROUP_TYPE_SEQUENCE: safe_sprintf(er->txt,"ERROR: EOF unclosed sequence\nline %d\n",*line_n); break; case GROUP_TYPE_OPTION: safe_sprintf(er->txt,"ERROR: EOF unclosed option\nline %d\n",*line_n); break; case GROUP_TYPE_PERMUTE: safe_sprintf(er->txt,"ERROR: EOF unclosed permute\nline %d\n",*line_n); break; default: break; //appease compiler } return 0; } } if(er->error != ERROR_INVALID_LINE) return 0; //let "invalid line" attempt parse as "end line" if(er->force) return 0; //if error force, don't allow passthrough ("unexpected parse" should only bubble up one level) s = *b; if(*s == '>' && g->type == GROUP_TYPE_SEQUENCE) s++; //great else if(*s == '}' && g->type == GROUP_TYPE_OPTION) s++; //great else if(*s == ')' && g->type == GROUP_TYPE_PERMUTE) s++; //great else { //er->error; //retain error from stack int n_chars = 0; while(buff[n_chars] != '\0') n_chars++; if(buff[n_chars-1] == '\n') n_chars--; buff[n_chars] = '\0'; if(g->type == GROUP_TYPE_SEQUENCE) safe_sprintf(er->txt,"ERROR: Invalid characters within sequence\nline %d ( %s )\n",*line_n,buff); if(g->type == GROUP_TYPE_OPTION) safe_sprintf(er->txt,"ERROR: Invalid characters within option\nline %d ( %s )\n",*line_n,buff); if(g->type == GROUP_TYPE_PERMUTE) safe_sprintf(er->txt,"ERROR: Invalid characters within permute\nline %d ( %s )\n",*line_n,buff); er->force = 1; return 0; } *b = s; return 1; } group *parse(FILE *fp, int unquoted) { char *buff; buff = (char *)safe_malloc(sizeof(char)*max_read_line_len); parse_error er; er.error = ERROR_NULL; er.force = 0; er.txt = (char *)safe_malloc(sizeof(char)*max_sprintf_len); int line_n = 0; group *g = (group *)safe_malloc(sizeof(group)); zero_group(g); g->type = GROUP_TYPE_SEQUENCE; char *b = buff; *b = '\0'; if(!parse_childs(fp, unquoted, &line_n, buff, &b, g, 0, &er)) { fprintf(stderr, "%s", er.txt); exit(1); } while(g->n == 1 && g->n_mods == 0 && (g->type == GROUP_TYPE_SEQUENCE || g->type == GROUP_TYPE_OPTION || g->type == GROUP_TYPE_PERMUTE)) { group *og = g->childs; *g = g->childs[0]; free(og); } free(buff); free(er.txt); return g; }
30.746331
150
0.503409
Phildo
feb98a5159c3b687e49309e21f4d66b38b96d70e
871
cc
C++
src/record_stack.cc
DouglasRMiles/QuProlog
798d86f87fb4372b8918ef582ef2f0fc0181af2d
[ "Apache-2.0" ]
5
2019-11-20T02:05:31.000Z
2022-01-06T18:59:16.000Z
src/record_stack.cc
logicmoo/QuProlog
798d86f87fb4372b8918ef582ef2f0fc0181af2d
[ "Apache-2.0" ]
null
null
null
src/record_stack.cc
logicmoo/QuProlog
798d86f87fb4372b8918ef582ef2f0fc0181af2d
[ "Apache-2.0" ]
2
2022-01-08T13:52:24.000Z
2022-03-07T17:41:37.000Z
// record_stack.cc - Fundamental stack arrangement. // // ##Copyright## // // Copyright 2000-2016 Peter Robinson (pjr@itee.uq.edu.au) // // 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.00 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ##Copyright## // // $Id: record_stack.cc,v 1.3 2001/06/07 05:18:12 qp Exp $ #include "area_offsets.h" #include "defs.h" #include "record_stack.h" #include "stack_qp.h"
31.107143
75
0.718714
DouglasRMiles
febad553870935dd75de39924f5beb8a6314fae0
1,445
cpp
C++
src/wmecore/Timer.cpp
retrowork/wme
54cf8905091736aef0a35fe6d3e05b818441f3c8
[ "MIT" ]
null
null
null
src/wmecore/Timer.cpp
retrowork/wme
54cf8905091736aef0a35fe6d3e05b818441f3c8
[ "MIT" ]
null
null
null
src/wmecore/Timer.cpp
retrowork/wme
54cf8905091736aef0a35fe6d3e05b818441f3c8
[ "MIT" ]
null
null
null
// This file is part of Wintermute Engine // For conditions of distribution and use, see copyright notice in license.txt #include "Wme.h" #include "Timer.h" namespace Wme { ////////////////////////////////////////////////////////////////////////// Timer::Timer() { m_OgreTimer = new Ogre::Timer(); Reset(); } ////////////////////////////////////////////////////////////////////////// Timer::~Timer() { SAFE_DELETE(m_OgreTimer); } ////////////////////////////////////////////////////////////////////////// void Timer::Reset() { m_CurrentTime = m_PrevTime = m_ElapsedTime = 0; m_IsFrozen = false; m_Multiplier = 1.0; } ////////////////////////////////////////////////////////////////////////// unsigned long Timer::Update() { if (m_IsFrozen) { m_ElapsedTime = 0; return m_CurrentTime; } unsigned long currentTime = m_OgreTimer->getMilliseconds(); unsigned long delta = currentTime - m_PrevTime; if (delta > 1000) delta = 1000; delta = (unsigned long)((float)delta * m_Multiplier); m_CurrentTime += delta; m_PrevTime = currentTime; m_ElapsedTime = delta; return m_CurrentTime; } ////////////////////////////////////////////////////////////////////////// void Timer::Freeze() { m_IsFrozen = true; } ////////////////////////////////////////////////////////////////////////// void Timer::Unfreeze() { m_IsFrozen = false; } } // namespace Wme
20.942029
79
0.445675
retrowork
febca984c8257a8aedff4f3ceb5e763bae9d7866
833
hpp
C++
include/avr/io/register/detail/all_state_representation_at_compiletime.hpp
ricardocosme/avrIO
b60238b48d1283324f8f73e530d582432c6c5f71
[ "MIT" ]
10
2021-02-03T09:51:58.000Z
2021-06-07T20:34:26.000Z
include/avr/io/register/detail/all_state_representation_at_compiletime.hpp
ricardocosme/avrIO
b60238b48d1283324f8f73e530d582432c6c5f71
[ "MIT" ]
null
null
null
include/avr/io/register/detail/all_state_representation_at_compiletime.hpp
ricardocosme/avrIO
b60238b48d1283324f8f73e530d582432c6c5f71
[ "MIT" ]
null
null
null
#pragma once #include "avr/io/detail/type_traits/enable_if.hpp" namespace avr { namespace io { namespace detail { template<typename Bit, typename... Rest> struct all_state_representation_at_compiletime { constexpr static bool value = all_state_representation_at_compiletime<Bit>::value && all_state_representation_at_compiletime<Rest...>::value; }; template<typename Bit> struct all_state_representation_at_compiletime<Bit> { constexpr static bool value = !Bit::representation_at_runtime; }; template<typename... Bits> using enable_if_state_representation_at_runtime = enable_if_t< !all_state_representation_at_compiletime<Bits...>::value>; template<typename... Bits> using enable_if_state_representation_at_compiletime = enable_if_t< all_state_representation_at_compiletime<Bits...>::value>; }}}
29.75
67
0.788715
ricardocosme
fec60fafebf268157110b35e1ec6557c78bb43b6
3,173
hpp
C++
libs/sprite/include/sge/sprite/geometry/detail/fill_texture_coordinates.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/sprite/include/sge/sprite/geometry/detail/fill_texture_coordinates.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/sprite/include/sge/sprite/geometry/detail/fill_texture_coordinates.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_SPRITE_GEOMETRY_DETAIL_FILL_TEXTURE_COORDINATES_HPP_INCLUDED #define SGE_SPRITE_GEOMETRY_DETAIL_FILL_TEXTURE_COORDINATES_HPP_INCLUDED #include <sge/renderer/lock_rect_to_coords.hpp> #include <sge/renderer/texture/planar.hpp> #include <sge/sprite/object_impl.hpp> #include <sge/sprite/detail/config/has_normal_size.hpp> #include <sge/sprite/detail/config/has_repetition.hpp> #include <sge/sprite/detail/config/has_texture_coordinates.hpp> #include <sge/sprite/geometry/detail/convert_texture_rect.hpp> #include <sge/sprite/geometry/detail/fill_texture_coordinates_rect.hpp> #include <sge/texture/area_texc.hpp> #include <sge/texture/part.hpp> #include <fcppt/config/external_begin.hpp> #include <type_traits> #include <fcppt/config/external_end.hpp> namespace sge::sprite::geometry::detail { template <typename Level, typename Iterator, typename Choices> inline std::enable_if_t< std::conjunction_v< sge::sprite::detail::config::has_texture_coordinates<Choices>, sge::sprite::detail::config::has_normal_size<Choices>>, void> fill_texture_coordinates( Level const &, Iterator const &_iterator, sge::sprite::object<Choices> const &_sprite, sge::texture::part const &) { sge::sprite::geometry::detail::fill_texture_coordinates_rect<Level, Choices>( _iterator, _sprite.template texture_coordinates_level<Level::value>()); } template <typename Level, typename Iterator, typename Choices> inline std::enable_if_t< std::conjunction_v< sge::sprite::detail::config::has_repetition<Choices>, sge::sprite::detail::config::has_normal_size<Choices>>, void> fill_texture_coordinates( Level const &, Iterator const &_iterator, sge::sprite::object<Choices> const &_sprite, sge::texture::part const &_texture) { sge::sprite::geometry::detail::fill_texture_coordinates_rect<Level, Choices>( _iterator, sge::sprite::geometry::detail::convert_texture_rect<Choices>( sge::texture::area_texc<typename Choices::type_choices::float_type>( _texture, _sprite.repetition()))); } template <typename Level, typename Iterator, typename Choices> inline std::enable_if_t< std::conjunction_v< sge::sprite::detail::config::has_normal_size<Choices>, std::negation<std::disjunction< sge::sprite::detail::config::has_repetition<Choices>, sge::sprite::detail::config::has_texture_coordinates<Choices>>>>, void> fill_texture_coordinates( Level const &, Iterator const &_iterator, sge::sprite::object<Choices> const &, sge::texture::part const &_texture) { sge::sprite::geometry::detail::fill_texture_coordinates_rect<Level, Choices>( _iterator, sge::sprite::geometry::detail::convert_texture_rect<Choices>( sge::renderer::lock_rect_to_coords<typename Choices::type_choices::float_type>( _texture.area(), _texture.texture().size()))); } } #endif
37.329412
89
0.734006
cpreh
fec8873992427be8e19f8959f232590f693556d7
1,027
cpp
C++
2. Рекуррентные соотношения/67. Ним #3241/[OK]235157.cpp
godnoTA/acm.bsu.by
3e1cf1c545c691de82b5e1d2e0768b41ea581734
[ "Unlicense" ]
19
2018-05-19T16:37:14.000Z
2022-03-23T20:13:43.000Z
2. Рекуррентные соотношения/67. Ним #3241/[OK]235157.cpp
godnoTA/acm.bsu.by
3e1cf1c545c691de82b5e1d2e0768b41ea581734
[ "Unlicense" ]
6
2020-05-07T21:06:48.000Z
2020-06-05T17:52:57.000Z
2. Рекуррентные соотношения/67. Ним #3241/[OK]235157.cpp
godnoTA/acm.bsu.by
3e1cf1c545c691de82b5e1d2e0768b41ea581734
[ "Unlicense" ]
31
2019-03-01T21:41:38.000Z
2022-03-27T17:56:39.000Z
#include <iostream> #include <fstream> using namespace std; const long long int del = 1000000007; long long int binpow (long long int a, long long int n) { long long int res = 1; while (n) { if (n & 1) { res *= a; res = res % del; } a *= a; a = a%del; n >>= 1; } return res; } int main() { ifstream f1("nim.in"); ofstream f2("nim.out"); long long int n,m,otv(0); f1>>n>>m; long long int g1 = 0, g2 = 0, maxm = binpow(2, m), gnext(0); long long int vch = ((maxm - 1)*(maxm - 2))%del, next = maxm - 3; for (int i = 3; i<=n; i++) { gnext = vch - g1 - ((i-1)*(maxm-1-(i-2))%del)*g2; if (gnext < 0) { gnext = gnext + ((-gnext)/del)*del; gnext = (del + gnext)%del; } vch *= next; vch %= del; next--; g2 = g1; g1 = gnext; } if (n == 1) { gnext = maxm - 1; } else { gnext = vch - gnext; if (gnext < 0) { gnext = gnext + ((-gnext)/del)*del; gnext = (del + gnext)%del; } } f2 << gnext; f1.close(); f2.close(); return 0; }
19.018519
84
0.500487
godnoTA
fec91541d90493d6bac3a004732866d7a6664797
3,059
cc
C++
garnet/lib/ui/gfx/tests/session_handler_test.cc
yanyushr/fuchsia
98e70672a81a206d235503e398f37b7b65581f79
[ "BSD-3-Clause" ]
null
null
null
garnet/lib/ui/gfx/tests/session_handler_test.cc
yanyushr/fuchsia
98e70672a81a206d235503e398f37b7b65581f79
[ "BSD-3-Clause" ]
null
null
null
garnet/lib/ui/gfx/tests/session_handler_test.cc
yanyushr/fuchsia
98e70672a81a206d235503e398f37b7b65581f79
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "garnet/lib/ui/gfx/tests/session_handler_test.h" namespace scenic_impl { namespace gfx { namespace test { void SessionHandlerTest::SetUp() { InitializeScenic(); InitializeDisplayManager(); InitializeEngine(); InitializeSessionHandler(); } void SessionHandlerTest::TearDown() { command_dispatcher_.reset(); engine_.reset(); command_buffer_sequencer_.reset(); display_manager_.reset(); scenic_.reset(); app_context_.reset(); events_.clear(); } void SessionHandlerTest::InitializeScenic() { // TODO(SCN-720): Wrap Create using ::gtest::Environment // instead of this hack. This code has the chance to break non-ScenicTests. app_context_ = sys::ComponentContext::Create(); scenic_ = std::make_unique<Scenic>(app_context_.get(), inspect::Object(), [] {}); } void SessionHandlerTest::InitializeSessionHandler() { auto session_context = engine_->session_context(); auto session_manager = session_context.session_manager; auto session_id = SessionId(1); InitializeScenicSession(session_id); command_dispatcher_ = session_manager->CreateCommandDispatcher( CommandDispatcherContext(scenic_.get(), scenic_session_.get()), std::move(session_context)); } void SessionHandlerTest::InitializeDisplayManager() { display_manager_ = std::make_unique<DisplayManager>(); display_manager_->SetDefaultDisplayForTests(std::make_unique<Display>( /*id*/ 0, /*px-width*/ 0, /*px-height*/ 0)); } void SessionHandlerTest::InitializeEngine() { command_buffer_sequencer_ = std::make_unique<escher::impl::CommandBufferSequencer>(); auto mock_release_fence_signaller = std::make_unique<ReleaseFenceSignallerForTest>( command_buffer_sequencer_.get()); engine_ = std::make_unique<EngineForTest>( app_context_.get(), display_manager_.get(), std::move(mock_release_fence_signaller), /*event reporter*/ this, this->error_reporter()); } void SessionHandlerTest::InitializeScenicSession(SessionId session_id) { fidl::InterfaceHandle<fuchsia::ui::scenic::SessionListener> listener; scenic_session_ = std::make_unique<scenic_impl::Session>(session_id, std::move(listener)); } void SessionHandlerTest::EnqueueEvent(fuchsia::ui::gfx::Event event) { fuchsia::ui::scenic::Event scenic_event; scenic_event.set_gfx(std::move(event)); events_.push_back(std::move(scenic_event)); } void SessionHandlerTest::EnqueueEvent(fuchsia::ui::input::InputEvent event) { fuchsia::ui::scenic::Event scenic_event; scenic_event.set_input(std::move(event)); events_.push_back(std::move(scenic_event)); } void SessionHandlerTest::EnqueueEvent(fuchsia::ui::scenic::Command unhandled) { fuchsia::ui::scenic::Event scenic_event; scenic_event.set_unhandled(std::move(unhandled)); events_.push_back(std::move(scenic_event)); } } // namespace test } // namespace gfx } // namespace scenic_impl
32.2
79
0.746322
yanyushr
feca71ac33e521b0471ed2505ff0a2d750a05eb6
114
cpp
C++
src/math/Bezier.cpp
daysofwonder/common-cpp
e191be23299ec502c91cf4224eb8a2def9295cf5
[ "MIT" ]
null
null
null
src/math/Bezier.cpp
daysofwonder/common-cpp
e191be23299ec502c91cf4224eb8a2def9295cf5
[ "MIT" ]
1
2019-09-18T09:51:21.000Z
2019-09-18T09:51:21.000Z
src/math/Bezier.cpp
daysofwonder/common-cpp
e191be23299ec502c91cf4224eb8a2def9295cf5
[ "MIT" ]
1
2021-07-28T01:26:07.000Z
2021-07-28T01:26:07.000Z
// // Created by Dawid Drozd aka Gelldur on 03.12.17. // #include "Bezier.h" //////////////////////////////////
14.25
50
0.447368
daysofwonder
fecd9fedf2261dfb43a515ede96c8c77de2dd7c0
1,769
cpp
C++
ngraph/core/src/op/util/elementwise_args.cpp
uikilin100/openvino
afc5191b8c75b1de4adc8cb07c6269b52882ddfe
[ "Apache-2.0" ]
1
2021-03-16T17:40:26.000Z
2021-03-16T17:40:26.000Z
ngraph/core/src/op/util/elementwise_args.cpp
uikilin100/openvino
afc5191b8c75b1de4adc8cb07c6269b52882ddfe
[ "Apache-2.0" ]
42
2020-11-23T08:09:57.000Z
2022-02-21T13:03:34.000Z
ngraph/core/src/op/util/elementwise_args.cpp
tsocha/openvino
3081fac7581933568b496a3c4e744d1cee481619
[ "Apache-2.0" ]
4
2021-04-02T08:48:38.000Z
2021-07-01T06:59:02.000Z
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "ngraph/op/util/elementwise_args.hpp" #include "ngraph/op/util/binary_elementwise_arithmetic.hpp" using namespace ngraph; std::tuple<element::Type, PartialShape> ngraph::op::util::validate_and_infer_elementwise_args( Node* node, const op::AutoBroadcastSpec& autob) { NGRAPH_CHECK(node != nullptr, "nGraph node is empty! Cannot validate eltwise arguments."); element::Type element_type = node->get_input_element_type(0); PartialShape pshape = node->get_input_partial_shape(0); if (node->get_input_size() > 1) { for (size_t i = 1; i < node->get_input_size(); ++i) { NODE_VALIDATION_CHECK(node, element::Type::merge(element_type, element_type, node->get_input_element_type(i)), "Argument element types are inconsistent."); if (autob.m_type == op::AutoBroadcastType::NONE) { NODE_VALIDATION_CHECK(node, PartialShape::merge_into(pshape, node->get_input_partial_shape(i)), "Argument shapes are inconsistent."); } else if (autob.m_type == op::AutoBroadcastType::NUMPY || autob.m_type == op::AutoBroadcastType::PDPD) { NODE_VALIDATION_CHECK( node, PartialShape::broadcast_merge_into(pshape, node->get_input_partial_shape(i), autob), "Argument shapes are inconsistent."); } else { NODE_VALIDATION_CHECK(node, false, "Unsupported auto broadcast specification"); } } } return std::make_tuple(element_type, pshape); }
43.146341
117
0.613906
uikilin100
fece7dfe948feccd2380bf75b01c1e871ceee992
457
cpp
C++
codes/Leetcode/leetcode042.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/Leetcode/leetcode042.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/Leetcode/leetcode042.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
class Solution { public: int trap(vector<int>& height) { int n = height.size(), h; int* l = new int[n]; int* r = new int[n]; h = 0; for (int i = 0; i < n; i++) { h = max(h, height[i]); l[i] = h; } h = 0; for (int i = n-1; i >= 0; i--) { h = max(h, height[i]); r[i] = h; } int ans = 0; for (int i = 0; i < n; i++) ans += min(l[i], r[i]) - height[i]; delete l; delete r; return ans; } };
15.758621
39
0.422319
JeraKrs
feceae921eb58a8d86f0e86ac939e421b90804b1
3,818
cpp
C++
src/reader/lmpBaseReader.cpp
martintb/correlate
b0be89af4e57cc5fe96ec3a5c7a9bb84430d2433
[ "MIT" ]
3
2018-02-26T19:53:46.000Z
2021-05-05T10:06:52.000Z
src/reader/lmpBaseReader.cpp
martintb/correlate
b0be89af4e57cc5fe96ec3a5c7a9bb84430d2433
[ "MIT" ]
1
2018-07-03T14:38:15.000Z
2018-07-09T19:06:01.000Z
src/reader/lmpBaseReader.cpp
martintb/correlate
b0be89af4e57cc5fe96ec3a5c7a9bb84430d2433
[ "MIT" ]
1
2019-03-28T03:02:07.000Z
2019-03-28T03:02:07.000Z
#include <iostream> #include <fstream> #include <sstream> #include <regex> #include <map> #include "lmpBaseReader.hpp" #include "debug.hpp" using namespace std; void lmpBaseReader::goToSection(ifstream &f, string section_title) { f.seekg(0,ios::beg); //return to top of file regex sectionRE(section_title+".*",regex::extended); string line; while (getline(f,line)) { if (regex_search(line,sectionRE)) { getline(f,line);// blank line break; } } } map<string,float> lmpBaseReader::readHeader(ifstream &f) { f.seekg(0,ios::beg); //return to top of file if (not f.good()) { cout << "file.bad(): " << boolalpha << f.bad() << endl; cout << "file.fail(): " << boolalpha << f.fail() << endl; cout << "file.eof(): " << boolalpha << f.eof() << endl; LOC(); exit(EXIT_FAILURE); } regex natoms("(.*) atoms",regex::extended); regex nbonds("(.*) bonds",regex::extended); regex nangles("(.*) angles",regex::extended); regex ndih("(.*) dihedrals",regex::extended); regex nimp("(.*) impropers",regex::extended); regex ntypes("(.*) atom types",regex::extended); regex nbtypes("(.*) bond types",regex::extended); regex natypes("(.*) angle types",regex::extended); regex ndtypes("(.*) dihedral types",regex::extended); regex nitypes("(.*) improper types",regex::extended); regex boxx("(.*) (.*) xlo xhi",regex::extended); regex boxy("(.*) (.*) ylo yhi",regex::extended); regex boxz("(.*) (.*) zlo zhi",regex::extended); map<string,float> headerData; smatch m; string line; float temp1,temp2; int lineNo=0; int maxHeaderSize = 50; while (getline(f,line)) { if (regex_search(line,m,boxz)) { istringstream (m[1].str()) >> temp1; istringstream (m[2].str()) >> temp2; headerData["zlo"] = temp1; headerData["zhi"] = temp2; headerData["lz"] = temp2 - temp1; } else if (regex_search(line,m,boxy)) { istringstream (m[1].str()) >> temp1; istringstream (m[2].str()) >> temp2; headerData["ylo"] = temp1; headerData["yhi"] = temp2; headerData["ly"] = temp2 - temp1; } else if (regex_search(line,m,boxx)) { istringstream (m[1].str()) >> temp1; istringstream (m[2].str()) >> temp2; headerData["xlo"] = temp1; headerData["xhi"] = temp2; headerData["lx"] = temp2 - temp1; } else if (regex_search(line,m,nitypes)) { istringstream (m[1].str()) >> temp1; headerData["nimpropertypes"] = temp1; } else if (regex_search(line,m,ndtypes)) { istringstream (m[1].str()) >> temp1; headerData["ndihedraltypes"] = temp1; } else if (regex_search(line,m,natypes)) { istringstream (m[1].str()) >> temp1; headerData["nangletypes"] = temp1; } else if (regex_search(line,m,nbtypes)) { istringstream (m[1].str()) >> temp1; headerData["nbondtypes"] = temp1; } else if (regex_search(line,m,ntypes)) { istringstream (m[1].str()) >> temp1; headerData["natomtypes"] = temp1; } else if (regex_search(line,m,nimp)) { istringstream (m[1].str()) >> temp1; headerData["nimpropers"] = temp1; } else if (regex_search(line,m,ndih)) { istringstream (m[1].str()) >> temp1; headerData["ndihedrals"] = temp1; } else if (regex_search(line,m,nangles)) { istringstream (m[1].str()) >> temp1; headerData["nangles"] = temp1; } else if (regex_search(line,m,nbonds)) { istringstream (m[1].str()) >> temp1; headerData["nbonds"] = temp1; } else if (regex_search(line,m,natoms)) { istringstream (m[1].str()) >> temp1; headerData["natoms"] = temp1; } if (lineNo>maxHeaderSize) break; lineNo++; } // nead to clear eofbit and failbit in case the end of the file was reached f.clear(); return headerData; }
32.913793
77
0.602672
martintb
fed1da7b625370f1b36f72716fcc0a6b1e1b0d18
2,914
cpp
C++
3rdparty/aws-sdk-cpp-master/aws-cpp-sdk-cognito-sync/source/model/IdentityUsage.cpp
prateek-s/mesos
4b81147797e4d9a45e0b2f5e5634d4a214dbc4e8
[ "Apache-2.0" ]
2
2019-02-08T21:29:57.000Z
2021-07-27T06:59:19.000Z
3rdparty/aws-sdk-cpp-master/aws-cpp-sdk-cognito-sync/source/model/IdentityUsage.cpp
prateek-s/mesos
4b81147797e4d9a45e0b2f5e5634d4a214dbc4e8
[ "Apache-2.0" ]
null
null
null
3rdparty/aws-sdk-cpp-master/aws-cpp-sdk-cognito-sync/source/model/IdentityUsage.cpp
prateek-s/mesos
4b81147797e4d9a45e0b2f5e5634d4a214dbc4e8
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/cognito-sync/model/IdentityUsage.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace CognitoSync { namespace Model { IdentityUsage::IdentityUsage() : m_identityIdHasBeenSet(false), m_identityPoolIdHasBeenSet(false), m_lastModifiedDateHasBeenSet(false), m_datasetCount(0), m_datasetCountHasBeenSet(false), m_dataStorage(0), m_dataStorageHasBeenSet(false) { } IdentityUsage::IdentityUsage(const JsonValue& jsonValue) : m_identityIdHasBeenSet(false), m_identityPoolIdHasBeenSet(false), m_lastModifiedDateHasBeenSet(false), m_datasetCount(0), m_datasetCountHasBeenSet(false), m_dataStorage(0), m_dataStorageHasBeenSet(false) { *this = jsonValue; } IdentityUsage& IdentityUsage::operator =(const JsonValue& jsonValue) { if(jsonValue.ValueExists("IdentityId")) { m_identityId = jsonValue.GetString("IdentityId"); m_identityIdHasBeenSet = true; } if(jsonValue.ValueExists("IdentityPoolId")) { m_identityPoolId = jsonValue.GetString("IdentityPoolId"); m_identityPoolIdHasBeenSet = true; } if(jsonValue.ValueExists("LastModifiedDate")) { m_lastModifiedDate = jsonValue.GetDouble("LastModifiedDate"); m_lastModifiedDateHasBeenSet = true; } if(jsonValue.ValueExists("DatasetCount")) { m_datasetCount = jsonValue.GetInteger("DatasetCount"); m_datasetCountHasBeenSet = true; } if(jsonValue.ValueExists("DataStorage")) { m_dataStorage = jsonValue.GetInt64("DataStorage"); m_dataStorageHasBeenSet = true; } return *this; } JsonValue IdentityUsage::Jsonize() const { JsonValue payload; if(m_identityIdHasBeenSet) { payload.WithString("IdentityId", m_identityId); } if(m_identityPoolIdHasBeenSet) { payload.WithString("IdentityPoolId", m_identityPoolId); } if(m_lastModifiedDateHasBeenSet) { payload.WithDouble("LastModifiedDate", m_lastModifiedDate.SecondsWithMSPrecision()); } if(m_datasetCountHasBeenSet) { payload.WithInteger("DatasetCount", m_datasetCount); } if(m_dataStorageHasBeenSet) { payload.WithInt64("DataStorage", m_dataStorage); } return payload; } } // namespace Model } // namespace CognitoSync } // namespace Aws
22.244275
87
0.738161
prateek-s
fed2e18c581f5ef3fbc79fdf68267f20e7aeac5a
266
cpp
C++
CPP/HelloCpp2/chapter_20/Inheritance.cpp
hrntsm/study-language
922578a5321d70c26b935e6052f400125e15649c
[ "MIT" ]
1
2022-02-06T10:50:42.000Z
2022-02-06T10:50:42.000Z
CPP/HelloCpp2/chapter_20/Inheritance.cpp
hrntsm/study-language
922578a5321d70c26b935e6052f400125e15649c
[ "MIT" ]
null
null
null
CPP/HelloCpp2/chapter_20/Inheritance.cpp
hrntsm/study-language
922578a5321d70c26b935e6052f400125e15649c
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; class Kitty{ public: void nyan(){cout << "Kitty on your lap\n";} }; class Di_Gi_Gharat : public Kitty{ public: void nyo(){cout << "Di Gi Gharat\n";} } obj; int main(){ obj.nyo(); obj.nyan(); return 0; }
14
47
0.605263
hrntsm
fed4f5b06c27558a69fdca3ceb704c397be48b40
461
cpp
C++
clang/test/clang-rename/CtorInitializer.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
3,102
2015-01-04T02:28:35.000Z
2022-03-30T12:53:41.000Z
clang/test/clang-rename/CtorInitializer.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
clang/test/clang-rename/CtorInitializer.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
1,868
2015-01-03T04:27:11.000Z
2022-03-25T13:37:35.000Z
class Baz {}; class Qux { Baz Foo; /* Test 1 */ // CHECK: Baz Bar; public: Qux(); }; Qux::Qux() : Foo() /* Test 2 */ {} // CHECK: Qux::Qux() : Bar() /* Test 2 */ {} // Test 1. // RUN: clang-rename -offset=33 -new-name=Bar %s -- | sed 's,//.*,,' | FileCheck %s // Test 2. // RUN: clang-rename -offset=118 -new-name=Bar %s -- | sed 's,//.*,,' | FileCheck %s // To find offsets after modifying the file, use: // grep -Ubo 'Foo.*' <file>
25.611111
84
0.511931
medismailben
fed70d1cf353bd7a228d932f5d4b500fbf8fefc1
4,824
cpp
C++
tests/filesystem.cpp
slater1/irrlicht
2860e828879b6acf9e39604cb4bcce0873c8b2d9
[ "IJG" ]
440
2015-01-04T16:01:46.000Z
2022-03-25T08:31:38.000Z
tests/filesystem.cpp
slater1/irrlicht
2860e828879b6acf9e39604cb4bcce0873c8b2d9
[ "IJG" ]
2
2020-01-28T08:36:22.000Z
2020-02-01T10:52:04.000Z
tests/filesystem.cpp
slater1/irrlicht
2860e828879b6acf9e39604cb4bcce0873c8b2d9
[ "IJG" ]
189
2015-01-06T10:39:46.000Z
2022-02-21T07:20:59.000Z
#include "testUtils.h" using namespace irr; using namespace core; using namespace io; static bool testgetAbsoluteFilename(io::IFileSystem* fs) { bool result=true; io::path apath = fs->getAbsolutePath("media"); io::path cwd = fs->getWorkingDirectory(); if (apath!=(cwd+"/media")) { logTestString("getAbsolutePath failed on existing dir %s\n", apath.c_str()); result = false; } apath = fs->getAbsolutePath("../media/"); core::deletePathFromPath(cwd, 1); if (apath!=(cwd+"media/")) { logTestString("getAbsolutePath failed on dir with postfix / %s\n", apath.c_str()); result = false; } apath = fs->getAbsolutePath ("../nothere.txt"); // file does not exist if (apath!=(cwd+"nothere.txt")) { logTestString("getAbsolutePath failed on non-existing file %s\n", apath.c_str()); result = false; } return result; } static bool testFlattenFilename(io::IFileSystem* fs) { bool result=true; io::path tmpString="../tmp"; io::path refString="../tmp/"; fs->flattenFilename(tmpString); if (tmpString != refString) { logTestString("flattening destroys path.\n%s!=%s\n", tmpString.c_str(),refString.c_str()); result = false; } tmpString="tmp/tmp/../"; refString="tmp/"; fs->flattenFilename(tmpString); if (tmpString != refString) { logTestString("flattening destroys path.\n%s!=%s\n", tmpString.c_str(),refString.c_str()); result = false; } tmpString="tmp/tmp/.."; fs->flattenFilename(tmpString); if (tmpString != refString) { logTestString("flattening destroys path.\n%s!=%s\n", tmpString.c_str(),refString.c_str()); result = false; } tmpString="tmp/next/../third"; refString="tmp/third/"; fs->flattenFilename(tmpString); if (tmpString != refString) { logTestString("flattening destroys path.\n%s!=%s\n", tmpString.c_str(),refString.c_str()); result = false; } tmpString="this/tmp/next/../../my/fourth"; refString="this/my/fourth/"; fs->flattenFilename(tmpString); if (tmpString != refString) { logTestString("flattening destroys path.\n%s!=%s\n", tmpString.c_str(),refString.c_str()); result = false; } tmpString="this/is/../../../a/fifth/test/"; refString="../a/fifth/test/"; fs->flattenFilename(tmpString); if (tmpString != refString) { logTestString("flattening destroys path.\n%s!=%s\n", tmpString.c_str(),refString.c_str()); result = false; } tmpString="this/../is/../../a/sixth/test/"; refString="../a/sixth/test/"; fs->flattenFilename(tmpString); if (tmpString != refString) { logTestString("flattening destroys path.\n%s!=%s\n", tmpString.c_str(),refString.c_str()); result = false; } return result; } static bool testgetRelativeFilename(io::IFileSystem* fs) { bool result=true; io::path apath = fs->getAbsolutePath("media"); io::path cwd = fs->getWorkingDirectory(); if (fs->getRelativeFilename(apath, cwd) != "media") { logTestString("getRelativePath failed on %s\n", apath.c_str()); result = false; } apath = fs->getAbsolutePath("../media/"); if (fs->getRelativeFilename(apath, cwd) != "../media/") { logTestString("getRelativePath failed on %s\n", apath.c_str()); result = false; } return result; } bool filesystem(void) { IrrlichtDevice * device = irr::createDevice(video::EDT_NULL, dimension2d<u32>(1, 1)); assert_log(device); if(!device) return false; io::IFileSystem * fs = device->getFileSystem (); if ( !fs ) return false; bool result = true; io::path workingDir = device->getFileSystem()->getWorkingDirectory(); io::path empty; if ( fs->existFile(empty) ) { logTestString("Empty filename should not exist.\n"); result = false; } io::path newWd = workingDir + "/media"; bool changed = device->getFileSystem()->changeWorkingDirectoryTo(newWd); assert_log(changed); if ( fs->existFile(empty) ) { logTestString("Empty filename should not exist even in another workingdirectory.\n"); result = false; } // The working directory must be restored for the other tests to work. changed = device->getFileSystem()->changeWorkingDirectoryTo(workingDir.c_str()); assert_log(changed); // adding a folder archive which just should not really change anything device->getFileSystem()->addFileArchive( "./" ); if ( fs->existFile(empty) ) { logTestString("Empty filename should not exist in folder file archive.\n"); result = false; } // remove it again to not affect other tests device->getFileSystem()->removeFileArchive( device->getFileSystem()->getFileArchiveCount() ); result &= testFlattenFilename(fs); result &= testgetAbsoluteFilename(fs); result &= testgetRelativeFilename(fs); device->closeDevice(); device->run(); device->drop(); return result; }
26.217391
95
0.662521
slater1
fed74b345d578e1fc34f463c52ac3009e8ba218a
795
cpp
C++
Source/Engine/Filesystem/Resource.cpp
kukiric/SomeGame
8c058d82a93bc3f276bbb3ec57a3978ae57de82c
[ "MIT" ]
null
null
null
Source/Engine/Filesystem/Resource.cpp
kukiric/SomeGame
8c058d82a93bc3f276bbb3ec57a3978ae57de82c
[ "MIT" ]
null
null
null
Source/Engine/Filesystem/Resource.cpp
kukiric/SomeGame
8c058d82a93bc3f276bbb3ec57a3978ae57de82c
[ "MIT" ]
null
null
null
#include "Resource.h" #define PREFETCH_SIZE 128*1024 using namespace Filesystem; HashMap<String, Resource*> Resource::pool; const Resource& Resource::request(StringRef path) { Resource* resource; auto iter = pool.find(path); if(iter != pool.end()) { resource = iter->second; } else { resource = new Resource(path); pool.emplace(path, resource); } return *resource; } void Resource::drop(StringRef path) { auto it = pool.find(path); if (it != pool.end()) { delete it->second; pool.erase(it); } } Resource::Resource(const File& file) : file(file) { } Resource::~Resource() { } void Resource::compile() { } const File& Resource::getFile() const { return file; }
17.282609
50
0.584906
kukiric
fedc655e92b03be6eac142eada22e92d0ab3cfb5
435
cpp
C++
Contests/World-CodeSprint-12/The-Salesman.cpp
Justin-Teng/HackerRank
bb501715d4fb0322ccffa70b75c4d6df1463a334
[ "MIT" ]
null
null
null
Contests/World-CodeSprint-12/The-Salesman.cpp
Justin-Teng/HackerRank
bb501715d4fb0322ccffa70b75c4d6df1463a334
[ "MIT" ]
null
null
null
Contests/World-CodeSprint-12/The-Salesman.cpp
Justin-Teng/HackerRank
bb501715d4fb0322ccffa70b75c4d6df1463a334
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; for(int a0 = 0; a0 < t; a0++){ int n; cin >> n; int min = 1001, max = 0; for(int x_i = 0; x_i < n; x_i++){ int x; cin >> x; if (x < min) min = x; if (x > max) max = x; } cout << max-min << endl; } return 0; }
18.125
41
0.344828
Justin-Teng
fedcd3881f438a16f148f7d91dd7b60b69efbffa
469
cc
C++
app_tuner/linux/flutter/generated_plugin_registrant.cc
MacherelR/instrument_tuner
fbdc3e2ad1dc825b1f74d7ee9c903212cd14f4a6
[ "MIT" ]
null
null
null
app_tuner/linux/flutter/generated_plugin_registrant.cc
MacherelR/instrument_tuner
fbdc3e2ad1dc825b1f74d7ee9c903212cd14f4a6
[ "MIT" ]
null
null
null
app_tuner/linux/flutter/generated_plugin_registrant.cc
MacherelR/instrument_tuner
fbdc3e2ad1dc825b1f74d7ee9c903212cd14f4a6
[ "MIT" ]
null
null
null
// // Generated file. Do not edit. // // clang-format off #include "generated_plugin_registrant.h" #include <flutter_audio_capture/flutter_audio_capture_plugin.h> void fl_register_plugins(FlPluginRegistry* registry) { g_autoptr(FlPluginRegistrar) flutter_audio_capture_registrar = fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterAudioCapturePlugin"); flutter_audio_capture_plugin_register_with_registrar(flutter_audio_capture_registrar); }
29.3125
89
0.833689
MacherelR
fedd46a1830bdd54ec65b94837445e4e0735175e
14,651
cc
C++
src/lepton/socket_serve.cc
suryatmodulus/lepton
2a08b777579819677e37af133f1565765d08db04
[ "Apache-2.0" ]
5,342
2016-07-14T04:40:58.000Z
2022-03-31T07:26:06.000Z
src/lepton/socket_serve.cc
suryatmodulus/lepton
2a08b777579819677e37af133f1565765d08db04
[ "Apache-2.0" ]
126
2016-07-14T18:30:39.000Z
2022-03-30T00:46:44.000Z
src/lepton/socket_serve.cc
suryatmodulus/lepton
2a08b777579819677e37af133f1565765d08db04
[ "Apache-2.0" ]
451
2016-07-14T14:27:08.000Z
2022-03-08T22:57:18.000Z
#ifndef _WIN32 #include <sys/types.h> #include <signal.h> #include <sys/socket.h> #include <sys/un.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/file.h> #include <fcntl.h> #include <unistd.h> #include <algorithm> #include <netinet/in.h> #include <sys/time.h> #if defined(__APPLE__) || defined(BSD) #include <sys/wait.h> #else #include <sys/signalfd.h> #include <wait.h> #endif #include <poll.h> #include <errno.h> #include "../io/Reader.hh" #include "socket_serve.hh" #include "../../vp8/util/memory.hh" #include <set> static char hex_nibble(uint8_t val) { if (val < 10) return val + '0'; return val - 10 + 'a'; } static const char last_prefix[] = "/tmp/"; static const char last_postfix[]=".uport"; static const char zlast_postfix[]=".z0"; static char socket_name[sizeof((struct sockaddr_un*)0)->sun_path] = {}; static char zsocket_name[sizeof((struct sockaddr_un*)0)->sun_path] = {}; static const char lock_ext[]=".lock"; bool random_name = false; static char socket_lock[sizeof((struct sockaddr_un*)0)->sun_path + sizeof(lock_ext)]; int lock_file = -1; bool is_parent_process = true; static void name_socket(FILE * dev_random) { random_name = true; char random_data[16] = {0}; auto retval = fread(random_data, 1, sizeof(random_data), dev_random); (void)retval;// dev random should yield reasonable results memcpy(socket_name, last_prefix, strlen(last_prefix)); memcpy(zsocket_name, last_prefix, strlen(last_prefix)); size_t offset = strlen(last_prefix); for (size_t i = 0; i < sizeof(random_data); ++i) { always_assert(offset + 3 + sizeof(last_postfix) < sizeof(socket_name)); always_assert(offset + 3 + sizeof(zlast_postfix) < sizeof(zsocket_name)); uint8_t hex = random_data[i]; socket_name[offset] = hex_nibble(hex>> 4); socket_name[offset + 1] = hex_nibble(hex & 0xf); zsocket_name[offset] = hex_nibble(hex>> 4); zsocket_name[offset + 1] = hex_nibble(hex & 0xf); offset += 2; if (i == 4 || i == 6 || i == 8 || i == 14) { socket_name[offset] = '-'; zsocket_name[offset] = '-'; ++offset; } } always_assert(offset + sizeof(last_postfix) < sizeof(socket_name)); always_assert(offset + sizeof(zlast_postfix) < sizeof(zsocket_name)); always_assert(offset + sizeof(lock_ext) < sizeof(socket_lock)); memcpy(socket_name+offset, last_postfix, sizeof(last_postfix)); memcpy(zsocket_name+offset, zlast_postfix, sizeof(zlast_postfix)); memcpy(socket_lock, socket_name, offset); memcpy(socket_lock+offset, lock_ext, sizeof(lock_ext)); } static void cleanup_socket(int) { if (is_parent_process) { unlink(socket_name); unlink(zsocket_name); if (socket_lock[0] && random_name) { unlink(socket_lock); } exit(0); return; } custom_exit(ExitCode::SUCCESS); } static void nop(int){} pid_t accept_new_connection(int active_connection, const SocketServeWorkFunction& work, uint32_t global_max_length, int lock_fd, bool force_zlib) { pid_t serve_file = fork(); if (serve_file == 0) { is_parent_process = false; while (close(1) < 0 && errno == EINTR){ // close stdout } if (lock_fd >= 0) { while (close(lock_fd) < 0 && errno == EINTR){ // close socket lock so future servers may reacquire the lock } } IOUtil::FileReader reader(active_connection, global_max_length, true); IOUtil::FileWriter writer(active_connection, false, true); work(&reader, &writer, global_max_length, force_zlib); custom_exit(ExitCode::SUCCESS); } else { while (close(active_connection) < 0 && errno == EINTR){ // close the Unix Domain Socket } } return serve_file; } int should_wait_bitmask(size_t children_size, uint32_t max_children) { if (max_children && children_size >= max_children) { return 0; } return WNOHANG; } int make_sigchld_fd() { int fd = -1; #if !(defined(__APPLE__) || defined(BSD)) sigset_t sigset; int err = sigemptyset(&sigset); always_assert(err == 0); err = sigaddset(&sigset, SIGCHLD); always_assert(err == 0); // the signalfd will only receive SIG_BLOCK'd signals err = sigprocmask(SIG_BLOCK, &sigset, NULL); always_assert(err == 0); fd = signalfd(-1, &sigset, 0); always_assert(fd != -1); #endif return fd; } void write_num_children(size_t num_children) { if (num_children > 0xff) { num_children = 0xff; } // lets just keep a byte of state about the number of children if (lock_file != -1) { int err; while((err = lseek(lock_file, 0, SEEK_SET)) < 0 && errno == EINTR){ } uint8_t num_children_byte = (uint8_t)num_children; while((err = write(lock_file, &num_children_byte, sizeof(num_children_byte))) < 0 && errno == EINTR) { } } } void serving_loop(int unix_domain_socket_server, int unix_domain_socket_server_zlib, int tcp_socket_server, int tcp_socket_server_zlib, const SocketServeWorkFunction& work, uint32_t global_max_length, uint32_t max_children, bool do_cleanup_socket, int lock_fd) { int sigchild_fd = make_sigchld_fd(); int num_fds = 0; struct pollfd fds[5]; if (sigchild_fd != -1) { fds[0].fd = sigchild_fd; fds[0].events = POLLIN | POLLERR | POLLHUP; num_fds+= 1; } if (unix_domain_socket_server_zlib != -1) { fds[num_fds].fd = unix_domain_socket_server_zlib; ++num_fds; } if (tcp_socket_server_zlib != -1) { fds[num_fds].fd = tcp_socket_server_zlib; ++num_fds; } if (unix_domain_socket_server != -1) { fds[num_fds].fd = unix_domain_socket_server; ++num_fds; } if (tcp_socket_server != -1) { fds[num_fds].fd = tcp_socket_server; ++num_fds; } for (int i = 0; i < num_fds; ++i) { int err; while ((err = fcntl(fds[i].fd, F_SETFL, O_NONBLOCK)) == -1 && errno == EINTR) {} always_assert(err == 0); fds[i].events = POLLIN; } std::set<pid_t> children; int status; while(true) { write_num_children(children.size()); for (pid_t term_pid = 0; (term_pid = waitpid(-1, &status, should_wait_bitmask(children.size(), max_children))) > 0;) { std::set<pid_t>::iterator where = children.find(term_pid); if (where != children.end()) { children.erase(where); } else { fprintf(stderr, "Pid %d not found as child of this\n", term_pid); assert(false && "pid msut be in child\n"); } if (WIFEXITED(status)) { fprintf(stderr, "Child %d exited with code %d\n", term_pid, WEXITSTATUS(status)); } else if (WIFSIGNALED(status)) { fprintf(stderr, "Child %d exited with signal %d\n", term_pid, WTERMSIG(status)); } else { fprintf(stderr, "Child %d exited with another cause: %d\n", term_pid, status); } fflush(stderr); write_num_children(children.size()); } int ret = poll(fds, num_fds, sigchild_fd == -1 ? 60 : -1); // need a timeout (30 ms) in case a SIGCHLD was missed between the waitpid and the poll if (ret == 0) { // no events ready, just timed out, check for missed SIGCHLD continue; } if (ret < 0 && errno == EINTR) { continue; } for (int i = 0; i < num_fds; ++i) { if (fds[i].revents & POLLIN) { fds[i].revents = 0; if (fds[i].fd == sigchild_fd) { #if !(defined(__APPLE__) || defined(BSD)) struct signalfd_siginfo info; ssize_t ignore = read(fds[i].fd, &info, sizeof(info)); (void)ignore; #endif continue; // we can't receive on this } struct sockaddr_un client; socklen_t len = sizeof(client); int active_connection = accept(fds[i].fd, (sockaddr*)&client, &len); if (active_connection >= 0) { int flags; while ((flags = fcntl(active_connection, F_GETFL, 0)) == -1 && errno == EINTR){} always_assert(flags != -1); if (flags & O_NONBLOCK) { flags &= ~O_NONBLOCK; // inheritance of nonblocking flag not specified across systems while (fcntl(active_connection, F_SETFL, flags) == -1 && errno == EINTR){} } children.insert(accept_new_connection(active_connection, work, global_max_length, lock_fd, fds[i].fd == unix_domain_socket_server_zlib || fds[i].fd == tcp_socket_server_zlib)); } else { if (errno != EINTR && errno != EWOULDBLOCK && errno != EAGAIN) { fprintf(stderr, "Error accepting connection: %s", strerror(errno)); cleanup_socket(0); } } } } } } int setup_tcp_socket(int port, int listen_backlog) { int socket_fd = socket(AF_INET, SOCK_STREAM, 0); always_assert(socket_fd > 0); struct sockaddr_in serv_addr; memset(&serv_addr, 0, sizeof(struct sockaddr_in)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(port); int optval = 1; setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); if (bind(socket_fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) { custom_exit(ExitCode::COULD_NOT_BIND_PORT); } int err = listen(socket_fd, listen_backlog); always_assert(err == 0); return socket_fd; } int setup_socket(const char *file_name, int listen_backlog) { int err; int socket_fd = socket(PF_UNIX, SOCK_STREAM, 0); always_assert(socket_fd > 0); struct sockaddr_un address; memset(&address, 0, sizeof(struct sockaddr_un)); address.sun_family = AF_UNIX; memcpy(address.sun_path, file_name, std::min(strlen(file_name), sizeof(address.sun_path))); err = bind(socket_fd, (struct sockaddr*)&address, sizeof(address)); always_assert(err == 0); err = listen(socket_fd, listen_backlog); int ret = chmod(file_name, 0666); (void)ret; always_assert(err == 0); return socket_fd; } void socket_serve(const SocketServeWorkFunction &work_fn, uint32_t global_max_length, const ServiceInfo &service_info) { bool do_cleanup_socket = true; int lock_fd = -1; if (service_info.uds != NULL) { do_cleanup_socket = false; size_t len = strlen(service_info.uds); if (len + 1 < sizeof(socket_name)) { memcpy(socket_name, service_info.uds, len); socket_name[len] = '\0'; } else { fprintf(stderr, "Path too long for %s\n", service_info.uds); always_assert(false && "input file name too long\n"); } memcpy(socket_lock, socket_name, sizeof(socket_name)); memcpy(zsocket_name, socket_name, sizeof(socket_name)); memcpy(socket_lock + strlen(socket_lock), lock_ext, sizeof(lock_ext)); memcpy(zsocket_name + strlen(zsocket_name), zlast_postfix, sizeof(zlast_postfix)); do { lock_file = open(socket_lock, O_RDWR|O_CREAT|O_TRUNC, S_IRUSR | S_IRGRP | S_IROTH | S_IWUSR); } while(lock_file < 0 && errno == EINTR); if (lock_file >= 0) { lock_fd = lock_file; int err = 0; do { err = ::flock(lock_file, LOCK_EX|LOCK_NB); } while(err < 0 && errno == EINTR); if (err == 0) { do { err = remove(socket_name); }while (err < 0 && errno == EINTR); do { err = remove(zsocket_name); }while (err < 0 && errno == EINTR); signal(SIGINT, &cleanup_socket); // if we have the lock we can clean it up signal(SIGQUIT, &cleanup_socket); signal(SIGTERM, &cleanup_socket); do_cleanup_socket = true; } } } else { FILE* dev_random = fopen("/dev/urandom", "rb"); name_socket(dev_random); int fret = fclose(dev_random); always_assert(fret == 0); do { lock_file = open(socket_lock, O_RDWR|O_CREAT|O_TRUNC, S_IRUSR | S_IRGRP | S_IROTH | S_IWUSR); } while(lock_file < 0 && errno == EINTR); signal(SIGINT, &cleanup_socket); signal(SIGQUIT, &cleanup_socket); signal(SIGTERM, &cleanup_socket); } signal(SIGCHLD, &nop); // listen int socket_fd = -1; int zsocket_fd = -1; int socket_tcp = -1; int zsocket_tcp = -1; if (service_info.listen_uds) { socket_fd = setup_socket(socket_name, service_info.listen_backlog); zsocket_fd = setup_socket(zsocket_name, service_info.listen_backlog); } if (service_info.listen_tcp) { socket_tcp = setup_tcp_socket(service_info.port, service_info.listen_backlog); zsocket_tcp = setup_tcp_socket(service_info.zlib_port, service_info.listen_backlog); } fprintf(stdout, "%s\n", socket_name); fflush(stdout); serving_loop(socket_fd, zsocket_fd, socket_tcp, zsocket_tcp, work_fn, global_max_length, service_info.max_children, do_cleanup_socket, lock_fd); } #endif
37.470588
110
0.561327
suryatmodulus
fedebf0ab22b554961dd5cb652cf512052355879
711
cpp
C++
userspace/libs/libwidget/elements/IconElement.cpp
GeGuNa/skift_oss2
8e674f5bfa24c009df5c683fefa02daf14d9a40f
[ "MIT" ]
1,724
2019-03-02T18:31:16.000Z
2022-03-31T18:35:42.000Z
userspace/libs/libwidget/elements/IconElement.cpp
GeGuNa/skift_oss2
8e674f5bfa24c009df5c683fefa02daf14d9a40f
[ "MIT" ]
280
2019-03-06T09:36:49.000Z
2022-03-30T18:56:14.000Z
userspace/libs/libwidget/elements/IconElement.cpp
GeGuNa/skift_oss2
8e674f5bfa24c009df5c683fefa02daf14d9a40f
[ "MIT" ]
263
2019-03-14T15:04:12.000Z
2022-03-26T19:28:36.000Z
#include <libgraphic/Painter.h> #include <libwidget/elements/IconElement.h> namespace Widget { IconElement::IconElement(Ref<Graphic::Icon> icon, Graphic::IconSize size) : _icon{icon}, _icon_size{size} { } void IconElement::paint(Graphic::Painter &painter, const Math::Recti &) { if (!_icon) { return; } Math::Recti destination = _icon->bound(_icon_size).centered_within(bound()); painter.blit( *_icon, _icon_size, destination, color(THEME_FOREGROUND)); } Math::Vec2i IconElement::size() { if (_icon) { return _icon->bound(_icon_size).size(); } else { return bound().size(); } } } // namespace Widget
17.341463
80
0.61744
GeGuNa
fedf12c9d473daa518dbd0923c2c3f699e2c19c2
550
cpp
C++
ADCore/ADApp/pluginTests/AttrPlotPluginWrapper.cpp
jerryjiahaha/areaDetector
a0ebc33a94a3cccffb4c9489d4b8e8ff33bf4231
[ "MIT" ]
20
2015-01-07T09:02:42.000Z
2021-07-27T14:35:19.000Z
ADCore/ADApp/pluginTests/AttrPlotPluginWrapper.cpp
jerryjiahaha/areaDetector
a0ebc33a94a3cccffb4c9489d4b8e8ff33bf4231
[ "MIT" ]
400
2015-01-06T14:44:30.000Z
2022-02-07T17:45:32.000Z
ADCore/ADApp/pluginTests/AttrPlotPluginWrapper.cpp
jerryjiahaha/areaDetector
a0ebc33a94a3cccffb4c9489d4b8e8ff33bf4231
[ "MIT" ]
72
2015-01-23T23:23:02.000Z
2022-02-07T15:14:35.000Z
/* * AttrPlotPluginWrapper.cpp * * Created on: 28 Feb 2017 * Author: Blaz Kranjc */ #include "AttrPlotPluginWrapper.h" AttrPlotPluginWrapper::AttrPlotPluginWrapper(const std::string& port, int max_attributes, int cache_size, int max_selected, const std::string& in_port, int in_addr) : NDPluginAttrPlot(port.c_str(), max_attributes, cache_size, max_selected, in_port.c_str(), in_addr, 1000, 0, 0, 0), AsynPortClientContainer(port) { } AttrPlotPluginWrapper::~AttrPlotPluginWrapper () { cleanup(); }
22.916667
77
0.701818
jerryjiahaha
fee033277ccbc9e01ae726b0ec3494cbe2814547
32,954
hpp
C++
heart/test/TestCardiacSimulation.hpp
SoftMatterMechanics/ApicalStressFibers
17d343c09a246a50f9e3a3cbfc399ca6bef353ce
[ "Apache-2.0", "BSD-3-Clause" ]
1
2020-09-10T16:12:13.000Z
2020-09-10T16:12:13.000Z
heart/test/TestCardiacSimulation.hpp
SoftMatterMechanics/ApicalStressFibers
17d343c09a246a50f9e3a3cbfc399ca6bef353ce
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
heart/test/TestCardiacSimulation.hpp
SoftMatterMechanics/ApicalStressFibers
17d343c09a246a50f9e3a3cbfc399ca6bef353ce
[ "Apache-2.0", "BSD-3-Clause" ]
1
2020-09-10T16:12:21.000Z
2020-09-10T16:12:21.000Z
/* Copyright (c) 2005-2020, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Oxford 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. */ #ifndef TESTCARDIACSIMULATION_HPP_ #define TESTCARDIACSIMULATION_HPP_ #include <cxxtest/TestSuite.h> #include <string> #include <vector> #include <sstream> #include "AbstractCardiacProblem.hpp" #include "MonodomainProblem.hpp" #include "CardiacSimulation.hpp" #include "OutputFileHandler.hpp" #include "CompareHdf5ResultsFiles.hpp" #include "FileFinder.hpp" #include "PetscTools.hpp" #include "HeartEventHandler.hpp" #include "AbstractCardiacCellInterface.hpp" #include "DistributedVectorFactory.hpp" #include "Warnings.hpp" #include "CellMLToSharedLibraryConverter.hpp" #include "PetscSetupAndFinalize.hpp" class TestCardiacSimulation : public CxxTest::TestSuite { void setUp() { HeartEventHandler::Reset(); } // // void CreateOptionsFile(const OutputFileHandler& rHandler, // const std::string& rModelName, // const std::vector<std::string>& rArgs, // const std::string& rExtraXml="") // { // if (PetscTools::AmMaster()) // { // out_stream p_optfile = rHandler.OpenOutputFile(rModelName + "-conf.xml"); // (*p_optfile) << "<?xml version='1.0'?>" << std::endl // << "<pycml_config>" << std::endl // << "<command_line_args>" << std::endl; // for (unsigned i=0; i<rArgs.size(); i++) // { // (*p_optfile) << "<arg>" << rArgs[i] << "</arg>" << std::endl; // } // (*p_optfile) << "</command_line_args>" << std::endl // << rExtraXml // << "</pycml_config>" << std::endl; // p_optfile->close(); // } // PetscTools::Barrier("CreateOptionsFile"); // } public: void TestMono1dSmall() { if (PetscTools::GetNumProcs() > 3u) { TS_TRACE("This test is not suitable for more than 3 processes."); return; } // Fox2002BackwardEuler cell model CardiacSimulation simulation("heart/test/data/xml/monodomain1d_small.xml", true); TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "mono_1d_small", false, "SaveMono1D", "SimulationResults", true, 1e-6)); /* If the above fails, and you are happy the new results are correct, uncomment the following line, * run the test, and then do cp /tmp/$USER/testoutput/SaveMono1D/SimulationResults.h5 heart/test/data/cardiac_simulations/mono_1d_small.h5 */ //assert(0); CardiacSimulation simulation2("heart/test/data/xml/monodomain1d_resume.xml", true); } void TestMono2dSmall() { if (PetscTools::GetNumProcs() > 3u) { TS_TRACE("This test is not suitable for more than 3 processes."); return; } //Clear any warnings from previous tests Warnings::QuietDestroy(); { CardiacSimulation simulation("heart/test/data/xml/monodomain2d_small.xml", false, true); boost::shared_ptr<AbstractUntemplatedCardiacProblem> p_problem = simulation.GetSavedProblem(); TS_ASSERT(p_problem); MonodomainProblem<2,2>* p_mono_problem = dynamic_cast<MonodomainProblem<2,2>*>(p_problem.get()); TS_ASSERT(p_mono_problem != NULL); DistributedVectorFactory* p_vector_factory = p_mono_problem->rGetMesh().GetDistributedVectorFactory(); for (unsigned node_global_index = p_vector_factory->GetLow(); node_global_index < p_vector_factory->GetHigh(); node_global_index++) { AbstractCardiacCellInterface* p_cell = p_mono_problem->GetTissue()->GetCardiacCell(node_global_index); TS_ASSERT_DELTA(p_cell->GetParameter("membrane_fast_sodium_current_conductance"), 23 * 0.99937539038101175, 1e-6); TS_ASSERT_DELTA(p_cell->GetParameter("membrane_rapid_delayed_rectifier_potassium_current_conductance"), 0.282/3.0, 1e-6); } if (p_vector_factory->GetLocalOwnership() > 0) { TS_ASSERT_EQUALS(Warnings::Instance()->GetNumWarnings(), p_vector_factory->GetLocalOwnership()); std::stringstream msg; msg << "Cannot apply drug to cell at node " << p_vector_factory->GetLow() << " as it has no parameter named 'not_a_current_conductance'."; TS_ASSERT_EQUALS(Warnings::Instance()->GetNextWarningMessage(), msg.str()); } else { //There is now a warning on the top processes about the fact that no cells were assigned TS_ASSERT_EQUALS(Warnings::Instance()->GetNumWarnings(), 1u); std::stringstream msg; msg << "No cells were assigned to process "<< PetscTools::GetMyRank(); msg << " in AbstractCardiacTissue constructor. Advice: Make total number of processors no greater than number of nodes in the mesh"; TS_ASSERT_EQUALS(Warnings::Instance()->GetNextWarningMessage(), msg.str()); } } //Check that the post-processed file is there and remove it FileFinder pseudoecg("SaveMono2D/output/PseudoEcgFromElectrodeAt_0.05_0.05_0.dat", RelativeTo::ChasteTestOutput); if (PetscTools::AmMaster()) { TS_ASSERT(pseudoecg.Exists()); // Only master tests. This prevents master from removing file before other processes have seen it pseudoecg.Remove(); TS_ASSERT(pseudoecg.Exists() == false); } //Check that archive which has just been produced can be read CardiacSimulation simulation2("heart/test/data/xml/monodomain2d_resume.xml"); //Check that the post-processed file is back after the simulation has been restarted TS_ASSERT(pseudoecg.Exists()); // (Should check that it's bigger than the one we deleted) Warnings::QuietDestroy(); } /* Do the same as before but ask for post-processing after the simulation has been run and checkpointed. */ void TestMono2dSmallAddPostprocessingOnResume() { if (PetscTools::GetNumProcs() > 3u) { TS_TRACE("This test is not suitable for more than 3 processes."); return; } //Clear any warnings from previous tests Warnings::QuietDestroy(); { CardiacSimulation simulation("heart/test/data/xml/monodomain2d_small2.xml", false, true); } //Check that the post-processed file is not produced in the original simulation FileFinder pseudoecg("SaveMono2D2/output/PseudoEcgFromElectrodeAt_0.05_0.05_0.dat", RelativeTo::ChasteTestOutput); TS_ASSERT(pseudoecg.Exists() == false); //Check that archive which has just been produced can be read CardiacSimulation simulation2("heart/test/data/xml/monodomain2d_resume2.xml"); //Check that the post-processed file is present after the simulation has been restarted TS_ASSERT(pseudoecg.Exists()); // (Should check that it's bigger than the one we deleted) Warnings::QuietDestroy(); } void TestMono3dSmall() { if (PetscTools::GetNumProcs() > 3u) { TS_TRACE("This test is not suitable for more than 3 processes."); return; } CardiacSimulation simulation("heart/test/data/xml/monodomain3d_small.xml"); //Check that archive which has just been produced can be read CardiacSimulation simulation2("heart/test/data/xml/monodomain3d_resume.xml"); } void TestMono1dSodiumBlockBySettingNamedParameter() { CardiacSimulation simulation("heart/test/data/xml/monodomain1d_sodium_block.xml"); TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "mono_1d_sodium_block", false, "Mono1dSodiumBlock", "SimulationResults", true, 2.5e-3)); // Test exception TS_ASSERT_THROWS_THIS(CardiacSimulation bad_param("heart/test/data/xml/bad_cell_parameter.xml"), "No parameter named 'missing-parameter'."); } void TestMonoStimUsingEllipsoids() { if (PetscTools::GetNumProcs() > 3u) { TS_TRACE("This test is not suitable for more than 3 processes."); return; } // Fox2002BackwardEuler cell model CardiacSimulation simulation("heart/test/data/xml/monodomain1d_stim_using_ellipsoid.xml", true); TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "monodomain1d_stim_using_ellipsoid", false, "Mono1DStimUsingEllipsoid", "SimulationResults", true, 1e-6)); } void TestBi1dSmall() { if (PetscTools::GetNumProcs() > 3u) { TS_TRACE("This test is not suitable for more than 3 processes."); return; } { CardiacSimulation simulation("heart/test/data/xml/bidomain1d_small.xml"); } { CardiacSimulation simulation2("heart/test/data/xml/bidomain1d_resume.xml"); } { // The default resume file specifies a simulation duration of zero. // In reality the user should edit the file to specify something sensible... FileFinder resume_xml("SaveBi1D_checkpoints/0.1ms/ResumeParameters.xml", RelativeTo::ChasteTestOutput); TS_ASSERT_THROWS_THIS(CardiacSimulation simulation(resume_xml.GetAbsolutePath()), "The simulation duration must be positive, not -0.1"); } } void TestBi2dSmall() { if (PetscTools::GetNumProcs() > 3u) { TS_TRACE("This test is not suitable for more than 3 processes."); return; } CardiacSimulation simulation("heart/test/data/xml/bidomain2d_small.xml"); //Check that archive which has just been produced can be read CardiacSimulation simulation2("heart/test/data/xml/bidomain2d_resume.xml"); } void TestBi3dSmall() { if (PetscTools::GetNumProcs() > 3u) { TS_TRACE("This test is not suitable for more than 3 processes."); return; } CardiacSimulation simulation("heart/test/data/xml/bidomain3d_small.xml"); //Check that archive which has just been produced can be read CardiacSimulation simulation2("heart/test/data/xml/bidomain3d_resume.xml"); } void TestBiWithBath1dSmall() { { CardiacSimulation simulation("heart/test/data/xml/bidomain_with_bath1d_small.xml"); } { CardiacSimulation simulation2("heart/test/data/xml/bidomain_with_bath1d_resume.xml"); } { // The default resume file specifies a simulation duration of zero. // In reality the user should edit the file to specify something sensible... FileFinder resume_xml("SaveBiWithBath1D_checkpoints/0.1ms/ResumeParameters.xml", RelativeTo::ChasteTestOutput); TS_ASSERT_THROWS_THIS(CardiacSimulation simulation(resume_xml.GetAbsolutePath()), "The simulation duration must be positive, not -0.1"); } } void TestBiWithBath2dSmall() { CardiacSimulation simulation("heart/test/data/xml/bidomain_with_bath2d_small.xml"); CardiacSimulation simulation2("heart/test/data/xml/bidomain_with_bath2d_resume.xml"); } void TestBiWithBath3dSmall() { CardiacSimulation simulation("heart/test/data/xml/bidomain_with_bath3d_small.xml"); CardiacSimulation simulation2("heart/test/data/xml/bidomain_with_bath3d_resume.xml"); } void TestBiWith2dHeterogeneousConductivities() { CardiacSimulation simulation("heart/test/data/xml/bidomain2d_heterogeneous.xml", true); } void TestCardiacSimulationBasicBidomainShort() { // Fox2002BackwardEuler cell model // run a bidomain_with_bath simulation CardiacSimulation simulation("heart/test/data/xml/base_bidomain_short.xml"); // compare the files, using the CompareFilesViaHdf5DataReader() method TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "base_bidomain_short_results", false, "BaseBidomainShort", "SimulationResults", true, 1e-6)); } void TestCardiacSimulationBasicMonodomainShort() { // Fox2002BackwardEuler cell model // run a bidomain simulation CardiacSimulation simulation("heart/test/data/xml/base_monodomain_short.xml"); // compare the files, using the CompareFilesViaHdf5DataReader() method TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "base_monodomain_short_results", false, "BaseMonodomainShort", "SimulationResults", true, 1e-6)); } void TestCardiacSimulationPostprocessMonodomain() { // Fox2002BackwardEuler cell model // run a bidomain simulation CardiacSimulation simulation("heart/test/data/xml/postprocess_monodomain_short.xml"); std::string foldername = "PostprocessMonodomainShort"; // compare the files, using the CompareFilesViaHdf5DataReader() method TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "postprocess_monodomain_short_results", false, foldername, "SimulationResults", true, 1e-6)); { // look for the existence of post-processing files TS_ASSERT(FileFinder(foldername + "/output/Apd_90_minus_30_Map.dat", RelativeTo::ChasteTestOutput).Exists()); TS_ASSERT(FileFinder(foldername + "/output/ConductionVelocityFromNode10.dat", RelativeTo::ChasteTestOutput).Exists()); TS_ASSERT(FileFinder(foldername + "/output/ConductionVelocityFromNode20.dat", RelativeTo::ChasteTestOutput).Exists()); TS_ASSERT(FileFinder(foldername + "/output/MaxUpstrokeVelocityMap_minus_30.dat", RelativeTo::ChasteTestOutput).Exists()); TS_ASSERT(FileFinder(foldername + "/output/UpstrokeTimeMap_minus_30.dat", RelativeTo::ChasteTestOutput).Exists()); TS_ASSERT(FileFinder(foldername + "/output/PseudoEcgFromElectrodeAt_0.05_0.05_0.dat", RelativeTo::ChasteTestOutput).Exists()); } } void TestCardiacSimulationArchiveBidomain() { // Fox2002BackwardEuler cell model // run a bidomain simulation CardiacSimulation simulation("heart/test/data/xml/save_bidomain_short.xml"); std::string foldername = "SaveBidomainShort"; // compare the files, using the CompareFilesViaHdf5DataReader() method TS_ASSERT(CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "save_bidomain_short_results", false, foldername, "SimulationResults", true, 1e-5)); FileFinder file(foldername + "_checkpoints/0.2ms/" + foldername + "_0.2ms/archive.arch.0", RelativeTo::ChasteTestOutput); TS_ASSERT(file.Exists()); /* If you want to update the .h5 results for this test for any reason, you need to stop the following test adding to them. * So uncomment the assert(), run the test, and then do: cp /tmp/chaste/testoutput/SaveBidomainShort/SimulationResults.h5 heart/test/data/cardiac_simulations/save_bidomain_short_results.h5 */ //assert(0); } // requires TestCardiacSimulationArchiveBidomain() to have been run void TestCardiacSimulationResumeBidomain() { // run a bidomain simulation HeartConfig::Instance()->SetSpaceDimension(1); FileFinder resume_xml("heart/test/data/xml/resume_bidomain_short.xml", RelativeTo::ChasteSourceRoot); OutputFileHandler checkpoint_dir("SaveBidomainShort_checkpoints/0.2ms", false); FileFinder copied_xml = checkpoint_dir.CopyFileTo(resume_xml); CardiacSimulation simulation(copied_xml.GetAbsolutePath()); std::string foldername = "SaveBidomainShort"; // compare the files, using the CompareFilesViaHdf5DataReader() method TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "resume_bidomain_short_results", false, foldername, "SimulationResults", true, 1e-5)); //assert(0); } void TestCardiacSimulationArchiveMonodomain() { // Fox2002BackwardEuler cell model // run a bidomain simulation CardiacSimulation simulation("heart/test/data/xml/save_monodomain_short.xml"); std::string foldername = "SaveMonodomainShort"; // compare the files, using the CompareFilesViaHdf5DataReader() method TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "save_monodomain_short_results", false, foldername, "SimulationResults", true, 1e-6)); FileFinder file(foldername + "_checkpoints/0.2ms/" + foldername + "_0.2ms/archive.arch.0", RelativeTo::ChasteTestOutput); TS_ASSERT(file.Exists()); /* If you want to update the .h5 results for this test for any reason, you need to stop the following test adding to them. * So uncomment the assert(), run the test, and then do: cp /tmp/chaste/testoutput/SaveMonodomainShort/SimulationResults.h5 heart/test/data/cardiac_simulations/save_monodomain_short_results.h5 */ //assert(0); } // requires TestCardiacSimulationArchiveMonodomain() to have been run void TestCardiacSimulationResumeMonodomain() { // run a monodomain simulation HeartConfig::Instance()->SetSpaceDimension(1); CardiacSimulation simulation("heart/test/data/xml/resume_monodomain_short.xml"); std::string foldername = "SaveMonodomainShort"; // compare the files, using the CompareFilesViaHdf5DataReader() method TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "resume_monodomain_short_results", false, foldername, "SimulationResults", true, 1e-6)); } void TestCardiacSimulationArchiveDynamic() { #ifdef CHASTE_CAN_CHECKPOINT_DLLS // run a monodomain simulation { CardiacSimulation simulation("heart/test/data/xml/save_monodomain_dynamic.xml"); } std::string foldername = "SaveMonodomainDynamic"; // compare the files, using the CompareFilesViaHdf5DataReader() method TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "save_monodomain_dynamic", false, foldername, "SimulationResults", true)); FileFinder file(foldername + "_checkpoints/0.2ms/" + foldername + "_0.2ms/archive.arch.0", RelativeTo::ChasteTestOutput); TS_ASSERT(file.Exists()); /* If you want to update the .h5 results for this test for any reason, you need to stop the following lines adding to them. * So uncomment the assert(), run the test, and then do: cp /tmp/chaste/testoutput/SaveMonodomainDynamic/SimulationResults.h5 heart/test/data/cardiac_simulations/save_monodomain_dynamic.h5 */ //assert(0); //resume the simulation { CardiacSimulation simulation("heart/test/data/xml/resume_monodomain_dynamic.xml"); } // compare the files, using the CompareFilesViaHdf5DataReader() method TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "resume_monodomain_dynamic", false, foldername, "SimulationResults", true)); #endif // CHASTE_CAN_CHECKPOINT_DLLS } /** * Note: from Chaste release 3.1 onward we no longer support Boost 1.33. * The earliest version of Boost supported is 1.34 * Run TestCardiacSimulationArchiveBidomain on 4 processors to create the archive for this test, * and copy it to the repository using: * scons build=GccOpt_hostconfig,boost=1-34_4 test_suite=heart/test/TestCardiacSimulation.hpp cp -r /tmp/$USER/testoutput/SaveBidomainShort_checkpoints/0.2ms heart/test/data/checkpoint_migration_via_xml/ rm -f heart/test/data/checkpoint_migration_via_xml/0.2ms/SaveBidomainShort/progress_status.txt rm -f heart/test/data/checkpoint_migration_via_xml/0.2ms/SaveBidomainShort_0.2ms/mesh.ncl rm -f heart/test/data/checkpoint_migration_via_xml/0.2ms/SaveBidomainShort_0.2ms/ChasteParameters_?_?xsd rm -rf heart/test/data/checkpoint_migration_via_xml/0.2ms/SaveBidomainShort/output */ void TestCardiacSimulationResumeMigration() { // We can only load simulations from CHASTE_TEST_OUTPUT, so copy the archives there std::string source_directory = "heart/test/data/checkpoint_migration_via_xml/0.2ms/"; std::string folder_1 = "SaveBidomainShort"; std::string folder_2 = "SaveBidomainShort_0.2ms"; FileFinder to_directory1(OutputFileHandler::GetChasteTestOutputDirectory() + folder_1, RelativeTo::Absolute); FileFinder to_directory2(OutputFileHandler::GetChasteTestOutputDirectory() + folder_2, RelativeTo::Absolute); FileFinder from_directory1(source_directory + folder_1, RelativeTo::ChasteSourceRoot); FileFinder from_directory2(source_directory + folder_2, RelativeTo::ChasteSourceRoot); TRY_IF_MASTER( to_directory1.Remove(); to_directory2.Remove(); TS_ASSERT_EQUALS(to_directory1.Exists(), false); TS_ASSERT_EQUALS(to_directory2.Exists(), false); from_directory1.CopyTo(to_directory1); from_directory2.CopyTo(to_directory2); ); // Resume CardiacSimulation simulation("heart/test/data/xml/resume_migration.xml"); // Compare results TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "resume_bidomain_short_results", false, "SaveBidomainShort", "SimulationResults", true, 1e-5)); } void runSimulation(const std::string& rParametersFileName) { CardiacSimulation simulation(rParametersFileName); } void checkParameter(AbstractCardiacCellInterface* pCell, unsigned globalIndex) { // Check one of the parameters has been set in the central region TS_ASSERT_EQUALS(pCell->GetNumberOfParameters(), 3u); double expected_value; if (globalIndex <= 4 || globalIndex >= 16) { expected_value = 23.0; } else { expected_value = 0.0; } TS_ASSERT_DELTA(pCell->GetParameter("membrane_fast_sodium_current_conductance"), expected_value, 1e-12); TS_ASSERT_DELTA(pCell->GetParameter("membrane_rapid_delayed_rectifier_potassium_current_conductance"), 0.282, 1e-12); TS_ASSERT_DELTA(pCell->GetParameter("membrane_L_type_calcium_current_conductance"), 0.09, 1e-12); // Check stimulus has been replaced. It started as 0-1ms at x<=0.02, and should now be 600-601ms at x<=0.02 if (globalIndex < 3) { TS_ASSERT_EQUALS(pCell->GetStimulus(0.0), 0.0); TS_ASSERT_EQUALS(pCell->GetStimulus(0.5), 0.0); TS_ASSERT_EQUALS(pCell->GetStimulus(1.0), 0.0); TS_ASSERT_EQUALS(pCell->GetStimulus(599.9), 0.0); TS_ASSERT_EQUALS(pCell->GetStimulus(600.0), -200000.0); TS_ASSERT_EQUALS(pCell->GetStimulus(600.5), -200000.0); TS_ASSERT_EQUALS(pCell->GetStimulus(601.0), -200000.0); TS_ASSERT_EQUALS(pCell->GetStimulus(601.1), 0.0); } else { // Always zero... TS_ASSERT_EQUALS(pCell->GetStimulus(0.0), 0.0); TS_ASSERT_EQUALS(pCell->GetStimulus(0.5), 0.0); TS_ASSERT_EQUALS(pCell->GetStimulus(600.5), 0.0); TS_ASSERT_EQUALS(pCell->GetStimulus(10.0), 0.0); } } void doTestResumeChangingSettings(const std::string& rParametersFileName) { std::string foldername = "SaveMonodomainWithParameter"; // Save runSimulation(rParametersFileName); // Just check that the checkpoint exists FileFinder archive(foldername + "_checkpoints/1ms/" + foldername + "_1ms/archive.arch.0", RelativeTo::ChasteTestOutput); TS_ASSERT(archive.Exists()); { // Load CardiacSimulation simulation("heart/test/data/xml/resume_monodomain_changing_parameter.xml", false, true); boost::shared_ptr<AbstractUntemplatedCardiacProblem> p_problem = simulation.GetSavedProblem(); TS_ASSERT(p_problem); MonodomainProblem<1,1>* p_mono_problem = dynamic_cast<MonodomainProblem<1,1>*>(p_problem.get()); TS_ASSERT(p_mono_problem != NULL); DistributedVectorFactory* p_vector_factory = p_mono_problem->rGetMesh().GetDistributedVectorFactory(); for (unsigned node_global_index = p_vector_factory->GetLow(); node_global_index < p_vector_factory->GetHigh(); node_global_index++) { AbstractCardiacCellInterface* p_cell = p_mono_problem->GetTissue()->GetCardiacCell(node_global_index); checkParameter(p_cell, node_global_index); } // compare the files, using the CompareFilesViaHdf5DataReader() method TS_ASSERT( CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "resume_monodomain_changing_parameter_results", false, foldername, "SimulationResults", true)); } } void TestResumeChangingSettings() { doTestResumeChangingSettings("heart/test/data/xml/save_monodomain_with_parameter.xml"); doTestResumeChangingSettings("heart/test/data/xml/save_monodomain_with_parameter_append.xml"); } void TestCardiacSimulationPatchwork() { OutputFileHandler handler("DynamicallyLoadedModel"); FileFinder cellml_file("heart/dynamic/luo_rudy_1991_dyn.cellml", RelativeTo::ChasteSourceRoot); handler.CopyFileTo(cellml_file); CardiacSimulation simulation("heart/test/data/xml/base_monodomain_patchwork.xml"); std::string foldername = "Patchwork"; // compare the files, using the CompareFilesViaHdf5DataReader() method TS_ASSERT(CompareFilesViaHdf5DataReader("heart/test/data/cardiac_simulations", "patchwork_results", false, foldername, "SimulationResults", true, 1e-5)); } void TestCardiacSimulationKirsten() { if (PetscTools::GetNumProcs() > 2u) { // There are only 2 layers of nodes in this simulation -- z length is equal to space step. TS_TRACE("This test is not suitable for more than 2 processes."); return; } CardiacSimulation simulation("heart/test/data/xml/base_monodomain_tt06_region.xml"); std::string foldername = "Kirsten"; TS_ASSERT(CompareFilesViaHdf5DataReaderGlobalNorm("heart/test/data/cardiac_simulations", "Kirsten", false, foldername, "SimulationResults", true, 5e-4)); // lower tolerance as comparing with non-backward-euler results. } void TestTransmuralCellularheterogeneities() { CardiacSimulation simulation("heart/test/data/xml/ChasteParametersCellHeterogeneities.xml"); std::string foldername = "ChasteResults_heterogeneities"; TS_ASSERT( CompareFilesViaHdf5DataReaderGlobalNorm("heart/test/data/cardiac_simulations", "transmural_heterogeneities_results", false, foldername, "SimulationResults", true)); } void TestElectrodes() { CardiacSimulation simulation("heart/test/data/xml/bidomain_with_bath2d_electrodes.xml"); std::string foldername = "ChasteResults_electrodes"; TS_ASSERT( CompareFilesViaHdf5DataReaderGlobalNorm("heart/test/data/cardiac_simulations", "electrodes_results", false, foldername, "SimulationResults", true, 1e-4)); } void TestExceptions() { TS_ASSERT_THROWS_THIS(CardiacSimulation simulation("heart/test/data/xml/monodomain8d_small.xml"), "Space dimension not supported: should be 1, 2 or 3"); TS_ASSERT_THROWS_THIS(CardiacSimulation simulation("heart/test/data/xml/bidomain8d_small.xml"), "Space dimension not supported: should be 1, 2 or 3"); #ifndef __APPLE__ ///\todo Passing error is fatal on Mac OSX TS_ASSERT_THROWS_THIS(CardiacSimulation simulation("heart/test/data/xml/base_monodomain_frankenstein.xml"), "XML parsing error in configuration file: heart/test/data/xml/base_monodomain_frankenstein.xml"); #endif TS_ASSERT_THROWS_THIS(CardiacSimulation simulation("no file"), "Missing file parsing configuration file: no file"); TS_ASSERT_THROWS_THIS(CardiacSimulation simulation(""), "No XML file name given"); #ifdef __APPLE__ FileFinder model("file_does_not_exist.dylib", RelativeTo::ChasteSourceRoot); #else FileFinder model("file_does_not_exist.so", RelativeTo::ChasteSourceRoot); #endif TS_ASSERT_THROWS_THIS(CardiacSimulation simulation("heart/test/data/xml/missing_dynamic_model.xml"), "Dynamically loadable cell model '" + model.GetAbsolutePath() + "' does not exist."); TS_ASSERT_THROWS_THIS(CardiacSimulation simulation("heart/test/data/xml/bidomain_with_bath2d_noelectrodes.xml"), "Simulation needs a stimulus (either <Stimuli> or <Electrodes>)."); #ifndef CHASTE_CAN_CHECKPOINT_DLLS TS_ASSERT_THROWS_THIS(CardiacSimulation simulation("heart/test/data/xml/dynamic_checkpoint.xml"), "Checkpointing is not compatible with dynamically loaded cell models on Mac OS X."); #endif } void TestDynamicallyLoadingCvodeCell() { // Coverage - using native CVODE cells should no longer throw #ifdef CHASTE_CVODE OutputFileHandler handler_cvode("DynamicallyLoadedModelCvode"); FileFinder cellml_file("heart/dynamic/luo_rudy_1991_dyn.cellml", RelativeTo::ChasteSourceRoot); handler_cvode.CopyFileTo(cellml_file); std::vector<std::string> args; args.push_back("--cvode"); CellMLToSharedLibraryConverter::CreateOptionsFile(handler_cvode, "luo_rudy_1991_dyn", args); CardiacSimulation simulation("heart/test/data/xml/dynamic_cvode_model.xml"); #else std::cout << "CVODE is not enabled.\n"; #endif } }; #endif /*TESTCARDIACSIMULATION_HPP_*/
48.108029
169
0.669479
SoftMatterMechanics
fee2f30bccc18b0e403ce3dce3eb3b9a88114ff5
1,029
cpp
C++
clang/test/CodeGen/tbaa-cast.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
3,102
2015-01-04T02:28:35.000Z
2022-03-30T12:53:41.000Z
clang/test/CodeGen/tbaa-cast.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
clang/test/CodeGen/tbaa-cast.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
1,868
2015-01-03T04:27:11.000Z
2022-03-25T13:37:35.000Z
// RUN: %clang_cc1 -triple x86_64-linux -O1 -disable-llvm-passes %s \ // RUN: -emit-llvm -o - | FileCheck %s -check-prefixes=CHECK,OLD-PATH // RUN: %clang_cc1 -triple x86_64-linux -O1 -disable-llvm-passes %s \ // RUN: -emit-llvm -new-struct-path-tbaa -o - | FileCheck %s -check-prefixes=CHECK,NEW-PATH // // Check that we generate correct TBAA information for lvalues constructed // with use of casts. struct V { unsigned n; }; struct S { char bytes[4]; }; void foo(S *p) { // CHECK-LABEL: _Z3fooP1S // CHECK: store i32 5, {{.*}}, !tbaa [[TAG_V_n:!.*]] ((V*)p->bytes)->n = 5; } // OLD-PATH-DAG: [[TAG_V_n]] = !{[[TYPE_V:!.*]], [[TYPE_int:!.*]], i64 0} // OLD-PATH-DAG: [[TYPE_V]] = !{!"_ZTS1V", !{{.*}}, i64 0} // OLD-PATH-DAG: [[TYPE_int]] = !{!"int", !{{.*}}, i64 0} // NEW-PATH-DAG: [[TAG_V_n]] = !{[[TYPE_V:!.*]], [[TYPE_int:!.*]], i64 0, i64 4} // NEW-PATH-DAG: [[TYPE_V]] = !{[[TYPE_char:!.*]], i64 4, !"_ZTS1V", [[TYPE_int]], i64 0, i64 4} // NEW-PATH-DAG: [[TYPE_int]] = !{[[TYPE_char]], i64 4, !"int"}
35.482759
96
0.573372
medismailben
fee6ce1f00857a3cced7cf02122fb14b29372f03
2,015
hh
C++
include/log4cpp/threading/DummyThreads.hh
soulcure/im_server
b5e3d5b54f930fdc3d29b60287582ede5940e91d
[ "Apache-2.0" ]
1
2021-07-12T12:06:27.000Z
2021-07-12T12:06:27.000Z
include/log4cpp/threading/DummyThreads.hh
soulcure/im_server
b5e3d5b54f930fdc3d29b60287582ede5940e91d
[ "Apache-2.0" ]
null
null
null
include/log4cpp/threading/DummyThreads.hh
soulcure/im_server
b5e3d5b54f930fdc3d29b60287582ede5940e91d
[ "Apache-2.0" ]
null
null
null
/* * DummyThreads.hh * * Copyright 2002, LifeLine Networks BV (www.lifeline.nl). All rights reserved. * Copyright 2002, Bastiaan Bakker. All rights reserved. * * See the COPYING file for the terms of usage and distribution. */ #ifndef _LOG4CPP_THREADING_DUMMYTHREADS_HH #define _LOG4CPP_THREADING_DUMMYTHREADS_HH #include <log4cpp/Portability.hh> #include <stdio.h> #include <string> namespace log4cpp { namespace threading { std::string getThreadId(); /** * Return an identifier for the current thread. What these * identifiers look like is completely up to the underlying * thread library. OmniThreads returns the POSIX thread Id. * * @param buffer Character buffer of at least 16 in size * @return buffer */ char* getThreadId(char* buffer); /** Dummy type 'int' for Mutex. Yes, this adds a bit of overhead in the for of extra memory, but unfortunately 'void' is illegal. **/ typedef int Mutex; /** Dummy type 'int' defintion of ScopedLock; **/ typedef int ScopedLock; template<typename T> class ThreadLocalDataHolder { public: typedef T data_type; inline ThreadLocalDataHolder() {}; inline ~ThreadLocalDataHolder() { if (_data) delete _data; }; inline T* get() const { return _data; }; inline T* operator->() const { return get(); }; inline T& operator*() const { return *get(); }; inline T* release() { T* result = _data; _data = NULL; return result; }; inline void reset(T* p = NULL) { if (_data) delete _data; _data = p; }; private: T* _data; }; } } #endif
26.168831
79
0.53201
soulcure
fee78a7881cf52687f363f7ee477a91dfd3abe8b
2,341
cc
C++
src/mqtt_api.cc
blumamir/wavplayeralsa
b219cf5d3377ac78ea82674d57ace3306cc39660
[ "MIT" ]
3
2020-11-30T12:11:05.000Z
2020-12-14T12:28:17.000Z
src/mqtt_api.cc
BlumAmir/wavplayeralsa
b219cf5d3377ac78ea82674d57ace3306cc39660
[ "MIT" ]
1
2020-12-01T07:34:12.000Z
2020-12-09T11:05:06.000Z
src/mqtt_api.cc
blumamir/wavplayeralsa
b219cf5d3377ac78ea82674d57ace3306cc39660
[ "MIT" ]
null
null
null
#include "mqtt_api.h" #include <iostream> #include <functional> #include <boost/date_time/time_duration.hpp> namespace wavplayeralsa { MqttApi::MqttApi(boost::asio::io_service &io_service) : io_service_(io_service), reconnect_timer_(io_service) { } void MqttApi::Initialize(std::shared_ptr<spdlog::logger> logger, const std::string &mqtt_host, uint16_t mqtt_port) { // set class members logger_ = logger; const char *mqtt_client_id = "wavplayeralsa"; logger_->info("creating mqtt connection to host {} on port {} with client id {}", mqtt_host, mqtt_port, mqtt_client_id); logger_->info("will publish current song updates on topic {}", CURRENT_SONG_TOPIC); mqtt_client_ = mqtt::make_sync_client(io_service_, mqtt_host, mqtt_port); mqtt_client_->set_client_id(mqtt_client_id); mqtt_client_->set_clean_session(true); mqtt_client_->set_error_handler(std::bind(&MqttApi::OnError, this, std::placeholders::_1)); mqtt_client_->set_close_handler(std::bind(&MqttApi::OnClose, this)); mqtt_client_->set_connack_handler(std::bind(&MqttApi::OnConnAck, this, std::placeholders::_1, std::placeholders::_2)); mqtt_client_->connect(); } void MqttApi::ReportCurrentSong(const std::string &json_str) { last_status_msg_ = json_str; PublishCurrentSong(); } void MqttApi::OnError(boost::system::error_code ec) { logger_->error("client disconnected from mqtt server. will try reconnect in {} ms", RECONNECT_WAIT_MS); reconnect_timer_.expires_from_now(boost::posix_time::milliseconds(RECONNECT_WAIT_MS)); reconnect_timer_.async_wait( [this] (boost::system::error_code ec) { if (ec != boost::asio::error::operation_aborted) { mqtt_client_->connect(); } }); } void MqttApi::OnClose() { logger_->error("client connection to mqtt server is closed"); } bool MqttApi::OnConnAck(bool session_present, std::uint8_t connack_return_code) { logger_->info("connack handler called. clean session: {}. coonack rerturn code: {}", session_present, mqtt::connect_return_code_to_str(connack_return_code)); PublishCurrentSong(); return true; } void MqttApi::PublishCurrentSong() { if(!this->mqtt_client_) return; if(last_status_msg_.empty()) return; this->mqtt_client_->publish_exactly_once(CURRENT_SONG_TOPIC, last_status_msg_, true); } }
29.632911
159
0.73302
blumamir
fee791c47707c37ae072012c2fb133f7444bcee8
24,867
cc
C++
src/core/prometheus.cc
liubangchen/seastar
5bf108406ae79a5f30383bf8e498dd9d4b51d1a5
[ "Apache-2.0" ]
1
2017-12-18T20:23:33.000Z
2017-12-18T20:23:33.000Z
src/core/prometheus.cc
liubangchen/seastar
5bf108406ae79a5f30383bf8e498dd9d4b51d1a5
[ "Apache-2.0" ]
2
2021-01-29T13:04:16.000Z
2021-05-12T13:25:34.000Z
src/core/prometheus.cc
liubangchen/seastar
5bf108406ae79a5f30383bf8e498dd9d4b51d1a5
[ "Apache-2.0" ]
3
2020-12-05T15:31:49.000Z
2020-12-12T16:11:20.000Z
/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. You may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (C) 2016 ScyllaDB */ #include <seastar/core/prometheus.hh> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/io/zero_copy_stream_impl_lite.h> #include "proto/metrics2.pb.h" #include <sstream> #include <seastar/core/scollectd_api.hh> #include "core/scollectd-impl.hh" #include <seastar/core/metrics_api.hh> #include <seastar/http/function_handlers.hh> #include <boost/algorithm/string/replace.hpp> #include <boost/range/algorithm_ext/erase.hpp> #include <boost/algorithm/string.hpp> #include <boost/range/algorithm.hpp> #include <boost/range/combine.hpp> #include <seastar/core/thread.hh> #include <seastar/core/loop.hh> namespace seastar { extern seastar::logger seastar_logger; namespace prometheus { namespace pm = io::prometheus::client; namespace mi = metrics::impl; /** * Taken from an answer in stackoverflow: * http://stackoverflow.com/questions/2340730/are-there-c-equivalents-for-the-protocol-buffers-delimited-i-o-functions-in-ja */ static bool write_delimited_to(const google::protobuf::MessageLite& message, google::protobuf::io::ZeroCopyOutputStream* rawOutput) { google::protobuf::io::CodedOutputStream output(rawOutput); #if GOOGLE_PROTOBUF_VERSION >= 3004000 const size_t size = message.ByteSizeLong(); output.WriteVarint64(size); #else const int size = message.ByteSize(); output.WriteVarint32(size); #endif uint8_t* buffer = output.GetDirectBufferForNBytesAndAdvance(size); if (buffer != nullptr) { message.SerializeWithCachedSizesToArray(buffer); } else { message.SerializeWithCachedSizes(&output); if (output.HadError()) { return false; } } return true; } static pm::Metric* add_label(pm::Metric* mt, const metrics::impl::metric_id & id, const config& ctx) { mt->mutable_label()->Reserve(id.labels().size() + 1); if (ctx.label) { auto label = mt->add_label(); label->set_name(ctx.label->key()); label->set_value(ctx.label->value()); } for (auto &&i : id.labels()) { auto label = mt->add_label(); label->set_name(i.first); label->set_value(i.second); } return mt; } static void fill_metric(pm::MetricFamily& mf, const metrics::impl::metric_value& c, const metrics::impl::metric_id & id, const config& ctx) { switch (c.type()) { case scollectd::data_type::DERIVE: add_label(mf.add_metric(), id, ctx)->mutable_counter()->set_value(c.i()); mf.set_type(pm::MetricType::COUNTER); break; case scollectd::data_type::GAUGE: add_label(mf.add_metric(), id, ctx)->mutable_gauge()->set_value(c.d()); mf.set_type(pm::MetricType::GAUGE); break; case scollectd::data_type::HISTOGRAM: { auto h = c.get_histogram(); auto mh = add_label(mf.add_metric(), id,ctx)->mutable_histogram(); mh->set_sample_count(h.sample_count); mh->set_sample_sum(h.sample_sum); for (auto b : h.buckets) { auto bc = mh->add_bucket(); bc->set_cumulative_count(b.count); bc->set_upper_bound(b.upper_bound); } mf.set_type(pm::MetricType::HISTOGRAM); break; } default: add_label(mf.add_metric(), id, ctx)->mutable_counter()->set_value(c.ui()); mf.set_type(pm::MetricType::COUNTER); break; } } static std::string to_str(seastar::metrics::impl::data_type dt) { switch (dt) { case seastar::metrics::impl::data_type::GAUGE: return "gauge"; case seastar::metrics::impl::data_type::COUNTER: return "counter"; case seastar::metrics::impl::data_type::HISTOGRAM: return "histogram"; case seastar::metrics::impl::data_type::DERIVE: // Prometheus server does not respect derive parameters // So we report them as counter return "counter"; default: break; } return "untyped"; } static std::string to_str(const seastar::metrics::impl::metric_value& v) { switch (v.type()) { case seastar::metrics::impl::data_type::GAUGE: return std::to_string(v.d()); case seastar::metrics::impl::data_type::COUNTER: return std::to_string(v.i()); case seastar::metrics::impl::data_type::DERIVE: return std::to_string(v.ui()); default: break; } return ""; // we should never get here but it makes the compiler happy } static void add_name(std::ostream& s, const sstring& name, const std::map<sstring, sstring>& labels, const config& ctx) { s << name << "{"; const char* delimiter = ""; if (ctx.label) { s << ctx.label->key() << "=\"" << ctx.label->value() << '"'; delimiter = ","; } if (!labels.empty()) { for (auto l : labels) { s << delimiter; s << l.first << "=\"" << l.second << '"'; delimiter = ","; } } s << "} "; } /*! * \brief iterator for metric family * * In prometheus, a single shard collecct all the data from the other * shards and report it. * * Each shard returns a value_copy struct that has a vector of vector values (a vector per metric family) * and a vector of metadata (and insdie it a vector of metric metadata) * * The metrics are sorted by the metric family name. * * In prometheus, all the metrics that belongs to the same metric family are reported together. * * For efficiency the results from the metrics layer are kept in a vector. * * So we have a vector of shards of a vector of metric families of a vector of values. * * To produce the result, we use the metric_family_iterator that is created by metric_family_range. * * When iterating over the metrics we use two helper structure. * * 1. A map between metric family name and the total number of values (combine on all shards) and * pointer to the metric family metadata. * 2. A vector of positions to the current metric family for each shard. * * The metric_family_range returns a metric_family_iterator that goes over all the families. * * The iterator returns a metric_family object, that can report the metric_family name, the size (how many * metrics in total belongs to the metric family) and a a foreach_metric method. * * The foreach_metric method can be used to perform an action on each of the metric that belongs to * that metric family * * Iterating over the metrics is done: * - go over each of the shard and each of the entry in the position vector: * - if the current family (the metric family that we get from the shard and position) has the current name: * - iterate over each of the metrics belong to that metric family: * * for example, if m is a metric_family_range * * for (auto&& i : m) { * std::cout << i.name() << std::endl; * i.foreach_metric([](const mi::metric_value& value, const mi::metric_info& value_info) { * std::cout << value_info.id.labels().size() <<std::cout; * }); * } * * Will print all the metric family names followed by the number of labels each metric has. */ class metric_family_iterator; class metric_family_range; class metrics_families_per_shard { using metrics_family_per_shard_data_container = std::vector<foreign_ptr<mi::values_reference>>; metrics_family_per_shard_data_container _data; using comp_function = std::function<bool(const sstring&, const mi::metric_family_metadata&)>; /*! * \brief find the last item in a range of metric family based on a comparator function * */ metric_family_iterator find_bound(const sstring& family_name, comp_function comp) const; public: using const_iterator = metrics_family_per_shard_data_container::const_iterator; using iterator = metrics_family_per_shard_data_container::iterator; using reference = metrics_family_per_shard_data_container::reference; using const_reference = metrics_family_per_shard_data_container::const_reference; /*! * \brief find the first item following a metric family range. * metric family are sorted, this will return the first item that is outside * of the range */ metric_family_iterator upper_bound(const sstring& family_name) const; /*! * \brief find the first item in a range of metric family. * metric family are sorted, the first item, is the first to match the * criteria. */ metric_family_iterator lower_bound(const sstring& family_name) const; /** * \defgroup Variables Global variables */ /* * @defgroup Vector properties * The following methods making metrics_families_per_shard act as * a vector of foreign_ptr<mi::values_reference> * @{ * * */ iterator begin() { return _data.begin(); } iterator end() { return _data.end(); } const_iterator begin() const { return _data.begin(); } const_iterator end() const { return _data.end(); } void resize(size_t new_size) { _data.resize(new_size); } reference& operator[](size_t n) { return _data[n]; } const_reference& operator[](size_t n) const { return _data[n]; } /** @} */ }; static future<> get_map_value(metrics_families_per_shard& vec) { vec.resize(smp::count); return parallel_for_each(boost::irange(0u, smp::count), [&vec] (auto cpu) { return smp::submit_to(cpu, [] { return mi::get_values(); }).then([&vec, cpu] (auto res) { vec[cpu] = std::move(res); }); }); } /*! * \brief a facade class for metric family */ class metric_family { const sstring* _name = nullptr; uint32_t _size = 0; const mi::metric_family_info* _family_info = nullptr; metric_family_iterator& _iterator_state; metric_family(metric_family_iterator& state) : _iterator_state(state) { } metric_family(const sstring* name , uint32_t size, const mi::metric_family_info* family_info, metric_family_iterator& state) : _name(name), _size(size), _family_info(family_info), _iterator_state(state) { } metric_family(const metric_family& info, metric_family_iterator& state) : metric_family(info._name, info._size, info._family_info, state) { } public: metric_family(const metric_family&) = delete; metric_family(metric_family&&) = delete; const sstring& name() const { return *_name; } const uint32_t size() const { return _size; } const mi::metric_family_info& metadata() const { return *_family_info; } void foreach_metric(std::function<void(const mi::metric_value&, const mi::metric_info&)>&& f); bool end() const { return !_name || !_family_info; } friend class metric_family_iterator; }; class metric_family_iterator { const metrics_families_per_shard& _families; std::vector<size_t> _positions; metric_family _info; void next() { if (_positions.empty()) { return; } const sstring *new_name = nullptr; const mi::metric_family_info* new_family_info = nullptr; _info._size = 0; for (auto&& i : boost::combine(_positions, _families)) { auto& pos_in_metric_per_shard = boost::get<0>(i); auto& metric_family = boost::get<1>(i); if (_info._name && pos_in_metric_per_shard < metric_family->metadata->size() && metric_family->metadata->at(pos_in_metric_per_shard).mf.name.compare(*_info._name) <= 0) { pos_in_metric_per_shard++; } if (pos_in_metric_per_shard >= metric_family->metadata->size()) { // no more metric family in this shard continue; } auto& metadata = metric_family->metadata->at(pos_in_metric_per_shard); int cmp = (!new_name) ? -1 : metadata.mf.name.compare(*new_name); if (cmp < 0) { new_name = &metadata.mf.name; new_family_info = &metadata.mf; _info._size = 0; } if (cmp <= 0) { _info._size += metadata.metrics.size(); } } _info._name = new_name; _info._family_info = new_family_info; } public: metric_family_iterator() = delete; metric_family_iterator(const metric_family_iterator& o) : _families(o._families), _positions(o._positions), _info(*this) { next(); } metric_family_iterator(metric_family_iterator&& o) : _families(o._families), _positions(std::move(o._positions)), _info(*this) { next(); } metric_family_iterator(const metrics_families_per_shard& families, unsigned shards) : _families(families), _positions(shards, 0), _info(*this) { next(); } metric_family_iterator(const metrics_families_per_shard& families, std::vector<size_t>&& positions) : _families(families), _positions(std::move(positions)), _info(*this) { next(); } metric_family_iterator& operator++() { next(); return *this; } metric_family_iterator operator++(int) { metric_family_iterator previous(*this); next(); return previous; } bool operator!=(const metric_family_iterator& o) const { return !(*this == o); } bool operator==(const metric_family_iterator& o) const { if (end()) { return o.end(); } if (o.end()) { return false; } return name() == o.name(); } metric_family& operator*() { return _info; } metric_family* operator->() { return &_info; } const sstring& name() const { return *_info._name; } const uint32_t size() const { return _info._size; } const mi::metric_family_info& metadata() const { return *_info._family_info; } bool end() const { return _positions.empty() || _info.end(); } void foreach_metric(std::function<void(const mi::metric_value&, const mi::metric_info&)>&& f) { // iterating over the shard vector and the position vector for (auto&& i : boost::combine(_positions, _families)) { auto& pos_in_metric_per_shard = boost::get<0>(i); auto& metric_family = boost::get<1>(i); if (pos_in_metric_per_shard >= metric_family->metadata->size()) { // no more metric family in this shard continue; } auto& metadata = metric_family->metadata->at(pos_in_metric_per_shard); // the the name is different, that means that on this shard, the metric family // does not exist, because everything is sorted by metric family name, this is fine. if (metadata.mf.name == name()) { const mi::value_vector& values = metric_family->values[pos_in_metric_per_shard]; const mi::metric_metadata_vector& metrics_metadata = metadata.metrics; for (auto&& vm : boost::combine(values, metrics_metadata)) { auto& value = boost::get<0>(vm); auto& metric_metadata = boost::get<1>(vm); f(value, metric_metadata); } } } } }; void metric_family::foreach_metric(std::function<void(const mi::metric_value&, const mi::metric_info&)>&& f) { _iterator_state.foreach_metric(std::move(f)); } class metric_family_range { metric_family_iterator _begin; metric_family_iterator _end; public: metric_family_range(const metrics_families_per_shard& families) : _begin(families, smp::count), _end(metric_family_iterator(families, 0)) { } metric_family_range(const metric_family_iterator& b, const metric_family_iterator& e) : _begin(b), _end(e) { } metric_family_iterator begin() const { return _begin; } metric_family_iterator end() const { return _end; } }; metric_family_iterator metrics_families_per_shard::find_bound(const sstring& family_name, comp_function comp) const { std::vector<size_t> positions; positions.reserve(smp::count); for (auto& shard_info : _data) { std::vector<mi::metric_family_metadata>& metadata = *(shard_info->metadata); std::vector<mi::metric_family_metadata>::iterator it_b = boost::range::upper_bound(metadata, family_name, comp); positions.emplace_back(it_b - metadata.begin()); } return metric_family_iterator(*this, std::move(positions)); } metric_family_iterator metrics_families_per_shard::lower_bound(const sstring& family_name) const { return find_bound(family_name, [](const sstring& a, const mi::metric_family_metadata& b) { //sstring doesn't have a <= operator return a < b.mf.name || a == b.mf.name; }); } metric_family_iterator metrics_families_per_shard::upper_bound(const sstring& family_name) const { return find_bound(family_name, [](const sstring& a, const mi::metric_family_metadata& b) { return a < b.mf.name; }); } /*! * \brief a helper function to get metric family range * if metric_family_name is empty will return everything, if not, it will return * the range of metric family that match the metric_family_name. * * if prefix is true the match will be based on prefix */ metric_family_range get_range(const metrics_families_per_shard& mf, const sstring& metric_family_name, bool prefix) { if (metric_family_name == "") { return metric_family_range(mf); } auto upper_bount_prefix = metric_family_name; ++upper_bount_prefix.back(); if (prefix) { return metric_family_range(mf.lower_bound(metric_family_name), mf.lower_bound(upper_bount_prefix)); } auto lb = mf.lower_bound(metric_family_name); if (lb.end() || lb->name() != metric_family_name) { return metric_family_range(lb, lb); // just return an empty range } auto up = lb; ++up; return metric_family_range(lb, up); } future<> write_text_representation(output_stream<char>& out, const config& ctx, const metric_family_range& m) { return seastar::async([&ctx, &out, &m] () mutable { bool found = false; for (metric_family& metric_family : m) { auto name = ctx.prefix + "_" + metric_family.name(); found = false; metric_family.foreach_metric([&out, &ctx, &found, &name, &metric_family](auto value, auto value_info) mutable { std::stringstream s; if (!found) { if (metric_family.metadata().d.str() != "") { s << "# HELP " << name << " " << metric_family.metadata().d.str() << "\n"; } s << "# TYPE " << name << " " << to_str(metric_family.metadata().type) << "\n"; found = true; } if (value.type() == mi::data_type::HISTOGRAM) { auto&& h = value.get_histogram(); std::map<sstring, sstring> labels = value_info.id.labels(); add_name(s, name + "_sum", labels, ctx); s << h.sample_sum; s << "\n"; add_name(s, name + "_count", labels, ctx); s << h.sample_count; s << "\n"; auto& le = labels["le"]; auto bucket = name + "_bucket"; for (auto i : h.buckets) { le = std::to_string(i.upper_bound); add_name(s, bucket, labels, ctx); s << i.count; s << "\n"; } labels["le"] = "+Inf"; add_name(s, bucket, labels, ctx); s << h.sample_count; s << "\n"; } else { add_name(s, name, value_info.id.labels(), ctx); s << to_str(value); s << "\n"; } out.write(s.str()).get(); thread::maybe_yield(); }); } }); } future<> write_protobuf_representation(output_stream<char>& out, const config& ctx, metric_family_range& m) { return do_for_each(m, [&ctx, &out](metric_family& metric_family) mutable { std::string s; google::protobuf::io::StringOutputStream os(&s); auto& name = metric_family.name(); pm::MetricFamily mtf; mtf.set_name(ctx.prefix + "_" + name); mtf.mutable_metric()->Reserve(metric_family.size()); metric_family.foreach_metric([&mtf, &ctx](auto value, auto value_info) { fill_metric(mtf, value, value_info.id, ctx); }); if (!write_delimited_to(mtf, &os)) { seastar_logger.warn("Failed to write protobuf metrics"); } return out.write(s); }); } bool is_accept_text(const std::string& accept) { std::vector<std::string> strs; boost::split(strs, accept, boost::is_any_of(",")); for (auto i : strs) { boost::trim(i); if (boost::starts_with(i, "application/vnd.google.protobuf;")) { return false; } } return true; } class metrics_handler : public handler_base { sstring _prefix; config _ctx; /*! * \brief tries to trim an asterisk from the end of the string * return true if an asterisk exists. */ bool trim_asterisk(sstring& name) { if (name.size() && name.back() == '*') { name.resize(name.length() - 1); return true; } // Prometheus uses url encoding for the path so '*' is encoded as '%2A' if (boost::algorithm::ends_with(name, "%2A")) { // This assert is obviously true. It is in here just to // silence a bogus gcc warning: // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=89337 assert(name.length() >= 3); name.resize(name.length() - 3); return true; } return false; } public: metrics_handler(config ctx) : _ctx(ctx) {} future<std::unique_ptr<httpd::reply>> handle(const sstring& path, std::unique_ptr<httpd::request> req, std::unique_ptr<httpd::reply> rep) override { auto text = is_accept_text(req->get_header("Accept")); sstring metric_family_name = req->get_query_param("name"); bool prefix = trim_asterisk(metric_family_name); rep->write_body((text) ? "txt" : "proto", [this, text, metric_family_name, prefix] (output_stream<char>&& s) { return do_with(metrics_families_per_shard(), output_stream<char>(std::move(s)), [this, text, prefix, &metric_family_name] (metrics_families_per_shard& families, output_stream<char>& s) mutable { return get_map_value(families).then([&s, &families, this, text, prefix, &metric_family_name]() mutable { return do_with(get_range(families, metric_family_name, prefix), [&s, this, text](metric_family_range& m) { return (text) ? write_text_representation(s, _ctx, m) : write_protobuf_representation(s, _ctx, m); }); }).finally([&s] () mutable { return s.close(); }); }); }); return make_ready_future<std::unique_ptr<httpd::reply>>(std::move(rep)); } }; future<> add_prometheus_routes(http_server& server, config ctx) { server._routes.put(GET, "/metrics", new metrics_handler(ctx)); return make_ready_future<>(); } future<> add_prometheus_routes(distributed<http_server>& server, config ctx) { return server.invoke_on_all([ctx](http_server& s) { return add_prometheus_routes(s, ctx); }); } future<> start(httpd::http_server_control& http_server, config ctx) { return add_prometheus_routes(http_server.server(), ctx); } } }
34.633705
134
0.620018
liubangchen
fee845322dd8be6b297c2bc610eeb5a9bf1bc4dc
2,272
cpp
C++
lib/Submix.cpp
gpeter12/amuse
d96be61e296031d5417e46dba1d3b9060b2ab6c0
[ "MIT" ]
36
2016-05-05T21:49:16.000Z
2022-03-20T02:28:41.000Z
lib/Submix.cpp
gpeter12/amuse
d96be61e296031d5417e46dba1d3b9060b2ab6c0
[ "MIT" ]
10
2016-06-26T21:05:22.000Z
2021-08-14T11:46:55.000Z
lib/Submix.cpp
gpeter12/amuse
d96be61e296031d5417e46dba1d3b9060b2ab6c0
[ "MIT" ]
5
2016-09-16T08:38:16.000Z
2021-01-08T22:37:52.000Z
#include "amuse/Submix.hpp" namespace amuse { Submix::Submix(Engine& engine) : m_root(engine) {} EffectChorus& Submix::makeChorus(uint32_t baseDelay, uint32_t variation, uint32_t period) { return makeEffect<EffectChorus>(baseDelay, variation, period); } EffectChorus& Submix::makeChorus(const EffectChorusInfo& info) { return makeEffect<EffectChorus>(info); } EffectDelay& Submix::makeDelay(uint32_t initDelay, uint32_t initFeedback, uint32_t initOutput) { return makeEffect<EffectDelay>(initDelay, initFeedback, initOutput); } EffectDelay& Submix::makeDelay(const EffectDelayInfo& info) { return makeEffect<EffectDelay>(info); } EffectReverbStd& Submix::makeReverbStd(float coloration, float mix, float time, float damping, float preDelay) { return makeEffect<EffectReverbStd>(coloration, mix, time, damping, preDelay); } EffectReverbStd& Submix::makeReverbStd(const EffectReverbStdInfo& info) { return makeEffect<EffectReverbStd>(info); } EffectReverbHi& Submix::makeReverbHi(float coloration, float mix, float time, float damping, float preDelay, float crosstalk) { return makeEffect<EffectReverbHi>(coloration, mix, time, damping, preDelay, crosstalk); } EffectReverbHi& Submix::makeReverbHi(const EffectReverbHiInfo& info) { return makeEffect<EffectReverbHi>(info); } void Submix::applyEffect(int16_t* audio, size_t frameCount, const ChannelMap& chanMap) const { for (const std::unique_ptr<EffectBaseTypeless>& effect : m_effectStack) ((EffectBase<int16_t>&)*effect).applyEffect(audio, frameCount, chanMap); } void Submix::applyEffect(int32_t* audio, size_t frameCount, const ChannelMap& chanMap) const { for (const std::unique_ptr<EffectBaseTypeless>& effect : m_effectStack) ((EffectBase<int32_t>&)*effect).applyEffect(audio, frameCount, chanMap); } void Submix::applyEffect(float* audio, size_t frameCount, const ChannelMap& chanMap) const { for (const std::unique_ptr<EffectBaseTypeless>& effect : m_effectStack) ((EffectBase<float>&)*effect).applyEffect(audio, frameCount, chanMap); } void Submix::resetOutputSampleRate(double sampleRate) { for (const std::unique_ptr<EffectBaseTypeless>& effect : m_effectStack) effect->resetOutputSampleRate(sampleRate); } } // namespace amuse
43.692308
117
0.767606
gpeter12
fee968f40d7905b046fbe3635141518830986b67
5,513
cpp
C++
src/devices/bus/tiki100/exp.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
26
2015-03-31T06:25:51.000Z
2021-12-14T09:29:04.000Z
src/devices/bus/tiki100/exp.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
null
null
null
src/devices/bus/tiki100/exp.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
10
2015-03-27T05:45:51.000Z
2022-02-04T06:57:36.000Z
// license:BSD-3-Clause // copyright-holders:Curt Coder /********************************************************************** TIKI-100 expansion bus emulation **********************************************************************/ #include "emu.h" #include "exp.h" //************************************************************************** // DEVICE DEFINITIONS //************************************************************************** DEFINE_DEVICE_TYPE(TIKI100_BUS, tiki100_bus_device, "tiki100bus", "TIKI-100 expansion bus") DEFINE_DEVICE_TYPE(TIKI100_BUS_SLOT, tiki100_bus_slot_device, "tiki100bus_slot", "TIKI-100 expansion bus slot") //************************************************************************** // LIVE DEVICE //************************************************************************** //------------------------------------------------- // tiki100_bus_slot_device - constructor //------------------------------------------------- tiki100_bus_slot_device::tiki100_bus_slot_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : device_t(mconfig, TIKI100_BUS_SLOT, tag, owner, clock), device_single_card_slot_interface<device_tiki100bus_card_interface>(mconfig, *this), device_z80daisy_interface(mconfig, *this), m_bus(*this, finder_base::DUMMY_TAG), m_card(nullptr) { } //------------------------------------------------- // device_start - device-specific startup //------------------------------------------------- void tiki100_bus_slot_device::device_start() { m_card = get_card_device(); if (m_card) m_bus->add_card(*m_card); } //------------------------------------------------- // tiki100_bus_device - constructor //------------------------------------------------- tiki100_bus_device::tiki100_bus_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : device_t(mconfig, TIKI100_BUS, tag, owner, clock), m_irq_cb(*this), m_nmi_cb(*this), m_busrq_cb(*this), m_in_mrq_cb(*this), m_out_mrq_cb(*this) { } //------------------------------------------------- // device_start - device-specific startup //------------------------------------------------- void tiki100_bus_device::device_start() { // resolve callbacks m_irq_cb.resolve_safe(); m_nmi_cb.resolve_safe(); m_busrq_cb.resolve_safe(); m_in_mrq_cb.resolve(); m_out_mrq_cb.resolve(); } //------------------------------------------------- // add_card - add card //------------------------------------------------- void tiki100_bus_device::add_card(device_tiki100bus_card_interface &card) { m_device_list.append(card); card.m_bus = this; } //------------------------------------------------- // mrq_r - memory read //------------------------------------------------- uint8_t tiki100_bus_device::mrq_r(offs_t offset, uint8_t data, bool &mdis) { device_tiki100bus_card_interface *entry = m_device_list.first(); while (entry) { data &= entry->mrq_r(offset, data, mdis); entry = entry->next(); } return data; } //------------------------------------------------- // mrq_w - memory write //------------------------------------------------- void tiki100_bus_device::mrq_w(offs_t offset, uint8_t data) { device_tiki100bus_card_interface *entry = m_device_list.first(); while (entry) { entry->mrq_w(offset, data); entry = entry->next(); } } //------------------------------------------------- // iorq_r - I/O read //------------------------------------------------- uint8_t tiki100_bus_device::iorq_r(offs_t offset, uint8_t data) { device_tiki100bus_card_interface *entry = m_device_list.first(); while (entry) { data &= entry->iorq_r(offset, data); entry = entry->next(); } return data; } //------------------------------------------------- // iorq_w - I/O write //------------------------------------------------- void tiki100_bus_device::iorq_w(offs_t offset, uint8_t data) { device_tiki100bus_card_interface *entry = m_device_list.first(); while (entry) { entry->iorq_w(offset, data); entry = entry->next(); } } //------------------------------------------------- // busak_w - bus acknowledge write //------------------------------------------------- WRITE_LINE_MEMBER( tiki100_bus_device::busak_w ) { device_tiki100bus_card_interface *entry = m_device_list.first(); while (entry) { entry->busak_w(state); entry = entry->next(); } } //************************************************************************** // DEVICE TIKI-100 BUS CARD INTERFACE //************************************************************************** //------------------------------------------------- // device_tiki100bus_card_interface - constructor //------------------------------------------------- device_tiki100bus_card_interface::device_tiki100bus_card_interface(const machine_config &mconfig, device_t &device) : device_interface(device, "tiki100bus"), m_bus(nullptr), m_busak(CLEAR_LINE), m_next(nullptr) { m_slot = dynamic_cast<tiki100_bus_slot_device *>(device.owner()); } void device_tiki100bus_card_interface::interface_pre_start() { if (!m_bus) throw device_missing_dependencies(); } //------------------------------------------------- // SLOT_INTERFACE( tiki100_cards ) //------------------------------------------------- // slot devices #include "8088.h" #include "hdc.h" void tiki100_cards(device_slot_interface &device) { device.option_add("8088", TIKI100_8088); device.option_add("hdc", TIKI100_HDC); }
25.40553
131
0.492835
Robbbert
feea116fac1614a6841a468795ea1b23442b2ffd
2,946
cpp
C++
src/Sobol.cpp
lilesper/SparseVoxelOctree
9c4c79ab746758d21070bb733dafe4f78438e4b5
[ "MIT" ]
338
2019-08-02T03:57:05.000Z
2022-03-29T20:49:21.000Z
src/Sobol.cpp
lilesper/SparseVoxelOctree
9c4c79ab746758d21070bb733dafe4f78438e4b5
[ "MIT" ]
12
2020-01-10T09:03:22.000Z
2022-03-25T02:03:23.000Z
src/Sobol.cpp
lilesper/SparseVoxelOctree
9c4c79ab746758d21070bb733dafe4f78438e4b5
[ "MIT" ]
36
2019-08-08T11:15:23.000Z
2022-02-26T00:31:13.000Z
#include "Sobol.hpp" constexpr uint32_t kMaxDimension = 64; constexpr VkDeviceSize kBufferSize = (kMaxDimension + 1) * sizeof(uint32_t); /*void Sobol::Next(float *out) { uint8_t c = get_first_zero_bit(m_index++); //uint8_t c = glm::findLSB(~(m_index ++)); for (unsigned j = 0; j < m_dim; ++j) out[j] = (float) ((m_x[j] ^= kMatrices[j][c]) / 4294967296.0); }*/ void Sobol::Initialize(const std::shared_ptr<myvk::Device> &device) { m_descriptor_pool = myvk::DescriptorPool::Create(device, 1, {{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}}); { VkDescriptorSetLayoutBinding sobol_binding = {}; sobol_binding.binding = 0; sobol_binding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; sobol_binding.descriptorCount = 1; sobol_binding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT | VK_SHADER_STAGE_FRAGMENT_BIT; m_descriptor_set_layout = myvk::DescriptorSetLayout::Create(device, {sobol_binding}); } m_descriptor_set = myvk::DescriptorSet::Create(m_descriptor_pool, m_descriptor_set_layout); m_sobol_buffer = myvk::Buffer::Create(device, kBufferSize, VMA_MEMORY_USAGE_GPU_ONLY, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT); m_descriptor_set->UpdateStorageBuffer(m_sobol_buffer, 0); m_staging_buffer = myvk::Buffer::CreateStaging(device, kBufferSize); { uint32_t *data = (uint32_t *)m_staging_buffer->Map(); std::fill(data, data + kMaxDimension + 1, 0u); m_staging_buffer->Unmap(); } m_pipeline_layout = myvk::PipelineLayout::Create(device, {m_descriptor_set_layout}, {{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(uint32_t)}}); { constexpr uint32_t kSobolCompSpv[] = { #include "spirv/sobol.comp.u32" }; std::shared_ptr<myvk::ShaderModule> sobol_shader_module = myvk::ShaderModule::Create(device, kSobolCompSpv, sizeof(kSobolCompSpv)); m_compute_pipeline = myvk::ComputePipeline::Create(m_pipeline_layout, sobol_shader_module); } } void Sobol::CmdNext(const std::shared_ptr<myvk::CommandBuffer> &command_buffer) { command_buffer->CmdBindDescriptorSets({m_descriptor_set}, m_pipeline_layout, VK_PIPELINE_BIND_POINT_COMPUTE, {}); command_buffer->CmdPushConstants(m_pipeline_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(uint32_t), &m_dimension); command_buffer->CmdBindPipeline(m_compute_pipeline); command_buffer->CmdDispatch(1, 1, 1); } void Sobol::Reset(const std::shared_ptr<myvk::CommandPool> &command_pool, uint32_t dimension) { m_dimension = dimension; std::shared_ptr<myvk::Fence> fence = myvk::Fence::Create(command_pool->GetDevicePtr()); std::shared_ptr<myvk::CommandBuffer> command_buffer = myvk::CommandBuffer::Create(command_pool); command_buffer->Begin(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT); command_buffer->CmdCopy(m_staging_buffer, m_sobol_buffer, {{0, 0, kBufferSize}}); command_buffer->End(); command_buffer->Submit(fence); fence->Wait(); }
43.970149
117
0.746436
lilesper
feefb161222befd1d66d36e7a487a859ed3ff3fb
786
cpp
C++
110.平衡二叉树/isBalanced.cpp
YichengZhong/Top-Interview-Questions
124828d321f482a0eaa30012b3706267487bfd24
[ "MIT" ]
1
2019-10-21T14:40:39.000Z
2019-10-21T14:40:39.000Z
110.平衡二叉树/isBalanced.cpp
YichengZhong/Top-Interview-Questions
124828d321f482a0eaa30012b3706267487bfd24
[ "MIT" ]
null
null
null
110.平衡二叉树/isBalanced.cpp
YichengZhong/Top-Interview-Questions
124828d321f482a0eaa30012b3706267487bfd24
[ "MIT" ]
1
2020-11-04T07:33:34.000Z
2020-11-04T07:33:34.000Z
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isBalanced(TreeNode* root) { if(root==NULL) { return true; } int maxDepthLeft=maxDepth(root->left) ; int maxDepthRight=maxDepth(root->right) ; if(abs(maxDepthLeft-maxDepthRight)>1) { return false; } return isBalanced(root->left) && isBalanced(root->right); } int maxDepth(TreeNode* root) { if (!root) return 0; return 1 + max(maxDepth(root->left), maxDepth(root->right)); } };
21.243243
68
0.507634
YichengZhong
fef1387435acfe817b3ba19ea241683d14a5fd01
6,734
cpp
C++
implementations/ugene/src/plugins_3rdparty/umuscle/src/muscle/objscoreda.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
implementations/ugene/src/plugins_3rdparty/umuscle/src/muscle/objscoreda.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
implementations/ugene/src/plugins_3rdparty/umuscle/src/muscle/objscoreda.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
#include "muscle.h" #include "msa.h" #include "profile.h" #include "objscore.h" #if DOUBLE_AFFINE #define TRACE 0 #define TEST_SPFAST 0 static SCORE GapPenalty(unsigned uLength, bool Term, SCORE g, SCORE e) { //if (Term) // { // switch (g_TermGap) // { // case TERMGAP_Full: // return g + (uLength - 1)*e; // case TERMGAP_Half: // return g/2 + (uLength - 1)*e; // case TERMGAP_Ext: // return uLength*e; // } // Quit("Bad termgap"); // } //else // return g + (uLength - 1)*e; //return MINUS_INFINITY; return g + (uLength - 1)*e; } static SCORE GapPenalty(unsigned uLength, bool Term) { SCORE s1 = GapPenalty(uLength, Term, g_scoreGapOpen, g_scoreGapExtend); #if DOUBLE_AFFINE SCORE s2 = GapPenalty(uLength, Term, g_scoreGapOpen2, g_scoreGapExtend2); if (s1 > s2) return s1; return s2; #else return s1; #endif } static const MSA *g_ptrMSA1; static const MSA *g_ptrMSA2; static unsigned g_uSeqIndex1; static unsigned g_uSeqIndex2; static void LogGap(unsigned uStart, unsigned uEnd, unsigned uGapLength, bool bNTerm, bool bCTerm) { Log("%16.16s ", ""); for (unsigned i = 0; i < uStart; ++i) Log(" "); unsigned uMyLength = 0; for (unsigned i = uStart; i <= uEnd; ++i) { bool bGap1 = g_ptrMSA1->IsGap(g_uSeqIndex1, i); bool bGap2 = g_ptrMSA2->IsGap(g_uSeqIndex2, i); if (!bGap1 && !bGap2) Quit("Error -- neither gapping"); if (bGap1 && bGap2) Log("."); else { ++uMyLength; Log("-"); } } SCORE s = GapPenalty(uGapLength, bNTerm || bCTerm); Log(" L=%d N%d C%d s=%.3g", uGapLength, bNTerm, bCTerm, s); Log("\n"); if (uMyLength != uGapLength) Quit("Lengths differ"); } static SCORE ScoreSeqPair(const MSA &msa1, unsigned uSeqIndex1, const MSA &msa2, unsigned uSeqIndex2, SCORE *ptrLetters, SCORE *ptrGaps) { g_ptrMSA1 = &msa1; g_ptrMSA2 = &msa2; g_uSeqIndex1 = uSeqIndex1; g_uSeqIndex2 = uSeqIndex2; const unsigned uColCount = msa1.GetColCount(); const unsigned uColCount2 = msa2.GetColCount(); if (uColCount != uColCount2) Quit("ScoreSeqPair, different lengths"); #if TRACE Log("ScoreSeqPair\n"); Log("%16.16s ", msa1.GetSeqName(uSeqIndex1)); for (unsigned i = 0; i < uColCount; ++i) Log("%c", msa1.GetChar(uSeqIndex1, i)); Log("\n"); Log("%16.16s ", msa2.GetSeqName(uSeqIndex2)); for (unsigned i = 0; i < uColCount; ++i) Log("%c", msa1.GetChar(uSeqIndex2, i)); Log("\n"); #endif SCORE scoreTotal = 0; // Substitution scores unsigned uFirstLetter1 = uInsane; unsigned uFirstLetter2 = uInsane; unsigned uLastLetter1 = uInsane; unsigned uLastLetter2 = uInsane; for (unsigned uColIndex = 0; uColIndex < uColCount; ++uColIndex) { bool bGap1 = msa1.IsGap(uSeqIndex1, uColIndex); bool bGap2 = msa2.IsGap(uSeqIndex2, uColIndex); bool bWildcard1 = msa1.IsWildcard(uSeqIndex1, uColIndex); bool bWildcard2 = msa2.IsWildcard(uSeqIndex2, uColIndex); if (!bGap1) { if (uInsane == uFirstLetter1) uFirstLetter1 = uColIndex; uLastLetter1 = uColIndex; } if (!bGap2) { if (uInsane == uFirstLetter2) uFirstLetter2 = uColIndex; uLastLetter2 = uColIndex; } if (bGap1 || bGap2 || bWildcard1 || bWildcard2) continue; unsigned uLetter1 = msa1.GetLetter(uSeqIndex1, uColIndex); unsigned uLetter2 = msa2.GetLetter(uSeqIndex2, uColIndex); SCORE scoreMatch = (*g_ptrScoreMatrix)[uLetter1][uLetter2]; scoreTotal += scoreMatch; #if TRACE Log("%c <-> %c = %7.1f %10.1f\n", msa1.GetChar(uSeqIndex1, uColIndex), msa2.GetChar(uSeqIndex2, uColIndex), scoreMatch, scoreTotal); #endif } *ptrLetters = scoreTotal; // Gap penalties unsigned uGapLength = uInsane; unsigned uGapStartCol = uInsane; bool bGapping1 = false; bool bGapping2 = false; for (unsigned uColIndex = 0; uColIndex < uColCount; ++uColIndex) { bool bGap1 = msa1.IsGap(uSeqIndex1, uColIndex); bool bGap2 = msa2.IsGap(uSeqIndex2, uColIndex); if (bGap1 && bGap2) continue; if (bGapping1) { if (bGap1) ++uGapLength; else { bGapping1 = false; bool bNTerm = (uFirstLetter2 == uGapStartCol); bool bCTerm = (uLastLetter2 + 1 == uColIndex); SCORE scoreGap = GapPenalty(uGapLength, bNTerm || bCTerm); scoreTotal += scoreGap; #if TRACE LogGap(uGapStartCol, uColIndex - 1, uGapLength, bNTerm, bCTerm); Log("GAP %7.1f %10.1f\n", scoreGap, scoreTotal); #endif } continue; } else { if (bGap1) { uGapStartCol = uColIndex; bGapping1 = true; uGapLength = 1; continue; } } if (bGapping2) { if (bGap2) ++uGapLength; else { bGapping2 = false; bool bNTerm = (uFirstLetter1 == uGapStartCol); bool bCTerm = (uLastLetter1 + 1 == uColIndex); SCORE scoreGap = GapPenalty(uGapLength, bNTerm || bCTerm); scoreTotal += scoreGap; #if TRACE LogGap(uGapStartCol, uColIndex - 1, uGapLength, bNTerm, bCTerm); Log("GAP %7.1f %10.1f\n", scoreGap, scoreTotal); #endif } } else { if (bGap2) { uGapStartCol = uColIndex; bGapping2 = true; uGapLength = 1; } } } if (bGapping1 || bGapping2) { SCORE scoreGap = GapPenalty(uGapLength, true); scoreTotal += scoreGap; #if TRACE LogGap(uGapStartCol, uColCount - 1, uGapLength, false, true); Log("GAP %7.1f %10.1f\n", scoreGap, scoreTotal); #endif } *ptrGaps = scoreTotal - *ptrLetters; return scoreTotal; } // The usual sum-of-pairs objective score: sum the score // of the alignment of each pair of sequences. SCORE ObjScoreDA(const MSA &msa, SCORE *ptrLetters, SCORE *ptrGaps) { const unsigned uSeqCount = msa.GetSeqCount(); SCORE scoreTotal = 0; unsigned uPairCount = 0; #if TRACE msa.LogMe(); Log(" Score Weight Weight Total\n"); Log("---------- ------ ------ ----------\n"); #endif SCORE TotalLetters = 0; SCORE TotalGaps = 0; for (unsigned uSeqIndex1 = 0; uSeqIndex1 < uSeqCount; ++uSeqIndex1) { const WEIGHT w1 = msa.GetSeqWeight(uSeqIndex1); for (unsigned uSeqIndex2 = uSeqIndex1 + 1; uSeqIndex2 < uSeqCount; ++uSeqIndex2) { const WEIGHT w2 = msa.GetSeqWeight(uSeqIndex2); const WEIGHT w = w1*w2; SCORE Letters; SCORE Gaps; SCORE scorePair = ScoreSeqPair(msa, uSeqIndex1, msa, uSeqIndex2, &Letters, &Gaps); scoreTotal += w1*w2*scorePair; TotalLetters += w1*w2*Letters; TotalGaps += w1*w2*Gaps; ++uPairCount; #if TRACE Log("%10.2f %6.3f %6.3f %10.2f %d=%s %d=%s\n", scorePair, w1, w2, scorePair*w1*w2, uSeqIndex1, msa.GetSeqName(uSeqIndex1), uSeqIndex2, msa.GetSeqName(uSeqIndex2)); #endif } } *ptrLetters = TotalLetters; *ptrGaps = TotalGaps; return scoreTotal; } #endif // DOUBLE_AFFINE
23.22069
82
0.648352
r-barnes
fef18edd36750ebc832bf59cc21067f4dee0c528
8,637
cpp
C++
cpp/godot-cpp/src/gen/Line2D.cpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
1
2021-03-16T09:51:00.000Z
2021-03-16T09:51:00.000Z
cpp/godot-cpp/src/gen/Line2D.cpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
null
null
null
cpp/godot-cpp/src/gen/Line2D.cpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
null
null
null
#include "Line2D.hpp" #include <core/GodotGlobal.hpp> #include <core/CoreTypes.hpp> #include <core/Ref.hpp> #include <core/Godot.hpp> #include "__icalls.hpp" #include "Curve.hpp" #include "Gradient.hpp" #include "Texture.hpp" namespace godot { Line2D::___method_bindings Line2D::___mb = {}; void Line2D::___init_method_bindings() { ___mb.mb__curve_changed = godot::api->godot_method_bind_get_method("Line2D", "_curve_changed"); ___mb.mb__gradient_changed = godot::api->godot_method_bind_get_method("Line2D", "_gradient_changed"); ___mb.mb_add_point = godot::api->godot_method_bind_get_method("Line2D", "add_point"); ___mb.mb_clear_points = godot::api->godot_method_bind_get_method("Line2D", "clear_points"); ___mb.mb_get_antialiased = godot::api->godot_method_bind_get_method("Line2D", "get_antialiased"); ___mb.mb_get_begin_cap_mode = godot::api->godot_method_bind_get_method("Line2D", "get_begin_cap_mode"); ___mb.mb_get_curve = godot::api->godot_method_bind_get_method("Line2D", "get_curve"); ___mb.mb_get_default_color = godot::api->godot_method_bind_get_method("Line2D", "get_default_color"); ___mb.mb_get_end_cap_mode = godot::api->godot_method_bind_get_method("Line2D", "get_end_cap_mode"); ___mb.mb_get_gradient = godot::api->godot_method_bind_get_method("Line2D", "get_gradient"); ___mb.mb_get_joint_mode = godot::api->godot_method_bind_get_method("Line2D", "get_joint_mode"); ___mb.mb_get_point_count = godot::api->godot_method_bind_get_method("Line2D", "get_point_count"); ___mb.mb_get_point_position = godot::api->godot_method_bind_get_method("Line2D", "get_point_position"); ___mb.mb_get_points = godot::api->godot_method_bind_get_method("Line2D", "get_points"); ___mb.mb_get_round_precision = godot::api->godot_method_bind_get_method("Line2D", "get_round_precision"); ___mb.mb_get_sharp_limit = godot::api->godot_method_bind_get_method("Line2D", "get_sharp_limit"); ___mb.mb_get_texture = godot::api->godot_method_bind_get_method("Line2D", "get_texture"); ___mb.mb_get_texture_mode = godot::api->godot_method_bind_get_method("Line2D", "get_texture_mode"); ___mb.mb_get_width = godot::api->godot_method_bind_get_method("Line2D", "get_width"); ___mb.mb_remove_point = godot::api->godot_method_bind_get_method("Line2D", "remove_point"); ___mb.mb_set_antialiased = godot::api->godot_method_bind_get_method("Line2D", "set_antialiased"); ___mb.mb_set_begin_cap_mode = godot::api->godot_method_bind_get_method("Line2D", "set_begin_cap_mode"); ___mb.mb_set_curve = godot::api->godot_method_bind_get_method("Line2D", "set_curve"); ___mb.mb_set_default_color = godot::api->godot_method_bind_get_method("Line2D", "set_default_color"); ___mb.mb_set_end_cap_mode = godot::api->godot_method_bind_get_method("Line2D", "set_end_cap_mode"); ___mb.mb_set_gradient = godot::api->godot_method_bind_get_method("Line2D", "set_gradient"); ___mb.mb_set_joint_mode = godot::api->godot_method_bind_get_method("Line2D", "set_joint_mode"); ___mb.mb_set_point_position = godot::api->godot_method_bind_get_method("Line2D", "set_point_position"); ___mb.mb_set_points = godot::api->godot_method_bind_get_method("Line2D", "set_points"); ___mb.mb_set_round_precision = godot::api->godot_method_bind_get_method("Line2D", "set_round_precision"); ___mb.mb_set_sharp_limit = godot::api->godot_method_bind_get_method("Line2D", "set_sharp_limit"); ___mb.mb_set_texture = godot::api->godot_method_bind_get_method("Line2D", "set_texture"); ___mb.mb_set_texture_mode = godot::api->godot_method_bind_get_method("Line2D", "set_texture_mode"); ___mb.mb_set_width = godot::api->godot_method_bind_get_method("Line2D", "set_width"); } Line2D *Line2D::_new() { return (Line2D *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, godot::api->godot_get_class_constructor((char *)"Line2D")()); } void Line2D::_curve_changed() { ___godot_icall_void(___mb.mb__curve_changed, (const Object *) this); } void Line2D::_gradient_changed() { ___godot_icall_void(___mb.mb__gradient_changed, (const Object *) this); } void Line2D::add_point(const Vector2 position, const int64_t at_position) { ___godot_icall_void_Vector2_int(___mb.mb_add_point, (const Object *) this, position, at_position); } void Line2D::clear_points() { ___godot_icall_void(___mb.mb_clear_points, (const Object *) this); } bool Line2D::get_antialiased() const { return ___godot_icall_bool(___mb.mb_get_antialiased, (const Object *) this); } Line2D::LineCapMode Line2D::get_begin_cap_mode() const { return (Line2D::LineCapMode) ___godot_icall_int(___mb.mb_get_begin_cap_mode, (const Object *) this); } Ref<Curve> Line2D::get_curve() const { return Ref<Curve>::__internal_constructor(___godot_icall_Object(___mb.mb_get_curve, (const Object *) this)); } Color Line2D::get_default_color() const { return ___godot_icall_Color(___mb.mb_get_default_color, (const Object *) this); } Line2D::LineCapMode Line2D::get_end_cap_mode() const { return (Line2D::LineCapMode) ___godot_icall_int(___mb.mb_get_end_cap_mode, (const Object *) this); } Ref<Gradient> Line2D::get_gradient() const { return Ref<Gradient>::__internal_constructor(___godot_icall_Object(___mb.mb_get_gradient, (const Object *) this)); } Line2D::LineJointMode Line2D::get_joint_mode() const { return (Line2D::LineJointMode) ___godot_icall_int(___mb.mb_get_joint_mode, (const Object *) this); } int64_t Line2D::get_point_count() const { return ___godot_icall_int(___mb.mb_get_point_count, (const Object *) this); } Vector2 Line2D::get_point_position(const int64_t i) const { return ___godot_icall_Vector2_int(___mb.mb_get_point_position, (const Object *) this, i); } PoolVector2Array Line2D::get_points() const { return ___godot_icall_PoolVector2Array(___mb.mb_get_points, (const Object *) this); } int64_t Line2D::get_round_precision() const { return ___godot_icall_int(___mb.mb_get_round_precision, (const Object *) this); } real_t Line2D::get_sharp_limit() const { return ___godot_icall_float(___mb.mb_get_sharp_limit, (const Object *) this); } Ref<Texture> Line2D::get_texture() const { return Ref<Texture>::__internal_constructor(___godot_icall_Object(___mb.mb_get_texture, (const Object *) this)); } Line2D::LineTextureMode Line2D::get_texture_mode() const { return (Line2D::LineTextureMode) ___godot_icall_int(___mb.mb_get_texture_mode, (const Object *) this); } real_t Line2D::get_width() const { return ___godot_icall_float(___mb.mb_get_width, (const Object *) this); } void Line2D::remove_point(const int64_t i) { ___godot_icall_void_int(___mb.mb_remove_point, (const Object *) this, i); } void Line2D::set_antialiased(const bool antialiased) { ___godot_icall_void_bool(___mb.mb_set_antialiased, (const Object *) this, antialiased); } void Line2D::set_begin_cap_mode(const int64_t mode) { ___godot_icall_void_int(___mb.mb_set_begin_cap_mode, (const Object *) this, mode); } void Line2D::set_curve(const Ref<Curve> curve) { ___godot_icall_void_Object(___mb.mb_set_curve, (const Object *) this, curve.ptr()); } void Line2D::set_default_color(const Color color) { ___godot_icall_void_Color(___mb.mb_set_default_color, (const Object *) this, color); } void Line2D::set_end_cap_mode(const int64_t mode) { ___godot_icall_void_int(___mb.mb_set_end_cap_mode, (const Object *) this, mode); } void Line2D::set_gradient(const Ref<Gradient> color) { ___godot_icall_void_Object(___mb.mb_set_gradient, (const Object *) this, color.ptr()); } void Line2D::set_joint_mode(const int64_t mode) { ___godot_icall_void_int(___mb.mb_set_joint_mode, (const Object *) this, mode); } void Line2D::set_point_position(const int64_t i, const Vector2 position) { ___godot_icall_void_int_Vector2(___mb.mb_set_point_position, (const Object *) this, i, position); } void Line2D::set_points(const PoolVector2Array points) { ___godot_icall_void_PoolVector2Array(___mb.mb_set_points, (const Object *) this, points); } void Line2D::set_round_precision(const int64_t precision) { ___godot_icall_void_int(___mb.mb_set_round_precision, (const Object *) this, precision); } void Line2D::set_sharp_limit(const real_t limit) { ___godot_icall_void_float(___mb.mb_set_sharp_limit, (const Object *) this, limit); } void Line2D::set_texture(const Ref<Texture> texture) { ___godot_icall_void_Object(___mb.mb_set_texture, (const Object *) this, texture.ptr()); } void Line2D::set_texture_mode(const int64_t mode) { ___godot_icall_void_int(___mb.mb_set_texture_mode, (const Object *) this, mode); } void Line2D::set_width(const real_t width) { ___godot_icall_void_float(___mb.mb_set_width, (const Object *) this, width); } }
43.40201
193
0.789858
GDNative-Gradle
fef3a91fa5e6548ac3b7bd618507c3d8ecbe5d45
38,751
cpp
C++
openstudiocore/src/model/CoilWaterHeatingAirToWaterHeatPump.cpp
jasondegraw/OpenStudio
2ab13f6e5e48940929041444e40ad9d36f80f552
[ "blessing" ]
1
2016-12-29T08:45:03.000Z
2016-12-29T08:45:03.000Z
openstudiocore/src/model/CoilWaterHeatingAirToWaterHeatPump.cpp
jasondegraw/OpenStudio
2ab13f6e5e48940929041444e40ad9d36f80f552
[ "blessing" ]
null
null
null
openstudiocore/src/model/CoilWaterHeatingAirToWaterHeatPump.cpp
jasondegraw/OpenStudio
2ab13f6e5e48940929041444e40ad9d36f80f552
[ "blessing" ]
null
null
null
/********************************************************************** * Copyright (c) 2008-2016, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #include "CoilWaterHeatingAirToWaterHeatPump.hpp" #include "CoilWaterHeatingAirToWaterHeatPump_Impl.hpp" #include "Model.hpp" #include "Model_Impl.hpp" #include "Curve.hpp" #include "Curve_Impl.hpp" #include "CurveBiquadratic.hpp" #include "CurveBiquadratic_Impl.hpp" #include "CurveQuadratic.hpp" #include "CurveQuadratic_Impl.hpp" #include <utilities/idd/IddFactory.hxx> #include <utilities/idd/OS_Coil_WaterHeating_AirToWaterHeatPump_FieldEnums.hxx> #include "../utilities/units/Unit.hpp" #include "../utilities/core/Assert.hpp" namespace openstudio { namespace model { namespace detail { CoilWaterHeatingAirToWaterHeatPump_Impl::CoilWaterHeatingAirToWaterHeatPump_Impl(const IdfObject& idfObject, Model_Impl* model, bool keepHandle) : HVACComponent_Impl(idfObject,model,keepHandle) { OS_ASSERT(idfObject.iddObject().type() == CoilWaterHeatingAirToWaterHeatPump::iddObjectType()); } CoilWaterHeatingAirToWaterHeatPump_Impl::CoilWaterHeatingAirToWaterHeatPump_Impl(const openstudio::detail::WorkspaceObject_Impl& other, Model_Impl* model, bool keepHandle) : HVACComponent_Impl(other,model,keepHandle) { OS_ASSERT(other.iddObject().type() == CoilWaterHeatingAirToWaterHeatPump::iddObjectType()); } CoilWaterHeatingAirToWaterHeatPump_Impl::CoilWaterHeatingAirToWaterHeatPump_Impl(const CoilWaterHeatingAirToWaterHeatPump_Impl& other, Model_Impl* model, bool keepHandle) : HVACComponent_Impl(other,model,keepHandle) {} const std::vector<std::string>& CoilWaterHeatingAirToWaterHeatPump_Impl::outputVariableNames() const { static std::vector<std::string> result; if (result.empty()){ } return result; } IddObjectType CoilWaterHeatingAirToWaterHeatPump_Impl::iddObjectType() const { return CoilWaterHeatingAirToWaterHeatPump::iddObjectType(); } double CoilWaterHeatingAirToWaterHeatPump_Impl::ratedHeatingCapacity() const { boost::optional<double> value = getDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedHeatingCapacity,true); OS_ASSERT(value); return value.get(); } double CoilWaterHeatingAirToWaterHeatPump_Impl::ratedCOP() const { boost::optional<double> value = getDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedCOP,true); OS_ASSERT(value); return value.get(); } double CoilWaterHeatingAirToWaterHeatPump_Impl::ratedSensibleHeatRatio() const { boost::optional<double> value = getDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedSensibleHeatRatio,true); OS_ASSERT(value); return value.get(); } double CoilWaterHeatingAirToWaterHeatPump_Impl::ratedEvaporatorInletAirDryBulbTemperature() const { boost::optional<double> value = getDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedEvaporatorInletAirDryBulbTemperature,true); OS_ASSERT(value); return value.get(); } double CoilWaterHeatingAirToWaterHeatPump_Impl::ratedEvaporatorInletAirWetBulbTemperature() const { boost::optional<double> value = getDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedEvaporatorInletAirWetBulbTemperature,true); OS_ASSERT(value); return value.get(); } double CoilWaterHeatingAirToWaterHeatPump_Impl::ratedCondenserInletWaterTemperature() const { boost::optional<double> value = getDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedCondenserInletWaterTemperature,true); OS_ASSERT(value); return value.get(); } boost::optional<double> CoilWaterHeatingAirToWaterHeatPump_Impl::ratedEvaporatorAirFlowRate() const { return getDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedEvaporatorAirFlowRate,true); } bool CoilWaterHeatingAirToWaterHeatPump_Impl::isRatedEvaporatorAirFlowRateAutosized() const { bool result = false; boost::optional<std::string> value = getString(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedEvaporatorAirFlowRate, true); if (value) { result = openstudio::istringEqual(value.get(), "autosize"); } return result; } boost::optional<double> CoilWaterHeatingAirToWaterHeatPump_Impl::ratedCondenserWaterFlowRate() const { return getDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedCondenserWaterFlowRate,true); } bool CoilWaterHeatingAirToWaterHeatPump_Impl::isRatedCondenserWaterFlowRateAutosized() const { bool result = false; boost::optional<std::string> value = getString(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedCondenserWaterFlowRate, true); if (value) { result = openstudio::istringEqual(value.get(), "autosize"); } return result; } bool CoilWaterHeatingAirToWaterHeatPump_Impl::evaporatorFanPowerIncludedinRatedCOP() const { boost::optional<std::string> value = getString(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::EvaporatorFanPowerIncludedinRatedCOP,true); OS_ASSERT(value); return openstudio::istringEqual(value.get(), "Yes"); } bool CoilWaterHeatingAirToWaterHeatPump_Impl::condenserPumpPowerIncludedinRatedCOP() const { boost::optional<std::string> value = getString(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::CondenserPumpPowerIncludedinRatedCOP,true); OS_ASSERT(value); return openstudio::istringEqual(value.get(), "Yes"); } bool CoilWaterHeatingAirToWaterHeatPump_Impl::condenserPumpHeatIncludedinRatedHeatingCapacityandRatedCOP() const { boost::optional<std::string> value = getString(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::CondenserPumpHeatIncludedinRatedHeatingCapacityandRatedCOP,true); OS_ASSERT(value); return openstudio::istringEqual(value.get(), "Yes"); } double CoilWaterHeatingAirToWaterHeatPump_Impl::condenserWaterPumpPower() const { boost::optional<double> value = getDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::CondenserWaterPumpPower,true); OS_ASSERT(value); return value.get(); } double CoilWaterHeatingAirToWaterHeatPump_Impl::fractionofCondenserPumpHeattoWater() const { boost::optional<double> value = getDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::FractionofCondenserPumpHeattoWater,true); OS_ASSERT(value); return value.get(); } double CoilWaterHeatingAirToWaterHeatPump_Impl::crankcaseHeaterCapacity() const { boost::optional<double> value = getDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::CrankcaseHeaterCapacity,true); OS_ASSERT(value); return value.get(); } double CoilWaterHeatingAirToWaterHeatPump_Impl::maximumAmbientTemperatureforCrankcaseHeaterOperation() const { boost::optional<double> value = getDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::MaximumAmbientTemperatureforCrankcaseHeaterOperation,true); OS_ASSERT(value); return value.get(); } std::string CoilWaterHeatingAirToWaterHeatPump_Impl::evaporatorAirTemperatureTypeforCurveObjects() const { boost::optional<std::string> value = getString(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::EvaporatorAirTemperatureTypeforCurveObjects,true); OS_ASSERT(value); return value.get(); } Curve CoilWaterHeatingAirToWaterHeatPump_Impl::heatingCapacityFunctionofTemperatureCurve() const { boost::optional<Curve> value = optionalHeatingCapacityFunctionofTemperatureCurve(); if (!value) { LOG_AND_THROW(briefDescription() << " does not have an Heating Capacity Functionof Temperature Curve attached."); } return value.get(); } Curve CoilWaterHeatingAirToWaterHeatPump_Impl::heatingCapacityFunctionofAirFlowFractionCurve() const { boost::optional<Curve> value = optionalHeatingCapacityFunctionofAirFlowFractionCurve(); if (!value) { LOG_AND_THROW(briefDescription() << " does not have an Heating Capacity Functionof Air Flow Fraction Curve attached."); } return value.get(); } Curve CoilWaterHeatingAirToWaterHeatPump_Impl::heatingCapacityFunctionofWaterFlowFractionCurve() const { boost::optional<Curve> value = optionalHeatingCapacityFunctionofWaterFlowFractionCurve(); if (!value) { LOG_AND_THROW(briefDescription() << " does not have an Heating Capacity Functionof Water Flow Fraction Curve attached."); } return value.get(); } Curve CoilWaterHeatingAirToWaterHeatPump_Impl::heatingCOPFunctionofTemperatureCurve() const { boost::optional<Curve> value = optionalHeatingCOPFunctionofTemperatureCurve(); if (!value) { LOG_AND_THROW(briefDescription() << " does not have an Heating COPFunctionof Temperature Curve attached."); } return value.get(); } Curve CoilWaterHeatingAirToWaterHeatPump_Impl::heatingCOPFunctionofAirFlowFractionCurve() const { boost::optional<Curve> value = optionalHeatingCOPFunctionofAirFlowFractionCurve(); if (!value) { LOG_AND_THROW(briefDescription() << " does not have an Heating COPFunctionof Air Flow Fraction Curve attached."); } return value.get(); } Curve CoilWaterHeatingAirToWaterHeatPump_Impl::heatingCOPFunctionofWaterFlowFractionCurve() const { boost::optional<Curve> value = optionalHeatingCOPFunctionofWaterFlowFractionCurve(); if (!value) { LOG_AND_THROW(briefDescription() << " does not have an Heating COPFunctionof Water Flow Fraction Curve attached."); } return value.get(); } Curve CoilWaterHeatingAirToWaterHeatPump_Impl::partLoadFractionCorrelationCurve() const { boost::optional<Curve> value = optionalPartLoadFractionCorrelationCurve(); if (!value) { LOG_AND_THROW(briefDescription() << " does not have an Part Load Fraction Correlation Curve attached."); } return value.get(); } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setRatedHeatingCapacity(double ratedHeatingCapacity) { bool result = setDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedHeatingCapacity, ratedHeatingCapacity); return result; } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setRatedCOP(double ratedCOP) { bool result = setDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedCOP, ratedCOP); return result; } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setRatedSensibleHeatRatio(double ratedSensibleHeatRatio) { bool result = setDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedSensibleHeatRatio, ratedSensibleHeatRatio); return result; } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setRatedEvaporatorInletAirDryBulbTemperature(double ratedEvaporatorInletAirDryBulbTemperature) { bool result = setDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedEvaporatorInletAirDryBulbTemperature, ratedEvaporatorInletAirDryBulbTemperature); return result; } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setRatedEvaporatorInletAirWetBulbTemperature(double ratedEvaporatorInletAirWetBulbTemperature) { bool result = setDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedEvaporatorInletAirWetBulbTemperature, ratedEvaporatorInletAirWetBulbTemperature); return result; } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setRatedCondenserInletWaterTemperature(double ratedCondenserInletWaterTemperature) { bool result = setDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedCondenserInletWaterTemperature, ratedCondenserInletWaterTemperature); return result; } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setRatedEvaporatorAirFlowRate(boost::optional<double> ratedEvaporatorAirFlowRate) { bool result(false); if (ratedEvaporatorAirFlowRate) { result = setDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedEvaporatorAirFlowRate, ratedEvaporatorAirFlowRate.get()); } return result; } void CoilWaterHeatingAirToWaterHeatPump_Impl::autosizeRatedEvaporatorAirFlowRate() { bool result = setString(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedEvaporatorAirFlowRate, "autosize"); OS_ASSERT(result); } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setRatedCondenserWaterFlowRate(boost::optional<double> ratedCondenserWaterFlowRate) { bool result(false); if (ratedCondenserWaterFlowRate) { result = setDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedCondenserWaterFlowRate, ratedCondenserWaterFlowRate.get()); } return result; } void CoilWaterHeatingAirToWaterHeatPump_Impl::autosizeRatedCondenserWaterFlowRate() { bool result = setString(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::RatedCondenserWaterFlowRate, "autosize"); OS_ASSERT(result); } void CoilWaterHeatingAirToWaterHeatPump_Impl::setEvaporatorFanPowerIncludedinRatedCOP(bool evaporatorFanPowerIncludedinRatedCOP) { setBooleanFieldValue(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::EvaporatorFanPowerIncludedinRatedCOP, evaporatorFanPowerIncludedinRatedCOP); } void CoilWaterHeatingAirToWaterHeatPump_Impl::setCondenserPumpPowerIncludedinRatedCOP(bool condenserPumpPowerIncludedinRatedCOP) { setBooleanFieldValue(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::CondenserPumpPowerIncludedinRatedCOP, condenserPumpPowerIncludedinRatedCOP); } void CoilWaterHeatingAirToWaterHeatPump_Impl::setCondenserPumpHeatIncludedinRatedHeatingCapacityandRatedCOP(bool condenserPumpHeatIncludedinRatedHeatingCapacityandRatedCOP) { setBooleanFieldValue(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::CondenserPumpHeatIncludedinRatedHeatingCapacityandRatedCOP, condenserPumpHeatIncludedinRatedHeatingCapacityandRatedCOP); } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setCondenserWaterPumpPower(double condenserWaterPumpPower) { bool result = setDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::CondenserWaterPumpPower, condenserWaterPumpPower); return result; } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setFractionofCondenserPumpHeattoWater(double fractionofCondenserPumpHeattoWater) { bool result = setDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::FractionofCondenserPumpHeattoWater, fractionofCondenserPumpHeattoWater); return result; } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setCrankcaseHeaterCapacity(double crankcaseHeaterCapacity) { bool result = setDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::CrankcaseHeaterCapacity, crankcaseHeaterCapacity); return result; } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setMaximumAmbientTemperatureforCrankcaseHeaterOperation(double maximumAmbientTemperatureforCrankcaseHeaterOperation) { bool result = setDouble(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::MaximumAmbientTemperatureforCrankcaseHeaterOperation, maximumAmbientTemperatureforCrankcaseHeaterOperation); return result; } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setEvaporatorAirTemperatureTypeforCurveObjects(std::string evaporatorAirTemperatureTypeforCurveObjects) { bool result = setString(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::EvaporatorAirTemperatureTypeforCurveObjects, evaporatorAirTemperatureTypeforCurveObjects); return result; } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setHeatingCapacityFunctionofTemperatureCurve(const Curve& curve) { bool result = setPointer(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::HeatingCapacityFunctionofTemperatureCurve, curve.handle()); return result; } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setHeatingCapacityFunctionofAirFlowFractionCurve(const Curve& curve) { bool result = setPointer(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::HeatingCapacityFunctionofAirFlowFractionCurve, curve.handle()); return result; } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setHeatingCapacityFunctionofWaterFlowFractionCurve(const Curve& curve) { bool result = setPointer(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::HeatingCapacityFunctionofWaterFlowFractionCurve, curve.handle()); return result; } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setHeatingCOPFunctionofTemperatureCurve(const Curve& curve) { bool result = setPointer(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::HeatingCOPFunctionofTemperatureCurve, curve.handle()); return result; } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setHeatingCOPFunctionofAirFlowFractionCurve(const Curve& curve) { bool result = setPointer(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::HeatingCOPFunctionofAirFlowFractionCurve, curve.handle()); return result; } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setHeatingCOPFunctionofWaterFlowFractionCurve(const Curve& curve) { bool result = setPointer(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::HeatingCOPFunctionofWaterFlowFractionCurve, curve.handle()); return result; } bool CoilWaterHeatingAirToWaterHeatPump_Impl::setPartLoadFractionCorrelationCurve(const Curve& curve) { bool result = setPointer(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::PartLoadFractionCorrelationCurve, curve.handle()); return result; } boost::optional<Curve> CoilWaterHeatingAirToWaterHeatPump_Impl::optionalHeatingCapacityFunctionofTemperatureCurve() const { return getObject<ModelObject>().getModelObjectTarget<Curve>(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::HeatingCapacityFunctionofTemperatureCurve); } boost::optional<Curve> CoilWaterHeatingAirToWaterHeatPump_Impl::optionalHeatingCapacityFunctionofAirFlowFractionCurve() const { return getObject<ModelObject>().getModelObjectTarget<Curve>(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::HeatingCapacityFunctionofAirFlowFractionCurve); } boost::optional<Curve> CoilWaterHeatingAirToWaterHeatPump_Impl::optionalHeatingCapacityFunctionofWaterFlowFractionCurve() const { return getObject<ModelObject>().getModelObjectTarget<Curve>(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::HeatingCapacityFunctionofWaterFlowFractionCurve); } boost::optional<Curve> CoilWaterHeatingAirToWaterHeatPump_Impl::optionalHeatingCOPFunctionofTemperatureCurve() const { return getObject<ModelObject>().getModelObjectTarget<Curve>(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::HeatingCOPFunctionofTemperatureCurve); } boost::optional<Curve> CoilWaterHeatingAirToWaterHeatPump_Impl::optionalHeatingCOPFunctionofAirFlowFractionCurve() const { return getObject<ModelObject>().getModelObjectTarget<Curve>(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::HeatingCOPFunctionofAirFlowFractionCurve); } boost::optional<Curve> CoilWaterHeatingAirToWaterHeatPump_Impl::optionalHeatingCOPFunctionofWaterFlowFractionCurve() const { return getObject<ModelObject>().getModelObjectTarget<Curve>(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::HeatingCOPFunctionofWaterFlowFractionCurve); } boost::optional<Curve> CoilWaterHeatingAirToWaterHeatPump_Impl::optionalPartLoadFractionCorrelationCurve() const { return getObject<ModelObject>().getModelObjectTarget<Curve>(OS_Coil_WaterHeating_AirToWaterHeatPumpFields::PartLoadFractionCorrelationCurve); } ModelObject CoilWaterHeatingAirToWaterHeatPump_Impl::clone(Model model) const { auto newCoil = ModelObject_Impl::clone(model).cast<CoilWaterHeatingAirToWaterHeatPump>(); return newCoil; } std::vector<ModelObject> CoilWaterHeatingAirToWaterHeatPump_Impl::children() const { std::vector<ModelObject> result; result.push_back(heatingCapacityFunctionofTemperatureCurve()); result.push_back(heatingCapacityFunctionofAirFlowFractionCurve()); result.push_back(heatingCapacityFunctionofWaterFlowFractionCurve()); result.push_back(heatingCOPFunctionofTemperatureCurve()); result.push_back(heatingCOPFunctionofAirFlowFractionCurve()); result.push_back(heatingCOPFunctionofWaterFlowFractionCurve()); result.push_back(partLoadFractionCorrelationCurve()); return result; } } // detail CoilWaterHeatingAirToWaterHeatPump::CoilWaterHeatingAirToWaterHeatPump(const Model& model) : HVACComponent(CoilWaterHeatingAirToWaterHeatPump::iddObjectType(),model) { OS_ASSERT(getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()); setRatedHeatingCapacity(4000.0); setRatedCOP(3.2); setRatedSensibleHeatRatio(0.6956); setRatedEvaporatorInletAirDryBulbTemperature(29.44); setRatedEvaporatorInletAirWetBulbTemperature(22.22); setRatedCondenserInletWaterTemperature(55.72); autosizeRatedEvaporatorAirFlowRate(); autosizeRatedCondenserWaterFlowRate(); setEvaporatorFanPowerIncludedinRatedCOP(false); setCondenserPumpPowerIncludedinRatedCOP(false); setCondenserPumpHeatIncludedinRatedHeatingCapacityandRatedCOP(false); setCondenserWaterPumpPower(150.0); setFractionofCondenserPumpHeattoWater(0.1); setCrankcaseHeaterCapacity(100.0); setMaximumAmbientTemperatureforCrankcaseHeaterOperation(5.0); setEvaporatorAirTemperatureTypeforCurveObjects("WetBulbTemperature"); { CurveBiquadratic curve(model); curve.setCoefficient1Constant(0.369827); curve.setCoefficient2x(0.043341); curve.setCoefficient3xPOW2(-0.00023); curve.setCoefficient4y(0.000466); curve.setCoefficient5yPOW2(0.000026); curve.setCoefficient6xTIMESY(-0.00027); curve.setMinimumValueofx(0.0); curve.setMaximumValueofx(40.0); curve.setMinimumValueofy(20.0); curve.setMaximumValueofy(90.0); curve.setInputUnitTypeforX("Temperature"); curve.setInputUnitTypeforY("Temperature"); curve.setOutputUnitType("Dimensionless"); setHeatingCapacityFunctionofTemperatureCurve(curve); } { CurveQuadratic curve(model); curve.setCoefficient1Constant(1.0); curve.setCoefficient2x(0.0); curve.setCoefficient3xPOW2(0.0); curve.setMinimumValueofx(0.0); curve.setMaximumValueofx(1.0); setHeatingCapacityFunctionofAirFlowFractionCurve(curve); } { CurveQuadratic curve(model); curve.setCoefficient1Constant(1.0); curve.setCoefficient2x(0.0); curve.setCoefficient3xPOW2(0.0); curve.setMinimumValueofx(0.0); curve.setMaximumValueofx(1.0); setHeatingCapacityFunctionofWaterFlowFractionCurve(curve); } { CurveBiquadratic curve(model); curve.setCoefficient1Constant(1.19713); curve.setCoefficient2x(0.077849); curve.setCoefficient3xPOW2(-0.0000016); curve.setCoefficient4y(-0.02675); curve.setCoefficient5yPOW2(0.000296); curve.setCoefficient6xTIMESY(-0.00112); curve.setMinimumValueofx(0.0); curve.setMaximumValueofx(40.0); curve.setMinimumValueofy(20.0); curve.setMaximumValueofy(90.0); curve.setInputUnitTypeforX("Temperature"); curve.setInputUnitTypeforY("Temperature"); curve.setOutputUnitType("Dimensionless"); setHeatingCOPFunctionofTemperatureCurve(curve); } { CurveQuadratic curve(model); curve.setCoefficient1Constant(1.0); curve.setCoefficient2x(0.0); curve.setCoefficient3xPOW2(0.0); curve.setMinimumValueofx(0.0); curve.setMaximumValueofx(1.0); setHeatingCOPFunctionofAirFlowFractionCurve(curve); } { CurveQuadratic curve(model); curve.setCoefficient1Constant(1.0); curve.setCoefficient2x(0.0); curve.setCoefficient3xPOW2(0.0); curve.setMinimumValueofx(0.0); curve.setMaximumValueofx(1.0); setHeatingCOPFunctionofWaterFlowFractionCurve(curve); } { CurveQuadratic curve(model); curve.setCoefficient1Constant(0.75); curve.setCoefficient2x(0.25); curve.setCoefficient3xPOW2(0.0); curve.setMinimumValueofx(0.0); curve.setMaximumValueofx(1.0); setPartLoadFractionCorrelationCurve(curve); } } CoilWaterHeatingAirToWaterHeatPump::CoilWaterHeatingAirToWaterHeatPump(const Model& model, Curve & heatingCapacityFunctionofTemperatureCurve, Curve & heatingCapacityFunctionofAirFlowFractionCurve, Curve & heatingCapacityFunctionofWaterFlowFractionCurve, Curve & heatingCOPFunctionofTemperatureCurve, Curve & heatingCOPFunctionofAirFlowFractionCurve, Curve & heatingCOPFunctionofWaterFlowFractionCurve, Curve & partLoadFractionCorrelationCurve) : HVACComponent(CoilWaterHeatingAirToWaterHeatPump::iddObjectType(),model) { OS_ASSERT(getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()); setRatedHeatingCapacity(4000.0); setRatedCOP(3.2); setRatedSensibleHeatRatio(0.6956); setRatedEvaporatorInletAirDryBulbTemperature(29.44); setRatedEvaporatorInletAirWetBulbTemperature(22.22); setRatedCondenserInletWaterTemperature(55.72); autosizeRatedEvaporatorAirFlowRate(); autosizeRatedCondenserWaterFlowRate(); setEvaporatorFanPowerIncludedinRatedCOP(false); setCondenserPumpPowerIncludedinRatedCOP(false); setCondenserPumpHeatIncludedinRatedHeatingCapacityandRatedCOP(false); setCondenserWaterPumpPower(150.0); setFractionofCondenserPumpHeattoWater(0.1); setCrankcaseHeaterCapacity(100.0); setMaximumAmbientTemperatureforCrankcaseHeaterOperation(5.0); setEvaporatorAirTemperatureTypeforCurveObjects("WetBulbTemperature"); setHeatingCapacityFunctionofTemperatureCurve(heatingCapacityFunctionofTemperatureCurve); setHeatingCapacityFunctionofAirFlowFractionCurve(heatingCapacityFunctionofAirFlowFractionCurve); setHeatingCapacityFunctionofWaterFlowFractionCurve(heatingCapacityFunctionofWaterFlowFractionCurve); setHeatingCOPFunctionofTemperatureCurve(heatingCOPFunctionofTemperatureCurve); setHeatingCOPFunctionofAirFlowFractionCurve(heatingCOPFunctionofAirFlowFractionCurve); setHeatingCOPFunctionofWaterFlowFractionCurve(heatingCOPFunctionofWaterFlowFractionCurve); setPartLoadFractionCorrelationCurve(partLoadFractionCorrelationCurve); } IddObjectType CoilWaterHeatingAirToWaterHeatPump::iddObjectType() { return IddObjectType(IddObjectType::OS_Coil_WaterHeating_AirToWaterHeatPump); } std::vector<std::string> CoilWaterHeatingAirToWaterHeatPump::evaporatorAirTemperatureTypeforCurveObjectsValues() { return getIddKeyNames(IddFactory::instance().getObject(iddObjectType()).get(), OS_Coil_WaterHeating_AirToWaterHeatPumpFields::EvaporatorAirTemperatureTypeforCurveObjects); } double CoilWaterHeatingAirToWaterHeatPump::ratedHeatingCapacity() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->ratedHeatingCapacity(); } double CoilWaterHeatingAirToWaterHeatPump::ratedCOP() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->ratedCOP(); } double CoilWaterHeatingAirToWaterHeatPump::ratedSensibleHeatRatio() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->ratedSensibleHeatRatio(); } double CoilWaterHeatingAirToWaterHeatPump::ratedEvaporatorInletAirDryBulbTemperature() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->ratedEvaporatorInletAirDryBulbTemperature(); } double CoilWaterHeatingAirToWaterHeatPump::ratedEvaporatorInletAirWetBulbTemperature() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->ratedEvaporatorInletAirWetBulbTemperature(); } double CoilWaterHeatingAirToWaterHeatPump::ratedCondenserInletWaterTemperature() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->ratedCondenserInletWaterTemperature(); } boost::optional<double> CoilWaterHeatingAirToWaterHeatPump::ratedEvaporatorAirFlowRate() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->ratedEvaporatorAirFlowRate(); } bool CoilWaterHeatingAirToWaterHeatPump::isRatedEvaporatorAirFlowRateAutosized() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->isRatedEvaporatorAirFlowRateAutosized(); } boost::optional<double> CoilWaterHeatingAirToWaterHeatPump::ratedCondenserWaterFlowRate() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->ratedCondenserWaterFlowRate(); } bool CoilWaterHeatingAirToWaterHeatPump::isRatedCondenserWaterFlowRateAutosized() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->isRatedCondenserWaterFlowRateAutosized(); } bool CoilWaterHeatingAirToWaterHeatPump::evaporatorFanPowerIncludedinRatedCOP() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->evaporatorFanPowerIncludedinRatedCOP(); } bool CoilWaterHeatingAirToWaterHeatPump::condenserPumpPowerIncludedinRatedCOP() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->condenserPumpPowerIncludedinRatedCOP(); } bool CoilWaterHeatingAirToWaterHeatPump::condenserPumpHeatIncludedinRatedHeatingCapacityandRatedCOP() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->condenserPumpHeatIncludedinRatedHeatingCapacityandRatedCOP(); } double CoilWaterHeatingAirToWaterHeatPump::condenserWaterPumpPower() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->condenserWaterPumpPower(); } double CoilWaterHeatingAirToWaterHeatPump::fractionofCondenserPumpHeattoWater() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->fractionofCondenserPumpHeattoWater(); } double CoilWaterHeatingAirToWaterHeatPump::crankcaseHeaterCapacity() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->crankcaseHeaterCapacity(); } double CoilWaterHeatingAirToWaterHeatPump::maximumAmbientTemperatureforCrankcaseHeaterOperation() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->maximumAmbientTemperatureforCrankcaseHeaterOperation(); } std::string CoilWaterHeatingAirToWaterHeatPump::evaporatorAirTemperatureTypeforCurveObjects() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->evaporatorAirTemperatureTypeforCurveObjects(); } Curve CoilWaterHeatingAirToWaterHeatPump::heatingCapacityFunctionofTemperatureCurve() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->heatingCapacityFunctionofTemperatureCurve(); } Curve CoilWaterHeatingAirToWaterHeatPump::heatingCapacityFunctionofAirFlowFractionCurve() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->heatingCapacityFunctionofAirFlowFractionCurve(); } Curve CoilWaterHeatingAirToWaterHeatPump::heatingCapacityFunctionofWaterFlowFractionCurve() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->heatingCapacityFunctionofWaterFlowFractionCurve(); } Curve CoilWaterHeatingAirToWaterHeatPump::heatingCOPFunctionofTemperatureCurve() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->heatingCOPFunctionofTemperatureCurve(); } Curve CoilWaterHeatingAirToWaterHeatPump::heatingCOPFunctionofAirFlowFractionCurve() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->heatingCOPFunctionofAirFlowFractionCurve(); } Curve CoilWaterHeatingAirToWaterHeatPump::heatingCOPFunctionofWaterFlowFractionCurve() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->heatingCOPFunctionofWaterFlowFractionCurve(); } Curve CoilWaterHeatingAirToWaterHeatPump::partLoadFractionCorrelationCurve() const { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->partLoadFractionCorrelationCurve(); } bool CoilWaterHeatingAirToWaterHeatPump::setRatedHeatingCapacity(double ratedHeatingCapacity) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setRatedHeatingCapacity(ratedHeatingCapacity); } bool CoilWaterHeatingAirToWaterHeatPump::setRatedCOP(double ratedCOP) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setRatedCOP(ratedCOP); } bool CoilWaterHeatingAirToWaterHeatPump::setRatedSensibleHeatRatio(double ratedSensibleHeatRatio) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setRatedSensibleHeatRatio(ratedSensibleHeatRatio); } bool CoilWaterHeatingAirToWaterHeatPump::setRatedEvaporatorInletAirDryBulbTemperature(double ratedEvaporatorInletAirDryBulbTemperature) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setRatedEvaporatorInletAirDryBulbTemperature(ratedEvaporatorInletAirDryBulbTemperature); } bool CoilWaterHeatingAirToWaterHeatPump::setRatedEvaporatorInletAirWetBulbTemperature(double ratedEvaporatorInletAirWetBulbTemperature) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setRatedEvaporatorInletAirWetBulbTemperature(ratedEvaporatorInletAirWetBulbTemperature); } bool CoilWaterHeatingAirToWaterHeatPump::setRatedCondenserInletWaterTemperature(double ratedCondenserInletWaterTemperature) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setRatedCondenserInletWaterTemperature(ratedCondenserInletWaterTemperature); } bool CoilWaterHeatingAirToWaterHeatPump::setRatedEvaporatorAirFlowRate(double ratedEvaporatorAirFlowRate) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setRatedEvaporatorAirFlowRate(ratedEvaporatorAirFlowRate); } void CoilWaterHeatingAirToWaterHeatPump::autosizeRatedEvaporatorAirFlowRate() { getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->autosizeRatedEvaporatorAirFlowRate(); } bool CoilWaterHeatingAirToWaterHeatPump::setRatedCondenserWaterFlowRate(double ratedCondenserWaterFlowRate) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setRatedCondenserWaterFlowRate(ratedCondenserWaterFlowRate); } void CoilWaterHeatingAirToWaterHeatPump::autosizeRatedCondenserWaterFlowRate() { getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->autosizeRatedCondenserWaterFlowRate(); } void CoilWaterHeatingAirToWaterHeatPump::setEvaporatorFanPowerIncludedinRatedCOP(bool evaporatorFanPowerIncludedinRatedCOP) { getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setEvaporatorFanPowerIncludedinRatedCOP(evaporatorFanPowerIncludedinRatedCOP); } void CoilWaterHeatingAirToWaterHeatPump::setCondenserPumpPowerIncludedinRatedCOP(bool condenserPumpPowerIncludedinRatedCOP) { getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setCondenserPumpPowerIncludedinRatedCOP(condenserPumpPowerIncludedinRatedCOP); } void CoilWaterHeatingAirToWaterHeatPump::setCondenserPumpHeatIncludedinRatedHeatingCapacityandRatedCOP(bool condenserPumpHeatIncludedinRatedHeatingCapacityandRatedCOP) { getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setCondenserPumpHeatIncludedinRatedHeatingCapacityandRatedCOP(condenserPumpHeatIncludedinRatedHeatingCapacityandRatedCOP); } bool CoilWaterHeatingAirToWaterHeatPump::setCondenserWaterPumpPower(double condenserWaterPumpPower) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setCondenserWaterPumpPower(condenserWaterPumpPower); } bool CoilWaterHeatingAirToWaterHeatPump::setFractionofCondenserPumpHeattoWater(double fractionofCondenserPumpHeattoWater) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setFractionofCondenserPumpHeattoWater(fractionofCondenserPumpHeattoWater); } bool CoilWaterHeatingAirToWaterHeatPump::setCrankcaseHeaterCapacity(double crankcaseHeaterCapacity) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setCrankcaseHeaterCapacity(crankcaseHeaterCapacity); } bool CoilWaterHeatingAirToWaterHeatPump::setMaximumAmbientTemperatureforCrankcaseHeaterOperation(double maximumAmbientTemperatureforCrankcaseHeaterOperation) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setMaximumAmbientTemperatureforCrankcaseHeaterOperation(maximumAmbientTemperatureforCrankcaseHeaterOperation); } bool CoilWaterHeatingAirToWaterHeatPump::setEvaporatorAirTemperatureTypeforCurveObjects(std::string evaporatorAirTemperatureTypeforCurveObjects) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setEvaporatorAirTemperatureTypeforCurveObjects(evaporatorAirTemperatureTypeforCurveObjects); } bool CoilWaterHeatingAirToWaterHeatPump::setHeatingCapacityFunctionofTemperatureCurve(const Curve& curve) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setHeatingCapacityFunctionofTemperatureCurve(curve); } bool CoilWaterHeatingAirToWaterHeatPump::setHeatingCapacityFunctionofAirFlowFractionCurve(const Curve& curve) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setHeatingCapacityFunctionofAirFlowFractionCurve(curve); } bool CoilWaterHeatingAirToWaterHeatPump::setHeatingCapacityFunctionofWaterFlowFractionCurve(const Curve& curve) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setHeatingCapacityFunctionofWaterFlowFractionCurve(curve); } bool CoilWaterHeatingAirToWaterHeatPump::setHeatingCOPFunctionofTemperatureCurve(const Curve& curve) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setHeatingCOPFunctionofTemperatureCurve(curve); } bool CoilWaterHeatingAirToWaterHeatPump::setHeatingCOPFunctionofAirFlowFractionCurve(const Curve& curve) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setHeatingCOPFunctionofAirFlowFractionCurve(curve); } bool CoilWaterHeatingAirToWaterHeatPump::setHeatingCOPFunctionofWaterFlowFractionCurve(const Curve& curve) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setHeatingCOPFunctionofWaterFlowFractionCurve(curve); } bool CoilWaterHeatingAirToWaterHeatPump::setPartLoadFractionCorrelationCurve(const Curve& curve) { return getImpl<detail::CoilWaterHeatingAirToWaterHeatPump_Impl>()->setPartLoadFractionCorrelationCurve(curve); } /// @cond CoilWaterHeatingAirToWaterHeatPump::CoilWaterHeatingAirToWaterHeatPump(std::shared_ptr<detail::CoilWaterHeatingAirToWaterHeatPump_Impl> impl) : HVACComponent(impl) {} /// @endcond } // model } // openstudio
49.301527
192
0.820779
jasondegraw
fef4987df264d2777297d68fb45de9c3eba67905
723
cpp
C++
src/log.cpp
vzwGrey/filter-magic
59e3ccc238716ab4b1b1b3ae560021e558f6718a
[ "MIT" ]
5
2018-08-16T16:51:16.000Z
2018-09-09T08:35:21.000Z
src/log.cpp
vzwGrey/filter-magic
59e3ccc238716ab4b1b1b3ae560021e558f6718a
[ "MIT" ]
null
null
null
src/log.cpp
vzwGrey/filter-magic
59e3ccc238716ab4b1b1b3ae560021e558f6718a
[ "MIT" ]
1
2018-10-08T03:30:12.000Z
2018-10-08T03:30:12.000Z
#include <string> #include <sstream> #include <iostream> #include "log.h" using std::string; using std::stringstream; void log::info(string message) { std::cout << "\e[0;32m[INFO]\e[0m - " << message << std::endl; } void log::error(string name, string message) { std::cerr << "\e[0;31m" << name << ":\e[0m " << message << std::endl; } void log::fatal(string name, string message) { stringstream err_name; err_name << "Fatal - " << name; log::error(err_name.str(), message); exit(1); } void log::missing_argument(string command, string parameter) { stringstream message; message << "Command `" << command << "' expects an argument of `" << parameter << "'."; log::fatal("Missing Argument", message.str()); }
23.322581
88
0.64592
vzwGrey
fef4d4554f28b3db44bc9ab02d52776b079892de
15,885
cpp
C++
tools/extras/irstlm/src/ngt.cpp
scscscscscsc/kaldi-trunk
aa9a8143e0fee12d85562ccc1d06e0e99f630029
[ "Apache-2.0" ]
4
2016-06-05T14:19:32.000Z
2016-06-07T09:21:10.000Z
tools/extras/irstlm/src/ngt.cpp
MistSC/kaldi-trunk
aa9a8143e0fee12d85562ccc1d06e0e99f630029
[ "Apache-2.0" ]
null
null
null
tools/extras/irstlm/src/ngt.cpp
MistSC/kaldi-trunk
aa9a8143e0fee12d85562ccc1d06e0e99f630029
[ "Apache-2.0" ]
null
null
null
// $Id: ngt.cpp 245 2009-04-02 14:05:40Z fabio_brugnara $ /****************************************************************************** IrstLM: IRST Language Model Toolkit Copyright (C) 2006 Marcello Federico, ITC-irst Trento, Italy This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ******************************************************************************/ // ngt // by M. Federico // Copyright Marcello Federico, ITC-irst, 1998 #include <iostream> #include <sstream> #include <cmath> #include "util.h" #include "cmd.h" #include "mfstream.h" #include "mempool.h" #include "htable.h" #include "dictionary.h" #include "n_gram.h" #include "ngramtable.h" using namespace std; void print_help(int TypeFlag=0){ std::cerr << std::endl << "ngt - collects n-grams" << std::endl; std::cerr << std::endl << "USAGE:" << std::endl; std::cerr << " ngt -i=<inputfile> [options]" << std::endl; std::cerr << std::endl << "OPTIONS:" << std::endl; FullPrintParams(TypeFlag, 0, 1, stderr); } void usage(const char *msg = 0) { if (msg){ std::cerr << msg << std::endl; } else{ print_help(); } } int main(int argc, char **argv) { char *inp=NULL; char *out=NULL; char *dic=NULL; // dictionary filename char *subdic=NULL; // subdictionary filename char *filterdict=NULL; // subdictionary filename char *filtertable=NULL; // ngramtable filename char *iknfile=NULL; // filename to save IKN statistics double filter_hit_rate=1.0; // minimum hit rate of filter char *aug=NULL; // augmentation data char *hmask=NULL; // historymask bool inputgoogleformat=false; //reads ngrams in Google format bool outputgoogleformat=false; //print ngrams in Google format int ngsz=0; // n-gram default size int dstco=0; // compute distance co-occurrences bool bin=false; bool ss=false; //generate single table bool LMflag=false; //work with LM table int inplen=0; //input length for mask generation bool tlm=false; //test lm table char* ftlm=NULL; //file to test LM table bool memuse=false; bool help=false; DeclareParams((char*) "Dictionary", CMDSTRINGTYPE|CMDMSG, &dic, "dictionary filename", "d", CMDSTRINGTYPE|CMDMSG, &dic, "dictionary filename", "NgramSize", CMDSUBRANGETYPE|CMDMSG, &ngsz, 1, MAX_NGRAM, "n-gram default size; default is 0", "n", CMDSUBRANGETYPE|CMDMSG, &ngsz, 1, MAX_NGRAM, "n-gram default size; default is 0", "InputFile", CMDSTRINGTYPE|CMDMSG, &inp, "input file", "i", CMDSTRINGTYPE|CMDMSG, &inp, "input file", "OutputFile", CMDSTRINGTYPE|CMDMSG, &out, "output file", "o", CMDSTRINGTYPE|CMDMSG, &out, "output file", "InputGoogleFormat", CMDBOOLTYPE|CMDMSG, &inputgoogleformat, "the input file contains data in the n-gram Google format; default is false", "gooinp", CMDBOOLTYPE|CMDMSG, &inputgoogleformat, "the input file contains data in the n-gram Google format; default is false", "OutputGoogleFormat", CMDBOOLTYPE|CMDMSG, &outputgoogleformat, "the output file contains data in the n-gram Google format; default is false", "gooout", CMDBOOLTYPE|CMDMSG, &outputgoogleformat, "the output file contains data in the n-gram Google format; default is false", "SaveBinaryTable", CMDBOOLTYPE|CMDMSG, &bin, "saves into binary format; default is false", "b", CMDBOOLTYPE|CMDMSG, &bin, "saves into binary format; default is false", "LmTable", CMDBOOLTYPE|CMDMSG, &LMflag, "works with LM table; default is false", "lm", CMDBOOLTYPE|CMDMSG, &LMflag, "works with LM table; default is false", "DistCo", CMDINTTYPE|CMDMSG, &dstco, "computes distance co-occurrences at the specified distance; default is 0", "dc", CMDINTTYPE|CMDMSG, &dstco, "computes distance co-occurrences at the specified distance; default is 0", "AugmentFile", CMDSTRINGTYPE|CMDMSG, &aug, "augmentation data", "aug", CMDSTRINGTYPE|CMDMSG, &aug, "augmentation data", "SaveSingle", CMDBOOLTYPE|CMDMSG, &ss, "generates single table; default is false", "ss", CMDBOOLTYPE|CMDMSG, &ss, "generates single table; default is false", "SubDict", CMDSTRINGTYPE|CMDMSG, &subdic, "subdictionary", "sd", CMDSTRINGTYPE|CMDMSG, &subdic, "subdictionary", "FilterDict", CMDSTRINGTYPE|CMDMSG, &filterdict, "filter dictionary", "fd", CMDSTRINGTYPE|CMDMSG, &filterdict, "filter dictionary", "ConvDict", CMDSTRINGTYPE|CMDMSG, &subdic, "subdictionary", "cd", CMDSTRINGTYPE|CMDMSG, &subdic, "subdictionary", "FilterTable", CMDSTRINGTYPE|CMDMSG, &filtertable, "ngramtable filename", "ftr", CMDDOUBLETYPE|CMDMSG, &filter_hit_rate, "ngramtable filename", "FilterTableRate", CMDDOUBLETYPE|CMDMSG, &filter_hit_rate, "minimum hit rate of filter; default is 1.0", "ft", CMDSTRINGTYPE|CMDMSG, &filtertable, "minimum hit rate of filter; default is 1.0", "HistoMask",CMDSTRINGTYPE|CMDMSG, &hmask, "history mask", "hm",CMDSTRINGTYPE|CMDMSG, &hmask, "history mask", "InpLen",CMDINTTYPE|CMDMSG, &inplen, "input length for mask generation; default is 0", "il",CMDINTTYPE|CMDMSG, &inplen, "input length for mask generation; default is 0", "tlm", CMDBOOLTYPE|CMDMSG, &tlm, "test LM table; default is false", "ftlm", CMDSTRINGTYPE|CMDMSG, &ftlm, "file to test LM table", "memuse", CMDBOOLTYPE|CMDMSG, &memuse, "default is false", "iknstat", CMDSTRINGTYPE|CMDMSG, &iknfile, "filename to save IKN statistics", "Help", CMDBOOLTYPE|CMDMSG, &help, "print this help", "h", CMDBOOLTYPE|CMDMSG, &help, "print this help", (char *)NULL ); if (argc == 1){ usage(); exit_error(IRSTLM_NO_ERROR); } GetParams(&argc, &argv, (char*) NULL); if (help){ usage(); exit_error(IRSTLM_NO_ERROR); } if (inp==NULL) { usage(); exit_error(IRSTLM_ERROR_DATA,"Warning: no input file specified"); }; if (out==NULL) { cerr << "Warning: no output file specified!\n"; } TABLETYPE table_type=COUNT; if (LMflag) { cerr << "Working with LM table\n"; table_type=LEAFPROB; } // check word order of subdictionary if (filtertable) { { ngramtable ngt(filtertable,1,NULL,NULL,NULL,0,0,NULL,0,table_type); mfstream inpstream(inp,ios::in); //google input table mfstream outstream(out,ios::out); //google output table cerr << "Filtering table " << inp << " assumed to be in Google Format with size " << ngsz << "\n"; cerr << "with table " << filtertable << " of size " << ngt.maxlevel() << "\n"; cerr << "with hit rate " << filter_hit_rate << "\n"; //order of filter table must be smaller than that of input n-grams assert(ngt.maxlevel() <= ngsz); //read input googletable of ngrams of size ngsz //output entries made of at least X% n-grams contained in filtertable //<unk> words are not accepted ngram ng(ngt.dict), ng2(ng.dict); double hits=0; double maxhits=(double)(ngsz-ngt.maxlevel()+1); long c=0; while(inpstream >> ng) { if (ng.size>= ngt.maxlevel()) { //need to make a copy ng2=ng; ng2.size=ngt.maxlevel(); //cerr << "check if " << ng2 << " is contained: "; hits+=(ngt.get(ng2)?1:0); } if (ng.size==ngsz) { if (!(++c % 1000000)) cerr << "."; //cerr << ng << " -> " << is_included << "\n"; //you reached the last word before freq inpstream >> ng.freq; //consistency check of n-gram if (((hits/maxhits)>=filter_hit_rate) && (!ng.containsWord(ngt.dict->OOV(),ng.size)) ) outstream << ng << "\n"; hits=0; ng.size=0; } } outstream.flush(); inpstream.flush(); } exit_error(IRSTLM_NO_ERROR); } //ngramtable* ngt=new ngramtable(inp,ngsz,NULL,dic,dstco,hmask,inplen,table_type); ngramtable* ngt=new ngramtable(inp,ngsz,NULL,NULL,filterdict,inputgoogleformat,dstco,hmask,inplen,table_type); if (aug) { ngt->dict->incflag(1); // ngramtable ngt2(aug,ngsz,isym,NULL,0,NULL,0,table_type); ngramtable ngt2(aug,ngsz,NULL,NULL,NULL,0,0,NULL,0,table_type); ngt->augment(&ngt2); ngt->dict->incflag(0); } if (subdic) { ngramtable *ngt2=new ngramtable(NULL,ngsz,NULL,NULL,NULL,0,0,NULL,0,table_type); // enforce the subdict to follow the same word order of the main dictionary dictionary tmpdict(subdic); ngt2->dict->incflag(1); for (int j=0; j<ngt->dict->size(); j++) { if (tmpdict.encode(ngt->dict->decode(j)) != tmpdict.oovcode()) { ngt2->dict->encode(ngt->dict->decode(j)); } } ngt2->dict->incflag(0); ngt2->dict->cleanfreq(); //possibly include standard symbols if (ngt->dict->encode(ngt->dict->EoS())!=ngt->dict->oovcode()) { ngt2->dict->incflag(1); ngt2->dict->encode(ngt2->dict->EoS()); ngt2->dict->incflag(0); } if (ngt->dict->encode(ngt->dict->BoS())!=ngt->dict->oovcode()) { ngt2->dict->incflag(1); ngt2->dict->encode(ngt2->dict->BoS()); ngt2->dict->incflag(0); } ngram ng(ngt->dict); ngram ng2(ngt2->dict); ngt->scan(ng,INIT,ngsz); long c=0; while (ngt->scan(ng,CONT,ngsz)) { ng2.trans(ng); ngt2->put(ng2); if (!(++c % 1000000)) cerr << "."; } //makes ngt2 aware of oov code int oov=ngt2->dict->getcode(ngt2->dict->OOV()); if(oov>=0) ngt2->dict->oovcode(oov); for (int j=0; j<ngt->dict->size(); j++) { ngt2->dict->incfreq(ngt2->dict->encode(ngt->dict->decode(j)), ngt->dict->freq(j)); } cerr <<" oov: " << ngt2->dict->freq(ngt2->dict->oovcode()) << "\n"; delete ngt; ngt=ngt2; } if (ngsz < ngt->maxlevel() && hmask) { cerr << "start projection of ngramtable " << inp << " according to hmask\n"; int selmask[MAX_NGRAM]; memset(selmask, 0, sizeof(int)*MAX_NGRAM); //parse hmask selmask[0]=1; int i=1; for (size_t c=0; c<strlen(hmask); c++) { cerr << hmask[c] << "\n"; if (hmask[c] == '1'){ selmask[i]=c+2; i++; } } if (i!= ngsz) { std::stringstream ss_msg; ss_msg << "wrong mask: 1 bits=" << i << " maxlev=" << ngsz; exit_error(IRSTLM_ERROR_DATA, ss_msg.str()); } if (selmask[ngsz-1] > ngt->maxlevel()) { std::stringstream ss_msg; ss_msg << "wrong mask: farest bits=" << selmask[ngsz-1] << " maxlev=" << ngt->maxlevel() << "\n"; exit_error(IRSTLM_ERROR_DATA, ss_msg.str()); } //ngramtable* ngt2=new ngramtable(NULL,ngsz,NULL,NULL,0,NULL,0,table_type); ngramtable* ngt2=new ngramtable(NULL,ngsz,NULL,NULL,NULL,0,0,NULL,0,table_type); ngt2->dict->incflag(1); ngram ng(ngt->dict); ngram png(ngt->dict,ngsz); ngram ng2(ngt2->dict,ngsz); ngt->scan(ng,INIT,ngt->maxlevel()); long c=0; while (ngt->scan(ng,CONT,ngt->maxlevel())) { //projection for (int j=0; j<ngsz; j++) *png.wordp(j+1)=*ng.wordp(selmask[j]); png.freq=ng.freq; //transfer ng2.trans(png); ngt2->put(ng2); if (!(++c % 1000000)) cerr << "."; } char info[100]; sprintf(info,"hm%s",hmask); ngt2->ngtype(info); //makes ngt2 aware of oov code int oov=ngt2->dict->getcode(ngt2->dict->OOV()); if(oov>=0) ngt2->dict->oovcode(oov); for (int j=0; j<ngt->dict->size(); j++) { ngt2->dict->incfreq(ngt2->dict->encode(ngt->dict->decode(j)), ngt->dict->freq(j)); } cerr <<" oov: " << ngt2->dict->freq(ngt2->dict->oovcode()) << "\n"; delete ngt; ngt=ngt2; } if (tlm && table_type==LEAFPROB) { ngram ng(ngt->dict); cout.setf(ios::scientific); cout << "> "; while(cin >> ng) { ngt->bo_state(0); if (ng.size>=ngsz) { cout << ng << " p= " << log(ngt->prob(ng)); cout << " bo= " << ngt->bo_state() << "\n"; } else cout << ng << " p= NULL\n"; cout << "> "; } } if (ftlm && table_type==LEAFPROB) { ngram ng(ngt->dict); cout.setf(ios::fixed); cout.precision(2); mfstream inptxt(ftlm,ios::in); int Nbo=0,Nw=0,Noov=0; float logPr=0,PP=0,PPwp=0; int bos=ng.dict->encode(ng.dict->BoS()); while(inptxt >> ng) { // reset ngram at begin of sentence if (*ng.wordp(1)==bos) { ng.size=1; continue; } ngt->bo_state(0); if (ng.size>=1) { logPr+=log(ngt->prob(ng)); if (*ng.wordp(1) == ngt->dict->oovcode()) Noov++; Nw++; if (ngt->bo_state()) Nbo++; } } PP=exp(-logPr/Nw); PPwp= PP * exp(Noov * log(10000000.0-ngt->dict->size())/Nw); cout << "%%% NGT TEST OF SMT LM\n"; cout << "%% LM=" << inp << " SIZE="<< ngt->maxlevel(); cout << " TestFile="<< ftlm << "\n"; cout << "%% OOV PENALTY = 1/" << 10000000.0-ngt->dict->size() << "\n"; cout << "%% Nw=" << Nw << " PP=" << PP << " PPwp=" << PPwp << " Nbo=" << Nbo << " Noov=" << Noov << " OOV=" << (float)Noov/Nw * 100.0 << "%\n"; } if (memuse) ngt->stat(0); if (iknfile) { //compute and save statistics of Improved Kneser Ney smoothing ngram ng(ngt->dict); int n1,n2,n3,n4; int unover3=0; mfstream iknstat(iknfile,ios::out); //output of ikn statistics for (int l=1; l<=ngt->maxlevel(); l++) { cerr << "level " << l << "\n"; iknstat << "level: " << l << " "; cerr << "computing statistics\n"; n1=0; n2=0; n3=0,n4=0; ngt->scan(ng,INIT,l); while(ngt->scan(ng,CONT,l)) { //skip ngrams containing _OOV if (l>1 && ng.containsWord(ngt->dict->OOV(),l)) { //cerr << "skp ngram" << ng << "\n"; continue; } //skip n-grams containing </s> in context if (l>1 && ng.containsWord(ngt->dict->EoS(),l-1)) { //cerr << "skp ngram" << ng << "\n"; continue; } //skip 1-grams containing <s> if (l==1 && ng.containsWord(ngt->dict->BoS(),l)) { //cerr << "skp ngram" << ng << "\n"; continue; } if (ng.freq==1) n1++; else if (ng.freq==2) n2++; else if (ng.freq==3) n3++; else if (ng.freq==4) n4++; if (l==1 && ng.freq >=3) unover3++; } cerr << " n1: " << n1 << " n2: " << n2 << " n3: " << n3 << " n4: " << n4 << "\n"; iknstat << " n1: " << n1 << " n2: " << n2 << " n3: " << n3 << " n4: " << n4 << " unover3: " << unover3 << "\n"; } } if (out) bin?ngt->savebin(out,ngsz): ngt->savetxt(out,ngsz,outputgoogleformat); }
31.961771
158
0.568398
scscscscscsc
67929a6fac94dc82d84a35be1d35711827556229
583
hpp
C++
cmdstan/stan/lib/stan_math/stan/math/fwd/scal/fun/trunc.hpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
cmdstan/stan/lib/stan_math/stan/math/fwd/scal/fun/trunc.hpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
cmdstan/stan/lib/stan_math/stan/math/fwd/scal/fun/trunc.hpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
#ifndef STAN_MATH_FWD_SCAL_FUN_TRUNC_HPP #define STAN_MATH_FWD_SCAL_FUN_TRUNC_HPP #include <stan/math/fwd/core.hpp> #include <stan/math/prim/scal/fun/trunc.hpp> namespace stan { namespace math { /** * Return the nearest integral value that is not larger in * magnitude than the specified argument. * * @tparam T Scalar type of autodiff variable. * @param[in] x Argument. * @return The truncated argument. */ template <typename T> inline fvar<T> trunc(const fvar<T>& x) { return fvar<T>(trunc(x.val_), 0); } } } #endif
22.423077
62
0.665523
yizhang-cae
6792e6f1333d5ddd8158c66833fb966f163692a7
1,684
cpp
C++
tests/test_constructors.cpp
IvanPleshkov/compact_vector
b6eba48e6520acef53139133f4503e3603560acd
[ "MIT" ]
1
2017-12-20T11:17:40.000Z
2017-12-20T11:17:40.000Z
tests/test_constructors.cpp
IvanPleshkov/compact_vector
b6eba48e6520acef53139133f4503e3603560acd
[ "MIT" ]
null
null
null
tests/test_constructors.cpp
IvanPleshkov/compact_vector
b6eba48e6520acef53139133f4503e3603560acd
[ "MIT" ]
null
null
null
#include "tests_runner.h" #include "../compact_vector.h" std::string test_string = "hello_world_hello_world_hello_world_hello_world"; COMPACT_VECTOR_TEST(constructor_1) { compact_vector<uint8_t> vector(10); } COMPACT_VECTOR_TEST(constructor_2) { compact_vector<uint8_t> vector(100); } COMPACT_VECTOR_TEST(constructor_3) { uint8_t default_value = 100; size_t size = 10; compact_vector<uint8_t> vector(size, default_value); COMPACT_VECTOR_ASSERT(vector.size() == size); for (int i = 0; i < vector.size(); i++) COMPACT_VECTOR_ASSERT(vector.at(i) == default_value); } COMPACT_VECTOR_TEST(constructor_4) { uint8_t default_value = 100; size_t size = 100; compact_vector<uint8_t> vector(size, default_value); auto t = vector.size(); COMPACT_VECTOR_ASSERT(vector.size() == size); for (int i = 0; i < vector.size(); i++) COMPACT_VECTOR_ASSERT(vector.at(i) == default_value); } COMPACT_VECTOR_TEST(constructor_5) { compact_vector<std::string, 10> vector(10); } COMPACT_VECTOR_TEST(constructor_6) { compact_vector<std::string, 10> vector(100); } COMPACT_VECTOR_TEST(constructor_7) { size_t size = 10; compact_vector<std::string, 10> vector(size, test_string); COMPACT_VECTOR_ASSERT(vector.size() == size); for (int i = 0; i < vector.size(); i++) COMPACT_VECTOR_ASSERT(vector.at(i) == test_string); } COMPACT_VECTOR_TEST(constructor_8) { size_t size = 100; compact_vector<std::string, 10> vector(size, test_string); auto t = vector.size(); COMPACT_VECTOR_ASSERT(vector.size() == size); for (int i = 0; i < vector.size(); i++) COMPACT_VECTOR_ASSERT(vector.at(i) == test_string); } COMPACT_VECTOR_TEST(constructor_end) { throw new std::exception(); }
22.756757
76
0.735748
IvanPleshkov
6793a3651e37ce20a965b39f9266372777880584
248
cc
C++
squid/squid3-3.3.8.spaceify/src/auth/CredentialState.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
4
2015-01-20T15:25:34.000Z
2017-12-20T06:47:42.000Z
squid/squid3-3.3.8.spaceify/src/auth/CredentialState.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
4
2015-05-15T09:32:55.000Z
2016-02-18T13:43:31.000Z
squid/squid3-3.3.8.spaceify/src/auth/CredentialState.cc
spaceify/spaceify
4296d6c93cad32bb735cefc9b8157570f18ffee4
[ "MIT" ]
null
null
null
/* * Auto-Generated File. Changes will be destroyed. */ #include "squid.h" #include "auth/CredentialState.h" namespace Auth { const char *CredentialState_str[] = { "Unchecked", "Ok", "Pending", "Handshake", "Failed" }; }; // namespace Auth
14.588235
50
0.669355
spaceify
6793e0664bb299b08132a2c4a966e06cced0aeaa
7,713
cpp
C++
newton-4.00/sdk/dCollision/ndShapeStaticMesh.cpp
MADEAPPS/newton-dynamics
e346eec9d19ffb1c995b09417400167d3c52a635
[ "Zlib" ]
1,031
2015-01-02T14:08:47.000Z
2022-03-29T02:25:27.000Z
newton-4.00/sdk/dCollision/ndShapeStaticMesh.cpp
MADEAPPS/newton-dynamics
e346eec9d19ffb1c995b09417400167d3c52a635
[ "Zlib" ]
240
2015-01-11T04:27:19.000Z
2022-03-30T00:35:57.000Z
newton-4.00/sdk/dCollision/ndShapeStaticMesh.cpp
MADEAPPS/newton-dynamics
e346eec9d19ffb1c995b09417400167d3c52a635
[ "Zlib" ]
224
2015-01-05T06:13:54.000Z
2022-02-25T14:39:51.000Z
/* Copyright (c) <2003-2021> <Julio Jerez, Newton Game Dynamics> * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. */ #include "dCoreStdafx.h" #include "ndCollisionStdafx.h" #include "ndShapeInstance.h" #include "ndContactSolver.h" #include "ndCollisionStdafx.h" #include "ndShapeStaticMesh.h" D_CLASS_REFLECTION_IMPLEMENT_LOADER(ndShapeStaticMesh) void ndPolygonMeshDesc::SortFaceArray() { dInt32 stride = 8; if (m_faceCount >= 8) { dInt32 stack[D_MAX_COLLIDING_FACES][2]; stack[0][0] = 0; stack[0][1] = m_faceCount - 1; dInt32 stackIndex = 1; while (stackIndex) { stackIndex--; dInt32 lo = stack[stackIndex][0]; dInt32 hi = stack[stackIndex][1]; if ((hi - lo) > stride) { dInt32 i = lo; dInt32 j = hi; dFloat32 dist = m_hitDistance[(lo + hi) >> 1]; do { while (m_hitDistance[i] < dist) i++; while (m_hitDistance[j] > dist) j--; if (i <= j) { dSwap(m_hitDistance[i], m_hitDistance[j]); dSwap(m_faceIndexStart[i], m_faceIndexStart[j]); dSwap(m_faceIndexCount[i], m_faceIndexCount[j]); i++; j--; } } while (i <= j); if (i < hi) { stack[stackIndex][0] = i; stack[stackIndex][1] = hi; stackIndex++; } if (lo < j) { stack[stackIndex][0] = lo; stack[stackIndex][1] = j; stackIndex++; } dAssert(stackIndex < dInt32(sizeof(stack) / (2 * sizeof(stack[0][0])))); } } } stride = stride * 2; if (m_faceCount < stride) { stride = m_faceCount; } for (dInt32 i = 1; i < stride; i++) { if (m_hitDistance[i] < m_hitDistance[0]) { dSwap(m_hitDistance[i], m_hitDistance[0]); dSwap(m_faceIndexStart[i], m_faceIndexStart[0]); dSwap(m_faceIndexCount[i], m_faceIndexCount[0]); } } for (dInt32 i = 1; i < m_faceCount; i++) { dInt32 j = i; dInt32 ptr = m_faceIndexStart[i]; dInt32 count = m_faceIndexCount[i]; dFloat32 dist = m_hitDistance[i]; for (; dist < m_hitDistance[j - 1]; j--) { dAssert(j > 0); m_hitDistance[j] = m_hitDistance[j - 1]; m_faceIndexStart[j] = m_faceIndexStart[j - 1]; m_faceIndexCount[j] = m_faceIndexCount[j - 1]; } m_hitDistance[j] = dist; m_faceIndexStart[j] = ptr; m_faceIndexCount[j] = count; } #ifdef _DEBUG for (dInt32 i = 0; i < m_faceCount - 1; i++) { dAssert(m_hitDistance[i] <= m_hitDistance[i + 1]); } #endif } ndPolygonMeshDesc::ndPolygonMeshDesc(ndContactSolver& proxy, bool ccdMode) :dFastAabb() ,m_boxDistanceTravelInMeshSpace(dVector::m_zero) ,m_faceCount(0) ,m_vertexStrideInBytes(0) ,m_skinThickness(proxy.m_skinThickness) ,m_convexInstance(&proxy.m_instance0) ,m_polySoupInstance(&proxy.m_instance1) ,m_vertex(nullptr) ,m_faceIndexCount(nullptr) ,m_faceVertexIndex(nullptr) ,m_faceIndexStart(nullptr) ,m_hitDistance(nullptr) ,m_maxT(dFloat32 (1.0f)) ,m_doContinuesCollisionTest(ccdMode) { const dMatrix& hullMatrix = m_convexInstance->GetGlobalMatrix(); const dMatrix& soupMatrix = m_polySoupInstance->GetGlobalMatrix(); dMatrix& matrix = *this; matrix = hullMatrix * soupMatrix.Inverse(); dMatrix convexMatrix (dGetIdentityMatrix()); switch (m_polySoupInstance->GetScaleType()) { case ndShapeInstance::m_unit: { break; } case ndShapeInstance::m_uniform: { const dVector& invScale = m_polySoupInstance->GetInvScale(); convexMatrix[0][0] = invScale.GetScalar(); convexMatrix[1][1] = invScale.GetScalar(); convexMatrix[2][2] = invScale.GetScalar(); matrix.m_posit = matrix.m_posit * (invScale | dVector::m_wOne); break; } case ndShapeInstance::m_nonUniform: { const dVector& invScale = m_polySoupInstance->GetInvScale(); dMatrix tmp (matrix[0] * invScale, matrix[1] * invScale, matrix[2] * invScale, dVector::m_wOne); convexMatrix = tmp * matrix.Inverse(); convexMatrix.m_posit = dVector::m_wOne; matrix.m_posit = matrix.m_posit * (invScale | dVector::m_wOne); break; } case ndShapeInstance::m_global: default: { dAssert (0); } } dMatrix fullMatrix (convexMatrix * matrix); m_convexInstance->CalculateAabb(fullMatrix, m_p0, m_p1); dVector p0; dVector p1; SetTransposeAbsMatrix(matrix); m_convexInstance->CalculateAabb(convexMatrix, p0, p1); m_size = dVector::m_half * (p1 - p0); m_posit = matrix.TransformVector(dVector::m_half * (p1 + p0)); dAssert (m_posit.m_w == dFloat32 (1.0f)); } ndShapeStaticMesh::ndShapeStaticMesh(ndShapeID id) :ndShape(id) { } ndShapeStaticMesh::ndShapeStaticMesh(const dLoadSaveBase::dLoadDescriptor&) :ndShape(m_staticMesh) { } ndShapeStaticMesh::~ndShapeStaticMesh() { } void ndShapeStaticMesh::CalculateAabb(const dMatrix& matrix, dVector &p0, dVector &p1) const { dVector origin(matrix.TransformVector(m_boxOrigin)); dVector size(matrix.m_front.Abs().Scale(m_boxSize.m_x) + matrix.m_up.Abs().Scale(m_boxSize.m_y) + matrix.m_right.Abs().Scale(m_boxSize.m_z)); p0 = (origin - size) & dVector::m_triplexMask; p1 = (origin + size) & dVector::m_triplexMask; } //dInt32 ndShapeStaticMesh::CalculatePlaneIntersection(const dFloat32* const vertex, const dInt32* const index, dInt32 indexCount, dInt32 stride, const dPlane& localPlane, dVector* const contactsOut) const dInt32 ndShapeStaticMesh::CalculatePlaneIntersection(const dFloat32* const, const dInt32* const, dInt32, dInt32, const dPlane&, dVector* const) const { dAssert(0); return 0; //dInt32 count = 0; //dInt32 j = index[indexCount - 1] * stride; //dVector p0(&vertex[j]); //p0 = p0 & dVector::m_triplexMask; //dFloat32 side0 = localPlane.Evalue(p0); //for (dInt32 i = 0; i < indexCount; i++) { // j = index[i] * stride; // dVector p1(&vertex[j]); // p1 = p1 & dVector::m_triplexMask; // dFloat32 side1 = localPlane.Evalue(p1); // // if (side0 < dFloat32(0.0f)) { // if (side1 >= dFloat32(0.0f)) { // dVector dp(p1 - p0); // dAssert(dp.m_w == dFloat32(0.0f)); // dFloat32 t = localPlane.DotProduct(dp).GetScalar(); // dAssert(dgAbs(t) >= dFloat32(0.0f)); // if (dgAbs(t) < dFloat32(1.0e-8f)) { // t = dgSign(t) * dFloat32(1.0e-8f); // } // dAssert(0); // contactsOut[count] = p0 - dp.Scale(side0 / t); // count++; // // } // } // else if (side1 <= dFloat32(0.0f)) { // dVector dp(p1 - p0); // dAssert(dp.m_w == dFloat32(0.0f)); // dFloat32 t = localPlane.DotProduct(dp).GetScalar(); // dAssert(dgAbs(t) >= dFloat32(0.0f)); // if (dgAbs(t) < dFloat32(1.0e-8f)) { // t = dgSign(t) * dFloat32(1.0e-8f); // } // dAssert(0); // contactsOut[count] = p0 - dp.Scale(side0 / t); // count++; // } // // side0 = side1; // p0 = p1; //} // //return count; } void ndShapeStaticMesh::Save(const dLoadSaveBase::dSaveDescriptor& desc) const { nd::TiXmlElement* const childNode = new nd::TiXmlElement(ClassName()); desc.m_rootNode->LinkEndChild(childNode); childNode->SetAttribute("hashId", desc.m_nodeNodeHash); ndShape::Save(dLoadSaveBase::dSaveDescriptor(desc, childNode)); }
28.252747
205
0.678465
MADEAPPS
679416add763d00f118a12d5e0526bd2e9703df7
836
hpp
C++
Addons/CommandCentre/ModuleVehicleCam.hpp
DPSO/LRG-Fundamentals
bf60b956d13346c46beacc24e940b1487cc480b6
[ "MIT" ]
5
2019-03-05T17:14:42.000Z
2021-03-09T00:43:10.000Z
Addons/CommandCentre/ModuleVehicleCam.hpp
DPSO/LRG-Fundamentals
bf60b956d13346c46beacc24e940b1487cc480b6
[ "MIT" ]
19
2019-01-17T15:17:01.000Z
2019-01-31T22:10:49.000Z
Addons/CommandCentre/ModuleVehicleCam.hpp
DPSO/LRG-Fundamentals
bf60b956d13346c46beacc24e940b1487cc480b6
[ "MIT" ]
9
2019-02-19T21:17:19.000Z
2021-03-29T08:37:16.000Z
class LRG_ModuleVehicleCam: Module_F { scope = 2; displayName = "Add Vehicle Camera"; icon = "\z\LRG Fundamentals\addons\media\images\icons\Camera.paa"; category = "LRG_CommandCentre"; function = "LR_fnc_moduleVehicleCam"; functionPriority = 4; isGlobal = 0; isTriggerActivated = 0; isDisposable = 0; is3DEN = 0; class Attributes: AttributesBase { class ModuleDescription: ModuleDescription{}; }; class ModuleDescription: ModuleDescription { description[] = { "Synched vehicle can be viewed from the Command Center screens.", "You can sync as many vehicles to this module as you like." }; position = 0; // Position is taken into effect direction = 0; // Direction is taken into effect optional = 0; // Synced entity is optional duplicate = 1; // Multiple entities of this type can be synced }; };
29.857143
68
0.7189
DPSO
679458c42408cb68406a00c3b1fee08c4e570e73
1,944
hpp
C++
svntrunk/src/pk/dtrace/inc/Ttimer_class.hpp
Bhaskers-Blu-Org1/BlueMatter
1ab2c41af870c19e2e1b1095edd1d5c85eeb9b5e
[ "BSD-2-Clause" ]
7
2020-02-25T15:46:18.000Z
2022-02-25T07:04:47.000Z
svntrunk/src/pk/dtrace/inc/Ttimer_class.hpp
IBM/BlueMatter
5243c0ef119e599fc3e9b7c4213ecfe837de59f3
[ "BSD-2-Clause" ]
null
null
null
svntrunk/src/pk/dtrace/inc/Ttimer_class.hpp
IBM/BlueMatter
5243c0ef119e599fc3e9b7c4213ecfe837de59f3
[ "BSD-2-Clause" ]
5
2019-06-06T16:30:21.000Z
2020-11-16T19:43:01.000Z
/* Copyright 2001, 2019 IBM Corporation * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the * following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TTIMER_CLASS_H #define TTIMER_CLASS_H // typedef int bool; #include <stdlib.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include <sys/time.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/dir.h> #include <fcntl.h> #include <assert.h> #include <sys/mman.h> #include <Ttypes.hpp> #include <Tdefs.hpp> #include <Tlib.hpp> class TTimer { public: TTimer(); ~TTimer(); void Start(); void Stop(); void DisplayDuration(char* Text); private: LTime StartTime; LTime StopTime; LTime Duration; }; #endif
34.105263
118
0.739198
Bhaskers-Blu-Org1
67964c684702e19f401c86f6eec7e47d0de2a327
469
cpp
C++
test/tga/test.cpp
shizgnit/asuka
5390bea8a376f5900714d28bf5cc5ecb0b17a5dd
[ "BSD-3-Clause" ]
null
null
null
test/tga/test.cpp
shizgnit/asuka
5390bea8a376f5900714d28bf5cc5ecb0b17a5dd
[ "BSD-3-Clause" ]
null
null
null
test/tga/test.cpp
shizgnit/asuka
5390bea8a376f5900714d28bf5cc5ecb0b17a5dd
[ "BSD-3-Clause" ]
null
null
null
#include "asuka.hpp" int main(void) { cout<<"starting up"<<endl; AT::Resource::Manager t; t.accept("/usr/lib/asuka/resource"); for(int i=0; i<10; i++) { AT::Field image = t.input("a24bit.tga"); cout<<"=["<<i<<"]============================"<<endl; cout<<"width: "<<image["header"]["width"]<<endl; cout<<"height: "<<image["header"]["height"]<<endl; cout<<"bpp: "<<image["header"]["bpp"]<<endl; t.release(image); } exit(0); }
23.45
58
0.509595
shizgnit
679b48c304cf80fd5d64201e5eebf42fd3fcb895
3,122
cpp
C++
src/utils/benchmark_common.cpp
Nic30/pclass-vectorized
33bc92c66f717896fb48bd5c382729f8c76bc882
[ "MIT" ]
1
2020-07-14T17:24:33.000Z
2020-07-14T17:24:33.000Z
src/utils/benchmark_common.cpp
Nic30/pclass-vectorized
33bc92c66f717896fb48bd5c382729f8c76bc882
[ "MIT" ]
14
2019-03-14T09:24:37.000Z
2019-12-19T17:44:21.000Z
src/utils/benchmark_common.cpp
Nic30/pclass-vectorized
33bc92c66f717896fb48bd5c382729f8c76bc882
[ "MIT" ]
null
null
null
#include <pcv/utils/benchmark_common.h> #include <cmath> namespace pcv { BenchmarkStats::BenchmarkStats(size_t LOOKUP_CNT, size_t real_rule_cnt, size_t trace_cnt, std::ostream &out) : LOOKUP_CNT(LOOKUP_CNT), out(out), construction_timer(nullptr), lookup_timer( nullptr), real_rule_cnt(real_rule_cnt), number_of_tries_or_tables( -1), ns_per_packet(trace_cnt) { std::fill(ns_per_packet.begin(), ns_per_packet.end(), 0); } void BenchmarkStats::construction_start() { construction_timer = new DebugTimer(); } void BenchmarkStats::construction_stop() { construction_timer->stop(); } void BenchmarkStats::lookup_packet_start() { actual_packet_start = std::chrono::high_resolution_clock::now(); } void BenchmarkStats::lookup_packet_stop(size_t p_id) { auto finish = std::chrono::high_resolution_clock::now(); std::chrono::duration<uint64_t, std::nano> t = finish - actual_packet_start; ns_per_packet[p_id] += t.count(); } void BenchmarkStats::lookup_start() { lookup_timer = new DebugTimer(); } void BenchmarkStats::lookup_stop() { lookup_timer->stop(); } void BenchmarkStats::set_number_of_tries_or_tables( int number_of_tries_or_tables) { this->number_of_tries_or_tables = number_of_tries_or_tables; } void BenchmarkStats::dump(std::function<void(std::ostream&)> json_extra, std::function<void(std::ostream&)> text_extra) { uint64_t lookup_time_from_packets = 0; for (auto t : ns_per_packet) lookup_time_from_packets += t; double lookup_speed; if (lookup_time_from_packets == 0) { // the packet time was not used at all lookup_speed = (double(LOOKUP_CNT) / lookup_timer->us()); } else { lookup_speed = ((LOOKUP_CNT / double(lookup_time_from_packets)) * 1000.0); } //out << lookup_time_from_packets << " " << lookup_timer->us() * 1000 << std::endl; //auto lookup_speed = (LOOKUP_CNT / double(lookup_timer->us())); if (std::isinf(lookup_speed)) lookup_speed = 0.0; // time can be lower than 1us and json can not contain inf out << "{ \"lookup_speed\":" << lookup_speed << "," << std::endl; // Mpkt/s auto overhead = (lookup_timer->us() * 1000 / double(lookup_time_from_packets)); if (std::isinf(overhead)) overhead = 0.0; out << "\"minimal_benchmark_overhead\":" << overhead << "," << std::endl; // (1 = zero overhead caused by precise timers) out << "\"construction_time\":" << uint64_t(construction_timer->us()) << "," // us << std::endl; out << "\"real_rule_cnt\":" << real_rule_cnt << "," << std::endl; out << "\"number_of_tries_or_tables\":" << number_of_tries_or_tables; bool all_zeros = true; for (auto t : ns_per_packet) { if (t != 0) { all_zeros = false; break; } } if (!all_zeros) { out << "," << std::endl << "\"packet_lookup_times\": [" << std::endl; for (size_t i = 0; i < ns_per_packet.size(); i++) { auto t = ns_per_packet[i]; out << t; // ns if (i != ns_per_packet.size() - 1) { out << ", "; } if ((i + 1) % 1024 == 0) out << std::endl; } out << "]" << std::endl; } json_extra(out); out << "}"; } BenchmarkStats::~BenchmarkStats() { delete construction_timer; delete lookup_timer; } }
30.31068
122
0.680013
Nic30
679cb8bf05437faa03e95ff554075e3d43b3b4a2
4,852
cpp
C++
src/mongo/s/type_tags_test.cpp
EshaMaharishi/pubsub-1
13cb194078ed39b00ea623db0d87df8e153e7981
[ "Apache-2.0" ]
29
2015-01-13T02:34:23.000Z
2022-01-30T16:57:10.000Z
src/mongo/s/type_tags_test.cpp
wujf/mongo
f2f48b749ded0c5585c798c302f6162f19336670
[ "Apache-2.0" ]
null
null
null
src/mongo/s/type_tags_test.cpp
wujf/mongo
f2f48b749ded0c5585c798c302f6162f19336670
[ "Apache-2.0" ]
12
2015-01-24T08:40:28.000Z
2017-10-04T17:23:39.000Z
/** * Copyright (C) 2012 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the GNU Affero General Public License in all respects * for all of the code used other than as permitted herein. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you do not * wish to do so, delete this exception statement from your version. If you * delete this exception statement from all source files in the program, * then also delete it in the license file. */ #include "mongo/s/type_tags.h" #include "mongo/unittest/unittest.h" namespace { using std::string; using mongo::BSONObj; using mongo::TagsType; TEST(Validity, Valid) { TagsType tag; BSONObj obj = BSON(TagsType::ns("test.mycol") << TagsType::tag("tag") << TagsType::min(BSON("a" << 10)) << TagsType::max(BSON("a" << 20))); string errMsg; ASSERT(tag.parseBSON(obj, &errMsg)); ASSERT_EQUALS(errMsg, ""); ASSERT_TRUE(tag.isValid(NULL)); ASSERT_EQUALS(tag.getNS(), "test.mycol"); ASSERT_EQUALS(tag.getTag(), "tag"); ASSERT_EQUALS(tag.getMin(), BSON("a" << 10)); ASSERT_EQUALS(tag.getMax(), BSON("a" << 20)); } TEST(Validity, MissingFields) { TagsType tag; BSONObj objModNS = BSON(TagsType::tag("tag") << TagsType::min(BSON("a" << 10)) << TagsType::max(BSON("a" << 20))); string errMsg; ASSERT(tag.parseBSON(objModNS, &errMsg)); ASSERT_EQUALS(errMsg, ""); ASSERT_FALSE(tag.isValid(NULL)); BSONObj objModName = BSON(TagsType::ns("test.mycol") << TagsType::min(BSON("a" << 10)) << TagsType::max(BSON("a" << 20))); ASSERT(tag.parseBSON(objModName, &errMsg)); ASSERT_EQUALS(errMsg, ""); ASSERT_FALSE(tag.isValid(NULL)); BSONObj objModKeys = BSON(TagsType::ns("test.mycol") << TagsType::tag("tag")); ASSERT(tag.parseBSON(objModKeys, &errMsg)); ASSERT_EQUALS(errMsg, ""); ASSERT_FALSE(tag.isValid(NULL)); } TEST(MinMaxValidity, DifferentNumberOfColumns) { TagsType tag; BSONObj obj = BSON(TagsType::tag("tag") << TagsType::ns("test.mycol") << TagsType::min(BSON("a" << 10 << "b" << 10)) << TagsType::max(BSON("a" << 20))); string errMsg; ASSERT(tag.parseBSON(obj, &errMsg)); ASSERT_EQUALS(errMsg, ""); ASSERT_FALSE(tag.isValid(NULL)); } TEST(MinMaxValidity, DifferentColumns) { TagsType tag; BSONObj obj = BSON(TagsType::tag("tag") << TagsType::ns("test.mycol") << TagsType::min(BSON("a" << 10)) << TagsType::max(BSON("b" << 20))); string errMsg; ASSERT(tag.parseBSON(obj, &errMsg)); ASSERT_EQUALS(errMsg, ""); ASSERT_FALSE(tag.isValid(NULL)); } TEST(MinMaxValidity, NotAscending) { TagsType tag; BSONObj obj = BSON(TagsType::tag("tag") << TagsType::ns("test.mycol") << TagsType::min(BSON("a" << 20)) << TagsType::max(BSON("a" << 10))); string errMsg; ASSERT(tag.parseBSON(obj, &errMsg)); ASSERT_EQUALS(errMsg, ""); ASSERT_FALSE(tag.isValid(NULL)); } TEST(Validity, BadType) { TagsType tag; BSONObj obj = BSON(TagsType::tag() << 0); string errMsg; ASSERT((!tag.parseBSON(obj, &errMsg)) && (errMsg != "")); } } // unnamed namespace
39.770492
79
0.566777
EshaMaharishi
679ebaad9f700e5a9df7b8a1b12ec31bb8e5e43f
1,090
cpp
C++
CodeForces/Complete/1200-1299/1251D-SalaryChanging.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
CodeForces/Complete/1200-1299/1251D-SalaryChanging.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
CodeForces/Complete/1200-1299/1251D-SalaryChanging.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
#include <cstdio> #include <vector> #include <algorithm> typedef long long ll; bool check(const std::vector<ll> &sv, ll med, const ll budget){ ll left(0), right(0), sum(0); for(ll p = 0; p < sv.size(); p++){ if(sv[p].first < m){++left; sum += (sv[p].second > m) ? sv[p].second : m;} if(sv[p].first < m){++left; sum += (sv[p].second > m) ? sv[p].second : m;} } return ( } int main(){ ll t; scanf("%lld", &t); while(t--){ ll n, s; scanf("%lld %lld", &n, &s); std::vector<ll> vl(n), vr(n); std::vector<std::pair<ll, ll> > v(n); for(ll p = 0; p < n; p++){scanf("%lld %lld", &v[p].first, &v[p].second); vl[p] = v[p].first; vr[p] = v[p].second;} sort(vl.begin(), vl.end()); sort(vr.begin(), vr.end()); ll left(vl[n / 2]), right(vr[n / 2]); ll res(left); while(left <= right){ ll mid = (left + right) / 2; if(check(v, mid)){res = mid; left = mid + 1;} else{right = mid - 1;} } printf("%lld\n", res); } return 0; }
25.952381
122
0.461468
Ashwanigupta9125
67a0e0913bcede60a1ca68c6c512814f40ff9b99
287
cpp
C++
cpp/test_node.cpp
jieyaren/hello-world
9fbc7d117b9aee98d748669646dd200c25a4122f
[ "WTFPL" ]
3
2021-11-12T09:20:21.000Z
2022-02-18T11:34:33.000Z
cpp/test_node.cpp
jieyaren/hello-world
9fbc7d117b9aee98d748669646dd200c25a4122f
[ "WTFPL" ]
1
2019-05-15T10:55:59.000Z
2019-05-15T10:56:31.000Z
cpp/test_node.cpp
jieyaren/hello-world
9fbc7d117b9aee98d748669646dd200c25a4122f
[ "WTFPL" ]
null
null
null
#include "node.hpp" int main() { //(20.0 + -10.0 ) * 0.1 node * p1 = new NumNode(20.0); node * p2 = new NumNode(-10.0); node * p3 = new AddNode(p1,p2); node * p4 = new NumNode(0.1); node * p5 = new MultNode(p3,p4); double x = p5->calc(); std::cout << x<<std::endl; delete p5; }
20.5
33
0.56446
jieyaren
67a2543752df4866e2618f94fce1b1ee3000c628
130
hpp
C++
opencv2.framework/Versions/A/Headers/stitching/detail/warpers.hpp
osis/nostalgia-scanner-ios
100163e3c09f0dfe4483fb6a708522c750b46c52
[ "MIT" ]
15
2018-02-02T12:15:59.000Z
2022-03-31T00:11:49.000Z
opencv2.framework/Versions/A/Headers/stitching/detail/warpers.hpp
osis/nostalgia-scanner-ios
100163e3c09f0dfe4483fb6a708522c750b46c52
[ "MIT" ]
null
null
null
opencv2.framework/Versions/A/Headers/stitching/detail/warpers.hpp
osis/nostalgia-scanner-ios
100163e3c09f0dfe4483fb6a708522c750b46c52
[ "MIT" ]
5
2018-07-24T12:13:33.000Z
2019-08-15T09:26:42.000Z
version https://git-lfs.github.com/spec/v1 oid sha256:03df42f0f44ce261f51089ffca63fb7aa5ce59ad275f40e295e6d8801e5a4d03 size 19831
32.5
75
0.884615
osis
67a356a35570faca20ae6b780c8c69dccee7be2e
21,460
cc
C++
src/win32/ime/ime_ui_visibility_tracker_test.cc
sousuke0422/crIME
abc711e0c2cad19950703d59ed4d1ffe4bd76953
[ "BSD-3-Clause" ]
1
2021-02-24T07:03:26.000Z
2021-02-24T07:03:26.000Z
src/win32/ime/ime_ui_visibility_tracker_test.cc
sousuke0422/crIME
abc711e0c2cad19950703d59ed4d1ffe4bd76953
[ "BSD-3-Clause" ]
108
2018-05-29T17:33:53.000Z
2019-07-22T00:01:54.000Z
src/win32/ime/ime_ui_visibility_tracker_test.cc
sousuke0422/crIME
abc711e0c2cad19950703d59ed4d1ffe4bd76953
[ "BSD-3-Clause" ]
1
2021-12-29T08:15:14.000Z
2021-12-29T08:15:14.000Z
// Copyright 2010-2018, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "testing/base/public/googletest.h" #include "testing/base/public/gunit.h" #include "win32/ime/ime_types.h" #include "win32/ime/ime_ui_visibility_tracker.h" namespace mozc { namespace win32 { TEST(ImeUIVisibilityTrackerTest, BasicTest) { UIVisibilityTracker tracker; tracker.Initialize(); // At first, no window is visible because IME does not have input focus. EXPECT_FALSE(tracker.IsAnyWindowVisible()); // Notify the tracker that the IME is getting input focus. tracker.OnFocus(); // Suggest window is visible by default when the IME has input focus. EXPECT_TRUE(tracker.IsSuggestWindowVisible()); // Candidate window is not visible by default when the IME has input focus. EXPECT_FALSE(tracker.IsCandidateWindowVisible()); // Composition window is not visible by default when the IME has input focus. EXPECT_FALSE(tracker.IsCompositionWindowVisible()); // Notify the tracker of the UI visibility bits passed from the application // as lParam of WM_IME_SETCONTEXT. These bits update the visibility for // each UI component. // ISC_SHOWUIALL means that the application allows the IME to show all the UI // components. const ShowUIAttributes ui_attributes(ISC_SHOWUIALL); tracker.OnSetContext(ui_attributes); // WM_IME_SETCONTEXT/ISC_SHOWUIALL do not change the UI visibilities. EXPECT_TRUE(tracker.IsSuggestWindowVisible()); EXPECT_FALSE(tracker.IsCandidateWindowVisible()); EXPECT_FALSE(tracker.IsCompositionWindowVisible()); } // When a user changes the input method by the LangBar, WM_IME_SETCONTEXT will // not be sent. Even in this case, the suggest window should be visible by // default. TEST(ImeUIVisibilityTrackerTest, SuggestWindowShouldBeVisibleWhenImeIsChangedByLangBar) { UIVisibilityTracker tracker; tracker.Initialize(); // At first, no window is visible because IME does not have input focus. EXPECT_FALSE(tracker.IsAnyWindowVisible()); // Even when the input context has already got focus, |OnFocus| will be // called from ImeSelect. tracker.OnFocus(); // Suggest window is visible just after the IME is changed by the LangBar. EXPECT_TRUE(tracker.IsSuggestWindowVisible()); } // When a user changes the input method by the LangBar, WM_IME_SETCONTEXT will // not be sent. Even in this case, the composition window can be visible, // without any focus change, which finally invokes ImeSetActiveContext. TEST(ImeUIVisibilityTrackerTest, CompositionWindowCanBeShownWhenImeIsChangedByLangBar) { UIVisibilityTracker tracker; tracker.Initialize(); // At first, no window is visible because IME does not have input focus. EXPECT_FALSE(tracker.IsAnyWindowVisible()); // Even when the input context has already got focus, |OnFocus| will be // called from ImeSelect. tracker.OnFocus(); // Composition window is not visible by default after the IME is changed by // the LangBar. EXPECT_FALSE(tracker.IsCompositionWindowVisible()); // WM_IME_STARTCOMPOSITION should be marked as a visibility-test-message by // BeginVisibilityTestForCompositionWindow. EXPECT_TRUE( UIVisibilityTracker::IsVisibilityTestMessageForComposiwionWindow( WM_IME_STARTCOMPOSITION, 0, 0)); // Since WM_IME_STARTCOMPOSITION is a visibility-test-message, the IME calls // BeginVisibilityTestForCompositionWindow the message is posted. tracker.BeginVisibilityTestForCompositionWindow(); // If WM_IME_STARTCOMPOSITION is passed to the IME UI Window, the IME is // responsible to draw the composition window. tracker.OnStartComposition(); EXPECT_TRUE(tracker.IsCompositionWindowVisible()); } // When a user changes the input method by the LangBar, WM_IME_SETCONTEXT will // not be sent. Even in this case, the candiate window can be visible, // without any focus change, which finally invokes ImeSetActiveContext. TEST(ImeUIVisibilityTrackerTest, CandidateWindowCanBeShownWhenImeIsChangedByLangBar) { UIVisibilityTracker tracker; tracker.Initialize(); // At first, no window is visible because IME does not have input focus. EXPECT_FALSE(tracker.IsAnyWindowVisible()); // Even when the input context has already got focus, |OnFocus| will be // called from ImeSelect. tracker.OnFocus(); // Candidate window is not visible by default after the IME is changed by the // LangBar. EXPECT_FALSE(tracker.IsCandidateWindowVisible()); // Since WM_IME_NOTIFY/IMN_OPENCANDIDATE is a visibility-test-message, the // IME calls BeginVisibilityTestForCandidateWindow the message is // posted. tracker.BeginVisibilityTestForCandidateWindow(); // BeginVisibilityTestForCandidateWindow changes the visibility bit for // candidate window. However, it does not change the visibility bit for // suggestion window. EXPECT_FALSE(tracker.IsCandidateWindowVisible()); // If WM_IME_NOTIFY/IMN_OPENCANDIDATE is passed to the IME UI Window, the IME // is responsible to draw the candidate window. tracker.OnNotify(IMN_OPENCANDIDATE, 1); EXPECT_TRUE(tracker.IsCandidateWindowVisible()); } TEST(ImeUIVisibilityTrackerTest, HideSuggestWindowBySetInputContext) { UIVisibilityTracker tracker; tracker.Initialize(); // At first, no window is visible because IME does not have input focus. EXPECT_FALSE(tracker.IsAnyWindowVisible()); // Notify the tracker that the IME is getting input focus. tracker.OnFocus(); // Suggest window is visible by default when the IME has input focus. EXPECT_TRUE(tracker.IsSuggestWindowVisible()); // Candidate window is not visible by default when the IME has input focus. EXPECT_FALSE(tracker.IsCandidateWindowVisible()); // Composition window is not visible by default when the IME has input focus. EXPECT_FALSE(tracker.IsCompositionWindowVisible()); // Suggest window should be visible if all the candidate windows are visible. // You may see this situation in Chrome, as reported in b/3002445. tracker.OnSetContext(ShowUIAttributes(ISC_SHOWUIALLCANDIDATEWINDOW)); // Suggest window should be visible. EXPECT_TRUE(tracker.IsSuggestWindowVisible()); // Suggest window should be invisible if none of the bits in // ISC_SHOWUIALLCANDIDATEWINDOW is cleared, where ISC_SHOWUICANDIDATEWINDOW // means that the first candidate window can be shown but the others must be // invisible. tracker.OnSetContext(ShowUIAttributes(ISC_SHOWUICANDIDATEWINDOW)); // Suggest window should be invisible. EXPECT_FALSE(tracker.IsSuggestWindowVisible()); } TEST(ImeUIVisibilityTrackerTest, CompositionIsDrawnByIME) { UIVisibilityTracker tracker; tracker.Initialize(); // Notify the tracker that the IME is getting input focus. tracker.OnFocus(); // Notify the tracker of the UI visibility bits passed from the application // as lParam of WM_IME_SETCONTEXT. These bits update the visibility for // each UI component. const ShowUIAttributes ui_attributes(ISC_SHOWUIALL); tracker.OnSetContext(ui_attributes); // WM_IME_STARTCOMPOSITION should be marked as a visibility-test-message by // BeginVisibilityTestForCompositionWindow. EXPECT_TRUE( UIVisibilityTracker::IsVisibilityTestMessageForComposiwionWindow( WM_IME_STARTCOMPOSITION, 0, 0)); // Since WM_IME_STARTCOMPOSITION is a visibility-test-message, the IME calls // BeginVisibilityTestForCompositionWindow the message is posted. tracker.BeginVisibilityTestForCompositionWindow(); // BeginVisibilityTestForCompositionWindow changes the visibility bit for // composition window. EXPECT_FALSE(tracker.IsCompositionWindowVisible()); // If WM_IME_STARTCOMPOSITION is passed to the IME UI Window, the IME is // responsible to draw the composition window. tracker.OnStartComposition(); EXPECT_TRUE(tracker.IsCompositionWindowVisible()); // UIVisibilityTracker ignores these bits though. const DWORD kCompositionUpdateBits = (GCS_COMPREADSTR | GCS_COMPREADATTR | GCS_COMPREADCLAUSE | GCS_COMPSTR | GCS_COMPATTR | GCS_COMPCLAUSE | GCS_CURSORPOS | GCS_DELTASTART); // WM_IME_COMPOSITION should be marked as a visibility-test-message by // BeginVisibilityTestForCompositionWindow. EXPECT_TRUE( UIVisibilityTracker::IsVisibilityTestMessageForComposiwionWindow( WM_IME_COMPOSITION, 0, kCompositionUpdateBits)); // Since WM_IME_COMPOSITION is a visibility-test-message, the IME calls // BeginVisibilityTestForCompositionWindow the message is posted. tracker.BeginVisibilityTestForCompositionWindow(); // BeginVisibilityTestForCompositionWindow changes the visibility bit for // composition window. EXPECT_FALSE(tracker.IsCompositionWindowVisible()); // If the IME UI Window receives WM_IME_COMPOSITION, the IME is responsible // to draw the composition window. tracker.OnComposition(); EXPECT_TRUE(tracker.IsCompositionWindowVisible()); // WM_IME_ENDCOMPOSITION should be marked as a visibility-test-message by // BeginVisibilityTestForCompositionWindow. EXPECT_TRUE( UIVisibilityTracker::IsVisibilityTestMessageForComposiwionWindow( WM_IME_ENDCOMPOSITION, 0, 0)); // Since WM_IME_ENDCOMPOSITION is a visibility-test-message, the IME calls // BeginVisibilityTestForCompositionWindow the message is posted. tracker.BeginVisibilityTestForCompositionWindow(); // BeginVisibilityTestForCompositionWindow changes the visibility bit for // composition window. EXPECT_FALSE(tracker.IsCompositionWindowVisible()); // WM_IME_ENDCOMPOSITION makes the composition window invisible either way. tracker.OnEndComposition(); EXPECT_FALSE(tracker.IsCompositionWindowVisible()); } TEST(ImeUIVisibilityTrackerTest, CompositionIsDrawnByApplication) { UIVisibilityTracker tracker; tracker.Initialize(); // Notify the tracker that the IME is getting input focus. tracker.OnFocus(); // Notify the tracker of the UI visibility bits passed from the application // as lParam of WM_IME_SETCONTEXT. These bits update the visibility for // each UI component. // Some applications such as GTK applications or OOo does not clear the UI // visibility bits even though they draw their own composition windows. // We conform with those applications. const ShowUIAttributes ui_attributes(ISC_SHOWUIALL); tracker.OnSetContext(ui_attributes); // WM_IME_STARTCOMPOSITION should be marked as a visibility-test-message by // BeginVisibilityTestForCompositionWindow. EXPECT_TRUE( UIVisibilityTracker::IsVisibilityTestMessageForComposiwionWindow( WM_IME_STARTCOMPOSITION, 0, 0)); // Since WM_IME_STARTCOMPOSITION is a visibility-test-message, the IME calls // BeginVisibilityTestForCompositionWindow the message is posted. tracker.BeginVisibilityTestForCompositionWindow(); // BeginVisibilityTestForCompositionWindow changes the visibility bit for // composition window. // If WM_IME_STARTCOMPOSITION is not passed to the IME UI Window, the // application is responsible to draw the composition window. EXPECT_FALSE(tracker.IsCompositionWindowVisible()); // UIVisibilityTracker ignores these bits though. const DWORD kCompositionUpdateBits = (GCS_COMPREADSTR | GCS_COMPREADATTR | GCS_COMPREADCLAUSE | GCS_COMPSTR | GCS_COMPATTR | GCS_COMPCLAUSE | GCS_CURSORPOS | GCS_DELTASTART); // WM_IME_COMPOSITION should be marked as a visibility-test-message by // BeginVisibilityTestForCompositionWindow. EXPECT_TRUE( UIVisibilityTracker::IsVisibilityTestMessageForComposiwionWindow( WM_IME_COMPOSITION, 0, kCompositionUpdateBits)); // Since WM_IME_COMPOSITION is a visibility-test-message, the IME calls // BeginVisibilityTestForCompositionWindow the message is posted. tracker.BeginVisibilityTestForCompositionWindow(); // BeginVisibilityTestForCompositionWindow changes the visibility bit for // composition window. // If WM_IME_COMPOSITION is not passed to the IME UI Window, the application // is responsible to draw the composition window. EXPECT_FALSE(tracker.IsCompositionWindowVisible()); // WM_IME_ENDCOMPOSITION should be marked as a visibility-test-message by // BeginVisibilityTestForCompositionWindow. EXPECT_TRUE( UIVisibilityTracker::IsVisibilityTestMessageForComposiwionWindow( WM_IME_ENDCOMPOSITION, 0, 0)); // Since WM_IME_ENDCOMPOSITION is a visibility-test-message, the IME calls // BeginVisibilityTestForCompositionWindow the message is posted. tracker.BeginVisibilityTestForCompositionWindow(); // BeginVisibilityTestForCompositionWindow changes the visibility bit for // composition window. // WM_IME_ENDCOMPOSITION makes the composition window invisible either way. EXPECT_FALSE(tracker.IsCompositionWindowVisible()); } TEST(ImeUIVisibilityTrackerTest, CandidateIsDrawnByIME) { UIVisibilityTracker tracker; tracker.Initialize(); // Notify the tracker that the IME is getting input focus. tracker.OnFocus(); // Notify the tracker of the UI visibility bits passed from the application // as lParam of WM_IME_SETCONTEXT. These bits update the visibility for // each UI component. const ShowUIAttributes ui_attributes(ISC_SHOWUIALL); tracker.OnSetContext(ui_attributes); // IMN_OPENCANDIDATE should be marked as a visibility-test-message by // IsVisibilityTestMessageForCandidateWindow. EXPECT_TRUE( UIVisibilityTracker::IsVisibilityTestMessageForCandidateWindow( WM_IME_NOTIFY, IMN_OPENCANDIDATE, 1)); // Since WM_IME_NOTIFY/IMN_OPENCANDIDATE is a visibility-test-message, the // IME calls BeginVisibilityTestForCandidateWindow the message is // posted. tracker.BeginVisibilityTestForCandidateWindow(); // BeginVisibilityTestForCandidateWindow changes the visibility bit for // candidate window. However, it does not change the visibility bit for // suggestion window. EXPECT_FALSE(tracker.IsCandidateWindowVisible()); EXPECT_TRUE(tracker.IsSuggestWindowVisible()); // If WM_IME_NOTIFY/IMN_OPENCANDIDATE is passed to the IME UI Window, the IME // is responsible to draw the candidate window. tracker.OnNotify(IMN_OPENCANDIDATE, 1); EXPECT_TRUE(tracker.IsCandidateWindowVisible()); // WM_IME_NOTIFY/IMN_CHANGECANDIDATE is not marked as a visibility-test- // message by IsVisibilityTestMessageForCandidateWindow. EXPECT_FALSE( UIVisibilityTracker::IsVisibilityTestMessageForCandidateWindow( WM_IME_NOTIFY, IMN_CHANGECANDIDATE, 1)); // WM_IME_NOTIFY/IMN_CLOSECANDIDATE is not marked as a visibility-test- // message by IsVisibilityTestMessageForCandidateWindow. EXPECT_TRUE( UIVisibilityTracker::IsVisibilityTestMessageForCandidateWindow( WM_IME_NOTIFY, IMN_CLOSECANDIDATE, 1)); // Since WM_IME_NOTIFY/IMN_CLOSECANDIDATE is a visibility-test-message, the // IME calls BeginVisibilityTestForCandidateWindow the message is // posted. tracker.BeginVisibilityTestForCandidateWindow(); // BeginVisibilityTestForCandidateWindow changes the visibility bit for // candidate window. EXPECT_FALSE(tracker.IsCandidateWindowVisible()); // WM_IME_NOTIFY/IMN_CLOSECANDIDATE makes the candidate window invisible // either way. tracker.OnNotify(IMN_CLOSECANDIDATE, 1); EXPECT_FALSE(tracker.IsCandidateWindowVisible()); } TEST(ImeUIVisibilityTrackerTest, CandidateIsDrawnByApplication) { UIVisibilityTracker tracker; tracker.Initialize(); // Notify the tracker that the IME is getting input focus. tracker.OnFocus(); // Notify the tracker of the UI visibility bits passed from the application // as lParam of WM_IME_SETCONTEXT. These bits update the visibility for // each UI component. // Some game applications might not clear the UI visibility bits even though // they draw their own candidate windows. // We conform with those applications. const ShowUIAttributes ui_attributes(ISC_SHOWUIALL); tracker.OnSetContext(ui_attributes); // IMN_OPENCANDIDATE should be marked as a visibility-test-message by // IsVisibilityTestMessageForCandidateWindow. EXPECT_TRUE( UIVisibilityTracker::IsVisibilityTestMessageForCandidateWindow( WM_IME_NOTIFY, IMN_OPENCANDIDATE, 1)); // Since WM_IME_NOTIFY/IMN_OPENCANDIDATE is a visibility-test-message, the // IME calls BeginVisibilityTestForCandidateWindow before the message is // posted. tracker.BeginVisibilityTestForCandidateWindow(); // BeginVisibilityTestForCandidateWindow changes the visibility bit for // candidate window. However, it does not change the visibility bit for // suggestion window. // If WM_IME_NOTIFY/IMN_OPENCANDIDATE is not passed to the IME UI Window, the // application is responsible to draw the candidate window. EXPECT_FALSE(tracker.IsCandidateWindowVisible()); EXPECT_TRUE(tracker.IsSuggestWindowVisible()); // WM_IME_NOTIFY/IMN_CHANGECANDIDATE is not marked as a visibility-test- // message by IsVisibilityTestMessageForCandidateWindow. EXPECT_FALSE( UIVisibilityTracker::IsVisibilityTestMessageForCandidateWindow( WM_IME_NOTIFY, IMN_CHANGECANDIDATE, 1)); // WM_IME_NOTIFY/IMN_CLOSECANDIDATE is not marked as a visibility-test- // message by IsVisibilityTestMessageForCandidateWindow. EXPECT_TRUE( UIVisibilityTracker::IsVisibilityTestMessageForCandidateWindow( WM_IME_NOTIFY, IMN_CLOSECANDIDATE, 1)); // Since WM_IME_NOTIFY/IMN_CLOSECANDIDATE is a visibility-test-message, the // IME calls BeginVisibilityTestForCandidateWindow before the message is // posted. // WM_IME_NOTIFY/IMN_CLOSECANDIDATE makes the candidate window invisible // either way. tracker.BeginVisibilityTestForCandidateWindow(); EXPECT_FALSE(tracker.IsCandidateWindowVisible()); } // Some applications such as gvim 7.3.55, Notepad++ 5.8.4 (Scintilla 2.22), // EmEditor 10.0.4, do not pass WM_IME_COMPOSITION message to ::DefWindowProc // when |lParam| contains GCS_RESULTSTR flag. (b/3223935) TEST(ImeUIVisibilityTrackerTest, Issue3223935_WM_IME_COMPOSITION_IsEatenIfItContainsResultString) { UIVisibilityTracker tracker; tracker.Initialize(); // Notify the tracker that the IME is getting input focus. tracker.OnFocus(); // Notify the tracker of the UI visibility bits passed from the application // as lParam of WM_IME_SETCONTEXT. These bits update the visibility for // each UI component. // Some game applications might not clear the UI visibility bits even though // they draw their own candidate windows. // We conform with those applications. const ShowUIAttributes ui_attributes(ISC_SHOWUIALL); tracker.OnSetContext(ui_attributes); // WM_IME_STARTCOMPOSITION should be marked as a visibility-test-message by // BeginVisibilityTestForCompositionWindow. EXPECT_TRUE( UIVisibilityTracker::IsVisibilityTestMessageForComposiwionWindow( WM_IME_STARTCOMPOSITION, 0, 0)); // Since WM_IME_STARTCOMPOSITION is a visibility-test-message, the IME calls // BeginVisibilityTestForCompositionWindow the message is posted. tracker.BeginVisibilityTestForCompositionWindow(); // If WM_IME_STARTCOMPOSITION is passed to the IME UI Window, the IME is // responsible to draw the composition window. tracker.OnStartComposition(); EXPECT_TRUE(tracker.IsCompositionWindowVisible()); // |lParam| contains GCS_RESULTSTR. Do not use WM_IME_COMPOSITION as a // visibility-test-message in this case. EXPECT_FALSE( UIVisibilityTracker::IsVisibilityTestMessageForCandidateWindow( WM_IME_COMPOSITION, 0, GCS_RESULTSTR)); // |lParam| contains GCS_RESULTSTR. Do not use WM_IME_COMPOSITION as a // visibility-test-message in this case. EXPECT_FALSE( UIVisibilityTracker::IsVisibilityTestMessageForCandidateWindow( WM_IME_COMPOSITION, 0, GCS_COMPSTR | GCS_RESULTSTR)); // Composition Window should be visible. EXPECT_TRUE(tracker.IsCompositionWindowVisible()); } } // namespace win32 } // namespace mozc
41.111111
79
0.783085
sousuke0422