text string | size int64 | token_count int64 |
|---|---|---|
// -*- C++ -*-
// $Id: Current.cpp 96992 2013-04-11 18:07:48Z huangh $
#include "tao/RTScheduling/Current.h"
#include "tao/RTScheduling/Distributable_Thread.h"
#include "tao/RTCORBA/Priority_Mapping_Manager.h"
#include "tao/RTCORBA/RT_Current.h"
#include "tao/ORB_Core.h"
#include "tao/TSS_Resources.h"
#include "ace/ACE.h"
#include "ace/OS_NS_errno.h"
#include "ace/OS_NS_string.h"
TAO_BEGIN_VERSIONED_NAMESPACE_DECL
ACE_Atomic_Op<TAO_SYNCH_MUTEX, long> TAO_RTScheduler_Current::guid_counter;
u_long
TAO_DTId_Hash::operator () (const IdType &id) const
{
return ACE::hash_pjw ((const char *) id.get_buffer (),
id.length ());
}
TAO_RTScheduler_Current::TAO_RTScheduler_Current (void) :
orb_ (0)
{
}
TAO_RTScheduler_Current::~TAO_RTScheduler_Current (void)
{
}
void
TAO_RTScheduler_Current::init (TAO_ORB_Core* orb)
{
this->orb_ = orb;
// Create the RT_Current.
RTCORBA::Current_ptr current;
ACE_NEW_THROW_EX (current,
TAO_RT_Current (orb),
CORBA::NO_MEMORY (CORBA::SystemException::_tao_minor_code (
TAO::VMCID,
ENOMEM),
CORBA::COMPLETED_NO));
this->rt_current_ = current;
}
void
TAO_RTScheduler_Current::rt_current (RTCORBA::Current_ptr rt_current)
{
this->rt_current_ = RTCORBA::Current::_duplicate (rt_current);
}
TAO_ORB_Core*
TAO_RTScheduler_Current::orb (void)
{
return this->orb_;
}
DT_Hash_Map*
TAO_RTScheduler_Current::dt_hash (void)
{
return &this->dt_hash_;
}
void
TAO_RTScheduler_Current::begin_scheduling_segment (
const char * name,
CORBA::Policy_ptr sched_param,
CORBA::Policy_ptr implicit_sched_param)
{
TAO_RTScheduler_Current_i *impl = this->implementation ();
if (impl == 0)
{
ACE_NEW_THROW_EX (impl,
TAO_RTScheduler_Current_i (this->orb_,
&this->dt_hash_),
CORBA::NO_MEMORY (
CORBA::SystemException::_tao_minor_code (
TAO::VMCID,
ENOMEM),
CORBA::COMPLETED_NO));
this->implementation (impl);
}
impl->begin_scheduling_segment (name,
sched_param,
implicit_sched_param
);
}
void
TAO_RTScheduler_Current::update_scheduling_segment (const char * name,
CORBA::Policy_ptr sched_param,
CORBA::Policy_ptr implicit_sched_param
)
{
TAO_RTScheduler_Current_i *impl = this->implementation ();
if (impl == 0)
throw ::CORBA::BAD_INV_ORDER ();
impl->update_scheduling_segment (name,
sched_param,
implicit_sched_param
);
}
void
TAO_RTScheduler_Current::end_scheduling_segment (const char * name)
{
TAO_RTScheduler_Current_i *impl = this->implementation ();
if (impl == 0)
{
TAOLIB_ERROR ((LM_ERROR,
"Missing scheduling context OR DT cancelled\n"));
throw ::CORBA::BAD_INV_ORDER ();
return;
}
impl->end_scheduling_segment (name
);
}
RTScheduling::DistributableThread_ptr
TAO_RTScheduler_Current::lookup(const RTScheduling::Current::IdType & id)
{
RTScheduling::DistributableThread_var DT;
int result = this->dt_hash_.find (id,
DT);
if (result == 0)
return DT._retn ();
else return RTScheduling::DistributableThread::_nil ();
}
// returns a null reference if
// the distributable thread is
// not known to the local scheduler
RTScheduling::DistributableThread_ptr
TAO_RTScheduler_Current::spawn (RTScheduling::ThreadAction_ptr start,
CORBA::VoidData data,
const char* name,
CORBA::Policy_ptr sched_param,
CORBA::Policy_ptr implicit_sched_param,
CORBA::ULong stack_size,
RTCORBA::Priority base_priority)
{
TAO_RTScheduler_Current_i *impl = this->implementation ();
if (impl == 0)
throw ::CORBA::BAD_INV_ORDER ();
return impl->spawn (start,
data,
name,
sched_param,
implicit_sched_param,
stack_size,
base_priority
);
}
RTScheduling::Current::IdType *
TAO_RTScheduler_Current::id (void)
{
TAO_RTScheduler_Current_i *impl = this->implementation ();
if (impl == 0)
throw ::CORBA::BAD_INV_ORDER ();
return impl->id ();
}
CORBA::Policy_ptr
TAO_RTScheduler_Current::scheduling_parameter (void)
{
TAO_RTScheduler_Current_i *impl = this->implementation ();
if (impl == 0)
throw ::CORBA::BAD_INV_ORDER ();
return impl->scheduling_parameter ();
}
CORBA::Policy_ptr
TAO_RTScheduler_Current::implicit_scheduling_parameter (void)
{
TAO_RTScheduler_Current_i *impl = this->implementation ();
if (impl == 0)
throw ::CORBA::BAD_INV_ORDER ();
return impl->implicit_scheduling_parameter ();
}
RTScheduling::Current::NameList *
TAO_RTScheduler_Current::current_scheduling_segment_names (void)
{
TAO_RTScheduler_Current_i *impl = this->implementation ();
if (impl == 0)
throw ::CORBA::BAD_INV_ORDER ();
return impl->current_scheduling_segment_names ();
}
RTCORBA::Priority
TAO_RTScheduler_Current::the_priority (void)
{
return this->rt_current_->the_priority ();
}
void
TAO_RTScheduler_Current::the_priority (RTCORBA::Priority the_priority)
{
this->rt_current_->the_priority(the_priority);
}
TAO_RTScheduler_Current_i*
TAO_RTScheduler_Current::implementation (TAO_RTScheduler_Current_i* new_current)
{
TAO_TSS_Resources *tss =
TAO_TSS_Resources::instance ();
TAO_RTScheduler_Current_i *old =
static_cast<TAO_RTScheduler_Current_i *> (tss->rtscheduler_current_impl_);
tss->rtscheduler_current_impl_ = new_current;
return old;
}
TAO_RTScheduler_Current_i*
TAO_RTScheduler_Current::implementation (void)
{
TAO_TSS_Resources *tss =
TAO_TSS_Resources::instance ();
TAO_RTScheduler_Current_i* impl =
static_cast<TAO_RTScheduler_Current_i *> (tss->rtscheduler_current_impl_);
return impl;
}
TAO_ORB_Core*
TAO_RTScheduler_Current_i::orb (void)
{
return this->orb_;
}
DT_Hash_Map*
TAO_RTScheduler_Current_i::dt_hash (void)
{
return this->dt_hash_;
}
RTScheduling::Scheduler_ptr
TAO_RTScheduler_Current_i::scheduler (void)
{
return RTScheduling::Scheduler::_duplicate (this->scheduler_.in ());
}
TAO_RTScheduler_Current_i::TAO_RTScheduler_Current_i (TAO_ORB_Core* orb,
DT_Hash_Map* dt_hash)
:orb_ (orb),
dt_ (RTScheduling::DistributableThread::_nil ()),
previous_current_ (0),
dt_hash_ (dt_hash)
{
CORBA::Object_var scheduler_obj =
this->orb_->object_ref_table ().resolve_initial_reference (
"RTScheduler");
this->scheduler_ = RTScheduling::Scheduler::_narrow (scheduler_obj.in ());
}
TAO_RTScheduler_Current_i::TAO_RTScheduler_Current_i (
TAO_ORB_Core* orb,
DT_Hash_Map* dt_hash,
RTScheduling::Current::IdType guid,
const char * name,
CORBA::Policy_ptr sched_param,
CORBA::Policy_ptr implicit_sched_param,
RTScheduling::DistributableThread_ptr dt,
TAO_RTScheduler_Current_i* prev_current)
: orb_ (orb),
guid_ (guid),
name_ (CORBA::string_dup (name)),
sched_param_ (CORBA::Policy::_duplicate (sched_param)),
implicit_sched_param_ (CORBA::Policy::_duplicate (implicit_sched_param)),
dt_ (RTScheduling::DistributableThread::_duplicate (dt)),
previous_current_ (prev_current),
dt_hash_ (dt_hash)
{
CORBA::Object_var scheduler_obj =
orb->object_ref_table ().resolve_initial_reference (
"RTScheduler");
this->scheduler_ = RTScheduling::Scheduler::_narrow (scheduler_obj.in ()
);
}
TAO_RTScheduler_Current_i::~TAO_RTScheduler_Current_i (void)
{
}
void
TAO_RTScheduler_Current_i::begin_scheduling_segment(
const char * name,
CORBA::Policy_ptr sched_param,
CORBA::Policy_ptr implicit_sched_param)
{
// Check if it is a new Scheduling Segmnet
if (this->guid_.length () == 0)
{
//Generate GUID
size_t temp = ++TAO_RTScheduler_Current::guid_counter;
this->guid_.length (sizeof(size_t));
ACE_OS::memcpy (this->guid_.get_buffer (),
&temp,
sizeof(size_t));
size_t guid;
ACE_OS::memcpy (&guid,
this->guid_.get_buffer (),
this->guid_.length ());
// Inform the scheduler of the new scheduling segment.
this->scheduler_->begin_new_scheduling_segment (this->guid_,
name,
sched_param,
implicit_sched_param
);
if (CORBA::is_nil (this->dt_.in ()))
//Create new DT.
this->dt_ = TAO_DistributableThread_Factory::create_DT ();
//Add new DT to map
int result = this->dt_hash_->bind (this->guid_,
this->dt_);
// Error in binding to the map - cancel thread.
if (result != 0)
{
this->cancel_thread ();
}
// Remember parameters for the scheduling segment.
this->name_ = CORBA::string_dup (name);
this->sched_param_ = CORBA::Policy::_duplicate (sched_param);
this->implicit_sched_param_ = CORBA::Policy::_duplicate (implicit_sched_param);
}
else //Nested segment
{
// Check current DT state.
if (this->dt_->state () == RTScheduling::DistributableThread::CANCELLED)
{
this->cancel_thread ();
}
// Inform scheduler of start of nested scheduling segment.
this->scheduler_->begin_nested_scheduling_segment
(this->guid_,
name,
sched_param,
implicit_sched_param
);
TAO_TSS_Resources *tss =
TAO_TSS_Resources::instance ();
TAO_RTScheduler_Current_i* new_current = 0;
ACE_NEW_THROW_EX (new_current,
TAO_RTScheduler_Current_i (this->orb_,
this->dt_hash_,
this->guid_,
name,
sched_param,
implicit_sched_param,
this->dt_.in (),
this),
CORBA::NO_MEMORY (
CORBA::SystemException::_tao_minor_code (
TAO::VMCID,
ENOMEM),
CORBA::COMPLETED_NO));
tss->rtscheduler_current_impl_ = new_current;
}
}
void
TAO_RTScheduler_Current_i::update_scheduling_segment (const char * name,
CORBA::Policy_ptr sched_param,
CORBA::Policy_ptr implicit_sched_param
)
{
// Check if DT has been cancelled
if (this->dt_->state () == RTScheduling::DistributableThread::CANCELLED)
{
this->cancel_thread ();
}
// Let scheduler know of the updates.
this->scheduler_->update_scheduling_segment (this->guid_,
name,
sched_param,
implicit_sched_param
);
// Remember the new values.
this->name_ = CORBA::string_dup (name);
this->sched_param_ = CORBA::Policy::_duplicate (sched_param);
this->implicit_sched_param_ = CORBA::Policy::_duplicate (implicit_sched_param);
}
void
TAO_RTScheduler_Current_i::end_scheduling_segment (const char * name)
{
// Check if DT has been cancelled
if (this->dt_->state () == RTScheduling::DistributableThread::CANCELLED)
{
this->cancel_thread ();
}
if (this->previous_current_ == 0)
{
// Let the scheduler know that the DT is
// terminating.
this->scheduler_->end_scheduling_segment(this->guid_,
name
);
// Cleanup DT.
this->cleanup_DT ();
// Cleanup current.
this->cleanup_current ();
// A Nested segment.
} else {
// Inform scheduler of end of nested
// scheduling segment.
this->scheduler_->end_nested_scheduling_segment (this->guid_,
name,
this->previous_current_->sched_param_.in ()
);
// Cleanup current.
this->cleanup_current ();
}
}
// returns a null reference if
// the distributable thread is
// not known to the local scheduler
RTScheduling::DistributableThread_ptr
TAO_RTScheduler_Current_i::spawn (RTScheduling::ThreadAction_ptr start,
CORBA::VoidData data,
const char* name,
CORBA::Policy_ptr sched_param,
CORBA::Policy_ptr implicit_sched_param,
CORBA::ULong stack_size,
RTCORBA::Priority base_priority
)
{
// Check if DT has been cancelled.
if (this->dt_->state () == RTScheduling::DistributableThread::CANCELLED)
{
this->cancel_thread ();
}
// Create new task for new DT.
DTTask *dttask = 0;
// If no scheduling parameter is specified then use the current
// implicit scheduling parameter as the scheduling parameter
if (sched_param == 0)
sched_param = this->implicit_sched_param_.in ();
RTScheduling::DistributableThread_var dt = TAO_DistributableThread_Factory::create_DT ();
TAO_RTScheduler_Current_i *new_current = 0;
ACE_NEW_RETURN (new_current,
TAO_RTScheduler_Current_i (this->orb_,
this->dt_hash_),
0);
new_current->DT (dt.in ());
ACE_NEW_RETURN (dttask,
DTTask (//thread_manager_,
this->orb_,
this->dt_hash_,
new_current,
start,
data,
name,
sched_param,
implicit_sched_param),
0);
if (dttask->activate_task (base_priority,
stack_size) == -1)
{
TAOLIB_ERROR((LM_ERROR,
"Unable to activate DistributableThread\n"));
delete dttask;
return RTScheduling::DistributableThread::_nil ();
}
return dt._retn ();
}
int
DTTask::activate_task (RTCORBA::Priority base_priority,
CORBA::ULong stack_size
)
{
// Activate thread.
long default_flags = THR_NEW_LWP | THR_JOINABLE;
long flags =
default_flags |
this->orb_->orb_params ()->scope_policy () |
this->orb_->orb_params ()->sched_policy ();
CORBA::Object_var object =
this->orb_->object_ref_table ().resolve_initial_reference (
TAO_OBJID_PRIORITYMAPPINGMANAGER);
RTCORBA::PriorityMappingManager_var mapping_manager =
RTCORBA::PriorityMappingManager::_narrow (object.in ()
);
RTCORBA::PriorityMapping *pm =
mapping_manager->mapping ();
RTCORBA::NativePriority native_priority;
pm->to_native (base_priority,
native_priority);
size_t stack [1];
stack [0] = stack_size;
if (this->activate (flags,
1,
0,//force_active
native_priority,//priority
-1,//grp_id
0,//ACE_Task_Base
0,//thread_handles
0,//stack
stack//stack_size
) == -1)
{
if (ACE_OS::last_error () == EPERM)
TAOLIB_ERROR_RETURN ((LM_ERROR,
ACE_TEXT ("Insufficient privilege to run this test.\n")),
-1);
}
return 0;
}
DTTask::DTTask (TAO_ORB_Core *orb,
DT_Hash_Map *dt_hash,
TAO_RTScheduler_Current_i* new_current,
RTScheduling::ThreadAction_ptr start,
CORBA::VoidData data,
const char *name,
CORBA::Policy_ptr sched_param,
CORBA::Policy_ptr implicit_sched_param)
:orb_ (orb),
dt_hash_ (dt_hash),
current_ (new_current),
start_ (RTScheduling::ThreadAction::_duplicate (start)),
data_ (data),
name_ (CORBA::string_dup (name)),
sched_param_ (CORBA::Policy::_duplicate (sched_param)),
implicit_sched_param_ (CORBA::Policy::_duplicate (implicit_sched_param))
{
}
DTTask::~DTTask (void)
{
delete this->current_;
}
int
DTTask::svc (void)
{
try
{
TAO_TSS_Resources *tss =
TAO_TSS_Resources::instance ();
tss->rtscheduler_current_impl_ = this->current_;
this->current_->begin_scheduling_segment (this->name_.in (),
this->sched_param_.in (),
this->implicit_sched_param_.in ()
);
// Invoke entry point into new DT.
this->start_->_cxx_do (this->data_
);
this->current_->end_scheduling_segment (this->name_.in ()
);
}
catch (const ::CORBA::Exception& ex)
{
ex._tao_print_exception ("Caught exception:");
return -1;
}
return 0;
}
RTScheduling::Current::IdType *
TAO_RTScheduler_Current_i::id (void)
{
RTScheduling::Current::IdType_var guid = this->guid_;
return guid._retn ();
}
CORBA::Policy_ptr
TAO_RTScheduler_Current_i::scheduling_parameter (void)
{
return CORBA::Policy::_duplicate (this->sched_param_.in ());
}
CORBA::Policy_ptr
TAO_RTScheduler_Current_i::implicit_scheduling_parameter (void)
{
return CORBA::Policy::_duplicate (this->implicit_sched_param_.in ());
}
RTScheduling::Current::NameList *
TAO_RTScheduler_Current_i::current_scheduling_segment_names (void)
{
RTScheduling::Current::NameList* name_list;
ACE_NEW_RETURN (name_list,
RTScheduling::Current::NameList,
0);
TAO_RTScheduler_Current_i* current = this;
for (int index = 0; current != 0; index++)
{
name_list->length (index+1);
(*name_list) [index] = current->name ();
current = current->previous_current_;
}
return name_list;
}
const char*
TAO_RTScheduler_Current_i::name (void)
{
return this->name_.in ();
}
#if defined (THREAD_CANCELLED)
#undef THREAD_CANCELLED
#endif /* THREAD_CANCELLED */
void
TAO_RTScheduler_Current_i::cancel_thread (void)
{
size_t guid;
ACE_OS::memcpy (&guid,
this->guid_.get_buffer (),
this->guid_.length ());
TAOLIB_DEBUG ((LM_DEBUG,
"Distributable Thread - %d is cancelled\n",
guid));
// Let the scheduler know that the thread has
// been cancelled.
this->scheduler_->cancel (this->guid_
);
this->cleanup_DT ();
// Remove all related nested currents.
this->delete_all_currents ();
// Throw exception.
throw ::CORBA::THREAD_CANCELLED ();
}
void
TAO_RTScheduler_Current_i::cleanup_DT (void)
{
// Remove DT from map.
this->dt_hash_->unbind (this->guid_);
}
void
TAO_RTScheduler_Current_i::cleanup_current (void)
{
TAO_TSS_Resources *tss =
TAO_TSS_Resources::instance ();
tss->rtscheduler_current_impl_ = this->previous_current_;
// Delete this current.
delete this;
}
void
TAO_RTScheduler_Current_i::delete_all_currents (void)
{
TAO_RTScheduler_Current_i* current = this;
while (current != 0)
{
TAO_RTScheduler_Current_i* prev_current = current->previous_current_;
current->cleanup_current ();
current = prev_current;
}
TAO_TSS_Resources *tss =
TAO_TSS_Resources::instance ();
tss->rtscheduler_current_impl_ = tss->rtscheduler_previous_current_impl_;
}
void
TAO_RTScheduler_Current_i::id (RTScheduling::Current::IdType guid)
{
this->guid_ = guid;
}
void
TAO_RTScheduler_Current_i::name (const char * name)
{
this->name_ = CORBA::string_dup (name);
}
RTScheduling::DistributableThread_ptr
TAO_RTScheduler_Current_i::DT (void)
{
return this->dt_._retn ();
}
void
TAO_RTScheduler_Current_i::DT (RTScheduling::DistributableThread_ptr dt)
{
this->dt_ = RTScheduling::DistributableThread::_duplicate (dt);
}
void
TAO_RTScheduler_Current_i::scheduling_parameter (CORBA::Policy_ptr sched_param)
{
this->sched_param_ = CORBA::Policy::_duplicate (sched_param);
}
void
TAO_RTScheduler_Current_i::implicit_scheduling_parameter (CORBA::Policy_ptr implicit_sched_param)
{
this->implicit_sched_param_ = CORBA::Policy::_duplicate (implicit_sched_param);
}
// *************************************************************
// *************************************************************
// Operations for class TAO_RTScheduler_Current_var
// *************************************************************
TAO_RTScheduler_Current_var::TAO_RTScheduler_Current_var (void) // default constructor
: ptr_ (TAO_RTScheduler_Current::_nil ())
{}
::TAO_RTScheduler_Current_ptr
TAO_RTScheduler_Current_var::ptr (void) const
{
return this->ptr_;
}
TAO_RTScheduler_Current_var::TAO_RTScheduler_Current_var (const ::TAO_RTScheduler_Current_var &p)
: TAO_Base_var (),
ptr_ (TAO_RTScheduler_Current::_duplicate (p.ptr ()))
{}
TAO_RTScheduler_Current_var::~TAO_RTScheduler_Current_var (void) // destructor
{
::CORBA::release (this->ptr_);
}
TAO_RTScheduler_Current_var &
TAO_RTScheduler_Current_var::operator= (TAO_RTScheduler_Current_ptr p)
{
::CORBA::release (this->ptr_);
this->ptr_ = p;
return *this;
}
TAO_RTScheduler_Current_var &
TAO_RTScheduler_Current_var::operator= (const ::TAO_RTScheduler_Current_var &p)
{
if (this != &p)
{
::CORBA::release (this->ptr_);
this->ptr_ = ::TAO_RTScheduler_Current::_duplicate (p.ptr ());
}
return *this;
}
TAO_RTScheduler_Current_var::operator const ::TAO_RTScheduler_Current_ptr &() const
{
return this->ptr_;
}
TAO_RTScheduler_Current_var::operator ::TAO_RTScheduler_Current_ptr &()
{
return this->ptr_;
}
TAO_RTScheduler_Current_ptr
TAO_RTScheduler_Current_var::operator-> (void) const
{
return this->ptr_;
}
TAO_RTScheduler_Current_ptr
TAO_RTScheduler_Current_var::in (void) const
{
return this->ptr_;
}
TAO_RTScheduler_Current_ptr &
TAO_RTScheduler_Current_var::inout (void)
{
return this->ptr_;
}
TAO_RTScheduler_Current_ptr &
TAO_RTScheduler_Current_var::out (void)
{
::CORBA::release (this->ptr_);
this->ptr_ = ::TAO_RTScheduler_Current::_nil ();
return this->ptr_;
}
TAO_RTScheduler_Current_ptr
TAO_RTScheduler_Current_var::_retn (void)
{
// yield ownership of managed obj reference
::TAO_RTScheduler_Current_ptr val = this->ptr_;
this->ptr_ = ::TAO_RTScheduler_Current::_nil ();
return val;
}
TAO_RTScheduler_Current_ptr
TAO_RTScheduler_Current_var::duplicate (TAO_RTScheduler_Current_ptr p)
{
return ::TAO_RTScheduler_Current::_duplicate (p);
}
void
TAO_RTScheduler_Current_var::release (TAO_RTScheduler_Current_ptr p)
{
::CORBA::release (p);
}
TAO_RTScheduler_Current_ptr
TAO_RTScheduler_Current_var::nil (void)
{
return ::TAO_RTScheduler_Current::_nil ();
}
TAO_RTScheduler_Current_ptr
TAO_RTScheduler_Current_var::narrow (
CORBA::Object *p
)
{
return ::TAO_RTScheduler_Current::_narrow (p);
}
CORBA::Object *
TAO_RTScheduler_Current_var::upcast (void *src)
{
TAO_RTScheduler_Current **tmp =
static_cast<TAO_RTScheduler_Current **> (src);
return *tmp;
}
TAO_RTScheduler_Current_ptr TAO_RTScheduler_Current::_narrow (
CORBA::Object_ptr obj
)
{
return
TAO_RTScheduler_Current::_duplicate (
dynamic_cast<TAO_RTScheduler_Current *> (obj)
);
}
TAO_RTScheduler_Current_ptr
TAO_RTScheduler_Current::_duplicate (TAO_RTScheduler_Current_ptr obj)
{
if (!CORBA::is_nil (obj))
obj->_add_ref ();
return obj;
}
const char* TAO_RTScheduler_Current::_interface_repository_id (void) const
{
return "IDL:TAO_RTScheduler_Current:1.0";
}
TAO_END_VERSIONED_NAMESPACE_DECL
| 25,394 | 8,512 |
#pragma once
#include <string>
#include <list>
#include <vector>
#include <map>
#include <iterator>
using namespace std;
#include <initguid.h>
#include "CPP/7zip/Archive/IArchive.h"
| 184 | 71 |
/**
* @file Test.cc
* @brief Generated class Test source file.
*
* This class is a part of SmartObjects solution. It provides
* factory functionallity which allows client to use SmartSchemas
* in accordance with definitions from Test.xml file
*/
// Copyright (c) 2013, Ford Motor Company
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with the
// distribution.
//
// Neither the name of the Ford Motor Company nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <map>
#include <set>
#include "Test.h"
#include "SmartObjects/CAlwaysTrueSchemaItem.hpp"
#include "SmartObjects/CAlwaysFalseSchemaItem.hpp"
#include "SmartObjects/CArraySchemaItem.hpp"
#include "SmartObjects/CBoolSchemaItem.hpp"
#include "SmartObjects/CObjectSchemaItem.hpp"
#include "SmartObjects/CStringSchemaItem.hpp"
#include "SmartObjects/TEnumSchemaItem.hpp"
#include "SmartObjects/TNumberSchemaItem.hpp"
#include "SmartObjects/TSchemaItemParameter.hpp"
using namespace ns_smart_device_link::ns_smart_objects;
XXX::YYY::ZZZ::Test::Test()
: CSmartFactory<FunctionID::eType, messageType::eType, StructIdentifiers::eType>() {
TStructsSchemaItems struct_schema_items;
InitStructSchemes(struct_schema_items);
std::set<FunctionID::eType> function_id_items;
std::set<messageType::eType> message_type_items;
message_type_items.insert(messageType::request);
message_type_items.insert(messageType::response);
message_type_items.insert(messageType::notification);
message_type_items.insert(messageType::error_response);
InitFunctionSchemes(struct_schema_items, function_id_items, message_type_items);
}
TSharedPtr<ISchemaItem> XXX::YYY::ZZZ::Test::ProvideObjectSchemaItemForStruct(
const TStructsSchemaItems &struct_schema_items,
const StructIdentifiers::eType struct_id) {
const TStructsSchemaItems::const_iterator it = struct_schema_items.find(struct_id);
if (it != struct_schema_items.end()) {
return it->second;
}
return ns_smart_device_link::ns_smart_objects::CAlwaysFalseSchemaItem::create();
}
void XXX::YYY::ZZZ::Test::InitStructSchemes(
TStructsSchemaItems &struct_schema_items) {
TSharedPtr<ISchemaItem> struct_schema_item_Struct2 = InitStructSchemaItem_Struct2(struct_schema_items);
struct_schema_items.insert(std::make_pair(StructIdentifiers::Struct2, struct_schema_item_Struct2));
structs_schemes_.insert(std::make_pair(StructIdentifiers::Struct2, CSmartSchema(struct_schema_item_Struct2)));
TSharedPtr<ISchemaItem> struct_schema_item_Struct1 = InitStructSchemaItem_Struct1(struct_schema_items);
struct_schema_items.insert(std::make_pair(StructIdentifiers::Struct1, struct_schema_item_Struct1));
structs_schemes_.insert(std::make_pair(StructIdentifiers::Struct1, CSmartSchema(struct_schema_item_Struct1)));
}
void XXX::YYY::ZZZ::Test::InitFunctionSchemes(
const TStructsSchemaItems &struct_schema_items,
const std::set<FunctionID::eType> &function_id_items,
const std::set<messageType::eType> &message_type_items) {
std::map<std::string, SMember> params_members;
params_members[ns_smart_device_link::ns_json_handler::strings::S_FUNCTION_ID] = SMember(TEnumSchemaItem<FunctionID::eType>::create(function_id_items), true);
params_members[ns_smart_device_link::ns_json_handler::strings::S_MESSAGE_TYPE] = SMember(TEnumSchemaItem<messageType::eType>::create(message_type_items), true);
params_members[ns_smart_device_link::ns_json_handler::strings::S_PROTOCOL_VERSION] = SMember(TNumberSchemaItem<int>::create(), true);
params_members[ns_smart_device_link::ns_json_handler::strings::S_PROTOCOL_TYPE] = SMember(TNumberSchemaItem<int>::create(), true);
params_members[ns_smart_device_link::ns_json_handler::strings::S_CORRELATION_ID] = SMember(TNumberSchemaItem<int>::create(), true);
params_members[ns_smart_device_link::ns_json_handler::strings::kCode] = SMember(TNumberSchemaItem<int>::create(), true);
params_members[ns_smart_device_link::ns_json_handler::strings::kMessage] = SMember(CStringSchemaItem::create(), true);
std::map<std::string, SMember> root_members_map;
root_members_map[ns_smart_device_link::ns_json_handler::strings::S_PARAMS] = SMember(CObjectSchemaItem::create(params_members), true);
CSmartSchema error_response_schema(CObjectSchemaItem::create(root_members_map));
functions_schemes_.insert(std::make_pair(ns_smart_device_link::ns_json_handler::SmartSchemaKey<FunctionID::eType, messageType::eType>(FunctionID::val_1, messageType::error_response), error_response_schema));
functions_schemes_.insert(std::make_pair(ns_smart_device_link::ns_json_handler::SmartSchemaKey<FunctionID::eType, messageType::eType>(FunctionID::name1, messageType::request), InitFunction_name1_request(struct_schema_items, function_id_items, message_type_items)));
functions_schemes_.insert(std::make_pair(ns_smart_device_link::ns_json_handler::SmartSchemaKey<FunctionID::eType, messageType::eType>(FunctionID::val_1, messageType::response), InitFunction_val_1_response(struct_schema_items, function_id_items, message_type_items)));
functions_schemes_.insert(std::make_pair(ns_smart_device_link::ns_json_handler::SmartSchemaKey<FunctionID::eType, messageType::eType>(FunctionID::val_2, messageType::notification), InitFunction_val_2_notification(struct_schema_items, function_id_items, message_type_items)));
}
//------------- Functions schemes initialization -------------
CSmartSchema XXX::YYY::ZZZ::Test::InitFunction_name1_request(
const TStructsSchemaItems &struct_schema_items,
const std::set<FunctionID::eType> &function_id_items,
const std::set<messageType::eType> &message_type_items) {
std::set<Enum_new4::eType> Enum_new4_all_enum_values;
Enum_new4_all_enum_values.insert(Enum_new4::_11);
Enum_new4_all_enum_values.insert(Enum_new4::_22);
std::set<Enum1::eType> param2_allowed_enum_subset_values;
param2_allowed_enum_subset_values.insert(Enum1::name1);
// Function parameter param1.
//
// Description Line1
// Description Line2
//
// Design Line1
//
// Note: Issue1
// Note: Issue2
// Note: Issue3
//
// ToDo: Do1
// ToDo: Do2
TSharedPtr<ISchemaItem> param1_SchemaItem = TEnumSchemaItem<Enum_new4::eType>::create(Enum_new4_all_enum_values, TSchemaItemParameter<Enum_new4::eType>(Enum_new4::_11));
// Function parameter param2.
TSharedPtr<ISchemaItem> param2_SchemaItem = TEnumSchemaItem<Enum1::eType>::create(param2_allowed_enum_subset_values, TSchemaItemParameter<Enum1::eType>(name1));
std::map<std::string, SMember> schema_members;
schema_members["param1"] = SMember(param1_SchemaItem, true);
schema_members["param2"] = SMember(param2_SchemaItem, true);
std::map<std::string, SMember> params_members;
params_members[ns_smart_device_link::ns_json_handler::strings::S_FUNCTION_ID] = SMember(TEnumSchemaItem<FunctionID::eType>::create(function_id_items), true);
params_members[ns_smart_device_link::ns_json_handler::strings::S_MESSAGE_TYPE] = SMember(TEnumSchemaItem<messageType::eType>::create(message_type_items), true);
params_members[ns_smart_device_link::ns_json_handler::strings::S_PROTOCOL_VERSION] = SMember(TNumberSchemaItem<int>::create(), true);
params_members[ns_smart_device_link::ns_json_handler::strings::S_PROTOCOL_TYPE] = SMember(TNumberSchemaItem<int>::create(), true);
params_members[ns_smart_device_link::ns_json_handler::strings::S_CORRELATION_ID] = SMember(TNumberSchemaItem<int>::create(), true);
std::map<std::string, SMember> root_members_map;
root_members_map[ns_smart_device_link::ns_json_handler::strings::S_MSG_PARAMS] = SMember(CObjectSchemaItem::create(schema_members), true);
root_members_map[ns_smart_device_link::ns_json_handler::strings::S_PARAMS] = SMember(CObjectSchemaItem::create(params_members), true);
return CSmartSchema(CObjectSchemaItem::create(root_members_map));
}
CSmartSchema XXX::YYY::ZZZ::Test::InitFunction_val_1_response(
const TStructsSchemaItems &struct_schema_items,
const std::set<FunctionID::eType> &function_id_items,
const std::set<messageType::eType> &message_type_items) {
std::map<std::string, SMember> schema_members;
std::map<std::string, SMember> params_members;
params_members[ns_smart_device_link::ns_json_handler::strings::S_FUNCTION_ID] = SMember(TEnumSchemaItem<FunctionID::eType>::create(function_id_items), true);
params_members[ns_smart_device_link::ns_json_handler::strings::S_MESSAGE_TYPE] = SMember(TEnumSchemaItem<messageType::eType>::create(message_type_items), true);
params_members[ns_smart_device_link::ns_json_handler::strings::S_PROTOCOL_VERSION] = SMember(TNumberSchemaItem<int>::create(), true);
params_members[ns_smart_device_link::ns_json_handler::strings::S_PROTOCOL_TYPE] = SMember(TNumberSchemaItem<int>::create(), true);
params_members[ns_smart_device_link::ns_json_handler::strings::S_CORRELATION_ID] = SMember(TNumberSchemaItem<int>::create(), true);
params_members[ns_smart_device_link::ns_json_handler::strings::kCode] = SMember(TNumberSchemaItem<int>::create(), true);
std::map<std::string, SMember> root_members_map;
root_members_map[ns_smart_device_link::ns_json_handler::strings::S_MSG_PARAMS] = SMember(CObjectSchemaItem::create(schema_members), true);
root_members_map[ns_smart_device_link::ns_json_handler::strings::S_PARAMS] = SMember(CObjectSchemaItem::create(params_members), true);
return CSmartSchema(CObjectSchemaItem::create(root_members_map));
}
CSmartSchema XXX::YYY::ZZZ::Test::InitFunction_val_2_notification(
const TStructsSchemaItems &struct_schema_items,
const std::set<FunctionID::eType> &function_id_items,
const std::set<messageType::eType> &message_type_items) {
std::map<std::string, SMember> schema_members;
std::map<std::string, SMember> params_members;
params_members[ns_smart_device_link::ns_json_handler::strings::S_FUNCTION_ID] = SMember(TEnumSchemaItem<FunctionID::eType>::create(function_id_items), true);
params_members[ns_smart_device_link::ns_json_handler::strings::S_MESSAGE_TYPE] = SMember(TEnumSchemaItem<messageType::eType>::create(message_type_items), true);
params_members[ns_smart_device_link::ns_json_handler::strings::S_PROTOCOL_VERSION] = SMember(TNumberSchemaItem<int>::create(), true);
params_members[ns_smart_device_link::ns_json_handler::strings::S_PROTOCOL_TYPE] = SMember(TNumberSchemaItem<int>::create(), true);
std::map<std::string, SMember> root_members_map;
root_members_map[ns_smart_device_link::ns_json_handler::strings::S_MSG_PARAMS] = SMember(CObjectSchemaItem::create(schema_members), true);
root_members_map[ns_smart_device_link::ns_json_handler::strings::S_PARAMS] = SMember(CObjectSchemaItem::create(params_members), true);
return CSmartSchema(CObjectSchemaItem::create(root_members_map));
}
//----------- Structs schema items initialization ------------
TSharedPtr<ISchemaItem> XXX::YYY::ZZZ::Test::InitStructSchemaItem_Struct1(
const TStructsSchemaItems &struct_schema_items) {
std::set<Enum1::eType> Enum1_all_enum_values;
Enum1_all_enum_values.insert(Enum1::name1);
Enum1_all_enum_values.insert(Enum1::internal_name2);
std::set<Enum1::eType> enumSubset1_allowed_enum_subset_values;
enumSubset1_allowed_enum_subset_values.insert(Enum1::name1);
std::set<Enum_new2::eType> Enum_new2_all_enum_values;
Enum_new2_all_enum_values.insert(Enum_new2::_1);
Enum_new2_all_enum_values.insert(Enum_new2::_2);
Enum_new2_all_enum_values.insert(Enum_new2::_3);
std::set<Enum1::eType> sub1_allowed_enum_subset_values;
sub1_allowed_enum_subset_values.insert(Enum1::name1);
std::set<Enum1::eType> sub2_allowed_enum_subset_values;
sub2_allowed_enum_subset_values.insert(Enum1::internal_name2);
std::set<Enum_new4::eType> sub3_allowed_enum_subset_values;
sub3_allowed_enum_subset_values.insert(Enum_new4::_22);
// Struct member intParam.
TSharedPtr<ISchemaItem> intParam_SchemaItem = TNumberSchemaItem<int>::create(TSchemaItemParameter<int>(), TSchemaItemParameter<int>(2), TSchemaItemParameter<int>());
// Struct member doubleParam.
TSharedPtr<ISchemaItem> doubleParam_SchemaItem = TNumberSchemaItem<double>::create(TSchemaItemParameter<double>(0.333), TSchemaItemParameter<double>(), TSchemaItemParameter<double>());
// Struct member boolParam.
TSharedPtr<ISchemaItem> boolParam_SchemaItem = CBoolSchemaItem::create(TSchemaItemParameter<bool>());
// Struct member structParam.
TSharedPtr<ISchemaItem> structParam_SchemaItem = ProvideObjectSchemaItemForStruct(struct_schema_items, StructIdentifiers::Struct2);
// Struct member enumParam.
TSharedPtr<ISchemaItem> enumParam_SchemaItem = TEnumSchemaItem<Enum1::eType>::create(Enum1_all_enum_values, TSchemaItemParameter<Enum1::eType>());
// Struct member enumParam1.
TSharedPtr<ISchemaItem> enumParam1_SchemaItem = TEnumSchemaItem<Enum1::eType>::create(Enum1_all_enum_values, TSchemaItemParameter<Enum1::eType>());
// Struct member enumSubset1.
TSharedPtr<ISchemaItem> enumSubset1_SchemaItem = TEnumSchemaItem<Enum1::eType>::create(enumSubset1_allowed_enum_subset_values, TSchemaItemParameter<Enum1::eType>());
// Struct member arrayOfInt.
TSharedPtr<ISchemaItem> arrayOfInt_SchemaItem = CArraySchemaItem::create(CBoolSchemaItem::create(TSchemaItemParameter<bool>()), TSchemaItemParameter<size_t>(0), TSchemaItemParameter<size_t>(20));
// Struct member arrayOfEnum1.
TSharedPtr<ISchemaItem> arrayOfEnum1_SchemaItem = CArraySchemaItem::create(TEnumSchemaItem<Enum1::eType>::create(Enum1_all_enum_values, TSchemaItemParameter<Enum1::eType>()), TSchemaItemParameter<size_t>(0), TSchemaItemParameter<size_t>(20));
// Struct member arrayOfEnum3.
TSharedPtr<ISchemaItem> arrayOfEnum3_SchemaItem = CArraySchemaItem::create(TEnumSchemaItem<Enum_new2::eType>::create(Enum_new2_all_enum_values, TSchemaItemParameter<Enum_new2::eType>()), TSchemaItemParameter<size_t>(10), TSchemaItemParameter<size_t>(40));
// Struct member arrayOfEnum4.
TSharedPtr<ISchemaItem> arrayOfEnum4_SchemaItem = CArraySchemaItem::create(TEnumSchemaItem<Enum1::eType>::create(sub1_allowed_enum_subset_values, TSchemaItemParameter<Enum1::eType>()), TSchemaItemParameter<size_t>(10), TSchemaItemParameter<size_t>(41));
// Struct member arrayOfEnum5.
TSharedPtr<ISchemaItem> arrayOfEnum5_SchemaItem = CArraySchemaItem::create(TEnumSchemaItem<Enum1::eType>::create(sub2_allowed_enum_subset_values, TSchemaItemParameter<Enum1::eType>()), TSchemaItemParameter<size_t>(10), TSchemaItemParameter<size_t>(42));
// Struct member arrayOfEnum6.
TSharedPtr<ISchemaItem> arrayOfEnum6_SchemaItem = CArraySchemaItem::create(TEnumSchemaItem<Enum_new4::eType>::create(sub3_allowed_enum_subset_values, TSchemaItemParameter<Enum_new4::eType>()), TSchemaItemParameter<size_t>(10), TSchemaItemParameter<size_t>(43));
std::map<std::string, SMember> schema_members;
schema_members["intParam"] = SMember(intParam_SchemaItem, true);
schema_members["doubleParam"] = SMember(doubleParam_SchemaItem, false);
schema_members["boolParam"] = SMember(boolParam_SchemaItem, true);
schema_members["structParam"] = SMember(structParam_SchemaItem, true);
schema_members["enumParam"] = SMember(enumParam_SchemaItem, true);
schema_members["enumParam1"] = SMember(enumParam1_SchemaItem, true);
schema_members["enumSubset1"] = SMember(enumSubset1_SchemaItem, false);
schema_members["arrayOfInt"] = SMember(arrayOfInt_SchemaItem, false);
schema_members["arrayOfEnum1"] = SMember(arrayOfEnum1_SchemaItem, false);
schema_members["arrayOfEnum3"] = SMember(arrayOfEnum3_SchemaItem, true);
schema_members["arrayOfEnum4"] = SMember(arrayOfEnum4_SchemaItem, true);
schema_members["arrayOfEnum5"] = SMember(arrayOfEnum5_SchemaItem, true);
schema_members["arrayOfEnum6"] = SMember(arrayOfEnum6_SchemaItem, true);
return CObjectSchemaItem::create(schema_members);
}
TSharedPtr<ISchemaItem> XXX::YYY::ZZZ::Test::InitStructSchemaItem_Struct2(
const TStructsSchemaItems &struct_schema_items) {
std::map<std::string, SMember> schema_members;
return CObjectSchemaItem::create(schema_members);
}
//-------------- String to value enum mapping ----------------
namespace ns_smart_device_link {
namespace ns_smart_objects {
template <>
const std::map<XXX::YYY::ZZZ::Enum1::eType, std::string> &TEnumSchemaItem<XXX::YYY::ZZZ::Enum1::eType>::getEnumElementsStringRepresentation() {
static bool is_initialized = false;
static std::map<XXX::YYY::ZZZ::Enum1::eType, std::string> enum_string_representation;
if (false == is_initialized) {
enum_string_representation.insert(std::make_pair(XXX::YYY::ZZZ::Enum1::name1, "name1"));
enum_string_representation.insert(std::make_pair(XXX::YYY::ZZZ::Enum1::internal_name2, "name2"));
is_initialized = true;
}
return enum_string_representation;
}
template <>
const std::map<XXX::YYY::ZZZ::E2::eType, std::string> &TEnumSchemaItem<XXX::YYY::ZZZ::E2::eType>::getEnumElementsStringRepresentation() {
static bool is_initialized = false;
static std::map<XXX::YYY::ZZZ::E2::eType, std::string> enum_string_representation;
if (false == is_initialized) {
enum_string_representation.insert(std::make_pair(XXX::YYY::ZZZ::E2::val_1, "xxx"));
enum_string_representation.insert(std::make_pair(XXX::YYY::ZZZ::E2::val_2, "yyy"));
enum_string_representation.insert(std::make_pair(XXX::YYY::ZZZ::E2::val_3, "val_3"));
is_initialized = true;
}
return enum_string_representation;
}
template <>
const std::map<XXX::YYY::ZZZ::Enum_new2::eType, std::string> &TEnumSchemaItem<XXX::YYY::ZZZ::Enum_new2::eType>::getEnumElementsStringRepresentation() {
static bool is_initialized = false;
static std::map<XXX::YYY::ZZZ::Enum_new2::eType, std::string> enum_string_representation;
if (false == is_initialized) {
enum_string_representation.insert(std::make_pair(XXX::YYY::ZZZ::Enum_new2::_1, "xxx"));
enum_string_representation.insert(std::make_pair(XXX::YYY::ZZZ::Enum_new2::_2, "xxx"));
enum_string_representation.insert(std::make_pair(XXX::YYY::ZZZ::Enum_new2::_3, "xxx"));
is_initialized = true;
}
return enum_string_representation;
}
template <>
const std::map<XXX::YYY::ZZZ::Enum_new4::eType, std::string> &TEnumSchemaItem<XXX::YYY::ZZZ::Enum_new4::eType>::getEnumElementsStringRepresentation() {
static bool is_initialized = false;
static std::map<XXX::YYY::ZZZ::Enum_new4::eType, std::string> enum_string_representation;
if (false == is_initialized) {
enum_string_representation.insert(std::make_pair(XXX::YYY::ZZZ::Enum_new4::_11, "xxx"));
enum_string_representation.insert(std::make_pair(XXX::YYY::ZZZ::Enum_new4::_22, "xxx"));
is_initialized = true;
}
return enum_string_representation;
}
template <>
const std::map<XXX::YYY::ZZZ::messageType::eType, std::string> &TEnumSchemaItem<XXX::YYY::ZZZ::messageType::eType>::getEnumElementsStringRepresentation() {
static bool is_initialized = false;
static std::map<XXX::YYY::ZZZ::messageType::eType, std::string> enum_string_representation;
if (false == is_initialized) {
enum_string_representation.insert(std::make_pair(XXX::YYY::ZZZ::messageType::request, "request"));
enum_string_representation.insert(std::make_pair(XXX::YYY::ZZZ::messageType::response, "response"));
enum_string_representation.insert(std::make_pair(XXX::YYY::ZZZ::messageType::notification, "notification"));
enum_string_representation.insert(std::make_pair(XXX::YYY::ZZZ::messageType::error_response, "error_response"));
is_initialized = true;
}
return enum_string_representation;
}
} // ns_smart_objects
} // ns_smart_device_link
| 20,875 | 7,182 |
#pragma once
#include <redx/core/platform.hpp>
#include <nlohmann/json.hpp>
#include <redx/core/stringpool.hpp>
#include <redx/core/gstring.hpp>
namespace redx {
inline constexpr uint32_t gstring_name_category_tag = 'GNAM';
using gname = gstring<gstring_name_category_tag>;
namespace literals {
using literal_gname_helper = literal_gstring_helper<gstring_name_category_tag>;
#if __cpp_nontype_template_args >= 201911 && !defined(__INTELLISENSE__)
// todo: finish that when c++20 finally works in msvc..
template <literal_gname_helper::builder Builder>
constexpr literal_gname_helper::singleton<Builder>::gstring_builder operator""_gndef()
{
return literal_gname_helper::singleton<Builder>::gstring_builder();
}
template <literal_gname_helper::builder Builder>
constexpr literal_gname_helper::singleton<Builder>::gstrid_builder operator""_gndef_id()
{
return literal_gname_helper::singleton<Builder>::gstrid_builder();
}
#else
// does register the name
constexpr literal_gname_helper::gstring_builder operator""_gndef(const char* s, std::size_t)
{
return literal_gname_helper::gstring_builder(s);
}
//constexpr literal_gname_helper::gstrid_builder operator""_gnid(const char* s, std::size_t)
//{
// return literal_gname_helper::gstrid_builder(s);
//}
#endif
inline constexpr auto gn_test1 = literal_gname_helper::builder("test1");
inline constexpr auto gn_test2 = "test2"_gndef;
} // namespace literals
using literals::operator""_gndef;
} // namespace redx
| 1,539 | 557 |
#pragma once
#import <MetalKit/MetalKit.h>
#include "drape/graphics_context.hpp"
#include "drape/metal/metal_gpu_program.hpp"
#include "drape/pointers.hpp"
#include "drape/texture_types.hpp"
#include <cstdint>
#include <map>
namespace dp
{
namespace metal
{
class MetalStates
{
public:
struct DepthStencilKey
{
void SetDepthTestEnabled(bool enabled);
void SetDepthTestFunction(TestFunction depthFunction);
void SetStencilTestEnabled(bool enabled);
void SetStencilFunction(StencilFace face, TestFunction stencilFunction);
void SetStencilActions(StencilFace face, StencilAction stencilFailAction,
StencilAction depthFailAction, StencilAction passAction);
bool operator<(DepthStencilKey const & rhs) const;
MTLDepthStencilDescriptor * BuildDescriptor() const;
bool m_depthEnabled = false;
bool m_stencilEnabled = false;
TestFunction m_depthFunction = TestFunction::Always;
uint64_t m_stencil = 0;
};
struct PipelineKey
{
PipelineKey() = default;
PipelineKey(ref_ptr<GpuProgram> program, MTLPixelFormat colorFormat,
MTLPixelFormat depthStencilFormat, bool blendingEnabled);
bool operator<(PipelineKey const & rhs) const;
MTLRenderPipelineDescriptor * BuildDescriptor() const;
ref_ptr<GpuProgram> m_program;
MTLPixelFormat m_colorFormat = MTLPixelFormatInvalid;
MTLPixelFormat m_depthStencilFormat = MTLPixelFormatInvalid;
bool m_blendingEnabled = false;
};
struct SamplerKey
{
SamplerKey() = default;
SamplerKey(TextureFilter filter, TextureWrapping wrapSMode, TextureWrapping wrapTMode);
void Set(TextureFilter filter, TextureWrapping wrapSMode, TextureWrapping wrapTMode);
bool operator<(SamplerKey const & rhs) const;
MTLSamplerDescriptor * BuildDescriptor() const;
uint32_t m_sampler = 0;
};
id<MTLDepthStencilState> GetDepthStencilState(id<MTLDevice> device, DepthStencilKey const & key);
id<MTLRenderPipelineState> GetPipelineState(id<MTLDevice> device, PipelineKey const & key);
id<MTLSamplerState> GetSamplerState(id<MTLDevice> device, SamplerKey const & key);
void ResetPipelineStatesCache();
private:
using DepthStencilCache = std::map<DepthStencilKey, id<MTLDepthStencilState>>;
DepthStencilCache m_depthStencilCache;
using PipelineCache = std::map<PipelineKey, id<MTLRenderPipelineState>>;
PipelineCache m_pipelineCache;
using SamplerCache = std::map<SamplerKey, id<MTLSamplerState>>;
SamplerCache m_samplerCache;
};
} // namespace metal
} // namespace dp
| 2,591 | 869 |
/*++
Copyright (c) 2001 Microsoft Corporation
Module Name :
options_handler.cxx
Abstract:
Handle OPTIONS requests
Author:
Anil Ruia (AnilR) 4-Apr-2001
Environment:
Win32 - User Mode
Project:
ULW3.DLL
--*/
#include "precomp.hxx"
#include "options_handler.hxx"
CONTEXT_STATUS
W3_OPTIONS_HANDLER::DoWork()
/*++
Routine Description:
Do the OPTIONS thing if DAV is disabled
Return Value:
CONTEXT_STATUS_PENDING if async pending, else CONTEXT_STATUS_CONTINUE
--*/
{
HRESULT hr;
W3_CONTEXT *pW3Context = QueryW3Context();
DBG_ASSERT(pW3Context != NULL);
W3_RESPONSE *pW3Response = pW3Context->QueryResponse();
W3_REQUEST *pW3Request = pW3Context->QueryRequest();
STACK_STRU (strUrl, MAX_PATH);
if (FAILED(hr = pW3Response->SetHeader(HEADER("Public"),
HEADER("OPTIONS, TRACE, GET, HEAD, POST"))))
{
goto Failed;
}
if (FAILED(hr = pW3Request->GetUrl(&strUrl)))
{
goto Failed;
}
if (wcscmp(strUrl.QueryStr(), L"*") != 0 &&
wcscmp(strUrl.QueryStr(), L"/*") != 0)
{
//
// Add Allow header
//
if (FAILED(hr = pW3Context->SetupAllowHeader()))
{
goto Failed;
}
//
// Also figure out whether Frontpage is enabled and send
// MS-Author-Via header if so
// Cannot store it with the metadata since we do not want to pick
// up the inherited value, can store with url-info but deferred
// for later (BUGBUG)
//
MB mb( g_pW3Server->QueryMDObject() );
BOOL fIsFrontPageWeb;
if (!mb.Open(pW3Context->QuerySite()->QueryMBRoot()->QueryStr()))
{
hr = HRESULT_FROM_WIN32(GetLastError());
goto Failed;
}
if (mb.GetDword(strUrl.QueryStr(),
MD_FRONTPAGE_WEB,
IIS_MD_UT_SERVER,
(DWORD *)&fIsFrontPageWeb,
METADATA_NO_ATTRIBUTES) &&
fIsFrontPageWeb)
{
if (FAILED(hr = pW3Response->SetHeader(HEADER("MS-Author-Via"),
HEADER("MS-FP/4.0"))))
{
goto Failed;
}
}
DBG_REQUIRE( mb.Close() );
}
else
{
pW3Response->SetHeaderByReference(HttpHeaderAllow,
HEADER("OPTIONS, TRACE, GET, HEAD, POST"));
}
if (FAILED(hr = pW3Context->SendResponse(W3_FLAG_ASYNC)))
{
goto Failed;
}
return CONTEXT_STATUS_PENDING;
Failed:
pW3Context->SetErrorStatus(hr);
pW3Response->SetStatus(HttpStatusServerError);
pW3Context->SendResponse(W3_FLAG_SYNC);
return CONTEXT_STATUS_CONTINUE;
}
| 2,998 | 1,044 |
#include <iostream>
#include "DataBus.h"
#include "ControlLines.h"
void TestDataBusWrite()
{
std::cout << "Testing the address bus\n";
ControlLines the_control_lines(HIGH, HIGH, HIGH);
DataBus the_data_bus(true);
unsigned short data = 1;
for (unsigned char i = 0; i < 8;i++) {
the_data_bus.Set(data);
std::cout << "Data bus set to 0x" << std::hex << data << "\n";
std::cin.get();
data <<= 1;
}
}
int main()
{
TestDataBusWrite();
return 0;
}
| 467 | 205 |
// The MIT License (MIT)
// Copyright (c) 2013 lailongwei<lailongwei@126.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include "llbc/common/Export.h"
#include "llbc/common/BeforeIncl.h"
#include "llbc/common/Config.h"
#include "llbc/core/os/OS_Console.h"
#include "llbc/core/utils/Util_Debug.h"
#include "llbc/core/objbase/Object.h"
#include "llbc/core/objbase/KeyHashAlgorithm.h"
#include "llbc/core/objbase/DictionaryElem.h"
__LLBC_INTERNAL_NS_BEGIN
static LLBC_NS LLBC_String __emptyStrKey;
__LLBC_INTERNAL_NS_END
__LLBC_NS_BEGIN
LLBC_DictionaryElem::LLBC_DictionaryElem(int key, LLBC_Object *o)
: _intKey(key)
, _strKey(NULL)
, _hash(0)
, _obj(o)
, _bucket(NULL)
, _bucketSize(0)
, _prev(NULL)
, _next(NULL)
, _bucketPrev(NULL)
, _bucketNext(NULL)
, _hashFun(*LLBC_KeyHashAlgorithmSingleton->GetAlgorithm(LLBC_CFG_OBJBASE_DICT_KEY_HASH_ALGO))
{
o->Retain();
}
LLBC_DictionaryElem::LLBC_DictionaryElem(const LLBC_String &key, LLBC_Object *o)
: _intKey(0)
, _strKey(LLBC_New(LLBC_String, key))
, _hash(0)
, _obj(o)
, _bucket(NULL)
, _bucketSize(0)
, _prev(NULL)
, _next(NULL)
, _bucketPrev(NULL)
, _bucketNext(NULL)
, _hashFun(*LLBC_KeyHashAlgorithmSingleton->GetAlgorithm(LLBC_CFG_OBJBASE_DICT_KEY_HASH_ALGO))
{
o->Retain();
}
LLBC_DictionaryElem::~LLBC_DictionaryElem()
{
LLBC_XDelete(_strKey);
_obj->Release();
}
bool LLBC_DictionaryElem::IsIntKey() const
{
return !_strKey;
}
bool LLBC_DictionaryElem::IsStrKey() const
{
return !!_strKey;
}
const int &LLBC_DictionaryElem::GetIntKey() const
{
return _intKey;
}
const LLBC_String &LLBC_DictionaryElem::GetStrKey() const
{
return _strKey ? *_strKey : LLBC_INL_NS __emptyStrKey;
}
uint32 LLBC_DictionaryElem::GetHashValue() const
{
return _hash;
}
LLBC_Object *&LLBC_DictionaryElem::GetObject()
{
return _obj;
}
LLBC_Object * const &LLBC_DictionaryElem::GetObject() const
{
return _obj;
}
void LLBC_DictionaryElem::Hash(LLBC_DictionaryElem **bucket, size_t bucketSize)
{
_bucket = bucket;
_bucketSize = bucketSize;
// Generate hash key.
if(IsIntKey())
{
_hash = _intKey % _bucketSize;
}
else
{
_hash = _hashFun(_strKey->c_str(),
_strKey->size()) % static_cast<uint32>(_bucketSize);
}
// Link to hash bucket.
SetBucketElemPrev(NULL);
LLBC_DictionaryElem *&hashed = _bucket[_hash];
if(!hashed)
{
SetBucketElemNext(NULL);
hashed = this;
}
else
{
hashed->SetBucketElemPrev(this);
SetBucketElemNext(hashed);
hashed = this;
#ifdef LLBC_DEBUG
int confictCount = 0;
LLBC_DictionaryElem *countElem = hashed;
for(; countElem != NULL; countElem = countElem->GetBucketElemNext())
{
confictCount += 1;
}
trace("Dictionary(addr: %x), key confict!, bucket: %d, count: %d\n", this, _hash, confictCount);
#endif
}
}
void LLBC_DictionaryElem::CancelHash()
{
if(_bucket[_hash] == this)
{
_bucket[_hash] = GetBucketElemNext();
}
if(GetBucketElemPrev())
{
GetBucketElemPrev()->
SetBucketElemNext(GetBucketElemNext());
}
if(GetBucketElemNext())
{
GetBucketElemNext()->
SetBucketElemPrev(GetBucketElemPrev());
}
}
LLBC_DictionaryElem **LLBC_DictionaryElem::GetBucket()
{
return _bucket;
}
size_t LLBC_DictionaryElem::GetBucketSize() const
{
return _bucketSize;
}
LLBC_DictionaryElem *LLBC_DictionaryElem::GetElemPrev()
{
return _prev;
}
const LLBC_DictionaryElem *LLBC_DictionaryElem::GetElemPrev() const
{
return _prev;
}
void LLBC_DictionaryElem::SetElemPrev(LLBC_DictionaryElem *prev)
{
_prev = prev;
}
LLBC_DictionaryElem *LLBC_DictionaryElem::GetElemNext()
{
return _next;
}
const LLBC_DictionaryElem *LLBC_DictionaryElem::GetElemNext() const
{
return _next;
}
void LLBC_DictionaryElem::SetElemNext(LLBC_DictionaryElem *next)
{
_next = next;
}
LLBC_DictionaryElem *LLBC_DictionaryElem::GetBucketElemPrev()
{
return _bucketPrev;
}
const LLBC_DictionaryElem *LLBC_DictionaryElem::GetBucketElemPrev() const
{
return _bucketPrev;
}
void LLBC_DictionaryElem::SetBucketElemPrev(LLBC_DictionaryElem *prev)
{
_bucketPrev = prev;
}
LLBC_DictionaryElem *LLBC_DictionaryElem::GetBucketElemNext()
{
return _bucketNext;
}
const LLBC_DictionaryElem *LLBC_DictionaryElem::GetBucketElemNext() const
{
return _bucketNext;
}
void LLBC_DictionaryElem::SetBucketElemNext(LLBC_DictionaryElem *next)
{
_bucketNext = next;
}
LLBC_Object *&LLBC_DictionaryElem::operator *()
{
return _obj;
}
LLBC_Object * const &LLBC_DictionaryElem::operator *() const
{
return _obj;
}
__LLBC_NS_END
#include "llbc/common/AfterIncl.h"
| 5,822 | 2,247 |
#include <iostream>
#include "./EntityManager.h"
#include "./Collision.h"
#include "./components/ColliderComponent.h"
void EntityManager::ClearData() {
for (auto& entity: entities) {
entity->Destroy();
}
}
bool EntityManager::HasNoEntities() {
return entities.size() == 0;
}
void EntityManager::Update(float deltaTime) {
for (auto& entity: entities) {
entity->Update(deltaTime);
}
}
void EntityManager::Render() {
for (int layerNum = 0; layerNum < NUM_LAYERS; layerNum++){
for (auto& entity: GetEntitiesByLayer(static_cast<LayerType>(layerNum))) {
entity->Render();
}
}
}
Entity& EntityManager::AddEntity(std::string entityName, LayerType layer) {
Entity *entity = new Entity(*this, entityName, layer);
entities.emplace_back(entity);
return *entity;
}
std::vector<Entity*> EntityManager::GetEntities() const {
return entities;
}
std::vector<Entity*> EntityManager::GetEntitiesByLayer(LayerType layer) const {
std::vector<Entity*> selectedEntities;
for (auto& entity: entities) {
if (entity->layer == layer) {
selectedEntities.emplace_back(entity);
}
}
return selectedEntities;
}
std::string EntityManager::CheckEntityCollisions(Entity& myEntity) const {
ColliderComponent* myCollider = myEntity.GetComponent<ColliderComponent>();
for (auto& entity: entities) {
if (entity->name.compare(myEntity.name) != 0 && entity->name.compare("Tile") != 0) {
if (entity->HasComponent<ColliderComponent>()) {
ColliderComponent* otherCollider = entity->GetComponent<ColliderComponent>();
if (Collision::CheckRectangleCollision(myCollider->collider, otherCollider->collider)) {
return otherCollider->colliderTag;
}
}
}
}
return std::string();
}
bool EntityManager::IsDebug() const { return this->isDebug; }
void EntityManager::ToggleDebug() { this->isDebug = !this->isDebug; }
unsigned int EntityManager::GetEntityCount() {
return entities.size();
}
void EntityManager::ListAllEntities() {
for (auto& entity: entities) {
std::cout << "Entity name: " << entity->name << std::endl;
entity->ListAllComponents();
}
}
| 2,295 | 673 |
//이건
#include <llvm/Transforms/Utils/BasicBlockUtils.h>
#include <llvm/Transforms/Utils/Local.h>
#include <llvm/ADT/Statistic.h>
#include <llvm/IR/InstIterator.h>
#include <llvm/IR/IntrinsicInst.h>
#include <map>
#include <set>
#include "util.h"
#include "MPAvailable.h"
#define DEBUG_TYPE "deltatags-prop"
using namespace llvm;
enum ArithCheckMode { nocheck, satarith, branch };
static cl::opt<bool> EnablePtrArith(
"deltatags-enable-ptr-arith",
cl::desc("Enable pointer arithmetic propagation to metadata bits"),
cl::init(true));
static cl::opt<bool> EnableMemIntrinsics(
"deltatags-enable-mem-intrinsics",
cl::desc("Enable checks on memory intrinsics (e.g., memcpy)"),
cl::init(true));
static cl::opt<bool>
SubtractionArith("deltatags-sub-arith",
cl::desc("Use pointer subtraction for non-constant "
"pointer arithmetic propagation"),
cl::init(false));
static cl::opt<enum ArithCheckMode> CheckOverflow(
"deltatags-check-overflow",
cl::desc("Add overflow checks to GEPs with positive or dynamic offsets:"),
cl::values(clEnumValN(nocheck, "none", "No overflow check (default)"),
clEnumVal(satarith, "Corrupt pointer on overflow (replace with "
"NULL) using setcc instructions"),
clEnumVal(branch, "Branch to error code on overflow"),
clEnumValEnd),
cl::init(nocheck));
// This is only necessary for dealII in SPEC, and adds minor runtime overhead
static cl::opt<bool> CheckUnderflow(
"deltatags-check-underflow",
cl::desc("Add runtime checks on zero metadata (implemented as cmov on x86) "
"at negative GEPs to avoid underflows"),
cl::init(true));
static cl::opt<bool> DisallowUnalignedAccess(
"deltatags-no-unaligned",
cl::desc("Disallow unaligned access by adding (derefsize - 1) to the size "
"tag before masking at dereference"),
cl::init(false));
struct MPProp : public FunctionPass {
static char ID;
MPProp() : FunctionPass(ID) {}
virtual void getAnalysisUsage(AnalysisUsage &AU) const;
private:
const DataLayout *DL;
Function *StrBufSizeFunc; //이런 것들은 나중에 해
Function *NewStrtokFunc; //이것도
Function *AddWithOverflowFunc; //이것도 지금은 걍 일반적인 포인터에 대해서만 해보자
Function *TrapFunc;
MPAvailable *SafeAlloc;
DominatorTree *DT;
DenseMap<Function *, BasicBlock *> ErrorBlocks;
DenseMap<Value *, GetElementPtrInst *> ReplacedPtrArithReverse;
DenseMap<GetElementPtrInst *, uint64_t> DerefBytes;
bool hasNegativeOffset(GetElementPtrInst *GEP);
bool propagatePtrMetadata(Instruction *I);
bool instrumentPtrArith(GetElementPtrInst *Gep);
bool instrumentDeref(Instruction *I);
bool instrumentMemIntrinsic(Instruction *I);
bool isVtableGep(GetElementPtrInst *Gep);
BasicBlock *getOrCreateErrorBlock(Function *F);
bool moveUpOffsetInsts(GetElementPtrInst *CheckGEP,
GetElementPtrInst *OffsetGEP, Instruction *InsertPt);
uint64_t getSmallestDerefSize(Value *Ptr);
bool runOnFunction(Function &F) override;
bool initializeModule(Module &M);
};
char MPProp::ID = 0;
static RegisterPass<MPProp>
X("deltatags-prop",
"Propagate deltatags metadata to return values on stdlib functions");
STATISTIC(NLibCall, "Number of libcalls instrumented: total");
STATISTIC(NIgnore, "Number of libcalls instrumented: Ignore");
STATISTIC(NCopyFromArg, "Number of libcalls instrumented: CopyFromArg");
STATISTIC(NPtrDiff, "Number of libcalls instrumented: PtrDiff");
STATISTIC(NRetSizeStatic, "Number of libcalls instrumented: RetSizeStatic");
STATISTIC(NStrlen, "Number of libcalls instrumented: Strlen");
STATISTIC(NStrtok, "Number of libcalls instrumented: Strtok");
STATISTIC(NGep, "Number of ptr arith instrumented: total");
STATISTIC(
NNoCheck,
"Number of ptr arith instrumented: no check (constant positive offset)");
STATISTIC(NUnderflowCheck, "Number of ptr arith instrumented: underflow check");
STATISTIC(NOverflowCheck,
"Number of ptr arith instrumented: overflow check (total)");
STATISTIC(NDynamicOverflowCheck,
"Number of ptr arith instrumented: overflow check (dynamic offset)");
STATISTIC(NMemIntrinsic, "Number of memory intrinsics instrumented");
STATISTIC(NMovedOffsets,
"Number of ptr arith offsets moved for preempted bound checks");
void MPProp::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addPreserved<MPAvailable>();
AU.addPreserved<ReinterpretedPointers>();
AU.addRequired<DominatorTreeWrapperPass>();
}
/* Copy size directly from one of input arguments. */
static std::map<std::string, unsigned int> CopyFromArgList = {
{"getcwd", 0},
{"realpath", 1},
{"strcat", 0},
{"strncat", 0},
{"gcvt", 2},
{"strcpy", 0},
{"strncpy", 0},
{"fgets", 0},
{"gets", 0},
{"tmpnam", 0}, /* XXX unless NULL is passed */
{"__dynamic_cast", 0},
{"_ZNSt13basic_filebufIcSt11char_traitsIcEE4openEPKcSt13_Ios_Openmode",
0}, /* std::basic_filebuf::open */
{"_ZNSt9basic_iosIcSt11char_traitsIcEE5rdbufEPSt15basic_streambufIcS1_E",
0}, /* std::basic_streambuf::rdbuf */
{"_ZNSo3putEc", 0}, /* std::basic_ostream::put */
{"_ZNSo5flushEv", 0}, /* std::basic_ostream::flush */
{"_ZNSo5writeEPKcl", 0}, /* std::basic_ostream::write */
{"_ZNSo9_M_insertIbEERSoT_", 0}, /* std::basic_ostream::_M_insert(bool) */
{"_ZNSo9_M_insertIdEERSoT_", 0}, /* std::basic_ostream::_M_insert(double) */
{"_ZNSo9_M_insertIlEERSoT_", 0}, /* std::basic_ostream::_M_insert(long) */
{"_ZNSo9_M_insertImEERSoT_",
0}, /* std::basic_ostream::_M_insert(unsigned long) */
{"_ZNSo9_M_insertIPKvEERSoT_",
0}, /* std::basic_ostream::_M_insert(void const*) */
{"_ZNSi10_M_extractIfEERSiRT_",
0}, /* std::basic_istream::_M_extract(float&) */
{"_ZNSi10_M_extractIdEERSiRT_",
0}, /* std::basic_istream::_M_extract(double&) */
{"_ZNSolsEi", 0}, /* std::basic_ostream::operator<<(int) */
{"_ZNSolsEl", 0}, /* std::basic_ostream::operator<<(long) */
{"_ZNSolsEd", 0}, /* std::basic_ostream::operator<<(double) */
{"_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc",
0}, /* ostream::operator<< */
{"_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_c",
0}, /* std::basic_ostream::operator<< */
{"_ZStrsIcSt11char_traitsIcEERSt13basic_istreamIT_T0_ES6_PS3_",
0}, /* std::operator>>(std::basic_istream&, char*) */
{"_ZNSolsEPFRSoS_E", 0}, /* std::basic_ostream::operator<< */
{"_ZSt16__ostream_insertIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_"
"PKS3_l",
0}, /* std::basic_ostream::__ostream_insert */
{"_ZNSi3getERc", 0}, /* std::basic_istream::get */
{"_ZNSi4readEPcl", 0}, /* std::basic_istream::read */
{"_ZNSi7getlineEPcl", 0}, /* std::basic_istream::getline */
{"_ZNSi7getlineEPclc", 0}, /* std::basic_istream::getline */
{"_ZNSi7putbackEc", 0}, /* std::basic_istream::putback */
{"_ZNSs6appendEPKcm", 0}, /* std::basic_string::append */
{"_ZNSs6appendERKSs", 0}, /* std::basic_string::append */
{"_ZNSs6assignEPKcm", 0}, /* std::basic_string::assign */
{"_ZNSs6assignERKSs", 0}, /* std::basic_string::assign */
{"_ZNSspLEPKc", 0}, /* std::basic_string::operator+= */
{"_ZNSolsEj", 0}, /* std::basic_ostream::operator<<(unsigned int) */
{"_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE9_M_appendEPKcm",
0}, /* std::basic_string::_M_append */
{"_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE10_M_replaceEmmPKcm",
0}, /* std::basic_string::_M_replace: s = "..."; */
/* Added for dealII -O0 */
{"_ZNSirsERb", 0},
{"_ZNSirsERd", 0},
{"_ZNSirsERi", 0},
{"_ZNSirsERj", 0},
{"_ZNSirsERt", 0},
{"_ZNSolsEb", 0},
{"_ZNSolsEf", 0},
{"_ZNSolsEm", 0},
{"_ZNSsaSERKSs", 0},
{"_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE5eraseEmm", 0},
{"_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE6appendERKS4_", 0},
{"_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE6assignERKS4_mm", 0},
{"_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE7replaceEmmPKc", 0},
{"_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEaSEPKc", 0},
{"_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEaSERKS4_", 0},
{"_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEpLEc", 0},
{"_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEpLERKS4_", 0},
{"_ZSt7getlineIcSt11char_traitsIcESaIcEERSt13basic_istreamIT_T0_ES7_RNSt7__"
"cxx1112basic_stringIS4_S5_T1_EE",
0},
{"_ZStlsIcSt11char_traitsIcESaIcEERSt13basic_ostreamIT_T0_ES7_RKSbIS4_S5_"
"T1_E",
0},
{"_ZStlsIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_St13_Setprecision",
0},
{"_ZStlsIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_St5_Setw", 0},
{"_ZStlsIcSt11char_traitsIcESaIcEERSt13basic_ostreamIT_T0_ES7_RKNSt7__"
"cxx1112basic_stringIS4_S5_T1_EE",
0},
{"_ZStrsIcSt11char_traitsIcEERSt13basic_istreamIT_T0_ES6_RS3_", 0},
{"_ZStrsIcSt11char_traitsIcESaIcEERSt13basic_istreamIT_T0_ES7_RNSt7__"
"cxx1112basic_stringIS4_S5_T1_EE",
0},
{"_ZSt18_Rb_tree_decrementPKSt18_Rb_tree_node_base",
0}, /* std::_Rb_tree_decrement */
{"_ZSt18_Rb_tree_decrementPSt18_Rb_tree_node_base",
0}, /* std::_Rb_tree_decrement */
{"_ZSt18_Rb_tree_incrementPKSt18_Rb_tree_node_base",
0}, /* std::_Rb_tree_increment */
{"_ZSt18_Rb_tree_incrementPSt18_Rb_tree_node_base",
0}, /* std::_Rb_tree_increment */
{"_ZSt28_Rb_tree_rebalance_for_erasePSt18_Rb_tree_node_baseRS_",
0}, /* std::_Rb_tree_rebalance_for_erase */
/* Added for omnetpp */
{"_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEpLEPKc", 0},
/* Added for deltatags-test */
{"_ZNSsaSEPKc", 0},
};
/* Take difference between input-pointer (argument n) and output-pointer. */
static std::map<std::string, unsigned int> PtrDiffList = {
{"strstr", 0}, {"strchr", 0}, {"strrchr", 0}, {"memchr", 0},
{"__rawmemchr", 0}, {"strpbrk", 0}, {"bsearch", 1}, {"__cmsg_nxthdr", 1},
};
/* Infer from return type (usually structs) */
static std::set<std::string> RetSizeStaticList = {
"localeconv",
"gmtime",
"localtime",
"readdir",
"fdopen",
"fopen",
"popen",
"tmpfile",
"freopen",
"__errno_location",
"getpwnam",
"getgrnam",
"gethostbyname",
"readdir64",
"pcre_study",
/* TODO: these point to pointer that holds table (e.g., *table['A"]) */
/* NOTE: they extend also -128 before pointer. */
"__ctype_b_loc",
"__ctype_tolower_loc",
"__ctype_toupper_loc",
};
/* Perform run-time strlen (+1) on resulting buffer. */
static std::set<std::string> StrlenList = {
"ctime", "getenv", "strerror", "strsignal",
"strdup", "__strdup", "crypt", "ttyname",
};
/* For some functions returning pointers we don't care, but list them to disable
* warning that we're missing cases. */
static std::set<std::string> IgnoreList = {
"opendir", /* RetSizeStatic but opaque. */
"signal", /* Function pointer. */
/* These return a pointer to the next exception in the chain it seems. */
"__cxa_get_exception_ptr", "__cxa_begin_catch",
/* Handled by Allocation.cpp */
"malloc", "valloc", "_Znwj", /* new(unsigned int) */
"_ZnwjRKSt9nothrow_t", "_Znwm", /* new(unsigned long) */
"_ZnwmRKSt9nothrow_t", "_Znaj", /* new[](unsigned int) */
"_ZnajRKSt9nothrow_t", "_Znam", /* new[](unsigned long) */
"_ZnamRKSt9nothrow_t", "__cxa_allocate_exception", "calloc", "realloc",
"reallocf", "mmap64", /* TODO */
"shmat", /* TODO? */
/* TODO should take arg1 + 1 */
"_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE9_M_createERmm", /* std::basic_string::_M_create
*/
/* XXX */
"_ZNKSs5c_strEv", /* std::basic_string::c_str */
"_ZNKSs4dataEv", /* std::basic_string::data */
"_ZNKSs5beginEv", /* std::basic_string::begin */
"_ZNKSs3endEv", /* std::basic_string::end */
"_ZNKSsixEm", /* i8* (std::basic_string*, i64)* */
"_ZNSs12_S_empty_repEv", /* ??? */
"_ZNSs4_Rep10_M_refdataEv", /* ??? */
/* Added for dealII -O0 */
"_ZNKSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE3endEv",
"_ZNKSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE4dataEv",
"_ZNKSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE5beginEv",
"_ZNKSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE5c_strEv",
"_ZNKSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE7_M_dataEv",
"_ZNKSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEixEm",
"_ZNKSt9basic_iosIcSt11char_traitsIcEE5rdbufEv",
"_ZNKSt9basic_iosIcSt11char_traitsIcEEcvPvEv",
"_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE13_M_local_dataEv",
"_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE3endEv",
"_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEE5beginEv",
"_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEixEm",
"_ZNSt13basic_filebufIcSt11char_traitsIcEE5closeEv", /* std::basic_filebuf::close
*/
/* PCRE */
"pcre_compile", /* private struct */
};
static inline bool scanList(std::set<std::string> list, Function *F) {
return list.count(F->getName().str()) > 0;
}
static inline bool scanList(std::map<std::string, unsigned int> list,
Function *F, int *dat) {
auto p = list.find(F->getName().str());
if (p != list.end()) {
*dat = p->second;
return true;
}
return false;
}
enum LibPtr getLibPtrType(Function *F, int *dat) {
if (scanList(StrlenList, F)) {
return LibPtr::Strlen;
} else if (scanList(IgnoreList, F)) {
return LibPtr::Ignore;
} else if (scanList(RetSizeStaticList, F)) {
return LibPtr::RetSizeStatic;
} else if (scanList(CopyFromArgList, F, dat)) {
return LibPtr::CopyFromArg;
} else if (scanList(PtrDiffList, F, dat)) {
return LibPtr::PtrDiff;
} else if (F->getName() == "strtok") {
*dat = 0;
return LibPtr::Strtok;
} else {
return LibPtr::None;
}
}
static inline unsigned getValueOpcode(Value *V) {
ifcast(Instruction, I, V) return I->getOpcode();
else ifcast(Operator, Op, V) return Op->getOpcode();
else assert(false);
return 0;
}
/*
* Determines if the instruction calls an external library function that returns
* a pointer, and propagates its metadata if so.
* StrBufSizeFunc should be a function that determines the size of a pointer,
* and is generally strlen + 1 unless NULL is passed to it.
* Returns true if the IR has been modified.
*/
bool MPProp::propagatePtrMetadata(Instruction *I) {
int arg;
if (!isa<CallInst>(I) && !isa<InvokeInst>(I))
return false;
CallSite CS(I);
Function *F = CS.getCalledFunction();
if (!F || F->isIntrinsic() || !F->isDeclaration())
return false;
if (SafeAlloc && !SafeAlloc->needsPropagation(I))
return false;
enum LibPtr type = getLibPtrType(F, &arg);
switch (type) {
case LibPtr::Strlen:
++NStrlen;
break;
case LibPtr::Ignore:
++NIgnore;
break;
case LibPtr::RetSizeStatic:
++NRetSizeStatic;
break;
case LibPtr::CopyFromArg:
++NCopyFromArg;
break;
case LibPtr::PtrDiff:
++NPtrDiff;
break;
case LibPtr::Strtok:
++NStrtok;
break;
case LibPtr::None:
break;
}
if (type == LibPtr::Ignore)
return false;
++NLibCall;
if (type == LibPtr::Strtok) {
CS.setCalledFunction(NewStrtokFunc);
return true;
} else if (type == LibPtr::None) {
/* Sanity check that it doesn't return pointer. */
if (F->getReturnType()->isPointerTy()) {
exit(1);
}
return false;
}
IRBuilder<> B(getInsertPointAfter(I));
Value *Ptr = I;
std::vector<User *> Users(Ptr->user_begin(), Ptr->user_end());
Value *PtrVal = B.CreatePtrToInt(Ptr, B.getInt64Ty());
Value *NewSize;
if (type == LibPtr::Strlen) {
Value *StrBufSizeArgs[] = {Ptr};
Value *StrSize = B.CreateCall(StrBufSizeFunc, StrBufSizeArgs);
// if (ALLOWED_OOB_BYTES) { ALLOWED_OOB_BYTES is 0
// IntegerType *Ty = cast<IntegerType>(StrSize->getType());
// StrSize = B.CreateAdd(StrSize, ConstantInt::get(Ty, ALLOWED_OOB_BYTES));
// }
Value *InvSz = B.CreateAnd(B.CreateNeg(StrSize), BOUND_MASK_LOW);
NewSize = B.CreateShl(InvSz, BOUND_SHIFT);
} else if (type == LibPtr::RetSizeStatic) {
Type *RetTy = F->getReturnType()->getPointerElementType();
uint64_t InvSz =
-(DL->getTypeStoreSize(RetTy) + 0) & BOUND_MASK_LOW; //ALLOWED_OOB_BYTES is zero
NewSize = B.getIntN(64, InvSz << BOUND_SHIFT);
} else if (type == LibPtr::CopyFromArg || type == LibPtr::PtrDiff) {
/* These two are very similar, the only difference that PtrDiff does an
* additional calculation on the size whereas CopyFromArg simply copies
* it as-is. */
IntegerType *PtrIntTy = getPtrIntTy(I->getContext());
Value *OrigPtrVal = B.CreatePtrToInt(CS.getArgOperand(arg), PtrIntTy);
Value *OldSize = B.CreateAnd(OrigPtrVal, TAG_MASK_HIGH);
if (type == LibPtr::PtrDiff) {
/* newsize = oldsize - (new_ptr - old_ptr) ==>
* newupper = oldupper + ((new_ptr - old_ptr) << bnd_shift) */
Value *OrigPtrMaskedVal = B.CreateAnd(OrigPtrVal, getAddressSpaceMask());
Value *SizeDiff = B.CreateSub(PtrVal, OrigPtrMaskedVal);
NewSize = B.CreateAdd(OldSize, B.CreateShl(SizeDiff, BOUND_SHIFT));
} else {
NewSize = OldSize;
}
}
Value *NewPtr = B.CreateIntToPtr(B.CreateOr(PtrVal, NewSize), Ptr->getType());
for (User *U : Users)
U->replaceUsesOfWith(Ptr, NewPtr);
return true;
}
bool MPProp::isVtableGep(GetElementPtrInst *Gep) {
Value *SrcPtr = Gep->getPointerOperand();
if (SrcPtr->hasName() && SrcPtr->getName().startswith("vtable")) {
// DEBUG_LINE("Ignoring vtable GEP: " << *Gep);
return true;
}
if (Gep->getNumIndices() == 1) {
Value *FirstOp = Gep->getOperand(1);
if (FirstOp->hasName() && FirstOp->getName().startswith("vbase.offset")) {
// DEBUG_LINE("Ignoring vbase GEP: " << *Gep);
return true;
}
}
ifcast(GlobalVariable, GV, SrcPtr) if (GV->getName().startswith("_ZTV")) {
// DEBUG_LINE("Ignoring GV vtable GEP: " << *Gep);
return true;
}
return false;
}
#if 0
static bool hasNonDereferencingUser(Value *Ptr, User *Ignore) {
for (User *U : Ptr->users()) {
if (U == Ignore)
continue;
if (isa<LoadInst>(U))
continue;
ifcast(StoreInst, SI, U) {
if (SI->getValueOperand() != Ptr)
continue;
}
return true;
}
return false;
}
#endif
bool MPProp::hasNegativeOffset(GetElementPtrInst *Gep) {
// Negative offsets are trivial
APInt ConstOffset(64, 0);
if (Gep->accumulateConstantOffset(*DL, ConstOffset))
return ConstOffset.isNegative();
// For synamid offsets, look for the pattern "gep %base, (sub 0, %idx)"
// XXX this is best-effort and may not catch all cases
for (int i = 1, l = Gep->getNumOperands(); i < l; i++) {
Value *Index = Gep->getOperand(i);
ifncast(Instruction, I, Index) continue;
if (I->getOpcode() != Instruction::Sub)
continue;
ifncast(ConstantInt, PossibleZero, I->getOperand(0)) continue;
if (PossibleZero->getSExtValue() == 0)
return true;
}
return false;
}
/*
* On pointer arithmetic, replicate the operations on the metadata in upper
* bits.
*/
bool MPProp::instrumentPtrArith(GetElementPtrInst *Gep) {
//이거 수정
GetElementPtrInst *PreemptedGep = nullptr;
if (SafeAlloc)
PreemptedGep = SafeAlloc->getPreemptedOffset(Gep);
if (!PreemptedGep) {
/* No effect on ptr means no effect on size. */
if (Gep->hasAllZeroIndices())
return false;
/* Safe allocations are not masked, so should not be tagged. */
if (SafeAlloc && !SafeAlloc->needsPropagation(Gep))
return false;
/* We want to skip GEPs on vtable stuff, as they shouldn't be able to
* overflow, and because they don't have metadata normally negative
* GEPs fail on these. */
if (isVtableGep(Gep))
return false;
}
/* TODO: we cannot support GEPs operating on vectors. */
if (Gep->getType()->isVectorTy()) {
return false;
}
std::string Prefix = Gep->hasName() ? Gep->getName().str() + "." : "";
IRBuilder<> B(getInsertPointAfter(Gep));
std::vector<User *> Users(Gep->user_begin(), Gep->user_end());
IntegerType *PtrIntTy = getPtrIntTy(Gep->getContext());
/* NOTE: further optimization: if only last index non-zero we can create a
* new GEP instead of all below, which may be better for optimizer? */
Instruction *PtrInt =
cast<Instruction>(B.CreatePtrToInt(Gep, PtrIntTy, Prefix + "int"));
/* Generate calculation of offset (for every idx, multiply element size by
* element idx, and add all together). IRBuilder does proper constant
* folding on this, meaning that if the entire offset is known at compile
* time, no calculation will be present in IR. */
Value *Diff;
ConstantInt *ConstOffset = nullptr;
APInt ConstOffsetVal(64, 0);
if (Gep->accumulateConstantOffset(*DL, ConstOffsetVal))
ConstOffset = B.getInt(ConstOffsetVal);
if (PreemptedGep) {
APInt PreemptedOffset(64, 0);
if (PreemptedGep->accumulateConstantOffset(*DL, PreemptedOffset)) {
Diff = ConstantInt::getSigned(PtrIntTy, PreemptedOffset.getSExtValue());
} else {
// Move up instructions that are needed for the merged offset
// calculation but are defined later than the GEP that does the check
if (moveUpOffsetInsts(Gep, PreemptedGep, PtrInt)) {
NMovedOffsets++;
// Offset instructions are inserted between the gep and the gep's
// ptrint so that we retreive the insertion point after the
// offsets. Set the insertion point and move the ptrint definition
// to directly after the gep for readaibility.
B.SetInsertPoint(getInsertPointAfter(PtrInt));
PtrInt->removeFromParent();
PtrInt->insertAfter(Gep);
}
Diff = EmitGEPOffset(&B, *DL, PreemptedGep);
}
} else if (ConstOffset) {
Diff = ConstOffset;
} else if (SubtractionArith) {
Value *Base = Gep->getPointerOperand();
Value *BaseInt = B.CreatePtrToInt(Base, PtrIntTy, Prefix + "baseint");
Diff = B.CreateSub(PtrInt, BaseInt, Prefix + "diff");
} else {
Diff = EmitGEPOffset(&B, *DL, Gep);
}
// Shift 두번 해야 됨
// Ushift 만들고
// LShift 만들고
// Ushift && LShift
//이부분 다시 체크
Value *Ushift = B.CreateShl(Diff, BOUND_SHIFT, Prefix + "Ushifted");
Value *Lshift = B.CreateShl(Diff, 56, Prefix + "Lshifted");
Value *Shifted = B.CreateAnd(Ushift, Lshift, "shifted");
Value *AddOffset = Shifted;
Value *PtrAdd;
Constant *ZeroPtr = B.getIntN(64, 0);
/* For known negative offsets, insert a check if the pointer indeed has
* metadata, and don't do a zero metadata addition if this is the case. */
if (CheckUnderflow && hasNegativeOffset(Gep)) {
// TODO: don't insert check if pointer operand certainly has metadata
// (if we can find the tag, i.e., if it is or'ed with a const)
// meta = ptr >> BOUND_SHIFT // XXX mask away overflow bit here?
// hasmeta = meta != 0
// Value *Meta = B.CreateLShr(PtrInt, BOUND_SHIFT, Prefix + "meta");
// Value *HasMeta = B.CreateICmpNE(Meta, Zero, Prefix + "hasmeta");
// hasmeta = ptr > ADDRSPACE_MASK
// addoffset = hasmeta ? (offset << BOUND_SHIFT) : 0 // select
Value *Zero = ConstantInt::get(PtrIntTy, 0);
Value *Mask = ConstantInt::get(PtrIntTy, getAddressSpaceMask());
Value *OrigPtrInt =
B.CreatePtrToInt(Gep->getOperand(0), PtrIntTy, Prefix + "origptrint");
Value *HasMeta = B.CreateICmpUGT(OrigPtrInt, Mask, Prefix + "hasmeta");
AddOffset = B.CreateSelect(HasMeta, Shifted, Zero, Prefix + "offset");
PtrAdd = B.CreateAdd(PtrInt, AddOffset, Prefix + "added");
++NUnderflowCheck;
}
/* For positive GEPs, replace the GEP with a nullptr if the carry flag is
* set after the operation.
* For dynamic GEPs, check if the offset is positive and if the operation
* overflows. */
else if (CheckOverflow != nocheck &&
!(ConstOffset && ConstOffset->isNegative())) {
Value *OAdd =
B.CreateCall(AddWithOverflowFunc, {PtrInt, AddOffset}, Prefix + "oadd");
Value *Result = B.CreateExtractValue(OAdd, 0, Prefix + "added");
Value *Overflow = B.CreateExtractValue(OAdd, 1, Prefix + "overflow");
Value *NotNegativeAndOverflow = Overflow;
if (!ConstOffset) {
Value *Positive = B.CreateICmpSGT(Diff, ZeroPtr, Prefix + "positive");
NotNegativeAndOverflow = B.CreateAnd(Positive, Overflow, Prefix + "both");
++NDynamicOverflowCheck;
}
switch (CheckOverflow) {
/* Branch to trap code if the operation overflows */
case branch: {
// Split on condition
BasicBlock *BB = Gep->getParent();
BasicBlock *Succ =
BB->splitBasicBlock(B.GetInsertPoint(), Prefix + "fallthru");
// Replace unconditional jump with conditional branch
BB->getTerminator()->eraseFromParent();
B.SetInsertPoint(BB);
B.CreateCondBr(NotNegativeAndOverflow,
getOrCreateErrorBlock(BB->getParent()), Succ);
// Reset insert point
B.SetInsertPoint(&*Succ->begin());
PtrAdd = Result;
break;
}
/* Nullify the result if the operation overflows */
case satarith:
PtrAdd = B.CreateSelect(NotNegativeAndOverflow, ZeroPtr, Result,
Prefix + "added");
break;
case nocheck:
break;
}
++NOverflowCheck;
}
/* Default: add the offset to the metadata bits */
else {
PtrAdd = B.CreateAdd(PtrInt, AddOffset, Prefix + "added");
++NNoCheck;
}
// TODO: try to make the final ptr, instead of the offset, a select inst
// (and measure performance for both)
Value *NewPtr = B.CreateIntToPtr(PtrAdd, Gep->getType(), Prefix + "newptr");
++NGep;
// TODO: check if this is optimized in asm
for (User *U : Users)
U->replaceUsesOfWith(Gep, NewPtr);
// Maintain mapping for instrumentDeref
ReplacedPtrArithReverse[NewPtr] = Gep;
return true;
}
/*
* On dereference, add (derefsize - 1) to the size tag to avoid unaligned OoB
* accesses,
*/
bool MPProp::instrumentDeref(Instruction *I) {
int PtrOperand = isa<LoadInst>(I) ? 0 : 1;
Value *Ptr = I->getOperand(PtrOperand);
if (SafeAlloc && !SafeAlloc->needsMask(I, Ptr))
return false;
Type *Ty = isa<LoadInst>(I)
? I->getType()
: cast<StoreInst>(I)->getValueOperand()->getType();
assert(Ty->isSized());
uint64_t Size = DL->getTypeStoreSize(Ty);
uint64_t AlignBytes = Size - 1;
// If this GEP takes the offset from a subsequent GEP, then take the number
// of alignment bytes from the accompanying load/store as well
if (SafeAlloc) {
if (GetElementPtrInst *Gep = ReplacedPtrArithReverse.lookup(Ptr)) {
if (uint64_t DerefSize = DerefBytes.lookup(Gep)) {
uint64_t PreemptedAlignBytes = DerefSize - 1;
if (PreemptedAlignBytes < AlignBytes) {
AlignBytes = PreemptedAlignBytes;
}
}
}
}
if (AlignBytes == 0)
return false;
IRBuilder<> B(I);
std::string Prefix = Ptr->hasName() ? Ptr->getName().str() + "." : "";
Value *AsInt =
B.CreatePtrToInt(Ptr, B.getIntNTy(64), Prefix + "int");
Value *Align =
B.CreateAdd(AsInt, B.getIntN(64, AlignBytes << BOUND_SHIFT),
Prefix + "align");
Value *Aligned = B.CreateIntToPtr(Align, Ptr->getType(), Prefix + "aligned");
I->setOperand(PtrOperand, Aligned);
return true;
}
BasicBlock *MPProp::getOrCreateErrorBlock(Function *F) {
auto it = ErrorBlocks.find(F);
if (it != ErrorBlocks.end())
return it->second;
BasicBlock *BB = BasicBlock::Create(F->getContext(), "oob_error", F);
IRBuilder<> B(BB);
// TODO
// Value *Fd = B.getInt32(2);
// Value *Format = B.CreateGlobalStringPtr("OoB pointer detected in %s\n",
// "oob_error"); setNoInstrument(Format); B.CreateCall(Printf, {Fd, Format, });
B.CreateCall(TrapFunc);
B.CreateUnreachable();
ErrorBlocks[F] = BB;
return BB;
}
bool MPProp::instrumentMemIntrinsic(Instruction *I) {
//이 부분이 사용됨
IRBuilder<> B(I);
IntegerType *PtrIntTy = getPtrIntTy(I->getContext());
Value *Length;
Use *PtrArg1Use, *PtrArg2Use = NULL;
if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
Length = MI->getLength();
PtrArg1Use = &MI->getRawDestUse();
ifcast(MemTransferInst, MTI, MI) { PtrArg2Use = &MTI->getRawSourceUse(); }
} else
ifcast(CallInst, CI, I) {
if (CI->getCalledFunction()->getName() == "memcmp") {
Length = CI->getArgOperand(2);
PtrArg1Use = &CI->getArgOperandUse(0);
PtrArg2Use = &CI->getArgOperandUse(1);
} else {
errs() << "Unhandled call: " << *CI << "\n";
llvm_unreachable("unhandled call");
}
}
else {
errs() << "Unhandled intrinsic inst: " << *I << "\n";
llvm_unreachable("unhandled inst");
}
Value *AccessedLength =
B.CreateSub(Length, ConstantInt::get(Length->getType(), 1),
"accessedlen"); // 이 부분은 최적화되서 없어지는 것 같음
Value *ShiftedLength = B.CreateShl(AccessedLength, BOUND_SHIFT,
"shiftedlen"); // 이 부분도 마찬가지...
Value *Test = B.CreateShl(AccessedLength, BOUND_SHIFT, "shiftedlen");
Test->getValueID();
Value *Ptr1 = PtrArg1Use->get();
Value *Ptr1Int = B.CreatePtrToInt(Ptr1, PtrIntTy, "ptr1.int");
Value *Ptr1Add = B.CreateAdd(Ptr1Int, ShiftedLength, "ptr1.add");
Value *Ptr1New = B.CreateIntToPtr(Ptr1Add, Ptr1->getType(), "ptr1.new");
PtrArg1Use->set(Ptr1New);
if (PtrArg2Use) {
Value *Ptr2 = PtrArg2Use->get();
Value *Ptr2Int = B.CreatePtrToInt(Ptr2, PtrIntTy, "ptr2.int");
Value *Ptr2Add = B.CreateAdd(Ptr2Int, ShiftedLength, "ptr2.add");
Value *Ptr2New = B.CreateIntToPtr(Ptr2Add, Ptr2->getType(), "ptr2.new");
PtrArg2Use->set(Ptr2New);
}
++NMemIntrinsic;
return true;
}
bool MPProp::runOnFunction(Function &F) {
bool Changed = false;
SmallVector<GetElementPtrInst *, 8> Geps;
SmallVector<Instruction *, 8> Derefs;
SmallVector<Instruction *, 8> MemIntrinsics;
DT = &getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
ReplacedPtrArithReverse.clear();
DerefBytes.clear();
for (Instruction &I : instructions(F)) {
Changed |= propagatePtrMetadata(&I);
if (EnablePtrArith) {
ifcast(GetElementPtrInst, Gep, &I) Geps.push_back(Gep);
}
if (DisallowUnalignedAccess) {
if (isa<LoadInst>(I) || isa<StoreInst>(I))
Derefs.push_back(&I);
}
if (EnableMemIntrinsics) {
if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&I))
MemIntrinsics.push_back(&I);
ifcast(CallInst, CI, &I) {
Function *CF = CI->getCalledFunction();
if (CF && CF->hasName() && CF->getName() == "memcmp")
MemIntrinsics.push_back(CI);
}
}
}
// Save preempted alignment sizes for instrumentDeref
if (SafeAlloc && !Derefs.empty()) {
for (GetElementPtrInst *Gep : Geps) {
if (GetElementPtrInst *PreemptedGep = SafeAlloc->getPreemptedOffset(Gep))
DerefBytes[Gep] = getSmallestDerefSize(PreemptedGep);
}
}
for (GetElementPtrInst *Gep : Geps)
Changed |= instrumentPtrArith(Gep);
for (Instruction *I : Derefs)
Changed |= instrumentDeref(I);
for (Instruction *I : MemIntrinsics)
Changed |= instrumentMemIntrinsic(I);
return Changed;
}
bool MPProp::initializeModule(Module &M) {
DL = &M.getDataLayout();
// StrBufSizeFunc = getNoInstrumentFunction(M, "strsize_nullsafe", false);
// NewStrtokFunc = getNoInstrumentFunction(M, "strtok", false);
if (CheckOverflow != nocheck) {
Type *PtrIntTy = getPtrIntTy(M.getContext());
AddWithOverflowFunc =
Intrinsic::getDeclaration(&M, Intrinsic::uadd_with_overflow, PtrIntTy);
}
TrapFunc = Intrinsic::getDeclaration(&M, Intrinsic::trap);
SafeAlloc = getAnalysisIfAvailable<MPAvailable>();
ErrorBlocks.clear();
return false;
}
bool MPProp::moveUpOffsetInsts(GetElementPtrInst *CheckGEP,
GetElementPtrInst *OffsetGEP,
Instruction *InsertPt) {
if (!DT->dominates(CheckGEP, OffsetGEP)) {
// If the check gep comes after the offset gep, no instructions need to
// be moved. Do make sure, however, that the offset is always available
// at the check, i.e. that the offset gep dominates the check
assert(DT->dominates(OffsetGEP, CheckGEP));
return false;
}
// XXX: we could use a SCEVExpander if we don't want to move the
// instructions. but rather duplicate their semantics at the check gep
// (this makes little sense if the distance between the geps is small and
// the result can be kept in a register)
// SCEVExpander Expander(*SE, *DL, "offset_expander");
// Type *Ty = DL->getIntPtrType(CheckGEP->getContext());
// Value *Offset = Expander.expandCodeFor(getGEPOffsetSCEV(OffsetGEP), Ty,
// CheckGEP);
// Move up any instructions that are needed for calculating the offset
SmallVector<Instruction *, 4> MoveList, Worklist;
for (Use &U : OffsetGEP->operands()) {
ifcast(Instruction, UI, U.get()) Worklist.push_back(UI);
}
// Collect instructions to move by traversing operands
while (!Worklist.empty()) {
Instruction *I = Worklist.pop_back_val();
if (!DT->dominates(CheckGEP, I))
continue;
// Avoid endless recursion
assert(!isa<PHINode>(I));
MoveList.push_back(I);
for (Use &U : I->operands()) {
ifcast(Instruction, UI, U.get()) Worklist.push_back(UI);
}
}
// Do the actual moving. The list is in reverse order, so move the
// insertion point after every move.
for (Instruction *I : MoveList) {
I->moveBefore(InsertPt);
InsertPt = I;
}
return !MoveList.empty();
}
uint64_t MPProp::getSmallestDerefSize(Value *Ptr) {
uint64_t MinDerefSize = 0;
bool Unmatching = false;
assert(Ptr->getNumUses() > 0);
for (User *U : Ptr->users()) {
assert(isa<LoadInst>(U) || isa<StoreInst>(U));
Type *Ty = isa<LoadInst>(U)
? U->getType()
: cast<StoreInst>(U)->getValueOperand()->getType();
assert(Ty->isSized());
uint64_t DerefSize = DL->getTypeStoreSize(Ty);
if (MinDerefSize && DerefSize != MinDerefSize)
Unmatching = true;
if (!MinDerefSize || DerefSize < MinDerefSize)
MinDerefSize = DerefSize;
}
return MinDerefSize;
}
| 35,041 | 13,197 |
#include <stdio.h>
#include <string.h>
#include <map>
#include <algorithm>
#include "comm_graph.h"
#include "lock_functions.h"
#include "fnv.h"
#include "pin.H"
#define HASH_MASK 0xffffff
#define HASH_SIZE 0x1000000
/*#define READ 1
#define WRITE 2*/
#define FREE "free"
#define MALLOC "malloc"
#define REQUEST 1
#define NONE 0
#define START_MALLOCS_ADDR 0x7ffff7df0d30
#define DELETED 0
#define ALLOCATED 1
#define GLOBAL 2
extern char lock_func_sets[SETS][MAX_FUNC_NAME_SIZE];
extern char lock_functions[SETS][TYPES][MAX_FUNC_NAME_SIZE];
extern char lock_functions_get[SETS][TYPES][MAX_FUNC_NAME_SIZE];
typedef struct {
unsigned long thid;
unsigned long id;
void * ipc;
void * addr;
unsigned char type;
unsigned long timestamp;
} mem_access_entry;
mem_access_entry table[HASH_SIZE];
typedef std::pair <mem_access_entry, mem_access_entry> idiom;
std::vector<idiom> interleavings;
typedef std::map<unsigned long, unsigned long> Mem_Req_State;
Mem_Req_State memory_req_state;
typedef std::map<unsigned long, unsigned int> Mem_Asked;
Mem_Asked mem_asked;
typedef std::map <unsigned long, unsigned int> Memory_Map;
typedef std::map <unsigned long, unsigned int> Memory_Map_State;
typedef std::map <unsigned long, string> Memory_Map_Descr;
Memory_Map memory_map;
Memory_Map_State memory_map_state;
Memory_Map_Descr memory_map_descr;
std::map <unsigned long, unsigned long> lock_refs;
std::map <unsigned long, unsigned long> pthreads_lock_refs;
unsigned long hash_val;
class CompareAddr {
public:
bool operator () (const unsigned long addr, std::pair <const unsigned long, unsigned int> & page) { return addr < page.first; }
bool operator () (std::pair <const unsigned long, unsigned int> & page, const unsigned long addr) { return page.first + page.second < addr; }
};
KNOB<BOOL> KnobAllMemAccesses (KNOB_MODE_WRITEONCE, "pintool",
"am", "0" , "gather all memory accesses or just globals and heap");
KNOB<BOOL> KnobGenerateGraph (KNOB_MODE_WRITEONCE, "pintool",
"g", "0" , "generate program execution graph as graphviz .dot files");
KNOB<string> KnobOutputFile(KNOB_MODE_WRITEONCE, "pintool",
"o", "racedet.trace", "specify output file name");
KNOB<string> KnobMmapFile(KNOB_MODE_WRITEONCE, "pintool",
"m", "racedet.mem", "specify output memory map file name");
KNOB<string> KnobSrcMapFile(KNOB_MODE_WRITEONCE, "pintool",
"c", "racedet.src", "specify output source file map");
KNOB<string> KnobIdiomFile(KNOB_MODE_WRITEONCE, "pintool",
"i", "racedet.id", "specify output interleavings list");
unsigned long timestamp=0;
//Fnv64_t hash_val;
FILE * out;
PIN_LOCK lock;
unsigned int gather_all=0;
unsigned int generate_graph=0;
#ifdef PTHREAD_MT_GRAPH
FILE * graph_file;
map <unsigned long, graph> thread_graphs;
map <unsigned long, unsigned long> thread_state;
void save_idioms (FILE*file);
unsigned long
shash(unsigned char *str)
{
unsigned long hash = 5381;
int c;
while ( (c = *str++) )
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
return hash;
}
map <std::string, unsigned int> files;
unsigned int counter=1;
unsigned int file_hash (std::string &str){
map<std::string, unsigned int>::iterator itr=files.begin();
if (str.empty())
return 0;
itr=files.find(str);
if(itr==files.end()){
files[str] = counter;
counter ++;
}
return files[str];
}
/* Retrieves the last executed state of thread id, return 0 if none */
unsigned long graph_last_state(unsigned long thd)
{
map<unsigned long, unsigned long>::iterator itr=thread_state.begin();
itr=thread_state.find(thd);
if(itr==thread_state.end())
return 0;
return thread_state[thd];
}
/* Sets the last executed state of thread id*/
void graph_set_last_state(unsigned long thd, unsigned long state)
{
thread_state[thd] = state;
}
/* Figures out if the graph for thread thd has been created or not */
bool graph_exists(unsigned long thd){
map<unsigned long, graph>::iterator itr=thread_graphs.begin();
itr=thread_graphs.find(thd);
if(itr==thread_graphs.end())
return false;
return true;
}
/* Creates a new graph for thread thd and sets the initial state */
bool graph_create(unsigned long thd, unsigned long state, unsigned long addr, unsigned long type, unsigned long ts, unsigned long th,
unsigned int l, unsigned int c, std::string &f)
{
if (! graph_exists(thd))
{
graph gr;
gr.tid = th;
thread_graphs[thd] = gr;
thread_graphs[thd].add_node (state, addr, type, ts, th, l ,c, f);
thread_state[thd] = state;
return true;
}
return false;
}
#ifdef LOCK_PROF
typedef std:: pair <node *, node*> interleaving;
vector <interleaving> idioms;
int find_idiom (unsigned long from_th, unsigned long from_id, unsigned long to_th, unsigned long to_id )
{
int i = 0;
node * f = NULL, * t = NULL;
if (!graph_exists(from_th) || !graph_exists(to_th))
return -4; // missing graph, don't do anything
if (thread_graphs[from_th].has_node(from_id))
{
f = thread_graphs[from_th].nodes[from_id];
}else{
return -3; // missing 'from' node, don't do anything
}
if (thread_graphs[to_th].has_node(to_id))
{
t = thread_graphs[to_th].nodes[to_id];
}else{
return -2; // missing 'to' node, don't do anything
}
for ( std::vector < interleaving>:: iterator itr = idioms.begin(); itr != idioms.end(); ++itr)
{
if (f == (*itr).first && t == (*itr).second)
return i;
i++;
}
return -1; // nodes exist, but no idiom registered. It's OK to add this new one.
}
int add_idiom (unsigned long from_th, unsigned long from_id, unsigned long to_th, unsigned long to_id )
{
node * f = NULL, * t = NULL;
if (!graph_exists(from_th) || !graph_exists(to_th))
return -4; // missing graph, didn't do anything
if (thread_graphs[from_th].has_node(from_id))
{
f = thread_graphs[from_th].nodes[from_id];
}else{
return -3; // missing 'from' node, didn't do anything
}
if (thread_graphs[to_th].has_node(to_id))
{
t = thread_graphs[to_th].nodes[to_id];
}else{
return -2; // missing 'to' node, didn't do anything
}
interleaving idiom = make_pair (f, t) ;
idioms.push_back (idiom);
//fprintf(stderr, "Runtime: ****************** Added idiom ***********************\n");
return 1;
}
#endif
#endif
// Note that opening a file in a callback is only supported on Linux systems.
// See buffer-win.cpp for how to work around this issue on Windows.
//
// This routine is executed every time a thread is created.
VOID ThreadStart(THREADID threadid, CONTEXT *ctxt, INT32 flags, VOID *v)
{
std::string empty;
unsigned char label[1024];
PIN_THREAD_UID uid;
uid = PIN_ThreadUid();
PIN_GetLock(&lock, threadid+1);
timestamp++;
//fprintf(out,"timestamp , thread , operation , addr , line , column , file\n");
sprintf((char *)label,"0x%lx , 0x%lx , THREADSTART , 0x%lx , 0 , 0 , 0", (unsigned long)v, (unsigned long)uid, (unsigned long)v);
if (generate_graph){
hash_val = shash(label);
graph_create(uid, hash_val, (unsigned long) v, THREAD_START, timestamp, uid,0,0,empty);
}
fprintf(out, "%ld , %s\n",timestamp, label);
fflush(out);
PIN_ReleaseLock(&lock);
}
// This routine is executed every time a thread is destroyed.
VOID ThreadFini(THREADID threadid, const CONTEXT *ctxt, INT32 code, VOID *v)
{
std::string empty;
unsigned char label[1024];
PIN_THREAD_UID uid;
uid = PIN_ThreadUid();
char graph_file_name[256];
sprintf (graph_file_name, "%s_%lx.dot", "racedet", (unsigned long)uid);
FILE * graph;
PIN_GetLock(&lock, threadid+1);
hash_val = shash(label);
timestamp ++;
//fprintf(out,"timestamp , ipc, thread , operation , addr , line , column , file\n");
sprintf((char *)label,"%ld , 0x%lx , 0x%lx , THREADEND , 0x%lx , 0 , 0 , 0", timestamp, (unsigned long) v, (unsigned long)uid, (unsigned long)v);
if (generate_graph){
pair<long, node*> * edge=NULL;
unsigned long last_item_executed = graph_last_state(uid);
if (!thread_graphs[uid].has_node(hash_val)){ // does this line id exist in the graph?
thread_graphs[uid].add_node (hash_val, (unsigned long) v, THREAD_END, timestamp, uid, 0,0,empty); // no, we have to create it.
}
edge = thread_graphs[uid].find_edge(last_item_executed, hash_val);
if (! edge) // does the edge between last item execited and id exist?
{
// no, we have to create it
thread_graphs[uid].add_edge(last_item_executed, hash_val, 1);
}else{
edge->first++;
}
graph_set_last_state(uid, hash_val);
}
fprintf(out, "%s\n",label);
PIN_ReleaseLock(&lock);
if (generate_graph){
graph = fopen (graph_file_name, "w");
if (graph != NULL)
{
fprintf(stderr, "Racedet: Saving graph for thread 0x%lx in file %s\n", (unsigned long)uid, graph_file_name);
if (graph_exists (uid) )
{
thread_graphs[uid].save_to_dot(graph);
//thread_graphs[selfThd].save_to_dot(stderr);
} else{
fprintf (stderr, "Racedet error: Graph for thread 0x%lx doesn't exist!\n", (unsigned long)uid);
}
fclose(graph);
}else{
fprintf (stderr, "Runtime error: could not write graph for thread 0x%lx into file %s!\n", (unsigned long)uid, graph_file_name);
}
}
}
IMG mainExe;
// Print a memory read record
VOID RecordMemRead(VOID * ip, VOID * addr, THREADID threadid)
{
INT32 line=0;
INT32 column=0;
string filename="";
unsigned char label[1024];
bool found;
PIN_THREAD_UID uid;
if (!gather_all){
found = binary_search(memory_map.begin(),memory_map.end(), (unsigned long) addr, CompareAddr());
if (!found){
return;
}
}
PIN_LockClient();
IMG img = IMG_FindByAddress ((ADDRINT)ip);
if (img != mainExe){
PIN_UnlockClient();
return;
}
PIN_GetSourceLocation((ADDRINT) ip,&column, &line, &filename);
PIN_UnlockClient();
uid = PIN_ThreadUid();
unsigned long index = (unsigned long)addr & HASH_MASK;
mem_access_entry * ref = & table[index];
PIN_GetLock(&lock, threadid+1);
timestamp++;
//fprintf(out,"timestamp , thread , operation , addr , line , column , file\n");
sprintf((char *)label,"0x%lx , 0x%lx , READ , 0x%lx , %d , %d , %d", (unsigned long)ip, (unsigned long)uid, (unsigned long)addr, line, column, file_hash(filename) );
// hash_val = fnv_64_str(label, hash_val);
if (generate_graph){
hash_val = shash(label);
if (graph_exists(uid)){
pair<long, node*> * edge=NULL;
unsigned long last_item_executed = graph_last_state(uid);
if (!thread_graphs[uid].has_node(hash_val)){ // does this line id exist in the graph?
thread_graphs[uid].add_node (hash_val, (unsigned long) addr, MEM_READ, timestamp, uid, line, column, filename); // no, we have to create it.
}
edge = thread_graphs[uid].find_edge(last_item_executed, hash_val);
if (! edge) // does the edge between last item execited and id exist?
{
// no, we have to create it
thread_graphs[uid].add_edge(last_item_executed, hash_val, 1);
}else{
edge->first++;
}
graph_set_last_state(uid, hash_val);
}else{
//fprintf(stderr, "Creating graph for thread x%x\n", selfThd);
graph_create(uid, hash_val, (unsigned long) addr, MEM_READ, timestamp, uid, line, column, filename);
}
}
fprintf (out, "%ld , %s\n", timestamp, label);
if (generate_graph){
if ((ref->thid != uid) && (ref->type !=MEM_READ)){
int result = find_idiom(ref->thid, ref->id, uid,hash_val);
//fprintf (stderr, "Runtime: find_idiom() result was %d\n", result);
if (result == -1) // the nodes exist but there is no interleaving idiom between them... add it
{
mem_access_entry old = *ref;
mem_access_entry new_a;
new_a.addr = addr;
new_a.ipc = ip;
new_a.thid = uid;
new_a.type = MEM_READ;
new_a.id = hash_val;
new_a.timestamp = timestamp;
idiom i = make_pair(old, new_a);
interleavings.push_back(i);
add_idiom(ref->thid, ref->id, uid, hash_val);
}
ref->addr = addr;
ref->ipc = ip;
ref->thid = uid;
ref->type = MEM_READ;
ref->id = hash_val;
ref->timestamp = timestamp;
}
}
PIN_ReleaseLock(&lock);
}
// Print a memory write record
VOID RecordMemWrite(VOID * ip, VOID * addr, THREADID threadid)
{
INT32 line=0;
INT32 column=0;
string filename="";
unsigned char label[1024];
PIN_THREAD_UID uid;
bool found;
if (!gather_all){
found = binary_search(memory_map.begin(),memory_map.end(), (unsigned long) addr, CompareAddr());
if (!found)
{
return;
}
}
PIN_LockClient();
IMG img = IMG_FindByAddress ((ADDRINT)ip);
if (img != mainExe){
PIN_UnlockClient();
return;
}
PIN_GetSourceLocation((ADDRINT) ip,&column, &line, &filename);
PIN_UnlockClient();
uid = PIN_ThreadUid();
unsigned long index = (unsigned long)addr & HASH_MASK;
mem_access_entry * ref = & table[index];
PIN_GetLock(&lock, threadid+1);
timestamp++;
//fprintf(out,"timestamp , thread , operation , addr , line , column , file\n");
sprintf((char *)label,"0x%lx , 0x%lx , WRITE , 0x%lx , %d , %d , %d", (unsigned long)ip, (unsigned long)uid, (unsigned long)addr, line, column, file_hash(filename) );
if (generate_graph){
//hash_val = fnv_64_str(label, hash_val);
hash_val = shash(label);
if (graph_exists(uid)){
pair<long, node*> * edge=NULL;
unsigned long last_item_executed = graph_last_state(uid);
if (!thread_graphs[uid].has_node(hash_val)){ // does this line id exist in the graph?
thread_graphs[uid].add_node (hash_val, (unsigned long) addr, MEM_WRITE, timestamp, uid, line, column, filename); // no, we have to create it.
}
edge = thread_graphs[uid].find_edge(last_item_executed, hash_val);
if (! edge) // does the edge between last item execited and id exist?
{
// no, we have to create it
thread_graphs[uid].add_edge(last_item_executed, hash_val, 1);
}else{
edge->first++;
}
graph_set_last_state(uid, hash_val);
}else{
//fprintf(stderr, "Creating graph for thread x%x\n", selfThd);
graph_create(uid, hash_val, (unsigned long) addr, MEM_WRITE, timestamp, uid, line, column, filename);
}
}
fprintf (out, "%ld , %s\n", timestamp , label);
if (generate_graph){
if (ref->addr == NULL)
{
ref->addr = addr;
ref->ipc = ip;
ref->thid = uid;
ref->type = MEM_WRITE;
ref->id = hash_val;
ref->timestamp = timestamp;
//fprintf(out,"THREAD %d : %p: W %p\n", threadid, ip, addr);
}
if ((ref->thid != uid)){
int result = find_idiom(ref->thid, ref->id, uid,hash_val);
//fprintf (stderr, "Runtime: find_idiom() result was %d\n", result);
if (result == -1) // the nodes exist but there is no interleaving idiom between them... add it
{
mem_access_entry old = *ref;
mem_access_entry new_a;
new_a.addr = addr;
new_a.ipc = ip;
new_a.thid = uid;
new_a.type = MEM_WRITE;
new_a.id = hash_val;
new_a.timestamp = timestamp;
idiom i = make_pair(old, new_a);
interleavings.push_back(i);
add_idiom(ref->thid, ref->id, uid, hash_val);
}
ref->addr = addr;
ref->ipc = ip;
ref->thid = uid;
ref->type = MEM_WRITE;
ref->id = hash_val;
ref->timestamp = timestamp;
}
}
PIN_ReleaseLock(&lock);
}
// Is called for every instruction and instruments reads and writes
VOID Instruction(INS ins, VOID *v)
{
// Instruments memory accesses using a predicated call, i.e.
// the instrumentation is called iff the instruction will actually be executed.
//
// On the IA-32 and Intel(R) 64 architectures conditional moves and REP
// prefixed instructions appear as predicated instructions in Pin.
UINT32 memOperands = INS_MemoryOperandCount(ins);
// Iterate over each memory operand of the instruction.
for (UINT32 memOp = 0; memOp < memOperands; memOp++)
{
if (INS_MemoryOperandIsRead(ins, memOp))
{
INS_InsertPredicatedCall(
ins, IPOINT_BEFORE, (AFUNPTR)RecordMemRead,
IARG_INST_PTR,
IARG_MEMORYOP_EA, memOp,
IARG_THREAD_ID,
IARG_END);
}
// Note that in some architectures a single memory operand can be
// both read and written (for instance incl (%eax) on IA-32)
// In that case we instrument it once for read and once for write.
if (INS_MemoryOperandIsWritten(ins, memOp))
{
INS_InsertPredicatedCall(
ins, IPOINT_BEFORE, (AFUNPTR)RecordMemWrite,
IARG_INST_PTR,
IARG_MEMORYOP_EA, memOp,
IARG_THREAD_ID,
IARG_END);
}
}
}
extern char lock_functions[SETS][TYPES][MAX_FUNC_NAME_SIZE];
/* ===================================================================== */
/* Analysis routines */
/* ===================================================================== */
VOID LockBefore(ADDRINT addr, THREADID thid, VOID *ipc, UINT32 set, UINT32 sem)
{
INT32 line=0;
INT32 column=0;
string filename="";
unsigned char label[1024];
PIN_THREAD_UID uid;
uid = PIN_ThreadUid();
PIN_LockClient();
PIN_GetSourceLocation((ADDRINT) ipc,&column, &line, &filename);
PIN_UnlockClient();
PIN_GetLock(&lock, thid+1);
switch (set){
case PTHREADS_SEM:
pthreads_lock_refs[uid] = (unsigned long)addr;
break;
}
timestamp ++;
//fprintf(out,"timestamp , thread , operation , addr , line , column , file\n");
//fprintf (stdout, "BEF: Thread 0x%lx, op %s lock addr is : 0x%lx\n", (unsigned long) uid, lock_functions[set][sem], lock_refs[uid]);
sprintf((char *)label,"0x%lx , 0x%lx , %s , 0x%lx , %d , %d , %d", (unsigned long)ipc, (unsigned long)uid, lock_functions[set][sem] , (unsigned long)addr, line, column, file_hash(filename) );
if(generate_graph){
hash_val = shash(label);
if (graph_exists(uid)){
pair<long, node*> * edge=NULL;
unsigned long last_item_executed = graph_last_state(uid);
if (!thread_graphs[uid].has_node(hash_val)){ // does this line id exist in the graph?
thread_graphs[uid].add_node (hash_val, (unsigned long) addr, LOCK_REQ, timestamp, uid,
line, column, filename); // no, we have to create it.
}
edge = thread_graphs[uid].find_edge(last_item_executed, hash_val);
if (!edge) // does the edge between last item execited and id exist?
{
// no we have to create it
thread_graphs[uid].add_edge(last_item_executed, hash_val, 1);
}else{
edge->first++;
}
graph_set_last_state(uid, hash_val);
}else{
//fprintf(stderr, "Creating graph for thread x%x\n", selfThd);
graph_create(uid, hash_val, (unsigned long) addr, LOCK_REQ, timestamp, uid, line, column, filename);
}
}
fprintf (out, "%ld , %s\n", timestamp , label);
/*fprintf(out, "THREAD: 0x%lx, IPC: 0x%lx, %s: ( 0x%lx ), line: %d, filename: %s\n", (unsigned long)uid , (unsigned long)ipc,
lock_functions[set][sem], ((unsigned long)size), line, filename.c_str() );*/
PIN_ReleaseLock(&lock);
}
VOID LockAfter(THREADID thid, VOID * ipc, ADDRINT ret , UINT32 set, UINT32 sem)
{
INT32 line=0;
INT32 column=0;
string filename="";
unsigned char label[1024];
PIN_THREAD_UID uid;
uid = PIN_ThreadUid();
unsigned long addr=0;
PIN_LockClient();
PIN_GetSourceLocation((ADDRINT) ipc,&column, &line, &filename);
PIN_UnlockClient();
PIN_GetLock(&lock, thid+1);
// sprintf((char *)label,"THREAD-0x%lx-IPC-%lx-LOCK_GET-0x%lx", (unsigned long)uid, (unsigned long)ipc, (unsigned long) lock_refs[uid]);
//hash_val = fnv_64_str(label, hash_val);
timestamp ++;
//fprintf (stdout, "AFT: Thread 0x%lx, op %s lock addr is : 0x%lx\n", (unsigned long) uid, lock_functions_get[set][sem], lock_refs[uid]);
//fprintf(out,"timestamp , thread , operation , addr , line , column , file\n");
switch (set) {
case PTHREADS_SEM:
addr = pthreads_lock_refs[uid];
break;
default:
addr = (unsigned long) ret;
}
sprintf((char *)label,"0x%lx , 0x%lx , %s , 0x%lx , %d , %d , %d", (unsigned long) ipc, (unsigned long)uid, lock_functions_get[set][sem] , addr, line, column, file_hash(filename) );
if (generate_graph){
hash_val = shash(label);
if (graph_exists(uid)){
pair<long, node*> * edge=NULL;
unsigned long last_item_executed = graph_last_state(uid);
if (!thread_graphs[uid].has_node(hash_val)){ // does this line id exist in the graph?
thread_graphs[uid].add_node (hash_val, (unsigned long) lock_refs[uid], LOCK_GET, timestamp, uid,
line, column, filename); // no, we have to create it.
}
edge = thread_graphs[uid].find_edge(last_item_executed, hash_val);
if (!edge) // does the edge between last item execited and id exist?
{
// no we have to create it
thread_graphs[uid].add_edge(last_item_executed, hash_val, 1);
}else{
edge->first++;
}
graph_set_last_state(uid, hash_val);
}else{
//fprintf(stderr, "Creating graph for thread x%x\n", selfThd);
graph_create(uid, hash_val, lock_refs[uid], LOCK_GET, timestamp, uid, line, column, filename);
}
}
fprintf (out, "%ld , %s\n", timestamp , label);
//lock_refs[uid] = 0;
PIN_ReleaseLock(&lock);
}
VOID UnlockBefore(ADDRINT size, THREADID thid, VOID *ipc , UINT32 set, UINT32 sem)
{
INT32 line=0;
INT32 column=0;
string filename="";
unsigned char label[1024];
PIN_THREAD_UID uid;
uid = PIN_ThreadUid();
PIN_LockClient();
PIN_GetSourceLocation((ADDRINT) ipc,&column, &line, &filename);
PIN_UnlockClient();
PIN_GetLock(&lock, thid+1);
// sprintf((char *)label,"THREAD-0x%lx-IPC-%p-UNLOCK_REQ-0x%lx", (unsigned long)uid, ipc,(unsigned long)size);
timestamp ++;
sprintf((char *)label,"0x%lx , 0x%lx , %s , 0x%lx , %d , %d , %d", (unsigned long)ipc, (unsigned long)uid, lock_functions[set][sem] , (unsigned long)size, line, column, file_hash(filename) );
if (generate_graph){
hash_val = shash(label);
if (graph_exists(uid)){
pair<long, node*> * edge=NULL;
unsigned long last_item_executed = graph_last_state(uid);
if (!thread_graphs[uid].has_node(hash_val)){ // does this line id exist in the graph?
thread_graphs[uid].add_node (hash_val, (unsigned long) size, LOCK_REL, timestamp, uid,
line, column, filename); // no, we have to create it.
}
edge = thread_graphs[uid].find_edge(last_item_executed, hash_val);
if (!edge) // does the edge between last item execited and id exist?
{
// no we have to create it
thread_graphs[uid].add_edge(last_item_executed, hash_val, 1);
}else{
edge->first++;
}
graph_set_last_state(uid, hash_val);
}else{
//fprintf(stderr, "Creating graph for thread x%x\n", selfThd);
graph_create(uid, hash_val, (unsigned long) size, LOCK_REL, timestamp, uid, line, column, filename);
}
}
fprintf (out, "%ld , %s\n", timestamp , label);
/* fprintf(out, "THREAD: 0x%lx, IPC: 0x%lx, %s : ( 0x%lx ) , line: %d, filename: %s\n", (unsigned long) uid , (unsigned long)ipc,
lock_functions[set][sem], ((unsigned long)size), line, filename.c_str());*/
PIN_ReleaseLock(&lock);
}
VOID UnlockAfter(THREADID thid, VOID * ipc , UINT32 set, UINT32 sem)
{
/* INT32 line=0;
string filename="";
PIN_THREAD_UID uid;
uid = PIN_ThreadUid();
PIN_LockClient();
PIN_GetSourceLocation((ADDRINT) ipc,NULL, &line, &filename);
PIN_UnlockClient();
PIN_GetLock(&lock, thid+1);
fprintf(out, "THREAD: 0x%lx, IPC: 0x%lx, %s called , line: %d, filename: %s\n", (unsigned long)uid, (unsigned long) ipc,
lock_functions[set][sem], line, filename.c_str());
PIN_ReleaseLock(&lock);*/
}
VOID FreeBefore(THREADID thid, VOID * ip, ADDRINT param)
{
INT32 line=0;
INT32 column=0;
string filename="";
unsigned char label[1024];
int n = memory_map.count(param);
PIN_THREAD_UID uid;
uid = PIN_ThreadUid();
PIN_LockClient();
PIN_GetSourceLocation((ADDRINT) ip,&column, &line, &filename);
PIN_UnlockClient();
PIN_GetLock(&lock, thid+1);
//fprintf(stdout, "malloc_mt: Trying to erase 0x%lx\n", param );
timestamp ++;
//fprintf(out,"timestamp , thread , operation , addr , line , column , file\n");
sprintf((char *)label,"%ld , 0x%lx , 0x%lx , free , 0x%lx , %d , %d , %d", timestamp, (unsigned long)ip, (unsigned long)uid, (unsigned long)param, line, column, file_hash(filename) );
if (n != 0){
memory_map_state[param] = DELETED;
fprintf(out, "%s\n", label);
}else{
fprintf(stderr, "Racedet error: tried to erase an unknown region! IPC: 0x%lx\n", (unsigned long)ip);
}
PIN_ReleaseLock(&lock);
}
VOID MallocBefore(THREADID thid,VOID * ip, ADDRINT size)
{
PIN_THREAD_UID uid;
uid = PIN_ThreadUid();
//TraceFile << name << "(" << size << ")" << endl;
if( (unsigned long) ip == START_MALLOCS_ADDR){
//fprintf(out, "THREAD: %d, IPC: 0x%lx, OS: %ld\n", thid, (unsigned long)ip, size);
}
else
{
PIN_GetLock(&lock, thid+1);
memory_req_state[uid] = REQUEST;
mem_asked[uid] = size;
//fprintf(out, "THREAD: %d, IPC: 0x%lx, malloc(): %ld\n", thid, (unsigned long)ip, size);
PIN_ReleaseLock(&lock);
}
}
VOID MallocAfter(THREADID thid,VOID * ip, ADDRINT ret)
{
INT32 line=0;
INT32 column=0;
string filename="";
char label[1024];
PIN_THREAD_UID uid;
uid = PIN_ThreadUid();
PIN_LockClient();
PIN_GetSourceLocation((ADDRINT) ip,&column, &line, &filename);
PIN_UnlockClient();
if(memory_req_state[uid] == REQUEST)
{
if (ret == 0){ // malloc failed
mem_asked[uid] = 0;
return;
}
PIN_GetLock(&lock, thid+1);
//TraceFile << " returns " << ret << endl;
memory_map[ret] = mem_asked[uid];
memory_map_state[ret] = ALLOCATED;
memory_req_state[uid] = NONE;
timestamp ++;
//fprintf(out,"timestamp , thread , operation , addr , line , column , file\n");
sprintf((char *)label,"%ld , 0x%lx , 0x%lx , malloc , 0x%lx , %d , %d , %d", timestamp, (unsigned long)ip, (unsigned long)uid, (unsigned long)ret, mem_asked[uid], line, file_hash(filename) );
memory_map_descr[ret] = std::string(label) ;
mem_asked[uid] = 0;
fprintf(out, "%s\n", label);
PIN_ReleaseLock(&lock);
}else{
fprintf(stderr, "Racedet : malloc()return without 1st call! IPC: 0x%lx\n" , (unsigned long)ip);
}
}
//====================================================================
// Instrumentation Routines
//====================================================================
// This routine is executed for each image.
VOID ImageLoad(IMG img, VOID *)
{
// Instrument the malloc() and free() functions. Print the input argument
// of each malloc() or free(), and the return value of malloc().
//
// Find the malloc() function.
if (IMG_IsMainExecutable (img)){
mainExe = img;
}
RTN mallocRtn = RTN_FindByName(img, MALLOC);
if (RTN_Valid(mallocRtn))
{
RTN_Open(mallocRtn);
// Instrument malloc() to print the input argument value and the return value.
RTN_InsertCall(mallocRtn, IPOINT_BEFORE, (AFUNPTR)MallocBefore,
IARG_THREAD_ID,
IARG_INST_PTR,
IARG_FUNCARG_ENTRYPOINT_VALUE, 0,
IARG_END);
RTN_InsertCall(mallocRtn, IPOINT_AFTER, (AFUNPTR)MallocAfter,
IARG_THREAD_ID,
IARG_INST_PTR,
IARG_FUNCRET_EXITPOINT_VALUE, IARG_END);
RTN_Close(mallocRtn);
}
// Find the free() function.
RTN freeRtn = RTN_FindByName(img, FREE);
if (RTN_Valid(freeRtn))
{
RTN_Open(freeRtn);
// Instrument free() to print the input argument value.
RTN_InsertCall(freeRtn, IPOINT_BEFORE, (AFUNPTR)FreeBefore,
IARG_THREAD_ID,
IARG_INST_PTR,
IARG_FUNCARG_ENTRYPOINT_VALUE, 0,
IARG_END);
RTN_Close(freeRtn);
}
RTN pthreads_lockRtn = RTN_FindByName(img, "pthread_mutex_lock");
if (RTN_Valid(pthreads_lockRtn))
{
RTN_Open(pthreads_lockRtn);
// Instrument pthread_mutex_lock() to print the input argument value and the return value.
RTN_InsertCall(pthreads_lockRtn, IPOINT_BEFORE, AFUNPTR(LockBefore),
IARG_FUNCARG_ENTRYPOINT_VALUE, 0,
IARG_THREAD_ID, IARG_INST_PTR,
IARG_UINT32, PTHREADS_SEM,
IARG_UINT32, REQ_LOCK,
IARG_END);
RTN_InsertCall(pthreads_lockRtn, IPOINT_AFTER, (AFUNPTR)LockAfter,
IARG_THREAD_ID,
IARG_INST_PTR,
IARG_FUNCRET_EXITPOINT_VALUE,
IARG_UINT32, PTHREADS_SEM,
IARG_UINT32, GOT_LOCK,
IARG_END);
RTN_Close(pthreads_lockRtn);
}
RTN pthreads_unlockRtn = RTN_FindByName(img, "pthread_mutex_unlock");
if (RTN_Valid(pthreads_unlockRtn))
{
RTN_Open(pthreads_unlockRtn);
// Instrument pthread_mutex_lock() to print the input argument value and the return value.
RTN_InsertCall(pthreads_unlockRtn, IPOINT_BEFORE, AFUNPTR(UnlockBefore),
IARG_FUNCARG_ENTRYPOINT_VALUE, 0,
IARG_THREAD_ID, IARG_INST_PTR,
IARG_UINT32, PTHREADS_SEM,
IARG_UINT32, RELEASE_LOCK,
IARG_END);
/* RTN_InsertCall(unlockRtn, IPOINT_AFTER, (AFUNPTR)UnlockAfter,
IARG_THREAD_ID,
IARG_INST_PTR,
IARG_FUNCRET_EXITPOINT_VALUE, IARG_END);*/
RTN_InsertCall(pthreads_unlockRtn, IPOINT_AFTER, (AFUNPTR)UnlockAfter,
IARG_THREAD_ID,
IARG_INST_PTR,
IARG_UINT32, PTHREADS_SEM,
IARG_UINT32, RELEASE_LOCK,
IARG_END);
RTN_Close(pthreads_unlockRtn);
}
}
// This routine is executed once at the end.
VOID Fini(INT32 code, VOID *v)
{
Memory_Map::const_iterator itr;
map<std::string, unsigned int>::const_iterator fmap_itr;
char from_type_str[20];
char to_type_str[20];
vector<idiom>::const_iterator i_itr;
fclose(out);
out = fopen (KnobMmapFile.Value().c_str(), "w");
if (out != NULL){
std::string str;
fprintf(out, "Address , Size , Freed? , Description\n");
for (itr = memory_map.begin(); itr != memory_map.end(); ++itr)
{
str = memory_map_descr[(*itr).first];
str.erase (std::remove (str.begin(), str.end(), ' '), str.end());
std::replace(str.begin(), str.end(), ',' , ':');
fprintf(out, "0x%lx , %d , %s , %s\n", (*itr).first, (*itr).second, memory_map_state[(*itr).first]? ( memory_map_state[(*itr).first]==1? "NO": "GLOBAL" ):"YES", str.c_str());
}
fclose(out);
}else{
PIN_ERROR("Unable to create memory map " + KnobMmapFile.Value() +"\n");
}
out = fopen (KnobSrcMapFile.Value().c_str(), "w");
if (out != NULL){
fprintf(out, "id , Filename\n");
for(fmap_itr = files.begin(); fmap_itr != files.end(); ++fmap_itr)
{
fprintf(out, " %d , %s\n", (unsigned int)((*fmap_itr).second), ((*fmap_itr).first).c_str());
}
fclose(out);
}else{
PIN_ERROR("Unable to create source file map " + KnobSrcMapFile.Value() +"\n");
}
// KnobIdiomFile
/*typedef struct {
unsigned long thid;
unsigned long id;
void * ipc;
void * addr;
unsigned char type;
unsigned long timestamp;
} mem_access_entry;*/
if (generate_graph){
out = fopen (KnobIdiomFile.Value().c_str(), "w");
if (out != NULL){
mem_access_entry from, to;
fprintf(out, "from_timestamp , to_timestamp , from_thread, to_thread , from_op , to_op , addr\n");
for (i_itr = interleavings.begin(); i_itr != interleavings.end(); ++i_itr){
from = (*i_itr).first;
to = (*i_itr).second;
fill_type_str(from_type_str, from.type);
fill_type_str(to_type_str, to.type);
fprintf(out, "%ld , %ld , 0x%lx , 0x%lx , %s , %s , 0x%lx\n", from.timestamp , to.timestamp , from.thid , to.thid , from_type_str, to_type_str, (unsigned long) to.addr);
}
fclose(out);
}else{
PIN_ERROR("Unable to create idiom list file " + KnobIdiomFile.Value() +"\n");
}
}
if (generate_graph){
char graph_file_name[256] = "racedet_overall.dot";
FILE * gr = fopen (graph_file_name, "w");
int i =0;
if (gr != NULL)
{
fprintf (gr, "digraph {\n");
fprintf (gr, " compound=true;\n");
for (map<unsigned long, graph>::iterator itr=thread_graphs.begin(); itr != thread_graphs.end(); ++itr)
{
(*itr).second.save_to_subgraph(gr, i);
i++;
}
save_idioms (gr);
fprintf (gr, "}\n");
}
fclose(gr);
}
}
KNOB<string> KnobSymbolFile(KNOB_MODE_WRITEONCE,
"pintool", "s", "default.lst", "specify list of symbols file name");
char tool_name[] = "thread scheduler 1.0";
bool read_symbol_list()
{
FILE * in;
unsigned long addr;
unsigned int size;
char name[1024];
int ret=0;
in = fopen(KnobSymbolFile.Value().c_str(), "r");
if (in==NULL){
PIN_ERROR("Unable to open symbol list " + KnobSymbolFile.Value() +"\n");
return false;
}
while (ret != EOF){
ret = fscanf (in, "%lx %d %s", &addr, &size, name);
if (ret == 3)
{
if (size > 0)
{
memory_map[addr] = size;
memory_map_state[addr] = GLOBAL;
memory_map_descr[addr] = name;
//fprintf(stdout, "ADDR: 0x%lx SIZE: %d NAME: %s\n", addr, size, name);
}
}
}
fclose(in);
return true;
}
/* ===================================================================== */
/* Print Help Message */
/* ===================================================================== */
INT32 Usage()
{
PIN_ERROR("This Pintool prints a trace of malloc calls in the guest application\n"
+ KNOB_BASE::StringKnobSummary() + "\n");
return -1;
}
/* ===================================================================== */
/* Main */
/* ===================================================================== */
int main(INT32 argc, CHAR **argv)
{
// Initialize the pin lock
PIN_InitLock(&lock);
// Initialize pin
if (PIN_Init(argc, argv)) return Usage();
PIN_InitSymbols();
out = fopen(KnobOutputFile.Value().c_str(), "w");
fprintf(out,"timestamp , ipc , thread , operation , addr , line , column , file\n");
if (KnobAllMemAccesses){
gather_all = 1;
fprintf(stderr, "Racedet: gathering all memory accesses\n");
}
else{
gather_all = 0;
fprintf(stderr, "Racedet: NOT gathering all memory accesses\n");
}
if (KnobGenerateGraph){
generate_graph = 1;
fprintf(stderr, "Racedet: generating graphs\n");
}
else{
generate_graph = 0;
fprintf(stderr, "Racedet: NOT generating graphs\n");
}
//gather_all = 0;
memset(&table[0], 0, HASH_SIZE * sizeof(mem_access_entry));
read_symbol_list();
// Register ImageLoad to be called when each image is loaded.
IMG_AddInstrumentFunction(ImageLoad, 0);
// Register Instruction to be called when every instruction runs
INS_AddInstrumentFunction(Instruction, 0);
// Register Analysis routines to be called when a thread begins/ends
PIN_AddThreadStartFunction(ThreadStart, 0);
PIN_AddThreadFiniFunction(ThreadFini, 0);
// Register Fini to be called when the application exits
PIN_AddFiniFunction(Fini, 0);
// Never returns
PIN_StartProgram();
return 0;
}
| 35,374 | 13,746 |
/*
* JSONConfiguration.cpp
*
* Created on: Jul 10, 2014
* Author: ahueck
*/
#include <core/configuration/JSONConfiguration.h>
#include <core/logging/Logger.h>
#include <fstream>
namespace opov {
JSONConfiguration::JSONConfiguration() {
// TODO Auto-generated constructor stub
}
bool JSONConfiguration::load(const std::string& file) {
std::ifstream in(file);
if (!in.is_open()) {
LOG_INFO("Configuration file not found: " << file << ". Exiting...");
return false;
}
json::parse(in, data);
return true;
}
void JSONConfiguration::getValue(const std::string& id, std::string& val, std::string def) const {
val = get<std::string>(id, std::move(def));
}
void JSONConfiguration::getValue(const std::string& id, double& val, double def) const {
val = get<double>(id, std::move(def));
}
void JSONConfiguration::getValue(const std::string& id, int& val, int def) const {
val = get<int>(id, std::move(def));
}
void JSONConfiguration::getValue(const std::string& id, bool& val, bool def) const {
val = get<bool>(id, std::move(def));
}
void JSONConfiguration::getVector(const std::string& id, std::vector<std::string>& vec) const {
vec = getVec<std::string>(id);
}
void JSONConfiguration::getVector(const std::string& id, std::vector<double>& vec) const {
vec = getVec<double>(id);
}
void JSONConfiguration::getVector(const std::string& id, std::vector<int>& vec) const {
vec = getVec<int>(id);
}
void JSONConfiguration::getVector(const std::string& id, std::vector<bool>& vec) const {
vec = getVec<bool>(id);
}
JSONConfiguration::~JSONConfiguration() {
// TODO Auto-generated destructor stub
}
} /* namespace opov */
| 1,669 | 544 |
#pragma once
#include <phantasm-hardware-interface/commands.hh>
#include <phantasm-renderer/argument.hh>
#include <phantasm-renderer/common/api.hh>
#include <phantasm-renderer/fwd.hh>
#include <phantasm-renderer/resource_types.hh>
namespace pr::raii
{
class Frame;
class PR_API ComputePass
{
public:
[[nodiscard]] ComputePass bind(prebuilt_argument const& sv)
{
ComputePass p = {mParent, mCmd, mArgNum};
p.add_argument(sv._sv, phi::handle::null_resource, 0);
return p;
}
[[nodiscard]] ComputePass bind(prebuilt_argument const& sv, buffer const& constant_buffer, uint32_t constant_buffer_offset = 0)
{
ComputePass p = {mParent, mCmd, mArgNum};
p.add_argument(sv._sv, constant_buffer.res.handle, constant_buffer_offset);
return p;
}
// CBV only
[[nodiscard]] ComputePass bind(buffer const& constant_buffer, uint32_t constant_buffer_offset = 0)
{
ComputePass p = {mParent, mCmd, mArgNum};
p.add_argument(phi::handle::null_shader_view, constant_buffer.res.handle, constant_buffer_offset);
return p;
}
// raw phi
[[nodiscard]] ComputePass bind(phi::handle::shader_view sv, phi::handle::resource cbv = phi::handle::null_resource, uint32_t cbv_offset = 0)
{
ComputePass p = {mParent, mCmd, mArgNum};
p.add_argument(sv, cbv, cbv_offset);
return p;
}
// cache-access variants
// hits a OS mutex
[[nodiscard]] ComputePass bind(argument const& arg)
{
ComputePass p = {mParent, mCmd, mArgNum};
p.add_cached_argument(arg, phi::handle::null_resource, 0);
return p;
}
[[nodiscard]] ComputePass bind(argument const& arg, buffer const& constant_buffer, uint32_t constant_buffer_offset = 0)
{
ComputePass p = {mParent, mCmd, mArgNum};
p.add_cached_argument(arg, constant_buffer.res.handle, constant_buffer_offset);
return p;
}
void dispatch(uint32_t x, uint32_t y = 1, uint32_t z = 1);
void dispatch_indirect(buffer const& argument_buffer, uint32_t num_arguments = 1, uint32_t offset_bytes = 0);
void set_constant_buffer(buffer const& constant_buffer, unsigned offset = 0);
void set_constant_buffer(phi::handle::resource raw_cbv, unsigned offset = 0);
void set_constant_buffer_offset(unsigned offset);
template <class T>
void write_constants(T const& val)
{
mCmd.write_root_constants<T>(val);
}
ComputePass(ComputePass&& rhs) = default;
private:
friend class Frame;
// Frame-side ctor
ComputePass(Frame* parent, phi::handle::pipeline_state pso) : mParent(parent) { mCmd.pipeline_state = pso; }
private:
// internal re-bind ctor
ComputePass(Frame* parent, phi::cmd::dispatch const& cmd, unsigned arg_i) : mParent(parent), mCmd(cmd), mArgNum(arg_i) {}
private:
// persisted, raw phi
void add_argument(phi::handle::shader_view sv, phi::handle::resource cbv, uint32_t cbv_offset);
// cache-access variant
// hits a OS mutex
void add_cached_argument(argument const& arg, phi::handle::resource cbv, uint32_t cbv_offset);
Frame* mParent = nullptr;
phi::cmd::dispatch mCmd;
// index of owning argument - 1, 0 means no arguments existing
unsigned mArgNum = 0;
};
// inline implementation
inline void ComputePass::set_constant_buffer(const buffer& constant_buffer, unsigned offset)
{
set_constant_buffer(constant_buffer.res.handle, offset);
}
inline void ComputePass::set_constant_buffer(phi::handle::resource raw_cbv, unsigned offset)
{
CC_ASSERT(mArgNum != 0 && "Attempted to set_constant_buffer on a ComputePass without prior bind");
mCmd.shader_arguments[uint8_t(mArgNum - 1)].constant_buffer = raw_cbv;
mCmd.shader_arguments[uint8_t(mArgNum - 1)].constant_buffer_offset = offset;
}
inline void ComputePass::set_constant_buffer_offset(unsigned offset)
{
CC_ASSERT(mArgNum != 0 && "Attempted to set_constant_buffer_offset on a ComputePass without prior bind");
mCmd.shader_arguments[uint8_t(mArgNum - 1)].constant_buffer_offset = offset;
}
inline void ComputePass::add_argument(phi::handle::shader_view sv, phi::handle::resource cbv, uint32_t cbv_offset)
{
++mArgNum;
mCmd.add_shader_arg(cbv, cbv_offset, sv);
}
}
| 4,281 | 1,489 |
#include <autograph/Core/Support/Debug.h>
#include <autograph/Core/Support/string_view.h>
#include <autograph/Core/Types.h>
#include <autograph/Engine/ResourceManager.h>
#include <experimental/filesystem>
namespace ag {
namespace fs = std::experimental::filesystem;
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
namespace ResourceManager {
static std::vector<std::string> resourceDirectories_;
// returns the main path part of the ID, or the empty string if it has none
std::string getPathPart(const char *id) {
ag::string_view idstr{id};
return idstr.substr(0, idstr.find_last_of('$')).to_string();
}
std::string getPathPart(const std::string &id) {
return getPathPart(id.c_str());
}
// returns the subpath part of the ID, or the empty string if it has none
std::string getSubpathPart(const char *id) {
ag::string_view idstr{id};
auto p = idstr.find_last_of('$');
if (p == std::string::npos) {
return {};
} else {
return idstr.substr(p + 1).to_string();
}
}
std::string getSubpathPart(const std::string &id) {
return getSubpathPart(id.c_str());
}
std::string getParentPath(const char *id) {
fs::path path = getPathPart(id);
return path.parent_path().generic_string();
}
std::string getParentPath(const std::string &id) {
return getParentPath(id.c_str());
}
void addResourceDirectory(const std::string &fullPath) {
addResourceDirectory(fullPath.c_str());
}
void addResourceDirectory(const char *fullPath) {
resourceDirectories_.emplace_back(fullPath);
}
int getResourceDirectoriesCount() { return (int)resourceDirectories_.size(); }
std::string getResourceDirectory(int index) {
return resourceDirectories_[index];
}
std::string getFilesystemPath(const char *id) {
return getFilesystemPath(id, {});
}
std::string getFilesystemPath(const std::string &id) {
return getFilesystemPath(id.c_str());
}
std::string getFilesystemPath(const char *id,
ag::span<const char *const> prefixes) {
namespace fs = std::experimental::filesystem;
std::string pathPart = getPathPart(id);
std::string ret;
// first, check if ID is a well-specified filesystem path
fs::path path{pathPart};
if (fs::is_regular_file(path)) {
return pathPart;
}
for (auto &dir : resourceDirectories_) {
fs::path baseDir{dir};
if (prefixes.empty()) {
auto fullPath = baseDir / pathPart;
if (fs::is_regular_file(fullPath)) {
// got our file
AG_DEBUG("{} -> {}", pathPart, fullPath.string());
ret = fullPath.string();
return ret;
}
} else {
for (auto prefix : prefixes) {
auto fullPath = baseDir / prefix / pathPart;
if (fs::is_regular_file(fullPath)) {
// got our file
AG_DEBUG("{} -> {}", pathPart, fullPath.string());
ret = fullPath.string();
return ret;
}
}
}
}
AG_DEBUG("findResourceFile: {} not found", pathPart);
AG_DEBUG(" Tried directories:");
for (auto &dir : resourceDirectories_) {
AG_DEBUG(" - {}", dir);
}
if (!prefixes.empty()) {
AG_DEBUG(" Tried prefixes:");
for (auto prefix : prefixes) {
AG_DEBUG(" - {}", prefix);
}
}
return {};
}
} // namespace ResourceManager
} // namespace ag
| 3,337 | 1,058 |
#include "pch.h"
#include "Shader.h"
#include <fstream>
#include <sstream>
const Shader* Shader::m_currentlyBound = nullptr;
Shader::Shader(const char* vertexShaderPath, const char* fragmentShaderPath)
: m_id(0)
{
PS_LOG("Shader object constructed");
assignData(vertexShaderPath, fragmentShaderPath);
m_isDataAssigned = true;
}
Shader::Shader()
: m_isDataAssigned(false), m_id(0)
{
PS_LOG("Shader object constructed without data assignment!");
}
Shader::~Shader()
{
GL_CALL(glDeleteProgram(m_id));
PS_LOG("Shader #%d deleted", m_id);
}
void Shader::assignData(const char* vertexShaderPath, const char* fragmentShaderPath)
{
std::string vertexStr;
std::string fragmentStr;
readFiles(vertexShaderPath, fragmentShaderPath, vertexStr, fragmentStr);
createShaderProgram(vertexStr, fragmentStr);
m_isDataAssigned = true;
PS_LOG("Shader #%d data assigned", m_id);
}
void Shader::bind() const
{
PS_ASSERT(m_isDataAssigned, "Tring to bind Shader without data assigned!");
if (Shader::m_currentlyBound != this)
{
GL_CALL(glUseProgram(m_id));
Shader::m_currentlyBound = this;
PS_LOG("Shader #%d is now bound", m_id);
}
}
void Shader::unbind() const
{
GL_CALL(glUseProgram(0));
Shader::m_currentlyBound = nullptr;
PS_LOG("No Shader bound.");
}
void Shader::setUniform(const std::string& name, float x)
{
int location = glGetUniformLocation(m_id, name.c_str());
glUniform1f(location, x);
}
void Shader::setUniform(const std::string& name, bool x)
{
int location = glGetUniformLocation(m_id, name.c_str());
glUniform1i(location, x);
}
void Shader::setUniform(const std::string& name, int x)
{
int location = glGetUniformLocation(m_id, name.c_str());
glUniform1i(location, x);
}
void Shader::setUniform(const std::string& name, float x, float y, float z, float w)
{
int location = glGetUniformLocation(m_id, name.c_str());
glUniform4f(location, x, y, z, w);
}
void Shader::setUniform(const std::string& name, const glm::vec4& vec)
{
setUniform(name, vec.x, vec.y, vec.z, vec.w);
}
void Shader::setUniform(const std::string& name, float x, float y, float z)
{
int location = glGetUniformLocation(m_id, name.c_str());
glUniform3f(location, x, y, z);
}
void Shader::setUniform(const std::string& name, const glm::vec3& vec)
{
setUniform(name, vec.x, vec.y, vec.z);
}
void Shader::setUniform(const std::string& name, float x, float y)
{
int location = glGetUniformLocation(m_id, name.c_str());
glUniform2f(location, x, y);
}
void Shader::setUniform(const std::string& name, const glm::vec2& vec)
{
setUniform(name, vec.x, vec.y);
}
void Shader::setUniform(const std::string& name, const glm::mat4& mat)
{
int location = glGetUniformLocation(m_id, name.c_str());
glUniformMatrix4fv(location, 1, GL_FALSE, glm::value_ptr(mat));
}
void Shader::setUniform(const std::string& name, const glm::mat3& mat)
{
int location = glGetUniformLocation(m_id, name.c_str());
glUniformMatrix3fv(location, 1, GL_FALSE, glm::value_ptr(mat));
}
void Shader::readFiles(const char* vertexShaderPath,
const char* fragmentShaderPath,
std::string& vertexStr,
std::string& fragmentStr)
{
std::ifstream vertexFile;
std::ifstream fragmentFile;
vertexFile.exceptions(std::ifstream::badbit | std::ifstream::failbit);
fragmentFile.exceptions(std::ifstream::badbit | std::ifstream::failbit);
try
{
std::stringstream vertexStream;
vertexFile.open(vertexShaderPath);
vertexStream << vertexFile.rdbuf();
vertexFile.close();
vertexStr = vertexStream.str();
std::stringstream fragmentStream;
fragmentFile.open(fragmentShaderPath);
fragmentStream << fragmentFile.rdbuf();
fragmentFile.close();
fragmentStr = fragmentStream.str();
}
catch (const std::exception & e)
{
PS_ASSERT(false, "Failed with some shader file!\n%s", e.what());
}
}
void Shader::createShaderProgram(std::string& vertexStr, std::string& fragmentStr)
{
unsigned int vertexShader = compileSingleShader(vertexStr.c_str(), GL_VERTEX_SHADER);
unsigned int fragmentShader = compileSingleShader(fragmentStr.c_str(), GL_FRAGMENT_SHADER);
int success;
GL_CALL(m_id = glCreateProgram());
GL_CALL(glAttachShader(m_id, vertexShader));
GL_CALL(glAttachShader(m_id, fragmentShader));
GL_CALL(glLinkProgram(m_id));
glGetProgramiv(m_id, GL_LINK_STATUS, &success);
if (!success)
{
char errorInfo[512];
glGetProgramInfoLog(m_id, 512, NULL, errorInfo);
PS_ASSERT(success, "%s", errorInfo);
}
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
}
unsigned int Shader::compileSingleShader(const char* shaderStr, GLenum shaderEnum)
{
int success;
GL_CALL(unsigned int shader = glCreateShader(shaderEnum));
GL_CALL(glShaderSource(shader, 1, &shaderStr, NULL));
GL_CALL(glCompileShader(shader));
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (!success)
{
char errorInfo[512];
glGetShaderInfoLog(shader, 512, NULL, errorInfo);
PS_ASSERT(success, "%s", errorInfo);
}
return shader;
} | 5,344 | 1,905 |
// Loader.hpp
// Class that loads a .obj file into vectors of floats for OpenGL
#ifndef LOADER_HPP
#define LOADER_HPP
#include <vector>
#include "IndexedVertexArray.hpp"
#include <glm/glm.hpp>
#include <glm/gtx/transform.hpp>
using std::vector;
class Loader {
private:
public:
static IndexedVertexArray* loadObjFile(const char * path);
};
#endif // LOADER_HPP
| 384 | 142 |
class Solution {
public:
string countAndSay(int n) {
int curr = 1;
string curr_str = "1";
while (curr < n) {
curr++;
string newString;
char curr_char = ' ';
int count = 0;
for (int i = 0; i < curr_str.size(); i++) {
if (curr_str[i] == curr_char) {
count++;
} else {
if (curr_char != ' ') {
newString.push_back('1' + count - 1);
newString.push_back(curr_char);
}
curr_char = curr_str[i];
count = 1;
}
}
newString.push_back('1' + count - 1);
newString.push_back(curr_char);
curr_str = newString;
}
return curr_str;
}
}; | 870 | 250 |
#include "acmacs-base/argv.hh"
#include "acmacs-base/read-file.hh"
#include "acmacs-base/range-v3.hh"
#include "acmacs-whocc/xlsx.hh"
#include "acmacs-whocc/log.hh"
// ----------------------------------------------------------------------
using namespace acmacs::argv;
struct Options : public argv
{
Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); }
option<str_array> verbose{*this, 'v', "verbose", desc{"comma separated list (or multiple switches) of enablers"}};
argument<str_array> xlsx{*this, arg_name{".xlsx"}, mandatory};
};
int main(int argc, char* const argv[])
{
using namespace std::string_view_literals;
using namespace acmacs;
int exit_code = 0;
try {
Options opt(argc, argv);
acmacs::log::enable(opt.verbose);
for (const auto& filename : *opt.xlsx) {
AD_INFO("{}", filename);
auto doc = acmacs::xlsx::open(filename);
// AD_INFO("{} sheets: {}", filename, doc.number_of_sheets());
for (const auto sheet_no : range_from_0_to(doc.number_of_sheets())) {
auto sheet = doc.sheet(sheet_no);
AD_INFO(" {}: \"{}\" {}-{}", sheet_no + 1, sheet->name(), sheet->number_of_rows(), sheet->number_of_columns());
for (acmacs::sheet::nrow_t row{0}; row < sheet->number_of_rows(); ++row) {
for (acmacs::sheet::ncol_t col{0}; col < sheet->number_of_columns(); ++col) {
const auto cell = fmt::format("{}", sheet->cell(row, col));
AD_LOG(acmacs::log::xlsx, "cell {}{}: \"{}\"", row, col, cell);
}
}
}
}
}
catch (std::exception& err) {
AD_ERROR("{}", err);
exit_code = 2;
}
return exit_code;
}
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
| 2,041 | 678 |
/////////////////////////////////////////////////////////////////////////////
// Copyright (C) 1993-1996 Microsoft Corporation. All Rights Reserved.
//
// MODULE: PickGrp.cpp
//
// PURPOSE: Dialog to allow the user to select groups to post to in the
// send note window.
//
#include "pch.hxx"
#include <iert.h>
#include "pickgrp.h"
#include "grplist2.h"
#include "shlwapip.h"
#include "resource.h"
#include "strconst.h"
#include "demand.h"
CPickGroupDlg::CPickGroupDlg()
{
m_cRef = 1;
m_ppszGroups = 0;
m_hwndPostTo = 0;
m_fPoster = FALSE;
m_hIcon = NULL;
m_pGrpList = NULL;
m_pszAcct = NULL;
m_idAcct = FOLDERID_INVALID;
}
CPickGroupDlg::~CPickGroupDlg()
{
if (m_hIcon)
SideAssert(DestroyIcon(m_hIcon));
if (m_pGrpList != NULL)
m_pGrpList->Release();
}
HRESULT STDMETHODCALLTYPE CPickGroupDlg::QueryInterface(REFIID riid, void **ppvObj)
{
if (IsEqualIID(riid, IID_IUnknown))
*ppvObj = (void*) (IUnknown *)(IGroupListAdvise *)this;
else if (IsEqualIID(riid, IID_IGroupListAdvise))
*ppvObj = (void*) (IGroupListAdvise *) this;
else
{
*ppvObj = NULL;
return E_NOINTERFACE;
}
AddRef();
return S_OK;
}
ULONG STDMETHODCALLTYPE CPickGroupDlg::AddRef()
{
return ++m_cRef;
}
ULONG STDMETHODCALLTYPE CPickGroupDlg::Release()
{
if (--m_cRef == 0)
{
delete this;
return 0;
}
return m_cRef;
}
//
// FUNCTION: CPickGroupsDlg::FCreate()
//
// PURPOSE: Handles initialization of the data and creation of the pick
// groups dialog.
//
// PARAMETERS:
// hwndOwner - Window that will own this dialog.
// pszAccount - account to use initially.
// ppszGroups - This is where we return the last selected group
//
// RETURN VALUE:
// Returns TRUE if successful, or FALSE otherwise.
//
BOOL CPickGroupDlg::FCreate(HWND hwndOwner, FOLDERID idServer, LPSTR *ppszGroups, BOOL fPoster)
{
int iret;
HRESULT hr;
FOLDERID idAcct;
FOLDERINFO info;
char szAcct[CCHMAX_ACCOUNT_NAME];
Assert(ppszGroups != NULL);
m_pGrpList = new CGroupList;
if (m_pGrpList == NULL)
return(FALSE);
m_ppszGroups = ppszGroups;
m_fPoster = fPoster;
hr = g_pStore->GetFolderInfo(idServer, &info);
if (FAILED(hr))
return(FALSE);
StrCpyN(szAcct, info.pszName, ARRAYSIZE(szAcct));
g_pStore->FreeRecord(&info);
m_pszAcct = szAcct;
m_idAcct = idServer;
// Now create the dialog.
iret = (int) DialogBoxParam(g_hLocRes, MAKEINTRESOURCE(iddPickGroup), hwndOwner, PickGrpDlgProc, (LPARAM)this);
return(iret == IDOK);
}
INT_PTR CALLBACK CPickGroupDlg::PickGrpDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
BOOL fRet;
CPickGroupDlg *pThis;
fRet = TRUE;
pThis = (CPickGroupDlg *)GetWindowLongPtr(hwnd, DWLP_USER);
switch (msg)
{
case WM_INITDIALOG:
Assert(pThis == NULL);
Assert(lParam != NULL);
pThis = (CPickGroupDlg *)lParam;
SetWindowLongPtr(hwnd, DWLP_USER, (LPARAM)pThis);
fRet = pThis->_OnInitDialog(hwnd);
break;
case WM_CLOSE:
pThis->_OnClose(hwnd);
break;
case WM_COMMAND:
pThis->_OnCommand(hwnd, LOWORD(wParam), (HWND)lParam, HIWORD(wParam));
break;
case WM_NOTIFY:
pThis->_OnNotify(hwnd, (int)wParam, (LPNMHDR)lParam);
break;
case WM_TIMER:
pThis->_OnTimer(hwnd, (UINT)wParam);
break;
case WM_PAINT:
pThis->_OnPaint(hwnd);
break;
case NVM_CHANGESERVERS:
pThis->_OnChangeServers(hwnd);
break;
default:
fRet = FALSE;
break;
}
return(fRet);
}
//
// FUNCTION: CPickGroupDlg::OnInitDialog()
//
// PURPOSE: Handles initializing the PickGroup dialog. Initializes the
// dependant classes, list view, buttons, etc.
//
// PARAMETERS:
// hwnd - Handle of the dialog box.
// hwndFocus - Handle of the control that will get focus if TRUE is returned.
// lParam - Contains a pointer to a string of newsgroups the user has
// already selected.
//
// RETURN VALUE:
// Returns TRUE to set the focus to hwndFocus, or FALSE otherwise.
//
BOOL CPickGroupDlg::_OnInitDialog(HWND hwnd)
{
char szTitle[256];
LV_COLUMN lvc;
RECT rc;
LONG cx;
HDC hdc;
TEXTMETRIC tm;
HIMAGELIST himl;
HRESULT hr;
HWND hwndList;
CColumns *pColumns;
m_hwnd = hwnd;
m_hwndPostTo = GetDlgItem(hwnd, idcPostTo);
hwndList = GetDlgItem(hwnd, idcGroupList);
pColumns = new CColumns;
if (pColumns == NULL)
{
EndDialog(hwnd, IDCANCEL);
return(FALSE);
}
pColumns->Initialize(hwndList, COLUMN_SET_PICKGRP);
pColumns->ApplyColumns(COLUMN_LOAD_DEFAULT, 0, 0);
Assert(m_pGrpList != NULL);
hr = m_pGrpList->Initialize((IGroupListAdvise *)this, pColumns, hwndList, FOLDER_NEWS);
Assert(SUCCEEDED(hr));
pColumns->Release();
// Bug #21471 - Add the server name to the dialog box title
GetWindowText(hwnd, szTitle, ARRAYSIZE(szTitle));
Assert(m_pszAcct);
StrCatBuff(szTitle, m_pszAcct, ARRAYSIZE(szTitle));
SetWindowText(hwnd, szTitle);
GetClientRect(m_hwndPostTo, &rc);
// Set the image lists for the listview
himl = ImageList_LoadBitmap(g_hLocRes, MAKEINTRESOURCE(idbFolders), 16, 0, RGB(255, 0, 255));
Assert(himl);
// Group name column
lvc.mask = LVCF_SUBITEM | LVCF_WIDTH;
lvc.cx = rc.right;
lvc.iSubItem = 0;
ListView_InsertColumn(m_hwndPostTo, 0, &lvc);
// Make the second listview have images too
ListView_SetImageList(m_hwndPostTo, himl, LVSIL_SMALL);
hdc = GetDC(hwndList);
if (GetTextMetrics(hdc, &tm))
{
cx = tm.tmAveCharWidth * 150;
ListView_SetColumnWidth(hwndList, 0, cx);
ListView_SetColumnWidth(m_hwndPostTo, 0, cx);
}
ReleaseDC(hwndList, hdc);
SendDlgItemMessage(hwnd, idcShowFavorites, BM_SETCHECK, TRUE, 0L);
if (!m_fPoster)
ShowWindow(GetDlgItem(hwnd, idcEmailAuthor), SW_HIDE);
m_hIcon = (HICON)LoadImage(g_hLocRes, MAKEINTRESOURCE(idiNewsGroup), IMAGE_ICON, 16, 16, 0);
SendDlgItemMessage(hwnd, idcShowFavorites, BM_SETIMAGE, IMAGE_ICON, (LPARAM)m_hIcon);
PostMessage(hwnd, NVM_CHANGESERVERS, 0, 0L);
return(FALSE);
}
BOOL CPickGroupDlg::_OnFilter(HWND hwnd)
{
UINT cch;
LPSTR pszText;
HRESULT hr;
BOOL fSub;
HWND hwndEdit;
pszText = NULL;
hwndEdit = GetDlgItem(hwnd, idcFindText);
cch = GetWindowTextLength(hwndEdit);
if (cch > 0)
{
cch++;
if (!MemAlloc((void **)&pszText, cch + 1))
return(FALSE);
GetWindowText(hwndEdit, pszText, cch);
}
fSub = (IsDlgButtonChecked(hwnd, idcShowFavorites));
hr = m_pGrpList->Filter(pszText, fSub ? SUB_TAB_SUBSCRIBED : SUB_TAB_ALL, FALSE);
Assert(SUCCEEDED(hr));
if (pszText != NULL)
MemFree(pszText);
return(TRUE);
}
void CPickGroupDlg::_OnChangeServers(HWND hwnd)
{
LPSTR pszTok, pszToken;
UINT index;
HRESULT hr;
FOLDERINFO Folder;
// TODO: we need to fix the initialization so the filtering is only performed
// once (we should call IGroupList::Filter once and then IGroupList::SetServer once
// during creation of the dialog)
UpdateWindow(hwnd);
_OnFilter(hwnd);
hr = m_pGrpList->SetServer(m_idAcct);
Assert(SUCCEEDED(hr));
if (m_ppszGroups)
{
pszTok = *m_ppszGroups;
pszToken = StrTokEx(&pszTok, c_szDelimiters);
while (pszToken != NULL)
{
if (m_fPoster && 0 == lstrcmpi(pszToken, c_szPosterKeyword))
CheckDlgButton(hwnd, idcEmailAuthor, TRUE);
ZeroMemory(&Folder, sizeof(FOLDERINFO));
Folder.idParent = m_idAcct;
Folder.pszName = pszToken;
if (DB_S_FOUND == g_pStore->FindRecord(IINDEX_ALL, COLUMNS_ALL, &Folder, NULL))
{
_InsertList(Folder.idFolder);
g_pStore->FreeRecord(&Folder);
}
pszToken = StrTokEx(&pszTok, c_szDelimiters);
}
MemFree(*m_ppszGroups);
*m_ppszGroups = 0;
}
// Bug #17674 - Make sure the post-to listview has an initial selection.
ListView_SetItemState(m_hwndPostTo, 0, LVIS_SELECTED, LVIS_SELECTED);
_UpdateStateUI(hwnd);
}
//
// FUNCTION: CPickGroupDlg::OnCommand()
//
// PURPOSE: Processes the WM_COMMAND messages for the pick group dialog.
//
// PARAMETERS:
// hwnd - Handle of the dialog window.
// id - ID of the control which sent the message.
// hwndCtl - Handle of the control sending the message.
// codeNotify - Notification code being sent.
//
void CPickGroupDlg::_OnCommand(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify)
{
switch (id)
{
case idcAddGroup:
_AddGroup();
break;
case idcRemoveGroup:
_RemoveGroup();
break;
case IDOK:
if (_OnOK(hwnd))
EndDialog(hwnd, IDOK);
break;
case IDCANCEL:
EndDialog(hwnd, IDCANCEL);
break;
case idcShowFavorites:
_OnFilter(hwnd);
_UpdateStateUI(hwnd);
break;
case idcFindText:
// This is generated when someone types in the find text edit box.
// We set a timer and when that timer expires we assume the user is
// done typing and go ahead and perform the query.
if (EN_CHANGE == codeNotify)
{
KillTimer(hwnd, idtFindDelay);
SetTimer(hwnd, idtFindDelay, dtFindDelay, NULL);
}
break;
}
}
HRESULT CPickGroupDlg::ItemUpdate(void)
{
_UpdateStateUI(m_hwnd);
return(S_OK);
}
HRESULT CPickGroupDlg::ItemActivate(FOLDERID id)
{
_AddGroup();
return(S_OK);
}
//
// FUNCTION: CPickGroupDlg::OnNotify()
//
// PURPOSE: Handles notification messages from the group list listview.
//
// PARAMETERS:
// hwnd - Handle of the pick group dialog.
// idFrom - ID of the control sending the notification.
// pnmhdr - Pointer to the NMHDR struct with the notification info.
//
// RETURN VALUE:
// Dependent on the notification.
//
LRESULT CPickGroupDlg::_OnNotify(HWND hwnd, int idFrom, LPNMHDR pnmhdr)
{
HRESULT hr;
LRESULT lRes;
hr = m_pGrpList->HandleNotify(hwnd, idFrom, pnmhdr, &lRes);
if (hr == S_OK)
return(lRes);
switch (pnmhdr->code)
{
case NM_DBLCLK:
if (pnmhdr->hwndFrom == m_hwndPostTo)
_RemoveGroup();
break;
case LVN_ITEMCHANGED:
_UpdateStateUI(hwnd);
break;
}
return(0);
}
void CPickGroupDlg::_OnTimer(HWND hwnd, UINT id)
{
KillTimer(hwnd, id);
_OnFilter(hwnd);
_UpdateStateUI(hwnd);
}
void CPickGroupDlg::_OnClose(HWND hwnd)
{
int iReturn;
iReturn = AthMessageBoxW(hwnd, MAKEINTRESOURCEW(idsAthenaNews),
MAKEINTRESOURCEW(idsDoYouWantToSave), 0,
MB_YESNOCANCEL | MB_ICONEXCLAMATION );
if (iReturn == IDYES)
_OnCommand(hwnd, IDOK, 0, 0);
else if (iReturn == IDNO)
_OnCommand(hwnd, IDCANCEL, 0, 0);
}
//
// FUNCTION: CPickGroupDlg::OnOK()
//
// PURPOSE: This function copies the group names from the dialog that
// the user has selected and returns them in the pointer the
// caller provided.
//
// RETURN VALUE:
// Returns TRUE if the copy was successful, or FALSE otherwise.
//
// COMMENTS:
// Note - 1000 characters is a good maximum line length (specified by the
// Son-of-RFC 1036 doc) so we limit the number of groups based on
// this line limit.
//
//
BOOL CPickGroupDlg::_OnOK(HWND hwnd)
{
// OK, we've got the entire sorted list. Create a string with all the groups
// and put it in the edit control.
char szGroups[c_cchLineMax], szGroup[256];
int cGroups;
LPSTR psz;
LV_ITEM lvi;
int cchGroups = 0, cch;
szGroups[0] = 0;
if (m_fPoster && IsDlgButtonChecked(hwnd, idcEmailAuthor))
{
StrCatBuff(szGroups, c_szPosterKeyword, ARRAYSIZE(szGroups));
cchGroups += lstrlen(c_szPosterKeyword);
}
if (cGroups = ListView_GetItemCount(m_hwndPostTo))
{
lvi.mask = LVIF_TEXT;
lvi.iSubItem = 0;
lvi.pszText = szGroup;
lvi.cchTextMax = ARRAYSIZE(szGroup);
for (lvi.iItem = 0; lvi.iItem < cGroups; lvi.iItem++)
{
// Get the item
ListView_GetItem(m_hwndPostTo, &lvi);
// Make sure the length of this next group doesn't push us over
// the max line length.
cch = lstrlen(lvi.pszText);
if ((cch + cchGroups + 2) > c_cchLineMax)
{
// Bug #24156 - If we have to truncate, then let the user know.
AthMessageBoxW(hwnd, MAKEINTRESOURCEW(idsAthenaNews),
MAKEINTRESOURCEW(idsErrNewsgroupLineTooLong), 0, MB_OK | MB_ICONINFORMATION);
return (FALSE);
}
if (cchGroups)
{
StrCatBuff(szGroups, ", ", ARRAYSIZE(szGroups));
}
StrCatBuff(szGroups, lvi.pszText, ARRAYSIZE(szGroups));
cchGroups += (cch + 2);
}
}
// Now that we're done building this marvelous string, copy it to
// the buffer for returning.
if (!MemAlloc((LPVOID *)&psz, cchGroups + 1))
return(FALSE);
StrCpyN(psz, szGroups, cchGroups + 1);
*m_ppszGroups = psz;
return(TRUE);
}
//
// FUNCTION: CPickGroupDlg::AddGroup()
//
// PURPOSE: Takes the group names selected in the ListView and adds them
// to the selected groups Post To list.
//
void CPickGroupDlg::_AddGroup(void)
{
FOLDERID *pid;
DWORD cid, i;
HCURSOR hcur;
HRESULT hr;
hcur = SetCursor(LoadCursor(NULL, IDC_WAIT));
SetWindowRedraw(m_hwndPostTo, FALSE);
hr = m_pGrpList->GetSelectedCount(&cid);
if (SUCCEEDED(hr) && cid > 0)
{
if (MemAlloc((void **)&pid, cid * sizeof(FOLDERID)))
{
hr = m_pGrpList->GetSelected(pid, &cid);
if (SUCCEEDED(hr))
{
for (i = 0; i < cid; i++)
{
_InsertList(pid[i]);
}
}
MemFree(pid);
}
}
if (-1 == ListView_GetNextItem(m_hwndPostTo, -1, LVNI_ALL | LVNI_SELECTED))
ListView_SetItemState(m_hwndPostTo, 0, LVIS_FOCUSED | LVIS_SELECTED, LVIS_FOCUSED | LVIS_SELECTED);
SetWindowRedraw(m_hwndPostTo, TRUE);
InvalidateRect(m_hwndPostTo, NULL, TRUE);
SetCursor(hcur);
}
//
// FUNCTION: CPickGroupDlg::InsertList()
//
// PURPOSE: Given a index into the CGroupList's newsgroup list, that group
// is inserted into the Post To list.
//
// PARAMETERS:
// index - Index of a newsgroup in the CGroupList newsgroup list.
//
void CPickGroupDlg::_InsertList(FOLDERID id)
{
LV_ITEM lvi;
int count;
FOLDERINFO info;
HRESULT hr;
count = ListView_GetItemCount(m_hwndPostTo);
// First make sure this isn't a duplicate.
lvi.mask = LVIF_PARAM;
lvi.iSubItem = 0;
for (lvi.iItem = 0; lvi.iItem < count; lvi.iItem++)
{
ListView_GetItem(m_hwndPostTo, &lvi);
if (id == (FOLDERID)lvi.lParam)
return;
}
hr = g_pStore->GetFolderInfo(id, &info);
if (SUCCEEDED(hr))
{
lvi.mask = LVIF_TEXT | LVIF_PARAM;
lvi.iItem = 0;
lvi.iSubItem = 0;
lvi.pszText = info.pszName;
if (!!(info.dwFlags & FOLDER_SUBSCRIBED))
{
lvi.iImage = iNewsGroup;
lvi.mask |= LVIF_IMAGE;
}
lvi.lParam = (LPARAM)id;
ListView_InsertItem(m_hwndPostTo, &lvi);
g_pStore->FreeRecord(&info);
}
}
void CPickGroupDlg::_RemoveGroup(void)
{
int index, count, iItemFocus;
HCURSOR hcur;
hcur = SetCursor(LoadCursor(NULL, IDC_WAIT));
SetWindowRedraw(m_hwndPostTo, FALSE);
count = ListView_GetItemCount(m_hwndPostTo);
iItemFocus = ListView_GetNextItem(m_hwndPostTo, -1, LVNI_FOCUSED);
// Loop through all the selected items and remove them from the ListView
for (index = count; index >= 0; index--)
{
if (ListView_GetItemState(m_hwndPostTo, index, LVIS_SELECTED))
ListView_DeleteItem(m_hwndPostTo, index);
}
// Bug #22189 - Make sure the focus/selection goes somewhere after we delete.
iItemFocus--;
if (iItemFocus < 0 || ListView_GetItemCount(m_hwndPostTo) < iItemFocus)
iItemFocus = 0;
ListView_SetItemState(m_hwndPostTo, iItemFocus, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
SetWindowRedraw(m_hwndPostTo, TRUE);
InvalidateRect(m_hwndPostTo, NULL, TRUE);
SetCursor(hcur);
}
void CPickGroupDlg::_UpdateStateUI(HWND hwnd)
{
DWORD cid;
HRESULT hr;
hr = m_pGrpList->GetSelectedCount(&cid);
if (FAILED(hr))
return;
EnableWindow(GetDlgItem(hwnd, idcAddGroup), cid > 0);
EnableWindow(GetDlgItem(hwnd, idcRemoveGroup), ListView_GetSelectedCount(m_hwndPostTo));
}
void CPickGroupDlg::_OnPaint(HWND hwnd)
{
RECT rc;
HDC hdc;
PAINTSTRUCT ps;
HFONT hf;
char szBuffer[CCHMAX_STRINGRES];
hdc = BeginPaint(hwnd, &ps);
// Only do this if the button is available
if (IsWindow(GetDlgItem(hwnd, idcShowFavorites)))
{
// Get the position of the toggle button
GetClientRect(GetDlgItem(hwnd, idcShowFavorites), &rc);
MapWindowPoints(GetDlgItem(hwnd, idcShowFavorites), hwnd, (LPPOINT) &rc, 1);
rc.left += (rc.right + 4);
rc.right = rc.left + 300;
rc.top += 1;
rc.bottom += rc.top;
AthLoadString(idsShowFavorites, szBuffer, ARRAYSIZE(szBuffer));
hf = (HFONT) SelectObject(hdc, (HFONT) SendMessage(hwnd, WM_GETFONT, 0, 0));
SetBkMode(hdc, TRANSPARENT);
SetTextColor(hdc, GetSysColor(COLOR_WINDOWTEXT));
DrawText(hdc, szBuffer, lstrlen(szBuffer),
&rc, DT_SINGLELINE | DT_VCENTER | DT_NOCLIP);
SelectObject(hdc, hf);
}
EndPaint(hwnd, &ps);
}
| 19,719 | 7,318 |
//
// Handshake.cpp
// HackerRank
//
// Created by Fabrizio Duroni on 02/09/16.
//
// https://www.hackerrank.com/challenges/handshake
#include <cmath>
#include <iostream>
using namespace std;
/*
In the previous version I used the
standard Binomial coefficient formula.
But there's a more efficient multiplicative
formula that could be used:
https://en.wikipedia.org/wiki/Binomial_coefficient#Multiplicative_formula
Expanding the multiplicative formula for k = 2
gives the following formula:
binomial_coefficient = (n^2 - n) / 2
This is the formula used below to compute the
number of handshakes between board members.
*/
int main() {
int t;
cin >> t;
unsigned long long n;
for(int i = 0; i < t; i++) {
cin >> n;
unsigned long long handshakes = (pow(n, 2) - n) / 2;
cout << handshakes << endl;
}
return 0;
}
| 938 | 322 |
/*
* Copyright (c) 2021, Krisna Pranav
*
* SPDX-License-Identifier: BSD-2-Clause
*/
// includes
#include <base/MACAddress.h>
#include <kernel/bus/PCI/IDs.h>
#include <kernel/net/E1000ENetworkAdapter.h>
#include <kernel/Sections.h>
namespace Kernel {
#define REG_EEPROM 0x0014
static bool is_valid_device_id(u16 device_id)
{
switch (device_id) {
case 0x10D3:
return true;
case 0x1000:
case 0x0438:
case 0x043A:
case 0x043C:
case 0x0440:
case 0x1001:
case 0x1004:
case 0x1008:
case 0x1009:
case 0x100C:
case 0x100D:
case 0x100E:
case 0x100F:
case 0x1010:
case 0x1011:
case 0x1012:
case 0x1013:
case 0x1014:
case 0x1015:
case 0x1016:
case 0x1017:
case 0x1018:
case 0x1019:
case 0x101A:
case 0x101D:
case 0x101E:
case 0x1026:
case 0x1027:
case 0x1028:
case 0x1049:
case 0x104A:
case 0x104B:
case 0x104C:
case 0x104D:
case 0x105E:
case 0x105F:
case 0x1060:
case 0x1075:
case 0x1076:
case 0x1077:
case 0x1078:
case 0x1079:
case 0x107A:
case 0x107B:
case 0x107C:
case 0x107D:
case 0x107E:
case 0x107F:
case 0x108A:
case 0x108B:
case 0x108C:
case 0x1096:
case 0x1098:
case 0x1099:
case 0x109A:
case 0x10A4:
case 0x10A5:
case 0x10A7:
case 0x10A9:
case 0x10B5:
case 0x10B9:
case 0x10BA:
case 0x10BB:
case 0x10BC:
case 0x10BD:
case 0x10BF:
case 0x10C0:
case 0x10C2:
case 0x10C3:
case 0x10C4:
case 0x10C5:
case 0x10C9:
case 0x10CA:
case 0x10CB:
case 0x10CC:
case 0x10CD:
case 0x10CE:
case 0x10D5:
case 0x10D6:
case 0x10D9:
case 0x10DA:
case 0x10DE:
case 0x10DF:
case 0x10E5:
case 0x10E6:
case 0x10E7:
case 0x10E8:
case 0x10EA:
case 0x10EB:
case 0x10EF:
case 0x10F0:
case 0x10F5:
case 0x10F6:
case 0x1501:
case 0x1502:
case 0x1503:
case 0x150A:
case 0x150C:
case 0x150D:
case 0x150E:
case 0x150F:
case 0x1510:
case 0x1511:
case 0x1516:
case 0x1518:
case 0x1520:
case 0x1521:
case 0x1522:
case 0x1523:
case 0x1524:
case 0x1525:
case 0x1526:
case 0x1527:
case 0x152D:
case 0x152F:
case 0x1533:
case 0x1534:
case 0x1535:
case 0x1536:
case 0x1537:
case 0x1538:
case 0x1539:
case 0x153A:
case 0x153B:
case 0x1546:
case 0x1559:
case 0x155A:
case 0x156F:
case 0x1570:
case 0x157B:
case 0x157C:
case 0x15A0:
case 0x15A1:
case 0x15A2:
case 0x15A3:
case 0x15B7:
case 0x15B8:
case 0x15B9:
case 0x15BB:
case 0x15BC:
case 0x15BD:
case 0x15BE:
case 0x15D6:
case 0x15D7:
case 0x15D8:
case 0x15DF:
case 0x15E0:
case 0x15E1:
case 0x15E2:
case 0x15E3:
case 0x1F40:
case 0x1F41:
case 0x1F45:
case 0x294C:
return false;
default:
return false;
}
}
UNMAP_AFTER_INIT RefPtr<E1000ENetworkAdapter> E1000ENetworkAdapter::try_to_initialize(PCI::Address address)
{
auto id = PCI::get_id(address);
if (id.vendor_id != PCI::VendorID::Intel)
return {};
if (!is_valid_device_id(id.device_id))
return {};
u8 irq = PCI::get_interrupt_line(address);
auto adapter = adopt_ref_if_nonnull(new (nothrow) E1000ENetworkAdapter(address, irq));
if (!adapter)
return {};
if (adapter->initialize())
return adapter;
return {};
}
UNMAP_AFTER_INIT bool E1000ENetworkAdapter::initialize()
{
dmesgln("E1000e: Found @ {}", pci_address());
m_io_base = IOAddress(PCI::get_BAR2(pci_address()) & ~1);
enable_bus_mastering(pci_address());
size_t mmio_base_size = PCI::get_BAR_space_size(pci_address(), 0);
m_mmio_region = MM.allocate_kernel_region(PhysicalAddress(page_base_of(PCI::get_BAR0(pci_address()))), page_round_up(mmio_base_size), "E1000e MMIO", Region::Access::Read | Region::Access::Write, Region::Cacheable::No);
if (!m_mmio_region)
return false;
m_mmio_base = m_mmio_region->vaddr();
m_use_mmio = true;
m_interrupt_line = PCI::get_interrupt_line(pci_address());
dmesgln("E1000e: port base: {}", m_io_base);
dmesgln("E1000e: MMIO base: {}", PhysicalAddress(PCI::get_BAR0(pci_address()) & 0xfffffffc));
dmesgln("E1000e: MMIO base size: {} bytes", mmio_base_size);
dmesgln("E1000e: Interrupt line: {}", m_interrupt_line);
detect_eeprom();
dmesgln("E1000e: Has EEPROM? {}", m_has_eeprom);
read_mac_address();
const auto& mac = mac_address();
dmesgln("E1000e: MAC address: {}", mac.to_string());
initialize_rx_descriptors();
initialize_tx_descriptors();
setup_link();
setup_interrupts();
return true;
}
UNMAP_AFTER_INIT E1000ENetworkAdapter::E1000ENetworkAdapter(PCI::Address address, u8 irq)
: E1000NetworkAdapter(address, irq)
{
}
UNMAP_AFTER_INIT E1000ENetworkAdapter::~E1000ENetworkAdapter()
{
}
UNMAP_AFTER_INIT void E1000ENetworkAdapter::detect_eeprom()
{
m_has_eeprom = true;
}
UNMAP_AFTER_INIT u32 E1000ENetworkAdapter::read_eeprom(u8 address)
{
VERIFY(m_has_eeprom);
u16 data = 0;
u32 tmp = 0;
if (m_has_eeprom) {
out32(REG_EEPROM, ((u32)address << 2) | 1);
while (!((tmp = in32(REG_EEPROM)) & (1 << 1)))
;
} else {
out32(REG_EEPROM, ((u32)address << 2) | 1);
while (!((tmp = in32(REG_EEPROM)) & (1 << 1)))
;
}
data = (tmp >> 16) & 0xffff;
return data;
}
} | 5,901 | 3,092 |
// Copyright (C) 2004-2006 The Trustees of Indiana University.
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// Authors: Douglas Gregor
// Andrew Lumsdaine
#ifndef BOOST_GRAPH_PARALLEL_DIJKSTRA_DETAIL_HPP
#define BOOST_GRAPH_PARALLEL_DIJKSTRA_DETAIL_HPP
#ifndef BOOST_GRAPH_USE_MPI
#error "Parallel BGL files should not be included unless <boost/graph/use_mpi.hpp> has been included"
#endif
#include <boost/property_map/property_map.hpp>
namespace boost { namespace graph { namespace distributed { namespace detail {
/**********************************************************************
* Dijkstra queue message data *
**********************************************************************/
template<typename DistanceMap, typename PredecessorMap>
class dijkstra_msg_value
{
typedef typename property_traits<DistanceMap>::value_type distance_type;
typedef typename property_traits<PredecessorMap>::value_type
predecessor_type;
public:
typedef std::pair<distance_type, predecessor_type> type;
static type create(distance_type dist, predecessor_type pred)
{ return std::make_pair(dist, pred); }
};
template<typename DistanceMap>
class dijkstra_msg_value<DistanceMap, dummy_property_map>
{
typedef typename property_traits<DistanceMap>::key_type vertex_descriptor;
public:
typedef typename property_traits<DistanceMap>::value_type type;
static type create(type dist, vertex_descriptor) { return dist; }
};
/**********************************************************************/
} } } } // end namespace boost::graph::distributed::detail
#endif // BOOST_GRAPH_PARALLEL_DIJKSTRA_DETAIL_HPP
| 1,812 | 555 |
/*
* Copyright (c) 2014, Autonomous Systems Lab
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Autonomous Systems Lab, ETH Zurich 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 ROVIO_ROVIO_INTERFACE_IMPL_H_
#define ROVIO_ROVIO_INTERFACE_IMPL_H_
#include <functional>
#include <memory>
#include <mutex>
#include <queue>
#include <glog/logging.h>
#include "rovio/CameraCalibration.hpp"
#include "rovio/CoordinateTransform/FeatureOutput.hpp"
#include "rovio/CoordinateTransform/FeatureOutputReadable.hpp"
#include "rovio/CoordinateTransform/LandmarkOutput.hpp"
#include "rovio/CoordinateTransform/RovioOutput.hpp"
#include "rovio/CoordinateTransform/YprOutput.hpp"
#include "rovio/FilterConfiguration.hpp"
#include "rovio/Memory.hpp"
#include "rovio/RovioFilter.hpp"
#include "RovioInterfaceStatesImpl.hpp"
#include "rovio/RovioInterface.hpp"
namespace rovio {
struct FilterInitializationState;
template <typename FILTER>
class RovioInterfaceImpl : public RovioInterface {
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
RovioInterfaceImpl(typename std::shared_ptr<FILTER> mpFilter);
explicit RovioInterfaceImpl(const std::string &filter_config_file);
RovioInterfaceImpl(
const std::string &filter_config_file,
const std::vector<std::string>& camera_calibration_files);
explicit RovioInterfaceImpl(const FilterConfiguration &filter_config);
RovioInterfaceImpl(
const FilterConfiguration &filter_config,
const CameraCalibrationVector& camera_calibrations);
virtual ~RovioInterfaceImpl() {}
typedef FILTER mtFilter;
typedef typename mtFilter::mtFilterState mtFilterState;
typedef typename mtFilterState::mtState mtState;
/** \brief Outputting the feature and patch update state involves allocating
* some large arrays and could result in some overhead. Therefore the
* state will not be retrieved by default.
*/
bool getState(const bool get_feature_update, const bool get_patch_update,
RovioState* filter_update);
bool getState(RovioState* filter_update);
/** \brief Returns the time step of the last/latest safe filter state..
*/
double getLastSafeTime();
/** \brief Reset the filter when the next IMU measurement is received.
* The orientaetion is initialized using an accel. measurement.
*/
void requestReset();
/** \brief Reset the filter when the next IMU measurement is received.
* The pose is initialized to the passed pose.
* @param WrWM - Position Vector, pointing from the World-Frame to the
* IMU-Frame, expressed in World-Coordinates.
* @param qMW - Quaternion, expressing World-Frame in IMU-Coordinates (World
* Coordinates->IMU Coordinates)
*/
void requestResetToPose(const V3D &WrWM, const QPD &qMW);
void resetToLastSafePose();
bool processVelocityUpdate(const Eigen::Vector3d &AvM, const double time_s);
bool processImuUpdate(const Eigen::Vector3d &acc, const Eigen::Vector3d &gyr,
const double time_s, bool update_filter);
bool processImageUpdate(const int camID, const cv::Mat &cv_img,
const double time_s);
bool processGroundTruthUpdate(const Eigen::Vector3d &JrJV, const QPD &qJV,
const double time_s);
bool processGroundTruthOdometryUpdate(
const Eigen::Vector3d &JrJV, const QPD &qJV,
const Eigen::Matrix<double, 6, 6> &measuredCov, const double time_s);
bool processLocalizationLandmarkUpdates(
const int camID, const Eigen::Matrix2Xd& keypoint_observations,
const Eigen::Matrix3Xd& G_landmarks, const double time_s);
void resetLocalizationMapBaseframeAndCovariance(
const V3D& WrWG, const QPD& qWG, double position_cov,
double rotation_cov);
/** \brief Register multiple callbacks that are invoked once the filter
* concludes a successful update.
*/
typedef std::function<void(const RovioState&)> RovioStateCallback;
void registerStateUpdateCallback(RovioStateCallback callback);
/** \brief Enable and disable feature and patch update output. If disabled,
* the RovioStateImpl<FILTER> returned by the callback does not contain
* any state information of the features/patches.
*/
void setEnableFeatureUpdateOutput(const bool enable_feature_update);
void setEnablePatchUpdateOutput(const bool get_patch_update);
bool isInitialized() const;
/** \brief Tests the functionality of the rovio node.
*
* @todo debug with doVECalibration = false and depthType = 0
*/
void makeTest();
private:
/** \brief Trigger a filter update. Will return true if an update happened.
*/
bool updateFilter();
void notifyAllStateUpdateCallbacks(const RovioState& state) const;
/** \brief Print update to std::cout and visualize images using opencv. The
* visualization is configured and enabled/disabled based on mpImgUpdate.
*/
void visualizeUpdate();
std::vector<RovioStateCallback> filter_update_state_callbacks_;
typedef StandardOutput mtOutput;
// TODO(mfehr): Ownership of the filter does not need to be shared, consider
// changing to unique ptr or raw ptr if someone outside the interface can own
// the filter.
std::shared_ptr<mtFilter> mpFilter_;
typedef typename mtFilter::mtPrediction::mtMeas mtPredictionMeas;
mtPredictionMeas predictionMeas_;
typedef typename std::tuple_element<0, typename mtFilter::mtUpdates>::type
mtImgUpdate;
mtImgUpdate *mpImgUpdate_;
typedef typename std::tuple_element<1, typename mtFilter::mtUpdates>::type
mtPoseUpdate;
mtPoseUpdate *mpPoseUpdate_;
typedef typename std::tuple_element<3, typename mtFilter::mtUpdates>::type
mtLocLandmarkUpdate;
mtLocLandmarkUpdate *mpLocLandmarkUpdate_;
typedef typename mtImgUpdate::mtMeas mtImgMeas;
mtImgMeas imgUpdateMeas_;
typedef typename mtPoseUpdate::mtMeas mtPoseMeas;
mtPoseMeas poseUpdateMeas_;
typedef typename mtLocLandmarkUpdate::mtMeas mtLocLandmarkMeas;
mtLocLandmarkMeas locLandmarkUpdateMeas_;
typedef typename std::tuple_element<2, typename mtFilter::mtUpdates>::type
mtVelocityUpdate;
typedef typename mtVelocityUpdate::mtMeas mtVelocityMeas;
mtVelocityMeas velocityUpdateMeas_;
struct FilterInitializationState {
FilterInitializationState()
: WrWM_(V3D::Zero()), state_(State::WaitForInitUsingAccel) {}
enum class State {
// Initialize the filter using accelerometer measurement on the next
// opportunity.
WaitForInitUsingAccel,
// Initialize the filter using an external pose on the next opportunity.
WaitForInitExternalPose,
// The filter is initialized.
Initialized
} state_;
// Buffer to hold the initial pose that should be set during initialization
// with the state WaitForInitExternalPose.
V3D WrWM_;
QPD qMW_;
explicit operator bool() const { return isInitialized(); }
bool isInitialized() const { return (state_ == State::Initialized); }
};
FilterInitializationState init_state_;
// Rovio outputs and coordinate transformations
Eigen::MatrixXd cameraOutputCov_;
CameraOutputCT<mtState> cameraOutputCT_;
ImuOutputCT<mtState> imuOutputCT_;
rovio::TransformFeatureOutputCT<mtState> transformFeatureOutputCT_;
rovio::LandmarkOutputImuCT<mtState> landmarkOutputImuCT_;
// Features.
rovio::FeatureOutput featureOutput_;
rovio::FeatureOutputReadable featureOutputReadable_;
rovio::FeatureOutputReadableCT featureOutputReadableCT_;
Eigen::MatrixXd featureOutputCov_;
Eigen::MatrixXd featureOutputReadableCov_;
// Landmarks.
rovio::LandmarkOutput landmarkOutput_;
Eigen::MatrixXd landmarkOutputCov_;
// State output config.
bool enable_feature_update_output_;
bool enable_patch_update_output_;
mutable std::recursive_mutex m_filter_;
};
} // namespace rovio
#endif // ROVIO_ROVIO_INTERFACE_IMPL_H_
#include "RovioInterfaceImplInl.hpp"
| 9,325 | 2,948 |
/*
* (c) Copyright 2020–2021 Xilinx, 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.
*
*/
#include <adf.h>
#include "system_settings.h"
// 16x8 x 8x8
// Can be extended to (2L)x(8M) (8M)x(8N)
void matmult_float(
input_window_float* __restrict matA,
input_window_float* __restrict matB,
output_window_float* __restrict matC)
{
v16float buf_matA = window_readincr_v16(matA); // holds the first 16 elements of matA
v8float buf_matB = undef_v8float(); // Holds 8 elements of matB
v8float acc1 = undef_v8float(); // 8 accumulation values on even rows
v8float acc2 = undef_v8float(); // 8 accumulation values on odd rows
#define FPMUL \
buf_matB = window_readincr_v8(matB); \
acc1 = fpmul(buf_matA,0,0x00000000,buf_matB,0,0x76543210);\
acc2 = fpmul(buf_matA,8,0x00000000,buf_matB,0,0x76543210)
#define FPMAC(Start1, Start2)\
buf_matB = window_readincr_v8(matB);\
acc1 = fpmac(acc1,buf_matA,Start1,0x00000000,buf_matB,0,0x76543210);\
acc2 = fpmac(acc2,buf_matA,Start2,0x00000000,buf_matB,0,0x76543210)
for (unsigned int i=0;i<F_Ra/2;i++) // Each iteration computes 2 rows of C
chess_prepare_for_pipelining
chess_loop_range(8,)
{
FPMUL;
FPMAC(1,9);
FPMAC(2,10);
FPMAC(3,11);
FPMAC(4,12);
FPMAC(5,13);
FPMAC(6,14);
FPMAC(7,15);
buf_matA = window_readincr_v16(matA); // reads the next 2 rows of A
window_decr_v8(matB,8); // reset B pointer
window_writeincr(matC,acc1); // Writes 1 row of C
window_writeincr(matC,acc2); // Writes the next row of C
}
}
| 2,128 | 917 |
#include <QtTest/QTest>
#include <QtTest/QSignalSpy>
#include "HttpHandlerTest.h"
#include "HttpHandler.h"
#include "HttpHandlerSimpleRouter.h"
#include "HttpConnection.h"
#include <QtCore/QDir>
#include <QtCore/QBuffer>
#include <QtCore/QCoreApplication>
using namespace Pillow;
Pillow::HttpConnection * HttpHandlerTestBase::createGetRequest(const QByteArray &path, const QByteArray& httpVersion)
{
return createRequest("GET", path, QByteArray(), httpVersion);
}
Pillow::HttpConnection * HttpHandlerTestBase::createPostRequest(const QByteArray &path, const QByteArray &content, const QByteArray &httpVersion)
{
return createRequest("POST", path, content, httpVersion);
}
Pillow::HttpConnection * HttpHandlerTestBase::createRequest(const QByteArray &method, const QByteArray &path, const QByteArray &content, const QByteArray &httpVersion)
{
QByteArray data = QByteArray().append(method).append(" ").append(path).append(" HTTP/").append(httpVersion).append("\r\n");
if (content.size() > 0)
{
data.append("Content-Length: ").append(QByteArray::number(content.size())).append("\r\n");
data.append("Content-Type: text/plain\r\n");
}
data.append("\r\n").append(content);
QBuffer* inputBuffer = new QBuffer(); inputBuffer->open(QIODevice::ReadWrite);
QBuffer* outputBuffer = new QBuffer(); outputBuffer->open(QIODevice::ReadWrite);
connect(outputBuffer, SIGNAL(bytesWritten(qint64)), this, SLOT(outputBuffer_bytesWritten()));
Pillow::HttpConnection* connection = new Pillow::HttpConnection(this);
connect(connection, SIGNAL(requestCompleted(Pillow::HttpConnection*)), this, SLOT(requestCompleted(Pillow::HttpConnection*)));
connection->initialize(inputBuffer, outputBuffer);
inputBuffer->setParent(connection);
outputBuffer->setParent(connection);
inputBuffer->write(data);
inputBuffer->seek(0);
while (connection->state() != Pillow::HttpConnection::SendingHeaders)
QCoreApplication::processEvents();
return connection;
}
void HttpHandlerTestBase::requestCompleted(Pillow::HttpConnection* connection)
{
QCoreApplication::processEvents();
response = responseBuffer;
responseBuffer = QByteArray();
requestParams = connection->requestParams();
}
void HttpHandlerTestBase::outputBuffer_bytesWritten()
{
QBuffer* buffer = static_cast<QBuffer*>(sender());
responseBuffer.append(buffer->data());
if (buffer->isOpen()) buffer->seek(0);
}
class MockHandler : public Pillow::HttpHandler
{
public:
MockHandler(const QByteArray& acceptPath, int statusCode, QObject* parent)
: Pillow::HttpHandler(parent), acceptPath(acceptPath), statusCode(statusCode), handleRequestCount(0)
{}
QByteArray acceptPath;
int statusCode;
int handleRequestCount;
bool handleRequest(Pillow::HttpConnection *connection)
{
++handleRequestCount;
if (acceptPath == connection->requestPath())
{
connection->writeResponse(statusCode);
return true;
}
return false;
}
};
void HttpHandlerTest::testHandlerStack()
{
HttpHandlerStack handler;
MockHandler* mock1 = new MockHandler("/1", 200, &handler);
MockHandler* mock1_1 = new MockHandler("/", 403, mock1);
new QObject(&handler); // Some dummy object, also child of handler.
MockHandler* mock2 = new MockHandler("/2", 302, &handler);
MockHandler* mock3 = new MockHandler("/", 500, &handler);
MockHandler* mock4 = new MockHandler("/", 200, &handler);
bool handled = handler.handleRequest(createGetRequest("/"));
QVERIFY(handled);
QVERIFY(response.startsWith("HTTP/1.0 500"));
QCOMPARE(mock1->handleRequestCount, 1);
QCOMPARE(mock1_1->handleRequestCount, 0);
QCOMPARE(mock2->handleRequestCount, 1);
QCOMPARE(mock3->handleRequestCount, 1);
QCOMPARE(mock4->handleRequestCount, 0);
handled = handler.handleRequest(createGetRequest("/2"));
QVERIFY(handled);
QVERIFY(response.startsWith("HTTP/1.0 302"));
QCOMPARE(mock1->handleRequestCount, 2);
QCOMPARE(mock1_1->handleRequestCount, 0);
QCOMPARE(mock2->handleRequestCount, 2);
QCOMPARE(mock3->handleRequestCount, 1);
QCOMPARE(mock4->handleRequestCount, 0);
}
void HttpHandlerTest::testHandlerFixed()
{
bool handled = HttpHandlerFixed(403, "Fixed test").handleRequest(createGetRequest());
QVERIFY(handled);
QVERIFY(response.startsWith("HTTP/1.0 403"));
QVERIFY(response.endsWith("\r\n\r\nFixed test"));
}
void HttpHandlerTest::testHandler404()
{
bool handled = HttpHandler404().handleRequest(createGetRequest("/some_path"));
QVERIFY(handled);
QVERIFY(response.startsWith("HTTP/1.0 404"));
QVERIFY(response.contains("/some_path"));
}
void HttpHandlerTest::testHandlerFunction()
{
#ifdef Q_COMPILER_LAMBDA
HttpHandlerFunction handler([](Pillow::HttpConnection* request)
{
request->writeResponse(200, Pillow::HttpHeaderCollection(), "hello from lambda");
});
QVERIFY(handler.handleRequest(createGetRequest("/some/random/path")));
QVERIFY(response.startsWith("HTTP/1.0 200 OK"));
QVERIFY(response.endsWith("hello from lambda"));
#else
QSKIP("Compiler does not support lambdas or C++0x support is not enabled.", SkipSingle);
#endif
}
void HttpHandlerTest::testHandlerLog()
{
QBuffer buffer; buffer.open(QIODevice::ReadWrite);
Pillow::HttpConnection* request1 = createGetRequest("/first");
Pillow::HttpConnection* request2 = createGetRequest("/second");
Pillow::HttpConnection* request3 = createGetRequest("/third");
HttpHandlerLog handler(&buffer, &buffer);
QVERIFY(!handler.handleRequest(request1));
QVERIFY(!handler.handleRequest(request2));
QVERIFY(!handler.handleRequest(request3));
QVERIFY(buffer.data().isEmpty());
request3->writeResponse(302);
request1->writeResponse(200);
request2->writeResponse(500);
// The log handler should write the log entries as they are completed.
buffer.seek(0);
QVERIFY(buffer.readLine().contains("GET /third"));
QVERIFY(buffer.readLine().contains("GET /first"));
QVERIFY(buffer.readLine().contains("GET /second"));
QVERIFY(buffer.readLine().isEmpty());
}
void HttpHandlerTest::testHandlerLogTrace()
{
QBuffer buffer; buffer.open(QIODevice::ReadWrite);
Pillow::HttpConnection* request1 = createGetRequest("/first", "1.1");
Pillow::HttpConnection* request2 = createGetRequest("/second", "1.1");
Pillow::HttpConnection* request3 = createGetRequest("/third", "1.1");
HttpHandlerLog handler(&buffer, &buffer);
handler.setMode(HttpHandlerLog::TraceRequests);
QVERIFY(!handler.handleRequest(request1));
QVERIFY(!buffer.data().isEmpty());
QVERIFY(buffer.data().contains("[BEGIN]"));
QVERIFY(!buffer.data().contains("[ END ]"));
QVERIFY(!handler.handleRequest(request2));
QVERIFY(!handler.handleRequest(request3));
request3->writeResponse(302);
QVERIFY(buffer.data().contains("[ END ]"));
request1->writeResponse(200);
request2->writeResponse(500);
QVERIFY(!buffer.data().contains("[CLOSE]"));
request1->close();
QVERIFY(buffer.data().contains("[CLOSE]"));
buffer.seek(0);
QVERIFY(buffer.readLine().contains("GET /first"));
QVERIFY(buffer.readLine().contains("GET /second"));
QVERIFY(buffer.readLine().contains("GET /third"));
QVERIFY(buffer.readLine().contains("GET /third")); // END
QVERIFY(buffer.readLine().contains("GET /first")); // END
QVERIFY(buffer.readLine().contains("GET /second")); // END
QVERIFY(buffer.readLine().contains("GET /first")); // CLOSE
QVERIFY(buffer.readLine().isEmpty());
}
void HttpHandlerFileTest::initTestCase()
{
testPath = QDir::tempPath() + "/HttpHandlerFileTest";
QDir(testPath).mkpath(".");
QVERIFY(QFile::exists(testPath));
QByteArray bigData(16 * 1024 * 1024, '-');
{ QFile f(testPath + "/first"); f.open(QIODevice::WriteOnly); f.write("first content"); f.flush(); f.close(); }
{ QFile f(testPath + "/second"); f.open(QIODevice::WriteOnly); f.write("second content"); f.flush(); f.close(); }
{ QFile f(testPath + "/large"); f.open(QIODevice::WriteOnly); f.write(bigData); f.flush(); f.close(); }
{ QFile f(testPath + "/first"); f.open(QIODevice::ReadOnly); QCOMPARE(f.readAll(), QByteArray("first content")); }
{ QFile f(testPath + "/second"); f.open(QIODevice::ReadOnly); QCOMPARE(f.readAll(), QByteArray("second content")); }
{ QFile f(testPath + "/large"); f.open(QIODevice::ReadOnly); QCOMPARE(f.readAll(), bigData); }
}
void HttpHandlerFileTest::testServesFiles()
{
HttpHandlerFile handler(testPath);
QVERIFY(!handler.handleRequest(createGetRequest("/")));
QVERIFY(!handler.handleRequest(createGetRequest("/bad_path")));
QVERIFY(!handler.handleRequest(createGetRequest("/another_bad")));
Pillow::HttpConnection* request = createGetRequest("/first");
QVERIFY(handler.handleRequest(request));
QVERIFY(response.startsWith("HTTP/1.0 200 OK"));
QVERIFY(response.endsWith("first content"));
response.clear();
// Note: the large files test currently fails when the output device is a QBuffer.
request = createGetRequest("/large");
QVERIFY(handler.handleRequest(request));
while (response.isEmpty())
QCoreApplication::processEvents();
QVERIFY(response.size() > 16 * 1024 * 1024);
QVERIFY(response.startsWith("HTTP/1.0 200 OK"));
QVERIFY(response.endsWith(QByteArray(16 * 1024 * 1024, '-')));
}
void HttpHandlerSimpleRouterTest::testHandlerRoute()
{
HttpHandlerSimpleRouter handler;
handler.addRoute("/some_path", new HttpHandlerFixed(303, "Hello"));
handler.addRoute("/other/path", new HttpHandlerFixed(404, "World"));
handler.addRoute("/some_path/even/deeper", new HttpHandlerFixed(200, "!"));
QVERIFY(!handler.handleRequest(createGetRequest("/should_not_match")));
QVERIFY(!handler.handleRequest(createGetRequest("/should/not/match/either")));
QVERIFY(!handler.handleRequest(createGetRequest("/some_path/should_not_match")));
QVERIFY(handler.handleRequest(createGetRequest("/other/path")));
QVERIFY(response.startsWith("HTTP/1.0 404"));
QVERIFY(response.endsWith("World"));
response.clear();
QVERIFY(handler.handleRequest(createGetRequest("/some_path/even/deeper?with=query_string")));
QVERIFY(response.startsWith("HTTP/1.0 200"));
QVERIFY(response.endsWith("!"));
response.clear();
}
void HttpHandlerSimpleRouterTest::testQObjectMetaCallRoute()
{
HttpHandlerSimpleRouter handler;
handler.addRoute("/first", this, "handleRequest1");
handler.addRoute("/first/second", this, "handleRequest2");
QVERIFY(!handler.handleRequest(createGetRequest("/should_not_match")));
QVERIFY(!handler.handleRequest(createGetRequest("/should/not/match/either")));
QVERIFY(!handler.handleRequest(createGetRequest("/first/should_not_match")));
QVERIFY(!handler.handleRequest(createGetRequest("/first/second/should_not_match")));
QVERIFY(handler.handleRequest(createGetRequest("/first")));
QVERIFY(response.startsWith("HTTP/1.0 403"));
QVERIFY(response.endsWith("Hello"));
response.clear();
QVERIFY(handler.handleRequest(createGetRequest("/first/second?with=query_string")));
QVERIFY(response.startsWith("HTTP/1.0 200"));
QVERIFY(response.endsWith("World"));
response.clear();
}
void HttpHandlerSimpleRouterTest::testQObjectSlotCallRoute()
{
HttpHandlerSimpleRouter handler;
handler.addRoute("/route", this, SLOT(handleRequest2(Pillow::HttpConnection*)));
QVERIFY(handler.handleRequest(createGetRequest("/route")));
QVERIFY(response.startsWith("HTTP/1.0 200"));
QVERIFY(response.endsWith("World"));
response.clear();
}
void HttpHandlerSimpleRouterTest::testStaticRoute()
{
HttpHandlerSimpleRouter handler;
handler.addRoute("/first", 200, Pillow::HttpHeaderCollection(), "First Route");
handler.addRoute("/first/second", 404, Pillow::HttpHeaderCollection(), "Second Route");
handler.addRoute("/third", 500, Pillow::HttpHeaderCollection(), "Third Route");
QVERIFY(!handler.handleRequest(createGetRequest("/should_not_match")));
QVERIFY(!handler.handleRequest(createGetRequest("/should/not/match/either")));
QVERIFY(!handler.handleRequest(createGetRequest("/first/should_not_match")));
QVERIFY(!handler.handleRequest(createGetRequest("/first/second/should_not_match")));
QVERIFY(handler.handleRequest(createGetRequest("/first")));
QVERIFY(response.startsWith("HTTP/1.0 200"));
QVERIFY(response.endsWith("First Route"));
response.clear();
QVERIFY(handler.handleRequest(createGetRequest("/third?with=query_string#and_fragment")));
QVERIFY(response.startsWith("HTTP/1.0 500"));
QVERIFY(response.endsWith("Third Route"));
response.clear();
}
void HttpHandlerSimpleRouterTest::testFuncRoute()
{
#ifdef Q_COMPILER_LAMBDA
HttpHandlerSimpleRouter handler;
handler.addRoute("/a_route", [](Pillow::HttpConnection* request) { request->writeResponse(200, Pillow::HttpHeaderCollection(), "Amazing First Route"); });
handler.addRoute("/a_route/and_another", [](Pillow::HttpConnection* request) { request->writeResponse(400, Pillow::HttpHeaderCollection(), "Delicious Second Route"); });
QVERIFY(!handler.handleRequest(createGetRequest("/should_not_match")));
QVERIFY(!handler.handleRequest(createGetRequest("/should/not/match/either")));
QVERIFY(!handler.handleRequest(createGetRequest("/a_route/should_not_match")));
QVERIFY(!handler.handleRequest(createGetRequest("/a_route/and_another/should_not_match")));
QVERIFY(handler.handleRequest(createGetRequest("/a_route")));
QVERIFY(response.startsWith("HTTP/1.0 200"));
QVERIFY(response.endsWith("Amazing First Route"));
response.clear();
QVERIFY(handler.handleRequest(createGetRequest("/a_route/and_another?with=query_string#and_fragment")));
QVERIFY(response.startsWith("HTTP/1.0 400"));
QVERIFY(response.endsWith("Delicious Second Route"));
response.clear();
#else
QSKIP("Compiler does not support lambdas or C++0x support is not enabled.", SkipSingle);
#endif
}
void HttpHandlerSimpleRouterTest::handleRequest1(Pillow::HttpConnection *request)
{
request->writeResponse(403, Pillow::HttpHeaderCollection(), "Hello");
}
void HttpHandlerSimpleRouterTest::handleRequest2(Pillow::HttpConnection *request)
{
request->writeResponse(200, Pillow::HttpHeaderCollection(), "World");
}
void HttpHandlerSimpleRouterTest::testPathParams()
{
HttpHandlerSimpleRouter handler;
handler.addRoute("/first/:with_param", 200, Pillow::HttpHeaderCollection(), "First Route");
handler.addRoute("/second/:with_param/and/:another", 200, Pillow::HttpHeaderCollection(), "Second Route");
handler.addRoute("/third/:with/:many/:params", 200, Pillow::HttpHeaderCollection(), "Third Route");
QVERIFY(handler.handleRequest(createGetRequest("/first/some_param-value")));
QVERIFY(response.startsWith("HTTP/1.0 200"));
QVERIFY(response.endsWith("First Route"));
QCOMPARE(requestParams.size(), 1);
QCOMPARE(requestParams.at(0).first, QString("with_param"));
QCOMPARE(requestParams.at(0).second, QString("some_param-value"));
response.clear();
QVERIFY(handler.handleRequest(createGetRequest("/second/some_param-value/and/another_value")));
QVERIFY(response.startsWith("HTTP/1.0 200"));
QVERIFY(response.endsWith("Second Route"));
QCOMPARE(requestParams.size(), 2);
QCOMPARE(requestParams.at(0).first, QString("with_param"));
QCOMPARE(requestParams.at(0).second, QString("some_param-value"));
QCOMPARE(requestParams.at(1).first, QString("another"));
QCOMPARE(requestParams.at(1).second, QString("another_value"));
response.clear();
QVERIFY(handler.handleRequest(createGetRequest("/third/some_param-value/another_value/and_a_last_one?with=overriden&extra=bonus_query_param#and_fragment")));
QVERIFY(response.startsWith("HTTP/1.0 200"));
QVERIFY(response.endsWith("Third Route"));
QCOMPARE(requestParams.size(), 4);
QCOMPARE(requestParams.at(0).first, QString("with"));
QCOMPARE(requestParams.at(0).second, QString("some_param-value")); // The route param should have overriden the query string param.
QCOMPARE(requestParams.at(1).first, QString("extra"));
QCOMPARE(requestParams.at(1).second, QString("bonus_query_param"));
QCOMPARE(requestParams.at(2).first, QString("many"));
QCOMPARE(requestParams.at(2).second, QString("another_value"));
QCOMPARE(requestParams.at(3).first, QString("params"));
QCOMPARE(requestParams.at(3).second, QString("and_a_last_one"));
response.clear();
QVERIFY(!handler.handleRequest(createGetRequest("/first/some_param-value/and_extra_stuff")));
QVERIFY(!handler.handleRequest(createGetRequest("/second/some_param-value/bad_part/another_value")));
QVERIFY(!handler.handleRequest(createGetRequest("/third/some_param-value/another_value/and_a_last_one/and_extra_stuff")));
}
void HttpHandlerSimpleRouterTest::testPathSplats()
{
HttpHandlerSimpleRouter handler;
handler.addRoute("/first/*with_splat", 200, Pillow::HttpHeaderCollection(), "First Route");
handler.addRoute("/second/:with_param/and/*splat", 200, Pillow::HttpHeaderCollection(), "Second Route");
handler.addRoute("/third/*with/two/*splats", 200, Pillow::HttpHeaderCollection(), "Third Route");
QVERIFY(handler.handleRequest(createGetRequest("/first/")));
QVERIFY(response.startsWith("HTTP/1.0 200"));
QVERIFY(response.endsWith("First Route"));
QCOMPARE(requestParams.size(), 1);
QCOMPARE(requestParams.at(0).first, QString("with_splat"));
QCOMPARE(requestParams.at(0).second, QString(""));
response.clear();
QVERIFY(handler.handleRequest(createGetRequest("/first/with/anything-after.that/really_I_tell_you.html")));
QVERIFY(response.startsWith("HTTP/1.0 200"));
QVERIFY(response.endsWith("First Route"));
QCOMPARE(requestParams.size(), 1);
QCOMPARE(requestParams.at(0).first, QString("with_splat"));
QCOMPARE(requestParams.at(0).second, QString("with/anything-after.that/really_I_tell_you.html"));
response.clear();
QVERIFY(handler.handleRequest(createGetRequest("/second/some-param-value/and/")));
QVERIFY(response.startsWith("HTTP/1.0 200"));
QVERIFY(response.endsWith("Second Route"));
QCOMPARE(requestParams.size(), 2);
QCOMPARE(requestParams.at(0).first, QString("with_param"));
QCOMPARE(requestParams.at(0).second, QString("some-param-value"));
QCOMPARE(requestParams.at(1).first, QString("splat"));
QCOMPARE(requestParams.at(1).second, QString(""));
response.clear();
QVERIFY(handler.handleRequest(createGetRequest("/second/some-param-value/and/extra/stuff/splatted.at/the.end?with=bonus_query_param#and_fragment")));
QVERIFY(response.startsWith("HTTP/1.0 200"));
QVERIFY(response.endsWith("Second Route"));
QCOMPARE(requestParams.size(), 3);
QCOMPARE(requestParams.at(0).first, QString("with"));
QCOMPARE(requestParams.at(0).second, QString("bonus_query_param"));
QCOMPARE(requestParams.at(1).first, QString("with_param"));
QCOMPARE(requestParams.at(1).second, QString("some-param-value"));
QCOMPARE(requestParams.at(2).first, QString("splat"));
QCOMPARE(requestParams.at(2).second, QString("extra/stuff/splatted.at/the.end"));
response.clear();
QVERIFY(handler.handleRequest(createGetRequest("/third/some/path/two/and/another/path%20with%20spaces.txt")));
QVERIFY(response.startsWith("HTTP/1.0 200"));
QVERIFY(response.endsWith("Third Route"));
QCOMPARE(requestParams.size(), 2);
QCOMPARE(requestParams.at(0).first, QString("with"));
QCOMPARE(requestParams.at(0).second, QString("some/path"));
QCOMPARE(requestParams.at(1).first, QString("splats"));
QCOMPARE(requestParams.at(1).second, QString("and/another/path with spaces.txt"));
response.clear();
QVERIFY(!handler.handleRequest(createGetRequest("/first")));
QVERIFY(!handler.handleRequest(createGetRequest("/second/some_param-value/")));
QVERIFY(!handler.handleRequest(createGetRequest("/second/some_param-value/and")));
QVERIFY(!handler.handleRequest(createGetRequest("/second/some_param-value/bad_part/splat/splat/splat")));
}
void HttpHandlerSimpleRouterTest::testMatchesMethod()
{
HttpHandlerSimpleRouter handler;
handler.addRoute("GET", "/get", 200, Pillow::HttpHeaderCollection(), "First Route");
handler.addRoute("POST", "/post", 200, Pillow::HttpHeaderCollection(), "Second Route");
handler.addRoute("GET", "/both", 200, Pillow::HttpHeaderCollection(), "Third Route (GET)");
handler.addRoute("POST", "/both", 200, Pillow::HttpHeaderCollection(), "Third Route (POST)");
QVERIFY(handler.handleRequest(createGetRequest("/get")));
QVERIFY(!handler.handleRequest(createPostRequest("/get")));
QVERIFY(!handler.handleRequest(createGetRequest("/post")));
QVERIFY(handler.handleRequest(createPostRequest("/post")));
QVERIFY(handler.handleRequest(createGetRequest("/both")));
QVERIFY(response.startsWith("HTTP/1.0 200"));
QVERIFY(response.endsWith("Third Route (GET)"));
response.clear();
QVERIFY(handler.handleRequest(createPostRequest("/both")));
QVERIFY(response.startsWith("HTTP/1.0 200"));
QVERIFY(response.endsWith("Third Route (POST)"));
response.clear();
}
void HttpHandlerSimpleRouterTest::testUnmatchedRequestAction()
{
HttpHandlerSimpleRouter handler;
QVERIFY(handler.unmatchedRequestAction() == HttpHandlerSimpleRouter::Passthrough);
handler.setUnmatchedRequestAction(HttpHandlerSimpleRouter::Return4xxResponse);
handler.addRoute("GET", "/a", 200, Pillow::HttpHeaderCollection(), "First Route (GET)");
handler.addRoute("DELETE", "/a", 200, Pillow::HttpHeaderCollection(), "First Route (DELETE)");
QVERIFY(handler.handleRequest(createGetRequest("/unmatched/route")));
QVERIFY(response.startsWith("HTTP/1.0 404"));
response.clear();
}
void HttpHandlerSimpleRouterTest::testMethodMismatchAction()
{
HttpHandlerSimpleRouter handler;
QVERIFY(handler.methodMismatchAction() == HttpHandlerSimpleRouter::Passthrough);
handler.setMethodMismatchAction(HttpHandlerSimpleRouter::Return4xxResponse);
handler.addRoute("GET", "/a", 200, Pillow::HttpHeaderCollection(), "First Route (GET)");
handler.addRoute("DELETE", "/a", 200, Pillow::HttpHeaderCollection(), "First Route (DELETE)");
QVERIFY(handler.handleRequest(createPostRequest("/a")));
QVERIFY(response.startsWith("HTTP/1.0 405"));
QVERIFY(response.contains("Allow: GET, DELETE"));
response.clear();
}
void HttpHandlerSimpleRouterTest::testSupportsMethodParam()
{
HttpHandlerSimpleRouter handler;
handler.addRoute("POST", "/a", 200, Pillow::HttpHeaderCollection(), "Route");
handler.addRoute("DELETE", "/b", 200, Pillow::HttpHeaderCollection(), "Route");
QVERIFY(handler.acceptsMethodParam() == false);
QVERIFY(!handler.handleRequest(createGetRequest("/a")));
QVERIFY(handler.handleRequest(createPostRequest("/a")));
QVERIFY(!handler.handleRequest(createGetRequest("/a?_method=post")));
QVERIFY(!handler.handleRequest(createGetRequest("/b?_method=delete")));
QVERIFY(!handler.handleRequest(createPostRequest("/b?_method=delete")));
handler.setAcceptsMethodParam(true);
QVERIFY(!handler.handleRequest(createGetRequest("/a")));
QVERIFY(handler.handleRequest(createPostRequest("/a")));
QVERIFY(handler.handleRequest(createGetRequest("/a?_method=POST")));
QVERIFY(handler.handleRequest(createGetRequest("/b?_method=DELETE")));
QVERIFY(handler.handleRequest(createPostRequest("/b?_method=DELETE")));
QVERIFY(handler.handleRequest(createGetRequest("/b?_method=delete")));
QVERIFY(handler.handleRequest(createPostRequest("/b?_method=delete")));
}
| 22,776 | 7,861 |
/****************************************************************************
** Meta object code from reading C++ file 'delete.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.15.2)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include <memory>
#include "../StudentManagementSystem/delete.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'delete.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.15.2. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_Delete_t {
QByteArrayData data[7];
char stringdata0[85];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_Delete_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_Delete_t qt_meta_stringdata_Delete = {
{
QT_MOC_LITERAL(0, 0, 6), // "Delete"
QT_MOC_LITERAL(1, 7, 25), // "on_listWidget_itemClicked"
QT_MOC_LITERAL(2, 33, 0), // ""
QT_MOC_LITERAL(3, 34, 16), // "QListWidgetItem*"
QT_MOC_LITERAL(4, 51, 4), // "item"
QT_MOC_LITERAL(5, 56, 23), // "on_lineEdit_textChanged"
QT_MOC_LITERAL(6, 80, 4) // "arg1"
},
"Delete\0on_listWidget_itemClicked\0\0"
"QListWidgetItem*\0item\0on_lineEdit_textChanged\0"
"arg1"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_Delete[] = {
// content:
8, // revision
0, // classname
0, 0, // classinfo
2, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 1, 24, 2, 0x08 /* Private */,
5, 1, 27, 2, 0x08 /* Private */,
// slots: parameters
QMetaType::Void, 0x80000000 | 3, 4,
QMetaType::Void, QMetaType::QString, 6,
0 // eod
};
void Delete::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
auto *_t = static_cast<Delete *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->on_listWidget_itemClicked((*reinterpret_cast< QListWidgetItem*(*)>(_a[1]))); break;
case 1: _t->on_lineEdit_textChanged((*reinterpret_cast< const QString(*)>(_a[1]))); break;
default: ;
}
}
}
QT_INIT_METAOBJECT const QMetaObject Delete::staticMetaObject = { {
QMetaObject::SuperData::link<QMainWindow::staticMetaObject>(),
qt_meta_stringdata_Delete.data,
qt_meta_data_Delete,
qt_static_metacall,
nullptr,
nullptr
} };
const QMetaObject *Delete::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *Delete::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_Delete.stringdata0))
return static_cast<void*>(this);
return QMainWindow::qt_metacast(_clname);
}
int Delete::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QMainWindow::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 2)
qt_static_metacall(this, _c, _id, _a);
_id -= 2;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 2)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 2;
}
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| 3,911 | 1,538 |
//
// Copyright Antony Polukhin, 2012-2014.
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/test/minimal.hpp>
#include <boost/type_index.hpp>
#include <boost/functional/hash.hpp>
#include <boost/lexical_cast.hpp>
#define BOOST_CHECK_EQUAL(x, y) BOOST_CHECK(x == y)
#define BOOST_CHECK_NE(x, y) BOOST_CHECK(x != y)
#define BOOST_CHECK_LE(x, y) BOOST_CHECK(x <= y)
#define BOOST_CHECK_GE(x, y) BOOST_CHECK(x >= y)
namespace my_namespace1 {
class my_class{};
}
namespace my_namespace2 {
class my_class{};
}
void names_matches_type_id()
{
using namespace boost::typeindex;
BOOST_CHECK_EQUAL(type_id<int>().pretty_name(), "int");
BOOST_CHECK_EQUAL(type_id<double>().pretty_name(), "double");
BOOST_CHECK_EQUAL(type_id<int>().name(), type_id<int>().name());
BOOST_CHECK_NE(type_id<int>().name(), type_id<double>().name());
BOOST_CHECK_NE(type_id<double>().name(), type_id<int>().name());
BOOST_CHECK_EQUAL(type_id<double>().name(), type_id<double>().name());
}
void default_construction()
{
using namespace boost::typeindex;
type_index ti1, ti2;
BOOST_CHECK_EQUAL(ti1, ti2);
BOOST_CHECK_EQUAL(type_id<void>(), ti1);
BOOST_CHECK_EQUAL(type_id<void>().name(), ti1.name());
BOOST_CHECK_NE(type_id<int>(), ti1);
}
void copy_construction()
{
using namespace boost::typeindex;
type_index ti1, ti2 = type_id<int>();
BOOST_CHECK_NE(ti1, ti2);
ti1 = ti2;
BOOST_CHECK_EQUAL(ti2, ti1);
const type_index ti3(ti1);
BOOST_CHECK_EQUAL(ti3, ti1);
}
void comparators_type_id()
{
using namespace boost::typeindex;
type_index t_int = type_id<int>();
type_index t_double = type_id<double>();
BOOST_CHECK_EQUAL(t_int, t_int);
BOOST_CHECK_LE(t_int, t_int);
BOOST_CHECK_GE(t_int, t_int);
BOOST_CHECK_NE(t_int, t_double);
BOOST_CHECK_LE(t_double, t_double);
BOOST_CHECK_GE(t_double, t_double);
BOOST_CHECK_NE(t_double, t_int);
BOOST_CHECK(t_double < t_int || t_int < t_double);
BOOST_CHECK(t_double > t_int || t_int > t_double);
}
void hash_code_type_id()
{
using namespace boost::typeindex;
std::size_t t_int1 = type_id<int>().hash_code();
std::size_t t_double1 = type_id<double>().hash_code();
std::size_t t_int2 = type_id<int>().hash_code();
std::size_t t_double2 = type_id<double>().hash_code();
BOOST_CHECK_EQUAL(t_int1, t_int2);
BOOST_CHECK_NE(t_int1, t_double2);
BOOST_CHECK_LE(t_double1, t_double2);
}
template <class T1, class T2>
static void test_with_modofiers() {
using namespace boost::typeindex;
type_index t1 = type_id_with_cvr<T1>();
type_index t2 = type_id_with_cvr<T2>();
BOOST_CHECK_NE(t2, t1);
BOOST_CHECK(t2 != t1.type_info());
BOOST_CHECK(t2.type_info() != t1);
BOOST_CHECK(t1 < t2 || t2 < t1);
BOOST_CHECK(t1 > t2 || t2 > t1);
BOOST_CHECK(t1.type_info() < t2 || t2.type_info() < t1);
BOOST_CHECK(t1.type_info() > t2 || t2.type_info() > t1);
BOOST_CHECK(t1 < t2.type_info() || t2 < t1.type_info());
BOOST_CHECK(t1 > t2.type_info() || t2 > t1.type_info());
// Chaecking that comparison operators overloads compile
BOOST_CHECK(t1 <= t2 || t2 <= t1);
BOOST_CHECK(t1 >= t2 || t2 >= t1);
BOOST_CHECK(t1.type_info() <= t2 || t2.type_info() <= t1);
BOOST_CHECK(t1.type_info() >= t2 || t2.type_info() >= t1);
BOOST_CHECK(t1 <= t2.type_info() || t2 <= t1.type_info());
BOOST_CHECK(t1 >= t2.type_info() || t2 >= t1.type_info());
BOOST_CHECK_EQUAL(t1, type_id_with_cvr<T1>());
BOOST_CHECK_EQUAL(t2, type_id_with_cvr<T2>());
BOOST_CHECK(t1 == type_id_with_cvr<T1>().type_info());
BOOST_CHECK(t2 == type_id_with_cvr<T2>().type_info());
BOOST_CHECK(t1.type_info() == type_id_with_cvr<T1>());
BOOST_CHECK(t2.type_info() == type_id_with_cvr<T2>());
BOOST_CHECK_EQUAL(t1.hash_code(), type_id_with_cvr<T1>().hash_code());
BOOST_CHECK_EQUAL(t2.hash_code(), type_id_with_cvr<T2>().hash_code());
BOOST_CHECK_NE(t1.hash_code(), type_id_with_cvr<T2>().hash_code());
BOOST_CHECK_NE(t2.hash_code(), type_id_with_cvr<T1>().hash_code());
}
void type_id_storing_modifiers()
{
test_with_modofiers<int, const int>();
test_with_modofiers<int, const int&>();
test_with_modofiers<int, int&>();
test_with_modofiers<int, volatile int>();
test_with_modofiers<int, volatile int&>();
test_with_modofiers<int, const volatile int>();
test_with_modofiers<int, const volatile int&>();
test_with_modofiers<const int, int>();
test_with_modofiers<const int, const int&>();
test_with_modofiers<const int, int&>();
test_with_modofiers<const int, volatile int>();
test_with_modofiers<const int, volatile int&>();
test_with_modofiers<const int, const volatile int>();
test_with_modofiers<const int, const volatile int&>();
test_with_modofiers<const int&, int>();
test_with_modofiers<const int&, const int>();
test_with_modofiers<const int&, int&>();
test_with_modofiers<const int&, volatile int>();
test_with_modofiers<const int&, volatile int&>();
test_with_modofiers<const int&, const volatile int>();
test_with_modofiers<const int&, const volatile int&>();
test_with_modofiers<int&, const int>();
test_with_modofiers<int&, const int&>();
test_with_modofiers<int&, int>();
test_with_modofiers<int&, volatile int>();
test_with_modofiers<int&, volatile int&>();
test_with_modofiers<int&, const volatile int>();
test_with_modofiers<int&, const volatile int&>();
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
test_with_modofiers<int&&, const int>();
test_with_modofiers<int&&, const int&>();
test_with_modofiers<int&&, const int&&>();
test_with_modofiers<int&&, int>();
test_with_modofiers<int&&, volatile int>();
test_with_modofiers<int&&, volatile int&>();
test_with_modofiers<int&&, volatile int&&>();
test_with_modofiers<int&&, const volatile int>();
test_with_modofiers<int&&, const volatile int&>();
test_with_modofiers<int&&, const volatile int&&>();
#endif
}
template <class T>
static void test_storing_nonstoring_modifiers_templ() {
using namespace boost::typeindex;
type_index t1 = type_id_with_cvr<T>();
type_index t2 = type_id<T>();
BOOST_CHECK_EQUAL(t2, t1);
BOOST_CHECK_EQUAL(t1, t2);
BOOST_CHECK(t1 <= t2);
BOOST_CHECK(t1 >= t2);
BOOST_CHECK(t2 <= t1);
BOOST_CHECK(t2 >= t1);
BOOST_CHECK_EQUAL(t2.pretty_name(), t1.pretty_name());
}
void type_id_storing_modifiers_vs_nonstoring()
{
test_storing_nonstoring_modifiers_templ<int>();
test_storing_nonstoring_modifiers_templ<my_namespace1::my_class>();
test_storing_nonstoring_modifiers_templ<my_namespace2::my_class>();
boost::typeindex::type_index t1 = boost::typeindex::type_id_with_cvr<const int>();
boost::typeindex::type_index t2 = boost::typeindex::type_id<int>();
BOOST_CHECK_NE(t2, t1);
BOOST_CHECK(t1.pretty_name() == "const int" || t1.pretty_name() == "int const");
}
void type_index_stream_operator_via_lexical_cast_testing()
{
using namespace boost::typeindex;
std::string s_int2 = boost::lexical_cast<std::string>(type_id<int>());
BOOST_CHECK_EQUAL(s_int2, "int");
std::string s_double2 = boost::lexical_cast<std::string>(type_id<double>());
BOOST_CHECK_EQUAL(s_double2, "double");
}
void type_index_stripping_cvr_test()
{
using namespace boost::typeindex;
BOOST_CHECK_EQUAL(type_id<int>(), type_id<const int>());
BOOST_CHECK_EQUAL(type_id<int>(), type_id<const volatile int>());
BOOST_CHECK_EQUAL(type_id<int>(), type_id<const volatile int&>());
BOOST_CHECK_EQUAL(type_id<int>(), type_id<int&>());
BOOST_CHECK_EQUAL(type_id<int>(), type_id<volatile int>());
BOOST_CHECK_EQUAL(type_id<int>(), type_id<volatile int&>());
BOOST_CHECK_EQUAL(type_id<double>(), type_id<const double>());
BOOST_CHECK_EQUAL(type_id<double>(), type_id<const volatile double>());
BOOST_CHECK_EQUAL(type_id<double>(), type_id<const volatile double&>());
BOOST_CHECK_EQUAL(type_id<double>(), type_id<double&>());
BOOST_CHECK_EQUAL(type_id<double>(), type_id<volatile double>());
BOOST_CHECK_EQUAL(type_id<double>(), type_id<volatile double&>());
}
void type_index_user_defined_class_test()
{
using namespace boost::typeindex;
BOOST_CHECK_EQUAL(type_id<my_namespace1::my_class>(), type_id<my_namespace1::my_class>());
BOOST_CHECK_EQUAL(type_id<my_namespace2::my_class>(), type_id<my_namespace2::my_class>());
#ifndef BOOST_NO_RTTI
BOOST_CHECK(type_id<my_namespace1::my_class>() == typeid(my_namespace1::my_class));
BOOST_CHECK(type_id<my_namespace2::my_class>() == typeid(my_namespace2::my_class));
BOOST_CHECK(typeid(my_namespace1::my_class) == type_id<my_namespace1::my_class>());
BOOST_CHECK(typeid(my_namespace2::my_class) == type_id<my_namespace2::my_class>());
#endif
BOOST_CHECK_NE(type_id<my_namespace1::my_class>(), type_id<my_namespace2::my_class>());
BOOST_CHECK_NE(
type_id<my_namespace1::my_class>().pretty_name().find("my_namespace1::my_class"),
std::string::npos);
}
struct A {
public:
BOOST_TYPE_INDEX_REGISTER_CLASS
virtual ~A(){}
};
struct B: public A {
BOOST_TYPE_INDEX_REGISTER_CLASS
};
struct C: public B {
BOOST_TYPE_INDEX_REGISTER_CLASS
};
void comparators_type_id_runtime()
{
C c1;
B b1;
A* pc1 = &c1;
A& rc1 = c1;
A* pb1 = &b1;
A& rb1 = b1;
#ifndef BOOST_NO_RTTI
BOOST_CHECK(typeid(rc1) == typeid(*pc1));
BOOST_CHECK(typeid(rb1) == typeid(*pb1));
BOOST_CHECK(typeid(rc1) != typeid(*pb1));
BOOST_CHECK(typeid(rb1) != typeid(*pc1));
BOOST_CHECK(typeid(&rc1) == typeid(pb1));
BOOST_CHECK(typeid(&rb1) == typeid(pc1));
#else
BOOST_CHECK(boost::typeindex::type_index(pc1->boost_type_index_type_id_runtime_()).raw_name());
#endif
BOOST_CHECK_EQUAL(boost::typeindex::type_id_runtime(rc1), boost::typeindex::type_id_runtime(*pc1));
BOOST_CHECK_EQUAL(boost::typeindex::type_id<C>(), boost::typeindex::type_id_runtime(*pc1));
BOOST_CHECK_EQUAL(boost::typeindex::type_id_runtime(rb1), boost::typeindex::type_id_runtime(*pb1));
BOOST_CHECK_EQUAL(boost::typeindex::type_id<B>(), boost::typeindex::type_id_runtime(*pb1));
BOOST_CHECK_NE(boost::typeindex::type_id_runtime(rc1), boost::typeindex::type_id_runtime(*pb1));
BOOST_CHECK_NE(boost::typeindex::type_id_runtime(rb1), boost::typeindex::type_id_runtime(*pc1));
#ifndef BOOST_NO_RTTI
BOOST_CHECK_EQUAL(boost::typeindex::type_id_runtime(&rc1), boost::typeindex::type_id_runtime(pb1));
BOOST_CHECK_EQUAL(boost::typeindex::type_id_runtime(&rb1), boost::typeindex::type_id_runtime(pc1));
BOOST_CHECK(boost::typeindex::type_id_runtime(rc1) == typeid(*pc1));
BOOST_CHECK(boost::typeindex::type_id_runtime(rb1) == typeid(*pb1));
BOOST_CHECK(boost::typeindex::type_id_runtime(rc1) != typeid(*pb1));
BOOST_CHECK(boost::typeindex::type_id_runtime(rb1) != typeid(*pc1));
BOOST_CHECK(boost::typeindex::type_id_runtime(&rc1) == typeid(pb1));
BOOST_CHECK(boost::typeindex::type_id_runtime(&rb1) == typeid(pc1));
#endif
}
#ifndef BOOST_NO_RTTI
void comparators_type_id_vs_type_info()
{
using namespace boost::typeindex;
type_index t_int = type_id<int>();
BOOST_CHECK(t_int == typeid(int));
BOOST_CHECK(typeid(int) == t_int);
BOOST_CHECK(t_int <= typeid(int));
BOOST_CHECK(typeid(int) <= t_int);
BOOST_CHECK(t_int >= typeid(int));
BOOST_CHECK(typeid(int) >= t_int);
type_index t_double = type_id<double>();
BOOST_CHECK(t_double == typeid(double));
BOOST_CHECK(typeid(double) == t_double);
BOOST_CHECK(t_double <= typeid(double));
BOOST_CHECK(typeid(double) <= t_double);
BOOST_CHECK(t_double >= typeid(double));
BOOST_CHECK(typeid(double) >= t_double);
if (t_double < t_int) {
BOOST_CHECK(t_double < typeid(int));
BOOST_CHECK(typeid(double) < t_int);
BOOST_CHECK(typeid(int) > t_double);
BOOST_CHECK(t_int > typeid(double));
BOOST_CHECK(t_double <= typeid(int));
BOOST_CHECK(typeid(double) <= t_int);
BOOST_CHECK(typeid(int) >= t_double);
BOOST_CHECK(t_int >= typeid(double));
} else {
BOOST_CHECK(t_double > typeid(int));
BOOST_CHECK(typeid(double) > t_int);
BOOST_CHECK(typeid(int) < t_double);
BOOST_CHECK(t_int < typeid(double));
BOOST_CHECK(t_double >= typeid(int));
BOOST_CHECK(typeid(double) >= t_int);
BOOST_CHECK(typeid(int) <= t_double);
BOOST_CHECK(t_int <= typeid(double));
}
}
#endif // BOOST_NO_RTTI
int test_main(int , char* []) {
names_matches_type_id();
default_construction();
copy_construction();
comparators_type_id();
hash_code_type_id();
type_id_storing_modifiers();
type_id_storing_modifiers_vs_nonstoring();
type_index_stream_operator_via_lexical_cast_testing();
type_index_stripping_cvr_test();
type_index_user_defined_class_test();
comparators_type_id_runtime();
#ifndef BOOST_NO_RTTI
comparators_type_id_vs_type_info();
#endif
return 0;
}
| 13,758 | 5,743 |
#include "libtg.hpp"
#define clip(X) min(X,10000)
using namespace std;
static vector<Vertex>* formula;
// position of u in a reverse toposort
static vector<int> posdp;
static int pos(int u) {
static int next = 1;
int& ans = posdp[u];
if (ans) return ans;
for (int v : (*formula)[u].down) pos(v);
return ans = next++;
}
// p(phi(u))
static vector<int> p;
static int p_(int u) {
int& ans = p[u];
if (ans) return ans;
switch ((*formula)[u].type) {
case CONJ:
ans = 0;
for (int v : (*formula)[u].down) ans = clip(ans+p_(v));
break;
case DISJ:
ans = 1;
for (int v : (*formula)[u].down) ans = clip(ans*p_(v));
break;
default:
ans = 1;
break;
}
return ans;
}
// Boy de la Tour's top-down renaming
static void R_rec(int u, int a) {
auto& phi = (*formula)[u];
if (p[u] == 1) return;
// check renaming condition
bool renamed = false;
if (a >= 2 && (a != 2 || p[u] != 2)) { // ap > a+p
a = 1;
renamed = true;
}
// search children
if (phi.type == CONJ) {
for (int v : phi.down) R_rec(v,a);
p[u] = 0; for (int v : phi.down) p[u] = clip(p[u]+p[v]);
}
else { // phi.type == DISJ
int n = phi.down.size();
vector<int> dp(n,1); // dp[i] = prod(phi_j.p), i < j < n
for (int i = n-2; 0 <= i; i--) dp[i] = clip(p[phi.down[i+1]]*dp[i+1]);
int ai = a; // ai = a*prod(phi_j.p), 0 <= j < i
for (int i = 0; i < n; i++) {
R_rec(phi.down[i],clip(ai*dp[i]));
ai = clip(ai*p[phi.down[i]]);
}
p[u] = 1; for (int v : phi.down) p[u] = clip(p[u]*p[v]);
}
if (renamed) {
R.push_back(u);
p[u] = 1;
}
}
void boydelatour() {
formula = (is_tree ? &T : &G);
// dp tables
posdp = vector<int>(formula->size(),0);
p = vector<int>(formula->size(),0);
// necessary preprocessing for Boy de la Tour's algorithm
// compute p field and reverse toposort edges
auto toposortless = [](int u, int v) { return pos(u) < pos(v); };
for (int u = 0; u < formula->size(); u++) {
auto& phi = (*formula)[u];
sort(phi.down.begin(),phi.down.end(),toposortless);
p[u] = p_(u);
}
R_rec(0,1); // recursive algorithm
}
| 2,190 | 959 |
/**
* Copyright 2021 Huawei Technologies 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.
*/
#include "backend/optimizer/graph_kernel/eliminate_redundant_complex.h"
#include <algorithm>
#include <vector>
#include <string>
#include <utility>
#include "frontend/optimizer/irpass.h"
#include "backend/session/anf_runtime_algorithm.h"
#include "backend/kernel_compiler/common_utils.h"
#include "debug/anf_ir_dump.h"
namespace mindspore {
namespace opt {
namespace {
bool EliminateRedudantComplexInGraphkernel(const FuncGraphPtr &func_graph) {
auto mng = func_graph->manager();
MS_EXCEPTION_IF_NULL(mng);
auto todos = TopoSort(func_graph->get_return());
bool changed = false;
for (const auto &node : todos) {
auto cnode = node->cast<CNodePtr>();
// Find all Complex node in graphkernel sub_graph
if (cnode != nullptr && IsPrimitiveCNode(cnode, std::make_shared<Primitive>("Complex"))) {
auto original_users = mng->node_users()[cnode];
for (const auto &getitem_iter : original_users) {
auto getitem = getitem_iter.first;
auto getitem_cnode = getitem->cast<CNodePtr>();
// Find all complex users which are CReal or CImag, then use Complex inputs replace them.
if (IsPrimitiveCNode(getitem_cnode, std::make_shared<Primitive>("CReal"))) {
mng->Replace(getitem, cnode->inputs()[1]);
changed = true;
} else if (IsPrimitiveCNode(getitem_cnode, std::make_shared<Primitive>("CImag"))) {
mng->Replace(getitem, cnode->inputs()[2]);
changed = true;
}
}
}
}
return changed;
}
} // namespace
bool EliminateRedundantComplex::Run(const FuncGraphPtr &func_graph) {
auto mng = func_graph->manager();
MS_EXCEPTION_IF_NULL(mng);
bool changed = false;
auto todos = TopoSort(func_graph->get_return());
std::reverse(todos.begin(), todos.end());
for (const auto &node : todos) {
auto cnode = node->cast<CNodePtr>();
// Check whether graph_kernel node
if (cnode != nullptr && AnfAlgo::IsGraphKernel(cnode)) {
auto graph_kernel_fg = AnfAlgo::GetCNodeFuncGraphPtr(cnode);
MS_EXCEPTION_IF_NULL(graph_kernel_fg);
changed = EliminateRedudantComplexInGraphkernel(graph_kernel_fg) || changed;
}
}
return changed;
}
} // namespace opt
} // namespace mindspore
| 2,831 | 929 |
#include "HardClip.hpp"
#include <cmath>
namespace brettstory {
namespace audio {
namespace clipping {
double HardClip::ClipSample(double sample, double threshold) {
return (0.5 * (abs(sample + threshold) - abs(sample - threshold))) / threshold;
}
}
}
} | 270 | 99 |
#include <iostream>
#include <algorithm>
#include <iterator>
#include <deque>
#include <tuple>
#include <string>
#include <fstream>
using namespace std;
using dict_entry = pair<string, string>;
namespace std {
ostream& operator<<(ostream &os, const dict_entry p)
{
return os << p.first << " " << p.second;
}
istream& operator>>(istream &is, dict_entry &p)
{
return is >> p.first >> p.second;
}
}
template <typename IS>
deque<dict_entry> from_instream(IS &&is)
{
deque<dict_entry> d {istream_iterator<dict_entry>{is}, {}};
sort(begin(d), end(d));
return d;
}
int main()
{
ifstream file_in {"dict.txt"};
const auto dict1 (from_instream(ifstream{"dict.txt"}));
const auto dict2 (from_instream(cin));
merge(begin(dict1), end(dict1),
begin(dict2), end(dict2),
ostream_iterator<dict_entry>{cout, "\n"});
} | 863 | 314 |
void atm::getting_pin() {
incoming.wait()
.handle<digit_pressed>([&](digit_pressed const& msg) {
unsigned const pin_length = 4;
pin += msg.digit;
if (pin.length() == pin_length) {
bank.send(verify_pin(account, pin, incoming));
state = &atm::verifying_pin;
}
})
.handle<clear_last_pressed>([&](clear_last_pressed const& msg) {
if (!pin.empty()) {
pin.resize(pin.length() - 1);
}
})
.handle<cancel_pressed>(
[&](cancel_pressed const& msg) { state = &atm::done_processing; });
}
| 596 | 193 |
// Copyright(c) 2019, NVIDIA CORPORATION. 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.
//
#pragma once
#include <glm/glm.hpp>
#include <vulkan/vulkan.hpp>
namespace vk
{
namespace su
{
class CameraManipulator
{
public:
enum class Action { None, Orbit, Dolly, Pan, LookAround };
enum class Mode { Examine, Fly, Walk, Trackball };
enum class MouseButton { None, Left, Middle, Right };
enum class ModifierFlagBits { Shift = 1, Ctrl = 2, Alt = 4 };
using ModifierFlags = vk::Flags<ModifierFlagBits, uint32_t, ModifierFlagBits::Shift>;
public:
CameraManipulator();
glm::vec3 const& getCameraPosition() const;
glm::vec3 const& getCenterPosition() const;
glm::mat4 const& getMatrix() const;
Mode getMode() const;
glm::ivec2 const& getMousePosition() const;
float getRoll() const;
float getSpeed() const;
glm::vec3 const& getUpVector() const;
glm::u32vec2 const& getWindowSize() const;
Action mouseMove(glm::ivec2 const& position, MouseButton mouseButton, ModifierFlags & modifiers);
void setLookat(const glm::vec3& cameraPosition, const glm::vec3& centerPosition, const glm::vec3& upVector);
void setMode(Mode mode);
void setMousePosition(glm::ivec2 const& position);
void setRoll(float roll); // roll in radians
void setSpeed(float speed);
void setWindowSize(glm::ivec2 const& size);
void wheel(int value);
private:
void dolly(glm::vec2 const& delta);
void motion(glm::ivec2 const& position, Action action = Action::None);
void orbit(glm::vec2 const& delta, bool invert = false);
void pan(glm::vec2 const& delta);
double projectOntoTBSphere(const glm::vec2& p);
void trackball(glm::ivec2 const& position);
void update();
private:
glm::vec3 m_cameraPosition = glm::vec3(10, 10, 10);
glm::vec3 m_centerPosition = glm::vec3(0, 0, 0);
glm::vec3 m_upVector = glm::vec3(0, 1, 0);
float m_roll = 0; // Rotation around the Z axis in RAD
glm::mat4 m_matrix = glm::mat4(1);
glm::u32vec2 m_windowSize = glm::u32vec2(1, 1);
float m_speed = 30.0f;
glm::ivec2 m_mousePosition = glm::ivec2(0, 0);
Mode m_mode = Mode::Examine;
};
} // namespace su
} // namespace vk
| 3,032 | 980 |
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* vim: set ts=8 sts=4 et sw=4 tw=99:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "jit/InstructionReordering.h"
#include "jit/MIRGraph.h"
using namespace js;
using namespace js::jit;
static void
MoveBefore(MBasicBlock* block, MInstruction* at, MInstruction* ins)
{
if (at == ins)
return;
// Update instruction numbers.
for (MInstructionIterator iter(block->begin(at)); *iter != ins; iter++) {
MOZ_ASSERT(iter->id() < ins->id());
iter->setId(iter->id() + 1);
}
ins->setId(at->id() - 1);
block->moveBefore(at, ins);
}
static bool
IsLastUse(MDefinition* ins, MDefinition* input, MBasicBlock* loopHeader)
{
// If we are in a loop, this cannot be the last use of any definitions from
// outside the loop, as those definitions can be used in future iterations.
if (loopHeader && input->block()->id() < loopHeader->id())
return false;
for (MUseDefIterator iter(input); iter; iter++) {
// Watch for uses defined in blocks which ReorderInstructions hasn't
// processed yet. These nodes have not had their ids set yet.
if (iter.def()->block()->id() > ins->block()->id())
return false;
if (iter.def()->id() > ins->id())
return false;
}
return true;
}
bool
jit::ReorderInstructions(MIRGenerator* mir, MIRGraph& graph)
{
// Renumber all instructions in the graph as we go.
size_t nextId = 0;
// List of the headers of any loops we are in.
Vector<MBasicBlock*, 4, SystemAllocPolicy> loopHeaders;
for (ReversePostorderIterator block(graph.rpoBegin()); block != graph.rpoEnd(); block++) {
// Don't reorder instructions within entry blocks, which have special requirements.
if (*block == graph.entryBlock() || *block == graph.osrBlock())
continue;
if (block->isLoopHeader()) {
if (!loopHeaders.append(*block))
return false;
}
MBasicBlock* innerLoop = loopHeaders.empty() ? nullptr : loopHeaders.back();
for (MPhiIterator iter(block->phisBegin()); iter != block->phisEnd(); iter++)
iter->setId(nextId++);
for (MInstructionIterator iter(block->begin()); iter != block->end(); iter++)
iter->setId(nextId++);
for (MInstructionIterator iter(block->begin()); iter != block->end(); ) {
MInstruction* ins = *iter;
// Filter out some instructions which are never reordered.
if (ins->isEffectful() ||
!ins->isMovable() ||
ins->resumePoint() ||
ins == block->lastIns())
{
iter++;
continue;
}
// Move constants with a single use in the current block to the
// start of the block. Constants won't be reordered by the logic
// below, as they have no inputs. Moving them up as high as
// possible can allow their use to be moved up further, though,
// and has no cost if the constant is emitted at its use.
if (ins->isConstant() &&
ins->hasOneUse() &&
ins->usesBegin()->consumer()->block() == *block &&
!IsFloatingPointType(ins->type()))
{
iter++;
MInstructionIterator targetIter = block->begin();
while (targetIter->isConstant() || targetIter->isInterruptCheck()) {
if (*targetIter == ins)
break;
targetIter++;
}
MoveBefore(*block, *targetIter, ins);
continue;
}
// Look for inputs where this instruction is the last use of that
// input. If we move this instruction up, the input's lifetime will
// be shortened, modulo resume point uses (which don't need to be
// stored in a register, and can be handled by the register
// allocator by just spilling at some point with no reload).
Vector<MDefinition*, 4, SystemAllocPolicy> lastUsedInputs;
for (size_t i = 0; i < ins->numOperands(); i++) {
MDefinition* input = ins->getOperand(i);
if (!input->isConstant() && IsLastUse(ins, input, innerLoop)) {
if (!lastUsedInputs.append(input))
return false;
}
}
// Don't try to move instructions which aren't the last use of any
// of their inputs (we really ought to move these down instead).
if (lastUsedInputs.length() < 2) {
iter++;
continue;
}
MInstruction* target = ins;
for (MInstructionReverseIterator riter = ++block->rbegin(ins); riter != block->rend(); riter++) {
MInstruction* prev = *riter;
if (prev->isInterruptCheck())
break;
// The instruction can't be moved before any of its uses.
bool isUse = false;
for (size_t i = 0; i < ins->numOperands(); i++) {
if (ins->getOperand(i) == prev) {
isUse = true;
break;
}
}
if (isUse)
break;
// The instruction can't be moved before an instruction that
// stores to a location read by the instruction.
if (prev->isEffectful() &&
(ins->getAliasSet().flags() & prev->getAliasSet().flags()) &&
ins->mightAlias(prev))
{
break;
}
// Make sure the instruction will still be the last use of one
// of its inputs when moved up this far.
for (size_t i = 0; i < lastUsedInputs.length(); ) {
bool found = false;
for (size_t j = 0; j < prev->numOperands(); j++) {
if (prev->getOperand(j) == lastUsedInputs[i]) {
found = true;
break;
}
}
if (found) {
lastUsedInputs[i] = lastUsedInputs.back();
lastUsedInputs.popBack();
} else {
i++;
}
}
if (lastUsedInputs.length() < 2)
break;
// We can move the instruction before this one.
target = prev;
}
iter++;
MoveBefore(*block, target, ins);
}
if (block->isLoopBackedge())
loopHeaders.popBack();
}
return true;
}
| 7,126 | 1,891 |
#include <pybind11/pybind11.h>
#include <pybind11/operators.h>
#include "box2d_wrapper.hpp"
namespace py = pybind11;
b2Vec2 operator+ (const b2Vec2 & lhs, const py::tuple & rhs)
{
return b2Vec2(
lhs.x + rhs[0].cast<float>() ,
lhs.y + rhs[1].cast<float>()
);
}
b2Vec2 operator+ (const py::tuple & lhs, const b2Vec2 & rhs)
{
return b2Vec2(
lhs[0].cast<float>() + rhs.x ,
lhs[1].cast<float>() + rhs.y
);
}
// b2Vec2 operator+ (const b2Vec2 & lhs, const b2Vec2 & rhs)
// {
// return b2Vec2(
// lhs.x + rhs.x ,
// lhs.y + rhs.y
// );
// }
#ifndef PYB2D_LIQUID_FUN
b2Vec2 operator/ (const b2Vec2 & lhs, float rhs)
{
return b2Vec2(
lhs.x / rhs ,
lhs.y / rhs
);
}
b2Vec2 operator* (const b2Vec2 & lhs, float rhs)
{
return b2Vec2(
lhs.x * rhs ,
lhs.y * rhs
);
}
#endif
void exportB2Math(py::module & pyb2dModule){
pyb2dModule.def("b2IsValid",&b2IsValid, py::arg("x"));
//pyb2dModule.def("b2InvSqrt",&b2InvSqrt, py::arg("x"));
pyb2dModule.def("b2Sqrt",&sqrtf, py::arg("x"));
pyb2dModule.def("b2Atan2",&atan2f, py::arg("x"),py::arg("y"));
py::class_<b2Vec2>(pyb2dModule,"Vec2")
.def(py::init([](py::tuple t) {
if(py::len(t) != 2)
{
throw std::runtime_error("tuple has wrong length");
}
return new b2Vec2(t[0].cast<float>(), t[1].cast<float>()); }
))
.def(py::init([](py::list t) {
if(py::len(t) != 2)
{
throw std::runtime_error("list has wrong length");
}
return new b2Vec2(t[0].cast<float>(), t[1].cast<float>()); }
))
.def(py::init<>())
.def(py::init<b2Vec2>())
.def(py::init<float,float>(),py::arg("x"),py::arg("y"))
.def_readwrite("x", &b2Vec2::x)
.def_readwrite("y", &b2Vec2::y)
// member functions
.def("set_zero",&b2Vec2::SetZero)
.def("Set",&b2Vec2::Set,py::arg("x"),py::arg("y"))
//.def("Length",&b2Vec2::Length)
.def("normalize",&b2Vec2::Normalize)
.def("is_valid",&b2Vec2::IsValid)
.def("skew",&b2Vec2::Skew)
.def("__len__",[](const b2Vec2 & vec){return 2;})
// operators
// .def(py::self += py::self)
// .def(py::self -= py::self)
// .def(py::self *= float())
// .def(py::self + float())
// .def(py::self - float())
.def(float() * py::self)
.def(py::self * float())
.def(py::self / float())
.def(py::self + py::self)
.def(py::self - py::self)
// .def(py::self + py::tuple())
// .def(py::tuple() + py::self)
.def_property_readonly("length",[](const b2Vec2 & self){
return std::sqrt(self.x * self.x + self.y * self.y);
})
.def_property_readonly("length_squared",&b2Vec2::LengthSquared)
;
py::implicitly_convertible<py::tuple, b2Vec2>();
py::implicitly_convertible<py::list, b2Vec2>();
py::class_<b2Vec3>(pyb2dModule,"Vec3")
.def(py::init<>())
.def(py::init<float,float,float>(),py::arg("x"),py::arg("y"),py::arg("z"))
.def_readwrite("x", &b2Vec3::x)
.def_readwrite("y", &b2Vec3::y)
.def_readwrite("z", &b2Vec3::z)
// member functions
.def("set_zero",&b2Vec3::SetZero)
.def("set",&b2Vec3::Set,py::arg("x"),py::arg("y"),py::arg("z"))
//.def("normalize",&b2Vec3::Normalize)
// operators
.def(py::self += py::self)
.def(py::self -= py::self)
.def(py::self *= float())
//.def_property_readonly("length",&b2Vec3::Length)
// .def_property_readonly("length_squared",&b2Vec3::LengthSquared)
;
// py::class_<b2Vec4>(pyb2dModule,"b2Vec4")
// .def(py::init<>())
// .def(py::init<float,float,float,float>(),py::arg("x"),py::arg("y"),py::arg("z"),py::arg("w"))
// .def_readwrite("x", &b2Vec4::x)
// .def_readwrite("y", &b2Vec4::y)
// .def_readwrite("z", &b2Vec4::z)
// .def_readwrite("z", &b2Vec4::w)
// //.def_property_readonly("length",&b2Vec4::Length)
// //.def_property_readonly("length_squared",&b2Vec4::LengthSquared)
// ;
py::class_<b2Mat22>(pyb2dModule,"Mat22")
.def(py::init<>())
.def(py::init<const b2Vec2 &,const b2Vec2 &>(),py::arg("c1"),py::arg("c2"))
.def(py::init<float,float,float,float>(),py::arg("a11"),py::arg("a12"),py::arg("a21"),py::arg("a22"))
.def_readwrite("ex", &b2Mat22::ex)
.def_readwrite("ey", &b2Mat22::ey)
// member functions
.def("set",&b2Mat22::Set,py::arg("c1"),py::arg("c2"))
.def("set_identity",&b2Mat22::SetIdentity)
.def("set_zero",&b2Mat22::SetZero)
.def("get_inverse",&b2Mat22::GetInverse)
.def("solve",&b2Mat22::Solve,py::arg("b"))
// operators
;
py::class_<b2Mat33>(pyb2dModule,"Mat33")
.def(py::init<>())
.def(py::init<const b2Vec3 &,const b2Vec3 &,const b2Vec3 &>(),py::arg("c1"),py::arg("c2"),py::arg("c3"))
.def_readwrite("ex", &b2Mat33::ex)
.def_readwrite("ey", &b2Mat33::ey)
.def_readwrite("ez", &b2Mat33::ez)
// member functions
.def("set_zero",&b2Mat33::SetZero)
.def("solve_33",&b2Mat33::Solve33,py::arg("b"))
.def("solve_22",&b2Mat33::Solve22,py::arg("b"))
.def("get_inverse_22",&b2Mat33::GetInverse22,py::arg("M"))
.def("get_sym_inverse_33",&b2Mat33::GetSymInverse33,py::arg("M"))
// operators
//
;
py::class_<b2Rot>(pyb2dModule,"Rot")
.def(py::init<>())
.def(py::init<float>(),py::arg("angle"))
.def_readwrite("s", &b2Rot::s)
.def_readwrite("c", &b2Rot::c)
// member functions
.def("set",&b2Rot::Set,py::arg("angle"))
.def("set_identity",&b2Rot::SetIdentity)
.def("get_angle",&b2Rot::GetAngle)
.def("get_x_axis",&b2Rot::GetXAxis)
.def("get_y_axis",&b2Rot::GetYAxis)
// operators
//
;
py::class_<b2Transform>(pyb2dModule,"Transform")
.def(py::init<>())
.def(py::init<const b2Vec2 &, const b2Rot & >(),py::arg("position"),py::arg("rotation"))
.def_readwrite("p", &b2Transform::p)
.def_readwrite("position", &b2Transform::p)
.def_readwrite("q", &b2Transform::q)
// member functions
.def("set",&b2Transform::Set,py::arg("position"),py::arg("angle"))
.def("set_identity",&b2Transform::SetIdentity)
// .def("GetPositionX",&b2Transform::GetPositionX)
// .def("GetPositionY",&b2Transform::GetPositionY)
//.def("GetRotationCos",&b2Transform::GetRotationCos)
// operators
//
;
py::class_<b2Sweep>(pyb2dModule,"Sweep")
.def(py::init<>())
.def_readwrite("local_center", &b2Sweep::localCenter)
.def_readwrite("c0", &b2Sweep::c0)
.def_readwrite("c", &b2Sweep::c)
.def_readwrite("a0", &b2Sweep::a0)
.def_readwrite("a", &b2Sweep::a)
.def_readwrite("alpha0", &b2Sweep::alpha0)
// member functions
.def("Advance",&b2Sweep::Advance,py::arg("alpha"))
.def("Normalize",&b2Sweep::Normalize)
// operators
//
;
pyb2dModule.def("dot", [](const b2Vec2& a, const b2Vec2& b){
return b2Dot(a,b);
},py::arg("a"),py::arg("b"));
pyb2dModule.def("dot", [](const b2Vec3& a, const b2Vec3& b){
return b2Dot(a,b);
},py::arg("a"),py::arg("b"));
pyb2dModule.def("cross", [](const b2Vec2& a, const b2Vec2& b){
return b2Cross(a,b);
},py::arg("a"),py::arg("b"));
pyb2dModule.def("cross", [](const b2Vec3& a, const b2Vec3& b){
return b2Cross(a,b);
},py::arg("a"),py::arg("b"));
pyb2dModule.def("cross", [](const b2Vec2& a, float b){
return b2Cross(a,b);
},py::arg("a"),py::arg("b"));
pyb2dModule.def("cross", [](float a, const b2Vec2& b){
return b2Cross(a,b);
},py::arg("a"),py::arg("b"));
pyb2dModule.def("mulT", [](const b2Mat22 & A, const b2Vec2& v){
return b2MulT(A,v);
},py::arg("A"),py::arg("v"));
pyb2dModule.def("mulT", [](const b2Rot & q, const b2Vec2& v){
return b2MulT(q,v);
},py::arg("q"),py::arg("v"));
pyb2dModule.def("distance", [](const b2Vec2& a, const b2Vec2& b){
return b2Distance(a,b);
},py::arg("a"),py::arg("b"));
pyb2dModule.def("distance_squared", [](const b2Vec2& a, const b2Vec2& b){
return b2DistanceSquared(a,b);
},py::arg("a"),py::arg("b"));
pyb2dModule.def("mul", [](const b2Mat22 & A, const b2Mat22& B){
return b2Mul(A,B);
},py::arg("A"),py::arg("B"));
pyb2dModule.def("mul", [](const b2Mat33 & A, const b2Vec3& v){
return b2Mul(A,v);
},py::arg("A"),py::arg("v"));
pyb2dModule.def("mul", [](const b2Rot & q, const b2Rot& r){
return b2Mul(q,r);
},py::arg("q"),py::arg("r"));
pyb2dModule.def("mul", [](const b2Rot & q, const b2Vec2& v){
return b2Mul(q,v);
},py::arg("q"),py::arg("v"));
pyb2dModule.def("mul", [](const b2Transform & T, const b2Vec2& v){
return b2Mul(T,v);
},py::arg("T"),py::arg("v"));
}
| 9,288 | 3,836 |
// Copyright (C) 2011-2020 Roki. Distributed under the MIT License
#ifndef INCLUDED_SROOK_MPL_TYPETRAITS_CLOCK_HPP
#define INCLUDED_SROOK_MPL_TYPETRAITS_CLOCK_HPP
#ifdef _MSC_VER
# if _MSC_VER > 1000
# pragma once
# endif
#endif
#include <srook/type_traits/clock/is_clock.hpp>
#include <srook/type_traits/clock/is_trivial_clock.hpp>
#endif
| 354 | 176 |
/*
Slackback!
*/
#include "RJModules.hpp"
#include "common.hpp"
#include "Chorus.h"
#include <iostream>
#include <cmath>
#include <sstream>
#include <iomanip>
#include <unistd.h>
#include <mutex>
using namespace std;
#define HISTORY_SIZE (1<<21)
struct RJChorusRoundSmallBlackKnob : RoundSmallBlackKnob
{
RJChorusRoundSmallBlackKnob()
{
setSvg(APP->window->loadSvg(asset::plugin(pluginInstance, "res/KTFRoundSmallBlackKnob.svg")));
}
};
struct RJChorus : Module {
enum ParamIds {
DELAY_PARAM,
FREQ_PARAM,
DEPTH_PARAM,
NUM_PARAMS
};
enum InputIds {
IN_INPUT,
DELAY_CV,
FREQ_CV,
DEPTH_CV,
NUM_INPUTS
};
enum OutputIds {
OUT_OUTPUT,
NUM_OUTPUTS
};
enum LightIds {
NUM_LIGHTS
};
int lastDelay = 50;
stk::Chorus chorus;
RJChorus() {
config(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS);
configParam(RJChorus::DELAY_PARAM, 1, 6000, 50, "Delay Time ms");
configParam(RJChorus::FREQ_PARAM, 0.0, 25.0, 2.0, "Frequency");
configParam(RJChorus::DEPTH_PARAM, 0.00001, 0.99999, 0.99999, "Depth");
chorus = stk::Chorus(50);
}
void process(const ProcessArgs &args) override {
float input = inputs[IN_INPUT].value;
int delay = params[DELAY_PARAM].value * clamp(inputs[DELAY_CV].getNormalVoltage(1.0f) / 1.0f, 0.0f, 1.0f);
if(delay != lastDelay){
chorus = stk::Chorus(delay);
lastDelay = delay;
}
chorus.setModFrequency( params[FREQ_PARAM].value * clamp(inputs[FREQ_CV].getNormalVoltage(1.0f) / 1.0f, 0.0f, 1.0f) );
chorus.setModDepth( params[DEPTH_PARAM].value * clamp(inputs[DEPTH_CV].getNormalVoltage(1.0f) / 1.0f, 0.0f, 1.0f) );
float processed = chorus.tick( input );
outputs[OUT_OUTPUT].value = processed;
}
};
struct RJChorusWidget : ModuleWidget {
RJChorusWidget(RJChorus *module) {
setModule(module);
setPanel(APP->window->loadSvg(asset::plugin(pluginInstance, "res/Chorus.svg")));
int ONE = -4;
addParam(createParam<RJChorusRoundSmallBlackKnob>(mm2px(Vec(3.5, 38.9593 + ONE)), module, RJChorus::DELAY_PARAM));
addInput(createInput<PJ301MPort>(mm2px(Vec(3.51398, 48.74977 + ONE)), module, RJChorus::DELAY_CV));
addParam(createParam<RJChorusRoundSmallBlackKnob>(mm2px(Vec(3.51398, 62.3 + ONE)), module, RJChorus::FREQ_PARAM));
addInput(createInput<PJ301MPort>(mm2px(Vec(3.51398, 73.3 + ONE)), module, RJChorus::FREQ_CV));
int TWO = 45;
addParam(createParam<RJChorusRoundSmallBlackKnob>(mm2px(Vec(3.5, 38.9593 + TWO)), module, RJChorus::DEPTH_PARAM));
addInput(createInput<PJ301MPort>(mm2px(Vec(3.51398, 48.74977 + TWO)), module, RJChorus::DEPTH_CV));
addInput(createInput<PJ301MPort>(mm2px(Vec(3.51398, 62.3 + TWO)), module, RJChorus::IN_INPUT));
addOutput(createOutput<PJ301MPort>(mm2px(Vec(3.51398, 73.3 + TWO)), module, RJChorus::OUT_OUTPUT));
}
};
Model *modelRJChorus = createModel<RJChorus, RJChorusWidget>("RJChorus");
| 3,135 | 1,374 |
/*
Copyright (c) 2017-2019,
Battelle Memorial Institute; Lawrence Livermore National Security, LLC; Alliance for Sustainable Energy, LLC. See the top-level NOTICE for
additional details. All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
*/
#include "../core/core-exceptions.hpp"
#include "../helics.hpp"
#include "gmlc/concurrency/TripWire.hpp"
#include "helics.h"
#include "internal/api_objects.h"
#include <iostream>
#include <map>
#include <mutex>
#include <vector>
/** this is a random identifier put in place when the federate or core or broker gets created*/
static const int fedValidationIdentifier = 0x2352188;
static const char *invalidFedString = "federate object is not valid";
static const std::string nullstr;
static constexpr char nullcstr[] = "";
namespace helics
{
FedObject *getFedObject (helics_federate fed, helics_error *err) noexcept
{
HELICS_ERROR_CHECK (err, nullptr);
if (fed == nullptr)
{
if (err != nullptr)
{
err->error_code = helics_error_invalid_object;
err->message = invalidFedString;
}
return nullptr;
}
auto fedObj = reinterpret_cast<helics::FedObject *> (fed);
if (fedObj->valid == fedValidationIdentifier)
{
return fedObj;
}
if (err != nullptr)
{
err->error_code = helics_error_invalid_object;
err->message = invalidFedString;
}
return nullptr;
}
} // namespace helics
helics::Federate *getFed (helics_federate fed, helics_error *err)
{
auto fedObj = helics::getFedObject (fed, err);
return (fedObj == nullptr) ? nullptr : fedObj->fedptr.get ();
}
static const char *notValueFedString = "Federate must be a value federate";
helics::ValueFederate *getValueFed (helics_federate fed, helics_error *err)
{
auto fedObj = helics::getFedObject (fed, err);
if (fedObj == nullptr)
{
return nullptr;
}
if ((fedObj->type == helics::vtype::value_fed) || (fedObj->type == helics::vtype::combination_fed))
{
auto rval = dynamic_cast<helics::ValueFederate *> (fedObj->fedptr.get ());
if (rval != nullptr)
{
return rval;
}
}
if (err != nullptr)
{
err->error_code = helics_error_invalid_object;
err->message = notValueFedString;
}
return nullptr;
}
static const char *notMessageFedString = "Federate must be a message federate";
helics::MessageFederate *getMessageFed (helics_federate fed, helics_error *err)
{
auto fedObj = helics::getFedObject (fed, err);
if (fedObj == nullptr)
{
return nullptr;
}
if ((fedObj->type == helics::vtype::message_fed) || (fedObj->type == helics::vtype::combination_fed))
{
auto rval = dynamic_cast<helics::MessageFederate *> (fedObj->fedptr.get ());
if (rval != nullptr)
{
return rval;
}
}
if (err != nullptr)
{
err->error_code = helics_error_invalid_object;
err->message = notMessageFedString;
}
return nullptr;
}
std::shared_ptr<helics::Federate> getFedSharedPtr (helics_federate fed, helics_error *err)
{
auto fedObj = helics::getFedObject (fed, err);
if (fedObj == nullptr)
{
return nullptr;
}
return fedObj->fedptr;
}
std::shared_ptr<helics::ValueFederate> getValueFedSharedPtr (helics_federate fed, helics_error *err)
{
auto fedObj = helics::getFedObject (fed, err);
if (fedObj == nullptr)
{
return nullptr;
}
if ((fedObj->type == helics::vtype::value_fed) || (fedObj->type == helics::vtype::combination_fed))
{
auto rval = std::dynamic_pointer_cast<helics::ValueFederate> (fedObj->fedptr);
if (rval)
{
return rval;
}
}
if (err != nullptr)
{
err->error_code = helics_error_invalid_object;
err->message = notValueFedString;
}
return nullptr;
}
std::shared_ptr<helics::MessageFederate> getMessageFedSharedPtr (helics_federate fed, helics_error *err)
{
auto fedObj = helics::getFedObject (fed, err);
if (fedObj == nullptr)
{
return nullptr;
}
if ((fedObj->type == helics::vtype::message_fed) || (fedObj->type == helics::vtype::combination_fed))
{
auto rval = std::dynamic_pointer_cast<helics::MessageFederate> (fedObj->fedptr);
if (rval)
{
return rval;
}
}
if (err != nullptr)
{
err->error_code = helics_error_invalid_object;
err->message = notMessageFedString;
}
return nullptr;
}
/* Creation and destruction of Federates */
helics_federate helicsCreateValueFederate (const char *fedName, helics_federate_info fi, helics_error *err)
{
HELICS_ERROR_CHECK (err, nullptr);
auto FedI = std::make_unique<helics::FedObject> ();
try
{
if (fi == nullptr)
{
FedI->fedptr = std::make_shared<helics::ValueFederate> (AS_STRING (fedName), helics::FederateInfo ());
}
else
{
FedI->fedptr = std::make_shared<helics::ValueFederate> (AS_STRING (fedName), *reinterpret_cast<helics::FederateInfo *> (fi));
}
}
catch (...)
{
helicsErrorHandler (err);
return nullptr;
}
FedI->type = helics::vtype::value_fed;
FedI->valid = fedValidationIdentifier;
auto fed = reinterpret_cast<helics_federate> (FedI.get ());
getMasterHolder ()->addFed (std::move (FedI));
return (fed);
}
helics_federate helicsCreateValueFederateFromConfig (const char *configFile, helics_error *err)
{
HELICS_ERROR_CHECK (err, nullptr);
auto FedI = std::make_unique<helics::FedObject> ();
try
{
FedI->fedptr = std::make_shared<helics::ValueFederate> (AS_STRING (configFile));
}
catch (...)
{
helicsErrorHandler (err);
return nullptr;
}
FedI->type = helics::vtype::value_fed;
FedI->valid = fedValidationIdentifier;
auto fed = reinterpret_cast<helics_federate> (FedI.get ());
getMasterHolder ()->addFed (std::move (FedI));
return (fed);
}
/* Creation and destruction of Federates */
helics_federate helicsCreateMessageFederate (const char *fedName, helics_federate_info fi, helics_error *err)
{
HELICS_ERROR_CHECK (err, nullptr);
auto FedI = std::make_unique<helics::FedObject> ();
try
{
if (fi == nullptr)
{
FedI->fedptr = std::make_shared<helics::MessageFederate> (AS_STRING (fedName), helics::FederateInfo ());
}
else
{
FedI->fedptr = std::make_shared<helics::MessageFederate> (AS_STRING (fedName), *reinterpret_cast<helics::FederateInfo *> (fi));
}
}
catch (...)
{
helicsErrorHandler (err);
return nullptr;
}
FedI->type = helics::vtype::message_fed;
FedI->valid = fedValidationIdentifier;
auto fed = reinterpret_cast<helics_federate> (FedI.get ());
getMasterHolder ()->addFed (std::move (FedI));
return (fed);
}
helics_federate helicsCreateMessageFederateFromConfig (const char *configFile, helics_error *err)
{
HELICS_ERROR_CHECK (err, nullptr);
auto FedI = std::make_unique<helics::FedObject> ();
try
{
FedI->fedptr = std::make_shared<helics::MessageFederate> (AS_STRING (configFile));
}
catch (...)
{
helicsErrorHandler (err);
return nullptr;
}
FedI->type = helics::vtype::message_fed;
FedI->valid = fedValidationIdentifier;
auto fed = reinterpret_cast<helics_federate> (FedI.get ());
getMasterHolder ()->addFed (std::move (FedI));
return (fed);
}
/* Creation and destruction of Federates */
helics_federate helicsCreateCombinationFederate (const char *fedName, helics_federate_info fi, helics_error *err)
{
HELICS_ERROR_CHECK (err, nullptr);
auto FedI = std::make_unique<helics::FedObject> ();
try
{
if (fi == nullptr)
{
FedI->fedptr = std::make_shared<helics::CombinationFederate> (AS_STRING (fedName), helics::FederateInfo ());
}
else
{
FedI->fedptr =
std::make_shared<helics::CombinationFederate> (AS_STRING (fedName), *reinterpret_cast<helics::FederateInfo *> (fi));
}
}
catch (...)
{
helicsErrorHandler (err);
return nullptr;
}
FedI->type = helics::vtype::combination_fed;
FedI->valid = fedValidationIdentifier;
auto fed = reinterpret_cast<helics_federate> (FedI.get ());
getMasterHolder ()->addFed (std::move (FedI));
return (fed);
}
helics_federate helicsCreateCombinationFederateFromConfig (const char *configFile, helics_error *err)
{
HELICS_ERROR_CHECK (err, nullptr);
auto FedI = std::make_unique<helics::FedObject> ();
try
{
FedI->fedptr = std::make_shared<helics::CombinationFederate> (AS_STRING (configFile));
}
catch (...)
{
helicsErrorHandler (err);
return nullptr;
}
FedI->type = helics::vtype::combination_fed;
FedI->valid = fedValidationIdentifier;
auto fed = reinterpret_cast<helics_federate> (FedI.get ());
getMasterHolder ()->addFed (std::move (FedI));
return (fed);
}
helics_federate helicsFederateClone (helics_federate fed, helics_error *err)
{
auto *fedObj = helics::getFedObject (fed, err);
if (fedObj == nullptr)
{
return nullptr;
}
auto fedClone = std::make_unique<helics::FedObject> ();
fedClone->fedptr = fedObj->fedptr;
fedClone->type = fedObj->type;
fedClone->valid = fedObj->valid;
auto fedB = reinterpret_cast<helics_federate> (fedClone.get ());
getMasterHolder ()->addFed (std::move (fedClone));
return (fedB);
}
helics_bool helicsFederateIsValid (helics_federate fed)
{
auto fedObj = getFed (fed, nullptr);
return (fedObj == nullptr) ? helics_false : helics_true;
}
helics_core helicsFederateGetCoreObject (helics_federate fed, helics_error *err)
{
auto fedObj = getFed (fed, err);
if (fedObj == nullptr)
{
return nullptr;
}
auto core = std::make_unique<helics::CoreObject> ();
core->valid = coreValidationIdentifier;
core->coreptr = fedObj->getCorePointer ();
auto retcore = reinterpret_cast<helics_core> (core.get ());
getMasterHolder ()->addCore (std::move (core));
return retcore;
}
static constexpr char invalidFile[] = "Invalid File specification";
void helicsFederateRegisterInterfaces (helics_federate fed, const char *file, helics_error *err)
{
auto fedObj = getFed (fed, err);
if (fedObj == nullptr)
{
return;
}
if (file == nullptr)
{
if (err != nullptr)
{
err->error_code = helics_error_invalid_argument;
err->message = invalidFile;
}
return;
}
try
{
fedObj->registerInterfaces (file);
}
catch (...)
{
return helicsErrorHandler (err);
}
}
void helicsFederateFinalize (helics_federate fed, helics_error *err)
{
auto fedObj = getFed (fed, err);
if (fedObj == nullptr)
{
return;
}
try
{
fedObj->finalize ();
}
catch (...)
{
helicsErrorHandler (err);
}
}
void helicsFederateFinalizeAsync (helics_federate fed, helics_error *err)
{
auto fedObj = getFed (fed, err);
if (fedObj == nullptr)
{
return;
}
try
{
fedObj->finalizeAsync ();
}
catch (...)
{
helicsErrorHandler (err);
}
}
void helicsFederateFinalizeComplete (helics_federate fed, helics_error *err)
{
auto fedObj = getFed (fed, err);
if (fedObj == nullptr)
{
return;
}
try
{
fedObj->finalizeComplete ();
}
catch (...)
{
helicsErrorHandler (err);
}
}
/* initialization, execution, and time requests */
void helicsFederateEnterInitializingMode (helics_federate fed, helics_error *err)
{
auto fedObj = getFed (fed, err);
if (fedObj == nullptr)
{
return;
}
try
{
fedObj->enterInitializingMode ();
}
catch (...)
{
return helicsErrorHandler (err);
}
}
void helicsFederateEnterInitializingModeAsync (helics_federate fed, helics_error *err)
{
auto fedObj = getFed (fed, err);
if (fedObj == nullptr)
{
return;
}
try
{
fedObj->enterInitializingModeAsync ();
}
catch (...)
{
return helicsErrorHandler (err);
}
}
helics_bool helicsFederateIsAsyncOperationCompleted (helics_federate fed, helics_error *err)
{
auto fedObj = getFed (fed, err);
if (fedObj == nullptr)
{
return helics_false;
}
return (fedObj->isAsyncOperationCompleted ()) ? helics_true : helics_false;
}
void helicsFederateEnterInitializingModeComplete (helics_federate fed, helics_error *err)
{
auto fedObj = getFed (fed, err);
if (fedObj == nullptr)
{
return;
}
try
{
fedObj->enterInitializingModeComplete ();
}
catch (...)
{
return helicsErrorHandler (err);
}
}
void helicsFederateEnterExecutingMode (helics_federate fed, helics_error *err)
{
auto fedObj = getFed (fed, err);
if (fedObj == nullptr)
{
return;
}
try
{
// printf("current state=%d\n", static_cast<int>(fedObj->getCurrentState()));
fedObj->enterExecutingMode ();
}
catch (...)
{
return helicsErrorHandler (err);
}
}
static helics::iteration_request getIterationRequest (helics_iteration_request iterate)
{
switch (iterate)
{
case helics_iteration_request_no_iteration:
default:
return helics::iteration_request::no_iterations;
case helics_iteration_request_force_iteration:
return helics::iteration_request::force_iteration;
case helics_iteration_request_iterate_if_needed:
return helics::iteration_request::iterate_if_needed;
}
}
static helics_iteration_result getIterationStatus (helics::iteration_result iterationState)
{
switch (iterationState)
{
case helics::iteration_result::next_step:
return helics_iteration_result_next_step;
case helics::iteration_result::iterating:
return helics_iteration_result_iterating;
case helics::iteration_result::error:
default:
return helics_iteration_result_error;
case helics::iteration_result::halted:
return helics_iteration_result_halted;
}
}
helics_iteration_result helicsFederateEnterExecutingModeIterative (helics_federate fed, helics_iteration_request iterate, helics_error *err)
{
auto fedObj = getFed (fed, err);
if (fedObj == nullptr)
{
return helics_iteration_result_error;
}
try
{
auto val = fedObj->enterExecutingMode (getIterationRequest (iterate));
return getIterationStatus (val);
}
catch (...)
{
helicsErrorHandler (err);
return helics_iteration_result_error;
}
}
void helicsFederateEnterExecutingModeAsync (helics_federate fed, helics_error *err)
{
auto fedObj = getFed (fed, err);
if (fedObj == nullptr)
{
return;
}
try
{
fedObj->enterExecutingModeAsync ();
}
catch (...)
{
helicsErrorHandler (err);
}
}
void helicsFederateEnterExecutingModeIterativeAsync (helics_federate fed, helics_iteration_request iterate, helics_error *err)
{
auto fedObj = getFed (fed, err);
if (fedObj == nullptr)
{
return;
}
try
{
fedObj->enterExecutingModeAsync (getIterationRequest (iterate));
}
catch (...)
{
return helicsErrorHandler (err);
}
}
void helicsFederateEnterExecutingModeComplete (helics_federate fed, helics_error *err)
{
auto fedObj = getFed (fed, err);
if (fedObj == nullptr)
{
return;
}
try
{
fedObj->enterExecutingModeComplete ();
}
catch (...)
{
return helicsErrorHandler (err);
}
}
helics_iteration_result helicsFederateEnterExecutingModeIterativeComplete (helics_federate fed, helics_error *err)
{
auto fedObj = getFed (fed, err);
if (fedObj == nullptr)
{
return helics_iteration_result_error;
}
try
{
auto val = fedObj->enterExecutingModeComplete ();
return getIterationStatus (val);
}
catch (...)
{
helicsErrorHandler (err);
return helics_iteration_result_error;
}
}
helics_time helicsFederateRequestTime (helics_federate fed, helics_time requestTime, helics_error *err)
{
auto fedObj = getFed (fed, err);
if (fedObj == nullptr)
{
return helics_time_invalid;
}
try
{
auto timeret = fedObj->requestTime (requestTime);
return (timeret < helics::Time::maxVal ()) ? static_cast<double> (timeret) : helics_time_maxtime;
}
catch (...)
{
helicsErrorHandler (err);
return helics_time_invalid;
}
}
helics_time helicsFederateRequestTimeAdvance (helics_federate fed, helics_time timeDelta, helics_error *err)
{
auto fedObj = getFed (fed, err);
if (fedObj == nullptr)
{
return helics_time_invalid;
}
try
{
auto timeret = fedObj->requestTimeAdvance (timeDelta);
return (timeret < helics::Time::maxVal ()) ? static_cast<double> (timeret) : helics_time_maxtime;
}
catch (...)
{
helicsErrorHandler (err);
return helics_time_invalid;
}
}
helics_time helicsFederateRequestNextStep (helics_federate fed, helics_error *err)
{
auto fedObj = getFed (fed, err);
if (fedObj == nullptr)
{
return helics_time_invalid;
}
try
{
auto timeret = fedObj->requestNextStep ();
return (timeret < helics::Time::maxVal ()) ? static_cast<double> (timeret) : helics_time_maxtime;
}
catch (...)
{
helicsErrorHandler (err);
return helics_time_invalid;
}
}
helics_time helicsFederateRequestTimeIterative (helics_federate fed,
helics_time requestTime,
helics_iteration_request iterate,
helics_iteration_result *outIterate,
helics_error *err)
{
auto fedObj = getFed (fed, err);
if (fedObj == nullptr)
{
if (outIterate != nullptr)
{
*outIterate = helics_iteration_result_error;
}
return helics_time_invalid;
}
try
{
auto val = fedObj->requestTimeIterative (requestTime, getIterationRequest (iterate));
if (outIterate != nullptr)
{
*outIterate = getIterationStatus (val.state);
}
return (val.grantedTime < helics::Time::maxVal ()) ? static_cast<double> (val.grantedTime) : helics_time_maxtime;
}
catch (...)
{
helicsErrorHandler (err);
if (outIterate != nullptr)
{
*outIterate = helics_iteration_result_error;
}
return helics_time_invalid;
}
}
void helicsFederateRequestTimeAsync (helics_federate fed, helics_time requestTime, helics_error *err)
{
auto fedObj = getFed (fed, err);
if (fedObj == nullptr)
{
return;
}
try
{
fedObj->requestTimeAsync (requestTime);
}
catch (...)
{
return helicsErrorHandler (err);
}
}
helics_time helicsFederateRequestTimeComplete (helics_federate fed, helics_error *err)
{
auto fedObj = getFed (fed, err);
if (fedObj == nullptr)
{
return helics_time_invalid;
}
try
{
auto timeret = fedObj->requestTimeComplete ();
return (timeret < helics::Time::maxVal ()) ? static_cast<double> (timeret) : helics_time_maxtime;
}
catch (...)
{
helicsErrorHandler (err);
return helics_time_invalid;
}
}
void helicsFederateRequestTimeIterativeAsync (helics_federate fed,
helics_time requestTime,
helics_iteration_request iterate,
helics_error *err)
{
auto fedObj = getFed (fed, err);
if (fedObj == nullptr)
{
return;
}
try
{
fedObj->requestTimeIterative (requestTime, getIterationRequest (iterate));
}
catch (...)
{
return helicsErrorHandler (err);
}
}
helics_time helicsFederateRequestTimeIterativeComplete (helics_federate fed, helics_iteration_result *outIteration, helics_error *err)
{
auto fedObj = getFed (fed, err);
if (fedObj == nullptr)
{
return helics_time_invalid;
}
try
{
auto val = fedObj->requestTimeIterativeComplete ();
if (outIteration != nullptr)
{
*outIteration = getIterationStatus (val.state);
}
return (val.grantedTime < helics::Time::maxVal ()) ? static_cast<double> (val.grantedTime) : helics_time_maxtime;
}
catch (...)
{
helicsErrorHandler (err);
return helics_time_invalid;
}
}
static const std::map<helics::Federate::modes, helics_federate_state> modeEnumConversions{
{helics::Federate::modes::error, helics_federate_state::helics_state_error},
{helics::Federate::modes::startup, helics_federate_state::helics_state_startup},
{helics::Federate::modes::executing, helics_federate_state::helics_state_execution},
{helics::Federate::modes::finalize, helics_federate_state::helics_state_finalize},
{helics::Federate::modes::pending_exec, helics_federate_state::helics_state_pending_exec},
{helics::Federate::modes::pending_init, helics_federate_state::helics_state_pending_init},
{helics::Federate::modes::pending_iterative_time, helics_federate_state::helics_state_pending_iterative_time},
{helics::Federate::modes::pending_time, helics_federate_state::helics_state_pending_time},
{helics::Federate::modes::initializing, helics_federate_state::helics_state_initialization},
{helics::Federate::modes::pending_finalize, helics_federate_state::helics_state_pending_finalize}};
helics_federate_state helicsFederateGetState (helics_federate fed, helics_error *err)
{
auto fedObj = getFed (fed, err);
if (fedObj == nullptr)
{
return helics_state_error;
}
try
{
auto FedMode = fedObj->getCurrentMode ();
return modeEnumConversions.at (FedMode);
}
catch (...)
{
helicsErrorHandler (err);
return helics_state_error;
}
}
const char *helicsFederateGetName (helics_federate fed)
{
auto fedObj = getFed (fed, nullptr);
if (fedObj == nullptr)
{
return nullcstr;
}
auto &ident = fedObj->getName ();
return ident.c_str ();
}
void helicsFederateSetTimeProperty (helics_federate fed, int timeProperty, helics_time time, helics_error *err)
{
auto fedObj = getFed (fed, err);
if (fedObj == nullptr)
{
return;
}
try
{
fedObj->setProperty (timeProperty, time);
}
catch (...)
{
return helicsErrorHandler (err);
}
}
void helicsFederateSetFlagOption (helics_federate fed, int flag, helics_bool flagValue, helics_error *err)
{
auto fedObj = getFed (fed, err);
if (fedObj == nullptr)
{
return;
}
try
{
fedObj->setFlagOption (flag, (flagValue != helics_false));
}
catch (...)
{
return helicsErrorHandler (err);
}
}
void helicsFederateSetIntegerProperty (helics_federate fed, int intProperty, int propVal, helics_error *err)
{
auto fedObj = getFed (fed, err);
if (fedObj == nullptr)
{
return;
}
try
{
fedObj->setProperty (intProperty, propVal);
}
catch (...)
{
return helicsErrorHandler (err);
}
}
helics_time helicsFederateGetTimeProperty (helics_federate fed, int timeProperty, helics_error *err)
{
auto fedObj = getFed (fed, err);
if (fedObj == nullptr)
{
return helics_time_invalid;
}
try
{
auto T = fedObj->getTimeProperty (timeProperty);
return (T < helics::Time::maxVal ()) ? static_cast<double> (T) : helics_time_maxtime;
}
catch (...)
{
helicsErrorHandler (err);
return helics_time_invalid;
}
}
helics_bool helicsFederateGetFlagOption (helics_federate fed, int flag, helics_error *err)
{
auto fedObj = getFed (fed, err);
if (fedObj == nullptr)
{
return helics_false;
}
try
{
bool res = fedObj->getFlagOption (flag);
return (res) ? helics_true : helics_false;
}
catch (...)
{
helicsErrorHandler (err);
return helics_false;
}
}
int helicsFederateGetIntegerProperty (helics_federate fed, int intProperty, helics_error *err)
{
auto fedObj = getFed (fed, err);
if (fedObj == nullptr)
{
return -101;
}
try
{
return fedObj->getIntegerProperty (intProperty);
}
catch (...)
{
helicsErrorHandler (err);
return -101;
}
}
void helicsFederateSetSeparator (helics_federate fed, char separator, helics_error *err)
{
auto fedObj = getFed (fed, err);
if (fedObj == nullptr)
{
return;
}
try
{
fedObj->setSeparator (separator);
}
catch (...)
{
helicsErrorHandler (err);
}
}
helics_time helicsFederateGetCurrentTime (helics_federate fed, helics_error *err)
{
auto fedObj = getFed (fed, err);
if (fedObj == nullptr)
{
return helics_time_invalid;
}
try
{
auto T = fedObj->getCurrentTime ();
return (T < helics::Time::maxVal ()) ? static_cast<double> (T) : helics_time_maxtime;
}
catch (...)
{
helicsErrorHandler (err);
return helics_time_invalid;
}
}
static constexpr char invalidGlobalString[] = "Global name cannot be null";
void helicsFederateSetGlobal (helics_federate fed, const char *valueName, const char *value, helics_error *err)
{
auto fedObj = getFed (fed, err);
if (fedObj == nullptr)
{
return;
}
if (valueName == nullptr)
{
if (err != nullptr)
{
err->error_code = helics_error_invalid_argument;
err->message = invalidGlobalString;
}
return;
}
fedObj->setGlobal (valueName, AS_STRING (value));
}
static constexpr char invalidFederateCore[] = "Federate core is not connected";
void helicsFederateSetLogFile (helics_federate fed, const char *logFile, helics_error *err)
{
auto fedObj = getFed (fed, err);
if (fedObj == nullptr)
{
return;
}
auto cr = fedObj->getCorePointer ();
try
{
if (cr)
{
cr->setLogFile (AS_STRING (logFile));
}
else
{
if (err != nullptr)
{
err->error_code = helics_error_invalid_function_call;
err->message = invalidFederateCore;
}
return;
}
}
catch (...)
{
helicsErrorHandler (err);
}
}
void helicsFederateLogErrorMessage (helics_federate fed, const char *logmessage, helics_error *err)
{
helicsFederateLogLevelMessage (fed, helics_log_level_error, logmessage, err);
}
void helicsFederateLogWarningMessage (helics_federate fed, const char *logmessage, helics_error *err)
{
helicsFederateLogLevelMessage (fed, helics_log_level_warning, logmessage, err);
}
void helicsFederateLogInfoMessage (helics_federate fed, const char *logmessage, helics_error *err)
{
helicsFederateLogLevelMessage (fed, helics_log_level_summary, logmessage, err);
}
void helicsFederateLogDebugMessage (helics_federate fed, const char *logmessage, helics_error *err)
{
helicsFederateLogLevelMessage (fed, helics_log_level_data, logmessage, err);
}
void helicsFederateLogLevelMessage (helics_federate fed, int loglevel, const char *logmessage, helics_error *err)
{
auto fedObj = getFed (fed, err);
if (fedObj == nullptr)
{
return;
}
fedObj->logMessage (loglevel, AS_STRING (logmessage));
}
| 28,193 | 9,664 |
#include "yacx/main.hpp"
#include <algorithm>
#include <array>
#include <cstdio>
#include <ctime>
#include <functional>
#include <iostream>
#include <iterator>
#include <random>
#include <string>
using yacx::Source, yacx::KernelArg, yacx::Kernel, yacx::Options, yacx::Device,
yacx::load, yacx::KernelTime, yacx::Devices;
void compare(float *lhs, float *rhs, int width) {
int errors = 0;
for (int i{0}; i < width; i += 1) {
//printf("[%d] expected %f : actually %f\n", i, lhs[i], rhs[i]);
if ((lhs[i] - rhs[i]) != 0) {
errors += 1;
}
}
if (errors > 0)
printf("\u001b[31m%d errors occured, out of %d values.\u001b[0m\n", errors,
width);
else
printf("\u001b[32mno errors occured.\u001b[0m\n");
}
std::function<bool(const float &, const float &)> comparator =
[](const float &left, const float &right) {
// double epsilon{1.0E-8};
double epsilon{1};
return (abs(left - right) < epsilon);
};
template <class Iter>
void fill(Iter start, Iter end, int min = 0, int max = 100) {
static std::random_device rd;
static std::mt19937 mte(rd());
std::uniform_int_distribution<int> dist(min, max);
std::generate(start, end, [&]() { return dist(mte); });
}
void MatrixMulSeq(const float *M, const float *N, float *P, size_t width) {
size_t Col, Row, k;
for (Col = 0; Col < width; ++Col)
for (Row = 0; Row < width; ++Row) {
float sum = 0;
for (k = 0; k < width; k += 1) {
sum += M[Row * width + k] * N[k * width + Col];
}
P[Row * width + Col] = sum;
}
}
int main() {
std::clock_t start;
bool equalMultiply1, equalMultiply1unfolded, equalMultiply2,
equalMultiplyNaive;
const size_t WIDTH{1024};
const size_t BLOCK_SIZE{16};
const size_t GRANULARITY{4};
const size_t matrix_size{WIDTH * WIDTH * sizeof(float)};
static_assert(WIDTH % BLOCK_SIZE == 0);
static_assert(BLOCK_SIZE % GRANULARITY == 0);
// problem with WIDTH > 500
// std::array<float, WIDTH * WIDTH> M, N, P_cuda, P_seq;
float *M = new float[WIDTH * WIDTH];
float *N = new float[WIDTH * WIDTH];
float *P_seq = new float[WIDTH * WIDTH];
float *P_cuda = new float[WIDTH * WIDTH];
KernelTime time;
// Fill arrays with random values
// fill(N.begin(), N.end());
// fill(M.begin(), M.end());
fill(M, M + (WIDTH * WIDTH));
fill(N, N + (WIDTH * WIDTH));
try {
// Select Device
Device dev = Devices::findDevice();
std::cout << "===================================\n";
std::cout << "Selected " << dev.name() << " with "
<< (dev.total_memory() / 1024) / 1024 << "mb VRAM\n";
std::cout << "Kernel Arguments total size: "
<< ((matrix_size * 3 + sizeof(size_t)) / 1024) << "kb\n\n";
std::cout << "Theoretical Bandwith: "
<< yacx::theoretical_bandwidth(dev) << " GB/s\n";
// Set kernel string and compile options
Source source{load("examples/kernels/matrixMult.cu")};
Options options;
options.insert("--std", "c++14");
options.insert("--device-debug");
options.insertOptions(yacx::options::GpuArchitecture{dev});
// Set arguments
std::vector<KernelArg> args;
// args.emplace_back(KernelArg{M.data(), matrix_size});
// args.emplace_back(KernelArg{N.data(), matrix_size});
// args.emplace_back(KernelArg{P_cuda.data(), matrix_size, true, false});
args.emplace_back(KernelArg{M, matrix_size});
args.emplace_back(KernelArg{N, matrix_size});
args.emplace_back(KernelArg{P_cuda, matrix_size, true, false});
args.emplace_back(KernelArg{const_cast<size_t *>(&WIDTH)});
// Compile Kernels
dim3 grid(WIDTH, WIDTH);
dim3 block(1, 1);
Kernel kernelNaive = source.program("MatrixMultyNaive")
.compile(options)
.configure(grid, block);
block.x = BLOCK_SIZE;
block.y = BLOCK_SIZE / GRANULARITY;
grid.x = WIDTH / block.x;
grid.y = WIDTH / GRANULARITY / block.y;
// std::cout << "get_global_size(0): " << block.x * grid.x << std::endl;
// std::cout << "get_global_size(1): " << block.y * grid.y << std::endl;
// std::cout << "get_local_size(0): " << block.x << std::endl;
// std::cout << "get_local_size(1): " << block.y << std::endl;
Kernel kernel1 = source.program("MatrixMulty1")
.instantiate(BLOCK_SIZE, GRANULARITY)
.compile(options)
.configure(grid, block);
block.x = BLOCK_SIZE;
block.y = BLOCK_SIZE / 4;
grid.x = WIDTH / block.x;
grid.y = WIDTH / 4 / block.y;
Kernel kernel1_1 = source.program("MatrixMulty1unfolded")
.instantiate(BLOCK_SIZE)
.compile(options)
.configure(grid, block);
block.x = BLOCK_SIZE;
block.y = BLOCK_SIZE;
grid.x = WIDTH / BLOCK_SIZE;
grid.y = WIDTH / BLOCK_SIZE;
Kernel kernel2 = source.program("MatrixMulty2")
.instantiate(BLOCK_SIZE)
.compile(options)
.configure(grid, block);
// Launch kernels
// CPU single threaded matrix multiplication
start = std::clock();
// MatrixMulSeq(M.data(), N.data(), P_seq.data(), WIDTH);
MatrixMulSeq(M, N, P_seq, WIDTH);
std::cout << "Time" << yacx::gColorBrightYellow << "[CPU single threaded]"
<< yacx::gColorReset << ": "
<< (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000)
<< " ms" << std::endl;
time = kernelNaive.launch(args, dev);
std::cout << "Time" << yacx::gColorBrightYellow << "[MatrixMultyNaive]"
<< yacx::gColorReset << ": " << time.total << " ms\n";
std::cout << "Effective Bandwith: "
<< time.effective_bandwidth_launch() << " GB/s\n";
equalMultiplyNaive =
std::equal(P_cuda, P_cuda + (WIDTH * WIDTH), P_seq, comparator);
if (!equalMultiplyNaive)
compare(P_seq, P_cuda, WIDTH * WIDTH);
if (BLOCK_SIZE % 4 == 0) {
time = kernel1_1.launch(args, dev);
std::cout << "Time" << yacx::gColorBrightYellow
<< "[MatrixMulty1unfolded]" << yacx::gColorReset << ": "
<< time.total << " ms\n";
std::cout << "Effective Bandwith: "
<< time.effective_bandwidth_launch() << " GB/s\n";
equalMultiply1unfolded =
std::equal(P_cuda, P_cuda + (WIDTH * WIDTH), P_seq, comparator);
if (!equalMultiply1unfolded)
compare(P_seq, P_cuda, WIDTH * WIDTH);
} else {
equalMultiply1unfolded = true;
}
time = kernel1.launch(args, dev);
std::cout << "Time" << yacx::gColorBrightYellow << "[MatrixMulty1]"
<< yacx::gColorReset << ": " << time.total << " ms\n";
std::cout << "Effective Bandwith: "
<< time.effective_bandwidth_launch() << " GB/s\n";
equalMultiply1 =
std::equal(P_cuda, P_cuda + (WIDTH * WIDTH), P_seq, comparator);
if (!equalMultiply1)
compare(P_seq, P_cuda, WIDTH * WIDTH);
time = kernel2.launch(args, dev);
std::cout << "Time" << yacx::gColorBrightYellow << "[MatrixMulty2]"
<< yacx::gColorReset << ": " << time.total << " ms\n";
std::cout << "Effective Bandwith: "
<< time.effective_bandwidth_launch() << " GB/s\n\n";
equalMultiply2 =
std::equal(P_cuda, P_cuda + (WIDTH * WIDTH), P_seq, comparator);
if (!equalMultiply2)
compare(P_seq, P_cuda, WIDTH * WIDTH);
} catch (const std::exception &e) {
std::cerr << e.what() << std::endl;
exit(1);
}
if (equalMultiplyNaive && equalMultiply1 && equalMultiply1unfolded &&
equalMultiply2) {
std::cout << yacx::gColorBrightGreen
<< "Everything was correctly calculated!" << yacx::gColorReset;
} else {
std::cout << yacx::gColorBrightRed;
}
if (!equalMultiplyNaive) {
std::cout << "Naive went wrong ;_;\n";
}
if (!equalMultiply1) {
std::cout << "Multy1 went wrong ;_;\n";
}
if (!equalMultiply1unfolded) {
std::cout << "Multy1unfolded went wrong ;_;\n";
}
if (!equalMultiply2) {
std::cout << "Multy2 went wrong ;_;\n";
}
std::cout << yacx::gColorReset
<< "===================================" << std::endl;
// Free resources
delete[] M;
delete[] N;
delete[] P_seq;
delete[] P_cuda;
return 0;
}
| 8,489 | 3,139 |
#include "ofApp.h"
//https://commons.wikimedia.org/wiki/File:Beer_in_glass_close_up.jpg
// This is the most basic pdsp example
// we set up everything and check that everything is working
// before running this also check that the basic oF audio output example is working
// ofxx_folder/examples/sound/audioOutputExample/
// for documentation of the modules and functions:
// http://npisanti.com/ofxPDSP/md__modules.html
/* roate
ofPushMatrix();
ofTranslate(leafImg.width/2, leafImg.height/2, 0);//move pivot to centre
ofRotate(ofGetFrameNum() * .01, 0, 0, 1);//rotate from centre
ofPushMatrix();
ofTranslate(-leafImg.width/2,-leafImg.height/2,0);//move back by the centre offset
leafImg.draw(0,0);
ofPopMatrix();
ofPopMatrix();
https://www.vidsplay.com/
*/
int AudioPlayer::number = 0;
void AudioPlayer::patch() {
addModuleOutput("0", fader0);
addModuleOutput("1", fader1);
pitchControl >> sampler0.in_pitch();
pitchControl >> sampler1.in_pitch();
sampleTrig >> sampler0 >> amp0;
envGate >> env >> amp0.in_mod();
sampleTrig >> sampler1 >> amp1;
env >> amp1.in_mod();
sampler0 >> amp0 >> fader0;
sampler1 >> amp1 >> fader1;
faderControl >> dBtoLin >> fader0.in_mod();
dBtoLin >> fader1.in_mod();
sampler0.addSample(&sample, 0);
sampler1.addSample(&sample, 1);
smoothControl >> env.in_attack();
smoothControl >> env.in_release();
ui.setName("pdsp player " + ofToString(++number));
ui.add(faderControl.set("volume", 0, -48, 24));
ui.add(loadButton.set("load", false));
ui.add(sampleName.set("sample", "no sample"));
ui.add(samplePath.set("path", "no path"));
ui.add(pitchControl.set("pitch", 0, -24, 24));
ui.add(smoothControl.set("fade ms", 0, 0, 50));
ui.add(bPlay.set("play", false));
ui.add(bPause.set("pause", false));
ui.add(bStop.set("stop", true));
loadButton.addListener(this, &AudioPlayer::loadButtonCall);
samplePath.addListener(this, &AudioPlayer::sampleChangedCall);
bPlay.addListener(this, &AudioPlayer::onPlay);
bPause.addListener(this, &AudioPlayer::onPause);
bStop.addListener(this, &AudioPlayer::onStop);
bSemaphore = true;
sample.setVerbose(true);
}
void AudioPlayer::onPlay(bool & value) {
if (bSemaphore) {
bSemaphore = false;
if (bStop) {
bPlay = true;
bStop = false;
envGate.trigger(1.0f);
sampleTrig.trigger(1.0f);
ofLogVerbose() << "[pdsp] player: playing\n";
}
else if (bPause) {
ofLogVerbose() << "[pdsp] player: unpaused\n";
bPlay = true;
bPause = false;
envGate.trigger(1.0f);
}
else {
bPlay = true;
sampleTrig.trigger(1.0f);
}
bSemaphore = true;
}
}
void AudioPlayer::onPause(bool & value) {
if (bSemaphore) {
bSemaphore = false;
if (bPlay) {
bPause = true;
bPlay = false;
ofLogVerbose() << "[pdsp] player: paused\n";
envGate.off();
}
else if (bStop) {
bPause = false;
ofLogVerbose() << "[pdsp] player: impossible to pause on stop";
}
else {
ofLogVerbose() << "[pdsp] player: unpaused\n";
bPlay = true;
bPause = false;
envGate.trigger(1.0f);
}
bSemaphore = true;
}
}
void AudioPlayer::onStop(bool & value) {
if (bSemaphore) {
bSemaphore = false;
if (bPlay || bPause) {
bStop = true;
bPlay = false;
bPause = false;
ofLogVerbose() << "[pdsp] player: stopped\n";
envGate.off();
}
bSemaphore = true;
}
}
void AudioPlayer::loadButtonCall(bool & value) {
if (value) {
float fvalue = faderControl.get();
faderControl.setv(0.0f);
//Open the Open File Dialog
ofFileDialogResult openFileResult = ofSystemLoadDialog("select an audio sample");
//Check if the user opened a file
if (openFileResult.bSuccess) {
string path = openFileResult.getPath();
samplePath = path;
ofLogVerbose("file loaded");
}
else {
ofLogVerbose("User hit cancel");
}
// switch to mono if the sample has just one channel
if (sample.channels == 1) {
sampler1.setSample(&sample, 0, 0);
}
else {
sampler1.setSample(&sample, 0, 1);
}
loadButton = false;
faderControl.setv(fvalue);
bool dummy = true;
onStop(dummy);
}
}
void AudioPlayer::sampleChangedCall(string & value) {
ofLogVerbose("loading" + value);
loadSample(samplePath);
auto v = ofSplitString(samplePath, "/");
sampleName = v[v.size() - 1];
}
void AudioPlayer::loadSample(string path) {
sample.load(path);
}
void AudioPlayer::load(string path) {
samplePath = path;
}
void AudioPlayer::play() {
bPlay = bPlay ? false : true;
}
void AudioPlayer::pause() {
bPause = bPause ? false : true;
}
void AudioPlayer::stop() {
bStop = bStop ? false : true;
}
//--------------------------------------------------------------
void ofApp::setup() {
player.load(ofToDataPath("song3.wav"));
player.play();
//-------------------GRAPHIC SETUP--------------
ofBackground(0);
ofSetFrameRate(30);
videos.add("Beer_Pour_Videvo.mp4", ofColor(255, 255, 255), 32.0f, 52.0f);
videos.add("lighthouse.mp4", ofColor(255, 255, 255));
videos.setNext();
background1.load("beer1.jpg");
beer.load("beer2.jpg");
popcorn.load("popcorn.jpg");
burger.load("burger.jpg");
ignore = 0;
//--------PATCHING-------
// a pdsp::ADSR is an ADSR envelope that makes a one-shot modulation when triggered
// pdsp::ADSR require an output sending trigger signals
// remember, in pdsp out_trig() always have to be connected to in_trig()
// in_trig() is the default pdsp::ADSR input signal
// a pdsp::Amp multiply in_signal() and in_mod()
player.out("0") >> engine.audio_out(0);
player.out("1") >> engine.audio_out(1);
gate_ctrl.out_trig() >> adsrEnvelop;
adsrEnvelop >> amp.in_mod();
pitch_ctrl >> oscillator.in_pitch();
//oscillator >> amp * dB(-12.0f) >> engine.audio_out(0);
//amp * dB(-12.0f) >> engine.audio_out(1);
// we patch the pdsp::Parameter to control pitch and amp
// and then patch the oscillator to the engine outs
osc1_pitch_ctrl >> fm1.in_pitch();
osc2_pitch_ctrl >> fm2.in_pitch();
osc3_pitch_ctrl >> fm3.in_pitch();
// pdsp::ParameterGain can be added to gui like an ofParameter
// and has an input and output for signals
// it is used to control volume as it has control in deciBel
// pdsp::ParameterAmp instead just multiply the input for the parameter value
// it is usefule for scaling modulation signals
fm1 >> osc1_amp >> engine.audio_out(0);
osc1_amp >> engine.audio_out(1);
//fm2 >> osc2_gain >> engine.audio_out(0);
// osc2_gain >> engine.audio_out(1);
//fm3 >> osc3_gain >> engine.audio_out(0);
// osc3_gain >> engine.audio_out(1);
osc1_pitch_ctrl.set("pitch", 60.0f, 24.0f, 96.0f);
osc1_amp.set("amp", 0.25f, 0.0f, 1.0f);
osc2_pitch_ctrl.set("pitch", 60, 24, 96);
osc2_gain.set("active", false, -48.0f, -12.0f);
osc3_pitch_ctrl.set("pitch coarse", 60, 24, 96);
osc3_pitch_ctrl.set("pitch fine ", 0.0f, -0.5f, 0.5f);
osc3_gain.set("gain", -24.f, -48.0f, 0.0f);
osc2_pitch_ctrl.setv(ofRandom(48.0f, 96.0f));
1.0f >> adsrEnvelop.in_attack();
50.0f >> adsrEnvelop.in_decay();
0.5f >> adsrEnvelop.in_sustain();
500.0f >> adsrEnvelop.in_release();
gate_ctrl.trigger(1.0f);
pitch_ctrl.setv(36.0f); // we control the value of an pdsp::Parameter directly with the setv function
// you can smooth out an pdsp::Parameter changes, decomment this for less "grainy" pitch changes
pitch_ctrl.enableSmoothing(50.0f); // 50ms smoothing
//----------------------AUDIO SETUP-------------
// set up the audio output device
engine.listDevices();
engine.setDeviceID(0); // REMEMBER TO SET THIS AT THE RIGHT INDEX!!!!
// start your audio engine !
engine.setup(44100, 512, 3);
// arguments are : sample rate, buffer size, and how many buffer there are in the audio callback queue
// 512 is the minimum buffer size for the raspberry Pi to work
// 3 buffers queue is the minimum for the rPi to work
// if you are using JACK you have to set this number to the bufferSize you set in JACK
// on Windows you have to set the sample rate to the system sample rate, usually 44100hz
// on iOS sometimes the systems forces the sample rate to 48khz, so if you have problems set 48000
}
//--------------------------------------------------------------
void ofApp::update() {
videos.update();
pitch_ctrl.setv(videos.getPitch());
osc1_pitch_ctrl.setv(videos.getPitch());
}
//--------------------------------------------------------------
void ofApp::draw() {
ofPushMatrix();
if (!ignore) {
background1.draw(0, 0, ofGetScreenWidth(), ofGetScreenHeight());
}
ofEnableAlphaBlending();
ofSetColor(videos.getColor().r, videos.getColor().g, videos.getColor().b, videos.getAlpha());
videos.draw(0, 0, ofGetScreenWidth(), ofGetScreenHeight());
ofDisableAlphaBlending();
ofPopMatrix();
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key) {
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key) {
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y) {
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button) {
float pitch = ofMap(x, 0, ofGetWidth(), 36.0f, 72.0f);
pitch_ctrl.setv(pitch);
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button) {
float pitch = ofMap(x, 0, ofGetWidth(), 36.0f, 72.0f);
pitch_ctrl.setv(pitch);
// y value controls the trigger intensity
float trig = ofMap(y, 0, ofGetHeight(), 1.0f, 0.000001f);
gate_ctrl.trigger(trig); // we send a trigger to the envelope
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button) {
gate_ctrl.off(); // we send an "off" trigger to the envelope
}
//--------------------------------------------------------------
void ofApp::mouseEntered(int x, int y) {
}
//--------------------------------------------------------------
void ofApp::mouseExited(int x, int y) {
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h) {
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg) {
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo) {
}
| 11,268 | 3,797 |
// Copyright (C) NeoAxis Group Ltd. 8 Copthall, Roseau Valley, 00152 Commonwealth of Dominica.
#include "OgreStableHeaders.h"
#include "OgreNativeWrapperGeneral.h"
#pragma hdrstop
#include "MiniDump.h"
#ifdef MINIDUMP
#include "MiniDump.h"
#include <windows.h>
#include <dbghelp.h>
#include <tchar.h>
typedef BOOL (WINAPI *MINIDUMPWRITEDUMP)( HANDLE hProcess,
DWORD dwPid,
HANDLE hFile,
MINIDUMP_TYPE DumpType,
CONST PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam,
CONST PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam,
CONST PMINIDUMP_CALLBACK_INFORMATION CallbackParam);
BOOL MiniDump::Create(HMODULE hModule, PEXCEPTION_POINTERS pExceptionInfo)
{
BOOL bRet = FALSE;
DWORD dwLastError = 0;
HANDLE hImpersonationToken = NULL;
if(!GetImpersonationToken(&hImpersonationToken))
return FALSE;
HMODULE hDbgDll = LocalLoadLibrary(hModule, _T("dbghelp.dll"));
if(!hDbgDll)
return FALSE;
MINIDUMPWRITEDUMP pDumpFunction = (MINIDUMPWRITEDUMP)::GetProcAddress(hDbgDll, "MiniDumpWriteDump");
if(!pDumpFunction)
{
FreeLibrary(hDbgDll);
return FALSE;
}
// ::CreateDirectory("Errors",NULL);
//const char* dumpfilename = "UserSettings//NativeError.dmp";
const char* dumpfilename = "C://NativeError.dmp";
HANDLE hDumpFile = ::CreateFile(dumpfilename,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_WRITE | FILE_SHARE_READ,
0, CREATE_ALWAYS, 0, 0);
if(hDumpFile == INVALID_HANDLE_VALUE)
{
MessageBox(0, "Cannot create dump file.", "Error", MB_OK);
return FALSE;
}
MINIDUMP_EXCEPTION_INFORMATION stInfo = {0};
stInfo.ThreadId = GetCurrentThreadId();
stInfo.ExceptionPointers = pExceptionInfo;
stInfo.ClientPointers = TRUE;
// We need the SeDebugPrivilege to be able to run MiniDumpWriteDump
TOKEN_PRIVILEGES tp;
BOOL bPrivilegeEnabled = EnablePriv(SE_DEBUG_NAME, hImpersonationToken, &tp);
// DBGHELP.DLL is not thread safe
//EnterCriticalSection(pCS);
bRet = pDumpFunction(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile,
MiniDumpWithDataSegs, &stInfo, NULL, NULL);
//LeaveCriticalSection(pCS);
if(bPrivilegeEnabled)
RestorePriv(hImpersonationToken, &tp);
CloseHandle(hDumpFile);
FreeLibrary(hDbgDll);
return bRet;
}
BOOL MiniDump::GetImpersonationToken(HANDLE* phToken)
{
*phToken = NULL;
if(!OpenThreadToken(GetCurrentThread(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES, TRUE, phToken))
{
if(GetLastError() == ERROR_NO_TOKEN)
{
// No impersonation token for the curren thread available - go for the process token
if(!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES, phToken))
return FALSE;
}
else
return FALSE;
}
return TRUE;
}
BOOL MiniDump::EnablePriv(LPCTSTR pszPriv, HANDLE hToken, TOKEN_PRIVILEGES* ptpOld)
{
BOOL bOk = FALSE;
TOKEN_PRIVILEGES tp;
tp.PrivilegeCount = 1;
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
bOk = LookupPrivilegeValue( 0, pszPriv, &tp.Privileges[0].Luid);
if(bOk)
{
DWORD cbOld = sizeof(*ptpOld);
bOk = AdjustTokenPrivileges(hToken, FALSE, &tp, cbOld, ptpOld, &cbOld);
}
return (bOk && (ERROR_NOT_ALL_ASSIGNED != GetLastError()));
}
BOOL MiniDump::RestorePriv(HANDLE hToken, TOKEN_PRIVILEGES* ptpOld)
{
BOOL bOk = AdjustTokenPrivileges(hToken, FALSE, ptpOld, 0, 0, 0);
return (bOk && (ERROR_NOT_ALL_ASSIGNED != GetLastError()));
}
HMODULE MiniDump::LocalLoadLibrary(HMODULE hModule, LPCTSTR pszModule)
{
HMODULE hDll = NULL;
// Attempt to load local module first
TCHAR pszModulePath[MAX_PATH];
if(GetModuleFileName(hModule, pszModulePath, sizeof(pszModulePath) / sizeof(pszModulePath[0])))
{
TCHAR* pSlash = _tcsrchr(pszModulePath, _T('\\'));
if(0 != pSlash)
{
_tcscpy(pSlash + 1, pszModule);
hDll = ::LoadLibrary(pszModulePath);
}
}
if(!hDll)
{
// If not found, load any available copy
hDll = ::LoadLibrary(pszModule);
}
return hDll;
}
unsigned long ExceptionHandler(LPEXCEPTION_POINTERS pExceptionPointers)
{
if(MiniDump::Create(NULL, pExceptionPointers))
{
}
else
{
}
return EXCEPTION_EXECUTE_HANDLER;
}
#endif
| 4,118 | 1,816 |
#include <algorithm>
#include <QList>
#include <QString>
#include <QStringList>
#include <QVector>
#include <SpiceUsr.h>
#include "Cube.h"
#include "Brick.h"
#include "Constants.h"
#include "Cube.h"
#include "IString.h"
#include "LeastSquares.h"
#include "NaifStatus.h"
#include "nocam2map.h"
#include "PolynomialBivariate.h"
#include "ProcessRubberSheet.h"
#include "ProjectionFactory.h"
#include "Statistics.h"
#include "Target.h"
#include "TextFile.h"
#include "TProjection.h"
using namespace std;
using namespace Isis;
namespace Isis {
static void DeleteTables(Pvl *label, PvlGroup kernels);
void nocam2map(UserInterface &ui, Pvl *log) {
QString inputFileName = ui.GetCubeName("FROM");
Cube iCube(inputFileName);
nocam2map(&iCube, ui, log);
}
void nocam2map(Cube *inCube, UserInterface &ui, Pvl *log) {
//Create a process to create the input cubes
Process p;
//Create the input cubes, matching sample/lines
Cube *latCube = p.SetInputCube(ui.GetCubeName("LATCUB"), ui.GetInputAttribute("LATCUB"), SpatialMatch);
Cube *lonCube = p.SetInputCube(ui.GetCubeName("LONCUB"), ui.GetInputAttribute("LONCUB"), SpatialMatch);
//A 1x1 brick to read in the latitude and longitude DN values from
//the specified cubes
Brick latBrick(1, 1, 1, latCube->pixelType());
Brick lonBrick(1, 1, 1, lonCube->pixelType());
//Set the sample and line increments
float sinc = (inCube->sampleCount() * 0.10);
if (ui.WasEntered("SINC")) {
sinc = ui.GetInteger("SINC");
}
float linc = (inCube->lineCount() * 0.10);
if (ui.WasEntered("LINC")) {
linc = ui.GetInteger("LINC");
}
//Set the degree of the polynomial to use in our functions
int degree = ui.GetInteger("DEGREE");
//We are using a polynomial with two variables
PolynomialBivariate sampFunct(degree);
PolynomialBivariate lineFunct(degree);
//We will be solving the function using the least squares method
LeastSquares sampSol(sampFunct);
LeastSquares lineSol(lineFunct);
//Setup the variables for solving the stereographic projection
//x = cos(latitude) * sin(longitude - lon_center)
//y = cos(lat_center) * sin(latitude) - sin(lat_center) * cos(latitude) * cos(longitude - lon_center)
//Get the center lat and long from the input cubes
double lat_center = latCube->statistics()->Average() * PI / 180.0;
double lon_center = lonCube->statistics()->Average() * PI / 180.0;
/**
* Loop through lines and samples projecting the latitude and longitude at those
* points to stereographic x and y and adding these points to the LeastSquares
* matrix.
*/
for (float i = 1; i <= inCube->lineCount(); i += linc) {
for (float j = 1; j <= inCube->sampleCount(); j += sinc) {
latBrick.SetBasePosition(j, i, 1);
latCube->read(latBrick);
if (IsSpecial(latBrick.at(0))) continue;
double lat = latBrick.at(0) * PI / 180.0;
lonBrick.SetBasePosition(j, i, 1);
lonCube->read(lonBrick);
if (IsSpecial(lonBrick.at(0))) continue;
double lon = lonBrick.at(0) * PI / 180.0;
//Project lat and lon to x and y using a stereographic projection
double k = 2 / (1 + sin(lat_center) * sin(lat) + cos(lat_center) * cos(lat) * cos(lon - lon_center));
double x = k * cos(lat) * sin(lon - lon_center);
double y = k * (cos(lat_center) * sin(lat)) - (sin(lat_center) * cos(lat) * cos(lon - lon_center));
//Add x and y to the least squares matrix
vector<double> data;
data.push_back(x);
data.push_back(y);
sampSol.AddKnown(data, j);
lineSol.AddKnown(data, i);
//If the sample increment goes past the last sample in the line, we want to
//always read the last sample..
if (j != inCube->sampleCount() && j + sinc > inCube->sampleCount()) {
j = inCube->sampleCount() - sinc;
}
}
//If the line increment goes past the last line in the cube, we want to
//always read the last line..
if (i != inCube->lineCount() && i + linc > inCube->lineCount()) {
i = inCube->lineCount() - linc;
}
}
//Solve the least squares functions using QR Decomposition
try {
sampSol.Solve(LeastSquares::QRD);
lineSol.Solve(LeastSquares::QRD);
}
catch (IException &e) {
FileName inFile = inCube->fileName();
QString msg = "Unable to calculate transformation of projection for [" + inFile.expanded() + "].";
throw IException(e, IException::Unknown, msg, _FILEINFO_);
}
//If the user wants to save the residuals to a file, create a file and write
//the column titles to it.
TextFile oFile;
if (ui.WasEntered("RESIDUALS")) {
oFile.Open(ui.GetFileName("RESIDUALS"), "overwrite");
oFile.PutLine("Sample,\tLine,\tX,\tY,\tSample Error,\tLine Error\n");
}
//Gather the statistics for the residuals from the least squares solutions
Statistics sampErr;
Statistics lineErr;
vector<double> sampResiduals = sampSol.Residuals();
vector<double> lineResiduals = lineSol.Residuals();
for (int i = 0; i < (int)sampResiduals.size(); i++) {
sampErr.AddData(sampResiduals[i]);
lineErr.AddData(lineResiduals[i]);
}
//If a residuals file was specified, write the previous data, and the errors to the file.
if (ui.WasEntered("RESIDUALS")) {
for (int i = 0; i < sampSol.Rows(); i++) {
vector<double> data = sampSol.GetInput(i);
QString tmp = "";
tmp += toString(sampSol.GetExpected(i));
tmp += ",\t";
tmp += toString(lineSol.GetExpected(i));
tmp += ",\t";
tmp += toString(data[0]);
tmp += ",\t";
tmp += toString(data[1]);
tmp += ",\t";
tmp += toString(sampResiduals[i]);
tmp += ",\t";
tmp += toString(lineResiduals[i]);
oFile.PutLine(tmp + "\n");
}
}
oFile.Close();
//Records the error to the log
PvlGroup error("Error");
error += PvlKeyword("Degree", toString(degree));
error += PvlKeyword("NumberOfPoints", toString((int)sampResiduals.size()));
error += PvlKeyword("SampleMinimumError", toString(sampErr.Minimum()));
error += PvlKeyword("SampleAverageError", toString(sampErr.Average()));
error += PvlKeyword("SampleMaximumError", toString(sampErr.Maximum()));
error += PvlKeyword("SampleStdDeviationError", toString(sampErr.StandardDeviation()));
error += PvlKeyword("LineMinimumError", toString(lineErr.Minimum()));
error += PvlKeyword("LineAverageError", toString(lineErr.Average()));
error += PvlKeyword("LineMaximumError", toString(lineErr.Maximum()));
error += PvlKeyword("LineStdDeviationError", toString(lineErr.StandardDeviation()));
if (log) {
log->addGroup(error);
}
//Close the input cubes for cleanup
p.EndProcess();
//If we want to warp the image, then continue, otherwise return
if (!ui.GetBoolean("NOWARP")) {
//Creates the mapping group
Pvl mapFile;
mapFile.read(ui.GetFileName("MAP"));
PvlGroup &mapGrp = mapFile.findGroup("Mapping", Pvl::Traverse);
//Reopen the lat and long cubes
latCube = new Cube();
latCube->setVirtualBands(ui.GetInputAttribute("LATCUB").bands());
latCube->open(ui.GetCubeName("LATCUB"));
lonCube = new Cube();
lonCube->setVirtualBands(ui.GetInputAttribute("LONCUB").bands());
lonCube->open(ui.GetCubeName("LONCUB"));
PvlKeyword targetName;
//If the user entered the target name
if (ui.WasEntered("TARGET")) {
targetName = PvlKeyword("TargetName", ui.GetString("TARGET"));
}
//Else read the target name from the input cube
else {
Pvl fromFile;
fromFile.read(inCube->fileName());
targetName = fromFile.findKeyword("TargetName", Pvl::Traverse);
}
mapGrp.addKeyword(targetName, Pvl::Replace);
PvlKeyword equRadius;
PvlKeyword polRadius;
//If the user entered the equatorial and polar radii
if (ui.WasEntered("EQURADIUS") && ui.WasEntered("POLRADIUS")) {
equRadius = PvlKeyword("EquatorialRadius", toString(ui.GetDouble("EQURADIUS")));
polRadius = PvlKeyword("PolarRadius", toString(ui.GetDouble("POLRADIUS")));
}
//Else read them from the pck
else {
PvlGroup radii = Target::radiiGroup(targetName[0]);
equRadius = radii["EquatorialRadius"];
polRadius = radii["PolarRadius"];
}
mapGrp.addKeyword(equRadius, Pvl::Replace);
mapGrp.addKeyword(polRadius, Pvl::Replace);
//If the latitude type is not in the mapping group, copy it from the input
if (!mapGrp.hasKeyword("LatitudeType")) {
if (ui.GetString("LATTYPE") == "PLANETOCENTRIC") {
mapGrp.addKeyword(PvlKeyword("LatitudeType", "Planetocentric"), Pvl::Replace);
}
else {
mapGrp.addKeyword(PvlKeyword("LatitudeType", "Planetographic"), Pvl::Replace);
}
}
//If the longitude direction is not in the mapping group, copy it from the input
if (!mapGrp.hasKeyword("LongitudeDirection")) {
if (ui.GetString("LONDIR") == "POSITIVEEAST") {
mapGrp.addKeyword(PvlKeyword("LongitudeDirection", "PositiveEast"), Pvl::Replace);
}
else {
mapGrp.addKeyword(PvlKeyword("LongitudeDirection", "PositiveWest"), Pvl::Replace);
}
}
//If the longitude domain is not in the mapping group, assume it is 360
if (!mapGrp.hasKeyword("LongitudeDomain")) {
mapGrp.addKeyword(PvlKeyword("LongitudeDomain", "360"), Pvl::Replace);
}
//If the default range is to be computed, use the input lat/long cubes to determine the range
if (ui.GetString("DEFAULTRANGE") == "COMPUTE") {
//NOTE - When computing the min/max longitude this application does not account for the
//longitude seam if it exists. Since the min/max are calculated from the statistics of
//the input longitude cube and then converted to the mapping group's domain they may be
//invalid for cubes containing the longitude seam.
Statistics *latStats = latCube->statistics();
Statistics *lonStats = lonCube->statistics();
double minLat = latStats->Minimum();
double maxLat = latStats->Maximum();
bool isOcentric = ((QString)mapGrp.findKeyword("LatitudeType")) == "Planetocentric";
if (isOcentric) {
if (ui.GetString("LATTYPE") != "PLANETOCENTRIC") {
minLat = TProjection::ToPlanetocentric(minLat, (double)equRadius, (double)polRadius);
maxLat = TProjection::ToPlanetocentric(maxLat, (double)equRadius, (double)polRadius);
}
}
else {
if (ui.GetString("LATTYPE") == "PLANETOCENTRIC") {
minLat = TProjection::ToPlanetographic(minLat, (double)equRadius, (double)polRadius);
maxLat = TProjection::ToPlanetographic(maxLat, (double)equRadius, (double)polRadius);
}
}
int lonDomain = (int)mapGrp.findKeyword("LongitudeDomain");
double minLon = lonDomain == 360 ? TProjection::To360Domain(lonStats->Minimum()) :
TProjection::To180Domain(lonStats->Minimum());
double maxLon = lonDomain == 360 ? TProjection::To360Domain(lonStats->Maximum()) :
TProjection::To180Domain(lonStats->Maximum());
bool isPosEast = ((QString)mapGrp.findKeyword("LongitudeDirection")) == "PositiveEast";
if (isPosEast) {
if (ui.GetString("LONDIR") != "POSITIVEEAST") {
minLon = TProjection::ToPositiveEast(minLon, lonDomain);
maxLon = TProjection::ToPositiveEast(maxLon, lonDomain);
}
}
else {
if (ui.GetString("LONDIR") == "POSITIVEEAST") {
minLon = TProjection::ToPositiveWest(minLon, lonDomain);
maxLon = TProjection::ToPositiveWest(maxLon, lonDomain);
}
}
if (minLon > maxLon) {
double temp = minLon;
minLon = maxLon;
maxLon = temp;
}
mapGrp.addKeyword(PvlKeyword("MinimumLatitude", toString(minLat)), Pvl::Replace);
mapGrp.addKeyword(PvlKeyword("MaximumLatitude", toString(maxLat)), Pvl::Replace);
mapGrp.addKeyword(PvlKeyword("MinimumLongitude", toString(minLon)), Pvl::Replace);
mapGrp.addKeyword(PvlKeyword("MaximumLongitude", toString(maxLon)), Pvl::Replace);
}
//If the user decided to enter a ground range then override
if (ui.WasEntered("MINLAT")) {
mapGrp.addKeyword(PvlKeyword("MinimumLatitude",
toString(ui.GetDouble("MINLAT"))), Pvl::Replace);
}
if (ui.WasEntered("MAXLAT")) {
mapGrp.addKeyword(PvlKeyword("MaximumLatitude",
toString(ui.GetDouble("MAXLAT"))), Pvl::Replace);
}
if (ui.WasEntered("MINLON")) {
mapGrp.addKeyword(PvlKeyword("MinimumLongitude",
toString(ui.GetDouble("MINLON"))), Pvl::Replace);
}
if (ui.WasEntered("MAXLON")) {
mapGrp.addKeyword(PvlKeyword("MaximumLongitude",
toString(ui.GetDouble("MAXLON"))), Pvl::Replace);
}
//If the pixel resolution is to be computed, compute the pixels/degree from the input
if (ui.GetString("PIXRES") == "COMPUTE") {
latBrick.SetBasePosition(1, 1, 1);
latCube->read(latBrick);
lonBrick.SetBasePosition(1, 1, 1);
lonCube->read(lonBrick);
//Read the lat and long at the upper left corner
double a = latBrick.at(0) * PI / 180.0;
double c = lonBrick.at(0) * PI / 180.0;
latBrick.SetBasePosition(latCube->sampleCount(), latCube->lineCount(), 1);
latCube->read(latBrick);
lonBrick.SetBasePosition(lonCube->sampleCount(), lonCube->lineCount(), 1);
lonCube->read(lonBrick);
//Read the lat and long at the lower right corner
double b = latBrick.at(0) * PI / 180.0;
double d = lonBrick.at(0) * PI / 180.0;
//Determine the angle between the two points
double angle = acos(cos(a) * cos(b) * cos(c - d) + sin(a) * sin(b));
//double angle = acos((cos(a1) * cos(b1) * cos(b2)) + (cos(a1) * sin(b1) * cos(a2) * sin(b2)) + (sin(a1) * sin(a2)));
angle *= 180 / PI;
//Determine the number of pixels between the two points
double pixels = sqrt(pow(latCube->sampleCount() - 1.0, 2.0) + pow(latCube->lineCount() - 1.0, 2.0));
//Add the scale in pixels/degree to the mapping group
mapGrp.addKeyword(PvlKeyword("Scale",
toString(pixels / angle), "pixels/degree"),
Pvl::Replace);
if (mapGrp.hasKeyword("PixelResolution")) {
mapGrp.deleteKeyword("PixelResolution");
}
}
// If the user decided to enter a resolution then override
if (ui.GetString("PIXRES") == "MPP") {
mapGrp.addKeyword(PvlKeyword("PixelResolution",
toString(ui.GetDouble("RESOLUTION")), "meters/pixel"),
Pvl::Replace);
if (mapGrp.hasKeyword("Scale")) {
mapGrp.deleteKeyword("Scale");
}
}
else if (ui.GetString("PIXRES") == "PPD") {
mapGrp.addKeyword(PvlKeyword("Scale",
toString(ui.GetDouble("RESOLUTION")), "pixels/degree"),
Pvl::Replace);
if (mapGrp.hasKeyword("PixelResolution")) {
mapGrp.deleteKeyword("PixelResolution");
}
}
//Create a projection using the map file we created
int samples, lines;
TProjection *outmap = (TProjection *) ProjectionFactory::CreateForCube(mapFile, samples, lines,
false);
//Create a process rubber sheet
ProcessRubberSheet r;
//Set the input cube
r.SetInputCube(inCube);
double tolerance = ui.GetDouble("TOLERANCE") * outmap->Resolution();
//Create a new transform object
Transform *transform = new NoCam2Map(sampSol, lineSol, outmap,
latCube, lonCube,
ui.GetString("LATTYPE") == "PLANETOCENTRIC",
ui.GetString("LONDIR") == "POSITIVEEAST",
tolerance, ui.GetInteger("ITERATIONS"),
inCube->sampleCount(), inCube->lineCount(),
samples, lines);
//Allocate the output cube and add the mapping labels
Cube *oCube = r.SetOutputCube(ui.GetCubeName("TO"), ui.GetOutputAttribute("TO"), transform->OutputSamples(),
transform->OutputLines(),
inCube->bandCount());
oCube->putGroup(mapGrp);
PvlGroup kernels;
Pvl *label=oCube->label();
if ( oCube->hasGroup("Kernels") ) {
kernels=oCube->group("Kernels");
DeleteTables(label, kernels);
oCube->deleteGroup("Kernels");
}
if ( label->hasObject("NaifKeywords") ) {
label->deleteObject("NaifKeywords");
}
//Determine which interpolation to use
Interpolator *interp = NULL;
if (ui.GetString("INTERP") == "NEARESTNEIGHBOR") {
interp = new Interpolator(Interpolator::NearestNeighborType);
}
else if (ui.GetString("INTERP") == "BILINEAR") {
interp = new Interpolator(Interpolator::BiLinearType);
}
else if (ui.GetString("INTERP") == "CUBICCONVOLUTION") {
interp = new Interpolator(Interpolator::CubicConvolutionType);
}
//Warp the cube
r.StartProcess(*transform, *interp);
r.EndProcess();
// add mapping to print.prt
PvlGroup mapping = outmap->Mapping();
if (log) {
log->addGroup(mapping);
}
//Clean up
delete latCube;
delete lonCube;
delete outmap;
delete transform;
delete interp;
}
}
// Transform object constructor
NoCam2Map::NoCam2Map(LeastSquares sample, LeastSquares line, TProjection *outmap,
Cube *latCube, Cube *lonCube,
bool isOcentric, bool isPosEast,
double tolerance, int iterations,
const int inputSamples, const int inputLines,
const int outputSamples, const int outputLines) {
p_sampleSol = &sample;
p_lineSol = &line;
p_outmap = outmap;
p_inputSamples = inputSamples;
p_inputLines = inputLines;
p_outputSamples = outputSamples;
p_outputLines = outputLines;
p_latCube = latCube;
p_lonCube = lonCube;
p_isOcentric = isOcentric;
p_isPosEast = isPosEast;
p_tolerance = tolerance;
p_iterations = iterations;
p_latCenter = p_latCube->statistics()->Average() * PI / 180.0;
p_lonCenter = p_lonCube->statistics()->Average() * PI / 180.0;
p_radius = p_outmap->LocalRadius(p_latCenter);
}
// Transform method mapping output line/samps to lat/lons to input line/samps
bool NoCam2Map::Xform(double &inSample, double &inLine,
const double outSample, const double outLine) {
if (!p_outmap->SetWorld(outSample, outLine)) return false;
if (outSample > p_outputSamples) return false;
if (outLine > p_outputLines) return false;
//Get the known latitude and longitudes from the projection
//Convert to the input's latitude/longitude domain if necessary
double lat_known, lon_known;
if (p_outmap->IsPlanetocentric()) {
if (!p_isOcentric) lat_known = p_outmap->ToPlanetographic(p_outmap->Latitude());
else lat_known = p_outmap->Latitude();
}
else {
if (p_isOcentric) lat_known = p_outmap->ToPlanetocentric(p_outmap->Latitude());
else lat_known = p_outmap->Latitude();
}
if (p_outmap->IsPositiveEast()) {
if (!p_isPosEast) lon_known = p_outmap->ToPositiveWest(p_outmap->Longitude(), 360);
else lon_known = p_outmap->Longitude();
}
else {
if (p_isPosEast) lon_known = p_outmap->ToPositiveEast(p_outmap->Longitude(), 360);
else lon_known = p_outmap->Longitude();
}
lat_known *= PI / 180.0;
lon_known *= PI / 180.0;
//Project the known lat/long to x/y using the stereographic projection
double k_known = 2 / (1 + sin(p_latCenter) * sin(lat_known) + cos(p_latCenter) * cos(lat_known) * cos(lon_known - p_lonCenter));
double x_known = k_known * cos(lat_known) * sin(lon_known - p_lonCenter);
double y_known = k_known * (cos(p_latCenter) * sin(lat_known)) - (sin(p_latCenter) * cos(lat_known) * cos(lon_known - p_lonCenter));
vector<double> data_known;
data_known.push_back(x_known);
data_known.push_back(y_known);
//Get the sample/line guess from the least squares solutions
double sample_guess = p_sampleSol->Evaluate(data_known);
double line_guess = p_lineSol->Evaluate(data_known);
//If the sample/line guess is out of bounds return false
if (sample_guess < -1.5) return false;
if (line_guess < -1.5) return false;
if (sample_guess > p_inputSamples + 1.5) return false;
if (line_guess > p_inputLines + 1.5) return false;
if (sample_guess < 0.5) sample_guess = 1;
if (line_guess < 0.5) line_guess = 1;
if (sample_guess > p_inputSamples + 0.5) sample_guess = p_inputSamples;
if (line_guess > p_inputLines + 0.5) line_guess = p_inputLines;
//Create a bilinear interpolator
Interpolator interp(Interpolator::BiLinearType);
//Create a 2x2 buffer to read the lat and long cubes
Portal latPortal(interp.Samples(), interp.Lines(),
p_latCube->pixelType() ,
interp.HotSample(), interp.HotLine());
Portal lonPortal(interp.Samples(), interp.Lines(),
p_lonCube->pixelType() ,
interp.HotSample(), interp.HotLine());
//Set the buffers positions to the sample/line guess and read from the lat/long cubes
latPortal.SetPosition(sample_guess, line_guess, 1);
p_latCube->read(latPortal);
lonPortal.SetPosition(sample_guess, line_guess, 1);
p_lonCube->read(lonPortal);
//Get the lat/long guess from the interpolator
double lat_guess = interp.Interpolate(sample_guess, line_guess, latPortal.DoubleBuffer()) * PI / 180.0;
double lon_guess = interp.Interpolate(sample_guess, line_guess, lonPortal.DoubleBuffer()) * PI / 180.0;
//Project the lat/long guess to x/y using the stereographic projection
double k_guess = 2 / (1 + sin(p_latCenter) * sin(lat_guess) + cos(p_latCenter) * cos(lat_guess) * cos(lon_guess - p_lonCenter));
double x_guess = k_guess * cos(lat_guess) * sin(lon_guess - p_lonCenter);
double y_guess = k_guess * (cos(p_latCenter) * sin(lat_guess)) - (sin(p_latCenter) * cos(lat_guess) * cos(lon_guess - p_lonCenter));
//Calculate the difference between the known x/y to the x/y from our least squares solutions
double x_diff = abs(x_guess - x_known) * p_radius;
double y_diff = abs(y_guess - y_known) * p_radius;
//If the difference is above the tolerance, correct it until it is below the tolerance or we have iterated through a set amount of times
int iteration = 0;
while (x_diff > p_tolerance || y_diff > p_tolerance) {
if (iteration++ >= p_iterations) return false;
//Create a 1st order polynomial function
PolynomialBivariate sampFunct(1);
PolynomialBivariate lineFunct(1);
//Create a least squares solution
LeastSquares sampConverge(sampFunct);
LeastSquares lineConverge(lineFunct);
//Add the points around the line/sample guess point to the least squares matrix
for (int i = (int)(line_guess + 0.5) - 1; i <= (int)(line_guess + 0.5) + 1; i++) {
//If the line is out of bounds, then skip it
if (i < 1 || i > p_inputLines) continue;
for (int j = (int)(sample_guess + 0.5) - 1; j <= (int)(sample_guess + 0.5) + 1; j++) {
//If the sample is out of bounds, then skip it
if (j < 1 || j > p_inputSamples) continue;
latPortal.SetPosition(j, i, 1);
p_latCube->read(latPortal);
if (IsSpecial(latPortal.at(0))) continue;
double n_lat = latPortal.at(0) * PI / 180.0;
lonPortal.SetPosition(j, i, 1);
p_lonCube->read(lonPortal);
if (IsSpecial(lonPortal.at(0))) continue;
double n_lon = lonPortal.at(0) * PI / 180.0;
//Conver the lat/lon to x/y using the stereographic projection
double n_k = 2 / (1 + sin(p_latCenter) * sin(n_lat) + cos(p_latCenter) * cos(n_lat) * cos(n_lon - p_lonCenter));
double n_x = n_k * cos(n_lat) * sin(n_lon - p_lonCenter);
double n_y = n_k * (cos(p_latCenter) * sin(n_lat)) - (sin(p_latCenter) * cos(n_lat) * cos(n_lon - p_lonCenter));
//Add the points to the least squares solution
vector<double> data;
data.push_back(n_x);
data.push_back(n_y);
sampConverge.AddKnown(data, j);
lineConverge.AddKnown(data, i);
}
}
//TODO: What if solve can't and throws an error?
//Solve the least squares functions
sampConverge.Solve(LeastSquares::QRD);
lineConverge.Solve(LeastSquares::QRD);
//Try to solve the known data with our new function
sample_guess = sampConverge.Evaluate(data_known);
line_guess = lineConverge.Evaluate(data_known);
//If the new sample/line is out of bounds return false
if (sample_guess < -1.5) return false;
if (line_guess < -1.5) return false;
if (sample_guess > p_inputSamples + 1.5) return false;
if (line_guess > p_inputLines + 1.5) return false;
if (sample_guess < 0.5) sample_guess = 1;
if (line_guess < 0.5) line_guess = 1;
if (sample_guess > p_inputSamples + 0.5) sample_guess = p_inputSamples;
if (line_guess > p_inputLines + 0.5) line_guess = p_inputLines;
//Set the buffers positions to the sample/line guess and read from the lat/long cubes
latPortal.SetPosition(sample_guess, line_guess, 1);
p_latCube->read(latPortal);
lonPortal.SetPosition(sample_guess, line_guess, 1);
p_lonCube->read(lonPortal);
//Get the lat/long guess from the interpolator
lat_guess = interp.Interpolate(sample_guess, line_guess, latPortal.DoubleBuffer()) * PI / 180.0;
lon_guess = interp.Interpolate(sample_guess, line_guess, lonPortal.DoubleBuffer()) * PI / 180.0;
//Project the lat/long guess to x/y using the stereographic projection
k_guess = 2 / (1 + sin(p_latCenter) * sin(lat_guess) + cos(p_latCenter) * cos(lat_guess) * cos(lon_guess - p_lonCenter));
x_guess = k_guess * cos(lat_guess) * sin(lon_guess - p_lonCenter);
y_guess = k_guess * (cos(p_latCenter) * sin(lat_guess)) - (sin(p_latCenter) * cos(lat_guess) * cos(lon_guess - p_lonCenter));
//Calculate the difference between the known x/y to the x/y from our least squares solutions
x_diff = abs(x_guess - x_known) * p_radius;
y_diff = abs(y_guess - y_known) * p_radius;
}
//Set the input sample/line to the sample/line we've determined to be the closest fit
inSample = sample_guess;
inLine = line_guess;
return true;
}
// Function to delete unwanted tables in header
void DeleteTables(Pvl *label, PvlGroup kernels) {
//Delete any tables in header corresponding to the Kernel
const QString tableStr("Table");
const QString nameStr("Name");
//Setup a list of tables to delete with predetermined values and any tables in the kernel.
//If additional tables need to be removed, they can be added to the list of tables that
//detine the 'tmpTablesToDelete' QString array directly below.
QString tmpTablesToDelete[] = {"SunPosition","BodyRotation","InstrumentPointing",
"InstrumentPosition"};
std::vector<QString> tablesToDelete;
int sizeOfTablesToDelete = (int) sizeof(tmpTablesToDelete)/sizeof(*tmpTablesToDelete);
for (int i = 0; i < sizeOfTablesToDelete; i++) {
tablesToDelete.push_back( tmpTablesToDelete[i] );
}
for (int j=0; j < kernels.keywords(); j++) {
if (kernels[j].operator[](0) == tableStr) {
bool newTableToDelete=true;
for (int k = 0; k<sizeOfTablesToDelete; k++) {
if ( tablesToDelete[k] == kernels[j].name() ) {
newTableToDelete=false;
break;
}
}
if (newTableToDelete) {
tablesToDelete.push_back( kernels[j].name() );
sizeOfTablesToDelete++;
}
}
}
int tablesToDeleteSize = (int) tablesToDelete.size();
//Now go through and find all entries in the label corresponding to our unwanted keywords
std::vector<int> indecesToDelete;
int indecesToDeleteSize=0;
for (int k=0; k < label->objects(); k++) {
PvlObject ¤tObject=(*label).object(k);
if (currentObject.name() == tableStr) {
PvlKeyword &nameKeyword = currentObject.findKeyword(nameStr);
for (int l=0; l < tablesToDeleteSize; l++) {
if ( nameKeyword[0] == tablesToDelete[l] ) {
indecesToDelete.push_back(k-indecesToDeleteSize);
indecesToDeleteSize++;
//(*label).deleteObject(k);
//tableDeleted = true;
break;
}
}
}
}
//Now go through and delete the corresponding tables
for (int k=0; k < indecesToDeleteSize; k++) {
(*label).deleteObject(indecesToDelete[k]);
}
}
int NoCam2Map::OutputSamples() const {
return p_outputSamples;
}
int NoCam2Map::OutputLines() const {
return p_outputLines;
}
} | 30,479 | 10,241 |
class Solution {
public:
vector<vector<int>> kClosest(vector<vector<int>>& points, int K) {
priority_queue<pair<int, int>> pq;
for (int i = 0; i < points.size(); ++i) {
pq.emplace(points[i][0]* points[i][0] + points[i][1] * points[i][1], i);
if (pq.size() > K) {
pq.pop();
}
}
vector<vector<int>> result;
while (!pq.empty()) {
int i = pq.top().second;
result.push_back(points[i]);
pq.pop();
}
return result;
}
};
| 566 | 196 |
/* Copyright 2018 Dimitrij Mijoski, Sander van Geloven
* Copyright 2016-2017 Dimitrij Mijoski
*
* This file is part of Nuspell.
*
* Nuspell 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.
*
* Nuspell 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 Nuspell. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file string_utils.hxx
* String algorithms.
*/
#ifndef NUSPELL_STRING_UTILS_HXX
#define NUSPELL_STRING_UTILS_HXX
#include <algorithm>
#include <iterator>
#include <locale>
#include <string>
#include <vector>
namespace nuspell {
#define LITERAL(T, x) ::nuspell::literal_choose<T>(x, L##x)
template <class CharT>
auto constexpr literal_choose(const char* narrow, const wchar_t* wide);
template <>
auto constexpr literal_choose<char>(const char* narrow, const wchar_t*)
{
return narrow;
}
template <>
auto constexpr literal_choose<wchar_t>(const char*, const wchar_t* wide)
{
return wide;
}
/**
* Splits string on set of single char seperators.
*
* Consecutive separators are treated as separate and will emit empty strings.
*
* @param s string to split.
* @param sep seperator to split on.
* @param out start of the output range where separated strings are
* appended.
* @return The end of the output range where separated strings are appended.
*/
template <class CharT, class SepT, class OutIt>
auto split_on_any_of(const std::basic_string<CharT>& s, const SepT& sep,
OutIt out)
{
using size_type = typename std::basic_string<CharT>::size_type;
size_type i1 = 0;
size_type i2;
do {
i2 = s.find_first_of(sep, i1);
*out++ = s.substr(i1, i2 - i1);
i1 = i2 + 1; // we can only add +1 if sep is single char.
// i2 gets s.npos after the last separator.
// Length of i2-i1 will always go past the end. That is defined.
} while (i2 != s.npos);
return out;
}
/**
* Splits string on single char seperator.
*
* Consecutive separators are treated as separate and will emit empty strings.
*
* @param s string to split.
* @param sep char that acts as separator to split on.
* @param out start of the output range where separated strings are
* appended.
* @return The iterator that indicates the end of the output range.
*/
template <class CharT, class OutIt>
auto split(const std::basic_string<CharT>& s, CharT sep, OutIt out)
{
return split_on_any_of(s, sep, out);
}
/**
* Splits string on string separator.
*
* @param s string to split.
* @param sep seperator to split on.
* @param out start of the output range where separated strings are
* appended.
* @return The end of the output range where separated strings are appended.
*/
template <class CharT, class OutIt>
auto split(const std::basic_string<CharT>& s,
const std::basic_string<CharT>& sep, OutIt out)
{
using size_type = typename std::basic_string<CharT>::size_type;
size_type i1 = 0;
size_type i2;
do {
i2 = s.find(sep, i1);
*out++ = s.substr(i1, i2 - i1);
i1 = i2 + sep.size();
} while (i2 != s.npos);
return out;
}
/**
* Splits string on string separator.
*
* @param s string to split.
* @param sep seperator to split on.
* @param out start of the output range where separated strings are
* appended.
* @return The end of the output range where separated strings are appended.
*/
template <class CharT, class OutIt>
auto split(const std::basic_string<CharT>& s, const CharT* sep, OutIt out)
{
return split(s, std::basic_string<CharT>(sep), out);
}
/**
* Splits string on seperator, output to vector of strings.
*
* See split().
*
* @param s string to split.
* @param sep separator to split on.
* @param[out] v vector with separated strings. The vector is first cleared.
*/
template <class CharT, class CharOrStr>
auto split_v(const std::basic_string<CharT>& s, const CharOrStr& sep,
std::vector<std::basic_string<CharT>>& v)
{
v.clear();
split(s, sep, std::back_inserter(v));
}
/**
* Gets the first token of a splitted string.
*
* @param s string to split.
* @param sep char or string that acts as separator to split on.
* @return The string that has been split off.
*/
template <class CharT, class CharOrStr>
auto split_first(const std::basic_string<CharT>& s, const CharOrStr& sep)
-> std::basic_string<CharT>
{
auto index = s.find(sep);
return s.substr(0, index);
}
/**
* Splits on whitespace.
*
* Consecutive whitespace is treated as single separator. Behaves same as
* Python's split called without separator argument.
*
* @param s string to split.
* @param out start of the output range where separated strings are
* appended.
* @param loc locale object that takes care of what is whitespace.
* @return The iterator that indicates the end of the output range.
*/
template <class CharT, class OutIt>
auto split_on_whitespace(const std::basic_string<CharT>& s, OutIt out,
const std::locale& loc = std::locale()) -> OutIt
{
auto& f = std::use_facet<std::ctype<CharT>>(loc);
auto isspace = [&](auto& c) { return f.is(std::ctype_base::space, c); };
auto i1 = begin(s);
auto endd = end(s);
do {
auto i2 = std::find_if_not(i1, endd, isspace);
if (i2 == endd)
break;
auto i3 = std::find_if(i2, endd, isspace);
*out++ = std::basic_string<CharT>(i2, i3);
i1 = i3;
} while (i1 != endd);
return out;
}
/**
* Splits on whitespace, outputs to vector of strings.
*
* See split_on_whitespace().
*
* @param s string to split.
* @param[out] v vector with separated strings. The vector is first cleared.
* @param loc input locale.
*/
template <class CharT>
auto split_on_whitespace_v(const std::basic_string<CharT>& s,
std::vector<std::basic_string<CharT>>& v,
const std::locale& loc = std::locale()) -> void
{
v.clear();
split_on_whitespace(s, back_inserter(v), loc);
}
template <class CharT>
auto& erase_chars(std::basic_string<CharT>& s,
const std::basic_string<CharT>& erase_chars)
{
if (erase_chars.empty())
return s;
auto is_erasable = [&](CharT c) {
return erase_chars.find(c) != erase_chars.npos;
};
auto it = remove_if(begin(s), end(s), is_erasable);
s.erase(it, end(s));
return s;
}
/**
* Tests if word is a number.
*
* Allow numbers with dots ".", dashes "-" and commas ",", but forbids double
* separators such as "..", "--" and ".,". This results in increase of
* performance over an implementation with <regex> use.
*/
template <class CharT>
auto is_number(const std::basic_string<CharT>& s) -> bool
{
if (s.empty())
return false;
size_t i = 0;
if (s[0] == '-')
++i;
for (; i != s.size();) {
auto next =
s.find_first_not_of(LITERAL(CharT, "0123456789"), i);
if (next == i)
return false;
if (next == s.npos)
return true;
i = next;
auto c = s[i];
if (c == '.' || c == ',' || c == '-')
++i;
else
return false;
}
return false;
}
} // namespace nuspell
#endif // NUSPELL_STRING_UTILS_HXX
| 7,382 | 2,594 |
// +-------------------------------------------------------------------------
// | Copyright (C) 2017 Yunify, Inc.
// +-------------------------------------------------------------------------
// | Licensed under the Apache License, Version 2.0 (the "License");
// | You may not use this work except in compliance with the License.
// | You may obtain a copy of the License in the LICENSE file, or 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 "data/Node.h"
#include <assert.h>
#include <deque>
#include <set>
#include <string>
#include <utility>
#include "boost/foreach.hpp"
#include "boost/shared_ptr.hpp"
#include "base/LogMacros.h"
#include "base/StringUtils.h"
#include "base/Utils.h"
#include "data/FileMetaDataManager.h"
namespace QS {
namespace Data {
using boost::shared_ptr;
using QS::StringUtils::FormatPath;
using QS::Utils::AppendPathDelim;
using std::deque;
using std::pair;
using std::set;
using std::string;
// --------------------------------------------------------------------------
Node::Node(const Entry &entry, const shared_ptr<Node> &parent)
: m_entry(entry), m_parent(parent) {
m_children.clear();
}
// --------------------------------------------------------------------------
Node::Node(const Entry &entry, const shared_ptr<Node> &parent,
const string &symbolicLink)
: m_entry(entry), m_parent(parent) {
// must use m_entry instead of entry which is moved to m_entry now
if (m_entry && m_entry.GetFileSize() <= symbolicLink.size()) {
m_symbolicLink = string(symbolicLink, 0, m_entry.GetFileSize());
}
}
// --------------------------------------------------------------------------
Node::~Node() {
if (!m_entry) return;
if (IsDirectory()) {
shared_ptr<Node> parent = m_parent.lock();
if (parent) {
parent->GetEntry().DecreaseNumLink();
}
}
GetEntry().DecreaseNumLink();
if (m_entry.GetNumLink() <= 0 ||
(m_entry.GetNumLink() <= 1 && m_entry.IsDirectory())) {
FileMetaDataManager::Instance().Erase(GetFilePath());
}
}
// --------------------------------------------------------------------------
shared_ptr<Node> Node::Find(const string &childFileName) const {
ChildrenMapConstIterator child = m_children.find(childFileName);
if (child != m_children.end()) {
return child->second;
}
return shared_ptr<Node>();
}
// --------------------------------------------------------------------------
bool Node::HaveChild(const string &childFilePath) const {
return m_children.find(childFilePath) != m_children.end();
}
// --------------------------------------------------------------------------
const FilePathToNodeUnorderedMap &Node::GetChildren() const {
return m_children;
}
// --------------------------------------------------------------------------
FilePathToNodeUnorderedMap &Node::GetChildren() { return m_children; }
// --------------------------------------------------------------------------
set<string> Node::GetChildrenIds() const {
set<string> ids;
BOOST_FOREACH(const FilePathToNodeUnorderedMap::value_type &p, m_children) {
ids.insert(p.first);
}
return ids;
}
// --------------------------------------------------------------------------
deque<string> Node::GetDescendantIds() const {
deque<string> ids;
deque<shared_ptr<Node> > childs;
BOOST_FOREACH(const FilePathToNodeUnorderedMap::value_type &p, m_children) {
ids.push_back(p.first);
childs.push_back(p.second);
}
while (!childs.empty()) {
shared_ptr<Node> &child = childs.front();
childs.pop_front();
if (child->IsDirectory()) {
BOOST_FOREACH(const FilePathToNodeUnorderedMap::value_type &p,
child->GetChildren()) {
ids.push_back(p.first);
childs.push_back(p.second);
}
}
}
return ids;
}
// --------------------------------------------------------------------------
shared_ptr<Node> Node::Insert(const shared_ptr<Node> &child) {
assert(IsDirectory());
if (child) {
pair<ChildrenMapIterator, bool> res =
m_children.emplace(child->GetFilePath(), child);
if (res.second) {
if (child->IsDirectory()) {
m_entry.IncreaseNumLink();
}
} else {
DebugWarning("Node insertion failed " +
FormatPath(child->GetFilePath()));
}
} else {
DebugWarning("Try to insert null Node");
}
return child;
}
// --------------------------------------------------------------------------
void Node::Remove(const shared_ptr<Node> &child) {
if (child) {
Remove(child->GetFilePath());
} else {
DebugWarning("Try to remove null Node")
}
}
// --------------------------------------------------------------------------
void Node::Remove(const string &childFilePath) {
if (childFilePath.empty()) return;
bool reset = m_children.size() == 1 ? true : false;
ChildrenMapIterator it = m_children.find(childFilePath);
if (it != m_children.end()) {
m_children.erase(it);
if (reset) m_children.clear();
} else {
DebugWarning("Node not exist, no remove " + FormatPath(childFilePath));
}
}
// --------------------------------------------------------------------------
void Node::Rename(const string &newFilePath) {
if (m_entry) {
string oldFilePath = m_entry.GetFilePath();
if (oldFilePath == newFilePath) {
return;
}
if (m_children.find(newFilePath) != m_children.end()) {
DebugWarning("Cannot rename, target node already exist " +
FormatPath(oldFilePath, newFilePath));
return;
}
m_entry.Rename(newFilePath);
if (m_children.empty()) {
return;
}
deque<shared_ptr<Node> > childs;
BOOST_FOREACH(FilePathToNodeUnorderedMap::value_type &p, m_children) {
childs.push_back(p.second);
}
m_children.clear();
BOOST_FOREACH(shared_ptr<Node> &child, childs) {
string newPath = AppendPathDelim(newFilePath) + child->MyBaseName();
pair<ChildrenMapIterator, bool> res = m_children.emplace(newPath, child);
if (res.second) {
child->Rename(newPath);
} else {
DebugWarning("Node rename failed " +
FormatPath(child->GetFilePath()));
}
}
}
}
// --------------------------------------------------------------------------
void Node::RenameChild(const string &oldFilePath, const string &newFilePath) {
if (oldFilePath == newFilePath) {
DebugInfo("Same file name, no rename " + FormatPath(oldFilePath));
return;
}
if (m_children.find(newFilePath) != m_children.end()) {
DebugWarning("Cannot rename, target node already exist " +
FormatPath(oldFilePath, newFilePath));
return;
}
ChildrenMapIterator it = m_children.find(oldFilePath);
if (it != m_children.end()) {
shared_ptr<Node> &child = it->second;
child->Rename(newFilePath);
// Need to emplace before erase, otherwise the shared_ptr
// will probably get deleted when erasing cause its' reference
// count to be 0.
pair<ChildrenMapIterator, bool> res = m_children.emplace(newFilePath, child);
if (!res.second) {
DebugWarning("Fail to rename " + FormatPath(oldFilePath, newFilePath));
}
m_children.erase(it);
} else {
DebugWarning("Node not exist, no rename " + FormatPath(oldFilePath));
}
}
} // namespace Data
} // namespace QS
| 7,752 | 2,310 |
//===-- Physics/PMXMotionState.cpp - Defines a Motion State for PMX ----*- C++ -*-===//
//
// The XBeat Project
//
// This file is distributed under the University of Illinois Open Source License.
// See LICENSE.TXT for details.
//
//===-----------------------------------------------------------------------------===//
///
/// \file
/// \brief This file defines everything related to the Physics::PMXMotionState class,
/// which is an interface between bullet dynamics world and a PMX::Model.
///
//===-----------------------------------------------------------------------------===//
#include "../PMX/PMXBone.h"
#include "PMXMotionState.h"
Physics::PMXMotionState::PMXMotionState(PMX::Bone *AssociatedBone, const btTransform &InitialTransform)
{
assert(AssociatedBone != nullptr);
this->InitialTransform = InitialTransform;
this->AssociatedBone = AssociatedBone;
}
void Physics::PMXMotionState::getWorldTransform(btTransform &WorldTransform) const
{
WorldTransform = InitialTransform * AssociatedBone->getLocalTransform();
}
void Physics::PMXMotionState::setWorldTransform(const btTransform &WorldTransform)
{
}
| 1,144 | 320 |
#include "testlib.h"
using namespace std;
int main(int argc, char * argv[])
{
setName("compare sequences of tokens");
registerTestlibCmd(argc, argv);
int n = 0;
string j, p;
while (!ans.seekEof() && !ouf.seekEof())
{
n++;
ans.readWordTo(j);
ouf.readWordTo(p);
if (j != p)
quitf(_wa, "%d%s words differ - expected: '%s', found: '%s'", n, englishEnding(n).c_str(), compress(j).c_str(), compress(p).c_str());
}
if (ans.seekEof() && ouf.seekEof())
{
if (n == 1)
quitf(_ok, "\"%s\"", compress(j).c_str());
else
quitf(_ok, "%d tokens", n);
}
else
{
if (ans.seekEof())
quitf(_wa, "Participant output contains extra tokens");
else
quitf(_wa, "Unexpected EOF in the participants output");
}
}
| 876 | 322 |
// Copyright (c) 2019 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 "net/third_party/quiche/src/quic/quic_transport/quic_transport_server_session.h"
#include <memory>
#include "url/gurl.h"
#include "net/third_party/quiche/src/quic/core/quic_error_codes.h"
#include "net/third_party/quiche/src/quic/core/quic_stream.h"
#include "net/third_party/quiche/src/quic/core/quic_types.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_str_cat.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_string_piece.h"
#include "net/third_party/quiche/src/quic/quic_transport/quic_transport_protocol.h"
#include "net/third_party/quiche/src/quic/quic_transport/quic_transport_stream.h"
namespace quic {
namespace {
class QuicTransportServerCryptoHelper : public QuicCryptoServerStream::Helper {
public:
bool CanAcceptClientHello(const CryptoHandshakeMessage& /*message*/,
const QuicSocketAddress& /*client_address*/,
const QuicSocketAddress& /*peer_address*/,
const QuicSocketAddress& /*self_address*/,
std::string* /*error_details*/) const override {
return true;
}
};
} // namespace
QuicTransportServerSession::QuicTransportServerSession(
QuicConnection* connection,
Visitor* owner,
const QuicConfig& config,
const ParsedQuicVersionVector& supported_versions,
const QuicCryptoServerConfig* crypto_config,
QuicCompressedCertsCache* compressed_certs_cache,
ServerVisitor* visitor)
: QuicSession(connection,
owner,
config,
supported_versions,
/*num_expected_unidirectional_static_streams*/ 0),
visitor_(visitor) {
for (const ParsedQuicVersion& version : supported_versions) {
QUIC_BUG_IF(version.handshake_protocol != PROTOCOL_TLS1_3)
<< "QuicTransport requires TLS 1.3 handshake";
}
static QuicTransportServerCryptoHelper* helper =
new QuicTransportServerCryptoHelper();
crypto_stream_ = std::make_unique<QuicCryptoServerStream>(
crypto_config, compressed_certs_cache, this, helper);
}
QuicStream* QuicTransportServerSession::CreateIncomingStream(QuicStreamId id) {
if (id == ClientIndicationStream()) {
auto indication = std::make_unique<ClientIndication>(this);
ClientIndication* indication_ptr = indication.get();
ActivateStream(std::move(indication));
return indication_ptr;
}
auto stream = std::make_unique<QuicTransportStream>(id, this, this);
QuicTransportStream* stream_ptr = stream.get();
ActivateStream(std::move(stream));
return stream_ptr;
}
QuicTransportServerSession::ClientIndication::ClientIndication(
QuicTransportServerSession* session)
: QuicStream(ClientIndicationStream(),
session,
/* is_static= */ false,
StreamType::READ_UNIDIRECTIONAL),
session_(session) {}
void QuicTransportServerSession::ClientIndication::OnDataAvailable() {
sequencer()->Read(&buffer_);
if (buffer_.size() > ClientIndicationMaxSize()) {
session_->connection()->CloseConnection(
QUIC_TRANSPORT_INVALID_CLIENT_INDICATION,
QuicStrCat("Client indication size exceeds ", ClientIndicationMaxSize(),
" bytes"),
ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
return;
}
if (sequencer()->IsClosed()) {
session_->ProcessClientIndication(buffer_);
OnFinRead();
}
}
bool QuicTransportServerSession::ClientIndicationParser::Parse() {
bool origin_received = false;
while (!reader_.IsDoneReading()) {
uint16_t key;
if (!reader_.ReadUInt16(&key)) {
ParseError("Expected 16-bit key");
return false;
}
QuicStringPiece value;
if (!reader_.ReadStringPiece16(&value)) {
ParseError(QuicStrCat("Failed to read value for key ", key));
return false;
}
switch (static_cast<QuicTransportClientIndicationKeys>(key)) {
case QuicTransportClientIndicationKeys::kOrigin: {
GURL origin_url{std::string(value)};
if (!origin_url.is_valid()) {
Error("Unable to parse the specified origin");
return false;
}
url::Origin origin = url::Origin::Create(origin_url);
QUIC_DLOG(INFO) << "QuicTransport server received origin " << origin;
if (!session_->visitor_->CheckOrigin(origin)) {
Error("Origin check failed");
return false;
}
origin_received = true;
break;
}
default:
QUIC_DLOG(INFO) << "Unknown client indication key: " << key;
break;
}
}
if (!origin_received) {
Error("No origin received");
return false;
}
return true;
}
void QuicTransportServerSession::ClientIndicationParser::Error(
const std::string& error_message) {
session_->connection()->CloseConnection(
QUIC_TRANSPORT_INVALID_CLIENT_INDICATION, error_message,
ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
}
void QuicTransportServerSession::ClientIndicationParser::ParseError(
QuicStringPiece error_message) {
Error(QuicStrCat("Failed to parse the client indication stream: ",
error_message, reader_.DebugString()));
}
void QuicTransportServerSession::ProcessClientIndication(
QuicStringPiece indication) {
ClientIndicationParser parser(this, indication);
if (!parser.Parse()) {
return;
}
// Don't set the ready bit if we closed the connection due to any error
// beforehand.
if (!connection()->connected()) {
return;
}
ready_ = true;
}
} // namespace quic
| 5,753 | 1,783 |
#include"Animal.h"
Animal::Animal(int health){
this->health=health;
}
void Animal::eat(Food& f,int quantity){
health+=f.eat(quantity);
};
int Animal::getHealth()const{
return health;
};
| 191 | 80 |
#ifndef PYTHONIC_NUMPY_ARGMINMAX_HPP
#define PYTHONIC_NUMPY_ARGMINMAX_HPP
#include "pythonic/utils/functor.hpp"
#include "pythonic/types/ndarray.hpp"
#include "pythonic/numpy/asarray.hpp"
#include "pythonic/builtins/ValueError.hpp"
PYTHONIC_NS_BEGIN
namespace numpy
{
namespace details
{
template <class P, size_t... Is>
P iota(utils::index_sequence<Is...>)
{
return {static_cast<typename P::value_type>(Is)...};
}
template <class P>
P iota()
{
return iota<P>(utils::make_index_sequence<P::size>());
}
}
template <class Op, class E, class T>
long _argminmax_seq(E const &elts, T &minmax_elts)
{
long index = 0;
long res = -1;
for (auto const &elt : elts) {
if (Op::value(elt, minmax_elts)) {
minmax_elts = elt;
res = index;
}
++index;
}
return res;
}
template <class Op, class E, class T>
#ifdef USE_XSIMD
typename std::enable_if<
!E::is_vectorizable ||
!types::is_vector_op<typename Op::op, T, T>::value ||
std::is_same<typename E::dtype, bool>::value,
long>::type
#else
long
#endif
_argminmax(E const &elts, T &minmax_elts, utils::int_<1>)
{
return _argminmax_seq<Op>(elts, minmax_elts);
}
template <class Op, class E, class T, class... Indices>
std::tuple<long, long> _argminmax_fast(E const &elts, T &minmax_elts,
long current_pos, utils::int_<1>,
Indices... indices)
{
long res = -1;
long n = elts.template shape<std::decay<E>::type::value - 1>();
for (long i = 0; i < n; ++i) {
auto elt = elts.load(indices..., i);
if (Op::value(elt, minmax_elts)) {
minmax_elts = elt;
res = current_pos + i;
}
}
return std::make_tuple(res, current_pos + n);
}
#ifdef USE_XSIMD
template <bool IsInt>
struct bool_caster;
template <>
struct bool_caster<true> {
template <class T>
auto operator()(T const &value) -> decltype(xsimd::bool_cast(value))
{
return xsimd::bool_cast(value);
}
};
template <>
struct bool_caster<false> {
template <class T>
T operator()(T const &value)
{
return value;
}
};
template <class Op, class E, class T>
typename std::enable_if<
E::is_vectorizable && types::is_vector_op<typename Op::op, T, T>::value &&
!std::is_same<typename E::dtype, bool>::value,
long>::type
_argminmax(E const &elts, T &minmax_elts, utils::int_<1>)
{
using vT = xsimd::simd_type<T>;
using iT = xsimd::as_integer_t<T>;
static const size_t vN = vT::size;
const long n = elts.size();
if (n >= std::numeric_limits<iT>::max()) {
return _argminmax_seq<Op>(elts, minmax_elts);
}
auto viter = types::vectorizer_nobroadcast::vbegin(elts),
vend = types::vectorizer_nobroadcast::vend(elts);
const long bound = std::distance(viter, vend);
long minmax_index = -1;
if (bound > 0) {
auto vacc = *viter;
iT iota[vN] = {0};
for (long i = 0; i < vN; ++i)
iota[i] = i;
auto curr = xsimd::load_unaligned(iota);
xsimd::simd_type<iT> indices = curr;
xsimd::simd_type<iT> step{vN};
for (++viter; viter != vend; ++viter) {
curr += step;
auto c = *viter;
vacc = typename Op::op{}(vacc, c);
auto mask = c == vacc;
indices =
xsimd::select(bool_caster<std::is_floating_point<T>::value>{}(mask),
curr, indices);
}
alignas(sizeof(vT)) T stored[vN];
vacc.store_aligned(&stored[0]);
alignas(sizeof(vT)) long indexed[vN];
indices.store_aligned(&indexed[0]);
for (size_t j = 0; j < vN; ++j) {
if (Op::value(stored[j], minmax_elts)) {
minmax_elts = stored[j];
minmax_index = indexed[j];
}
}
}
auto iter = elts.begin() + bound * vN;
for (long i = bound * vN; i < n; ++i, ++iter) {
if (Op::value(*iter, minmax_elts)) {
minmax_elts = *iter;
minmax_index = i;
}
}
return minmax_index;
}
#endif
template <class Op, class E, size_t N, class T>
long _argminmax(E const &elts, T &minmax_elts, utils::int_<N>)
{
long current_pos = 0;
long current_minmaxarg = 0;
for (auto &&elt : elts) {
long v = _argminmax<Op>(elt, minmax_elts, utils::int_<N - 1>());
if (v >= 0)
current_minmaxarg = current_pos + v;
current_pos += elt.flat_size();
}
return current_minmaxarg;
}
template <class Op, class E, size_t N, class T, class... Indices>
typename std::enable_if<N != 1, std::tuple<long, long>>::type
_argminmax_fast(E const &elts, T &minmax_elts, long current_pos,
utils::int_<N>, Indices... indices)
{
long current_minmaxarg = 0;
for (long i = 0, n = elts.template shape<std::decay<E>::type::value - N>();
i < n; ++i) {
long v;
std::tie(v, current_pos) = _argminmax_fast<Op>(
elts, minmax_elts, current_pos, utils::int_<N - 1>(), indices..., i);
if (v >= 0)
current_minmaxarg = v;
}
return std::make_tuple(current_minmaxarg, current_pos);
}
template <class Op, class E>
long argminmax(E const &expr)
{
if (!expr.flat_size())
throw types::ValueError("empty sequence");
using elt_type = typename E::dtype;
elt_type argminmax_value = Op::limit();
#ifndef USE_XSIMD
if (utils::no_broadcast_ex(expr)) {
return std::get<0>(_argminmax_fast<Op>(expr, argminmax_value, 0,
utils::int_<E::value>()));
} else
#endif
return _argminmax<Op>(expr, argminmax_value, utils::int_<E::value>());
}
template <class Op, size_t Dim, size_t Axis, class T, class E, class V>
void _argminmax_tail(T &out, E const &expr, long curr, V &curr_minmax,
std::integral_constant<size_t, 0>)
{
if (Op::value(expr, curr_minmax)) {
out = curr;
curr_minmax = expr;
}
}
template <class Op, size_t Dim, size_t Axis, class T, class E, class V,
size_t N>
typename std::enable_if<Axis != (Dim - N), void>::type
_argminmax_tail(T &&out, E const &expr, long curr, V &&curr_minmax,
std::integral_constant<size_t, N>)
{
static_assert(N >= 1, "specialization ok");
for (long i = 0, n = expr.template shape<0>(); i < n; ++i)
_argminmax_tail<Op, Dim, Axis>(out.fast(i), expr.fast(i), curr,
curr_minmax.fast(i),
std::integral_constant<size_t, N - 1>());
}
template <class Op, size_t Dim, size_t Axis, class T, class E>
typename std::enable_if<Axis == (Dim - 1), void>::type
_argminmax_head(T &&out, E const &expr, std::integral_constant<size_t, 1>)
{
typename E::dtype val = Op::limit();
for (long i = 0, n = expr.template shape<0>(); i < n; ++i)
_argminmax_tail<Op, Dim, Axis>(std::forward<T>(out), expr.fast(i), i, val,
std::integral_constant<size_t, 0>());
}
template <class Op, size_t Dim, size_t Axis, class T, class E, size_t N>
typename std::enable_if<Axis == (Dim - N), void>::type
_argminmax_head(T &&out, E const &expr, std::integral_constant<size_t, N>)
{
static_assert(N > 1, "specialization ok");
types::ndarray<typename E::dtype, types::array<long, N - 1>> val{
sutils::getshape(out), Op::limit()};
for (long i = 0, n = expr.template shape<0>(); i < n; ++i)
_argminmax_tail<Op, Dim, Axis>(std::forward<T>(out), expr.fast(i), i, val,
std::integral_constant<size_t, N - 1>());
}
template <class Op, size_t Dim, size_t Axis, class T, class E, size_t N>
typename std::enable_if<Axis != (Dim - N), void>::type
_argminmax_head(T &&out, E const &expr, std::integral_constant<size_t, N>)
{
static_assert(N >= 1, "specialization ok");
for (long i = 0, n = expr.template shape<0>(); i < n; ++i)
_argminmax_head<Op, Dim, Axis>(out.fast(i), expr.fast(i),
std::integral_constant<size_t, N - 1>());
}
template <class Op, size_t N, class T, class E, size_t... Axis>
void _argminmax_pick_axis(long axis, T &out, E const &expr,
utils::index_sequence<Axis...>)
{
std::initializer_list<bool>{
((Axis == axis) && (_argminmax_head<Op, N, Axis>(
out, expr, std::integral_constant<size_t, N>()),
true))...};
}
template <class Op, class E>
types::ndarray<long, types::array<long, E::value - 1>>
argminmax(E const &array, long axis)
{
if (axis < 0)
axis += E::value;
if (axis < 0 || size_t(axis) >= E::value)
throw types::ValueError("axis out of bounds");
auto shape = sutils::getshape(array);
types::array<long, E::value - 1> shp;
auto next = std::copy(shape.begin(), shape.begin() + axis, shp.begin());
std::copy(shape.begin() + axis + 1, shape.end(), next);
types::ndarray<long, types::array<long, E::value - 1>> out{shp,
builtins::None};
typename E::dtype curr_minmax;
_argminmax_pick_axis<Op, E::value>(axis, out, array,
utils::make_index_sequence<E::value>());
return out;
}
}
PYTHONIC_NS_END
#endif
| 9,491 | 3,521 |
class Solution {
public:
int maxProfit(vector<int>& prices) {
int cost = INT_MAX, sell=0;
for(int i:prices)
{
cost = min(cost,i);
sell = max(sell,i-cost) ;
}
return sell ;
}
}; | 266 | 88 |
/**
* @file timer.h
* @brief 中断抽象头文件
* @author Zone.N (Zone.Niuzh@hotmail.com)
* @version 1.0
* @date 2021-09-18
* @copyright MIT LICENSE
* https://github.com/Simple-XX/SimpleKernel
* @par change log:
* <table>
* <tr><th>Date<th>Author<th>Description
* <tr><td>2021-09-18<td>digmouse233<td>迁移到 doxygen
* </table>
*/
#include "stdint.h"
#include "stdio.h"
#include "cpu.hpp"
#include "opensbi.h"
#include "intr.h"
/// timer interrupt interval
/// @todo 从 dts 读取
static constexpr const uint64_t INTERVAL = 390000000 / 20;
/**
* @brief 设置下一次时钟
*/
void set_next(void) {
// 调用 opensbi 提供的接口设置时钟
OPENSBI::set_timer(CPU::READ_TIME() + INTERVAL);
return;
}
/**
* @brief 时钟中断
*/
void timer_intr(void) {
// 每次执行中断时设置下一次中断的时间
set_next();
return;
}
void TIMER::init(void) {
// 注册中断函数
CLINT::register_interrupt_handler(CLINT::INTR_S_TIMER, timer_intr);
// 设置初次中断
OPENSBI::set_timer(CPU::READ_TIME());
// 开启时钟中断
CPU::WRITE_SIE(CPU::READ_SIE() | CPU::SIE_STIE);
info("timer init.\n");
return;
}
| 1,059 | 537 |
#include <iostream>
#include <vector>
#include <string>
#include <math.h>
using namespace std;
int main() {
/*int N, M, D;
cin >> N >> M >> D;
cout << N << " " << M << " " << D << endl;*/
cout << "Type your message:" << endl;
cin.ignore();
string x;
getline(cin, x);
int length = x.length();
cout << length << endl;
vector<char> my_vector;
for (int i = 0; i < length; i++) {
my_vector.push_back(x[i]);
}
for (int j = 0; j < length; j++) {
cout << my_vector[j] << endl;
}
} | 502 | 217 |
// Copyright 2020 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/exo/ui_lock_controller.h"
#include "ash/constants/ash_features.h"
#include "ash/public/cpp/app_types.h"
#include "ash/wm/window_state.h"
#include "base/feature_list.h"
#include "base/optional.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "chromeos/ui/base/window_properties.h"
#include "components/exo/seat.h"
#include "components/exo/shell_surface_util.h"
#include "components/exo/surface.h"
#include "components/exo/ui_lock_bubble.h"
#include "components/exo/wm_helper.h"
#include "ui/aura/client/aura_constants.h"
#include "ui/aura/window.h"
#include "ui/events/event_constants.h"
#include "ui/events/keycodes/dom/dom_code.h"
#include "ui/views/widget/widget.h"
namespace exo {
constexpr auto kLongPressEscapeDuration = base::TimeDelta::FromSeconds(2);
constexpr auto kExcludedFlags = ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN |
ui::EF_ALT_DOWN | ui::EF_COMMAND_DOWN |
ui::EF_ALTGR_DOWN | ui::EF_IS_REPEAT;
UILockController::UILockController(Seat* seat) : seat_(seat) {
WMHelper::GetInstance()->AddPreTargetHandler(this);
seat_->AddObserver(this);
}
UILockController::~UILockController() {
seat_->RemoveObserver(this);
WMHelper::GetInstance()->RemovePreTargetHandler(this);
if (bubble_widget_) {
bubble_widget_->CloseWithReason(views::Widget::ClosedReason::kUnspecified);
bubble_widget_ = nullptr;
}
}
void UILockController::OnKeyEvent(ui::KeyEvent* event) {
// TODO(oshima): Rather than handling key event here, add a hook in
// keyboard.cc to intercept key event and handle this.
// If no surface is focused, let another handler process the event.
aura::Window* window = static_cast<aura::Window*>(event->target());
if (!GetTargetSurfaceForKeyboardFocus(window))
return;
if (event->code() == ui::DomCode::ESCAPE &&
(event->flags() & kExcludedFlags) == 0) {
OnEscapeKey(event->type() == ui::ET_KEY_PRESSED);
}
}
void UILockController::OnSurfaceFocused(Surface* gained_focus) {
if (gained_focus != focused_surface_to_unlock_)
StopTimer();
if (!base::FeatureList::IsEnabled(chromeos::features::kExoLockNotification))
return;
if (!gained_focus || !gained_focus->window())
return;
views::Widget* top_level_widget =
views::Widget::GetTopLevelWidgetForNativeView(gained_focus->window());
aura::Window* native_window =
top_level_widget ? top_level_widget->GetNativeWindow() : nullptr;
ash::WindowState* window_state = ash::WindowState::Get(native_window);
// If the window is not fullscreen do not display.
if (!window_state || !window_state->IsFullscreen())
return;
// If the bubble exists and is already anchored to the current view then exit.
if (bubble_widget_ && bubble_widget_->parent()->GetContentsView() ==
top_level_widget->GetContentsView()) {
return;
}
// If the bubble exists and is anchored to a different surface, destroy that
// bubble before creating a new one.
if (bubble_widget_ && bubble_widget_->parent()->GetContentsView() !=
top_level_widget->GetContentsView()) {
bubble_widget_->CloseWithReason(views::Widget::ClosedReason::kUnspecified);
bubble_widget_ = nullptr;
}
bubble_widget_ =
UILockBubbleView::DisplayBubble(top_level_widget->GetContentsView());
}
void UILockController::OnPostWindowStateTypeChange(
ash::WindowState* window_state,
chromeos::WindowStateType old_type) {
// If the window is no longer fullscreen and there is a bubble showing, close
// it.
if (!window_state->IsFullscreen() && bubble_widget_) {
bubble_widget_->CloseWithReason(views::Widget::ClosedReason::kUnspecified);
bubble_widget_ = nullptr;
}
}
views::Widget* UILockController::GetBubbleForTesting() {
return bubble_widget_;
}
namespace {
bool EscapeHoldShouldExitFullscreen(Seat* seat) {
auto* surface = seat->GetFocusedSurface();
if (!surface)
return false;
auto* widget =
views::Widget::GetTopLevelWidgetForNativeView(surface->window());
if (!widget)
return false;
aura::Window* window = widget->GetNativeWindow();
if (!window || !window->GetProperty(chromeos::kEscHoldToExitFullscreen)) {
return false;
}
auto* window_state = ash::WindowState::Get(window);
return window_state && window_state->IsFullscreen();
}
} // namespace
void UILockController::OnEscapeKey(bool pressed) {
if (pressed) {
if (EscapeHoldShouldExitFullscreen(seat_) &&
!exit_fullscreen_timer_.IsRunning()) {
focused_surface_to_unlock_ = seat_->GetFocusedSurface();
exit_fullscreen_timer_.Start(
FROM_HERE, kLongPressEscapeDuration,
base::BindOnce(&UILockController::OnEscapeHeld,
base::Unretained(this)));
}
} else {
StopTimer();
}
}
void UILockController::OnEscapeHeld() {
auto* surface = seat_->GetFocusedSurface();
if (!surface || surface != focused_surface_to_unlock_) {
focused_surface_to_unlock_ = nullptr;
return;
}
if (bubble_widget_) {
bubble_widget_->CloseWithReason(views::Widget::ClosedReason::kUnspecified);
bubble_widget_ = nullptr;
}
focused_surface_to_unlock_ = nullptr;
auto* widget =
views::Widget::GetTopLevelWidgetForNativeView(surface->window());
auto* window_state =
ash::WindowState::Get(widget ? widget->GetNativeWindow() : nullptr);
if (window_state) {
if (window_state->window()->GetProperty(
chromeos::kEscHoldExitFullscreenToMinimized)) {
window_state->Minimize();
} else {
window_state->Restore();
}
}
}
void UILockController::StopTimer() {
if (exit_fullscreen_timer_.IsRunning()) {
exit_fullscreen_timer_.Stop();
focused_surface_to_unlock_ = nullptr;
}
}
} // namespace exo
| 6,003 | 1,998 |
#include "sdk/object/entity.hpp"
#include "sdk/object/weapon.hpp"
#include "csgo/engine.hpp"
C_BaseEntity* C_BaseEntity::GetBaseEntity( const int index )
{
const auto client_entity = csgo::m_client_entity_list->GetClientEntity( index );
return (client_entity ? client_entity->GetBaseEntity() : nullptr);
}
C_BaseEntity* C_BaseEntity::GetBaseEntityFromHandle( const CBaseHandle base_handle )
{
const auto client_entity = csgo::m_client_entity_list->GetClientEntityFromHandle( base_handle );
return (client_entity ? client_entity->GetBaseEntity() : nullptr);
}
void C_BaseEntity::SetPredictionSeed(CUserCmd* cmd)
{
static auto m_pPredictionRandomSeed = memory::scan< int* >(XorStr("client.dll"), XorStr("8B 0D ? ? ? ? BA ? ? ? ? E8 ? ? ? ? 83 C4 04"), 2, 1u);
if (cmd)
*m_pPredictionRandomSeed = cmd->random_seed;
else
*m_pPredictionRandomSeed = -1;
}
bool C_BaseAnimating::GetBoneTransform(matrix3x4_t* output, float time /*= 0.f*/)
{
return SetupBones(output, 128, 256, time);
}
bool C_BaseAnimating::GetBonePosition( matrix3x4_t* bone_transform, const int bone, Vector& output )
{
if( bone_transform )
{
for( auto i = 0; i < 3; i++ )
output[ i ] = bone_transform[ bone ][ i ][ 3 ];
}
return ( !output.IsZero() && output.IsValid() );
}
bool C_BaseAnimating::GetBoneWorld(int index, matrix3x4_t* transform, Vector& output)
{
if (transform)
{
for (auto i = 0; i < 3; i++)
output[i] = transform[index][i][3];
}
return !output.IsZero();
}
bool C_BaseAnimating::GetBoxBoundWorld(int index, matrix3x4_t* transform, Vector& min, Vector& max)
{
if (transform)
{
auto model = GetModel();
if (model)
{
auto studio = csgo::m_model_info_client->GetStudioModel(model);
if (studio)
{
auto box = studio->pHitbox(index, m_nHitboxSet());
if (box)
{
min = box->bbmin.Transform(transform[box->bone]);
max = box->bbmax.Transform(transform[box->bone]);
}
}
}
}
return (!min.IsZero() && !max.IsZero());
}
bool C_BaseAnimating::GetBoxWorld(int index, matrix3x4_t* transform, Vector& output)
{
Vector min = { };
Vector max = { };
if (GetBoxBoundWorld(index, transform, min, max))
output = (min + max) * 0.5f;
return !output.IsZero();
}
bool C_BaseAnimating::GetHitboxVector(int hitbox, Vector& out)
{
matrix3x4_t mat[128];
if (!GetBoneTransform(mat))
return false;
auto studio = csgo::m_model_info_client->GetStudioModel(GetModel());
if (!studio)
return false;
auto set = studio->pHitboxSet(m_nHitboxSet());
if (!set)
return false;
auto box = set->pHitbox(hitbox);
if (!box)
return false;
Vector mins = { }, maxs = { };
mins = box->bbmin.Transform(mat[box->bone]);
maxs = box->bbmax.Transform(mat[box->bone]);
if (mins.IsZero() || maxs.IsZero())
return false;
out = (mins + maxs) * 0.5f;
return !(out.IsZero());
}
Vector C_BaseAnimating::GetHitboxPosition(int index)
{
matrix3x4_t transform[128] = { };
if (!GetBoneTransform(transform))
return Vector::Zero;
Vector position = { };
if (!GetBoxWorld(index, transform, position))
return Vector::Zero;
return position;
}
C_BaseViewModel* C_BaseAttributeItem::GetBaseModel()
{
auto base_model = reinterpret_cast<C_BaseViewModel*>(this);
return base_model;
}
| 3,235 | 1,315 |
#pragma once
#include "../../JObject.hpp"
class JObject;
namespace android::media
{
class MediaCodecInfo_CodecProfileLevel : public JObject
{
public:
// Fields
static jint AACObjectELD();
static jint AACObjectERLC();
static jint AACObjectERScalable();
static jint AACObjectHE();
static jint AACObjectHE_PS();
static jint AACObjectLC();
static jint AACObjectLD();
static jint AACObjectLTP();
static jint AACObjectMain();
static jint AACObjectSSR();
static jint AACObjectScalable();
static jint AACObjectXHE();
static jint AVCLevel1();
static jint AVCLevel11();
static jint AVCLevel12();
static jint AVCLevel13();
static jint AVCLevel1b();
static jint AVCLevel2();
static jint AVCLevel21();
static jint AVCLevel22();
static jint AVCLevel3();
static jint AVCLevel31();
static jint AVCLevel32();
static jint AVCLevel4();
static jint AVCLevel41();
static jint AVCLevel42();
static jint AVCLevel5();
static jint AVCLevel51();
static jint AVCLevel52();
static jint AVCProfileBaseline();
static jint AVCProfileConstrainedBaseline();
static jint AVCProfileConstrainedHigh();
static jint AVCProfileExtended();
static jint AVCProfileHigh();
static jint AVCProfileHigh10();
static jint AVCProfileHigh422();
static jint AVCProfileHigh444();
static jint AVCProfileMain();
static jint DolbyVisionLevelFhd24();
static jint DolbyVisionLevelFhd30();
static jint DolbyVisionLevelFhd60();
static jint DolbyVisionLevelHd24();
static jint DolbyVisionLevelHd30();
static jint DolbyVisionLevelUhd24();
static jint DolbyVisionLevelUhd30();
static jint DolbyVisionLevelUhd48();
static jint DolbyVisionLevelUhd60();
static jint DolbyVisionProfileDvavPen();
static jint DolbyVisionProfileDvavPer();
static jint DolbyVisionProfileDvavSe();
static jint DolbyVisionProfileDvheDen();
static jint DolbyVisionProfileDvheDer();
static jint DolbyVisionProfileDvheDtb();
static jint DolbyVisionProfileDvheDth();
static jint DolbyVisionProfileDvheDtr();
static jint DolbyVisionProfileDvheSt();
static jint DolbyVisionProfileDvheStn();
static jint H263Level10();
static jint H263Level20();
static jint H263Level30();
static jint H263Level40();
static jint H263Level45();
static jint H263Level50();
static jint H263Level60();
static jint H263Level70();
static jint H263ProfileBackwardCompatible();
static jint H263ProfileBaseline();
static jint H263ProfileH320Coding();
static jint H263ProfileHighCompression();
static jint H263ProfileHighLatency();
static jint H263ProfileISWV2();
static jint H263ProfileISWV3();
static jint H263ProfileInterlace();
static jint H263ProfileInternet();
static jint HEVCHighTierLevel1();
static jint HEVCHighTierLevel2();
static jint HEVCHighTierLevel21();
static jint HEVCHighTierLevel3();
static jint HEVCHighTierLevel31();
static jint HEVCHighTierLevel4();
static jint HEVCHighTierLevel41();
static jint HEVCHighTierLevel5();
static jint HEVCHighTierLevel51();
static jint HEVCHighTierLevel52();
static jint HEVCHighTierLevel6();
static jint HEVCHighTierLevel61();
static jint HEVCHighTierLevel62();
static jint HEVCMainTierLevel1();
static jint HEVCMainTierLevel2();
static jint HEVCMainTierLevel21();
static jint HEVCMainTierLevel3();
static jint HEVCMainTierLevel31();
static jint HEVCMainTierLevel4();
static jint HEVCMainTierLevel41();
static jint HEVCMainTierLevel5();
static jint HEVCMainTierLevel51();
static jint HEVCMainTierLevel52();
static jint HEVCMainTierLevel6();
static jint HEVCMainTierLevel61();
static jint HEVCMainTierLevel62();
static jint HEVCProfileMain();
static jint HEVCProfileMain10();
static jint HEVCProfileMain10HDR10();
static jint HEVCProfileMainStill();
static jint MPEG2LevelH14();
static jint MPEG2LevelHL();
static jint MPEG2LevelHP();
static jint MPEG2LevelLL();
static jint MPEG2LevelML();
static jint MPEG2Profile422();
static jint MPEG2ProfileHigh();
static jint MPEG2ProfileMain();
static jint MPEG2ProfileSNR();
static jint MPEG2ProfileSimple();
static jint MPEG2ProfileSpatial();
static jint MPEG4Level0();
static jint MPEG4Level0b();
static jint MPEG4Level1();
static jint MPEG4Level2();
static jint MPEG4Level3();
static jint MPEG4Level3b();
static jint MPEG4Level4();
static jint MPEG4Level4a();
static jint MPEG4Level5();
static jint MPEG4Level6();
static jint MPEG4ProfileAdvancedCoding();
static jint MPEG4ProfileAdvancedCore();
static jint MPEG4ProfileAdvancedRealTime();
static jint MPEG4ProfileAdvancedScalable();
static jint MPEG4ProfileAdvancedSimple();
static jint MPEG4ProfileBasicAnimated();
static jint MPEG4ProfileCore();
static jint MPEG4ProfileCoreScalable();
static jint MPEG4ProfileHybrid();
static jint MPEG4ProfileMain();
static jint MPEG4ProfileNbit();
static jint MPEG4ProfileScalableTexture();
static jint MPEG4ProfileSimple();
static jint MPEG4ProfileSimpleFBA();
static jint MPEG4ProfileSimpleFace();
static jint MPEG4ProfileSimpleScalable();
static jint VP8Level_Version0();
static jint VP8Level_Version1();
static jint VP8Level_Version2();
static jint VP8Level_Version3();
static jint VP8ProfileMain();
static jint VP9Level1();
static jint VP9Level11();
static jint VP9Level2();
static jint VP9Level21();
static jint VP9Level3();
static jint VP9Level31();
static jint VP9Level4();
static jint VP9Level41();
static jint VP9Level5();
static jint VP9Level51();
static jint VP9Level52();
static jint VP9Level6();
static jint VP9Level61();
static jint VP9Level62();
static jint VP9Profile0();
static jint VP9Profile1();
static jint VP9Profile2();
static jint VP9Profile2HDR();
static jint VP9Profile3();
static jint VP9Profile3HDR();
jint level();
jint profile();
// QJniObject forward
template<typename ...Ts> explicit MediaCodecInfo_CodecProfileLevel(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {}
MediaCodecInfo_CodecProfileLevel(QJniObject obj);
// Constructors
MediaCodecInfo_CodecProfileLevel();
// Methods
jboolean equals(JObject arg0) const;
jint hashCode() const;
};
} // namespace android::media
| 6,296 | 2,523 |
/**
* MXS-1947: Composite roles are not supported
*
* https://jira.mariadb.org/browse/MXS-1947
*/
#include <maxtest/testconnections.hh>
int main(int argc, char** argv)
{
TestConnections test(argc, argv);
test.repl->connect();
auto prepare =
{
"DROP USER test@'%'",
"CREATE USER test@'%' IDENTIFIED BY 'test';",
"CREATE ROLE a;",
"CREATE ROLE b;",
"CREATE DATABASE db;",
"GRANT ALL ON db.* TO a;",
"GRANT a TO b;",
"GRANT b TO test@'%';",
"SET DEFAULT ROLE b FOR test@'%';"
};
for (auto a : prepare)
{
execute_query_silent(test.repl->nodes[0], a);
}
// Wait for the users to replicate
test.repl->sync_slaves();
test.tprintf("Connect with a user that has a composite role as the default role");
MYSQL* conn = open_conn_db(test.maxscales->rwsplit_port[0], test.maxscales->ip4(), "db", "test", "test");
test.expect(mysql_errno(conn) == 0, "Connection failed: %s", mysql_error(conn));
mysql_close(conn);
auto cleanup =
{
"DROP DATABASE IF EXISTS db;",
"DROP ROLE IF EXISTS a;",
"DROP ROLE IF EXISTS b;",
"DROP USER 'test'@'%';"
};
for (auto a : cleanup)
{
execute_query_silent(test.repl->nodes[0], a);
}
return test.global_result;
}
| 1,346 | 502 |
#include "Shared.h"
#include "DictionaryReader.h"
#include <string>
#include <fstream>
namespace
{
void Trim( std::string &str )
{
size_t charPos = str.find_first_not_of( " \n" );
if ( charPos != std::string::npos ) {
str.erase( 0, charPos );
}
charPos = str.find_last_not_of( " \n" );
if ( charPos != std::string::npos ) {
str.erase( charPos + 1 );
}
}
}
const int Io_ReadDictionaryFile( const char* fileName, dictionary_t& dico )
{
std::ifstream fStream( fileName );
if ( fStream.is_open() ) {
std::string fLine = "",
dicoKey = "",
dicoVal = "";
while ( fStream.good() ) {
std::getline( fStream, fLine );
const size_t separator = fLine.find_first_of( ':' );
const size_t commentSep = fLine.find_first_of( ';' );
if ( commentSep != -1 ) {
fLine.erase( fLine.begin() + commentSep, fLine.end() );
}
if ( !fLine.empty() && separator != std::string::npos ) {
dicoKey = fLine.substr( 0, separator );
dicoVal = fLine.substr( separator + 1 );
Trim( dicoKey );
Trim( dicoVal );
if ( !dicoVal.empty() ) {
dico.insert( std::make_pair( dicoKey, dicoVal ) );
}
}
}
} else {
return 1;
}
fStream.close();
return 0;
}
| 1,221 | 552 |
#include "main.h"
int main(){
Pessoa Joao, Cleide, Claudo;
Joao.setId(1);
Joao.setIdade(10);
Joao.setSexo(true);
Joao.setUsaOculos(false);
Joao.copy(Joao);
std::cout << Cleide.getId() << std::endl;
std::cout << Joao.getIdade() << std::endl;
Produto cadeira, ventilador, amplificador;
cadeira.fill();
cadeira.setEstoque(10);
cadeira.show();
return 0;
} | 412 | 180 |
#include <iostream>
#include <stdint.h>
using namespace std;
class A
{
int32_t a;
};
class B: public A
{
int32_t a;
};
int main()
{
cout << "sizeof(A): " << sizeof(A) << endl; // Печатает 4.
// Печатает 8, так как содержит в том числе родительские члены.
cout << "sizeof(B): " << sizeof(B) << endl;
}
| 325 | 146 |
#pragma once
#include "sub0pub/sub0pub.hpp"
#if Sub0Pub_CrossModule_Publisher_EXPORTS
#define DLLEXPORT __declspec(dllexport)
#define DLLEXTERN
#else
#define DLLEXPORT __declspec(dllimport)
#define DLLEXTERN extern
#endif
// @note Exporting the broker is critical for the instance to become shared across DLL module boundaries
DLLEXTERN template class DLLEXPORT sub0::Broker<float>;
DLLEXTERN template class DLLEXPORT sub0::Broker<int>;
#include "sub0pub/sub0pub.hpp"
DLLEXPORT void doPublisher(); | 506 | 188 |
/*
bullet.cpp
Aron Lebani
29 March 2016
*/
#include "../include/character.h"
#include "../include/bullet.h"
#include "../include/tools.h"
bullet::bullet()
{
width = 13;
height = 2;
}
void bullet::draw()
{
tools::printw(getY() , getX(), " x ");
tools::printw(getY()+1, getX(), " x ");
}
void bullet::erase()
{
int i, j;
for (i=0; i<height; i++)
{
for (j=0; j<width; j++)
{
tools::printw(getY()+i, getX()+j, " ");
}
}
} | 460 | 219 |
#include<iostream>
#include<string>
#include<algorithm>
#include<list>
#include<stdexcept>
#include<boost/program_options.hpp>
#include <Interp.hpp>
#include <AnyInterpolator.hpp>
#include <Utils/ReadFunction.hpp>
using namespace std;
namespace po = boost::program_options;
void print_version()
{
cout<<"interp-cli - linked against libInterp version "<< libInterp_VERSION_FULL << endl;
}
void print_usage(char prog_name[])
{
cout<<"usage: "<<prog_name<<" [OPTIONS]"<<"\n";
}
void print_documentation( )
{
cout<<"Reads x-y pairs from a file and interpolates to x values listed in another file."
<<"\n"
<<"The interpoalted data (data that is interpolated from) is contained in a gnuplot-style text file, with each x-y pair on a new line, separated by white space."
<<"The x points to interpoalte to are contained in plain text file, with each value on a new line."
<<"\n"
<<"Notes:\n"
<<"\tthe x values to be interpolated to can also be stored in a gnuplot-style text file. If the file containes more than one column, only the first will be used.\n"
<<"\n";
}
_1D::AnyInterpolator<double> create(std::string type)
{
if( type == "linear" )
return _1D::LinearInterpolator<double>();
if( type == "spline" )
return _1D::CubicSplineInterpolator<double>();
if( type == "monotonic" )
return _1D::MonotonicInterpolator<double>();
throw std::runtime_error("Interpolator type was not recognized: '"+type+"'");
}
int main( int argc, char* argv[])
{
po::options_description options("Allowed options");
options.add_options()
("help,h" , "print help message")
("batch,b" , "output in 'batch' mode")
("method,m" , po::value<string>()->default_value("spline"), "interpolation method.")
("list,l" , "list available interpolation methods.")
("interp-data" , "file containing data to be interpolated from.")
("x-values" , "file containing x values to interpolate to.")
("output-file" , "file to write interpolated data to.")
("precision,p" , po::value<int>(), "precision to use when writing output.")
;
po::positional_options_description args;
args.add("interp-data", 1);
args.add("x-values", 1);
args.add("output-file", 1);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(options).positional(args).run(), vm);
po::notify(vm);
if (argc == 1 || vm.count("help"))
{
print_version();
print_usage( argv[0] );
cout<<"\n";
cout << options<< "\n";
cout<<"\n";
print_documentation();
cout<<"\n";
return 1;
}
if (vm.count("list"))
{
print_version();
cout<<"\tlinear\n";
cout<<"\tspline\n";
cout<<"\tmonotonic\n";
return 1;
}
ifstream in;
double *x, *y;
int n;
// load data
in.open( vm["interp-data"].as<string>().c_str() );
Utils::ReadFunction( in, x, y, n );
in.close();
_1D::AnyInterpolator<double> interp = create(vm["method"].as<string>());
interp.setData(n,x,y);
delete[] x;
delete[] y;
// load x values
in.open( vm["x-values"].as<string>().c_str() );
Utils::ReadFunction( in, x, y, n, 1, 0 ); // multiplicity 0, only 1 column with coordinates.
in.close();
// write interpolated data
ofstream out;
if(vm.count("precision"))
{
out.precision( vm["precision"].as<int>() );
}
out.open( vm["output-file"].as<string>().c_str() );
for(int i = 0; i < n; i++)
out << x[i] << " " << interp(x[i]) << "\n";
out.close();
delete[] x;
delete[] y;
return 0;
}
| 3,920 | 1,299 |
#pragma once
#include "Command.hpp"
#include "Variable.hpp"
class Cheats {
public:
void Init();
void Shutdown();
};
extern Variable sar_autorecord;
extern Variable sar_autojump;
extern Variable sar_jumpboost;
extern Variable sar_aircontrol;
extern Variable sar_duckjump;
extern Variable sar_disable_challenge_stats_hud;
extern Variable sar_disable_steam_pause;
extern Variable sar_disable_no_focus_sleep;
extern Variable sar_disable_progress_bar_update;
extern Variable sar_prevent_mat_snapshot_recompute;
extern Variable sar_challenge_autostop;
extern Variable sar_show_entinp;
extern Variable sv_laser_cube_autoaim;
extern Variable ui_loadingscreen_transition_time;
extern Variable ui_loadingscreen_fadein_time;
extern Variable ui_loadingscreen_mintransition_time;
extern Variable hide_gun_when_holding;
extern Command sar_togglewait;
| 843 | 276 |
// Copyright (c) 2018-2021 Pocketnet developers
// Distributed under the Apache 2.0 software license, see the accompanying
// https://www.apache.org/licenses/LICENSE-2.0
#include <primitives/transaction.h>
#include "pocketdb/models/dto/User.h"
namespace PocketTx
{
User::User() : Transaction()
{
SetType(TxType::ACCOUNT_USER);
}
User::User(const std::shared_ptr<const CTransaction>& tx) : Transaction(tx)
{
SetType(TxType::ACCOUNT_USER);
}
shared_ptr <UniValue> User::Serialize() const
{
auto result = Transaction::Serialize();
result->pushKV("address", GetAddress() ? *GetAddress() : "");
result->pushKV("referrer", GetReferrerAddress() ? *GetReferrerAddress() : "");
result->pushKV("regdate", *GetTime());
result->pushKV("lang", (m_payload && m_payload->GetString1()) ? *m_payload->GetString1() : "en");
result->pushKV("name", (m_payload && m_payload->GetString2()) ? *m_payload->GetString2() : "");
result->pushKV("avatar", (m_payload && m_payload->GetString3()) ? *m_payload->GetString3() : "");
result->pushKV("about", (m_payload && m_payload->GetString4()) ? *m_payload->GetString4() : "");
result->pushKV("url", (m_payload && m_payload->GetString5()) ? *m_payload->GetString5() : "");
result->pushKV("pubkey", (m_payload && m_payload->GetString6()) ? *m_payload->GetString6() : "");
result->pushKV("donations", (m_payload && m_payload->GetString7()) ? *m_payload->GetString7() : "");
result->pushKV("birthday", 0);
result->pushKV("gender", 0);
result->pushKV("id", 0);
return result;
}
void User::Deserialize(const UniValue& src)
{
Transaction::Deserialize(src);
if (auto[ok, val] = TryGetStr(src, "address"); ok) SetAddress(val);
if (auto[ok, val] = TryGetStr(src, "referrer"); ok) SetReferrerAddress(val);
}
void User::DeserializeRpc(const UniValue& src)
{
if (auto[ok, val] = TryGetStr(src, "r"); ok) SetReferrerAddress(val);
GeneratePayload();
if (auto[ok, val] = TryGetStr(src, "l"); ok) m_payload->SetString1(val);
else m_payload->SetString1("en");
if (auto[ok, val] = TryGetStr(src, "n"); ok) m_payload->SetString2(val);
else m_payload->SetString2("");
if (auto[ok, val] = TryGetStr(src, "i"); ok) m_payload->SetString3(val);
if (auto[ok, val] = TryGetStr(src, "a"); ok) m_payload->SetString4(val);
if (auto[ok, val] = TryGetStr(src, "s"); ok) m_payload->SetString5(val);
if (auto[ok, val] = TryGetStr(src, "k"); ok) m_payload->SetString6(val);
if (auto[ok, val] = TryGetStr(src, "b"); ok) m_payload->SetString7(val);
}
shared_ptr <string> User::GetAddress() const { return m_string1; }
void User::SetAddress(const string& value) { m_string1 = make_shared<string>(value); }
shared_ptr <string> User::GetReferrerAddress() const { return m_string2; }
void User::SetReferrerAddress(const string& value) { m_string2 = make_shared<string>(value); }
// Payload getters
shared_ptr <string> User::GetPayloadName() const { return GetPayload() ? GetPayload()->GetString2() : nullptr; }
shared_ptr <string> User::GetPayloadAvatar() const { return GetPayload() ? GetPayload()->GetString3() : nullptr; }
shared_ptr <string> User::GetPayloadUrl() const { return GetPayload() ? GetPayload()->GetString5() : nullptr; }
shared_ptr <string> User::GetPayloadLang() const { return GetPayload() ? GetPayload()->GetString1() : nullptr; }
shared_ptr <string> User::GetPayloadAbout() const { return GetPayload() ? GetPayload()->GetString4() : nullptr; }
shared_ptr <string> User::GetPayloadDonations() const { return GetPayload() ? GetPayload()->GetString7() : nullptr; }
shared_ptr <string> User::GetPayloadPubkey() const { return GetPayload() ? GetPayload()->GetString6() : nullptr; }
void User::DeserializePayload(const UniValue& src)
{
Transaction::DeserializePayload(src);
if (auto[ok, val] = TryGetStr(src, "lang"); ok) m_payload->SetString1(val);
if (auto[ok, val] = TryGetStr(src, "name"); ok) m_payload->SetString2(val);
else m_payload->SetString2("");
if (auto[ok, val] = TryGetStr(src, "avatar"); ok) m_payload->SetString3(val);
if (auto[ok, val] = TryGetStr(src, "about"); ok) m_payload->SetString4(val);
if (auto[ok, val] = TryGetStr(src, "url"); ok) m_payload->SetString5(val);
if (auto[ok, val] = TryGetStr(src, "pubkey"); ok) m_payload->SetString6(val);
if (auto[ok, val] = TryGetStr(src, "donations"); ok) m_payload->SetString7(val);
}
string User::BuildHash()
{
return BuildHash(true);
}
string User::BuildHash(bool includeReferrer)
{
std::string data;
data += m_payload && m_payload->GetString2() ? *m_payload->GetString2() : "";
data += m_payload && m_payload->GetString5() ? *m_payload->GetString5() : "";
data += m_payload && m_payload->GetString1() ? *m_payload->GetString1() : "";
data += m_payload && m_payload->GetString4() ? *m_payload->GetString4() : "";
data += m_payload && m_payload->GetString3() ? *m_payload->GetString3() : "";
data += m_payload && m_payload->GetString7() ? *m_payload->GetString7() : "";
data += includeReferrer && GetReferrerAddress() ? *GetReferrerAddress() : "";
data += m_payload && m_payload->GetString6() ? *m_payload->GetString6() : "";
return Transaction::GenerateHash(data);
}
string User::PreBuildHash()
{
std::string data;
data += m_payload && m_payload->GetString2() ? *m_payload->GetString2() : "";
data += m_payload && m_payload->GetString5() ? *m_payload->GetString5() : "";
data += m_payload && m_payload->GetString1() ? *m_payload->GetString1() : "";
data += m_payload && m_payload->GetString4() ? *m_payload->GetString4() : "";
data += m_payload && m_payload->GetString3() ? *m_payload->GetString3() : "";
data += m_payload && m_payload->GetString7() ? *m_payload->GetString7() : "";
data += GetReferrerAddress() ? *GetReferrerAddress() : "";
data += m_payload && m_payload->GetString6() ? *m_payload->GetString6() : "";
return data;
}
} // namespace PocketTx
| 6,393 | 2,169 |
// Copyright 2021 Xeni Robotics
//
// 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 <inttypes.h>
#include <memory>
#include <chrono>
#include <functional>
#include <string>
#include <vector>
#include <sstream>
#include "cv_bridge/cv_bridge.h"
#include <opencv2/core/core.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/aruco.hpp>
// #include <sensor_msgs/msg/compressed_image.hpp>
#include <sensor_msgs/msg/image.hpp>
#include <image_transport/image_transport.hpp>
#include "std_msgs/msg/string.hpp"
#include <geometry_msgs/msg/point_stamped.hpp>
#include <message_filters/subscriber.h>
#include <rclcpp/rclcpp.hpp>
#include "camera_lite_interfaces/srv/save.hpp"
#include "rclcpp/rclcpp.hpp"
using namespace std::chrono_literals;
using SavePicture = camera_lite_interfaces::srv::Save;
class PictureNode : public rclcpp::Node
{
public:
PictureNode()
: Node("picture_node"), save_next_image_(false)
{
file_name_ = "undefined.jpg";
image_subscription_ = this->create_subscription<sensor_msgs::msg::Image>(
"/camera/image_raw", 10, std::bind(&PictureNode::image_callback, this, std::placeholders::_1));
service_ = create_service<SavePicture>("camera/save_picture", std::bind(&PictureNode::handle_service, this, std::placeholders::_1, std::placeholders::_2));
}
private:
void image_callback(const sensor_msgs::msg::Image::SharedPtr msg)
{
RCLCPP_DEBUG(this->get_logger(),
"Image received\t Timestamp: %u.%u sec ",msg->header.stamp.sec,msg->header.stamp.nanosec);
if( save_next_image_ ) {
// Frame acquisition
cv_bridge::CvImagePtr cv_ptr;
try
{
cv_ptr = cv_bridge::toCvCopy(msg, msg->encoding);
}
catch (cv_bridge::Exception& e)
{
RCLCPP_ERROR(this->get_logger(), "cv_bridge exception: %s",e.what());
return;
}
cv::Mat image;
cv_ptr->image.copyTo(image); // BGR image coming from Raspberry Pi Camera via ROSinputVideo.retrieve(image);
cv::imwrite(file_name_, image); // Save the image to a JPG file.
save_next_image_ = false;
}
}
void handle_service(
const std::shared_ptr<SavePicture::Request> request,
const std::shared_ptr<SavePicture::Response> response)
{
file_name_ = request->name;
save_next_image_ = true;
response->result = true;
}
// Private Variables ///////////////////////////////////////////////////////////////////////////
rclcpp::Subscription<sensor_msgs::msg::Image>::SharedPtr image_subscription_;
rclcpp::Service<SavePicture>::SharedPtr service_;
bool save_next_image_;
std::string file_name_;
};
int main(int argc, char * argv[])
{
rclcpp::init(argc, argv);
rclcpp::spin(std::make_shared<PictureNode>());
rclcpp::shutdown();
return 0;
}
| 3,405 | 1,167 |
#include "Acceptor.hh"
#include "TCPConnection.hh"
#include "EventLoop.hh"
#include <iostream>
#include <string>
using namespace std;
using namespace wd;
// 普通函数版的回调函数
void onConnection(const TCPConnectionPtr &conn)
{
cout << conn->toString() << " has connected" << endl;
conn->send("welcome to server");
}
void onMessage(const TCPConnectionPtr &conn){
cout << "gets from client: " << conn->recv();
/**
* 业务逻辑处理
* decode
* compute
* encode
* **/
conn->send("wo hen shuai");
}
void onClose(const TCPConnectionPtr &conn){
cout << ">> " << conn->toString() << " has disconnected" << endl;
}
int main()
{
Acceptor acceptor("172.25.40.81", 8888);
acceptor.ready();
EventLoop event(acceptor);
event.setConnectionCallback(onConnection);
event.setMessageCallback(onMessage);
event.setCloseCallback(onClose);
event.loop();
return 0;
} | 917 | 324 |
/**********************************************************************
// @@@ START COPYRIGHT @@@
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.
//
// @@@ END COPYRIGHT @@@
**********************************************************************/
/* -*-C++-*-
******************************************************************************
*
* File: LmJavaExceptionReporter.cpp
* Description: Java Exception Reporting Mechanism
*
* Created: 08/21/2003
* Language: C++
*
*
******************************************************************************
*/
#include "Platform.h"
#include "lmjni.h"
#include "LmJavaExceptionReporter.h"
LmJavaExceptionReporter::LmJavaExceptionReporter(LmHandle jniEnv,
LmLanguageManagerJava *langMan,
LmResult &result,
ComDiagsArea *diagsArea)
: jniEnv_(jniEnv),
langMan_(langMan),
throwableClass_(NULL),
throwableToStringId_(NULL),
throwableGetCauseId_(NULL),
exSQLClass_(NULL),
exSQLStateId_(NULL),
exErrorCodeId_(NULL),
exNextExceptionId_(NULL),
exMetValFailedClass_(NULL),
exGetMethodName_(NULL),
exGetSignature_(NULL)
{
if (loadThrowable(diagsArea) == LM_ERR ||
loadSQLException(diagsArea) == LM_ERR ||
loadMethodValidationFailedException(diagsArea) == LM_ERR)
{
result = LM_ERR;
return;
}
}
LmJavaExceptionReporter::~LmJavaExceptionReporter()
{
JNIEnv *jni = (JNIEnv*) jniEnv_;
if (throwableClass_)
jni->DeleteGlobalRef((jobject) throwableClass_);
if (exSQLClass_)
jni->DeleteGlobalRef((jobject) exSQLClass_);
if (exMetValFailedClass_)
jni->DeleteGlobalRef((jobject) exMetValFailedClass_);
}
//
// loadThrowable: loads java.lang.Throwable and some of its methods.
//
LmResult
LmJavaExceptionReporter::loadThrowable(ComDiagsArea *diagsArea)
{
JNIEnv *jni = (JNIEnv *) jniEnv_;
jclass jc = NULL;
jc = (jclass) jni->FindClass("java/lang/Throwable");
if (jc != NULL)
{
throwableClass_ = (jclass) jni->NewGlobalRef(jc);
jni->DeleteLocalRef(jc);
if (throwableClass_ != NULL)
{
throwableToStringId_ = jni->GetMethodID((jclass) throwableClass_,
"toString",
"()Ljava/lang/String;");
throwableGetCauseId_ = jni->GetMethodID((jclass) throwableClass_,
"getCause",
"()Ljava/lang/Throwable;");
}
}
// *** we tolerate throwableGetCauseId_ being NULL because
// it is a new feature in JDK 1.4. Need to change this when
// we move to JDK1.4
if (throwableClass_ == NULL || throwableToStringId_ == NULL)
{
*diagsArea << DgSqlCode(-LME_JVM_SYS_CLASS_ERROR)
<< DgString0("java.lang.Throwable");
return LM_ERR;
}
// We may get to this point with a pending exception in the JVM if
// the getCause() method was not found. We will tolerate that
// condition, clear the pending exception, and proceed.
jni->ExceptionClear();
return LM_OK;
}
//
// loadSQLException: Loads java.sql.SQLException
//
LmResult
LmJavaExceptionReporter::loadSQLException(ComDiagsArea *diagsArea)
{
jclass jc = NULL;
JNIEnv *jni = (JNIEnv *) jniEnv_;
jc = (jclass) jni->FindClass("java/sql/SQLException");
if (jc != NULL)
{
exSQLClass_ = (jclass) jni->NewGlobalRef(jc);
jni->DeleteLocalRef(jc);
if (exSQLClass_ != NULL)
{
exSQLStateId_ = jni->GetMethodID((jclass) exSQLClass_,
"getSQLState",
"()Ljava/lang/String;");
exErrorCodeId_ = jni->GetMethodID((jclass) exSQLClass_,
"getErrorCode", "()I");
exNextExceptionId_ = jni->GetMethodID((jclass) exSQLClass_,
"getNextException",
"()Ljava/sql/SQLException;");
}
}
if (exSQLClass_ == NULL || exSQLStateId_ == NULL ||
exErrorCodeId_ == NULL || exNextExceptionId_ == NULL ||
jni->ExceptionOccurred())
{
insertDiags(diagsArea, -LME_JVM_SYS_CLASS_ERROR, "java.sql.SQLException");
return LM_ERR;
}
return LM_OK;
}
//
// loadMethodValidationFailedException: Loads org.trafodion.sql.udr
// MethodValidationFailedException class
//
LmResult
LmJavaExceptionReporter::loadMethodValidationFailedException(
ComDiagsArea *diagsArea)
{
jclass jc = NULL;
JNIEnv *jni = (JNIEnv *) jniEnv_;
jc = (jclass)
jni->FindClass("org/trafodion/sql/udr/MethodValidationFailedException");
if (jc != NULL)
{
exMetValFailedClass_ = (jclass) jni->NewGlobalRef(jc);
jni->DeleteLocalRef(jc);
if (exMetValFailedClass_ != NULL)
{
exGetMethodName_ = jni->GetMethodID((jclass) exMetValFailedClass_,
"getMethodName",
"()Ljava/lang/String;");
exGetSignature_ = jni->GetMethodID((jclass) exMetValFailedClass_,
"getMethodSignature",
"()Ljava/lang/String;");
}
}
if (exGetMethodName_ == NULL || exGetSignature_ == NULL ||
jni->ExceptionOccurred())
{
insertDiags(diagsArea,
-LME_JVM_SYS_CLASS_ERROR,
"org.trafodion.sql.udr.MethodValidationFailedException");
return LM_ERR;
}
return LM_OK;
}
//
// checkJVMException(): Raises an error for JVM's exception
// if there is any and adds a condition for each JVM exception.
// If 'exception' parameter is not NULL that will be used as exception.
//
// Returns: LM_OK if there is no exception
// LM_ERR if there is an exception
//
LmResult
LmJavaExceptionReporter::checkJVMException(ComDiagsArea *da,
LmHandle exception)
{
JNIEnv *jni = (JNIEnv*)jniEnv_;
jthrowable jex = NULL;
LmResult result = LM_OK;
// This boolean will track whether this method owns a reference to
// the current exception object, or whether the caller owns the
// reference. This method must release any of its own references
// before it returns.
NABoolean callerOwnsTheCurrentException;
if (exception == NULL)
{
jex = jni->ExceptionOccurred();
callerOwnsTheCurrentException = FALSE;
}
else
{
jex = (jthrowable) exception;
callerOwnsTheCurrentException = TRUE;
}
if (jex != NULL)
{
result = LM_ERR;
}
//
// ExceptionDescribe() prints the exception information including
// the stack trace to standard error. We want to do this so that
// user can see the stack. But right now we see two errors if we
// enable this
// 1. ":" missing in exception message java.lang.NullPointerException
// TEST501
// 2. 11229 error with message "Exception in thread "main" "
// So we are commenting calls to ExceptionDescribe().
//
// jni->ExceptionDescribe();
jni->ExceptionClear();
// Each iteration of this while loop will add a diags condition for
// the current exception jex, then move jex to point to the next
// exception in the chain.
while (jex != NULL)
{
addJavaExceptionToDiags(jex, *da);
jthrowable next = (jthrowable) getNextChainedException(jex);
if (!callerOwnsTheCurrentException)
{
jni->DeleteLocalRef(jex);
}
jex = next;
callerOwnsTheCurrentException = FALSE;
}
jni->ExceptionClear();
return result;
}
//
// checkNewObjectExceptions(): checks for exceptions after a JNI
// call to create a new Java Object, populate diags with exception
// messages.
//
// Returns LM_OK if the jobj is not NULL and there is no
// exception occurred
// LM_ERR otherwise
//
LmResult
LmJavaExceptionReporter::checkNewObjectExceptions(LmHandle jobj,
ComDiagsArea *da)
{
JNIEnv *jni = (JNIEnv*)jniEnv_;
jthrowable jt = jni->ExceptionOccurred();
// jni->ExceptionDescribe();
jni->ExceptionClear();
if(jt == NULL)
{
if(jobj)
{
return LM_OK;
}
else
{
*da << DgSqlCode(-LME_INTERNAL_ERROR)
<< DgString0(": a JNI error was encountered but no exception was found in the Java Virtual machine.");
return LM_ERR;
}
}
else
{
// LCOV_EXCL_START
jstring jstr =
(jstring) jni->CallObjectMethod(jt, (jmethodID) throwableToStringId_);
if (jstr)
{
const char *msg = jni->GetStringUTFChars(jstr, NULL);
if ((str_cmp(msg, "java.lang.OutOfMemoryError", 28) == 0))
{
*da << DgSqlCode(-LME_JVM_OUT_OF_MEMORY)
<< DgString0(msg);
}
else
{
*da << DgSqlCode(-LME_JAVA_EXCEPTION)
<< DgString0(msg);
}
jni->ReleaseStringUTFChars(jstr, msg);
jni->DeleteLocalRef(jstr);
}
else
{
*da << DgSqlCode(-LME_JAVA_EXCEPTION);
}
jthrowable next = (jthrowable) getNextChainedException(jt);
if (next)
{
checkJVMException(da, next);
jni->DeleteLocalRef(next);
}
jni->DeleteLocalRef(jt);
jni->ExceptionClear();
return LM_ERR;
// LCOV_EXCL_STOP
}
}
//
// addJavaExceptionToDiags(): Adds a single diags condition
// describing an uncaught Java exception.
//
// Returns Nothing
//
void
LmJavaExceptionReporter::addJavaExceptionToDiags(LmHandle throwable,
ComDiagsArea &diags)
{
JNIEnv *jni = (JNIEnv *) jniEnv_;
jthrowable t = (jthrowable) throwable;
const char *msg;
if (t)
{
if (!throwableToStringId_)
{
// We should never get here. For some reason the Throwable class
// and its methods have not been loaded yet.
msg = ": A Java exception was thrown but the Language Manager was unable to retrieve the message text.";
diags << DgSqlCode(-LME_INTERNAL_ERROR) << DgString0(msg);
}
else
{
jstring jstr =
(jstring) jni->CallObjectMethod(t, (jmethodID) throwableToStringId_);
if (jstr != NULL)
{
msg = jni->GetStringUTFChars(jstr, NULL);
diags << DgSqlCode(-LME_JVM_EXCEPTION) << DgString0(msg);
jni->ReleaseStringUTFChars(jstr, msg);
jni->DeleteLocalRef(jstr);
}
else
{
// An exception occurred but it contains no message
msg = ": A Java exception with no message text was thrown.";
diags << DgSqlCode(-LME_INTERNAL_ERROR) << DgString0(msg);
}
}
}
jni->ExceptionClear();
}
//
// getNextChainedException(): Return a reference to the
// next chained Java exception. This method attempts to
// avoid method lookups by name if possible, using cached
// class references and method IDs if they have non-NULL values.
//
// Returns LmHandle to next exception
// NULL if there is no next exception
//
LmHandle
LmJavaExceptionReporter::getNextChainedException(LmHandle throwable)
{
if (throwable == NULL)
{
return NULL;
}
JNIEnv *jni = (JNIEnv *) jniEnv_;
LmHandle result = NULL;
jthrowable t = (jthrowable) throwable;
jmethodID methodID;
jclass classRef = jni->GetObjectClass((jobject) t);
jni->ExceptionClear();
if (classRef)
{
// 1. Is this a SQLException?
if (exSQLClass_ != NULL &&
jni->IsInstanceOf(t, (jclass) exSQLClass_) == JNI_TRUE)
{
methodID = (jmethodID) exNextExceptionId_;
}
else
{
methodID = (jmethodID) jni->GetMethodID(classRef, "getNextException",
"()Ljava/sql/SQLException;");
}
jni->ExceptionClear();
// 2. If not, does this object have a getCause() method?
// The getCause() chaining framework is new in JDK 1.4
if (methodID == NULL)
{
if (throwableClass_ != NULL)
{
methodID = (jmethodID) throwableGetCauseId_;
}
else
{
methodID = (jmethodID) jni->GetMethodID(classRef, "getCause",
"()Ljava/lang/Throwable;");
}
jni->ExceptionClear();
}
// 3. If not, does the object happen to have a getException() method?
// Some Throwable subclasses supported this method for exception
// chaining before the getCause() framework arrived in JDK 1.4.
if (methodID == NULL)
{
methodID = (jmethodID) jni->GetMethodID(classRef, "getException",
"()Ljava/lang/Throwable;");
jni->ExceptionClear();
}
if (methodID)
{
result = (LmHandle) jni->CallObjectMethod(t, methodID);
jni->ExceptionClear();
}
jni->DeleteLocalRef(classRef);
} // if (classRef)
jni->ExceptionClear();
return result;
}
//
// insertDiags() : Inserts conditions into diags area.
// This method works only with error messages that take string
// parameters. Typically this method is called when the calling
// method wants to insert a condition as main SQLCode and one
// condition for every exception in the exception chain. Currently
// this method can accept at most 2 params to the condition item.
// This method calls checkJVMException() to insert conditions
// for JVM exceptions.
//
// Returns: LM_ERR unconditionally
//
// LCOV_EXCL_START
LmResult
LmJavaExceptionReporter::insertDiags(ComDiagsArea *diags,
Int32 errCode,
const char *arg1,
const char *arg2,
LmHandle jt)
{
Int32 numArgs;
numArgs = (arg2 == NULL)? ((arg1 == NULL)? 0 : 1) : 2;
// This is mainSQLCode in the diags area
switch (numArgs)
{
case 0:
{
*diags << DgSqlCode(errCode);
break;
}
case 1:
{
*diags << DgSqlCode(errCode)
<< DgString0(arg1);
break;
}
case 2:
{
*diags << DgSqlCode(errCode)
<< DgString0(arg1)
<< DgString1(arg2);
break;
}
}
// Insert a diags condition for every exception in exception chain.
checkJVMException(diags, jt);
return LM_ERR;
}
//
// checkGetMethodExceptions() : checks for possible exceptions after
// a call to jni GetMethodID(). GetMethodID() can throw
// NoSuchMethodError, ExceptionInInitializerError, or OutOfMemoryError.
//
LmResult
LmJavaExceptionReporter::checkGetMethodExceptions(const char *routineName,
const char *className,
ComDiagsArea *da)
{
JNIEnv *jni = (JNIEnv*)jniEnv_;
jthrowable jt;
if ((jt = jni->ExceptionOccurred()) == NULL)
{
*da << DgSqlCode(-LME_INTERNAL_ERROR)
<< DgString0(": A JNI error was encountered but no exception was found in the Java Virtual Machine.");
return LM_ERR;
}
// jni->ExceptionDescribe();
jni->ExceptionClear();
jstring jstr = (jstring)
jni->CallObjectMethod(jt, (jmethodID) throwableToStringId_);
if (jstr != NULL)
{
const char *msg = jni->GetStringUTFChars(jstr, NULL);
if ((str_cmp(msg, "java.lang.ExceptionInInitializerError", 37)) == 0)
{
insertDiags(da, -LME_CLASS_INIT_FAIL, className, NULL, jt);
}
else if ((str_cmp(msg, "java.lang.OutOfMemoryError", 28) == 0))
{
insertDiags(da, -LME_JVM_OUT_OF_MEMORY, NULL, NULL, jt);
}
else
{
insertDiags(da, -LME_ROUTINE_NOT_FOUND, routineName, className, jt);
}
jni->ReleaseStringUTFChars(jstr, msg);
jni->DeleteLocalRef(jstr);
}
else
{
// Exception occurred, but no message
*da << DgSqlCode(-LME_INTERNAL_ERROR)
<< DgString0(": Unknown error occurred.");
}
jni->DeleteLocalRef(jt);
jni->ExceptionClear();
return LM_ERR;
}
// LCOV_EXCL_STOP
//
// processUserException(): Processes possible uncaught Java exceptions.
// If no exception occurred, returns OK. In the event of an exception,
// diagsArea is filled with proper error message.
//
// The SQLSTATE value is set according to section 13 'Status Code' of JRT.
//
// 38000 - For standard java exceptions.
// 38??? - For SQL exceptions(java.sql.Exception) when Class = 38
// and Subclass != 000. So valid SQLSTATE values from Java method
// are between 38001 to 38999
// 39001 - For all other SQL exceptions(java.sql.Exception) ie. for
// SQL exceptions with invalid SQLSTATE value
//
LmResult
LmJavaExceptionReporter::processUserException(LmRoutineJava *routine_handle,
ComDiagsArea *da)
{
jthrowable jex;
JNIEnv *jni = (JNIEnv*)jniEnv_;
char errText[LMJ_ERR_SIZE_512];
// Get Java exception if one occurred.
if ((jex = jni->ExceptionOccurred()) == NULL)
return LM_OK;
// jni->ExceptionDescribe();
jni->ExceptionClear();
jstring jstr = (jstring)
jni->CallObjectMethod(jex, (jmethodID) throwableToStringId_);
if (jstr != NULL)
{
// Record exception error text.
const char *msg = jni->GetStringUTFChars(jstr, NULL);
Int32 len = min(str_len(msg), (LMJ_ERR_SIZE_512 - 1));
str_cpy_all(errText, msg, len);
errText[len] = '\0';
if (str_cmp(errText, "java.sql", 8) == 0 ||
str_cmp(errText, "com.hp.jdbc.HPT4Exception", 25) == 0)
{
reportUserSQLException(jex, errText, da);
}
else if (routine_handle->isInternalSPJ())
{
reportInternalSPJException(jex, errText, da);
}
else
{
*da << DgSqlCode(-LME_JAVA_EXCEPTION)
<< DgString0(errText);
}
jni->ReleaseStringUTFChars(jstr, msg);
jni->DeleteLocalRef(jstr);
}
// Now insert the remaining error messages into diags
jthrowable next = (jthrowable) getNextChainedException(jex);
if (next)
{
checkJVMException(da, next);
jni->DeleteLocalRef(next);
}
jni->DeleteLocalRef(jex);
jni->ExceptionClear();
return LM_ERR;
}
//
// reportUserSQLException(): populates the diags for SQLException.
// Look at the comments of processUserException().
//
void
LmJavaExceptionReporter::reportUserSQLException(LmHandle jt,
char *errText,
ComDiagsArea *da)
{
JNIEnv *jni = (JNIEnv*)jniEnv_;
jthrowable jex = (jthrowable) jt;
char sqlState[6];
// Get the error code, SQLState
Int32 errcode = (Int32) jni->CallIntMethod((jobject)jex,
(jmethodID)exErrorCodeId_);
jstring jsstate = (jstring)
jni->CallObjectMethod(jex, (jmethodID)exSQLStateId_);
if (jsstate != NULL)
{
const char *sstate = jni->GetStringUTFChars(jsstate, NULL);
// Check for the validity of the SQLSTATE
if (sstate != NULL &&
str_len(sstate) >= 5 &&
str_cmp(&sstate[0], "38", 2) == 0 &&
str_cmp(&sstate[2], "000", 3) != 0)
{
// Valid sqlstate. Report this as LME_CUSTOM_ERROR
// with sqlState as SQLSTATE of LME_CUSTOM_ERROR.
str_cpy_all(sqlState, sstate, 5);
sqlState[5] = '\0';
*da << DgSqlCode(-LME_CUSTOM_ERROR)
<< DgString0(errText)
<< DgString1(sqlState)
<< DgCustomSQLState(sqlState);
}
else
{
// Invalid sqlstate. Report this value wrapped in the message
// of LME_JAVA_SQL_EXCEPTION_INVALID. The sqlstate of the reported
// message is 39001.
Int32 min_len = min(str_len(sstate), 5); // interested only upto 5 chars
str_cpy_all(sqlState, sstate, min_len);
sqlState[min_len] = '\0';
*da << DgSqlCode(-LME_JAVA_SQL_EXCEPTION_INVALID)
<< DgInt0(errcode)
<< DgString0(sqlState)
<< DgString1(errText);
}
if (sstate != NULL)
jni->ReleaseStringUTFChars(jsstate, sstate);
jni->DeleteLocalRef(jsstate);
} // if (jsstate != NULL)
else
{
// sqlstate is not specified.
// LME_JAVA_SQL_EXCEPTION_INVALID is reported
sqlState[0] = '\0';
*da << DgSqlCode(-LME_JAVA_SQL_EXCEPTION_INVALID)
<< DgInt0(errcode)
<< DgString0(sqlState)
<< DgString1(errText);
}
return;
}
//
// reportInternalSPJException(): populates the diags for
// MethodValidationException. This exception is thrown by
// the internal SPJ VALIDATEROUTINE.
//
// LCOV_EXCL_START
void
LmJavaExceptionReporter::reportInternalSPJException(LmHandle jt,
char *errText,
ComDiagsArea *da)
{
JNIEnv *jni = (JNIEnv*)jniEnv_;
jthrowable jex = (jthrowable) jt;
jstring metNameStr = NULL;
jstring metSigStr = NULL;
if (exMetValFailedClass_ != NULL &&
jni->IsInstanceOf(jex, (jclass) exMetValFailedClass_))
{
metNameStr = (jstring)
jni->CallObjectMethod(jex, (jmethodID) exGetMethodName_);
metSigStr = (jstring)
jni->CallObjectMethod(jex, (jmethodID) exGetSignature_);
}
if (metNameStr != NULL && metSigStr != NULL)
{
const char *metName = jni->GetStringUTFChars(metNameStr, NULL);
const char *metSig = jni->GetStringUTFChars(metSigStr, NULL);
LmJavaSignature lmSig(metSig, collHeap());
ComSInt32 unpackedSigSize = lmSig.getUnpackedSignatureSize();
ComUInt32 totLen = str_len(metName) + unpackedSigSize;
char *signature = new (collHeap()) char[totLen + 1];
sprintf(signature, "%s", metName);
lmSig.unpackSignature(signature + str_len(metName));
signature[totLen] = '\0';
*da << DgSqlCode(-LME_VALIDATION_FAILED)
<< DgString0(signature)
<< DgString1(errText);
jni->ReleaseStringUTFChars(metNameStr, metName);
jni->DeleteLocalRef(metNameStr);
jni->ReleaseStringUTFChars(metSigStr, metSig);
jni->DeleteLocalRef(metSigStr);
if (signature) NADELETEBASIC(signature, collHeap());
}
else
{
*da << DgSqlCode(-LME_JAVA_EXCEPTION)
<< DgString0(errText);
if (metNameStr) jni->DeleteLocalRef(metNameStr);
if (metSigStr) jni->DeleteLocalRef(metSigStr);
}
}
// LCOV_EXCL_STOP
//
// reportJavaObjException(): populates the diags for
// a return status returned in an LmUDRObjMethodInvoke.ReturnInfo
// object used in the Java object interface
void
LmJavaExceptionReporter::processJavaObjException(
LmHandle returnInfoObj,
int returnStatus,
int callPhase,
const char *errText,
const char *udrName,
ComDiagsArea *da)
{
if (da)
{
JNIEnv *jni = (JNIEnv*)jniEnv_;
const char *sqlState = NULL;
const char *message = NULL;
jobject jniResult = (jobject) returnInfoObj;
jstring returnedSQLState =
static_cast<jstring>(jni->GetObjectField(
jniResult,
(jfieldID) langMan_->getReturnInfoSQLStateField()));
jstring returnedMessage =
static_cast<jstring>(jni->GetObjectField(
jniResult,
(jfieldID) langMan_->getReturnInfoMessageField()));
if (returnedSQLState != NULL)
sqlState = jni->GetStringUTFChars(returnedSQLState, NULL);
if (returnedMessage != NULL)
message = jni->GetStringUTFChars(returnedMessage, NULL);
if (sqlState || message)
{
const char *diagsMessage =
(message ? message : "no message provided");
const char *diagsSQLState =
(sqlState ? sqlState : "no SQLSTATE provided");
// Check the returned SQLSTATE value and raise appropriate
// SQL code. Valid SQLSTATE values begin with "38" except "38000"
if (sqlState &&
(strncmp(diagsSQLState, "38", 2) == 0) &&
(strncmp(diagsSQLState, "38000", 5) != 0))
{
*da << DgSqlCode(-LME_CUSTOM_ERROR)
<< DgString0(diagsMessage)
<< DgString1(diagsSQLState);
*da << DgCustomSQLState(diagsSQLState);
}
else
{
*da << DgSqlCode(-LME_UDF_ERROR)
<< DgString0(udrName)
<< DgString1(diagsSQLState)
<< DgString2(diagsMessage);
}
}
else
{
// Report the return status as an internal error, since
// we didn't get a UDRException. This should be rare, since
// Java exceptions are caught above.
char buf1[4];
snprintf(buf1, sizeof(buf1), "%d", callPhase);
char buf2[80];
snprintf(buf2, sizeof(buf2), "Return status %d from JNI call", returnStatus);
*da << DgSqlCode(-LME_OBJECT_INTERFACE_ERROR)
<< DgString0(udrName)
<< DgString1(buf1)
<< DgString2(errText)
<< DgString3(buf2);
}
if (sqlState)
jni->ReleaseStringUTFChars(returnedSQLState, sqlState);
if (message)
jni->ReleaseStringUTFChars(returnedMessage, message);
if (returnedSQLState)
jni->DeleteLocalRef(returnedSQLState);
if (returnedMessage)
jni->DeleteLocalRef(returnedMessage);
}
}
| 25,891 | 8,487 |
/*================================================================================
code generated by: java2cpp
author: Zoran Angelov, mailto://baldzar@gmail.com
class: javax.crypto.spec.DESKeySpec
================================================================================*/
#ifndef J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_JAVAX_CRYPTO_SPEC_DESKEYSPEC_HPP_DECL
#define J2CPP_JAVAX_CRYPTO_SPEC_DESKEYSPEC_HPP_DECL
namespace j2cpp { namespace java { namespace lang { class Object; } } }
namespace j2cpp { namespace java { namespace security { namespace spec { class KeySpec; } } } }
#include <java/lang/Object.hpp>
#include <java/security/spec/KeySpec.hpp>
namespace j2cpp {
namespace javax { namespace crypto { namespace spec {
class DESKeySpec;
class DESKeySpec
: public object<DESKeySpec>
{
public:
J2CPP_DECLARE_CLASS
J2CPP_DECLARE_METHOD(0)
J2CPP_DECLARE_METHOD(1)
J2CPP_DECLARE_METHOD(2)
J2CPP_DECLARE_METHOD(3)
J2CPP_DECLARE_METHOD(4)
J2CPP_DECLARE_FIELD(0)
explicit DESKeySpec(jobject jobj)
: object<DESKeySpec>(jobj)
{
}
operator local_ref<java::lang::Object>() const;
operator local_ref<java::security::spec::KeySpec>() const;
DESKeySpec(local_ref< array<jbyte,1> > const&);
DESKeySpec(local_ref< array<jbyte,1> > const&, jint);
local_ref< array<jbyte,1> > getKey();
static jboolean isParityAdjusted(local_ref< array<jbyte,1> > const&, jint);
static jboolean isWeak(local_ref< array<jbyte,1> > const&, jint);
static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(0), J2CPP_FIELD_SIGNATURE(0), jint > DES_KEY_LEN;
}; //class DESKeySpec
} //namespace spec
} //namespace crypto
} //namespace javax
} //namespace j2cpp
#endif //J2CPP_JAVAX_CRYPTO_SPEC_DESKEYSPEC_HPP_DECL
#else //J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_JAVAX_CRYPTO_SPEC_DESKEYSPEC_HPP_IMPL
#define J2CPP_JAVAX_CRYPTO_SPEC_DESKEYSPEC_HPP_IMPL
namespace j2cpp {
javax::crypto::spec::DESKeySpec::operator local_ref<java::lang::Object>() const
{
return local_ref<java::lang::Object>(get_jobject());
}
javax::crypto::spec::DESKeySpec::operator local_ref<java::security::spec::KeySpec>() const
{
return local_ref<java::security::spec::KeySpec>(get_jobject());
}
javax::crypto::spec::DESKeySpec::DESKeySpec(local_ref< array<jbyte,1> > const &a0)
: object<javax::crypto::spec::DESKeySpec>(
call_new_object<
javax::crypto::spec::DESKeySpec::J2CPP_CLASS_NAME,
javax::crypto::spec::DESKeySpec::J2CPP_METHOD_NAME(0),
javax::crypto::spec::DESKeySpec::J2CPP_METHOD_SIGNATURE(0)
>(a0)
)
{
}
javax::crypto::spec::DESKeySpec::DESKeySpec(local_ref< array<jbyte,1> > const &a0, jint a1)
: object<javax::crypto::spec::DESKeySpec>(
call_new_object<
javax::crypto::spec::DESKeySpec::J2CPP_CLASS_NAME,
javax::crypto::spec::DESKeySpec::J2CPP_METHOD_NAME(1),
javax::crypto::spec::DESKeySpec::J2CPP_METHOD_SIGNATURE(1)
>(a0, a1)
)
{
}
local_ref< array<jbyte,1> > javax::crypto::spec::DESKeySpec::getKey()
{
return call_method<
javax::crypto::spec::DESKeySpec::J2CPP_CLASS_NAME,
javax::crypto::spec::DESKeySpec::J2CPP_METHOD_NAME(2),
javax::crypto::spec::DESKeySpec::J2CPP_METHOD_SIGNATURE(2),
local_ref< array<jbyte,1> >
>(get_jobject());
}
jboolean javax::crypto::spec::DESKeySpec::isParityAdjusted(local_ref< array<jbyte,1> > const &a0, jint a1)
{
return call_static_method<
javax::crypto::spec::DESKeySpec::J2CPP_CLASS_NAME,
javax::crypto::spec::DESKeySpec::J2CPP_METHOD_NAME(3),
javax::crypto::spec::DESKeySpec::J2CPP_METHOD_SIGNATURE(3),
jboolean
>(a0, a1);
}
jboolean javax::crypto::spec::DESKeySpec::isWeak(local_ref< array<jbyte,1> > const &a0, jint a1)
{
return call_static_method<
javax::crypto::spec::DESKeySpec::J2CPP_CLASS_NAME,
javax::crypto::spec::DESKeySpec::J2CPP_METHOD_NAME(4),
javax::crypto::spec::DESKeySpec::J2CPP_METHOD_SIGNATURE(4),
jboolean
>(a0, a1);
}
static_field<
javax::crypto::spec::DESKeySpec::J2CPP_CLASS_NAME,
javax::crypto::spec::DESKeySpec::J2CPP_FIELD_NAME(0),
javax::crypto::spec::DESKeySpec::J2CPP_FIELD_SIGNATURE(0),
jint
> javax::crypto::spec::DESKeySpec::DES_KEY_LEN;
J2CPP_DEFINE_CLASS(javax::crypto::spec::DESKeySpec,"javax/crypto/spec/DESKeySpec")
J2CPP_DEFINE_METHOD(javax::crypto::spec::DESKeySpec,0,"<init>","([B)V")
J2CPP_DEFINE_METHOD(javax::crypto::spec::DESKeySpec,1,"<init>","([BI)V")
J2CPP_DEFINE_METHOD(javax::crypto::spec::DESKeySpec,2,"getKey","()[B")
J2CPP_DEFINE_METHOD(javax::crypto::spec::DESKeySpec,3,"isParityAdjusted","([BI)Z")
J2CPP_DEFINE_METHOD(javax::crypto::spec::DESKeySpec,4,"isWeak","([BI)Z")
J2CPP_DEFINE_FIELD(javax::crypto::spec::DESKeySpec,0,"DES_KEY_LEN","I")
} //namespace j2cpp
#endif //J2CPP_JAVAX_CRYPTO_SPEC_DESKEYSPEC_HPP_IMPL
#endif //J2CPP_INCLUDE_IMPLEMENTATION
| 4,922 | 2,232 |
#include "Global.h"
#define MAKERGB15(R, G, B) ((((R)>>3)<<10)|(((G)>>3)<<5)|((B)>>3))
#define ROUND(c) rtbl[(c) + 128 + 256]
#define RGB15CL(N) IMAGE[N] = MAKERGB15(ROUND(GETY + R), ROUND(GETY + G), ROUND(GETY + B));
#define RGB24CL(N) IMAGE[N+ 2] = ROUND(GETY + R); IMAGE[N+ 1] = ROUND(GETY + G); IMAGE[N+ 0] = ROUND(GETY + B);
#define MULR(A) (((sw)0x0000059B * (A)) >> 10)
#define MULG(A) (((sw)0xFFFFFEA1 * (A)) >> 10)
#define MULB(A) (((sw)0x00000716 * (A)) >> 10)
#define MULF(A) (((sw)0xFFFFFD25 * (A)) >> 10)
#define RUNOF(a) ((a)>>10)
#define VALOF(a) ((sw)(((a)<<22)>>22))
CstrMotionDecoder mdec;
void CstrMotionDecoder::reset() {
rl = (uh *)&mem.ram.ptr[0x100000];
status = cmd = 0;
for (sw k=0; k<256; k++) {
rtbl[k+0x000] = 0;
rtbl[k+0x100] = k;
rtbl[k+0x200] = 255;
}
}
void CstrMotionDecoder::write(uw addr, uw data) {
switch(addr & 0xf) {
case 0:
cmd = data;
if ((data&0xf5ff0000) == 0x30000000) {
len = data&0xffff;
}
return;
case 4:
if (data & 0x80000000) {
reset();
}
return;
}
printx("/// PSeudo MDEC write: 0x%08x <- 0x%08x", addr, data);
}
uw CstrMotionDecoder::read(uw addr) {
switch(addr & 0xf) {
case 0:
return cmd;
case 4:
return status;
}
printx("/// PSeudo MDEC read: 0x%08x", addr);
return 0;
}
sw iq_y[64], iq_uv[64];
void CstrMotionDecoder::MacroBlock(sw *block, sw kh, sw sh) {
for (sw k=0; k<8; k++, (sh) ? block+=8 : block++) {
if((block[kh*1]|
block[kh*2]|
block[kh*3]|
block[kh*4]|
block[kh*5]|
block[kh*6]|
block[kh*7]) == 0) {
block[kh*0]=
block[kh*1]=
block[kh*2]=
block[kh*3]=
block[kh*4]=
block[kh*5]=
block[kh*6]=
block[kh*7]=
block[kh*0]>>sh;
continue;
}
sw z10 = block[kh*0]+block[kh*4];
sw z11 = block[kh*0]-block[kh*4];
sw z13 = block[kh*2]+block[kh*6];
sw z12 = block[kh*2]-block[kh*6]; z12 = ((z12*362)>>8)-z13;
sw tmp0 = z10+z13;
sw tmp3 = z10-z13;
sw tmp1 = z11+z12;
sw tmp2 = z11-z12;
z13 = block[kh*3]+block[kh*5];
z10 = block[kh*3]-block[kh*5];
z11 = block[kh*1]+block[kh*7];
z12 = block[kh*1]-block[kh*7]; sw z5 = (((z12-z10)*473)>>8);
sw tmp7 = z11+z13;
sw tmp6 = (((z10)*669)>>8)+z5 -tmp7;
sw tmp5 = (((z11-z13)*362)>>8)-tmp6;
sw tmp4 = (((z12)*277)>>8)-z5 +tmp5;
block[kh*0] = (tmp0+tmp7)>>sh;
block[kh*7] = (tmp0-tmp7)>>sh;
block[kh*1] = (tmp1+tmp6)>>sh;
block[kh*6] = (tmp1-tmp6)>>sh;
block[kh*2] = (tmp2+tmp5)>>sh;
block[kh*5] = (tmp2-tmp5)>>sh;
block[kh*4] = (tmp3+tmp4)>>sh;
block[kh*3] = (tmp3-tmp4)>>sh;
}
}
void CstrMotionDecoder::idct(sw *block, sw k) {
if (k == 0) {
sw val = block[0]>>5;
for (sw i=0; i<64; i++) {
block[i] = val;
}
return;
}
MacroBlock(block, 8, 0);
MacroBlock(block, 1, 5);
}
void CstrMotionDecoder::TabInit(sw *iqtab, ub *iq_y) {
for (sw i=0; i<64; i++) {
iqtab[i] = iq_y[i]*aanscales[zscan[i]]>>12;
}
}
uh *CstrMotionDecoder::rl2blk(sw *blk, uh *mdec_rl) {
sw k,q_scale,rl;
sw *iqtab;
memset(blk, 0, 6*64*4);
iqtab = iq_uv;
for (sw i=0; i<6; i++) {
if (i>1) iqtab = iq_y;
rl = *mdec_rl++;
q_scale = rl>>10;
blk[0] = iqtab[0]*VALOF(rl);
k = 0;
for(;;) {
rl = *mdec_rl++; if (rl==0xfe00) break;
k += (rl>>10)+1;if (k > 63) break;
blk[zscan[k]] = (iqtab[k] * q_scale * VALOF(rl)) >> 3;
}
idct(blk, k+1);
blk+=64;
}
return mdec_rl;
}
void CstrMotionDecoder::Yuv15(sw *Block, uh *IMAGE) {
sw GETY;
sw CB,CR,R,G,B;
sw *YYBLK = Block + 64 * 2;
sw *CBBLK = Block;
sw *CRBLK = Block + 64;
for (sw Y=0; Y<16; Y+=2, CRBLK+=4, CBBLK+=4, YYBLK+=8, IMAGE+=24) {
if (Y == 8) {
YYBLK = YYBLK + 64;
}
for (sw X=0; X<4; X++, IMAGE+=2, CRBLK++, CBBLK++, YYBLK+=2) {
CR = *CRBLK;
CB = *CBBLK;
R = MULR(CR);
G = MULG(CB) + MULF(CR);
B = MULB(CB);
GETY = YYBLK[0]; RGB15CL(0x00);
GETY = YYBLK[1]; RGB15CL(0x01);
GETY = YYBLK[8]; RGB15CL(0x10);
GETY = YYBLK[9]; RGB15CL(0x11);
CR = *(CRBLK + 4);
CB = *(CBBLK + 4);
R = MULR(CR);
G = MULG(CB) + MULF(CR);
B = MULB(CB);
GETY = YYBLK[64 + 0]; RGB15CL(0x08);
GETY = YYBLK[64 + 1]; RGB15CL(0x09);
GETY = YYBLK[64 + 8]; RGB15CL(0x18);
GETY = YYBLK[64 + 9]; RGB15CL(0x19);
}
}
}
void CstrMotionDecoder::Yuv24(sw *Block, ub *IMAGE) {
sw GETY;
sw CB, CR, R, G, B;
sw *YYBLK = Block + 64 * 2;
sw *CBBLK = Block;
sw *CRBLK = Block + 64;
for (sw Y=0; Y<16; Y+=2, CRBLK+=4, CBBLK+=4, YYBLK+=8, IMAGE+=24*3) {
if (Y == 8) {
YYBLK = YYBLK + 64;
}
for (sw X=0; X<4; X++, IMAGE+=2*3, CRBLK++, CBBLK++, YYBLK+=2) {
CR = *CRBLK;
CB = *CBBLK;
R = MULR(CR);
G = MULG(CB) + MULF(CR);
B = MULB(CB);
GETY = YYBLK[0]; RGB24CL(0x00 * 3);
GETY = YYBLK[1]; RGB24CL(0x01 * 3);
GETY = YYBLK[8]; RGB24CL(0x10 * 3);
GETY = YYBLK[9]; RGB24CL(0x11 * 3);
CR = *(CRBLK + 4);
CB = *(CBBLK + 4);
R = MULR(CR);
G = MULG(CB) + MULF(CR);
B = MULB(CB);
GETY = YYBLK[64 + 0]; RGB24CL(0x08 * 3);
GETY = YYBLK[64 + 1]; RGB24CL(0x09 * 3);
GETY = YYBLK[64 + 8]; RGB24CL(0x18 * 3);
GETY = YYBLK[64 + 9]; RGB24CL(0x19 * 3);
}
}
}
void CstrMotionDecoder::executeDMA(CstrBus::castDMA *dma) {
ub *p = &mem.ram.ptr[dma->madr&(mem.ram.size-1)];
sw z = (dma->bcr>>16)*(dma->bcr&0xffff);
switch (dma->chcr&0xfff) {
case 0x200:
{
sw blocksize, blk[384];
uh *im = (uh *)p;
if (cmd&0x08000000) {
blocksize = 256;
}
else {
blocksize = 384;
}
for (; z>0; z-=blocksize/2, im+=blocksize) {
rl = rl2blk(blk, rl);
if (cmd&0x8000000) {
Yuv15(blk, im);
}
else {
Yuv24(blk, (ub *)im);
}
}
break;
}
case 0x201:
if (cmd == 0x40000001) {
TabInit(iq_y, p);
TabInit(iq_uv, p+64);
}
if ((cmd&0xf5ff0000) == 0x30000000) {
rl = (uh *)p;
}
break;
}
}
| 7,572 | 3,486 |
#pragma once
#include "Quaternion.hpp"
#include "vbConfiguration.hpp"
#include "vbGeometry.hpp"
#include "vbCamera.hpp"
#include "vbTrackCameraControl.hpp"
#include "vbFPSCameraControl.hpp"
#include "vbMoveOrbitZoomCameraControl.hpp"
#include "vbMovingForwardCameraControl.hpp"
#include "vbHorizontalPanCameraControl.hpp"
#include "vbFreeCameraControl.hpp"
#include "vbAnimationCameraControl.hpp"
#include "vbPerspectiveProjection.hpp"
#include "vbOrthogonalProjection.hpp"
#include <vector>
using std::vector;
class vbViewInfo
{
public:
vbViewInfo();
~vbViewInfo();
enum ProjectionMode
{
PROJECTION_PERSPECTIVE=0,
PROJECTION_ORTHO,
PROJECTION_MODE_NONE
};
enum NavigationMode
{
NAVIGATION_3D=0,
NAVIGATION_2D,
NAVIGATION_WALK,
NAVIGATION_ME,
NAVIGATION_2D_FIXED, //NAVIGATION_2D는 확대 축소 이동이 되지만 이것은 고정 뷰이다.
NAVIGATION_ENVRN //환경맵용 고정 카메라
};
enum NavigationMode3D
{
NAVIGATION_3D_NONE=0,
NAVIGATION_3D_ORBIT_V,
NAVIGATION_3D_ORBIT_H,
NAVIGATION_3D_PANZOOM,
NAVIGATION_3D_ROTATEZOOM,
NAVIGATION_3D_PAN,
NAVIGATION_3D_ZOOM,
NAVIGATION_3D_FIXED_V, //고정 상태에서 Pitch 제어(Vertical)
NAVIGATION_3D_FIXED_H, //고정 상태에서 Yaw 제어
NAVIGATION_3D_ELEVATION,
NAVIGATION_3D_FORWARD,
NAVIGATION_3D_ZOOMHROTATION
};
enum CameraAniMode
{
CAMERA_ANI_NONE = 0,
CAMERA_ANI_JUMPPAN = 1,
CAMERA_ANI_JUMPZOOM = 2,
CAMERA_ANI_JUMPPANROT = 3,
CAMERA_ANI_3D2WALK = 4,
CAMERA_ANI_3DTO2D = 5,
CAMERA_ANI_2DTO3D = 6,
CAMERA_ANI_DEVICE_ROT = 7,
CAMERA_ANI_FIXEDFREE = 8,
CAMERA_ANI_YAW_ROTATE = 9,
};
enum vbViewControlSet
{
vbViewControlSetDefaultLBS =0, //PISA
vbViewControlSetYawPitch =1, //IIAC
vbViewControlSetStandardI =2, //STD1
vbViewControlSetGongVueTypeA=3, //GongVue Type A
vbViewControlSetZoneView =4, //Zone view - Yaw only
vbViewControlSetPalladiON =5, //PISA default에서 수직 제어 없애고 수평 연속 회전 되도록 함.
vbViewControlSetPlanar3D =6, //2touch planar rotation
vbViewControlSetFixedFPS =7 //임의 좌표에서 임의 방향을 바라 볼 수 있도록 함(터치로는 제어 안됨)
};
struct vbScreenControlAreaParam
{
/*
0 - LControl left px offset from Left
1 - LControl right px offset from Left
2 - RControl left px offset from Right
3 - RControl right px offset from
4 - BControl top px offset from bottom
5 - BControl bottom px offset from bottom
6 - TControl top px offset from top
7 - TControl bottom px offset from top
*/
unsigned short area_param[8];
};
enum vbViewScreenControlArea
{
vbViewScreenControlAreaMid = 0,
vbViewScreenControlAreaTop = 1,
vbViewScreenControlAreaLeft = 2,
vbViewScreenControlAreaRight = 3,
vbViewScreenControlAreaBottom = 4
};
protected:
//vbConfiguration
vbConfiguration* m_pConf;
vbScreenControlAreaParam m_area_param;
//GroundPlane
vbPlane m_ground_plane;
//Pan Valid range
float m_pan_valid_ratio;
//View Matrix
mat4 m_view_matrix;
//Projection Matrix
mat4 m_prj_matrix;
//view matrix X projection matrix - for Window/World conversion
mat4 m_view_prj_matrix;
bool m_bViewUpdated;
//Projection mode
ProjectionMode m_projection_mode; //Projection mode
float m_min_near_clip;
float m_rad_bounding_sphere;
vec3 m_bounding_center;
vec3 m_bound_min;
vec3 m_bound_max;
//Camera
vbCamera m_Camera;
//Move
vbFPSCameraControl m_CameraFPSControl;
vbMoveOrbitZoomCameraControl m_CameraZoomControl;
vbHorizontalPanCameraControl m_CameraHPanControl;
vbMovingForwardCameraControl m_CameraForwardControl;
//Rotation
vbTrackCameraControl m_CameraTrackControl;
vbFreeCameraControl m_CameraFreeControl;
//Animation
vbAnimationCameraControl m_CameraAnimationControl;
//Projection
vbPerspectiveProjection m_CameraPerspective;
vbOrthogonalProjection m_CameraOrthogonal;
float m_cam_fMaxDistRatioBBSize;
float m_cam_fMaxPanRatioToBSphereRad;
bool m_cam_bJumpZoomed;
//Environment sphere
float m_cam_fEnvSphereRadius;
//Camera animation
CameraAniMode m_cam_ani_mode;
float m_cam_jumpzoom_ratio;
bool m_cam_jumpzoom_with_jumppan;
//
bool m_bBrokePan;
bool m_bBrokeZoom;
bool m_bBrokeRotate;
//Navigation
NavigationMode m_cam_navi_mode; //camera navigation mode
NavigationMode m_cam_navi_mode_backup; //camera navigation mode
NavigationMode3D m_cam_navi_3d_mode; //
bool m_bNavigation;
ivec2 m_DownPos_prev;
vec3 m_cam_reference3D_first; //Reference 3d position 1
vec3 m_cam_reference3D_second; //Reference 3d position 2
//3D View camera backup
Quaternion m_cam_3D_backup_rotation;
vec3 m_cam_3D_backup_orbit_cntr;
float m_cam_3D_backup_distance;
//Turn angle
float m_fDeviceAngle;
vbViewDirection m_eViewDirection;
//View mode
vbViewControlSet m_eViewControlSet;
float m_fRotateAreaRatio; //화면의 아래쪽에서 몇 %까지 수평 회전 영역에 쓸 것인지 (0~1)
public:
CameraAniMode GetAniMode() { return m_cam_ani_mode; };
vbMoveOrbitZoomCameraControl* GetCameraControl_OrbitZoom() { return &m_CameraZoomControl; }
vbTrackCameraControl* GetCameraTrackControl() { return &m_CameraTrackControl; }
//Turn
vbViewDirection GetViewTurnDirection() { return m_eViewDirection; };
void SetViewTurnDirection(vbViewDirection dir, bool bAnimating=false);
float GetDeviceAngle() { return m_fDeviceAngle; };
void UpdateDeviceAngleDeg();
ivec2 ConvertToRotatedDeviceCoord(ivec2 tPos);
//Init
void InitializeViewInfo(int width, int height, vbConfiguration* pConf);
void ReloadConfiguration();
//Viewport
void SetScreenSize(ivec2 screen_size);
ivec2 GetScreenSize() ;
////////////////////////////////////// Projection - vbViewInfoProjection.cpp
//View matrix
mat4* GetViewMatrix() { return &m_view_matrix; }
float const* GetViewMatrixPointer() { return m_view_matrix.Pointer(); }
void SetViewMatrix(mat4 view_mat) { m_view_matrix = view_mat; }
void UpdateViewMatrix();
//Projection matrix
mat4* GetProjectionMatrix() { return &m_prj_matrix; }
float const* GetProjectionMatrixPointer() { return m_prj_matrix.Pointer(); }
void SetProjectionMatrix(mat4 view_mat) { m_prj_matrix = view_mat; }
void UpdateProjectionMatrix();
ivec2 WorldToWindow(vec3 world_pt);
void WindowToWorld(ivec2 win_pos, vec3& near_pt, vec3& far_pt);
mat4* GetViewProjectionMatrix() { return &m_view_prj_matrix; }
bool IsViewUpdated() { return m_bViewUpdated; }
void SetViewUpdated(bool bUpdated) { m_bViewUpdated = bUpdated; }
//Projection mode
ProjectionMode GetProjectionMode() { return m_projection_mode; }
void SetProjectionMode(ProjectionMode mode) { m_projection_mode = mode; }
//Perspective
void SetPerspectiveParameters(float* perspective_param);
void SetPerspectiveParameters(float fovy, float aspect, float near, float far);
const float* GetPerspectiveParameters();
void UpdateNearFarClip();
public:
//Orthogonal
void SetOrthogonalParameters(float left, float right, float bottom, float top, float near, float far);
const float* GetOrthogonalParameters();
////////////////////////////////////// Projection - vbViewInfoProjection.cpp
////////////////////////////////////// Navigation - vbViewInfoNavi.cpp
//Fit
void FitAABBtoScreen(bool bBoundMinMaxDist=false);
void FitAABBtoVertices(std::vector<vec3>& target_vtx, bool bBoundMinMaxDist=false);
//Ground
void SetGroundPlane(vbPlane ground_plane) { m_ground_plane = ground_plane; }
vbPlane GetGroundPlane() { return m_ground_plane; }
float GetPanValidRatio() { return m_pan_valid_ratio; }
void SetPanValidRatio(float pRatio) { m_pan_valid_ratio = pRatio; }
void SetPanValidRange(vec3 min, vec3 max, float pRatio);
//Orbit
float GetTrackBallRatio();
void SetTrackBallRatio(float trRatio);
void SetOrbitCenter(vec3 orbit_center);
vec3 GetOrbitCenter();
void StartFreeRotation(ivec2 finger_pos);
bool DoFreeRotation(ivec2 touchpoint);
void StartRotation(ivec2 finger_pos);
void StartHRotation(ivec2 finger_pos);
void StartVRotation(ivec2 finger_pos);
void StartYawPitchRotation(ivec2 finger_pos);
bool DoOrbit(ivec2 touchpoint); //싱글터치, 초기 이동 방향에 따라 수직/수평 회전
bool DoYawRotation(ivec2 touchpoint); //수평 왕복 회전
bool DoContinuousYawRotation(ivec2 touchpoint); //수평 연속 회전
bool DoPitchRotation(ivec2 touchpoint); //수직 회전
bool DoYawPitchRotation(ivec2 touchpoint); //수직/수평 회전
bool DoLandscapeYawPitchRotation(ivec2 touchpoint); //VR용 수직,수평 회전
void EndRotation();
void JumpOrbit(ivec2 finger_pos);
void SetHRotationRatio(float fVertialRatioFromBottom) { m_fRotateAreaRatio=fVertialRatioFromBottom;}
float GetHRotationRatio() { return m_fRotateAreaRatio; }
bool StartHRotationAnimation(float fStepYaw);
bool EndHRotationAnimation();
//Panning
void StartHPanning(ivec2 finger_pos);
bool DoHPanning(ivec2 touchpoint);
void EndHPanning();
void JumpPanning(ivec2 finger_pos);
void JumpPanning(vec3 new_orbit_cntr);
void JumpPanRotation(vec3 new_orbit_cntr, Quaternion new_orientation);
void UpdateValidRange(vec3 bbMin, vec3 bbMax);
//Zoom
void StartZooming(ivec2 finger_pos);
bool DoZooming(ivec2 touchpoint);
void EndZooming();
void StartZooming2Pt(ivec2 finger_pos1,ivec2 finger_pos2);
void StartZooming2PtEnvironment(ivec2 finger_pos1,ivec2 finger_pos2);
bool DoZooming2Pt(ivec2 finger_pos1,ivec2 finger_pos2);
bool DoZooming2PtEnvironment(ivec2 finger_pos1,ivec2 finger_pos2);
void JumpZooming(ivec2 finger_pos);
void SphereJumpZooming(ivec2 finger_pos);
float GetPreviousZoomDistance();
void SetPreviousZoomDistance(float prevDist);
//Pan & Zoom
void StartPanZoom(ivec2 pos1, ivec2 pos2);
bool DoPanZoom(ivec2 pos1, ivec2 pos2);
void EndPanZoom();
//HRotate & Zoom
void StartHRotateZoom(ivec2 pos1, ivec2 pos2);
bool DoHRotateZoom(ivec2 pos1, ivec2 pos2);
void EndHRotateZoom();
//Fixed Yaw & Pitch control
void StartFixedYawPitchRotate(ivec2 pos1);
void StartForwardZoom(ivec2 pos1, ivec2 pos2);
void StartElevation(ivec2 pos1);
bool DoFixedYawRotate(ivec2 pos1);
bool DoFixedPitchRotate(ivec2 pos1);
bool DoFixedYawPitchRotate(ivec2 pos1);
bool DoForwardZoom(ivec2 pos1, ivec2 pos2);
bool DoElevation(ivec2 pos1);
void EndFixedYawPitchRotate();
void EndForwardZoom();
//
void BrokeControl(bool bBrokePan, bool bBrokeZoom, bool bBrokeRotate);
//Navi
void InvalidateManipulation();
//2D-3D Camera
void SetTopView();
void ReturnTo3DView();
//Walk
float GetEyeHeight();
void SetEyeHeight(float eye_h);
void InitWalk();//현재 회전 중심 위치로 내려가 걸어다닌다.
void StartWalking(ivec2 finger_pos);
bool DoWalking(ivec2 finger_pos);
void EndWalking();
void SetWalkingCamera(vec3 pos, Quaternion dir);
//FPS-Manipulation
void StartFPS();
void EndFPS();
//Navigation mode
bool IsNavigation() { return m_bNavigation; }
void SetNavigation(bool bNavi) { m_bNavigation = bNavi; }
NavigationMode GetNavigationMode() { return m_cam_navi_mode; }
bool SetNavigationMode(NavigationMode nMode);
void RecoverNavigationMode();
//Calculation
vec3 MapToSphere(ivec2 touchpoint);
vec3 GetRayFromCamera(ivec2 win_pos, vec3& fromPt);
vec3 GetRayIntersectionWithGround(ivec2 ray_win_pos); //Ground = XY Plane
////////////////////////////////////// Navigation - vbViewInfoNavi.cpp
////////////////////////////////////// Camera - vbViewInfoCamera.cpp
//camera position
void SetCameraPosition(vec3 cam_pos);
vec3 GetCameraPosition();
void UpdateCameraPositionFromOrbit();//Orbit center에서 지정된 distance에 지정 된 방향으로 위치
void UpdateCameraTargetPosition();
void UpdateOrbitCenterFromCamPosition();
void InitOrientation(bool bUpdateViewMat=true);
void SetCameraPitchRatio(float pitch_ratio);
float GetPitchRatio();
float GetPitchDegree();
float GetYawDegree();
void SetYawDegree(float fYaw);
void SetYawDegree(vec3 dirYaw);
void SetCamera(float cx, float cy, float cz,
float yaw_deg_from_nZ, float pitch_deg_from_xz_plane,
float fDist);
//camera distance
float GetCameraDistance();
void SetCameraDistance(float dist, bool bBoundMinMaxDistance=false);
void SetCameraMaxDistanceRatioBBSize(float ratio) { m_cam_fMaxDistRatioBBSize = ratio; }
void SetCameraMaxPanRatioBSphereRad(float ratio) { m_cam_fMaxPanRatioToBSphereRad = ratio; }
void SetCameraMinMaxDistance(float fMinDistance, float fMaxDistance, bool bBoundMinMaxDist=false);
//Zoom In/Out (Close to/ Far fromt Rot.Center)
void MoveToRotationCenter(bool bToCenter);
//Environmental map
void SetEnvironmentalCamera();
//camera orientation
void SetOrientation(Quaternion qtn);
Quaternion GetOrientation(); //회전 쿼터니언을 반환한다.
vec3 GetDirection(); //카메라의 방향 벡터
vec3 GetRight();
vec3 GetUp();
//Environment map
float GetEnvironmentSphereRadius() { return m_cam_fEnvSphereRadius; }
//camera fitting
void FullExtendVertexVector(std::vector<vec3>& target_vtx, bool bBoundMinMaxDist=false);
bool GetPerspectiveFittingCameraPosition(vec3 inputCameraDirection,/*대상을 바라보고 있을 카메라의 방향. 보통 현재 카메라의 방향*/
vec3 inputCameraUp,/*대상을 바라보고 있을 카메라의 Upvector.*/
float inputCameraFOV_Y_radian,/*카메라의 세로 방향 시야각*/
float inputCameraFOV_X_radian,/*카메라의 가로 방향 시야각*/
std::vector<vec3>& inputVts,/*Fitting 대상이 되는 점들*/
float inputFit_ratio,/* 1 : 화면에 꼭 맞게, 0.5 : 화면의 절반 크기에 맞게, 0.01 : 최소값*/
vec3& outputCameraPosition,/*카메라의 위치*/
vec3& outputOrbitCenter,//New orbit center
bool& outVerticalFit,/*세로방향으로 맞췄는지 여부*/
float& outDistance,
bool bBoundMinMaxDist=false);//
//Orthogonal mode에서 Fitting
bool GetOrthogonalFittingCameraPosition(vec3 inputCameraDirection/*대상을 바라보고 있을 카메라의 방향. 보통 현재 카메라의 방향*/,
vec3 inputCameraUp/*대상을 바라보고 있을 카메라의 Upvector.*/,
std::vector<vec3>& inputVts/*Fitting 대상이 되는 점들*/,
float inputFit_ratio/* 1 : 화면에 꼭 맞게, 0.5 : 화면의 절반 크기에 맞게, 0.01 : 최소값*/,
float inputDistance_for_ortho/*직교투영은 원근감이 없으므로, 거리에 상관없이 동일한 화면이 나오기 때문에 거리를 지정해야 한다*/,
float inputViewAspectRatio/* Width/height*/,
vec3& outputCameraPosition/*카메라의 위치*/,
float& outputCamWidth/*카메라의 Orthogonal Width*/,
float& outputCamHeight/*카메라의 Orthogonal Height*/,
bool& outVerticalFit);/*세로방향으로 맞췄는지 여부*/
void UpdateCameraDistWithScreenCenter(bool bBoundMinMaxDist=false);
//
////////////////////////////////////// Camera - vbViewInfoCamera.cpp
//////////////////// RANGE PARAMETER
const vbScreenControlAreaParam* GetScreenAreaParam() { return (const vbScreenControlAreaParam*)&m_area_param; }
void SetScreenAreaParam(const vbScreenControlAreaParam* pParam);
vbViewScreenControlArea IsScreenControlArea(ivec2 tPos);
////////////////////////////////////// Interaction - vbViewInfoFinger.cpp
//Touch interaction
bool SingleFingerUp(ivec2 tPos, int tapCount, vec3& pos3d);
void SingleFingerDown(ivec2 tPos, int tapCount);
bool SingleFingerMove(ivec2 tPos, int tapCount);
bool DoubleFingerUp(ivec2 pos1/*pressed*/, int tapCount1,ivec2 pos2/*unpressed*/, int tapCount2);
void DoubleFingerDown(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2);
bool DoubleFingerMove(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2);
vbViewControlSet GetViewControlSet() { return m_eViewControlSet; }
void SetViewControlSet(vbViewControlSet viewControlSet) { m_eViewControlSet = viewControlSet; }
/////////////// ViewControlSet별 이벤트 처리 함수
//////////// Default
bool SingleFingerUp_Default(ivec2 tPos, int tapCount, vec3& pos3d);
void SingleFingerDown_Default(ivec2 tPos, int tapCount);
bool SingleFingerMove_Default(ivec2 tPos, int tapCount);
bool DoubleFingerUp_Default(ivec2 pos1/*pressed*/, int tapCount1,ivec2 pos2/*unpressed*/, int tapCount2);
void DoubleFingerDown_Default(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2);
bool DoubleFingerMove_Default(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2);
//////////// Yaw & Pitch
bool SingleFingerUp_YawPitch(ivec2 tPos, int tapCount, vec3& pos3d);
void SingleFingerDown_YawPitch(ivec2 tPos, int tapCount);
bool SingleFingerMove_YawPitch(ivec2 tPos, int tapCount);
bool DoubleFingerUp_YawPitch(ivec2 pos1/*pressed*/, int tapCount1,ivec2 pos2/*unpressed*/, int tapCount2);
void DoubleFingerDown_YawPitch(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2);
bool DoubleFingerMove_YawPitch(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2);
//////////// STD1
bool SingleFingerUp_STD1(ivec2 tPos, int tapCount, vec3& pos3d);
void SingleFingerDown_STD1(ivec2 tPos, int tapCount);
bool SingleFingerMove_STD1(ivec2 tPos, int tapCount);
bool DoubleFingerUp_STD1(ivec2 pos1/*pressed*/, int tapCount1,ivec2 pos2/*unpressed*/, int tapCount2);
void DoubleFingerDown_STD1(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2);
bool DoubleFingerMove_STD1(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2);
//////////// GongVueA
bool SingleFingerUp_GongVueA(ivec2 tPos, int tapCount, vec3& pos3d);
void SingleFingerDown_GongVueA(ivec2 tPos, int tapCount);
bool SingleFingerMove_GongVueA(ivec2 tPos, int tapCount);
bool DoubleFingerUp_GongVueA(ivec2 pos1/*pressed*/, int tapCount1,ivec2 pos2/*unpressed*/, int tapCount2);
void DoubleFingerDown_GongVueA(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2);
bool DoubleFingerMove_GongVueA(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2);
//////////// ZoneView
bool SingleFingerUp_ZoneView(ivec2 tPos, int tapCount, vec3& pos3d);
void SingleFingerDown_ZoneView(ivec2 tPos, int tapCount);
bool SingleFingerMove_ZoneView(ivec2 tPos, int tapCount);
bool DoubleFingerUp_ZoneView(ivec2 pos1/*pressed*/, int tapCount1,ivec2 pos2/*unpressed*/, int tapCount2);
void DoubleFingerDown_ZoneView(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2);
bool DoubleFingerMove_ZoneView(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2);
//////////// PalladiON
bool SingleFingerUp_PalladiON(ivec2 tPos, int tapCount, vec3& pos3d);
void SingleFingerDown_PalladiON(ivec2 tPos, int tapCount);
bool SingleFingerMove_PalladiON(ivec2 tPos, int tapCount);
bool DoubleFingerUp_PalladiON(ivec2 pos1/*pressed*/, int tapCount1,ivec2 pos2/*unpressed*/, int tapCount2);
void DoubleFingerDown_PalladiON(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2);
bool DoubleFingerMove_PalladiON(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2);
//////////// Planar3D
bool SingleFingerUp_Planar3D(ivec2 tPos, int tapCount, vec3& pos3d);
void SingleFingerDown_Planar3D(ivec2 tPos, int tapCount);
bool SingleFingerMove_Planar3D(ivec2 tPos, int tapCount);
bool DoubleFingerUp_Planar3D(ivec2 pos1/*pressed*/, int tapCount1,ivec2 pos2/*unpressed*/, int tapCount2);
void DoubleFingerDown_Planar3D(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2);
bool DoubleFingerMove_Planar3D(ivec2 pos1, int tapCount1,ivec2 pos2, int tapCount2);
////////////////////////////////////// Interaction - vbViewInfoFinger.cpp
/////////////////////////////////////// Animation - vbViewInfoAnimation.cpp
void UseCameraAnimation(bool bUseCameraAnimation);
bool IsCameraAnimationAvailable();
void UpdateAnimationFrame();
bool UpdateWalkingAnimation();
void InitCameraMoveAni(vec3 pos_start, vec3 pos_end, Quaternion dir_start, Quaternion dir_end, CameraAniMode aniMode);
void InitDeviceRotateAni(vbViewDirection eEndDirection);
void UpdateAnimatedCamera();
bool IsOnAnimating();
/////////////////////////////////////// Animation - vbViewInfoAnimation.cpp
/////////
}; | 24,117 | 8,472 |
#ifndef CONTRACTOR_TERMS_GENERALTERM_HPP_
#define CONTRACTOR_TERMS_GENERALTERM_HPP_
#include "terms/Tensor.hpp"
#include "terms/Term.hpp"
#include <memory>
#include <vector>
namespace Contractor::Terms {
class BinaryTerm;
/**
* This special kind of Term simply describes the contained Terms as a list of Tensors. No information about
* the optimal order of factorizing the different Tensors is contained (hence the name).
*/
class GeneralTerm : public Term {
public:
/**
* Type of the container used to store the Tensors
*/
using tensor_list_t = std::vector< Tensor >;
explicit GeneralTerm(const Tensor &result = Tensor(), Term::factor_t prefactor = {},
const tensor_list_t &tensorList = {});
explicit GeneralTerm(const Tensor &result, Term::factor_t prefactor, tensor_list_t &&tensorList);
explicit GeneralTerm(const BinaryTerm &binary);
GeneralTerm(const GeneralTerm &) = default;
GeneralTerm(GeneralTerm &&other) = default;
GeneralTerm &operator=(const GeneralTerm &other) = default;
GeneralTerm &operator=(GeneralTerm &&other) = default;
virtual std::size_t size() const override;
/**
* Adds a copy of the given Tensor to this Term
*/
void add(const Tensor &tensor);
/**
* Adds the given Tensor to this Term
*/
void add(Tensor &&tensor);
/**
* Removes a Tensor matching the given one from this Term
*
* @returns Whether the removal was successful
*/
bool remove(const Tensor &tensor);
/**
* @returns A mutable reference of the contained Tensor list
*/
tensor_list_t &accessTensorList();
/**
* @returns A reference of the contained Tensor list
*/
const tensor_list_t &accessTensorList() const;
virtual void sort() override;
protected:
tensor_list_t m_tensors;
Tensor &get(std::size_t index) override;
const Tensor &get(std::size_t index) const override;
};
}; // namespace Contractor::Terms
#endif // CONTRACTOR_TERMS_GENERALTERM_HPP_
| 1,916 | 628 |
/*
* Licensed under the Apache License, Version 2.0 (the 'License');
* you may not use this file except in compliance with the License.
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "allocator/CrSeparableAllocator.h"
#include <factory/ObjectFactory.h>
#include <cassert>
#include "arbiter/Arbiter.h"
CrSeparableAllocator::CrSeparableAllocator(
const std::string& _name, const Component* _parent,
u32 _numClients, u32 _numResources, Json::Value _settings)
: Allocator(_name, _parent, _numClients, _numResources, _settings) {
// pointer arrays
requests_ = new bool*[numClients_ * numResources_];
metadatas_ = new u64*[numClients_ * numResources_];
intermediates_ = new bool[numClients_ * numResources_];
grants_ = new bool*[numClients_ * numResources_];
// use vector to hold arbiter pointers
clientArbiters_.resize(numClients_, nullptr);
resourceArbiters_.resize(numResources_, nullptr);
// instantiate the client arbiters
for (u32 c = 0; c < numClients_; c++) {
std::string name = "ArbiterC" + std::to_string(c);
clientArbiters_[c] = Arbiter::create(
name, this, numResources_, _settings["client_arbiter"]);
}
// instantiate the resource arbiters
for (u32 r = 0; r < numResources_; r++) {
std::string name = "ArbiterR" + std::to_string(r);
resourceArbiters_[r] = Arbiter::create(
name, this, numClients_, _settings["resource_arbiter"]);
}
// map intermediate request signals to arbiters
for (u32 c = 0; c < numClients_; c++) {
for (u32 r = 0; r < numResources_; r++) {
bool* i = &intermediates_[index(c, r)];
clientArbiters_[c]->setGrant(r, i);
resourceArbiters_[r]->setRequest(c, i);
}
}
// parse settings
iterations_ = _settings["iterations"].asUInt();
assert(iterations_ > 0);
slipLatch_ = _settings["slip_latch"].asBool();
}
CrSeparableAllocator::~CrSeparableAllocator() {
for (u32 c = 0; c < numClients_; c++) {
delete clientArbiters_[c];
}
for (u32 r = 0; r < numResources_; r++) {
delete resourceArbiters_[r];
}
delete[] requests_;
delete[] metadatas_;
delete[] intermediates_;
delete[] grants_;
}
void CrSeparableAllocator::setRequest(u32 _client, u32 _resource,
bool* _request) {
requests_[index(_client, _resource)] = _request;
clientArbiters_[_client]->setRequest(_resource, _request);
}
void CrSeparableAllocator::setMetadata(u32 _client, u32 _resource,
u64* _metadata) {
metadatas_[index(_client, _resource)] = _metadata;
clientArbiters_[_client]->setMetadata(_resource, _metadata);
resourceArbiters_[_resource]->setMetadata(_client, _metadata);
}
void CrSeparableAllocator::setGrant(u32 _client, u32 _resource, bool* _grant) {
grants_[index(_client, _resource)] = _grant;
resourceArbiters_[_resource]->setGrant(_client, _grant);
}
void CrSeparableAllocator::allocate() {
for (u32 remaining = iterations_; remaining > 0; remaining--) {
// clear the intermediate stage
for (u32 c = 0; c < numClients_; c++) {
for (u32 r = 0; r < numResources_; r++) {
intermediates_[index(c, r)] = false;
}
}
// run the client arbiters
for (u32 c = 0; c < numClients_; c++) {
clientArbiters_[c]->arbitrate();
// perform arbiter state latching
if (!slipLatch_) {
// regular latch always algorithm
clientArbiters_[c]->latch();
}
}
// run the resource arbiters
for (u32 r = 0; r < numResources_; r++) {
u32 winningClient = resourceArbiters_[r]->arbitrate();
if (winningClient != U32_MAX) {
// remove the requests from this client
for (u32 r = 0; r < numResources_; r++) {
*requests_[index(winningClient, r)] = false;
}
// remove the requests for this resource
for (u32 c = 0; c < numClients_; c++) {
*requests_[index(c, r)] = false;
}
}
// perform arbiter state latching
if (slipLatch_) {
// slip latching (iSLIP algorithm)
if (winningClient != U32_MAX) {
resourceArbiters_[r]->latch();
clientArbiters_[winningClient]->latch();
}
} else {
// regular latch always algorithm
resourceArbiters_[r]->latch();
}
}
}
}
u64 CrSeparableAllocator::index(u64 _client, u64 _resource) const {
return (numResources_ * _client) + _resource;
}
registerWithObjectFactory("cr_separable", Allocator, CrSeparableAllocator,
ALLOCATOR_ARGS);
| 5,051 | 1,729 |
/*
* LibCassandra
* Copyright (C) 2010 Padraig O'Sullivan
* All rights reserved.
*
* Use and distribution licensed under the BSD license. See
* the COPYING file in the parent directory for full text.
*/
#include <string>
#include <sstream>
#include "libcassandra/cassandra.h"
#include "libcassandra/cassandra_host.h"
#include "libcassandra/util_functions.h"
using namespace std;
using namespace libcassandra;
CassandraHost::CassandraHost()
:
name(),
host(),
ip_address(),
url(),
port(0)
{
}
CassandraHost::CassandraHost(const string &in_url)
:
name(),
host(),
ip_address(),
url(in_url),
port(0)
{
host= parseHostFromURL(url);
port= parsePortFromURL(url);
}
CassandraHost::CassandraHost(const string &in_host, int in_port)
:
name(),
host(in_host),
ip_address(),
url(),
port(in_port)
{
url.append(host);
url.append(":");
ostringstream port_str;
port_str << port;
url.append(port_str.str());
}
CassandraHost::~CassandraHost() {}
const string &CassandraHost::getName() const
{
return name;
}
const string &CassandraHost::getHost() const
{
return host;
}
const string &CassandraHost::getIPAddress() const
{
return ip_address;
}
const string &CassandraHost::getURL() const
{
return url;
}
int CassandraHost::getPort() const
{
return port;
}
| 1,354 | 508 |
/******************************************************************************
* Copyright (c) 2018, Sylvain Corlay and Johan Mabille, and Wolf Vollprecht *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
*******************************************************************************/
#ifndef XLEAFLET_TILE_LAYER_HPP
#define XLEAFLET_TILE_LAYER_HPP
#include <string>
#include "xwidgets/xmaterialize.hpp"
#include "xwidgets/xwidget.hpp"
#include "xleaflet_config.hpp"
#include "xraster_layer.hpp"
namespace xlf
{
/**************************
* tile_layer declaration *
**************************/
template <class D>
class xtile_layer : public xraster_layer<D>
{
public:
using load_callback_type = std::function<void(const xeus::xjson&)>;
using base_type = xraster_layer<D>;
using derived_type = D;
void serialize_state(xeus::xjson&, xeus::buffer_sequence&) const;
void apply_patch(const xeus::xjson&, const xeus::buffer_sequence&);
void on_load(load_callback_type);
void handle_custom_message(const xeus::xjson&);
XPROPERTY(
std::string, derived_type, url,
"https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png");
XPROPERTY(int, derived_type, min_zoom, 0);
XPROPERTY(int, derived_type, max_zoom, 18);
XPROPERTY(int, derived_type, tile_size, 256);
XPROPERTY(
std::string, derived_type, attribution,
"Map data (c) <a href=\"https://openstreetmap.org\">OpenStreetMap</a> contributors");
XPROPERTY(bool, derived_type, detect_retina, false);
protected:
xtile_layer();
using base_type::base_type;
private:
void set_defaults();
std::list<load_callback_type> m_load_callbacks;
};
using tile_layer = xw::xmaterialize<xtile_layer>;
using tile_layer_generator = xw::xgenerator<xtile_layer>;
/******************************
* xtile_layer implementation *
******************************/
template <class D>
inline void xtile_layer<D>::serialize_state(xeus::xjson& state,
xeus::buffer_sequence& buffers) const
{
base_type::serialize_state(state, buffers);
using xw::set_patch_from_property;
set_patch_from_property(url, state, buffers);
set_patch_from_property(min_zoom, state, buffers);
set_patch_from_property(max_zoom, state, buffers);
set_patch_from_property(tile_size, state, buffers);
set_patch_from_property(attribution, state, buffers);
set_patch_from_property(detect_retina, state, buffers);
}
template <class D>
inline void xtile_layer<D>::apply_patch(const xeus::xjson& patch,
const xeus::buffer_sequence& buffers)
{
base_type::apply_patch(patch, buffers);
using xw::set_property_from_patch;
set_property_from_patch(url, patch, buffers);
set_property_from_patch(min_zoom, patch, buffers);
set_property_from_patch(max_zoom, patch, buffers);
set_property_from_patch(tile_size, patch, buffers);
set_property_from_patch(attribution, patch, buffers);
set_property_from_patch(detect_retina, patch, buffers);
}
template <class D>
inline void xtile_layer<D>::on_load(load_callback_type callback)
{
m_load_callbacks.emplace_back(std::move(callback));
}
template <class D>
inline xtile_layer<D>::xtile_layer()
: base_type()
{
set_defaults();
}
template <class D>
inline void xtile_layer<D>::set_defaults()
{
this->_model_name() = "LeafletTileLayerModel";
this->_view_name() = "LeafletTileLayerView";
this->bottom() = true;
this->options().insert(
this->options().end(),
{
"min_zoom",
"max_zoom",
"tile_size",
"attribution",
"detect_retina"
}
);
}
template <class D>
inline void xtile_layer<D>::handle_custom_message(const xeus::xjson& content)
{
auto it = content.find("event");
if (it != content.end() && it.value() == "load")
{
for (auto it = m_load_callbacks.begin(); it != m_load_callbacks.end(); ++it)
{
it->operator()(content);
}
}
}
}
/*********************
* precompiled types *
*********************/
#ifndef _WIN32
extern template class xw::xmaterialize<xlf::xtile_layer>;
extern template xw::xmaterialize<xlf::xtile_layer>::xmaterialize();
extern template class xw::xtransport<xw::xmaterialize<xlf::xtile_layer>>;
extern template class xw::xgenerator<xlf::xtile_layer>;
extern template xw::xgenerator<xlf::xtile_layer>::xgenerator();
extern template class xw::xtransport<xw::xgenerator<xlf::xtile_layer>>;
#endif
#endif
| 5,279 | 1,652 |
#include "stdafx.h"
// General
#include "MPQArchiveManager.h"
// Additional
#include "BaseManager.h"
#if (VERSION == VERSION_Vanila)
const char* archives = "D:/_games/World of Warcraft 1.12.1/Data/";
#elif (VERSION == VERSION_WotLK)
const char* archives = "D:/_games/World of Warcraft 3.3.5a/Data/";
#endif
//
CMPQArchiveManager::CMPQArchiveManager()
{
AddManager<IMPQArchiveManager>(this);
// Files 1.12
#if (VERSION == VERSION_Vanila)
AddArchive(string("backup.MPQ"));
AddArchive(string("base.MPQ"));
AddArchive(string("dbc.MPQ"));
AddArchive(string("fonts.MPQ"));
AddArchive(string("interface.MPQ"));
AddArchive(string("misc.MPQ"));
AddArchive(string("model.MPQ"));
AddArchive(string("patch.MPQ"));
AddArchive(string("patch-2.MPQ"));
AddArchive(string("patch-3.MPQ"));
AddArchive(string("sound.MPQ"));
AddArchive(string("speech.MPQ"));
AddArchive(string("terrain.MPQ"));
AddArchive(string("texture.MPQ"));
AddArchive(string("wmo.MPQ"));
//AddArchive(string("ruRU/patch-1.MPQ"));
//AddArchive(string("ruRU/patch-2.MPQ"));
//AddArchive(string("ruRU/patch-3.MPQ"));
#elif (VERSION == VERSION_WotLK)
AddArchive(string("common.MPQ"));
AddArchive(string("common-2.MPQ"));
AddArchive(string("expansion.MPQ"));
AddArchive(string("lichking.MPQ"));
AddArchive(string("patch.MPQ"));
AddArchive(string("patch-2.MPQ"));
AddArchive(string("patch-3.MPQ"));
//AddArchive(string("patch-w.MPQ"));
//AddArchive(string("patch-x.MPQ"));
AddArchive(string("ruRU/locale-ruRU.MPQ"));
AddArchive(string("ruRU/expansion-locale-ruRU.MPQ"));
AddArchive(string("ruRU/lichking-locale-ruRU.MPQ"));
AddArchive(string("ruRU/patch-ruRU.MPQ"));
AddArchive(string("ruRU/patch-ruRU-2.MPQ"));
AddArchive(string("ruRU/patch-ruRU-3.MPQ"));
//AddArchive(string("ruRU/patch-ruRU-w.MPQ"));
//AddArchive(string("ruRU/patch-ruRU-x.MPQ"));
#endif
}
CMPQArchiveManager::~CMPQArchiveManager()
{
for (auto it : m_OpenArchives)
{
libmpq__archive_close(it);
}
}
void CMPQArchiveManager::AddArchive(string filename)
{
mpq_archive_s* mpq_a;
int result = libmpq__archive_open(&mpq_a, (archives + filename).c_str(), -1);
Log::Info("Opening %s", filename.c_str());
if (result)
{
switch (result)
{
case LIBMPQ_ERROR_OPEN:
Log::Error("Error opening archive [%s]: Does file really exist?", filename.c_str());
break;
case LIBMPQ_ERROR_FORMAT: /* bad file format */
Log::Error("Error opening archive [%s]: Bad file format", filename.c_str());
break;
case LIBMPQ_ERROR_SEEK: /* seeking in file failed */
Log::Error("Error opening archive [%s]: Seeking in file failed", filename.c_str());
break;
case LIBMPQ_ERROR_READ: /* Read error in archive */
Log::Error("Error opening archive [%s]: Read error in archive", filename.c_str());
break;
case LIBMPQ_ERROR_MALLOC: /* maybe not enough memory? :) */
Log::Error("Error opening archive [%s]: Maybe not enough memory", filename.c_str());
break;
default:
Log::Error("Error opening archive [%s]: Unknown error\n", filename.c_str());
break;
}
return;
}
m_OpenArchives.push_back(mpq_a);
Log::Green("CMPQFile[%s]: Added!", filename.c_str());
}
SMPQFileLocation CMPQArchiveManager::GetFileLocation(cstring filename)
{
for (auto& i = m_OpenArchives.rbegin(); i != m_OpenArchives.rend(); ++i)
{
mpq_archive_s* mpq_a = *i;
uint32 filenum;
if (libmpq__file_number(mpq_a, filename.c_str(), &filenum) == LIBMPQ_ERROR_EXIST)
{
continue;
}
return SMPQFileLocation(mpq_a, filenum);
}
return SMPQFileLocation();
} | 3,579 | 1,464 |
#include <iostream>
using namespace std;
int main()
{
int test;
cin >> test;
int PP[] = {2, 3, 5, 7, 11, 101, 131, 151, 181, 191, 313, 353, 373, 383, 727, 757, 787, 797, 919, 929, 10301, 10501, 10601, 11311, 11411, 12421, 12721, 12821, 13331, 13831, 13931, 14341, 14741, 15451, 15551, 16061, 16361, 16561, 16661, 17471, 17971, 18181, 18481, 19391, 19891, 19991, 30103, 30203, 30403, 30703, 30803, 31013, 31513, 32323, 32423, 33533, 34543, 34843, 35053, 35153, 35353, 35753, 36263, 36563, 37273, 37573, 38083, 38183, 38783, 39293, 70207, 70507, 70607, 71317, 71917, 72227, 72727, 73037, 73237, 73637, 74047, 74747, 75557, 76367, 76667, 77377, 77477, 77977, 78487, 78787, 78887, 79397, 79697, 79997, 90709, 91019, 93139, 93239, 93739, 94049, 94349, 94649, 94849, 94949, 95959, 96269, 96469, 96769, 97379, 97579, 97879, 98389, 98689};
int P[] = {3, 5, 11, 17, 2, 2, 5, 11, 19, 23, 23, 197, 307, 359, 521, 1553, 2693, 3083, 419, 953, 5, 11, 13, 5, 7, 53, 107, 131, 103, 359, 419, 223, 613, 541, 691, 151, 593, 1069, 1321, 1193, 3083, 311, 1619, 1543, 4813, 5519, 23, 61, 151, 307, 359, 23, 197, 593, 827, 2789, 5443, 9311, 1427, 1427, 5039, 13249, 4813, 13697, 6857, 19447, 4211, 4211, 38197, 12197, 521, 1553, 1931, 853, 3083, 2693, 11353, 3083, 6857, 23789, 6007, 53881, 60761, 51713, 111599, 72871, 100169, 244691, 134587, 248851, 288359, 127081, 272141, 424243, 4127, 419, 5519, 12197, 49681, 10627, 36677, 79349, 109037, 124181, 202987, 57559, 124181, 229727, 127081, 222863, 373019, 170627, 364523};
while(test--) {
int n;
cin >> n;
cout << PP[n-1] << " " << P[n-1] << endl;
}
return 0;
} | 1,666 | 1,507 |
// Copyright 2014 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 "core/frame/VisualViewport.h"
#include "core/dom/Document.h"
#include "core/frame/BrowserControls.h"
#include "core/frame/FrameHost.h"
#include "core/frame/FrameView.h"
#include "core/frame/LocalFrame.h"
#include "core/html/HTMLBodyElement.h"
#include "core/html/HTMLElement.h"
#include "core/input/EventHandler.h"
#include "core/layout/LayoutObject.h"
#include "core/layout/api/LayoutViewItem.h"
#include "core/layout/compositing/PaintLayerCompositor.h"
#include "core/page/Page.h"
#include "core/paint/PaintLayer.h"
#include "platform/PlatformGestureEvent.h"
#include "platform/geometry/DoublePoint.h"
#include "platform/geometry/DoubleRect.h"
#include "platform/graphics/CompositorElementId.h"
#include "platform/testing/RuntimeEnabledFeaturesTestHelpers.h"
#include "platform/testing/URLTestHelpers.h"
#include "public/platform/Platform.h"
#include "public/platform/WebCachePolicy.h"
#include "public/platform/WebInputEvent.h"
#include "public/platform/WebLayerTreeView.h"
#include "public/platform/WebURLLoaderMockFactory.h"
#include "public/web/WebCache.h"
#include "public/web/WebContextMenuData.h"
#include "public/web/WebDocument.h"
#include "public/web/WebFrameClient.h"
#include "public/web/WebScriptSource.h"
#include "public/web/WebSettings.h"
#include "public/web/WebViewClient.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "web/WebLocalFrameImpl.h"
#include "web/tests/FrameTestHelpers.h"
#include <string>
#define ASSERT_POINT_EQ(expected, actual) \
do { \
ASSERT_EQ((expected).x(), (actual).x()); \
ASSERT_EQ((expected).y(), (actual).y()); \
} while (false)
#define ASSERT_SIZE_EQ(expected, actual) \
do { \
ASSERT_EQ((expected).width(), (actual).width()); \
ASSERT_EQ((expected).height(), (actual).height()); \
} while (false)
#define EXPECT_POINT_EQ(expected, actual) \
do { \
EXPECT_EQ((expected).x(), (actual).x()); \
EXPECT_EQ((expected).y(), (actual).y()); \
} while (false)
#define EXPECT_FLOAT_POINT_EQ(expected, actual) \
do { \
EXPECT_FLOAT_EQ((expected).x(), (actual).x()); \
EXPECT_FLOAT_EQ((expected).y(), (actual).y()); \
} while (false)
#define EXPECT_POINT_EQ(expected, actual) \
do { \
EXPECT_EQ((expected).x(), (actual).x()); \
EXPECT_EQ((expected).y(), (actual).y()); \
} while (false)
#define EXPECT_SIZE_EQ(expected, actual) \
do { \
EXPECT_EQ((expected).width(), (actual).width()); \
EXPECT_EQ((expected).height(), (actual).height()); \
} while (false)
#define EXPECT_FLOAT_SIZE_EQ(expected, actual) \
do { \
EXPECT_FLOAT_EQ((expected).width(), (actual).width()); \
EXPECT_FLOAT_EQ((expected).height(), (actual).height()); \
} while (false)
#define EXPECT_FLOAT_RECT_EQ(expected, actual) \
do { \
EXPECT_FLOAT_EQ((expected).x(), (actual).x()); \
EXPECT_FLOAT_EQ((expected).y(), (actual).y()); \
EXPECT_FLOAT_EQ((expected).width(), (actual).width()); \
EXPECT_FLOAT_EQ((expected).height(), (actual).height()); \
} while (false)
using namespace blink;
using ::testing::_;
using ::testing::PrintToString;
using ::testing::Mock;
using blink::URLTestHelpers::toKURL;
namespace blink {
::std::ostream& operator<<(::std::ostream& os, const WebContextMenuData& data) {
return os << "Context menu location: [" << data.mousePosition.x << ", "
<< data.mousePosition.y << "]";
}
}
namespace {
typedef bool TestParamRootLayerScrolling;
class VisualViewportTest
: public testing::Test,
public testing::WithParamInterface<TestParamRootLayerScrolling>,
private ScopedRootLayerScrollingForTest {
public:
VisualViewportTest()
: ScopedRootLayerScrollingForTest(GetParam()),
m_baseURL("http://www.test.com/") {}
void initializeWithDesktopSettings(
void (*overrideSettingsFunc)(WebSettings*) = 0) {
if (!overrideSettingsFunc)
overrideSettingsFunc = &configureSettings;
m_helper.initialize(true, nullptr, &m_mockWebViewClient, nullptr,
overrideSettingsFunc);
webViewImpl()->setDefaultPageScaleLimits(1, 4);
}
void initializeWithAndroidSettings(
void (*overrideSettingsFunc)(WebSettings*) = 0) {
if (!overrideSettingsFunc)
overrideSettingsFunc = &configureAndroidSettings;
m_helper.initialize(true, nullptr, &m_mockWebViewClient, nullptr,
overrideSettingsFunc);
webViewImpl()->setDefaultPageScaleLimits(0.25f, 5);
}
~VisualViewportTest() override {
Platform::current()->getURLLoaderMockFactory()->unregisterAllURLs();
WebCache::clear();
}
void navigateTo(const std::string& url) {
FrameTestHelpers::loadFrame(webViewImpl()->mainFrame(), url);
}
void forceFullCompositingUpdate() {
webViewImpl()->updateAllLifecyclePhases();
}
void registerMockedHttpURLLoad(const std::string& fileName) {
URLTestHelpers::registerMockedURLFromBaseURL(
WebString::fromUTF8(m_baseURL.c_str()),
WebString::fromUTF8(fileName.c_str()));
}
WebLayer* getRootScrollLayer() {
PaintLayerCompositor* compositor =
frame()->contentLayoutItem().compositor();
DCHECK(compositor);
DCHECK(compositor->scrollLayer());
WebLayer* webScrollLayer = compositor->scrollLayer()->platformLayer();
return webScrollLayer;
}
WebViewImpl* webViewImpl() const { return m_helper.webView(); }
LocalFrame* frame() const {
return m_helper.webView()->mainFrameImpl()->frame();
}
static void configureSettings(WebSettings* settings) {
settings->setJavaScriptEnabled(true);
settings->setPreferCompositingToLCDTextEnabled(true);
}
static void configureAndroidSettings(WebSettings* settings) {
configureSettings(settings);
settings->setViewportEnabled(true);
settings->setViewportMetaEnabled(true);
settings->setShrinksViewportContentToFit(true);
settings->setMainFrameResizesAreOrientationChanges(true);
}
protected:
std::string m_baseURL;
FrameTestHelpers::TestWebViewClient m_mockWebViewClient;
private:
FrameTestHelpers::WebViewHelper m_helper;
};
INSTANTIATE_TEST_CASE_P(All, VisualViewportTest, ::testing::Bool());
// Test that resizing the VisualViewport works as expected and that resizing the
// WebView resizes the VisualViewport.
TEST_P(VisualViewportTest, TestResize) {
initializeWithDesktopSettings();
webViewImpl()->resize(IntSize(320, 240));
navigateTo("about:blank");
forceFullCompositingUpdate();
VisualViewport& visualViewport =
frame()->page()->frameHost().visualViewport();
IntSize webViewSize = webViewImpl()->size();
// Make sure the visual viewport was initialized.
EXPECT_SIZE_EQ(webViewSize, visualViewport.size());
// Resizing the WebView should change the VisualViewport.
webViewSize = IntSize(640, 480);
webViewImpl()->resize(webViewSize);
EXPECT_SIZE_EQ(webViewSize, IntSize(webViewImpl()->size()));
EXPECT_SIZE_EQ(webViewSize, visualViewport.size());
// Resizing the visual viewport shouldn't affect the WebView.
IntSize newViewportSize = IntSize(320, 200);
visualViewport.setSize(newViewportSize);
EXPECT_SIZE_EQ(webViewSize, IntSize(webViewImpl()->size()));
EXPECT_SIZE_EQ(newViewportSize, visualViewport.size());
}
// Make sure that the visibleContentRect method acurately reflects the scale and
// scroll location of the viewport with and without scrollbars.
TEST_P(VisualViewportTest, TestVisibleContentRect) {
RuntimeEnabledFeatures::setOverlayScrollbarsEnabled(false);
initializeWithDesktopSettings();
registerMockedHttpURLLoad("200-by-300.html");
navigateTo(m_baseURL + "200-by-300.html");
IntSize size = IntSize(150, 100);
// Vertical scrollbar width and horizontal scrollbar height.
IntSize scrollbarSize = IntSize(15, 15);
webViewImpl()->resize(size);
// Scroll layout viewport and verify visibleContentRect.
webViewImpl()->mainFrame()->setScrollOffset(WebSize(0, 50));
VisualViewport& visualViewport =
frame()->page()->frameHost().visualViewport();
EXPECT_EQ(IntRect(IntPoint(0, 0), size - scrollbarSize),
visualViewport.visibleContentRect(ExcludeScrollbars));
EXPECT_EQ(IntRect(IntPoint(0, 0), size),
visualViewport.visibleContentRect(IncludeScrollbars));
webViewImpl()->setPageScaleFactor(2.0);
// Scroll visual viewport and verify visibleContentRect.
size.scale(0.5);
scrollbarSize.scale(0.5);
visualViewport.setLocation(FloatPoint(10, 10));
EXPECT_EQ(IntRect(IntPoint(10, 10), size - scrollbarSize),
visualViewport.visibleContentRect(ExcludeScrollbars));
EXPECT_EQ(IntRect(IntPoint(10, 10), size),
visualViewport.visibleContentRect(IncludeScrollbars));
}
// This tests that shrinking the WebView while the page is fully scrolled
// doesn't move the viewport up/left, it should keep the visible viewport
// unchanged from the user's perspective (shrinking the FrameView will clamp
// the VisualViewport so we need to counter scroll the FrameView to make it
// appear to stay still). This caused bugs like crbug.com/453859.
TEST_P(VisualViewportTest, TestResizeAtFullyScrolledPreservesViewportLocation) {
initializeWithDesktopSettings();
webViewImpl()->resize(IntSize(800, 600));
registerMockedHttpURLLoad("content-width-1000.html");
navigateTo(m_baseURL + "content-width-1000.html");
FrameView& frameView = *webViewImpl()->mainFrameImpl()->frameView();
VisualViewport& visualViewport =
frame()->page()->frameHost().visualViewport();
visualViewport.setScale(2);
// Fully scroll both viewports.
frameView.layoutViewportScrollableArea()->setScrollOffset(
ScrollOffset(10000, 10000), ProgrammaticScroll);
visualViewport.move(FloatSize(10000, 10000));
// Sanity check.
ASSERT_SIZE_EQ(FloatSize(400, 300), visualViewport.scrollOffset());
ASSERT_SIZE_EQ(ScrollOffset(200, 1400),
frameView.layoutViewportScrollableArea()->scrollOffset());
IntPoint expectedLocation =
frameView.getScrollableArea()->visibleContentRect().location();
// Shrink the WebView, this should cause both viewports to shrink and
// WebView should do whatever it needs to do to preserve the visible
// location.
webViewImpl()->resize(IntSize(700, 550));
EXPECT_POINT_EQ(
expectedLocation,
frameView.getScrollableArea()->visibleContentRect().location());
webViewImpl()->resize(IntSize(800, 600));
EXPECT_POINT_EQ(
expectedLocation,
frameView.getScrollableArea()->visibleContentRect().location());
}
// Test that the VisualViewport works as expected in case of a scaled
// and scrolled viewport - scroll down.
TEST_P(VisualViewportTest, TestResizeAfterVerticalScroll) {
/*
200 200
| | | |
| | | |
| | 800 | | 800
|-------------------| | |
| | | |
| | | |
| | | |
| | --------> | |
| 300 | | |
| | | |
| 400 | | |
| | |-------------------|
| | | 75 |
| 50 | | 50 100|
o----- | o---- |
| | | | | 25 |
| |100 | |-------------------|
| | | | |
| | | | |
-------------------- --------------------
*/
// Disable the test on Mac OSX until futher investigation.
// Local build on Mac is OK but thes bot fails.
#if OS(MACOSX)
return;
#endif
initializeWithAndroidSettings();
registerMockedHttpURLLoad("200-by-800-viewport.html");
navigateTo(m_baseURL + "200-by-800-viewport.html");
webViewImpl()->resize(IntSize(100, 200));
// Scroll main frame to the bottom of the document
webViewImpl()->mainFrame()->setScrollOffset(WebSize(0, 400));
EXPECT_SIZE_EQ(
ScrollOffset(0, 400),
frame()->view()->layoutViewportScrollableArea()->scrollOffset());
webViewImpl()->setPageScaleFactor(2.0);
// Scroll visual viewport to the bottom of the main frame
VisualViewport& visualViewport =
frame()->page()->frameHost().visualViewport();
visualViewport.setLocation(FloatPoint(0, 300));
EXPECT_FLOAT_SIZE_EQ(FloatSize(0, 300), visualViewport.scrollOffset());
// Verify the initial size of the visual viewport in the CSS pixels
EXPECT_FLOAT_SIZE_EQ(FloatSize(50, 100), visualViewport.visibleRect().size());
// Perform the resizing
webViewImpl()->resize(IntSize(200, 100));
// After resizing the scale changes 2.0 -> 4.0
EXPECT_FLOAT_SIZE_EQ(FloatSize(50, 25), visualViewport.visibleRect().size());
EXPECT_SIZE_EQ(
ScrollOffset(0, 625),
frame()->view()->layoutViewportScrollableArea()->scrollOffset());
EXPECT_FLOAT_SIZE_EQ(FloatSize(0, 75), visualViewport.scrollOffset());
}
// Test that the VisualViewport works as expected in case if a scaled
// and scrolled viewport - scroll right.
TEST_P(VisualViewportTest, TestResizeAfterHorizontalScroll) {
/*
200 200
---------------o----- ---------------o-----
| | | | 25| |
| | | | -----|
| 100| | |100 50 |
| | | | |
| ---- | |-------------------|
| | | |
| | | |
| | | |
| | | |
| | | |
|400 | ---------> | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
|-------------------| | |
| | | |
*/
// Disable the test on Mac OSX until futher investigation.
// Local build on Mac is OK but thes bot fails.
#if OS(MACOSX)
return;
#endif
initializeWithAndroidSettings();
registerMockedHttpURLLoad("200-by-800-viewport.html");
navigateTo(m_baseURL + "200-by-800-viewport.html");
webViewImpl()->resize(IntSize(100, 200));
// Outer viewport takes the whole width of the document.
webViewImpl()->setPageScaleFactor(2.0);
// Scroll visual viewport to the right edge of the frame
VisualViewport& visualViewport =
frame()->page()->frameHost().visualViewport();
visualViewport.setLocation(FloatPoint(150, 0));
EXPECT_FLOAT_SIZE_EQ(FloatSize(150, 0), visualViewport.scrollOffset());
// Verify the initial size of the visual viewport in the CSS pixels
EXPECT_FLOAT_SIZE_EQ(FloatSize(50, 100), visualViewport.visibleRect().size());
webViewImpl()->resize(IntSize(200, 100));
// After resizing the scale changes 2.0 -> 4.0
EXPECT_FLOAT_SIZE_EQ(FloatSize(50, 25), visualViewport.visibleRect().size());
EXPECT_SIZE_EQ(ScrollOffset(0, 0), frame()->view()->scrollOffset());
EXPECT_FLOAT_SIZE_EQ(FloatSize(150, 0), visualViewport.scrollOffset());
}
// Test that the container layer gets sized properly if the WebView is resized
// prior to the VisualViewport being attached to the layer tree.
TEST_P(VisualViewportTest, TestWebViewResizedBeforeAttachment) {
initializeWithDesktopSettings();
FrameView& frameView = *webViewImpl()->mainFrameImpl()->frameView();
GraphicsLayer* rootGraphicsLayer =
frameView.layoutViewItem().compositor()->rootGraphicsLayer();
// Make sure that a resize that comes in while there's no root layer is
// honoured when we attach to the layer tree.
WebFrameWidgetBase* mainFrameWidget =
webViewImpl()->mainFrameImpl()->frameWidget();
mainFrameWidget->setRootGraphicsLayer(nullptr);
webViewImpl()->resize(IntSize(320, 240));
mainFrameWidget->setRootGraphicsLayer(rootGraphicsLayer);
navigateTo("about:blank");
webViewImpl()->updateAllLifecyclePhases();
VisualViewport& visualViewport =
frame()->page()->frameHost().visualViewport();
EXPECT_FLOAT_SIZE_EQ(FloatSize(320, 240),
visualViewport.containerLayer()->size());
}
// Make sure that the visibleRect method acurately reflects the scale and scroll
// location of the viewport.
TEST_P(VisualViewportTest, TestVisibleRect) {
initializeWithDesktopSettings();
webViewImpl()->resize(IntSize(320, 240));
navigateTo("about:blank");
forceFullCompositingUpdate();
VisualViewport& visualViewport =
frame()->page()->frameHost().visualViewport();
// Initial visible rect should be the whole frame.
EXPECT_SIZE_EQ(IntSize(webViewImpl()->size()), visualViewport.size());
// Viewport is whole frame.
IntSize size = IntSize(400, 200);
webViewImpl()->resize(size);
webViewImpl()->updateAllLifecyclePhases();
visualViewport.setSize(size);
// Scale the viewport to 2X; size should not change.
FloatRect expectedRect(FloatPoint(0, 0), FloatSize(size));
expectedRect.scale(0.5);
visualViewport.setScale(2);
EXPECT_EQ(2, visualViewport.scale());
EXPECT_SIZE_EQ(size, visualViewport.size());
EXPECT_FLOAT_RECT_EQ(expectedRect, visualViewport.visibleRect());
// Move the viewport.
expectedRect.setLocation(FloatPoint(5, 7));
visualViewport.setLocation(expectedRect.location());
EXPECT_FLOAT_RECT_EQ(expectedRect, visualViewport.visibleRect());
expectedRect.setLocation(FloatPoint(200, 100));
visualViewport.setLocation(expectedRect.location());
EXPECT_FLOAT_RECT_EQ(expectedRect, visualViewport.visibleRect());
// Scale the viewport to 3X to introduce some non-int values.
FloatPoint oldLocation = expectedRect.location();
expectedRect = FloatRect(FloatPoint(), FloatSize(size));
expectedRect.scale(1 / 3.0f);
expectedRect.setLocation(oldLocation);
visualViewport.setScale(3);
EXPECT_FLOAT_RECT_EQ(expectedRect, visualViewport.visibleRect());
expectedRect.setLocation(FloatPoint(0.25f, 0.333f));
visualViewport.setLocation(expectedRect.location());
EXPECT_FLOAT_RECT_EQ(expectedRect, visualViewport.visibleRect());
}
// Make sure that the visibleRectInDocument method acurately reflects the scale
// and scroll location of the viewport relative to the document.
TEST_P(VisualViewportTest, TestVisibleRectInDocument) {
initializeWithDesktopSettings();
webViewImpl()->resize(IntSize(100, 400));
registerMockedHttpURLLoad("200-by-800-viewport.html");
navigateTo(m_baseURL + "200-by-800-viewport.html");
VisualViewport& visualViewport =
frame()->page()->frameHost().visualViewport();
// Scale the viewport to 2X and move it.
visualViewport.setScale(2);
visualViewport.setLocation(FloatPoint(10, 15));
EXPECT_FLOAT_RECT_EQ(FloatRect(10, 15, 50, 200),
visualViewport.visibleRectInDocument());
// Scroll the layout viewport. Ensure its offset is reflected in
// visibleRectInDocument().
FrameView& frameView = *webViewImpl()->mainFrameImpl()->frameView();
frameView.layoutViewportScrollableArea()->setScrollOffset(
ScrollOffset(40, 100), ProgrammaticScroll);
EXPECT_FLOAT_RECT_EQ(FloatRect(50, 115, 50, 200),
visualViewport.visibleRectInDocument());
}
TEST_P(VisualViewportTest, TestFractionalScrollOffsetIsNotOverwritten) {
bool origFractionalOffsetsEnabled =
RuntimeEnabledFeatures::fractionalScrollOffsetsEnabled();
RuntimeEnabledFeatures::setFractionalScrollOffsetsEnabled(true);
initializeWithAndroidSettings();
webViewImpl()->resize(IntSize(200, 250));
registerMockedHttpURLLoad("200-by-800-viewport.html");
navigateTo(m_baseURL + "200-by-800-viewport.html");
FrameView& frameView = *webViewImpl()->mainFrameImpl()->frameView();
frameView.layoutViewportScrollableArea()->setScrollOffset(
ScrollOffset(0, 10.5), ProgrammaticScroll);
frameView.layoutViewportScrollableArea()->ScrollableArea::setScrollOffset(
ScrollOffset(10, 30.5), CompositorScroll);
EXPECT_EQ(30.5,
frameView.layoutViewportScrollableArea()->scrollOffset().height());
RuntimeEnabledFeatures::setFractionalScrollOffsetsEnabled(
origFractionalOffsetsEnabled);
}
// Test that the viewport's scroll offset is always appropriately bounded such
// that the visual viewport always stays within the bounds of the main frame.
TEST_P(VisualViewportTest, TestOffsetClamping) {
initializeWithDesktopSettings();
webViewImpl()->resize(IntSize(320, 240));
navigateTo("about:blank");
forceFullCompositingUpdate();
// Visual viewport should be initialized to same size as frame so no scrolling
// possible.
VisualViewport& visualViewport =
frame()->page()->frameHost().visualViewport();
EXPECT_FLOAT_POINT_EQ(FloatPoint(0, 0),
visualViewport.visibleRect().location());
visualViewport.setLocation(FloatPoint(-1, -2));
EXPECT_FLOAT_POINT_EQ(FloatPoint(0, 0),
visualViewport.visibleRect().location());
visualViewport.setLocation(FloatPoint(100, 200));
EXPECT_FLOAT_POINT_EQ(FloatPoint(0, 0),
visualViewport.visibleRect().location());
visualViewport.setLocation(FloatPoint(-5, 10));
EXPECT_FLOAT_POINT_EQ(FloatPoint(0, 0),
visualViewport.visibleRect().location());
// Scale by 2x. The viewport's visible rect should now have a size of 160x120.
visualViewport.setScale(2);
FloatPoint location(10, 50);
visualViewport.setLocation(location);
EXPECT_FLOAT_POINT_EQ(location, visualViewport.visibleRect().location());
visualViewport.setLocation(FloatPoint(1000, 2000));
EXPECT_FLOAT_POINT_EQ(FloatPoint(160, 120),
visualViewport.visibleRect().location());
visualViewport.setLocation(FloatPoint(-1000, -2000));
EXPECT_FLOAT_POINT_EQ(FloatPoint(0, 0),
visualViewport.visibleRect().location());
// Make sure offset gets clamped on scale out. Scale to 1.25 so the viewport
// is 256x192.
visualViewport.setLocation(FloatPoint(160, 120));
visualViewport.setScale(1.25);
EXPECT_FLOAT_POINT_EQ(FloatPoint(64, 48),
visualViewport.visibleRect().location());
// Scale out smaller than 1.
visualViewport.setScale(0.25);
EXPECT_FLOAT_POINT_EQ(FloatPoint(0, 0),
visualViewport.visibleRect().location());
}
// Test that the viewport can be scrolled around only within the main frame in
// the presence of viewport resizes, as would be the case if the on screen
// keyboard came up.
TEST_P(VisualViewportTest, TestOffsetClampingWithResize) {
initializeWithDesktopSettings();
webViewImpl()->resize(IntSize(320, 240));
navigateTo("about:blank");
forceFullCompositingUpdate();
// Visual viewport should be initialized to same size as frame so no scrolling
// possible.
VisualViewport& visualViewport =
frame()->page()->frameHost().visualViewport();
EXPECT_FLOAT_POINT_EQ(FloatPoint(0, 0),
visualViewport.visibleRect().location());
// Shrink the viewport vertically. The resize shouldn't affect the location,
// but it should allow vertical scrolling.
visualViewport.setSize(IntSize(320, 200));
EXPECT_FLOAT_POINT_EQ(FloatPoint(0, 0),
visualViewport.visibleRect().location());
visualViewport.setLocation(FloatPoint(10, 20));
EXPECT_FLOAT_POINT_EQ(FloatPoint(0, 20),
visualViewport.visibleRect().location());
visualViewport.setLocation(FloatPoint(0, 100));
EXPECT_FLOAT_POINT_EQ(FloatPoint(0, 40),
visualViewport.visibleRect().location());
visualViewport.setLocation(FloatPoint(0, 10));
EXPECT_FLOAT_POINT_EQ(FloatPoint(0, 10),
visualViewport.visibleRect().location());
visualViewport.setLocation(FloatPoint(0, -100));
EXPECT_FLOAT_POINT_EQ(FloatPoint(0, 0),
visualViewport.visibleRect().location());
// Repeat the above but for horizontal dimension.
visualViewport.setSize(IntSize(280, 240));
EXPECT_FLOAT_POINT_EQ(FloatPoint(0, 0),
visualViewport.visibleRect().location());
visualViewport.setLocation(FloatPoint(10, 20));
EXPECT_FLOAT_POINT_EQ(FloatPoint(10, 0),
visualViewport.visibleRect().location());
visualViewport.setLocation(FloatPoint(100, 0));
EXPECT_FLOAT_POINT_EQ(FloatPoint(40, 0),
visualViewport.visibleRect().location());
visualViewport.setLocation(FloatPoint(10, 0));
EXPECT_FLOAT_POINT_EQ(FloatPoint(10, 0),
visualViewport.visibleRect().location());
visualViewport.setLocation(FloatPoint(-100, 0));
EXPECT_FLOAT_POINT_EQ(FloatPoint(0, 0),
visualViewport.visibleRect().location());
// Now with both dimensions.
visualViewport.setSize(IntSize(280, 200));
EXPECT_FLOAT_POINT_EQ(FloatPoint(0, 0),
visualViewport.visibleRect().location());
visualViewport.setLocation(FloatPoint(10, 20));
EXPECT_FLOAT_POINT_EQ(FloatPoint(10, 20),
visualViewport.visibleRect().location());
visualViewport.setLocation(FloatPoint(100, 100));
EXPECT_FLOAT_POINT_EQ(FloatPoint(40, 40),
visualViewport.visibleRect().location());
visualViewport.setLocation(FloatPoint(10, 3));
EXPECT_FLOAT_POINT_EQ(FloatPoint(10, 3),
visualViewport.visibleRect().location());
visualViewport.setLocation(FloatPoint(-10, -4));
EXPECT_FLOAT_POINT_EQ(FloatPoint(0, 0),
visualViewport.visibleRect().location());
}
// Test that the viewport is scrollable but bounded appropriately within the
// main frame when we apply both scaling and resizes.
TEST_P(VisualViewportTest, TestOffsetClampingWithResizeAndScale) {
initializeWithDesktopSettings();
webViewImpl()->resize(IntSize(320, 240));
navigateTo("about:blank");
forceFullCompositingUpdate();
// Visual viewport should be initialized to same size as WebView so no
// scrolling possible.
VisualViewport& visualViewport =
frame()->page()->frameHost().visualViewport();
EXPECT_FLOAT_POINT_EQ(FloatPoint(0, 0),
visualViewport.visibleRect().location());
// Zoom in to 2X so we can scroll the viewport to 160x120.
visualViewport.setScale(2);
visualViewport.setLocation(FloatPoint(200, 200));
EXPECT_FLOAT_POINT_EQ(FloatPoint(160, 120),
visualViewport.visibleRect().location());
// Now resize the viewport to make it 10px smaller. Since we're zoomed in by
// 2X it should allow us to scroll by 5px more.
visualViewport.setSize(IntSize(310, 230));
visualViewport.setLocation(FloatPoint(200, 200));
EXPECT_FLOAT_POINT_EQ(FloatPoint(165, 125),
visualViewport.visibleRect().location());
// The viewport can be larger than the main frame (currently 320, 240) though
// typically the scale will be clamped to prevent it from actually being
// larger.
visualViewport.setSize(IntSize(330, 250));
EXPECT_SIZE_EQ(IntSize(330, 250), visualViewport.size());
// Resize both the viewport and the frame to be larger.
webViewImpl()->resize(IntSize(640, 480));
webViewImpl()->updateAllLifecyclePhases();
EXPECT_SIZE_EQ(IntSize(webViewImpl()->size()), visualViewport.size());
EXPECT_SIZE_EQ(IntSize(webViewImpl()->size()),
frame()->view()->frameRect().size());
visualViewport.setLocation(FloatPoint(1000, 1000));
EXPECT_FLOAT_POINT_EQ(FloatPoint(320, 240),
visualViewport.visibleRect().location());
// Make sure resizing the viewport doesn't change its offset if the resize
// doesn't make the viewport go out of bounds.
visualViewport.setLocation(FloatPoint(200, 200));
visualViewport.setSize(IntSize(880, 560));
EXPECT_FLOAT_POINT_EQ(FloatPoint(200, 200),
visualViewport.visibleRect().location());
}
// The main FrameView's size should be set such that its the size of the visual
// viewport at minimum scale. If there's no explicit minimum scale set, the
// FrameView should be set to the content width and height derived by the aspect
// ratio.
TEST_P(VisualViewportTest, TestFrameViewSizedToContent) {
initializeWithAndroidSettings();
webViewImpl()->resize(IntSize(320, 240));
registerMockedHttpURLLoad("200-by-300-viewport.html");
navigateTo(m_baseURL + "200-by-300-viewport.html");
webViewImpl()->resize(IntSize(600, 800));
webViewImpl()->updateAllLifecyclePhases();
// Note: the size is ceiled and should match the behavior in CC's
// LayerImpl::bounds().
EXPECT_SIZE_EQ(
IntSize(200, 267),
webViewImpl()->mainFrameImpl()->frameView()->frameRect().size());
}
// The main FrameView's size should be set such that its the size of the visual
// viewport at minimum scale. On Desktop, the minimum scale is set at 1 so make
// sure the FrameView is sized to the viewport.
TEST_P(VisualViewportTest, TestFrameViewSizedToMinimumScale) {
initializeWithDesktopSettings();
webViewImpl()->resize(IntSize(320, 240));
registerMockedHttpURLLoad("200-by-300.html");
navigateTo(m_baseURL + "200-by-300.html");
webViewImpl()->resize(IntSize(100, 160));
webViewImpl()->updateAllLifecyclePhases();
EXPECT_SIZE_EQ(
IntSize(100, 160),
webViewImpl()->mainFrameImpl()->frameView()->frameRect().size());
}
// Test that attaching a new frame view resets the size of the inner viewport
// scroll layer. crbug.com/423189.
TEST_P(VisualViewportTest, TestAttachingNewFrameSetsInnerScrollLayerSize) {
initializeWithAndroidSettings();
webViewImpl()->resize(IntSize(320, 240));
// Load a wider page first, the navigation should resize the scroll layer to
// the smaller size on the second navigation.
registerMockedHttpURLLoad("content-width-1000.html");
navigateTo(m_baseURL + "content-width-1000.html");
webViewImpl()->updateAllLifecyclePhases();
VisualViewport& visualViewport =
frame()->page()->frameHost().visualViewport();
visualViewport.setScale(2);
visualViewport.move(ScrollOffset(50, 60));
// Move and scale the viewport to make sure it gets reset in the navigation.
EXPECT_SIZE_EQ(FloatSize(50, 60), visualViewport.scrollOffset());
EXPECT_EQ(2, visualViewport.scale());
// Navigate again, this time the FrameView should be smaller.
registerMockedHttpURLLoad("viewport-device-width.html");
navigateTo(m_baseURL + "viewport-device-width.html");
// Ensure the scroll layer matches the frame view's size.
EXPECT_SIZE_EQ(FloatSize(320, 240), visualViewport.scrollLayer()->size());
EXPECT_EQ(static_cast<int>(CompositorSubElementId::Viewport),
visualViewport.scrollLayer()->elementId().secondaryId);
// Ensure the location and scale were reset.
EXPECT_SIZE_EQ(FloatSize(), visualViewport.scrollOffset());
EXPECT_EQ(1, visualViewport.scale());
}
// The main FrameView's size should be set such that its the size of the visual
// viewport at minimum scale. Test that the FrameView is appropriately sized in
// the presence of a viewport <meta> tag.
TEST_P(VisualViewportTest, TestFrameViewSizedToViewportMetaMinimumScale) {
initializeWithAndroidSettings();
webViewImpl()->resize(IntSize(320, 240));
registerMockedHttpURLLoad("200-by-300-min-scale-2.html");
navigateTo(m_baseURL + "200-by-300-min-scale-2.html");
webViewImpl()->resize(IntSize(100, 160));
webViewImpl()->updateAllLifecyclePhases();
EXPECT_SIZE_EQ(
IntSize(50, 80),
webViewImpl()->mainFrameImpl()->frameView()->frameRect().size());
}
// Test that the visual viewport still gets sized in AutoSize/AutoResize mode.
TEST_P(VisualViewportTest, TestVisualViewportGetsSizeInAutoSizeMode) {
initializeWithDesktopSettings();
EXPECT_SIZE_EQ(IntSize(0, 0), IntSize(webViewImpl()->size()));
EXPECT_SIZE_EQ(IntSize(0, 0),
frame()->page()->frameHost().visualViewport().size());
webViewImpl()->enableAutoResizeMode(WebSize(10, 10), WebSize(1000, 1000));
registerMockedHttpURLLoad("200-by-300.html");
navigateTo(m_baseURL + "200-by-300.html");
EXPECT_SIZE_EQ(IntSize(200, 300),
frame()->page()->frameHost().visualViewport().size());
}
// Test that the text selection handle's position accounts for the visual
// viewport.
TEST_P(VisualViewportTest, TestTextSelectionHandles) {
initializeWithDesktopSettings();
webViewImpl()->resize(IntSize(500, 800));
registerMockedHttpURLLoad("pinch-viewport-input-field.html");
navigateTo(m_baseURL + "pinch-viewport-input-field.html");
VisualViewport& visualViewport =
frame()->page()->frameHost().visualViewport();
webViewImpl()->setInitialFocus(false);
WebRect originalAnchor;
WebRect originalFocus;
webViewImpl()->selectionBounds(originalAnchor, originalFocus);
webViewImpl()->setPageScaleFactor(2);
visualViewport.setLocation(FloatPoint(100, 400));
WebRect anchor;
WebRect focus;
webViewImpl()->selectionBounds(anchor, focus);
IntPoint expected(IntRect(originalAnchor).location());
expected.moveBy(-flooredIntPoint(visualViewport.visibleRect().location()));
expected.scale(visualViewport.scale(), visualViewport.scale());
EXPECT_POINT_EQ(expected, IntRect(anchor).location());
EXPECT_POINT_EQ(expected, IntRect(focus).location());
// FIXME(bokan) - http://crbug.com/364154 - Figure out how to test text
// selection as well rather than just carret.
}
// Test that the HistoryItem for the page stores the visual viewport's offset
// and scale.
TEST_P(VisualViewportTest, TestSavedToHistoryItem) {
initializeWithDesktopSettings();
webViewImpl()->resize(IntSize(200, 300));
webViewImpl()->updateAllLifecyclePhases();
registerMockedHttpURLLoad("200-by-300.html");
navigateTo(m_baseURL + "200-by-300.html");
EXPECT_SIZE_EQ(ScrollOffset(0, 0),
toLocalFrame(webViewImpl()->page()->mainFrame())
->loader()
.currentItem()
->visualViewportScrollOffset());
VisualViewport& visualViewport =
frame()->page()->frameHost().visualViewport();
visualViewport.setScale(2);
EXPECT_EQ(2, toLocalFrame(webViewImpl()->page()->mainFrame())
->loader()
.currentItem()
->pageScaleFactor());
visualViewport.setLocation(FloatPoint(10, 20));
EXPECT_SIZE_EQ(ScrollOffset(10, 20),
toLocalFrame(webViewImpl()->page()->mainFrame())
->loader()
.currentItem()
->visualViewportScrollOffset());
}
// Test restoring a HistoryItem properly restores the visual viewport's state.
TEST_P(VisualViewportTest, TestRestoredFromHistoryItem) {
initializeWithDesktopSettings();
webViewImpl()->resize(IntSize(200, 300));
registerMockedHttpURLLoad("200-by-300.html");
WebHistoryItem item;
item.initialize();
WebURL destinationURL(URLTestHelpers::toKURL(m_baseURL + "200-by-300.html"));
item.setURLString(destinationURL.string());
item.setVisualViewportScrollOffset(WebFloatPoint(100, 120));
item.setPageScaleFactor(2);
FrameTestHelpers::loadHistoryItem(webViewImpl()->mainFrame(), item,
WebHistoryDifferentDocumentLoad,
WebCachePolicy::UseProtocolCachePolicy);
VisualViewport& visualViewport =
frame()->page()->frameHost().visualViewport();
EXPECT_EQ(2, visualViewport.scale());
EXPECT_FLOAT_POINT_EQ(FloatPoint(100, 120),
visualViewport.visibleRect().location());
}
// Test restoring a HistoryItem without the visual viewport offset falls back to
// distributing the scroll offset between the main frame and the visual
// viewport.
TEST_P(VisualViewportTest, TestRestoredFromLegacyHistoryItem) {
initializeWithDesktopSettings();
webViewImpl()->resize(IntSize(100, 150));
registerMockedHttpURLLoad("200-by-300-viewport.html");
WebHistoryItem item;
item.initialize();
WebURL destinationURL(
URLTestHelpers::toKURL(m_baseURL + "200-by-300-viewport.html"));
item.setURLString(destinationURL.string());
// (-1, -1) will be used if the HistoryItem is an older version prior to
// having visual viewport scroll offset.
item.setVisualViewportScrollOffset(WebFloatPoint(-1, -1));
item.setScrollOffset(WebPoint(120, 180));
item.setPageScaleFactor(2);
FrameTestHelpers::loadHistoryItem(webViewImpl()->mainFrame(), item,
WebHistoryDifferentDocumentLoad,
WebCachePolicy::UseProtocolCachePolicy);
VisualViewport& visualViewport =
frame()->page()->frameHost().visualViewport();
EXPECT_EQ(2, visualViewport.scale());
EXPECT_SIZE_EQ(
ScrollOffset(100, 150),
frame()->view()->layoutViewportScrollableArea()->scrollOffset());
EXPECT_FLOAT_POINT_EQ(FloatPoint(20, 30),
visualViewport.visibleRect().location());
}
// Test that navigation to a new page with a different sized main frame doesn't
// clobber the history item's main frame scroll offset. crbug.com/371867
TEST_P(VisualViewportTest,
TestNavigateToSmallerFrameViewHistoryItemClobberBug) {
initializeWithAndroidSettings();
webViewImpl()->resize(IntSize(400, 400));
webViewImpl()->updateAllLifecyclePhases();
registerMockedHttpURLLoad("content-width-1000.html");
navigateTo(m_baseURL + "content-width-1000.html");
FrameView* frameView = webViewImpl()->mainFrameImpl()->frameView();
frameView->layoutViewportScrollableArea()->setScrollOffset(
ScrollOffset(0, 1000), ProgrammaticScroll);
EXPECT_SIZE_EQ(IntSize(1000, 1000), frameView->frameRect().size());
VisualViewport& visualViewport =
frame()->page()->frameHost().visualViewport();
visualViewport.setScale(2);
visualViewport.setLocation(FloatPoint(350, 350));
Persistent<HistoryItem> firstItem =
webViewImpl()->mainFrameImpl()->frame()->loader().currentItem();
EXPECT_SIZE_EQ(ScrollOffset(0, 1000), firstItem->scrollOffset());
// Now navigate to a page which causes a smaller frameView. Make sure that
// navigating doesn't cause the history item to set a new scroll offset
// before the item was replaced.
navigateTo("about:blank");
frameView = webViewImpl()->mainFrameImpl()->frameView();
EXPECT_NE(firstItem,
webViewImpl()->mainFrameImpl()->frame()->loader().currentItem());
EXPECT_LT(frameView->frameRect().size().width(), 1000);
EXPECT_SIZE_EQ(ScrollOffset(0, 1000), firstItem->scrollOffset());
}
// Test that the coordinates sent into moveRangeSelection are offset by the
// visual viewport's location.
TEST_P(VisualViewportTest,
DISABLED_TestWebFrameRangeAccountsForVisualViewportScroll) {
initializeWithDesktopSettings();
webViewImpl()->settings()->setDefaultFontSize(12);
webViewImpl()->resize(WebSize(640, 480));
registerMockedHttpURLLoad("move_range.html");
navigateTo(m_baseURL + "move_range.html");
WebRect baseRect;
WebRect extentRect;
webViewImpl()->setPageScaleFactor(2);
WebFrame* mainFrame = webViewImpl()->mainFrame();
// Select some text and get the base and extent rects (that's the start of
// the range and its end). Do a sanity check that the expected text is
// selected
mainFrame->executeScript(WebScriptSource("selectRange();"));
EXPECT_EQ("ir", mainFrame->toWebLocalFrame()->selectionAsText().utf8());
webViewImpl()->selectionBounds(baseRect, extentRect);
WebPoint initialPoint(baseRect.x, baseRect.y);
WebPoint endPoint(extentRect.x, extentRect.y);
// Move the visual viewport over and make the selection in the same
// screen-space location. The selection should change to two characters to the
// right and down one line.
VisualViewport& visualViewport =
frame()->page()->frameHost().visualViewport();
visualViewport.move(ScrollOffset(60, 25));
mainFrame->toWebLocalFrame()->moveRangeSelection(initialPoint, endPoint);
EXPECT_EQ("t ", mainFrame->toWebLocalFrame()->selectionAsText().utf8());
}
// Test that the scrollFocusedEditableElementIntoRect method works with the
// visual viewport.
TEST_P(VisualViewportTest, DISABLED_TestScrollFocusedEditableElementIntoRect) {
initializeWithDesktopSettings();
webViewImpl()->resize(IntSize(500, 300));
registerMockedHttpURLLoad("pinch-viewport-input-field.html");
navigateTo(m_baseURL + "pinch-viewport-input-field.html");
VisualViewport& visualViewport =
frame()->page()->frameHost().visualViewport();
webViewImpl()->resizeVisualViewport(IntSize(200, 100));
webViewImpl()->setInitialFocus(false);
visualViewport.setLocation(FloatPoint());
webViewImpl()->scrollFocusedEditableElementIntoRect(IntRect(0, 0, 500, 200));
EXPECT_SIZE_EQ(
ScrollOffset(0, frame()->view()->maximumScrollOffset().height()),
frame()->view()->scrollOffset());
EXPECT_FLOAT_POINT_EQ(FloatPoint(150, 200),
visualViewport.visibleRect().location());
// Try it again but with the page zoomed in
frame()->view()->setScrollOffset(ScrollOffset(0, 0), ProgrammaticScroll);
webViewImpl()->resizeVisualViewport(IntSize(500, 300));
visualViewport.setLocation(FloatPoint(0, 0));
webViewImpl()->setPageScaleFactor(2);
webViewImpl()->scrollFocusedEditableElementIntoRect(IntRect(0, 0, 500, 200));
EXPECT_SIZE_EQ(
ScrollOffset(0, frame()->view()->maximumScrollOffset().height()),
frame()->view()->scrollOffset());
EXPECT_FLOAT_POINT_EQ(FloatPoint(125, 150),
visualViewport.visibleRect().location());
// Once more but make sure that we don't move the visual viewport unless
// necessary.
registerMockedHttpURLLoad("pinch-viewport-input-field-long-and-wide.html");
navigateTo(m_baseURL + "pinch-viewport-input-field-long-and-wide.html");
webViewImpl()->setInitialFocus(false);
visualViewport.setLocation(FloatPoint());
frame()->view()->setScrollOffset(ScrollOffset(0, 0), ProgrammaticScroll);
webViewImpl()->resizeVisualViewport(IntSize(500, 300));
visualViewport.setLocation(FloatPoint(30, 50));
webViewImpl()->setPageScaleFactor(2);
webViewImpl()->scrollFocusedEditableElementIntoRect(IntRect(0, 0, 500, 200));
EXPECT_SIZE_EQ(ScrollOffset(200 - 30 - 75, 600 - 50 - 65),
frame()->view()->scrollOffset());
EXPECT_FLOAT_POINT_EQ(FloatPoint(30, 50),
visualViewport.visibleRect().location());
}
// Test that resizing the WebView causes ViewportConstrained objects to
// relayout.
TEST_P(VisualViewportTest, TestWebViewResizeCausesViewportConstrainedLayout) {
initializeWithDesktopSettings();
webViewImpl()->resize(IntSize(500, 300));
registerMockedHttpURLLoad("pinch-viewport-fixed-pos.html");
navigateTo(m_baseURL + "pinch-viewport-fixed-pos.html");
LayoutObject* navbar =
frame()->document()->getElementById("navbar")->layoutObject();
EXPECT_FALSE(navbar->needsLayout());
frame()->view()->resize(IntSize(500, 200));
EXPECT_TRUE(navbar->needsLayout());
}
class MockWebFrameClient : public FrameTestHelpers::TestWebFrameClient {
public:
MOCK_METHOD1(showContextMenu, void(const WebContextMenuData&));
MOCK_METHOD1(didChangeScrollOffset, void(WebLocalFrame*));
};
MATCHER_P2(ContextMenuAtLocation,
x,
y,
std::string(negation ? "is" : "isn't") + " at expected location [" +
PrintToString(x) +
", " +
PrintToString(y) +
"]") {
return arg.mousePosition.x == x && arg.mousePosition.y == y;
}
// Test that the context menu's location is correct in the presence of visual
// viewport offset.
TEST_P(VisualViewportTest, TestContextMenuShownInCorrectLocation) {
initializeWithDesktopSettings();
webViewImpl()->resize(IntSize(200, 300));
registerMockedHttpURLLoad("200-by-300.html");
navigateTo(m_baseURL + "200-by-300.html");
WebMouseEvent mouseDownEvent;
mouseDownEvent.type = WebInputEvent::MouseDown;
mouseDownEvent.x = 10;
mouseDownEvent.y = 10;
mouseDownEvent.windowX = 10;
mouseDownEvent.windowY = 10;
mouseDownEvent.globalX = 110;
mouseDownEvent.globalY = 210;
mouseDownEvent.clickCount = 1;
mouseDownEvent.button = WebMouseEvent::Button::Right;
// Corresponding release event (Windows shows context menu on release).
WebMouseEvent mouseUpEvent(mouseDownEvent);
mouseUpEvent.type = WebInputEvent::MouseUp;
WebFrameClient* oldClient = webViewImpl()->mainFrameImpl()->client();
MockWebFrameClient mockWebFrameClient;
EXPECT_CALL(mockWebFrameClient, showContextMenu(ContextMenuAtLocation(
mouseDownEvent.x, mouseDownEvent.y)));
// Do a sanity check with no scale applied.
webViewImpl()->mainFrameImpl()->setClient(&mockWebFrameClient);
webViewImpl()->handleInputEvent(mouseDownEvent);
webViewImpl()->handleInputEvent(mouseUpEvent);
Mock::VerifyAndClearExpectations(&mockWebFrameClient);
mouseDownEvent.button = WebMouseEvent::Button::Left;
webViewImpl()->handleInputEvent(mouseDownEvent);
// Now pinch zoom into the page and move the visual viewport. The context menu
// should still appear at the location of the event, relative to the WebView.
VisualViewport& visualViewport =
frame()->page()->frameHost().visualViewport();
webViewImpl()->setPageScaleFactor(2);
EXPECT_CALL(mockWebFrameClient, didChangeScrollOffset(_));
visualViewport.setLocation(FloatPoint(60, 80));
EXPECT_CALL(mockWebFrameClient, showContextMenu(ContextMenuAtLocation(
mouseDownEvent.x, mouseDownEvent.y)));
mouseDownEvent.button = WebMouseEvent::Button::Right;
webViewImpl()->handleInputEvent(mouseDownEvent);
webViewImpl()->handleInputEvent(mouseUpEvent);
// Reset the old client so destruction can occur naturally.
webViewImpl()->mainFrameImpl()->setClient(oldClient);
}
// Test that the client is notified if page scroll events.
TEST_P(VisualViewportTest, TestClientNotifiedOfScrollEvents) {
initializeWithAndroidSettings();
webViewImpl()->resize(IntSize(200, 300));
registerMockedHttpURLLoad("200-by-300.html");
navigateTo(m_baseURL + "200-by-300.html");
WebFrameClient* oldClient = webViewImpl()->mainFrameImpl()->client();
MockWebFrameClient mockWebFrameClient;
webViewImpl()->mainFrameImpl()->setClient(&mockWebFrameClient);
webViewImpl()->setPageScaleFactor(2);
VisualViewport& visualViewport =
frame()->page()->frameHost().visualViewport();
EXPECT_CALL(mockWebFrameClient, didChangeScrollOffset(_));
visualViewport.setLocation(FloatPoint(60, 80));
Mock::VerifyAndClearExpectations(&mockWebFrameClient);
// Scroll vertically.
EXPECT_CALL(mockWebFrameClient, didChangeScrollOffset(_));
visualViewport.setLocation(FloatPoint(60, 90));
Mock::VerifyAndClearExpectations(&mockWebFrameClient);
// Scroll horizontally.
EXPECT_CALL(mockWebFrameClient, didChangeScrollOffset(_));
visualViewport.setLocation(FloatPoint(70, 90));
// Reset the old client so destruction can occur naturally.
webViewImpl()->mainFrameImpl()->setClient(oldClient);
}
// Tests that calling scroll into view on a visible element doesn't cause
// a scroll due to a fractional offset. Bug crbug.com/463356.
TEST_P(VisualViewportTest, ScrollIntoViewFractionalOffset) {
initializeWithAndroidSettings();
webViewImpl()->resize(IntSize(1000, 1000));
registerMockedHttpURLLoad("scroll-into-view.html");
navigateTo(m_baseURL + "scroll-into-view.html");
FrameView& frameView = *webViewImpl()->mainFrameImpl()->frameView();
ScrollableArea* layoutViewportScrollableArea =
frameView.layoutViewportScrollableArea();
VisualViewport& visualViewport =
frame()->page()->frameHost().visualViewport();
Element* inputBox = frame()->document()->getElementById("box");
webViewImpl()->setPageScaleFactor(2);
// The element is already in the view so the scrollIntoView shouldn't move
// the viewport at all.
webViewImpl()->setVisualViewportOffset(WebFloatPoint(250.25f, 100.25f));
layoutViewportScrollableArea->setScrollOffset(ScrollOffset(0, 900.75),
ProgrammaticScroll);
inputBox->scrollIntoViewIfNeeded(false);
EXPECT_SIZE_EQ(ScrollOffset(0, 900),
layoutViewportScrollableArea->scrollOffset());
EXPECT_SIZE_EQ(FloatSize(250.25f, 100.25f), visualViewport.scrollOffset());
// Change the fractional part of the frameview to one that would round down.
layoutViewportScrollableArea->setScrollOffset(ScrollOffset(0, 900.125),
ProgrammaticScroll);
inputBox->scrollIntoViewIfNeeded(false);
EXPECT_SIZE_EQ(ScrollOffset(0, 900),
layoutViewportScrollableArea->scrollOffset());
EXPECT_SIZE_EQ(FloatSize(250.25f, 100.25f), visualViewport.scrollOffset());
// Repeat both tests above with the visual viewport at a high fractional.
webViewImpl()->setVisualViewportOffset(WebFloatPoint(250.875f, 100.875f));
layoutViewportScrollableArea->setScrollOffset(ScrollOffset(0, 900.75),
ProgrammaticScroll);
inputBox->scrollIntoViewIfNeeded(false);
EXPECT_SIZE_EQ(ScrollOffset(0, 900),
layoutViewportScrollableArea->scrollOffset());
EXPECT_SIZE_EQ(FloatSize(250.875f, 100.875f), visualViewport.scrollOffset());
// Change the fractional part of the frameview to one that would round down.
layoutViewportScrollableArea->setScrollOffset(ScrollOffset(0, 900.125),
ProgrammaticScroll);
inputBox->scrollIntoViewIfNeeded(false);
EXPECT_SIZE_EQ(ScrollOffset(0, 900),
layoutViewportScrollableArea->scrollOffset());
EXPECT_SIZE_EQ(FloatSize(250.875f, 100.875f), visualViewport.scrollOffset());
// Both viewports with a 0.5 fraction.
webViewImpl()->setVisualViewportOffset(WebFloatPoint(250.5f, 100.5f));
layoutViewportScrollableArea->setScrollOffset(ScrollOffset(0, 900.5),
ProgrammaticScroll);
inputBox->scrollIntoViewIfNeeded(false);
EXPECT_SIZE_EQ(ScrollOffset(0, 900),
layoutViewportScrollableArea->scrollOffset());
EXPECT_SIZE_EQ(FloatSize(250.5f, 100.5f), visualViewport.scrollOffset());
}
static ScrollOffset expectedMaxFrameViewScrollOffset(
VisualViewport& visualViewport,
FrameView& frameView) {
float aspectRatio = visualViewport.visibleRect().width() /
visualViewport.visibleRect().height();
float newHeight = frameView.frameRect().width() / aspectRatio;
return ScrollOffset(
frameView.contentsSize().width() - frameView.frameRect().width(),
frameView.contentsSize().height() - newHeight);
}
TEST_P(VisualViewportTest, TestBrowserControlsAdjustment) {
initializeWithAndroidSettings();
webViewImpl()->resizeWithBrowserControls(IntSize(500, 450), 20, false);
registerMockedHttpURLLoad("content-width-1000.html");
navigateTo(m_baseURL + "content-width-1000.html");
VisualViewport& visualViewport =
frame()->page()->frameHost().visualViewport();
FrameView& frameView = *webViewImpl()->mainFrameImpl()->frameView();
visualViewport.setScale(1);
EXPECT_SIZE_EQ(IntSize(500, 450), visualViewport.visibleRect().size());
EXPECT_SIZE_EQ(IntSize(1000, 900), frameView.frameRect().size());
// Simulate bringing down the browser controls by 20px.
webViewImpl()->applyViewportDeltas(WebFloatSize(), WebFloatSize(),
WebFloatSize(), 1, 1);
EXPECT_SIZE_EQ(IntSize(500, 430), visualViewport.visibleRect().size());
// Test that the scroll bounds are adjusted appropriately: the visual viewport
// should be shrunk by 20px to 430px. The outer viewport was shrunk to
// maintain the
// aspect ratio so it's height is 860px.
visualViewport.move(ScrollOffset(10000, 10000));
EXPECT_SIZE_EQ(FloatSize(500, 860 - 430), visualViewport.scrollOffset());
// The outer viewport (FrameView) should be affected as well.
frameView.layoutViewportScrollableArea()->scrollBy(ScrollOffset(10000, 10000),
UserScroll);
EXPECT_SIZE_EQ(expectedMaxFrameViewScrollOffset(visualViewport, frameView),
frameView.layoutViewportScrollableArea()->scrollOffset());
// Simulate bringing up the browser controls by 10.5px.
webViewImpl()->applyViewportDeltas(WebFloatSize(), WebFloatSize(),
WebFloatSize(), 1, -10.5f / 20);
EXPECT_FLOAT_SIZE_EQ(FloatSize(500, 440.5f),
visualViewport.visibleRect().size());
// maximumScrollPosition |ceil|s the browser controls adjustment.
visualViewport.move(ScrollOffset(10000, 10000));
EXPECT_FLOAT_SIZE_EQ(FloatSize(500, 881 - 441),
visualViewport.scrollOffset());
// The outer viewport (FrameView) should be affected as well.
frameView.layoutViewportScrollableArea()->scrollBy(ScrollOffset(10000, 10000),
UserScroll);
EXPECT_SIZE_EQ(expectedMaxFrameViewScrollOffset(visualViewport, frameView),
frameView.layoutViewportScrollableArea()->scrollOffset());
}
TEST_P(VisualViewportTest, TestBrowserControlsAdjustmentWithScale) {
initializeWithAndroidSettings();
webViewImpl()->resizeWithBrowserControls(IntSize(500, 450), 20, false);
registerMockedHttpURLLoad("content-width-1000.html");
navigateTo(m_baseURL + "content-width-1000.html");
VisualViewport& visualViewport =
frame()->page()->frameHost().visualViewport();
FrameView& frameView = *webViewImpl()->mainFrameImpl()->frameView();
visualViewport.setScale(2);
EXPECT_SIZE_EQ(IntSize(250, 225), visualViewport.visibleRect().size());
EXPECT_SIZE_EQ(IntSize(1000, 900), frameView.frameRect().size());
// Simulate bringing down the browser controls by 20px. Since we're zoomed in,
// the browser controls take up half as much space (in document-space) than
// they do at an unzoomed level.
webViewImpl()->applyViewportDeltas(WebFloatSize(), WebFloatSize(),
WebFloatSize(), 1, 1);
EXPECT_SIZE_EQ(IntSize(250, 215), visualViewport.visibleRect().size());
// Test that the scroll bounds are adjusted appropriately.
visualViewport.move(ScrollOffset(10000, 10000));
EXPECT_SIZE_EQ(FloatSize(750, 860 - 215), visualViewport.scrollOffset());
// The outer viewport (FrameView) should be affected as well.
frameView.layoutViewportScrollableArea()->scrollBy(ScrollOffset(10000, 10000),
UserScroll);
ScrollOffset expected =
expectedMaxFrameViewScrollOffset(visualViewport, frameView);
EXPECT_SIZE_EQ(expected,
frameView.layoutViewportScrollableArea()->scrollOffset());
// Scale back out, FrameView max scroll shouldn't have changed. Visual
// viewport should be moved up to accomodate larger view.
webViewImpl()->applyViewportDeltas(WebFloatSize(), WebFloatSize(),
WebFloatSize(), 0.5f, 0);
EXPECT_EQ(1, visualViewport.scale());
EXPECT_SIZE_EQ(expected,
frameView.layoutViewportScrollableArea()->scrollOffset());
frameView.layoutViewportScrollableArea()->scrollBy(ScrollOffset(10000, 10000),
UserScroll);
EXPECT_SIZE_EQ(expected,
frameView.layoutViewportScrollableArea()->scrollOffset());
EXPECT_SIZE_EQ(FloatSize(500, 860 - 430), visualViewport.scrollOffset());
visualViewport.move(ScrollOffset(10000, 10000));
EXPECT_SIZE_EQ(FloatSize(500, 860 - 430), visualViewport.scrollOffset());
// Scale out, use a scale that causes fractional rects.
webViewImpl()->applyViewportDeltas(WebFloatSize(), WebFloatSize(),
WebFloatSize(), 0.8f, -1);
EXPECT_SIZE_EQ(FloatSize(625, 562.5), visualViewport.visibleRect().size());
// Bring out the browser controls by 11
webViewImpl()->applyViewportDeltas(WebFloatSize(), WebFloatSize(),
WebFloatSize(), 1, 11 / 20.f);
EXPECT_SIZE_EQ(FloatSize(625, 548.75), visualViewport.visibleRect().size());
// Ensure max scroll offsets are updated properly.
visualViewport.move(ScrollOffset(10000, 10000));
EXPECT_FLOAT_SIZE_EQ(FloatSize(375, 877.5 - 548.75),
visualViewport.scrollOffset());
frameView.layoutViewportScrollableArea()->scrollBy(ScrollOffset(10000, 10000),
UserScroll);
EXPECT_SIZE_EQ(expectedMaxFrameViewScrollOffset(visualViewport, frameView),
frameView.layoutViewportScrollableArea()->scrollOffset());
}
// Tests that a scroll all the way to the bottom of the page, while hiding the
// browser controls doesn't cause a clamp in the viewport scroll offset when the
// top controls initiated resize occurs.
TEST_P(VisualViewportTest, TestBrowserControlsAdjustmentAndResize) {
int browserControlsHeight = 20;
int visualViewportHeight = 450;
int layoutViewportHeight = 900;
float pageScale = 2;
float minPageScale = 0.5;
initializeWithAndroidSettings();
// Initialize with browser controls showing and shrinking the Blink size.
webViewImpl()->resizeWithBrowserControls(
WebSize(500, visualViewportHeight - browserControlsHeight), 20, true);
webViewImpl()->browserControls().setShownRatio(1);
registerMockedHttpURLLoad("content-width-1000.html");
navigateTo(m_baseURL + "content-width-1000.html");
VisualViewport& visualViewport =
frame()->page()->frameHost().visualViewport();
FrameView& frameView = *webViewImpl()->mainFrameImpl()->frameView();
visualViewport.setScale(pageScale);
EXPECT_SIZE_EQ(
IntSize(250, (visualViewportHeight - browserControlsHeight) / pageScale),
visualViewport.visibleRect().size());
EXPECT_SIZE_EQ(IntSize(1000, layoutViewportHeight -
browserControlsHeight / minPageScale),
frameView.frameRect().size());
EXPECT_SIZE_EQ(IntSize(500, visualViewportHeight - browserControlsHeight),
visualViewport.size());
// Scroll all the way to the bottom, hiding the browser controls in the
// process.
visualViewport.move(ScrollOffset(10000, 10000));
frameView.layoutViewportScrollableArea()->scrollBy(ScrollOffset(10000, 10000),
UserScroll);
webViewImpl()->browserControls().setShownRatio(0);
EXPECT_SIZE_EQ(IntSize(250, visualViewportHeight / pageScale),
visualViewport.visibleRect().size());
ScrollOffset frameViewExpected =
expectedMaxFrameViewScrollOffset(visualViewport, frameView);
ScrollOffset visualViewportExpected = ScrollOffset(
750, layoutViewportHeight - visualViewportHeight / pageScale);
EXPECT_SIZE_EQ(visualViewportExpected, visualViewport.scrollOffset());
EXPECT_SIZE_EQ(frameViewExpected,
frameView.layoutViewportScrollableArea()->scrollOffset());
ScrollOffset totalExpected = visualViewportExpected + frameViewExpected;
// Resize the widget to match the browser controls adjustment. Ensure that the
// total offset (i.e. what the user sees) doesn't change because of clamping
// the offsets to valid values.
webViewImpl()->resizeWithBrowserControls(WebSize(500, visualViewportHeight),
20, false);
EXPECT_SIZE_EQ(IntSize(500, visualViewportHeight), visualViewport.size());
EXPECT_SIZE_EQ(IntSize(250, visualViewportHeight / pageScale),
visualViewport.visibleRect().size());
EXPECT_SIZE_EQ(IntSize(1000, layoutViewportHeight),
frameView.frameRect().size());
EXPECT_SIZE_EQ(totalExpected,
visualViewport.scrollOffset() +
frameView.layoutViewportScrollableArea()->scrollOffset());
}
// Tests that a scroll all the way to the bottom while showing the browser
// controls doesn't cause a clamp to the viewport scroll offset when the browser
// controls initiated resize occurs.
TEST_P(VisualViewportTest, TestBrowserControlsShrinkAdjustmentAndResize) {
int browserControlsHeight = 20;
int visualViewportHeight = 500;
int layoutViewportHeight = 1000;
int contentHeight = 2000;
float pageScale = 2;
float minPageScale = 0.5;
initializeWithAndroidSettings();
// Initialize with browser controls hidden and not shrinking the Blink size.
webViewImpl()->resizeWithBrowserControls(IntSize(500, visualViewportHeight),
20, false);
webViewImpl()->browserControls().setShownRatio(0);
registerMockedHttpURLLoad("content-width-1000.html");
navigateTo(m_baseURL + "content-width-1000.html");
VisualViewport& visualViewport =
frame()->page()->frameHost().visualViewport();
FrameView& frameView = *webViewImpl()->mainFrameImpl()->frameView();
visualViewport.setScale(pageScale);
EXPECT_SIZE_EQ(IntSize(250, visualViewportHeight / pageScale),
visualViewport.visibleRect().size());
EXPECT_SIZE_EQ(IntSize(1000, layoutViewportHeight),
frameView.frameRect().size());
EXPECT_SIZE_EQ(IntSize(500, visualViewportHeight), visualViewport.size());
// Scroll all the way to the bottom, showing the the browser controls in the
// process. (This could happen via window.scrollTo during a scroll, for
// example).
webViewImpl()->browserControls().setShownRatio(1);
visualViewport.move(ScrollOffset(10000, 10000));
frameView.layoutViewportScrollableArea()->scrollBy(ScrollOffset(10000, 10000),
UserScroll);
EXPECT_SIZE_EQ(
IntSize(250, (visualViewportHeight - browserControlsHeight) / pageScale),
visualViewport.visibleRect().size());
ScrollOffset frameViewExpected(
0, contentHeight -
(layoutViewportHeight - browserControlsHeight / minPageScale));
ScrollOffset visualViewportExpected = ScrollOffset(
750, (layoutViewportHeight - browserControlsHeight / minPageScale -
visualViewport.visibleRect().height()));
EXPECT_SIZE_EQ(visualViewportExpected, visualViewport.scrollOffset());
EXPECT_SIZE_EQ(frameViewExpected,
frameView.layoutViewportScrollableArea()->scrollOffset());
ScrollOffset totalExpected = visualViewportExpected + frameViewExpected;
// Resize the widget to match the browser controls adjustment. Ensure that the
// total offset (i.e. what the user sees) doesn't change because of clamping
// the offsets to valid values.
webViewImpl()->resizeWithBrowserControls(
WebSize(500, visualViewportHeight - browserControlsHeight), 20, true);
EXPECT_SIZE_EQ(IntSize(500, visualViewportHeight - browserControlsHeight),
visualViewport.size());
EXPECT_SIZE_EQ(
IntSize(250, (visualViewportHeight - browserControlsHeight) / pageScale),
visualViewport.visibleRect().size());
EXPECT_SIZE_EQ(IntSize(1000, layoutViewportHeight -
browserControlsHeight / minPageScale),
frameView.frameRect().size());
EXPECT_SIZE_EQ(totalExpected,
visualViewport.scrollOffset() +
frameView.layoutViewportScrollableArea()->scrollOffset());
}
// Tests that a resize due to browser controls hiding doesn't incorrectly clamp
// the main frame's scroll offset. crbug.com/428193.
TEST_P(VisualViewportTest, TestTopControlHidingResizeDoesntClampMainFrame) {
initializeWithAndroidSettings();
webViewImpl()->resizeWithBrowserControls(webViewImpl()->size(), 500, false);
webViewImpl()->applyViewportDeltas(WebFloatSize(), WebFloatSize(),
WebFloatSize(), 1, 1);
webViewImpl()->resizeWithBrowserControls(WebSize(1000, 1000), 500, true);
registerMockedHttpURLLoad("content-width-1000.html");
navigateTo(m_baseURL + "content-width-1000.html");
// Scroll the FrameView to the bottom of the page but "hide" the browser
// controls on the compositor side so the max scroll position should account
// for the full viewport height.
webViewImpl()->applyViewportDeltas(WebFloatSize(), WebFloatSize(),
WebFloatSize(), 1, -1);
FrameView& frameView = *webViewImpl()->mainFrameImpl()->frameView();
frameView.layoutViewportScrollableArea()->setScrollOffset(
ScrollOffset(0, 10000), ProgrammaticScroll);
EXPECT_EQ(500,
frameView.layoutViewportScrollableArea()->scrollOffset().height());
// Now send the resize, make sure the scroll offset doesn't change.
webViewImpl()->resizeWithBrowserControls(WebSize(1000, 1500), 500, false);
EXPECT_EQ(500,
frameView.layoutViewportScrollableArea()->scrollOffset().height());
}
static void configureHiddenScrollbarsSettings(WebSettings* settings) {
VisualViewportTest::configureAndroidSettings(settings);
settings->setHideScrollbars(true);
}
// Tests that scrollbar layers are not attached to the inner viewport container
// layer when hideScrollbars WebSetting is true.
TEST_P(VisualViewportTest,
TestScrollbarsNotAttachedWhenHideScrollbarsSettingIsTrue) {
initializeWithAndroidSettings(configureHiddenScrollbarsSettings);
webViewImpl()->resize(IntSize(100, 150));
navigateTo("about:blank");
VisualViewport& visualViewport =
frame()->page()->frameHost().visualViewport();
EXPECT_FALSE(visualViewport.layerForHorizontalScrollbar()->parent());
EXPECT_FALSE(visualViewport.layerForVerticalScrollbar()->parent());
}
// Tests that scrollbar layers are attached to the inner viewport container
// layer when hideScrollbars WebSetting is false.
TEST_P(VisualViewportTest,
TestScrollbarsAttachedWhenHideScrollbarsSettingIsFalse) {
initializeWithAndroidSettings();
webViewImpl()->resize(IntSize(100, 150));
navigateTo("about:blank");
VisualViewport& visualViewport =
frame()->page()->frameHost().visualViewport();
EXPECT_TRUE(visualViewport.layerForHorizontalScrollbar()->parent());
EXPECT_TRUE(visualViewport.layerForVerticalScrollbar()->parent());
}
// Tests that the layout viewport's scroll layer bounds are updated in a
// compositing change update. crbug.com/423188.
TEST_P(VisualViewportTest, TestChangingContentSizeAffectsScrollBounds) {
initializeWithAndroidSettings();
webViewImpl()->resize(IntSize(100, 150));
registerMockedHttpURLLoad("content-width-1000.html");
navigateTo(m_baseURL + "content-width-1000.html");
FrameView& frameView = *webViewImpl()->mainFrameImpl()->frameView();
WebLayer* scrollLayer = frameView.layerForScrolling()->platformLayer();
webViewImpl()->mainFrame()->executeScript(
WebScriptSource("var content = document.getElementById(\"content\");"
"content.style.width = \"1500px\";"
"content.style.height = \"2400px\";"));
frameView.updateAllLifecyclePhases();
EXPECT_SIZE_EQ(IntSize(1500, 2400), IntSize(scrollLayer->bounds()));
}
// Tests that resizing the visual viepwort keeps its bounds within the outer
// viewport.
TEST_P(VisualViewportTest, ResizeVisualViewportStaysWithinOuterViewport) {
initializeWithDesktopSettings();
webViewImpl()->resize(IntSize(100, 200));
navigateTo("about:blank");
webViewImpl()->updateAllLifecyclePhases();
webViewImpl()->resizeVisualViewport(IntSize(100, 100));
VisualViewport& visualViewport =
frame()->page()->frameHost().visualViewport();
visualViewport.move(ScrollOffset(0, 100));
EXPECT_EQ(100, visualViewport.scrollOffset().height());
webViewImpl()->resizeVisualViewport(IntSize(100, 200));
EXPECT_EQ(0, visualViewport.scrollOffset().height());
}
TEST_P(VisualViewportTest, ElementBoundsInViewportSpaceAccountsForViewport) {
initializeWithAndroidSettings();
webViewImpl()->resize(IntSize(500, 800));
registerMockedHttpURLLoad("pinch-viewport-input-field.html");
navigateTo(m_baseURL + "pinch-viewport-input-field.html");
webViewImpl()->setInitialFocus(false);
Element* inputElement = webViewImpl()->focusedElement();
IntRect bounds = inputElement->layoutObject()->absoluteBoundingBoxRect();
VisualViewport& visualViewport =
frame()->page()->frameHost().visualViewport();
IntPoint scrollDelta(250, 400);
visualViewport.setScale(2);
visualViewport.setLocation(scrollDelta);
const IntRect boundsInViewport = inputElement->boundsInViewport();
IntRect expectedBounds = bounds;
expectedBounds.scale(2.f);
IntPoint expectedScrollDelta = scrollDelta;
expectedScrollDelta.scale(2.f, 2.f);
EXPECT_POINT_EQ(IntPoint(expectedBounds.location() - expectedScrollDelta),
boundsInViewport.location());
EXPECT_SIZE_EQ(expectedBounds.size(), boundsInViewport.size());
}
TEST_P(VisualViewportTest, ElementVisibleBoundsInVisualViewport) {
initializeWithAndroidSettings();
webViewImpl()->resize(IntSize(640, 1080));
registerMockedHttpURLLoad("viewport-select.html");
navigateTo(m_baseURL + "viewport-select.html");
ASSERT_EQ(2.0f, webViewImpl()->pageScaleFactor());
webViewImpl()->setInitialFocus(false);
Element* element = webViewImpl()->focusedElement();
EXPECT_FALSE(element->visibleBoundsInVisualViewport().isEmpty());
webViewImpl()->setPageScaleFactor(4.0);
EXPECT_TRUE(element->visibleBoundsInVisualViewport().isEmpty());
}
// Test that the various window.scroll and document.body.scroll properties and
// methods work unchanged from the pre-virtual viewport mode.
TEST_P(VisualViewportTest, bodyAndWindowScrollPropertiesAccountForViewport) {
initializeWithAndroidSettings();
webViewImpl()->resize(IntSize(200, 300));
// Load page with no main frame scrolling.
registerMockedHttpURLLoad("200-by-300-viewport.html");
navigateTo(m_baseURL + "200-by-300-viewport.html");
VisualViewport& visualViewport =
frame()->page()->frameHost().visualViewport();
visualViewport.setScale(2);
// Chrome's quirky behavior regarding viewport scrolling means we treat the
// body element as the viewport and don't apply scrolling to the HTML element.
RuntimeEnabledFeatures::setScrollTopLeftInteropEnabled(false);
LocalDOMWindow* window =
webViewImpl()->mainFrameImpl()->frame()->localDOMWindow();
window->scrollTo(100, 150);
EXPECT_EQ(100, window->scrollX());
EXPECT_EQ(150, window->scrollY());
EXPECT_FLOAT_SIZE_EQ(FloatSize(100, 150), visualViewport.scrollOffset());
HTMLElement* body = toHTMLBodyElement(window->document()->body());
body->setScrollLeft(50);
body->setScrollTop(130);
EXPECT_EQ(50, body->scrollLeft());
EXPECT_EQ(130, body->scrollTop());
EXPECT_FLOAT_SIZE_EQ(FloatSize(50, 130), visualViewport.scrollOffset());
HTMLElement* documentElement =
toHTMLElement(window->document()->documentElement());
documentElement->setScrollLeft(40);
documentElement->setScrollTop(50);
EXPECT_EQ(0, documentElement->scrollLeft());
EXPECT_EQ(0, documentElement->scrollTop());
EXPECT_FLOAT_SIZE_EQ(FloatSize(50, 130), visualViewport.scrollOffset());
visualViewport.setLocation(FloatPoint(10, 20));
EXPECT_EQ(10, body->scrollLeft());
EXPECT_EQ(20, body->scrollTop());
EXPECT_EQ(0, documentElement->scrollLeft());
EXPECT_EQ(0, documentElement->scrollTop());
EXPECT_EQ(10, window->scrollX());
EXPECT_EQ(20, window->scrollY());
// Turning on the standards-compliant viewport scrolling impl should make the
// document element the viewport and not body.
RuntimeEnabledFeatures::setScrollTopLeftInteropEnabled(true);
window->scrollTo(100, 150);
EXPECT_EQ(100, window->scrollX());
EXPECT_EQ(150, window->scrollY());
EXPECT_FLOAT_SIZE_EQ(FloatSize(100, 150), visualViewport.scrollOffset());
body->setScrollLeft(50);
body->setScrollTop(130);
EXPECT_EQ(0, body->scrollLeft());
EXPECT_EQ(0, body->scrollTop());
EXPECT_FLOAT_SIZE_EQ(FloatSize(100, 150), visualViewport.scrollOffset());
documentElement->setScrollLeft(40);
documentElement->setScrollTop(50);
EXPECT_EQ(40, documentElement->scrollLeft());
EXPECT_EQ(50, documentElement->scrollTop());
EXPECT_FLOAT_SIZE_EQ(FloatSize(40, 50), visualViewport.scrollOffset());
visualViewport.setLocation(FloatPoint(10, 20));
EXPECT_EQ(0, body->scrollLeft());
EXPECT_EQ(0, body->scrollTop());
EXPECT_EQ(10, documentElement->scrollLeft());
EXPECT_EQ(20, documentElement->scrollTop());
EXPECT_EQ(10, window->scrollX());
EXPECT_EQ(20, window->scrollY());
}
// Tests that when a new frame is created, it is created with the intended size
// (i.e. viewport at minimum scale, 100x200 / 0.5).
TEST_P(VisualViewportTest, TestMainFrameInitializationSizing) {
initializeWithAndroidSettings();
webViewImpl()->resize(IntSize(100, 200));
registerMockedHttpURLLoad("content-width-1000-min-scale.html");
navigateTo(m_baseURL + "content-width-1000-min-scale.html");
WebLocalFrameImpl* localFrame = webViewImpl()->mainFrameImpl();
// The shutdown() calls are a hack to prevent this test from violating
// invariants about frame state during navigation/detach.
localFrame->frame()->document()->shutdown();
localFrame->createFrameView();
FrameView& frameView = *localFrame->frameView();
EXPECT_SIZE_EQ(IntSize(200, 400), frameView.frameRect().size());
frameView.dispose();
}
// Tests that the maximum scroll offset of the viewport can be fractional.
TEST_P(VisualViewportTest, FractionalMaxScrollOffset) {
initializeWithDesktopSettings();
webViewImpl()->resize(IntSize(101, 201));
navigateTo("about:blank");
VisualViewport& visualViewport =
frame()->page()->frameHost().visualViewport();
ScrollableArea* scrollableArea = &visualViewport;
webViewImpl()->setPageScaleFactor(1.0);
EXPECT_SIZE_EQ(ScrollOffset(), scrollableArea->maximumScrollOffset());
webViewImpl()->setPageScaleFactor(2);
EXPECT_SIZE_EQ(ScrollOffset(101. / 2., 201. / 2.),
scrollableArea->maximumScrollOffset());
}
// Tests that the slow scrolling after an impl scroll on the visual viewport is
// continuous. crbug.com/453460 was caused by the impl-path not updating the
// ScrollAnimatorBase class.
TEST_P(VisualViewportTest, SlowScrollAfterImplScroll) {
initializeWithDesktopSettings();
webViewImpl()->resize(IntSize(800, 600));
navigateTo("about:blank");
VisualViewport& visualViewport =
frame()->page()->frameHost().visualViewport();
// Apply some scroll and scale from the impl-side.
webViewImpl()->applyViewportDeltas(WebFloatSize(300, 200), WebFloatSize(0, 0),
WebFloatSize(0, 0), 2, 0);
EXPECT_SIZE_EQ(FloatSize(300, 200), visualViewport.scrollOffset());
// Send a scroll event on the main thread path.
PlatformGestureEvent gsu(PlatformEvent::GestureScrollUpdate, IntPoint(0, 0),
IntPoint(0, 0), IntSize(5, 5), 0,
PlatformEvent::NoModifiers,
PlatformGestureSourceTouchpad);
gsu.setScrollGestureData(-50, -60, ScrollByPrecisePixel, 1, 1,
ScrollInertialPhaseUnknown, false,
-1 /* null plugin id */);
frame()->eventHandler().handleGestureEvent(gsu);
// The scroll sent from the impl-side must not be overwritten.
EXPECT_SIZE_EQ(FloatSize(350, 260), visualViewport.scrollOffset());
}
static void accessibilitySettings(WebSettings* settings) {
VisualViewportTest::configureSettings(settings);
settings->setAccessibilityEnabled(true);
}
TEST_P(VisualViewportTest, AccessibilityHitTestWhileZoomedIn) {
initializeWithDesktopSettings(accessibilitySettings);
registerMockedHttpURLLoad("hit-test.html");
navigateTo(m_baseURL + "hit-test.html");
webViewImpl()->resize(IntSize(500, 500));
webViewImpl()->updateAllLifecyclePhases();
WebDocument webDoc = webViewImpl()->mainFrame()->document();
FrameView& frameView = *webViewImpl()->mainFrameImpl()->frameView();
webViewImpl()->setPageScaleFactor(2);
webViewImpl()->setVisualViewportOffset(WebFloatPoint(200, 230));
frameView.layoutViewportScrollableArea()->setScrollOffset(
ScrollOffset(400, 1100), ProgrammaticScroll);
// FIXME(504057): PaintLayerScrollableArea dirties the compositing state.
forceFullCompositingUpdate();
// Because of where the visual viewport is located, this should hit the bottom
// right target (target 4).
WebAXObject hitNode =
webDoc.accessibilityObject().hitTest(WebPoint(154, 165));
WebAXNameFrom nameFrom;
WebVector<WebAXObject> nameObjects;
EXPECT_EQ(std::string("Target4"), hitNode.name(nameFrom, nameObjects).utf8());
}
// Tests that the maximum scroll offset of the viewport can be fractional.
TEST_P(VisualViewportTest, TestCoordinateTransforms) {
initializeWithAndroidSettings();
webViewImpl()->resize(IntSize(800, 600));
registerMockedHttpURLLoad("content-width-1000.html");
navigateTo(m_baseURL + "content-width-1000.html");
VisualViewport& visualViewport =
webViewImpl()->page()->frameHost().visualViewport();
FrameView& frameView = *webViewImpl()->mainFrameImpl()->frameView();
// At scale = 1 the transform should be a no-op.
visualViewport.setScale(1);
EXPECT_FLOAT_POINT_EQ(
FloatPoint(314, 273),
visualViewport.viewportToRootFrame(FloatPoint(314, 273)));
EXPECT_FLOAT_POINT_EQ(
FloatPoint(314, 273),
visualViewport.rootFrameToViewport(FloatPoint(314, 273)));
// At scale = 2.
visualViewport.setScale(2);
EXPECT_FLOAT_POINT_EQ(FloatPoint(55, 75), visualViewport.viewportToRootFrame(
FloatPoint(110, 150)));
EXPECT_FLOAT_POINT_EQ(FloatPoint(110, 150),
visualViewport.rootFrameToViewport(FloatPoint(55, 75)));
// At scale = 2 and with the visual viewport offset.
visualViewport.setLocation(FloatPoint(10, 12));
EXPECT_FLOAT_POINT_EQ(FloatPoint(50, 62), visualViewport.viewportToRootFrame(
FloatPoint(80, 100)));
EXPECT_FLOAT_POINT_EQ(FloatPoint(80, 100),
visualViewport.rootFrameToViewport(FloatPoint(50, 62)));
// Test points that will cause non-integer values.
EXPECT_FLOAT_POINT_EQ(
FloatPoint(50.5, 62.4),
visualViewport.viewportToRootFrame(FloatPoint(81, 100.8)));
EXPECT_FLOAT_POINT_EQ(
FloatPoint(81, 100.8),
visualViewport.rootFrameToViewport(FloatPoint(50.5, 62.4)));
// Scrolling the main frame should have no effect.
frameView.layoutViewportScrollableArea()->setScrollOffset(
ScrollOffset(100, 120), ProgrammaticScroll);
EXPECT_FLOAT_POINT_EQ(FloatPoint(50, 62), visualViewport.viewportToRootFrame(
FloatPoint(80, 100)));
EXPECT_FLOAT_POINT_EQ(FloatPoint(80, 100),
visualViewport.rootFrameToViewport(FloatPoint(50, 62)));
}
// Tests that the window dimensions are available before a full layout occurs.
// More specifically, it checks that the innerWidth and innerHeight window
// properties will trigger a layout which will cause an update to viewport
// constraints and a refreshed initial scale. crbug.com/466718
TEST_P(VisualViewportTest, WindowDimensionsOnLoad) {
initializeWithAndroidSettings();
registerMockedHttpURLLoad("window_dimensions.html");
webViewImpl()->resize(IntSize(800, 600));
navigateTo(m_baseURL + "window_dimensions.html");
Element* output = frame()->document()->getElementById("output");
DCHECK(output);
EXPECT_EQ(std::string("1600x1200"),
std::string(output->innerHTML().ascii().data()));
}
// Similar to above but make sure the initial scale is updated with the content
// width for a very wide page. That is, make that innerWidth/Height actually
// trigger a layout of the content, and not just an update of the viepwort.
// crbug.com/466718
TEST_P(VisualViewportTest, WindowDimensionsOnLoadWideContent) {
initializeWithAndroidSettings();
registerMockedHttpURLLoad("window_dimensions_wide_div.html");
webViewImpl()->resize(IntSize(800, 600));
navigateTo(m_baseURL + "window_dimensions_wide_div.html");
Element* output = frame()->document()->getElementById("output");
DCHECK(output);
EXPECT_EQ(std::string("2000x1500"),
std::string(output->innerHTML().ascii().data()));
}
TEST_P(VisualViewportTest, PinchZoomGestureScrollsVisualViewportOnly) {
initializeWithDesktopSettings();
webViewImpl()->resize(IntSize(100, 100));
registerMockedHttpURLLoad("200-by-800-viewport.html");
navigateTo(m_baseURL + "200-by-800-viewport.html");
WebGestureEvent pinchUpdate;
pinchUpdate.type = WebInputEvent::GesturePinchUpdate;
pinchUpdate.sourceDevice = WebGestureDeviceTouchpad;
pinchUpdate.x = 100;
pinchUpdate.y = 100;
pinchUpdate.data.pinchUpdate.scale = 2;
pinchUpdate.data.pinchUpdate.zoomDisabled = false;
webViewImpl()->handleInputEvent(pinchUpdate);
VisualViewport& visualViewport =
webViewImpl()->page()->frameHost().visualViewport();
FrameView& frameView = *webViewImpl()->mainFrameImpl()->frameView();
EXPECT_FLOAT_SIZE_EQ(FloatSize(50, 50), visualViewport.scrollOffset());
EXPECT_SIZE_EQ(ScrollOffset(0, 0),
frameView.layoutViewportScrollableArea()->scrollOffset());
}
TEST_P(VisualViewportTest, ResizeWithScrollAnchoring) {
bool wasScrollAnchoringEnabled =
RuntimeEnabledFeatures::scrollAnchoringEnabled();
RuntimeEnabledFeatures::setScrollAnchoringEnabled(true);
initializeWithDesktopSettings();
webViewImpl()->resize(IntSize(800, 600));
registerMockedHttpURLLoad("icb-relative-content.html");
navigateTo(m_baseURL + "icb-relative-content.html");
FrameView& frameView = *webViewImpl()->mainFrameImpl()->frameView();
frameView.layoutViewportScrollableArea()->setScrollOffset(
ScrollOffset(700, 500), ProgrammaticScroll);
webViewImpl()->updateAllLifecyclePhases();
webViewImpl()->resize(IntSize(800, 300));
EXPECT_SIZE_EQ(ScrollOffset(700, 200),
frameView.layoutViewportScrollableArea()->scrollOffset());
RuntimeEnabledFeatures::setScrollAnchoringEnabled(wasScrollAnchoringEnabled);
}
// Ensure that resize anchoring as happens when browser controls hide/show
// affects the scrollable area that's currently set as the root scroller.
TEST_P(VisualViewportTest, ResizeAnchoringWithRootScroller) {
bool wasRootScrollerEnabled =
RuntimeEnabledFeatures::setRootScrollerEnabled();
RuntimeEnabledFeatures::setSetRootScrollerEnabled(true);
initializeWithAndroidSettings();
webViewImpl()->resize(IntSize(800, 600));
registerMockedHttpURLLoad("root-scroller-div.html");
navigateTo(m_baseURL + "root-scroller-div.html");
FrameView& frameView = *webViewImpl()->mainFrameImpl()->frameView();
Element* scroller = frame()->document()->getElementById("rootScroller");
NonThrowableExceptionState nonThrow;
frame()->document()->setRootScroller(scroller, nonThrow);
webViewImpl()->setPageScaleFactor(3.f);
frameView.getScrollableArea()->setScrollOffset(ScrollOffset(0, 400),
ProgrammaticScroll);
VisualViewport& visualViewport =
webViewImpl()->page()->frameHost().visualViewport();
visualViewport.setScrollOffset(ScrollOffset(0, 400), ProgrammaticScroll);
webViewImpl()->resize(IntSize(800, 500));
EXPECT_SIZE_EQ(ScrollOffset(),
frameView.layoutViewportScrollableArea()->scrollOffset());
RuntimeEnabledFeatures::setSetRootScrollerEnabled(wasRootScrollerEnabled);
}
// Ensure that resize anchoring as happens when the device is rotated affects
// the scrollable area that's currently set as the root scroller.
TEST_P(VisualViewportTest, RotationAnchoringWithRootScroller) {
bool wasRootScrollerEnabled =
RuntimeEnabledFeatures::setRootScrollerEnabled();
RuntimeEnabledFeatures::setSetRootScrollerEnabled(true);
initializeWithAndroidSettings();
webViewImpl()->resize(IntSize(800, 600));
registerMockedHttpURLLoad("root-scroller-div.html");
navigateTo(m_baseURL + "root-scroller-div.html");
FrameView& frameView = *webViewImpl()->mainFrameImpl()->frameView();
Element* scroller = frame()->document()->getElementById("rootScroller");
NonThrowableExceptionState nonThrow;
frame()->document()->setRootScroller(scroller, nonThrow);
webViewImpl()->updateAllLifecyclePhases();
scroller->setScrollTop(800);
webViewImpl()->resize(IntSize(600, 800));
EXPECT_SIZE_EQ(ScrollOffset(),
frameView.layoutViewportScrollableArea()->scrollOffset());
EXPECT_EQ(600, scroller->scrollTop());
RuntimeEnabledFeatures::setSetRootScrollerEnabled(wasRootScrollerEnabled);
}
static void configureAndroidCompositing(WebSettings* settings) {
settings->setAcceleratedCompositingEnabled(true);
settings->setPreferCompositingToLCDTextEnabled(true);
settings->setViewportMetaEnabled(true);
settings->setViewportEnabled(true);
settings->setMainFrameResizesAreOrientationChanges(true);
settings->setShrinksViewportContentToFit(true);
}
// Make sure a composited background-attachment:fixed background gets resized
// when using inert (non-layout affecting) browser controls.
TEST_P(VisualViewportTest, ResizeCompositedAndFixedBackground) {
bool originalInertTopControls =
RuntimeEnabledFeatures::inertTopControlsEnabled();
RuntimeEnabledFeatures::setInertTopControlsEnabled(true);
std::unique_ptr<FrameTestHelpers::TestWebViewClient>
fakeCompositingWebViewClient =
makeUnique<FrameTestHelpers::TestWebViewClient>();
FrameTestHelpers::WebViewHelper webViewHelper;
WebViewImpl* webViewImpl = webViewHelper.initialize(
true, nullptr, fakeCompositingWebViewClient.get(), nullptr,
&configureAndroidCompositing);
int pageWidth = 640;
int pageHeight = 480;
float browserControlsHeight = 50.0f;
int smallestHeight = pageHeight - browserControlsHeight;
webViewImpl->resizeWithBrowserControls(WebSize(pageWidth, pageHeight),
browserControlsHeight, false);
URLTestHelpers::registerMockedURLLoad(toKURL("http://example.com/foo.png"),
"white-1x1.png");
WebURL baseURL = URLTestHelpers::toKURL("http://example.com/");
FrameTestHelpers::loadHTMLString(webViewImpl->mainFrame(),
"<!DOCTYPE html>"
"<style>"
" body {"
" background: url('foo.png');"
" background-attachment: fixed;"
" background-size: cover;"
" background-repeat: no-repeat;"
" }"
" div { height:1000px; width: 200px; }"
"</style>"
"<div></div>",
baseURL);
webViewImpl->updateAllLifecyclePhases();
Document* document =
toLocalFrame(webViewImpl->page()->mainFrame())->document();
PaintLayerCompositor* compositor = document->layoutView()->compositor();
ASSERT_TRUE(compositor->needsFixedRootBackgroundLayer(
document->layoutView()->layer()));
ASSERT_TRUE(compositor->fixedRootBackgroundLayer());
ASSERT_EQ(pageWidth, compositor->fixedRootBackgroundLayer()->size().width());
ASSERT_EQ(pageHeight,
compositor->fixedRootBackgroundLayer()->size().height());
ASSERT_EQ(pageWidth, document->view()->layoutSize().width());
ASSERT_EQ(smallestHeight, document->view()->layoutSize().height());
webViewImpl->resizeWithBrowserControls(WebSize(pageWidth, smallestHeight),
browserControlsHeight, true);
// The layout size should not have changed.
ASSERT_EQ(pageWidth, document->view()->layoutSize().width());
ASSERT_EQ(smallestHeight, document->view()->layoutSize().height());
// The background layer's size should have changed though.
EXPECT_EQ(pageWidth, compositor->fixedRootBackgroundLayer()->size().width());
EXPECT_EQ(smallestHeight,
compositor->fixedRootBackgroundLayer()->size().height());
webViewImpl->resizeWithBrowserControls(WebSize(pageWidth, pageHeight),
browserControlsHeight, true);
// The background layer's size should change again.
EXPECT_EQ(pageWidth, compositor->fixedRootBackgroundLayer()->size().width());
EXPECT_EQ(pageHeight,
compositor->fixedRootBackgroundLayer()->size().height());
RuntimeEnabledFeatures::setInertTopControlsEnabled(originalInertTopControls);
}
static void configureAndroidNonCompositing(WebSettings* settings) {
settings->setAcceleratedCompositingEnabled(true);
settings->setPreferCompositingToLCDTextEnabled(false);
settings->setViewportMetaEnabled(true);
settings->setViewportEnabled(true);
settings->setMainFrameResizesAreOrientationChanges(true);
settings->setShrinksViewportContentToFit(true);
}
// Make sure a non-composited background-attachment:fixed background gets
// resized when using inert (non-layout affecting) browser controls.
TEST_P(VisualViewportTest, ResizeNonCompositedAndFixedBackground) {
bool originalInertTopControls =
RuntimeEnabledFeatures::inertTopControlsEnabled();
RuntimeEnabledFeatures::setInertTopControlsEnabled(true);
FrameTestHelpers::WebViewHelper webViewHelper;
WebViewImpl* webViewImpl = webViewHelper.initialize(
true, nullptr, nullptr, nullptr, &configureAndroidNonCompositing);
int pageWidth = 640;
int pageHeight = 480;
float browserControlsHeight = 50.0f;
int smallestHeight = pageHeight - browserControlsHeight;
webViewImpl->resizeWithBrowserControls(WebSize(pageWidth, pageHeight),
browserControlsHeight, false);
URLTestHelpers::registerMockedURLLoad(toKURL("http://example.com/foo.png"),
"white-1x1.png");
WebURL baseURL = URLTestHelpers::toKURL("http://example.com/");
FrameTestHelpers::loadHTMLString(webViewImpl->mainFrame(),
"<!DOCTYPE html>"
"<style>"
" body {"
" margin: 0px;"
" background: url('foo.png');"
" background-attachment: fixed;"
" background-size: cover;"
" background-repeat: no-repeat;"
" }"
" div { height:1000px; width: 200px; }"
"</style>"
"<div></div>",
baseURL);
webViewImpl->updateAllLifecyclePhases();
Document* document =
toLocalFrame(webViewImpl->page()->mainFrame())->document();
PaintLayerCompositor* compositor = document->layoutView()->compositor();
ASSERT_FALSE(compositor->needsFixedRootBackgroundLayer(
document->layoutView()->layer()));
ASSERT_FALSE(compositor->fixedRootBackgroundLayer());
document->view()->setTracksPaintInvalidations(true);
webViewImpl->resizeWithBrowserControls(WebSize(pageWidth, smallestHeight),
browserControlsHeight, true);
// The layout size should not have changed.
ASSERT_EQ(pageWidth, document->view()->layoutSize().width());
ASSERT_EQ(smallestHeight, document->view()->layoutSize().height());
const RasterInvalidationTracking* invalidationTracking =
document->layoutView()
->layer()
->graphicsLayerBacking()
->getRasterInvalidationTracking();
// If no invalidations occured, this will be a nullptr.
ASSERT_TRUE(invalidationTracking);
const auto* rasterInvalidations =
&invalidationTracking->trackedRasterInvalidations;
bool rootLayerScrolling = GetParam();
// Without root-layer-scrolling, the LayoutView is the size of the document
// content so invalidating it for background-attachment: fixed
// overinvalidates as we should only need to invalidate the viewport size.
// With root-layer-scrolling, we should invalidate the entire viewport height.
int expectedHeight = rootLayerScrolling ? pageHeight : 1000;
// The entire viewport should have been invalidated.
EXPECT_EQ(1u, rasterInvalidations->size());
EXPECT_EQ(IntRect(0, 0, 640, expectedHeight), (*rasterInvalidations)[0].rect);
document->view()->setTracksPaintInvalidations(false);
invalidationTracking = document->layoutView()
->layer()
->graphicsLayerBacking()
->getRasterInvalidationTracking();
ASSERT_FALSE(invalidationTracking);
document->view()->setTracksPaintInvalidations(true);
webViewImpl->resizeWithBrowserControls(WebSize(pageWidth, pageHeight),
browserControlsHeight, true);
invalidationTracking = document->layoutView()
->layer()
->graphicsLayerBacking()
->getRasterInvalidationTracking();
ASSERT_TRUE(invalidationTracking);
rasterInvalidations = &invalidationTracking->trackedRasterInvalidations;
// Once again, the entire page should have been invalidated.
expectedHeight = rootLayerScrolling ? 480 : 1000;
EXPECT_EQ(1u, rasterInvalidations->size());
EXPECT_EQ(IntRect(0, 0, 640, expectedHeight), (*rasterInvalidations)[0].rect);
document->view()->setTracksPaintInvalidations(false);
RuntimeEnabledFeatures::setInertTopControlsEnabled(originalInertTopControls);
}
// Make sure a browser control resize with background-attachment:not-fixed
// background doesn't cause invalidation or layout.
TEST_P(VisualViewportTest, ResizeNonFixedBackgroundNoLayoutOrInvalidation) {
bool originalInertTopControls =
RuntimeEnabledFeatures::inertTopControlsEnabled();
RuntimeEnabledFeatures::setInertTopControlsEnabled(true);
std::unique_ptr<FrameTestHelpers::TestWebViewClient>
fakeCompositingWebViewClient =
makeUnique<FrameTestHelpers::TestWebViewClient>();
FrameTestHelpers::WebViewHelper webViewHelper;
WebViewImpl* webViewImpl = webViewHelper.initialize(
true, nullptr, fakeCompositingWebViewClient.get(), nullptr,
&configureAndroidCompositing);
int pageWidth = 640;
int pageHeight = 480;
float browserControlsHeight = 50.0f;
int smallestHeight = pageHeight - browserControlsHeight;
webViewImpl->resizeWithBrowserControls(WebSize(pageWidth, pageHeight),
browserControlsHeight, false);
URLTestHelpers::registerMockedURLLoad(toKURL("http://example.com/foo.png"),
"white-1x1.png");
WebURL baseURL = URLTestHelpers::toKURL("http://example.com/");
// This time the background is the default attachment.
FrameTestHelpers::loadHTMLString(webViewImpl->mainFrame(),
"<!DOCTYPE html>"
"<style>"
" body {"
" margin: 0px;"
" background: url('foo.png');"
" background-size: cover;"
" background-repeat: no-repeat;"
" }"
" div { height:1000px; width: 200px; }"
"</style>"
"<div></div>",
baseURL);
webViewImpl->updateAllLifecyclePhases();
Document* document =
toLocalFrame(webViewImpl->page()->mainFrame())->document();
// A resize will do a layout synchronously so manually check that we don't
// setNeedsLayout from viewportSizeChanged.
document->view()->viewportSizeChanged(false, true);
unsigned needsLayoutObjects = 0;
unsigned totalObjects = 0;
bool isSubtree = false;
EXPECT_FALSE(document->view()->needsLayout());
document->view()->countObjectsNeedingLayout(needsLayoutObjects, totalObjects,
isSubtree);
EXPECT_EQ(0u, needsLayoutObjects);
// Do a real resize to check for invalidations.
document->view()->setTracksPaintInvalidations(true);
webViewImpl->resizeWithBrowserControls(WebSize(pageWidth, smallestHeight),
browserControlsHeight, true);
// The layout size should not have changed.
ASSERT_EQ(pageWidth, document->view()->layoutSize().width());
ASSERT_EQ(smallestHeight, document->view()->layoutSize().height());
const RasterInvalidationTracking* invalidationTracking =
document->layoutView()
->layer()
->graphicsLayerBacking()
->getRasterInvalidationTracking();
// No invalidations should have occured in FrameView scrolling. If
// root-layer-scrolls is on, an invalidation is necessary for now, see the
// comment and TODO in FrameView::viewportSizeChanged.
// http://crbug.com/568847.
bool rootLayerScrolling = GetParam();
if (rootLayerScrolling)
EXPECT_TRUE(invalidationTracking);
else
EXPECT_FALSE(invalidationTracking);
document->view()->setTracksPaintInvalidations(false);
RuntimeEnabledFeatures::setInertTopControlsEnabled(originalInertTopControls);
}
// Make sure we don't crash when the visual viewport's height is 0. This can
// happen transiently in autoresize mode and cause a crash. This test passes if
// it doesn't crash.
TEST_P(VisualViewportTest, AutoResizeNoHeightUsesMinimumHeight) {
initializeWithDesktopSettings();
webViewImpl()->resizeWithBrowserControls(WebSize(0, 0), 0, false);
webViewImpl()->enableAutoResizeMode(WebSize(25, 25), WebSize(100, 100));
WebURL baseURL = URLTestHelpers::toKURL("http://example.com/");
FrameTestHelpers::loadHTMLString(webViewImpl()->mainFrame(),
"<!DOCTYPE html>"
"<style>"
" body {"
" margin: 0px;"
" }"
" div { height:110vh; width: 110vw; }"
"</style>"
"<div></div>",
baseURL);
}
} // namespace
| 100,492 | 31,183 |
// 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,477 | 10,589 |
// 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);
}
| 6,289 | 2,016 |
#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();
}
| 20,442 | 8,016 |
// 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>;
//----------------------------------------------------------------------------
}
| 10,485 | 4,532 |
/// @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;
| 1,332 | 323 |
#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;
}
| 2,923 | 1,182 |
#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
| 187 | 88 |
#include "GripPipeline.h"
namespace grip {
GripPipeline::GripPipeline() {
}
/**
* Runs an iteration of the pipeline and updates outputs.
*/
void GripPipeline::Process(cv::Mat& source0){
//Step Resize_Image0:
//input
cv::Mat resizeImageInput = source0;
double resizeImageWidth = 640.0; // default Double
double resizeImageHeight = 480.0; // default Double
int resizeImageInterpolation = cv::INTER_CUBIC;
resizeImage(resizeImageInput, resizeImageWidth, resizeImageHeight, resizeImageInterpolation, this->resizeImageOutput);
//Step HSV_Threshold0:
//input
cv::Mat hsvThresholdInput = resizeImageOutput;
double hsvThresholdHue[] = {0.0, 180.0};
double hsvThresholdSaturation[] = {0.0, 51.51952461799661};
double hsvThresholdValue[] = {123.83093525179855, 255.0};
hsvThreshold(hsvThresholdInput, hsvThresholdHue, hsvThresholdSaturation, hsvThresholdValue, this->hsvThresholdOutput);
//Step CV_erode0:
//input
cv::Mat cvErodeSrc = hsvThresholdOutput;
cv::Mat cvErodeKernel;
cv::Point cvErodeAnchor(-1, -1);
double cvErodeIterations = 20.0; // default Double
int cvErodeBordertype = cv::BORDER_CONSTANT;
cv::Scalar cvErodeBordervalue(-1);
cvErode(cvErodeSrc, cvErodeKernel, cvErodeAnchor, cvErodeIterations, cvErodeBordertype, cvErodeBordervalue, this->cvErodeOutput);
//Step CV_dilate0:
//input
cv::Mat cvDilateSrc = cvErodeOutput;
cv::Mat cvDilateKernel;
cv::Point cvDilateAnchor(-1, -1);
double cvDilateIterations = 42.0; // default Double
int cvDilateBordertype = cv::BORDER_CONSTANT;
cv::Scalar cvDilateBordervalue(-1);
cvDilate(cvDilateSrc, cvDilateKernel, cvDilateAnchor, cvDilateIterations, cvDilateBordertype, cvDilateBordervalue, this->cvDilateOutput);
//Step Mask0:
//input
cv::Mat maskInput = resizeImageOutput;
cv::Mat maskMask = cvDilateOutput;
mask(maskInput, maskMask, this->maskOutput);
//Step Find_Contours0:
//input
cv::Mat findContoursInput = cvDilateOutput;
bool findContoursExternalOnly = false; // default Boolean
findContours(findContoursInput, findContoursExternalOnly, this->findContoursOutput);
}
/**
* This method is a generated getter for the output of a Resize_Image.
* @return Mat output from Resize_Image.
*/
cv::Mat* GripPipeline::GetResizeImageOutput(){
return &(this->resizeImageOutput);
}
/**
* This method is a generated getter for the output of a HSV_Threshold.
* @return Mat output from HSV_Threshold.
*/
cv::Mat* GripPipeline::GetHsvThresholdOutput(){
return &(this->hsvThresholdOutput);
}
/**
* This method is a generated getter for the output of a CV_erode.
* @return Mat output from CV_erode.
*/
cv::Mat* GripPipeline::GetCvErodeOutput(){
return &(this->cvErodeOutput);
}
/**
* This method is a generated getter for the output of a CV_dilate.
* @return Mat output from CV_dilate.
*/
cv::Mat* GripPipeline::GetCvDilateOutput(){
return &(this->cvDilateOutput);
}
/**
* This method is a generated getter for the output of a Mask.
* @return Mat output from Mask.
*/
cv::Mat* GripPipeline::GetMaskOutput(){
return &(this->maskOutput);
}
/**
* This method is a generated getter for the output of a Find_Contours.
* @return ContoursReport output from Find_Contours.
*/
std::vector<std::vector<cv::Point> >* GripPipeline::GetFindContoursOutput(){
return &(this->findContoursOutput);
}
/**
* Scales and image to an exact size.
*
* @param input The image on which to perform the Resize.
* @param width The width of the output in pixels.
* @param height The height of the output in pixels.
* @param interpolation The type of interpolation.
* @param output The image in which to store the output.
*/
void GripPipeline::resizeImage(cv::Mat &input, double width, double height, int interpolation, cv::Mat &output) {
cv::resize(input, output, cv::Size(width, height), 0.0, 0.0, interpolation);
}
/**
* Segment an image based on hue, saturation, and value ranges.
*
* @param input The image on which to perform the HSL threshold.
* @param hue The min and max hue.
* @param sat The min and max saturation.
* @param val The min and max value.
* @param output The image in which to store the output.
*/
void GripPipeline::hsvThreshold(cv::Mat &input, double hue[], double sat[], double val[], cv::Mat &out) {
cv::cvtColor(input, out, cv::COLOR_BGR2HSV);
cv::inRange(out,cv::Scalar(hue[0], sat[0], val[0]), cv::Scalar(hue[1], sat[1], val[1]), out);
}
/**
* Expands area of lower value in an image.
* @param src the Image to erode.
* @param kernel the kernel for erosion.
* @param anchor the center of the kernel.
* @param iterations the number of times to perform the erosion.
* @param borderType pixel extrapolation method.
* @param borderValue value to be used for a constant border.
* @param dst Output Image.
*/
void GripPipeline::cvErode(cv::Mat &src, cv::Mat &kernel, cv::Point &anchor, double iterations, int borderType, cv::Scalar &borderValue, cv::Mat &dst) {
cv::erode(src, dst, kernel, anchor, (int)iterations, borderType, borderValue);
}
/**
* Expands area of higher value in an image.
* @param src the Image to dilate.
* @param kernel the kernel for dilation.
* @param anchor the center of the kernel.
* @param iterations the number of times to perform the dilation.
* @param borderType pixel extrapolation method.
* @param borderValue value to be used for a constant border.
* @param dst Output Image.
*/
void GripPipeline::cvDilate(cv::Mat &src, cv::Mat &kernel, cv::Point &anchor, double iterations, int borderType, cv::Scalar &borderValue, cv::Mat &dst) {
cv::dilate(src, dst, kernel, anchor, (int)iterations, borderType, borderValue);
}
/**
* Filter out an area of an image using a binary mask.
*
* @param input The image on which the mask filters.
* @param mask The binary image that is used to filter.
* @param output The image in which to store the output.
*/
void GripPipeline::mask(cv::Mat &input, cv::Mat &mask, cv::Mat &output) {
mask.convertTo(mask, CV_8UC1);
cv::bitwise_xor(output, output, output);
input.copyTo(output, mask);
}
/**
* Finds contours in an image.
*
* @param input The image to find contours in.
* @param externalOnly if only external contours are to be found.
* @param contours vector of contours to put contours in.
*/
void GripPipeline::findContours(cv::Mat &input, bool externalOnly, std::vector<std::vector<cv::Point> > &contours) {
std::vector<cv::Vec4i> hierarchy;
contours.clear();
int mode = externalOnly ? cv::RETR_EXTERNAL : cv::RETR_LIST;
int method = cv::CHAIN_APPROX_SIMPLE;
cv::findContours(input, contours, hierarchy, mode, method);
}
} // end grip namespace
| 6,671 | 2,357 |
#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"
| 407 | 171 |
// 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
| 594 | 255 |
#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;
}
| 1,792 | 840 |
#pragma once
#include <libng_core/types/noncopyable.hpp>
namespace libng {
class JSONLexer : public NonCopyable {
public:
void nextChar();
};
} // namespace libng | 168 | 59 |
// 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
| 1,570 | 524 |
/* -*- 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
| 2,143 | 655 |
/*
* 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
| 6,475 | 1,661 |
#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
| 5,916 | 2,372 |
/// \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 | 1,808 | 564 |
/*
* 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 ;
}
}
| 5,605 | 2,112 |
/**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() | 57,619 | 27,003 |
//==============================================================================
// 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);
}
}
}
| 1,964 | 876 |
/*++
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 );
}
| 7,001 | 2,221 |
/****************************************************************************
*
* 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 );
| 45,458 | 17,323 |