text
stringlengths 5
1.04M
|
|---|
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#include "PakFilePrivatePCH.h"
#include "IPlatformFilePak.h"
#include "SecureHash.h"
#include "FileManagerGeneric.h"
#include "ModuleManager.h"
#include "IPlatformFileModule.h"
#include "IOBase.h"
#include "BigInt.h"
#include "SignedArchiveReader.h"
#include "PublicKey.inl"
DECLARE_CYCLE_STAT( TEXT( "FChunkCacheWorker.ProcessQueue" ), STAT_FChunkCacheWorker_ProcessQueue, STATGROUP_PakFile );
DECLARE_CYCLE_STAT( TEXT( "FChunkCacheWorker.CheckSignature" ), STAT_FChunkCacheWorker_CheckSignature, STATGROUP_PakFile );
DECLARE_CYCLE_STAT( TEXT( "FSignedArchiveReader.Serialize" ), STAT_SignedArchiveReader_Serialize, STATGROUP_PakFile );
FChunkCacheWorker::FChunkCacheWorker(FArchive* InReader)
: Reader(InReader)
, QueuedRequestsEvent(NULL)
{
DecryptionKey.Exponent.Parse(DECRYPTION_KEY_EXPONENT);
DecryptionKey.Modulus.Parse(DECYRPTION_KEY_MODULUS);
// Public key should never be zero at this point. Check PublicKey.inl for more details.
check(!DecryptionKey.Exponent.IsZero() && !DecryptionKey.Modulus.IsZero());
QueuedRequestsEvent = FPlatformProcess::GetSynchEventFromPool();
Thread = FRunnableThread::Create(this, TEXT("FChunkCacheWorker"), 0, TPri_BelowNormal);
}
FChunkCacheWorker::~FChunkCacheWorker()
{
delete Thread;
Thread = NULL;
FPlatformProcess::ReturnSynchEventToPool(QueuedRequestsEvent);
QueuedRequestsEvent = nullptr;
}
bool FChunkCacheWorker::Init()
{
return true;
}
uint32 FChunkCacheWorker::Run()
{
while (StopTaskCounter.GetValue() == 0)
{
int32 ProcessedRequests = ProcessQueue();
if (ProcessedRequests == 0)
{
QueuedRequestsEvent->Wait(500);
}
}
return 0;
}
void FChunkCacheWorker::Stop()
{
StopTaskCounter.Increment();
}
FChunkBuffer* FChunkCacheWorker::GetCachedChunkBuffer(int32 ChunkIndex)
{
for (int32 BufferIndex = 0; BufferIndex < MaxCachedChunks; ++BufferIndex)
{
if (CachedChunks[BufferIndex].ChunkIndex == ChunkIndex)
{
// Update access info and lock
CachedChunks[BufferIndex].LockCount++;
CachedChunks[BufferIndex].LastAccessTime = FPlatformTime::Seconds();
return &CachedChunks[BufferIndex];
}
}
return NULL;
}
FChunkBuffer* FChunkCacheWorker::GetFreeBuffer()
{
// Find the least recently accessed, free buffer.
FChunkBuffer* LeastRecentFreeBuffer = NULL;
for (int32 BufferIndex = 0; BufferIndex < MaxCachedChunks; ++BufferIndex)
{
if (CachedChunks[BufferIndex].LockCount == 0 &&
(LeastRecentFreeBuffer == NULL || LeastRecentFreeBuffer->LastAccessTime > CachedChunks[BufferIndex].LastAccessTime))
{
LeastRecentFreeBuffer = &CachedChunks[BufferIndex];
}
}
if (LeastRecentFreeBuffer)
{
// Update access info and lock
LeastRecentFreeBuffer->LockCount++;
LeastRecentFreeBuffer->LastAccessTime = FPlatformTime::Seconds();
}
return LeastRecentFreeBuffer;
}
void FChunkCacheWorker::ReleaseBuffer(int32 ChunkIndex)
{
for (int32 BufferIndex = 0; BufferIndex < MaxCachedChunks; ++BufferIndex)
{
if (CachedChunks[BufferIndex].ChunkIndex == ChunkIndex)
{
CachedChunks[BufferIndex].LockCount--;
check(CachedChunks[BufferIndex].LockCount >= 0);
}
}
}
int32 FChunkCacheWorker::ProcessQueue()
{
SCOPE_CYCLE_COUNTER( STAT_FChunkCacheWorker_ProcessQueue );
// Add the queue to the active requests list
{
FScopeLock LockQueue(&QueueLock);
ActiveRequests.Append(RequestQueue);
RequestQueue.Empty();
}
// Keep track how many request have been process this loop
int32 ProcessedRequests = ActiveRequests.Num();
for (int32 RequestIndex = 0; RequestIndex < ActiveRequests.Num(); ++RequestIndex)
{
FChunkRequest& Request = *ActiveRequests[RequestIndex];
if (Request.RefCount.GetValue() == 0)
{
// ChunkRequest is no longer used by anything. Add it to the free requests lists
// and release the associated buffer.
ReleaseBuffer(Request.Index);
ActiveRequests.RemoveAt(RequestIndex--);
FreeChunkRequests.Push(&Request);
}
else if (Request.Buffer == NULL)
{
// See if the requested chunk is already cached.
FChunkBuffer* CachedBuffer = GetCachedChunkBuffer(Request.Index);
if (!CachedBuffer)
{
// This chunk is not cached. Get a free buffer if possible.
CachedBuffer = GetFreeBuffer();
if (!!CachedBuffer)
{
// Load and verify.
CachedBuffer->ChunkIndex = Request.Index;
Request.Buffer = CachedBuffer;
CheckSignature(Request);
}
}
else
{
Request.Buffer = CachedBuffer;
}
if (!!CachedBuffer)
{
check(Request.Buffer == CachedBuffer);
// Chunk is cached and trusted. We no longer need the request handle on this thread.
// Let the other thread know the chunk is ready to read.
Request.RefCount.Decrement();
Request.IsTrusted.Increment();
}
}
}
return ProcessedRequests;
}
void FChunkCacheWorker::Decrypt(uint8* DecryptedData, const int256* Data, const int64 DataLength)
{
for (int64 Index = 0; Index < DataLength; ++Index)
{
int256 DecryptedByte = FEncryption::ModularPow(Data[Index], DecryptionKey.Exponent, DecryptionKey.Modulus);
DecryptedData[Index] = (uint8)DecryptedByte.ToInt();
}
}
bool FChunkCacheWorker::CheckSignature(const FChunkRequest& ChunkInfo)
{
SCOPE_CYCLE_COUNTER( STAT_FChunkCacheWorker_CheckSignature );
FSignature Signature;
Reader->Seek(ChunkInfo.Offset);
Reader->Serialize(ChunkInfo.Buffer->Data, ChunkInfo.Size);
Signature.Serialize(*Reader);
// Hash data
uint8 Hash[20];
FSHA1::HashBuffer(ChunkInfo.Buffer->Data, ChunkInfo.Size, Hash);
// Decrypt serialized hash
uint8 DecryptedHash[20];
Decrypt(DecryptedHash, Signature.Data, ARRAY_COUNT(DecryptedHash));
// Compare hashes
if (FMemory::Memcmp(Hash, DecryptedHash, sizeof(DecryptedHash)) != 0)
{
UE_LOG(LogPakFile, Fatal, TEXT("Pak file has been tampered with."));
}
return true;
}
FChunkRequest& FChunkCacheWorker::RequestChunk(int32 ChunkIndex, int64 StartOffset, int64 ChunkSize)
{
FChunkRequest* NewChunk = FreeChunkRequests.Pop();
if (NewChunk == NULL)
{
NewChunk = new FChunkRequest();
}
NewChunk->Index = ChunkIndex;
NewChunk->Offset = StartOffset;
NewChunk->Size = ChunkSize;
NewChunk->Buffer = NULL;
NewChunk->IsTrusted.Set(0);
// At this point both worker and the archive use this chunk so increase ref count
NewChunk->RefCount.Set(2);
QueueLock.Lock();
RequestQueue.Add(NewChunk);
QueueLock.Unlock();
QueuedRequestsEvent->Trigger();
return *NewChunk;
}
void FChunkCacheWorker::ReleaseChunk(FChunkRequest& Chunk)
{
Chunk.RefCount.Decrement();
}
FSignedArchiveReader::FSignedArchiveReader(FArchive* InPakReader, FChunkCacheWorker* InSignatureChecker)
: SignatureSize(FSignature::Size())
, ChunkCount(0)
, PakReader(InPakReader)
, SizeOnDisk(0)
, PakSize(0)
, PakOffset(0)
, SignatureChecker(InSignatureChecker)
{
// Cache global info about the archive
const int64 MaxChunkSize = FPakInfo::MaxChunkDataSize + SignatureSize;
SizeOnDisk = PakReader->TotalSize();
ChunkCount = SizeOnDisk / MaxChunkSize + ((SizeOnDisk % MaxChunkSize) ? 1 : 0);
PakSize = SizeOnDisk - ChunkCount * SignatureSize;
}
FSignedArchiveReader::~FSignedArchiveReader()
{
delete PakReader;
PakReader = NULL;
}
int64 FSignedArchiveReader::CalculateChunkSize(int64 ChunkIndex) const
{
if (ChunkIndex == (ChunkCount - 1))
{
const int64 MaxChunkSize = FPakInfo::MaxChunkDataSize + SignatureSize;
int64 Slack = SizeOnDisk % MaxChunkSize;
if (!Slack)
{
return FPakInfo::MaxChunkDataSize;
}
else
{
Slack -= SignatureSize;
check(Slack > 0);
return Slack;
}
}
else
{
return FPakInfo::MaxChunkDataSize;
}
}
void FSignedArchiveReader::PrecacheChunks(TArray<FSignedArchiveReader::FReadInfo>& Chunks, int64 Length)
{
// Request all the chunks that are needed to complete this read
int64 DataOffset;
int64 DestOffset = 0;
int32 FirstChunkIndex = CalculateChunkIndex(PakOffset);
int64 ChunkStartOffset = CalculateChunkOffset(PakOffset, DataOffset);
int32 NumChunks = (DataOffset - ChunkStartOffset + Length) / FPakInfo::MaxChunkDataSize + 1;
int64 RemainingLength = Length;
int64 ArchiveOffset = PakOffset;
// And then try to precache 'PrecacheLength' more chunks because it's likely
// we're going to try to read them next
if ((NumChunks + FirstChunkIndex + PrecacheLength - 1) < ChunkCount)
{
NumChunks += PrecacheLength;
}
Chunks.Empty(NumChunks);
for (int32 ChunkIndexOffset = 0; ChunkIndexOffset < NumChunks; ++ChunkIndexOffset)
{
ChunkStartOffset = CalculateChunkOffset(ArchiveOffset, DataOffset);
int64 SizeToReadFromBuffer = RemainingLength;
if (DataOffset + SizeToReadFromBuffer > ChunkStartOffset + FPakInfo::MaxChunkDataSize)
{
SizeToReadFromBuffer = ChunkStartOffset + FPakInfo::MaxChunkDataSize - DataOffset;
}
FReadInfo ChunkInfo;
ChunkInfo.SourceOffset = DataOffset - ChunkStartOffset;
ChunkInfo.DestOffset = DestOffset;
ChunkInfo.Size = SizeToReadFromBuffer;
const int32 ChunkIndex = ChunkIndexOffset + FirstChunkIndex;
if (LastCachedChunk.ChunkIndex == ChunkIndex)
{
ChunkInfo.Request = NULL;
ChunkInfo.PreCachedChunk = &LastCachedChunk;
}
else
{
const int64 ChunkSize = CalculateChunkSize(ChunkIndex);
ChunkInfo.Request = &SignatureChecker->RequestChunk(ChunkIndex, ChunkStartOffset, ChunkSize);
ChunkInfo.PreCachedChunk = NULL;
}
Chunks.Add(ChunkInfo);
ArchiveOffset += SizeToReadFromBuffer;
DestOffset += SizeToReadFromBuffer;
RemainingLength -= SizeToReadFromBuffer;
}
}
void FSignedArchiveReader::Serialize(void* Data, int64 Length)
{
SCOPE_CYCLE_COUNTER( STAT_SignedArchiveReader_Serialize );
// First make sure the chunks we're going to read are actually cached.
TArray<FReadInfo> QueuedChunks;
PrecacheChunks(QueuedChunks, Length);
// Read data from chunks.
int64 RemainingLength = Length;
uint8* DestData = (uint8*)Data;
int32 ChunksToRead = QueuedChunks.Num() - PrecacheLength;
const int32 LastRequestIndex = ChunksToRead - 1;
do
{
int32 ChunksReadThisLoop = 0;
// Try to read cached chunks. If a chunk is not yet ready, skip to the next chunk - it's possible
// that it has already been precached in one of the previous reads.
for (int32 QueueIndex = 0; QueueIndex <= LastRequestIndex; ++QueueIndex)
{
FReadInfo& ChunkInfo = QueuedChunks[QueueIndex];
if (ChunkInfo.Request && ChunkInfo.Request->IsReady())
{
// Read
FMemory::Memcpy(DestData + ChunkInfo.DestOffset, ChunkInfo.Request->Buffer->Data + ChunkInfo.SourceOffset, ChunkInfo.Size);
// Is this the last chunk? if so, copy it to pre-cache
if (LastRequestIndex == QueueIndex && ChunkInfo.Request->Index != LastCachedChunk.ChunkIndex)
{
LastCachedChunk.ChunkIndex = ChunkInfo.Request->Index;
FMemory::Memcpy(LastCachedChunk.Data, ChunkInfo.Request->Buffer->Data, FPakInfo::MaxChunkDataSize);
}
// Let the worker know we're done with this chunk for now.
SignatureChecker->ReleaseChunk(*ChunkInfo.Request);
ChunkInfo.Request = NULL;
// One less chunk remaining
ChunksToRead--;
ChunksReadThisLoop++;
}
else if (ChunkInfo.PreCachedChunk)
{
// Copy directly from the pre-cached chunk.
FMemory::Memcpy(DestData + ChunkInfo.DestOffset, ChunkInfo.PreCachedChunk->Data + ChunkInfo.SourceOffset, ChunkInfo.Size);
ChunkInfo.PreCachedChunk = NULL;
// One less chunk remaining
ChunksToRead--;
ChunksReadThisLoop++;
}
}
if (ChunksReadThisLoop == 0)
{
// No chunks read, avoid tight spinning loops and give up some time to the other threads
FPlatformProcess::Sleep(0.0f);
}
}
while (ChunksToRead > 0);
PakOffset += Length;
// Free precached chunks (they will still get precached but simply marked as not used by anything)
for (int32 QueueIndex = QueuedChunks.Num() - PrecacheLength; QueueIndex < QueuedChunks.Num(); ++QueueIndex)
{
FReadInfo& CachedChunk = QueuedChunks[QueueIndex];
SignatureChecker->ReleaseChunk(*CachedChunk.Request);
}
}
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: Zenject.FromBinder
#include "Zenject/FromBinder.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: Zenject
namespace Zenject {
// Forward declaring type: IProvider
class IProvider;
// Forward declaring type: DiContainer
class DiContainer;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Type
class Type;
}
// Completed forward declares
// Type namespace: Zenject
namespace Zenject {
// Forward declaring type: <>c__DisplayClass72_0
class $$c__DisplayClass72_0;
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(Zenject::FromBinder::$$c__DisplayClass72_0);
DEFINE_IL2CPP_ARG_TYPE(Zenject::FromBinder::$$c__DisplayClass72_0*, "Zenject", "FromBinder/<>c__DisplayClass72_0");
// Type namespace: Zenject
namespace Zenject {
// Size: 0x18
#pragma pack(push, 1)
// Autogenerated type: Zenject.FromBinder/Zenject.<>c__DisplayClass72_0
// [TokenAttribute] Offset: FFFFFFFF
// [CompilerGeneratedAttribute] Offset: FFFFFFFF
class FromBinder::$$c__DisplayClass72_0 : public ::Il2CppObject {
public:
#ifdef USE_CODEGEN_FIELDS
public:
#else
protected:
#endif
// public System.Object instance
// Size: 0x8
// Offset: 0x10
::Il2CppObject* instance;
// Field size check
static_assert(sizeof(::Il2CppObject*) == 0x8);
public:
// Creating conversion operator: operator ::Il2CppObject*
constexpr operator ::Il2CppObject*() const noexcept {
return instance;
}
// Get instance field reference: public System.Object instance
::Il2CppObject*& dyn_instance();
// Zenject.IProvider <FromInstanceBase>b__0(Zenject.DiContainer container, System.Type type)
// Offset: 0x1815A1C
Zenject::IProvider* $FromInstanceBase$b__0(Zenject::DiContainer* container, System::Type* type);
// public System.Void .ctor()
// Offset: 0x1813138
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static FromBinder::$$c__DisplayClass72_0* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("Zenject::FromBinder::$$c__DisplayClass72_0::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<FromBinder::$$c__DisplayClass72_0*, creationType>()));
}
}; // Zenject.FromBinder/Zenject.<>c__DisplayClass72_0
#pragma pack(pop)
static check_size<sizeof(FromBinder::$$c__DisplayClass72_0), 16 + sizeof(::Il2CppObject*)> __Zenject_FromBinder_$$c__DisplayClass72_0SizeCheck;
static_assert(sizeof(FromBinder::$$c__DisplayClass72_0) == 0x18);
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: Zenject::FromBinder::$$c__DisplayClass72_0::$FromInstanceBase$b__0
// Il2CppName: <FromInstanceBase>b__0
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<Zenject::IProvider* (Zenject::FromBinder::$$c__DisplayClass72_0::*)(Zenject::DiContainer*, System::Type*)>(&Zenject::FromBinder::$$c__DisplayClass72_0::$FromInstanceBase$b__0)> {
static const MethodInfo* get() {
static auto* container = &::il2cpp_utils::GetClassFromName("Zenject", "DiContainer")->byval_arg;
static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(Zenject::FromBinder::$$c__DisplayClass72_0*), "<FromInstanceBase>b__0", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{container, type});
}
};
// Writing MetadataGetter for method: Zenject::FromBinder::$$c__DisplayClass72_0::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1 == NULL) return l2;
if(l2 == NULL) return l1;
if(l2->val < l1->val) swap(l1, l2);
ListNode* curl1 = l1;
ListNode* lastl1 = l1;
while(l2 != NULL) { // merge l2 into l1
if(curl1 == NULL) {
lastl1->next = l2;
break;
} else {
if(curl1->val <= l2->val) {
lastl1 = curl1;
curl1 = curl1->next;
} else {
lastl1->next = l2;
lastl1 = l2;
ListNode* tmp = l2->next;
l2->next = curl1;
l2 = tmp;
}
}
}
return l1;
}
};
|
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++03, c++11, c++14, c++17
// template <class T>
// constexpr T bit_ceil(T x) noexcept;
// Remarks: This function shall not participate in overload resolution unless
// T is an unsigned integer type
#include <bit>
#include <cstdint>
#include <limits>
#include <cassert>
#include "test_macros.h"
class A{};
enum E1 : unsigned char { rEd };
enum class E2 : unsigned char { red };
template <typename T>
constexpr bool toobig()
{
return 0 == std::bit_ceil(std::numeric_limits<T>::max());
}
int main(int, char**)
{
// Make sure we generate a compile-time error for UB
static_assert(toobig<unsigned char>(), ""); // expected-error {{static_assert expression is not an integral constant expression}}
static_assert(toobig<unsigned short>(), ""); // expected-error {{static_assert expression is not an integral constant expression}}
static_assert(toobig<unsigned>(), ""); // expected-error {{static_assert expression is not an integral constant expression}}
static_assert(toobig<unsigned long>(), ""); // expected-error {{static_assert expression is not an integral constant expression}}
static_assert(toobig<unsigned long long>(), ""); // expected-error {{static_assert expression is not an integral constant expression}}
static_assert(toobig<uint8_t>(), ""); // expected-error {{static_assert expression is not an integral constant expression}}
static_assert(toobig<uint16_t>(), ""); // expected-error {{static_assert expression is not an integral constant expression}}
static_assert(toobig<uint32_t>(), ""); // expected-error {{static_assert expression is not an integral constant expression}}
static_assert(toobig<uint64_t>(), ""); // expected-error {{static_assert expression is not an integral constant expression}}
static_assert(toobig<size_t>(), ""); // expected-error {{static_assert expression is not an integral constant expression}}
static_assert(toobig<uintmax_t>(), ""); // expected-error {{static_assert expression is not an integral constant expression}}
static_assert(toobig<uintptr_t>(), ""); // expected-error {{static_assert expression is not an integral constant expression}}
return 0;
}
|
// Note the second line of this file must ALWAYS be the git SHA, third line ALWAYS the git SHA update time
#define QUICKCPPLIB_PREVIOUS_COMMIT_REF 01e18d3e6549400646f41b79de318994eac95f25
#define QUICKCPPLIB_PREVIOUS_COMMIT_DATE "2019-02-11 10:00:33 +00:00"
#define QUICKCPPLIB_PREVIOUS_COMMIT_UNIQUE 01e18d3e
|
/**
* \class L1GtTriggerMask
*
*
* Description: L1 GT mask.
*
* Implementation:
* <TODO: enter implementation details>
*
* \author: Vasile Mihai Ghete - HEPHY Vienna
*
* $Date$
* $Revision$
*
*/
// this class header
#include "CondFormats/L1TObjects/interface/L1GtTriggerMask.h"
// system include files
#include <iostream>
#include <iomanip>
// user include files
// base class
// constructors
L1GtTriggerMask::L1GtTriggerMask()
{
//empty - all value set by default to zero
}
L1GtTriggerMask::L1GtTriggerMask(std::vector<unsigned int>& maskValue)
{
m_triggerMask = maskValue;
}
// destructor
L1GtTriggerMask::~L1GtTriggerMask()
{
// empty
}
// set the trigger mask
void L1GtTriggerMask::setGtTriggerMask(std::vector<unsigned int>& maskValue)
{
m_triggerMask = maskValue;
}
// print the mask
void L1GtTriggerMask::print(std::ostream& outputStream) const {
outputStream << "\nL1 GT Trigger masks are printed for all L1 partitions. "
<< "\n Partition numbering: partition \"i\" -> bit i"
<< " (bit 0 is LSB)\n"
<< "\n If mask value is 1 for a given algorithm/technical trigger in a given partition "
<< "\n then the algorithm/technical trigger is masked (has value 0 = false) in the evaluation "
<< "\n of FinalOR.\n"
<< "\n For veto masks, if the mask is set to 1 and the result of the trigger for that bit is true, "
<< "\n then the FinalOR is set to false (no L1A).\n"
<< std::endl;
for (unsigned i = 0; i < m_triggerMask.size(); i++) {
outputStream << " Algorithm/technical trigger bit number "
<< std::setw(3) << i << ":\t mask: 0x" << std::hex
<< std::setw(2) << m_triggerMask[i] << std::dec << std::endl;
}
}
|
#include "Commit.h"
std::string EmailLine(std::string str)
{
int ipos;
while ((ipos = str.find("\n")) != std::string::npos)
{
str = str.replace(ipos, 1, "");
}
std::string strRetVal("-M \"");
strRetVal.append(str);
strRetVal.append("\" ");
return strRetVal;
}
void Commit::PopulateFromJson(Json::Value jsonval)
{
_strAuthor = jsonval["author"].asString();
_strMsg = jsonval["message"].asString();
for (unsigned int i = 0; i < jsonval["files"].size(); i++)
_vectstrFiles.push_back(jsonval["files"][i]["file"].asString());
}
std::string Commit::GetString()
{
std::string strRetVal = "";
strRetVal.append(EmailLine("Developer:"));
strRetVal.append(EmailLine(_strAuthor));
strRetVal.append(EmailLine(" "));
strRetVal.append(EmailLine("Commit Message:"));
strRetVal.append(EmailLine(_strMsg));
strRetVal.append(EmailLine(" "));
strRetVal.append(EmailLine("Files Changed:"));
for (unsigned int i = 0; i < _vectstrFiles.size(); i++)
{
strRetVal.append(EmailLine(_vectstrFiles[i]));
}
strRetVal.append(EmailLine(" "));
return strRetVal;
}
|
#ifndef QRPROCESSES_HPP
#define QRPROCESSES_HPP
#include "QrDefinitions.hpp"
#include "QrDefinitions_Internal.hpp"
#include <string>
#include "QrMatrixFunction.hpp"
#include "QrAlignmentPatternLocations.hpp"
#include "QrMatrixData.hpp"
#include "QrMask.hpp"
#include "QrInformationStrings.hpp"
#include "QrErrorCorrection.hpp"
#include <memory>
namespace GtkQR
{
class QrProcesses
{
public:
QrProcesses(QRDataContainer *);
~QrProcesses();
void QR_GetData(std::string &);
char ** calculateMatrix(std::string & );
void encodeproces(std::shared_ptr<Dictionaries> );
protected:
private:
void padding (QrErrorCorrection *);
void errorproces();
QRDataContainer *data;
std::string result;
bool error;
};
}
#endif // QRPROCESSES_HPP
|
#ifndef PEDIDO_H
#define PEDIDO_H
#pragma once
#define MAX_PRATOS 10
#include <string>
namespace pkt_comanda {
class Pedido
{
private:
int quantidade, prato;
std::string cardapio[MAX_PRATOS] {"Executivo", "Churrasco", "Sopa suspeita", "Cafe", "Suco",
"Feijoada", "Salada", "Pipoca na manteiga", "Pizza", "Sushi"};
double preco[MAX_PRATOS] {12.50, 24.99, 99.99, 5.0, 4.0, 21.75, 8.50, 2.0, 31.47, 2.50};
public:
Pedido();
~Pedido();
void setQuantidade(int q);
void setPrato(int p);
int getQuantidade();
int getPrato();
std::string getStrPrato();
};
};
#endif
|
/** Benchmark different event implementations. */
#include <iostream>
#include <cuda.h>
#include "Al.hpp"
#include "benchmark_utils.hpp"
#include "wait.hpp"
class Event {
public:
virtual void record(cudaStream_t stream) = 0;
virtual bool query() = 0;
};
class CudaEvent : public Event {
public:
CudaEvent() {
cudaEventCreateWithFlags(&event, cudaEventDisableTiming);
}
~CudaEvent() {
cudaEventDestroy(event);
}
void record(cudaStream_t stream) override {
cudaEventRecord(event, stream);
}
bool query() override {
return cudaEventQuery(event) == cudaSuccess;
}
private:
cudaEvent_t event;
};
class CustomEvent : public Event {
public:
CustomEvent() {
cudaMallocHost(&event, sizeof(int32_t));
__atomic_store_n(event, 1, __ATOMIC_SEQ_CST);
cuMemHostGetDevicePointer(
&dev_ptr, event, 0);
}
~CustomEvent() {
cudaFreeHost(event);
}
void record(cudaStream_t stream) override {
__atomic_store_n(event, 0, __ATOMIC_SEQ_CST);
cuStreamWriteValue32(
stream, dev_ptr, 1, CU_STREAM_WRITE_VALUE_DEFAULT);
}
bool query() override {
return __atomic_load_n(event, __ATOMIC_SEQ_CST);
}
private:
int32_t* event __attribute__((aligned(64)));
CUdeviceptr dev_ptr;
};
void do_benchmark(cudaStream_t stream, Event& event) {
const double wait_time = 0.0001;
std::vector<double> times, launch_times;
for (int i = 0; i < 100000; ++i) {
double launch_start = Al::get_time();
gpu_wait(wait_time, stream);
event.record(stream);
double start = Al::get_time();
while (!event.query()) {}
double end = Al::get_time();
launch_times.push_back(start - launch_start);
times.push_back(end - start);
cudaStreamSynchronize(stream);
}
std::cout << "Launch: " << SummaryStats(launch_times) << std::endl;
std::cout << "Query: " << SummaryStats(times) << std::endl;
}
int main(int, char**) {
cudaSetDevice(0);
cudaStream_t stream;
cudaStreamCreate(&stream);
{
CudaEvent cuda_event;
CustomEvent custom_event;
std::cout << "Custom event:" << std::endl;
do_benchmark(stream, custom_event);
std::cout << "CUDA Event:" << std::endl;
do_benchmark(stream, cuda_event);
}
cudaStreamSynchronize(stream);
cudaStreamDestroy(stream);
return 0;
}
|
/*
* Copyright (c) 2016, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* This file includes definitions for UDP/IPv6 sockets.
*/
#ifndef UDP6_HPP_
#define UDP6_HPP_
#include "openthread-core-config.h"
#include <openthread/udp.h>
#include "common/locator.hpp"
#include "net/ip6_headers.hpp"
namespace ot {
namespace Ip6 {
class Udp;
/**
* @addtogroup core-udp
*
* @brief
* This module includes definitions for UDP/IPv6 sockets.
*
* @{
*
*/
/**
* This class implements a UDP receiver.
*
*/
class UdpReceiver : public otUdpReceiver
{
friend class Udp;
public:
/**
* This constructor initializes the object.
*
* @param[in] aUdpHandler A pointer to the function to handle UDP message.
* @param[in] aContext A pointer to arbitrary context information.
*
*/
UdpReceiver(otUdpHandler aHandler, void *aContext)
{
mNext = NULL;
mHandler = aHandler;
mContext = aContext;
}
private:
UdpReceiver *GetNext(void) { return static_cast<UdpReceiver *>(mNext); }
void SetNext(UdpReceiver *aReceiver) { mNext = static_cast<otUdpReceiver *>(aReceiver); }
bool HandleMessage(Message &aMessage, const MessageInfo &aMessageInfo)
{
return mHandler(mContext, &aMessage, &aMessageInfo);
}
};
/**
* This class implements a UDP/IPv6 socket.
*
*/
class UdpSocket : public otUdpSocket, public InstanceLocator
{
friend class Udp;
public:
/**
* This constructor initializes the object.
*
* @param[in] aUdp A reference to the UDP transport object.
*
*/
explicit UdpSocket(Udp &aUdp);
/**
* This method returns a new UDP message with sufficient header space reserved.
*
* @note If @p aSettings is 'NULL', the link layer security is enabled and the message priority is set to
* OT_MESSAGE_PRIORITY_NORMAL by default.
*
* @param[in] aReserved The number of header bytes to reserve after the UDP header.
* @param[in] aSettings A pointer to the message settings or NULL to set default settings.
*
* @returns A pointer to the message or NULL if no buffers are available.
*
*/
Message *NewMessage(uint16_t aReserved, const otMessageSettings *aSettings = NULL);
/**
* This method opens the UDP socket.
*
* @param[in] aHandler A pointer to a function that is called when receiving UDP messages.
* @param[in] aContext A pointer to arbitrary context information.
*
* @retval OT_ERROR_NONE Successfully opened the socket.
* @retval OT_ERROR_ALREADY The socket is already open.
*
*/
otError Open(otUdpReceive aHandler, void *aContext);
/**
* This method binds the UDP socket.
*
* @param[in] aSockAddr A reference to the socket address.
*
* @retval OT_ERROR_NONE Successfully bound the socket.
* @retval OT_ERROR_FAILED Failed to bind UDP Socket.
*
*/
otError Bind(const SockAddr &aSockAddr);
/**
* This method indicates whether or not the socket is bound.
*
* @retval TRUE if the socket is bound (i.e. source port is non-zero).
* @retval FALSE if the socket is not bound (source port is zero).
*
*/
bool IsBound(void) const { return mSockName.mPort != 0; }
/**
* This method connects the UDP socket.
*
* @param[in] aSockAddr A reference to the socket address.
*
* @retval OT_ERROR_NONE Successfully connected the socket.
* @retval OT_ERROR_FAILED Failed to connect UDP Socket.
*
*/
otError Connect(const SockAddr &aSockAddr);
/**
* This method closes the UDP socket.
*
* @retval OT_ERROR_NONE Successfully closed the UDP socket.
* @retval OT_ERROR_FAILED Failed to close UDP Socket.
*
*/
otError Close(void);
/**
* This method sends a UDP message.
*
* @param[in] aMessage The message to send.
* @param[in] aMessageInfo The message info associated with @p aMessage.
*
* @retval OT_ERROR_NONE Successfully sent the UDP message.
* @retval OT_ERROR_INVALID_ARGS If no peer is specified in @p aMessageInfo or by connect().
* @retval OT_ERROR_NO_BUFS Insufficient available buffer to add the UDP and IPv6 headers.
*
*/
otError SendTo(Message &aMessage, const MessageInfo &aMessageInfo);
/**
* This method returns the local socket address.
*
* @returns A reference to the local socket address.
*
*/
SockAddr &GetSockName(void) { return *static_cast<SockAddr *>(&mSockName); }
/**
* This method returns the peer's socket address.
*
* @returns A reference to the peer's socket address.
*
*/
SockAddr &GetPeerName(void) { return *static_cast<SockAddr *>(&mPeerName); }
private:
UdpSocket *GetNext(void) { return static_cast<UdpSocket *>(mNext); }
void SetNext(UdpSocket *socket) { mNext = static_cast<otUdpSocket *>(socket); }
void HandleUdpReceive(Message &aMessage, const MessageInfo &aMessageInfo)
{
mHandler(mContext, &aMessage, &aMessageInfo);
}
};
/**
* This class implements core UDP message handling.
*
*/
class Udp : public InstanceLocator
{
friend class UdpSocket;
public:
/**
* This constructor initializes the object.
*
* @param[in] aIp6 A reference to OpenThread instance.
*
*/
explicit Udp(Instance &aInstance);
/**
* This method adds a UDP receiver.
*
* @param[in] aReceiver A reference to the UDP receiver.
*
* @retval OT_ERROR_NONE Successfully added the UDP receiver.
* @retval OT_ERROR_ALREADY The UDP receiver was already added.
*
*/
otError AddReceiver(UdpReceiver &aReceiver);
/**
* This method removes a UDP receiver.
*
* @param[in] aReceiver A reference to the UDP receiver.
*
* @retval OT_ERROR_NONE Successfully removed the UDP receiver.
* @retval OT_ERROR_NOT_FOUND The UDP receiver was not added.
*
*/
otError RemoveReceiver(UdpReceiver &aReceiver);
/**
* This method adds a UDP socket.
*
* @param[in] aSocket A reference to the UDP socket.
*
*/
void AddSocket(UdpSocket &aSocket);
/**
* This method removes a UDP socket.
*
* @param[in] aSocket A reference to the UDP socket.
*
*/
void RemoveSocket(UdpSocket &aSocket);
/**
* This method returns a new ephemeral port.
*
* @returns A new ephemeral port.
*
*/
uint16_t GetEphemeralPort(void);
/**
* This method returns a new UDP message with sufficient header space reserved.
*
* @param[in] aReserved The number of header bytes to reserve after the UDP header.
* @param[in] aPriority The priority of the message.
*
* @returns A pointer to the message or NULL if no buffers are available.
*
*/
Message *NewMessage(uint16_t aReserved, const otMessageSettings *aSettings = NULL);
/**
* This method sends an IPv6 datagram.
*
* @param[in] aMessage A reference to the message.
* @param[in] aMessageInfo A reference to the message info associated with @p aMessage.
* @param[in] aIpProto The Internet Protocol value.
*
* @retval OT_ERROR_NONE Successfully enqueued the message into an output interface.
* @retval OT_ERROR_NO_BUFS Insufficient available buffer to add the IPv6 headers.
*
*/
otError SendDatagram(Message &aMessage, MessageInfo &aMessageInfo, IpProto aIpProto);
/**
* This method handles a received UDP message.
*
* @param[in] aMessage A reference to the UDP message to process.
* @param[in] aMessageInfo A reference to the message info associated with @p aMessage.
*
* @retval OT_ERROR_NONE Successfully processed the UDP message.
* @retval OT_ERROR_DROP Could not fully process the UDP message.
*
*/
otError HandleMessage(Message &aMessage, MessageInfo &aMessageInfo);
/**
* This method handles a received UDP message with offset set to the payload.
*
* @param[in] aMessage A reference to the UDP message to process.
* @param[in] aMessageInfo A reference to the message info associated with @p aMessage.
*
*/
void HandlePayload(Message &aMessage, MessageInfo &aMessageInfo);
/**
* This method updates the UDP checksum.
*
* @param[in] aMessage A reference to the UDP message.
* @param[in] aChecksum The pseudo-header checksum value.
*
*/
void UpdateChecksum(Message &aMessage, uint16_t aChecksum);
#if OPENTHREAD_ENABLE_PLATFORM_UDP
otUdpSocket *GetUdpSockets(void) { return mSockets; }
#endif
#if OPENTHREAD_ENABLE_UDP_FORWARD
/**
* This method sets the forward sender.
*
* @param[in] aForwarder A function pointer to forward UDP packets.
* @param[in] aContext A pointer to arbitrary context information.
*
*/
void SetUdpForwarder(otUdpForwarder aForwarder, void *aContext)
{
mUdpForwarder = aForwarder;
mUdpForwarderContext = aContext;
}
#endif // OPENTHREAD_ENABLE_UDP_FORWARD
private:
enum
{
kDynamicPortMin = 49152, ///< Service Name and Transport Protocol Port Number Registry
kDynamicPortMax = 65535, ///< Service Name and Transport Protocol Port Number Registry
};
uint16_t mEphemeralPort;
UdpReceiver *mReceivers;
UdpSocket * mSockets;
#if OPENTHREAD_ENABLE_UDP_FORWARD
void * mUdpForwarderContext;
otUdpForwarder mUdpForwarder;
#endif
};
OT_TOOL_PACKED_BEGIN
struct UdpHeaderPoD
{
uint16_t mSource;
uint16_t mDestination;
uint16_t mLength;
uint16_t mChecksum;
} OT_TOOL_PACKED_END;
/**
* This class implements UDP header generation and parsing.
*
*/
OT_TOOL_PACKED_BEGIN
class UdpHeader : private UdpHeaderPoD
{
public:
/**
* This method returns the UDP Source Port.
*
* @returns The UDP Source Port.
*
*/
uint16_t GetSourcePort(void) const { return HostSwap16(mSource); }
/**
* This method sets the UDP Source Port.
*
* @param[in] aPort The UDP Source Port.
*
*/
void SetSourcePort(uint16_t aPort) { mSource = HostSwap16(aPort); }
/**
* This method returns the UDP Destination Port.
*
* @returns The UDP Destination Port.
*
*/
uint16_t GetDestinationPort(void) const { return HostSwap16(mDestination); }
/**
* This method sets the UDP Destination Port.
*
* @param[in] aPort The UDP Destination Port.
*
*/
void SetDestinationPort(uint16_t aPort) { mDestination = HostSwap16(aPort); }
/**
* This method returns the UDP Length.
*
* @returns The UDP Length.
*
*/
uint16_t GetLength(void) const { return HostSwap16(mLength); }
/**
* This method sets the UDP Length.
*
* @param[in] aLength The UDP Length.
*
*/
void SetLength(uint16_t aLength) { mLength = HostSwap16(aLength); }
/**
* This method returns the UDP Checksum.
*
* @returns The UDP Checksum.
*
*/
uint16_t GetChecksum(void) const { return HostSwap16(mChecksum); }
/**
* This method sets the UDP Checksum.
*
* @param[in] aChecksum The UDP Checksum.
*
*/
void SetChecksum(uint16_t aChecksum) { mChecksum = HostSwap16(aChecksum); }
/**
* This static method returns the byte offset for the UDP Length.
*
* @returns The byte offset for the UDP Length.
*
*/
static uint8_t GetLengthOffset(void) { return offsetof(UdpHeaderPoD, mLength); }
/**
* This static method returns the byte offset for the UDP Checksum.
*
* @returns The byte offset for the UDP Checksum.
*
*/
static uint8_t GetChecksumOffset(void) { return offsetof(UdpHeaderPoD, mChecksum); }
} OT_TOOL_PACKED_END;
/**
* @}
*
*/
} // namespace Ip6
} // namespace ot
#endif // UDP6_HPP_
|
#pragma once
#include "Base.hpp"
enum class CollisionKind { Asteroid, Projectile, Player };
struct CollisionEvent: public Event {
CollisionEvent(Entity* asteroid, Entity* collider, const CollisionKind kind):
asteroid{asteroid}, collider{collider}, kind{kind} {}
Entity* asteroid;
Entity* collider;
CollisionKind kind;
};
|
#include <memory>
#define CATCH_CONFIG_DEFAULT_REPORTER "multiprocess"
#define CATCH_CONFIG_MAIN
#include "Catch/single_include/catch2/catch.hpp"
#include "uitsl/debug/MultiprocessReporter.hpp"
#include "uitsl/mpi/MpiGuard.hpp"
#include "uit/ducts/proc/impl/inlet/accumulating+type=span/s::IsendDuct.hpp"
#include "uit/setup/ImplSpec.hpp"
#include "uit/setup/InterProcAddress.hpp"
const uitsl::MpiGuard guard;
TEST_CASE("Test s::IsendDuct") {
using ImplSpec = uit::MockSpec<emp::vector<char>>;
using BackEnd = uit::s::IsendDuct<ImplSpec>::BackEndImpl;
// TODO flesh out stub test
uit::InterProcAddress address;
std::shared_ptr<BackEnd> backing{ std::make_shared<BackEnd>( 42 ) };
uit::s::IsendDuct<ImplSpec>{ address, backing };
}
|
/******************************************************************************\
* Author: Matthew Beauregard Smith *
* Affiliation: The University of Texas at Austin *
* Department: Oden Institute and Institute for Cellular and Molecular Biology *
* PI: Edward Marcotte *
* Project: Protein Fluorosequencing *
\******************************************************************************/
// Boost unit test framework (recommended to be the first include):
#include <boost/test/unit_test.hpp>
// File under test:
#include "radiometry.h"
namespace whatprot {
BOOST_AUTO_TEST_SUITE(common_suite)
BOOST_AUTO_TEST_SUITE(radiometry_suite)
BOOST_AUTO_TEST_CASE(constructor_test) {
int num_timesteps = 3;
int num_channels = 2;
Radiometry r(num_timesteps, num_channels);
BOOST_TEST(r.num_timesteps = num_timesteps);
BOOST_TEST(r.num_channels = num_channels);
BOOST_TEST(r.intensities != (void*)NULL);
}
BOOST_AUTO_TEST_CASE(copy_constructor_test) {
int num_timesteps = 3;
int num_channels = 2;
Radiometry r1(num_timesteps, num_channels);
r1.intensities[0] = 60;
r1.intensities[1] = 61;
r1.intensities[2] = 62;
r1.intensities[3] = 63;
r1.intensities[4] = 64;
r1.intensities[5] = 65;
Radiometry r2(r1);
BOOST_TEST(r1.num_timesteps = num_timesteps);
BOOST_TEST(r1.num_channels = num_channels);
BOOST_TEST(r1.intensities != (void*)NULL);
BOOST_TEST(r1.intensities[0] == 60);
BOOST_TEST(r1.intensities[1] == 61);
BOOST_TEST(r1.intensities[2] == 62);
BOOST_TEST(r1.intensities[3] == 63);
BOOST_TEST(r1.intensities[4] == 64);
BOOST_TEST(r1.intensities[5] == 65);
BOOST_TEST(r2.num_timesteps = num_timesteps);
BOOST_TEST(r2.num_channels = num_channels);
BOOST_TEST(r2.intensities != (void*)NULL);
BOOST_TEST(r2.intensities[0] == 60);
BOOST_TEST(r2.intensities[1] == 61);
BOOST_TEST(r2.intensities[2] == 62);
BOOST_TEST(r2.intensities[3] == 63);
BOOST_TEST(r2.intensities[4] == 64);
BOOST_TEST(r2.intensities[5] == 65);
}
BOOST_AUTO_TEST_CASE(paren_op_test) {
int num_timesteps = 3;
int num_channels = 2;
Radiometry r(num_timesteps, num_channels);
r(0, 0) = 600;
r(0, 1) = 601;
r(1, 0) = 610;
r(1, 1) = 611;
r(2, 0) = 620;
r(2, 1) = 621;
BOOST_TEST(r(0, 0) == 600);
BOOST_TEST(r(0, 1) == 601);
BOOST_TEST(r(1, 0) == 610);
BOOST_TEST(r(1, 1) == 611);
BOOST_TEST(r(2, 0) == 620);
BOOST_TEST(r(2, 1) == 621);
}
BOOST_AUTO_TEST_CASE(paren_op_const_test) {
int num_timesteps = 3;
int num_channels = 2;
Radiometry r(num_timesteps, num_channels);
r(0, 0) = 600;
r(0, 1) = 601;
r(1, 0) = 610;
r(1, 1) = 611;
r(2, 0) = 620;
r(2, 1) = 621;
const Radiometry& cr = r;
BOOST_TEST(cr(0, 0) == 600);
BOOST_TEST(cr(0, 1) == 601);
BOOST_TEST(cr(1, 0) == 610);
BOOST_TEST(cr(1, 1) == 611);
BOOST_TEST(cr(2, 0) == 620);
BOOST_TEST(cr(2, 1) == 621);
}
BOOST_AUTO_TEST_SUITE_END() // radiometry_suite
BOOST_AUTO_TEST_SUITE_END() // common_suite
} // namespace whatprot
|
#pragma once
/*
MIT License
Copyright (c) 2017 ZetaChain_Native
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 "platform.hpp" // Platform Specific Stuff NOTE: Must Always be the first include in a file
#include <string>
namespace ZetaChain_Native::IO::Filesystem {
#ifdef _WIN32
HANDLE createFile(LPCSTR fileName, DWORD desiredAccess, DWORD shareMode, LPSECURITY_ATTRIBUTES attributes,
DWORD creationDisposition, DWORD flags, HANDLE templateFile);
BOOL createDirectory(LPCSTR directoryName, LPSECURITY_ATTRIBUTES attributes);
bool directoryExists(LPCSTR directoryName);
BOOL closeFile(HANDLE file);
BOOL openFile(LPCSTR fileName, LPOFSTRUCT reOpenBuf, UINT style);
BOOL deleteFile(LPCSTR filePath);
#elif __linux__ || __unix__ || __APPLE__
int createDirectory(std::string path, mode_t mode);
bool directoryExists(std::string directory);
int openFile(std::string pathname, int flags);
int openFile(std::string pathname, int flags, mode_t mode);
int createFile(std::string pathname, mode_t mode);
void deleteFile(std::string file);
#endif
}
|
// Copyright (c) 2012-2020 The Beans Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <rpc/client.h>
#include <rpc/server.h>
#include <rpc/util.h>
#include <core_io.h>
#include <interfaces/chain.h>
#include <node/context.h>
#include <test/util/setup_common.h>
#include <util/ref.h>
#include <util/time.h>
#include <boost/algorithm/string.hpp>
#include <boost/test/unit_test.hpp>
#include <univalue.h>
#include <rpc/blockchain.h>
class RPCTestingSetup : public TestingSetup
{
public:
UniValue CallRPC(std::string args);
};
UniValue RPCTestingSetup::CallRPC(std::string args)
{
std::vector<std::string> vArgs;
boost::split(vArgs, args, boost::is_any_of(" \t"));
std::string strMethod = vArgs[0];
vArgs.erase(vArgs.begin());
util::Ref context{m_node};
JSONRPCRequest request(context);
request.strMethod = strMethod;
request.params = RPCConvertValues(strMethod, vArgs);
request.fHelp = false;
if (RPCIsInWarmup(nullptr)) SetRPCWarmupFinished();
try {
UniValue result = tableRPC.execute(request);
return result;
}
catch (const UniValue& objError) {
throw std::runtime_error(find_value(objError, "message").get_str());
}
}
BOOST_FIXTURE_TEST_SUITE(rpc_tests, RPCTestingSetup)
BOOST_AUTO_TEST_CASE(rpc_rawparams)
{
// Test raw transaction API argument handling
UniValue r;
BOOST_CHECK_THROW(CallRPC("getrawtransaction"), std::runtime_error);
BOOST_CHECK_THROW(CallRPC("getrawtransaction not_hex"), std::runtime_error);
BOOST_CHECK_THROW(CallRPC("getrawtransaction a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed not_int"), std::runtime_error);
BOOST_CHECK_THROW(CallRPC("createrawtransaction"), std::runtime_error);
BOOST_CHECK_THROW(CallRPC("createrawtransaction null null"), std::runtime_error);
BOOST_CHECK_THROW(CallRPC("createrawtransaction not_array"), std::runtime_error);
BOOST_CHECK_THROW(CallRPC("createrawtransaction {} {}"), std::runtime_error);
BOOST_CHECK_NO_THROW(CallRPC("createrawtransaction [] {}"));
BOOST_CHECK_THROW(CallRPC("createrawtransaction [] {} extra"), std::runtime_error);
BOOST_CHECK_THROW(CallRPC("decoderawtransaction"), std::runtime_error);
BOOST_CHECK_THROW(CallRPC("decoderawtransaction null"), std::runtime_error);
BOOST_CHECK_THROW(CallRPC("decoderawtransaction DEADBEEF"), std::runtime_error);
std::string rawtx = "0100000001a15d57094aa7a21a28cb20b59aab8fc7d1149a3bdbcddba9c622e4f5f6a99ece010000006c493046022100f93bb0e7d8db7bd46e40132d1f8242026e045f03a0efe71bbb8e3f475e970d790221009337cd7f1f929f00cc6ff01f03729b069a7c21b59b1736ddfee5db5946c5da8c0121033b9b137ee87d5a812d6f506efdd37f0affa7ffc310711c06c7f3e097c9447c52ffffffff0100e1f505000000001976a9140389035a9225b3839e2bbf32d826a1e222031fd888ac00000000";
BOOST_CHECK_NO_THROW(r = CallRPC(std::string("decoderawtransaction ")+rawtx));
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "size").get_int(), 193);
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "version").get_int(), 1);
BOOST_CHECK_EQUAL(find_value(r.get_obj(), "locktime").get_int(), 0);
BOOST_CHECK_THROW(CallRPC(std::string("decoderawtransaction ")+rawtx+" extra"), std::runtime_error);
BOOST_CHECK_NO_THROW(r = CallRPC(std::string("decoderawtransaction ")+rawtx+" false"));
BOOST_CHECK_THROW(r = CallRPC(std::string("decoderawtransaction ")+rawtx+" false extra"), std::runtime_error);
// Only check failure cases for sendrawtransaction, there's no network to send to...
BOOST_CHECK_THROW(CallRPC("sendrawtransaction"), std::runtime_error);
BOOST_CHECK_THROW(CallRPC("sendrawtransaction null"), std::runtime_error);
BOOST_CHECK_THROW(CallRPC("sendrawtransaction DEADBEEF"), std::runtime_error);
BOOST_CHECK_THROW(CallRPC(std::string("sendrawtransaction ")+rawtx+" extra"), std::runtime_error);
}
BOOST_AUTO_TEST_CASE(rpc_togglenetwork)
{
UniValue r;
r = CallRPC("getnetworkinfo");
bool netState = find_value(r.get_obj(), "networkactive").get_bool();
BOOST_CHECK_EQUAL(netState, true);
BOOST_CHECK_NO_THROW(CallRPC("setnetworkactive false"));
r = CallRPC("getnetworkinfo");
int numConnection = find_value(r.get_obj(), "connections").get_int();
BOOST_CHECK_EQUAL(numConnection, 0);
netState = find_value(r.get_obj(), "networkactive").get_bool();
BOOST_CHECK_EQUAL(netState, false);
BOOST_CHECK_NO_THROW(CallRPC("setnetworkactive true"));
r = CallRPC("getnetworkinfo");
netState = find_value(r.get_obj(), "networkactive").get_bool();
BOOST_CHECK_EQUAL(netState, true);
}
BOOST_AUTO_TEST_CASE(rpc_rawsign)
{
UniValue r;
// input is a 1-of-2 multisig (so is output):
std::string prevout =
"[{\"txid\":\"b4cc287e58f87cdae59417329f710f3ecd75a4ee1d2872b7248f50977c8493f3\","
"\"vout\":1,\"scriptPubKey\":\"a914b10c9df5f7edf436c697f02f1efdba4cf399615187\","
"\"redeemScript\":\"512103debedc17b3df2badbcdd86d5feb4562b86fe182e5998abd8bcd4f122c6155b1b21027e940bb73ab8732bfdf7f9216ecefca5b94d6df834e77e108f68e66f126044c052ae\"}]";
r = CallRPC(std::string("createrawtransaction ")+prevout+" "+
"{\"3HqAe9LtNBjnsfM4CyYaWTnvCaUYT7v4oZ\":11}");
std::string notsigned = r.get_str();
std::string privkey1 = "\"KzsXybp9jX64P5ekX1KUxRQ79Jht9uzW7LorgwE65i5rWACL6LQe\"";
std::string privkey2 = "\"Kyhdf5LuKTRx4ge69ybABsiUAWjVRK4XGxAKk2FQLp2HjGMy87Z4\"";
r = CallRPC(std::string("signrawtransactionwithkey ")+notsigned+" [] "+prevout);
BOOST_CHECK(find_value(r.get_obj(), "complete").get_bool() == false);
r = CallRPC(std::string("signrawtransactionwithkey ")+notsigned+" ["+privkey1+","+privkey2+"] "+prevout);
BOOST_CHECK(find_value(r.get_obj(), "complete").get_bool() == true);
}
BOOST_AUTO_TEST_CASE(rpc_createraw_op_return)
{
BOOST_CHECK_NO_THROW(CallRPC("createrawtransaction [{\"txid\":\"a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed\",\"vout\":0}] {\"data\":\"68656c6c6f776f726c64\"}"));
// Key not "data" (bad address)
BOOST_CHECK_THROW(CallRPC("createrawtransaction [{\"txid\":\"a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed\",\"vout\":0}] {\"somedata\":\"68656c6c6f776f726c64\"}"), std::runtime_error);
// Bad hex encoding of data output
BOOST_CHECK_THROW(CallRPC("createrawtransaction [{\"txid\":\"a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed\",\"vout\":0}] {\"data\":\"12345\"}"), std::runtime_error);
BOOST_CHECK_THROW(CallRPC("createrawtransaction [{\"txid\":\"a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed\",\"vout\":0}] {\"data\":\"12345g\"}"), std::runtime_error);
// Data 81 bytes long
BOOST_CHECK_NO_THROW(CallRPC("createrawtransaction [{\"txid\":\"a3b807410df0b60fcb9736768df5823938b2f838694939ba45f3c0a1bff150ed\",\"vout\":0}] {\"data\":\"010203040506070809101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081\"}"));
}
BOOST_AUTO_TEST_CASE(rpc_format_monetary_values)
{
BOOST_CHECK(ValueFromAmount(0LL).write() == "0.00000000");
BOOST_CHECK(ValueFromAmount(1LL).write() == "0.00000001");
BOOST_CHECK(ValueFromAmount(17622195LL).write() == "0.17622195");
BOOST_CHECK(ValueFromAmount(50000000LL).write() == "0.50000000");
BOOST_CHECK(ValueFromAmount(89898989LL).write() == "0.89898989");
BOOST_CHECK(ValueFromAmount(100000000LL).write() == "1.00000000");
BOOST_CHECK(ValueFromAmount(2099999999999990LL).write() == "20999999.99999990");
BOOST_CHECK(ValueFromAmount(2099999999999999LL).write() == "20999999.99999999");
BOOST_CHECK_EQUAL(ValueFromAmount(0).write(), "0.00000000");
BOOST_CHECK_EQUAL(ValueFromAmount((COIN/10000)*123456789).write(), "12345.67890000");
BOOST_CHECK_EQUAL(ValueFromAmount(-COIN).write(), "-1.00000000");
BOOST_CHECK_EQUAL(ValueFromAmount(-COIN/10).write(), "-0.10000000");
BOOST_CHECK_EQUAL(ValueFromAmount(COIN*100000000).write(), "100000000.00000000");
BOOST_CHECK_EQUAL(ValueFromAmount(COIN*10000000).write(), "10000000.00000000");
BOOST_CHECK_EQUAL(ValueFromAmount(COIN*1000000).write(), "1000000.00000000");
BOOST_CHECK_EQUAL(ValueFromAmount(COIN*100000).write(), "100000.00000000");
BOOST_CHECK_EQUAL(ValueFromAmount(COIN*10000).write(), "10000.00000000");
BOOST_CHECK_EQUAL(ValueFromAmount(COIN*1000).write(), "1000.00000000");
BOOST_CHECK_EQUAL(ValueFromAmount(COIN*100).write(), "100.00000000");
BOOST_CHECK_EQUAL(ValueFromAmount(COIN*10).write(), "10.00000000");
BOOST_CHECK_EQUAL(ValueFromAmount(COIN).write(), "1.00000000");
BOOST_CHECK_EQUAL(ValueFromAmount(COIN/10).write(), "0.10000000");
BOOST_CHECK_EQUAL(ValueFromAmount(COIN/100).write(), "0.01000000");
BOOST_CHECK_EQUAL(ValueFromAmount(COIN/1000).write(), "0.00100000");
BOOST_CHECK_EQUAL(ValueFromAmount(COIN/10000).write(), "0.00010000");
BOOST_CHECK_EQUAL(ValueFromAmount(COIN/100000).write(), "0.00001000");
BOOST_CHECK_EQUAL(ValueFromAmount(COIN/1000000).write(), "0.00000100");
BOOST_CHECK_EQUAL(ValueFromAmount(COIN/10000000).write(), "0.00000010");
BOOST_CHECK_EQUAL(ValueFromAmount(COIN/100000000).write(), "0.00000001");
}
static UniValue ValueFromString(const std::string &str)
{
UniValue value;
BOOST_CHECK(value.setNumStr(str));
return value;
}
BOOST_AUTO_TEST_CASE(rpc_parse_monetary_values)
{
BOOST_CHECK_THROW(AmountFromValue(ValueFromString("-0.00000001")), UniValue);
BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0")), 0LL);
BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.00000000")), 0LL);
BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.00000001")), 1LL);
BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.17622195")), 17622195LL);
BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.5")), 50000000LL);
BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.50000000")), 50000000LL);
BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.89898989")), 89898989LL);
BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("1.00000000")), 100000000LL);
BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("20999999.9999999")), 2099999999999990LL);
BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("20999999.99999999")), 2099999999999999LL);
BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("1e-8")), COIN/100000000);
BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.1e-7")), COIN/100000000);
BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.01e-6")), COIN/100000000);
BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.0000000000000000000000000000000000000000000000000000000000000000000000000001e+68")), COIN/100000000);
BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("10000000000000000000000000000000000000000000000000000000000000000e-64")), COIN);
BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000e64")), COIN);
BOOST_CHECK_THROW(AmountFromValue(ValueFromString("1e-9")), UniValue); //should fail
BOOST_CHECK_THROW(AmountFromValue(ValueFromString("0.000000019")), UniValue); //should fail
BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.00000001000000")), 1LL); //should pass, cut trailing 0
BOOST_CHECK_THROW(AmountFromValue(ValueFromString("19e-9")), UniValue); //should fail
BOOST_CHECK_EQUAL(AmountFromValue(ValueFromString("0.19e-6")), 19); //should pass, leading 0 is present
BOOST_CHECK_THROW(AmountFromValue(ValueFromString("92233720368.54775808")), UniValue); //overflow error
BOOST_CHECK_THROW(AmountFromValue(ValueFromString("1e+11")), UniValue); //overflow error
BOOST_CHECK_THROW(AmountFromValue(ValueFromString("1e11")), UniValue); //overflow error signless
BOOST_CHECK_THROW(AmountFromValue(ValueFromString("93e+9")), UniValue); //overflow error
}
BOOST_AUTO_TEST_CASE(json_parse_errors)
{
// Valid
BOOST_CHECK_EQUAL(ParseNonRFCJSONValue("1.0").get_real(), 1.0);
// Valid, with leading or trailing whitespace
BOOST_CHECK_EQUAL(ParseNonRFCJSONValue(" 1.0").get_real(), 1.0);
BOOST_CHECK_EQUAL(ParseNonRFCJSONValue("1.0 ").get_real(), 1.0);
BOOST_CHECK_THROW(AmountFromValue(ParseNonRFCJSONValue(".19e-6")), std::runtime_error); //should fail, missing leading 0, therefore invalid JSON
BOOST_CHECK_EQUAL(AmountFromValue(ParseNonRFCJSONValue("0.00000000000000000000000000000000000001e+30 ")), 1);
// Invalid, initial garbage
BOOST_CHECK_THROW(ParseNonRFCJSONValue("[1.0"), std::runtime_error);
BOOST_CHECK_THROW(ParseNonRFCJSONValue("a1.0"), std::runtime_error);
// Invalid, trailing garbage
BOOST_CHECK_THROW(ParseNonRFCJSONValue("1.0sds"), std::runtime_error);
BOOST_CHECK_THROW(ParseNonRFCJSONValue("1.0]"), std::runtime_error);
// BNS addresses should fail parsing
BOOST_CHECK_THROW(ParseNonRFCJSONValue("175tWpb8K1S7NmH4Zx6rewF9WQrcZv245W"), std::runtime_error);
BOOST_CHECK_THROW(ParseNonRFCJSONValue("3J98t1WpEZ73CNmQviecrnyiWrnqRhWNL"), std::runtime_error);
}
BOOST_AUTO_TEST_CASE(rpc_ban)
{
BOOST_CHECK_NO_THROW(CallRPC(std::string("clearbanned")));
UniValue r;
BOOST_CHECK_NO_THROW(r = CallRPC(std::string("setban 127.0.0.0 add")));
BOOST_CHECK_THROW(r = CallRPC(std::string("setban 127.0.0.0:8334")), std::runtime_error); //portnumber for setban not allowed
BOOST_CHECK_NO_THROW(r = CallRPC(std::string("listbanned")));
UniValue ar = r.get_array();
UniValue o1 = ar[0].get_obj();
UniValue adr = find_value(o1, "address");
BOOST_CHECK_EQUAL(adr.get_str(), "127.0.0.0/32");
BOOST_CHECK_NO_THROW(CallRPC(std::string("setban 127.0.0.0 remove")));
BOOST_CHECK_NO_THROW(r = CallRPC(std::string("listbanned")));
ar = r.get_array();
BOOST_CHECK_EQUAL(ar.size(), 0U);
BOOST_CHECK_NO_THROW(r = CallRPC(std::string("setban 127.0.0.0/24 add 9907731200 true")));
BOOST_CHECK_NO_THROW(r = CallRPC(std::string("listbanned")));
ar = r.get_array();
o1 = ar[0].get_obj();
adr = find_value(o1, "address");
UniValue banned_until = find_value(o1, "banned_until");
BOOST_CHECK_EQUAL(adr.get_str(), "127.0.0.0/24");
BOOST_CHECK_EQUAL(banned_until.get_int64(), 9907731200); // absolute time check
BOOST_CHECK_NO_THROW(CallRPC(std::string("clearbanned")));
BOOST_CHECK_NO_THROW(r = CallRPC(std::string("setban 127.0.0.0/24 add 200")));
BOOST_CHECK_NO_THROW(r = CallRPC(std::string("listbanned")));
ar = r.get_array();
o1 = ar[0].get_obj();
adr = find_value(o1, "address");
banned_until = find_value(o1, "banned_until");
BOOST_CHECK_EQUAL(adr.get_str(), "127.0.0.0/24");
int64_t now = GetTime();
BOOST_CHECK(banned_until.get_int64() > now);
BOOST_CHECK(banned_until.get_int64()-now <= 200);
// must throw an exception because 127.0.0.1 is in already banned subnet range
BOOST_CHECK_THROW(r = CallRPC(std::string("setban 127.0.0.1 add")), std::runtime_error);
BOOST_CHECK_NO_THROW(CallRPC(std::string("setban 127.0.0.0/24 remove")));
BOOST_CHECK_NO_THROW(r = CallRPC(std::string("listbanned")));
ar = r.get_array();
BOOST_CHECK_EQUAL(ar.size(), 0U);
BOOST_CHECK_NO_THROW(r = CallRPC(std::string("setban 127.0.0.0/255.255.0.0 add")));
BOOST_CHECK_THROW(r = CallRPC(std::string("setban 127.0.1.1 add")), std::runtime_error);
BOOST_CHECK_NO_THROW(CallRPC(std::string("clearbanned")));
BOOST_CHECK_NO_THROW(r = CallRPC(std::string("listbanned")));
ar = r.get_array();
BOOST_CHECK_EQUAL(ar.size(), 0U);
BOOST_CHECK_THROW(r = CallRPC(std::string("setban test add")), std::runtime_error); //invalid IP
//IPv6 tests
BOOST_CHECK_NO_THROW(r = CallRPC(std::string("setban FE80:0000:0000:0000:0202:B3FF:FE1E:8329 add")));
BOOST_CHECK_NO_THROW(r = CallRPC(std::string("listbanned")));
ar = r.get_array();
o1 = ar[0].get_obj();
adr = find_value(o1, "address");
BOOST_CHECK_EQUAL(adr.get_str(), "fe80::202:b3ff:fe1e:8329/128");
BOOST_CHECK_NO_THROW(CallRPC(std::string("clearbanned")));
BOOST_CHECK_NO_THROW(r = CallRPC(std::string("setban 2001:db8::/ffff:fffc:0:0:0:0:0:0 add")));
BOOST_CHECK_NO_THROW(r = CallRPC(std::string("listbanned")));
ar = r.get_array();
o1 = ar[0].get_obj();
adr = find_value(o1, "address");
BOOST_CHECK_EQUAL(adr.get_str(), "2001:db8::/30");
BOOST_CHECK_NO_THROW(CallRPC(std::string("clearbanned")));
BOOST_CHECK_NO_THROW(r = CallRPC(std::string("setban 2001:4d48:ac57:400:cacf:e9ff:fe1d:9c63/128 add")));
BOOST_CHECK_NO_THROW(r = CallRPC(std::string("listbanned")));
ar = r.get_array();
o1 = ar[0].get_obj();
adr = find_value(o1, "address");
BOOST_CHECK_EQUAL(adr.get_str(), "2001:4d48:ac57:400:cacf:e9ff:fe1d:9c63/128");
}
BOOST_AUTO_TEST_CASE(rpc_convert_values_generatetoaddress)
{
UniValue result;
BOOST_CHECK_NO_THROW(result = RPCConvertValues("generatetoaddress", {"101", "mkESjLZW66TmHhiFX8MCaBjrhZ543PPh9a"}));
BOOST_CHECK_EQUAL(result[0].get_int(), 101);
BOOST_CHECK_EQUAL(result[1].get_str(), "mkESjLZW66TmHhiFX8MCaBjrhZ543PPh9a");
BOOST_CHECK_NO_THROW(result = RPCConvertValues("generatetoaddress", {"101", "mhMbmE2tE9xzJYCV9aNC8jKWN31vtGrguU"}));
BOOST_CHECK_EQUAL(result[0].get_int(), 101);
BOOST_CHECK_EQUAL(result[1].get_str(), "mhMbmE2tE9xzJYCV9aNC8jKWN31vtGrguU");
BOOST_CHECK_NO_THROW(result = RPCConvertValues("generatetoaddress", {"1", "mkESjLZW66TmHhiFX8MCaBjrhZ543PPh9a", "9"}));
BOOST_CHECK_EQUAL(result[0].get_int(), 1);
BOOST_CHECK_EQUAL(result[1].get_str(), "mkESjLZW66TmHhiFX8MCaBjrhZ543PPh9a");
BOOST_CHECK_EQUAL(result[2].get_int(), 9);
BOOST_CHECK_NO_THROW(result = RPCConvertValues("generatetoaddress", {"1", "mhMbmE2tE9xzJYCV9aNC8jKWN31vtGrguU", "9"}));
BOOST_CHECK_EQUAL(result[0].get_int(), 1);
BOOST_CHECK_EQUAL(result[1].get_str(), "mhMbmE2tE9xzJYCV9aNC8jKWN31vtGrguU");
BOOST_CHECK_EQUAL(result[2].get_int(), 9);
}
BOOST_AUTO_TEST_CASE(rpc_getblockstats_calculate_percentiles_by_weight)
{
int64_t total_weight = 200;
std::vector<std::pair<CAmount, int64_t>> feerates;
CAmount result[NUM_GETBLOCKSTATS_PERCENTILES] = { 0 };
for (int64_t i = 0; i < 100; i++) {
feerates.emplace_back(std::make_pair(1 ,1));
}
for (int64_t i = 0; i < 100; i++) {
feerates.emplace_back(std::make_pair(2 ,1));
}
CalculatePercentilesByWeight(result, feerates, total_weight);
BOOST_CHECK_EQUAL(result[0], 1);
BOOST_CHECK_EQUAL(result[1], 1);
BOOST_CHECK_EQUAL(result[2], 1);
BOOST_CHECK_EQUAL(result[3], 2);
BOOST_CHECK_EQUAL(result[4], 2);
// Test with more pairs, and two pairs overlapping 2 percentiles.
total_weight = 100;
CAmount result2[NUM_GETBLOCKSTATS_PERCENTILES] = { 0 };
feerates.clear();
feerates.emplace_back(std::make_pair(1, 9));
feerates.emplace_back(std::make_pair(2 , 16)); //10th + 25th percentile
feerates.emplace_back(std::make_pair(4 ,50)); //50th + 75th percentile
feerates.emplace_back(std::make_pair(5 ,10));
feerates.emplace_back(std::make_pair(9 ,15)); // 90th percentile
CalculatePercentilesByWeight(result2, feerates, total_weight);
BOOST_CHECK_EQUAL(result2[0], 2);
BOOST_CHECK_EQUAL(result2[1], 2);
BOOST_CHECK_EQUAL(result2[2], 4);
BOOST_CHECK_EQUAL(result2[3], 4);
BOOST_CHECK_EQUAL(result2[4], 9);
// Same test as above, but one of the percentile-overlapping pairs is split in 2.
total_weight = 100;
CAmount result3[NUM_GETBLOCKSTATS_PERCENTILES] = { 0 };
feerates.clear();
feerates.emplace_back(std::make_pair(1, 9));
feerates.emplace_back(std::make_pair(2 , 11)); // 10th percentile
feerates.emplace_back(std::make_pair(2 , 5)); // 25th percentile
feerates.emplace_back(std::make_pair(4 ,50)); //50th + 75th percentile
feerates.emplace_back(std::make_pair(5 ,10));
feerates.emplace_back(std::make_pair(9 ,15)); // 90th percentile
CalculatePercentilesByWeight(result3, feerates, total_weight);
BOOST_CHECK_EQUAL(result3[0], 2);
BOOST_CHECK_EQUAL(result3[1], 2);
BOOST_CHECK_EQUAL(result3[2], 4);
BOOST_CHECK_EQUAL(result3[3], 4);
BOOST_CHECK_EQUAL(result3[4], 9);
// Test with one transaction spanning all percentiles.
total_weight = 104;
CAmount result4[NUM_GETBLOCKSTATS_PERCENTILES] = { 0 };
feerates.clear();
feerates.emplace_back(std::make_pair(1, 100));
feerates.emplace_back(std::make_pair(2, 1));
feerates.emplace_back(std::make_pair(3, 1));
feerates.emplace_back(std::make_pair(3, 1));
feerates.emplace_back(std::make_pair(999999, 1));
CalculatePercentilesByWeight(result4, feerates, total_weight);
for (int64_t i = 0; i < NUM_GETBLOCKSTATS_PERCENTILES; i++) {
BOOST_CHECK_EQUAL(result4[i], 1);
}
}
BOOST_AUTO_TEST_SUITE_END()
|
#include "../Ui/ProgressBar.h"
#include "../Graphics/Colour.h"
#include "../Graphics/Gfx.h"
#include "../Graphics/ImageIds.h"
#include "../Interop/Interop.hpp"
#include "../OpenLoco.h"
#include "../Ui/WindowManager.h"
#include "../Window.h"
#include <array>
#include <string>
#include <string_view>
using namespace OpenLoco::Interop;
namespace OpenLoco::Ui::Windows::ProgressBar
{
enum Widx
{
frame,
caption,
panel,
};
constexpr Gfx::ui_size_t windowSize = { 350, 47 };
widget_t widgets[] = {
makeWidget({ 0, 0 }, { 350, 47 }, widget_type::frame, 0),
makeWidget({ 1, 1 }, { 348, 13 }, widget_type::caption_25, 0, StringIds::buffer_1250),
makeWidget({ 0, 15 }, { 350, 32 }, widget_type::panel, 1),
widgetEnd(),
};
static window_event_list _events;
static std::string _captionString;
static uint8_t _progressBarStyle = 0; // 0x005233C8
static uint8_t _progressBarValue = 0; // 0x011370A8
void setProgress(uint8_t value);
static void initEvents();
// 0x004CF6E2
window* open(std::string_view captionString)
{
_captionString = captionString;
setScreenFlag(ScreenFlags::progressBarActive);
_progressBarValue = 0xFF;
initEvents();
auto window = WindowManager::createWindowCentred(
WindowType::progressBar,
windowSize,
WindowFlags::flag_11 | WindowFlags::stick_to_front,
&_events);
window->widgets = widgets;
window->initScrollWidgets();
window->colours[0] = Colour::black;
window->colours[1] = Colour::black;
setProgress(0);
return window;
}
// 0x004CF74E
void close()
{
clearScreenFlag(ScreenFlags::progressBarActive);
WindowManager::close(WindowType::progressBar);
Gfx::invalidateScreen();
_progressBarStyle ^= 1;
}
// 0x004CF76D
void setProgress(uint8_t value)
{
if (_progressBarValue == value)
return;
_progressBarValue = value;
WindowManager::invalidate(WindowType::progressBar);
Ui::ProgressBar::sub_4CF63B();
}
// 0x004CF78A
static void prepareDraw(window* self)
{
char* buffer = const_cast<char*>(StringManager::getString(StringIds::buffer_1250));
strncpy(buffer, _captionString.c_str(), 256);
}
// 004CF7A0
static void draw(window* self, Gfx::Context* context)
{
self->draw(context);
Gfx::Context* clipped = nullptr;
if (!Gfx::clipContext(&clipped, context, Gfx::point_t(self->x + 2, self->y + 17), Gfx::ui_size_t(self->width - 5, self->height - 19)))
return;
// First, draw the train track.
Gfx::drawImage(clipped, 0, 0, ImageIds::progressbar_track);
// What train image to use depends on the progress bar style.
uint32_t trainImage;
if (_progressBarStyle == 0)
{
static std::array<uint32_t, 4> style0Frames = {
ImageIds::progressbar_style0_frame0,
ImageIds::progressbar_style0_frame1,
ImageIds::progressbar_style0_frame2,
ImageIds::progressbar_style0_frame3,
};
auto currentFrame = (_progressBarValue / 4) % std::size(style0Frames);
trainImage = Gfx::recolour2(style0Frames.at(currentFrame), Colour::saturated_green, Colour::salmon_pink);
}
else
{
static std::array<uint32_t, 4> style1Frames = {
ImageIds::progressbar_style1_frame0,
ImageIds::progressbar_style1_frame1,
ImageIds::progressbar_style1_frame2,
ImageIds::progressbar_style1_frame3,
};
auto currentFrame = (_progressBarValue / 4) % std::size(style1Frames);
trainImage = Gfx::recolour2(style1Frames.at(currentFrame), Colour::black, Colour::dark_green);
}
// Draw the train image from the right of the window,
int16_t xPos = _progressBarValue - 255;
Gfx::drawImage(clipped, xPos, 0, trainImage);
}
static void initEvents()
{
_events.draw = draw;
_events.prepare_draw = prepareDraw;
}
}
|
//=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://www.opensource.org/licenses/MIT)
//=======================================================================
#ifndef NEW_H
#define NEW_H
inline void* operator new( size_t , void* place){
return place;
}
inline void* operator new[]( size_t , void* place){
return place;
}
#endif
|
// 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.
// The history system runs on a background thread so that potentially slow
// database operations don't delay the browser. This backend processing is
// represented by HistoryBackend. The HistoryService's job is to dispatch to
// that thread.
//
// Main thread History thread
// ----------- --------------
// HistoryService <----------------> HistoryBackend
// -> HistoryDatabase
// -> SQLite connection to History
// -> ThumbnailDatabase
// -> SQLite connection to Thumbnails
// (and favicons)
#include "components/history/core/browser/history_service.h"
#include <utility>
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/location.h"
#include "base/memory/ref_counted.h"
#include "base/metrics/histogram_macros.h"
#include "base/single_thread_task_runner.h"
#include "base/thread_task_runner_handle.h"
#include "base/threading/thread.h"
#include "base/time/time.h"
#include "base/trace_event/trace_event.h"
#include "build/build_config.h"
#include "components/history/core/browser/download_row.h"
#include "components/history/core/browser/history_backend.h"
#include "components/history/core/browser/history_backend_client.h"
#include "components/history/core/browser/history_client.h"
#include "components/history/core/browser/history_database_params.h"
#include "components/history/core/browser/history_db_task.h"
#include "components/history/core/browser/history_service_observer.h"
#include "components/history/core/browser/history_types.h"
#include "components/history/core/browser/in_memory_database.h"
#include "components/history/core/browser/in_memory_history_backend.h"
#include "components/history/core/browser/keyword_search_term.h"
#include "components/history/core/browser/visit_database.h"
#include "components/history/core/browser/visit_delegate.h"
#include "components/history/core/browser/visit_filter.h"
#include "components/history/core/browser/web_history_service.h"
#include "components/history/core/common/thumbnail_score.h"
#include "sync/api/sync_error_factory.h"
#include "third_party/skia/include/core/SkBitmap.h"
#if defined(OS_IOS)
#include "base/critical_closure.h"
#endif
using base::Time;
namespace history {
namespace {
static const char* kHistoryThreadName = "Chrome_HistoryThread";
void RunWithFaviconResults(
const favicon_base::FaviconResultsCallback& callback,
std::vector<favicon_base::FaviconRawBitmapResult>* bitmap_results) {
callback.Run(*bitmap_results);
}
void RunWithFaviconResult(
const favicon_base::FaviconRawBitmapCallback& callback,
favicon_base::FaviconRawBitmapResult* bitmap_result) {
callback.Run(*bitmap_result);
}
void RunWithQueryURLResult(const HistoryService::QueryURLCallback& callback,
const QueryURLResult* result) {
callback.Run(result->success, result->row, result->visits);
}
void RunWithVisibleVisitCountToHostResult(
const HistoryService::GetVisibleVisitCountToHostCallback& callback,
const VisibleVisitCountToHostResult* result) {
callback.Run(result->success, result->count, result->first_visit);
}
// Callback from WebHistoryService::ExpireWebHistory().
void ExpireWebHistoryComplete(bool success) {
// Ignore the result.
//
// TODO(davidben): ExpireLocalAndRemoteHistoryBetween callback should not fire
// until this completes.
}
} // namespace
// Sends messages from the backend to us on the main thread. This must be a
// separate class from the history service so that it can hold a reference to
// the history service (otherwise we would have to manually AddRef and
// Release when the Backend has a reference to us).
class HistoryService::BackendDelegate : public HistoryBackend::Delegate {
public:
BackendDelegate(
const base::WeakPtr<HistoryService>& history_service,
const scoped_refptr<base::SequencedTaskRunner>& service_task_runner)
: history_service_(history_service),
service_task_runner_(service_task_runner) {}
void NotifyProfileError(sql::InitStatus init_status) override {
// Send to the history service on the main thread.
service_task_runner_->PostTask(
FROM_HERE, base::Bind(&HistoryService::NotifyProfileError,
history_service_, init_status));
}
void SetInMemoryBackend(scoped_ptr<InMemoryHistoryBackend> backend) override {
// Send the backend to the history service on the main thread.
service_task_runner_->PostTask(
FROM_HERE, base::Bind(&HistoryService::SetInMemoryBackend,
history_service_, base::Passed(&backend)));
}
void NotifyFaviconsChanged(const std::set<GURL>& page_urls,
const GURL& icon_url) override {
// Send the notification to the history service on the main thread.
service_task_runner_->PostTask(
FROM_HERE, base::Bind(&HistoryService::NotifyFaviconsChanged,
history_service_, page_urls, icon_url));
}
void NotifyURLVisited(ui::PageTransition transition,
const URLRow& row,
const RedirectList& redirects,
base::Time visit_time) override {
service_task_runner_->PostTask(
FROM_HERE,
base::Bind(&HistoryService::NotifyURLVisited, history_service_,
transition, row, redirects, visit_time));
}
void NotifyURLsModified(const URLRows& changed_urls) override {
service_task_runner_->PostTask(
FROM_HERE, base::Bind(&HistoryService::NotifyURLsModified,
history_service_, changed_urls));
}
void NotifyURLsDeleted(bool all_history,
bool expired,
const URLRows& deleted_rows,
const std::set<GURL>& favicon_urls) override {
service_task_runner_->PostTask(
FROM_HERE,
base::Bind(&HistoryService::NotifyURLsDeleted, history_service_,
all_history, expired, deleted_rows, favicon_urls));
}
void NotifyKeywordSearchTermUpdated(const URLRow& row,
KeywordID keyword_id,
const base::string16& term) override {
service_task_runner_->PostTask(
FROM_HERE, base::Bind(&HistoryService::NotifyKeywordSearchTermUpdated,
history_service_, row, keyword_id, term));
}
void NotifyKeywordSearchTermDeleted(URLID url_id) override {
service_task_runner_->PostTask(
FROM_HERE, base::Bind(&HistoryService::NotifyKeywordSearchTermDeleted,
history_service_, url_id));
}
void DBLoaded() override {
service_task_runner_->PostTask(
FROM_HERE, base::Bind(&HistoryService::OnDBLoaded, history_service_));
}
private:
const base::WeakPtr<HistoryService> history_service_;
const scoped_refptr<base::SequencedTaskRunner> service_task_runner_;
};
// The history thread is intentionally not a BrowserThread because the
// sync integration unit tests depend on being able to create more than one
// history thread.
HistoryService::HistoryService()
: thread_(new base::Thread(kHistoryThreadName)),
history_client_(nullptr),
backend_loaded_(false),
weak_ptr_factory_(this) {
}
HistoryService::HistoryService(scoped_ptr<HistoryClient> history_client,
scoped_ptr<VisitDelegate> visit_delegate)
: thread_(new base::Thread(kHistoryThreadName)),
history_client_(std::move(history_client)),
visit_delegate_(std::move(visit_delegate)),
backend_loaded_(false),
weak_ptr_factory_(this) {}
HistoryService::~HistoryService() {
DCHECK(thread_checker_.CalledOnValidThread());
// Shutdown the backend. This does nothing if Cleanup was already invoked.
Cleanup();
}
bool HistoryService::BackendLoaded() {
DCHECK(thread_checker_.CalledOnValidThread());
return backend_loaded_;
}
#if defined(OS_IOS)
void HistoryService::HandleBackgrounding() {
if (!thread_ || !history_backend_.get())
return;
ScheduleTask(PRIORITY_NORMAL,
base::MakeCriticalClosure(base::Bind(
&HistoryBackend::PersistState, history_backend_.get())));
}
#endif
void HistoryService::ClearCachedDataForContextID(ContextID context_id) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
ScheduleTask(PRIORITY_NORMAL,
base::Bind(&HistoryBackend::ClearCachedDataForContextID,
history_backend_.get(), context_id));
}
URLDatabase* HistoryService::InMemoryDatabase() {
DCHECK(thread_checker_.CalledOnValidThread());
return in_memory_backend_ ? in_memory_backend_->db() : nullptr;
}
bool HistoryService::GetTypedCountForURL(const GURL& url, int* typed_count) {
DCHECK(thread_checker_.CalledOnValidThread());
URLRow url_row;
if (!GetRowForURL(url, &url_row))
return false;
*typed_count = url_row.typed_count();
return true;
}
bool HistoryService::GetLastVisitTimeForURL(const GURL& url,
base::Time* last_visit) {
DCHECK(thread_checker_.CalledOnValidThread());
URLRow url_row;
if (!GetRowForURL(url, &url_row))
return false;
*last_visit = url_row.last_visit();
return true;
}
bool HistoryService::GetVisitCountForURL(const GURL& url, int* visit_count) {
DCHECK(thread_checker_.CalledOnValidThread());
URLRow url_row;
if (!GetRowForURL(url, &url_row))
return false;
*visit_count = url_row.visit_count();
return true;
}
TypedUrlSyncableService* HistoryService::GetTypedUrlSyncableService() const {
return history_backend_->GetTypedUrlSyncableService();
}
void HistoryService::Shutdown() {
DCHECK(thread_checker_.CalledOnValidThread());
Cleanup();
}
void HistoryService::SetKeywordSearchTermsForURL(const GURL& url,
KeywordID keyword_id,
const base::string16& term) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
ScheduleTask(PRIORITY_UI,
base::Bind(&HistoryBackend::SetKeywordSearchTermsForURL,
history_backend_.get(), url, keyword_id, term));
}
void HistoryService::DeleteAllSearchTermsForKeyword(KeywordID keyword_id) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
if (in_memory_backend_)
in_memory_backend_->DeleteAllSearchTermsForKeyword(keyword_id);
ScheduleTask(PRIORITY_UI,
base::Bind(&HistoryBackend::DeleteAllSearchTermsForKeyword,
history_backend_.get(), keyword_id));
}
void HistoryService::DeleteKeywordSearchTermForURL(const GURL& url) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
ScheduleTask(PRIORITY_UI,
base::Bind(&HistoryBackend::DeleteKeywordSearchTermForURL,
history_backend_.get(), url));
}
void HistoryService::DeleteMatchingURLsForKeyword(KeywordID keyword_id,
const base::string16& term) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
ScheduleTask(PRIORITY_UI,
base::Bind(&HistoryBackend::DeleteMatchingURLsForKeyword,
history_backend_.get(), keyword_id, term));
}
void HistoryService::URLsNoLongerBookmarked(const std::set<GURL>& urls) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
ScheduleTask(PRIORITY_NORMAL,
base::Bind(&HistoryBackend::URLsNoLongerBookmarked,
history_backend_.get(), urls));
}
void HistoryService::AddObserver(HistoryServiceObserver* observer) {
DCHECK(thread_checker_.CalledOnValidThread());
observers_.AddObserver(observer);
}
void HistoryService::RemoveObserver(HistoryServiceObserver* observer) {
DCHECK(thread_checker_.CalledOnValidThread());
observers_.RemoveObserver(observer);
}
base::CancelableTaskTracker::TaskId HistoryService::ScheduleDBTask(
scoped_ptr<HistoryDBTask> task,
base::CancelableTaskTracker* tracker) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
base::CancelableTaskTracker::IsCanceledCallback is_canceled;
base::CancelableTaskTracker::TaskId task_id =
tracker->NewTrackedTaskId(&is_canceled);
// Use base::ThreadTaskRunnerHandler::Get() to get a message loop proxy to
// the current message loop so that we can forward the call to the method
// HistoryDBTask::DoneRunOnMainThread() in the correct thread.
thread_->task_runner()->PostTask(
FROM_HERE, base::Bind(&HistoryBackend::ProcessDBTask,
history_backend_.get(), base::Passed(&task),
base::ThreadTaskRunnerHandle::Get(), is_canceled));
return task_id;
}
void HistoryService::FlushForTest(const base::Closure& flushed) {
thread_->task_runner()->PostTaskAndReply(
FROM_HERE, base::Bind(&base::DoNothing), flushed);
}
void HistoryService::SetOnBackendDestroyTask(const base::Closure& task) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
ScheduleTask(
PRIORITY_NORMAL,
base::Bind(&HistoryBackend::SetOnBackendDestroyTask,
history_backend_.get(), base::MessageLoop::current(), task));
}
void HistoryService::TopHosts(size_t num_hosts,
const TopHostsCallback& callback) const {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
PostTaskAndReplyWithResult(
thread_->task_runner().get(), FROM_HERE,
base::Bind(&HistoryBackend::TopHosts, history_backend_.get(), num_hosts),
callback);
}
void HistoryService::GetCountsForOrigins(
const std::set<GURL>& origins,
const GetCountsForOriginsCallback& callback) const {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
PostTaskAndReplyWithResult(thread_->task_runner().get(), FROM_HERE,
base::Bind(&HistoryBackend::GetCountsForOrigins,
history_backend_.get(), origins),
callback);
}
void HistoryService::HostRankIfAvailable(
const GURL& url,
const base::Callback<void(int)>& callback) const {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
PostTaskAndReplyWithResult(thread_->task_runner().get(), FROM_HERE,
base::Bind(&HistoryBackend::HostRankIfAvailable,
history_backend_.get(), url),
callback);
}
void HistoryService::AddPage(const GURL& url,
Time time,
ContextID context_id,
int nav_entry_id,
const GURL& referrer,
const RedirectList& redirects,
ui::PageTransition transition,
VisitSource visit_source,
bool did_replace_entry) {
DCHECK(thread_checker_.CalledOnValidThread());
AddPage(HistoryAddPageArgs(url, time, context_id, nav_entry_id, referrer,
redirects, transition, visit_source,
did_replace_entry));
}
void HistoryService::AddPage(const GURL& url,
base::Time time,
VisitSource visit_source) {
DCHECK(thread_checker_.CalledOnValidThread());
AddPage(HistoryAddPageArgs(url, time, nullptr, 0, GURL(), RedirectList(),
ui::PAGE_TRANSITION_LINK, visit_source, false));
}
void HistoryService::AddPage(const HistoryAddPageArgs& add_page_args) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
// Filter out unwanted URLs. We don't add auto-subframe URLs. They are a
// large part of history (think iframes for ads) and we never display them in
// history UI. We will still add manual subframes, which are ones the user
// has clicked on to get.
if (history_client_ && !history_client_->CanAddURL(add_page_args.url))
return;
// Inform VisitedDelegate of all links and redirects.
if (visit_delegate_) {
if (!add_page_args.redirects.empty()) {
// We should not be asked to add a page in the middle of a redirect chain,
// and thus add_page_args.url should be the last element in the array
// add_page_args.redirects which mean we can use VisitDelegate::AddURLs()
// with the whole array.
DCHECK_EQ(add_page_args.url, add_page_args.redirects.back());
visit_delegate_->AddURLs(add_page_args.redirects);
} else {
visit_delegate_->AddURL(add_page_args.url);
}
}
ScheduleTask(PRIORITY_NORMAL,
base::Bind(&HistoryBackend::AddPage, history_backend_.get(),
add_page_args));
}
void HistoryService::AddPageNoVisitForBookmark(const GURL& url,
const base::string16& title) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
if (history_client_ && !history_client_->CanAddURL(url))
return;
ScheduleTask(PRIORITY_NORMAL,
base::Bind(&HistoryBackend::AddPageNoVisitForBookmark,
history_backend_.get(), url, title));
}
void HistoryService::SetPageTitle(const GURL& url,
const base::string16& title) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
ScheduleTask(PRIORITY_NORMAL, base::Bind(&HistoryBackend::SetPageTitle,
history_backend_.get(), url, title));
}
void HistoryService::UpdateWithPageEndTime(ContextID context_id,
int nav_entry_id,
const GURL& url,
Time end_ts) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
ScheduleTask(
PRIORITY_NORMAL,
base::Bind(&HistoryBackend::UpdateWithPageEndTime, history_backend_.get(),
context_id, nav_entry_id, url, end_ts));
}
void HistoryService::AddPageWithDetails(const GURL& url,
const base::string16& title,
int visit_count,
int typed_count,
Time last_visit,
bool hidden,
VisitSource visit_source) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
// Filter out unwanted URLs.
if (history_client_ && !history_client_->CanAddURL(url))
return;
// Inform VisitDelegate of the URL.
if (visit_delegate_)
visit_delegate_->AddURL(url);
URLRow row(url);
row.set_title(title);
row.set_visit_count(visit_count);
row.set_typed_count(typed_count);
row.set_last_visit(last_visit);
row.set_hidden(hidden);
URLRows rows;
rows.push_back(row);
ScheduleTask(PRIORITY_NORMAL,
base::Bind(&HistoryBackend::AddPagesWithDetails,
history_backend_.get(), rows, visit_source));
}
void HistoryService::AddPagesWithDetails(const URLRows& info,
VisitSource visit_source) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
// Inform the VisitDelegate of the URLs
if (!info.empty() && visit_delegate_) {
std::vector<GURL> urls;
urls.reserve(info.size());
for (const auto& row : info)
urls.push_back(row.url());
visit_delegate_->AddURLs(urls);
}
ScheduleTask(PRIORITY_NORMAL,
base::Bind(&HistoryBackend::AddPagesWithDetails,
history_backend_.get(), info, visit_source));
}
base::CancelableTaskTracker::TaskId HistoryService::GetFavicons(
const std::vector<GURL>& icon_urls,
int icon_types,
const std::vector<int>& desired_sizes,
const favicon_base::FaviconResultsCallback& callback,
base::CancelableTaskTracker* tracker) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
std::vector<favicon_base::FaviconRawBitmapResult>* results =
new std::vector<favicon_base::FaviconRawBitmapResult>();
return tracker->PostTaskAndReply(
thread_->task_runner().get(), FROM_HERE,
base::Bind(&HistoryBackend::GetFavicons, history_backend_.get(),
icon_urls, icon_types, desired_sizes, results),
base::Bind(&RunWithFaviconResults, callback, base::Owned(results)));
}
base::CancelableTaskTracker::TaskId HistoryService::GetFaviconsForURL(
const GURL& page_url,
int icon_types,
const std::vector<int>& desired_sizes,
const favicon_base::FaviconResultsCallback& callback,
base::CancelableTaskTracker* tracker) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
std::vector<favicon_base::FaviconRawBitmapResult>* results =
new std::vector<favicon_base::FaviconRawBitmapResult>();
return tracker->PostTaskAndReply(
thread_->task_runner().get(), FROM_HERE,
base::Bind(&HistoryBackend::GetFaviconsForURL, history_backend_.get(),
page_url, icon_types, desired_sizes, results),
base::Bind(&RunWithFaviconResults, callback, base::Owned(results)));
}
base::CancelableTaskTracker::TaskId HistoryService::GetLargestFaviconForURL(
const GURL& page_url,
const std::vector<int>& icon_types,
int minimum_size_in_pixels,
const favicon_base::FaviconRawBitmapCallback& callback,
base::CancelableTaskTracker* tracker) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
favicon_base::FaviconRawBitmapResult* result =
new favicon_base::FaviconRawBitmapResult();
return tracker->PostTaskAndReply(
thread_->task_runner().get(), FROM_HERE,
base::Bind(&HistoryBackend::GetLargestFaviconForURL,
history_backend_.get(), page_url, icon_types,
minimum_size_in_pixels, result),
base::Bind(&RunWithFaviconResult, callback, base::Owned(result)));
}
base::CancelableTaskTracker::TaskId HistoryService::GetFaviconForID(
favicon_base::FaviconID favicon_id,
int desired_size,
const favicon_base::FaviconResultsCallback& callback,
base::CancelableTaskTracker* tracker) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
std::vector<favicon_base::FaviconRawBitmapResult>* results =
new std::vector<favicon_base::FaviconRawBitmapResult>();
return tracker->PostTaskAndReply(
thread_->task_runner().get(), FROM_HERE,
base::Bind(&HistoryBackend::GetFaviconForID, history_backend_.get(),
favicon_id, desired_size, results),
base::Bind(&RunWithFaviconResults, callback, base::Owned(results)));
}
base::CancelableTaskTracker::TaskId
HistoryService::UpdateFaviconMappingsAndFetch(
const GURL& page_url,
const std::vector<GURL>& icon_urls,
int icon_types,
const std::vector<int>& desired_sizes,
const favicon_base::FaviconResultsCallback& callback,
base::CancelableTaskTracker* tracker) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
std::vector<favicon_base::FaviconRawBitmapResult>* results =
new std::vector<favicon_base::FaviconRawBitmapResult>();
return tracker->PostTaskAndReply(
thread_->task_runner().get(), FROM_HERE,
base::Bind(&HistoryBackend::UpdateFaviconMappingsAndFetch,
history_backend_.get(), page_url, icon_urls, icon_types,
desired_sizes, results),
base::Bind(&RunWithFaviconResults, callback, base::Owned(results)));
}
void HistoryService::MergeFavicon(
const GURL& page_url,
const GURL& icon_url,
favicon_base::IconType icon_type,
scoped_refptr<base::RefCountedMemory> bitmap_data,
const gfx::Size& pixel_size) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
if (history_client_ && !history_client_->CanAddURL(page_url))
return;
ScheduleTask(
PRIORITY_NORMAL,
base::Bind(&HistoryBackend::MergeFavicon, history_backend_.get(),
page_url, icon_url, icon_type, bitmap_data, pixel_size));
}
void HistoryService::SetFavicons(const GURL& page_url,
favicon_base::IconType icon_type,
const GURL& icon_url,
const std::vector<SkBitmap>& bitmaps) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
if (history_client_ && !history_client_->CanAddURL(page_url))
return;
ScheduleTask(PRIORITY_NORMAL,
base::Bind(&HistoryBackend::SetFavicons, history_backend_.get(),
page_url, icon_type, icon_url, bitmaps));
}
void HistoryService::SetFaviconsOutOfDateForPage(const GURL& page_url) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
ScheduleTask(PRIORITY_NORMAL,
base::Bind(&HistoryBackend::SetFaviconsOutOfDateForPage,
history_backend_.get(), page_url));
}
void HistoryService::SetImportedFavicons(
const favicon_base::FaviconUsageDataList& favicon_usage) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
ScheduleTask(PRIORITY_NORMAL,
base::Bind(&HistoryBackend::SetImportedFavicons,
history_backend_.get(), favicon_usage));
}
base::CancelableTaskTracker::TaskId HistoryService::QueryURL(
const GURL& url,
bool want_visits,
const QueryURLCallback& callback,
base::CancelableTaskTracker* tracker) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
QueryURLResult* query_url_result = new QueryURLResult();
return tracker->PostTaskAndReply(
thread_->task_runner().get(), FROM_HERE,
base::Bind(&HistoryBackend::QueryURL, history_backend_.get(), url,
want_visits, base::Unretained(query_url_result)),
base::Bind(&RunWithQueryURLResult, callback,
base::Owned(query_url_result)));
}
// Statistics ------------------------------------------------------------------
base::CancelableTaskTracker::TaskId HistoryService::GetHistoryCount(
const Time& begin_time,
const Time& end_time,
const GetHistoryCountCallback& callback,
base::CancelableTaskTracker* tracker) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
return tracker->PostTaskAndReplyWithResult(
thread_->task_runner().get(), FROM_HERE,
base::Bind(&HistoryBackend::GetHistoryCount,
history_backend_.get(),
begin_time,
end_time),
callback);
}
// Downloads -------------------------------------------------------------------
// Handle creation of a download by creating an entry in the history service's
// 'downloads' table.
void HistoryService::CreateDownload(
const DownloadRow& create_info,
const HistoryService::DownloadCreateCallback& callback) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
PostTaskAndReplyWithResult(thread_->task_runner().get(), FROM_HERE,
base::Bind(&HistoryBackend::CreateDownload,
history_backend_.get(), create_info),
callback);
}
void HistoryService::GetNextDownloadId(const DownloadIdCallback& callback) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
PostTaskAndReplyWithResult(
thread_->task_runner().get(), FROM_HERE,
base::Bind(&HistoryBackend::GetNextDownloadId, history_backend_.get()),
callback);
}
// Handle queries for a list of all downloads in the history database's
// 'downloads' table.
void HistoryService::QueryDownloads(const DownloadQueryCallback& callback) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
std::vector<DownloadRow>* rows = new std::vector<DownloadRow>();
scoped_ptr<std::vector<DownloadRow>> scoped_rows(rows);
// Beware! The first Bind() does not simply |scoped_rows.get()| because
// base::Passed(&scoped_rows) nullifies |scoped_rows|, and compilers do not
// guarantee that the first Bind's arguments are evaluated before the second
// Bind's arguments.
thread_->task_runner()->PostTaskAndReply(
FROM_HERE,
base::Bind(&HistoryBackend::QueryDownloads, history_backend_.get(), rows),
base::Bind(callback, base::Passed(&scoped_rows)));
}
// Handle updates for a particular download. This is a 'fire and forget'
// operation, so we don't need to be called back.
void HistoryService::UpdateDownload(const DownloadRow& data) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
ScheduleTask(PRIORITY_NORMAL, base::Bind(&HistoryBackend::UpdateDownload,
history_backend_.get(), data));
}
void HistoryService::RemoveDownloads(const std::set<uint32_t>& ids) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
ScheduleTask(PRIORITY_NORMAL, base::Bind(&HistoryBackend::RemoveDownloads,
history_backend_.get(), ids));
}
base::CancelableTaskTracker::TaskId HistoryService::QueryHistoryWStatement(
const char* sql_statement,
const std::string& search_string,
int max_hits,
const QueryHistoryCallback& callback,
base::CancelableTaskTracker* tracker) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
QueryResults* query_results = new QueryResults();
return tracker->PostTaskAndReply(
thread_->task_runner().get(), FROM_HERE,
base::Bind(&HistoryBackend::QueryHistoryWStatement,
history_backend_.get(), sql_statement, search_string, max_hits,
base::Unretained(query_results)),
base::Bind(callback, base::Owned(query_results)));
}
base::CancelableTaskTracker::TaskId HistoryService::QueryHistory(
const base::string16& text_query,
const QueryOptions& options,
const QueryHistoryCallback& callback,
base::CancelableTaskTracker* tracker) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
QueryResults* query_results = new QueryResults();
return tracker->PostTaskAndReply(
thread_->task_runner().get(), FROM_HERE,
base::Bind(&HistoryBackend::QueryHistory, history_backend_.get(),
text_query, options, base::Unretained(query_results)),
base::Bind(callback, base::Owned(query_results)));
}
base::CancelableTaskTracker::TaskId HistoryService::QueryRedirectsFrom(
const GURL& from_url,
const QueryRedirectsCallback& callback,
base::CancelableTaskTracker* tracker) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
RedirectList* result = new RedirectList();
return tracker->PostTaskAndReply(
thread_->task_runner().get(), FROM_HERE,
base::Bind(&HistoryBackend::QueryRedirectsFrom, history_backend_.get(),
from_url, base::Unretained(result)),
base::Bind(callback, base::Owned(result)));
}
base::CancelableTaskTracker::TaskId HistoryService::QueryRedirectsTo(
const GURL& to_url,
const QueryRedirectsCallback& callback,
base::CancelableTaskTracker* tracker) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
RedirectList* result = new RedirectList();
return tracker->PostTaskAndReply(
thread_->task_runner().get(), FROM_HERE,
base::Bind(&HistoryBackend::QueryRedirectsTo, history_backend_.get(),
to_url, base::Unretained(result)),
base::Bind(callback, base::Owned(result)));
}
base::CancelableTaskTracker::TaskId HistoryService::GetVisibleVisitCountToHost(
const GURL& url,
const GetVisibleVisitCountToHostCallback& callback,
base::CancelableTaskTracker* tracker) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
VisibleVisitCountToHostResult* result = new VisibleVisitCountToHostResult();
return tracker->PostTaskAndReply(
thread_->task_runner().get(), FROM_HERE,
base::Bind(&HistoryBackend::GetVisibleVisitCountToHost,
history_backend_.get(), url, base::Unretained(result)),
base::Bind(&RunWithVisibleVisitCountToHostResult, callback,
base::Owned(result)));
}
base::CancelableTaskTracker::TaskId HistoryService::QueryMostVisitedURLs(
int result_count,
int days_back,
const QueryMostVisitedURLsCallback& callback,
base::CancelableTaskTracker* tracker) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
MostVisitedURLList* result = new MostVisitedURLList();
return tracker->PostTaskAndReply(
thread_->task_runner().get(), FROM_HERE,
base::Bind(&HistoryBackend::QueryMostVisitedURLs, history_backend_.get(),
result_count, days_back, base::Unretained(result)),
base::Bind(callback, base::Owned(result)));
}
base::CancelableTaskTracker::TaskId HistoryService::QueryFilteredURLs(
int result_count,
const VisitFilter& filter,
bool extended_info,
const QueryFilteredURLsCallback& callback,
base::CancelableTaskTracker* tracker) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
FilteredURLList* result = new FilteredURLList();
return tracker->PostTaskAndReply(
thread_->task_runner().get(), FROM_HERE,
base::Bind(&HistoryBackend::QueryFilteredURLs, history_backend_.get(),
result_count, filter, extended_info, base::Unretained(result)),
base::Bind(callback, base::Owned(result)));
}
void HistoryService::Cleanup() {
DCHECK(thread_checker_.CalledOnValidThread());
if (!thread_) {
// We've already cleaned up.
return;
}
NotifyHistoryServiceBeingDeleted();
weak_ptr_factory_.InvalidateWeakPtrs();
// Inform the HistoryClient that we are shuting down.
if (history_client_)
history_client_->Shutdown();
// Unload the backend.
if (history_backend_.get()) {
// Get rid of the in-memory backend.
in_memory_backend_.reset();
// The backend's destructor must run on the history thread since it is not
// threadsafe. So this thread must not be the last thread holding a
// reference to the backend, or a crash could happen.
//
// We have a reference to the history backend. There is also an extra
// reference held by our delegate installed in the backend, which
// HistoryBackend::Closing will release. This means if we scheduled a call
// to HistoryBackend::Closing and *then* released our backend reference,
// there will be a race between us and the backend's Closing function to see
// who is the last holder of a reference. If the backend thread's Closing
// manages to run before we release our backend refptr, the last reference
// will be held by this thread and the destructor will be called from here.
//
// Therefore, we create a closure to run the Closing operation first. This
// holds a reference to the backend. Then we release our reference, then we
// schedule the task to run. After the task runs, it will delete its
// reference from the history thread, ensuring everything works properly.
//
// TODO(ajwong): Cleanup HistoryBackend lifetime issues.
// See http://crbug.com/99767.
history_backend_->AddRef();
base::Closure closing_task =
base::Bind(&HistoryBackend::Closing, history_backend_.get());
ScheduleTask(PRIORITY_NORMAL, closing_task);
closing_task.Reset();
HistoryBackend* raw_ptr = history_backend_.get();
history_backend_ = nullptr;
thread_->message_loop()->ReleaseSoon(FROM_HERE, raw_ptr);
}
// Delete the thread, which joins with the background thread. We defensively
// nullptr the pointer before deleting it in case somebody tries to use it
// during shutdown, but this shouldn't happen.
base::Thread* thread = thread_;
thread_ = nullptr;
delete thread;
}
bool HistoryService::Init(
bool no_db,
const std::string& languages,
const HistoryDatabaseParams& history_database_params) {
TRACE_EVENT0("browser,startup", "HistoryService::Init")
SCOPED_UMA_HISTOGRAM_TIMER("History.HistoryServiceInitTime");
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
base::Thread::Options options;
options.timer_slack = base::TIMER_SLACK_MAXIMUM;
if (!thread_->StartWithOptions(options)) {
Cleanup();
return false;
}
// Create the history backend.
scoped_refptr<HistoryBackend> backend(new HistoryBackend(
new BackendDelegate(weak_ptr_factory_.GetWeakPtr(),
base::ThreadTaskRunnerHandle::Get()),
history_client_ ? history_client_->CreateBackendClient() : nullptr,
thread_->task_runner()));
history_backend_.swap(backend);
ScheduleTask(PRIORITY_UI,
base::Bind(&HistoryBackend::Init, history_backend_.get(),
languages, no_db, history_database_params));
if (visit_delegate_ && !visit_delegate_->Init(this))
return false;
if (history_client_)
history_client_->OnHistoryServiceCreated(this);
return true;
}
void HistoryService::ScheduleAutocomplete(
const base::Callback<void(HistoryBackend*, URLDatabase*)>& callback) {
DCHECK(thread_checker_.CalledOnValidThread());
ScheduleTask(PRIORITY_UI, base::Bind(&HistoryBackend::ScheduleAutocomplete,
history_backend_.get(), callback));
}
void HistoryService::ScheduleTask(SchedulePriority priority,
const base::Closure& task) {
DCHECK(thread_checker_.CalledOnValidThread());
CHECK(thread_);
CHECK(thread_->message_loop());
// TODO(brettw): Do prioritization.
thread_->task_runner()->PostTask(FROM_HERE, task);
}
base::WeakPtr<HistoryService> HistoryService::AsWeakPtr() {
DCHECK(thread_checker_.CalledOnValidThread());
return weak_ptr_factory_.GetWeakPtr();
}
syncer::SyncMergeResult HistoryService::MergeDataAndStartSyncing(
syncer::ModelType type,
const syncer::SyncDataList& initial_sync_data,
scoped_ptr<syncer::SyncChangeProcessor> sync_processor,
scoped_ptr<syncer::SyncErrorFactory> error_handler) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK_EQ(type, syncer::HISTORY_DELETE_DIRECTIVES);
delete_directive_handler_.Start(this, initial_sync_data,
std::move(sync_processor));
return syncer::SyncMergeResult(type);
}
void HistoryService::StopSyncing(syncer::ModelType type) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK_EQ(type, syncer::HISTORY_DELETE_DIRECTIVES);
delete_directive_handler_.Stop();
}
syncer::SyncDataList HistoryService::GetAllSyncData(
syncer::ModelType type) const {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK_EQ(type, syncer::HISTORY_DELETE_DIRECTIVES);
// TODO(akalin): Keep track of existing delete directives.
return syncer::SyncDataList();
}
syncer::SyncError HistoryService::ProcessSyncChanges(
const tracked_objects::Location& from_here,
const syncer::SyncChangeList& change_list) {
delete_directive_handler_.ProcessSyncChanges(this, change_list);
return syncer::SyncError();
}
syncer::SyncError HistoryService::ProcessLocalDeleteDirective(
const sync_pb::HistoryDeleteDirectiveSpecifics& delete_directive) {
DCHECK(thread_checker_.CalledOnValidThread());
return delete_directive_handler_.ProcessLocalDeleteDirective(
delete_directive);
}
void HistoryService::SetInMemoryBackend(
scoped_ptr<InMemoryHistoryBackend> mem_backend) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(!in_memory_backend_) << "Setting mem DB twice";
in_memory_backend_.reset(mem_backend.release());
// The database requires additional initialization once we own it.
in_memory_backend_->AttachToHistoryService(this);
}
void HistoryService::NotifyProfileError(sql::InitStatus init_status) {
DCHECK(thread_checker_.CalledOnValidThread());
if (history_client_)
history_client_->NotifyProfileError(init_status);
}
void HistoryService::DeleteURL(const GURL& url) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
// We will update the visited links when we observe the delete notifications.
ScheduleTask(PRIORITY_NORMAL, base::Bind(&HistoryBackend::DeleteURL,
history_backend_.get(), url));
}
void HistoryService::DeleteURLsForTest(const std::vector<GURL>& urls) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
// We will update the visited links when we observe the delete
// notifications.
ScheduleTask(PRIORITY_NORMAL, base::Bind(&HistoryBackend::DeleteURLs,
history_backend_.get(), urls));
}
void HistoryService::ExpireHistoryBetween(
const std::set<GURL>& restrict_urls,
Time begin_time,
Time end_time,
const base::Closure& callback,
base::CancelableTaskTracker* tracker) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
tracker->PostTaskAndReply(
thread_->task_runner().get(), FROM_HERE,
base::Bind(&HistoryBackend::ExpireHistoryBetween, history_backend_,
restrict_urls, begin_time, end_time),
callback);
}
void HistoryService::ExpireHistory(
const std::vector<ExpireHistoryArgs>& expire_list,
const base::Closure& callback,
base::CancelableTaskTracker* tracker) {
DCHECK(thread_) << "History service being called after cleanup";
DCHECK(thread_checker_.CalledOnValidThread());
tracker->PostTaskAndReply(
thread_->task_runner().get(), FROM_HERE,
base::Bind(&HistoryBackend::ExpireHistory, history_backend_, expire_list),
callback);
}
void HistoryService::ExpireLocalAndRemoteHistoryBetween(
WebHistoryService* web_history,
const std::set<GURL>& restrict_urls,
Time begin_time,
Time end_time,
const base::Closure& callback,
base::CancelableTaskTracker* tracker) {
// TODO(dubroy): This should be factored out into a separate class that
// dispatches deletions to the proper places.
if (web_history) {
// TODO(dubroy): This API does not yet support deletion of specific URLs.
DCHECK(restrict_urls.empty());
delete_directive_handler_.CreateDeleteDirectives(std::set<int64_t>(),
begin_time, end_time);
// Attempt online deletion from the history server, but ignore the result.
// Deletion directives ensure that the results will eventually be deleted.
//
// TODO(davidben): |callback| should not run until this operation completes
// too.
web_history->ExpireHistoryBetween(restrict_urls, begin_time, end_time,
base::Bind(&ExpireWebHistoryComplete));
}
ExpireHistoryBetween(restrict_urls, begin_time, end_time, callback, tracker);
}
void HistoryService::OnDBLoaded() {
DCHECK(thread_checker_.CalledOnValidThread());
backend_loaded_ = true;
NotifyHistoryServiceLoaded();
}
bool HistoryService::GetRowForURL(const GURL& url, URLRow* url_row) {
DCHECK(thread_checker_.CalledOnValidThread());
URLDatabase* db = InMemoryDatabase();
return db && (db->GetRowForURL(url, url_row) != 0);
}
void HistoryService::NotifyURLVisited(ui::PageTransition transition,
const URLRow& row,
const RedirectList& redirects,
base::Time visit_time) {
DCHECK(thread_checker_.CalledOnValidThread());
FOR_EACH_OBSERVER(HistoryServiceObserver, observers_,
OnURLVisited(this, transition, row, redirects, visit_time));
}
void HistoryService::NotifyURLsModified(const URLRows& changed_urls) {
DCHECK(thread_checker_.CalledOnValidThread());
FOR_EACH_OBSERVER(HistoryServiceObserver, observers_,
OnURLsModified(this, changed_urls));
}
void HistoryService::NotifyURLsDeleted(bool all_history,
bool expired,
const URLRows& deleted_rows,
const std::set<GURL>& favicon_urls) {
DCHECK(thread_checker_.CalledOnValidThread());
if (!thread_)
return;
// Inform the VisitDelegate of the deleted URLs. We will inform the delegate
// of added URLs as soon as we get the add notification (we don't have to wait
// for the backend, which allows us to be faster to update the state).
//
// For deleted URLs, we don't typically know what will be deleted since
// delete notifications are by time. We would also like to be more
// respectful of privacy and never tell the user something is gone when it
// isn't. Therefore, we update the delete URLs after the fact.
if (visit_delegate_) {
if (all_history) {
visit_delegate_->DeleteAllURLs();
} else {
std::vector<GURL> urls;
urls.reserve(deleted_rows.size());
for (const auto& row : deleted_rows)
urls.push_back(row.url());
visit_delegate_->DeleteURLs(urls);
}
}
FOR_EACH_OBSERVER(
HistoryServiceObserver, observers_,
OnURLsDeleted(this, all_history, expired, deleted_rows, favicon_urls));
}
void HistoryService::NotifyHistoryServiceLoaded() {
DCHECK(thread_checker_.CalledOnValidThread());
FOR_EACH_OBSERVER(HistoryServiceObserver, observers_,
OnHistoryServiceLoaded(this));
}
void HistoryService::NotifyHistoryServiceBeingDeleted() {
DCHECK(thread_checker_.CalledOnValidThread());
FOR_EACH_OBSERVER(HistoryServiceObserver, observers_,
HistoryServiceBeingDeleted(this));
}
void HistoryService::NotifyKeywordSearchTermUpdated(
const URLRow& row,
KeywordID keyword_id,
const base::string16& term) {
DCHECK(thread_checker_.CalledOnValidThread());
FOR_EACH_OBSERVER(HistoryServiceObserver, observers_,
OnKeywordSearchTermUpdated(this, row, keyword_id, term));
}
void HistoryService::NotifyKeywordSearchTermDeleted(URLID url_id) {
DCHECK(thread_checker_.CalledOnValidThread());
FOR_EACH_OBSERVER(HistoryServiceObserver, observers_,
OnKeywordSearchTermDeleted(this, url_id));
}
scoped_ptr<base::CallbackList<void(const std::set<GURL>&,
const GURL&)>::Subscription>
HistoryService::AddFaviconsChangedCallback(
const HistoryService::OnFaviconsChangedCallback& callback) {
DCHECK(thread_checker_.CalledOnValidThread());
return favicon_changed_callback_list_.Add(callback);
}
void HistoryService::NotifyFaviconsChanged(const std::set<GURL>& page_urls,
const GURL& icon_url) {
DCHECK(thread_checker_.CalledOnValidThread());
favicon_changed_callback_list_.Notify(page_urls, icon_url);
}
} // namespace history
|
/*
* The MIT License (MIT)
*
* 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 "CH376.h"
CH376::CH376(uint8_t spiSelect, uint8_t intPin, SPISettings speed) {
_intPin = intPin;
_spiChipSelect = spiSelect;
_spiSpeed = speed;
}
CH376::CH376(uint8_t spiSelect, SPISettings speed) {
_intPin = MISO;
_spiChipSelect = spiSelect;
_spiSpeed = speed;
}
CH376::~CH376() {
// Auto-generated destructor stub
}
void CH376::init() {
delay(60);
if (_intPin != MISO) {
pinMode(_intPin, INPUT_PULLUP);
}
pinMode(_spiChipSelect, OUTPUT);
digitalWrite(_spiChipSelect, HIGH);
SPI.begin();
resetAll();
delay(100);
if (_intPin == MISO) {
setSDOINT(0x16, 0x90); //10H=DISABLE SDO PIN FOR INTERRUPT OUTPUT
}
_controllerReady = pingDevice();
setMode();
}
bool CH376::pingDevice(byte value) { return (CheckExist(value) == (255 - value)); }
bool CH376::getDeviceAttached() { return _deviceAttached; }
bool CH376::getControllerReady() { return _controllerReady; }
bool CH376::setMode(USB_MODE mode) { return (setUSBMode(mode) == CMD_RET_SUCCESS); }
void CH376::setSpeed(USB_SPEED speed) { setUSBSpeed(speed); }
void CH376::setError(uint8_t errCode) {
_errorCode = errCode;
_deviceAttached = false;
#ifdef DEBUG
Serial.println();
Serial.print("Error:");
Serial.print("\t 0x");
Serial.print(errCode, HEX);
Serial.println();
#endif
}
uint8_t CH376::getError() { return _errorCode; }
void CH376::clearError() { _errorCode = 0; }
#pragma region SPI
void CH376::spiBeginTransfer() {
delayMicroseconds(2);
SPI.beginTransaction(_spiSpeed);
digitalWrite(_spiChipSelect, LOW);
}
void CH376::spiEndTransfer() {
digitalWrite(_spiChipSelect, HIGH);
SPI.endTransaction();
}
void CH376::spiWrite(uint8_t data) {
delayMicroseconds(2); // datasheet TSC min 1.5uSec
SPI.transfer(data);
}
void CH376::spiPrint(const char str[]) {
uint8_t stringCounter = 0;
while (str[stringCounter]) {
spiWrite(str[stringCounter]);
stringCounter++;
}
}
uint8_t CH376::spiRead() {
delayMicroseconds(2); //datasheet TSC min 1.5uSec
return SPI.transfer(0x00);
}
uint8_t CH376::spiReadMultiple(uint8_t* buffer, uint8_t b_size)
{
if (b_size == 0) b_size = sizeof(buffer);
int i;
for (int i = 0; i < b_size; i++)
{
uint8_t value;
uint8_t bytes = spiRead();
*(buffer + i) = value;
}
return i;
}
uint8_t CH376::waitInterrupt(bool endTransfer) {
uint32_t oldMillis = millis();
while (digitalRead(_intPin)) {
if ((millis() - oldMillis) > ANSWTIMEOUT) {
setError(ERR_TIMEOUT);
return 0x00;
}
}
return getInterrupt();
}
#pragma endregion
#pragma region CMD00
void CH376::exec00(uint8_t CMD00) {
spiBeginTransfer();
spiWrite(CMD00);
spiEndTransfer();
#ifdef DEBUG
Serial.println();
Serial.print("Command:");
Serial.print("\t 0x");
Serial.print(CMD00, HEX);
Serial.println();
#endif
}
void CH376::abortNAK() { exec00(CMD00_ABORT_NAK); }
void CH376::dirtyBuffer() { exec00(CMD00_DIRTY_BUFFER); }
void CH376::enterSleep() { exec00(CMD00_ENTER_SLEEP); }
void CH376::resetAll() { exec00(CMD00_RESET_ALL); }
void CH376::unlockUSB() { exec00(CMD00_UNLOCK_USB); }
#pragma endregion
#pragma region CMD10
void CH376::exec10(uint8_t CMD10, uint8_t input, bool endTransfer) {
spiBeginTransfer();
spiWrite(CMD10);
spiWrite(input);
if (endTransfer) { spiEndTransfer(); }
#ifdef DEBUG
Serial.println();
Serial.print("Command:");
Serial.print("\t 0x");
Serial.print(CMD10, HEX);
Serial.println();
Serial.print("input:");
Serial.print("\t 0x");
Serial.print(input, HEX);
Serial.println();
#endif // DEBUG
}
void CH376::setENDPoint2(uint8_t input) { exec10(CMD10_SET_ENDP2, input); }
void CH376::setENDPoint3(uint8_t input) { exec10(CMD10_SET_ENDP3, input); }
void CH376::setENDPoint4(uint8_t input) { exec10(CMD10_SET_ENDP4, input); }
void CH376::setENDPoint5(uint8_t input) { exec10(CMD10_SET_ENDP5, input); }
void CH376::setENDPoint6(uint8_t input) { exec10(CMD10_SET_ENDP6, input); }
void CH376::setENDPoint7(uint8_t input) { exec10(CMD10_SET_ENDP7, input); }
void CH376::setFileName(uint8_t input) { exec10(CMD10_SET_FILE_NAME, input); }
void CH376::setFileName(const char* filename) {
spiBeginTransfer();
spiWrite(CMD10_SET_FILE_NAME);
//write(0x2f); // "/" root directory
spiPrint(filename); // filename
//write(0x5C); // this is the "\" sign
spiWrite((uint8_t)0x00); // terminating null character
spiEndTransfer();
}
void CH376::setUSBAddress(uint8_t input) { exec10(CMD10_SET_USB_ADDR, input); }
void CH376::setUSBSpeed(uint8_t input) { exec10(CMD10_SET_USB_SPEED, input); }
void CH376::writeHostData(uint8_t input) { exec10(CMD10_WR_HOST_DATA, input, false); }
void CH376::writeUSBData3(uint8_t input) { exec10(CMD10_WR_USB_DATA3, input, false); }
void CH376::writeUSBData5(uint8_t input) { exec10(CMD10_WR_USB_DATA5, input, false); }
void CH376::writeUSBData7(uint8_t input) { exec10(CMD10_WR_USB_DATA7, input, false); }
#pragma endregion
#pragma region CMD20
void CH376::exec20(uint8_t CMD20, uint8_t input, uint8_t input2, bool endTransfer) {
spiBeginTransfer();
spiWrite(CMD20);
spiWrite(input);
spiWrite(input2);
if (endTransfer) { spiEndTransfer(); }
#ifdef DEBUG
Serial.println();
Serial.print("Command:");
Serial.print("\t 0x");
Serial.print(CMD20, HEX);
Serial.println();
Serial.print("input:");
Serial.print("\t 0x");
Serial.print(input, HEX);
Serial.println();
Serial.print("input2:");
Serial.print("\t 0x");
Serial.print(input2, HEX);
Serial.println();
#endif // DEBUG
}
void CH376::checkSuspended(uint8_t input, uint8_t input2) { exec20(CMD20_CHK_SUSPEND, input, input2); }
void CH376::setRetry(uint8_t input, uint8_t input2) { exec20(CMD20_SET_RETRY, input, input2); }
void CH376::setSDOINT(uint8_t input, uint8_t input2) { exec20(CMD20_SET_SDO_INT, input, input2); }
void CH376::writeVAR8(uint8_t input, uint8_t input2) { exec20(CMD20_WRITE_VAR8, input, input2); }
void CH376::writeOffsetData(uint8_t input, uint8_t input2) { exec20(CMD20_WR_OFS_DATA, input, input2, false); }
#pragma endregion
#pragma region CMDx0
void CH376::execx0(uint8_t CMDx0, uint8_t input[], int num, bool endTransfer) {
spiBeginTransfer();
spiWrite(CMDx0);
for (int i = 0; i < num; i++) { spiWrite(input[i]); }
if (endTransfer) { spiEndTransfer(); }
#ifdef DEBUG
Serial.println();
Serial.print("Command:");
Serial.print("\t 0x");
Serial.print(CMDx0, HEX);
for (int i = 0; i < num; i++) {
Serial.println();
Serial.print("input");
Serial.print(i);
Serial.print(":");
Serial.print("\t 0x");
Serial.print(input[i], HEX);
}
Serial.println();
#endif // DEBUG
}
void CH376::setUSBID(uint8_t input, uint8_t input2, uint8_t input3, uint8_t input4) {
uint8_t inputs[4] = { input, input2, input3, input4 };
execx0(CMD40_SET_USB_ID, inputs, 4);
}
void CH376::setFileSize(uint8_t input, uint8_t input2, uint8_t input3, uint8_t input4, uint8_t input5) {
uint8_t inputs[5] = { input, input2, input3, input4, input5};
execx0(CMD50_SET_FILE_SIZE, inputs, 5);
}
void CH376::writeVAR32(uint8_t input, uint8_t input2, uint8_t input3, uint8_t input4, uint8_t input5) {
uint8_t inputs[5] = { input, input2, input3, input4, input5};
execx0(CMD50_WRITE_VAR32, inputs, 5);
}
#pragma endregion
#pragma region CMD01
uint8_t CH376::exec01(uint8_t CMD01, bool endTransfer) {
uint8_t tmpRet = 0;
spiBeginTransfer();
spiWrite(CMD01);
tmpRet = spiRead();
if (endTransfer) { spiEndTransfer(); }
#ifdef DEBUG
Serial.println();
Serial.print("Command:");
Serial.print("\t 0x");
Serial.print(CMD01, HEX);
Serial.println();
Serial.print("Returned:");
Serial.print("\t 0x");
Serial.print(tmpRet, HEX);
Serial.println();
#endif // DEBUG
return tmpRet;
}
uint8_t CH376::delay100US() { return exec01(CMD01_DELAY_100US); }
uint8_t CH376::getICVersion() { return exec01(CMD01_GET_IC_VER); }
uint8_t CH376::getInterrupt() { return exec01(CMD01_GET_STATUS); }
uint8_t CH376::readUSBData() { return exec01(CMD01_RD_USB_DATA, false); }
uint8_t CH376::readUSBData0() { return exec01(CMD01_RD_USB_DATA0, false); }
uint8_t CH376::testConnect() { return exec01(CMD01_TEST_CONNECT); }
uint8_t CH376::writeRequestedData() { return exec01(CMD01_WR_REQ_DATA, false); }
#pragma endregion
#pragma region CMD11
uint8_t CH376::exec11(uint8_t CMD11, uint8_t input, bool endTransfer) {
uint8_t tmpRet = 0;
spiBeginTransfer();
spiWrite(CMD11);
spiWrite(input);
tmpRet = spiRead();
if (endTransfer) { spiEndTransfer(); }
#ifdef DEBUG
Serial.println();
Serial.print("Command:");
Serial.print("\t 0x");
Serial.print(CMD11, HEX);
Serial.println();
Serial.print("Returned:");
Serial.print("\t 0x");
Serial.print(tmpRet, HEX);
Serial.println();
#endif // DEBUG
return tmpRet;
}
uint8_t CH376::CheckExist(uint8_t input) { return exec11(CMD11_CHECK_EXIST, input); }
USB_SPEED CH376::getDevRate(uint8_t input) { return (USB_SPEED)exec11(CMD11_GET_DEV_RATE, input); }
uint8_t CH376::getToggle(uint8_t input) { return exec11(CMD11_GET_TOGGLE, input); }
uint8_t CH376::readVar8(uint8_t input) { return exec11(CMD11_READ_VAR8, input); }
uint8_t CH376::setUSBMode(uint8_t input) {
return exec11(CMD11_SET_USB_MODE, input);
delayMicroseconds(40);
}
#pragma endregion
#pragma region CMD21
uint8_t CH376::exec21(uint8_t CMD21, uint8_t input, uint8_t input2, bool endTransfer) {
uint8_t tmpRet = 0;
spiBeginTransfer();
spiWrite(CMD21);
spiWrite(input);
spiWrite(input2);
tmpRet = spiRead();
if (endTransfer) { spiEndTransfer(); }
#ifdef DEBUG
Serial.println();
Serial.print("Command:");
Serial.print("\t 0x");
Serial.print(CMD21, HEX);
Serial.println();
Serial.print("input:");
Serial.print("\t 0x");
Serial.print(input, HEX);
Serial.println();
Serial.print("input2:");
Serial.print("\t 0x");
Serial.print(input2, HEX);
Serial.println();
Serial.print("Returned:");
Serial.print("\t 0x");
Serial.print(tmpRet, HEX);
Serial.println();
#endif // DEBUG
return tmpRet;
}
uint8_t CH376::setBaudrate(uint8_t input, uint8_t input2) { return exec21(CMD21_SET_BAUDRATE, input, input2); }
#pragma endregion
#pragma region CMD0H
uint8_t CH376::exec0H(uint8_t CMD0H, bool endTransfer) {
uint8_t tmpRet = 0;
spiBeginTransfer();
spiWrite(CMD0H);
spiEndTransfer();
tmpRet = waitInterrupt(endTransfer);
#ifdef DEBUG
Serial.println();
Serial.print("Command:");
Serial.print("\t 0x");
Serial.print(CMD0H, HEX);
Serial.println();
Serial.print("Returned:");
Serial.print("\t 0x");
Serial.print(tmpRet, HEX);
Serial.println();
#endif // DEBUG
return tmpRet;
}
uint8_t CH376::autoSetup() { return exec0H(CMD0H_AUTO_SETUP); }
uint8_t CH376::byteReadGo() {
uint8_t tmpRet = exec0H(CMD0H_BYTE_RD_GO);
if (tmpRet != USB_INT_DISK_READ && tmpRet != USB_INT_SUCCESS) {
setError(tmpRet);
}
return tmpRet;
}
uint8_t CH376::byteWriteGo() {
uint8_t tmpRet = exec0H(CMD0H_BYTE_WR_GO);
if (tmpRet != USB_INT_DISK_WRITE && tmpRet != USB_INT_SUCCESS) {
setError(tmpRet);
}
return tmpRet;
}
uint8_t CH376::dirCreate() { return exec0H(CMD0H_DIR_CREATE); }
uint8_t CH376::dirInfoSave() { return exec0H(CMD0H_DIR_INFO_SAVE); }
uint8_t CH376::diskBulgOnly(bool fillStruct) {
uint8_t tmpRet = exec0H(CMD0H_DISK_BOC_CMD);
if (tmpRet == USB_INT_SUCCESS) {
if (fillStruct) {
uint8_t tempDiskBocCbw[sizeof(BULK_ONLY_CBW)];
uint8_t dataLength = readUSBData0();
if (dataLength > sizeof(tempDiskBocCbw)) {
setError(ERR_OVERFLOW);
}
else {
spiReadMultiple(tempDiskBocCbw, dataLength);
spiEndTransfer();
memcpy(&DiskBocCbw, &tempDiskBocCbw, dataLength);
}
}
}
else { setError(tmpRet); }
return tmpRet;
}
uint8_t CH376::diskCapacity() { return exec0H(CMD0H_DISK_CAPACITY); }
uint8_t CH376::diskConnect() { return exec0H(CMD0H_DISK_CONNECT); }
uint8_t CH376::diskInit(bool fillStruct) {
uint8_t tmpRet = exec0H(CMD0H_DISK_INIT);
if (tmpRet == USB_INT_SUCCESS) {
if (fillStruct) {
uint8_t tempDiskInitInq[sizeof (INQUIRY_DATA)];
uint8_t dataLength = readUSBData0();
if (dataLength > sizeof(tempDiskInitInq)) {
setError(ERR_OVERFLOW);
}
else {
spiReadMultiple(tempDiskInitInq, dataLength);
spiEndTransfer();
memcpy(&DiskInitInq, &tempDiskInitInq, dataLength);
}
}
}
else { setError(tmpRet); }
return tmpRet;
}
uint8_t CH376::diskInquiry(bool fillStruct) {
uint8_t tmpRet = exec0H(CMD0H_DISK_INQUIRY);
if (tmpRet == USB_INT_SUCCESS) {
if (fillStruct) {
uint8_t tempDiskInqData[sizeof (INQUIRY_DATA)];
uint8_t dataLength = readUSBData0();
if (dataLength > sizeof(tempDiskInqData)) {
setError(ERR_OVERFLOW);
}
else {
spiReadMultiple(tempDiskInqData, dataLength);
spiEndTransfer();
memcpy(&DiskInqData, &tempDiskInqData, dataLength);
}
}
}
else { setError(tmpRet); }
return tmpRet;
}
uint8_t CH376::diskMaxLogicalUnitNumber() { return exec0H(CMD0H_DISK_MAX_LUN); }
uint8_t CH376::diskMount(bool fillStruct) {
uint8_t tmpRet = exec0H(CMD0H_DISK_MOUNT);
if (tmpRet == USB_INT_SUCCESS) {
if (fillStruct) {
uint8_t tempDiskMountInq[sizeof(INQUIRY_DATA)];
uint8_t dataLength = readUSBData0();
if (dataLength > sizeof(tempDiskMountInq)) {
setError(ERR_OVERFLOW);
}
else {
spiReadMultiple(tempDiskMountInq, dataLength);
spiEndTransfer();
memcpy(&DiskMountInq, &tempDiskMountInq, dataLength);
}
}
}
else { setError(tmpRet); }
return tmpRet;
}
uint8_t CH376::diskQuery(bool fillStruct) {
uint8_t tmpRet = exec0H(CMD0H_DISK_QUERY);
if (tmpRet == USB_INT_DISK_READ) {
if (fillStruct) {
uint8_t tmpDiskQueryInfo[sizeof(DiskQuery)];
uint8_t dataLength = readUSBData0();
if (dataLength > sizeof(tmpDiskQueryInfo)) {
setError(ERR_OVERFLOW);
}
else {
spiReadMultiple(tmpDiskQueryInfo, dataLength);
spiEndTransfer();
memcpy(&DiskQueryInfo, &tmpDiskQueryInfo, dataLength);
}
}
}
else { setError(tmpRet); }
return tmpRet;
}
uint8_t CH376::diskReadGo() { return exec0H(CMD0H_DISK_RD_GO); }
uint8_t CH376::diskReady() { return exec0H(CMD0H_DISK_READY); }
uint8_t CH376::diskReset() { return exec0H(CMD0H_DISK_RESET); }
uint8_t CH376::diskCheckErrors(bool fillStruct) {
uint8_t tmpRet = exec0H(CMD0H_DISK_R_SENSE);
if (tmpRet == USB_INT_SUCCESS) {
if (fillStruct) {
uint8_t tempReqSenseData[sizeof (SENSE_DATA)];
uint8_t dataLength = readUSBData0();
if (dataLength > sizeof(tempReqSenseData)) {
setError(ERR_OVERFLOW);
}
else {
spiReadMultiple(tempReqSenseData, dataLength);
spiEndTransfer();
memcpy(&ReqSenseData, &tempReqSenseData, dataLength);
}
}
}
else { setError(tmpRet); }
return tmpRet;
}
uint8_t CH376::diskSize() {
return exec0H(CMD0H_DISK_SIZE);
}
uint8_t CH376::diskWriteGo() { return exec0H(CMD0H_DISK_WR_GO); }
uint8_t CH376::fileCreate() { return exec0H(CMD0H_FILE_CREATE); }
uint8_t CH376::fileEnumGo(bool fillStruct) {
uint8_t tmpRet = exec0H(CMD0H_FILE_ENUM_GO);
if (tmpRet == USB_INT_DISK_READ) {
if (fillStruct) {
uint8_t tempEnumDirInfo[sizeof(FAT_DIR_INFO)];
uint8_t dataLength = readUSBData0();
if (dataLength > sizeof(tempEnumDirInfo)) {
setError(ERR_OVERFLOW);
}
else {
spiReadMultiple(tempEnumDirInfo, dataLength);
spiEndTransfer();
memcpy(&EnumDirInfo, &tempEnumDirInfo, dataLength);
}
}
}
else { setError(tmpRet); }
return tmpRet;
}
uint8_t CH376::fileErase() { return exec0H(CMD0H_FILE_ERASE); }
uint8_t CH376::fileOpen(bool fillStruct) {
uint8_t tmpRet = exec0H(CMD0H_FILE_OPEN);
if (tmpRet == USB_INT_SUCCESS) {
if (fillStruct) {
uint8_t tempOpenDirInfo[sizeof(FAT_DIR_INFO)];
uint8_t dataLength = readUSBData0();
if (dataLength > sizeof(tempOpenDirInfo)) {
setError(ERR_OVERFLOW);
}
else {
spiReadMultiple(tempOpenDirInfo, dataLength);
spiEndTransfer();
memcpy(&OpenDirInfo, &tempOpenDirInfo, dataLength);
}
}
}
else { setError(tmpRet); }
return tmpRet;
}
uint8_t CH376::readDiskSector() { return exec0H(CMD0H_RD_DISK_SEC); }
uint8_t CH376::writeDiskSector() { return exec0H(CMD0H_WR_DISK_SEC); }
#pragma endregion
#pragma region CMD1H
uint8_t CH376::exec1H(uint8_t CMD1H, uint8_t input, bool endTransfer) {
uint8_t tmpRet = 0;
spiBeginTransfer();
spiWrite(CMD1H);
spiWrite(input);
spiEndTransfer();
tmpRet = waitInterrupt(endTransfer);
#ifdef DEBUG
Serial.println();
Serial.print("Command:");
Serial.print("\t 0x");
Serial.print(CMD1H, HEX);
Serial.println();
Serial.print("Returned:");
Serial.print("\t 0x");
Serial.print(tmpRet, HEX);
Serial.println();
#endif // DEBUG
return tmpRet;
}
uint8_t CH376::clearEndPointError(uint8_t input) { return exec1H(CMD1H_CLR_STALL, input); }
uint8_t CH376::dirInfoRead(uint8_t input) { return exec1H(CMD1H_DIR_INFO_READ, input); }
uint8_t CH376::fileClose(uint8_t input) { return exec1H(CMD1H_FILE_CLOSE, input); }
uint8_t CH376::getDescription(uint8_t input) { return exec1H(CMD1H_GET_DESCR, input); }
uint8_t CH376::issueToken(uint8_t input) { return exec1H(CMD1H_ISSUE_TOKEN, input); }
uint8_t CH376::readFromSector(uint8_t input) { return exec1H(CMD1H_SEC_READ, input); }
uint8_t CH376::writeToSector(uint8_t input) { return exec1H(CMD1H_SEC_WRITE, input); }
uint8_t CH376::setAddress(uint8_t input) { return exec1H(CMD1H_SET_ADDRESS, input); }
uint8_t CH376::setConfig(uint8_t input) { return exec1H(CMD1H_SET_CONFIG, input); }
#pragma endregion
#pragma region CMD2H
uint8_t CH376::exec2H(uint8_t CMD2H, uint8_t input, uint8_t input2, bool endTransfer) {
uint8_t tmpRet = 0;
spiBeginTransfer();
spiWrite(CMD2H);
spiWrite(input);
spiWrite(input2);
spiEndTransfer();
tmpRet = waitInterrupt(endTransfer);
#ifdef DEBUG
Serial.println();
Serial.print("Command:");
Serial.print("\t 0x");
Serial.print(CMD2H, HEX);
Serial.println();
Serial.print("input:");
Serial.print("\t 0x");
Serial.print(input, HEX);
Serial.println();
Serial.print("input2:");
Serial.print("\t 0x");
Serial.print(input2, HEX);
Serial.println();
Serial.print("Returned:");
Serial.print("\t 0x");
Serial.print(tmpRet, HEX);
Serial.println();
#endif // DEBUG
return tmpRet;
}
uint8_t CH376::readByte(uint8_t input, uint8_t input2) {
uint8_t tmpRet = exec2H(CMD2H_BYTE_READ, input, input2);
if (tmpRet != USB_INT_SUCCESS && tmpRet != USB_INT_DISK_READ) {
setError(tmpRet);
}
return tmpRet;
}
uint8_t CH376::writeByte(uint8_t input, uint8_t input2) {
uint8_t tmpRet = exec2H(CMD2H_BYTE_WRITE, input, input2);
if (tmpRet != USB_INT_SUCCESS && tmpRet != USB_INT_DISK_WRITE) {
setError(tmpRet);
}
return tmpRet;
}
uint8_t CH376::issueToken(uint8_t input, uint8_t input2) { return exec2H(CMD2H_ISSUE_TKN_X, input, input2); }
#pragma endregion
#pragma region CMDxH
uint8_t CH376::execxH(uint8_t CMDxH, uint8_t input[], int num, bool endTransfer) {
uint8_t tmpRet = 0;
spiBeginTransfer();
spiWrite(CMDxH);
for (int i = 0; i < num; i++) { spiWrite(input[i]); }
spiEndTransfer();
tmpRet = waitInterrupt(endTransfer);
#ifdef DEBUG
Serial.println();
Serial.print("Command:");
Serial.print("\t 0x");
Serial.print(CMDxH, HEX);
for (int i = 0; i < num; i++) {
Serial.println();
Serial.print("input");
Serial.print(i);
Serial.print(":");
Serial.print("\t 0x");
Serial.print(input[i], HEX);
}
Serial.println();
Serial.print("Returned:");
Serial.print("\t 0x");
Serial.print(tmpRet, HEX);
Serial.println();
#endif // DEBUG
return tmpRet;
}
uint8_t CH376::movePointer(uint8_t input, uint8_t input2, uint8_t input3, uint8_t input4) {
uint8_t inputs[4] = { input, input2, input3, input4 };
return execxH(CMD4H_BYTE_LOCATE, inputs, 4);
}
uint8_t CH376::moveSectorPointer(uint8_t input, uint8_t input2, uint8_t input3, uint8_t input4) {
uint8_t inputs[4] = { input, input2, input3, input4 };
return execxH(CMD4H_SEC_LOCATE, inputs, 4);
}
uint8_t CH376::diskRead(uint8_t input, uint8_t input2, uint8_t input3, uint8_t input4, uint8_t input5) {
uint8_t inputs[4] = { input, input2, input3, input4 };
return execxH(CMD5H_DISK_READ, inputs, 5);
}
uint8_t CH376::diskWrite(uint8_t input, uint8_t input2, uint8_t input3, uint8_t input4, uint8_t input5) {
uint8_t inputs[4] = { input, input2, input3, input4 };
return execxH(CMD5H_DISK_WRITE, inputs, 5);
}
#pragma endregion
|
/**
* @file unit_test_fnd_concepts_regular_invocable.cpp
*
* @brief regular_invocable のテスト
*
* @author myoukaku
*/
#include <bksge/fnd/concepts/regular_invocable.hpp>
#include <bksge/fnd/config.hpp>
#if defined(BKSGE_HAS_CXX20_CONCEPTS)
# define BKSGE_REGULAR_INVOCABLE_TEST(B, ...) \
static_assert(B == bksge::regular_invocable<__VA_ARGS__>, "")
#else
# define BKSGE_REGULAR_INVOCABLE_TEST(B, ...) \
static_assert(B == bksge::regular_invocable<__VA_ARGS__>::value, "")
#endif
namespace bksge_concepts_test
{
namespace regular_invocable_test
{
BKSGE_REGULAR_INVOCABLE_TEST(false, int);
BKSGE_REGULAR_INVOCABLE_TEST(true, int());
BKSGE_REGULAR_INVOCABLE_TEST(true, int(*)());
BKSGE_REGULAR_INVOCABLE_TEST(true, int(&)());
BKSGE_REGULAR_INVOCABLE_TEST(false, int(), int);
BKSGE_REGULAR_INVOCABLE_TEST(false, int() const);
BKSGE_REGULAR_INVOCABLE_TEST(true, int(const long*, short), long*, char);
struct A;
BKSGE_REGULAR_INVOCABLE_TEST(true, int A::*, const A&);
BKSGE_REGULAR_INVOCABLE_TEST(false, void (A::*)(long&), const A*, long&);
BKSGE_REGULAR_INVOCABLE_TEST(true, void (A::*)(long&) const, A*, long&);
struct F
{
void operator()() const;
void operator()(int);
};
BKSGE_REGULAR_INVOCABLE_TEST(true, F);
BKSGE_REGULAR_INVOCABLE_TEST(true, F, int);
BKSGE_REGULAR_INVOCABLE_TEST(true, const F&);
BKSGE_REGULAR_INVOCABLE_TEST(false, const F&, int);
} // namespace regular_invocable_test
} // namespace bksge_concepts_test
#undef BKSGE_REGULAR_INVOCABLE_TEST
|
/////////////////////////////////////////////////////////////////////////////////////////////////
//
// Tencent is pleased to support the open source community by making libpag available.
//
// Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// unless required by applicable law or agreed to in writing, software distributed under the
// license is distributed on an "as is" basis, without warranties or conditions of any kind,
// either express or implied. see the license for the specific language governing permissions
// and limitations under the license.
//
/////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef SKIP_FRAME_COMPARE
#include <map>
#include <thread>
#include <vector>
#include "base/utils/Task.h"
#include "base/utils/TimeUtil.h"
#include "core/Clock.h"
#include "framework/pag_test.h"
#include "framework/utils/PAGTestUtils.h"
#include "framework/utils/Semaphore.h"
#include "nlohmann/json.hpp"
#include "rendering/caches/RenderCache.h"
namespace pag {
using namespace tgfx;
using nlohmann::json;
static constexpr float MAX_FRAME_SIZE = 360.0f;
static constexpr int MAX_THREADS = 6;
static constexpr bool PrintPerformance = false;
struct RenderCost {
int64_t totalTime = 0;
int64_t readPixelsCost = 0;
int64_t compareCost = 0;
std::string performance;
};
class CompareFrameTask : public Executor {
public:
CompareFrameTask(const std::string& fileName, Frame currentFrame,
std::shared_ptr<PixelBuffer> pixelBuffer)
: fileName(fileName), _currentFrame(currentFrame), pixelBuffer(std::move(pixelBuffer)) {
}
Frame currentFrame() const {
return _currentFrame;
}
bool isSuccess() {
return success;
}
private:
const std::string fileName = "";
Frame _currentFrame = 0;
std::shared_ptr<PixelBuffer> pixelBuffer = nullptr;
bool success = false;
void execute() override {
success = Baseline::Compare(pixelBuffer,
"PAGCompareFrameTest/" + fileName + "/" + ToString(_currentFrame));
}
};
void CompareFileFrames(Semaphore* semaphore, std::string pagPath) {
Clock fileClock = {};
auto fileName = pagPath.substr(pagPath.rfind('/') + 1, pagPath.size());
auto pagFile = PAGFile::Load(pagPath);
ASSERT_NE(pagFile, nullptr);
auto width = static_cast<float>(pagFile->width());
auto height = static_cast<float>(pagFile->height());
if (std::max(width, height) > MAX_FRAME_SIZE) {
if (width > height) {
height = static_cast<int>(
ceilf(static_cast<float>(height) * MAX_FRAME_SIZE / static_cast<float>(width)));
width = MAX_FRAME_SIZE;
} else {
width = static_cast<int>(
ceilf(static_cast<float>(width) * MAX_FRAME_SIZE / static_cast<float>(height)));
height = MAX_FRAME_SIZE;
}
}
auto pagSurface =
PAGSurface::MakeOffscreen(static_cast<int>(roundf(width)), static_cast<int>(roundf(height)));
ASSERT_NE(pagSurface, nullptr);
auto pagPlayer = std::make_shared<PAGPlayer>();
pagPlayer->setSurface(pagSurface);
pagPlayer->setComposition(pagFile);
Frame totalFrames = TimeToFrame(pagFile->duration(), pagFile->frameRate());
Frame currentFrame = 0;
std::string errorMsg;
std::map<Frame, RenderCost> performanceMap = {};
std::shared_ptr<PixelBuffer> currentSnapshot = nullptr;
std::shared_ptr<Task> lastTask = nullptr;
auto CompareFrame = [&](Frame currentFrame) {
if (lastTask == nullptr) {
return;
}
Clock clock = {};
auto task = static_cast<CompareFrameTask*>(lastTask->wait());
auto compareCost = clock.measure();
if (currentFrame == task->currentFrame()) {
auto& cost = performanceMap[currentFrame];
cost.compareCost = compareCost;
cost.totalTime += compareCost;
}
if (!task->isSuccess()) {
errorMsg += (std::to_string(currentFrame) + ";");
}
lastTask = nullptr;
};
while (currentFrame < totalFrames) {
auto changed = pagPlayer->flush();
if (changed) {
RenderCost cost = {};
Clock clock = {};
currentSnapshot = MakeSnapshot(pagSurface);
cost.readPixelsCost = clock.measure();
auto cache = pagPlayer->renderCache;
cost.totalTime = cache->totalTime + cost.readPixelsCost;
cost.performance = cache->getPerformanceString();
performanceMap[currentFrame] = cost;
}
CompareFrame(currentFrame - 1);
if (changed) {
auto executor = new CompareFrameTask(fileName, currentFrame, currentSnapshot);
lastTask = Task::Make(std::unique_ptr<CompareFrameTask>(executor));
lastTask->run();
}
pagPlayer->nextFrame();
currentFrame++;
}
CompareFrame(currentFrame - 1);
auto cost = static_cast<float>(fileClock.measure()) / 1000000;
if (PrintPerformance) {
LOGI(
"========================================== %s : start"
" ==========================================",
fileName.c_str());
for (auto& item : performanceMap) {
// if (item.second.totalTime < 10000) { // 小于10ms不打印
// continue;
// }
auto& renderCost = item.second;
LOGI("%4d | %6.1fms :%s %6.1fms[Pixels] %6.1fms[Compare]", item.first,
renderCost.totalTime / 1000.0, renderCost.performance.c_str(),
renderCost.readPixelsCost / 1000.0, renderCost.compareCost / 1000.0);
}
}
EXPECT_EQ(errorMsg, "") << fileName << " frame fail";
LOGI(
"====================================== %s : %.2fs "
"======================================\n",
fileName.c_str(), cost);
semaphore->signal();
}
/**
* 用例描述: 校验 compare 文件夹中各个文件渲染结果
*/
PAG_TEST(PAGFrameCompareTest, RenderFiles) {
std::vector<std::string> files;
GetAllPAGFiles("../resources/compare", files);
Semaphore semaphore(MAX_THREADS);
std::vector<std::thread> threads = {};
for (auto& file : files) {
semaphore.wait();
threads.emplace_back(CompareFileFrames, &semaphore, file);
}
for (auto& thread : threads) {
thread.join();
}
}
} // namespace pag
#endif
|
// testmainmodule.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
#include "testmainmodule.h"
#include <websocketpp/config/asio_no_tls.hpp>
#include <websocketpp/server.hpp>
typedef websocketpp::server<websocketpp::config::asio> WebsocketServer;
typedef WebsocketServer::message_ptr message_ptr;
const std::string URC_WSPATH = "/local/wsconnection/";
class WsConnect : public BaseRoot
{
public:
WsConnect(WebsocketServer* server, websocketpp::connection_hdl hdl)
{
m_server = server;
m_hdl = hdl;
}
virtual ~WsConnect()
{
#ifdef SULOKI_MEMALLOCATOR_DEBUG_BASEFRAMEWORK
DEL_MDEBUG(this)
#endif
}
WebsocketServer* GetServer(void)
{
return m_server;
}
websocketpp::connection_hdl GetHdl(void)
{
return m_hdl;
}
private:
WsConnect(WsConnect& ref) {}
WsConnect& operator=(WsConnect& ref) { return *this; }
protected:
WebsocketServer* m_server;
websocketpp::connection_hdl m_hdl;
};
void OnOpen(WebsocketServer *server, websocketpp::connection_hdl hdl)
{
boost::shared_ptr<WsConnect> wsconnSmartPtr(new WsConnect(server, hdl));
if (wsconnSmartPtr.get() == NULL)
return;
#ifdef SULOKI_MEMALLOCATOR_DEBUG_BASEFRAMEWORK
NEW_MDEBUG(wsconnSmartPtr.get(), "")
#endif
std::stringstream strStream;
strStream << URC_WSPATH << hdl.lock().get();
boost::shared_ptr<BaseRoot> baseSmartPtr = boost::static_pointer_cast<BaseRoot>(wsconnSmartPtr);
if (MySulokiUrcModuleInterface::GetSulokiUrcModuleInterface()->AddObject(strStream.str(), baseSmartPtr) != Suloki::SUCCESS)
{
std::cout << "AddUr error " << __FILE__ << __LINE__ << std::endl;
return;
}
std::cout << "have client connected" << std::endl;
}
void OnClose(WebsocketServer *server, websocketpp::connection_hdl hdl)
{
std::stringstream strStream;
strStream << URC_WSPATH << hdl.lock().get();
boost::shared_ptr<BaseRoot> baseSmartPtr;
if (MySulokiUrcModuleInterface::GetSulokiUrcModuleInterface()->DelObject(strStream.str(), baseSmartPtr) != Suloki::SUCCESS)
{
std::cout << "DelUr error " << __FILE__ << __LINE__ << std::endl;
return;
}
//boost::shared_ptr<WsConnect> connSmartPtr = boost::dynamic_pointer_cast<WsConnect>(baseSmartPtr);
//if (connSmartPtr.get() == NULL)
// return;
std::cout << "have client disconnected" << std::endl;
}
void AsyncFunc(SulokiContext* pContextOri, std::auto_ptr<SulokiMessage> msgSmart, SulokiContext& contextNew)//Suloki::Uint pCcontext, Suloki::Uint msgPtr, bool bTimeout)
{
std::auto_ptr<SulokiContext> contextSmart(pContextOri);
if(Suloki::Global::GetState() >= Suloki::STOP_GLOBALSTATE_BASEFRAMEWORK)
return;
//
if (!contextNew.has_b())
{
SULOKI_ERROR_LOG_BASEFRAMEWORK << "contextNew has not b field";
return;
}
//?????
if (!contextSmart->has_msgori())
{
SULOKI_ERROR_LOG_BASEFRAMEWORK << "contextSmart has not msgori field";
return;
}
if (contextNew.b())
{
std::cout << "timeout.msg info:" << contextSmart->msgori() << std::endl;// , businessid:" << contextSmart->msgori().businessid() << "; messageid:" << contextSmart->msgori().messageid() << std::endl;
return;
}
//
if (msgSmart->businessid() == SULOKI_URC_BISINESSID_PROTO && msgSmart->messageid() == SULOKI_SQL_MESSAGEID_URC_PROTO && msgSmart->messagetype() == SulokiMessage::response)
{
std::cout << "async sql query res in AsyncFunc" << std::endl;
suloki::SulokiSqlResUrcMsgBody resBody;
if(Suloki::SulokiProtoSwrap::GetBody<suloki::SulokiSqlResUrcMsgBody>(*msgSmart, resBody) != Suloki::SUCCESS)
{
SULOKI_ERROR_LOG_BASEFRAMEWORK << "GetBody SulokiSqlResUrcMsgBody error";
return;
}
for (int i = 0; i < resBody.sqlres_size(); i++)
{
const suloki::SulokiSqlResItemUrcMsgBody& bodyitem = resBody.sqlres(i);
for (int j = 0; j < bodyitem.sqlresitem_size(); j++)
;//std::cout << bodyitem.sqlresitem(j) << std::endl;
}
}
//
if (!contextSmart->has_urname())
{
std::cout << "context has not urname field error" << std::endl;
return;
}
std::string wsconnUrName = contextSmart->urname();
std::cout << "AsyncFunc,wsconnect name:" << wsconnUrName << std::endl;
std::cout << "AsyncFunc,timeout:" << contextNew.b() << std::endl;
boost::shared_ptr<BaseRoot> baseSmartPtr;
if (!(MySulokiUrcModuleInterface::GetSulokiUrcModuleInterface()->GetObject(wsconnUrName, baseSmartPtr) == Suloki::SUCCESS && baseSmartPtr.get() != NULL))
{
std::cout << "error:ws conn urname have not existed" << std::endl;
return;
}
boost::shared_ptr<WsConnect> connSmartPtr = boost::dynamic_pointer_cast<WsConnect>(baseSmartPtr);
if (connSmartPtr.get() == NULL)
return;
//connSmartPtr->GetServer()->send(connSmartPtr->GetHdl(), "test ok", websocketpp::frame::opcode::text);
/*
std::string wsconnUrName;
{//pop router
int routerSize = msgSmart->routers_size();
if (routerSize > 0)
wsconnUrName = msgSmart->routers(routerSize - 1);
//????? slow
std::vector<std::string> nameVec;
for (Suloki::Int i = 0; i < routerSize - 1; i++)
nameVec.push_back(msgSmart->routers(i));
msgSmart->clear_routers();
for (Suloki::Int i = 0; i < routerSize - 1; i++)
msgSmart->add_routers(nameVec[i]);
}
std::cout << "AsyncFunc,wsconnect name:" << wsconnUrName << std::endl;
std::cout << "AsyncFunc,timeout:" << contextNew.b() << std::endl;
boost::shared_ptr<BaseRoot> baseSmartPtr;
if (!(MySulokiUrcModuleInterface::GetSulokiUrcModuleInterface()->GetObject(wsconnUrName, baseSmartPtr) == Suloki::SUCCESS && baseSmartPtr.get() != NULL))
{
std::cout << "error:ws conn urname have not existed" << std::endl;
return;
}
boost::shared_ptr<WsConnect> connSmartPtr = boost::dynamic_pointer_cast<WsConnect>(baseSmartPtr);
if (connSmartPtr.get() == NULL)
return;
connSmartPtr->GetServer()->send(connSmartPtr->GetHdl(), "test ok", websocketpp::frame::opcode::text);
*/
}
void AsyncFuncSub(SulokiContext* pContextOri, std::auto_ptr<SulokiMessage> msgSmart, SulokiContext& contextNew)//Suloki::Uint pCcontext, Suloki::Uint msgPtr, bool bTimeout)
{
std::auto_ptr<SulokiContext> contextSmart(pContextOri);
if (Suloki::Global::GetState() >= Suloki::STOP_GLOBALSTATE_BASEFRAMEWORK)
return;
//
if (msgSmart.get() == NULL)
{
std::cout << "msgSmart is NULL error" << std::endl;
return;
}
if (msgSmart->messagetype() != SulokiMessage::push)
{
std::cout << "is not push msg type error, type:" << msgSmart->messagetype() << std::endl;
return;
}
//
if (!contextSmart->has_urname())
{
std::cout << "context has not urname field error" << std::endl;
return;
}
;
}
void OnMessage(WebsocketServer *server, websocketpp::connection_hdl hdl, message_ptr msg)
{
/*
std::string strMsg = msg->get_payload();
std::cout << strMsg << std::endl;
//
std::string strRespon = "receive: ";
strRespon.append(strMsg);
//
server->send(hdl, strRespon, websocketpp::frame::opcode::text);
*/
for (Suloki::Int i = 0; i < 1; i++)
{
Suloki::Ret ret = Suloki::SUCCESS;
{//remoted sql query sync
SulokiMessage req;
Suloki::SulokiProtoSwrap::MakeBaseMessage(req);
req.set_businessid(SULOKI_URC_BISINESSID_PROTO);
req.set_messageid(SULOKI_SQL_MESSAGEID_URC_PROTO);
req.set_messagetype(SulokiMessage::request);
req.set_sequencenumber(Suloki::IdManagerSingleton::Instance().GetFreeId());
/*
std::stringstream strStream;
strStream << URC_WSPATH << hdl.lock().get();
req.add_routers(strStream.str());
*/
suloki::SulokiSqlReqUrcMsgBody body;
body.set_urckey(Suloki::SULOKI_SQL_NAME_URC_BASE);
body.set_urcsql("select * from user_v");
Suloki::SulokiProtoSwrap::SetBody<suloki::SulokiSqlReqUrcMsgBody>(req, body);
//std::string strMsg;
//SulokiProtoSwrap::EncodeProtocol<suloki::SulokiOperatorUrcMsgBody>(req, body, strMsg);
//if (Suloki::UrcSingleton::Instance().GetUr("/remoted/sqldata", req, 1000) != Suloki::SUCCESS)
// std::cout << "sync GetUr sql data error" << std::endl;
//else
// std::cout << "sync GetUr sql data ok" << std::endl;
ret = MySulokiUrcModuleInterface::GetSulokiUrcModuleInterface()->GetSqlData("/remoted/sqldata", req, 3000);
if (ret != Suloki::SUCCESS)
std::cout << "sync GetUr sql data error, error code:" << ret << std::endl;
else
{
std::cout << "sync GetUr sql data ok" << std::endl;
suloki::SulokiSqlResUrcMsgBody resBody;
Suloki::SulokiProtoSwrap::GetBody<suloki::SulokiSqlResUrcMsgBody>(req, resBody);
for (int i = 0; i < resBody.sqlres_size(); i++)
{
const suloki::SulokiSqlResItemUrcMsgBody& bodyitem = resBody.sqlres(i);
for (int j = 0; j < bodyitem.sqlresitem_size(); j++)
;//std::cout << bodyitem.sqlresitem(j) << std::endl;
}
}
}
{//remoted sql query async
SulokiMessage req;
Suloki::SulokiProtoSwrap::MakeBaseMessage(req);
req.set_businessid(SULOKI_URC_BISINESSID_PROTO);
req.set_messageid(SULOKI_SQL_MESSAGEID_URC_PROTO);
req.set_messagetype(SulokiMessage::request);
req.set_sequencenumber(Suloki::IdManagerSingleton::Instance().GetFreeId());
//
//std::stringstream strStream;
//strStream << URC_WSPATH << hdl.lock().get();
//req.add_routers(strStream.str());
//
suloki::SulokiSqlReqUrcMsgBody body;
body.set_urckey(Suloki::SULOKI_SQL_NAME_URC_BASE);
body.set_urcsql("select * from user_v");
Suloki::SulokiProtoSwrap::SetBody<suloki::SulokiSqlReqUrcMsgBody>(req, body);
//Suloki::Urc<>::AsyncFunc asyncCb = boost::bind(&MyModuleStateMachine::AsyncFunc, this, 0, _1, _1);
std::auto_ptr<SulokiContext> contextOriSmart(new SulokiContext);
if (contextOriSmart.get() == NULL)
return;
#ifdef SULOKI_MEMALLOCATOR_DEBUG_BASEFRAMEWORK
NEW_MDEBUG(contextOriSmart.get(), "")
#endif
//?????
//SulokiMessage* pMsgBack = contextOriSmart->mutable_msgori();
//if (pMsgBack == NULL)
// return;
//Suloki::SulokiProtoSwrap::MakeSimpleCopy(req, *pMsgBack);
{
std::stringstream strStream;
strStream << "businessid:" << req.businessid() << ";messageid:" << req.messageid();
contextOriSmart->set_msgori(strStream.str());
}
std::stringstream strStream;
strStream << URC_WSPATH << hdl.lock().get();
contextOriSmart->set_urname(strStream.str());
ret = MySulokiUrcModuleInterface::GetSulokiUrcModuleInterface()->GetSqlData("/remoted/sqldata", req, 3000, AsyncFunc, contextOriSmart);
if (ret != Suloki::SUCCESS)
std::cout << "async GetUr sql data error, error code:" << ret << std::endl;
else
std::cout << "async GetUr sql data ok" << std::endl;
}
//
{//remoted nosql add sync
std::string strVal = "nosqldata_val";
ret = MySulokiUrcModuleInterface::GetSulokiUrcModuleInterface()->AddNoSqlData("/remoted/nosqldatakey", strVal, false, 5000);
if (ret != Suloki::SUCCESS)
std::cout << "sync AddUr nosql data error, error code:" << ret << std::endl;
else
std::cout << "sync AddUr nosql data ok" << std::endl;
}
{//remoted nosql get sync
std::string strVal = "";
ret = MySulokiUrcModuleInterface::GetSulokiUrcModuleInterface()->GetNoSqlData("/remoted/nosqldatakey", strVal, 8000);
if (ret != Suloki::SUCCESS)
std::cout << "sync GetUr nosql data error, error code:" << ret << std::endl;
else
std::cout << "sync GetUr nosql data ok, val=" << strVal << std::endl;
}
//
{//req to a server sync
SulokiMessage req;
Suloki::SulokiProtoSwrap::MakeBaseMessage(req);
req.set_businessid(SULOKI_SYSTEM_BISINESSID_PROTO);
req.set_messageid(SULOKI_TEST_MESSAGEID_SYSTEM_PROTO);
req.set_messagetype(SulokiMessage::request);
req.set_sequencenumber(Suloki::IdManagerSingleton::Instance().GetFreeId());
/*
std::stringstream strStream;
strStream << URC_WSPATH << hdl.lock().get();
req.add_routers(strStream.str());
*/
suloki::SulokiTestMsgBody body;
body.set_test("testreq");
Suloki::SulokiProtoSwrap::SetBody<suloki::SulokiTestMsgBody>(req, body);
ret = MySulokiUrcModuleInterface::GetSulokiUrcModuleInterface()->ReqRes("testgroup", "testserver0", req, 10000);
if (ret != Suloki::SUCCESS)
std::cout << "sync ReqRes to service error, error code:" << ret << std::endl;
else
std::cout << "sync ReqRes to service ok" << std::endl;
}
{//req to a server sync
SulokiMessage req;
Suloki::SulokiProtoSwrap::MakeBaseMessage(req);
req.set_businessid(SULOKI_SYSTEM_BISINESSID_PROTO);
req.set_messageid(SULOKI_TEST_MESSAGEID_SYSTEM_PROTO);
req.set_messagetype(SulokiMessage::request);
req.set_sequencenumber(Suloki::IdManagerSingleton::Instance().GetFreeId());
/*
std::stringstream strStream;
strStream << URC_WSPATH << hdl.lock().get();
req.add_routers(strStream.str());
*/
suloki::SulokiTestMsgBody body;
body.set_test("testreq");
Suloki::SulokiProtoSwrap::SetBody<suloki::SulokiTestMsgBody>(req, body);
ret = MySulokiUrcModuleInterface::GetSulokiUrcModuleInterface()->ReqRes("testgroup", "", req, 10000);
if (ret != Suloki::SUCCESS)
std::cout << "sync ReqRes to service error, error code:" << ret << std::endl;
else
std::cout << "sync ReqRes to service ok" << std::endl;
}
{//sub
Suloki::Ret ret = MySulokiUrcModuleInterface::GetSulokiUrcModuleInterface()->Subscribe("/remoted/nosqldatakey", "testsub", 8000);
if (ret != Suloki::SUCCESS)
std::cout << "sync Subscribe error, error code:" << ret << std::endl;
else
std::cout << "sync Subscribe ok" << std::endl;
std::string strVal = "nosqldata_val1";
ret = MySulokiUrcModuleInterface::GetSulokiUrcModuleInterface()->UpdateNoSqlData("/remoted/nosqldatakey", strVal, 8000);
if (ret != Suloki::SUCCESS)
std::cout << "sync UpdateNoSqlData data error, error code:" << ret << std::endl;
else
std::cout << "sync UpdateNoSqlData data ok, val=" << strVal << std::endl;
}
{//unsub
Suloki::Ret ret = MySulokiUrcModuleInterface::GetSulokiUrcModuleInterface()->Unsubscribe("/remoted/nosqldatakey", "testsub", 8000);
if (ret != Suloki::SUCCESS)
std::cout << "sync Unsubscribe error, error code:" << ret << std::endl;
else
std::cout << "sync Unsubscribe ok" << std::endl;
}
{//del
std::string strVal;
Suloki::Ret ret = MySulokiUrcModuleInterface::GetSulokiUrcModuleInterface()->DelNoSqlData("/remoted/nosqldatakey", strVal, 8000);
if (ret != Suloki::SUCCESS)
std::cout << "sync DelNoSqlData error, error code:" << ret << std::endl;
else
std::cout << "sync DelNoSqlData ok" << std::endl;
}
Suloki::Sleep(1000);
}
server->send(hdl, "test have completed", websocketpp::frame::opcode::text);
}
class MyModuleStateMachine : public Suloki::AppStateMachine
{
public:
MyModuleStateMachine()
{}
virtual ~MyModuleStateMachine()
{
#ifdef SULOKI_MEMALLOCATOR_DEBUG_BASEFRAMEWORK
DEL_MDEBUG(this)
#endif
}
virtual Suloki::Ret Init(void)
{
#ifdef SULOKI_WINDOWS_OS_SULOKI
Suloki::ConfigSingleton::Instance().SetConfig(Suloki::SULOKI_LOGNAME_KEY_CONFIG_BASE, "testmainmodule");
//Suloki::ConfigSingleton::Instance().SetConfig(Suloki::SULOKI_LOGLEVEL_KEY_CONFIG_BASE, Suloki::LOG_INFO_LEVEL);
try{
boost::property_tree::ptree root;
boost::property_tree::read_json<boost::property_tree::ptree>("config", root);
std::string logLevel = root.get<std::string>(Suloki::SULOKI_LOGLEVEL_KEY_CONFIG_BASE);
Suloki::ConfigSingleton::Instance().SetConfig(Suloki::SULOKI_LOGLEVEL_KEY_CONFIG_BASE, logLevel);
}
catch (boost::property_tree::ptree_error pt){
//SULOKI_ERROR_LOG_BASEFRAMEWORK << "read config error";
std::cout << "read config error" << std::endl;
return Suloki::FAIL;
}
catch (Suloki::Exception e){
//SULOKI_ERROR_LOG_BASEFRAMEWORK << "read config error," << e.what();
std::cout << "read config error," << e.what() << std::endl;
return Suloki::FAIL;
}
//
if (Suloki::AppStateMachine::Init() != 0)
{
SULOKI_ERROR_LOG_BASEFRAMEWORK << "AppStateMachine::Init error";
return Suloki::FAIL;
}
#endif
m_serverSmart = std::auto_ptr<WebsocketServer>(new WebsocketServer());
if(m_serverSmart.get() == NULL)
{
SULOKI_ERROR_LOG_BASEFRAMEWORK << "create WebsocketServer error";
return Suloki::FAIL;
}
#ifdef SULOKI_MEMALLOCATOR_DEBUG_BASEFRAMEWORK
NEW_MDEBUG(m_serverSmart.get(), "")
#endif
;
Suloki::Global::SetState(Suloki::INIT_GLOBALSTATE_BASEFRAMEWORK);
//
SULOKI_INFO_LOG_BASEFRAMEWORK << "testmainmodule init successfully";
return Suloki::SUCCESS;
}
virtual Suloki::Ret Start(void)
{
if (Suloki::AppStateMachine::Start() != 0)
{
SULOKI_ERROR_LOG_BASEFRAMEWORK << "AppStateMachine::Start() error";
return 1;
}
//
try {
// Set logging settings
m_serverSmart->set_access_channels(websocketpp::log::alevel::all);
m_serverSmart->clear_access_channels(websocketpp::log::alevel::frame_payload);
// Initialize ASIO
m_serverSmart->init_asio();
// Register our open handler
m_serverSmart->set_open_handler(bind(&OnOpen, m_serverSmart.get(), ::_1));
// Register our close handler
m_serverSmart->set_close_handler(bind(&OnClose, m_serverSmart.get(), ::_1));
// Register our message handler
m_serverSmart->set_message_handler(bind(&OnMessage, m_serverSmart.get(), ::_1, ::_2));
//Listen on port 2152
m_serverSmart->listen(9002);
//Start the server accept loop
m_serverSmart->start_accept();
}
catch (websocketpp::exception const & e) {
SULOKI_ERROR_LOG_BASEFRAMEWORK << "websocketpp::exception, " << e.what();
exit(1);
}
catch (...) {
SULOKI_ERROR_LOG_BASEFRAMEWORK << "websocketpp other exception";
exit(1);
}
;
m_threadRunnedSmart = std::auto_ptr<boost::thread>(new boost::thread(boost::bind(&MyModuleStateMachine::FuncThread, this)));
if (m_threadRunnedSmart.get() == NULL)
return Suloki::FAIL;
#ifdef SULOKI_MEMALLOCATOR_DEBUG_BASEFRAMEWORK
NEW_MDEBUG(m_threadRunnedSmart.get(), "")
#endif
;
Suloki::Global::SetState(Suloki::START_GLOBALSTATE_BASEFRAMEWORK);
SULOKI_INFO_LOG_BASEFRAMEWORK << "testmainmodule start successfully";
return Suloki::SUCCESS;
}
virtual Suloki::Ret Run(void)
{
return Suloki::SUCCESS;
}
virtual Suloki::Ret Stop(void)
{
SULOKI_INFO_LOG_BASEFRAMEWORK << "testmainmodule will stop";
//
Suloki::Global::SetState(Suloki::STOP_GLOBALSTATE_BASEFRAMEWORK);
;
m_serverSmart->stop();
//m_serverSmart.reset(NULL);
//#ifdef SULOKI_WINDOWS_OS_SULOKI
if (m_threadRunnedSmart.get() != NULL)
m_threadRunnedSmart->join();
//#endif
#ifdef SULOKI_MEMALLOCATOR_DEBUG_BASEFRAMEWORK
DEL_MDEBUG(m_serverSmart.get())
m_serverSmart.reset(NULL);
#endif
#ifdef SULOKI_MEMALLOCATOR_DEBUG_BASEFRAMEWORK
DEL_MDEBUG(m_threadRunnedSmart.get())
m_threadRunnedSmart.reset(NULL);
#endif
;
return AppStateMachine::Stop();
}
virtual Suloki::Ret Clear(void)
{
SULOKI_INFO_LOG_BASEFRAMEWORK << "testmainmodule will clear";
//
Suloki::Global::SetState(Suloki::CLEAR_GLOBALSTATE_BASEFRAMEWORK);
;
Suloki::IdManagerSingleton::Deinstance();
;
return AppStateMachine::Clear();
}
protected:
void FuncThread(void)
{
// Create a server endpoint
//server echo_server;
try {
//Start the ASIO io_service run loop
m_serverSmart->run();
}
catch (websocketpp::exception const & e) {
SULOKI_ERROR_LOG_BASEFRAMEWORK << "websocketpp::exception, " << e.what();
exit(1);
}
catch (...) {
SULOKI_ERROR_LOG_BASEFRAMEWORK << "websocketpp other exception";
exit(1);
}
}
private:
MyModuleStateMachine(MyModuleStateMachine& ref) {}
MyModuleStateMachine& operator=(MyModuleStateMachine& ref) { return *this; }
private:
std::auto_ptr<boost::thread> m_threadRunnedSmart;
std::auto_ptr<WebsocketServer> m_serverSmart;
};
typedef Suloki::Singleton<MyModuleStateMachine> MyModuleStateMachineSingleton;
class MyDispatcher : public Suloki::Dispatcher<SulokiMessage, SulokiContext>
{
public:
MyDispatcher()
{
//std::stringstream sStream;
//sStream << XHMOMSDK_SYSTEM_BUSINESSID_PROTOCOL << "_" << XHMOMSDK_TEST_MESSAGEID_PROTOCOL;
//m_syncMsgHandlerMap[sStream.str()] = HandlerFunctor(this, &MyHandler::Handler_SYSTEM_TEST1);
//m_syncMsgHandlerMap["test"] = HandlerFunctor(this, &MyDispatcher::Handler_SYSTEM_TEST1);
{
std::stringstream sStream;
sStream << SULOKI_SYSTEM_BISINESSID_PROTO << "_" << SULOKI_START_MESSAGEID_SYSTEM_PROTO;
m_syncMsgHandlerMapSimple[sStream.str()] = HandlerFunctorSimple(this, &MyDispatcher::Handler_System_Start);
}
{
std::stringstream sStream;
sStream << SULOKI_SYSTEM_BISINESSID_PROTO << "_" << SULOKI_TEST_MESSAGEID_SYSTEM_PROTO;
m_syncMsgHandlerMapSimple[sStream.str()] = HandlerFunctorSimple(this, &MyDispatcher::Handler_System_Test);
}
{
std::stringstream sStream;
sStream << SULOKI_URC_BISINESSID_PROTO << "_" << SULOKI_CONNTOURCSERVEROK_MESSAGEID_URC_PROTO;
m_syncMsgHandlerMapSimple[sStream.str()] = HandlerFunctorSimple(this, &MyDispatcher::Handler_Urc_Connok);
}
{
std::stringstream sStream;
sStream << SULOKI_URC_BISINESSID_PROTO << "_" << SULOKI_UPDATE_MESSAGEID_URC_PROTO;
m_syncMsgHandlerMapSimple[sStream.str()] = HandlerFunctorSimple(this, &MyDispatcher::Handler_Urc_Update);
}
}
virtual ~MyDispatcher()
{
#ifdef SULOKI_MEMALLOCATOR_DEBUG_BASEFRAMEWORK
DEL_MDEBUG(this)
#endif
}
//void SetSulokiUrcModuleInterface(SulokiUrcModuleInterface* pSulokiUrcModuleInterface)
//{
// m_pSulokiUrcModuleInterface = pSulokiUrcModuleInterface;
//}
protected:
virtual std::string CalKey(SulokiMessage& msg)
{
std::stringstream sStream;
sStream << msg.businessid() << "_" << msg.messageid();
return sStream.str();// protocolReq.m_msgKey;
}
virtual Suloki::Ret HandleUnmatched(SulokiMessage& msg, SulokiContext& context)
{
std::cout << "some msg have not handler, businessid:" << msg.businessid() << ";messageid:" << msg.messageid() << std::endl;
return Suloki::FAIL;
}
protected:
/*
static void AsyncFunc(SulokiContext* pContextOri, std::auto_ptr<SulokiMessage> msgSmart, SulokiContext& contextNew)//Suloki::Uint pCcontext, Suloki::Uint msgPtr, bool bTimeout)
{
std::auto_ptr<SulokiContext> contextSmart(pContextOri);
if(Suloki::Global::GetState() >= Suloki::STOP_GLOBALSTATE_BASEFRAMEWORK)
return;
if (!contextNew.has_b())
{
SULOKI_ERROR_LOG_BASEFRAMEWORK << "contextNew has not b field";
return;
}
std::cout << "AsyncFunc,timeout:" << contextNew.b() << std::endl;
}
*/
//Suloki::Ret Handler_SYSTEM_TEST1(SulokiMessage& protocolReq, SulokiContext& paraIn, SulokiMessage& protocolRes, SulokiContext& paraOut)
//{
// std::cout << "Handler_SYSTEM_TEST1" << std::endl;
// return Suloki::SUCCESS;
//}
Suloki::Ret Handler_System_Start(SulokiMessage& msg, SulokiContext& context)
{
//std::cout << "recv system start msg" << std::endl;
return Suloki::SUCCESS;
}
Suloki::Ret Handler_System_Test(SulokiMessage& msg, SulokiContext& context)
{
std::cout << "recv system test msg" << std::endl;
if (!context.has_b())
{
SULOKI_ERROR_LOG_BASEFRAMEWORK << "context has not b field";
return Suloki::FAIL;
}
if (context.b() && msg.messagetype() == SulokiMessage::request)
{
suloki::SulokiTestMsgBody body;
if(Suloki::SulokiProtoSwrap::GetBody<suloki::SulokiTestMsgBody>(msg, body) != Suloki::SUCCESS)
{
SULOKI_ERROR_LOG_BASEFRAMEWORK << "GetBody SulokiTestMsgBody error";
return Suloki::FAIL;
}
//
SulokiMessage res;
Suloki::SulokiProtoSwrap::MakeResMessage(msg, res);
res.set_errorcode(Suloki::SUCCESS);
suloki::SulokiTestMsgBody resBody;
resBody.set_test("testres");
Suloki::SulokiProtoSwrap::SetBody<suloki::SulokiTestMsgBody>(res, resBody);
//
if (!context.has_urname())
{
std::cout << "context has not urname field error" << std::endl;
return Suloki::FAIL;
}
boost::shared_ptr<BaseRoot> baseSmartPtr;
if (!(MySulokiUrcModuleInterface::GetSulokiUrcModuleInterface()->GetObject(context.urname(), baseSmartPtr) == Suloki::SUCCESS && baseSmartPtr.get() != NULL))
return Suloki::FAIL;
boost::shared_ptr<Suloki::UrcTcpConnection> connSmartPtr = boost::dynamic_pointer_cast<Suloki::UrcTcpConnection>(baseSmartPtr);
if (connSmartPtr.get() == NULL)
return Suloki::FAIL;
connSmartPtr->WriteAsync(res);// strResMsg.c_str(), strResMsg.length());
return Suloki::SUCCESS;
}
return Suloki::FAIL;
}
Suloki::Ret Handler_Urc_Connok(SulokiMessage& msg, SulokiContext& context)
{
//std::cout << "recv urc conn ok msg" << std::endl;
//Suloki::Ret ret = MySulokiUrcModuleInterface::GetSulokiUrcModuleInterface()->Subscribe(Suloki::SULOKI_SQL_NAME_URC_BASE, "sqlsub", 8000);
//if (ret != Suloki::SUCCESS)
// std::cout << "sync Subscribe " << Suloki::SULOKI_SQL_NAME_URC_BASE << " error, error code:" << ret << std::endl;
//else
// std::cout << "sync Subscribe " << Suloki::SULOKI_SQL_NAME_URC_BASE << " ok" << std::endl;
return Suloki::SUCCESS;
}
Suloki::Ret Handler_Urc_Update(SulokiMessage& msg, SulokiContext& context)
{
std::cout << "recv urc update msg" << std::endl;
if (msg.messagetype() == SulokiMessage::push)
{
std::cout << "recv urc update push msg,";
if (msg.has_urckey())
std::cout << "urc name:" << msg.urckey();
if (msg.has_urcval())
std::cout << ",urc val:" << msg.urcval();
std::cout << std::endl;
}
return Suloki::SUCCESS;
}
protected:
//SulokiUrcModuleInterface* m_pSulokiUrcModuleInterface;
};
class MySulokiHandleModule : public SulokiHandleModuleInterface
{
public:
//explicit MySulokiHandleModule(std::string moduleName){}
MySulokiHandleModule(){}
virtual ~MySulokiHandleModule()
{
#ifdef SULOKI_MEMALLOCATOR_DEBUG_BASEFRAMEWORK
DEL_MDEBUG(this)
#endif
}
//
virtual SulokiRet Init(SULOKI_IN SulokiUrcModuleInterface* pSulokiUrcModuleInterface, SULOKI_IN std::string groupName, SULOKI_IN std::string serviceName, SULOKI_IN std::string strModuleName, SULOKI_IN std::string strConfig)
{
//MySulokiUrcModuleInterface::SetSulokiUrcModuleInterface(pSulokiUrcModuleInterface);
//m_sulokiUrcModuleInterfaceSmart = sulokiUrcModuleInterfaceSmart;
//m_pSulokiUrcModuleInterface = pSulokiUrcModuleInterface;
//m_dispatcher.SetSulokiUrcModuleInterface(m_pSulokiUrcModuleInterface);
return Suloki::SUCCESS;
}
virtual SulokiRet Start(void){ return Suloki::SUCCESS; }
virtual SulokiRet TestValid(SULOKI_IN const SulokiMessage& msg){ return Suloki::SUCCESS; }
virtual SulokiRet Handle(SULOKI_IN std::auto_ptr< SulokiMessage > msgSmart, SULOKI_IN SulokiContext& context)
{
return m_dispatcher.Handle(*msgSmart, context);
}
virtual SulokiRet Stop(void){ return Suloki::SUCCESS; }
virtual SulokiRet Clear(void){ return Suloki::SUCCESS; }
//
protected:
//MySulokiHandleModule(){}
//explicit MySulokiHandleModule(std::string modulePath){}// throw(Suloki::Exception){}
private:
MySulokiHandleModule(MySulokiHandleModule& ref) {}
MySulokiHandleModule& operator=(MySulokiHandleModule& ref) { return *this; }
protected:
MyDispatcher m_dispatcher;
//std::auto_ptr<SulokiUrcModuleInterface> m_sulokiUrcModuleInterfaceSmart;
//SulokiUrcModuleInterface* m_pSulokiUrcModuleInterface;
};
typedef Suloki::Singleton<MySulokiHandleModule> MySulokiHandleModuleSingleton;
TESTMAINMODULE_API SulokiRet Init(SULOKI_IN SulokiUrcModuleInterface* pSulokiUrcModuleInterface, SULOKI_IN std::string groupName, SULOKI_IN std::string serviceName, SULOKI_IN std::string strModuleName, SULOKI_IN std::string strConfig)
{
MySulokiUrcModuleInterface::SetSulokiUrcModuleInterface(pSulokiUrcModuleInterface);
if (MyModuleStateMachineSingleton::Instance().Init() != 0)
{
SULOKI_ERROR_LOG_BASEFRAMEWORK << "MyModuleStateMachineSingleton::Instance().Init() error";
return -1;
}
//return SULOKI_SUCCESS;
return MySulokiHandleModuleSingleton::Instance().Init(pSulokiUrcModuleInterface, groupName, serviceName, strModuleName, strConfig);
}
TESTMAINMODULE_API SulokiRet Start(void)
{
if (MyModuleStateMachineSingleton::Instance().Start() != 0)
{
SULOKI_ERROR_LOG_BASEFRAMEWORK << "MyModuleStateMachineSingleton::Instance().Start() error";
return -1;
}
return MySulokiHandleModuleSingleton::Instance().Start();
}
TESTMAINMODULE_API SulokiRet TestValid(SULOKI_IN const SulokiMessage& msg)
{
return MySulokiHandleModuleSingleton::Instance().TestValid(msg);
}
TESTMAINMODULE_API SulokiRet Handle(SULOKI_IN std::auto_ptr< SulokiMessage > msgSmart, SULOKI_IN SulokiContext& context)
{
return MySulokiHandleModuleSingleton::Instance().Handle(msgSmart, context);
}
TESTMAINMODULE_API SulokiRet Stop(void)
{
MySulokiHandleModuleSingleton::Instance().Stop();
MyModuleStateMachineSingleton::Instance().Stop();
return Suloki::SUCCESS;
}
TESTMAINMODULE_API SulokiRet Clear(void)
{
MySulokiHandleModuleSingleton::Instance().Clear();
MySulokiHandleModuleSingleton::Deinstance();
MyModuleStateMachineSingleton::Instance().Clear();
MyModuleStateMachineSingleton::Deinstance();
return Suloki::SUCCESS;
}
/*
// This is an example of an exported variable
TESTMAINMODULE_API int ntestmainmodule=0;
// This is an example of an exported function.
TESTMAINMODULE_API int fntestmainmodule(void)
{
return 42;
}
// This is the constructor of a class that has been exported.
// see testmainmodule.h for the class definition
Ctestmainmodule::Ctestmainmodule()
{
return;
}
*/
|
#include "cwpch.h"
#include "Crowny/Scripting/Bindings/Utils/ScriptCompression.h"
#include <mono/metadata/object.h>
namespace Crowny
{
ScriptCompression::ScriptCompression() : ScriptObject() {}
void ScriptCompression::InitRuntimeData()
{
MetaData.ScriptClass->AddInternalCall("Internal_Compress", &ScriptCompression::Internal_Compress);
}
uint64_t ScriptCompression::Internal_Compress(MonoArray* dst, MonoArray* src, CompressionMethod method)
{
char* rawSrc = mono_array_addr(src, char, 0);
char* rawDest = mono_array_addr(dst, char, 0);
uint64_t length = mono_array_length(src);
if (length > mono_array_length(dst))
return -1;
::MonoClass* arrayClass = mono_object_get_class((MonoObject*)src);
::MonoClass* elementClass = mono_class_get_element_class(arrayClass);
// TODO: Make sure element class is a char.
CW_ENGINE_ASSERT(mono_class_array_element_size(elementClass));
uint64_t byteSize = length * mono_class_array_element_size(elementClass); // does this code even work?
return Compression::Compress((uint8_t*)rawSrc, (uint8_t*)rawDest, byteSize, method);
}
} // namespace Crowny
|
#include <EnginePCH.h>
#include "TextureDX11.h"
#include "StructuredBufferDX11.h"
#include "RenderTargetDX11.h"
RenderTargetDX11::RenderTargetDX11( ID3D11Device2* pDevice )
: m_pDevice( pDevice )
, m_Width( 0 )
, m_Height( 0 )
, m_bCheckValidity( false )
{
m_pDevice->GetImmediateContext2( &m_pDeviceContext );
m_Textures.resize( (size_t)RenderTarget::AttachmentPoint::NumAttachmentPoints + 1 );
m_StructuredBuffers.resize( 8 );
}
RenderTargetDX11::~RenderTargetDX11()
{
}
void RenderTargetDX11::AttachTexture( AttachmentPoint attachment, std::shared_ptr<Texture> texture )
{
std::shared_ptr<TextureDX11> textureDX11 = std::dynamic_pointer_cast<TextureDX11>( texture );
m_Textures[(uint8_t)attachment] = textureDX11;
// Next time the render target is "bound", check that it is valid.
m_bCheckValidity = true;
}
std::shared_ptr<Texture> RenderTargetDX11::GetTexture( AttachmentPoint attachment )
{
return m_Textures[(uint8_t)attachment];
}
void RenderTargetDX11::Clear( AttachmentPoint attachment, ClearFlags clearFlags, const glm::vec4& color, float depth, uint8_t stencil )
{
std::shared_ptr<TextureDX11> texture = m_Textures[(uint8_t)attachment];
if ( texture )
{
texture->Clear( clearFlags, color, depth, stencil );
}
}
void RenderTargetDX11::Clear( ClearFlags clearFlags, const glm::vec4& color, float depth, uint8_t stencil )
{
for ( uint8_t i = 0; i < (uint8_t)AttachmentPoint::NumAttachmentPoints; ++i )
{
Clear( (AttachmentPoint)i, clearFlags, color, depth, stencil );
}
}
void RenderTargetDX11::GenerateMipMaps()
{
for ( auto texture : m_Textures )
{
if ( texture )
{
texture->GenerateMipMaps();
}
}
}
void RenderTargetDX11::AttachStructuredBuffer( uint8_t slot, std::shared_ptr<StructuredBuffer> rwBuffer )
{
std::shared_ptr<StructuredBufferDX11> rwbufferDX11 = std::dynamic_pointer_cast<StructuredBufferDX11>( rwBuffer );
m_StructuredBuffers[slot] = rwbufferDX11;
// Next time the render target is "bound", check that it is valid.
m_bCheckValidity = true;
}
std::shared_ptr<StructuredBuffer> RenderTargetDX11::GetStructuredBuffer( uint8_t slot )
{
if ( slot < m_StructuredBuffers.size() )
{
return m_StructuredBuffers[slot];
}
return std::shared_ptr<StructuredBuffer>();
}
void RenderTargetDX11::Resize( uint16_t width, uint16_t height )
{
if ( m_Width != width || m_Height != height )
{
m_Width = glm::max<uint16_t>( width, 1 );
m_Height = glm::max<uint16_t>( height, 1 );
// Resize the attached textures.
for ( auto texture : m_Textures )
{
if ( texture )
{
texture->Resize( m_Width, m_Height );
}
}
}
}
void RenderTargetDX11::Bind()
{
if ( m_bCheckValidity )
{
if ( !IsValid() )
{
ReportError( "Invalid render target." );
}
m_bCheckValidity = false;
}
ID3D11RenderTargetView* renderTargetViews[8];
UINT numRTVs = 0;
for ( uint8_t i = 0; i < 8; i++ )
{
std::shared_ptr<TextureDX11> texture = m_Textures[i];
if ( texture )
{
renderTargetViews[numRTVs++] = texture->GetRenderTargetView();
}
}
ID3D11UnorderedAccessView* uavViews[8];
UINT uavStartSlot = numRTVs;
UINT numUAVs = 0;
for ( uint8_t i = 0; i < 8; i++ )
{
std::shared_ptr<StructuredBufferDX11> rwbuffer = m_StructuredBuffers[i];
if ( rwbuffer )
{
uavViews[numUAVs++] = rwbuffer->GetUnorderedAccessView();
}
}
ID3D11DepthStencilView* depthStencilView = nullptr;
std::shared_ptr<TextureDX11> depthTexture = m_Textures[(uint8_t)AttachmentPoint::Depth];
std::shared_ptr<TextureDX11> depthStencilTexture = m_Textures[(uint8_t)AttachmentPoint::DepthStencil];
if ( depthTexture )
{
depthStencilView = depthTexture->GetDepthStencilView();
}
else if ( depthStencilTexture )
{
depthStencilView = depthStencilTexture->GetDepthStencilView();
}
m_pDeviceContext->OMSetRenderTargetsAndUnorderedAccessViews( numRTVs, renderTargetViews, depthStencilView, uavStartSlot, numUAVs, uavViews, nullptr );
}
void RenderTargetDX11::UnBind()
{
m_pDeviceContext->OMSetRenderTargetsAndUnorderedAccessViews( 0, nullptr, nullptr, 0, 0, nullptr, nullptr );
}
bool RenderTargetDX11::IsValid() const
{
UINT numRTV = 0;
int width = -1;
int height = -1;
for ( auto texture : m_Textures )
{
if ( texture )
{
if ( texture->GetRenderTargetView() ) ++numRTV;
if ( width == -1 || height == -1 )
{
width = texture->GetWidth();
height = texture->GetHeight();
}
else
{
if ( texture->GetWidth() != width || texture->GetHeight() != height )
{
return false;
}
}
}
}
UINT numUAV = 0;
for ( auto rwBuffer : m_StructuredBuffers )
{
if ( rwBuffer )
{
++numUAV;
}
}
if ( numRTV + numUAV > 8 )
{
return false;
}
return true;
}
|
#include "ConstantPool/ConstantFloatInfo.h"
#include "ClassReader.h"
#include <sstream>
namespace Compiler
{
std::string CConstantFloatInfo::ToString() const
{
std::ostringstream oss;
oss << "ConstantFloatInfo {" << std::endl;
oss << " Bytes: " << Bytes << std::endl;
oss << "}" << std::endl;
return std::move(oss.str());
}
void CConstantFloatInfo::DeserializeFrom(CClassReader& Reader)
{
Reader >> Bytes;
}
void operator>>(CClassReader& Reader, CConstantFloatInfo& Instance)
{
Instance.DeserializeFrom(Reader);
}
}
|
/*
* 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.
*/
/*!
* Compile executable modules.
* \file driver_api.cc
*/
#include <dmlc/thread_local.h>
#include <tvm/driver/driver_api.h>
#include <tvm/ir/transform.h>
#include <tvm/runtime/registry.h>
#include <tvm/target/codegen.h>
#include <tvm/te/operation.h>
#include <tvm/tir/analysis.h>
#include <tvm/tir/transform.h>
#include <algorithm>
#include <mutex>
#include <stack>
namespace tvm {
// Register build pipeline related options
TVM_REGISTER_PASS_CONFIG_OPTION("tir.noalias", Bool);
TVM_REGISTER_PASS_CONFIG_OPTION("tir.detect_global_barrier", Bool);
TVM_REGISTER_PASS_CONFIG_OPTION("tir.instrument_bound_checkers", Bool);
TVM_REGISTER_PASS_CONFIG_OPTION("tir.disable_assert", Bool);
TVM_REGISTER_PASS_CONFIG_OPTION("tir.disable_vectorize", Bool);
TVM_REGISTER_PASS_CONFIG_OPTION("tir.add_lower_pass", Array<Array<ObjectRef>>);
using runtime::PackedFunc;
using runtime::TVMArgs;
using runtime::TVMRetValue;
bool LLVMEnabled() {
const runtime::PackedFunc* pf = runtime::Registry::Get("target.build.llvm");
return pf != nullptr;
}
/*! \return The default host target for a given device target */
Target DefaultTargetHost(Target target) {
if (target.defined() && target->kind->device_type == kDLCPU) {
return target;
} else {
if (LLVMEnabled()) {
return Target("llvm");
} else {
return Target("stackvm");
}
}
}
tir::Buffer BufferWithOffsetAlignment(Array<PrimExpr> shape, DataType dtype, std::string name,
int data_alignment, int offset_factor, bool compact) {
DataType storage_dtype = (dtype == DataType::Bool() ? DataType::Int(8) : dtype);
auto data = tir::Var(name, PointerType(PrimType(storage_dtype)));
bool has_any = false;
if (!compact) {
for (const auto& it : shape) {
if (it.as<tir::VarNode>()) {
has_any = true;
break;
}
}
}
tir::BufferType buffer_type = has_any ? tir::kAutoBroadcast : tir::kDefault;
PrimExpr elem_offset;
if (offset_factor != 0) {
elem_offset = tir::Var(name + "_elem_offset", shape[0].dtype());
} else {
elem_offset = PrimExpr();
}
return tir::Buffer(data, dtype, shape, Array<PrimExpr>(), elem_offset, name, "", data_alignment,
offset_factor, buffer_type);
}
void GetBinds(const Array<te::Tensor>& args, bool compact,
const std::unordered_map<te::Tensor, tir::Buffer>& binds,
Map<te::Tensor, tir::Buffer>* out_binds, Array<ObjectRef>* out_arg_list) {
*out_binds = binds;
for (const auto& x : args) {
if (out_binds->find(x) == out_binds->end()) {
auto buf = BufferWithOffsetAlignment(x->shape, x->dtype, x->op->name, -1, 0, compact);
out_binds->Set(x, buf);
out_arg_list->push_back(buf);
} else {
out_arg_list->push_back((*out_binds)[x]);
}
}
}
transform::Pass BindTarget(Target target) {
auto fpass = [target](tir::PrimFunc f, IRModule m, transform::PassContext ctx) {
return WithAttr(std::move(f), tvm::attr::kTarget, target);
};
return tir::transform::CreatePrimFuncPass(fpass, 0, "BindTarget", {});
}
template <typename FCond>
transform::Pass Filter(FCond fcond) {
auto fpass = [fcond](tir::PrimFunc f, IRModule m, transform::PassContext ctx) {
if (fcond(f)) {
return f;
} else {
return tir::PrimFunc(nullptr);
}
};
return tir::transform::CreatePrimFuncPass(fpass, 0, "Filter", {});
}
IRModule lower(te::Schedule sch, const Array<te::Tensor>& args, const std::string& name,
const std::unordered_map<te::Tensor, tir::Buffer>& binds) {
Array<ObjectRef> out_arg_list;
auto pass_ctx = transform::PassContext::Current();
sch = sch.normalize();
// Before TIR transformation.
auto bounds = te::InferBound(sch);
auto stmt = te::ScheduleOps(sch, bounds, false);
bool compact = te::VerifyCompactBuffer(stmt);
Map<te::Tensor, tir::Buffer> out_binds;
GetBinds(args, compact, binds, &out_binds, &out_arg_list);
// build the function
tir::PrimFunc f = te::SchedulePostProcToPrimFunc(out_arg_list, std::move(stmt), out_binds);
f = WithAttr(std::move(f), "global_symbol", runtime::String(name));
bool noalias = pass_ctx->GetConfig<Bool>("tir.noalias", Bool(true)).value();
bool disable_vectorize = pass_ctx->GetConfig<Bool>("tir.disable_vectorize", Bool(false)).value();
bool instrument_bound_checkers =
pass_ctx->GetConfig<Bool>("tir.instrument_bound_checkers", Bool(false)).value();
if (noalias) {
f = WithAttr(std::move(f), "tir.noalias", Bool(true));
}
auto mod = IRModule(Map<GlobalVar, BaseFunc>({{GlobalVar(name), f}}));
auto pass_list = Array<tvm::transform::Pass>();
// Phase 0
pass_list.push_back(tir::transform::InjectPrefetch());
pass_list.push_back(tir::transform::StorageFlatten(64, instrument_bound_checkers));
// Phase 1
pass_list.push_back(tir::transform::BF16Legalize());
pass_list.push_back(tir::transform::NarrowDataType(32));
pass_list.push_back(tir::transform::Simplify());
pass_list.push_back(tir::transform::LoopPartition());
pass_list.push_back(tir::transform::VectorizeLoop(!disable_vectorize));
pass_list.push_back(tir::transform::InjectVirtualThread());
pass_list.push_back(tir::transform::InjectDoubleBuffer());
pass_list.push_back(tir::transform::StorageRewrite());
pass_list.push_back(tir::transform::UnrollLoop());
// Phase 2
pass_list.push_back(tir::transform::Simplify());
pass_list.push_back(tir::transform::RemoveNoOp());
pass_list.push_back(tir::transform::RewriteUnsafeSelect());
if (instrument_bound_checkers) {
pass_list.push_back(tir::transform::InstrumentBoundCheckers());
}
// run
auto optimize = transform::Sequential(pass_list);
mod = optimize(std::move(mod));
return mod;
}
std::pair<IRModule, IRModule> SplitDevHostFuncs(IRModule mod_mixed, const Target& target_arg,
const Target& target_host_arg,
const transform::PassContext& pass_ctx) {
Target target = target_arg, target_host = target_host_arg;
CheckAndUpdateHostConsistency(&target, &target_host);
Array<tvm::transform::Pass> mixed_pass_list = {BindTarget(target),
tir::transform::VerifyMemory()};
if (pass_ctx->GetConfig<Bool>("tir.detect_global_barrier", Bool(false)).value()) {
mixed_pass_list.push_back(tir::transform::ThreadSync("global"));
}
mixed_pass_list.push_back(tir::transform::ThreadSync("shared"));
mixed_pass_list.push_back(tir::transform::ThreadSync("warp"));
mixed_pass_list.push_back(tir::transform::InferFragment());
mixed_pass_list.push_back(tir::transform::LowerThreadAllreduce());
if (target->GetAttr<Bool>("unpacked-api").value_or(Bool(false))) {
mixed_pass_list.push_back(tir::transform::MakeUnpackedAPI());
} else {
mixed_pass_list.push_back(tir::transform::MakePackedAPI(0));
}
mixed_pass_list.push_back(tir::transform::SplitHostDevice());
auto opt_mixed = transform::Sequential(mixed_pass_list);
mod_mixed = opt_mixed(std::move(mod_mixed));
auto host_pass_list = {
Filter([](const tir::PrimFunc& f) {
return f->GetAttr<Integer>(tvm::attr::kCallingConv, Integer(CallingConv::kDefault)) !=
CallingConv::kDeviceKernelLaunch;
}),
BindTarget(target_host),
tir::transform::LowerTVMBuiltin(),
tir::transform::LowerCustomDatatypes(),
tir::transform::LowerIntrin(),
tir::transform::LowerDeviceStorageAccessInfo(),
tir::transform::CombineContextCall(),
};
auto opt_host = transform::Sequential(host_pass_list);
ICHECK(mod_mixed.defined()) << "This module must be defined";
auto mhost = opt_host(mod_mixed);
// device pipeline
auto device_pass_list = {
Filter([](const tir::PrimFunc& f) {
return f->GetAttr<Integer>(tvm::attr::kCallingConv, Integer(CallingConv::kDefault)) ==
CallingConv::kDeviceKernelLaunch;
}),
BindTarget(target),
tir::transform::LowerWarpMemory(),
tir::transform::Simplify(),
tir::transform::LowerCustomDatatypes(),
tir::transform::LowerIntrin(),
tir::transform::LowerDeviceStorageAccessInfo(),
};
auto opt_device = transform::Sequential(device_pass_list);
auto mdevice = opt_device(mod_mixed);
// some final misc checks.
auto keys = target->GetKeys();
bool target_is_gpu = std::find(keys.begin(), keys.end(), "gpu") != keys.end();
if (target_is_gpu && mdevice->functions.size() == 0) {
LOG(WARNING) << "Specified target " << target->str()
<< " but cannot find device code. Did you forget to bind?";
}
if (target->kind->device_type == kDLCPU && target_host == target) {
ICHECK(mdevice->functions.empty()) << "No device code should be generated when target "
<< "and host_target are both llvm target."
<< "\n";
}
return {mhost, mdevice};
}
// Build for heterogeneous execution.
runtime::Module build(const Map<Target, IRModule>& inputs_arg, const Target& target_host_arg) {
auto pass_ctx = transform::PassContext::Current();
std::vector<runtime::Module> device_modules;
Map<Target, IRModule> inputs = inputs_arg;
Target target_host = target_host_arg;
// Fetch previous defined target host in targets
CheckAndUpdateHostConsistency(&inputs, &target_host);
if (!target_host.defined()) {
for (const auto& it : inputs) {
if (it.first->kind->device_type == kDLCPU || it.first->kind->device_type == kDLMicroDev) {
target_host = it.first;
break;
}
}
}
if (!target_host.defined()) {
target_host = DefaultTargetHost(target_host);
}
// Update target host for all targets
CheckAndUpdateHostConsistency(&inputs, &target_host);
IRModule mhost_all = IRModule(Map<GlobalVar, BaseFunc>());
ICHECK(mhost_all.defined()) << "The host module must be defined";
for (const auto& it : inputs) {
if (it.second.defined()) {
auto pair = SplitDevHostFuncs(it.second, it.first, target_host, pass_ctx);
auto& mhost = pair.first;
auto& mdevice = pair.second;
ICHECK(mhost.defined()) << "The split host module must be defined";
ICHECK(mhost_all.defined()) << "The host module must be defined";
mhost_all->Update(mhost);
if (mdevice->functions.size() != 0) {
device_modules.push_back(codegen::Build(mdevice, it.first));
}
}
}
runtime::Module mhost = codegen::Build(mhost_all, target_host);
// Import all modules
for (const auto& it : device_modules) {
if (it.operator->()) {
mhost.Import(it);
}
}
return mhost;
}
// Build for heterogeneous execution when target is a string.
runtime::Module build(const Map<String, IRModule>& inputs_arg, const Target& target_host_arg) {
Map<Target, IRModule> updated_inputs;
Target target_host = target_host_arg;
for (const auto& it : inputs_arg) {
Target target = Target(it.first);
CheckAndUpdateHostConsistency(&target, &target_host);
Optional<String> device = target->GetAttr<String>("device");
if (device.defined() && device.value() == "vta") {
target = Target("ext_dev");
}
updated_inputs.Set(target, it.second);
}
return build(updated_inputs, target_host);
}
// Build for homogeneous execution.
runtime::Module build(const IRModule& funcs, const Target& target_arg,
const Target& target_host_arg) {
auto target = target_arg, target_host = target_host_arg;
CheckAndUpdateHostConsistency(&target, &target_host);
Map<Target, IRModule> inputs = {{target, funcs}};
return build(inputs, target_host);
}
} // namespace tvm
|
/*
* Copyright 2013 Matthew Harvey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef GUARD_flag_set_hpp_4153674614687299
#define GUARD_flag_set_hpp_4153674614687299
/** @file
*
* @brief Provides facilities for working with sets of boolean flags.
*
* @see jewel::InvalidFlagException
*/
#include "assert.hpp"
#include "exception.hpp"
namespace jewel
{
/** @class jewel::InvalidFlagException
*
* @extends jewel::Exception
*
* Defines an exception type to be thrown when a boolean / bit flag is
* invalid is some context.
*/
/// @cond
JEWEL_DERIVED_EXCEPTION(InvalidFlagException, jewel::Exception);
/// @endcond
/**
* Provides traits used in FlagSet class template. Specialize this
* for your \e "FlagT" class (see documentation for \e FlagSet) if you want
* to use different traits than the defaults.
*/
template <typename EnumT>
struct EnumTraits
{
typedef unsigned int IntT;
};
/**
* Encapsulates a set of flags. A certain set of flags is
* defined to be relevant for this particular set, and then
* the client can switch these flags on or off, and query them,
* via a reasonably safe and intuitive interface that avoids the use of
* direct bit-twiddling, but is protected
* against accidentally switching or query flags not in the
* relevant set.
*
* This is useful in, for example, a family of widgets accepting
* a large number of options, but for which not all all options
* are relevant for all widgets. Particular widgets can
* specify that their options must be of a given instantiation
* of FlagSet.
*
* @tparam EnumT is an enum defined in client code, in which the enumerators are
* initialized with progressive powers of 2, i.e.: 1, 2, 4 etc.. Each
* enumerator represents a boolean flag. EnumT should be a plain enum,
* not an enum class.\n\n
*
* @tparam mask is an integer mask of those enumerators in EnumT that are
* considered relevant for this
* instantiation of FlagSet. E.g. suppose \e EnumT is: \n
* <b><tt> enum Color { red = 1, blue = 2, green = 4, orange = 8 };</tt></b>\n
* Then \e mask might be <em>(red | green)</em>, which
* expresses that only red and green are relevant for this instantiation
* of FlagSet.\n\n
*
* @tparam default_value determines the set of flags which an instance of this
* instantiation of FlagSet
* will hold if it is constructed with the default constructor. This must
* either
* be 0, or else be some combination of the flags in EnumT such that
* all flags are in \e mask (compilation will fail if not). If this
* template parameter is not specified, it will default to 0, so
* that a default-constructed instance will have no flags set.\n
*
* By default, the underlying integer value holding the flags is stored in
* an <em>unsigned int</em>. An alternative underlying integral type can
* be supplied be specializing EnumTraits for \e EnumT. It is the
* client's responsibility to ensure that this type will be sufficiently
* large.
*
* @see jewel::InvalidFlagException
*/
template
< typename EnumT,
typename EnumTraits<EnumT>::IntT mask,
typename EnumTraits<EnumT>::IntT default_value = 0
>
class FlagSet
{
// typedefs
public:
typedef typename EnumTraits<EnumT>::IntT IntT;
// constructors, assignment and destructor
public:
/**
* By default the flags are initialized with \e default_value.
*/
FlagSet();
FlagSet(FlagSet const&) = default;
FlagSet(FlagSet&&) = default;
FlagSet& operator=(FlagSet const&) = default;
FlagSet& operator=(FlagSet&&) = default;
// setters
public:
/**
* Set the flag given by p_flag. Only one flag should be set at a time.
* If \e p_flag is not in \e mask, then InvalidFlagException will be
* thrown.
*
* Note that if we want to pass multiple flags simultaneously (having
* ORed them together), we can still
* do so by explicitly casting from an integer to an \e EnumT. This will
* \e not throw an exception, providing all of the ORed flags lie within
* the \e mask.
*
* @returns a reference to \e *this, which enables calls to this function
* to be chained.
*/
FlagSet& set(EnumT p_flag);
/**
* Clear the flag given by p_flag.
*
* Exception throwing behaviour is exactly the same as for the \e set
* function: the caller cannot clear p_flag that is not in \e mask.
*
* @returns a reference to \e *this, which enables calls to this function
* to be chained.
*/
FlagSet& clear(EnumT p_flag);
// getters
public:
/**
* @returns \e true if e\ p_flag is set; otherwise, returns \e false.
*
* Note exception throwing behaviour is exactly the same as for the \e set
* function: the caller cannot test a flag that is not in \e mask.
*/
bool test(EnumT p_flag) const;
/**
* @returns the underlying integral representation. This could be useful
* for serialization, for example.
*/
IntT underlying() const;
// helper functions
private:
void check_flag_acceptance(EnumT p_flag) const;
// data members
private:
IntT m_value;
// compile-time assertions
private:
/**
* Ensure \e default_value is consistent with \e mask.
*/
static_assert
( (default_value & mask) || !default_value,
"default_value for FlagSet is inconconsistent with mask."
);
};
// MEMBER FUNCTION DEFINITIONS
template
< typename EnumT,
typename EnumTraits<EnumT>::IntT mask,
typename EnumTraits<EnumT>::IntT default_value
>
inline
FlagSet<EnumT, mask, default_value>::FlagSet(): m_value(default_value)
{
}
template
< typename EnumT,
typename EnumTraits<EnumT>::IntT mask,
typename EnumTraits<EnumT>::IntT default_value
>
FlagSet<EnumT, mask, default_value>&
FlagSet<EnumT, mask, default_value>::set(EnumT p_flag)
{
check_flag_acceptance(p_flag);
m_value |= p_flag;
return *this;
}
template
< typename EnumT,
typename EnumTraits<EnumT>::IntT mask,
typename EnumTraits<EnumT>::IntT default_value
>
FlagSet<EnumT, mask, default_value>&
FlagSet<EnumT, mask, default_value>::clear(EnumT p_flag)
{
check_flag_acceptance(p_flag);
m_value &= ~p_flag;
return *this;
}
template
< typename EnumT,
typename EnumTraits<EnumT>::IntT mask,
typename EnumTraits<EnumT>::IntT default_value
>
bool
FlagSet<EnumT, mask, default_value>::test(EnumT p_flag) const
{
check_flag_acceptance(p_flag);
return (m_value & p_flag) != 0;
}
template
< typename EnumT,
typename EnumTraits<EnumT>::IntT mask,
typename EnumTraits<EnumT>::IntT default_value
>
void
FlagSet<EnumT, mask, default_value>::check_flag_acceptance(EnumT p_flag) const
{
if ((p_flag | mask) != mask)
{
JEWEL_THROW
( InvalidFlagException,
"Flag not recognized by this instantiation of FlagSet."
);
}
return;
}
template
< typename EnumT,
typename EnumTraits<EnumT>::IntT mask,
typename EnumTraits<EnumT>::IntT default_value
>
inline
typename EnumTraits<EnumT>::IntT
FlagSet<EnumT, mask, default_value>::underlying() const
{
return m_value;
}
} // namespace jewel
#endif // GUARD_flag_set_hpp_4153674614687299
|
#include <vector>
#include <iostream>
#include <queue>
#include <algorithm>
#include <string>
using namespace std;
int n, m;
int map[101][101];
bool visit[101][101];
vector<pair<int, int>> dxy = { {1, 0}, {-1, 0}, {0, 1}, {0,-1} };
void bfs(int start) { //1
int cnt = 1;
queue<pair<int, int>> q;
q.push({ start, start });
visit[start][start] = true;
while (!q.empty()) {
int size = q.size();
for (int j = 0; j < size; j++) {
int dx = q.front().first;
int dy = q.front().second;
q.pop();
for (int i = 0; i < 4; i++) {
int nx = dx + dxy[i].first;
int ny = dy + dxy[i].second;
if (!visit[nx][ny] && nx > 0 && nx <= n && ny > 0 && ny <= m && map[nx][ny]) {
visit[nx][ny] = true;
q.push({ nx, ny });
}
if (nx == n && ny == m) {
cout << cnt+1;
return;
}
}
}
cnt++;
}
}
int main() {
string a;
cin >> n >> m;
vector<string> temp;
for (int i = 0; i < n; i++) {
cin >> a;
temp.push_back(a);
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
map[i][j] = temp[i-1][j-1] - '0';
}
}
bfs(1);
return 0;
}
|
#include "dragon/operators/math/elementwise_op.h"
#include "dragon/core/workspace.h"
#include "dragon/utils/math_functions.h"
namespace dragon {
#define DISPATCH_WITH_TENSOR_TYPES(name, tensor_types, X_ref) \
template <class Context> \
void name##Op<Context>::RunOnDevice() { \
DispatchHelper<tensor_types>::Call(this, X_ref); \
}
DISPATCH_WITH_TENSOR_TYPES(Ceil, dtypes::Floating, Input(0));
DISPATCH_WITH_TENSOR_TYPES(Floor, dtypes::Floating, Input(0));
DISPATCH_WITH_TENSOR_TYPES(Round, dtypes::Floating, Input(0));
DISPATCH_WITH_TENSOR_TYPES(Sqrt, dtypes::Floating, Input(0));
DISPATCH_WITH_TENSOR_TYPES(Rsqrt, dtypes::Floating, Input(0));
DISPATCH_WITH_TENSOR_TYPES(Exp, dtypes::Floating, Input(0));
DISPATCH_WITH_TENSOR_TYPES(Log, dtypes::Floating, Input(0));
DISPATCH_WITH_TENSOR_TYPES(Sin, dtypes::Floating, Input(0));
DISPATCH_WITH_TENSOR_TYPES(Cos, dtypes::Floating, Input(0));
DISPATCH_WITH_TENSOR_TYPES(Square, dtypes::Numerical, Input(0));
DISPATCH_WITH_TENSOR_TYPES(Sign, dtypes::Numerical, Input(0));
DISPATCH_WITH_TENSOR_TYPES(Abs, dtypes::Numerical, Input(0));
DISPATCH_WITH_TENSOR_TYPES(IsInf, dtypes::Floating, Input(0));
DISPATCH_WITH_TENSOR_TYPES(IsNaN, dtypes::Floating, Input(0));
DISPATCH_WITH_TENSOR_TYPES(IsFinite, dtypes::Floating, Input(0));
DISPATCH_WITH_TENSOR_TYPES(Pow, dtypes::Floating, Input(0));
DISPATCH_WITH_TENSOR_TYPES(Minimum, dtypes::Numerical, Input(0));
DISPATCH_WITH_TENSOR_TYPES(Maximum, dtypes::Numerical, Input(0));
DISPATCH_WITH_TENSOR_TYPES(BitwiseNot, dtypes::Bitwise, Input(0));
DISPATCH_WITH_TENSOR_TYPES(BitwiseAnd, dtypes::Bitwise, Input(0));
DISPATCH_WITH_TENSOR_TYPES(BitwiseOr, dtypes::Bitwise, Input(0));
DISPATCH_WITH_TENSOR_TYPES(BitwiseXor, dtypes::Bitwise, Input(0));
DISPATCH_WITH_TENSOR_TYPES(Not, dtypes::Generic, Input(0));
DISPATCH_WITH_TENSOR_TYPES(And, dtypes::Generic, Input(0));
DISPATCH_WITH_TENSOR_TYPES(Or, dtypes::Generic, Input(0));
DISPATCH_WITH_TENSOR_TYPES(Xor, dtypes::Generic, Input(0));
DISPATCH_WITH_TENSOR_TYPES(Equal, dtypes::Generic, Input(0));
DISPATCH_WITH_TENSOR_TYPES(NotEqual, dtypes::Generic, Input(0));
DISPATCH_WITH_TENSOR_TYPES(Less, dtypes::Generic, Input(0));
DISPATCH_WITH_TENSOR_TYPES(LessEqual, dtypes::Generic, Input(0));
DISPATCH_WITH_TENSOR_TYPES(Greater, dtypes::Generic, Input(0));
DISPATCH_WITH_TENSOR_TYPES(GreaterEqual, dtypes::Generic, Input(0));
#undef DISPATCH_WITH_TENSOR_TYPES
#define DEFINE_SIMPLE_UNARY_OP_IMPL(name, TOut) \
template <class Context> \
template <typename T> \
void name##Op<Context>::DoRunWithType() { \
auto &X = Input(0), *Y = Output(0); \
math::name( \
X.count(), \
X.template data<T, Context>(), \
Y->ReshapeLike(X)->template mutable_data<TOut, Context>(), \
ctx()); \
}
DEFINE_SIMPLE_UNARY_OP_IMPL(Log, T);
DEFINE_SIMPLE_UNARY_OP_IMPL(Sin, T);
DEFINE_SIMPLE_UNARY_OP_IMPL(Cos, T);
DEFINE_SIMPLE_UNARY_OP_IMPL(Square, T);
DEFINE_SIMPLE_UNARY_OP_IMPL(Abs, T);
DEFINE_SIMPLE_UNARY_OP_IMPL(IsInf, bool);
DEFINE_SIMPLE_UNARY_OP_IMPL(IsNaN, bool);
DEFINE_SIMPLE_UNARY_OP_IMPL(IsFinite, bool);
DEFINE_SIMPLE_UNARY_OP_IMPL(Not, bool);
#undef DEFINE_SIMPLE_UNARY_OP_IMPL
#define DEFINE_INPLACE_UNARY_OP_IMPL(name, TOut) \
template <class Context> \
template <typename T> \
void name##Op<Context>::DoRunWithType() { \
auto &X = Input(0), *Y = Output(0, {0}); \
math::name( \
X.count(), \
X.template data<T, Context>(), \
Y->ReshapeLike(X)->template mutable_data<TOut, Context>(), \
ctx()); \
}
DEFINE_INPLACE_UNARY_OP_IMPL(Ceil, T);
DEFINE_INPLACE_UNARY_OP_IMPL(Floor, T);
DEFINE_INPLACE_UNARY_OP_IMPL(Round, T);
DEFINE_INPLACE_UNARY_OP_IMPL(Sign, T);
DEFINE_INPLACE_UNARY_OP_IMPL(Sqrt, T);
DEFINE_INPLACE_UNARY_OP_IMPL(Rsqrt, T);
DEFINE_INPLACE_UNARY_OP_IMPL(Exp, T);
DEFINE_INPLACE_UNARY_OP_IMPL(BitwiseNot, T);
#undef DEFINE_INPLACE_UNARY_OP_IMPL
#define DEFINE_SIMPLE_BINARY_OP_IMPL(name, TOut) \
template <class Context> \
template <typename T> \
void name##Op<Context>::DoRunWithType() { \
auto &A = Input(0), &B = Input(1), *Y = Output(0); \
\
vec64_t Y_dims(A.dims()); \
if (A.dims() == B.dims()) { \
math::name( \
A.count(), \
A.template data<T, Context>(), \
B.template data<T, Context>(), \
Y->Reshape(Y_dims)->template mutable_data<TOut, Context>(), \
ctx()); \
} else if (math::utils::IsBinaryBroadcast(A.dims(), B.dims(), Y_dims)) { \
math::name( \
A.ndim(), \
A.dims().data(), \
B.ndim(), \
B.dims().data(), \
A.template data<T, Context>(), \
B.template data<T, Context>(), \
Y->Reshape(Y_dims)->template mutable_data<TOut, Context>(), \
ctx()); \
} else { \
LOG(FATAL) << "Could not broadcast together with shapes: " \
<< A.DimString() << " " << B.DimString(); \
} \
}
DEFINE_SIMPLE_BINARY_OP_IMPL(Pow, T);
DEFINE_SIMPLE_BINARY_OP_IMPL(Minimum, T);
DEFINE_SIMPLE_BINARY_OP_IMPL(Maximum, T);
DEFINE_SIMPLE_BINARY_OP_IMPL(BitwiseAnd, T);
DEFINE_SIMPLE_BINARY_OP_IMPL(BitwiseOr, T);
DEFINE_SIMPLE_BINARY_OP_IMPL(BitwiseXor, T);
DEFINE_SIMPLE_BINARY_OP_IMPL(And, bool);
DEFINE_SIMPLE_BINARY_OP_IMPL(Or, bool);
DEFINE_SIMPLE_BINARY_OP_IMPL(Xor, bool);
DEFINE_SIMPLE_BINARY_OP_IMPL(Equal, bool);
DEFINE_SIMPLE_BINARY_OP_IMPL(NotEqual, bool);
DEFINE_SIMPLE_BINARY_OP_IMPL(Less, bool);
DEFINE_SIMPLE_BINARY_OP_IMPL(LessEqual, bool);
DEFINE_SIMPLE_BINARY_OP_IMPL(Greater, bool);
DEFINE_SIMPLE_BINARY_OP_IMPL(GreaterEqual, bool);
#undef DEFINE_SIMPLE_BINARY_OP_IMPL
DEPLOY_CPU_OPERATOR(Ceil);
DEPLOY_CPU_OPERATOR(Floor);
DEPLOY_CPU_OPERATOR(Round);
DEPLOY_CPU_OPERATOR(Sqrt);
DEPLOY_CPU_OPERATOR(Rsqrt);
DEPLOY_CPU_OPERATOR(Exp);
DEPLOY_CPU_OPERATOR(Log);
DEPLOY_CPU_OPERATOR(Sin);
DEPLOY_CPU_OPERATOR(Cos);
DEPLOY_CPU_OPERATOR(Square);
DEPLOY_CPU_OPERATOR(Sign);
DEPLOY_CPU_OPERATOR(Abs);
DEPLOY_CPU_OPERATOR(IsInf);
DEPLOY_CPU_OPERATOR(IsNaN);
DEPLOY_CPU_OPERATOR(IsFinite);
DEPLOY_CPU_OPERATOR(Pow);
DEPLOY_CPU_OPERATOR(Minimum);
DEPLOY_CPU_OPERATOR(Maximum);
DEPLOY_CPU_OPERATOR(BitwiseNot);
DEPLOY_CPU_OPERATOR(BitwiseAnd);
DEPLOY_CPU_OPERATOR(BitwiseOr);
DEPLOY_CPU_OPERATOR(BitwiseXor);
DEPLOY_CPU_OPERATOR(Not);
DEPLOY_CPU_OPERATOR(And);
DEPLOY_CPU_OPERATOR(Or);
DEPLOY_CPU_OPERATOR(Xor);
DEPLOY_CPU_OPERATOR(Equal);
DEPLOY_CPU_OPERATOR(NotEqual);
DEPLOY_CPU_OPERATOR(Less);
DEPLOY_CPU_OPERATOR(LessEqual);
DEPLOY_CPU_OPERATOR(Greater);
DEPLOY_CPU_OPERATOR(GreaterEqual);
#ifdef USE_CUDA
DEPLOY_CUDA_OPERATOR(Ceil);
DEPLOY_CUDA_OPERATOR(Floor);
DEPLOY_CUDA_OPERATOR(Round);
DEPLOY_CUDA_OPERATOR(Sqrt);
DEPLOY_CUDA_OPERATOR(Rsqrt);
DEPLOY_CUDA_OPERATOR(Exp);
DEPLOY_CUDA_OPERATOR(Log);
DEPLOY_CUDA_OPERATOR(Sin);
DEPLOY_CUDA_OPERATOR(Cos);
DEPLOY_CUDA_OPERATOR(Square);
DEPLOY_CUDA_OPERATOR(Sign);
DEPLOY_CUDA_OPERATOR(Abs);
DEPLOY_CUDA_OPERATOR(IsInf);
DEPLOY_CUDA_OPERATOR(IsNaN);
DEPLOY_CUDA_OPERATOR(IsFinite);
DEPLOY_CUDA_OPERATOR(Pow);
DEPLOY_CUDA_OPERATOR(Minimum);
DEPLOY_CUDA_OPERATOR(Maximum);
DEPLOY_CUDA_OPERATOR(BitwiseNot);
DEPLOY_CUDA_OPERATOR(BitwiseAnd);
DEPLOY_CUDA_OPERATOR(BitwiseOr);
DEPLOY_CUDA_OPERATOR(BitwiseXor);
DEPLOY_CUDA_OPERATOR(Not);
DEPLOY_CUDA_OPERATOR(And);
DEPLOY_CUDA_OPERATOR(Or);
DEPLOY_CUDA_OPERATOR(Xor);
DEPLOY_CUDA_OPERATOR(Equal);
DEPLOY_CUDA_OPERATOR(NotEqual);
DEPLOY_CUDA_OPERATOR(Less);
DEPLOY_CUDA_OPERATOR(LessEqual);
DEPLOY_CUDA_OPERATOR(Greater);
DEPLOY_CUDA_OPERATOR(GreaterEqual);
#endif
OPERATOR_SCHEMA(Ceil).NumInputs(1).NumOutputs(1).AllowInplace({{0, 0}});
OPERATOR_SCHEMA(Floor).NumInputs(1).NumOutputs(1).AllowInplace({{0, 0}});
OPERATOR_SCHEMA(Round).NumInputs(1).NumOutputs(1).AllowInplace({{0, 0}});
OPERATOR_SCHEMA(Sign).NumInputs(1).NumOutputs(1).AllowInplace({{0, 0}});
OPERATOR_SCHEMA(Sqrt).NumInputs(1).NumOutputs(1).AllowInplace({{0, 0}});
OPERATOR_SCHEMA(Rsqrt).NumInputs(1).NumOutputs(1).AllowInplace({{0, 0}});
OPERATOR_SCHEMA(Exp).NumInputs(1).NumOutputs(1).AllowInplace({{0, 0}});
OPERATOR_SCHEMA(Log).NumInputs(1).NumOutputs(1).AllowInplace({{0, 0}});
OPERATOR_SCHEMA(BitwiseNot).NumInputs(1).NumOutputs(1).AllowInplace({{0, 0}});
OPERATOR_SCHEMA(Sin).NumInputs(1).NumOutputs(1);
OPERATOR_SCHEMA(Cos).NumInputs(1).NumOutputs(1);
OPERATOR_SCHEMA(Square).NumInputs(1).NumOutputs(1);
OPERATOR_SCHEMA(Abs).NumInputs(1).NumOutputs(1);
OPERATOR_SCHEMA(IsInf).NumInputs(1).NumOutputs(1);
OPERATOR_SCHEMA(IsNaN).NumInputs(1).NumOutputs(1);
OPERATOR_SCHEMA(IsFinite).NumInputs(1).NumOutputs(1);
OPERATOR_SCHEMA(Not).NumInputs(1).NumOutputs(1);
OPERATOR_SCHEMA(Pow).NumInputs(2).NumOutputs(1);
OPERATOR_SCHEMA(Minimum).NumInputs(2).NumOutputs(1);
OPERATOR_SCHEMA(Maximum).NumInputs(2).NumOutputs(1);
OPERATOR_SCHEMA(BitwiseAnd)
.NumInputs(2)
.NumOutputs(1)
.AllowInplace({{0, 0}, {1, 0}});
OPERATOR_SCHEMA(BitwiseOr).NumInputs(2).NumOutputs(1).AllowInplace({{0, 0},
{1, 0}});
OPERATOR_SCHEMA(BitwiseXor)
.NumInputs(2)
.NumOutputs(1)
.AllowInplace({{0, 0}, {1, 0}});
OPERATOR_SCHEMA(And).NumInputs(2).NumOutputs(1);
OPERATOR_SCHEMA(Or).NumInputs(2).NumOutputs(1);
OPERATOR_SCHEMA(Xor).NumInputs(2).NumOutputs(1);
OPERATOR_SCHEMA(Equal).NumInputs(2).NumOutputs(1);
OPERATOR_SCHEMA(NotEqual).NumInputs(2).NumOutputs(1);
OPERATOR_SCHEMA(Less).NumInputs(2).NumOutputs(1);
OPERATOR_SCHEMA(LessEqual).NumInputs(2).NumOutputs(1);
OPERATOR_SCHEMA(Greater).NumInputs(2).NumOutputs(1);
OPERATOR_SCHEMA(GreaterEqual).NumInputs(2).NumOutputs(1);
NO_GRADIENT(Ceil);
NO_GRADIENT(Floor);
NO_GRADIENT(Round);
NO_GRADIENT(IsInf);
NO_GRADIENT(IsNaN);
NO_GRADIENT(IsFinite);
NO_GRADIENT(BitwiseNot);
NO_GRADIENT(BitwiseAnd);
NO_GRADIENT(BitwiseOr);
NO_GRADIENT(BitwiseXor);
NO_GRADIENT(Not);
NO_GRADIENT(And);
NO_GRADIENT(Or);
NO_GRADIENT(Xor);
NO_GRADIENT(Equal);
NO_GRADIENT(NotEqual);
NO_GRADIENT(Less);
NO_GRADIENT(LessEqual);
NO_GRADIENT(Greater);
NO_GRADIENT(GreaterEqual);
} // namespace dragon
|
#include "qhotkey.h"
#include "qhotkey_p.h"
#include <QDebug>
#include <QX11Info>
#include <QThreadStorage>
#include <QTimer>
#include <X11/Xlib.h>
#include <xcb/xcb.h>
//compability to pre Qt 5.8
#ifndef Q_FALLTHROUGH
#define Q_FALLTHROUGH() (void)0
#endif
class QHotkeyPrivateX11 : public QHotkeyPrivate
{
public:
// QAbstractNativeEventFilter interface
bool nativeEventFilter(const QByteArray &eventType, void *message, long *result) Q_DECL_OVERRIDE;
protected:
// QHotkeyPrivate interface
quint32 nativeKeycode(Qt::Key keycode, bool &ok) Q_DECL_OVERRIDE;
quint32 nativeModifiers(Qt::KeyboardModifiers modifiers, bool &ok) Q_DECL_OVERRIDE;
static QString getX11String(Qt::Key keycode);
bool registerShortcut(QHotkey::NativeShortcut shortcut) Q_DECL_OVERRIDE;
bool unregisterShortcut(QHotkey::NativeShortcut shortcut) Q_DECL_OVERRIDE;
private:
static const QVector<quint32> specialModifiers;
static const quint32 validModsMask;
xcb_key_press_event_t prevHandledEvent;
xcb_key_press_event_t prevEvent;
static QString formatX11Error(Display *display, int errorCode);
class HotkeyErrorHandler
{
public:
HotkeyErrorHandler();
~HotkeyErrorHandler();
static bool hasError;
static QString errorString;
private:
XErrorHandler prevHandler;
static int handleError(Display *display, XErrorEvent *error);
};
};
NATIVE_INSTANCE(QHotkeyPrivateX11)
bool QHotkeyPrivate::isPlatformSupported()
{
return QX11Info::isPlatformX11();
}
const QVector<quint32> QHotkeyPrivateX11::specialModifiers = {0, Mod2Mask, LockMask, (Mod2Mask | LockMask)};
const quint32 QHotkeyPrivateX11::validModsMask = ShiftMask | ControlMask | Mod1Mask | Mod4Mask;
bool QHotkeyPrivateX11::nativeEventFilter(const QByteArray &eventType, void *message, long *result)
{
Q_UNUSED(eventType)
Q_UNUSED(result)
auto *genericEvent = static_cast<xcb_generic_event_t *>(message);
if (genericEvent->response_type == XCB_KEY_PRESS)
{
xcb_key_press_event_t keyEvent = *static_cast<xcb_key_press_event_t *>(message);
this->prevEvent = keyEvent;
if (this->prevHandledEvent.response_type == XCB_KEY_RELEASE)
{
if(this->prevHandledEvent.time == keyEvent.time) return false;
}
this->activateShortcut({keyEvent.detail, keyEvent.state & QHotkeyPrivateX11::validModsMask});
}
else if (genericEvent->response_type == XCB_KEY_RELEASE)
{
xcb_key_release_event_t keyEvent = *static_cast<xcb_key_release_event_t *>(message);
this->prevEvent = keyEvent;
QTimer::singleShot(50, [this, keyEvent]
{
if(this->prevEvent.time == keyEvent.time && this->prevEvent.response_type == keyEvent.response_type && this->prevEvent.detail == keyEvent.detail)
{
this->releaseShortcut({keyEvent.detail, keyEvent.state & QHotkeyPrivateX11::validModsMask});
}
});
this->prevHandledEvent = keyEvent;
}
return false;
}
QString QHotkeyPrivateX11::getX11String(Qt::Key keycode)
{
switch(keycode)
{
case Qt::Key_MediaLast :
case Qt::Key_MediaPrevious :
return QStringLiteral("XF86AudioPrev");
case Qt::Key_MediaNext :
return QStringLiteral("XF86AudioNext");
case Qt::Key_MediaPause :
case Qt::Key_MediaPlay :
case Qt::Key_MediaTogglePlayPause :
return QStringLiteral("XF86AudioPlay");
case Qt::Key_MediaRecord :
return QStringLiteral("XF86AudioRecord");
case Qt::Key_MediaStop :
return QStringLiteral("XF86AudioStop");
default :
return QKeySequence(keycode).toString(QKeySequence::NativeText);
}
}
quint32 QHotkeyPrivateX11::nativeKeycode(Qt::Key keycode, bool &ok)
{
QString keyString = getX11String(keycode);
KeySym keysym = XStringToKeysym(keyString.toLatin1().constData());
if (keysym == NoSymbol)
{
//not found -> just use the key
if(keycode <= 0xFFFF)
keysym = keycode;
else
return 0;
}
if(QX11Info::isPlatformX11())
{
auto res = XKeysymToKeycode(QX11Info::display(), keysym);
if(res != 0)
ok = true;
return res;
}
return 0;
}
quint32 QHotkeyPrivateX11::nativeModifiers(Qt::KeyboardModifiers modifiers, bool &ok)
{
quint32 nMods = 0;
if (modifiers & Qt::ShiftModifier)
nMods |= ShiftMask;
if (modifiers & Qt::ControlModifier)
nMods |= ControlMask;
if (modifiers & Qt::AltModifier)
nMods |= Mod1Mask;
if (modifiers & Qt::MetaModifier)
nMods |= Mod4Mask;
ok = true;
return nMods;
}
bool QHotkeyPrivateX11::registerShortcut(QHotkey::NativeShortcut shortcut)
{
Display *display = QX11Info::display();
if(!display || !QX11Info::isPlatformX11())
return false;
HotkeyErrorHandler errorHandler;
for(quint32 specialMod : QHotkeyPrivateX11::specialModifiers)
{
XGrabKey(display,
shortcut.key,
shortcut.modifier | specialMod,
DefaultRootWindow(display),
True,
GrabModeAsync,
GrabModeAsync);
}
XSync(display, False);
if(errorHandler.hasError)
{
error = errorHandler.errorString;
this->unregisterShortcut(shortcut);
return false;
}
return true;
}
bool QHotkeyPrivateX11::unregisterShortcut(QHotkey::NativeShortcut shortcut)
{
Display *display = QX11Info::display();
if(!display)
return false;
HotkeyErrorHandler errorHandler;
for(quint32 specialMod : QHotkeyPrivateX11::specialModifiers)
{
XUngrabKey(display,
shortcut.key,
shortcut.modifier | specialMod,
XDefaultRootWindow(display));
}
XSync(display, False);
if(HotkeyErrorHandler::hasError)
{
error = HotkeyErrorHandler::errorString;
return false;
}
return true;
}
QString QHotkeyPrivateX11::formatX11Error(Display *display, int errorCode)
{
char errStr[256];
XGetErrorText(display, errorCode, errStr, 256);
return QString::fromLatin1(errStr);
}
// ---------- QHotkeyPrivateX11::HotkeyErrorHandler implementation ----------
bool QHotkeyPrivateX11::HotkeyErrorHandler::hasError = false;
QString QHotkeyPrivateX11::HotkeyErrorHandler::errorString;
QHotkeyPrivateX11::HotkeyErrorHandler::HotkeyErrorHandler()
{
prevHandler = XSetErrorHandler(&HotkeyErrorHandler::handleError);
}
QHotkeyPrivateX11::HotkeyErrorHandler::~HotkeyErrorHandler()
{
XSetErrorHandler(prevHandler);
hasError = false;
errorString.clear();
}
int QHotkeyPrivateX11::HotkeyErrorHandler::handleError(Display *display, XErrorEvent *error)
{
switch (error->error_code)
{
case BadAccess:
case BadValue:
case BadWindow:
if (error->request_code == 33 || //grab key
error->request_code == 34) // ungrab key
{
hasError = true;
errorString = QHotkeyPrivateX11::formatX11Error(display, error->error_code);
return 1;
}
Q_FALLTHROUGH();
// fall through
default:
return 0;
}
}
|
/**
* Copyright (c) 2015 Parrot S.A.
* 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 Parrot 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 PARROT COMPANY 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 <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
#include <unistd.h>
#include <assert.h>
#include <sys/stat.h>
#include "futils/timetools.h"
#include "libtelemetry.hpp"
#define DEFAULT_ROOT_DIR "/var/lib/tlm-logger"
/** */
static volatile bool running = true;
/** */
class MyLoggerCb : public telemetry::LoggerCb {
private:
typedef std::map<std::string, FILE *> LogFileMap;
typedef std::map<std::string, int> IndexMap;
telemetry::Logger *mLogger;
std::string mRootDir;
LogFileMap mLogFileMap;
IndexMap mIndexMap;
std::string getLogFilePath(const std::string §ion);
void openLogFile(const std::string §ion);
void closeLogFile(const std::string §ion);
public:
inline MyLoggerCb(telemetry::Logger *logger, const std::string &rootDir)
: mLogger(logger), mRootDir(rootDir) {}
virtual ~MyLoggerCb();
virtual void sectionAdded(uint32_t sectionId);
virtual void sectionRemoved(uint32_t sectionId);
virtual void sectionChanged(uint32_t sectionId,
const void *buf, size_t len);
virtual void sampleBegin(uint32_t sectionId,
const struct timespec *timestamp,
const void *buf, size_t len);
virtual void sampleEnd(uint32_t sectionId);
virtual void sample(uint32_t sectionId,
const struct timespec *timestamp,
uint32_t varId,
const telemetry::VarDesc &varDesc,
const void *buf, size_t len);
};
/**
*/
MyLoggerCb::~MyLoggerCb()
{
while (mLogFileMap.size() != 0) {
closeLogFile(mLogFileMap.begin()->first);
}
}
/**
*/
std::string MyLoggerCb::getLogFilePath(const std::string §ion)
{
/* Append '/' to root directory if needed, then file name */
std::string path = mRootDir;
if (path.size() > 0 && path[path.size() - 1] != '/')
path += "/";
/* Append pid to simulate a dirty log rotation... */
return path + section + ".log." + std::to_string(getpid());
}
/**
*/
void MyLoggerCb::openLogFile(const std::string §ion)
{
std::string path = getLogFilePath(section);
fprintf(stdout, "Opening log file '%s'\n", path.c_str());
FILE *file = fopen(path.c_str(), "wb");
mLogFileMap.insert(LogFileMap::value_type(section, file));
mIndexMap.insert(IndexMap::value_type(section, 0));
}
/**
*/
void MyLoggerCb::closeLogFile(const std::string §ion)
{
LogFileMap::iterator it = mLogFileMap.find(section);
if (it != mLogFileMap.end()) {
FILE *file = it->second;
if (file != NULL) {
std::string path = getLogFilePath(section);
fprintf(stdout, "Closing log file '%s'\n", path.c_str());
fclose(file);
}
mLogFileMap.erase(it);
}
IndexMap::iterator it2 = mIndexMap.find(section);
if (it2 != mIndexMap.end())
mIndexMap.erase(it2);
}
/**
*/
void MyLoggerCb::sectionAdded(uint32_t sectionId)
{
const std::string §ion = mLogger->getSection(sectionId);
fprintf(stdout, "sectionAdded '%s'\n", section.c_str());
/* Wait for sectionChanged to open log file and write header */
}
/**
*/
void MyLoggerCb::sectionRemoved(uint32_t sectionId)
{
const std::string §ion = mLogger->getSection(sectionId);
fprintf(stdout, "sectionRemoved '%s'\n", section.c_str());
closeLogFile(section);
}
/**
*/
void MyLoggerCb::sectionChanged(uint32_t sectionId, const void *buf, size_t len)
{
const std::string §ion = mLogger->getSection(sectionId);
fprintf(stdout, "sectionChanged '%s'\n", section.c_str());
/* Reopen log file */
closeLogFile(section);
openLogFile(section);
FILE *file = mLogFileMap[section];
if (file == NULL)
return;
/* Write header */
fprintf(file, "-- Build infos\n");
fprintf(file, "product: BebopDrone\n");
fprintf(file, "name: bebop\n");
fprintf(file, "version: 1.0\n");
fprintf(file, "date: 01/01/1970\n");
fprintf(file, "time: 00:00\n");
fprintf(file, "compiler: gcc\n");
fprintf(file, "-- Navdata infos\n");
uint32_t varCount = mLogger->getVarCount(sectionId);
/* Determine number of entries (expanding arrays), index and timeStamp
* are always added */
uint32_t entryCount = 2;
for (uint32_t i = 0; i < varCount; i++) {
const telemetry::VarDesc &varDesc = mLogger->getVarDesc(sectionId, i);
entryCount += varDesc.getCount();
}
fprintf(file, "nentries: %d\n", entryCount);
fprintf(file, "datasize: 8\n");
/* Names */
fprintf(file, "titles: index, time_s");
for (uint32_t i = 0; i < varCount; i++) {
const telemetry::VarDesc &varDesc = mLogger->getVarDesc(sectionId, i);
if (varDesc.getCount() == 1) {
fprintf(file, ", %s", varDesc.getName().c_str());
} else {
for (uint32_t j = 0; j < varDesc.getCount(); j++) {
fprintf(file, ", %s%d", varDesc.getName().c_str(), j);
}
}
}
fprintf(file, "\n");
fprintf(file, "-- Data\n");
}
/**
*/
void MyLoggerCb::sampleBegin(uint32_t sectionId,
const struct timespec *timestamp,
const void *buf, size_t len)
{
const std::string §ion = mLogger->getSection(sectionId);
FILE *file = mLogFileMap[section];
if (file == NULL)
return;
uint64_t ts = 0;
time_timespec_to_us(timestamp, &ts);
double data[2] = {(double)mIndexMap[section]++, (double)ts / (1000 * 1000) };
if (fwrite(data, sizeof(data), 1, file) != 1)
fprintf(stderr, "fwrite: err=%d (%s)\n", errno, strerror(errno));
}
/**
*/
void MyLoggerCb::sampleEnd(uint32_t sectionId)
{
}
/**
*/
template<typename T>
static double convertToDouble(const void *buf, size_t len)
{
assert(len >= sizeof(T));
T val;
memcpy(&val, buf, sizeof(T));
return (double)val;
}
/**
*/
void MyLoggerCb::sample(uint32_t sectionId,
const struct timespec *timestamp,
uint32_t varId,
const telemetry::VarDesc &varDesc,
const void *buf, size_t len)
{
const std::string §ion = mLogger->getSection(sectionId);
FILE *file = mLogFileMap[section];
if (file == NULL)
return;
/* Convert each variable to a 'double'*/
const uint8_t *ptr = (const uint8_t *)buf;
size_t off = 0;
for (uint32_t i = 0; i < varDesc.getCount(); i++) {
double data = 0.0;
switch (varDesc.getType()) {
case TLM_TYPE_BOOL:
data = convertToDouble<uint8_t>(ptr, len - off);
break;
case TLM_TYPE_UINT8:
data = convertToDouble<uint8_t>(ptr, len - off);
break;
case TLM_TYPE_INT8:
data = convertToDouble<int8_t>(ptr, len - off);
break;
case TLM_TYPE_UINT16:
data = convertToDouble<uint16_t>(ptr, len - off);
break;
case TLM_TYPE_INT16:
data = convertToDouble<int16_t>(ptr, len - off);
break;
case TLM_TYPE_UINT32:
data = convertToDouble<uint32_t>(ptr, len - off);
break;
case TLM_TYPE_INT32:
data = convertToDouble<int32_t>(ptr, len - off);
break;
case TLM_TYPE_UINT64:
data = convertToDouble<uint64_t>(ptr, len - off);
break;
case TLM_TYPE_INT64:
data = convertToDouble<int64_t>(ptr, len - off);
break;
case TLM_TYPE_FLOAT32:
data = convertToDouble<float>(ptr, len - off);
break;
case TLM_TYPE_FLOAT64:
data = convertToDouble<double>(ptr, len - off);
break;
case TLM_TYPE_STRING:
/* Not supported in bbx format */
data = 0.0;
break;
case TLM_TYPE_BINARY:
/* Not supported in bbx format */
data = 0.0;
break;
case TLM_TYPE_INVALID: /* NO BREAK */
default:
data = 0.0;
break;
}
if (fwrite(&data, sizeof(double), 1, file) != 1) {
fprintf(stderr, "fwrite: err=%d (%s)\n", errno,
strerror(errno));
}
/* Advance buffer to next element in case of array */
ptr += varDesc.getSize();
off += varDesc.getSize();
}
}
/**
*/
static void usage(const char *progname)
{
fprintf(stderr, "usage: %s [<rootdir>]\n", progname);
fprintf(stderr, "Continuously log the contents of all active shared\n");
fprintf(stderr, "memory sections in log files in bbx format\n");
fprintf(stderr, "\n");
fprintf(stderr, "<rootdir>: root directory where to save logs.\n");
fprintf(stderr, " default is '%s'\n", DEFAULT_ROOT_DIR);
fprintf(stderr, "\n");
}
/**
*/
int main(int argc, char *argv[])
{
signal(SIGINT, [](int signo){running = false;});
signal(SIGTERM, [](int signo){running = false;});
/* Check for help */
if (argc >= 2 && (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0)) {
usage(argv[0]);
exit(EXIT_SUCCESS);
}
/* Determine root directory */
std::string rootDir = DEFAULT_ROOT_DIR;
if (argc >= 2)
rootDir = argv[1];
fprintf(stdout, "root directory is '%s'\n", rootDir.c_str());
/* Create root directory (not recursive) */
if (mkdir(rootDir.c_str(), 0755) < 0 && errno != EEXIST) {
fprintf(stderr, "Failed to create root directory '%s': err=%d(%s)\n",
rootDir.c_str(), errno, strerror(errno));
exit(EXIT_FAILURE);
}
/* Create logger */
telemetry::Logger *logger = telemetry::Logger::create();
MyLoggerCb cb(logger, rootDir);
/* Read samples every seconds */
while (running) {
logger->fetchNextSamples(&cb);
usleep(1000 * 1000);
}
/* Free resources */
telemetry::Logger::release(logger);
return 0;
}
|
#include "Display.h"
const double Display::LOGIC_VIEWPORT_SIZE_MUL = 2;
Display::Display()
{
}
Display::~Display()
{
}
void Display::draw()
{
// Render into buffer:
for (int x = 0; x < mViewportSize.width; x++) {
for (int y = 0; y < mViewportSize.height; y++) {
double shaderX = (static_cast<double>(x) - mViewportOrigin.x) / mViewportSize.width * 2 * LOGIC_VIEWPORT_SIZE_MUL;
double shaderY = ((mViewportSize.height - static_cast<double>(y)) - mViewportOrigin.y) / mViewportSize.height * 2 * LOGIC_VIEWPORT_SIZE_MUL;
char c = mShader(shaderX, shaderY);
mBuffer[y][x] = c;
}
}
// Print buffer:
for (int y = 0; y < mViewportSize.height; y++) {
std::cout << mBuffer[y] << '\n';
}
std::cout << std::flush;
}
|
/**
* @file arc.cpp
* @author Petr Vana
* @brief Arc is a basic segment in Dubins maneuver
*/
#include "arc.h"
namespace opendubins {
State Arc::getState(double len) const {
return getStateByAngle(len * sgn(angle) / radius);
}
StateAtDistance Arc::getClosestStateAndDistance(const Point &p) const {
StateAtDistance ret;
// start state
ret.state = state;
ret.distance = 0;
// end state
auto end = getEnd();
if (end.point.distance(p) < ret.state.point.distance(p)) {
ret.state = end;
ret.distance = getLength();
}
// center state
if (angle > 0) { // left turn
auto dir = (p - getCenter()).left().getAngle();
auto turn = angleToLeft(state.ang, dir);
auto turnLen = turn * radius;
if (turnLen < getLength()) {
auto actPos = getState(turnLen);
if (actPos.point.distance(p) < ret.state.point.distance(p)) {
ret.state = actPos;
ret.distance = turnLen;
}
}
} else { // right turn
auto dir = (p - getCenter()).right().getAngle();
auto turn = angleToRight(state.ang, dir);
auto turnLen = -turn * radius;
if (turnLen < getLength()) {
auto actPos = getState(turnLen);
if (actPos.point.distance(p) < ret.state.point.distance(p)) {
ret.state = actPos;
ret.distance = turnLen;
}
}
}
return ret;
}
StateAtDistance Arc::intersectionPoint(const Line &line) const {
double rad = getLength() + line.getLength();
if ((state.point - line.p1).lengthSquared() > rad * rad) {
return StateAtDistance(State(), 0);
}
// calculate two points of intersection
Vector dir = line.getDirection().normalize();
Vector normal = dir.left();
double distance = normal.dotProduct(getCenter() - line.p1);
// vector to closest point on line from center of arc
Vector vDistance = -distance * normal;
if (distance > radius) {
return StateAtDistance(State(), 0);
}
double tangentAngle = vDistance.getAngle() + (angle > 0 ? M_PI / 2 : -M_PI / 2);
double diffAngle = acos(fabs(distance) / radius);
double ang1 = tangentAngle + diffAngle;
double ang2 = tangentAngle - diffAngle;
if (angle > 0) { // left
double turn1 = angleToLeft(state.ang, ang1);
double turn2 = angleToLeft(state.ang, ang2);
double less = std::min(turn1, turn2);
double more = std::max(turn1, turn2);
if (less <= angle) {
State p = getStateByAngle(less);
double dist = dir.dotProduct(p.point - line.p1);
if (dist >= 0 && dist < line.getDirection().length()) {
return StateAtDistance(p, less * radius);
}
if (more <= angle) {
p = getStateByAngle(more);
dist = dir.dotProduct(p.point - line.p1);
if (dist >= 0 && dist < line.getDirection().length()) {
return StateAtDistance(p, more * radius);
}
}
}
} else {
double turn1 = angleToRight(state.ang, ang1);
double turn2 = angleToRight(state.ang, ang2);
double less = std::max(turn1, turn2);
double more = std::min(turn1, turn2);
if (less >= angle) {
State p = getStateByAngle(less);
double dist = dir.dotProduct(p.point - line.p1);
if (dist >= 0 && dist < line.getDirection().length()) {
return StateAtDistance(p, less * -radius);
}
if (more >= angle) {
p = getStateByAngle(more);
dist = dir.dotProduct(p.point - line.p1);
if (dist >= 0 && dist < line.getDirection().length()) {
return StateAtDistance(p, more * -radius);
}
}
}
}
// todo - try to refactor
return StateAtDistance(State(), 0);
}
Point Arc::getCenter() const {
Point center = state.point;
Vector toCenter = state.getNormalizedDirection().left();
toCenter *= radius;
if (angle < 0) {
toCenter *= -1;
}
center += toCenter;
return center;
}
State Arc::getStateByAngle(double arcAngle) const {
Point center = getCenter();
Vector dir = state.getNormalizedDirection() * radius;
Vector norm = state.point - center;
double aa = std::fabs(arcAngle);
center += dir * std::sin(aa);
center += norm * std::cos(aa);
return State(center, state.ang + arcAngle);
}
State Arc::getEnd() const {
return getStateByAngle(angle);
}
}
|
/*=========================================================================
*
* Copyright UMC Utrecht and contributors
*
* 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.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef itkPCAMetric_F_multithreaded_hxx
#define itkPCAMetric_F_multithreaded_hxx
#include "itkPCAMetric_F_multithreaded.h"
#include "itkMersenneTwisterRandomVariateGenerator.h"
#include <vnl/algo/vnl_matrix_update.h>
#include "itkImage.h"
#include <vnl/algo/vnl_svd.h>
#include <vnl/vnl_trace.h>
#include <vnl/algo/vnl_symmetric_eigensystem.h>
#include <numeric>
#include <fstream>
#ifdef ELASTIX_USE_OPENMP
# include <omp.h>
#endif
namespace itk
{
/**
* ******************* Constructor *******************
*/
template <class TFixedImage, class TMovingImage>
PCAMetric<TFixedImage, TMovingImage>::PCAMetric()
{
this->SetUseImageSampler(true);
this->SetUseFixedImageLimiter(false);
this->SetUseMovingImageLimiter(false);
// Multi-threading structs
this->m_PCAMetricGetSamplesPerThreadVariables = nullptr;
this->m_PCAMetricGetSamplesPerThreadVariablesSize = 0;
/** Initialize the m_ParzenWindowHistogramThreaderParameters. */
this->m_PCAMetricThreaderParameters.m_Metric = this;
} // end constructor
/**
* ******************* Destructor *******************
*/
template <class TFixedImage, class TMovingImage>
PCAMetric<TFixedImage, TMovingImage>::~PCAMetric()
{
delete[] this->m_PCAMetricGetSamplesPerThreadVariables;
} // end Destructor
/**
* ******************* Initialize *******************
*/
template <class TFixedImage, class TMovingImage>
void
PCAMetric<TFixedImage, TMovingImage>::Initialize()
{
/** Initialize transform, interpolator, etc. */
Superclass::Initialize();
/** Retrieve slowest varying dimension and its size. */
this->m_LastDimIndex = this->GetFixedImage()->GetImageDimension() - 1;
this->m_G = this->GetFixedImage()->GetLargestPossibleRegion().GetSize(m_LastDimIndex);
if (this->m_NumEigenValues > this->m_G)
{
std::cerr << "ERROR: Number of eigenvalues is larger than number of images. Maximum number of eigenvalues equals: "
<< this->m_G << std::endl;
}
} // end Initializes
/**
* ******************* PrintSelf *******************
*/
template <class TFixedImage, class TMovingImage>
void
PCAMetric<TFixedImage, TMovingImage>::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
} // end PrintSelf
/**
* ********************* InitializeThreadingParameters ****************************
*/
template <class TFixedImage, class TMovingImage>
void
PCAMetric<TFixedImage, TMovingImage>::InitializeThreadingParameters() const
{
const ThreadIdType numberOfThreads = Self::GetNumberOfWorkUnits();
/** Resize and initialize the threading related parameters.
* The SetSize() functions do not resize the data when this is not
* needed, which saves valuable re-allocation time.
* Filling the potentially large vectors is performed later, in each thread,
* which has performance benefits for larger vector sizes.
*/
/** Only resize the array of structs when needed. */
if (this->m_PCAMetricGetSamplesPerThreadVariablesSize != numberOfThreads)
{
delete[] this->m_PCAMetricGetSamplesPerThreadVariables;
this->m_PCAMetricGetSamplesPerThreadVariables = new AlignedPCAMetricGetSamplesPerThreadStruct[numberOfThreads];
this->m_PCAMetricGetSamplesPerThreadVariablesSize = numberOfThreads;
}
/** Some initialization. */
for (ThreadIdType i = 0; i < numberOfThreads; ++i)
{
this->m_PCAMetricGetSamplesPerThreadVariables[i].st_NumberOfPixelsCounted = NumericTraits<SizeValueType>::Zero;
this->m_PCAMetricGetSamplesPerThreadVariables[i].st_Derivative.SetSize(this->GetNumberOfParameters());
}
this->m_PixelStartIndex.resize(numberOfThreads);
} // end InitializeThreadingParameters()
/**
* *************** EvaluateTransformJacobianInnerProduct ****************
*/
template <class TFixedImage, class TMovingImage>
void
PCAMetric<TFixedImage, TMovingImage>::EvaluateTransformJacobianInnerProduct(
const TransformJacobianType & jacobian,
const MovingImageDerivativeType & movingImageDerivative,
DerivativeType & imageJacobian) const
{
using JacobianIteratorType = typename TransformJacobianType::const_iterator;
JacobianIteratorType jac = jacobian.begin();
imageJacobian.Fill(0.0);
for (unsigned int dim = 0; dim < FixedImageDimension; ++dim)
{
const double imDeriv = movingImageDerivative[dim];
for (auto & imageJacobianElement : imageJacobian)
{
imageJacobianElement += (*jac) * imDeriv;
++jac;
}
}
} // end EvaluateTransformJacobianInnerProduct()
/**
* ******************* GetValue *******************
*/
template <class TFixedImage, class TMovingImage>
auto
PCAMetric<TFixedImage, TMovingImage>::GetValue(const TransformParametersType & parameters) const -> MeasureType
{
itkDebugMacro("GetValue( " << parameters << " ) ");
/** Call non-thread-safe stuff, such as:
* this->SetTransformParameters( parameters );
* this->GetImageSampler()->Update();
* Because of these calls GetValueAndDerivative itself is not thread-safe,
* so cannot be called multiple times simultaneously.
* This is however needed in the CombinationImageToImageMetric.
* In that case, you need to:
* - switch the use of this function to on, using m_UseMetricSingleThreaded = true
* - call BeforeThreadedGetValueAndDerivative once (single-threaded) before
* calling GetValueAndDerivative
* - switch the use of this function to off, using m_UseMetricSingleThreaded = false
* - Now you can call GetValueAndDerivative multi-threaded.
*/
this->BeforeThreadedGetValueAndDerivative(parameters);
/** Initialize some variables */
this->m_NumberOfPixelsCounted = 0;
MeasureType measure = NumericTraits<MeasureType>::Zero;
/** Update the imageSampler and get a handle to the sample container. */
ImageSampleContainerPointer sampleContainer = this->GetImageSampler()->GetOutput();
/** Create iterator over the sample container. */
typename ImageSampleContainerType::ConstIterator fiter;
typename ImageSampleContainerType::ConstIterator fbegin = sampleContainer->Begin();
typename ImageSampleContainerType::ConstIterator fend = sampleContainer->End();
/** The rows of the ImageSampleMatrix contain the samples of the images of the stack */
const unsigned int numberOfSamples = sampleContainer->Size();
MatrixType datablock(numberOfSamples, this->m_G);
/** Initialize dummy loop variable */
unsigned int pixelIndex = 0;
/** Initialize image sample matrix . */
datablock.fill(itk::NumericTraits<RealType>::Zero);
for (fiter = fbegin; fiter != fend; ++fiter)
{
/** Read fixed coordinates. */
FixedImagePointType fixedPoint = (*fiter).Value().m_ImageCoordinates;
/** Transform sampled point to voxel coordinates. */
FixedImageContinuousIndexType voxelCoord;
this->GetFixedImage()->TransformPhysicalPointToContinuousIndex(fixedPoint, voxelCoord);
unsigned int numSamplesOk = 0;
/** Loop over t */
for (unsigned int d = 0; d < this->m_G; ++d)
{
/** Initialize some variables. */
RealType movingImageValue;
/** Set fixed point's last dimension to lastDimPosition. */
voxelCoord[this->m_LastDimIndex] = d;
/** Transform sampled point back to world coordinates. */
this->GetFixedImage()->TransformContinuousIndexToPhysicalPoint(voxelCoord, fixedPoint);
/** Transform point. */
const MovingImagePointType mappedPoint = this->TransformPoint(fixedPoint);
/** Check if the point is inside the moving mask. */
bool sampleOk = this->IsInsideMovingMask(mappedPoint);
if (sampleOk)
{
sampleOk = this->Superclass::EvaluateMovingImageValueAndDerivative(mappedPoint, movingImageValue, nullptr);
}
if (sampleOk)
{
numSamplesOk++;
datablock(pixelIndex, d) = movingImageValue;
}
} /** end loop over t */
if (numSamplesOk == this->m_G)
{
pixelIndex++;
this->m_NumberOfPixelsCounted++;
}
} /** end first loop over image sample container */
/** Check if enough samples were valid. */
this->CheckNumberOfSamples(numberOfSamples, this->m_NumberOfPixelsCounted);
MatrixType A(datablock.extract(this->m_NumberOfPixelsCounted, this->m_G));
/** Calculate mean of from columns */
vnl_vector<RealType> mean(this->m_G);
mean.fill(NumericTraits<RealType>::Zero);
for (unsigned int i = 0; i < this->m_NumberOfPixelsCounted; ++i)
{
for (unsigned int j = 0; j < this->m_G; ++j)
{
mean(j) += A(i, j);
}
}
mean /= RealType(this->m_NumberOfPixelsCounted);
MatrixType Amm(this->m_NumberOfPixelsCounted, this->m_G);
Amm.fill(NumericTraits<RealType>::Zero);
for (unsigned int i = 0; i < this->m_NumberOfPixelsCounted; ++i)
{
for (unsigned int j = 0; j < this->m_G; ++j)
{
Amm(i, j) = A(i, j) - mean(j);
}
}
/** Compute covariance matrix C */
MatrixType C(Amm.transpose() * Amm);
C /= static_cast<RealType>(RealType(this->m_NumberOfPixelsCounted) - 1.0);
vnl_diag_matrix<RealType> S(this->m_G);
S.fill(NumericTraits<RealType>::Zero);
for (unsigned int j = 0; j < this->m_G; ++j)
{
S(j, j) = 1.0 / sqrt(C(j, j));
}
/** Compute correlation matrix K */
MatrixType K(S * C * S);
/** Compute first eigenvalue and eigenvector of K */
vnl_symmetric_eigensystem<RealType> eig(K);
RealType sumEigenValuesUsed = itk::NumericTraits<RealType>::Zero;
for (unsigned int i = 1; i < this->m_NumEigenValues + 1; ++i)
{
sumEigenValuesUsed += eig.get_eigenvalue(this->m_G - i);
}
measure = this->m_G - sumEigenValuesUsed;
/** Return the measure value. */
return measure;
} // end GetValue()
/**
* ******************* GetDerivative *******************
*/
template <class TFixedImage, class TMovingImage>
void
PCAMetric<TFixedImage, TMovingImage>::GetDerivative(const TransformParametersType & parameters,
DerivativeType & derivative) const
{
/** When the derivative is calculated, all information for calculating
* the metric value is available. It does not cost anything to calculate
* the metric value now. Therefore, we have chosen to only implement the
* GetValueAndDerivative(), supplying it with a dummy value variable. */
MeasureType dummyvalue = NumericTraits<MeasureType>::Zero;
this->GetValueAndDerivative(parameters, dummyvalue, derivative);
} // end GetDerivative()
/**
* ******************* GetValueAndDerivativeSingleThreaded *******************
*/
template <class TFixedImage, class TMovingImage>
void
PCAMetric<TFixedImage, TMovingImage>::GetValueAndDerivativeSingleThreaded(const TransformParametersType & parameters,
MeasureType & value,
DerivativeType & derivative) const
{
itkDebugMacro("GetValueAndDerivative( " << parameters << " ) ");
/** Initialize some variables */
this->m_NumberOfPixelsCounted = 0;
MeasureType measure = NumericTraits<MeasureType>::Zero;
derivative = DerivativeType(this->GetNumberOfParameters());
derivative.Fill(NumericTraits<DerivativeValueType>::Zero);
/** Call non-thread-safe stuff, such as:
* this->SetTransformParameters( parameters );
* this->GetImageSampler()->Update();
* Because of these calls GetValueAndDerivative itself is not thread-safe,
* so cannot be called multiple times simultaneously.
* This is however needed in the CombinationImageToImageMetric.
* In that case, you need to:
* - switch the use of this function to on, using m_UseMetricSingleThreaded = true
* - call BeforeThreadedGetValueAndDerivative once (single-threaded) before
* calling GetValueAndDerivative
* - switch the use of this function to off, using m_UseMetricSingleThreaded = false
* - Now you can call GetValueAndDerivative multi-threaded.
*/
this->BeforeThreadedGetValueAndDerivative(parameters);
ImageSampleContainerPointer sampleContainer = this->GetImageSampler()->GetOutput();
/** Create iterator over the sample container. */
typename ImageSampleContainerType::ConstIterator fiter;
typename ImageSampleContainerType::ConstIterator fbegin = sampleContainer->Begin();
typename ImageSampleContainerType::ConstIterator fend = sampleContainer->End();
std::vector<FixedImagePointType> SamplesOK;
/** The rows of the ImageSampleMatrix contain the samples of the images of the stack */
const unsigned int numberOfSamples = sampleContainer->Size();
MatrixType datablock(numberOfSamples, this->m_G);
/** Initialize dummy loop variables */
unsigned int pixelIndex = 0;
/** Initialize image sample matrix . */
datablock.fill(itk::NumericTraits<RealType>::Zero);
for (fiter = fbegin; fiter != fend; ++fiter)
{
/** Read fixed coordinates. */
FixedImagePointType fixedPoint = (*fiter).Value().m_ImageCoordinates;
/** Transform sampled point to voxel coordinates. */
FixedImageContinuousIndexType voxelCoord;
this->GetFixedImage()->TransformPhysicalPointToContinuousIndex(fixedPoint, voxelCoord);
unsigned int numSamplesOk = 0;
/** Loop over t */
for (unsigned int d = 0; d < this->m_G; ++d)
{
/** Initialize some variables. */
RealType movingImageValue;
/** Set fixed point's last dimension to lastDimPosition. */
voxelCoord[this->m_LastDimIndex] = d;
/** Transform sampled point back to world coordinates. */
this->GetFixedImage()->TransformContinuousIndexToPhysicalPoint(voxelCoord, fixedPoint);
/** Transform point. */
const MovingImagePointType mappedPoint = this->TransformPoint(fixedPoint);
/** Check if the point is inside the moving mask. */
bool sampleOk = this->IsInsideMovingMask(mappedPoint);
if (sampleOk)
{
sampleOk = this->Superclass::EvaluateMovingImageValueAndDerivative(mappedPoint, movingImageValue, nullptr);
}
if (sampleOk)
{
numSamplesOk++;
datablock(pixelIndex, d) = movingImageValue;
} // end if sampleOk
} // end loop over t
if (numSamplesOk == this->m_G)
{
SamplesOK.push_back(fixedPoint);
pixelIndex++;
this->m_NumberOfPixelsCounted++;
}
} /** end first loop over image sample container */
/** Check if enough samples were valid. */
this->CheckNumberOfSamples(sampleContainer->Size(), this->m_NumberOfPixelsCounted);
MatrixType A(datablock.extract(this->m_NumberOfPixelsCounted, this->m_G));
/** Calculate mean of from columns */
vnl_vector<RealType> mean(this->m_G);
mean.fill(NumericTraits<RealType>::Zero);
for (unsigned int i = 0; i < this->m_NumberOfPixelsCounted; ++i)
{
for (unsigned int j = 0; j < this->m_G; ++j)
{
mean(j) += A(i, j);
}
}
mean /= RealType(this->m_NumberOfPixelsCounted);
/** Calculate standard deviation from columns */
MatrixType Amm(this->m_NumberOfPixelsCounted, this->m_G);
Amm.fill(NumericTraits<RealType>::Zero);
for (unsigned int i = 0; i < this->m_NumberOfPixelsCounted; ++i)
{
for (unsigned int j = 0; j < this->m_G; ++j)
{
Amm(i, j) = A(i, j) - mean(j);
}
}
/** Compute covariance matrix C */
MatrixType Atmm = Amm.transpose();
MatrixType C(Atmm * Amm);
C /= static_cast<RealType>(RealType(this->m_NumberOfPixelsCounted) - 1.0);
vnl_diag_matrix<RealType> S(this->m_G);
S.fill(NumericTraits<RealType>::Zero);
for (unsigned int j = 0; j < this->m_G; ++j)
{
S(j, j) = 1.0 / sqrt(C(j, j));
}
MatrixType K(S * C * S);
/** Compute first eigenvalue and eigenvector of K */
vnl_symmetric_eigensystem<RealType> eig(K);
RealType sumEigenValuesUsed = itk::NumericTraits<RealType>::Zero;
for (unsigned int i = 1; i < this->m_NumEigenValues + 1; ++i)
{
sumEigenValuesUsed += eig.get_eigenvalue(this->m_G - i);
}
MatrixType eigenVectorMatrix(this->m_G, this->m_NumEigenValues);
for (unsigned int i = 1; i < this->m_NumEigenValues + 1; ++i)
{
eigenVectorMatrix.set_column(i - 1, (eig.get_eigenvector(this->m_G - i)).normalize());
}
MatrixType eigenVectorMatrixTranspose(eigenVectorMatrix.transpose());
/** Create variables to store intermediate results in. */
TransformJacobianType jacobian;
DerivativeType dMTdmu;
DerivativeType imageJacobian(this->m_AdvancedTransform->GetNumberOfNonZeroJacobianIndices());
std::vector<NonZeroJacobianIndicesType> nzjis(this->m_G, NonZeroJacobianIndicesType());
/** Sub components of metric derivative */
vnl_diag_matrix<DerivativeValueType> dSdmu_part1(this->m_G);
/** initialize */
dSdmu_part1.fill(itk::NumericTraits<DerivativeValueType>::Zero);
for (unsigned int d = 0; d < this->m_G; ++d)
{
double S_sqr = S(d, d) * S(d, d);
double S_qub = S_sqr * S(d, d);
dSdmu_part1(d, d) = -S_qub;
}
DerivativeMatrixType vSAtmm(eigenVectorMatrixTranspose * S * Atmm);
DerivativeMatrixType CSv(C * S * eigenVectorMatrix);
DerivativeMatrixType Sv(S * eigenVectorMatrix);
DerivativeMatrixType vdSdmu_part1(eigenVectorMatrixTranspose * dSdmu_part1);
/** Second loop over fixed image samples. */
for (pixelIndex = 0; pixelIndex < SamplesOK.size(); ++pixelIndex)
{
/** Read fixed coordinates. */
FixedImagePointType fixedPoint = SamplesOK[pixelIndex];
/** Transform sampled point to voxel coordinates. */
FixedImageContinuousIndexType voxelCoord;
this->GetFixedImage()->TransformPhysicalPointToContinuousIndex(fixedPoint, voxelCoord);
for (unsigned int d = 0; d < this->m_G; ++d)
{
/** Initialize some variables. */
RealType movingImageValue;
MovingImageDerivativeType movingImageDerivative;
/** Set fixed point's last dimension to lastDimPosition. */
voxelCoord[this->m_LastDimIndex] = d;
/** Transform sampled point back to world coordinates. */
this->GetFixedImage()->TransformContinuousIndexToPhysicalPoint(voxelCoord, fixedPoint);
const MovingImagePointType mappedPoint = this->TransformPoint(fixedPoint);
this->Superclass::EvaluateMovingImageValueAndDerivative(mappedPoint, movingImageValue, &movingImageDerivative);
/** Get the TransformJacobian dT/dmu */
this->EvaluateTransformJacobian(fixedPoint, jacobian, nzjis[d]);
/** Compute the innerproduct (dM/dx)^T (dT/dmu). */
this->EvaluateTransformJacobianInnerProduct(jacobian, movingImageDerivative, imageJacobian);
/** Store values. */
dMTdmu = imageJacobian;
/** build metric derivative components */
for (unsigned int p = 0; p < nzjis[d].size(); ++p)
{
for (unsigned int z = 0; z < this->m_NumEigenValues; ++z)
{
derivative[nzjis[d][p]] += vSAtmm[z][pixelIndex] * dMTdmu[p] * Sv[d][z] +
vdSdmu_part1[z][d] * Atmm[d][pixelIndex] * dMTdmu[p] * CSv[d][z];
} // end loop over eigenvalues
} // end loop over non-zero jacobian indices
} // end loop over last dimension
} // end second for loop over sample container
derivative *= -(2.0 / (DerivativeValueType(this->m_NumberOfPixelsCounted) - 1.0)); // normalize
measure = this->m_G - sumEigenValuesUsed;
/** Subtract mean from derivative elements. */
if (this->m_SubtractMean)
{
if (!this->m_TransformIsStackTransform)
{
/** Update derivative per dimension.
* Parameters are ordered xxxxxxx yyyyyyy zzzzzzz ttttttt and
* per dimension xyz.
*/
const unsigned int lastDimGridSize = this->m_GridSize[this->m_LastDimIndex];
const unsigned int numParametersPerDimension =
this->GetNumberOfParameters() / this->GetMovingImage()->GetImageDimension();
const unsigned int numControlPointsPerDimension = numParametersPerDimension / lastDimGridSize;
DerivativeType mean(numControlPointsPerDimension);
for (unsigned int d = 0; d < this->GetMovingImage()->GetImageDimension(); ++d)
{
/** Compute mean per dimension. */
mean.Fill(0.0);
const unsigned int starti = numParametersPerDimension * d;
for (unsigned int i = starti; i < starti + numParametersPerDimension; ++i)
{
const unsigned int index = i % numControlPointsPerDimension;
mean[index] += derivative[i];
}
mean /= static_cast<RealType>(lastDimGridSize);
/** Update derivative for every control point per dimension. */
for (unsigned int i = starti; i < starti + numParametersPerDimension; ++i)
{
const unsigned int index = i % numControlPointsPerDimension;
derivative[i] -= mean[index];
}
}
}
else
{
/** Update derivative per dimension.
* Parameters are ordered x0x0x0y0y0y0z0z0z0x1x1x1y1y1y1z1z1z1 with
* the number the time point index.
*/
const unsigned int numParametersPerLastDimension = this->GetNumberOfParameters() / this->m_G;
DerivativeType mean(numParametersPerLastDimension);
mean.Fill(0.0);
/** Compute mean per control point. */
for (unsigned int t = 0; t < this->m_G; ++t)
{
const unsigned int startc = numParametersPerLastDimension * t;
for (unsigned int c = startc; c < startc + numParametersPerLastDimension; ++c)
{
const unsigned int index = c % numParametersPerLastDimension;
mean[index] += derivative[c];
}
}
mean /= static_cast<RealType>(this->m_G);
/** Update derivative per control point. */
for (unsigned int t = 0; t < this->m_G; ++t)
{
const unsigned int startc = numParametersPerLastDimension * t;
for (unsigned int c = startc; c < startc + numParametersPerLastDimension; ++c)
{
const unsigned int index = c % numParametersPerLastDimension;
derivative[c] -= mean[index];
}
}
}
}
/** Return the measure value. */
value = measure;
} // end GetValueAndDerivativeSingleThreaded()
/**
* ******************* GetValueAndDerivative *******************
*/
template <class TFixedImage, class TMovingImage>
void
PCAMetric<TFixedImage, TMovingImage>::GetValueAndDerivative(const TransformParametersType & parameters,
MeasureType & value,
DerivativeType & derivative) const
{
/** Option for now to still use the single threaded code. */
if (!this->m_UseMultiThread)
{
return this->GetValueAndDerivativeSingleThreaded(parameters, value, derivative);
}
/** Call non-thread-safe stuff, such as:
* this->SetTransformParameters( parameters );
* this->GetImageSampler()->Update();
* Because of these calls GetValueAndDerivative itself is not thread-safe,
* so cannot be called multiple times simultaneously.
* This is however needed in the CombinationImageToImageMetric.
* In that case, you need to:
* - switch the use of this function to on, using m_UseMetricSingleThreaded = true
* - call BeforeThreadedGetValueAndDerivative once (single-threaded) before
* calling GetValueAndDerivative
* - switch the use of this function to off, using m_UseMetricSingleThreaded = false
* - Now you can call GetValueAndDerivative multi-threaded.
*/
this->BeforeThreadedGetValueAndDerivative(parameters);
this->InitializeThreadingParameters();
/** Launch multi-threading GetSamples */
this->LaunchGetSamplesThreaderCallback();
/** Get the metric value contributions from all threads. */
this->AfterThreadedGetSamples(value);
/** Launch multi-threading ComputeDerivative */
this->LaunchComputeDerivativeThreaderCallback();
/** Sum derivative contributions from all threads */
this->AfterThreadedComputeDerivative(derivative);
} // end GetValueAndDerivative()
/**
* ******************* ThreadedGetSamples *******************
*/
template <class TFixedImage, class TMovingImage>
void
PCAMetric<TFixedImage, TMovingImage>::ThreadedGetSamples(ThreadIdType threadId)
{
/** Get a handle to the sample container. */
ImageSampleContainerPointer sampleContainer = this->GetImageSampler()->GetOutput();
const unsigned long sampleContainerSize = sampleContainer->Size();
/** Get the samples for this thread. */
const unsigned long nrOfSamplesPerThreads = static_cast<unsigned long>(
std::ceil(static_cast<double>(sampleContainerSize) / static_cast<double>(Self::GetNumberOfWorkUnits())));
unsigned long pos_begin = nrOfSamplesPerThreads * threadId;
unsigned long pos_end = nrOfSamplesPerThreads * (threadId + 1);
pos_begin = (pos_begin > sampleContainerSize) ? sampleContainerSize : pos_begin;
pos_end = (pos_end > sampleContainerSize) ? sampleContainerSize : pos_end;
/** Create iterator over the sample container. */
typename ImageSampleContainerType::ConstIterator threader_fiter;
typename ImageSampleContainerType::ConstIterator threader_fbegin = sampleContainer->Begin();
typename ImageSampleContainerType::ConstIterator threader_fend = sampleContainer->Begin();
threader_fbegin += (int)pos_begin;
threader_fend += (int)pos_end;
std::vector<FixedImagePointType> SamplesOK;
MatrixType datablock(nrOfSamplesPerThreads, this->m_G);
unsigned int pixelIndex = 0;
for (threader_fiter = threader_fbegin; threader_fiter != threader_fend; ++threader_fiter)
{
/** Read fixed coordinates. */
FixedImagePointType fixedPoint = (*threader_fiter).Value().m_ImageCoordinates;
/** Transform sampled point to voxel coordinates. */
FixedImageContinuousIndexType voxelCoord;
this->GetFixedImage()->TransformPhysicalPointToContinuousIndex(fixedPoint, voxelCoord);
unsigned int numSamplesOk = 0;
/** Loop over t */
for (unsigned int d = 0; d < this->m_G; ++d)
{
/** Initialize some variables. */
RealType movingImageValue;
/** Set fixed point's last dimension to lastDimPosition. */
voxelCoord[this->m_LastDimIndex] = d;
/** Transform sampled point back to world coordinates. */
this->GetFixedImage()->TransformContinuousIndexToPhysicalPoint(voxelCoord, fixedPoint);
/** Transform point. */
const MovingImagePointType mappedPoint = this->TransformPoint(fixedPoint);
/** Check if the point is inside the moving mask. */
bool sampleOk = this->IsInsideMovingMask(mappedPoint);
if (sampleOk)
{
sampleOk = this->FastEvaluateMovingImageValueAndDerivative(mappedPoint, movingImageValue, nullptr, threadId);
}
if (sampleOk)
{
numSamplesOk++;
datablock(pixelIndex, d) = movingImageValue;
} // end if sampleOk
} // end loop over t
if (numSamplesOk == m_G)
{
SamplesOK.push_back(fixedPoint);
pixelIndex++;
}
} /** end first loop over image sample container */
/** Only update these variables at the end to prevent unnecessary "false sharing". */
this->m_PCAMetricGetSamplesPerThreadVariables[threadId].st_NumberOfPixelsCounted = pixelIndex;
this->m_PCAMetricGetSamplesPerThreadVariables[threadId].st_DataBlock = datablock.extract(pixelIndex, this->m_G);
this->m_PCAMetricGetSamplesPerThreadVariables[threadId].st_ApprovedSamples = SamplesOK;
} // end ThreadedGetSamples()
/**
* ******************* AfterThreadedGetSamples *******************
*/
template <class TFixedImage, class TMovingImage>
void
PCAMetric<TFixedImage, TMovingImage>::AfterThreadedGetSamples(MeasureType & value) const
{
const ThreadIdType numberOfThreads = Self::GetNumberOfWorkUnits();
/** Accumulate the number of pixels. */
this->m_NumberOfPixelsCounted = this->m_PCAMetricGetSamplesPerThreadVariables[0].st_NumberOfPixelsCounted;
for (ThreadIdType i = 1; i < numberOfThreads; ++i)
{
this->m_NumberOfPixelsCounted += this->m_PCAMetricGetSamplesPerThreadVariables[i].st_NumberOfPixelsCounted;
}
/** Check if enough samples were valid. */
ImageSampleContainerPointer sampleContainer = this->GetImageSampler()->GetOutput();
this->CheckNumberOfSamples(sampleContainer->Size(), this->m_NumberOfPixelsCounted);
MatrixType A(this->m_NumberOfPixelsCounted, this->m_G);
unsigned int row_start = 0;
for (ThreadIdType i = 0; i < numberOfThreads; ++i)
{
A.update(this->m_PCAMetricGetSamplesPerThreadVariables[i].st_DataBlock, row_start, 0);
this->m_PixelStartIndex[i] = row_start;
row_start += this->m_PCAMetricGetSamplesPerThreadVariables[i].st_DataBlock.rows();
}
/** Calculate mean of from columns */
vnl_vector<RealType> mean(this->m_G);
mean.fill(NumericTraits<RealType>::Zero);
for (unsigned int i = 0; i < this->m_NumberOfPixelsCounted; ++i)
{
for (unsigned int j = 0; j < this->m_G; ++j)
{
mean(j) += A(i, j);
}
}
mean /= RealType(this->m_NumberOfPixelsCounted);
/** Calculate standard deviation from columns */
MatrixType Amm(this->m_NumberOfPixelsCounted, this->m_G);
Amm.fill(NumericTraits<RealType>::Zero);
for (unsigned int i = 0; i < this->m_NumberOfPixelsCounted; ++i)
{
for (unsigned int j = 0; j < this->m_G; ++j)
{
Amm(i, j) = A(i, j) - mean(j);
}
}
/** Compute covariancematrix C */
this->m_Atmm = Amm.transpose();
MatrixType C(this->m_Atmm * Amm);
C /= static_cast<RealType>(RealType(this->m_NumberOfPixelsCounted) - 1.0);
vnl_diag_matrix<RealType> S(this->m_G);
S.fill(NumericTraits<RealType>::Zero);
for (unsigned int j = 0; j < this->m_G; ++j)
{
S(j, j) = 1.0 / sqrt(C(j, j));
}
MatrixType K(S * C * S);
/** Compute first eigenvalue and eigenvector of K */
vnl_symmetric_eigensystem<RealType> eig(K);
RealType sumEigenValuesUsed = itk::NumericTraits<RealType>::Zero;
MatrixType eigenVectorMatrix(this->m_G, this->m_NumEigenValues);
for (unsigned int i = 1; i < this->m_NumEigenValues + 1; ++i)
{
sumEigenValuesUsed += eig.get_eigenvalue(this->m_G - i);
eigenVectorMatrix.set_column(i - 1, (eig.get_eigenvector(this->m_G - i)).normalize());
}
value = this->m_G - sumEigenValuesUsed;
MatrixType eigenVectorMatrixTranspose(eigenVectorMatrix.transpose());
/** Sub components of metric derivative */
vnl_diag_matrix<DerivativeValueType> dSdmu_part1(this->m_G);
for (unsigned int d = 0; d < this->m_G; ++d)
{
double S_sqr = S(d, d) * S(d, d);
double S_qub = S_sqr * S(d, d);
dSdmu_part1(d, d) = -S_qub;
}
this->m_vSAtmm = eigenVectorMatrixTranspose * S * this->m_Atmm;
this->m_CSv = C * S * eigenVectorMatrix;
this->m_Sv = S * eigenVectorMatrix;
this->m_vdSdmu_part1 = eigenVectorMatrixTranspose * dSdmu_part1;
} // end AfterThreadedGetSamples()
/**
* **************** GetSamplesThreaderCallback *******
*/
template <class TFixedImage, class TMovingImage>
ITK_THREAD_RETURN_TYPE
PCAMetric<TFixedImage, TMovingImage>::GetSamplesThreaderCallback(void * arg)
{
ThreadInfoType * infoStruct = static_cast<ThreadInfoType *>(arg);
ThreadIdType threadId = infoStruct->WorkUnitID;
PCAMetricMultiThreaderParameterType * temp = static_cast<PCAMetricMultiThreaderParameterType *>(infoStruct->UserData);
temp->m_Metric->ThreadedGetSamples(threadId);
return itk::ITK_THREAD_RETURN_DEFAULT_VALUE;
} // GetSamplesThreaderCallback()
/**
* *********************** LaunchGetSamplesThreaderCallback***************
*/
template <class TFixedImage, class TMovingImage>
void
PCAMetric<TFixedImage, TMovingImage>::LaunchGetSamplesThreaderCallback() const
{
/** Setup local threader. */
// \todo: is a global threader better performance-wise? check
auto local_threader = ThreaderType::New();
local_threader->SetNumberOfWorkUnits(Self::GetNumberOfWorkUnits());
local_threader->SetSingleMethod(this->GetSamplesThreaderCallback,
const_cast<void *>(static_cast<const void *>(&this->m_PCAMetricThreaderParameters)));
/** Launch. */
local_threader->SingleMethodExecute();
} // end LaunchGetSamplesThreaderCallback()
/**
* ******************* ThreadedComputeDerivative *******************
*/
template <class TFixedImage, class TMovingImage>
void
PCAMetric<TFixedImage, TMovingImage>::ThreadedComputeDerivative(ThreadIdType threadId)
{
/** Create variables to store intermediate results in. */
DerivativeType & derivative = this->m_PCAMetricGetSamplesPerThreadVariables[threadId].st_Derivative;
derivative.Fill(0.0);
/** Initialize some variables. */
RealType movingImageValue;
MovingImageDerivativeType movingImageDerivative;
TransformJacobianType jacobian;
DerivativeType imageJacobian(this->m_AdvancedTransform->GetNumberOfNonZeroJacobianIndices());
NonZeroJacobianIndicesType nzjis(this->m_AdvancedTransform->GetNumberOfNonZeroJacobianIndices());
unsigned int dummyindex = 0;
/** Second loop over fixed image samples. */
for (unsigned int pixelIndex = this->m_PixelStartIndex[threadId];
pixelIndex < (this->m_PixelStartIndex[threadId] +
this->m_PCAMetricGetSamplesPerThreadVariables[threadId].st_ApprovedSamples.size());
++pixelIndex)
{
/** Read fixed coordinates. */
FixedImagePointType fixedPoint =
this->m_PCAMetricGetSamplesPerThreadVariables[threadId].st_ApprovedSamples[dummyindex];
/** Transform sampled point to voxel coordinates. */
FixedImageContinuousIndexType voxelCoord;
this->GetFixedImage()->TransformPhysicalPointToContinuousIndex(fixedPoint, voxelCoord);
for (unsigned int d = 0; d < this->m_G; ++d)
{
/** Set fixed point's last dimension to lastDimPosition. */
voxelCoord[this->m_LastDimIndex] = d;
/** Transform sampled point back to world coordinates. */
this->GetFixedImage()->TransformContinuousIndexToPhysicalPoint(voxelCoord, fixedPoint);
const MovingImagePointType mappedPoint = this->TransformPoint(fixedPoint);
this->FastEvaluateMovingImageValueAndDerivative(mappedPoint, movingImageValue, &movingImageDerivative, threadId);
/** Get the TransformJacobian dT/dmu */
this->EvaluateTransformJacobian(fixedPoint, jacobian, nzjis);
/** Compute the innerproduct (dM/dx)^T (dT/dmu). */
this->EvaluateTransformJacobianInnerProduct(jacobian, movingImageDerivative, imageJacobian);
/** build metric derivative components */
for (unsigned int p = 0; p < nzjis.size(); ++p)
{
DerivativeValueType tmp = 0.0;
for (unsigned int z = 0; z < this->m_NumEigenValues; ++z)
{
tmp += this->m_vSAtmm[z][pixelIndex] * imageJacobian[p] * this->m_Sv[d][z] +
this->m_vdSdmu_part1[z][d] * this->m_Atmm[d][pixelIndex] * imageJacobian[p] * this->m_CSv[d][z];
} // end loop over eigenvalues
derivative[nzjis[p]] += tmp;
} // end loop over non-zero jacobian indices
} // end loop over last dimension
dummyindex++;
} // end second for loop over sample container
} // end ThreadedGetValueAndDerivative()
/**
* ******************* AfterThreadedComputeDerivative *******************
*/
template <class TFixedImage, class TMovingImage>
void
PCAMetric<TFixedImage, TMovingImage>::AfterThreadedComputeDerivative(DerivativeType & derivative) const
{
const ThreadIdType numberOfThreads = Self::GetNumberOfWorkUnits();
derivative = this->m_PCAMetricGetSamplesPerThreadVariables[0].st_Derivative;
for (ThreadIdType i = 1; i < numberOfThreads; ++i)
{
derivative += this->m_PCAMetricGetSamplesPerThreadVariables[i].st_Derivative;
}
derivative *= -(2.0 / (DerivativeValueType(this->m_NumberOfPixelsCounted) - 1.0)); // normalize
/** Subtract mean from derivative elements. */
if (this->m_SubtractMean)
{
if (!this->m_TransformIsStackTransform)
{
/** Update derivative per dimension.
* Parameters are ordered xxxxxxx yyyyyyy zzzzzzz ttttttt and
* per dimension xyz.
*/
const unsigned int lastDimGridSize = this->m_GridSize[this->m_LastDimIndex];
const unsigned int numParametersPerDimension =
this->GetNumberOfParameters() / this->GetMovingImage()->GetImageDimension();
const unsigned int numControlPointsPerDimension = numParametersPerDimension / lastDimGridSize;
DerivativeType mean(numControlPointsPerDimension);
for (unsigned int d = 0; d < this->GetMovingImage()->GetImageDimension(); ++d)
{
/** Compute mean per dimension. */
mean.Fill(0.0);
const unsigned int starti = numParametersPerDimension * d;
for (unsigned int i = starti; i < starti + numParametersPerDimension; ++i)
{
const unsigned int index = i % numControlPointsPerDimension;
mean[index] += derivative[i];
}
mean /= static_cast<RealType>(lastDimGridSize);
/** Update derivative for every control point per dimension. */
for (unsigned int i = starti; i < starti + numParametersPerDimension; ++i)
{
const unsigned int index = i % numControlPointsPerDimension;
derivative[i] -= mean[index];
}
}
}
else
{
/** Update derivative per dimension.
* Parameters are ordered x0x0x0y0y0y0z0z0z0x1x1x1y1y1y1z1z1z1 with
* the number the time point index.
*/
const unsigned int numParametersPerLastDimension = this->GetNumberOfParameters() / this->m_G;
DerivativeType mean(numParametersPerLastDimension);
mean.Fill(0.0);
/** Compute mean per control point. */
for (unsigned int t = 0; t < this->m_G; ++t)
{
const unsigned int startc = numParametersPerLastDimension * t;
for (unsigned int c = startc; c < startc + numParametersPerLastDimension; ++c)
{
const unsigned int index = c % numParametersPerLastDimension;
mean[index] += derivative[c];
}
}
mean /= static_cast<RealType>(this->m_G);
/** Update derivative per control point. */
for (unsigned int t = 0; t < this->m_G; ++t)
{
const unsigned int startc = numParametersPerLastDimension * t;
for (unsigned int c = startc; c < startc + numParametersPerLastDimension; ++c)
{
const unsigned int index = c % numParametersPerLastDimension;
derivative[c] -= mean[index];
}
}
}
}
} // end AftherThreadedComputeDerivative()
/**
* **************** ComputeDerivativeThreaderCallback *******
*/
template <class TFixedImage, class TMovingImage>
ITK_THREAD_RETURN_TYPE
PCAMetric<TFixedImage, TMovingImage>::ComputeDerivativeThreaderCallback(void * arg)
{
ThreadInfoType * infoStruct = static_cast<ThreadInfoType *>(arg);
ThreadIdType threadId = infoStruct->WorkUnitID;
PCAMetricMultiThreaderParameterType * temp = static_cast<PCAMetricMultiThreaderParameterType *>(infoStruct->UserData);
temp->m_Metric->ThreadedComputeDerivative(threadId);
return itk::ITK_THREAD_RETURN_DEFAULT_VALUE;
} // end omputeDerivativeThreaderCallback()
/**
* ************** LaunchComputeDerivativeThreaderCallback **********
*/
template <class TFixedImage, class TMovingImage>
void
PCAMetric<TFixedImage, TMovingImage>::LaunchComputeDerivativeThreaderCallback() const
{
/** Setup local threader. */
// \todo: is a global threader better performance-wise? check
auto local_threader = ThreaderType::New();
local_threader->SetNumberOfWorkUnits(Self::GetNumberOfWorkUnits());
local_threader->SetSingleMethod(this->ComputeDerivativeThreaderCallback,
const_cast<void *>(static_cast<const void *>(&this->m_PCAMetricThreaderParameters)));
/** Launch. */
local_threader->SingleMethodExecute();
} // end LaunchComputeDerivativeThreaderCallback()
} // end namespace itk
#endif // itkPCAMetric_F_multithreaded_hxx
|
// Copyright (c) 2011 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 <limits>
#include "base/memory/scoped_ptr.h"
#include "base/string16.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace base {
TEST(ValuesTest, Basic) {
// Test basic dictionary getting/setting
DictionaryValue settings;
std::string homepage = "http://google.com";
ASSERT_FALSE(settings.GetString("global.homepage", &homepage));
ASSERT_EQ(std::string("http://google.com"), homepage);
ASSERT_FALSE(settings.Get("global", NULL));
settings.Set("global", Value::CreateBooleanValue(true));
ASSERT_TRUE(settings.Get("global", NULL));
settings.SetString("global.homepage", "http://scurvy.com");
ASSERT_TRUE(settings.Get("global", NULL));
homepage = "http://google.com";
ASSERT_TRUE(settings.GetString("global.homepage", &homepage));
ASSERT_EQ(std::string("http://scurvy.com"), homepage);
// Test storing a dictionary in a list.
ListValue* toolbar_bookmarks;
ASSERT_FALSE(
settings.GetList("global.toolbar.bookmarks", &toolbar_bookmarks));
toolbar_bookmarks = new ListValue;
settings.Set("global.toolbar.bookmarks", toolbar_bookmarks);
ASSERT_TRUE(settings.GetList("global.toolbar.bookmarks", &toolbar_bookmarks));
DictionaryValue* new_bookmark = new DictionaryValue;
new_bookmark->SetString("name", "Froogle");
new_bookmark->SetString("url", "http://froogle.com");
toolbar_bookmarks->Append(new_bookmark);
ListValue* bookmark_list;
ASSERT_TRUE(settings.GetList("global.toolbar.bookmarks", &bookmark_list));
DictionaryValue* bookmark;
ASSERT_EQ(1U, bookmark_list->GetSize());
ASSERT_TRUE(bookmark_list->GetDictionary(0, &bookmark));
std::string bookmark_name = "Unnamed";
ASSERT_TRUE(bookmark->GetString("name", &bookmark_name));
ASSERT_EQ(std::string("Froogle"), bookmark_name);
std::string bookmark_url;
ASSERT_TRUE(bookmark->GetString("url", &bookmark_url));
ASSERT_EQ(std::string("http://froogle.com"), bookmark_url);
}
TEST(ValuesTest, List) {
scoped_ptr<ListValue> mixed_list(new ListValue());
mixed_list->Set(0, Value::CreateBooleanValue(true));
mixed_list->Set(1, Value::CreateIntegerValue(42));
mixed_list->Set(2, Value::CreateDoubleValue(88.8));
mixed_list->Set(3, Value::CreateStringValue("foo"));
ASSERT_EQ(4u, mixed_list->GetSize());
Value *value = NULL;
bool bool_value = false;
int int_value = 0;
double double_value = 0.0;
std::string string_value;
ASSERT_FALSE(mixed_list->Get(4, &value));
ASSERT_FALSE(mixed_list->GetInteger(0, &int_value));
ASSERT_EQ(0, int_value);
ASSERT_FALSE(mixed_list->GetBoolean(1, &bool_value));
ASSERT_FALSE(bool_value);
ASSERT_FALSE(mixed_list->GetString(2, &string_value));
ASSERT_EQ("", string_value);
ASSERT_FALSE(mixed_list->GetInteger(2, &int_value));
ASSERT_EQ(0, int_value);
ASSERT_FALSE(mixed_list->GetBoolean(3, &bool_value));
ASSERT_FALSE(bool_value);
ASSERT_TRUE(mixed_list->GetBoolean(0, &bool_value));
ASSERT_TRUE(bool_value);
ASSERT_TRUE(mixed_list->GetInteger(1, &int_value));
ASSERT_EQ(42, int_value);
// implicit conversion from Integer to Double should be possible.
ASSERT_TRUE(mixed_list->GetDouble(1, &double_value));
ASSERT_EQ(42, double_value);
ASSERT_TRUE(mixed_list->GetDouble(2, &double_value));
ASSERT_EQ(88.8, double_value);
ASSERT_TRUE(mixed_list->GetString(3, &string_value));
ASSERT_EQ("foo", string_value);
// Try searching in the mixed list.
scoped_ptr<Value> sought_value(Value::CreateIntegerValue(42));
scoped_ptr<Value> not_found_value(Value::CreateBooleanValue(false));
ASSERT_NE(mixed_list->end(), mixed_list->Find(*sought_value));
ASSERT_TRUE((*mixed_list->Find(*sought_value))->GetAsInteger(&int_value));
ASSERT_EQ(42, int_value);
ASSERT_EQ(mixed_list->end(), mixed_list->Find(*not_found_value));
}
TEST(ValuesTest, BinaryValue) {
char* buffer = NULL;
// Passing a null buffer pointer doesn't yield a BinaryValue
scoped_ptr<BinaryValue> binary(BinaryValue::Create(buffer, 0));
ASSERT_FALSE(binary.get());
// If you want to represent an empty binary value, use a zero-length buffer.
buffer = new char[1];
ASSERT_TRUE(buffer);
binary.reset(BinaryValue::Create(buffer, 0));
ASSERT_TRUE(binary.get());
ASSERT_TRUE(binary->GetBuffer());
ASSERT_EQ(buffer, binary->GetBuffer());
ASSERT_EQ(0U, binary->GetSize());
// Test the common case of a non-empty buffer
buffer = new char[15];
binary.reset(BinaryValue::Create(buffer, 15));
ASSERT_TRUE(binary.get());
ASSERT_TRUE(binary->GetBuffer());
ASSERT_EQ(buffer, binary->GetBuffer());
ASSERT_EQ(15U, binary->GetSize());
char stack_buffer[42];
memset(stack_buffer, '!', 42);
binary.reset(BinaryValue::CreateWithCopiedBuffer(stack_buffer, 42));
ASSERT_TRUE(binary.get());
ASSERT_TRUE(binary->GetBuffer());
ASSERT_NE(stack_buffer, binary->GetBuffer());
ASSERT_EQ(42U, binary->GetSize());
ASSERT_EQ(0, memcmp(stack_buffer, binary->GetBuffer(), binary->GetSize()));
}
TEST(ValuesTest, StringValue) {
// Test overloaded CreateStringValue.
scoped_ptr<Value> narrow_value(Value::CreateStringValue("narrow"));
ASSERT_TRUE(narrow_value.get());
ASSERT_TRUE(narrow_value->IsType(Value::TYPE_STRING));
scoped_ptr<Value> utf16_value(
Value::CreateStringValue(ASCIIToUTF16("utf16")));
ASSERT_TRUE(utf16_value.get());
ASSERT_TRUE(utf16_value->IsType(Value::TYPE_STRING));
// Test overloaded GetString.
std::string narrow = "http://google.com";
string16 utf16 = ASCIIToUTF16("http://google.com");
ASSERT_TRUE(narrow_value->GetAsString(&narrow));
ASSERT_TRUE(narrow_value->GetAsString(&utf16));
ASSERT_EQ(std::string("narrow"), narrow);
ASSERT_EQ(ASCIIToUTF16("narrow"), utf16);
ASSERT_TRUE(utf16_value->GetAsString(&narrow));
ASSERT_TRUE(utf16_value->GetAsString(&utf16));
ASSERT_EQ(std::string("utf16"), narrow);
ASSERT_EQ(ASCIIToUTF16("utf16"), utf16);
}
// This is a Value object that allows us to tell if it's been
// properly deleted by modifying the value of external flag on destruction.
class DeletionTestValue : public Value {
public:
explicit DeletionTestValue(bool* deletion_flag) : Value(TYPE_NULL) {
Init(deletion_flag); // Separate function so that we can use ASSERT_*
}
void Init(bool* deletion_flag) {
ASSERT_TRUE(deletion_flag);
deletion_flag_ = deletion_flag;
*deletion_flag_ = false;
}
~DeletionTestValue() {
*deletion_flag_ = true;
}
private:
bool* deletion_flag_;
};
TEST(ValuesTest, ListDeletion) {
bool deletion_flag = true;
{
ListValue list;
list.Append(new DeletionTestValue(&deletion_flag));
EXPECT_FALSE(deletion_flag);
}
EXPECT_TRUE(deletion_flag);
{
ListValue list;
list.Append(new DeletionTestValue(&deletion_flag));
EXPECT_FALSE(deletion_flag);
list.Clear();
EXPECT_TRUE(deletion_flag);
}
{
ListValue list;
list.Append(new DeletionTestValue(&deletion_flag));
EXPECT_FALSE(deletion_flag);
EXPECT_TRUE(list.Set(0, Value::CreateNullValue()));
EXPECT_TRUE(deletion_flag);
}
}
TEST(ValuesTest, ListRemoval) {
bool deletion_flag = true;
Value* removed_item = NULL;
{
ListValue list;
list.Append(new DeletionTestValue(&deletion_flag));
EXPECT_FALSE(deletion_flag);
EXPECT_EQ(1U, list.GetSize());
EXPECT_FALSE(list.Remove(std::numeric_limits<size_t>::max(),
&removed_item));
EXPECT_FALSE(list.Remove(1, &removed_item));
EXPECT_TRUE(list.Remove(0, &removed_item));
ASSERT_TRUE(removed_item);
EXPECT_EQ(0U, list.GetSize());
}
EXPECT_FALSE(deletion_flag);
delete removed_item;
removed_item = NULL;
EXPECT_TRUE(deletion_flag);
{
ListValue list;
list.Append(new DeletionTestValue(&deletion_flag));
EXPECT_FALSE(deletion_flag);
EXPECT_TRUE(list.Remove(0, NULL));
EXPECT_TRUE(deletion_flag);
EXPECT_EQ(0U, list.GetSize());
}
{
ListValue list;
DeletionTestValue* value = new DeletionTestValue(&deletion_flag);
list.Append(value);
EXPECT_FALSE(deletion_flag);
size_t index = 0;
list.Remove(*value, &index);
EXPECT_EQ(0U, index);
EXPECT_TRUE(deletion_flag);
EXPECT_EQ(0U, list.GetSize());
}
}
TEST(ValuesTest, DictionaryDeletion) {
std::string key = "test";
bool deletion_flag = true;
{
DictionaryValue dict;
dict.Set(key, new DeletionTestValue(&deletion_flag));
EXPECT_FALSE(deletion_flag);
}
EXPECT_TRUE(deletion_flag);
{
DictionaryValue dict;
dict.Set(key, new DeletionTestValue(&deletion_flag));
EXPECT_FALSE(deletion_flag);
dict.Clear();
EXPECT_TRUE(deletion_flag);
}
{
DictionaryValue dict;
dict.Set(key, new DeletionTestValue(&deletion_flag));
EXPECT_FALSE(deletion_flag);
dict.Set(key, Value::CreateNullValue());
EXPECT_TRUE(deletion_flag);
}
}
TEST(ValuesTest, DictionaryRemoval) {
std::string key = "test";
bool deletion_flag = true;
Value* removed_item = NULL;
{
DictionaryValue dict;
dict.Set(key, new DeletionTestValue(&deletion_flag));
EXPECT_FALSE(deletion_flag);
EXPECT_TRUE(dict.HasKey(key));
EXPECT_FALSE(dict.Remove("absent key", &removed_item));
EXPECT_TRUE(dict.Remove(key, &removed_item));
EXPECT_FALSE(dict.HasKey(key));
ASSERT_TRUE(removed_item);
}
EXPECT_FALSE(deletion_flag);
delete removed_item;
removed_item = NULL;
EXPECT_TRUE(deletion_flag);
{
DictionaryValue dict;
dict.Set(key, new DeletionTestValue(&deletion_flag));
EXPECT_FALSE(deletion_flag);
EXPECT_TRUE(dict.HasKey(key));
EXPECT_TRUE(dict.Remove(key, NULL));
EXPECT_TRUE(deletion_flag);
EXPECT_FALSE(dict.HasKey(key));
}
}
TEST(ValuesTest, DictionaryWithoutPathExpansion) {
DictionaryValue dict;
dict.Set("this.is.expanded", Value::CreateNullValue());
dict.SetWithoutPathExpansion("this.isnt.expanded", Value::CreateNullValue());
EXPECT_FALSE(dict.HasKey("this.is.expanded"));
EXPECT_TRUE(dict.HasKey("this"));
Value* value1;
EXPECT_TRUE(dict.Get("this", &value1));
DictionaryValue* value2;
ASSERT_TRUE(dict.GetDictionaryWithoutPathExpansion("this", &value2));
EXPECT_EQ(value1, value2);
EXPECT_EQ(1U, value2->size());
EXPECT_TRUE(dict.HasKey("this.isnt.expanded"));
Value* value3;
EXPECT_FALSE(dict.Get("this.isnt.expanded", &value3));
Value* value4;
ASSERT_TRUE(dict.GetWithoutPathExpansion("this.isnt.expanded", &value4));
EXPECT_EQ(Value::TYPE_NULL, value4->GetType());
}
TEST(ValuesTest, DeepCopy) {
DictionaryValue original_dict;
Value* original_null = Value::CreateNullValue();
original_dict.Set("null", original_null);
FundamentalValue* original_bool = Value::CreateBooleanValue(true);
original_dict.Set("bool", original_bool);
FundamentalValue* original_int = Value::CreateIntegerValue(42);
original_dict.Set("int", original_int);
FundamentalValue* original_double = Value::CreateDoubleValue(3.14);
original_dict.Set("double", original_double);
StringValue* original_string = Value::CreateStringValue("hello");
original_dict.Set("string", original_string);
StringValue* original_string16 =
Value::CreateStringValue(ASCIIToUTF16("hello16"));
original_dict.Set("string16", original_string16);
char* original_buffer = new char[42];
memset(original_buffer, '!', 42);
BinaryValue* original_binary = BinaryValue::Create(original_buffer, 42);
original_dict.Set("binary", original_binary);
ListValue* original_list = new ListValue();
FundamentalValue* original_list_element_0 = Value::CreateIntegerValue(0);
original_list->Append(original_list_element_0);
FundamentalValue* original_list_element_1 = Value::CreateIntegerValue(1);
original_list->Append(original_list_element_1);
original_dict.Set("list", original_list);
DictionaryValue* original_nested_dictionary = new DictionaryValue();
original_nested_dictionary->Set("key", Value::CreateStringValue("value"));
original_dict.Set("dictionary", original_nested_dictionary);
scoped_ptr<DictionaryValue> copy_dict(original_dict.DeepCopy());
ASSERT_TRUE(copy_dict.get());
ASSERT_NE(copy_dict.get(), &original_dict);
Value* copy_null = NULL;
ASSERT_TRUE(copy_dict->Get("null", ©_null));
ASSERT_TRUE(copy_null);
ASSERT_NE(copy_null, original_null);
ASSERT_TRUE(copy_null->IsType(Value::TYPE_NULL));
Value* copy_bool = NULL;
ASSERT_TRUE(copy_dict->Get("bool", ©_bool));
ASSERT_TRUE(copy_bool);
ASSERT_NE(copy_bool, original_bool);
ASSERT_TRUE(copy_bool->IsType(Value::TYPE_BOOLEAN));
bool copy_bool_value = false;
ASSERT_TRUE(copy_bool->GetAsBoolean(©_bool_value));
ASSERT_TRUE(copy_bool_value);
Value* copy_int = NULL;
ASSERT_TRUE(copy_dict->Get("int", ©_int));
ASSERT_TRUE(copy_int);
ASSERT_NE(copy_int, original_int);
ASSERT_TRUE(copy_int->IsType(Value::TYPE_INTEGER));
int copy_int_value = 0;
ASSERT_TRUE(copy_int->GetAsInteger(©_int_value));
ASSERT_EQ(42, copy_int_value);
Value* copy_double = NULL;
ASSERT_TRUE(copy_dict->Get("double", ©_double));
ASSERT_TRUE(copy_double);
ASSERT_NE(copy_double, original_double);
ASSERT_TRUE(copy_double->IsType(Value::TYPE_DOUBLE));
double copy_double_value = 0;
ASSERT_TRUE(copy_double->GetAsDouble(©_double_value));
ASSERT_EQ(3.14, copy_double_value);
Value* copy_string = NULL;
ASSERT_TRUE(copy_dict->Get("string", ©_string));
ASSERT_TRUE(copy_string);
ASSERT_NE(copy_string, original_string);
ASSERT_TRUE(copy_string->IsType(Value::TYPE_STRING));
std::string copy_string_value;
string16 copy_string16_value;
ASSERT_TRUE(copy_string->GetAsString(©_string_value));
ASSERT_TRUE(copy_string->GetAsString(©_string16_value));
ASSERT_EQ(std::string("hello"), copy_string_value);
ASSERT_EQ(ASCIIToUTF16("hello"), copy_string16_value);
Value* copy_string16 = NULL;
ASSERT_TRUE(copy_dict->Get("string16", ©_string16));
ASSERT_TRUE(copy_string16);
ASSERT_NE(copy_string16, original_string16);
ASSERT_TRUE(copy_string16->IsType(Value::TYPE_STRING));
ASSERT_TRUE(copy_string16->GetAsString(©_string_value));
ASSERT_TRUE(copy_string16->GetAsString(©_string16_value));
ASSERT_EQ(std::string("hello16"), copy_string_value);
ASSERT_EQ(ASCIIToUTF16("hello16"), copy_string16_value);
Value* copy_binary = NULL;
ASSERT_TRUE(copy_dict->Get("binary", ©_binary));
ASSERT_TRUE(copy_binary);
ASSERT_NE(copy_binary, original_binary);
ASSERT_TRUE(copy_binary->IsType(Value::TYPE_BINARY));
ASSERT_NE(original_binary->GetBuffer(),
static_cast<BinaryValue*>(copy_binary)->GetBuffer());
ASSERT_EQ(original_binary->GetSize(),
static_cast<BinaryValue*>(copy_binary)->GetSize());
ASSERT_EQ(0, memcmp(original_binary->GetBuffer(),
static_cast<BinaryValue*>(copy_binary)->GetBuffer(),
original_binary->GetSize()));
Value* copy_value = NULL;
ASSERT_TRUE(copy_dict->Get("list", ©_value));
ASSERT_TRUE(copy_value);
ASSERT_NE(copy_value, original_list);
ASSERT_TRUE(copy_value->IsType(Value::TYPE_LIST));
ListValue* copy_list = NULL;
ASSERT_TRUE(copy_value->GetAsList(©_list));
ASSERT_TRUE(copy_list);
ASSERT_EQ(2U, copy_list->GetSize());
Value* copy_list_element_0;
ASSERT_TRUE(copy_list->Get(0, ©_list_element_0));
ASSERT_TRUE(copy_list_element_0);
ASSERT_NE(copy_list_element_0, original_list_element_0);
int copy_list_element_0_value;
ASSERT_TRUE(copy_list_element_0->GetAsInteger(©_list_element_0_value));
ASSERT_EQ(0, copy_list_element_0_value);
Value* copy_list_element_1;
ASSERT_TRUE(copy_list->Get(1, ©_list_element_1));
ASSERT_TRUE(copy_list_element_1);
ASSERT_NE(copy_list_element_1, original_list_element_1);
int copy_list_element_1_value;
ASSERT_TRUE(copy_list_element_1->GetAsInteger(©_list_element_1_value));
ASSERT_EQ(1, copy_list_element_1_value);
copy_value = NULL;
ASSERT_TRUE(copy_dict->Get("dictionary", ©_value));
ASSERT_TRUE(copy_value);
ASSERT_NE(copy_value, original_nested_dictionary);
ASSERT_TRUE(copy_value->IsType(Value::TYPE_DICTIONARY));
DictionaryValue* copy_nested_dictionary = NULL;
ASSERT_TRUE(copy_value->GetAsDictionary(©_nested_dictionary));
ASSERT_TRUE(copy_nested_dictionary);
EXPECT_TRUE(copy_nested_dictionary->HasKey("key"));
}
TEST(ValuesTest, Equals) {
Value* null1 = Value::CreateNullValue();
Value* null2 = Value::CreateNullValue();
EXPECT_NE(null1, null2);
EXPECT_TRUE(null1->Equals(null2));
Value* boolean = Value::CreateBooleanValue(false);
EXPECT_FALSE(null1->Equals(boolean));
delete null1;
delete null2;
delete boolean;
DictionaryValue dv;
dv.SetBoolean("a", false);
dv.SetInteger("b", 2);
dv.SetDouble("c", 2.5);
dv.SetString("d1", "string");
dv.SetString("d2", ASCIIToUTF16("http://google.com"));
dv.Set("e", Value::CreateNullValue());
scoped_ptr<DictionaryValue> copy;
copy.reset(dv.DeepCopy());
EXPECT_TRUE(dv.Equals(copy.get()));
ListValue* list = new ListValue;
list->Append(Value::CreateNullValue());
list->Append(new DictionaryValue);
dv.Set("f", list);
EXPECT_FALSE(dv.Equals(copy.get()));
copy->Set("f", list->DeepCopy());
EXPECT_TRUE(dv.Equals(copy.get()));
list->Append(Value::CreateBooleanValue(true));
EXPECT_FALSE(dv.Equals(copy.get()));
// Check if Equals detects differences in only the keys.
copy.reset(dv.DeepCopy());
EXPECT_TRUE(dv.Equals(copy.get()));
copy->Remove("a", NULL);
copy->SetBoolean("aa", false);
EXPECT_FALSE(dv.Equals(copy.get()));
}
TEST(ValuesTest, StaticEquals) {
scoped_ptr<Value> null1(Value::CreateNullValue());
scoped_ptr<Value> null2(Value::CreateNullValue());
EXPECT_TRUE(Value::Equals(null1.get(), null2.get()));
EXPECT_TRUE(Value::Equals(NULL, NULL));
scoped_ptr<Value> i42(Value::CreateIntegerValue(42));
scoped_ptr<Value> j42(Value::CreateIntegerValue(42));
scoped_ptr<Value> i17(Value::CreateIntegerValue(17));
EXPECT_TRUE(Value::Equals(i42.get(), i42.get()));
EXPECT_TRUE(Value::Equals(j42.get(), i42.get()));
EXPECT_TRUE(Value::Equals(i42.get(), j42.get()));
EXPECT_FALSE(Value::Equals(i42.get(), i17.get()));
EXPECT_FALSE(Value::Equals(i42.get(), NULL));
EXPECT_FALSE(Value::Equals(NULL, i42.get()));
// NULL and Value::CreateNullValue() are intentionally different: We need
// support for NULL as a return value for "undefined" without caring for
// ownership of the pointer.
EXPECT_FALSE(Value::Equals(null1.get(), NULL));
EXPECT_FALSE(Value::Equals(NULL, null1.get()));
}
TEST(ValuesTest, DeepCopyCovariantReturnTypes) {
DictionaryValue original_dict;
Value* original_null = Value::CreateNullValue();
original_dict.Set("null", original_null);
FundamentalValue* original_bool = Value::CreateBooleanValue(true);
original_dict.Set("bool", original_bool);
FundamentalValue* original_int = Value::CreateIntegerValue(42);
original_dict.Set("int", original_int);
FundamentalValue* original_double = Value::CreateDoubleValue(3.14);
original_dict.Set("double", original_double);
StringValue* original_string = Value::CreateStringValue("hello");
original_dict.Set("string", original_string);
StringValue* original_string16 =
Value::CreateStringValue(ASCIIToUTF16("hello16"));
original_dict.Set("string16", original_string16);
char* original_buffer = new char[42];
memset(original_buffer, '!', 42);
BinaryValue* original_binary = BinaryValue::Create(original_buffer, 42);
original_dict.Set("binary", original_binary);
ListValue* original_list = new ListValue();
FundamentalValue* original_list_element_0 = Value::CreateIntegerValue(0);
original_list->Append(original_list_element_0);
FundamentalValue* original_list_element_1 = Value::CreateIntegerValue(1);
original_list->Append(original_list_element_1);
original_dict.Set("list", original_list);
Value* original_dict_value = &original_dict;
Value* original_bool_value = original_bool;
Value* original_int_value = original_int;
Value* original_double_value = original_double;
Value* original_string_value = original_string;
Value* original_string16_value = original_string16;
Value* original_binary_value = original_binary;
Value* original_list_value = original_list;
scoped_ptr<Value> copy_dict_value(original_dict_value->DeepCopy());
scoped_ptr<Value> copy_bool_value(original_bool_value->DeepCopy());
scoped_ptr<Value> copy_int_value(original_int_value->DeepCopy());
scoped_ptr<Value> copy_double_value(original_double_value->DeepCopy());
scoped_ptr<Value> copy_string_value(original_string_value->DeepCopy());
scoped_ptr<Value> copy_string16_value(original_string16_value->DeepCopy());
scoped_ptr<Value> copy_binary_value(original_binary_value->DeepCopy());
scoped_ptr<Value> copy_list_value(original_list_value->DeepCopy());
EXPECT_TRUE(original_dict_value->Equals(copy_dict_value.get()));
EXPECT_TRUE(original_bool_value->Equals(copy_bool_value.get()));
EXPECT_TRUE(original_int_value->Equals(copy_int_value.get()));
EXPECT_TRUE(original_double_value->Equals(copy_double_value.get()));
EXPECT_TRUE(original_string_value->Equals(copy_string_value.get()));
EXPECT_TRUE(original_string16_value->Equals(copy_string16_value.get()));
EXPECT_TRUE(original_binary_value->Equals(copy_binary_value.get()));
EXPECT_TRUE(original_list_value->Equals(copy_list_value.get()));
}
TEST(ValuesTest, RemoveEmptyChildren) {
scoped_ptr<DictionaryValue> root(new DictionaryValue);
// Remove empty lists and dictionaries.
root->Set("empty_dict", new DictionaryValue);
root->Set("empty_list", new ListValue);
root->SetWithoutPathExpansion("a.b.c.d.e", new DictionaryValue);
root.reset(root->DeepCopyWithoutEmptyChildren());
EXPECT_TRUE(root->empty());
// Make sure we don't prune too much.
root->SetBoolean("bool", true);
root->Set("empty_dict", new DictionaryValue);
root->SetString("empty_string", "");
root.reset(root->DeepCopyWithoutEmptyChildren());
EXPECT_EQ(2U, root->size());
// Should do nothing.
root.reset(root->DeepCopyWithoutEmptyChildren());
EXPECT_EQ(2U, root->size());
// Nested test cases. These should all reduce back to the bool and string
// set above.
{
root->Set("a.b.c.d.e", new DictionaryValue);
root.reset(root->DeepCopyWithoutEmptyChildren());
EXPECT_EQ(2U, root->size());
}
{
DictionaryValue* inner = new DictionaryValue;
root->Set("dict_with_emtpy_children", inner);
inner->Set("empty_dict", new DictionaryValue);
inner->Set("empty_list", new ListValue);
root.reset(root->DeepCopyWithoutEmptyChildren());
EXPECT_EQ(2U, root->size());
}
{
ListValue* inner = new ListValue;
root->Set("list_with_empty_children", inner);
inner->Append(new DictionaryValue);
inner->Append(new ListValue);
root.reset(root->DeepCopyWithoutEmptyChildren());
EXPECT_EQ(2U, root->size());
}
// Nested with siblings.
{
ListValue* inner = new ListValue;
root->Set("list_with_empty_children", inner);
inner->Append(new DictionaryValue);
inner->Append(new ListValue);
DictionaryValue* inner2 = new DictionaryValue;
root->Set("dict_with_empty_children", inner2);
inner2->Set("empty_dict", new DictionaryValue);
inner2->Set("empty_list", new ListValue);
root.reset(root->DeepCopyWithoutEmptyChildren());
EXPECT_EQ(2U, root->size());
}
// Make sure nested values don't get pruned.
{
ListValue* inner = new ListValue;
root->Set("list_with_empty_children", inner);
ListValue* inner2 = new ListValue;
inner->Append(new DictionaryValue);
inner->Append(inner2);
inner2->Append(Value::CreateStringValue("hello"));
root.reset(root->DeepCopyWithoutEmptyChildren());
EXPECT_EQ(3U, root->size());
EXPECT_TRUE(root->GetList("list_with_empty_children", &inner));
EXPECT_EQ(1U, inner->GetSize()); // Dictionary was pruned.
EXPECT_TRUE(inner->GetList(0, &inner2));
EXPECT_EQ(1U, inner2->GetSize());
}
}
TEST(ValuesTest, MergeDictionary) {
scoped_ptr<DictionaryValue> base(new DictionaryValue);
base->SetString("base_key", "base_key_value_base");
base->SetString("collide_key", "collide_key_value_base");
DictionaryValue* base_sub_dict = new DictionaryValue;
base_sub_dict->SetString("sub_base_key", "sub_base_key_value_base");
base_sub_dict->SetString("sub_collide_key", "sub_collide_key_value_base");
base->Set("sub_dict_key", base_sub_dict);
scoped_ptr<DictionaryValue> merge(new DictionaryValue);
merge->SetString("merge_key", "merge_key_value_merge");
merge->SetString("collide_key", "collide_key_value_merge");
DictionaryValue* merge_sub_dict = new DictionaryValue;
merge_sub_dict->SetString("sub_merge_key", "sub_merge_key_value_merge");
merge_sub_dict->SetString("sub_collide_key", "sub_collide_key_value_merge");
merge->Set("sub_dict_key", merge_sub_dict);
base->MergeDictionary(merge.get());
EXPECT_EQ(4U, base->size());
std::string base_key_value;
EXPECT_TRUE(base->GetString("base_key", &base_key_value));
EXPECT_EQ("base_key_value_base", base_key_value); // Base value preserved.
std::string collide_key_value;
EXPECT_TRUE(base->GetString("collide_key", &collide_key_value));
EXPECT_EQ("collide_key_value_merge", collide_key_value); // Replaced.
std::string merge_key_value;
EXPECT_TRUE(base->GetString("merge_key", &merge_key_value));
EXPECT_EQ("merge_key_value_merge", merge_key_value); // Merged in.
DictionaryValue* res_sub_dict;
EXPECT_TRUE(base->GetDictionary("sub_dict_key", &res_sub_dict));
EXPECT_EQ(3U, res_sub_dict->size());
std::string sub_base_key_value;
EXPECT_TRUE(res_sub_dict->GetString("sub_base_key", &sub_base_key_value));
EXPECT_EQ("sub_base_key_value_base", sub_base_key_value); // Preserved.
std::string sub_collide_key_value;
EXPECT_TRUE(res_sub_dict->GetString("sub_collide_key",
&sub_collide_key_value));
EXPECT_EQ("sub_collide_key_value_merge", sub_collide_key_value); // Replaced.
std::string sub_merge_key_value;
EXPECT_TRUE(res_sub_dict->GetString("sub_merge_key", &sub_merge_key_value));
EXPECT_EQ("sub_merge_key_value_merge", sub_merge_key_value); // Merged in.
}
TEST(ValuesTest, DictionaryIterator) {
DictionaryValue dict;
for (DictionaryValue::Iterator it(dict); it.HasNext(); it.Advance()) {
ADD_FAILURE();
}
StringValue value1("value1");
dict.Set("key1", value1.DeepCopy());
bool seen1 = false;
for (DictionaryValue::Iterator it(dict); it.HasNext(); it.Advance()) {
EXPECT_FALSE(seen1);
EXPECT_EQ("key1", it.key());
EXPECT_TRUE(value1.Equals(&it.value()));
seen1 = true;
}
EXPECT_TRUE(seen1);
StringValue value2("value2");
dict.Set("key2", value2.DeepCopy());
bool seen2 = seen1 = false;
for (DictionaryValue::Iterator it(dict); it.HasNext(); it.Advance()) {
if (it.key() == "key1") {
EXPECT_FALSE(seen1);
EXPECT_TRUE(value1.Equals(&it.value()));
seen1 = true;
} else if (it.key() == "key2") {
EXPECT_FALSE(seen2);
EXPECT_TRUE(value2.Equals(&it.value()));
seen2 = true;
} else {
ADD_FAILURE();
}
}
EXPECT_TRUE(seen1);
EXPECT_TRUE(seen2);
}
} // namespace base
|
// Filename: config_interrogatedb.cxx
// Created by: drose (01Aug00)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University. All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license. You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////
#include "config_interrogatedb.h"
#include "interrogate_request.h"
#include "configVariableBool.h"
#include "configVariableSearchPath.h"
#include "dconfig.h"
#if defined(WIN32_VC) && defined(_DEBUG)
// _DEBUG assumes you are linking to msvcrt70d.dll, not msvcrt70.dll
#define USE_WIN32_DBGHEAP
#include <crtdbg.h>
#endif
Configure(config_interrogatedb);
NotifyCategoryDef(interrogatedb, "");
ConfigureFn(config_interrogatedb) {
// interrogate_request_library("types");
#ifdef USE_WIN32_DBGHEAP
ConfigVariableBool use_win32_dbgheap("use-win32-dbgheap", false);
ConfigVariableBool win32_report_leaks("win32-report-leaks", false);
int dbg_flags = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
if (use_win32_dbgheap.get_string_value() == "full") {
// "full" means check the heap after *every* alloc/dealloc.
// Expensive.
dbg_flags |= (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_CHECK_ALWAYS_DF |
_CRTDBG_CHECK_CRT_DF);
} else {
// Otherwise, it's a bool flag. true means check the heap
// normally, false means don't do any debug checking.
if (!use_win32_dbgheap) {
// deflt disable complete heap verify every 1024 allocations (VC7 deflt).
// With vc7 stl small-string-optimization causing more allocs,
// this can cause order-of-magnitude slowdowns in dbg builds
dbg_flags = 0;
}
}
if (win32_report_leaks) {
// Report memory still allocated at program termination. Not sure
// how useful this is, as many things get allocated once and never
// freed, but they aren't really leaks.
dbg_flags |= _CRTDBG_LEAK_CHECK_DF;
}
_CrtSetDbgFlag(dbg_flags);
#endif
}
ConfigVariableSearchPath interrogatedb_path
("interrogatedb-path", "The search path for interrogate's *.in files.");
|
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int len = nums.size();
int sum = 0, maxSum = -2147483647;
for(int i=0; i<len; i++) {
sum += nums[i];
maxSum = max(maxSum, sum);
if(sum < 0) sum = 0;
}
return maxSum;
}
};
|
/*
* Souffle - A Datalog Compiler
* Copyright (c) 2020, The Souffle Developers. All rights reserved
* Licensed under the Universal Permissive License v 1.0 as shown at:
* - https://opensource.org/licenses/UPL
* - <souffle root>/licenses/SOUFFLE-UPL.txt
*/
/************************************************************************
*
* @file MaterializeSingletonAggregation.cpp
*
***********************************************************************/
#include "ast/transform/MaterializeSingletonAggregation.h"
#include "ast/Aggregator.h"
#include "ast/Argument.h"
#include "ast/Atom.h"
#include "ast/Attribute.h"
#include "ast/BinaryConstraint.h"
#include "ast/Clause.h"
#include "ast/Literal.h"
#include "ast/Node.h"
#include "ast/Program.h"
#include "ast/QualifiedName.h"
#include "ast/Relation.h"
#include "ast/TranslationUnit.h"
#include "ast/Variable.h"
#include "ast/analysis/Aggregate.h"
#include "ast/utility/NodeMapper.h"
#include "ast/utility/Utils.h"
#include "ast/utility/Visitor.h"
#include "souffle/BinaryConstraintOps.h"
#include "souffle/utility/MiscUtil.h"
#include "souffle/utility/StringUtil.h"
#include <cassert>
#include <map>
#include <memory>
#include <set>
#include <utility>
#include <vector>
namespace souffle::ast::transform {
bool MaterializeSingletonAggregationTransformer::transform(TranslationUnit& translationUnit) {
Program& program = translationUnit.getProgram();
std::set<std::pair<Aggregator*, Clause*>> pairs;
// avoid trying to deal with inner aggregates directly.
// We will apply a fixpoint operator so that it ends up all getting
// wound out but we can't rush this.
std::set<const Aggregator*> innerAggregates;
visitDepthFirst(program, [&](const Aggregator& agg) {
visitDepthFirst(agg, [&](const Aggregator& innerAgg) {
if (agg != innerAgg) {
innerAggregates.insert(&innerAgg);
}
});
});
// collect references to clause / aggregate pairs
visitDepthFirst(program, [&](const Clause& clause) {
visitDepthFirst(clause, [&](const Aggregator& agg) {
// only unroll one level at a time
if (innerAggregates.find(&agg) != innerAggregates.end()) {
return;
}
// if the aggregate isn't single valued
// (ie it relies on a grounding from the outer scope)
// or it's a constituent of the only atom in the clause,
// then there's no point materialising it!
if (!isSingleValued(translationUnit, agg, clause) || clause.getBodyLiterals().size() == 1) {
return;
}
auto* foundAggregate = const_cast<Aggregator*>(&agg);
auto* foundClause = const_cast<Clause*>(&clause);
pairs.insert(std::make_pair(foundAggregate, foundClause));
});
});
for (auto pair : pairs) {
// Clone the aggregate that we're going to be deleting.
auto aggregate = souffle::clone(pair.first);
Clause* clause = pair.second;
// synthesise an aggregate relation
// __agg_rel_0()
auto aggRel = mk<Relation>();
auto aggHead = mk<Atom>();
auto aggClause = mk<Clause>();
std::string aggRelName = analysis::findUniqueRelationName(program, "__agg");
aggRel->setQualifiedName(aggRelName);
aggHead->setQualifiedName(aggRelName);
// create a synthesised variable to replace the aggregate term!
std::string variableName = analysis::findUniqueVariableName(*clause, "z");
auto variable = mk<ast::Variable>(variableName);
// __agg_rel_0(z) :- ...
aggHead->addArgument(souffle::clone(variable));
aggRel->addAttribute(mk<Attribute>(variableName, "number"));
aggClause->setHead(souffle::clone(aggHead));
// A(x) :- x = sum .., B(x).
// -> A(x) :- x = z, B(x), __agg_rel_0(z).
auto equalityLiteral = mk<BinaryConstraint>(
BinaryConstraintOp::EQ, souffle::clone(variable), souffle::clone(aggregate));
// __agg_rel_0(z) :- z = sum ...
aggClause->addToBody(std::move(equalityLiteral));
program.addRelation(std::move(aggRel));
program.addClause(std::move(aggClause));
// the only thing left to do is just replace the aggregate terms in the original
// clause with the synthesised variable
struct replaceAggregate : public NodeMapper {
const Aggregator& aggregate;
const Own<ast::Variable> variable;
replaceAggregate(const Aggregator& aggregate, Own<ast::Variable> variable)
: aggregate(aggregate), variable(std::move(variable)) {}
Own<Node> operator()(Own<Node> node) const override {
if (auto* current = dynamic_cast<Aggregator*>(node.get())) {
if (*current == aggregate) {
auto replacement = souffle::clone(variable);
assert(replacement != nullptr);
return replacement;
}
}
node->apply(*this);
return node;
}
};
replaceAggregate update(*aggregate, std::move(variable));
clause->apply(update);
clause->addToBody(std::move(aggHead));
}
return pairs.size() > 0;
}
bool MaterializeSingletonAggregationTransformer::isSingleValued(
const TranslationUnit& tu, const Aggregator& agg, const Clause& clause) {
// An aggregate is single valued as long as it is not complex.
// This just means there are NO injected variables in the aggregate.
auto injectedVariables = analysis::getInjectedVariables(tu, clause, agg);
return injectedVariables.empty();
}
} // namespace souffle::ast::transform
|
// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in
// the main distribution directory for license terms and copyright or visit
// https://github.com/actor-framework/actor-framework/blob/master/LICENSE.
#pragma once
#include <utility>
#include "caf/detail/as_mutable_ref.hpp"
#include "caf/detail/core_export.hpp"
#include "caf/error.hpp"
#include "caf/inspector_access.hpp"
#include "caf/sec.hpp"
#include "caf/string_view.hpp"
namespace caf {
/// Base type for inspectors that save objects to some output sink. Deriving
/// from this class enables the inspector DSL.
/// @note The derived type still needs to provide an `object()` member function
/// for the DSL.
class CAF_CORE_EXPORT save_inspector {
public:
// -- constants --------------------------------------------------------------
/// Enables dispatching on the inspector type.
static constexpr bool is_loading = false;
// -- constructors, destructors, and assignment operators --------------------
virtual ~save_inspector();
// -- properties -------------------------------------------------------------
void set_error(error stop_reason) {
err_ = std::move(stop_reason);
}
template <class... Ts>
void emplace_error(Ts&&... xs) {
err_ = make_error(std::forward<Ts>(xs)...);
}
const error& get_error() const noexcept {
return err_;
}
error&& move_error() noexcept {
return std::move(err_);
}
// -- DSL types for regular fields -------------------------------------------
template <class T, class U>
struct field_with_fallback_t {
string_view field_name;
T* val;
U fallback;
template <class Inspector>
bool operator()(Inspector& f) {
auto is_present = [this] { return *val != fallback; };
auto get = [this] { return *val; };
return detail::save_field(f, field_name, is_present, get);
}
template <class Predicate>
field_with_fallback_t&& invariant(Predicate&&) && {
return std::move(*this);
}
};
template <class T>
struct field_t {
string_view field_name;
T* val;
template <class Inspector>
bool operator()(Inspector& f) {
return detail::save_field(f, field_name, *val);
}
template <class U>
auto fallback(U value) && {
return field_with_fallback_t<T, U>{field_name, val, std::move(value)};
}
template <class Predicate>
field_t&& invariant(Predicate&&) && {
return std::move(*this);
}
};
// -- DSL types for virtual fields (getter and setter access) ----------------
template <class T, class Get, class U>
struct virt_field_with_fallback_t {
string_view field_name;
Get get;
U fallback;
template <class Inspector>
bool operator()(Inspector& f) {
auto is_present = [this] { return get() != fallback; };
return detail::save_field(f, field_name, is_present, get);
}
template <class Predicate>
virt_field_with_fallback_t&& invariant(Predicate&&) && {
return std::move(*this);
}
};
template <class T, class Get>
struct virt_field_t {
string_view field_name;
Get get;
template <class Inspector>
bool operator()(Inspector& f) {
auto&& x = get();
return detail::save_field(f, field_name, detail::as_mutable_ref(x));
}
template <class U>
auto fallback(U value) && {
return virt_field_with_fallback_t<T, Get, U>{
field_name,
std::move(get),
std::move(value),
};
}
template <class Predicate>
virt_field_t&& invariant(Predicate&&) && {
return std::move(*this);
}
};
template <class T, class IsPresent, class Get>
struct optional_virt_field_t {
string_view field_name;
IsPresent is_present;
Get get;
template <class Inspector>
bool operator()(Inspector& f) {
return detail::save_field(f, field_name, is_present, get);
}
};
// -- DSL type for the object ------------------------------------------------
template <class Inspector, class SaveCallback>
struct object_with_save_callback_t {
type_id_t object_type;
string_view object_name;
Inspector* f;
SaveCallback save_callback;
template <class... Fields>
bool fields(Fields&&... fs) {
using save_callback_result = decltype(save_callback());
if (!(f->begin_object(object_type, object_name) && (fs(*f) && ...)))
return false;
if constexpr (std::is_same<save_callback_result, bool>::value) {
if (!save_callback()) {
f->set_error(sec::save_callback_failed);
return false;
}
} else {
if (auto err = save_callback()) {
f->set_error(std::move(err));
return false;
}
}
return f->end_object();
}
auto pretty_name(string_view name) && {
return object_t{name, f};
}
template <class F>
object_with_save_callback_t&& on_load(F&&) && {
return std::move(*this);
}
};
template <class Inspector>
struct object_t {
type_id_t object_type;
string_view object_name;
Inspector* f;
template <class... Fields>
bool fields(Fields&&... fs) {
return f->begin_object(object_type, object_name) //
&& (fs(*f) && ...) //
&& f->end_object();
}
auto pretty_name(string_view name) && {
return object_t{object_type, name, f};
}
template <class F>
object_t&& on_load(F&&) && {
return std::move(*this);
}
template <class F>
auto on_save(F fun) && {
return object_with_save_callback_t<Inspector, F>{
object_type,
object_name,
f,
std::move(fun),
};
}
};
// -- factory functions ------------------------------------------------------
template <class T>
static auto field(string_view name, T& x) {
static_assert(!std::is_const<T>::value);
return field_t<T>{name, std::addressof(x)};
}
template <class Get, class Set>
static auto field(string_view name, Get get, Set&&) {
using field_type = std::decay_t<decltype(get())>;
return virt_field_t<field_type, Get>{name, get};
}
template <class IsPresent, class Get, class... Ts>
static auto field(string_view name, IsPresent is_present, Get get, Ts&&...) {
using field_type = std::decay_t<decltype(get())>;
return optional_virt_field_t<field_type, IsPresent, Get>{
name,
is_present,
get,
};
}
protected:
error err_;
};
} // namespace caf
|
/*************************************************************************/
/* script_language.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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 "script_language.h"
#include "core/core_string_names.h"
#include "core/project_settings.h"
ScriptLanguage *ScriptServer::_languages[MAX_LANGUAGES];
int ScriptServer::_language_count = 0;
bool ScriptServer::scripting_enabled = true;
bool ScriptServer::reload_scripts_on_save = false;
bool ScriptServer::languages_finished = false;
ScriptEditRequestFunction ScriptServer::edit_request_func = NULL;
void Script::_notification(int p_what) {
if (p_what == NOTIFICATION_POSTINITIALIZE) {
if (ScriptDebugger::get_singleton())
ScriptDebugger::get_singleton()->set_break_language(get_language());
}
}
Variant Script::_get_property_default_value(const StringName &p_property) {
Variant ret;
get_property_default_value(p_property, ret);
return ret;
}
Array Script::_get_script_property_list() {
Array ret;
List<PropertyInfo> list;
get_script_property_list(&list);
for (List<PropertyInfo>::Element *E = list.front(); E; E = E->next()) {
ret.append(E->get().operator Dictionary());
}
return ret;
}
Array Script::_get_script_method_list() {
Array ret;
List<MethodInfo> list;
get_script_method_list(&list);
for (List<MethodInfo>::Element *E = list.front(); E; E = E->next()) {
ret.append(E->get().operator Dictionary());
}
return ret;
}
Array Script::_get_script_signal_list() {
Array ret;
List<MethodInfo> list;
get_script_signal_list(&list);
for (List<MethodInfo>::Element *E = list.front(); E; E = E->next()) {
ret.append(E->get().operator Dictionary());
}
return ret;
}
Dictionary Script::_get_script_constant_map() {
Dictionary ret;
Map<StringName, Variant> map;
get_constants(&map);
for (Map<StringName, Variant>::Element *E = map.front(); E; E = E->next()) {
ret[E->key()] = E->value();
}
return ret;
}
void Script::_bind_methods() {
ClassDB::bind_method(D_METHOD("can_instance"), &Script::can_instance);
//ClassDB::bind_method(D_METHOD("instance_create","base_object"),&Script::instance_create);
ClassDB::bind_method(D_METHOD("instance_has", "base_object"), &Script::instance_has);
ClassDB::bind_method(D_METHOD("has_source_code"), &Script::has_source_code);
ClassDB::bind_method(D_METHOD("get_source_code"), &Script::get_source_code);
ClassDB::bind_method(D_METHOD("set_source_code", "source"), &Script::set_source_code);
ClassDB::bind_method(D_METHOD("reload", "keep_state"), &Script::reload, DEFVAL(false));
ClassDB::bind_method(D_METHOD("get_base_script"), &Script::get_base_script);
ClassDB::bind_method(D_METHOD("get_instance_base_type"), &Script::get_instance_base_type);
ClassDB::bind_method(D_METHOD("has_script_signal", "signal_name"), &Script::has_script_signal);
ClassDB::bind_method(D_METHOD("get_script_property_list"), &Script::_get_script_property_list);
ClassDB::bind_method(D_METHOD("get_script_method_list"), &Script::_get_script_method_list);
ClassDB::bind_method(D_METHOD("get_script_signal_list"), &Script::_get_script_signal_list);
ClassDB::bind_method(D_METHOD("get_script_constant_map"), &Script::_get_script_constant_map);
ClassDB::bind_method(D_METHOD("get_property_default_value", "property"), &Script::_get_property_default_value);
ClassDB::bind_method(D_METHOD("is_tool"), &Script::is_tool);
ADD_PROPERTY(PropertyInfo(Variant::STRING, "source_code", PROPERTY_HINT_NONE, "", 0), "set_source_code", "get_source_code");
}
bool Script::is_equals(const Script *p_other) {
return p_other == this;
}
void ScriptServer::set_scripting_enabled(bool p_enabled) {
scripting_enabled = p_enabled;
}
bool ScriptServer::is_scripting_enabled() {
return scripting_enabled;
}
ScriptLanguage *ScriptServer::get_language(int p_idx) {
ERR_FAIL_INDEX_V(p_idx, _language_count, NULL);
return _languages[p_idx];
}
void ScriptServer::register_language(ScriptLanguage *p_language) {
ERR_FAIL_COND(_language_count >= MAX_LANGUAGES);
_languages[_language_count++] = p_language;
}
void ScriptServer::unregister_language(ScriptLanguage *p_language) {
for (int i = 0; i < _language_count; i++) {
if (_languages[i] == p_language) {
_language_count--;
if (i < _language_count) {
SWAP(_languages[i], _languages[_language_count]);
}
return;
}
}
}
void ScriptServer::init_languages() {
{ //load global classes
global_classes_clear();
if (ProjectSettings::get_singleton()->has_setting("_global_script_classes")) {
Array script_classes = ProjectSettings::get_singleton()->get("_global_script_classes");
for (int i = 0; i < script_classes.size(); i++) {
Dictionary c = script_classes[i];
if (!c.has("class") || !c.has("language") || !c.has("path") || !c.has("base"))
continue;
add_global_class(c["class"], c["base"], c["language"], c["path"]);
}
}
}
for (int i = 0; i < _language_count; i++) {
_languages[i]->init();
}
}
void ScriptServer::finish_languages() {
for (int i = 0; i < _language_count; i++) {
_languages[i]->finish();
}
global_classes_clear();
languages_finished = true;
}
void ScriptServer::set_reload_scripts_on_save(bool p_enable) {
reload_scripts_on_save = p_enable;
}
bool ScriptServer::is_reload_scripts_on_save_enabled() {
return reload_scripts_on_save;
}
void ScriptServer::thread_enter() {
for (int i = 0; i < _language_count; i++) {
_languages[i]->thread_enter();
}
}
void ScriptServer::thread_exit() {
for (int i = 0; i < _language_count; i++) {
_languages[i]->thread_exit();
}
}
HashMap<StringName, ScriptServer::GlobalScriptClass> ScriptServer::global_classes;
void ScriptServer::global_classes_clear() {
global_classes.clear();
}
void ScriptServer::add_global_class(const StringName &p_class, const StringName &p_base, const StringName &p_language, const String &p_path) {
ERR_FAIL_COND_MSG(p_class == p_base || (global_classes.has(p_base) && get_global_class_native_base(p_base) == p_class), "Cyclic inheritance in script class.");
GlobalScriptClass g;
g.language = p_language;
g.path = p_path;
g.base = p_base;
global_classes[p_class] = g;
}
void ScriptServer::remove_global_class(const StringName &p_class) {
global_classes.erase(p_class);
}
bool ScriptServer::is_global_class(const StringName &p_class) {
return global_classes.has(p_class);
}
StringName ScriptServer::get_global_class_language(const StringName &p_class) {
ERR_FAIL_COND_V(!global_classes.has(p_class), StringName());
return global_classes[p_class].language;
}
String ScriptServer::get_global_class_path(const String &p_class) {
ERR_FAIL_COND_V(!global_classes.has(p_class), String());
return global_classes[p_class].path;
}
StringName ScriptServer::get_global_class_base(const String &p_class) {
ERR_FAIL_COND_V(!global_classes.has(p_class), String());
return global_classes[p_class].base;
}
StringName ScriptServer::get_global_class_native_base(const String &p_class) {
ERR_FAIL_COND_V(!global_classes.has(p_class), String());
String base = global_classes[p_class].base;
while (global_classes.has(base)) {
base = global_classes[base].base;
}
return base;
}
void ScriptServer::get_global_class_list(List<StringName> *r_global_classes) {
const StringName *K = NULL;
List<StringName> classes;
while ((K = global_classes.next(K))) {
classes.push_back(*K);
}
classes.sort_custom<StringName::AlphCompare>();
for (List<StringName>::Element *E = classes.front(); E; E = E->next()) {
r_global_classes->push_back(E->get());
}
}
void ScriptServer::save_global_classes() {
List<StringName> gc;
get_global_class_list(&gc);
Array gcarr;
for (List<StringName>::Element *E = gc.front(); E; E = E->next()) {
Dictionary d;
d["class"] = E->get();
d["language"] = global_classes[E->get()].language;
d["path"] = global_classes[E->get()].path;
d["base"] = global_classes[E->get()].base;
gcarr.push_back(d);
}
ProjectSettings::get_singleton()->set("_global_script_classes", gcarr);
ProjectSettings::get_singleton()->save();
}
////////////////////
void ScriptInstance::get_property_state(List<Pair<StringName, Variant> > &state) {
List<PropertyInfo> pinfo;
get_property_list(&pinfo);
for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
if (E->get().usage & PROPERTY_USAGE_STORAGE) {
Pair<StringName, Variant> p;
p.first = E->get().name;
if (get(p.first, p.second))
state.push_back(p);
}
}
}
Variant ScriptInstance::call(const StringName &p_method, VARIANT_ARG_DECLARE) {
VARIANT_ARGPTRS;
int argc = 0;
for (int i = 0; i < VARIANT_ARG_MAX; i++) {
if (argptr[i]->get_type() == Variant::NIL)
break;
argc++;
}
Variant::CallError error;
return call(p_method, argptr, argc, error);
}
void ScriptInstance::call_multilevel(const StringName &p_method, const Variant **p_args, int p_argcount) {
Variant::CallError ce;
call(p_method, p_args, p_argcount, ce); // script may not support multilevel calls
}
void ScriptInstance::call_multilevel_reversed(const StringName &p_method, const Variant **p_args, int p_argcount) {
Variant::CallError ce;
call(p_method, p_args, p_argcount, ce); // script may not support multilevel calls
}
void ScriptInstance::property_set_fallback(const StringName &, const Variant &, bool *r_valid) {
if (r_valid)
*r_valid = false;
}
Variant ScriptInstance::property_get_fallback(const StringName &, bool *r_valid) {
if (r_valid)
*r_valid = false;
return Variant();
}
void ScriptInstance::call_multilevel(const StringName &p_method, VARIANT_ARG_DECLARE) {
VARIANT_ARGPTRS;
int argc = 0;
for (int i = 0; i < VARIANT_ARG_MAX; i++) {
if (argptr[i]->get_type() == Variant::NIL)
break;
argc++;
}
call_multilevel(p_method, argptr, argc);
}
ScriptInstance::~ScriptInstance() {
}
ScriptCodeCompletionCache *ScriptCodeCompletionCache::singleton = NULL;
ScriptCodeCompletionCache::ScriptCodeCompletionCache() {
singleton = this;
}
void ScriptLanguage::frame() {
}
ScriptDebugger *ScriptDebugger::singleton = NULL;
void ScriptDebugger::set_lines_left(int p_left) {
lines_left = p_left;
}
int ScriptDebugger::get_lines_left() const {
return lines_left;
}
void ScriptDebugger::set_depth(int p_depth) {
depth = p_depth;
}
int ScriptDebugger::get_depth() const {
return depth;
}
void ScriptDebugger::insert_breakpoint(int p_line, const StringName &p_source) {
if (!breakpoints.has(p_line))
breakpoints[p_line] = Set<StringName>();
breakpoints[p_line].insert(p_source);
}
void ScriptDebugger::remove_breakpoint(int p_line, const StringName &p_source) {
if (!breakpoints.has(p_line))
return;
breakpoints[p_line].erase(p_source);
if (breakpoints[p_line].size() == 0)
breakpoints.erase(p_line);
}
bool ScriptDebugger::is_breakpoint(int p_line, const StringName &p_source) const {
if (!breakpoints.has(p_line))
return false;
return breakpoints[p_line].has(p_source);
}
bool ScriptDebugger::is_breakpoint_line(int p_line) const {
return breakpoints.has(p_line);
}
String ScriptDebugger::breakpoint_find_source(const String &p_source) const {
return p_source;
}
void ScriptDebugger::clear_breakpoints() {
breakpoints.clear();
}
void ScriptDebugger::idle_poll() {
}
void ScriptDebugger::line_poll() {
}
void ScriptDebugger::set_break_language(ScriptLanguage *p_lang) {
break_lang = p_lang;
}
ScriptLanguage *ScriptDebugger::get_break_language() const {
return break_lang;
}
ScriptDebugger::ScriptDebugger() {
singleton = this;
lines_left = -1;
depth = -1;
break_lang = NULL;
}
bool PlaceHolderScriptInstance::set(const StringName &p_name, const Variant &p_value) {
if (script->is_placeholder_fallback_enabled())
return false;
if (values.has(p_name)) {
Variant defval;
if (script->get_property_default_value(p_name, defval)) {
if (defval == p_value) {
values.erase(p_name);
return true;
}
}
values[p_name] = p_value;
return true;
} else {
Variant defval;
if (script->get_property_default_value(p_name, defval)) {
if (defval != p_value) {
values[p_name] = p_value;
}
return true;
}
}
return false;
}
bool PlaceHolderScriptInstance::get(const StringName &p_name, Variant &r_ret) const {
if (values.has(p_name)) {
r_ret = values[p_name];
return true;
}
if (constants.has(p_name)) {
r_ret = constants[p_name];
return true;
}
if (!script->is_placeholder_fallback_enabled()) {
Variant defval;
if (script->get_property_default_value(p_name, defval)) {
r_ret = defval;
return true;
}
}
return false;
}
void PlaceHolderScriptInstance::get_property_list(List<PropertyInfo> *p_properties) const {
if (script->is_placeholder_fallback_enabled()) {
for (const List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) {
p_properties->push_back(E->get());
}
} else {
for (const List<PropertyInfo>::Element *E = properties.front(); E; E = E->next()) {
PropertyInfo pinfo = E->get();
if (!values.has(pinfo.name)) {
pinfo.usage |= PROPERTY_USAGE_SCRIPT_DEFAULT_VALUE;
}
p_properties->push_back(E->get());
}
}
}
Variant::Type PlaceHolderScriptInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const {
if (values.has(p_name)) {
if (r_is_valid)
*r_is_valid = true;
return values[p_name].get_type();
}
if (constants.has(p_name)) {
if (r_is_valid)
*r_is_valid = true;
return constants[p_name].get_type();
}
if (r_is_valid)
*r_is_valid = false;
return Variant::NIL;
}
void PlaceHolderScriptInstance::get_method_list(List<MethodInfo> *p_list) const {
if (script->is_placeholder_fallback_enabled())
return;
if (script.is_valid()) {
script->get_script_method_list(p_list);
}
}
bool PlaceHolderScriptInstance::has_method(const StringName &p_method) const {
if (script->is_placeholder_fallback_enabled())
return false;
if (script.is_valid()) {
return script->has_method(p_method);
}
return false;
}
void PlaceHolderScriptInstance::update(const List<PropertyInfo> &p_properties, const Map<StringName, Variant> &p_values) {
Set<StringName> new_values;
for (const List<PropertyInfo>::Element *E = p_properties.front(); E; E = E->next()) {
StringName n = E->get().name;
new_values.insert(n);
if (!values.has(n) || values[n].get_type() != E->get().type) {
if (p_values.has(n))
values[n] = p_values[n];
}
}
properties = p_properties;
List<StringName> to_remove;
for (Map<StringName, Variant>::Element *E = values.front(); E; E = E->next()) {
if (!new_values.has(E->key()))
to_remove.push_back(E->key());
Variant defval;
if (script->get_property_default_value(E->key(), defval)) {
//remove because it's the same as the default value
if (defval == E->get()) {
to_remove.push_back(E->key());
}
}
}
while (to_remove.size()) {
values.erase(to_remove.front()->get());
to_remove.pop_front();
}
if (owner && owner->get_script_instance() == this) {
owner->_change_notify();
}
//change notify
constants.clear();
script->get_constants(&constants);
}
void PlaceHolderScriptInstance::property_set_fallback(const StringName &p_name, const Variant &p_value, bool *r_valid) {
if (script->is_placeholder_fallback_enabled()) {
Map<StringName, Variant>::Element *E = values.find(p_name);
if (E) {
E->value() = p_value;
} else {
values.insert(p_name, p_value);
}
bool found = false;
for (const List<PropertyInfo>::Element *F = properties.front(); F; F = F->next()) {
if (F->get().name == p_name) {
found = true;
break;
}
}
if (!found) {
properties.push_back(PropertyInfo(p_value.get_type(), p_name, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_SCRIPT_VARIABLE));
}
}
if (r_valid)
*r_valid = false; // Cannot change the value in either case
}
Variant PlaceHolderScriptInstance::property_get_fallback(const StringName &p_name, bool *r_valid) {
if (script->is_placeholder_fallback_enabled()) {
const Map<StringName, Variant>::Element *E = values.find(p_name);
if (E) {
if (r_valid)
*r_valid = true;
return E->value();
}
E = constants.find(p_name);
if (E) {
if (r_valid)
*r_valid = true;
return E->value();
}
}
if (r_valid)
*r_valid = false;
return Variant();
}
PlaceHolderScriptInstance::PlaceHolderScriptInstance(ScriptLanguage *p_language, Ref<Script> p_script, Object *p_owner) :
owner(p_owner),
language(p_language),
script(p_script) {
}
PlaceHolderScriptInstance::~PlaceHolderScriptInstance() {
if (script.is_valid()) {
script->_placeholder_erased(this);
}
}
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/chime-sdk-meetings/model/TranscribeLanguageCode.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>
using namespace Aws::Utils;
namespace Aws
{
namespace ChimeSDKMeetings
{
namespace Model
{
namespace TranscribeLanguageCodeMapper
{
static const int en_US_HASH = HashingUtils::HashString("en-US");
static const int en_GB_HASH = HashingUtils::HashString("en-GB");
static const int es_US_HASH = HashingUtils::HashString("es-US");
static const int fr_CA_HASH = HashingUtils::HashString("fr-CA");
static const int fr_FR_HASH = HashingUtils::HashString("fr-FR");
static const int en_AU_HASH = HashingUtils::HashString("en-AU");
static const int it_IT_HASH = HashingUtils::HashString("it-IT");
static const int de_DE_HASH = HashingUtils::HashString("de-DE");
static const int pt_BR_HASH = HashingUtils::HashString("pt-BR");
static const int ja_JP_HASH = HashingUtils::HashString("ja-JP");
static const int ko_KR_HASH = HashingUtils::HashString("ko-KR");
static const int zh_CN_HASH = HashingUtils::HashString("zh-CN");
TranscribeLanguageCode GetTranscribeLanguageCodeForName(const Aws::String& name)
{
int hashCode = HashingUtils::HashString(name.c_str());
if (hashCode == en_US_HASH)
{
return TranscribeLanguageCode::en_US;
}
else if (hashCode == en_GB_HASH)
{
return TranscribeLanguageCode::en_GB;
}
else if (hashCode == es_US_HASH)
{
return TranscribeLanguageCode::es_US;
}
else if (hashCode == fr_CA_HASH)
{
return TranscribeLanguageCode::fr_CA;
}
else if (hashCode == fr_FR_HASH)
{
return TranscribeLanguageCode::fr_FR;
}
else if (hashCode == en_AU_HASH)
{
return TranscribeLanguageCode::en_AU;
}
else if (hashCode == it_IT_HASH)
{
return TranscribeLanguageCode::it_IT;
}
else if (hashCode == de_DE_HASH)
{
return TranscribeLanguageCode::de_DE;
}
else if (hashCode == pt_BR_HASH)
{
return TranscribeLanguageCode::pt_BR;
}
else if (hashCode == ja_JP_HASH)
{
return TranscribeLanguageCode::ja_JP;
}
else if (hashCode == ko_KR_HASH)
{
return TranscribeLanguageCode::ko_KR;
}
else if (hashCode == zh_CN_HASH)
{
return TranscribeLanguageCode::zh_CN;
}
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
overflowContainer->StoreOverflow(hashCode, name);
return static_cast<TranscribeLanguageCode>(hashCode);
}
return TranscribeLanguageCode::NOT_SET;
}
Aws::String GetNameForTranscribeLanguageCode(TranscribeLanguageCode enumValue)
{
switch(enumValue)
{
case TranscribeLanguageCode::en_US:
return "en-US";
case TranscribeLanguageCode::en_GB:
return "en-GB";
case TranscribeLanguageCode::es_US:
return "es-US";
case TranscribeLanguageCode::fr_CA:
return "fr-CA";
case TranscribeLanguageCode::fr_FR:
return "fr-FR";
case TranscribeLanguageCode::en_AU:
return "en-AU";
case TranscribeLanguageCode::it_IT:
return "it-IT";
case TranscribeLanguageCode::de_DE:
return "de-DE";
case TranscribeLanguageCode::pt_BR:
return "pt-BR";
case TranscribeLanguageCode::ja_JP:
return "ja-JP";
case TranscribeLanguageCode::ko_KR:
return "ko-KR";
case TranscribeLanguageCode::zh_CN:
return "zh-CN";
default:
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
}
return {};
}
}
} // namespace TranscribeLanguageCodeMapper
} // namespace Model
} // namespace ChimeSDKMeetings
} // namespace Aws
|
// Copyright 1996-2018 Cyberbotics 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.
#ifndef FONT_HPP
#define FONT_HPP
#include <ft2build.h>
#ifdef FT_FREETYPE_H
// cppcheck-suppress preprocessorErrorDirective
#include FT_FREETYPE_H
#endif
#include <wren/font.h>
namespace wren {
class Font {
public:
static Font *createFont() { return new Font(); }
static void deleteFont(Font *font) { delete font; }
void setFontFace(const char *filename);
void setFontSize(unsigned int size);
unsigned char *generateCharBuffer(unsigned long character, bool antiAliasing, int *width, int *rows, int *verticalOffset,
int *horizontalOffset, int *transparencyFactor, int *horizontalAdvance, int *pitch);
unsigned int verticalSpace() const;
int descender() const { return mFace->descender * (mFontSize / static_cast<float>(mFace->units_per_EM)); }
void getBoundingBox(const char *text, int *width, int *height);
unsigned int fontSize() const { return mFontSize; }
WrFontError error() const { return mError; }
private:
Font();
~Font();
FT_Library mLibrary;
FT_Face mFace;
bool mFaceIsInitialized;
WrFontError mError;
unsigned int mFontSize;
};
} // namespace wren
#endif
|
// Copyright (c) 2011-2016 The Bitcoin Core developers
// Copyright (c) 2017 The LISYNetwork Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "arith_uint256.h"
#include "uint256.h"
#include "version.h"
#include "test/test_lisynetwork.h"
#include <boost/test/unit_test.hpp>
#include <stdint.h>
#include <sstream>
#include <iomanip>
#include <limits>
#include <cmath>
#include <string>
#include <stdio.h>
BOOST_FIXTURE_TEST_SUITE(uint256_tests, BasicTestingSetup)
const unsigned char R1Array[] =
"\x9c\x52\x4a\xdb\xcf\x56\x11\x12\x2b\x29\x12\x5e\x5d\x35\xd2\xd2"
"\x22\x81\xaa\xb5\x33\xf0\x08\x32\xd5\x56\xb1\xf9\xea\xe5\x1d\x7d";
const char R1ArrayHex[] = "7D1DE5EAF9B156D53208F033B5AA8122D2d2355d5e12292b121156cfdb4a529c";
const uint256 R1L = uint256(std::vector<unsigned char>(R1Array,R1Array+32));
const uint160 R1S = uint160(std::vector<unsigned char>(R1Array,R1Array+20));
const unsigned char R2Array[] =
"\x70\x32\x1d\x7c\x47\xa5\x6b\x40\x26\x7e\x0a\xc3\xa6\x9c\xb6\xbf"
"\x13\x30\x47\xa3\x19\x2d\xda\x71\x49\x13\x72\xf0\xb4\xca\x81\xd7";
const uint256 R2L = uint256(std::vector<unsigned char>(R2Array,R2Array+32));
const uint160 R2S = uint160(std::vector<unsigned char>(R2Array,R2Array+20));
const unsigned char ZeroArray[] =
"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";
const uint256 ZeroL = uint256(std::vector<unsigned char>(ZeroArray,ZeroArray+32));
const uint160 ZeroS = uint160(std::vector<unsigned char>(ZeroArray,ZeroArray+20));
const unsigned char OneArray[] =
"\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";
const uint256 OneL = uint256(std::vector<unsigned char>(OneArray,OneArray+32));
const uint160 OneS = uint160(std::vector<unsigned char>(OneArray,OneArray+20));
const unsigned char MaxArray[] =
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff"
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff";
const uint256 MaxL = uint256(std::vector<unsigned char>(MaxArray,MaxArray+32));
const uint160 MaxS = uint160(std::vector<unsigned char>(MaxArray,MaxArray+20));
std::string ArrayToString(const unsigned char A[], unsigned int width)
{
std::stringstream Stream;
Stream << std::hex;
for (unsigned int i = 0; i < width; ++i)
{
Stream<<std::setw(2)<<std::setfill('0')<<(unsigned int)A[width-i-1];
}
return Stream.str();
}
inline uint160 uint160S(const char *str)
{
uint160 rv;
rv.SetHex(str);
return rv;
}
inline uint160 uint160S(const std::string& str)
{
uint160 rv;
rv.SetHex(str);
return rv;
}
BOOST_AUTO_TEST_CASE( basics ) // constructors, equality, inequality
{
BOOST_CHECK(1 == 0+1);
// constructor uint256(vector<char>):
BOOST_CHECK(R1L.ToString() == ArrayToString(R1Array,32));
BOOST_CHECK(R1S.ToString() == ArrayToString(R1Array,20));
BOOST_CHECK(R2L.ToString() == ArrayToString(R2Array,32));
BOOST_CHECK(R2S.ToString() == ArrayToString(R2Array,20));
BOOST_CHECK(ZeroL.ToString() == ArrayToString(ZeroArray,32));
BOOST_CHECK(ZeroS.ToString() == ArrayToString(ZeroArray,20));
BOOST_CHECK(OneL.ToString() == ArrayToString(OneArray,32));
BOOST_CHECK(OneS.ToString() == ArrayToString(OneArray,20));
BOOST_CHECK(MaxL.ToString() == ArrayToString(MaxArray,32));
BOOST_CHECK(MaxS.ToString() == ArrayToString(MaxArray,20));
BOOST_CHECK(OneL.ToString() != ArrayToString(ZeroArray,32));
BOOST_CHECK(OneS.ToString() != ArrayToString(ZeroArray,20));
// == and !=
BOOST_CHECK(R1L != R2L && R1S != R2S);
BOOST_CHECK(ZeroL != OneL && ZeroS != OneS);
BOOST_CHECK(OneL != ZeroL && OneS != ZeroS);
BOOST_CHECK(MaxL != ZeroL && MaxS != ZeroS);
// String Constructor and Copy Constructor
BOOST_CHECK(uint256S("0x"+R1L.ToString()) == R1L);
BOOST_CHECK(uint256S("0x"+R2L.ToString()) == R2L);
BOOST_CHECK(uint256S("0x"+ZeroL.ToString()) == ZeroL);
BOOST_CHECK(uint256S("0x"+OneL.ToString()) == OneL);
BOOST_CHECK(uint256S("0x"+MaxL.ToString()) == MaxL);
BOOST_CHECK(uint256S(R1L.ToString()) == R1L);
BOOST_CHECK(uint256S(" 0x"+R1L.ToString()+" ") == R1L);
BOOST_CHECK(uint256S("") == ZeroL);
BOOST_CHECK(R1L == uint256S(R1ArrayHex));
BOOST_CHECK(uint256(R1L) == R1L);
BOOST_CHECK(uint256(ZeroL) == ZeroL);
BOOST_CHECK(uint256(OneL) == OneL);
BOOST_CHECK(uint160S("0x"+R1S.ToString()) == R1S);
BOOST_CHECK(uint160S("0x"+R2S.ToString()) == R2S);
BOOST_CHECK(uint160S("0x"+ZeroS.ToString()) == ZeroS);
BOOST_CHECK(uint160S("0x"+OneS.ToString()) == OneS);
BOOST_CHECK(uint160S("0x"+MaxS.ToString()) == MaxS);
BOOST_CHECK(uint160S(R1S.ToString()) == R1S);
BOOST_CHECK(uint160S(" 0x"+R1S.ToString()+" ") == R1S);
BOOST_CHECK(uint160S("") == ZeroS);
BOOST_CHECK(R1S == uint160S(R1ArrayHex));
BOOST_CHECK(uint160(R1S) == R1S);
BOOST_CHECK(uint160(ZeroS) == ZeroS);
BOOST_CHECK(uint160(OneS) == OneS);
}
BOOST_AUTO_TEST_CASE( comparison ) // <= >= < >
{
uint256 LastL;
for (int i = 255; i >= 0; --i) {
uint256 TmpL;
*(TmpL.begin() + (i>>3)) |= 1<<(7-(i&7));
BOOST_CHECK( LastL < TmpL );
LastL = TmpL;
}
BOOST_CHECK( ZeroL < R1L );
BOOST_CHECK( R2L < R1L );
BOOST_CHECK( ZeroL < OneL );
BOOST_CHECK( OneL < MaxL );
BOOST_CHECK( R1L < MaxL );
BOOST_CHECK( R2L < MaxL );
uint160 LastS;
for (int i = 159; i >= 0; --i) {
uint160 TmpS;
*(TmpS.begin() + (i>>3)) |= 1<<(7-(i&7));
BOOST_CHECK( LastS < TmpS );
LastS = TmpS;
}
BOOST_CHECK( ZeroS < R1S );
BOOST_CHECK( R2S < R1S );
BOOST_CHECK( ZeroS < OneS );
BOOST_CHECK( OneS < MaxS );
BOOST_CHECK( R1S < MaxS );
BOOST_CHECK( R2S < MaxS );
}
BOOST_AUTO_TEST_CASE( methods ) // GetHex SetHex begin() end() size() GetLow64 GetSerializeSize, Serialize, Unserialize
{
BOOST_CHECK(R1L.GetHex() == R1L.ToString());
BOOST_CHECK(R2L.GetHex() == R2L.ToString());
BOOST_CHECK(OneL.GetHex() == OneL.ToString());
BOOST_CHECK(MaxL.GetHex() == MaxL.ToString());
uint256 TmpL(R1L);
BOOST_CHECK(TmpL == R1L);
TmpL.SetHex(R2L.ToString()); BOOST_CHECK(TmpL == R2L);
TmpL.SetHex(ZeroL.ToString()); BOOST_CHECK(TmpL == uint256());
TmpL.SetHex(R1L.ToString());
BOOST_CHECK(memcmp(R1L.begin(), R1Array, 32)==0);
BOOST_CHECK(memcmp(TmpL.begin(), R1Array, 32)==0);
BOOST_CHECK(memcmp(R2L.begin(), R2Array, 32)==0);
BOOST_CHECK(memcmp(ZeroL.begin(), ZeroArray, 32)==0);
BOOST_CHECK(memcmp(OneL.begin(), OneArray, 32)==0);
BOOST_CHECK(R1L.size() == sizeof(R1L));
BOOST_CHECK(sizeof(R1L) == 32);
BOOST_CHECK(R1L.size() == 32);
BOOST_CHECK(R2L.size() == 32);
BOOST_CHECK(ZeroL.size() == 32);
BOOST_CHECK(MaxL.size() == 32);
BOOST_CHECK(R1L.begin() + 32 == R1L.end());
BOOST_CHECK(R2L.begin() + 32 == R2L.end());
BOOST_CHECK(OneL.begin() + 32 == OneL.end());
BOOST_CHECK(MaxL.begin() + 32 == MaxL.end());
BOOST_CHECK(TmpL.begin() + 32 == TmpL.end());
BOOST_CHECK(GetSerializeSize(R1L, 0, PROTOCOL_VERSION) == 32);
BOOST_CHECK(GetSerializeSize(ZeroL, 0, PROTOCOL_VERSION) == 32);
CDataStream ss(0, PROTOCOL_VERSION);
ss << R1L;
BOOST_CHECK(ss.str() == std::string(R1Array,R1Array+32));
ss >> TmpL;
BOOST_CHECK(R1L == TmpL);
ss.clear();
ss << ZeroL;
BOOST_CHECK(ss.str() == std::string(ZeroArray,ZeroArray+32));
ss >> TmpL;
BOOST_CHECK(ZeroL == TmpL);
ss.clear();
ss << MaxL;
BOOST_CHECK(ss.str() == std::string(MaxArray,MaxArray+32));
ss >> TmpL;
BOOST_CHECK(MaxL == TmpL);
ss.clear();
BOOST_CHECK(R1S.GetHex() == R1S.ToString());
BOOST_CHECK(R2S.GetHex() == R2S.ToString());
BOOST_CHECK(OneS.GetHex() == OneS.ToString());
BOOST_CHECK(MaxS.GetHex() == MaxS.ToString());
uint160 TmpS(R1S);
BOOST_CHECK(TmpS == R1S);
TmpS.SetHex(R2S.ToString()); BOOST_CHECK(TmpS == R2S);
TmpS.SetHex(ZeroS.ToString()); BOOST_CHECK(TmpS == uint160());
TmpS.SetHex(R1S.ToString());
BOOST_CHECK(memcmp(R1S.begin(), R1Array, 20)==0);
BOOST_CHECK(memcmp(TmpS.begin(), R1Array, 20)==0);
BOOST_CHECK(memcmp(R2S.begin(), R2Array, 20)==0);
BOOST_CHECK(memcmp(ZeroS.begin(), ZeroArray, 20)==0);
BOOST_CHECK(memcmp(OneS.begin(), OneArray, 20)==0);
BOOST_CHECK(R1S.size() == sizeof(R1S));
BOOST_CHECK(sizeof(R1S) == 20);
BOOST_CHECK(R1S.size() == 20);
BOOST_CHECK(R2S.size() == 20);
BOOST_CHECK(ZeroS.size() == 20);
BOOST_CHECK(MaxS.size() == 20);
BOOST_CHECK(R1S.begin() + 20 == R1S.end());
BOOST_CHECK(R2S.begin() + 20 == R2S.end());
BOOST_CHECK(OneS.begin() + 20 == OneS.end());
BOOST_CHECK(MaxS.begin() + 20 == MaxS.end());
BOOST_CHECK(TmpS.begin() + 20 == TmpS.end());
BOOST_CHECK(GetSerializeSize(R1S, 0, PROTOCOL_VERSION) == 20);
BOOST_CHECK(GetSerializeSize(ZeroS, 0, PROTOCOL_VERSION) == 20);
ss << R1S;
BOOST_CHECK(ss.str() == std::string(R1Array,R1Array+20));
ss >> TmpS;
BOOST_CHECK(R1S == TmpS);
ss.clear();
ss << ZeroS;
BOOST_CHECK(ss.str() == std::string(ZeroArray,ZeroArray+20));
ss >> TmpS;
BOOST_CHECK(ZeroS == TmpS);
ss.clear();
ss << MaxS;
BOOST_CHECK(ss.str() == std::string(MaxArray,MaxArray+20));
ss >> TmpS;
BOOST_CHECK(MaxS == TmpS);
ss.clear();
}
BOOST_AUTO_TEST_CASE( conversion )
{
BOOST_CHECK(ArithToUint256(UintToArith256(ZeroL)) == ZeroL);
BOOST_CHECK(ArithToUint256(UintToArith256(OneL)) == OneL);
BOOST_CHECK(ArithToUint256(UintToArith256(R1L)) == R1L);
BOOST_CHECK(ArithToUint256(UintToArith256(R2L)) == R2L);
BOOST_CHECK(UintToArith256(ZeroL) == 0);
BOOST_CHECK(UintToArith256(OneL) == 1);
BOOST_CHECK(ArithToUint256(0) == ZeroL);
BOOST_CHECK(ArithToUint256(1) == OneL);
BOOST_CHECK(arith_uint256(R1L.GetHex()) == UintToArith256(R1L));
BOOST_CHECK(arith_uint256(R2L.GetHex()) == UintToArith256(R2L));
BOOST_CHECK(R1L.GetHex() == UintToArith256(R1L).GetHex());
BOOST_CHECK(R2L.GetHex() == UintToArith256(R2L).GetHex());
}
BOOST_AUTO_TEST_SUITE_END()
|
// MFCActiveSoftwareDlg.cpp: 实现文件
//
#include "pch.h"
#include "framework.h"
#include "MFCActiveSoftware.h"
#include "MFCActiveSoftwareDlg.h"
#include "afxdialogex.h"
#include "activity.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
#include "CDlgMakeDlg.h"
#include "CDlgOkExit.h"
#include "md5.h"
// 用于应用程序“关于”菜单项的 CAboutDlg 对话框
class CAboutDlg : public CDialogEx
{
public:
CAboutDlg();
// 对话框数据
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_ABOUTBOX };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
// 实现
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()
// CMFCActiveSoftwareDlg 对话框
CMFCActiveSoftwareDlg::CMFCActiveSoftwareDlg(CWnd* pParent /*=nullptr*/)
: CDialogEx(IDD_MFCACTIVESOFTWARE_DIALOG, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CMFCActiveSoftwareDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CMFCActiveSoftwareDlg, CDialogEx)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDCANCEL, &CMFCActiveSoftwareDlg::OnBnClickedCancel)
ON_BN_CLICKED(IDOK, &CMFCActiveSoftwareDlg::OnBnClickedOk)
ON_NOTIFY(NM_CLICK, IDC_SYSLINK_TOBUY, &CMFCActiveSoftwareDlg::OnNMClickSyslinkTobuy)
END_MESSAGE_MAP()
// CMFCActiveSoftwareDlg 消息处理程序
CActivitySoftware act;
string prod;
BOOL CMFCActiveSoftwareDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// 将“关于...”菜单项添加到系统菜单中。
// IDM_ABOUTBOX 必须在系统命令范围内。
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != nullptr)
{
BOOL bNameValid;
CString strAboutMenu;
bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
ASSERT(bNameValid);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// 设置此对话框的图标。 当应用程序主窗口不是对话框时,框架将自动
// 执行此操作
SetIcon(m_hIcon, TRUE); // 设置大图标
SetIcon(m_hIcon, FALSE); // 设置小图标
// TODO: 在此添加额外的初始化代码
fstream fp("act.key", ios::in|ios::binary);
if (!fp) {
fp.close();
CDlgMakeDlg mk;
mk.DoModal();
exit(2);
}
fstream okfp("act.ok.key", ios::in | ios::binary);
string cmdl = ::GetCommandLineA();
int cmdlpos = cmdl.find_last_of('\\', cmdl.length());
if(cmdlpos!=cmdl.npos) cmdl = cmdl.substr(cmdlpos,cmdl.length());
vector<string> cmdlarr;
str_split(cmdl, " ", cmdlarr);
if (cmdlarr.size() > 1 && cmdlarr[1] == "--checkActiveStatus") {
if (okfp) {
vector<string> lst;
GetActKeyList(lst);
char ukay[64];
okfp.getline(ukay, 64);
okfp.close();
for (auto i : lst) {
if ((string)ukay == i) {
exit(0);
}
}
if (MessageBox(L"错误!文件遭到非法篡改!\n恢复文件?", L"错误", MB_ICONERROR | MB_YESNO) == IDYES) {
system("del /f /s /q act.ok.key");
}
else
exit(3);
}
else { okfp.close(); exit(1); }
exit(1);
}
if (okfp) {
vector<string> lst;
GetActKeyList(lst);
char ukay[64];
okfp.getline(ukay, 64);
okfp.close();
for (auto i : lst) {
if ((string)ukay == i) {
exit(0);
}
}
if (MessageBox(L"错误!文件遭到非法篡改!\n恢复文件?", L"错误", MB_ICONERROR | MB_YESNO) == IDYES) {
system("del /f /s /q act.ok.key");
} else
exit(3);
} else okfp.close();
CActivitySoftwareIFMS ifms;
ActKeyFileToObj(ifms);
prod = ifms.product;
SetDlgItemTextA(AfxGetMainWnd()->GetSafeHwnd(), IDC_SHOW_WEL_SOFTNAME, ((string)"欢迎使用 " + prod + "!").c_str());
SetDlgItemTextA(this->GetSafeHwnd(), IDC_SHOW_ACTIFMS, ((string)"" +
"软件名称: " + ifms.product +"\r\n"
"公司名称: " + ifms.company +"\r\n"
"购买激活码: " + ifms.buyurl +"\r\n"
"").c_str());
SetDlgItemTextA(this->GetSafeHwnd(), IDC_SHOW_CRIFMS, ifms.copyright.c_str());
SetWindowTextA(this->GetSafeHwnd(), ((string)"激活" + prod).c_str());
fp.close();
return TRUE; // 除非将焦点设置到控件,否则返回 TRUE
}
void CMFCActiveSoftwareDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialogEx::OnSysCommand(nID, lParam);
}
}
// 如果向对话框添加最小化按钮,则需要下面的代码
// 来绘制该图标。 对于使用文档/视图模型的 MFC 应用程序,
// 这将由框架自动完成。
void CMFCActiveSoftwareDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // 用于绘制的设备上下文
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// 使图标在工作区矩形中居中
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// 绘制图标
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialogEx::OnPaint();
}
}
//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CMFCActiveSoftwareDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CMFCActiveSoftwareDlg::OnBnClickedCancel()
{
// TODO: 在此添加控件通知处理程序代码
exit(1);
}
string ws2s(wstring wstr)
{
string result;
int len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), NULL, 0, NULL, NULL);
if (len <= 0)return result;
char* buffer = new char[len + 1];
if (buffer == NULL)return result;
WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), buffer, len, NULL, NULL);
buffer[len] = '\0';
result.append(buffer);
delete[] buffer;
return result;
}
#include<vector>
#include<algorithm>
void CMFCActiveSoftwareDlg::OnBnClickedOk()
{
// TODO: 在此添加控件通知处理程序代码
CString uk=L"";
GetDlgItemText(IDC_EDIT_ACTCODE, uk);
if(uk.GetLength()<1) {
MessageBox(L"请输入激活码!", L"错误", MB_ICONERROR); return;
}
string ukay = MD5(ws2s(uk.GetBuffer())).toString();
vector<string> kls;
GetActKeyList(kls);
for (auto k : kls) {
if (ukay==k) {
fstream fpok("act.ok.key", ios::out); fpok << ukay; fpok.close();
CDlgOkExit ok;
ok.DoModal();
exit(0);
}
}
MessageBox(L"激活失败!", L"错误", MB_ICONERROR);
}
void CMFCActiveSoftwareDlg::OnNMClickSyslinkTobuy(NMHDR* pNMHDR, LRESULT* pResult)
{
// TODO: 在此添加控件通知处理程序代码
CActivitySoftwareIFMS i;
ActKeyFileToObj(i);
system(i.buyurl.c_str());
}
BOOL CMFCActiveSoftwareDlg::PreTranslateMessage(MSG* pMsg)
{
// TODO: 在此添加专用代码和/或调用基类
return CDialogEx::PreTranslateMessage(pMsg);
}
|
/* $Id$ */
/*
* Copyright (c) 2013 Roland van Rijswijk-Deij
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
/*****************************************************************************
silvia_verifier.cpp
Command-line verifier utility
*****************************************************************************/
#include "config.h"
#include "silvia_parameters.h"
#include "silvia_irma_verifier.h"
#ifdef WITH_PCSC
#include "silvia_pcsc_card.h"
#endif // WITH_PCSC
#ifdef WITH_NFC
#include "silvia_nfc_card.h"
#endif // WITH_NFC
#include "silvia_stdio_card.h"
#include "silvia_card_channel.h"
#include "silvia_irma_xmlreader.h"
#include "silvia_idemix_xmlreader.h"
#include "silvia_types.h"
#include <string>
#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <time.h>
#include <signal.h>
const char* weekday[7] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
const char* month[12] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
#define IRMA_VERIFIER_METADATA_OFFSET (32 - 6)
bool parseable_output = false;
void signal_handler(int signal)
{
// Exit on any signal we receive and handle
if(parseable_output)
{
printf("error signal\n"); fflush(stdout);
exit(-1);
}
else
{
fprintf(stderr, "\nCaught signal, exiting...\n");
}
exit(0);
}
void set_parameters()
{
////////////////////////////////////////////////////////////////////
// Set the system parameters in the IRMA library; this function must
// be updated if we ever change the parameters for IRMA cards!!!
////////////////////////////////////////////////////////////////////
silvia_system_parameters::i()->set_l_n(1024);
silvia_system_parameters::i()->set_l_m(256);
silvia_system_parameters::i()->set_l_statzk(80);
silvia_system_parameters::i()->set_l_H(256);
silvia_system_parameters::i()->set_l_v(1700);
silvia_system_parameters::i()->set_l_e(597);
silvia_system_parameters::i()->set_l_e_prime(120);
silvia_system_parameters::i()->set_hash_type("sha256");
}
void version(void)
{
if(parseable_output)
{
printf("info version %s\n", VERSION); fflush(stdout);
}
else
{
printf("The Simple Library for Verifying and Issuing Attributes (silvia)\n");
printf("\n");
printf("Command-line verification utility for IRMA cards %s\n", VERSION);
printf("\n");
printf("Copyright (c) 2013 Roland van Rijswijk-Deij\n\n");
printf("Use, modification and redistribution of this software is subject to the terms\n");
printf("of the license agreement. This software is licensed under a 2-clause BSD-style\n");
printf("license a copy of which is included as the file LICENSE in the distribution.\n");
}
}
void usage(void)
{
printf("Silvia command-line IRMA verifier %s\n\n", VERSION);
printf("Usage:\n");
printf("\tsilvia_verifier -I <issuer-spec> -V <verifier-spec> -k <issuer-pubkey> [-p] [-S]");
#if defined(WITH_PCSC)
printf(" [-P]");
#endif // WITH_PCSC
#if defined(WITH_NFC)
printf(" [-N]");
#endif // WITH_NFC
printf("\n");
printf("\tsilvia_verifier -h\n");
printf("\tsilvia_verifier -v\n");
printf("\n");
printf("\t-I <issuer-spec> Read issuer specification from <issuer-spec>\n");
printf("\t-V <verifier-spec> Read verifier specification from <verifier-spec>\n");
printf("\t-k <issuer-pubkey> Read issuer public key from <issuer-pubkey>\n");
printf("\t-p Force PIN verification\n");
#if defined(WITH_PCSC)
printf("\t-P Use PC/SC for card communication (default)\n");
#endif // WITH_PCSC
#if defined(WITH_NFC)
printf("\t-N Use NFC for card communication\n");
#endif // WITH_NFC
printf("\t-S Use StdIO for card communication (changes output to parseable format)\n");
printf("\n");
printf("\t-h Print this help message\n");
printf("\n");
printf("\t-v Print the version number\n");
}
bool verify_pin(silvia_card_channel* card)
{
if(parseable_output)
{
printf("control send-pin\n"); fflush(stdout);
}
else
{
printf("\n");
printf("=================================================\n");
printf(" PIN VERIFICATION REQUIRED \n");
printf("=================================================\n");
printf("\n");
}
std::string PIN;
do
{
if(parseable_output)
{
char response_type[50];
std::string response;
std::cin >> response_type >> response;
if(strcmp(response_type, "PIN") == 0)
{
PIN = response;
}
else
{
if(strcmp(response_type, "PIN-result") == 0 && response.compare("OK"))
{
// The client said it authenticated successfully to the card.
// If it had not, the card will error out later
return true;
}
// TODO: Wrong state?
}
}
else
{
PIN = getpass("Please enter your PIN: ");
}
if (PIN.size() > 8)
{
if(parseable_output)
{
printf("warning pin-too-long\n"); fflush(stdout);
}
else
{
printf("PIN too long; 8 characters or less expected!\n");
}
}
else if (PIN.empty())
{
if(parseable_output)
{
printf("warning no-pin\n"); fflush(stdout);
}
else
{
printf("You must enter a PIN!\n");
}
}
}
while (PIN.empty() || (PIN.size() > 8));
if(!parseable_output)
{
printf("\n");
printf("Verifying PIN... "); fflush(stdout);
}
bytestring verify_pin_apdu = "0020000008";
for (std::string::iterator i = PIN.begin(); i != PIN.end(); i++)
{
verify_pin_apdu += (unsigned char) *i;
}
while (verify_pin_apdu.size() < 13)
{
verify_pin_apdu += "00";
}
bytestring data;
unsigned short sw;
if (!card->transmit(verify_pin_apdu, data, sw))
{
if(!parseable_output)
{
printf("FAILED (card communication)\n");
}
return false;
}
if (sw == 0x9000)
{
if(!parseable_output)
{
printf("OK\n");
}
return true;
}
else if (sw == 0x63C0)
{
if(parseable_output)
{
printf("error card-blocked\n"); fflush(stdout);
exit(-1);
}
else
{
printf("FAILED, the card has been blocked (entered wrong PIN too many times)\n");
}
}
else if ((sw > 0x63C0) && (sw <= 0x63CF))
{
if(parseable_output)
{
printf("error incorrect-pin %u\n", sw - 0x63C0); fflush(stdout);
exit(-1);
}
else
{
printf("FAILED (%u attempts remaining)\n", sw - 0x63C0);
}
}
else
{
if(parseable_output)
{
printf("error card-error 0x%04X\n", sw); fflush(stdout);
exit(-1);
}
else
{
printf("FAILED (card error 0x%04X)\n", sw);
}
}
return false;
}
bytestring bs2str(const bytestring& in)
{
bytestring out = in;
// Strip leading 00's
while ((out.size() > 0) && (out[0] == 0x00))
{
out = out.substr(1);
}
// Append null-termination
out += 0x00;
return out;
}
bool communicate_with_card(silvia_card_channel* card, std::vector<bytestring>& commands, std::vector<bytestring>& results, bool force_pin)
{
if(!parseable_output)
{
printf("Communicating with the card... "); fflush(stdout);
}
bool comm_ok = true;
size_t cmd_ctr = 0;
for (std::vector<bytestring>::iterator i = commands.begin(); (i != commands.end()) && comm_ok; i++)
{
bytestring result;
if (!card->transmit(*i, result))
{
comm_ok = false;
break;
}
cmd_ctr++;
if ((force_pin) && (cmd_ctr == 1))
{
if (!verify_pin(card))
{
comm_ok = false;
break;
}
if(!parseable_output)
{
printf("Communicating with the card... "); fflush(stdout);
}
}
else if (result.substr(result.size() - 2) == "6982")
{
// The card wants us to enter a PIN before producing the proof
if (!verify_pin(card))
{
comm_ok = false;
break;
}
if(!parseable_output)
{
printf("Communicating with the card... "); fflush(stdout);
}
// Re-execute the command
if (!card->transmit(*i, result))
{
comm_ok = false;
break;
}
}
else if ((result.substr(result.size() - 2) != "9000") &&
(result.substr(result.size() - 2) != "6A82") &&
(result.substr(result.size() - 2) != "6D00"))
{
if(parseable_output)
{
printf("error card-error 0x%s", result.substr(result.size() - 2).hex_str().c_str()); fflush(stdout);
exit(-1);
}
else
{
printf("(0x%s) ", result.substr(result.size() - 2).hex_str().c_str());
}
comm_ok = false;
break;
}
results.push_back(result);
}
if(!parseable_output)
{
if (comm_ok)
{
printf("OK\n");
}
else
{
printf("FAILED!\n");
}
}
return comm_ok;
}
void verifier_loop(std::string issuer_spec, std::string verifier_spec, std::string issuer_pubkey, bool force_pin, int channel_type)
{
silvia_card_channel* card = NULL;
if(!parseable_output)
{
printf("Silvia command-line IRMA verifier %s\n\n", VERSION);
}
// Read configuration files
silvia_verifier_specification* vspec = silvia_irma_xmlreader::i()->read_verifier_spec(issuer_spec, verifier_spec);
if (vspec == NULL)
{
if(parseable_output)
{
printf("error spec-error\n"); fflush(stdout);
exit(-2);
}
else
{
fprintf(stderr, "Failed to read issuer and verifier specification\n");
}
return;
}
silvia_pub_key* pubkey = silvia_idemix_xmlreader::i()->read_idemix_pubkey(issuer_pubkey);
if (pubkey == NULL)
{
if(parseable_output)
{
printf("error key-error\n"); fflush(stdout);
exit(-2);
}
else
{
fprintf(stderr, "Failed to read issuer public key\n");
}
delete vspec;
return;
}
// Create verifier object
silvia_irma_verifier verifier(pubkey, vspec);
while (true)
{
if(!parseable_output)
{
printf("\n********************************************************************************\n");
printf("%s: %s\n\n", vspec->get_verifier_name().c_str(), vspec->get_short_msg().c_str());
printf("Waiting for card");
}
#ifdef WITH_PCSC
if (channel_type == SILVIA_CHANNEL_PCSC)
{
printf(" (PCSC) ..."); fflush(stdout);
silvia_pcsc_card* pcsc_card = NULL;
if (!silvia_pcsc_card_monitor::i()->wait_for_card(&pcsc_card))
{
printf("FAILED, exiting\n");
exit(-1);
}
card = pcsc_card;
}
#endif // WITH_PCSC
#ifdef WITH_NFC
if (channel_type == SILVIA_CHANNEL_NFC)
{
printf(" (NFC) ..."); fflush(stdout);
silvia_nfc_card* nfc_card = NULL;
if (!silvia_nfc_card_monitor::i()->wait_for_card(&nfc_card))
{
printf("FAILED, exiting\n");
exit(-1);
}
card = nfc_card;
}
#endif // WITH_NFC
if (channel_type == SILVIA_CHANNEL_STDIO)
{
silvia_stdio_card* stdio_card = NULL;
stdio_card = new silvia_stdio_card();
card = stdio_card;
}
if(!parseable_output)
{
printf("OK\n");
}
// First, perform application selection
std::vector<bytestring> commands;
std::vector<bytestring> results;
commands = verifier.get_select_commands();
if (communicate_with_card(card, commands, results, false))
{
if (verifier.submit_select_data(results))
{
// Now, perform the actual verification
commands.clear();
results.clear();
commands = verifier.get_proof_commands();
if (communicate_with_card(card, commands, results, force_pin))
{
if(!parseable_output)
{
printf("Verifying proof... "); fflush(stdout);
}
std::vector<std::pair<std::string, bytestring> > revealed;
if (verifier.submit_and_verify(results, revealed))
{
if(!parseable_output)
{
printf("OK\n");
printf("\n");
}
if (revealed.size() > 0)
{
if(parseable_output)
{
printf("result OK\n"); fflush(stdout);
}
else
{
printf("Revealed attributes:\n\n");
printf("Attribute |Value\n");
printf("--------------------+-----------------------------------------------------------\n");
}
std::vector<std::pair<std::string, bytestring> >::iterator i = revealed.begin();
// Check if the first attribute is "expires"
if ((i->first == "expires") || (i->first == "metadata"))
{
// Check if this is an "old style" expires or a "new style" expires attribute
time_t expires;
if (i->second[IRMA_VERIFIER_METADATA_OFFSET] != 0x00)
{
// Check metadata version number
if (i->second[IRMA_VERIFIER_METADATA_OFFSET] != 0x01)
{
if(parseable_output)
{
printf("result expiry unknown\n"); fflush(stdout);
}
else
{
printf("Invalid metadata attribute found!\n");
}
}
else
{
// Reconstruct expiry data from metadata
expires = 0;
expires += i->second[IRMA_VERIFIER_METADATA_OFFSET + 1] << 16;
expires += i->second[IRMA_VERIFIER_METADATA_OFFSET + 2] << 8;
expires += i->second[IRMA_VERIFIER_METADATA_OFFSET + 3];
expires *= 86400; // convert days to seconds
// Reconstruct credential ID as issued from metadata
unsigned short issued_id = 0;
issued_id += i->second[IRMA_VERIFIER_METADATA_OFFSET + 4] << 8;
issued_id += i->second[IRMA_VERIFIER_METADATA_OFFSET + 5];
if(parseable_output)
{
if(!issued_id == vspec->get_credential_id())
{
printf("carderror credential-mismatch\n"); fflush(stdout);
}
std::cout << "result expiry " << expires << std::endl;
}
else
{
struct tm* date = gmtime(&expires);
printf("%-20s|%d (%s)\n", "credential ID", issued_id, (issued_id == vspec->get_credential_id()) ? "matches" : "DOES NOT MATCH");
printf("%-20s|%s %s %d %d\n", i->first.c_str(),
weekday[date->tm_wday],
month[date->tm_mon],
date->tm_mday,
date->tm_year + 1900);
}
}
}
else
{
// This is old style
expires = (i->second[i->second.size() - 2] << 8) + (i->second[i->second.size() - 1]);
expires *= 86400; // convert days to seconds
if(parseable_output)
{
std::cout << "result expiry " << expires << std::endl;
}
else
{
struct tm* date = gmtime(&expires);
printf("%-20s|%s %s %d %d\n", i->first.c_str(),
weekday[date->tm_wday],
month[date->tm_mon],
date->tm_mday,
date->tm_year + 1900);
}
}
i++;
}
// Assume the other attributes are strings
for (; i != revealed.end(); i++)
{
if(parseable_output)
{
printf("attribute %s %s\n", i->first.c_str(), (const char*) bs2str(i->second).byte_str()); fflush(stdout);
}
else
{
printf("%-20s|%-59s\n", i->first.c_str(), (const char*) bs2str(i->second).byte_str());
}
}
if(!parseable_output)
{
printf("\n");
}
}
}
else
{
if(parseable_output)
{
printf("carderror invalid-sig\n"); fflush(stdout);
exit(-1);
}
else
{
printf("FAILED\n");
}
}
}
else
{
verifier.abort();
}
}
else
{
if(parseable_output)
{
printf("carderror no-application\n"); fflush(stdout);
exit(-1);
}
else
{
printf("Failed to select IRMA application!\n");
}
verifier.abort();
}
}
else
{
verifier.abort();
}
if(!parseable_output)
{
printf("Waiting for card to be removed... "); fflush(stdout);
while (card->status())
{
usleep(10000);
}
printf("OK\n");
printf("********************************************************************************\n");
}
delete card;
if(parseable_output)
{
// Exit
break;
}
}
delete vspec;
delete pubkey;
}
int main(int argc, char* argv[])
{
// Set library parameters
set_parameters();
// Program parameters
std::string issuer_spec;
std::string verifier_spec;
std::string issuer_pubkey;
bool force_pin = false;
int c = 0;
#if defined(WITH_PCSC)
int channel_type = SILVIA_CHANNEL_PCSC;
#elif defined(WITH_NFC)
int channel_type = SILVIA_CHANNEL_NFC;
#else
int channel_type = SILVIA_CHANNEL_STDIO;
#endif
#if defined(WITH_PCSC) && defined(WITH_NFC)
while ((c = getopt(argc, argv, "I:V:k:phvSPN")) != -1)
#elif defined(WITH_PCSC)
while ((c = getopt(argc, argv, "I:V:k:phvSP")) != -1)
#elif defined(WITH_NFC)
while ((c = getopt(argc, argv, "I:V:k:phvSN")) != -1)
#else
while ((c = getopt(argc, argv, "I:V:k:phvS")) != -1)
#endif
{
switch (c)
{
case 'h':
usage();
return 0;
case 'v':
version();
return 0;
case 'I':
issuer_spec = std::string(optarg);
break;
case 'V':
verifier_spec = std::string(optarg);
break;
case 'k':
issuer_pubkey = std::string(optarg);
break;
case 'p':
force_pin = true;
break;
case 'S':
channel_type = SILVIA_CHANNEL_STDIO;
parseable_output = true;
break;
#if defined(WITH_PCSC)
case 'P':
channel_type = SILVIA_CHANNEL_PCSC;
break;
#endif
#if defined(WITH_NFC)
case 'N':
channel_type = SILVIA_CHANNEL_NFC;
break;
#endif
}
}
if (issuer_spec.empty())
{
if(parseable_output)
{
printf("error no-spec\n"); fflush(stdout);
exit(-3);
}
else
{
fprintf(stderr, "No issuer specification file specified!\n");
}
return -1;
}
if (verifier_spec.empty())
{
if(parseable_output)
{
printf("error no-verifier\n"); fflush(stdout);
exit(-3);
}
else
{
fprintf(stderr, "No verifier specification file specified!\n");
}
return -1;
}
if (issuer_pubkey.empty())
{
if(parseable_output)
{
printf("error no-pubkey\n"); fflush(stdout);
exit(-3);
}
else
{
fprintf(stderr, "No issuer public key file specified!\n");
}
return -1;
}
#ifdef WITH_NFC
if (channel_type == SILVIA_CHANNEL_NFC)
{
// Handle signals when using NFC; this prevents the NFC reader
// from going into an undefined state when the user aborts the
// program by pressing Ctrl+C
signal(SIGQUIT, signal_handler);
signal(SIGTERM, signal_handler);
signal(SIGINT, signal_handler);
signal(SIGABRT, signal_handler);
}
#endif
verifier_loop(issuer_spec, verifier_spec, issuer_pubkey, force_pin, channel_type);
return 0;
}
|
#include "../features.hpp"
#include "../rage/backtrack.h"
extern hooks::draw_model_execute::fn draw_model_execute_original;
////////////////////////////////////////////////////////////////////////////////////////////////////////
/* Smoke Shit */
std::vector<const char*> vistasmoke_mats =
{
"particle/vistasmokev1/vistasmokev1_fire",
"particle/vistasmokev1/vistasmokev1_smokegrenade",
"particle/vistasmokev1/vistasmokev1_emods",
"particle/vistasmokev1/vistasmokev1_emods_impactdust",
};
void override_material(bool ignorez, bool wireframe, const color& rgba) {
auto material = interfaces::material_system->find_material("debug/debugambientcube", TEXTURE_GROUP_MODEL);
material->set_material_var_flag(material_var_ignorez, ignorez);
material->set_material_var_flag(material_var_wireframe, wireframe);
material->alpha_modulate(rgba.a / 255.f);
material->color_modulate(rgba.r / 255.f, rgba.g / 255.f, rgba.b / 255.f);
interfaces::model_render->override_material(material);
}
void override_material_smoke(bool ignorez, bool wireframe, bool draw, const color& rgba) {
auto material = interfaces::material_system->find_material("debug/debugambientcube", TEXTURE_GROUP_MODEL);
material->set_material_var_flag(material_var_ignorez, ignorez);
material->set_material_var_flag(material_var_wireframe, wireframe);
material->set_material_var_flag(material_var_no_draw, draw);
material->alpha_modulate(rgba.a / 255.f);
material->color_modulate(rgba.r / 255.f, rgba.g / 255.f, rgba.b / 255.f);
interfaces::model_render->override_material(material);
}
void override_material_flat(bool ignorez, bool wireframe, bool flat, const color& rgba) {
auto material = interfaces::material_system->find_material("debug/debugdrawflat", TEXTURE_GROUP_MODEL);
material->set_material_var_flag(material_var_ignorez, ignorez);
material->set_material_var_flag(material_var_wireframe, wireframe);
material->set_material_var_flag(material_var_flat, flat);
material->alpha_modulate(rgba.a / 255.f);
material->color_modulate(rgba.r / 255.f, rgba.g / 255.f, rgba.b / 255.f);
interfaces::model_render->override_material(material);
}
void override_material_gloss(bool ignorez, bool wireframe, const color& rgba) {
auto material = interfaces::material_system->find_material("models/inventory_items/trophy_majors/gloss", TEXTURE_GROUP_MODEL);
material->set_material_var_flag(material_var_ignorez, ignorez);
material->set_material_var_flag(material_var_wireframe, wireframe);
material->alpha_modulate(rgba.a / 255.f);
material->color_modulate(rgba.r / 255.f, rgba.g / 255.f, rgba.b / 255.f);
interfaces::model_render->override_material(material);
}
void override_material_crystal(bool ignorez, bool wireframe, const color& rgba) {
auto material = interfaces::material_system->find_material("debug/debugtranslucentvertexcolor", TEXTURE_GROUP_MODEL);
material->set_material_var_flag(material_var_ignorez, ignorez);
material->set_material_var_flag(material_var_wireframe, wireframe);
material->alpha_modulate(rgba.a / 255.f);
material->color_modulate(rgba.r / 255.f, rgba.g / 255.f, rgba.b / 255.f);
interfaces::model_render->override_material(material);
}
void noarms(bool ignorez, bool wireframe, const color& rgba) {
auto material = interfaces::material_system->find_material("models/inventory_items/trophy_majors/crystal_clear.vmt", TEXTURE_GROUP_MODEL);
material->set_material_var_flag(material_var_ignorez, ignorez);
material->set_material_var_flag(material_var_wireframe, wireframe);
material->alpha_modulate(rgba.a / 255.f);
material->color_modulate(rgba.r / 255.f, rgba.g / 255.f, rgba.b / 255.f);
interfaces::model_render->override_material(material);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
void chams(i_mat_render_context* ctx, const draw_model_state_t& state, const model_render_info_t& info, matrix_t* matrix)
{
if (interfaces::engine->is_in_game() == false)
return;
if (csgo::local_player == nullptr)
return;
const auto mdl = info.model;
if (!mdl)
return;
bool is_player = strstr(mdl->name, "models/player") != nullptr; /* Check if model is player */
if (variables::misc::nosmoke == true)
{
if (!csgo::local_player->is_alive())
return;
bool smoke = strstr(mdl->name, "particle/vistasmokev1/vistasmokev1_fire") != nullptr;
bool smokea = strstr(mdl->name, "vistasmokev1/vistasmokev1_smokegrenade") != nullptr;
bool smokeb = strstr(mdl->name, "particle/vistasmokev1/vistasmokev1_emods") != nullptr;
bool smokec = strstr(mdl->name, "particle/vistasmokev1/vistasmokev1_emods_impactdust") != nullptr;
if (smoke)
{
override_material_smoke(true, true, true, color(70, 70, 70, 255));
}
if (smokea)
{
override_material_smoke(true, true, true, color(70, 70, 70, 255));
}
if (smokeb)
{
override_material_smoke(true, true, true, color(70, 70, 70, 255));
}
if (smokec)
{
override_material_smoke(true, true, true, color(70, 70, 70, 150));
}
}
if (!csgo::local_player)
return;
if (csgo::local_player == nullptr)
return;
if (variables::Visuals::chams::backtrackchams == true)
{
player_t* player = reinterpret_cast<player_t*>(interfaces::entity_list->get_client_entity(info.entity_index));
if (player == nullptr)
return;
if (is_player && records[player->index()].size() > 0 && variables::aimbots::backtrack == true)
{
if (!player || !player->is_alive() || player->dormant())
return;
if (player->team() != csgo::local_player->team())
{
for (uint32_t i = 0; i < records[player->index()].size(); i++)
{
if (!backtrack.valid_tick(records[player->index()][i].simulation_time, 0.2f) || records[player->index()][i].matrix == nullptr)
continue;
override_material(false, false, color(variables::colors::cFloats::b_red - (i * (255 / records[player->index()].size())), i * (variables::colors::cFloats::b_green / records[player->index()].size()), variables::colors::cFloats::b_blue, 150));
draw_model_execute_original(interfaces::model_render, 0, ctx, state, info, records[player->index()][i].matrix);
}
}
}
}
if (variables::Visuals::chams::chams == true) /* Chams run here */
{
if (variables::Visuals::chams::chamsalways == true)
{
variables::Visuals::chams::chamsvisible = false; /* Saves cheat from having a stroke */
variables::Visuals::chams::chamsxqz = false;
if (is_player)
{
player_t* player = reinterpret_cast<player_t*>(interfaces::entity_list->get_client_entity(info.entity_index));
if (!player || !player->is_alive() || player->dormant())
return;
if (player->team() != csgo::local_player->team())
{
if (variables::colors::cMats::m_normal == true)
{
override_material(true, variables::Visuals::chams::wireframe, color(variables::colors::cFloats::c_red, variables::colors::cFloats::c_green, variables::colors::cFloats::c_blue, 255));
draw_model_execute_original(interfaces::model_render, 0, ctx, state, info, matrix);
}
if (variables::colors::cMats::m_flat)
{
override_material_flat(true, variables::Visuals::chams::wireframe, true, color(variables::colors::cFloats::c_red, variables::colors::cFloats::c_green, variables::colors::cFloats::c_blue, 255));
draw_model_execute_original(interfaces::model_render, 0, ctx, state, info, matrix);
}
if (variables::colors::cMats::m_ghost)
{
override_material_crystal(false, variables::Visuals::chams::wireframe, color(variables::colors::cFloats::c_red, variables::colors::cFloats::c_green, variables::colors::cFloats::c_blue, 255));
draw_model_execute_original(interfaces::model_render, 0, ctx, state, info, matrix);
}
}
}
}
if (variables::Visuals::chams::chamsxqz == true)
{
if (is_player)
{
player_t* player = reinterpret_cast<player_t*>(interfaces::entity_list->get_client_entity(info.entity_index));
if (!player || !player->is_alive() || player->dormant())
return;
if (player->team() != csgo::local_player->team())
{
if (variables::colors::cMats::xqz_m_normal == true)
{
if (variables::Visuals::chams::chamsvisible == true)
{
override_material(false, variables::Visuals::chams::xqz_wireframe, color(variables::colors::cFloats::c_red, variables::colors::cFloats::c_green, variables::colors::cFloats::c_blue, 255));
draw_model_execute_original(interfaces::model_render, 0, ctx, state, info, matrix);
}
override_material(true, variables::Visuals::chams::xqz_wireframe, color(variables::colors::cFloats::xqz_c_red, variables::colors::cFloats::xqz_c_green, variables::colors::cFloats::xqz_c_blue, 255));
draw_model_execute_original(interfaces::model_render, 0, ctx, state, info, matrix);
}
if (variables::colors::cMats::xqz_m_flat)
{
if (variables::Visuals::chams::chamsvisible == true)
{
override_material(false, variables::Visuals::chams::xqz_wireframe, color(variables::colors::cFloats::c_red, variables::colors::cFloats::c_green, variables::colors::cFloats::c_blue, 255));
draw_model_execute_original(interfaces::model_render, 0, ctx, state, info, matrix);
}
override_material_flat(true, variables::Visuals::chams::xqz_wireframe, true, color(variables::colors::cFloats::xqz_c_red, variables::colors::cFloats::xqz_c_green, variables::colors::cFloats::xqz_c_blue, 255));
draw_model_execute_original(interfaces::model_render, 0, ctx, state, info, matrix);
}
if (variables::colors::cMats::xqz_m_ghost)
{
if (variables::Visuals::chams::chamsvisible == true)
{
override_material(false, variables::Visuals::chams::xqz_wireframe, color(variables::colors::cFloats::c_red, variables::colors::cFloats::c_green, variables::colors::cFloats::c_blue, 255));
draw_model_execute_original(interfaces::model_render, 0, ctx, state, info, matrix);
}
override_material_crystal(true, variables::Visuals::chams::xqz_wireframe, color(variables::colors::cFloats::xqz_c_red, variables::colors::cFloats::xqz_c_green, variables::colors::cFloats::xqz_c_blue, 255));
draw_model_execute_original(interfaces::model_render, 0, ctx, state, info, matrix);
}
}
}
}
if (variables::Visuals::chams::chamsvisible == true)
{
if (is_player)
{
player_t* player = reinterpret_cast<player_t*>(interfaces::entity_list->get_client_entity(info.entity_index));
if (!player || !player->is_alive() || player->dormant())
return;
if (player->team() != csgo::local_player->team())
{
if (variables::colors::cMats::m_normal == true)
{
override_material(false, variables::Visuals::chams::wireframe, color(variables::colors::cFloats::c_red, variables::colors::cFloats::c_green, variables::colors::cFloats::c_blue, 255));
draw_model_execute_original(interfaces::model_render, 0, ctx, state, info, matrix);
}
if (variables::colors::cMats::m_flat == true)
{
override_material_flat(false, variables::Visuals::chams::wireframe, true, color(variables::colors::cFloats::c_red, variables::colors::cFloats::c_green, variables::colors::cFloats::c_blue, 255));
draw_model_execute_original(interfaces::model_render, 0, ctx, state, info, matrix);
}
if (variables::colors::cMats::m_ghost == true)
{
override_material_crystal(false, variables::Visuals::chams::wireframe, color(variables::colors::cFloats::c_red, variables::colors::cFloats::c_green, variables::colors::cFloats::c_blue, 255));
draw_model_execute_original(interfaces::model_render, 0, ctx, state, info, matrix);
}
}
}
}
}
if (variables::Visuals::chams::armschams == true) /* Chams for arms */
{
bool arms = strstr(mdl->name, "models/arms") != nullptr; /* Check model is arms */
if (arms)
{
if (csgo::local_player && csgo::local_player->is_alive()) /* Only overide localplayers arms */
{
if (variables::colors::cMats::arms::m_normal == true)
{
override_material(true, variables::Visuals::chams::hands_wireframe, color(variables::colors::cMats::arms::c_red, variables::colors::cMats::arms::c_green, variables::colors::cMats::arms::c_blue, 255));
}
if (variables::colors::cMats::arms::m_flat == true)
{
override_material_flat(true, variables::Visuals::chams::hands_wireframe, true, color(variables::colors::cMats::arms::c_red, variables::colors::cMats::arms::c_green, variables::colors::cMats::arms::c_blue, 255));
}
if (variables::colors::cMats::arms::m_crystal == true)
{
override_material_crystal(true, variables::Visuals::chams::hands_wireframe, color(variables::colors::cMats::arms::c_red, variables::colors::cMats::arms::c_green, variables::colors::cMats::arms::c_blue, 255));
}
}
}
}
if (variables::Visuals::chams::nohands == true) /* No hands, pretty self explanitory */
{
bool arms = strstr(mdl->name, "models/arms") != nullptr; /* Same thing arms chams does */
if (arms)
{
if (csgo::local_player && csgo::local_player->is_alive())
{
override_material(true, false, color(255, 255, 255, 0));
}
}
}
}
|
#pragma once
#include <filesystem>
#include <cereal/cereal.hpp>
#include <cereal/types/vector.hpp>
#include <cereal/types/string.hpp>
#include <chopper/cereal/path.hpp>
namespace chopper::layout
{
struct configuration
{
std::string input_prefix{}; // provided by user
std::filesystem::path count_filename{}; // internally set
std::filesystem::path sketch_directory{}; // internally set
std::filesystem::path output_filename{"binning.out"};
uint16_t tmax{64};
int8_t aggregate_by_column{-1};
//!\brief The number of hash functions for the IBFs.
size_t num_hash_functions{2};
//!\brief The desired false positive rate of the IBFs.
double false_positive_rate{0.05};
/*\brief A scaling factor to influence the amount of merged bins produced by the algorithm.
*
* The higher alpha, the more weight is added artificially to the low level IBFs and thus the optimal
* solution will contain less merged bins in the end because it costs more to merge bins.
*/
double alpha{1.2};
//!\brief The maximal cardinality ratio in the clustering intervals.
double max_rearrangement_ratio{0.5};
//!\brief The number of threads to use to compute merged HLL sketches.
size_t threads{1u};
//!\brief Whether to estimate the union of kmer sets to possibly improve the binning or not.
bool estimate_union{false};
//!\brief Whether to do a second sorting of the bins which takes into account similarity or not.
bool rearrange_user_bins{false};
//!\brief Whether the program should determine the best number of IBF bins by doing multiple binning runs
bool determine_best_tmax{false};
//!\brief Whether the programm should compute all binnings up to the given t_max
bool force_all_binnings{false};
bool output_statistics{false};
bool debug{false};
private:
friend class cereal::access;
template <typename archive_t>
void serialize(archive_t & archive)
{
uint32_t const version{1};
archive(CEREAL_NVP(version));
archive(CEREAL_NVP(input_prefix));
archive(CEREAL_NVP(count_filename));
archive(CEREAL_NVP(sketch_directory));
archive(CEREAL_NVP(output_filename));
archive(CEREAL_NVP(tmax));
// archive(CEREAL_NVP(aggregate_by_column));
archive(CEREAL_NVP(num_hash_functions));
archive(CEREAL_NVP(false_positive_rate));
archive(CEREAL_NVP(alpha));
archive(CEREAL_NVP(max_rearrangement_ratio));
archive(CEREAL_NVP(threads));
archive(CEREAL_NVP(estimate_union));
archive(CEREAL_NVP(rearrange_user_bins));
archive(CEREAL_NVP(determine_best_tmax));
archive(CEREAL_NVP(force_all_binnings));
archive(CEREAL_NVP(output_statistics));
}
};
} // namespace chopper::layout
|
// Copyright (c) 2020 PaddlePaddle Authors. 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 "lite/core/mir/fusion/scales_fuse_pass.h"
#include <memory>
#include <vector>
#include "lite/core/mir/fusion/scales_fuser.h"
#include "lite/core/mir/pass_registry.h"
namespace paddle {
namespace lite {
namespace mir {
void ScalesFusePass::Apply(const std::unique_ptr<SSAGraph>& graph) {
fusion::ScalesFuser fuser;
fuser(graph.get());
}
} // namespace mir
} // namespace lite
} // namespace paddle
REGISTER_MIR_PASS(lite_scales_fuse_pass, paddle::lite::mir::ScalesFusePass)
.BindTargets({TARGET(kCUDA)});
|
// Copyright (c) 2017-2018 Hartmut Kaiser
//
// 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(PHYLANX_PRIMITIVES_BLOCK_OPERATION_OCT_08_2017_0757PM)
#define PHYLANX_PRIMITIVES_BLOCK_OPERATION_OCT_08_2017_0757PM
#include <phylanx/config.hpp>
#include <phylanx/execution_tree/primitives/base_primitive.hpp>
#include <phylanx/execution_tree/primitives/primitive_component_base.hpp>
#include <phylanx/ir/node_data.hpp>
#include <hpx/lcos/future.hpp>
#include <cstddef>
#include <memory>
#include <string>
#include <vector>
namespace phylanx { namespace execution_tree { namespace primitives
{
class block_operation
: public primitive_component_base
, public std::enable_shared_from_this<block_operation>
{
protected:
hpx::future<primitive_argument_type> eval(
std::vector<primitive_argument_type> const& operands,
std::vector<primitive_argument_type> args) const;
public:
static match_pattern_type const match_data;
block_operation() = default;
block_operation(std::vector<primitive_argument_type>&& operands,
std::string const& name, std::string const& codename);
hpx::future<primitive_argument_type> eval(
std::vector<primitive_argument_type> const& args) const override;
private:
void next(std::size_t i,
std::vector<primitive_argument_type>&& args,
hpx::lcos::local::promise<primitive_argument_type>&& result) const;
};
PHYLANX_EXPORT primitive create_block_operation(
hpx::id_type const& locality,
std::vector<primitive_argument_type>&& operands,
std::string const& name = "", std::string const& codename = "");
}}}
#endif
|
// Copyright (C) 2008, 2009 International Business Machines and others.
// All Rights Reserved.
// This code is published under the Eclipse Public License.
//
// $Id$
//
// Authors: Andreas Waechter IBM 2008-08-31
#include "IpInexactSearchDirCalc.hpp"
namespace Ipopt
{
#if COIN_IPOPT_VERBOSITY > 0
static const Index dbg_verbosity = 0;
#endif
InexactSearchDirCalculator::
InexactSearchDirCalculator(SmartPtr<InexactNormalStepCalculator> normal_step_calculator,
SmartPtr<InexactPDSolver> inexact_pd_solver)
:
normal_step_calculator_(normal_step_calculator),
inexact_pd_solver_(inexact_pd_solver)
{}
InexactSearchDirCalculator::~InexactSearchDirCalculator()
{}
void InexactSearchDirCalculator::RegisterOptions(SmartPtr<RegisteredOptions> roptions)
{
roptions->AddLowerBoundedNumberOption(
"local_inf_Ac_tol",
"Termination tolerance for local infeasibility (scaled ||Ac||).",
0.0, true,
1e-8,
"");
roptions->AddStringOption3(
"inexact_step_decomposition",
"Determines if the steps should be decomposed into normal and tangential components.",
"adaptive",
"always", "always compute the step as two components",
"adaptive", "try to use undecomposed steps if possible",
"switch-once", "try to use undecomposed steps, but if decomposition is necessary, always keep it",
"TO BE WRITTEN");
}
bool InexactSearchDirCalculator::InitializeImpl(const OptionsList& options,
const std::string& prefix)
{
options.GetNumericValue("local_inf_Ac_tol", local_inf_Ac_tol_, prefix);
Index enum_int;
options.GetEnumValue("inexact_step_decomposition", enum_int, prefix);
decomposition_type_ = DecompositionTypeEnum(enum_int);
bool compute_normal = false;
switch (decomposition_type_) {
case ALWAYS:
compute_normal = true;
break;
case ADAPTIVE:
case SWITCH_ONCE:
compute_normal = false;
break;
}
InexData().set_compute_normal(compute_normal);
InexData().set_next_compute_normal(compute_normal);
bool retval = inexact_pd_solver_->Initialize(Jnlst(), IpNLP(), IpData(),
IpCq(), options, prefix);
if (!retval) return false;
return normal_step_calculator_->Initialize(Jnlst(), IpNLP(), IpData(),
IpCq(), options, prefix);
}
bool
InexactSearchDirCalculator::ComputeSearchDirection()
{
DBG_START_METH("InexactSearchDirCalculator::ComputeSearchDirection",
dbg_verbosity);
// First check if the iterates have converged to a locally
// infeasible point
Number curr_scaled_Ac_norm = InexCq().curr_scaled_Ac_norm();
Jnlst().Printf(J_DETAILED, J_SOLVE_PD_SYSTEM,
"curr_scaled_Ac_norm = %e\n", curr_scaled_Ac_norm);
Number curr_inf = IpCq().curr_primal_infeasibility(NORM_2);
// ToDo work on termination criteria
if (curr_scaled_Ac_norm <= local_inf_Ac_tol_ && curr_inf > 1e-4) {
THROW_EXCEPTION(LOCALLY_INFEASIBLE,
"The scaled norm of Ac is satisfying tolerance");
}
bool compute_normal = false;
switch (decomposition_type_) {
case ALWAYS:
compute_normal = true;
break;
case ADAPTIVE:
compute_normal = InexData().next_compute_normal();
break;
case SWITCH_ONCE:
compute_normal = InexData().next_compute_normal() || InexData().compute_normal();
break;
}
SmartPtr<Vector> normal_x;
SmartPtr<Vector> normal_s;
bool retval;
SmartPtr<IteratesVector> delta;
SmartPtr<const IteratesVector> curr = IpData().curr();
SmartPtr<IteratesVector> rhs;
SmartPtr<Vector> tmp;
// Now we set up the primal-dual system for computing the
// tangential step and the search direction for the multipliers.
// This is taken from IpPDSearchDirCal.cpp (rev 549).
// We do not need entries for the variable bound multipliers
// Upper part of right-hand-side vector is same for both systems
rhs = curr->MakeNewContainer();
tmp = curr->x()->MakeNew();
tmp->AddOneVector(-1., *IpCq().curr_grad_lag_with_damping_x(), 0.);
rhs->Set_x(*tmp);
tmp = curr->s()->MakeNew();
tmp->AddOneVector(-1., *IpCq().curr_grad_lag_with_damping_s(), 0.);
rhs->Set_s(*tmp);
tmp = curr->v_L()->MakeNew();
tmp->AddOneVector(-1., *IpCq().curr_relaxed_compl_s_L(), 0.);
rhs->Set_v_L(*tmp);
tmp = curr->v_U()->MakeNew();
tmp->AddOneVector(-1., *IpCq().curr_relaxed_compl_s_U(), 0.);
rhs->Set_v_U(*tmp);
// Loop through algorithms
bool done = false;
while (!done) {
InexData().set_compute_normal(compute_normal);
InexData().set_next_compute_normal(compute_normal);
if (!compute_normal) {
normal_x = NULL;
normal_s = NULL;
}
else {
retval =
normal_step_calculator_->ComputeNormalStep(normal_x, normal_s);
if (!retval) return false;
// output
if (Jnlst().ProduceOutput(J_VECTOR, J_SOLVE_PD_SYSTEM)) {
Jnlst().Printf(J_VECTOR, J_SOLVE_PD_SYSTEM,
"Normal step (without slack scaling):\n");
normal_x->Print(Jnlst(), J_VECTOR, J_SOLVE_PD_SYSTEM, "normal_x");
normal_s->Print(Jnlst(), J_VECTOR, J_SOLVE_PD_SYSTEM, "normal_s");
}
}
// Lower part of right-hand-side vector is different for each system
if (!compute_normal) {
tmp = curr->y_c()->MakeNew();
tmp->AddOneVector(-1., *IpCq().curr_c(), 0.);
rhs->Set_y_c(*tmp);
tmp = curr->y_d()->MakeNew();
tmp->AddOneVector(-1., *IpCq().curr_d_minus_s(), 0.);
rhs->Set_y_d(*tmp);
}
else {
rhs->Set_y_c(*IpCq().curr_jac_c_times_vec(*normal_x));
tmp = normal_s->MakeNew();
tmp->AddTwoVectors(1., *IpCq().curr_jac_d_times_vec(*normal_x),
-1., *normal_s, 0.);
rhs->Set_y_d(*tmp);
}
InexData().set_normal_x(normal_x);
InexData().set_normal_s(normal_s);
delta = rhs->MakeNewIteratesVector();
retval = inexact_pd_solver_->Solve(*rhs, *delta);
// Determine if acceptable step has been computed
if (!compute_normal && (!retval || InexData().next_compute_normal())) {
// If normal step has not been computed and step is not satisfactory, try computing normal step
InexData().set_compute_normal(true);
compute_normal = true;
}
else {
// If normal step has been computed, stop anyway
done = true;
}
}
if (retval) {
// Store the search directions in the IpData object
IpData().set_delta(delta);
if (InexData().compute_normal()) {
IpData().Append_info_string("NT ");
}
else {
IpData().Append_info_string("PD ");
}
}
return retval;
}
} // namespace Ipopt
|
/*
* Copyright (c) 2017-2018, The Alloy Developers.
*
* This file is part of Alloy.
*
* This file is subject to the terms and conditions defined in the
* file 'LICENSE', which is part of this source code package.
*/
#include <System/Dispatcher.h>
#include <System/ContextGroup.h>
#include <System/InterruptedException.h>
#include <System/Ipv4Address.h>
#include <System/Ipv4Resolver.h>
#include <gtest/gtest.h>
using namespace System;
class Ipv4ResolverTests : public testing::Test {
public:
Ipv4ResolverTests() : contextGroup(dispatcher), resolver(dispatcher) {
}
Dispatcher dispatcher;
ContextGroup contextGroup;
Ipv4Resolver resolver;
};
TEST_F(Ipv4ResolverTests, start) {
contextGroup.spawn([&] {
ASSERT_NO_THROW(Ipv4Resolver(dispatcher).resolve("localhost"));
});
contextGroup.wait();
}
TEST_F(Ipv4ResolverTests, stop) {
contextGroup.spawn([&] {
contextGroup.interrupt();
ASSERT_THROW(resolver.resolve("localhost"), InterruptedException);
});
contextGroup.wait();
}
TEST_F(Ipv4ResolverTests, interruptWhileResolving) {
contextGroup.spawn([&] {
ASSERT_THROW(resolver.resolve("localhost"), InterruptedException);
});
contextGroup.interrupt();
contextGroup.wait();
}
TEST_F(Ipv4ResolverTests, reuseAfterInterrupt) {
contextGroup.spawn([&] {
ASSERT_THROW(resolver.resolve("localhost"), InterruptedException);
});
contextGroup.interrupt();
contextGroup.wait();
contextGroup.spawn([&] {
ASSERT_NO_THROW(resolver.resolve("localhost"));
});
contextGroup.wait();
}
TEST_F(Ipv4ResolverTests, resolve) {
ASSERT_EQ(Ipv4Address("0.0.0.0"), resolver.resolve("0.0.0.0"));
ASSERT_EQ(Ipv4Address("1.2.3.4"), resolver.resolve("1.2.3.4"));
ASSERT_EQ(Ipv4Address("127.0.0.1"), resolver.resolve("127.0.0.1"));
ASSERT_EQ(Ipv4Address("254.253.252.251"), resolver.resolve("254.253.252.251"));
ASSERT_EQ(Ipv4Address("255.255.255.255"), resolver.resolve("255.255.255.255"));
ASSERT_EQ(Ipv4Address("127.0.0.1"), resolver.resolve("localhost"));
//ASSERT_EQ(Ipv4Address("93.184.216.34"), resolver.resolve("example.com"));
ASSERT_THROW(resolver.resolve(".0.0.0.0"), std::runtime_error);
ASSERT_THROW(resolver.resolve("0..0.0.0"), std::runtime_error);
//ASSERT_THROW(resolver.resolve("0.0.0"), std::runtime_error);
ASSERT_THROW(resolver.resolve("0.0.0."), std::runtime_error);
//ASSERT_THROW(resolver.resolve("0.0.0.0."), std::runtime_error);
ASSERT_THROW(resolver.resolve("0.0.0.0.0"), std::runtime_error);
//ASSERT_THROW(resolver.resolve("0.0.0.00"), std::runtime_error);
//ASSERT_THROW(resolver.resolve("0.0.0.01"), std::runtime_error);
ASSERT_THROW(resolver.resolve("0.0.0.256"), std::runtime_error);
//ASSERT_THROW(resolver.resolve("00.0.0.0"), std::runtime_error);
//ASSERT_THROW(resolver.resolve("01.0.0.0"), std::runtime_error);
ASSERT_THROW(resolver.resolve("256.0.0.0"), std::runtime_error);
ASSERT_THROW(resolver.resolve("invalid"), std::runtime_error);
}
|
#using <system.dll>
using namespace System;
using namespace System::ComponentModel;
using namespace System::ComponentModel::Design;
namespace MiscCompModSamples
{
public ref class ComponentRenameEventArgsExample
{
public:
ComponentRenameEventArgsExample()
{
}
//<Snippet1>
public:
// This example method creates a ComponentRenameEventArgs using the specified arguments.
// Typically, this type of event args is created by a design mode subsystem.
ComponentRenameEventArgs^ CreateComponentRenameEventArgs( Object^ component, String^ oldName, String^ newName )
{
// The component that was renamed: args.Component
// The previous name of the component: args.OldName
// The new name of the component: args.NewName
return gcnew ComponentRenameEventArgs( component, oldName, newName );
}
//</Snippet1>
};
}
|
// Distributed under the MIT License.
// See LICENSE.txt for details.
#include "Framework/TestingFramework.hpp"
#include <cstddef>
#include <type_traits>
#include "DataStructures/DataBox/DataBox.hpp"
#include "Framework/ActionTesting.hpp"
#include "IO/Observer/Actions/GetLockPointer.hpp"
#include "IO/Observer/ObserverComponent.hpp"
#include "IO/Observer/Tags.hpp"
#include "Parallel/GlobalCache.hpp"
#include "Parallel/Local.hpp"
#include "Parallel/NodeLock.hpp"
#include "Utilities/Gsl.hpp"
#include "Utilities/TMPL.hpp"
namespace {
Parallel::NodeLock* h5_lock_to_check;
Parallel::NodeLock* volume_lock_to_check;
template <typename LockTag>
struct mock_lock_retrieval_action {
template <typename ParallelComponent, typename DbTagList,
typename Metavariables, typename ArrayIndex>
static void apply(const db::DataBox<DbTagList>& /*box*/,
Parallel::GlobalCache<Metavariables>& cache,
const ArrayIndex& /*array_index*/) {
auto lock = Parallel::local_branch(
Parallel::get_parallel_component<
observers::ObserverWriter<Metavariables>>(cache))
->template local_synchronous_action<
observers::Actions::GetLockPointer<LockTag>>();
if constexpr (std::is_same_v<LockTag, observers::Tags::H5FileLock>) {
h5_lock_to_check = lock;
} else {
volume_lock_to_check = lock;
}
}
};
template <typename Metavariables>
struct mock_observer_writer {
using chare_type = ActionTesting::MockNodeGroupChare;
using component_being_mocked = observers::ObserverWriter<Metavariables>;
using replace_these_simple_actions = tmpl::list<>;
using with_these_simple_actions = tmpl::list<>;
using simple_tags =
tmpl::list<observers::Tags::H5FileLock, observers::Tags::VolumeDataLock>;
using const_global_cache_tags = tmpl::list<>;
using metavariables = Metavariables;
using array_index = size_t;
using phase_dependent_action_list = tmpl::list<Parallel::PhaseActions<
typename Metavariables::Phase, Metavariables::Phase::Initialization,
tmpl::list<ActionTesting::InitializeDataBox<simple_tags>>>>;
};
template <typename Metavariables>
struct mock_array {
using chare_type = ActionTesting::MockArrayChare;
using replace_these_simple_actions = tmpl::list<>;
using with_these_simple_actions = tmpl::list<>;
using const_global_cache_tags = tmpl::list<>;
using metavariables = Metavariables;
using array_index = size_t;
using phase_dependent_action_list =
tmpl::list<Parallel::PhaseActions<typename Metavariables::Phase,
Metavariables::Phase::Initialization,
tmpl::list<>>>;
};
struct test_metavariables {
using component_list = tmpl::list<mock_observer_writer<test_metavariables>,
mock_array<test_metavariables>>;
enum class Phase { Initialization, Evolve, Exit };
};
} // namespace
SPECTRE_TEST_CASE("Unit.IO.Observer.GetNodeLockPointer", "[Unit][Cce]") {
using array_component = mock_array<test_metavariables>;
using writer_component = mock_observer_writer<test_metavariables>;
ActionTesting::MockRuntimeSystem<test_metavariables> runner{{}};
ActionTesting::set_phase(make_not_null(&runner),
test_metavariables::Phase::Initialization);
ActionTesting::emplace_array_component_and_initialize<writer_component>(
&runner, ActionTesting::NodeId{0}, ActionTesting::LocalCoreId{0}, 0,
{Parallel::NodeLock{}, Parallel::NodeLock{}});
ActionTesting::emplace_array_component<array_component>(
&runner, ActionTesting::NodeId{0}, ActionTesting::LocalCoreId{0}, 0);
ActionTesting::simple_action<
array_component, mock_lock_retrieval_action<observers::Tags::H5FileLock>>(
make_not_null(&runner), 0);
ActionTesting::simple_action<
array_component,
mock_lock_retrieval_action<observers::Tags::VolumeDataLock>>(
make_not_null(&runner), 0);
db::mutate<observers::Tags::H5FileLock, observers::Tags::VolumeDataLock>(
make_not_null(
&ActionTesting::get_databox<
writer_component, tmpl::list<observers::Tags::H5FileLock,
observers::Tags::VolumeDataLock>>(
make_not_null(&runner), 0)),
[](const gsl::not_null<Parallel::NodeLock*> h5_lock,
const gsl::not_null<Parallel::NodeLock*> volume_lock) {
CHECK(h5_lock.get() == h5_lock_to_check);
CHECK(volume_lock.get() == volume_lock_to_check);
});
}
|
// Copyright 2015 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 <stddef.h>
#include <stdint.h>
#include <memory>
#include "base/logging.h"
#include "media/formats/mp4/box_reader.h"
class NullMediaLog : public media::MediaLog {
public:
NullMediaLog() {}
~NullMediaLog() override {}
void AddEvent(std::unique_ptr<media::MediaLogEvent> event) override {}
private:
DISALLOW_COPY_AND_ASSIGN(NullMediaLog);
};
// Entry point for LibFuzzer.
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
bool err;
NullMediaLog media_log;
std::unique_ptr<media::mp4::BoxReader> reader(
media::mp4::BoxReader::ReadTopLevelBox(data, static_cast<int>(size),
&media_log, &err));
return !err && reader && reader->ScanChildren() ? 0 : 0;
}
|
//------------------------------------------------------------------------------
/*
This file is part of MUSO: https://github.com/MUSO/MUSO
Copyright (c) 2012-2015 MUSO Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#include <MUSO/app/ledger/LedgerMaster.h>
#include <MUSO/protocol/ErrorCodes.h>
#include <MUSO/protocol/Feature.h>
#include <MUSO/resource/Fees.h>
#include <MUSO/rpc/Context.h>
#include <MUSO/rpc/impl/TransactionSign.h>
namespace MUSO {
// {
// tx_json: <object>,
// account: <signing account>
// secret: <secret of signing account>
// }
Json::Value
doSignFor(RPC::JsonContext& context)
{
if (context.role != Role::ADMIN && !context.app.config().canSign())
{
return RPC::make_error(
rpcNOT_SUPPORTED, "Signing is not supported by this server.");
}
context.loadType = Resource::feeHighBurdenRPC;
auto const failHard = context.params[jss::fail_hard].asBool();
auto const failType = NetworkOPs::doFailHard(failHard);
auto ret = RPC::transactionSignFor(
context.params,
failType,
context.role,
context.ledgerMaster.getValidatedLedgerAge(),
context.app);
ret[jss::deprecated] =
"This command has been deprecated and will be "
"removed in a future version of the server. Please "
"migrate to a standalone signing tool.";
return ret;
}
} // namespace MUSO
|
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/bluetooth/bluetooth_blocklist.h"
#include "base/check.h"
#include "base/metrics/histogram_macros.h"
#include "base/optional.h"
#include "base/strings/string_split.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/common/content_client.h"
using device::BluetoothUUID;
namespace {
static base::LazyInstance<content::BluetoothBlocklist>::Leaky g_singleton =
LAZY_INSTANCE_INITIALIZER;
void RecordUMAParsedNonEmptyString(bool success) {
UMA_HISTOGRAM_BOOLEAN("Bluetooth.Web.Blocklist.ParsedNonEmptyString",
success);
}
} // namespace
namespace content {
BluetoothBlocklist::~BluetoothBlocklist() {}
// static
BluetoothBlocklist& BluetoothBlocklist::Get() {
return g_singleton.Get();
}
void BluetoothBlocklist::Add(const BluetoothUUID& uuid, Value value) {
CHECK(uuid.IsValid());
auto insert_result = blocklisted_uuids_.insert(std::make_pair(uuid, value));
bool inserted = insert_result.second;
if (!inserted) {
Value& stored = insert_result.first->second;
if (stored != value)
stored = Value::EXCLUDE;
}
}
void BluetoothBlocklist::Add(base::StringPiece blocklist_string) {
if (blocklist_string.empty())
return;
base::StringPairs kv_pairs;
bool parsed_values = false;
bool invalid_values = false;
SplitStringIntoKeyValuePairs(blocklist_string,
':', // Key-value delimiter
',', // Key-value pair delimiter
&kv_pairs);
for (const auto& pair : kv_pairs) {
BluetoothUUID uuid(pair.first);
if (uuid.IsValid() && pair.second.size() == 1u) {
switch (pair.second[0]) {
case 'e':
Add(uuid, Value::EXCLUDE);
parsed_values = true;
continue;
case 'r':
Add(uuid, Value::EXCLUDE_READS);
parsed_values = true;
continue;
case 'w':
Add(uuid, Value::EXCLUDE_WRITES);
parsed_values = true;
continue;
}
}
invalid_values = true;
}
RecordUMAParsedNonEmptyString(parsed_values && !invalid_values);
}
bool BluetoothBlocklist::IsExcluded(const BluetoothUUID& uuid) const {
CHECK(uuid.IsValid());
const auto& it = blocklisted_uuids_.find(uuid);
if (it == blocklisted_uuids_.end())
return false;
return it->second == Value::EXCLUDE;
}
bool BluetoothBlocklist::IsExcluded(
const std::vector<blink::mojom::WebBluetoothLeScanFilterPtr>& filters) {
for (const blink::mojom::WebBluetoothLeScanFilterPtr& filter : filters) {
if (!filter->services) {
continue;
}
for (const BluetoothUUID& service : filter->services.value()) {
if (IsExcluded(service)) {
return true;
}
}
}
return false;
}
bool BluetoothBlocklist::IsExcludedFromReads(const BluetoothUUID& uuid) const {
CHECK(uuid.IsValid());
const auto& it = blocklisted_uuids_.find(uuid);
if (it == blocklisted_uuids_.end())
return false;
return it->second == Value::EXCLUDE || it->second == Value::EXCLUDE_READS;
}
bool BluetoothBlocklist::IsExcludedFromWrites(const BluetoothUUID& uuid) const {
CHECK(uuid.IsValid());
const auto& it = blocklisted_uuids_.find(uuid);
if (it == blocklisted_uuids_.end())
return false;
return it->second == Value::EXCLUDE || it->second == Value::EXCLUDE_WRITES;
}
void BluetoothBlocklist::RemoveExcludedUUIDs(
blink::mojom::WebBluetoothRequestDeviceOptions* options) {
std::vector<device::BluetoothUUID> optional_services_blocklist_filtered;
for (const BluetoothUUID& uuid : options->optional_services) {
if (!IsExcluded(uuid)) {
optional_services_blocklist_filtered.push_back(uuid);
}
}
options->optional_services = std::move(optional_services_blocklist_filtered);
}
void BluetoothBlocklist::ResetToDefaultValuesForTest() {
blocklisted_uuids_.clear();
PopulateWithDefaultValues();
PopulateWithServerProvidedValues();
}
BluetoothBlocklist::BluetoothBlocklist() {
PopulateWithDefaultValues();
PopulateWithServerProvidedValues();
}
void BluetoothBlocklist::PopulateWithDefaultValues() {
blocklisted_uuids_.clear();
// Testing from Web Tests Note:
//
// Random UUIDs for object & exclude permutations that do not exist in the
// standard blocklist are included to facilitate integration testing from
// Web Tests. Unit tests can dynamically modify the blocklist, but don't
// offer the full integration test to the Web Bluetooth Javascript bindings.
//
// This is done for simplicity as opposed to exposing a testing API that can
// add to the blocklist over time, which would be over engineered.
//
// Remove testing UUIDs if the specified blocklist is updated to include UUIDs
// that match the specific permutations.
DCHECK(BluetoothUUID("00001800-0000-1000-8000-00805f9b34fb") ==
BluetoothUUID("1800"));
// Blocklist UUIDs updated 2016-09-01 from:
// https://github.com/WebBluetoothCG/registries/blob/master/gatt_blocklist.txt
// Short UUIDs are used for readability of this list.
//
// Services:
Add(BluetoothUUID("1812"), Value::EXCLUDE);
Add(BluetoothUUID("00001530-1212-efde-1523-785feabcd123"), Value::EXCLUDE);
Add(BluetoothUUID("f000ffc0-0451-4000-b000-000000000000"), Value::EXCLUDE);
Add(BluetoothUUID("00060000"), Value::EXCLUDE);
Add(BluetoothUUID("fffd"), Value::EXCLUDE);
// Characteristics:
Add(BluetoothUUID("2a02"), Value::EXCLUDE_WRITES);
Add(BluetoothUUID("2a03"), Value::EXCLUDE);
Add(BluetoothUUID("2a25"), Value::EXCLUDE);
// Characteristics for Web Tests:
Add(BluetoothUUID("bad1c9a2-9a5b-4015-8b60-1579bbbf2135"),
Value::EXCLUDE_READS);
// Descriptors:
Add(BluetoothUUID("2902"), Value::EXCLUDE_WRITES);
Add(BluetoothUUID("2903"), Value::EXCLUDE_WRITES);
// Descriptors for Web Tests:
Add(BluetoothUUID("bad2ddcf-60db-45cd-bef9-fd72b153cf7c"), Value::EXCLUDE);
Add(BluetoothUUID("bad3ec61-3cc3-4954-9702-7977df514114"),
Value::EXCLUDE_READS);
}
void BluetoothBlocklist::PopulateWithServerProvidedValues() {
// DCHECK to maybe help debug https://crbug.com/604078.
DCHECK(GetContentClient());
Add(GetContentClient()->browser()->GetWebBluetoothBlocklist());
}
} // namespace content
|
#include <stdio.h>
#include <sys/types.h>
#include <sys/time.h>
#include "tiles.h"
void runit (int num=10, int ct=2048, int numt=1)
{
int i,j;
float vars[2];
int* the_tiles = (int*) malloc(numt*sizeof(int));
for (i=0; i<num; i++)
{
for (j=0; j<num; j++)
{
vars[0] = i*0.5;
vars[1] = j*0.5;
tiles(the_tiles, numt, ct, vars, 2, NULL, 0);
}
}
}
void runit2 (int num=10, int ct=2048, int numt=1)
{
int i,j;
float vars[4];
int ints[2];
int* the_tiles = (int*)malloc(numt*sizeof(int));
for (i=0; i < num; i++)
{
for (j=0; j < num; j++)
{
vars[0] = i*0.5;
vars[1] = j*0.5;
vars[2] = float(i+j)/2;
vars[3] = float(i-j)/2;
ints[0] = i;
ints[1] = j;
tiles(the_tiles, numt, ct, vars, 4, ints, 2);
}
}
}
void runitw (int num=10, int ct=2048, int numt=1)
{
int i,j;
float vars[2];
int ints[2];
int* the_tiles = (int*)malloc(numt * sizeof(int));
for (i=0; i < num; i++)
{
for (j=0; j < num; j++)
{
vars[0] = i*0.5;
vars[1] = j*0.5;
ints[0] = 10;
ints[1] = 1;
tileswrap(the_tiles,numt, ct, vars, 2, ints,NULL,0);
}
}
}
void runitl (int num=10, int ct=2048, int numt=1)
{
int i,j;
float vars[2];
int* tlist = (int*)malloc((num*num*numt)*sizeof(int));
for (i=0; i < num; i++)
{
for (j=0; j < num; j++)
{
vars[0] = i*0.5;
vars[1] = j*0.5;
tiles(tlist+(i*num*num+j), numt, ct, vars, 2,NULL,0);
}
}
}
void runitlw (int num=10, int ct=2048, int numt=1)
{
int i,j;
float vars[2];
int ints[2];
int* tlist = (int*)malloc((num*num*numt)*sizeof(int));
for (i=0; i < num; i++)
{
for (j=0; j < num; j++)
{
vars[0] = i*0.5;
vars[1] = j*0.5;
ints[0] = 10;
ints[1] = 1;
tileswrap(tlist+(i*num*numt+j), numt, ct, vars, 2, ints,NULL,0);
}
}
}
////////////////////Collision table versions
void runit_ct (int num=10, collision_table* ct=NULL, int numt=1)
{
int i,j;
float vars[2];
int* the_tiles = (int*) malloc(numt*sizeof(int));
for (i=0; i<num; i++)
{
for (j=0; j<num; j++)
{
vars[0] = i*0.5;
vars[1] = j*0.5;
tiles(the_tiles, numt, ct, vars, 2, NULL, 0);
}
}
}
void runitn_ct (int num=10, collision_table* ct=NULL, int numt=4)
{
int i,j;
float vars[2];
int* the_tiles = (int*)malloc(numt*sizeof(int));
for (i=0; i < num; i++)
{
for (j=0; j < num; j++)
{
vars[0] = i*0.5;
vars[1] = j*0.5;
tiles(the_tiles,numt, ct, vars, 2, NULL, 0);
}
}
}
void runit2_ct (int num=10, collision_table* ct=NULL, int numt=1)
{
int i,j;
float vars[4];
int ints[2];
int* the_tiles = (int*)malloc(numt*sizeof(int));
for (i=0; i < num; i++)
{
for (j=0; j < num; j++)
{
vars[0] = i*0.5;
vars[1] = j*0.5;
vars[2] = float(i+j)/2;
vars[3] = float(i-j)/2;
ints[0] = i;
ints[1] = j;
tiles(the_tiles, numt, ct, vars, 4, ints, 2);
}
}
}
void runitw_ct (int num=10, collision_table* ct=NULL, int numt=1)
{
int i,j;
float vars[2];
int ints[2];
int* the_tiles = (int*)malloc(numt * sizeof(int));
for (i=0; i < num; i++)
{
for (j=0; j < num; j++)
{
vars[0] = i*0.5;
vars[1] = j*0.5;
ints[0] = 10;
ints[1] = 1;
tileswrap(the_tiles,numt, ct, vars, 2, ints,NULL,0);
}
}
}
void runitl_ct (int num=10, collision_table* ct=NULL, int numt=1)
{
int i,j;
float vars[2];
int* tlist = (int*)malloc((num*num*numt)*sizeof(int));
for (i=0; i < num; i++)
{
for (j=0; j < num; j++)
{
vars[0] = i*0.5;
vars[1] = j*0.5;
tiles(tlist+(i*num*num+j), numt, ct, vars, 2,NULL,0);
}
}
}
void runitlw_ct (int num=10, collision_table* ct=NULL, int numt=1)
{
int i,j;
float vars[2];
int ints[2];
int* tlist = (int*)malloc((num*num*numt)*sizeof(int));
for (i=0; i < num; i++)
{
for (j=0; j < num; j++)
{
vars[0] = i*0.5;
vars[1] = j*0.5;
ints[0] = 10;
ints[1] = 1;
tileswrap(tlist+(i*num*numt+j), numt, ct, vars, 2, ints,NULL,0);
}
}
}
collision_table* ctu;
collision_table* cts;
collision_table* ctss;
void initct(int mem=16384)
{
ctu=new collision_table(mem, 0);
cts=new collision_table(mem, 1);
ctss=new collision_table(mem, 2);
}
void timetest(void (*command)(int,int,int),void (*command2)(int,collision_table*,int), char* info,
char* info2="2 floats", int num=100, int numt=1, int mem=16384)
{
//time_t t1,t2;
timeval t1, t2;
float t;
initct(mem);
printf(" \n");
printf("%s\n",info);
printf("Timing over %d calls to tiles, %d tiling each for %s\n", num*num, numt, info2);
(void)gettimeofday(&t1,0);
(*command)(num,mem,numt);
(void)gettimeofday(&t2,0);
t = t2.tv_sec-t1.tv_sec + ((float)(t2.tv_usec - t1.tv_usec))/1000000.0;
printf("With no collision table %f seconds\n",t);
(void)gettimeofday(&t1,0);
(*command2)(num,ctu,numt);
(void)gettimeofday(&t2,0);
t = t2.tv_sec-t1.tv_sec + ((float)(t2.tv_usec - t1.tv_usec))/1000000.0;
printf("With unsafe collision table %f seconds\n",t);
ctu->print();
(void)gettimeofday(&t1,0);
(*command2)(num,cts,numt);
(void)gettimeofday(&t2,0);
t = t2.tv_sec-t1.tv_sec + ((float)(t2.tv_usec - t1.tv_usec))/1000000.0;
printf("With safe collision table %f seconds\n",t);
cts->print();
(void)gettimeofday(&t1,0);
(*command2)(num,ctss,numt);
(void)gettimeofday(&t2,0);
t = t2.tv_sec-t1.tv_sec + ((float)(t2.tv_usec - t1.tv_usec))/1000000.0;
printf("With super safe collision table %f seconds\n",t);
ctss->print();
printf(" \n");
printf("Timing over %d calls to tiles, 16 tilings each for %s\n", num*num, info2);
(void)gettimeofday(&t1,0);
(*command)(num,16384,16);
(void)gettimeofday(&t2,0);
t = t2.tv_sec-t1.tv_sec + ((float)(t2.tv_usec - t1.tv_usec))/1000000.0;
printf("With no collision table %f seconds\n",t);
}
int main(void)
{
timeval t1, t2;
float t;
timetest(runit, runit_ct, "Standard test", "2 floats",100,4);
timetest(runit2,runit2_ct, "Testing with more input variables","4 floats, 2 ints", 100, 3, 32768);
timetest(runitw,runitw_ct, "WRAP version", "2 floats",100,4);
timetest(runitl,runitl_ct, "Load version", "2 floats", 10, 4); //# only do 10 x 10 calls, but with 4 tilings each
timetest(runitlw,runitlw_ct, "Load WRAP version", "2 floats", 10, 4);
return 0;
}
|
/*!
@file
@author Alexander Ptakhin
@date 01/2009
*/
/*
This file is part of MyGUI.
MyGUI 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.
MyGUI 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 MyGUI. If not, see <http://www.gnu.org/licenses/>.
*/
#include "MyGUI_Precompiled.h"
#include "MyGUI_Canvas.h"
#include "MyGUI_ResourceManager.h"
#include "MyGUI_Gui.h"
#include "MyGUI_RenderManager.h"
#include "MyGUI_Bitwise.h"
namespace MyGUI
{
Canvas::Canvas() :
mTexture( nullptr ),
mTexResizeMode( TRM_PT_CONST_SIZE ),
mTexData( 0 ),
mTexManaged( true ),
mFrameAdvise( false ),
mInvalidateData(false)
{
mGenTexName = utility::toString( this, "_Canvas" );
}
void Canvas::createTexture( TextureResizeMode _resizeMode, TextureUsage _usage, PixelFormat _format )
{
int width = std::max(1, getWidth());
int height = std::max(1, getHeight());
createTexture( width, height, _resizeMode, _usage, _format );
}
void Canvas::createTexture( const IntSize& _size, TextureResizeMode _resizeMode, TextureUsage _usage, PixelFormat _format )
{
int width = std::max(1, _size.width);
int height = std::max(1, _size.height);
createTexture( width, height, _resizeMode, _usage, _format );
}
void Canvas::createExactTexture( int _width, int _height, TextureUsage _usage, PixelFormat _format )
{
int width = std::max(1, _width);
int height = std::max(1, _height);
destroyTexture();
mTexture = RenderManager::getInstance().createTexture(mGenTexName);
mTexture->setInvalidateListener(this);
mTexture->createManual( width, height, _usage, _format );
mTexManaged = true;
_setTextureName( mGenTexName );
correctUV();
requestUpdateCanvas( this, Event( true, true, mInvalidateData ) );
}
void Canvas::resize( const IntSize& _size )
{
if ( _size.width <= 0 || _size.height <= 0 || ! mTexManaged )
return;
mReqTexSize = _size;
frameAdvise( true );
}
void Canvas::createTexture( int _width, int _height, TextureResizeMode _resizeMode, TextureUsage _usage, PixelFormat _format )
{
int width = std::max(1, _width);
int height = std::max(1, _height);
if ( mReqTexSize.empty() )
mReqTexSize = IntSize( width, height );
mTexResizeMode = _resizeMode;
bool create = checkCreate( width, height );
width = Bitwise::firstPO2From(width);
height = Bitwise::firstPO2From(height);
if ( create )
createExactTexture( width, height, _usage, _format );
}
void Canvas::setSize( const IntSize& _size )
{
resize( _size );
Base::setSize( _size );
}
void Canvas::setCoord( const IntCoord& _coord )
{
resize( _coord.size() );
Base::setCoord( _coord );
}
void Canvas::updateTexture()
{
mInvalidateData = true;
frameAdvise( true );
}
bool Canvas::checkCreate( int _width, int _height ) const
{
if ( mTexture == nullptr )
return true;
if ( mTexture->getWidth() >= _width && mTexture->getHeight() >= _height )
return false;
return true;
}
void Canvas::validate( int& _width, int& _height, TextureUsage& _usage, PixelFormat& _format ) const
{
_width = std::max(1, _width);
_height = std::max(1, _height);
_width = Bitwise::firstPO2From(_width);
_height = Bitwise::firstPO2From(_height);
// restore usage and format
if ( mTexture != nullptr )
{
if ( _usage == getDefaultTextureUsage() )
_usage = mTexture->getUsage();
if ( _format == getDefaultTextureFormat() )
_format = mTexture->getFormat();
}
}
void Canvas::destroyTexture()
{
_destroyTexture( true );
}
void Canvas::shutdownOverride()
{
_destroyTexture(false);
frameAdvise(false);
}
void Canvas::initialiseOverride()
{
}
void Canvas::_destroyTexture( bool _sendEvent )
{
if ( mTexture != nullptr )
{
if ( _sendEvent )
{
eventPreTextureChanges( this );
}
RenderManager::getInstance().destroyTexture( mTexture );
mTexture = nullptr;
}
}
void Canvas::correctUV()
{
if ( mTexResizeMode == TRM_PT_VIEW_REQUESTED )
{
_setUVSet(
FloatRect(
0,
0,
(float) mReqTexSize.width / (float) getTextureRealWidth(),
(float) mReqTexSize.height / (float) getTextureRealHeight()
)
);
}
if ( mTexResizeMode == TRM_PT_CONST_SIZE || mTexResizeMode == TRM_PT_VIEW_ALL )
{
_setUVSet( FloatRect( 0, 0, 1, 1 ) );
}
}
void* Canvas::lock(TextureUsage _usage)
{
void* data = mTexture->lock(_usage);
mTexData = reinterpret_cast< uint8* >( data );
return data;
}
void Canvas::unlock()
{
mTexture->unlock();
}
bool Canvas::isTextureSrcSize() const
{
return getTextureSrcSize() == getTextureRealSize();
}
void Canvas::frameAdvise( bool _advise )
{
if ( _advise )
{
if ( ! mFrameAdvise )
{
MyGUI::Gui::getInstance().eventFrameStart += MyGUI::newDelegate( this, &Canvas::frameEntered );
mFrameAdvise = true;
}
}
else
{
if ( mFrameAdvise )
{
MyGUI::Gui::getInstance().eventFrameStart -= MyGUI::newDelegate( this, &Canvas::frameEntered );
mFrameAdvise = false;
}
}
}
void Canvas::frameEntered( float _time )
{
int width = mReqTexSize.width;
int height = mReqTexSize.height;
TextureUsage usage = getDefaultTextureUsage();
PixelFormat format = getDefaultTextureFormat();
validate( width, height, usage, format );
bool create = checkCreate( width, height );
if ( mTexResizeMode == TRM_PT_CONST_SIZE )
create = false;
if ( create )
{
createExactTexture( width, height, usage, format );
correctUV();
}
else // I thought order is important
{
correctUV();
requestUpdateCanvas( this, Event( false, true, mInvalidateData ) );
}
mInvalidateData = false;
frameAdvise( false );
}
void Canvas::textureInvalidate(ITexture* _texture)
{
updateTexture();
}
void Canvas::_setUVSet(const FloatRect& _rect)
{
if (nullptr != getSubWidgetMain())
getSubWidgetMain()->_setUVSet(_rect);
}
bool Canvas::isLocked() const
{
return mTexture->isLocked();
}
int Canvas::getTextureRealWidth() const
{
return (int) mTexture->getWidth();
}
int Canvas::getTextureRealHeight() const
{
return (int) mTexture->getHeight();
}
IntSize Canvas::getTextureRealSize() const
{
return IntSize( getTextureRealWidth(), getTextureRealHeight() );
}
int Canvas::getTextureSrcWidth() const
{
return mReqTexSize.width;
}
int Canvas::getTextureSrcHeight() const
{
return mReqTexSize.height;
}
IntSize Canvas::getTextureSrcSize() const
{
return mReqTexSize;
}
PixelFormat Canvas::getTextureFormat() const
{
return mTexture->getFormat();
}
const std::string& Canvas::getTextureName() const
{
return mTexture->getName();
}
void Canvas::setSize(int _width, int _height)
{
setSize(IntSize(_width, _height));
}
void Canvas::setCoord(int _left, int _top, int _width, int _height)
{
setCoord(IntCoord(_left, _top, _width, _height));
}
Canvas::TextureResizeMode Canvas::getResizeMode() const
{
return mTexResizeMode;
}
void Canvas::setResizeMode(TextureResizeMode _value)
{
mTexResizeMode = _value;
}
bool Canvas::isTextureCreated() const
{
return mTexture != nullptr;
}
bool Canvas::isTextureManaged() const
{
return mTexManaged;
}
ITexture* Canvas::getTexture() const
{
return mTexture;
}
void Canvas::setTextureManaged(bool _value)
{
mTexManaged = _value;
}
TextureUsage Canvas::getDefaultTextureUsage()
{
return TextureUsage::Stream | TextureUsage::Write;
}
PixelFormat Canvas::getDefaultTextureFormat()
{
return PixelFormat::R8G8B8A8;
}
} // namespace MyGUI
|
#include "optionsdialog.h"
#include "ui_optionsdialog.h"
#include "bitcoinunits.h"
#include "monitoreddatamapper.h"
#include "netbase.h"
#include "optionsmodel.h"
#include <QDir>
#include <QIntValidator>
#include <QLocale>
#include <QMessageBox>
OptionsDialog::OptionsDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::OptionsDialog),
model(0),
mapper(0),
fRestartWarningDisplayed_Proxy(false),
fRestartWarningDisplayed_Lang(false),
fProxyIpValid(true)
{
ui->setupUi(this);
/* Network elements init */
#ifndef USE_UPNP
ui->mapPortUpnp->setEnabled(false);
#endif
ui->proxyIp->setEnabled(false);
ui->proxyPort->setEnabled(false);
ui->proxyPort->setValidator(new QIntValidator(1, 65535, this));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning_Proxy()));
ui->proxyIp->installEventFilter(this);
/* Window elements init */
#ifdef Q_OS_MAC
ui->tabWindow->setVisible(false);
#endif
/* Display elements init */
QDir translations(":translations");
ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant(""));
foreach(const QString &langStr, translations.entryList())
{
QLocale locale(langStr);
/** check if the locale name consists of 2 parts (language_country) */
if(langStr.contains("_"))
{
#if QT_VERSION >= 0x040800
/** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */
ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
/** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */
ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
}
else
{
#if QT_VERSION >= 0x040800
/** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */
ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
/** display language strings as "language (locale name)", e.g. "German (de)" */
ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
}
}
ui->unit->setModel(new BitcoinUnits(this));
/* Widget-to-option mapper */
mapper = new MonitoredDataMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
mapper->setOrientation(Qt::Vertical);
/* enable apply button when data modified */
connect(mapper, SIGNAL(viewModified()), this, SLOT(enableApplyButton()));
/* disable apply button when new data loaded */
connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(disableApplyButton()));
/* setup/change UI elements when proxy IP is invalid/valid */
connect(this, SIGNAL(proxyIpValid(QValidatedLineEdit *, bool)), this, SLOT(handleProxyIpValid(QValidatedLineEdit *, bool)));
}
OptionsDialog::~OptionsDialog()
{
delete ui;
}
void OptionsDialog::setModel(OptionsModel *model)
{
this->model = model;
if(model)
{
connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
mapper->setModel(model);
setMapper();
mapper->toFirst();
}
/* update the display unit, to not use the default ("BTC") */
updateDisplayUnit();
/* warn only when language selection changes by user action (placed here so init via mapper doesn't trigger this) */
connect(ui->lang, SIGNAL(valueChanged()), this, SLOT(showRestartWarning_Lang()));
/* disable apply button after settings are loaded as there is nothing to save */
disableApplyButton();
}
void OptionsDialog::setMapper()
{
/* Main */
mapper->addMapping(ui->transactionFee, OptionsModel::Fee);
mapper->addMapping(ui->reserveBalance, OptionsModel::ReserveBalance);
mapper->addMapping(ui->bitcoinAtStartup, OptionsModel::StartAtStartup);
/* Network */
mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP);
mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse);
mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP);
mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort);
/* Window */
#ifndef Q_OS_MAC
mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray);
mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose);
#endif
/* Display */
mapper->addMapping(ui->lang, OptionsModel::Language);
mapper->addMapping(ui->unit, OptionsModel::DisplayUnit);
mapper->addMapping(ui->coinControlFeatures, OptionsModel::CoinControlFeatures);
mapper->addMapping(ui->minimizeCoinAge, OptionsModel::MinimizeCoinAge);
mapper->addMapping(ui->useBlackTheme, OptionsModel::UseBlackTheme);
}
void OptionsDialog::enableApplyButton()
{
ui->applyButton->setEnabled(true);
}
void OptionsDialog::disableApplyButton()
{
ui->applyButton->setEnabled(false);
}
void OptionsDialog::enableSaveButtons()
{
/* prevent enabling of the save buttons when data modified, if there is an invalid proxy address present */
if(fProxyIpValid)
setSaveButtonState(true);
}
void OptionsDialog::disableSaveButtons()
{
setSaveButtonState(false);
}
void OptionsDialog::setSaveButtonState(bool fState)
{
ui->applyButton->setEnabled(fState);
ui->okButton->setEnabled(fState);
}
void OptionsDialog::on_okButton_clicked()
{
mapper->submit();
accept();
}
void OptionsDialog::on_cancelButton_clicked()
{
reject();
}
void OptionsDialog::on_applyButton_clicked()
{
mapper->submit();
disableApplyButton();
}
void OptionsDialog::showRestartWarning_Proxy()
{
if(!fRestartWarningDisplayed_Proxy)
{
QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting LOV."), QMessageBox::Ok);
fRestartWarningDisplayed_Proxy = true;
}
}
void OptionsDialog::showRestartWarning_Lang()
{
if(!fRestartWarningDisplayed_Lang)
{
QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting LOV."), QMessageBox::Ok);
fRestartWarningDisplayed_Lang = true;
}
}
void OptionsDialog::updateDisplayUnit()
{
if(model)
{
/* Update transactionFee with the current unit */
ui->transactionFee->setDisplayUnit(model->getDisplayUnit());
}
}
void OptionsDialog::handleProxyIpValid(QValidatedLineEdit *object, bool fState)
{
// this is used in a check before re-enabling the save buttons
fProxyIpValid = fState;
if(fProxyIpValid)
{
enableSaveButtons();
ui->statusLabel->clear();
}
else
{
disableSaveButtons();
object->setValid(fProxyIpValid);
ui->statusLabel->setStyleSheet("QLabel { color: red; }");
ui->statusLabel->setText(tr("The supplied proxy address is invalid."));
}
}
bool OptionsDialog::eventFilter(QObject *object, QEvent *event)
{
if(event->type() == QEvent::FocusOut)
{
if(object == ui->proxyIp)
{
CService addr;
/* Check proxyIp for a valid IPv4/IPv6 address and emit the proxyIpValid signal */
emit proxyIpValid(ui->proxyIp, LookupNumeric(ui->proxyIp->text().toStdString().c_str(), addr));
}
}
return QDialog::eventFilter(object, event);
}
|
/* Copyright 2020 The TensorFlow Authors. 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.
==============================================================================*/
// A pass that eliminates certain element types as the input or output of ops by
// inserting Convert ops. This allows a backend to support an element type while
// only actually implementing the Convert op for that element type. This is
// generally not the fastest approach, but it works.
#include "mlir-hlo/Dialect/mhlo/IR/hlo_ops.h"
#include "mlir/IR/Attributes.h" // from @llvm-project
#include "mlir/IR/Location.h" // from @llvm-project
#include "mlir/IR/MLIRContext.h" // from @llvm-project
#include "mlir/IR/Operation.h" // from @llvm-project
#include "mlir/IR/PatternMatch.h" // from @llvm-project
#include "mlir/Pass/Pass.h" // from @llvm-project
#include "mlir/Transforms/GreedyPatternRewriteDriver.h" // from @llvm-project
#include "mlir/Transforms/Passes.h" // from @llvm-project
#include "transforms/PassDetail.h"
namespace mlir {
namespace disc_ral {
namespace {
template <typename Op>
static void BuildReduceBody(Type element_type, Region* body,
OpBuilder* builder) {
OpBuilder::InsertionGuard guard(*builder);
Block* block = builder->createBlock(body);
// Block arguments are scalars of the given element type.
RankedTensorType type = RankedTensorType::get(/*shape=*/{}, element_type);
Location loc = body->getLoc();
block->addArgument(type, loc);
block->addArgument(type, loc);
Op reducer =
builder->create<Op>(loc, block->getArgument(0), block->getArgument(1));
builder->create<mhlo::ReturnOp>(loc, reducer.getResult());
}
mhlo::ReduceOp CloneAndReplaceElementType(mhlo::ReduceOp op,
PatternRewriter& rewriter,
Type elem_type,
ArrayRef<Value> operands) {
int num_non_return_hlo_ops = 0;
Operation* map_op = nullptr;
op.body().walk([&](Operation* hlo_op) {
if (isa<mhlo::ReturnOp>(hlo_op)) return;
++num_non_return_hlo_ops;
map_op = hlo_op;
});
assert(num_non_return_hlo_ops == 1 && map_op &&
"Not support reduction region");
Location loc = op.getLoc();
mhlo::ReduceOp new_op = rewriter.create<mhlo::ReduceOp>(
loc, operands[0], operands[1], op.dimensions());
if (isa<mhlo::AddOp>(map_op)) {
BuildReduceBody<mhlo::AddOp>(elem_type, &new_op.body(), &rewriter);
} else if (isa<mhlo::MulOp>(map_op)) {
BuildReduceBody<mhlo::MulOp>(elem_type, &new_op.body(), &rewriter);
} else if (isa<mhlo::MaxOp>(map_op)) {
BuildReduceBody<mhlo::MaxOp>(elem_type, &new_op.body(), &rewriter);
} else if (isa<mhlo::MinOp>(map_op)) {
BuildReduceBody<mhlo::MinOp>(elem_type, &new_op.body(), &rewriter);
} else if (isa<mhlo::AndOp>(map_op)) {
// We use MinOp to replace AndOp since std AndOp requires operands have i1
// type.
BuildReduceBody<mhlo::MinOp>(elem_type, &new_op.body(), &rewriter);
} else if (isa<mhlo::OrOp>(map_op)) {
// We use MaxOp to replace OrOp since std AndOp requires operands have i1
// type.
BuildReduceBody<mhlo::MaxOp>(elem_type, &new_op.body(), &rewriter);
} else {
assert(false && "not supported reduce type");
}
return new_op;
}
struct ConvertReduceOpWithSmallWidthIntType
: public OpRewritePattern<mhlo::ReduceOp> {
using OpRewritePattern::OpRewritePattern;
LogicalResult matchAndRewrite(mhlo::ReduceOp op,
PatternRewriter& rewriter) const override {
if (op.getNumOperands() > 2) {
// Currently do not support Variadic operand number.
return failure();
}
SmallVector<int64_t, 4> dims_to_reduce;
for (auto v : op.dimensions().getValues<APInt>()) {
dims_to_reduce.push_back(v.getSExtValue());
}
RankedTensorType ty =
op.getOperand(0).getType().dyn_cast<RankedTensorType>();
assert(ty && "suppose reduce input is a ranked tensor");
int rank = ty.getRank();
int ndims_to_reduce = static_cast<int>(dims_to_reduce.size());
if (rank != 2 || ndims_to_reduce != 1) {
// Suppose that there are only rank-2 row/colunm reduction after
// `canonicalize-reduction` pass.
return failure();
}
// Currently we convert column reduce ops having type i1, i8 or i16 to i32
// since our codegen engine does not support column reduction ATM.
//
// To be concrete, we currently rely on atomic ops to implement column
// reduction. On Nvidia GPUs, atomic op can only operate on 32 bit and 64
// bit integers. In XLA, if the element type of the binary operation is
// smaller than 32 bits, int32 is used to wrapper original element type.
// The implementation rely on `atomicCAS` with is not accessible in the
// current MLIR version.
auto int_tp = ty.getElementType().dyn_cast<IntegerType>();
if (!int_tp || int_tp.getWidth() >= 32) {
return failure();
}
Location loc = op.getLoc();
IntegerType elem_type = rewriter.getIntegerType(32);
SmallVector<Value, 4> converted_operands;
for (auto value : op.getOperands()) {
converted_operands.push_back(
rewriter.create<mhlo::ConvertOp>(loc, value, elem_type));
}
mhlo::ReduceOp new_op =
CloneAndReplaceElementType(op, rewriter, elem_type, converted_operands);
assert(new_op && "convert element type of reduce op failed");
SmallVector<Value, 4> converted_results;
for (auto value : new_op.getResults()) {
converted_results.push_back(
rewriter.create<mhlo::ConvertOp>(loc, value, ty.getElementType()));
}
rewriter.replaceOp(op, converted_results);
return success();
}
};
template <typename OpTy>
struct ConvertConvOp : public OpRewritePattern<OpTy> {
using OpRewritePattern<OpTy>::OpRewritePattern;
LogicalResult matchAndRewrite(OpTy op,
PatternRewriter& rewriter) const override {
Location loc = op.getLoc();
Value lhs = op->getOperand(0);
Value rhs = op->getOperand(1);
FloatType f16_ty = rewriter.getF16Type();
FloatType f32_ty = rewriter.getF32Type();
RankedTensorType lhs_ty = lhs.getType().dyn_cast<RankedTensorType>();
RankedTensorType rhs_ty = rhs.getType().dyn_cast<RankedTensorType>();
RankedTensorType result_ty =
op.getType().template dyn_cast<RankedTensorType>();
if (!lhs_ty || !rhs_ty || lhs_ty.getElementType() != f32_ty ||
rhs_ty.getElementType() != f32_ty) {
return failure();
}
Value lhs_f16 = rewriter.create<mhlo::ConvertOp>(loc, lhs, f16_ty);
Value rhs_f16 = rewriter.create<mhlo::ConvertOp>(loc, rhs, f16_ty);
RankedTensorType f16_tensor_ty =
RankedTensorType::getChecked(loc, result_ty.getShape(), f16_ty);
SmallVector<Value, 4> newOperands = {lhs_f16, rhs_f16};
for (int i = 2; i < op->getOperands().size(); ++i) {
newOperands.push_back(op->getOperand(i));
}
Value conv =
rewriter.create<OpTy>(loc, f16_tensor_ty, newOperands, op->getAttrs());
Value fp32_conv = rewriter.create<mhlo::ConvertOp>(loc, conv, f32_ty);
rewriter.replaceOp(op, fp32_conv);
return success();
}
};
struct ConvertDotGeneralOp : public OpRewritePattern<mhlo::DotGeneralOp> {
using OpRewritePattern::OpRewritePattern;
LogicalResult matchAndRewrite(mhlo::DotGeneralOp op,
PatternRewriter& rewriter) const override {
Location loc = op.getLoc();
Value lhs = op.lhs();
Value rhs = op.rhs();
FloatType f16_ty = rewriter.getF16Type();
FloatType f32_ty = rewriter.getF32Type();
RankedTensorType lhs_ty = lhs.getType().dyn_cast<RankedTensorType>();
RankedTensorType rhs_ty = rhs.getType().dyn_cast<RankedTensorType>();
RankedTensorType result_ty = op.getType().dyn_cast<RankedTensorType>();
if (!lhs_ty || !rhs_ty || lhs_ty.getElementType() != f32_ty ||
rhs_ty.getElementType() != f32_ty) {
return failure();
}
Value lhs_f16 = rewriter.create<mhlo::ConvertOp>(loc, lhs, f16_ty);
Value rhs_f16 = rewriter.create<mhlo::ConvertOp>(loc, rhs, f16_ty);
RankedTensorType f16_tensor_ty =
RankedTensorType::getChecked(loc, result_ty.getShape(), f16_ty);
// tensor dot general
Value dot = rewriter.create<mhlo::DotGeneralOp>(
loc, f16_tensor_ty, lhs_f16, rhs_f16, op.dot_dimension_numbers(),
nullptr);
Value fp32_dot = rewriter.create<mhlo::ConvertOp>(loc, dot, f32_ty);
rewriter.replaceOp(op, fp32_dot);
return success();
}
};
struct ElementTypeConverterPass
: public ElementTypeConverterPassBase<ElementTypeConverterPass> {
explicit ElementTypeConverterPass(bool enable_fp16_gemm)
: ElementTypeConverterPassBase<
ElementTypeConverterPass>::ElementTypeConverterPassBase() {
this->enable_fp16_gemm_ = enable_fp16_gemm;
}
void runOnOperation() override {
func::FuncOp func = getOperation();
MLIRContext& ctx = getContext();
RewritePatternSet patterns(&ctx);
patterns.insert<ConvertReduceOpWithSmallWidthIntType>(&ctx);
if (enable_fp16_gemm_) {
patterns.insert<ConvertDotGeneralOp, ConvertConvOp<mhlo::DynamicConvOp>,
ConvertConvOp<mhlo::ConvOp>>(&ctx);
}
if (failed(applyPatternsAndFoldGreedily(func, std::move(patterns)))) {
func.emitError("applyPatternsAndFoldGreedily does not converge");
signalPassFailure();
}
}
};
} // namespace
std::unique_ptr<OperationPass<func::FuncOp>> createDiscElementTypeConverterPass(
bool enable_fp16_gemm) {
return std::make_unique<ElementTypeConverterPass>(enable_fp16_gemm);
}
} // namespace disc_ral
} // namespace mlir
|
#include "GameScene.h"
#include "Ship.h"
#include "MeteorSpawner.h"
GameScene::GameScene() {
ShipPtr ship = std::make_shared<Ship>();
addGameObject(ship);
MeteorSpawnerPtr meteorSpawner = std::make_shared<MeteorSpawner>();
addGameObject(meteorSpawner);
}
|
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include <AzFramework/Components/TransformComponent.h>
#include <RigidBodyComponent.h>
#include <StaticRigidBodyComponent.h>
namespace PhysX
{
namespace TestUtils
{
template<typename ColliderType>
EntityPtr AddUnitTestObject(const AZ::Vector3& position, const char* name)
{
EntityPtr entity = AZStd::make_shared<AZ::Entity>(name);
AZ::TransformConfig transformConfig;
transformConfig.m_worldTransform = AZ::Transform::CreateTranslation(position);
entity->CreateComponent<AzFramework::TransformComponent>()->SetConfiguration(transformConfig);
auto colliderComponent = entity->CreateComponent<ColliderType>();
auto colliderConfig = AZStd::make_shared<Physics::ColliderConfiguration>();
auto shapeConfig = AZStd::make_shared<typename ColliderType::Configuration>();
colliderComponent->SetShapeConfigurationList({ AZStd::make_pair(colliderConfig, shapeConfig) });
Physics::RigidBodyConfiguration rigidBodyConfig;
rigidBodyConfig.m_computeMass = false;
entity->CreateComponent<RigidBodyComponent>(rigidBodyConfig);
entity->Init();
entity->Activate();
return entity;
}
template<typename ColliderType>
EntityPtr AddStaticUnitTestObject(const AZ::Vector3& position, const char* name)
{
EntityPtr entity = AZStd::make_shared<AZ::Entity>(name);
AZ::TransformConfig transformConfig;
transformConfig.m_worldTransform = AZ::Transform::CreateTranslation(position);
entity->CreateComponent<AzFramework::TransformComponent>()->SetConfiguration(transformConfig);
auto colliderComponent = entity->CreateComponent<ColliderType>();
auto colliderConfig = AZStd::make_shared<Physics::ColliderConfiguration>();
auto shapeConfig = AZStd::make_shared<typename ColliderType::Configuration>();
colliderComponent->SetShapeConfigurationList({ AZStd::make_pair(colliderConfig, shapeConfig) });
entity->CreateComponent<StaticRigidBodyComponent>();
entity->Init();
entity->Activate();
return entity;
}
template<typename ColliderT>
EntityPtr CreateTriggerAtPosition(const AZ::Vector3& position)
{
EntityPtr triggerEntity = AZStd::make_shared<AZ::Entity>("TriggerEntity");
AZ::TransformConfig transformConfig;
transformConfig.m_worldTransform = AZ::Transform::CreateTranslation(position);
triggerEntity->CreateComponent<AzFramework::TransformComponent>()->SetConfiguration(transformConfig);
auto colliderConfiguration = AZStd::make_shared<Physics::ColliderConfiguration>();
colliderConfiguration->m_isTrigger = true;
auto shapeConfiguration = AZStd::make_shared<typename ColliderT::Configuration>();
auto colliderComponent = triggerEntity->CreateComponent<ColliderT>();
colliderComponent->SetShapeConfigurationList({ AZStd::make_pair(colliderConfiguration, shapeConfiguration) });
triggerEntity->CreateComponent<StaticRigidBodyComponent>();
triggerEntity->Init();
triggerEntity->Activate();
return triggerEntity;
}
template<typename ColliderT>
EntityPtr CreateDynamicTriggerAtPosition(const AZ::Vector3& position)
{
EntityPtr triggerEntity = AZStd::make_shared<AZ::Entity>("DynamicTriggerEntity");
AZ::TransformConfig transformConfig;
transformConfig.m_worldTransform = AZ::Transform::CreateTranslation(position);
triggerEntity->CreateComponent<AzFramework::TransformComponent>()->SetConfiguration(transformConfig);
auto colliderConfiguration = AZStd::make_shared<Physics::ColliderConfiguration>();
colliderConfiguration->m_isTrigger = true;
auto shapeConfiguration = AZStd::make_shared<typename ColliderT::Configuration>();
auto colliderComponent = triggerEntity->CreateComponent<ColliderT>();
colliderComponent->SetShapeConfigurationList({ AZStd::make_pair(colliderConfiguration, shapeConfiguration) });
triggerEntity->CreateComponent<RigidBodyComponent>();
triggerEntity->Init();
triggerEntity->Activate();
return triggerEntity;
}
}
}
|
// 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 "chrome/browser/component_updater/registration.h"
#include "base/feature_list.h"
#include "base/files/file_path.h"
#include "base/metrics/histogram_functions.h"
#include "base/path_service.h"
#include "build/branding_buildflags.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/buildflags.h"
#include "chrome/browser/component_updater/autofill_regex_component_installer.h"
#include "chrome/browser/component_updater/chrome_origin_trials_component_installer.h"
#include "chrome/browser/component_updater/client_side_phishing_component_installer.h"
#include "chrome/browser/component_updater/crl_set_component_installer.h"
#include "chrome/browser/component_updater/crowd_deny_component_installer.h"
#include "chrome/browser/component_updater/file_type_policies_component_installer.h"
#include "chrome/browser/component_updater/first_party_sets_component_installer.h"
#include "chrome/browser/component_updater/floc_component_installer.h"
#include "chrome/browser/component_updater/hyphenation_component_installer.h"
#include "chrome/browser/component_updater/mei_preload_component_installer.h"
#include "chrome/browser/component_updater/pki_metadata_component_installer.h"
#include "chrome/browser/component_updater/ssl_error_assistant_component_installer.h"
#include "chrome/browser/component_updater/sth_set_component_remover.h"
#include "chrome/browser/component_updater/subresource_filter_component_installer.h"
#include "chrome/browser/component_updater/trust_token_key_commitments_component_installer.h"
#include "chrome/common/buildflags.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/pref_names.h"
#include "components/component_updater/component_updater_service.h"
#include "components/component_updater/crl_set_remover.h"
#include "components/component_updater/installer_policies/autofill_states_component_installer.h"
#include "components/component_updater/installer_policies/on_device_head_suggest_component_installer.h"
#include "components/component_updater/installer_policies/optimization_hints_component_installer.h"
#include "components/component_updater/installer_policies/safety_tips_component_installer.h"
#include "components/nacl/common/buildflags.h"
#include "device/vr/buildflags/buildflags.h"
#include "ppapi/buildflags/buildflags.h"
#include "third_party/widevine/cdm/buildflags.h"
#if defined(OS_WIN)
#include "chrome/browser/component_updater/sw_reporter_installer_win.h"
#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
#include "chrome/browser/component_updater/third_party_module_list_component_installer_win.h"
#endif // BUILDFLAG(GOOGLE_CHROME_BRANDING)
#endif // defined(OS_WIN)
#if defined(OS_WIN)
#include "chrome/browser/component_updater/recovery_improved_component_installer.h"
#else
#include "chrome/browser/component_updater/recovery_component_installer.h"
#endif // defined(OS_WIN)
#if defined(OS_ANDROID)
#include "chrome/browser/component_updater/desktop_sharing_hub_component_remover.h"
#endif // defined(OS_ANDROID)
#if !defined(OS_ANDROID)
#include "chrome/browser/component_updater/desktop_sharing_hub_component_installer.h"
#include "chrome/browser/component_updater/soda_component_installer.h"
#include "chrome/browser/component_updater/zxcvbn_data_component_installer.h"
#include "chrome/browser/resource_coordinator/tab_manager.h"
#include "media/base/media_switches.h"
#endif // !defined(OS_ANDROID)
#if BUILDFLAG(IS_CHROMEOS_ASH)
#include "chrome/browser/component_updater/smart_dim_component_installer.h"
#endif // BUILDFLAG(IS_CHROMEOS_ASH)
#if BUILDFLAG(ENABLE_NACL)
#include "chrome/browser/component_updater/pnacl_component_installer.h"
#endif // BUILDFLAG(ENABLE_NACL)
#if BUILDFLAG(ENABLE_PLUGINS)
#include "chrome/browser/component_updater/pepper_flash_component_installer.h"
#endif
#if BUILDFLAG(ENABLE_VR)
#include "chrome/browser/component_updater/vr_assets_component_installer.h"
#endif
#if BUILDFLAG(ENABLE_MEDIA_FOUNDATION_WIDEVINE_CDM)
#include "chrome/browser/component_updater/media_foundation_widevine_cdm_component_installer.h"
#endif
#if BUILDFLAG(ENABLE_WIDEVINE_CDM_COMPONENT)
#include "chrome/browser/component_updater/widevine_cdm_component_installer.h"
#endif // BUILDFLAG(ENABLE_WIDEVINE_CDM_COMPONENT)
#if defined(USE_AURA)
#include "ui/aura/env.h"
#endif
namespace component_updater {
void RegisterComponentsForUpdate(bool is_off_the_record_profile,
PrefService* profile_prefs,
const base::FilePath& profile_path) {
auto* const cus = g_browser_process->component_updater();
#if defined(OS_WIN)
RegisterRecoveryImprovedComponent(cus, g_browser_process->local_state());
#else
// TODO(crbug.com/687231): Implement the Improved component on Mac, etc.
RegisterRecoveryComponent(cus, g_browser_process->local_state());
#endif // defined(OS_WIN)
#if BUILDFLAG(ENABLE_PLUGINS)
// TODO(crbug.com/1069814): Remove after 2021-10-01.
CleanUpPepperFlashComponent(profile_path);
#endif
#if BUILDFLAG(ENABLE_MEDIA_FOUNDATION_WIDEVINE_CDM)
RegisterMediaFoundationWidevineCdmComponent(cus);
#endif
#if BUILDFLAG(ENABLE_WIDEVINE_CDM_COMPONENT)
RegisterWidevineCdmComponent(cus);
#endif // BUILDFLAG(ENABLE_WIDEVINE_CDM_COMPONENT)
#if BUILDFLAG(ENABLE_NACL) && !defined(OS_ANDROID)
#if BUILDFLAG(IS_CHROMEOS_ASH)
// PNaCl on Chrome OS is on rootfs and there is no need to download it. But
// Chrome4ChromeOS on Linux doesn't contain PNaCl so enable component
// installer when running on Linux. See crbug.com/422121 for more details.
if (!base::SysInfo::IsRunningOnChromeOS()) {
#endif // BUILDFLAG(IS_CHROMEOS_ASH)
RegisterPnaclComponent(cus);
#if BUILDFLAG(IS_CHROMEOS_ASH)
}
#endif // BUILDFLAG(IS_CHROMEOS_ASH)
#endif // BUILDFLAG(ENABLE_NACL) && !defined(OS_ANDROID)
RegisterSubresourceFilterComponent(cus);
RegisterFlocComponent(cus,
g_browser_process->floc_sorting_lsh_clusters_service());
RegisterOnDeviceHeadSuggestComponent(
cus, g_browser_process->GetApplicationLocale());
RegisterOptimizationHintsComponent(cus);
RegisterTrustTokenKeyCommitmentsComponentIfTrustTokensEnabled(cus);
RegisterFirstPartySetsComponent(cus);
base::FilePath path;
if (base::PathService::Get(chrome::DIR_USER_DATA, &path)) {
// The CRLSet component previously resided in a different location: delete
// the old file.
component_updater::DeleteLegacyCRLSet(path);
#if !BUILDFLAG(IS_CHROMEOS_ASH) && !defined(OS_ANDROID)
// Clean up previous STH sets that may have been installed. This is not
// done for:
// Android: Because STH sets were never used
// Chrome OS: On Chrome OS, this cleanup is delayed until user login.
component_updater::DeleteLegacySTHSet(path);
#endif
#if defined(OS_ANDROID)
// Clean up any desktop sharing hubs that were installed on Android.
component_updater::DeleteDesktopSharingHub(path);
#endif // defined(OS_ANDROID)
}
RegisterSSLErrorAssistantComponent(cus);
// Since file type policies are per-platform, and we don't support
// Fuchsia-specific component versions, we don't dynamically update file type
// policies on Fuchsia.
#if !defined(OS_FUCHSIA)
RegisterFileTypePoliciesComponent(cus);
#endif
#if !BUILDFLAG(IS_CHROMEOS_ASH)
// CRLSetFetcher attempts to load a CRL set from either the local disk or
// network.
// For Chrome OS this registration is delayed until user login.
component_updater::RegisterCRLSetComponent(cus);
#endif // !BUILDFLAG(IS_CHROMEOS_ASH)
RegisterOriginTrialsComponent(cus);
RegisterMediaEngagementPreloadComponent(cus, base::OnceClosure());
#if defined(OS_WIN)
// SwReporter is only needed for official builds. However, to enable testing
// on chromium build bots, it is always registered here and
// RegisterSwReporterComponent() has support for running only in official
// builds or tests.
RegisterSwReporterComponent(cus);
#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
RegisterThirdPartyModuleListComponent(cus);
#endif // BUILDFLAG(GOOGLE_CHROME_BRANDING)
#endif // defined(OS_WIN)
#if BUILDFLAG(ENABLE_VR)
if (component_updater::ShouldRegisterVrAssetsComponentOnStartup()) {
component_updater::RegisterVrAssetsComponent(cus);
}
#endif
MaybeRegisterPKIMetadataComponent(cus);
RegisterSafetyTipsComponent(cus);
RegisterCrowdDenyComponent(cus);
#if BUILDFLAG(IS_CHROMEOS_ASH)
RegisterSmartDimComponent(cus);
#endif // !BUILDFLAG(IS_CHROMEOS_ASH)
#if BUILDFLAG(USE_MINIKIN_HYPHENATION) && !defined(OS_ANDROID)
RegisterHyphenationComponent(cus);
#endif
#if !defined(OS_ANDROID)
RegisterDesktopSharingHubComponent(cus);
RegisterZxcvbnDataComponent(cus);
#endif // !defined(OS_ANDROID)
RegisterAutofillStatesComponent(cus, g_browser_process->local_state());
RegisterAutofillRegexComponent(cus);
RegisterClientSidePhishingComponent(cus);
}
} // namespace component_updater
|
/*
* Copyright 2021 The Modelbox Project Authors. 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 "modelbox/match_stream.h"
#include <functional>
#include <future>
#include <thread>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "mock_driver_ctl.h"
#include "modelbox/base/log.h"
#include "modelbox/device/mockdevice/device_mockdevice.h"
#include "modelbox/session.h"
namespace modelbox {
class MatchStreamTest : public testing::Test {
protected:
void SetUp() override {
in_port1_ = std::make_shared<InPort>("a", nullptr);
in_port2_ = std::make_shared<InPort>("b", nullptr);
data_ports_.push_back(in_port1_);
data_ports_.push_back(in_port2_);
// prepare data
auto root_buffer_index = std::make_shared<BufferIndexInfo>();
auto session = std::make_shared<Session>(nullptr);
auto stream1 = std::make_shared<Stream>(session);
buffer1_ = std::make_shared<Buffer>();
auto buffer1_index = std::make_shared<BufferIndexInfo>();
auto buffer1_inherit = std::make_shared<BufferInheritInfo>();
buffer1_inherit->SetInheritFrom(root_buffer_index);
buffer1_inherit->SetType(BufferProcessType::EXPAND);
buffer1_index->SetInheritInfo(buffer1_inherit);
buffer1_index->SetStream(stream1);
buffer1_index->SetIndex(0);
BufferManageView::SetIndexInfo(buffer1_, buffer1_index);
auto stream2 = std::make_shared<Stream>(session);
buffer2_ = std::make_shared<Buffer>();
auto buffer2_index = std::make_shared<BufferIndexInfo>();
auto buffer2_inherit = std::make_shared<BufferInheritInfo>();
buffer2_inherit->SetInheritFrom(root_buffer_index);
buffer2_inherit->SetType(BufferProcessType::EXPAND);
buffer2_index->SetInheritInfo(buffer2_inherit);
buffer2_index->SetStream(stream2);
buffer2_index->SetIndex(0);
BufferManageView::SetIndexInfo(buffer2_, buffer2_index);
// push data
in_port1_->GetQueue()->Push(buffer1_);
in_port2_->GetQueue()->Push(buffer2_);
}
std::shared_ptr<Buffer> buffer1_;
std::shared_ptr<Buffer> buffer2_;
std::shared_ptr<InPort> in_port1_;
std::shared_ptr<InPort> in_port2_;
std::vector<std::shared_ptr<InPort>> data_ports_;
};
TEST_F(MatchStreamTest, InputMatchStreamManagerTest) {
// run
InputMatchStreamManager input_match_stream_mgr("test", 32, 2);
auto ret = input_match_stream_mgr.LoadData(data_ports_);
EXPECT_EQ(ret, STATUS_SUCCESS);
std::list<std::shared_ptr<MatchStreamData>> match_stream_list;
ret = input_match_stream_mgr.GenMatchStreamData(match_stream_list);
EXPECT_EQ(ret, STATUS_SUCCESS);
ASSERT_EQ(match_stream_list.size(), 1);
auto match_stream = match_stream_list.front();
ASSERT_EQ(match_stream->GetDataCount(), 1);
auto data_map = match_stream->GetBufferList();
ASSERT_EQ(data_map->size(), 2);
ASSERT_EQ(data_map->at("a").size(), 1);
ASSERT_EQ(data_map->at("a").size(), 1);
EXPECT_EQ(data_map->at("a").front(), buffer1_);
EXPECT_EQ(data_map->at("b").front(), buffer2_);
}
TEST_F(MatchStreamTest, OutputMatchStream) {
std::set<std::string> output_port_names{"a", "b"};
OutputMatchStreamManager output_match_stream_mgr(
"test", std::move(output_port_names));
auto buffer1_index = BufferManageView::GetIndexInfo(buffer1_);
auto buffer2_index = BufferManageView::GetIndexInfo(buffer2_);
auto out_buffer1 = std::make_shared<Buffer>();
auto out_index = std::make_shared<BufferIndexInfo>();
auto out_inherit = std::make_shared<BufferInheritInfo>();
out_inherit->SetInheritFrom(buffer1_index);
out_inherit->SetType(BufferProcessType::EXPAND);
auto out_process = std::make_shared<BufferProcessInfo>();
out_process->SetParentBuffers("a", {buffer1_index});
out_process->SetParentBuffers("b", {buffer2_index});
out_index->SetInheritInfo(out_inherit);
out_index->SetProcessInfo(out_process);
BufferManageView::SetIndexInfo(out_buffer1, out_index);
auto out_buffer2 = std::make_shared<Buffer>();
auto out_index2 = std::make_shared<BufferIndexInfo>();
auto out_inherit2 = std::make_shared<BufferInheritInfo>();
out_inherit2->SetInheritFrom(buffer1_index);
out_inherit2->SetType(BufferProcessType::EXPAND);
auto out_process2 = std::make_shared<BufferProcessInfo>();
out_process2->SetParentBuffers("a", {buffer1_index});
out_process2->SetParentBuffers("b", {buffer2_index});
out_index2->SetInheritInfo(out_inherit2);
out_index2->SetProcessInfo(out_process2);
BufferManageView::SetIndexInfo(out_buffer2, out_index2);
std::unordered_map<std::string, std::vector<std::shared_ptr<Buffer>>>
output_data;
output_data["a"].push_back(out_buffer1);
output_data["b"].push_back(out_buffer2);
std::unordered_map<std::string, std::shared_ptr<DataMeta>> port_stream_meta;
auto ret = output_match_stream_mgr.UpdateStreamInfo(
output_data, port_stream_meta, nullptr);
ASSERT_EQ(ret, STATUS_SUCCESS);
ASSERT_EQ(output_match_stream_mgr.GetOutputStreamCount(), 1);
EXPECT_NE(out_index->GetStream(), nullptr);
EXPECT_EQ(out_index->GetIndex(), 0);
EXPECT_NE(out_index2->GetStream(), nullptr);
EXPECT_EQ(out_index2->GetIndex(), 0);
}
} // namespace modelbox
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <float.h>
#include <limits.h>
#include "mex.h"
#include "../src/TVopt.h"
/* solveTV.cpp
Solves 1-dimensional unweighted TV proximity problems by applying the most appropriate algorithm
Parameters:
- 0: reference signal y.
- 1: lambda penalty.
- 2: p norm.
Outputs:
- 0: primal solution x.
- 1: array with optimizer information:
+ [0]: number of iterations run.
+ [1]: dual gap.
*/
void mexFunction(int nlhs, mxArray *plhs[ ],int nrhs, const mxArray *prhs[ ]) {
double *x=NULL,*y,*info=NULL;
double lambda,p;
int M,N,nn,i;
#define FREE \
if(!nlhs) free(x);
#define CANCEL(txt) \
printf("Error in solveTVp_GP: %s\n",txt); \
if(x) free(x); \
if(info) free(info); \
return;
/* Check input correctness */
if(nrhs < 3){CANCEL("not enought inputs");}
if(!mxIsClass(prhs[0],"double")) {CANCEL("input signal must be in double format")}
/* Create output arrays */
M = mxGetM(prhs[0]);
N = mxGetN(prhs[0]);
nn = (M > N) ? M : N;
if(nlhs >= 1){
plhs[0] = mxCreateDoubleMatrix(nn,1,mxREAL);
x = mxGetPr(plhs[0]);
}
else x = (double*)malloc(sizeof(double)*nn);
if(nlhs >= 2){
plhs[1] = mxCreateDoubleMatrix(N_INFO,1,mxREAL);
info = mxGetPr(plhs[1]);
}
/* Retrieve input data */
y = mxGetPr(prhs[0]);
lambda = mxGetScalar(prhs[1]);
p = mxGetScalar(prhs[2]);
/* Run general method, which choses best algorithm */
TV(y, lambda, x, info, nn, p, NULL);
/* Free resources */
FREE
return;
}
|
#include "animation_gradientpattern.h"
#include "keyframes.h"
#include "data_set/data_set.h"
#include "data_set/data_animation_bits.h"
#include "assert.h"
#include "../utils/utils.h"
#include "nrf_log.h"
// FIXME!!!
#include "modules/anim_controller.h"
#include "utils/rainbow.h"
#include "config/board_config.h"
namespace Animations
{
/// <summary>
/// constructor for keyframe-based animation instances
/// Needs to have an associated preset passed in
/// </summary>
AnimationInstanceGradientPattern::AnimationInstanceGradientPattern(const AnimationGradientPattern* preset, const DataSet::AnimationBits* bits)
: AnimationInstance(preset, bits) {
}
/// <summary>
/// destructor
/// </summary>
AnimationInstanceGradientPattern::~AnimationInstanceGradientPattern() {
}
/// <summary>
/// Small helper to return the expected size of the preset data
/// </summary>
int AnimationInstanceGradientPattern::animationSize() const {
return sizeof(AnimationGradientPattern);
}
/// <summary>
/// (re)Initializes the instance to animate leds. This can be called on a reused instance.
/// </summary>
void AnimationInstanceGradientPattern::start(int _startTime, uint8_t _remapFace, bool _loop) {
AnimationInstance::start(_startTime, _remapFace, _loop);
auto preset = getPreset();
NRF_LOG_INFO("override: %d", preset->overrideWithFace);
if (preset->overrideWithFace) {
// Compute color based on face is 127
rgb = animationBits->getPaletteColor(PALETTE_COLOR_FROM_FACE);
}
}
/// <summary>
/// Computes the list of LEDs that need to be on, and what their intensities should be
/// based on the different tracks of this animation.
/// </summary>
/// <param name="ms">The animation time (in milliseconds)</param>
/// <param name="retIndices">the return list of LED indices to fill, max size should be at least 21, the max number of leds</param>
/// <param name="retColors">the return list of LED color to fill, max size should be at least 21, the max number of leds</param>
/// <returns>The number of leds/intensities added to the return array</returns>
int AnimationInstanceGradientPattern::updateLEDs(int ms, int retIndices[], uint32_t retColors[])
{
int time = ms - startTime;
auto preset = getPreset();
// Figure out the color from the gradient
auto& gradient = animationBits->getRGBTrack(preset->gradientTrackOffset);
uint32_t gradientColor = 0;
if (preset->overrideWithFace) {
gradientColor = rgb;
} else {
int gradientTime = time * 1000 / preset->duration;
gradientColor = gradient.evaluateColor(animationBits, gradientTime);
}
int trackTime = time * 256 / preset->speedMultiplier256;
// Each track will append its led indices and colors into the return array
// The assumption is that led indices don't overlap between tracks of a single animation,
// so there will always be enough room in the return arrays.
int totalCount = 0;
int indices[20];
uint32_t colors[20];
for (int i = 0; i < preset->trackCount; ++i)
{
auto track = animationBits->getTrack((uint16_t)(preset->tracksOffset + i));
int count = track.evaluate(animationBits, gradientColor, trackTime, indices, colors);
for (int j = 0; j < count; ++j)
{
retIndices[totalCount+j] = indices[j];
retColors[totalCount+j] = colors[j];
}
totalCount += count;
}
return totalCount;
}
/// <summary>
/// Clear all LEDs controlled by this animation, for instance when the anim gets interrupted.
/// </summary>
int AnimationInstanceGradientPattern::stop(int retIndices[]) {
auto preset = getPreset();
// Each track will append its led indices and colors into the return array
// The assumption is that led indices don't overlap between tracks of a single animation,
// so there will always be enough room in the return arrays.
int totalCount = 0;
int indices[20];
for (int i = 0; i < preset->trackCount; ++i)
{
auto track = animationBits->getTrack((uint16_t)(preset->tracksOffset + i));
int count = track.extractLEDIndices(indices);
for (int j = 0; j < count; ++j)
{
retIndices[totalCount+j] = indices[j];
}
totalCount += count;
}
return totalCount;
}
/// <summary>
/// Small helper to get the correct type preset data pointer stored in the instance
/// </summary
const AnimationGradientPattern* AnimationInstanceGradientPattern::getPreset() const {
return static_cast<const AnimationGradientPattern*>(animationPreset);
}
/// <summary>
/// Returns a track
/// </summary>
const Track& AnimationInstanceGradientPattern::GetTrack(int index) const {
auto preset = getPreset();
assert(index < preset->trackCount);
return animationBits->getTrack(preset->tracksOffset + index);
}
}
|
// Hossein Moein
// September 12, 2017
/*
Copyright (c) 2019-2022, Hossein Moein
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 Hossein Moein and/or the DataFrame 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 <COPYRIGHT HOLDER> 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 <DataFrame/Vectors/HeteroVector.h>
#include <algorithm>
// ----------------------------------------------------------------------------
namespace hmdf
{
template<typename T>
std::vector<T> &HeteroVector::get_vector() {
auto iter = vectors_<T>.find (this);
// don't have it yet, so create functions for copying and destroying
if (iter == vectors_<T>.end()) {
clear_functions_.emplace_back (
[](HeteroVector &hv) { vectors_<T>.erase(&hv); });
// if someone copies me, they need to call each
// copy_function and pass themself
copy_functions_.emplace_back (
[](const HeteroVector &from, HeteroVector &to) {
vectors_<T>[&to] = vectors_<T>[&from];
});
move_functions_.emplace_back (
[](HeteroVector &from, HeteroVector &to) {
vectors_<T>[&to] = std::move(vectors_<T>[&from]);
});
iter = vectors_<T>.emplace (this, std::vector<T>()).first;
}
return (iter->second);
}
// ----------------------------------------------------------------------------
template<typename T>
HeteroView HeteroVector::get_view(size_type begin, size_type end) {
std::vector<T> &vec = get_vector<T>();
return (HeteroView(
&(vec[begin]), end == size_t(-1) ? &(vec.back()) : &(vec[end])));
}
// ----------------------------------------------------------------------------
template<typename T>
HeteroPtrView HeteroVector::get_ptr_view(size_type begin, size_type end) {
std::vector<T> &vec = get_vector<T>();
return (HeteroPtrView(
&(*(vec.begin() + begin)),
end == size_type(-1) ? &(*(vec.end())) : &(*(vec.begin() + end))));
}
// ----------------------------------------------------------------------------
template<typename T>
const std::vector<T> &HeteroVector::get_vector() const {
return (const_cast<HeteroVector *>(this)->get_vector<T>());
}
// ----------------------------------------------------------------------------
template<typename T>
void HeteroVector::push_back(const T &v) { get_vector<T>().push_back (v); }
// ----------------------------------------------------------------------------
template<typename T, class... Args>
void HeteroVector::emplace_back (Args &&... args) {
get_vector<T>().emplace_back (std::forward<Args>(args)...);
}
// ----------------------------------------------------------------------------
template<typename T, typename ITR, class... Args>
void HeteroVector::emplace (ITR pos, Args &&... args) {
get_vector<T>().emplace (pos, std::forward<Args>(args)...);
}
// ----------------------------------------------------------------------------
template<typename T, typename U>
void HeteroVector::visit_impl_help_ (T &visitor) {
auto iter = vectors_<U>.find (this);
if (iter != vectors_<U>.end())
for (auto &&element : iter->second)
visitor(element);
}
// ----------------------------------------------------------------------------
template<typename T, typename U>
void HeteroVector::visit_impl_help_ (T &visitor) const {
const auto citer = vectors_<U>.find (this);
if (citer != vectors_<U>.end())
for (auto &&element : citer->second)
visitor(element);
}
// ----------------------------------------------------------------------------
template<typename T, typename U>
void HeteroVector::sort_impl_help_ (T &functor) {
auto iter = vectors_<U>.find (this);
if (iter != vectors_<U>.end())
std::sort (iter->second.begin(), iter->second.end(), functor);
}
// ----------------------------------------------------------------------------
template<typename T, typename U>
void HeteroVector::change_impl_help_ (T &functor) {
auto iter = vectors_<U>.find (this);
if (iter != vectors_<U>.end())
functor(iter->second);
}
// ----------------------------------------------------------------------------
template<typename T, typename U>
void HeteroVector::change_impl_help_ (T &functor) const {
const auto citer = vectors_<U>.find (this);
if (citer != vectors_<U>.end())
functor(citer->second);
}
// ----------------------------------------------------------------------------
template<class T, template<class...> class TLIST, class... TYPES>
void HeteroVector::visit_impl_ (T &&visitor, TLIST<TYPES...>) {
// (..., visit_impl_help_<std::decay_t<T>, TYPES>(visitor)); // C++17
using expander = int[];
(void) expander { 0, (visit_impl_help_<T, TYPES>(visitor), 0) ... };
}
// ----------------------------------------------------------------------------
template<class T, template<class...> class TLIST, class... TYPES>
void HeteroVector::visit_impl_ (T &&visitor, TLIST<TYPES...>) const {
// (..., visit_impl_help_<std::decay_t<T>, TYPES>(visitor)); // C++17
using expander = int[];
(void) expander { 0, (visit_impl_help_<T, TYPES>(visitor), 0) ... };
}
// ----------------------------------------------------------------------------
template<class T, template<class...> class TLIST, class... TYPES>
void HeteroVector::sort_impl_ (T &&functor, TLIST<TYPES...>) {
using expander = int[];
(void) expander { 0, (sort_impl_help_<T, TYPES>(functor), 0) ... };
}
// ----------------------------------------------------------------------------
template<class T, template<class...> class TLIST, class... TYPES>
void HeteroVector::change_impl_ (T &&functor, TLIST<TYPES...>) {
using expander = int[];
(void) expander { 0, (change_impl_help_<T, TYPES>(functor), 0) ... };
}
// ----------------------------------------------------------------------------
template<class T, template<class...> class TLIST, class... TYPES>
void HeteroVector::change_impl_ (T &&functor, TLIST<TYPES...>) const {
using expander = int[];
(void) expander { 0, (change_impl_help_<T, TYPES>(functor), 0) ... };
}
// ----------------------------------------------------------------------------
template<typename T>
void HeteroVector::erase(size_type pos) {
auto &vec = get_vector<T>();
vec.erase (vec.begin() + pos);
}
// ----------------------------------------------------------------------------
template<typename T>
void HeteroVector::resize(size_type count) {
get_vector<T>().resize (count);
}
// ----------------------------------------------------------------------------
template<typename T>
void HeteroVector::resize(size_type count, const T &v) {
get_vector<T>().resize (count, v);
}
// ----------------------------------------------------------------------------
template<typename T>
void HeteroVector::pop_back() { get_vector<T>().pop_back (); }
// ----------------------------------------------------------------------------
template<typename T>
bool HeteroVector::empty() const noexcept {
return (get_vector<T>().empty ());
}
// ----------------------------------------------------------------------------
template<typename T>
T &HeteroVector::at(size_type idx) {
return (get_vector<T>().at (idx));
}
// ----------------------------------------------------------------------------
template<typename T>
const T &HeteroVector::at(size_type idx) const {
return (get_vector<T>().at (idx));
}
// ----------------------------------------------------------------------------
template<typename T>
T &HeteroVector::back() { return (get_vector<T>().back ()); }
// ----------------------------------------------------------------------------
template<typename T>
const T &HeteroVector::back() const { return (get_vector<T>().back ()); }
// ----------------------------------------------------------------------------
template<typename T>
T &HeteroVector::front() { return (get_vector<T>().front ()); }
// ----------------------------------------------------------------------------
template<typename T>
const T &HeteroVector::front() const { return (get_vector<T>().front ()); }
} // namespace hmdf
// ----------------------------------------------------------------------------
// Local Variables:
// mode:C++
// tab-width:4
// c-basic-offset:4
// End:
|
#include <iostream>
using namespace std;
typedef long long ll;
typedef long double ld;
#define rep(i, n) for (int i = 0; i < (int)(n); ++i)
#define rep3(i, m, n) for (int i = (m); i < (int)(n); ++i)
#define rrep(i, n) for (int i = (int)(n)-1; i >= 0; --i)
#define rrep3(i, m, n) for (int i = (int)(n)-1; i >= (m); --i)
#define endl '\n'
#define INF 0x7f7f7f7f7f7f7f7f
#define INFi 0x7f7f7f7f
ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; }
ll solve(int N, const vector<string> & S, const vector<ll> & C) {
// TODO: edit here
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int N;
cin >> N;
vector<ll> S(N);
vector<ll> C(N);
rep (i, N) {
cin >> S[i] >> C[i];
}
auto ans = solve(N, S, C);
cout << ans << endl;
return 0;
}
|
#pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/CName.hpp>
#include <RED4ext/Scripting/Natives/Generated/anim/IPoseBlendMethod.hpp>
namespace RED4ext
{
namespace anim {
struct PoseBlendMethod_Mask : anim::IPoseBlendMethod
{
static constexpr const char* NAME = "animPoseBlendMethod_Mask";
static constexpr const char* ALIAS = NAME;
CName maskName; // 30
uint8_t unk38[0x48 - 0x38]; // 38
};
RED4EXT_ASSERT_SIZE(PoseBlendMethod_Mask, 0x48);
} // namespace anim
} // namespace RED4ext
|
/*!
@file WaveTrackShifter.cpp
@brief headerless file injects method definitions for time shifting of WaveTrack
*/
#include "../../../ui/TimeShiftHandle.h"
#include "ViewInfo.h"
#include "../../../../WaveClip.h"
#include "../../../../WaveTrack.h"
class WaveTrackShifter final : public TrackShifter {
public:
WaveTrackShifter( WaveTrack &track )
: mpTrack{ track.SharedPointer<WaveTrack>() }
{
InitIntervals();
}
~WaveTrackShifter() override {}
Track &GetTrack() const override { return *mpTrack; }
HitTestResult HitTest(
double time, const ViewInfo &viewInfo, HitTestParams* ) override
{
auto pClip = mpTrack->GetClipAtTime( time );
if (!pClip)
return HitTestResult::Miss;
auto t0 = viewInfo.selectedRegion.t0();
auto t1 = viewInfo.selectedRegion.t1();
if ( mpTrack->IsSelected() && time >= t0 && time < t1 ) {
// Unfix maybe many intervals (at least one because of test above)
SelectInterval({t0, t1});
return HitTestResult::Selection;
}
// Select just one interval
UnfixIntervals( [&](const auto &interval){
return
static_cast<WaveTrack::IntervalData*>(interval.Extra())
->GetClip().get() == pClip;
} );
return HitTestResult::Intervals;
}
void SelectInterval( const TrackInterval &interval ) override
{
UnfixIntervals( [&](auto &myInterval){
// Use a slightly different test from CommonSelectInterval, rounding times
// to exact samples according to the clip's rate
auto data =
static_cast<WaveTrack::IntervalData*>( myInterval.Extra() );
auto clip = data->GetClip().get();
return !(clip->IsClipStartAfterClip(interval.Start()) ||
clip->BeforeClip(interval.End()));
});
}
bool SyncLocks() override { return true; }
bool MayMigrateTo(Track &other) override
{
return TrackShifter::CommonMayMigrateTo(other);
}
double HintOffsetLarger(double desiredOffset) override
{
// set it to a sample point, and minimum of 1 sample point
bool positive = (desiredOffset > 0);
if (!positive)
desiredOffset *= -1;
double nSamples = rint(mpTrack->GetRate() * desiredOffset);
nSamples = std::max(nSamples, 1.0);
desiredOffset = nSamples / mpTrack->GetRate();
if (!positive)
desiredOffset *= -1;
return desiredOffset;
}
double QuantizeOffset( double desiredOffset ) override
{
const auto rate = mpTrack->GetRate();
// set it to a sample point
return rint(desiredOffset * rate) / rate;
}
double AdjustOffsetSmaller(double desiredOffset) override
{
std::vector< WaveClip * > movingClips;
for ( auto &interval : MovingIntervals() ) {
auto data =
static_cast<WaveTrack::IntervalData*>( interval.Extra() );
movingClips.push_back(data->GetClip().get());
}
double newAmount = 0;
(void) mpTrack->CanOffsetClips(movingClips, desiredOffset, &newAmount);
return newAmount;
}
Intervals Detach() override
{
for ( auto &interval: mMoving ) {
auto pData = static_cast<WaveTrack::IntervalData*>( interval.Extra() );
auto pClip = pData->GetClip().get();
// interval will still hold the clip, so ignore the return:
(void) mpTrack->RemoveAndReturnClip(pClip);
mMigrated.erase(pClip);
}
return std::move( mMoving );
}
bool AdjustFit(
const Track &otherTrack, const Intervals &intervals,
double &desiredOffset, double tolerance) override
{
bool ok = true;
auto pOtherWaveTrack = static_cast<const WaveTrack*>(&otherTrack);
for ( auto &interval: intervals ) {
auto pData =
static_cast<WaveTrack::IntervalData*>( interval.Extra() );
auto pClip = pData->GetClip().get();
ok = pOtherWaveTrack->CanInsertClip(
pClip, desiredOffset, tolerance );
if( !ok )
break;
}
return ok;
}
bool Attach( Intervals intervals ) override
{
for (auto &interval : intervals) {
auto pData = static_cast<WaveTrack::IntervalData*>( interval.Extra() );
auto pClip = pData->GetClip();
if ( !mpTrack->AddClip( pClip ) )
return false;
mMigrated.insert( pClip.get() );
mMoving.emplace_back( std::move( interval ) );
}
return true;
}
bool FinishMigration() override
{
auto rate = mpTrack->GetRate();
for (auto pClip : mMigrated) {
// Now that user has dropped the clip into a different track,
// make sure the sample rate matches the destination track.
pClip->Resample(rate);
pClip->MarkChanged();
}
return true;
}
void DoHorizontalOffset( double offset ) override
{
for ( auto &interval : MovingIntervals() ) {
auto data =
static_cast<WaveTrack::IntervalData*>( interval.Extra() );
data->GetClip()->Offset( offset );
}
}
// Ensure that t0 is still within the clip which it was in before the move.
// This corrects for any rounding errors.
double AdjustT0( double t0 ) const override
{
if (MovingIntervals().empty())
return t0;
else {
auto data = static_cast<WaveTrack::IntervalData*>(MovingIntervals()[0].Extra());
auto& clip = data->GetClip();
if (t0 < clip->GetStartTime())
t0 = clip->GetStartTime();
if (t0 > clip->GetEndTime())
t0 = clip->GetEndTime();
}
return t0;
}
private:
std::shared_ptr<WaveTrack> mpTrack;
// Clips that may require resampling
std::unordered_set<WaveClip *> mMigrated;
};
using MakeWaveTrackShifter = MakeTrackShifter::Override<WaveTrack>;
DEFINE_ATTACHED_VIRTUAL_OVERRIDE(MakeWaveTrackShifter) {
return [](WaveTrack &track, AudacityProject&) {
return std::make_unique<WaveTrackShifter>(track);
};
}
|
// Copyright (c) 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 "base/strings/escape.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversion_utils.h"
#include "base/third_party/icu/icu_utf.h"
namespace gurl_base {
namespace {
// Contains nonzero when the corresponding character is unescapable for normal
// URLs. These characters are the ones that may change the parsing of a URL, so
// we don't want to unescape them sometimes. In many case we won't want to
// unescape spaces, but that is controlled by parameters to Unescape*.
//
// The basic rule is that we can't unescape anything that would changing parsing
// like # or ?. We also can't unescape &, =, or + since that could be part of a
// query and that could change the server's parsing of the query. Nor can we
// unescape \ since src/url/ will convert it to a /.
//
// Lastly, we can't unescape anything that doesn't have a canonical
// representation in a URL. This means that unescaping will change the URL, and
// you could get different behavior if you copy and paste the URL, or press
// enter in the URL bar. The list of characters that fall into this category
// are the ones labeled PASS (allow either escaped or unescaped) in the big
// lookup table at the top of url/url_canon_path.cc. Also, characters
// that have CHAR_QUERY set in url/url_canon_internal.cc but are not
// allowed in query strings according to http://www.ietf.org/rfc/rfc3261.txt are
// not unescaped, to avoid turning a valid url according to spec into an
// invalid one.
// clang-format off
const char kUrlUnescape[128] = {
// Null, control chars...
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
// ' ' ! " # $ % & ' ( ) * + , - . /
0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0,
// 0 1 2 3 4 5 6 7 8 9 : ; < = > ?
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,
// @ A B C D E F G H I J K L M N O
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
// P Q R S T U V W X Y Z [ \ ] ^ _
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,
// ` a b c d e f g h i j k l m n o
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
// p q r s t u v w x y z { | } ~ <NBSP>
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0,
};
// clang-format on
// Attempts to unescape the sequence at |index| within |escaped_text|. If
// successful, sets |value| to the unescaped value. Returns whether
// unescaping succeeded.
bool UnescapeUnsignedByteAtIndex(StringPiece escaped_text,
size_t index,
unsigned char* value) {
if ((index + 2) >= escaped_text.size())
return false;
if (escaped_text[index] != '%')
return false;
char most_sig_digit(escaped_text[index + 1]);
char least_sig_digit(escaped_text[index + 2]);
if (IsHexDigit(most_sig_digit) && IsHexDigit(least_sig_digit)) {
*value =
HexDigitToInt(most_sig_digit) * 16 + HexDigitToInt(least_sig_digit);
return true;
}
return false;
}
// Attempts to unescape and decode a UTF-8-encoded percent-escaped character at
// the specified index. On success, returns true, sets |code_point_out| to be
// the character's code point and |unescaped_out| to be the unescaped UTF-8
// string. |unescaped_out| will always be 1/3rd the length of the substring of
// |escaped_text| that corresponds to the unescaped character.
bool UnescapeUTF8CharacterAtIndex(StringPiece escaped_text,
size_t index,
uint32_t* code_point_out,
std::string* unescaped_out) {
GURL_DCHECK(unescaped_out->empty());
unsigned char bytes[CBU8_MAX_LENGTH];
if (!UnescapeUnsignedByteAtIndex(escaped_text, index, &bytes[0]))
return false;
size_t num_bytes = 1;
// If this is a lead byte, need to collect trail bytes as well.
if (CBU8_IS_LEAD(bytes[0])) {
// Look for the last trail byte of the UTF-8 character. Give up once
// reach max character length number of bytes, or hit an unescaped
// character. No need to check length of escaped_text, as
// UnescapeUnsignedByteAtIndex checks lengths.
while (num_bytes < size(bytes) &&
UnescapeUnsignedByteAtIndex(escaped_text, index + num_bytes * 3,
&bytes[num_bytes]) &&
CBU8_IS_TRAIL(bytes[num_bytes])) {
++num_bytes;
}
}
int32_t char_index = 0;
// Check if the unicode "character" that was just unescaped is valid.
if (!ReadUnicodeCharacter(reinterpret_cast<char*>(bytes), num_bytes,
&char_index, code_point_out)) {
return false;
}
// It's possible that a prefix of |bytes| forms a valid UTF-8 character,
// and the rest are not valid UTF-8, so need to update |num_bytes| based
// on the result of ReadUnicodeCharacter().
num_bytes = char_index + 1;
*unescaped_out = std::string(reinterpret_cast<char*>(bytes), num_bytes);
return true;
}
// This method takes a Unicode code point and returns true if it should be
// unescaped, based on |rules|.
bool ShouldUnescapeCodePoint(UnescapeRule::Type rules, uint32_t code_point) {
// If this is an ASCII character, use the lookup table.
if (code_point < 0x80) {
return kUrlUnescape[code_point] ||
// Allow some additional unescaping when flags are set.
(code_point == ' ' && (rules & UnescapeRule::SPACES)) ||
// Allow any of the prohibited but non-control characters when doing
// "special" chars.
((code_point == '/' || code_point == '\\') &&
(rules & UnescapeRule::PATH_SEPARATORS)) ||
(code_point > ' ' && code_point != '/' && code_point != '\\' &&
(rules & UnescapeRule::URL_SPECIAL_CHARS_EXCEPT_PATH_SEPARATORS));
}
// Compare the code point against a list of characters that can be used
// to spoof other URLs.
//
// Can't use icu to make this cleaner, because Cronet cannot depend on
// icu, and currently uses this file.
// TODO(https://crbug.com/829873): Try to make this use icu, both to
// protect against regressions as the Unicode standard is updated and to
// reduce the number of long lists of characters.
return !(
// Per http://tools.ietf.org/html/rfc3987#section-4.1, certain BiDi
// control characters are not allowed to appear unescaped in URLs.
code_point == 0x200E || // LEFT-TO-RIGHT MARK (%E2%80%8E)
code_point == 0x200F || // RIGHT-TO-LEFT MARK (%E2%80%8F)
code_point == 0x202A || // LEFT-TO-RIGHT EMBEDDING (%E2%80%AA)
code_point == 0x202B || // RIGHT-TO-LEFT EMBEDDING (%E2%80%AB)
code_point == 0x202C || // POP DIRECTIONAL FORMATTING (%E2%80%AC)
code_point == 0x202D || // LEFT-TO-RIGHT OVERRIDE (%E2%80%AD)
code_point == 0x202E || // RIGHT-TO-LEFT OVERRIDE (%E2%80%AE)
// The Unicode Technical Report (TR9) as referenced by RFC 3987 above has
// since added some new BiDi control characters that are not safe to
// unescape. http://www.unicode.org/reports/tr9
code_point == 0x061C || // ARABIC LETTER MARK (%D8%9C)
code_point == 0x2066 || // LEFT-TO-RIGHT ISOLATE (%E2%81%A6)
code_point == 0x2067 || // RIGHT-TO-LEFT ISOLATE (%E2%81%A7)
code_point == 0x2068 || // FIRST STRONG ISOLATE (%E2%81%A8)
code_point == 0x2069 || // POP DIRECTIONAL ISOLATE (%E2%81%A9)
// The following spoofable characters are also banned in unescaped URLs,
// because they could be used to imitate parts of a web browser's UI.
code_point == 0x1F50F || // LOCK WITH INK PEN (%F0%9F%94%8F)
code_point == 0x1F510 || // CLOSED LOCK WITH KEY (%F0%9F%94%90)
code_point == 0x1F512 || // LOCK (%F0%9F%94%92)
code_point == 0x1F513 || // OPEN LOCK (%F0%9F%94%93)
// Spaces are also banned, as they can be used to scroll text out of view.
code_point == 0x0085 || // NEXT LINE (%C2%85)
code_point == 0x00A0 || // NO-BREAK SPACE (%C2%A0)
code_point == 0x1680 || // OGHAM SPACE MARK (%E1%9A%80)
code_point == 0x2000 || // EN QUAD (%E2%80%80)
code_point == 0x2001 || // EM QUAD (%E2%80%81)
code_point == 0x2002 || // EN SPACE (%E2%80%82)
code_point == 0x2003 || // EM SPACE (%E2%80%83)
code_point == 0x2004 || // THREE-PER-EM SPACE (%E2%80%84)
code_point == 0x2005 || // FOUR-PER-EM SPACE (%E2%80%85)
code_point == 0x2006 || // SIX-PER-EM SPACE (%E2%80%86)
code_point == 0x2007 || // FIGURE SPACE (%E2%80%87)
code_point == 0x2008 || // PUNCTUATION SPACE (%E2%80%88)
code_point == 0x2009 || // THIN SPACE (%E2%80%89)
code_point == 0x200A || // HAIR SPACE (%E2%80%8A)
code_point == 0x2028 || // LINE SEPARATOR (%E2%80%A8)
code_point == 0x2029 || // PARAGRAPH SEPARATOR (%E2%80%A9)
code_point == 0x202F || // NARROW NO-BREAK SPACE (%E2%80%AF)
code_point == 0x205F || // MEDIUM MATHEMATICAL SPACE (%E2%81%9F)
code_point == 0x3000 || // IDEOGRAPHIC SPACE (%E3%80%80)
// U+2800 is rendered as a space, but is not considered whitespace (see
// crbug.com/1068531).
code_point == 0x2800 || // BRAILLE PATTERN BLANK (%E2%A0%80)
// Default Ignorable ([:Default_Ignorable_Code_Point=Yes:]) and Format
// characters ([:Cf:]) are also banned (see crbug.com/824715).
code_point == 0x00AD || // SOFT HYPHEN (%C2%AD)
code_point == 0x034F || // COMBINING GRAPHEME JOINER (%CD%8F)
// Arabic number formatting
(code_point >= 0x0600 && code_point <= 0x0605) ||
// U+061C is already banned as a BiDi control character.
code_point == 0x06DD || // ARABIC END OF AYAH (%DB%9D)
code_point == 0x070F || // SYRIAC ABBREVIATION MARK (%DC%8F)
code_point == 0x08E2 || // ARABIC DISPUTED END OF AYAH (%E0%A3%A2)
code_point == 0x115F || // HANGUL CHOSEONG FILLER (%E1%85%9F)
code_point == 0x1160 || // HANGUL JUNGSEONG FILLER (%E1%85%A0)
code_point == 0x17B4 || // KHMER VOWEL INHERENT AQ (%E1%9E%B4)
code_point == 0x17B5 || // KHMER VOWEL INHERENT AA (%E1%9E%B5)
code_point == 0x180B || // MONGOLIAN FREE VARIATION SELECTOR ONE
// (%E1%A0%8B)
code_point == 0x180C || // MONGOLIAN FREE VARIATION SELECTOR TWO
// (%E1%A0%8C)
code_point == 0x180D || // MONGOLIAN FREE VARIATION SELECTOR THREE
// (%E1%A0%8D)
code_point == 0x180E || // MONGOLIAN VOWEL SEPARATOR (%E1%A0%8E)
code_point == 0x200B || // ZERO WIDTH SPACE (%E2%80%8B)
code_point == 0x200C || // ZERO WIDTH SPACE NON-JOINER (%E2%80%8C)
code_point == 0x200D || // ZERO WIDTH JOINER (%E2%80%8D)
// U+200E, U+200F, U+202A--202E, and U+2066--2069 are already banned as
// BiDi control characters.
code_point == 0x2060 || // WORD JOINER (%E2%81%A0)
code_point == 0x2061 || // FUNCTION APPLICATION (%E2%81%A1)
code_point == 0x2062 || // INVISIBLE TIMES (%E2%81%A2)
code_point == 0x2063 || // INVISIBLE SEPARATOR (%E2%81%A3)
code_point == 0x2064 || // INVISIBLE PLUS (%E2%81%A4)
code_point == 0x2065 || // null (%E2%81%A5)
// 0x2066--0x2069 are already banned as a BiDi control characters.
// General Punctuation - Deprecated (U+206A--206F)
(code_point >= 0x206A && code_point <= 0x206F) ||
code_point == 0x3164 || // HANGUL FILLER (%E3%85%A4)
(code_point >= 0xFFF0 && code_point <= 0xFFF8) || // null
// Variation selectors (%EF%B8%80 -- %EF%B8%8F)
(code_point >= 0xFE00 && code_point <= 0xFE0F) ||
code_point == 0xFEFF || // ZERO WIDTH NO-BREAK SPACE (%EF%BB%BF)
code_point == 0xFFA0 || // HALFWIDTH HANGUL FILLER (%EF%BE%A0)
code_point == 0xFFF9 || // INTERLINEAR ANNOTATION ANCHOR (%EF%BF%B9)
code_point == 0xFFFA || // INTERLINEAR ANNOTATION SEPARATOR (%EF%BF%BA)
code_point == 0xFFFB || // INTERLINEAR ANNOTATION TERMINATOR (%EF%BF%BB)
code_point == 0x110BD || // KAITHI NUMBER SIGN (%F0%91%82%BD)
code_point == 0x110CD || // KAITHI NUMBER SIGN ABOVE (%F0%91%83%8D)
// Egyptian hieroglyph formatting (%F0%93%90%B0 -- %F0%93%90%B8)
(code_point >= 0x13430 && code_point <= 0x13438) ||
// Shorthand format controls (%F0%9B%B2%A0 -- %F0%9B%B2%A3)
(code_point >= 0x1BCA0 && code_point <= 0x1BCA3) ||
// Beams and slurs (%F0%9D%85%B3 -- %F0%9D%85%BA)
(code_point >= 0x1D173 && code_point <= 0x1D17A) ||
// Tags, Variation Selectors, nulls
(code_point >= 0xE0000 && code_point <= 0xE0FFF));
}
// Unescapes |escaped_text| according to |rules|, returning the resulting
// string. Fills in an |adjustments| parameter, if non-nullptr, so it reflects
// the alterations done to the string that are not one-character-to-one-
// character. The resulting |adjustments| will always be sorted by increasing
// offset.
std::string UnescapeURLWithAdjustmentsImpl(
StringPiece escaped_text,
UnescapeRule::Type rules,
OffsetAdjuster::Adjustments* adjustments) {
if (adjustments)
adjustments->clear();
// Do not unescape anything, return the |escaped_text| text.
if (rules == UnescapeRule::NONE)
return std::string(escaped_text);
// The output of the unescaping is always smaller than the input, so we can
// reserve the input size to make sure we have enough buffer and don't have
// to allocate in the loop below.
std::string result;
result.reserve(escaped_text.length());
// Locations of adjusted text.
for (size_t i = 0, max = escaped_text.size(); i < max;) {
// Try to unescape the character.
uint32_t code_point;
std::string unescaped;
if (!UnescapeUTF8CharacterAtIndex(escaped_text, i, &code_point,
&unescaped)) {
// Check if the next character can be unescaped, but not as a valid UTF-8
// character. In that case, just unescaped and write the non-sense
// character.
//
// TODO(https://crbug.com/829868): Do not unescape illegal UTF-8
// sequences.
unsigned char non_utf8_byte;
if (UnescapeUnsignedByteAtIndex(escaped_text, i, &non_utf8_byte)) {
result.push_back(non_utf8_byte);
if (adjustments)
adjustments->push_back(OffsetAdjuster::Adjustment(i, 3, 1));
i += 3;
continue;
}
// Character is not escaped, so append as is, unless it's a '+' and
// REPLACE_PLUS_WITH_SPACE is being applied.
if (escaped_text[i] == '+' &&
(rules & UnescapeRule::REPLACE_PLUS_WITH_SPACE)) {
result.push_back(' ');
} else {
result.push_back(escaped_text[i]);
}
++i;
continue;
}
GURL_DCHECK(!unescaped.empty());
if (!ShouldUnescapeCodePoint(rules, code_point)) {
// If it's a valid UTF-8 character, but not safe to unescape, copy all
// bytes directly.
result.append(escaped_text.begin() + i,
escaped_text.begin() + i + 3 * unescaped.length());
i += unescaped.length() * 3;
continue;
}
// If the code point is allowed, and append the entire unescaped character.
result.append(unescaped);
if (adjustments) {
for (size_t j = 0; j < unescaped.length(); ++j) {
adjustments->push_back(OffsetAdjuster::Adjustment(i + j * 3, 3, 1));
}
}
i += 3 * unescaped.length();
}
return result;
}
} // namespace
std::string UnescapeURLComponent(StringPiece escaped_text,
UnescapeRule::Type rules) {
return UnescapeURLWithAdjustmentsImpl(escaped_text, rules, nullptr);
}
std::u16string UnescapeAndDecodeUTF8URLComponentWithAdjustments(
StringPiece text,
UnescapeRule::Type rules,
OffsetAdjuster::Adjustments* adjustments) {
std::u16string result;
OffsetAdjuster::Adjustments unescape_adjustments;
std::string unescaped_url(
UnescapeURLWithAdjustmentsImpl(text, rules, &unescape_adjustments));
if (UTF8ToUTF16WithAdjustments(unescaped_url.data(), unescaped_url.length(),
&result, adjustments)) {
// Character set looks like it's valid.
if (adjustments) {
OffsetAdjuster::MergeSequentialAdjustments(unescape_adjustments,
adjustments);
}
return result;
}
// Character set is not valid. Return the escaped version.
return UTF8ToUTF16WithAdjustments(text, adjustments);
}
std::string UnescapeBinaryURLComponent(StringPiece escaped_text,
UnescapeRule::Type rules) {
// Only NORMAL and REPLACE_PLUS_WITH_SPACE are supported.
GURL_DCHECK(rules != UnescapeRule::NONE);
GURL_DCHECK(!(rules &
~(UnescapeRule::NORMAL | UnescapeRule::REPLACE_PLUS_WITH_SPACE)));
std::string unescaped_text;
// The output of the unescaping is always smaller than the input, so we can
// reserve the input size to make sure we have enough buffer and don't have
// to allocate in the loop below.
// Increase capacity before size, as just resizing can grow capacity
// needlessly beyond our requested size.
unescaped_text.reserve(escaped_text.size());
unescaped_text.resize(escaped_text.size());
size_t output_index = 0;
for (size_t i = 0, max = escaped_text.size(); i < max;) {
unsigned char byte;
// UnescapeUnsignedByteAtIndex does bounds checking, so this is always safe
// to call.
if (UnescapeUnsignedByteAtIndex(escaped_text, i, &byte)) {
unescaped_text[output_index++] = byte;
i += 3;
continue;
}
if ((rules & UnescapeRule::REPLACE_PLUS_WITH_SPACE) &&
escaped_text[i] == '+') {
unescaped_text[output_index++] = ' ';
++i;
continue;
}
unescaped_text[output_index++] = escaped_text[i++];
}
GURL_DCHECK_LE(output_index, unescaped_text.size());
unescaped_text.resize(output_index);
return unescaped_text;
}
bool UnescapeBinaryURLComponentSafe(StringPiece escaped_text,
bool fail_on_path_separators,
std::string* unescaped_text) {
unescaped_text->clear();
std::set<unsigned char> illegal_encoded_bytes;
for (char c = '\x00'; c < '\x20'; ++c) {
illegal_encoded_bytes.insert(c);
}
if (fail_on_path_separators) {
illegal_encoded_bytes.insert('/');
illegal_encoded_bytes.insert('\\');
}
if (ContainsEncodedBytes(escaped_text, illegal_encoded_bytes))
return false;
*unescaped_text = UnescapeBinaryURLComponent(escaped_text);
return true;
}
bool ContainsEncodedBytes(StringPiece escaped_text,
const std::set<unsigned char>& bytes) {
for (size_t i = 0, max = escaped_text.size(); i < max;) {
unsigned char byte;
// UnescapeUnsignedByteAtIndex does bounds checking, so this is always safe
// to call.
if (UnescapeUnsignedByteAtIndex(escaped_text, i, &byte)) {
if (bytes.find(byte) != bytes.end())
return true;
i += 3;
continue;
}
++i;
}
return false;
}
} // namespace base
|
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/dayu/v20180709/model/L4RuleEntry.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Dayu::V20180709::Model;
using namespace rapidjson;
using namespace std;
L4RuleEntry::L4RuleEntry() :
m_protocolHasBeenSet(false),
m_virtualPortHasBeenSet(false),
m_sourcePortHasBeenSet(false),
m_sourceTypeHasBeenSet(false),
m_keepTimeHasBeenSet(false),
m_sourceListHasBeenSet(false),
m_lbTypeHasBeenSet(false),
m_keepEnableHasBeenSet(false),
m_ruleIdHasBeenSet(false),
m_ruleNameHasBeenSet(false),
m_removeSwitchHasBeenSet(false)
{
}
CoreInternalOutcome L4RuleEntry::Deserialize(const Value &value)
{
string requestId = "";
if (value.HasMember("Protocol") && !value["Protocol"].IsNull())
{
if (!value["Protocol"].IsString())
{
return CoreInternalOutcome(Error("response `L4RuleEntry.Protocol` IsString=false incorrectly").SetRequestId(requestId));
}
m_protocol = string(value["Protocol"].GetString());
m_protocolHasBeenSet = true;
}
if (value.HasMember("VirtualPort") && !value["VirtualPort"].IsNull())
{
if (!value["VirtualPort"].IsUint64())
{
return CoreInternalOutcome(Error("response `L4RuleEntry.VirtualPort` IsUint64=false incorrectly").SetRequestId(requestId));
}
m_virtualPort = value["VirtualPort"].GetUint64();
m_virtualPortHasBeenSet = true;
}
if (value.HasMember("SourcePort") && !value["SourcePort"].IsNull())
{
if (!value["SourcePort"].IsUint64())
{
return CoreInternalOutcome(Error("response `L4RuleEntry.SourcePort` IsUint64=false incorrectly").SetRequestId(requestId));
}
m_sourcePort = value["SourcePort"].GetUint64();
m_sourcePortHasBeenSet = true;
}
if (value.HasMember("SourceType") && !value["SourceType"].IsNull())
{
if (!value["SourceType"].IsUint64())
{
return CoreInternalOutcome(Error("response `L4RuleEntry.SourceType` IsUint64=false incorrectly").SetRequestId(requestId));
}
m_sourceType = value["SourceType"].GetUint64();
m_sourceTypeHasBeenSet = true;
}
if (value.HasMember("KeepTime") && !value["KeepTime"].IsNull())
{
if (!value["KeepTime"].IsUint64())
{
return CoreInternalOutcome(Error("response `L4RuleEntry.KeepTime` IsUint64=false incorrectly").SetRequestId(requestId));
}
m_keepTime = value["KeepTime"].GetUint64();
m_keepTimeHasBeenSet = true;
}
if (value.HasMember("SourceList") && !value["SourceList"].IsNull())
{
if (!value["SourceList"].IsArray())
return CoreInternalOutcome(Error("response `L4RuleEntry.SourceList` is not array type"));
const Value &tmpValue = value["SourceList"];
for (Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
L4RuleSource item;
CoreInternalOutcome outcome = item.Deserialize(*itr);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_sourceList.push_back(item);
}
m_sourceListHasBeenSet = true;
}
if (value.HasMember("LbType") && !value["LbType"].IsNull())
{
if (!value["LbType"].IsUint64())
{
return CoreInternalOutcome(Error("response `L4RuleEntry.LbType` IsUint64=false incorrectly").SetRequestId(requestId));
}
m_lbType = value["LbType"].GetUint64();
m_lbTypeHasBeenSet = true;
}
if (value.HasMember("KeepEnable") && !value["KeepEnable"].IsNull())
{
if (!value["KeepEnable"].IsUint64())
{
return CoreInternalOutcome(Error("response `L4RuleEntry.KeepEnable` IsUint64=false incorrectly").SetRequestId(requestId));
}
m_keepEnable = value["KeepEnable"].GetUint64();
m_keepEnableHasBeenSet = true;
}
if (value.HasMember("RuleId") && !value["RuleId"].IsNull())
{
if (!value["RuleId"].IsString())
{
return CoreInternalOutcome(Error("response `L4RuleEntry.RuleId` IsString=false incorrectly").SetRequestId(requestId));
}
m_ruleId = string(value["RuleId"].GetString());
m_ruleIdHasBeenSet = true;
}
if (value.HasMember("RuleName") && !value["RuleName"].IsNull())
{
if (!value["RuleName"].IsString())
{
return CoreInternalOutcome(Error("response `L4RuleEntry.RuleName` IsString=false incorrectly").SetRequestId(requestId));
}
m_ruleName = string(value["RuleName"].GetString());
m_ruleNameHasBeenSet = true;
}
if (value.HasMember("RemoveSwitch") && !value["RemoveSwitch"].IsNull())
{
if (!value["RemoveSwitch"].IsUint64())
{
return CoreInternalOutcome(Error("response `L4RuleEntry.RemoveSwitch` IsUint64=false incorrectly").SetRequestId(requestId));
}
m_removeSwitch = value["RemoveSwitch"].GetUint64();
m_removeSwitchHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void L4RuleEntry::ToJsonObject(Value &value, Document::AllocatorType& allocator) const
{
if (m_protocolHasBeenSet)
{
Value iKey(kStringType);
string key = "Protocol";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_protocol.c_str(), allocator).Move(), allocator);
}
if (m_virtualPortHasBeenSet)
{
Value iKey(kStringType);
string key = "VirtualPort";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_virtualPort, allocator);
}
if (m_sourcePortHasBeenSet)
{
Value iKey(kStringType);
string key = "SourcePort";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_sourcePort, allocator);
}
if (m_sourceTypeHasBeenSet)
{
Value iKey(kStringType);
string key = "SourceType";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_sourceType, allocator);
}
if (m_keepTimeHasBeenSet)
{
Value iKey(kStringType);
string key = "KeepTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_keepTime, allocator);
}
if (m_sourceListHasBeenSet)
{
Value iKey(kStringType);
string key = "SourceList";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(kArrayType).Move(), allocator);
int i=0;
for (auto itr = m_sourceList.begin(); itr != m_sourceList.end(); ++itr, ++i)
{
value[key.c_str()].PushBack(Value(kObjectType).Move(), allocator);
(*itr).ToJsonObject(value[key.c_str()][i], allocator);
}
}
if (m_lbTypeHasBeenSet)
{
Value iKey(kStringType);
string key = "LbType";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_lbType, allocator);
}
if (m_keepEnableHasBeenSet)
{
Value iKey(kStringType);
string key = "KeepEnable";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_keepEnable, allocator);
}
if (m_ruleIdHasBeenSet)
{
Value iKey(kStringType);
string key = "RuleId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_ruleId.c_str(), allocator).Move(), allocator);
}
if (m_ruleNameHasBeenSet)
{
Value iKey(kStringType);
string key = "RuleName";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, Value(m_ruleName.c_str(), allocator).Move(), allocator);
}
if (m_removeSwitchHasBeenSet)
{
Value iKey(kStringType);
string key = "RemoveSwitch";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_removeSwitch, allocator);
}
}
string L4RuleEntry::GetProtocol() const
{
return m_protocol;
}
void L4RuleEntry::SetProtocol(const string& _protocol)
{
m_protocol = _protocol;
m_protocolHasBeenSet = true;
}
bool L4RuleEntry::ProtocolHasBeenSet() const
{
return m_protocolHasBeenSet;
}
uint64_t L4RuleEntry::GetVirtualPort() const
{
return m_virtualPort;
}
void L4RuleEntry::SetVirtualPort(const uint64_t& _virtualPort)
{
m_virtualPort = _virtualPort;
m_virtualPortHasBeenSet = true;
}
bool L4RuleEntry::VirtualPortHasBeenSet() const
{
return m_virtualPortHasBeenSet;
}
uint64_t L4RuleEntry::GetSourcePort() const
{
return m_sourcePort;
}
void L4RuleEntry::SetSourcePort(const uint64_t& _sourcePort)
{
m_sourcePort = _sourcePort;
m_sourcePortHasBeenSet = true;
}
bool L4RuleEntry::SourcePortHasBeenSet() const
{
return m_sourcePortHasBeenSet;
}
uint64_t L4RuleEntry::GetSourceType() const
{
return m_sourceType;
}
void L4RuleEntry::SetSourceType(const uint64_t& _sourceType)
{
m_sourceType = _sourceType;
m_sourceTypeHasBeenSet = true;
}
bool L4RuleEntry::SourceTypeHasBeenSet() const
{
return m_sourceTypeHasBeenSet;
}
uint64_t L4RuleEntry::GetKeepTime() const
{
return m_keepTime;
}
void L4RuleEntry::SetKeepTime(const uint64_t& _keepTime)
{
m_keepTime = _keepTime;
m_keepTimeHasBeenSet = true;
}
bool L4RuleEntry::KeepTimeHasBeenSet() const
{
return m_keepTimeHasBeenSet;
}
vector<L4RuleSource> L4RuleEntry::GetSourceList() const
{
return m_sourceList;
}
void L4RuleEntry::SetSourceList(const vector<L4RuleSource>& _sourceList)
{
m_sourceList = _sourceList;
m_sourceListHasBeenSet = true;
}
bool L4RuleEntry::SourceListHasBeenSet() const
{
return m_sourceListHasBeenSet;
}
uint64_t L4RuleEntry::GetLbType() const
{
return m_lbType;
}
void L4RuleEntry::SetLbType(const uint64_t& _lbType)
{
m_lbType = _lbType;
m_lbTypeHasBeenSet = true;
}
bool L4RuleEntry::LbTypeHasBeenSet() const
{
return m_lbTypeHasBeenSet;
}
uint64_t L4RuleEntry::GetKeepEnable() const
{
return m_keepEnable;
}
void L4RuleEntry::SetKeepEnable(const uint64_t& _keepEnable)
{
m_keepEnable = _keepEnable;
m_keepEnableHasBeenSet = true;
}
bool L4RuleEntry::KeepEnableHasBeenSet() const
{
return m_keepEnableHasBeenSet;
}
string L4RuleEntry::GetRuleId() const
{
return m_ruleId;
}
void L4RuleEntry::SetRuleId(const string& _ruleId)
{
m_ruleId = _ruleId;
m_ruleIdHasBeenSet = true;
}
bool L4RuleEntry::RuleIdHasBeenSet() const
{
return m_ruleIdHasBeenSet;
}
string L4RuleEntry::GetRuleName() const
{
return m_ruleName;
}
void L4RuleEntry::SetRuleName(const string& _ruleName)
{
m_ruleName = _ruleName;
m_ruleNameHasBeenSet = true;
}
bool L4RuleEntry::RuleNameHasBeenSet() const
{
return m_ruleNameHasBeenSet;
}
uint64_t L4RuleEntry::GetRemoveSwitch() const
{
return m_removeSwitch;
}
void L4RuleEntry::SetRemoveSwitch(const uint64_t& _removeSwitch)
{
m_removeSwitch = _removeSwitch;
m_removeSwitchHasBeenSet = true;
}
bool L4RuleEntry::RemoveSwitchHasBeenSet() const
{
return m_removeSwitchHasBeenSet;
}
|
// Copyright (c) 2009-2013 The Bitcoin developers
//Copyright (c) 2017-2020 The PIVX developers
//Copyright (c) 2020 The Bitcrore Coin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "crypter.h"
#include "crypto/aes.h"
#include "crypto/sha512.h"
#include "script/script.h"
#include "script/standard.h"
#include "util.h"
#include "init.h"
#include "uint256.h"
#include "wallet/wallet.h"
int CCrypter::BytesToKeySHA512AES(const std::vector<unsigned char>& chSalt, const SecureString& strKeyData, int count, unsigned char *key,unsigned char *iv) const
{
// This mimics the behavior of openssl's EVP_BytesToKey with an aes256cbc
// cipher and sha512 message digest. Because sha512's output size (64b) is
// greater than the aes256 block size (16b) + aes256 key size (32b),
// there's no need to process more than once (D_0).
if(!count || !key || !iv)
return 0;
unsigned char buf[CSHA512::OUTPUT_SIZE];
CSHA512 di;
di.Write((const unsigned char*)strKeyData.c_str(), strKeyData.size());
if(chSalt.size())
di.Write(&chSalt[0], chSalt.size());
di.Finalize(buf);
for(int i = 0; i != count - 1; i++)
di.Reset().Write(buf, sizeof(buf)).Finalize(buf);
memcpy(key, buf, WALLET_CRYPTO_KEY_SIZE);
memcpy(iv, buf + WALLET_CRYPTO_KEY_SIZE, WALLET_CRYPTO_IV_SIZE);
memory_cleanse(buf, sizeof(buf));
return WALLET_CRYPTO_KEY_SIZE;
}
bool CCrypter::SetKeyFromPassphrase(const SecureString& strKeyData, const std::vector<unsigned char>& chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod)
{
if (nRounds < 1 || chSalt.size() != WALLET_CRYPTO_SALT_SIZE)
return false;
int i = 0;
if (nDerivationMethod == 0)
i = BytesToKeySHA512AES(chSalt, strKeyData, nRounds, vchKey.data(), vchIV.data());
if (i != (int)WALLET_CRYPTO_KEY_SIZE) {
memory_cleanse(vchKey.data(), vchKey.size());
memory_cleanse(vchIV.data(), vchIV.size());
return false;
}
fKeySet = true;
return true;
}
bool CCrypter::SetKey(const CKeyingMaterial& chNewKey, const std::vector<unsigned char>& chNewIV)
{
if (chNewKey.size() != WALLET_CRYPTO_KEY_SIZE || chNewIV.size() != WALLET_CRYPTO_IV_SIZE)
return false;
memcpy(vchKey.data(), chNewKey.data(), chNewKey.size());
memcpy(vchIV.data(), chNewIV.data(), chNewIV.size());
fKeySet = true;
return true;
}
bool CCrypter::Encrypt(const CKeyingMaterial& vchPlaintext, std::vector<unsigned char>& vchCiphertext) const
{
if (!fKeySet)
return false;
// max ciphertext len for a n bytes of plaintext is
// n + AES_BLOCKSIZE bytes
vchCiphertext.resize(vchPlaintext.size() + AES_BLOCKSIZE);
AES256CBCEncrypt enc(vchKey.data(), vchIV.data(), true);
size_t nLen = enc.Encrypt(&vchPlaintext[0], vchPlaintext.size(), &vchCiphertext[0]);
if(nLen < vchPlaintext.size())
return false;
vchCiphertext.resize(nLen);
return true;
}
bool CCrypter::Decrypt(const std::vector<unsigned char>& vchCiphertext, CKeyingMaterial& vchPlaintext) const
{
if (!fKeySet)
return false;
// plaintext will always be equal to or lesser than length of ciphertext
int nLen = vchCiphertext.size();
vchPlaintext.resize(nLen);
AES256CBCDecrypt dec(vchKey.data(), vchIV.data(), true);
nLen = dec.Decrypt(&vchCiphertext[0], vchCiphertext.size(), &vchPlaintext[0]);
if(nLen == 0)
return false;
vchPlaintext.resize(nLen);
return true;
}
bool EncryptSecret(const CKeyingMaterial& vMasterKey, const CKeyingMaterial& vchPlaintext, const uint256& nIV, std::vector<unsigned char>& vchCiphertext)
{
CCrypter cKeyCrypter;
std::vector<unsigned char> chIV(WALLET_CRYPTO_IV_SIZE);
memcpy(&chIV[0], &nIV, WALLET_CRYPTO_IV_SIZE);
if (!cKeyCrypter.SetKey(vMasterKey, chIV))
return false;
return cKeyCrypter.Encrypt(*((const CKeyingMaterial*)&vchPlaintext), vchCiphertext);
}
bool DecryptSecret(const CKeyingMaterial& vMasterKey, const std::vector<unsigned char>& vchCiphertext, const uint256& nIV, CKeyingMaterial& vchPlaintext)
{
CCrypter cKeyCrypter;
std::vector<unsigned char> chIV(WALLET_CRYPTO_IV_SIZE);
memcpy(&chIV[0], &nIV, WALLET_CRYPTO_IV_SIZE);
if (!cKeyCrypter.SetKey(vMasterKey, chIV))
return false;
return cKeyCrypter.Decrypt(vchCiphertext, *((CKeyingMaterial*)&vchPlaintext));
}
bool CCryptoKeyStore::SetCrypted()
{
LOCK(cs_KeyStore);
if (fUseCrypto)
return true;
if (!mapKeys.empty())
return false;
fUseCrypto = true;
return true;
}
bool CCryptoKeyStore::AddKeyPubKey(const CKey& key, const CPubKey& pubkey)
{
{
LOCK(cs_KeyStore);
if (!IsCrypted())
return CBasicKeyStore::AddKeyPubKey(key, pubkey);
if (IsLocked())
return false;
std::vector<unsigned char> vchCryptedSecret;
CKeyingMaterial vchSecret(key.begin(), key.end());
if (!EncryptSecret(vMasterKey, vchSecret, pubkey.GetHash(), vchCryptedSecret))
return false;
if (!AddCryptedKey(pubkey, vchCryptedSecret))
return false;
}
return true;
}
bool CCryptoKeyStore::AddCryptedKey(const CPubKey& vchPubKey, const std::vector<unsigned char>& vchCryptedSecret)
{
{
LOCK(cs_KeyStore);
if (!SetCrypted())
return false;
mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
}
return true;
}
bool CCryptoKeyStore::GetKey(const CKeyID& address, CKey& keyOut) const
{
{
LOCK(cs_KeyStore);
if (!IsCrypted())
return CBasicKeyStore::GetKey(address, keyOut);
CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
if (mi != mapCryptedKeys.end()) {
const CPubKey& vchPubKey = (*mi).second.first;
const std::vector<unsigned char>& vchCryptedSecret = (*mi).second.second;
CKeyingMaterial vchSecret;
if (!DecryptSecret(vMasterKey, vchCryptedSecret, vchPubKey.GetHash(), vchSecret))
return false;
if (vchSecret.size() != 32)
return false;
keyOut.Set(vchSecret.begin(), vchSecret.end(), vchPubKey.IsCompressed());
return true;
}
}
return false;
}
bool CCryptoKeyStore::GetPubKey(const CKeyID& address, CPubKey& vchPubKeyOut) const
{
{
LOCK(cs_KeyStore);
if (!IsCrypted())
return CKeyStore::GetPubKey(address, vchPubKeyOut);
CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
if (mi != mapCryptedKeys.end()) {
vchPubKeyOut = (*mi).second.first;
return true;
}
}
return false;
}
bool CCryptoKeyStore::EncryptKeys(CKeyingMaterial& vMasterKeyIn)
{
{
LOCK(cs_KeyStore);
if (!mapCryptedKeys.empty() || IsCrypted())
return false;
fUseCrypto = true;
for (KeyMap::value_type& mKey : mapKeys) {
const CKey& key = mKey.second;
CPubKey vchPubKey = key.GetPubKey();
CKeyingMaterial vchSecret(key.begin(), key.end());
std::vector<unsigned char> vchCryptedSecret;
if (!EncryptSecret(vMasterKeyIn, vchSecret, vchPubKey.GetHash(), vchCryptedSecret))
return false;
if (!AddCryptedKey(vchPubKey, vchCryptedSecret))
return false;
}
mapKeys.clear();
}
return true;
}
|
#include <cstdint>
#include <memory>
#include <string>
#include "common/buffer/buffer_impl.h"
#include "common/common/empty_string.h"
#include "common/common/fmt.h"
#include "common/event/dispatcher_impl.h"
#include "common/network/address_impl.h"
#include "common/network/connection_impl.h"
#include "common/network/listen_socket_impl.h"
#include "common/network/utility.h"
#include "common/runtime/runtime_impl.h"
#include "common/stats/stats_impl.h"
#include "test/mocks/buffer/mocks.h"
#include "test/mocks/event/mocks.h"
#include "test/mocks/network/mocks.h"
#include "test/mocks/server/mocks.h"
#include "test/mocks/stats/mocks.h"
#include "test/test_common/environment.h"
#include "test/test_common/network_utility.h"
#include "test/test_common/printers.h"
#include "test/test_common/utility.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using testing::AnyNumber;
using testing::DoAll;
using testing::InSequence;
using testing::Invoke;
using testing::InvokeWithoutArgs;
using testing::Return;
using testing::SaveArg;
using testing::Sequence;
using testing::StrictMock;
using testing::Test;
using testing::_;
namespace Envoy {
namespace Network {
TEST(ConnectionImplUtility, updateBufferStats) {
StrictMock<Stats::MockCounter> counter;
StrictMock<Stats::MockGauge> gauge;
uint64_t previous_total = 0;
InSequence s;
EXPECT_CALL(counter, add(5));
EXPECT_CALL(gauge, add(5));
ConnectionImplUtility::updateBufferStats(5, 5, previous_total, counter, gauge);
EXPECT_EQ(5UL, previous_total);
EXPECT_CALL(counter, add(1));
EXPECT_CALL(gauge, sub(1));
ConnectionImplUtility::updateBufferStats(1, 4, previous_total, counter, gauge);
EXPECT_CALL(gauge, sub(4));
ConnectionImplUtility::updateBufferStats(0, 0, previous_total, counter, gauge);
EXPECT_CALL(counter, add(3));
EXPECT_CALL(gauge, add(3));
ConnectionImplUtility::updateBufferStats(3, 3, previous_total, counter, gauge);
}
class ConnectionImplDeathTest : public testing::TestWithParam<Address::IpVersion> {};
INSTANTIATE_TEST_CASE_P(IpVersions, ConnectionImplDeathTest,
testing::ValuesIn(TestEnvironment::getIpVersionsForTest()));
TEST_P(ConnectionImplDeathTest, BadFd) {
Event::DispatcherImpl dispatcher;
EXPECT_DEATH(ConnectionImpl(dispatcher,
std::make_unique<ConnectionSocketImpl>(-1, nullptr, nullptr),
Network::Test::createRawBufferSocket(), false),
".*assert failure: fd\\(\\) != -1.*");
}
class ConnectionImplTest : public testing::TestWithParam<Address::IpVersion> {
public:
void setUpBasicConnection() {
if (dispatcher_.get() == nullptr) {
dispatcher_.reset(new Event::DispatcherImpl);
}
listener_ = dispatcher_->createListener(socket_, listener_callbacks_, true, false);
client_connection_ = dispatcher_->createClientConnection(
socket_.localAddress(), source_address_, Network::Test::createRawBufferSocket(), nullptr);
client_connection_->addConnectionCallbacks(client_callbacks_);
EXPECT_EQ(nullptr, client_connection_->ssl());
const Network::ClientConnection& const_connection = *client_connection_;
EXPECT_EQ(nullptr, const_connection.ssl());
EXPECT_FALSE(client_connection_->localAddressRestored());
}
void connect() {
int expected_callbacks = 2;
client_connection_->connect();
read_filter_.reset(new NiceMock<MockReadFilter>());
EXPECT_CALL(listener_callbacks_, onAccept_(_, _))
.WillOnce(Invoke([&](Network::ConnectionSocketPtr& socket, bool) -> void {
Network::ConnectionPtr new_connection = dispatcher_->createServerConnection(
std::move(socket), Network::Test::createRawBufferSocket());
listener_callbacks_.onNewConnection(std::move(new_connection));
}));
EXPECT_CALL(listener_callbacks_, onNewConnection_(_))
.WillOnce(Invoke([&](Network::ConnectionPtr& conn) -> void {
server_connection_ = std::move(conn);
server_connection_->addConnectionCallbacks(server_callbacks_);
server_connection_->addReadFilter(read_filter_);
expected_callbacks--;
if (expected_callbacks == 0) {
dispatcher_->exit();
}
}));
EXPECT_CALL(client_callbacks_, onEvent(ConnectionEvent::Connected))
.WillOnce(Invoke([&](Network::ConnectionEvent) -> void {
expected_callbacks--;
if (expected_callbacks == 0) {
dispatcher_->exit();
}
}));
dispatcher_->run(Event::Dispatcher::RunType::Block);
}
void disconnect(bool wait_for_remote_close) {
EXPECT_CALL(client_callbacks_, onEvent(ConnectionEvent::LocalClose));
client_connection_->close(ConnectionCloseType::NoFlush);
if (wait_for_remote_close) {
EXPECT_CALL(server_callbacks_, onEvent(ConnectionEvent::RemoteClose))
.WillOnce(Invoke([&](Network::ConnectionEvent) -> void { dispatcher_->exit(); }));
dispatcher_->run(Event::Dispatcher::RunType::Block);
} else {
dispatcher_->run(Event::Dispatcher::RunType::NonBlock);
}
}
void useMockBuffer() {
// This needs to be called before the dispatcher is created.
ASSERT(dispatcher_.get() == nullptr);
MockBufferFactory* factory = new StrictMock<MockBufferFactory>;
dispatcher_.reset(new Event::DispatcherImpl(Buffer::WatermarkFactoryPtr{factory}));
// The first call to create a client session will get a MockBuffer.
// Other calls for server sessions will by default get a normal OwnedImpl.
EXPECT_CALL(*factory, create_(_, _))
.Times(AnyNumber())
.WillOnce(Invoke([&](std::function<void()> below_low,
std::function<void()> above_high) -> Buffer::Instance* {
client_write_buffer_ = new MockWatermarkBuffer(below_low, above_high);
return client_write_buffer_;
}))
.WillRepeatedly(Invoke([](std::function<void()> below_low,
std::function<void()> above_high) -> Buffer::Instance* {
return new Buffer::WatermarkBuffer(below_low, above_high);
}));
}
protected:
Event::DispatcherPtr dispatcher_;
Stats::IsolatedStoreImpl stats_store_;
Network::TcpListenSocket socket_{Network::Test::getAnyAddress(GetParam()), true};
Network::MockListenerCallbacks listener_callbacks_;
Network::MockConnectionHandler connection_handler_;
Network::ListenerPtr listener_;
Network::ClientConnectionPtr client_connection_;
StrictMock<MockConnectionCallbacks> client_callbacks_;
Network::ConnectionPtr server_connection_;
StrictMock<Network::MockConnectionCallbacks> server_callbacks_;
std::shared_ptr<MockReadFilter> read_filter_;
MockWatermarkBuffer* client_write_buffer_ = nullptr;
Address::InstanceConstSharedPtr source_address_;
};
INSTANTIATE_TEST_CASE_P(IpVersions, ConnectionImplTest,
testing::ValuesIn(TestEnvironment::getIpVersionsForTest()));
TEST_P(ConnectionImplTest, CloseDuringConnectCallback) {
setUpBasicConnection();
Buffer::OwnedImpl buffer("hello world");
client_connection_->write(buffer);
client_connection_->connect();
EXPECT_CALL(client_callbacks_, onEvent(ConnectionEvent::Connected))
.WillOnce(Invoke([&](Network::ConnectionEvent) -> void {
client_connection_->close(ConnectionCloseType::NoFlush);
}));
EXPECT_CALL(client_callbacks_, onEvent(ConnectionEvent::LocalClose));
read_filter_.reset(new NiceMock<MockReadFilter>());
EXPECT_CALL(listener_callbacks_, onAccept_(_, _))
.WillOnce(Invoke([&](Network::ConnectionSocketPtr& socket, bool) -> void {
Network::ConnectionPtr new_connection = dispatcher_->createServerConnection(
std::move(socket), Network::Test::createRawBufferSocket());
listener_callbacks_.onNewConnection(std::move(new_connection));
}));
EXPECT_CALL(listener_callbacks_, onNewConnection_(_))
.WillOnce(Invoke([&](Network::ConnectionPtr& conn) -> void {
server_connection_ = std::move(conn);
server_connection_->addConnectionCallbacks(server_callbacks_);
server_connection_->addReadFilter(read_filter_);
}));
EXPECT_CALL(server_callbacks_, onEvent(ConnectionEvent::RemoteClose))
.WillOnce(Invoke([&](Network::ConnectionEvent) -> void { dispatcher_->exit(); }));
dispatcher_->run(Event::Dispatcher::RunType::Block);
}
TEST_P(ConnectionImplTest, ImmediateConnectError) {
dispatcher_.reset(new Event::DispatcherImpl);
// Using a broadcast/multicast address as the connection destiantion address causes an
// immediate error return from connect().
Address::InstanceConstSharedPtr broadcast_address;
if (socket_.localAddress()->ip()->version() == Address::IpVersion::v4) {
broadcast_address.reset(new Address::Ipv4Instance("224.0.0.1", 0));
} else {
broadcast_address.reset(new Address::Ipv6Instance("ff02::1", 0));
}
client_connection_ = dispatcher_->createClientConnection(
broadcast_address, source_address_, Network::Test::createRawBufferSocket(), nullptr);
client_connection_->addConnectionCallbacks(client_callbacks_);
client_connection_->connect();
// Verify that also the immediate connect errors generate a remote close event.
EXPECT_CALL(client_callbacks_, onEvent(ConnectionEvent::RemoteClose))
.WillOnce(Invoke([&](Network::ConnectionEvent) -> void { dispatcher_->exit(); }));
dispatcher_->run(Event::Dispatcher::RunType::Block);
}
TEST_P(ConnectionImplTest, SocketOptions) {
Network::ClientConnectionPtr upstream_connection_;
setUpBasicConnection();
Buffer::OwnedImpl buffer("hello world");
client_connection_->write(buffer);
client_connection_->connect();
EXPECT_CALL(client_callbacks_, onEvent(ConnectionEvent::Connected))
.WillOnce(Invoke([&](Network::ConnectionEvent) -> void {
client_connection_->close(ConnectionCloseType::NoFlush);
}));
EXPECT_CALL(client_callbacks_, onEvent(ConnectionEvent::LocalClose));
read_filter_.reset(new NiceMock<MockReadFilter>());
auto options = std::make_shared<MockSocketOptions>();
EXPECT_CALL(*options, setOptions(_)).WillOnce(Return(true));
EXPECT_CALL(listener_callbacks_, onAccept_(_, _))
.WillOnce(Invoke([&](Network::ConnectionSocketPtr& socket, bool) -> void {
socket->setOptions(options);
Network::ConnectionPtr new_connection = dispatcher_->createServerConnection(
std::move(socket), Network::Test::createRawBufferSocket());
listener_callbacks_.onNewConnection(std::move(new_connection));
}));
EXPECT_CALL(listener_callbacks_, onNewConnection_(_))
.WillOnce(Invoke([&](Network::ConnectionPtr& conn) -> void {
server_connection_ = std::move(conn);
server_connection_->addConnectionCallbacks(server_callbacks_);
server_connection_->addReadFilter(read_filter_);
upstream_connection_ = dispatcher_->createClientConnection(
socket_.localAddress(), source_address_, Network::Test::createRawBufferSocket(),
server_connection_->socketOptions());
}));
EXPECT_CALL(server_callbacks_, onEvent(ConnectionEvent::RemoteClose))
.WillOnce(Invoke([&](Network::ConnectionEvent) -> void {
upstream_connection_->close(ConnectionCloseType::NoFlush);
dispatcher_->exit();
}));
dispatcher_->run(Event::Dispatcher::RunType::Block);
}
TEST_P(ConnectionImplTest, SocketOptionsFailureTest) {
Network::ClientConnectionPtr upstream_connection_;
StrictMock<Network::MockConnectionCallbacks> upstream_callbacks_;
setUpBasicConnection();
Buffer::OwnedImpl buffer("hello world");
client_connection_->write(buffer);
client_connection_->connect();
EXPECT_CALL(client_callbacks_, onEvent(ConnectionEvent::Connected))
.WillOnce(Invoke([&](Network::ConnectionEvent) -> void {
client_connection_->close(ConnectionCloseType::NoFlush);
}));
EXPECT_CALL(client_callbacks_, onEvent(ConnectionEvent::LocalClose));
read_filter_.reset(new NiceMock<MockReadFilter>());
auto options = std::make_shared<MockSocketOptions>();
EXPECT_CALL(*options, setOptions(_)).WillOnce(Return(false));
EXPECT_CALL(listener_callbacks_, onAccept_(_, _))
.WillOnce(Invoke([&](Network::ConnectionSocketPtr& socket, bool) -> void {
socket->setOptions(options);
Network::ConnectionPtr new_connection = dispatcher_->createServerConnection(
std::move(socket), Network::Test::createRawBufferSocket());
listener_callbacks_.onNewConnection(std::move(new_connection));
}));
EXPECT_CALL(listener_callbacks_, onNewConnection_(_))
.WillOnce(Invoke([&](Network::ConnectionPtr& conn) -> void {
server_connection_ = std::move(conn);
server_connection_->addConnectionCallbacks(server_callbacks_);
server_connection_->addReadFilter(read_filter_);
upstream_connection_ = dispatcher_->createClientConnection(
socket_.localAddress(), source_address_, Network::Test::createRawBufferSocket(),
server_connection_->socketOptions());
upstream_connection_->addConnectionCallbacks(upstream_callbacks_);
}));
EXPECT_CALL(upstream_callbacks_, onEvent(ConnectionEvent::LocalClose));
EXPECT_CALL(server_callbacks_, onEvent(ConnectionEvent::RemoteClose))
.WillOnce(Invoke([&](Network::ConnectionEvent) -> void {
upstream_connection_->close(ConnectionCloseType::NoFlush);
dispatcher_->exit();
}));
dispatcher_->run(Event::Dispatcher::RunType::Block);
}
struct MockConnectionStats {
Connection::ConnectionStats toBufferStats() {
return {rx_total_, rx_current_, tx_total_, tx_current_, &bind_errors_};
}
StrictMock<Stats::MockCounter> rx_total_;
StrictMock<Stats::MockGauge> rx_current_;
StrictMock<Stats::MockCounter> tx_total_;
StrictMock<Stats::MockGauge> tx_current_;
StrictMock<Stats::MockCounter> bind_errors_;
};
TEST_P(ConnectionImplTest, ConnectionStats) {
setUpBasicConnection();
MockConnectionStats client_connection_stats;
client_connection_->setConnectionStats(client_connection_stats.toBufferStats());
client_connection_->connect();
std::shared_ptr<MockWriteFilter> write_filter(new MockWriteFilter());
std::shared_ptr<MockFilter> filter(new MockFilter());
client_connection_->addWriteFilter(write_filter);
client_connection_->addFilter(filter);
Sequence s1;
EXPECT_CALL(*write_filter, onWrite(_))
.InSequence(s1)
.WillOnce(Return(FilterStatus::StopIteration));
EXPECT_CALL(*write_filter, onWrite(_)).InSequence(s1).WillOnce(Return(FilterStatus::Continue));
EXPECT_CALL(*filter, onWrite(_)).InSequence(s1).WillOnce(Return(FilterStatus::Continue));
EXPECT_CALL(client_callbacks_, onEvent(ConnectionEvent::Connected)).InSequence(s1);
EXPECT_CALL(client_connection_stats.tx_total_, add(4)).InSequence(s1);
read_filter_.reset(new NiceMock<MockReadFilter>());
MockConnectionStats server_connection_stats;
EXPECT_CALL(listener_callbacks_, onAccept_(_, _))
.WillOnce(Invoke([&](Network::ConnectionSocketPtr& socket, bool) -> void {
Network::ConnectionPtr new_connection = dispatcher_->createServerConnection(
std::move(socket), Network::Test::createRawBufferSocket());
listener_callbacks_.onNewConnection(std::move(new_connection));
}));
EXPECT_CALL(listener_callbacks_, onNewConnection_(_))
.WillOnce(Invoke([&](Network::ConnectionPtr& conn) -> void {
server_connection_ = std::move(conn);
server_connection_->addConnectionCallbacks(server_callbacks_);
server_connection_->setConnectionStats(server_connection_stats.toBufferStats());
server_connection_->addReadFilter(read_filter_);
EXPECT_EQ("", server_connection_->nextProtocol());
}));
Sequence s2;
EXPECT_CALL(server_connection_stats.rx_total_, add(4)).InSequence(s2);
EXPECT_CALL(server_connection_stats.rx_current_, add(4)).InSequence(s2);
EXPECT_CALL(server_connection_stats.rx_current_, sub(4)).InSequence(s2);
EXPECT_CALL(server_callbacks_, onEvent(ConnectionEvent::LocalClose)).InSequence(s2);
EXPECT_CALL(*read_filter_, onNewConnection());
EXPECT_CALL(*read_filter_, onData(_))
.WillOnce(Invoke([&](Buffer::Instance& data) -> FilterStatus {
data.drain(data.length());
server_connection_->close(ConnectionCloseType::FlushWrite);
return FilterStatus::StopIteration;
}));
EXPECT_CALL(client_callbacks_, onEvent(ConnectionEvent::RemoteClose))
.WillOnce(Invoke([&](Network::ConnectionEvent) -> void { dispatcher_->exit(); }));
Buffer::OwnedImpl data("1234");
client_connection_->write(data);
client_connection_->write(data);
dispatcher_->run(Event::Dispatcher::RunType::Block);
}
// Ensure the new counter logic in ReadDisable avoids tripping asserts in ReadDisable guarding
// against actual enabling twice in a row.
TEST_P(ConnectionImplTest, ReadDisable) {
setUpBasicConnection();
client_connection_->readDisable(true);
client_connection_->readDisable(false);
client_connection_->readDisable(true);
client_connection_->readDisable(true);
client_connection_->readDisable(false);
client_connection_->readDisable(false);
client_connection_->readDisable(true);
client_connection_->readDisable(true);
client_connection_->readDisable(false);
client_connection_->readDisable(true);
client_connection_->readDisable(false);
client_connection_->readDisable(false);
disconnect(false);
}
TEST_P(ConnectionImplTest, EarlyCloseOnReadDisabledConnection) {
#ifdef __APPLE__
// On our current OSX build, the client connection does not get the early
// close notification and instead gets the close after reading the FIN.
return;
#endif
setUpBasicConnection();
connect();
client_connection_->readDisable(true);
EXPECT_CALL(client_callbacks_, onEvent(ConnectionEvent::RemoteClose))
.WillOnce(InvokeWithoutArgs([&]() -> void { dispatcher_->exit(); }));
EXPECT_CALL(server_callbacks_, onEvent(ConnectionEvent::LocalClose));
server_connection_->close(ConnectionCloseType::FlushWrite);
dispatcher_->run(Event::Dispatcher::RunType::Block);
}
TEST_P(ConnectionImplTest, CloseOnReadDisableWithoutCloseDetection) {
setUpBasicConnection();
connect();
client_connection_->detectEarlyCloseWhenReadDisabled(false);
client_connection_->readDisable(true);
EXPECT_CALL(client_callbacks_, onEvent(ConnectionEvent::RemoteClose)).Times(0);
EXPECT_CALL(server_callbacks_, onEvent(ConnectionEvent::LocalClose))
.WillOnce(InvokeWithoutArgs([&]() -> void { dispatcher_->exit(); }));
server_connection_->close(ConnectionCloseType::FlushWrite);
dispatcher_->run(Event::Dispatcher::RunType::Block);
client_connection_->readDisable(false);
EXPECT_CALL(client_callbacks_, onEvent(ConnectionEvent::RemoteClose))
.WillOnce(InvokeWithoutArgs([&]() -> void { dispatcher_->exit(); }));
dispatcher_->run(Event::Dispatcher::RunType::Block);
}
// Test that as watermark levels are changed, the appropriate callbacks are triggered.
TEST_P(ConnectionImplTest, Watermarks) {
useMockBuffer();
setUpBasicConnection();
EXPECT_FALSE(client_connection_->aboveHighWatermark());
// Stick 5 bytes in the connection buffer.
std::unique_ptr<Buffer::OwnedImpl> buffer(new Buffer::OwnedImpl("hello"));
int buffer_len = buffer->length();
EXPECT_CALL(*client_write_buffer_, write(_))
.WillOnce(Invoke(client_write_buffer_, &MockWatermarkBuffer::failWrite));
EXPECT_CALL(*client_write_buffer_, move(_));
client_write_buffer_->move(*buffer);
{
// Go from watermarks being off to being above the high watermark.
EXPECT_CALL(client_callbacks_, onAboveWriteBufferHighWatermark());
EXPECT_CALL(client_callbacks_, onBelowWriteBufferLowWatermark()).Times(0);
client_connection_->setBufferLimits(buffer_len - 3);
EXPECT_TRUE(client_connection_->aboveHighWatermark());
}
{
// Go from above the high watermark to in between both.
EXPECT_CALL(client_callbacks_, onAboveWriteBufferHighWatermark()).Times(0);
EXPECT_CALL(client_callbacks_, onBelowWriteBufferLowWatermark()).Times(0);
client_connection_->setBufferLimits(buffer_len + 1);
EXPECT_TRUE(client_connection_->aboveHighWatermark());
}
{
// Go from above the high watermark to below the low watermark.
EXPECT_CALL(client_callbacks_, onAboveWriteBufferHighWatermark()).Times(0);
EXPECT_CALL(client_callbacks_, onBelowWriteBufferLowWatermark());
client_connection_->setBufferLimits(buffer_len * 3);
EXPECT_FALSE(client_connection_->aboveHighWatermark());
}
{
// Go back in between and verify neither callback is called.
EXPECT_CALL(client_callbacks_, onAboveWriteBufferHighWatermark()).Times(0);
EXPECT_CALL(client_callbacks_, onBelowWriteBufferLowWatermark()).Times(0);
client_connection_->setBufferLimits(buffer_len * 2);
EXPECT_FALSE(client_connection_->aboveHighWatermark());
}
disconnect(false);
}
// Write some data to the connection. It will automatically attempt to flush
// it to the upstream file descriptor via a write() call to buffer_, which is
// configured to succeed and accept all bytes read.
TEST_P(ConnectionImplTest, BasicWrite) {
useMockBuffer();
setUpBasicConnection();
connect();
// Send the data to the connection and verify it is sent upstream.
std::string data_to_write = "hello world";
Buffer::OwnedImpl buffer_to_write(data_to_write);
std::string data_written;
EXPECT_CALL(*client_write_buffer_, move(_))
.WillRepeatedly(DoAll(AddBufferToStringWithoutDraining(&data_written),
Invoke(client_write_buffer_, &MockWatermarkBuffer::baseMove)));
EXPECT_CALL(*client_write_buffer_, write(_))
.WillOnce(Invoke(client_write_buffer_, &MockWatermarkBuffer::trackWrites));
client_connection_->write(buffer_to_write);
dispatcher_->run(Event::Dispatcher::RunType::NonBlock);
EXPECT_EQ(data_to_write, data_written);
disconnect(true);
}
// Similar to BasicWrite, only with watermarks set.
TEST_P(ConnectionImplTest, WriteWithWatermarks) {
useMockBuffer();
setUpBasicConnection();
connect();
client_connection_->setBufferLimits(2);
std::string data_to_write = "hello world";
Buffer::OwnedImpl first_buffer_to_write(data_to_write);
std::string data_written;
EXPECT_CALL(*client_write_buffer_, move(_))
.WillRepeatedly(DoAll(AddBufferToStringWithoutDraining(&data_written),
Invoke(client_write_buffer_, &MockWatermarkBuffer::baseMove)));
EXPECT_CALL(*client_write_buffer_, write(_))
.WillOnce(Invoke(client_write_buffer_, &MockWatermarkBuffer::trackWrites));
// The write() call on the connection will buffer enough data to bring the connection above the
// high watermark but the subsequent drain immediately brings it back below.
// A nice future performance optimization would be to latch if the socket is writable in the
// connection_impl, and try an immediate drain inside of write() to avoid thrashing here.
EXPECT_CALL(client_callbacks_, onAboveWriteBufferHighWatermark());
EXPECT_CALL(client_callbacks_, onBelowWriteBufferLowWatermark());
client_connection_->write(first_buffer_to_write);
dispatcher_->run(Event::Dispatcher::RunType::NonBlock);
EXPECT_EQ(data_to_write, data_written);
// Now do the write again, but this time configure buffer_ to reject the write
// with errno set to EAGAIN via failWrite(). This should result in going above the high
// watermark and not returning.
Buffer::OwnedImpl second_buffer_to_write(data_to_write);
EXPECT_CALL(*client_write_buffer_, move(_))
.WillRepeatedly(DoAll(AddBufferToStringWithoutDraining(&data_written),
Invoke(client_write_buffer_, &MockWatermarkBuffer::baseMove)));
EXPECT_CALL(*client_write_buffer_, write(_)).WillOnce(Invoke([&](int fd) -> int {
dispatcher_->exit();
return client_write_buffer_->failWrite(fd);
}));
// The write() call on the connection will buffer enough data to bring the connection above the
// high watermark and as the data will not flush it should not return below the watermark.
EXPECT_CALL(client_callbacks_, onAboveWriteBufferHighWatermark());
EXPECT_CALL(client_callbacks_, onBelowWriteBufferLowWatermark()).Times(0);
client_connection_->write(second_buffer_to_write);
dispatcher_->run(Event::Dispatcher::RunType::Block);
// Clean up the connection. The close() (called via disconnect) will attempt to flush. The
// call to write() will succeed, bringing the connection back under the low watermark.
EXPECT_CALL(*client_write_buffer_, write(_))
.WillOnce(Invoke(client_write_buffer_, &MockWatermarkBuffer::trackWrites));
EXPECT_CALL(client_callbacks_, onBelowWriteBufferLowWatermark()).Times(1);
disconnect(true);
}
// Read and write random bytes and ensure we don't encounter issues.
TEST_P(ConnectionImplTest, WatermarkFuzzing) {
useMockBuffer();
setUpBasicConnection();
connect();
client_connection_->setBufferLimits(10);
TestRandomGenerator rand;
int bytes_buffered = 0;
int new_bytes_buffered = 0;
bool is_below = true;
bool is_above = false;
ON_CALL(*client_write_buffer_, write(_))
.WillByDefault(testing::Invoke(client_write_buffer_, &MockWatermarkBuffer::failWrite));
ON_CALL(*client_write_buffer_, drain(_))
.WillByDefault(testing::Invoke(client_write_buffer_, &MockWatermarkBuffer::baseDrain));
EXPECT_CALL(*client_write_buffer_, drain(_)).Times(AnyNumber());
// Randomly write 1-20 bytes and read 1-30 bytes per loop.
for (int i = 0; i < 50; ++i) {
// The bytes to read this loop.
int bytes_to_write = rand.random() % 20 + 1;
// The bytes buffered at the begining of this loop.
bytes_buffered = new_bytes_buffered;
// Bytes to flush upstream.
int bytes_to_flush = std::min<int>(rand.random() % 30 + 1, bytes_to_write + bytes_buffered);
// The number of bytes buffered at the end of this loop.
new_bytes_buffered = bytes_buffered + bytes_to_write - bytes_to_flush;
ENVOY_LOG_MISC(trace,
"Loop iteration {} bytes_to_write {} bytes_to_flush {} bytes_buffered is {} and "
"will be be {}",
i, bytes_to_write, bytes_to_flush, bytes_buffered, new_bytes_buffered);
std::string data(bytes_to_write, 'a');
Buffer::OwnedImpl buffer_to_write(data);
// If the current bytes buffered plus the bytes we write this loop go over
// the watermark and we're not currently above, we will get a callback for
// going above.
if (bytes_to_write + bytes_buffered > 11 && is_below) {
ENVOY_LOG_MISC(trace, "Expect onAboveWriteBufferHighWatermark");
EXPECT_CALL(client_callbacks_, onAboveWriteBufferHighWatermark());
is_below = false;
is_above = true;
}
// If after the bytes are flushed upstream the number of bytes remaining is
// below the low watermark and the bytes were not previously below the low
// watermark, expect the callback for going below.
if (new_bytes_buffered < 5 && is_above) {
ENVOY_LOG_MISC(trace, "Expect onBelowWriteBufferLowWatermark");
EXPECT_CALL(client_callbacks_, onBelowWriteBufferLowWatermark());
is_below = true;
is_above = false;
}
// Do the actual work. Write |buffer_to_write| bytes to the connection and
// drain |bytes_to_flush| before having the buffer failWrite()
EXPECT_CALL(*client_write_buffer_, move(_))
.WillOnce(Invoke(client_write_buffer_, &MockWatermarkBuffer::baseMove));
EXPECT_CALL(*client_write_buffer_, write(_))
.WillOnce(DoAll(Invoke([&](int) -> void { client_write_buffer_->drain(bytes_to_flush); }),
Return(bytes_to_flush)))
.WillRepeatedly(testing::Invoke(client_write_buffer_, &MockWatermarkBuffer::failWrite));
client_connection_->write(buffer_to_write);
dispatcher_->run(Event::Dispatcher::RunType::NonBlock);
}
disconnect(true);
}
TEST_P(ConnectionImplTest, BindTest) {
std::string address_string = TestUtility::getIpv4Loopback();
if (GetParam() == Network::Address::IpVersion::v4) {
source_address_ = Network::Address::InstanceConstSharedPtr{
new Network::Address::Ipv4Instance(address_string, 0)};
} else {
address_string = "::1";
source_address_ = Network::Address::InstanceConstSharedPtr{
new Network::Address::Ipv6Instance(address_string, 0)};
}
setUpBasicConnection();
connect();
EXPECT_EQ(address_string, server_connection_->remoteAddress()->ip()->addressAsString());
disconnect(true);
}
TEST_P(ConnectionImplTest, BindFailureTest) {
// Swap the constraints from BindTest to create an address family mismatch.
if (GetParam() == Network::Address::IpVersion::v6) {
const std::string address_string = TestUtility::getIpv4Loopback();
source_address_ = Network::Address::InstanceConstSharedPtr{
new Network::Address::Ipv4Instance(address_string, 0)};
} else {
const std::string address_string = "::1";
source_address_ = Network::Address::InstanceConstSharedPtr{
new Network::Address::Ipv6Instance(address_string, 0)};
}
dispatcher_.reset(new Event::DispatcherImpl);
listener_ = dispatcher_->createListener(socket_, listener_callbacks_, true, false);
client_connection_ = dispatcher_->createClientConnection(
socket_.localAddress(), source_address_, Network::Test::createRawBufferSocket(), nullptr);
MockConnectionStats connection_stats;
client_connection_->setConnectionStats(connection_stats.toBufferStats());
client_connection_->addConnectionCallbacks(client_callbacks_);
EXPECT_CALL(connection_stats.bind_errors_, inc());
EXPECT_CALL(client_callbacks_, onEvent(ConnectionEvent::LocalClose));
dispatcher_->run(Event::Dispatcher::RunType::NonBlock);
}
// ReadOnCloseTest verifies that the read filter's onData function is invoked with available data
// when the connection is closed.
TEST_P(ConnectionImplTest, ReadOnCloseTest) {
setUpBasicConnection();
connect();
// Close without flush immediately invokes this callback.
EXPECT_CALL(client_callbacks_, onEvent(ConnectionEvent::LocalClose));
const int buffer_size = 32;
Buffer::OwnedImpl data(std::string(buffer_size, 'a'));
client_connection_->write(data);
client_connection_->close(ConnectionCloseType::NoFlush);
EXPECT_CALL(*read_filter_, onNewConnection());
EXPECT_CALL(*read_filter_, onData(_))
.Times(1)
.WillOnce(Invoke([&](Buffer::Instance& data) -> FilterStatus {
EXPECT_EQ(buffer_size, data.length());
return FilterStatus::StopIteration;
}));
EXPECT_CALL(server_callbacks_, onEvent(ConnectionEvent::RemoteClose))
.WillOnce(Invoke([&](Network::ConnectionEvent) -> void { dispatcher_->exit(); }));
dispatcher_->run(Event::Dispatcher::RunType::Block);
}
// EmptyReadOnCloseTest verifies that the read filter's onData function is not invoked on empty
// read events due to connection closure.
TEST_P(ConnectionImplTest, EmptyReadOnCloseTest) {
setUpBasicConnection();
connect();
// Write some data and verify that the read filter's onData callback is invoked exactly once.
const int buffer_size = 32;
Buffer::OwnedImpl data(std::string(buffer_size, 'a'));
EXPECT_CALL(*read_filter_, onNewConnection());
EXPECT_CALL(*read_filter_, onData(_))
.Times(1)
.WillOnce(Invoke([&](Buffer::Instance& data) -> FilterStatus {
EXPECT_EQ(buffer_size, data.length());
dispatcher_->exit();
return FilterStatus::StopIteration;
}));
client_connection_->write(data);
dispatcher_->run(Event::Dispatcher::RunType::Block);
disconnect(true);
}
class ConnectionImplBytesSentTest : public testing::Test {
public:
ConnectionImplBytesSentTest() {
EXPECT_CALL(dispatcher_.buffer_factory_, create_(_, _))
.WillRepeatedly(Invoke([](std::function<void()> below_low,
std::function<void()> above_high) -> Buffer::Instance* {
return new Buffer::WatermarkBuffer(below_low, above_high);
}));
EXPECT_CALL(dispatcher_, createFileEvent_(0, _, _, _))
.WillOnce(DoAll(SaveArg<1>(&file_ready_cb_), Return(new Event::MockFileEvent)));
transport_socket_ = new NiceMock<MockTransportSocket>;
connection_.reset(
new ConnectionImpl(dispatcher_, std::make_unique<ConnectionSocketImpl>(0, nullptr, nullptr),
TransportSocketPtr(transport_socket_), true));
connection_->addConnectionCallbacks(callbacks_);
}
~ConnectionImplBytesSentTest() { connection_->close(ConnectionCloseType::NoFlush); }
std::unique_ptr<ConnectionImpl> connection_;
Event::MockDispatcher dispatcher_;
NiceMock<MockConnectionCallbacks> callbacks_;
NiceMock<MockTransportSocket>* transport_socket_;
Event::FileReadyCb file_ready_cb_;
};
// Test that BytesSentCb is invoked at the correct times
TEST_F(ConnectionImplBytesSentTest, BytesSentCallback) {
uint64_t bytes_sent = 0;
uint64_t cb_called = 0;
connection_->addBytesSentCallback([&](uint64_t arg) {
cb_called++;
bytes_sent = arg;
});
// 100 bytes were sent; expect BytesSent event
EXPECT_CALL(*transport_socket_, doWrite(_))
.WillOnce(Return(IoResult{PostIoAction::KeepOpen, 100}));
file_ready_cb_(Event::FileReadyType::Write);
EXPECT_EQ(cb_called, 1);
EXPECT_EQ(bytes_sent, 100);
cb_called = false;
bytes_sent = 0;
// 0 bytes were sent; no event
EXPECT_CALL(*transport_socket_, doWrite(_)).WillOnce(Return(IoResult{PostIoAction::KeepOpen, 0}));
file_ready_cb_(Event::FileReadyType::Write);
EXPECT_EQ(cb_called, 0);
// Reading should not cause BytesSent
EXPECT_CALL(*transport_socket_, doRead(_)).WillOnce(Return(IoResult{PostIoAction::KeepOpen, 1}));
file_ready_cb_(Event::FileReadyType::Read);
EXPECT_EQ(cb_called, 0);
// Closed event should not raise a BytesSent event (but does raise RemoteClose)
EXPECT_CALL(callbacks_, onEvent(ConnectionEvent::RemoteClose));
file_ready_cb_(Event::FileReadyType::Closed);
EXPECT_EQ(cb_called, 0);
}
// Make sure that multiple registered callbacks all get called
TEST_F(ConnectionImplBytesSentTest, BytesSentMultiple) {
uint64_t cb_called1 = 0;
uint64_t cb_called2 = 0;
uint64_t bytes_sent1 = 0;
uint64_t bytes_sent2 = 0;
connection_->addBytesSentCallback([&](uint64_t arg) {
cb_called1++;
bytes_sent1 = arg;
});
connection_->addBytesSentCallback([&](uint64_t arg) {
cb_called2++;
bytes_sent2 = arg;
});
EXPECT_CALL(*transport_socket_, doWrite(_))
.WillOnce(Return(IoResult{PostIoAction::KeepOpen, 100}));
file_ready_cb_(Event::FileReadyType::Write);
EXPECT_EQ(cb_called1, 1);
EXPECT_EQ(cb_called2, 1);
EXPECT_EQ(bytes_sent1, 100);
EXPECT_EQ(bytes_sent2, 100);
}
// Test that if a callback closes the connection, further callbacks are not called.
TEST_F(ConnectionImplBytesSentTest, CloseInCallback) {
// Order is not defined, so register two callbacks that both close the connection. Only
// one of them should be called.
uint64_t cb_called = 0;
Connection::BytesSentCb cb = [&](uint64_t) {
cb_called++;
connection_->close(ConnectionCloseType::NoFlush);
};
connection_->addBytesSentCallback(cb);
connection_->addBytesSentCallback(cb);
EXPECT_CALL(*transport_socket_, doWrite(_))
.WillOnce(Return(IoResult{PostIoAction::KeepOpen, 100}));
file_ready_cb_(Event::FileReadyType::Write);
EXPECT_EQ(cb_called, 1);
EXPECT_EQ(connection_->state(), Connection::State::Closed);
}
class ReadBufferLimitTest : public ConnectionImplTest {
public:
void readBufferLimitTest(uint32_t read_buffer_limit, uint32_t expected_chunk_size) {
const uint32_t buffer_size = 256 * 1024;
dispatcher_.reset(new Event::DispatcherImpl);
listener_ = dispatcher_->createListener(socket_, listener_callbacks_, true, false);
client_connection_ = dispatcher_->createClientConnection(
socket_.localAddress(), Network::Address::InstanceConstSharedPtr(),
Network::Test::createRawBufferSocket(), nullptr);
client_connection_->addConnectionCallbacks(client_callbacks_);
client_connection_->connect();
read_filter_.reset(new NiceMock<MockReadFilter>());
EXPECT_CALL(listener_callbacks_, onAccept_(_, _))
.WillOnce(Invoke([&](Network::ConnectionSocketPtr& socket, bool) -> void {
Network::ConnectionPtr new_connection = dispatcher_->createServerConnection(
std::move(socket), Network::Test::createRawBufferSocket());
new_connection->setBufferLimits(read_buffer_limit);
listener_callbacks_.onNewConnection(std::move(new_connection));
}));
EXPECT_CALL(listener_callbacks_, onNewConnection_(_))
.WillOnce(Invoke([&](Network::ConnectionPtr& conn) -> void {
server_connection_ = std::move(conn);
server_connection_->addReadFilter(read_filter_);
EXPECT_EQ("", server_connection_->nextProtocol());
EXPECT_EQ(read_buffer_limit, server_connection_->bufferLimit());
}));
uint32_t filter_seen = 0;
EXPECT_CALL(*read_filter_, onNewConnection());
EXPECT_CALL(*read_filter_, onData(_))
.WillRepeatedly(Invoke([&](Buffer::Instance& data) -> FilterStatus {
EXPECT_GE(expected_chunk_size, data.length());
filter_seen += data.length();
data.drain(data.length());
if (filter_seen == buffer_size) {
server_connection_->close(ConnectionCloseType::FlushWrite);
}
return FilterStatus::StopIteration;
}));
EXPECT_CALL(client_callbacks_, onEvent(ConnectionEvent::Connected))
.WillOnce(Invoke([&](Network::ConnectionEvent) -> void { dispatcher_->exit(); }));
dispatcher_->run(Event::Dispatcher::RunType::Block);
EXPECT_CALL(client_callbacks_, onEvent(ConnectionEvent::RemoteClose))
.WillOnce(Invoke([&](Network::ConnectionEvent) -> void {
EXPECT_EQ(buffer_size, filter_seen);
dispatcher_->exit();
}));
Buffer::OwnedImpl data(std::string(buffer_size, 'a'));
client_connection_->write(data);
dispatcher_->run(Event::Dispatcher::RunType::Block);
}
};
INSTANTIATE_TEST_CASE_P(IpVersions, ReadBufferLimitTest,
testing::ValuesIn(TestEnvironment::getIpVersionsForTest()));
TEST_P(ReadBufferLimitTest, NoLimit) { readBufferLimitTest(0, 256 * 1024); }
TEST_P(ReadBufferLimitTest, SomeLimit) {
const uint32_t read_buffer_limit = 32 * 1024;
// Envoy has soft limits, so as long as the first read is <= read_buffer_limit - 1 it will do a
// second read. The effective chunk size is then read_buffer_limit - 1 + MaxReadSize,
// which is currently 16384.
readBufferLimitTest(read_buffer_limit, read_buffer_limit - 1 + 16384);
}
class TcpClientConnectionImplTest : public testing::TestWithParam<Address::IpVersion> {};
INSTANTIATE_TEST_CASE_P(IpVersions, TcpClientConnectionImplTest,
testing::ValuesIn(TestEnvironment::getIpVersionsForTest()));
TEST_P(TcpClientConnectionImplTest, BadConnectNotConnRefused) {
Event::DispatcherImpl dispatcher;
Address::InstanceConstSharedPtr address;
if (GetParam() == Network::Address::IpVersion::v4) {
// Connecting to 255.255.255.255 will cause a perm error and not ECONNREFUSED which is a
// different path in libevent. Make sure this doesn't crash.
address = Utility::resolveUrl("tcp://255.255.255.255:1");
} else {
// IPv6 reserved multicast address.
address = Utility::resolveUrl("tcp://[ff00::]:1");
}
ClientConnectionPtr connection =
dispatcher.createClientConnection(address, Network::Address::InstanceConstSharedPtr(),
Network::Test::createRawBufferSocket(), nullptr);
connection->connect();
connection->noDelay(true);
connection->close(ConnectionCloseType::NoFlush);
dispatcher.run(Event::Dispatcher::RunType::Block);
}
TEST_P(TcpClientConnectionImplTest, BadConnectConnRefused) {
Event::DispatcherImpl dispatcher;
// Connecting to an invalid port on localhost will cause ECONNREFUSED which is a different code
// path from other errors. Test this also.
ClientConnectionPtr connection = dispatcher.createClientConnection(
Utility::resolveUrl(
fmt::format("tcp://{}:1", Network::Test::getLoopbackAddressUrlString(GetParam()))),
Network::Address::InstanceConstSharedPtr(), Network::Test::createRawBufferSocket(), nullptr);
connection->connect();
connection->noDelay(true);
dispatcher.run(Event::Dispatcher::RunType::Block);
}
} // namespace Network
} // namespace Envoy
|
/*
* Copyright (c) 2021, Itamar S. <itamar8910@gmail.com>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include "Parser.h"
#include "AST.h"
#include <AK/Debug.h>
#include <AK/ScopeGuard.h>
#include <AK/ScopeLogger.h>
#include <LibCpp/Lexer.h>
namespace Cpp {
Parser::Parser(const StringView& program, const String& filename, Preprocessor::Definitions&& definitions)
: m_definitions(move(definitions))
, m_filename(filename)
{
initialize_program_tokens(program);
if constexpr (CPP_DEBUG) {
dbgln("Tokens:");
for (auto& token : m_tokens) {
StringView text;
if (token.start().line != token.end().line || token.start().column > token.end().column)
text = {};
else
text = text_of_token(token);
dbgln("{} {}:{}-{}:{} ({})", token.to_string(), token.start().line, token.start().column, token.end().line, token.end().column, text);
}
}
}
void Parser::initialize_program_tokens(const StringView& program)
{
Lexer lexer(program);
for (auto& token : lexer.lex()) {
if (token.type() == Token::Type::Whitespace)
continue;
if (token.type() == Token::Type::Identifier) {
if (auto defined_value = m_definitions.find(text_of_token(token)); defined_value != m_definitions.end()) {
add_tokens_for_preprocessor(token, defined_value->value);
m_replaced_preprocessor_tokens.append({ token, defined_value->value });
continue;
}
}
m_tokens.append(move(token));
}
}
NonnullRefPtr<TranslationUnit> Parser::parse()
{
ScopeLogger<CPP_DEBUG> logger;
if (m_tokens.is_empty())
return create_root_ast_node({}, {});
auto unit = create_root_ast_node(m_tokens.first().start(), m_tokens.last().end());
unit->m_declarations = parse_declarations_in_translation_unit(*unit);
return unit;
}
NonnullRefPtrVector<Declaration> Parser::parse_declarations_in_translation_unit(ASTNode& parent)
{
NonnullRefPtrVector<Declaration> declarations;
while (!eof()) {
auto declaration = parse_single_declaration_in_translation_unit(parent);
if (declaration) {
declarations.append(declaration.release_nonnull());
} else {
error("unexpected token");
consume();
}
}
return declarations;
}
RefPtr<Declaration> Parser::parse_single_declaration_in_translation_unit(ASTNode& parent)
{
while (!eof()) {
if (match_comment()) {
consume(Token::Type::Comment);
continue;
}
if (match_preprocessor()) {
consume_preprocessor();
continue;
}
auto declaration = match_declaration_in_translation_unit();
if (declaration.has_value()) {
return parse_declaration(parent, declaration.value());
}
return {};
}
return {};
}
NonnullRefPtr<Declaration> Parser::parse_declaration(ASTNode& parent, DeclarationType declaration_type)
{
switch (declaration_type) {
case DeclarationType::Function:
return parse_function_declaration(parent);
case DeclarationType::Variable:
return parse_variable_declaration(parent);
case DeclarationType::Enum:
return parse_enum_declaration(parent);
case DeclarationType::Class:
return parse_struct_or_class_declaration(parent, StructOrClassDeclaration::Type::Class);
case DeclarationType::Struct:
return parse_struct_or_class_declaration(parent, StructOrClassDeclaration::Type::Struct);
case DeclarationType::Namespace:
return parse_namespace_declaration(parent);
default:
error("unexpected declaration type");
return create_ast_node<InvalidDeclaration>(parent, position(), position());
}
}
NonnullRefPtr<FunctionDeclaration> Parser::parse_function_declaration(ASTNode& parent)
{
auto func = create_ast_node<FunctionDeclaration>(parent, position(), {});
func->m_qualifiers = parse_function_qualifiers();
func->m_return_type = parse_type(*func);
auto function_name = consume(Token::Type::Identifier);
func->m_name = text_of_token(function_name);
consume(Token::Type::LeftParen);
auto parameters = parse_parameter_list(*func);
if (parameters.has_value())
func->m_parameters = move(parameters.value());
consume(Token::Type::RightParen);
RefPtr<FunctionDefinition> body;
Position func_end {};
if (peek(Token::Type::LeftCurly).has_value()) {
body = parse_function_definition(*func);
func_end = body->end();
} else {
func_end = position();
if (match_attribute_specification())
consume_attribute_specification(); // we don't use the value of __attribute__
consume(Token::Type::Semicolon);
}
func->m_definition = move(body);
func->set_end(func_end);
return func;
}
NonnullRefPtr<FunctionDefinition> Parser::parse_function_definition(ASTNode& parent)
{
ScopeLogger<CPP_DEBUG> logger;
auto func = create_ast_node<FunctionDefinition>(parent, position(), {});
consume(Token::Type::LeftCurly);
while (!eof() && peek().type() != Token::Type::RightCurly) {
func->statements().append(parse_statement(func));
}
func->set_end(position());
if (!eof())
consume(Token::Type::RightCurly);
return func;
}
NonnullRefPtr<Statement> Parser::parse_statement(ASTNode& parent)
{
ScopeLogger<CPP_DEBUG> logger;
ArmedScopeGuard consume_semicolon([this]() {
consume(Token::Type::Semicolon);
});
if (match_block_statement()) {
consume_semicolon.disarm();
return parse_block_statement(parent);
}
if (match_comment()) {
consume_semicolon.disarm();
return parse_comment(parent);
}
if (match_variable_declaration()) {
return parse_variable_declaration(parent, false);
}
if (match_expression()) {
return parse_expression(parent);
}
if (match_keyword("return")) {
return parse_return_statement(parent);
}
if (match_keyword("for")) {
consume_semicolon.disarm();
return parse_for_statement(parent);
}
if (match_keyword("if")) {
consume_semicolon.disarm();
return parse_if_statement(parent);
} else {
error("unexpected statement type");
consume_semicolon.disarm();
consume();
return create_ast_node<InvalidStatement>(parent, position(), position());
}
}
NonnullRefPtr<Comment> Parser::parse_comment(ASTNode& parent)
{
auto comment = create_ast_node<Comment>(parent, position(), {});
consume(Token::Type::Comment);
comment->set_end(position());
return comment;
}
bool Parser::match_block_statement()
{
return peek().type() == Token::Type::LeftCurly;
}
NonnullRefPtr<BlockStatement> Parser::parse_block_statement(ASTNode& parent)
{
ScopeLogger<CPP_DEBUG> logger;
auto block_statement = create_ast_node<BlockStatement>(parent, position(), {});
consume(Token::Type::LeftCurly);
while (!eof() && peek().type() != Token::Type::RightCurly) {
block_statement->m_statements.append(parse_statement(*block_statement));
}
consume(Token::Type::RightCurly);
block_statement->set_end(position());
return block_statement;
}
bool Parser::match_type()
{
save_state();
ScopeGuard state_guard = [this] { load_state(); };
parse_type_qualifiers();
if (match_keyword("struct")) {
consume(Token::Type::Keyword); // Consume struct prefix
}
if (!match_name())
return false;
return true;
}
bool Parser::match_template_arguments()
{
save_state();
ScopeGuard state_guard = [this] { load_state(); };
if (!peek(Token::Type::Less).has_value())
return false;
consume();
while (!eof() && peek().type() != Token::Type::Greater) {
if (!match_type())
return false;
parse_type(get_dummy_node());
}
return peek().type() == Token::Type::Greater;
}
NonnullRefPtrVector<Type> Parser::parse_template_arguments(ASTNode& parent)
{
ScopeLogger<CPP_DEBUG> logger;
consume(Token::Type::Less);
NonnullRefPtrVector<Type> template_arguments;
while (!eof() && peek().type() != Token::Type::Greater) {
template_arguments.append(parse_type(parent));
}
consume(Token::Type::Greater);
return template_arguments;
}
bool Parser::match_variable_declaration()
{
ScopeLogger<CPP_DEBUG> logger;
save_state();
ScopeGuard state_guard = [this] { load_state(); };
if (!match_type()) {
return false;
}
VERIFY(m_root_node);
parse_type(get_dummy_node());
// Identifier
if (!peek(Token::Type::Identifier).has_value()) {
return false;
}
consume();
if (match(Token::Type::Equals)) {
consume(Token::Type::Equals);
if (!match_expression()) {
error("initial value of variable is not an expression");
return false;
}
return true;
}
return match(Token::Type::Semicolon);
}
NonnullRefPtr<VariableDeclaration> Parser::parse_variable_declaration(ASTNode& parent, bool expect_semicolon)
{
ScopeLogger<CPP_DEBUG> logger;
auto var = create_ast_node<VariableDeclaration>(parent, position(), {});
if (!match_variable_declaration()) {
error("unexpected token for variable type");
var->set_end(position());
return var;
}
var->m_type = parse_type(var);
auto identifier_token = consume(Token::Type::Identifier);
RefPtr<Expression> initial_value;
if (match(Token::Type::Equals)) {
consume(Token::Type::Equals);
initial_value = parse_expression(var);
}
if (expect_semicolon)
consume(Token::Type::Semicolon);
var->set_end(position());
var->m_name = text_of_token(identifier_token);
var->m_initial_value = move(initial_value);
return var;
}
NonnullRefPtr<Expression> Parser::parse_expression(ASTNode& parent)
{
ScopeLogger<CPP_DEBUG> logger;
auto expression = parse_primary_expression(parent);
// TODO: remove eof() logic, should still work without it
if (eof() || match(Token::Type::Semicolon)) {
return expression;
}
NonnullRefPtrVector<Expression> secondary_expressions;
while (match_secondary_expression()) {
// FIXME: Handle operator precedence
expression = parse_secondary_expression(parent, expression);
secondary_expressions.append(expression);
}
for (size_t i = 0; secondary_expressions.size() != 0 && i < secondary_expressions.size() - 1; ++i) {
secondary_expressions[i].set_parent(secondary_expressions[i + 1]);
}
return expression;
}
bool Parser::match_secondary_expression()
{
auto type = peek().type();
return type == Token::Type::Plus
|| type == Token::Type::PlusEquals
|| type == Token::Type::Minus
|| type == Token::Type::MinusEquals
|| type == Token::Type::Asterisk
|| type == Token::Type::AsteriskEquals
|| type == Token::Type::Percent
|| type == Token::Type::PercentEquals
|| type == Token::Type::Equals
|| type == Token::Type::Greater
|| type == Token::Type::Greater
|| type == Token::Type::Less
|| type == Token::Type::LessEquals
|| type == Token::Type::Dot
|| type == Token::Type::PlusPlus
|| type == Token::Type::MinusMinus
|| type == Token::Type::And
|| type == Token::Type::AndEquals
|| type == Token::Type::Pipe
|| type == Token::Type::PipeEquals
|| type == Token::Type::Caret
|| type == Token::Type::CaretEquals
|| type == Token::Type::LessLess
|| type == Token::Type::LessLessEquals
|| type == Token::Type::GreaterGreater
|| type == Token::Type::GreaterGreaterEquals
|| type == Token::Type::EqualsEquals
|| type == Token::Type::AndAnd
|| type == Token::Type::PipePipe
|| type == Token::Type::ExclamationMarkEquals
|| type == Token::Type::PipePipe
|| type == Token::Type::Arrow
|| type == Token::Type::LeftParen;
}
NonnullRefPtr<Expression> Parser::parse_primary_expression(ASTNode& parent)
{
ScopeLogger<CPP_DEBUG> logger;
// TODO: remove eof() logic, should still work without it
if (eof()) {
auto node = create_ast_node<Identifier>(parent, position(), position());
return node;
}
if (match_unary_expression())
return parse_unary_expression(parent);
if (match_literal()) {
return parse_literal(parent);
}
if (match_cpp_cast_expression())
return parse_cpp_cast_expression(parent);
if (match_c_style_cast_expression())
return parse_c_style_cast_expression(parent);
if (match_sizeof_expression())
return parse_sizeof_expression(parent);
if (match_braced_init_list())
return parse_braced_init_list(parent);
if (match_name()) {
return parse_name(parent);
}
error("could not parse primary expression");
auto token = consume();
return create_ast_node<InvalidExpression>(parent, token.start(), token.end());
}
bool Parser::match_literal()
{
switch (peek().type()) {
case Token::Type::Integer:
return true;
case Token::Type::SingleQuotedString:
return true;
case Token::Type::DoubleQuotedString:
return true;
case Token::Type::Float:
return true;
case Token::Type::Keyword: {
return match_boolean_literal() || peek().text() == "nullptr";
}
default:
return false;
}
}
bool Parser::match_unary_expression()
{
auto type = peek().type();
return type == Token::Type::PlusPlus
|| type == Token::Type::MinusMinus
|| type == Token::Type::ExclamationMark
|| type == Token::Type::Tilde
|| type == Token::Type::Plus
|| type == Token::Type::Minus
|| type == Token::Type::And;
}
NonnullRefPtr<UnaryExpression> Parser::parse_unary_expression(ASTNode& parent)
{
auto unary_exp = create_ast_node<UnaryExpression>(parent, position(), {});
auto op_token = consume();
UnaryOp op { UnaryOp::Invalid };
switch (op_token.type()) {
case Token::Type::Minus:
op = UnaryOp::Minus;
break;
case Token::Type::Plus:
op = UnaryOp::Plus;
break;
case Token::Type::ExclamationMark:
op = UnaryOp::Not;
break;
case Token::Type::Tilde:
op = UnaryOp::BitwiseNot;
break;
case Token::Type::PlusPlus:
op = UnaryOp::PlusPlus;
break;
case Token::Type::And:
op = UnaryOp::Address;
break;
default:
break;
}
unary_exp->m_op = op;
auto lhs = parse_expression(*unary_exp);
unary_exp->m_lhs = lhs;
unary_exp->set_end(lhs->end());
return unary_exp;
}
NonnullRefPtr<Expression> Parser::parse_literal(ASTNode& parent)
{
switch (peek().type()) {
case Token::Type::Integer: {
auto token = consume();
return create_ast_node<NumericLiteral>(parent, token.start(), token.end(), text_of_token(token));
}
case Token::Type::SingleQuotedString:
[[fallthrough]];
case Token::Type::DoubleQuotedString:
return parse_string_literal(parent);
case Token::Type::Keyword: {
if (match_boolean_literal())
return parse_boolean_literal(parent);
if (peek().text() == "nullptr") {
auto token = consume();
return create_ast_node<NullPointerLiteral>(parent, token.start(), token.end());
}
[[fallthrough]];
}
default: {
error("could not parse literal");
auto token = consume();
return create_ast_node<InvalidExpression>(parent, token.start(), token.end());
}
}
}
NonnullRefPtr<Expression> Parser::parse_secondary_expression(ASTNode& parent, NonnullRefPtr<Expression> lhs)
{
ScopeLogger<CPP_DEBUG> logger;
switch (peek().type()) {
case Token::Type::Plus:
return parse_binary_expression(parent, lhs, BinaryOp::Addition);
case Token::Type::Less:
return parse_binary_expression(parent, lhs, BinaryOp::LessThan);
case Token::Type::EqualsEquals:
return parse_binary_expression(parent, lhs, BinaryOp::EqualsEquals);
case Token::Type::ExclamationMarkEquals:
return parse_binary_expression(parent, lhs, BinaryOp::NotEqual);
case Token::Type::And:
return parse_binary_expression(parent, lhs, BinaryOp::BitwiseAnd);
case Token::Type::AndAnd:
return parse_binary_expression(parent, lhs, BinaryOp::LogicalAnd);
case Token::Type::Pipe:
return parse_binary_expression(parent, lhs, BinaryOp::BitwiseOr);
case Token::Type::PipePipe:
return parse_binary_expression(parent, lhs, BinaryOp::LogicalOr);
case Token::Type::Arrow:
return parse_binary_expression(parent, lhs, BinaryOp::Arrow);
case Token::Type::Equals:
return parse_assignment_expression(parent, lhs, AssignmentOp::Assignment);
case Token::Type::Dot: {
consume();
auto exp = create_ast_node<MemberExpression>(parent, lhs->start(), {});
lhs->set_parent(*exp);
exp->m_object = move(lhs);
auto identifier_token = consume(Token::Type::Identifier);
exp->m_property = create_ast_node<Identifier>(*exp, identifier_token.start(), identifier_token.end(), identifier_token.text());
exp->set_end(position());
return exp;
}
case Token::Type::LeftParen: {
consume();
auto func = create_ast_node<FunctionCall>(parent, lhs->start(), {});
lhs->set_parent(*func);
func->m_callee = lhs;
while (peek().type() != Token::Type::RightParen && !eof()) {
func->m_arguments.append(parse_expression(*func));
if (peek().type() == Token::Type::Comma)
consume(Token::Type::Comma);
}
consume(Token::Type::RightParen);
func->set_end(position());
return func;
}
default: {
error(String::formatted("unexpected operator for expression. operator: {}", peek().to_string()));
auto token = consume();
return create_ast_node<InvalidExpression>(parent, token.start(), token.end());
}
}
}
NonnullRefPtr<BinaryExpression> Parser::parse_binary_expression(ASTNode& parent, NonnullRefPtr<Expression> lhs, BinaryOp op)
{
consume(); // Operator
auto exp = create_ast_node<BinaryExpression>(parent, lhs->start(), {});
lhs->set_parent(*exp);
exp->m_op = op;
exp->m_lhs = move(lhs);
auto rhs = parse_expression(exp);
exp->set_end(rhs->end());
exp->m_rhs = move(rhs);
return exp;
}
NonnullRefPtr<AssignmentExpression> Parser::parse_assignment_expression(ASTNode& parent, NonnullRefPtr<Expression> lhs, AssignmentOp op)
{
consume(); // Operator
auto exp = create_ast_node<AssignmentExpression>(parent, lhs->start(), {});
lhs->set_parent(*exp);
exp->m_op = op;
exp->m_lhs = move(lhs);
auto rhs = parse_expression(exp);
exp->set_end(rhs->end());
exp->m_rhs = move(rhs);
return exp;
}
Optional<Parser::DeclarationType> Parser::match_declaration_in_translation_unit()
{
if (match_function_declaration())
return DeclarationType::Function;
if (match_enum_declaration())
return DeclarationType::Enum;
if (match_class_declaration())
return DeclarationType::Class;
if (match_struct_declaration())
return DeclarationType::Struct;
if (match_namespace_declaration())
return DeclarationType::Namespace;
if (match_variable_declaration())
return DeclarationType::Variable;
return {};
}
bool Parser::match_enum_declaration()
{
return match_keyword("enum");
}
bool Parser::match_class_declaration()
{
return match_keyword("class");
}
bool Parser::match_struct_declaration()
{
return match_keyword("struct");
}
bool Parser::match_namespace_declaration()
{
return match_keyword("namespace");
}
bool Parser::match_function_declaration()
{
save_state();
ScopeGuard state_guard = [this] { load_state(); };
parse_function_qualifiers();
if (!match_type())
return false;
VERIFY(m_root_node);
parse_type(get_dummy_node());
if (!peek(Token::Type::Identifier).has_value())
return false;
consume();
if (!peek(Token::Type::LeftParen).has_value())
return false;
consume();
while (consume().type() != Token::Type::RightParen && !eof()) { };
if (peek(Token::Type::Semicolon).has_value() || peek(Token::Type::LeftCurly).has_value())
return true;
if (match_attribute_specification()) {
consume_attribute_specification();
return peek(Token::Type::Semicolon).has_value();
}
return false;
}
Optional<NonnullRefPtrVector<Parameter>> Parser::parse_parameter_list(ASTNode& parent)
{
ScopeLogger<CPP_DEBUG> logger;
NonnullRefPtrVector<Parameter> parameters;
while (peek().type() != Token::Type::RightParen && !eof()) {
if (match_ellipsis()) {
auto last_dot = consume();
while (peek().type() == Token::Type::Dot)
last_dot = consume();
auto param = create_ast_node<Parameter>(parent, position(), last_dot.end(), StringView {});
param->m_is_ellipsis = true;
parameters.append(move(param));
} else {
auto type = parse_type(parent);
auto name_identifier = peek(Token::Type::Identifier);
if (name_identifier.has_value())
consume(Token::Type::Identifier);
StringView name;
if (name_identifier.has_value())
name = text_of_token(name_identifier.value());
auto param = create_ast_node<Parameter>(parent, type->start(), name_identifier.has_value() ? name_identifier.value().end() : type->end(), name);
param->m_type = move(type);
parameters.append(move(param));
}
if (peek(Token::Type::Comma).has_value())
consume(Token::Type::Comma);
}
return parameters;
}
bool Parser::match_comment()
{
return match(Token::Type::Comment);
}
bool Parser::match_whitespace()
{
return match(Token::Type::Whitespace);
}
bool Parser::match_preprocessor()
{
return match(Token::Type::PreprocessorStatement) || match(Token::Type::IncludeStatement);
}
void Parser::consume_preprocessor()
{
ScopeLogger<CPP_DEBUG> logger;
switch (peek().type()) {
case Token::Type::PreprocessorStatement:
consume();
break;
case Token::Type::IncludeStatement:
consume();
consume(Token::Type::IncludePath);
break;
default:
error("unexpected token while parsing preprocessor statement");
consume();
}
}
Optional<Token> Parser::consume_whitespace()
{
ScopeLogger<CPP_DEBUG> logger;
return consume(Token::Type::Whitespace);
}
Token Parser::consume(Token::Type type)
{
auto token = consume();
if (token.type() != type)
error(String::formatted("expected {} at {}:{}, found: {}", Token::type_to_string(type), token.start().line, token.start().column, Token::type_to_string(token.type())));
return token;
}
bool Parser::match(Token::Type type)
{
return peek().type() == type;
}
Token Parser::consume()
{
if (eof()) {
error("C++ Parser: out of tokens");
return { Token::Type::EOF_TOKEN, position(), position(), {} };
}
return m_tokens[m_state.token_index++];
}
Token Parser::peek(size_t offset) const
{
if (m_state.token_index + offset >= m_tokens.size())
return { Token::Type::EOF_TOKEN, position(), position(), {} };
return m_tokens[m_state.token_index + offset];
}
Optional<Token> Parser::peek(Token::Type type) const
{
auto token = peek();
if (token.type() == type)
return token;
return {};
}
void Parser::save_state()
{
m_saved_states.append(m_state);
}
void Parser::load_state()
{
m_state = m_saved_states.take_last();
}
StringView Parser::text_of_token(const Cpp::Token& token) const
{
return token.text();
}
String Parser::text_of_node(const ASTNode& node) const
{
return text_in_range(node.start(), node.end());
}
String Parser::text_in_range(Position start, Position end) const
{
auto start_token_index = index_of_token_at(start);
auto end_node_index = index_of_token_at(end);
VERIFY(start_token_index.has_value());
VERIFY(end_node_index.has_value());
StringBuilder text;
for (size_t i = start_token_index.value(); i <= end_node_index.value(); ++i) {
text.append(m_tokens[i].text());
}
return text.build();
}
void Parser::error(StringView message)
{
ScopeLogger<CPP_DEBUG> logger;
if (message.is_null() || message.is_empty())
message = "<empty>";
String formatted_message;
if (m_state.token_index >= m_tokens.size()) {
formatted_message = String::formatted("C++ Parsed error on EOF.{}", message);
} else {
formatted_message = String::formatted("C++ Parser error: {}. token: {} ({}:{})",
message,
m_state.token_index < m_tokens.size() ? text_of_token(m_tokens[m_state.token_index]) : "EOF",
m_tokens[m_state.token_index].start().line,
m_tokens[m_state.token_index].start().column);
}
m_state.errors.append(formatted_message);
}
bool Parser::match_expression()
{
auto token_type = peek().type();
return match_literal()
|| token_type == Token::Type::Identifier
|| match_unary_expression()
|| match_cpp_cast_expression()
|| match_c_style_cast_expression()
|| match_sizeof_expression()
|| match_braced_init_list();
}
bool Parser::eof() const
{
return m_state.token_index >= m_tokens.size();
}
Position Parser::position() const
{
if (eof())
return m_tokens.last().end();
return peek().start();
}
RefPtr<ASTNode> Parser::eof_node() const
{
VERIFY(m_tokens.size());
return node_at(m_tokens.last().end());
}
RefPtr<ASTNode> Parser::node_at(Position pos) const
{
auto index = index_of_node_at(pos);
if (!index.has_value())
return nullptr;
return m_state.nodes[index.value()];
}
Optional<size_t> Parser::index_of_node_at(Position pos) const
{
VERIFY(!m_tokens.is_empty());
Optional<size_t> match_node_index;
auto node_span = [](const ASTNode& node) {
VERIFY(node.end().line >= node.start().line);
VERIFY((node.end().line > node.start().line) || (node.end().column >= node.start().column));
return Position { node.end().line - node.start().line, node.start().line != node.end().line ? 0 : node.end().column - node.start().column };
};
for (size_t node_index = 0; node_index < m_state.nodes.size(); ++node_index) {
auto& node = m_state.nodes[node_index];
if (node.start() > pos || node.end() < pos)
continue;
if (!match_node_index.has_value() || (node_span(node) < node_span(m_state.nodes[match_node_index.value()])))
match_node_index = node_index;
}
return match_node_index;
}
Optional<Token> Parser::token_at(Position pos) const
{
auto index = index_of_token_at(pos);
if (!index.has_value())
return {};
return m_tokens[index.value()];
}
Optional<size_t> Parser::index_of_token_at(Position pos) const
{
for (size_t token_index = 0; token_index < m_tokens.size(); ++token_index) {
auto token = m_tokens[token_index];
if (token.start() > pos || token.end() < pos)
continue;
return token_index;
}
return {};
}
void Parser::print_tokens() const
{
for (auto& token : m_tokens) {
dbgln("{}", token.to_string());
}
}
NonnullRefPtr<StringLiteral> Parser::parse_string_literal(ASTNode& parent)
{
ScopeLogger<CPP_DEBUG> logger;
Optional<size_t> start_token_index;
Optional<size_t> end_token_index;
while (!eof()) {
auto token = peek();
if (token.type() != Token::Type::DoubleQuotedString && token.type() != Token::Type::SingleQuotedString && token.type() != Token::Type::EscapeSequence) {
VERIFY(start_token_index.has_value());
end_token_index = m_state.token_index - 1;
break;
}
if (!start_token_index.has_value())
start_token_index = m_state.token_index;
consume();
}
// String was not terminated
if (!end_token_index.has_value()) {
end_token_index = m_tokens.size() - 1;
}
VERIFY(start_token_index.has_value());
VERIFY(end_token_index.has_value());
Token start_token = m_tokens[start_token_index.value()];
Token end_token = m_tokens[end_token_index.value()];
auto text = text_in_range(start_token.start(), end_token.end());
auto string_literal = create_ast_node<StringLiteral>(parent, start_token.start(), end_token.end());
string_literal->m_value = text;
return string_literal;
}
NonnullRefPtr<ReturnStatement> Parser::parse_return_statement(ASTNode& parent)
{
ScopeLogger<CPP_DEBUG> logger;
auto return_statement = create_ast_node<ReturnStatement>(parent, position(), {});
consume(Token::Type::Keyword);
if (!peek(Token::Type::Semicolon).has_value()) {
auto expression = parse_expression(*return_statement);
return_statement->m_value = expression;
}
return_statement->set_end(position());
return return_statement;
}
NonnullRefPtr<EnumDeclaration> Parser::parse_enum_declaration(ASTNode& parent)
{
ScopeLogger<CPP_DEBUG> logger;
auto enum_decl = create_ast_node<EnumDeclaration>(parent, position(), {});
consume_keyword("enum");
auto name_token = consume(Token::Type::Identifier);
enum_decl->m_name = text_of_token(name_token);
consume(Token::Type::LeftCurly);
while (!eof() && peek().type() != Token::Type::RightCurly) {
enum_decl->m_entries.append(text_of_token(consume(Token::Type::Identifier)));
if (peek().type() != Token::Type::Comma) {
break;
}
consume(Token::Type::Comma);
}
consume(Token::Type::RightCurly);
consume(Token::Type::Semicolon);
enum_decl->set_end(position());
return enum_decl;
}
Token Parser::consume_keyword(const String& keyword)
{
auto token = consume();
if (token.type() != Token::Type::Keyword) {
error(String::formatted("unexpected token: {}, expected Keyword", token.to_string()));
return token;
}
if (text_of_token(token) != keyword) {
error(String::formatted("unexpected keyword: {}, expected {}", text_of_token(token), keyword));
return token;
}
return token;
}
bool Parser::match_keyword(const String& keyword)
{
auto token = peek();
if (token.type() != Token::Type::Keyword) {
return false;
}
if (text_of_token(token) != keyword) {
return false;
}
return true;
}
NonnullRefPtr<StructOrClassDeclaration> Parser::parse_struct_or_class_declaration(ASTNode& parent, StructOrClassDeclaration::Type type)
{
ScopeLogger<CPP_DEBUG> logger;
auto decl = create_ast_node<StructOrClassDeclaration>(parent, position(), {}, type);
switch (type) {
case StructOrClassDeclaration::Type::Struct:
consume_keyword("struct");
break;
case StructOrClassDeclaration::Type::Class:
consume_keyword("class");
break;
}
auto name_token = consume(Token::Type::Identifier);
decl->m_name = text_of_token(name_token);
consume(Token::Type::LeftCurly);
while (!eof() && peek().type() != Token::Type::RightCurly) {
decl->m_members.append(parse_member_declaration(*decl));
}
consume(Token::Type::RightCurly);
consume(Token::Type::Semicolon);
decl->set_end(position());
return decl;
}
NonnullRefPtr<MemberDeclaration> Parser::parse_member_declaration(ASTNode& parent)
{
ScopeLogger<CPP_DEBUG> logger;
auto member_decl = create_ast_node<MemberDeclaration>(parent, position(), {});
member_decl->m_type = parse_type(*member_decl);
auto identifier_token = consume(Token::Type::Identifier);
member_decl->m_name = text_of_token(identifier_token);
if (match_braced_init_list()) {
member_decl->m_initial_value = parse_braced_init_list(*member_decl);
}
consume(Token::Type::Semicolon);
member_decl->set_end(position());
return member_decl;
}
NonnullRefPtr<BooleanLiteral> Parser::parse_boolean_literal(ASTNode& parent)
{
ScopeLogger<CPP_DEBUG> logger;
auto token = consume(Token::Type::Keyword);
auto text = text_of_token(token);
// text == "true" || text == "false";
bool value = (text == "true");
return create_ast_node<BooleanLiteral>(parent, token.start(), token.end(), value);
}
bool Parser::match_boolean_literal()
{
auto token = peek();
if (token.type() != Token::Type::Keyword)
return false;
auto text = text_of_token(token);
return text == "true" || text == "false";
}
NonnullRefPtr<Type> Parser::parse_type(ASTNode& parent)
{
ScopeLogger<CPP_DEBUG> logger;
if (!match_type()) {
auto token = consume();
return create_ast_node<Type>(parent, token.start(), token.end());
}
auto type = create_ast_node<Type>(parent, position(), {});
auto qualifiers = parse_type_qualifiers();
type->m_qualifiers = move(qualifiers);
if (match_keyword("struct")) {
consume(Token::Type::Keyword); // Consume struct prefix
}
if (!match_name()) {
type->set_end(position());
error(String::formatted("expected name instead of: {}", peek().text()));
return type;
}
type->m_name = parse_name(*type);
while (!eof() && peek().type() == Token::Type::Asterisk) {
type->set_end(position());
auto asterisk = consume();
auto ptr = create_ast_node<Pointer>(parent, asterisk.start(), asterisk.end());
type->set_parent(*ptr);
ptr->m_pointee = type;
type = ptr;
}
type->set_end(position());
return type;
}
NonnullRefPtr<ForStatement> Parser::parse_for_statement(ASTNode& parent)
{
ScopeLogger<CPP_DEBUG> logger;
auto for_statement = create_ast_node<ForStatement>(parent, position(), {});
consume(Token::Type::Keyword);
consume(Token::Type::LeftParen);
if (peek().type() != Token::Type::Semicolon)
for_statement->m_init = parse_variable_declaration(*for_statement, false);
consume(Token::Type::Semicolon);
if (peek().type() != Token::Type::Semicolon)
for_statement->m_test = parse_expression(*for_statement);
consume(Token::Type::Semicolon);
if (peek().type() != Token::Type::RightParen)
for_statement->m_update = parse_expression(*for_statement);
consume(Token::Type::RightParen);
for_statement->m_body = parse_statement(*for_statement);
for_statement->set_end(for_statement->m_body->end());
return for_statement;
}
NonnullRefPtr<IfStatement> Parser::parse_if_statement(ASTNode& parent)
{
ScopeLogger<CPP_DEBUG> logger;
auto if_statement = create_ast_node<IfStatement>(parent, position(), {});
consume(Token::Type::Keyword);
consume(Token::Type::LeftParen);
if_statement->m_predicate = parse_expression(*if_statement);
consume(Token::Type::RightParen);
if_statement->m_then = parse_statement(*if_statement);
if (match_keyword("else")) {
consume(Token::Type::Keyword);
if_statement->m_else = parse_statement(*if_statement);
if_statement->set_end(if_statement->m_else->end());
} else {
if_statement->set_end(if_statement->m_then->end());
}
return if_statement;
}
Vector<StringView> Parser::parse_type_qualifiers()
{
ScopeLogger<CPP_DEBUG> logger;
Vector<StringView> qualifiers;
while (!eof()) {
auto token = peek();
if (token.type() != Token::Type::Keyword)
break;
auto text = text_of_token(token);
if (text == "static" || text == "const") {
qualifiers.append(text);
consume();
} else {
break;
}
}
return qualifiers;
}
Vector<StringView> Parser::parse_function_qualifiers()
{
ScopeLogger<CPP_DEBUG> logger;
Vector<StringView> qualifiers;
while (!eof()) {
auto token = peek();
if (token.type() != Token::Type::Keyword)
break;
auto text = text_of_token(token);
if (text == "static" || text == "inline") {
qualifiers.append(text);
consume();
} else {
break;
}
}
return qualifiers;
}
bool Parser::match_attribute_specification()
{
return text_of_token(peek()) == "__attribute__";
}
void Parser::consume_attribute_specification()
{
consume(); // __attribute__
consume(Token::Type::LeftParen);
size_t left_count = 1;
while (!eof()) {
auto token = consume();
if (token.type() == Token::Type::LeftParen) {
++left_count;
}
if (token.type() == Token::Type::RightParen) {
--left_count;
}
if (left_count == 0)
return;
}
}
bool Parser::match_ellipsis()
{
if (m_state.token_index > m_tokens.size() - 3)
return false;
return peek().type() == Token::Type::Dot && peek().type() == Token::Type::Dot && peek().type() == Token::Type::Dot;
}
void Parser::add_tokens_for_preprocessor(Token& replaced_token, Preprocessor::DefinedValue& definition)
{
if (!definition.value.has_value())
return;
Lexer lexer(definition.value.value());
for (auto token : lexer.lex()) {
if (token.type() == Token::Type::Whitespace)
continue;
token.set_start(replaced_token.start());
token.set_end(replaced_token.end());
m_tokens.append(move(token));
}
}
NonnullRefPtr<NamespaceDeclaration> Parser::parse_namespace_declaration(ASTNode& parent, bool is_nested_namespace)
{
auto namespace_decl = create_ast_node<NamespaceDeclaration>(parent, position(), {});
if (!is_nested_namespace)
consume(Token::Type::Keyword);
auto name_token = consume(Token::Type::Identifier);
namespace_decl->m_name = name_token.text();
if (peek().type() == Token::Type::ColonColon) {
consume(Token::Type::ColonColon);
namespace_decl->m_declarations.append(parse_namespace_declaration(*namespace_decl, true));
namespace_decl->set_end(position());
return namespace_decl;
}
consume(Token::Type::LeftCurly);
while (!eof() && peek().type() != Token::Type::RightCurly) {
auto declaration = parse_single_declaration_in_translation_unit(*namespace_decl);
if (declaration) {
namespace_decl->m_declarations.append(declaration.release_nonnull());
} else {
error("unexpected token");
consume();
}
}
consume(Token::Type::RightCurly);
namespace_decl->set_end(position());
return namespace_decl;
}
bool Parser::match_name()
{
auto type = peek().type();
return type == Token::Type::Identifier || type == Token::Type::KnownType;
}
NonnullRefPtr<Name> Parser::parse_name(ASTNode& parent)
{
NonnullRefPtr<Name> name_node = create_ast_node<Name>(parent, position(), {});
while (!eof() && (peek().type() == Token::Type::Identifier || peek().type() == Token::Type::KnownType)) {
auto token = consume();
name_node->m_scope.append(create_ast_node<Identifier>(*name_node, token.start(), token.end(), token.text()));
if (peek().type() == Token::Type::ColonColon)
consume();
else
break;
}
VERIFY(!name_node->m_scope.is_empty());
name_node->m_name = name_node->m_scope.take_last();
if (match_template_arguments()) {
consume(Token::Type::Less);
NonnullRefPtr<TemplatizedName> templatized_name = create_ast_node<TemplatizedName>(parent, name_node->start(), {});
templatized_name->m_name = move(name_node->m_name);
templatized_name->m_scope = move(name_node->m_scope);
name_node->set_end(position());
name_node = templatized_name;
while (peek().type() != Token::Type::Greater && !eof()) {
templatized_name->m_template_arguments.append(parse_type(*templatized_name));
if (peek().type() == Token::Type::Comma)
consume(Token::Type::Comma);
}
consume(Token::Type::Greater);
}
name_node->set_end(position());
return name_node;
}
bool Parser::match_cpp_cast_expression()
{
save_state();
ScopeGuard state_guard = [this] { load_state(); };
auto token = consume();
if (token.type() != Token::Type::Keyword)
return false;
auto text = token.text();
if (text == "static_cast" || text == "reinterpret_cast" || text == "dynamic_cast" || text == "const_cast")
return true;
return false;
}
bool Parser::match_c_style_cast_expression()
{
save_state();
ScopeGuard state_guard = [this] { load_state(); };
if (consume().type() != Token::Type::LeftParen)
return false;
if (!match_type())
return false;
parse_type(get_dummy_node());
if (consume().type() != Token::Type::RightParen)
return false;
if (!match_expression())
return false;
return true;
}
NonnullRefPtr<CStyleCastExpression> Parser::parse_c_style_cast_expression(ASTNode& parent)
{
auto parse_exp = create_ast_node<CStyleCastExpression>(parent, position(), {});
consume(Token::Type::LeftParen);
parse_exp->m_type = parse_type(*parse_exp);
consume(Token::Type::RightParen);
parse_exp->m_expression = parse_expression(*parse_exp);
parse_exp->set_end(position());
return parse_exp;
}
NonnullRefPtr<CppCastExpression> Parser::parse_cpp_cast_expression(ASTNode& parent)
{
auto cast_expression = create_ast_node<CppCastExpression>(parent, position(), {});
cast_expression->m_cast_type = consume(Token::Type::Keyword).text();
consume(Token::Type::Less);
cast_expression->m_type = parse_type(*cast_expression);
consume(Token::Type::Greater);
consume(Token::Type::LeftParen);
cast_expression->m_expression = parse_expression(*cast_expression);
consume(Token::Type::RightParen);
cast_expression->set_end(position());
return cast_expression;
}
bool Parser::match_sizeof_expression()
{
return match_keyword("sizeof");
}
NonnullRefPtr<SizeofExpression> Parser::parse_sizeof_expression(ASTNode& parent)
{
auto exp = create_ast_node<SizeofExpression>(parent, position(), {});
consume(Token::Type::Keyword);
consume(Token::Type::LeftParen);
exp->m_type = parse_type(parent);
consume(Token::Type::RightParen);
exp->set_end(position());
return exp;
}
bool Parser::match_braced_init_list()
{
return match(Token::Type::LeftCurly);
}
NonnullRefPtr<BracedInitList> Parser::parse_braced_init_list(ASTNode& parent)
{
auto init_list = create_ast_node<BracedInitList>(parent, position(), {});
consume(Token::Type::LeftCurly);
while (!eof() && peek().type() != Token::Type::RightCurly) {
init_list->m_expressions.append(parse_expression(*init_list));
}
consume(Token::Type::RightCurly);
init_list->set_end(position());
return init_list;
}
}
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/chime/model/GetMessagingSessionEndpointResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::Chime::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
GetMessagingSessionEndpointResult::GetMessagingSessionEndpointResult()
{
}
GetMessagingSessionEndpointResult::GetMessagingSessionEndpointResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
*this = result;
}
GetMessagingSessionEndpointResult& GetMessagingSessionEndpointResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("Endpoint"))
{
m_endpoint = jsonValue.GetObject("Endpoint");
}
return *this;
}
|
#include <aslam/cameras/camera.h>
#include <aslam/cameras/ncamera.h>
#include <aslam/cameras/yaml/camera-yaml-serialization.h>
#include <aslam/cameras/yaml/ncamera-yaml-serialization.h>
#include <aslam/common/memory.h>
#include <aslam/common/yaml-serialization.h>
namespace YAML {
//
bool convert<std::shared_ptr<aslam::NCamera> >::decode(const Node& node,
aslam::NCamera::Ptr& ncamera) {
ncamera.reset();
try {
if (!node.IsMap()) {
LOG(ERROR) << "Unable to parse the ncamera because the node is not a map.";
return true;
}
// Parse the label.
std::string label = "";
if (!YAML::safeGet<std::string>(node, "label", &label)) {
LOG(ERROR) << "Unable to get the label for the ncamera.";
return true;
}
// Parse the id.
aslam::NCameraId ncam_id;
std::string id_string;
if (!node["id"] || !YAML::safeGet<std::string>(node, "id", &id_string)) {
LOG(WARNING) << "Unable to get the id for the ncamera. Generating new random id.";
ncam_id.randomize();
} else {
ncam_id.fromHexString(id_string);
}
// Parse the cameras.
const Node& cameras_node = node["cameras"];
if (!cameras_node.IsSequence()) {
LOG(ERROR) << "Unable to parse the cameras because the camera node is not a sequence.";
return true;
}
size_t num_cameras = cameras_node.size();
if (num_cameras == 0) {
LOG(ERROR) << "Number of cameras is 0.";
return true;
}
aslam::TransformationVector T_Ci_B;
std::vector<aslam::Camera::Ptr> cameras;
for (size_t camera_index = 0; camera_index < num_cameras; ++camera_index) {
// Decode the camera
const Node& camera_node = cameras_node[camera_index];
if (!camera_node) {
LOG(ERROR) << "Unable to get camera node for camera " << camera_index;
return true;
}
if (!camera_node.IsMap()) {
LOG(ERROR) << "Camera node for camera " << camera_index << " is not a map.";
return true;
}
aslam::Camera::Ptr camera;
if (!YAML::safeGet(camera_node, "camera", &camera)) {
LOG(ERROR) << "Unable to retrieve camera " << camera_index;
return true;
}
// Get the transformation matrix T_B_C (takes points from the frame C to frame B).
Eigen::Matrix4d T_B_C_raw;
if (!YAML::safeGet(camera_node, "T_B_C", &T_B_C_raw)) {
LOG(ERROR) << "Unable to get extrinsic transformation T_B_C for camera " << camera_index;
return true;
}
// This call will fail hard if the matrix is not a rotation matrix.
aslam::Quaternion q_B_C = aslam::Quaternion(
static_cast<Eigen::Matrix3d>(T_B_C_raw.block<3,3>(0,0)));
aslam::Transformation T_B_C(q_B_C, T_B_C_raw.block<3,1>(0,3));
// Fill in the data in the ncamera.
cameras.push_back(camera);//在这里逆了一下
T_Ci_B.push_back(T_B_C.inverse());
}
// Create the ncamera and fill in all the data.
ncamera.reset(new aslam::NCamera(ncam_id, T_Ci_B, cameras, label));
} catch (const std::exception& ex) {
LOG(ERROR) << "Yaml exception during parsing: " << ex.what();
ncamera.reset();
return true;
}
return true;
}
Node convert<std::shared_ptr<aslam::NCamera> >::encode(
const std::shared_ptr<aslam::NCamera>& ncamera) {
return convert<aslam::NCamera>::encode(*CHECK_NOTNULL(ncamera.get()));
}
bool convert<aslam::NCamera>::decode(const Node& /*node*/, aslam::NCamera& /*ncamera*/) {
LOG(FATAL) << "Not implemented!";
return false;
}
Node convert<aslam::NCamera>::encode(const aslam::NCamera& ncamera) {
Node ncamera_node;
ncamera_node["label"] = ncamera.getLabel();
if(ncamera.getId().isValid()) {
ncamera_node["id"] = ncamera.getId().hexString();
}
Node cameras_node;
size_t num_cameras = ncamera.numCameras();
for (size_t camera_index = 0; camera_index < num_cameras; ++camera_index) {
Node camera_node;
camera_node["camera"] = ncamera.getCamera(camera_index);
camera_node["T_B_C"] = ncamera.get_T_C_B(camera_index).inverse().getTransformationMatrix();
cameras_node.push_back(camera_node);
}
ncamera_node["cameras"] = cameras_node;
return ncamera_node;
}
} // namespace YAML
|
/*
* Copyright (c) 2014, Matias Fontanini
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <stdexcept>
#include <sstream>
#include <memory>
#include <cassert>
#include <cstring>
#include "utils.h"
#ifndef WIN32
#if defined(BSD) || defined(__FreeBSD_kernel__)
#include <sys/socket.h>
#include <netinet/in.h>
#include <net/if_dl.h>
#else
#include <netpacket/packet.h>
#endif
#include <netdb.h>
#include <net/if.h>
#else
#include <ws2tcpip.h>
#endif
#include "pdu.h"
#include "arp.h"
#include "ethernetII.h"
#include "endianness.h"
#include "network_interface.h"
#include "packet_sender.h"
#include "cxxstd.h"
using namespace std;
/** \cond */
struct InterfaceCollector {
set<string> ifaces;
#ifdef WIN32
bool operator() (PIP_ADAPTER_ADDRESSES addr) {
ifaces.insert(addr->AdapterName);
return false;
}
#else
bool operator() (struct ifaddrs *addr) {
ifaces.insert(addr->ifa_name);
return false;
}
#endif
};
addrinfo *resolve_domain(const std::string &to_resolve, int family) {
addrinfo *result, hints = addrinfo();
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_family = family;
if(!getaddrinfo(to_resolve.c_str(), 0, &hints, &result))
return result;
else {
throw std::runtime_error("Could not resolve address");
}
}
namespace Tins {
/** \endcond */
namespace Utils {
IPv4Address resolve_domain(const std::string &to_resolve) {
addrinfo *result = ::resolve_domain(to_resolve, AF_INET);
IPv4Address addr(((sockaddr_in*)result->ai_addr)->sin_addr.s_addr);
freeaddrinfo(result);
return addr;
}
IPv6Address resolve_domain6(const std::string &to_resolve) {
addrinfo *result = ::resolve_domain(to_resolve, AF_INET6);
IPv6Address addr((const uint8_t*)&((sockaddr_in6*)result->ai_addr)->sin6_addr);
freeaddrinfo(result);
return addr;
}
HWAddress<6> resolve_hwaddr(const NetworkInterface &iface, IPv4Address ip, PacketSender &sender)
{
IPv4Address my_ip;
NetworkInterface::Info info(iface.addresses());
EthernetII packet = ARP::make_arp_request(ip, info.ip_addr, info.hw_addr);
Internals::smart_ptr<PDU>::type response(sender.send_recv(packet, iface));
if(response.get()) {
const ARP *arp_resp = response->find_pdu<ARP>();
if(arp_resp)
return arp_resp->sender_hw_addr();
}
throw std::runtime_error("Could not resolve hardware address");
}
HWAddress<6> resolve_hwaddr(IPv4Address ip, PacketSender &sender) {
return resolve_hwaddr(sender.default_interface(), ip, sender);
}
std::vector<RouteEntry> route_entries() {
std::vector<RouteEntry> entries;
route_entries(std::back_inserter(entries));
return entries;
}
bool gateway_from_ip(IPv4Address ip, IPv4Address &gw_addr) {
typedef std::vector<RouteEntry> entries_type;
entries_type entries;
uint32_t ip_int = ip;
route_entries(std::back_inserter(entries));
for(entries_type::const_iterator it(entries.begin()); it != entries.end(); ++it) {
if((ip_int & it->mask) == it->destination) {
gw_addr = it->gateway;
return true;
}
}
return false;
}
set<string> network_interfaces() {
InterfaceCollector collector;
generic_iface_loop(collector);
return collector.ifaces;
}
uint16_t channel_to_mhz(uint16_t channel) {
return 2407 + (channel * 5);
}
uint16_t mhz_to_channel(uint16_t mhz) {
return (mhz - 2407) / 5;
}
std::string to_string(PDU::PDUType pduType) {
#define ENUM_TEXT(p) case(PDU::p): return #p;
switch(pduType){
ENUM_TEXT(RAW);
ENUM_TEXT(ETHERNET_II);
ENUM_TEXT(IEEE802_3);
ENUM_TEXT(RADIOTAP);
ENUM_TEXT(DOT11);
ENUM_TEXT(DOT11_ACK);
ENUM_TEXT(DOT11_ASSOC_REQ);
ENUM_TEXT(DOT11_ASSOC_RESP);
ENUM_TEXT(DOT11_AUTH);
ENUM_TEXT(DOT11_BEACON);
ENUM_TEXT(DOT11_BLOCK_ACK);
ENUM_TEXT(DOT11_BLOCK_ACK_REQ);
ENUM_TEXT(DOT11_CF_END);
ENUM_TEXT(DOT11_DATA);
ENUM_TEXT(DOT11_CONTROL);
ENUM_TEXT(DOT11_DEAUTH);
ENUM_TEXT(DOT11_DIASSOC);
ENUM_TEXT(DOT11_END_CF_ACK);
ENUM_TEXT(DOT11_MANAGEMENT);
ENUM_TEXT(DOT11_PROBE_REQ);
ENUM_TEXT(DOT11_PROBE_RESP);
ENUM_TEXT(DOT11_PS_POLL);
ENUM_TEXT(DOT11_REASSOC_REQ);
ENUM_TEXT(DOT11_REASSOC_RESP);
ENUM_TEXT(DOT11_RTS);
ENUM_TEXT(DOT11_QOS_DATA);
ENUM_TEXT(LLC);
ENUM_TEXT(SNAP);
ENUM_TEXT(IP);
ENUM_TEXT(ARP);
ENUM_TEXT(TCP);
ENUM_TEXT(UDP);
ENUM_TEXT(ICMP);
ENUM_TEXT(BOOTP);
ENUM_TEXT(DHCP);
ENUM_TEXT(EAPOL);
ENUM_TEXT(RC4EAPOL);
ENUM_TEXT(RSNEAPOL);
ENUM_TEXT(DNS);
ENUM_TEXT(LOOPBACK);
ENUM_TEXT(IPv6);
ENUM_TEXT(ICMPv6);
ENUM_TEXT(SLL);
ENUM_TEXT(DHCPv6);
ENUM_TEXT(DOT1Q);
ENUM_TEXT(PPPOE);
ENUM_TEXT(STP);
ENUM_TEXT(PPI);
ENUM_TEXT(IPSEC_AH);
ENUM_TEXT(IPSEC_ESP);
ENUM_TEXT(USER_DEFINED_PDU);
default: return "";
}
#undef ENUM_TEXT
}
uint32_t do_checksum(const uint8_t *start, const uint8_t *end) {
uint32_t checksum(0);
uint16_t *ptr = (uint16_t*)start, *last = (uint16_t*)end, padding(0);
if(((end - start) & 1) == 1) {
last = (uint16_t*)end - 1;
padding = *(end - 1) << 8;
}
while(ptr < last)
checksum += Endian::host_to_be(*(ptr++));
return checksum + padding;
}
uint32_t pseudoheader_checksum(IPv4Address source_ip, IPv4Address dest_ip, uint32_t len, uint32_t flag) {
uint32_t checksum(0);
uint32_t source_ip_int = Endian::host_to_be<uint32_t>(source_ip),
dest_ip_int = Endian::host_to_be<uint32_t>(dest_ip);
char buffer[sizeof(uint32_t) * 2];
uint16_t *ptr = (uint16_t*)buffer, *end = (uint16_t*)(buffer + sizeof(buffer));
std::memcpy(buffer, &source_ip_int, sizeof(source_ip_int));
std::memcpy(buffer + sizeof(uint32_t), &dest_ip_int, sizeof(dest_ip_int));
while(ptr < end)
checksum += (uint32_t)*ptr++;
checksum += flag + len;
return checksum;
}
uint32_t pseudoheader_checksum(IPv6Address source_ip, IPv6Address dest_ip, uint32_t len, uint32_t flag) {
uint32_t checksum(0);
uint16_t *ptr = (uint16_t*) source_ip.begin();
uint16_t *end = (uint16_t*) source_ip.end();
while(ptr < end)
checksum += (uint32_t) Endian::be_to_host(*ptr++);
ptr = (uint16_t*) dest_ip.begin();
end = (uint16_t*) dest_ip.end();
while(ptr < end)
checksum += (uint32_t) Endian::be_to_host(*ptr++);
checksum += flag + len;
return checksum;
}
uint32_t crc32(const uint8_t* data, uint32_t data_size) {
uint32_t i, crc = 0;
static uint32_t crc_table[] = {
0x4DBDF21C, 0x500AE278, 0x76D3D2D4, 0x6B64C2B0,
0x3B61B38C, 0x26D6A3E8, 0x000F9344, 0x1DB88320,
0xA005713C, 0xBDB26158, 0x9B6B51F4, 0x86DC4190,
0xD6D930AC, 0xCB6E20C8, 0xEDB71064, 0xF0000000
};
for (i = 0; i < data_size; ++i) {
crc = (crc >> 4) ^ crc_table[(crc ^ data[i]) & 0x0F];
crc = (crc >> 4) ^ crc_table[(crc ^ (data[i] >> 4)) & 0x0F];
}
return crc;
}
}
}
|
#include <iostream>
#include "LinkedList.h"
#include <iterator>
#include <string>
bool compare(std::string s1, std::string s2){
if ((s1.length() == s2.length()) || (s1.length() > s2.length())){
return false; // For some reason >= is not working in isSorted method
}
return true;
}
int main() {
int n{5};
// double proxy{0};
// double array[] = {1.0050,20.350,3.302,40.254,5.90,1.2,0.08,.3,0.000001,6.5};
std::string array[] = {
"I am Anik Saha",
"I am anik",
"I am Roni Saha",
"I am anik kumar Saha",
"LinkedList<double> myList;"
};
// LinkedList<double> myList;
// LinkedList<double> myList(array,array+n);
LinkedList<std::string> myList(array,array+n);
myList.display();
// LinkedList otherList(myList);
// otherList.display();
//
// myList.insert(69,4);
// myList.atNext() += 50;
// std::cout << myList.atNext() << std::endl;
// myList.atPrevious() += 50;
// std::cout << myList.atPrevious() << std::endl;
// myList.pointAt(3);
// std::cout << myList.atNext() << std::endl;
//
// myList.getCurrentData() = 1000;
// std::cout << myList.getCurrentData() << std::endl;
// if (myList.isSorted()){
// std::cout << "List is sorted" << std::endl;
// } else{
// std::cout << "List is NOT sorted" << std::endl;
// }
//
// myList.sort();
//
// if (myList.isSorted()){
// std::cout << "List is sorted" << std::endl;
// } else{
// std::cout << "List is NOT sorted" << std::endl;
// }
if (myList.isSorted(compare)){
std::cout << "List is sorted" << std::endl;
} else{
std::cout << "List is NOT sorted" << std::endl;
}
myList.sort(compare);
if (myList.isSorted(compare)){
std::cout << "List is sorted" << std::endl;
} else{
std::cout << "List is NOT sorted" << std::endl;
}
//
// myList.display();
//
// myList.remove(4);
// myList.display();
//
// std::cout << myList.findAndRemove(.08) << std::endl;
// std::cout << myList.count(50) << std::endl;
//
// std::cout << myList.min() << std::endl;
// std::cout << myList.max() << std::endl;
//
// std::cout << myList.getFront() << std::endl;
// std::cout << myList.getBack() << std::endl;
// std::cout << myList.popAndGetFront() << std::endl;
// std::cout << myList.popAndGetBack() << std::endl;
//
// myList.display();
// myList.popFront();
// myList.popBack();
// myList.popBack();
//
// std::cout << myList.getSize() << std::endl;
//
//
// myList.at(4) += 2;
// std::cout<<myList.at(4)<<std::endl;
//
// for(int i = 0; i < n; i++){
// std::cin >> proxy;
// myList.pushFront(proxy);
// }
myList.display();
return 0;
}
|
/*
* Copyright (c) 2019 Michael Mathers
*/
#include <penguin/Timer.h>
#include <iostream>
#include <thread>
#include <type_traits>
namespace
{
bool test_basic_timer_ms(void)
{
Penguin::Timer<unsigned long long, std::milli> timer;
unsigned long long intermediate_split;
timer.start();
std::this_thread::sleep_for(std::chrono::seconds(1));
intermediate_split = timer.get_current_duration();
std::cout << "Slept for " << intermediate_split << "ms so far.\n";
std::this_thread::sleep_for(std::chrono::seconds(1));
intermediate_split = timer.get_current_duration();
std::cout << "Slept for " << intermediate_split << "ms so far.\n";
std::this_thread::sleep_for(std::chrono::seconds(1));
timer.stop();
std::cout << "Slept for " << timer.get_finish_duration() << "ms in total.\n";
return true;
}
bool test_basic_timer_us(void)
{
Penguin::Timer<unsigned long long, std::micro> timer;
unsigned long long intermediate_split;
timer.start();
std::this_thread::sleep_for(std::chrono::seconds(1));
intermediate_split = timer.get_current_duration();
std::cout << "Slept for " << intermediate_split << "us so far.\n";
std::this_thread::sleep_for(std::chrono::seconds(1));
intermediate_split = timer.get_current_duration();
std::cout << "Slept for " << intermediate_split << "us so far.\n";
std::this_thread::sleep_for(std::chrono::seconds(1));
timer.stop();
std::cout << "Slept for " << timer.get_finish_duration() << "us in total.\n";
return true;
}
}
int main(int argc, char *argv[])
{
std::cout << "Test_Timer" << std::endl;
bool tests_passed = true;
tests_passed &= test_basic_timer_ms();
tests_passed &= test_basic_timer_us();
return (tests_passed ? 0 : -1);
}
|
/*******************************************************************************
* Copyright 2019 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#ifndef COMPUTE_KERNEL_CTX_HPP
#define COMPUTE_KERNEL_CTX_HPP
#include <cassert>
#ifdef DEBUG_PRINT
#include <iostream>
#endif
#include <map>
#include <set>
#include <sstream>
#include <string>
#include <type_traits>
namespace dnnl {
namespace impl {
namespace compute {
class kernel_ctx_t {
public:
kernel_ctx_t() { set_default_options(); }
std::string options() const {
std::ostringstream oss;
for (auto &opt : option_set_)
oss << " " << opt;
for (auto &int_var : int_var_map_)
oss << " -D" << int_var.first << "=" << int_var.second;
for (auto &float_var : float_var_map_) {
union {
float f;
uint32_t u;
} f2u = {float_var.second};
oss << " -D" << float_var.first << "=as_float(0x" << std::hex
<< f2u.u << ")";
}
return oss.str();
}
void define_int(const char *variable, int64_t value) {
int_var_map_.insert({variable, value});
}
void define_int(const std::string &variable, int64_t value) {
define_int(variable.c_str(), value);
}
// TODO: should be removed, any float values should be passed in
// kernel parameters
void define_float(const char *variable, float value) {
float_var_map_.insert({variable, value});
}
void add_option(const char *option) { option_set_.insert(option); }
void add_option(const std::string &option) { add_option(option.c_str()); }
bool has_macro(const char *name) const {
std::string opt_start = std::string("-D") + name + "=";
for (auto &opt : option_set_)
if (opt.find(opt_start) != std::string::npos) return true;
return int_var_map_.count(name) != 0 || float_var_map_.count(name) != 0;
}
bool has_macro(const std::string &name) const {
return has_macro(name.c_str());
}
void set_data_type(data_type_t dt) {
switch (dt) {
case data_type::bf16: define_int("DT_BF16", 1); break;
case data_type::f16: define_int("DT_F16", 1); break;
case data_type::f32: define_int("DT_F32", 1); break;
case data_type::s8: define_int("DT_S8", 1); break;
case data_type::u8: define_int("DT_U8", 1); break;
case data_type::s32: define_int("DT_S32", 1); break;
default: assert(!"unknown data type"); break;
}
}
void print_options() const {
#ifdef DEBUG_PRINT
std::cout << "OPT:\n" << options() << std::endl;
#endif
}
template <typename T>
T get_scalar(const std::string &s) const {
UNUSED(s);
static_assert(!std::is_same<T, T>::value, "not expected");
return {};
}
std::string data_type() const {
if (int_var_map_.count("DT_F16") != 0) return "f16";
if (int_var_map_.count("DT_F32") != 0) return "f32";
if (int_var_map_.count("DT_S8") != 0) return "s8";
return "";
}
private:
void set_default_options() {
// By default fp32 division and sqrt are not IEEE-compliant
add_option("-cl-fp32-correctly-rounded-divide-sqrt");
}
std::map<std::string, int64_t> int_var_map_;
std::map<std::string, float> float_var_map_;
std::set<std::string> option_set_;
};
template <>
inline int64_t kernel_ctx_t::get_scalar(const std::string &name) const {
assert(int_var_map_.count(name) != 0 && "not expected");
return int_var_map_.at(name);
}
} // namespace compute
} // namespace impl
} // namespace dnnl
#endif // COMPUTE_KERNEL_CTX_HPP
|
//------------------------------------------------------------------------------
/*
This file is part of rippled: https://github.com/ripple/rippled
Copyright (c) 2012, 2013 Ripple Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#include <BeastConfig.h>
#include <ripple/app/ledger/InboundLedgers.h>
#include <ripple/app/ledger/LedgerMaster.h>
#include <ripple/app/ledger/LedgerTiming.h>
#include <ripple/app/ledger/LedgerToJson.h>
#include <ripple/app/ledger/OpenLedger.h>
#include <ripple/app/ledger/impl/DisputedTx.h>
#include <ripple/app/ledger/impl/LedgerConsensusImp.h>
#include <ripple/app/main/Application.h>
#include <ripple/app/misc/AmendmentTable.h>
#include <ripple/app/misc/CanonicalTXSet.h>
#include <ripple/app/misc/IHashRouter.h>
#include <ripple/app/misc/NetworkOPs.h>
#include <ripple/app/misc/Validations.h>
#include <ripple/app/tx/TransactionAcquire.h>
#include <ripple/app/tx/apply.h>
#include <ripple/basics/CountedObject.h>
#include <ripple/basics/Log.h>
#include <ripple/core/Config.h>
#include <ripple/core/JobQueue.h>
#include <ripple/core/LoadFeeTrack.h>
#include <ripple/json/to_string.h>
#include <ripple/overlay/Overlay.h>
#include <ripple/overlay/predicates.h>
#include <ripple/protocol/STValidation.h>
#include <ripple/protocol/UintTypes.h>
#include <beast/module/core/text/LexicalCast.h>
#include <beast/utility/make_lock.h>
#include <type_traits>
namespace ripple {
/** Determines whether the current ledger should close at this time.
This function should be called when a ledger is open and there is no close
in progress, or when a transaction is received and no close is in progress.
@param anyTransactions indicates whether any transactions have been received
@param previousProposers proposers in the last closing
@param proposersClosed proposers who have currently closed this ledger
@param proposersValidated proposers who have validated the last closed ledger
@param previousMSeconds time, in milliseconds, for the previous ledger to
reach consensus (in milliseconds)
@param currentMSeconds time, in milliseconds since the previous ledger closed
@param openMSeconds time, in milliseconds, since the previous LCL was computed
@param idleInterval the network's desired idle interval
*/
bool shouldCloseLedger (
bool anyTransactions,
int previousProposers,
int proposersClosed,
int proposersValidated,
int previousMSeconds,
int currentMSeconds,
int openMSeconds,
int idleInterval)
{
if ((previousMSeconds < -1000) || (previousMSeconds > 600000) ||
(currentMSeconds < -1000) || (currentMSeconds > 600000))
{
WriteLog (lsWARNING, LedgerTiming) <<
"shouldCloseLedger Trans=" << (anyTransactions ? "yes" : "no") <<
" Prop: " << previousProposers << "/" << proposersClosed <<
" Secs: " << currentMSeconds << " (last: " << previousMSeconds << ")";
return true;
}
if (!anyTransactions)
{
// did we miss a transaction?
if (proposersClosed > (previousProposers / 4))
{
WriteLog (lsTRACE, LedgerTiming) <<
"no transactions, many proposers: now (" << proposersClosed <<
" closed, " << previousProposers << " before)";
return true;
}
// Only close if we have idled for too long.
return currentMSeconds >= (idleInterval * 1000); // normal idle
}
// If we have any transactions, we don't want to close too frequently:
if (openMSeconds < LEDGER_MIN_CLOSE)
{
if ((proposersClosed + proposersValidated) < (previousProposers / 2 ))
{
WriteLog (lsDEBUG, LedgerTiming) <<
"Must wait minimum time before closing";
return false;
}
}
if (currentMSeconds < previousMSeconds)
{
if ((proposersClosed + proposersValidated) < previousProposers)
{
WriteLog (lsDEBUG, LedgerTiming) <<
"We are waiting for more closes/validations";
return false;
}
}
return true;
}
bool
checkConsensusReached (int agreeing, int proposing)
{
int currentPercentage = (agreeing * 100) / (proposing + 1);
return currentPercentage > minimumConsensusPercentage;
}
/** What state the consensus process is on. */
enum class ConsensusState
{
No, // We do not have consensus
MovedOn, // The network has consensus without us
Yes // We have consensus along with the network
};
/** Determine whether the network reached consensus and whether we joined.
@param previousProposers proposers in the last closing (not including us)
@param currentProposers proposers in this closing so far (not including us)
@param currentAgree proposers who agree with us
@param currentFinished proposers who have validated a ledger after this one
@param previousAgreeTime how long, in milliseconds, it took to agree on the
last ledger
@param currentAgreeTime how long, in milliseconds, we've been trying to agree
*/
ConsensusState checkConsensus (
int previousProposers,
int currentProposers,
int currentAgree,
int currentFinished,
int previousAgreeTime,
int currentAgreeTime)
{
WriteLog (lsTRACE, LedgerTiming) <<
"checkConsensus: prop=" << currentProposers <<
"/" << previousProposers <<
" agree=" << currentAgree << " validated=" << currentFinished <<
" time=" << currentAgreeTime << "/" << previousAgreeTime;
if (currentAgreeTime <= LEDGER_MIN_CONSENSUS)
return ConsensusState::No;
if (currentProposers < (previousProposers * 3 / 4))
{
// Less than 3/4 of the last ledger's proposers are present; don't
// rush: we may need more time.
if (currentAgreeTime < (previousAgreeTime + LEDGER_MIN_CONSENSUS))
{
WriteLog (lsTRACE, LedgerTiming) <<
"too fast, not enough proposers";
return ConsensusState::No;
}
}
// Have we, together with the nodes on our UNL list, reached the treshold
// to declare consensus?
if (checkConsensusReached (currentAgree + 1, currentProposers))
{
WriteLog (lsDEBUG, LedgerTiming) << "normal consensus";
return ConsensusState::Yes;
}
// Have sufficient nodes on our UNL list moved on and reached the threshold
// to declare consensus?
if (checkConsensusReached (currentFinished, currentProposers))
{
WriteLog (lsWARNING, LedgerTiming) <<
"We see no consensus, but 80% of nodes have moved on";
return ConsensusState::MovedOn;
}
// no consensus yet
WriteLog (lsTRACE, LedgerTiming) << "no consensus";
return ConsensusState::No;
}
LedgerConsensusImp::LedgerConsensusImp (
ConsensusImp& consensus,
int previousProposers,
int previousConvergeTime,
InboundTransactions& inboundTransactions,
LocalTxs& localtx,
LedgerMaster& ledgerMaster,
LedgerHash const & prevLCLHash,
Ledger::ref previousLedger,
std::uint32_t closeTime,
FeeVote& feeVote)
: consensus_ (consensus)
, inboundTransactions_ (inboundTransactions)
, m_localTX (localtx)
, ledgerMaster_ (ledgerMaster)
, m_feeVote (feeVote)
, state_ (State::open)
, mCloseTime (closeTime)
, mPrevLedgerHash (prevLCLHash)
, mPreviousLedger (previousLedger)
, mValPublic (getConfig ().VALIDATION_PUB)
, mValPrivate (getConfig ().VALIDATION_PRIV)
, mConsensusFail (false)
, mCurrentMSeconds (0)
, mClosePercent (0)
, mHaveCloseTimeConsensus (false)
, mConsensusStartTime (std::chrono::steady_clock::now ())
, mPreviousProposers (previousProposers)
, mPreviousMSeconds (previousConvergeTime)
{
WriteLog (lsDEBUG, LedgerConsensus) << "Creating consensus object";
WriteLog (lsTRACE, LedgerConsensus)
<< "LCL:" << previousLedger->getHash () << ", ct=" << closeTime;
assert (mPreviousMSeconds);
inboundTransactions_.newRound (mPreviousLedger->info().seq);
// Adapt close time resolution to recent network conditions
mCloseResolution = getNextLedgerTimeResolution (
mPreviousLedger->info().closeTimeResolution,
getCloseAgree (mPreviousLedger->info()),
mPreviousLedger->info().seq + 1);
if (mValPublic.isSet () && mValPrivate.isSet ()
&& !getApp().getOPs ().isNeedNetworkLedger ())
{
// If the validation keys were set, and if we need a ledger,
// then we want to validate, and possibly propose a ledger.
WriteLog (lsINFO, LedgerConsensus)
<< "Entering consensus process, validating";
mValidating = true;
// Propose if we are in sync with the network
mProposing =
getApp().getOPs ().getOperatingMode () == NetworkOPs::omFULL;
}
else
{
// Otherwise we just want to monitor the validation process.
WriteLog (lsINFO, LedgerConsensus)
<< "Entering consensus process, watching";
mProposing = mValidating = false;
}
mHaveCorrectLCL = (mPreviousLedger->getHash () == mPrevLedgerHash);
if (!mHaveCorrectLCL)
{
// If we were not handed the correct LCL, then set our state
// to not proposing.
consensus_.setProposing (false, false);
handleLCL (mPrevLedgerHash);
if (!mHaveCorrectLCL)
{
// mProposing = mValidating = false;
WriteLog (lsINFO, LedgerConsensus)
<< "Entering consensus with: "
<< previousLedger->getHash ();
WriteLog (lsINFO, LedgerConsensus)
<< "Correct LCL is: " << prevLCLHash;
}
}
else // update the network status table as to whether we're proposing/validating
consensus_.setProposing (mProposing, mValidating);
}
Json::Value LedgerConsensusImp::getJson (bool full)
{
Json::Value ret (Json::objectValue);
ret["proposing"] = mProposing;
ret["validating"] = mValidating;
ret["proposers"] = static_cast<int> (mPeerPositions.size ());
if (mHaveCorrectLCL)
{
ret["synched"] = true;
ret["ledger_seq"] = mPreviousLedger->info().seq + 1;
ret["close_granularity"] = mCloseResolution;
}
else
ret["synched"] = false;
switch (state_)
{
case State::open:
ret[jss::state] = "open";
break;
case State::establish:
ret[jss::state] = "consensus";
break;
case State::finished:
ret[jss::state] = "finished";
break;
case State::accepted:
ret[jss::state] = "accepted";
break;
}
int v = mDisputes.size ();
if ((v != 0) && !full)
ret["disputes"] = v;
if (mOurPosition)
ret["our_position"] = mOurPosition->getJson ();
if (full)
{
ret["current_ms"] = mCurrentMSeconds;
ret["close_percent"] = mClosePercent;
ret["close_resolution"] = mCloseResolution;
ret["have_time_consensus"] = mHaveCloseTimeConsensus;
ret["previous_proposers"] = mPreviousProposers;
ret["previous_mseconds"] = mPreviousMSeconds;
if (!mPeerPositions.empty ())
{
Json::Value ppj (Json::objectValue);
for (auto& pp : mPeerPositions)
{
ppj[to_string (pp.first)] = pp.second->getJson ();
}
ret["peer_positions"] = ppj;
}
if (!mAcquired.empty ())
{
// acquired
Json::Value acq (Json::objectValue);
for (auto& at : mAcquired)
{
if (at.second)
acq[to_string (at.first)] = "acquired";
else
acq[to_string (at.first)] = "failed";
}
ret["acquired"] = acq;
}
if (!mDisputes.empty ())
{
Json::Value dsj (Json::objectValue);
for (auto& dt : mDisputes)
{
dsj[to_string (dt.first)] = dt.second->getJson ();
}
ret["disputes"] = dsj;
}
if (!mCloseTimes.empty ())
{
Json::Value ctj (Json::objectValue);
for (auto& ct : mCloseTimes)
{
ctj[beast::lexicalCastThrow <std::string> (ct.first)] = ct.second;
}
ret["close_times"] = ctj;
}
if (!mDeadNodes.empty ())
{
Json::Value dnj (Json::arrayValue);
for (auto const& dn : mDeadNodes)
{
dnj.append (to_string (dn));
}
ret["dead_nodes"] = dnj;
}
}
return ret;
}
uint256 LedgerConsensusImp::getLCL ()
{
return mPrevLedgerHash;
}
void LedgerConsensusImp::mapCompleteInternal (
uint256 const& hash,
std::shared_ptr<SHAMap> const& map,
bool acquired)
{
CondLog (acquired, lsDEBUG, LedgerConsensus)
<< "We have acquired TXS " << hash;
if (!map) // If the map was invalid
{
// this is an invalid/corrupt map
mAcquired[hash] = map;
WriteLog (lsWARNING, LedgerConsensus)
<< "A trusted node directed us to acquire an invalid TXN map";
return;
}
assert (hash == map->getHash ());
auto it = mAcquired.find (hash);
// If we have already acquired this transaction set
if (mAcquired.find (hash) != mAcquired.end ())
{
if (it->second)
{
return; // we already have this map
}
// We previously failed to acquire this map, now we have it
mAcquired.erase (hash);
}
// We now have a map that we did not have before
if (!acquired)
{
// Put the map where others can get it
inboundTransactions_.giveSet (hash, map, false);
}
// Inform directly-connected peers that we have this transaction set
sendHaveTxSet (hash, true);
if (mOurPosition && (!mOurPosition->isBowOut ())
&& (hash != mOurPosition->getCurrentHash ()))
{
// this will create disputed transactions
auto it2 = mAcquired.find (mOurPosition->getCurrentHash ());
if (it2 != mAcquired.end ())
{
assert ((it2->first == mOurPosition->getCurrentHash ())
&& it2->second);
mCompares.insert(hash);
// Our position is not the same as the acquired position
createDisputes (it2->second, map);
}
else
assert (false); // We don't have our own position?!
}
else
WriteLog (lsDEBUG, LedgerConsensus)
<< "Not ready to create disputes";
mAcquired[hash] = map;
// Adjust tracking for each peer that takes this position
std::vector<NodeID> peers;
for (auto& it : mPeerPositions)
{
if (it.second->getCurrentHash () == map->getHash ())
peers.push_back (it.second->getPeerID ());
}
if (!peers.empty ())
{
adjustCount (map, peers);
}
else
{
CondLog (acquired, lsWARNING, LedgerConsensus)
<< "By the time we got the map "
<< hash << " no peers were proposing it";
}
}
void LedgerConsensusImp::mapComplete (
uint256 const& hash,
std::shared_ptr<SHAMap> const& map,
bool acquired)
{
try
{
mapCompleteInternal (hash, map, acquired);
}
catch (SHAMapMissingNode const& mn)
{
leaveConsensus();
WriteLog (lsERROR, LedgerConsensus) <<
"Missing node processing complete map " << mn;
throw;
}
}
void LedgerConsensusImp::checkLCL ()
{
uint256 netLgr = mPrevLedgerHash;
int netLgrCount = 0;
uint256 favoredLedger = mPrevLedgerHash; // Don't jump forward
uint256 priorLedger;
if (mHaveCorrectLCL)
priorLedger = mPreviousLedger->info().parentHash; // don't jump back
// Get validators that are on our ledger, or "close" to being on
// our ledger.
hash_map<uint256, ValidationCounter> vals =
getApp().getValidations ().getCurrentValidations
(favoredLedger, priorLedger);
for (auto& it : vals)
{
if ((it.second.first > netLgrCount) ||
((it.second.first == netLgrCount) && (it.first == mPrevLedgerHash)))
{
netLgr = it.first;
netLgrCount = it.second.first;
}
}
if (netLgr != mPrevLedgerHash)
{
// LCL change
const char* status;
switch (state_)
{
case State::open:
status = "open";
break;
case State::establish:
status = "establish";
break;
case State::finished:
status = "finished";
break;
case State::accepted:
status = "accepted";
break;
default:
status = "unknown";
}
WriteLog (lsWARNING, LedgerConsensus)
<< "View of consensus changed during " << status
<< " (" << netLgrCount << ") status="
<< status << ", "
<< (mHaveCorrectLCL ? "CorrectLCL" : "IncorrectLCL");
WriteLog (lsWARNING, LedgerConsensus) << mPrevLedgerHash
<< " to " << netLgr;
WriteLog (lsWARNING, LedgerConsensus)
<< ripple::getJson (*mPreviousLedger);
if (ShouldLog (lsDEBUG, LedgerConsensus))
{
for (auto& it : vals)
{
WriteLog (lsDEBUG, LedgerConsensus)
<< "V: " << it.first << ", " << it.second.first;
}
}
if (mHaveCorrectLCL)
getApp().getOPs ().consensusViewChange ();
handleLCL (netLgr);
}
else if (mPreviousLedger->getHash () != mPrevLedgerHash)
handleLCL (netLgr);
}
void LedgerConsensusImp::handleLCL (uint256 const& lclHash)
{
assert ((lclHash != mPrevLedgerHash) || (mPreviousLedger->getHash () != lclHash));
if (mPrevLedgerHash != lclHash)
{
// first time switching to this ledger
mPrevLedgerHash = lclHash;
if (mHaveCorrectLCL && mProposing && mOurPosition)
{
WriteLog (lsINFO, LedgerConsensus) << "Bowing out of consensus";
mOurPosition->bowOut ();
propose ();
}
// Stop proposing because we are out of sync
mProposing = false;
mPeerPositions.clear ();
mDisputes.clear ();
mCloseTimes.clear ();
mDeadNodes.clear ();
// To get back in sync:
playbackProposals ();
}
if (mPreviousLedger->getHash () == mPrevLedgerHash)
return;
// we need to switch the ledger we're working from
auto newLCL = ledgerMaster_.getLedgerByHash (mPrevLedgerHash);
if (!newLCL)
{
if (mAcquiringLedger != lclHash)
{
// need to start acquiring the correct consensus LCL
WriteLog (lsWARNING, LedgerConsensus) <<
"Need consensus ledger " << mPrevLedgerHash;
// Tell the ledger acquire system that we need the consensus ledger
mAcquiringLedger = mPrevLedgerHash;
getApp().getJobQueue().addJob (jtADVANCE, "getConsensusLedger",
std::bind (
&InboundLedgers::acquire,
&getApp().getInboundLedgers(),
mPrevLedgerHash, 0, InboundLedger::fcCONSENSUS));
mHaveCorrectLCL = false;
}
return;
}
assert (!newLCL->info().open && newLCL->isImmutable ());
assert (newLCL->getHash () == lclHash);
mPreviousLedger = newLCL;
mPrevLedgerHash = lclHash;
WriteLog (lsINFO, LedgerConsensus) <<
"Have the consensus ledger " << mPrevLedgerHash;
mHaveCorrectLCL = true;
mCloseResolution = getNextLedgerTimeResolution (
mPreviousLedger->info().closeTimeResolution,
getCloseAgree(mPreviousLedger->info()),
mPreviousLedger->info().seq + 1);
}
void LedgerConsensusImp::timerEntry ()
{
try
{
if ((state_ != State::finished) && (state_ != State::accepted))
checkLCL ();
mCurrentMSeconds = std::chrono::duration_cast <std::chrono::milliseconds>
(std::chrono::steady_clock::now() - mConsensusStartTime).count ();
mClosePercent = mCurrentMSeconds * 100 / mPreviousMSeconds;
switch (state_)
{
case State::open:
statePreClose ();
return;
case State::establish:
stateEstablish ();
if (state_ != State::finished) return;
// Fall through
case State::finished:
stateFinished ();
if (state_ != State::accepted) return;
// Fall through
case State::accepted:
stateAccepted ();
return;
}
assert (false);
}
catch (SHAMapMissingNode const& mn)
{
leaveConsensus ();
WriteLog (lsERROR, LedgerConsensus) <<
"Missing node during consensus process " << mn;
throw;
}
}
void LedgerConsensusImp::statePreClose ()
{
// it is shortly before ledger close time
bool anyTransactions = ledgerMaster_.getCurrentLedger ()
->txMap ().getHash ().isNonZero ();
int proposersClosed = mPeerPositions.size ();
int proposersValidated
= getApp().getValidations ().getTrustedValidationCount
(mPrevLedgerHash);
// This ledger is open. This computes how long since last ledger closed
int sinceClose;
int idleInterval = 0;
if (mHaveCorrectLCL && getCloseAgree(mPreviousLedger->info()))
{
// we can use consensus timing
sinceClose = 1000 * (getApp().getOPs ().getCloseTimeNC ()
- mPreviousLedger->info().closeTime);
idleInterval = 2 * mPreviousLedger->info().closeTimeResolution;
if (idleInterval < LEDGER_IDLE_INTERVAL)
idleInterval = LEDGER_IDLE_INTERVAL;
}
else
{
// Use the time we saw the last ledger close
sinceClose = 1000 * (getApp().getOPs ().getCloseTimeNC ()
- consensus_.getLastCloseTime ());
idleInterval = LEDGER_IDLE_INTERVAL;
}
idleInterval = std::max (idleInterval, LEDGER_IDLE_INTERVAL);
idleInterval = std::max (idleInterval, 2 * mPreviousLedger->info().closeTimeResolution);
// Decide if we should close the ledger
if (shouldCloseLedger (anyTransactions
, mPreviousProposers, proposersClosed, proposersValidated
, mPreviousMSeconds, sinceClose, mCurrentMSeconds
, idleInterval))
{
closeLedger ();
}
}
void LedgerConsensusImp::stateEstablish ()
{
// Give everyone a chance to take an initial position
if (mCurrentMSeconds < LEDGER_MIN_CONSENSUS)
return;
updateOurPositions ();
// Nothing to do if we don't have consensus.
if (!haveConsensus ())
return;
if (!mHaveCloseTimeConsensus)
{
WriteLog (lsINFO, LedgerConsensus) <<
"We have TX consensus but not CT consensus";
return;
}
WriteLog (lsINFO, LedgerConsensus) <<
"Converge cutoff (" << mPeerPositions.size () << " participants)";
state_ = State::finished;
beginAccept (false);
}
void LedgerConsensusImp::stateFinished ()
{
// we are processing the finished ledger
// logic of calculating next ledger advances us out of this state
// nothing to do
}
void LedgerConsensusImp::stateAccepted ()
{
// we have accepted a new ledger
endConsensus ();
}
bool LedgerConsensusImp::haveConsensus ()
{
// CHECKME: should possibly count unacquired TX sets as disagreeing
int agree = 0, disagree = 0;
uint256 ourPosition = mOurPosition->getCurrentHash ();
// Count number of agreements/disagreements with our position
for (auto& it : mPeerPositions)
{
if (!it.second->isBowOut ())
{
if (it.second->getCurrentHash () == ourPosition)
{
++agree;
}
else
{
WriteLog (lsDEBUG, LedgerConsensus) << to_string (it.first)
<< " has " << to_string (it.second->getCurrentHash ());
++disagree;
if (mCompares.count(it.second->getCurrentHash()) == 0)
{ // Make sure we have generated disputes
uint256 hash = it.second->getCurrentHash();
WriteLog (lsDEBUG, LedgerConsensus)
<< "We have not compared to " << hash;
auto it1 = mAcquired.find (hash);
auto it2 = mAcquired.find(mOurPosition->getCurrentHash ());
if ((it1 != mAcquired.end()) && (it2 != mAcquired.end())
&& (it1->second) && (it2->second))
{
mCompares.insert(hash);
createDisputes(it2->second, it1->second);
}
}
}
}
}
int currentValidations = getApp().getValidations ()
.getNodesAfter (mPrevLedgerHash);
WriteLog (lsDEBUG, LedgerConsensus)
<< "Checking for TX consensus: agree=" << agree
<< ", disagree=" << disagree;
// Determine if we actually have consensus or not
auto ret = checkConsensus (mPreviousProposers, agree + disagree, agree,
currentValidations, mPreviousMSeconds, mCurrentMSeconds);
if (ret == ConsensusState::No)
return false;
// There is consensus, but we need to track if the network moved on
// without us.
if (ret == ConsensusState::MovedOn)
mConsensusFail = true;
else
mConsensusFail = false;
return true;
}
std::shared_ptr<SHAMap> LedgerConsensusImp::getTransactionTree (uint256 const& hash)
{
auto it = mAcquired.find (hash);
if (it != mAcquired.end() && it->second)
return it->second;
auto set = inboundTransactions_.getSet (hash, true);
if (set)
mAcquired[hash] = set;
return set;
}
bool LedgerConsensusImp::peerPosition (LedgerProposal::ref newPosition)
{
auto const peerID = newPosition->getPeerID ();
if (mDeadNodes.find (peerID) != mDeadNodes.end ())
{
WriteLog (lsINFO, LedgerConsensus)
<< "Position from dead node: " << to_string (peerID);
return false;
}
LedgerProposal::pointer& currentPosition = mPeerPositions[peerID];
if (currentPosition)
{
assert (peerID == currentPosition->getPeerID ());
if (newPosition->getProposeSeq ()
<= currentPosition->getProposeSeq ())
{
return false;
}
}
if (newPosition->isBowOut ())
{
WriteLog (lsINFO, LedgerConsensus)
<< "Peer bows out: " << to_string (peerID);
for (auto& it : mDisputes)
it.second->unVote (peerID);
mPeerPositions.erase (peerID);
mDeadNodes.insert (peerID);
return true;
}
if (newPosition->isInitial ())
{
// Record the close time estimate
WriteLog (lsTRACE, LedgerConsensus)
<< "Peer reports close time as "
<< newPosition->getCloseTime ();
++mCloseTimes[newPosition->getCloseTime ()];
}
WriteLog (lsTRACE, LedgerConsensus) << "Processing peer proposal "
<< newPosition->getProposeSeq () << "/"
<< newPosition->getCurrentHash ();
currentPosition = newPosition;
std::shared_ptr<SHAMap> set
= getTransactionTree (newPosition->getCurrentHash ());
if (set)
{
for (auto& it : mDisputes)
it.second->setVote (peerID, set->hasItem (it.first));
}
else
{
WriteLog (lsDEBUG, LedgerConsensus)
<< "Don't have tx set for peer";
}
return true;
}
void LedgerConsensusImp::simulate ()
{
WriteLog (lsINFO, LedgerConsensus) << "Simulating consensus";
closeLedger ();
mCurrentMSeconds = 100;
beginAccept (true);
endConsensus ();
WriteLog (lsINFO, LedgerConsensus) << "Simulation complete";
}
void LedgerConsensusImp::accept (std::shared_ptr<SHAMap> set)
{
{
auto lock = beast::make_lock(getApp().getMasterMutex());
// put our set where others can get it later
if (set->getHash ().isNonZero ())
consensus_.takePosition (mPreviousLedger->info().seq, set);
assert (set->getHash () == mOurPosition->getCurrentHash ());
// these are now obsolete
consensus_.peekStoredProposals ().clear ();
}
std::uint32_t closeTime = roundCloseTime (
mOurPosition->getCloseTime (), mCloseResolution);
bool closeTimeCorrect = true;
if (closeTime == 0)
{
// we agreed to disagree
closeTimeCorrect = false;
closeTime = mPreviousLedger->info().closeTime + 1;
}
WriteLog (lsDEBUG, LedgerConsensus)
<< "Report: Prop=" << (mProposing ? "yes" : "no")
<< " val=" << (mValidating ? "yes" : "no")
<< " corLCL=" << (mHaveCorrectLCL ? "yes" : "no")
<< " fail=" << (mConsensusFail ? "yes" : "no");
WriteLog (lsDEBUG, LedgerConsensus)
<< "Report: Prev = " << mPrevLedgerHash
<< ":" << mPreviousLedger->info().seq;
WriteLog (lsDEBUG, LedgerConsensus)
<< "Report: TxSt = " << set->getHash ()
<< ", close " << closeTime << (closeTimeCorrect ? "" : "X");
// Put failed transactions into a deterministic order
CanonicalTXSet retriableTransactions (set->getHash ());
// Build the new last closed ledger
auto newLCL = std::make_shared<Ledger>(
open_ledger, *mPreviousLedger);
newLCL->setClosed (); // so applyTransactions sees a closed ledger
// Set up to write SHAMap changes to our database,
// perform updates, extract changes
WriteLog (lsDEBUG, LedgerConsensus)
<< "Applying consensus set transactions to the"
<< " last closed ledger";
{
OpenView accum(&*newLCL);
assert(accum.closed());
applyTransactions (set.get(), accum,
newLCL, retriableTransactions, tapNONE);
accum.apply(*newLCL);
}
// retriableTransactions will include any transactions that
// made it into the consensus set but failed during application
// to the ledger.
// Make a copy for OpenLedger
#if RIPPLE_OPEN_LEDGER
CanonicalTXSet retries =
retriableTransactions;
#endif
newLCL->updateSkipList ();
int asf = newLCL->stateMap().flushDirty (
hotACCOUNT_NODE, newLCL->info().seq);
int tmf = newLCL->txMap().flushDirty (
hotTRANSACTION_NODE, newLCL->info().seq);
WriteLog (lsDEBUG, LedgerConsensus) << "Flushed " << asf << " accounts and " <<
tmf << " transaction nodes";
// Accept ledger
newLCL->setAccepted (closeTime, mCloseResolution, closeTimeCorrect);
// And stash the ledger in the ledger master
if (ledgerMaster_.storeLedger (newLCL))
WriteLog (lsDEBUG, LedgerConsensus)
<< "Consensus built ledger we already had";
else if (getApp().getInboundLedgers().find (newLCL->getHash()))
WriteLog (lsDEBUG, LedgerConsensus)
<< "Consensus built ledger we were acquiring";
else
WriteLog (lsDEBUG, LedgerConsensus)
<< "Consensus built new ledger";
uint256 const newLCLHash = newLCL->getHash ();
WriteLog (lsDEBUG, LedgerConsensus)
<< "Report: NewL = " << newLCL->getHash ()
<< ":" << newLCL->info().seq;
// Tell directly connected peers that we have a new LCL
statusChange (protocol::neACCEPTED_LEDGER, *newLCL);
if (mValidating && !mConsensusFail)
{
// Build validation
auto v = std::make_shared<STValidation> (newLCLHash,
consensus_.validationTimestamp (getApp().getOPs ().getNetworkTimeNC ()),
mValPublic, mProposing);
v->setFieldU32 (sfLedgerSequence, newLCL->info().seq);
addLoad(v); // Our network load
if (((newLCL->info().seq + 1) % 256) == 0)
// next ledger is flag ledger
{
// Suggest fee changes and new features
m_feeVote.doValidation (newLCL, *v);
getApp().getAmendmentTable ().doValidation (newLCL, *v);
}
auto const signingHash = v->sign (mValPrivate);
v->setTrusted ();
// suppress it if we receive it - FIXME: wrong suppression
getApp().getHashRouter ().addSuppression (signingHash);
getApp().getValidations ().addValidation (v, "local");
consensus_.setLastValidation (v);
Blob validation = v->getSigned ();
protocol::TMValidation val;
val.set_validation (&validation[0], validation.size ());
// Send signed validation to all of our directly connected peers
getApp().overlay().send(val);
WriteLog (lsINFO, LedgerConsensus)
<< "CNF Val " << newLCLHash;
}
else
WriteLog (lsINFO, LedgerConsensus)
<< "CNF newLCL " << newLCLHash;
// See if we can accept a ledger as fully-validated
ledgerMaster_.consensusBuilt (newLCL);
// Build new open ledger
auto newOL = std::make_shared<Ledger>(
open_ledger, *newLCL);
OpenView accum(&*newOL);
assert(accum.open());
// Apply disputed transactions that didn't get in
//
// The first crack of transactions to get into the new
// open ledger goes to transactions proposed by a validator
// we trust but not included in the consensus set.
//
// These are done first because they are the most likely
// to receive agreement during consensus. They are also
// ordered logically "sooner" than transactions not mentioned
// in the previous consensus round.
//
bool anyDisputes = false;
for (auto& it : mDisputes)
{
if (!it.second->getOurVote ())
{
// we voted NO
try
{
WriteLog (lsDEBUG, LedgerConsensus)
<< "Test applying disputed transaction that did"
<< " not get in";
SerialIter sit (it.second->peekTransaction().slice());
auto txn = std::make_shared<STTx>(sit);
retriableTransactions.insert (txn);
// For OpenLedger
#if RIPPLE_OPEN_LEDGER
retries.insert(txn);
#endif
anyDisputes = true;
}
catch (...)
{
WriteLog (lsDEBUG, LedgerConsensus)
<< "Failed to apply transaction we voted NO on";
}
}
}
if (anyDisputes)
{
applyTransactions (nullptr, accum,
newLCL, retriableTransactions, tapNONE);
}
{
auto lock = beast::make_lock(getApp().getMasterMutex(), std::defer_lock);
LedgerMaster::ScopedLockType sl (ledgerMaster_.peekMutex (), std::defer_lock);
std::lock(lock, sl);
auto const localTx = m_localTX.getTxSet();
auto const oldOL = ledgerMaster_.getCurrentLedger();
#if RIPPLE_OPEN_LEDGER
getApp().openLedger().verify(*oldOL, "consensus before");
#endif
if (oldOL->txMap().getHash().isNonZero ())
{
WriteLog (lsDEBUG, LedgerConsensus)
<< "Applying transactions from current open ledger";
applyTransactions (&oldOL->txMap(), accum,
newLCL, retriableTransactions, tapNONE);
}
for (auto const& item : localTx)
apply (accum, *item.second, tapNONE, getConfig(),
deprecatedLogs().journal("LedgerConsensus"));
accum.apply(*newOL);
// We have a new Last Closed Ledger and new Open Ledger
ledgerMaster_.pushLedger (newLCL, newOL);
#if RIPPLE_OPEN_LEDGER
getApp().openLedger().accept(newLCL,
localTx, anyDisputes, retries, tapNONE,
getApp().getHashRouter(), "consensus");
getApp().openLedger().verify(*newOL, "consensus after");
#endif
}
mNewLedgerHash = newLCL->getHash ();
state_ = State::accepted;
if (mValidating)
{
// see how close our close time is to other node's
// close time reports, and update our clock.
WriteLog (lsINFO, LedgerConsensus)
<< "We closed at " << mCloseTime;
std::uint64_t closeTotal = mCloseTime;
int closeCount = 1;
for (auto it = mCloseTimes.begin ()
, end = mCloseTimes.end (); it != end; ++it)
{
// FIXME: Use median, not average
WriteLog (lsINFO, LedgerConsensus)
<< beast::lexicalCastThrow <std::string> (it->second)
<< " time votes for "
<< beast::lexicalCastThrow <std::string> (it->first);
closeCount += it->second;
closeTotal += static_cast<std::uint64_t>
(it->first) * static_cast<std::uint64_t> (it->second);
}
closeTotal += (closeCount / 2);
closeTotal /= closeCount;
int offset = static_cast<int> (closeTotal)
- static_cast<int> (mCloseTime);
WriteLog (lsINFO, LedgerConsensus)
<< "Our close offset is estimated at "
<< offset << " (" << closeCount << ")";
getApp().getOPs ().closeTimeOffset (offset);
}
}
void LedgerConsensusImp::createDisputes (
std::shared_ptr<SHAMap> const& m1,
std::shared_ptr<SHAMap> const& m2)
{
if (m1->getHash() == m2->getHash())
return;
WriteLog (lsDEBUG, LedgerConsensus) << "createDisputes "
<< m1->getHash() << " to " << m2->getHash();
SHAMap::Delta differences;
m1->compare (*m2, differences, 16384);
int dc = 0;
// for each difference between the transactions
for (auto& pos : differences)
{
++dc;
// create disputed transactions (from the ledger that has them)
if (pos.second.first)
{
// transaction is only in first map
assert (!pos.second.second);
addDisputedTransaction (pos.first
, pos.second.first->peekData ());
}
else if (pos.second.second)
{
// transaction is only in second map
assert (!pos.second.first);
addDisputedTransaction (pos.first
, pos.second.second->peekData ());
}
else // No other disagreement over a transaction should be possible
assert (false);
}
WriteLog (lsDEBUG, LedgerConsensus) << dc << " differences found";
}
void LedgerConsensusImp::addDisputedTransaction (
uint256 const& txID,
Blob const& tx)
{
if (mDisputes.find (txID) != mDisputes.end ())
return;
WriteLog (lsDEBUG, LedgerConsensus) << "Transaction "
<< txID << " is disputed";
bool ourVote = false;
// Update our vote on the disputed transaction
if (mOurPosition)
{
auto mit (mAcquired.find (mOurPosition->getCurrentHash ()));
if (mit != mAcquired.end ())
ourVote = mit->second->hasItem (txID);
else
assert (false); // We don't have our own position?
}
auto txn = std::make_shared<DisputedTx> (txID, tx, ourVote);
mDisputes[txID] = txn;
// Update all of the peer's votes on the disputed transaction
for (auto& pit : mPeerPositions)
{
auto cit (mAcquired.find (pit.second->getCurrentHash ()));
if ((cit != mAcquired.end ()) && cit->second)
{
txn->setVote (pit.first, cit->second->hasItem (txID));
}
}
// If we didn't relay this transaction recently, relay it
if (getApp().getHashRouter ().setFlag (txID, SF_RELAYED))
{
protocol::TMTransaction msg;
msg.set_rawtransaction (& (tx.front ()), tx.size ());
msg.set_status (protocol::tsNEW);
msg.set_receivetimestamp (getApp().getOPs ().getNetworkTimeNC ());
getApp ().overlay ().foreach (send_always (
std::make_shared<Message> (
msg, protocol::mtTRANSACTION)));
}
}
void LedgerConsensusImp::adjustCount (std::shared_ptr<SHAMap> const& map,
const std::vector<NodeID>& peers)
{
for (auto& it : mDisputes)
{
bool setHas = map->hasItem (it.second->getTransactionID ());
for (auto const& pit : peers)
it.second->setVote (pit, setHas);
}
}
void LedgerConsensusImp::leaveConsensus ()
{
if (mProposing)
{
if (mOurPosition && ! mOurPosition->isBowOut ())
{
mOurPosition->bowOut();
propose();
}
mProposing = false;
}
}
void LedgerConsensusImp::propose ()
{
WriteLog (lsTRACE, LedgerConsensus) << "We propose: " <<
(mOurPosition->isBowOut ()
? std::string ("bowOut")
: to_string (mOurPosition->getCurrentHash ()));
protocol::TMProposeSet prop;
prop.set_currenttxhash (mOurPosition->getCurrentHash ().begin ()
, 256 / 8);
prop.set_previousledger (mOurPosition->getPrevLedger ().begin ()
, 256 / 8);
prop.set_proposeseq (mOurPosition->getProposeSeq ());
prop.set_closetime (mOurPosition->getCloseTime ());
Blob const pubKey = mValPublic.getNodePublic ();
prop.set_nodepubkey (&pubKey[0], pubKey.size ());
Blob const sig = mOurPosition->sign (mValPrivate);
prop.set_signature (&sig[0], sig.size ());
getApp().overlay().send(prop);
}
void LedgerConsensusImp::sendHaveTxSet (uint256 const& hash, bool direct)
{
protocol::TMHaveTransactionSet msg;
msg.set_hash (hash.begin (), 256 / 8);
msg.set_status (direct ? protocol::tsHAVE : protocol::tsCAN_GET);
getApp ().overlay ().foreach (send_always (
std::make_shared <Message> (
msg, protocol::mtHAVE_SET)));
}
void LedgerConsensusImp::statusChange (protocol::NodeEvent event, Ledger& ledger)
{
protocol::TMStatusChange s;
if (!mHaveCorrectLCL)
s.set_newevent (protocol::neLOST_SYNC);
else
s.set_newevent (event);
s.set_ledgerseq (ledger.info().seq);
s.set_networktime (getApp().getOPs ().getNetworkTimeNC ());
s.set_ledgerhashprevious(ledger.info().parentHash.begin (),
std::decay_t<decltype(ledger.info().parentHash)>::bytes);
s.set_ledgerhash (ledger.getHash ().begin (),
std::decay_t<decltype(ledger.getHash ())>::bytes);
std::uint32_t uMin, uMax;
if (!ledgerMaster_.getFullValidatedRange (uMin, uMax))
{
uMin = 0;
uMax = 0;
}
else
{
// Don't advertise ledgers we're not willing to serve
std::uint32_t early = ledgerMaster_.getEarliestFetch ();
if (uMin < early)
uMin = early;
}
s.set_firstseq (uMin);
s.set_lastseq (uMax);
getApp ().overlay ().foreach (send_always (
std::make_shared <Message> (
s, protocol::mtSTATUS_CHANGE)));
WriteLog (lsTRACE, LedgerConsensus) << "send status change to peer";
}
void LedgerConsensusImp::takeInitialPosition (Ledger& initialLedger)
{
std::shared_ptr<SHAMap> initialSet;
if ((getConfig ().RUN_STANDALONE || (mProposing && mHaveCorrectLCL))
&& ((mPreviousLedger->info().seq % 256) == 0))
{
// previous ledger was flag ledger
std::shared_ptr<SHAMap> preSet
= initialLedger.txMap().snapShot (true);
ValidationSet parentSet = getApp().getValidations().getValidations (
mPreviousLedger->info().parentHash);
m_feeVote.doVoting (mPreviousLedger, parentSet, preSet);
getApp().getAmendmentTable ().doVoting (mPreviousLedger, parentSet, preSet);
initialSet = preSet->snapShot (false);
}
else
initialSet = initialLedger.txMap().snapShot (false);
// Tell the ledger master not to acquire the ledger we're probably building
ledgerMaster_.setBuildingLedger (mPreviousLedger->info().seq + 1);
uint256 txSet = initialSet->getHash ();
WriteLog (lsINFO, LedgerConsensus) << "initial position " << txSet;
mapCompleteInternal (txSet, initialSet, false);
mOurPosition = std::make_shared<LedgerProposal>
(mValPublic, initialLedger.info().parentHash, txSet, mCloseTime);
for (auto& it : mDisputes)
{
it.second->setOurVote (initialLedger.txExists(it.first));
}
// if any peers have taken a contrary position, process disputes
hash_set<uint256> found;
for (auto& it : mPeerPositions)
{
uint256 set = it.second->getCurrentHash ();
if (found.insert (set).second)
{
auto iit (mAcquired.find (set));
if (iit != mAcquired.end ())
{
mCompares.insert(iit->second->getHash());
createDisputes (initialSet, iit->second);
}
}
}
if (mProposing)
propose ();
}
/** How many of the participants must agree to reach a given threshold?
Note that the number may not precisely yield the requested percentage.
For example, with with size = 5 and percent = 70, we return 3, but
3 out of 5 works out to 60%. There are no security implications to
this.
@param participants the number of participants (i.e. validators)
@param the percent that we want to reach
@return the number of participants which must agree
*/
static
int
participantsNeeded (int participants, int percent)
{
int result = ((participants * percent) + (percent / 2)) / 100;
return (result == 0) ? 1 : result;
}
void LedgerConsensusImp::updateOurPositions ()
{
// Compute a cutoff time
auto peerCutoff
= std::chrono::steady_clock::now ();
auto ourCutoff
= peerCutoff - std::chrono::seconds (PROPOSE_INTERVAL);
peerCutoff -= std::chrono::seconds (PROPOSE_FRESHNESS);
bool changes = false;
std::shared_ptr<SHAMap> ourPosition;
// std::vector<uint256> addedTx, removedTx;
// Verify freshness of peer positions and compute close times
std::map<std::uint32_t, int> closeTimes;
auto it = mPeerPositions.begin ();
while (it != mPeerPositions.end ())
{
if (it->second->isStale (peerCutoff))
{
// peer's proposal is stale, so remove it
auto const& peerID = it->second->getPeerID ();
WriteLog (lsWARNING, LedgerConsensus)
<< "Removing stale proposal from " << peerID;
for (auto& dt : mDisputes)
dt.second->unVote (peerID);
it = mPeerPositions.erase (it);
}
else
{
// proposal is still fresh
++closeTimes[roundCloseTime (it->second->getCloseTime (), mCloseResolution)];
++it;
}
}
// Update votes on disputed transactions
for (auto& it : mDisputes)
{
// Because the threshold for inclusion increases,
// time can change our position on a dispute
if (it.second->updateVote (mClosePercent, mProposing))
{
if (!changes)
{
ourPosition = mAcquired[mOurPosition->getCurrentHash ()]
->snapShot (true);
assert (ourPosition);
changes = true;
}
if (it.second->getOurVote ()) // now a yes
{
ourPosition->addItem (SHAMapItem (it.first
, it.second->peekTransaction ()), true, false);
// addedTx.push_back(it.first);
}
else // now a no
{
ourPosition->delItem (it.first);
// removedTx.push_back(it.first);
}
}
}
int neededWeight;
if (mClosePercent < AV_MID_CONSENSUS_TIME)
neededWeight = AV_INIT_CONSENSUS_PCT;
else if (mClosePercent < AV_LATE_CONSENSUS_TIME)
neededWeight = AV_MID_CONSENSUS_PCT;
else if (mClosePercent < AV_STUCK_CONSENSUS_TIME)
neededWeight = AV_LATE_CONSENSUS_PCT;
else
neededWeight = AV_STUCK_CONSENSUS_PCT;
std::uint32_t closeTime = 0;
mHaveCloseTimeConsensus = false;
if (mPeerPositions.empty ())
{
// no other times
mHaveCloseTimeConsensus = true;
closeTime = roundCloseTime (mOurPosition->getCloseTime (), mCloseResolution);
}
else
{
int participants = mPeerPositions.size ();
if (mProposing)
{
++closeTimes[roundCloseTime (mOurPosition->getCloseTime (), mCloseResolution)];
++participants;
}
// Threshold for non-zero vote
int threshVote = participantsNeeded (participants,
neededWeight);
// Threshold to declare consensus
int const threshConsensus = participantsNeeded (
participants, AV_CT_CONSENSUS_PCT);
WriteLog (lsINFO, LedgerConsensus) << "Proposers:"
<< mPeerPositions.size () << " nw:" << neededWeight
<< " thrV:" << threshVote << " thrC:" << threshConsensus;
for (auto it = closeTimes.begin ()
, end = closeTimes.end (); it != end; ++it)
{
WriteLog (lsDEBUG, LedgerConsensus) << "CCTime: seq"
<< mPreviousLedger->info().seq + 1 << ": "
<< it->first << " has " << it->second << ", "
<< threshVote << " required";
if (it->second >= threshVote)
{
WriteLog (lsDEBUG, LedgerConsensus)
<< "Close time consensus reached: " << it->first;
closeTime = it->first;
threshVote = it->second;
if (threshVote >= threshConsensus)
mHaveCloseTimeConsensus = true;
}
}
// If we agree to disagree on the close time, don't delay consensus
if (!mHaveCloseTimeConsensus && (closeTimes[0] > threshConsensus))
{
closeTime = 0;
mHaveCloseTimeConsensus = true;
}
CondLog (!mHaveCloseTimeConsensus, lsDEBUG, LedgerConsensus)
<< "No CT consensus: Proposers:" << mPeerPositions.size ()
<< " Proposing:" << (mProposing ? "yes" : "no") << " Thresh:"
<< threshConsensus << " Pos:" << closeTime;
}
if (!changes &&
((closeTime != roundCloseTime (mOurPosition->getCloseTime (), mCloseResolution))
|| mOurPosition->isStale (ourCutoff)))
{
// close time changed or our position is stale
ourPosition = mAcquired[mOurPosition->getCurrentHash ()]
->snapShot (true);
assert (ourPosition);
changes = true; // We pretend our position changed to force
} // a new proposal
if (changes)
{
uint256 newHash = ourPosition->getHash ();
WriteLog (lsINFO, LedgerConsensus)
<< "Position change: CTime " << closeTime
<< ", tx " << newHash;
if (mOurPosition->changePosition (newHash, closeTime))
{
if (mProposing)
propose ();
mapCompleteInternal (newHash, ourPosition, false);
}
}
}
void LedgerConsensusImp::playbackProposals ()
{
for (auto const& it: consensus_.peekStoredProposals ())
{
for (auto const& proposal : it.second)
{
if (proposal->isPrevLedger (mPrevLedgerHash) &&
peerPosition (proposal))
{
WriteLog (lsWARNING, LedgerConsensus)
<< "We should do delayed relay of this proposal,"
<< " but we cannot";
}
}
}
}
void LedgerConsensusImp::closeLedger ()
{
checkOurValidation ();
state_ = State::establish;
mConsensusStartTime = std::chrono::steady_clock::now ();
mCloseTime = getApp().getOPs ().getCloseTimeNC ();
consensus_.setLastCloseTime (mCloseTime);
statusChange (protocol::neCLOSING_LEDGER, *mPreviousLedger);
ledgerMaster_.applyHeldTransactions ();
takeInitialPosition (*ledgerMaster_.getCurrentLedger ());
}
void LedgerConsensusImp::checkOurValidation ()
{
// This only covers some cases - Fix for the case where we can't ever
// acquire the consensus ledger
if (!mHaveCorrectLCL || !mValPublic.isSet ()
|| !mValPrivate.isSet ()
|| getApp().getOPs ().isNeedNetworkLedger ())
{
return;
}
auto lastValidation = consensus_.getLastValidation ();
if (lastValidation)
{
if (lastValidation->getFieldU32 (sfLedgerSequence)
== mPreviousLedger->info().seq)
{
return;
}
if (lastValidation->getLedgerHash () == mPrevLedgerHash)
return;
}
auto v = std::make_shared<STValidation> (mPreviousLedger->getHash (),
consensus_.validationTimestamp (getApp().getOPs ().getNetworkTimeNC ()),
mValPublic, false);
addLoad(v);
v->setTrusted ();
auto const signingHash = v->sign (mValPrivate);
// FIXME: wrong supression
getApp().getHashRouter ().addSuppression (signingHash);
getApp().getValidations ().addValidation (v, "localMissing");
Blob validation = v->getSigned ();
protocol::TMValidation val;
val.set_validation (&validation[0], validation.size ());
consensus_.setLastValidation (v);
WriteLog (lsWARNING, LedgerConsensus) << "Sending partial validation";
}
void LedgerConsensusImp::beginAccept (bool synchronous)
{
auto consensusSet = mAcquired[mOurPosition->getCurrentHash ()];
if (!consensusSet)
{
WriteLog (lsFATAL, LedgerConsensus)
<< "We don't have a consensus set";
abort ();
return;
}
consensus_.newLCL (mPeerPositions.size (), mCurrentMSeconds, mNewLedgerHash);
if (synchronous)
accept (consensusSet);
else
{
getApp().getJobQueue().addJob (jtACCEPT, "acceptLedger",
std::bind (&LedgerConsensusImp::accept, shared_from_this (), consensusSet));
}
}
void LedgerConsensusImp::endConsensus ()
{
getApp().getOPs ().endConsensus (mHaveCorrectLCL);
}
void LedgerConsensusImp::addLoad(STValidation::ref val)
{
std::uint32_t fee = std::max(
getApp().getFeeTrack().getLocalFee(),
getApp().getFeeTrack().getClusterFee());
std::uint32_t ref = getApp().getFeeTrack().getLoadBase();
if (fee > ref)
val->setFieldU32(sfLoadFee, fee);
}
//------------------------------------------------------------------------------
std::shared_ptr <LedgerConsensus>
make_LedgerConsensus (ConsensusImp& consensus, int previousProposers,
int previousConvergeTime, InboundTransactions& inboundTransactions,
LocalTxs& localtx, LedgerMaster& ledgerMaster, LedgerHash const &prevLCLHash,
Ledger::ref previousLedger, std::uint32_t closeTime, FeeVote& feeVote)
{
return std::make_shared <LedgerConsensusImp> (consensus, previousProposers,
previousConvergeTime, inboundTransactions, localtx, ledgerMaster,
prevLCLHash, previousLedger, closeTime, feeVote);
}
//------------------------------------------------------------------------------
/** Apply a transaction to a ledger
@param engine The transaction engine containing the ledger.
@param txn The transaction to be applied to ledger.
@param retryAssured true if the transaction should be retried on failure.
@return One of resultSuccess, resultFail or resultRetry.
*/
static
int
applyTransaction (OpenView& view,
std::shared_ptr<STTx const> const& txn,
bool retryAssured, ApplyFlags flags)
{
// Returns false if the transaction has need not be retried.
if (retryAssured)
flags = flags | tapRETRY;
if ((getApp().getHashRouter ().getFlags (txn->getTransactionID ())
& SF_SIGGOOD) == SF_SIGGOOD)
flags = flags | tapNO_CHECK_SIGN;
WriteLog (lsDEBUG, LedgerConsensus) << "TXN "
<< txn->getTransactionID ()
//<< (engine.view().open() ? " open" : " closed") // because of the optional in engine
<< (retryAssured ? "/retry" : "/final");
WriteLog (lsTRACE, LedgerConsensus) << txn->getJson (0);
try
{
auto const result = apply(view, *txn, flags, getConfig(),
deprecatedLogs().journal("LedgerConsensus"));
if (result.second)
{
WriteLog (lsDEBUG, LedgerConsensus)
<< "Transaction applied: " << transHuman (result.first);
return LedgerConsensusImp::resultSuccess;
}
if (isTefFailure (result.first) || isTemMalformed (result.first) ||
isTelLocal (result.first))
{
// failure
WriteLog (lsDEBUG, LedgerConsensus)
<< "Transaction failure: " << transHuman (result.first);
return LedgerConsensusImp::resultFail;
}
WriteLog (lsDEBUG, LedgerConsensus)
<< "Transaction retry: " << transHuman (result.first);
return LedgerConsensusImp::resultRetry;
}
catch (...)
{
WriteLog (lsWARNING, LedgerConsensus) << "Throws";
return LedgerConsensusImp::resultFail;
}
}
void applyTransactions (
SHAMap const* set,
OpenView& view,
Ledger::ref checkLedger,
CanonicalTXSet& retriableTransactions,
ApplyFlags flags)
{
if (set)
{
for (auto const& item : *set)
{
if (checkLedger->txExists (item.key()))
continue;
// The transaction isn't in the check ledger, try to apply it
WriteLog (lsDEBUG, LedgerConsensus) <<
"Processing candidate transaction: " << item.key();
std::shared_ptr<STTx const> txn;
try
{
txn = std::make_shared<STTx const>(SerialIter{item.slice()});
}
catch (...)
{
WriteLog (lsWARNING, LedgerConsensus) << " Throws";
}
if (txn)
{
if (applyTransaction(view, txn, true, flags) ==
LedgerConsensusImp::resultRetry)
{
// On failure, stash the failed transaction for
// later retry.
retriableTransactions.insert (txn);
}
}
}
}
bool certainRetry = true;
// Attempt to apply all of the retriable transactions
for (int pass = 0; pass < LEDGER_TOTAL_PASSES; ++pass)
{
WriteLog (lsDEBUG, LedgerConsensus) << "Pass: " << pass << " Txns: "
<< retriableTransactions.size ()
<< (certainRetry ? " retriable" : " final");
int changes = 0;
auto it = retriableTransactions.begin ();
while (it != retriableTransactions.end ())
{
try
{
switch (applyTransaction (view,
it->second, certainRetry, flags))
{
case LedgerConsensusImp::resultSuccess:
it = retriableTransactions.erase (it);
++changes;
break;
case LedgerConsensusImp::resultFail:
it = retriableTransactions.erase (it);
break;
case LedgerConsensusImp::resultRetry:
++it;
}
}
catch (...)
{
WriteLog (lsWARNING, LedgerConsensus)
<< "Transaction throws";
it = retriableTransactions.erase (it);
}
}
WriteLog (lsDEBUG, LedgerConsensus) << "Pass: "
<< pass << " finished " << changes << " changes";
// A non-retry pass made no changes
if (!changes && !certainRetry)
return;
// Stop retriable passes
if (!changes || (pass >= LEDGER_RETRY_PASSES))
certainRetry = false;
}
// If there are any transactions left, we must have
// tried them in at least one final pass
assert (retriableTransactions.empty() || !certainRetry);
}
} // ripple
|
/***************************************************
* Problem Name : 1140 - How Many Zeroes?(2).cpp
* Problem Link : http://lightoj.com/volume_showproblem.php?problem=1140
* OJ : LOJ
* Verdict : AC
* Date : 2019-01-28
* Problem Type : DigitDP
* Author Name : Saikat Sharma
* University : CSE, MBSTU
***************************************************/
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<climits>
#include<cstring>
#include<string>
#include<sstream>
#include<cmath>
#include<vector>
#include<queue>
#include<cstdlib>
#include<deque>
#include<stack>
#include<map>
#include<set>
#define __FastIO ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#define FileRead freopen ("/home/saikat/Desktop/logN/input.txt", "r", stdin);
#define FileWrite freopen ("/home/saikat/Desktop/logN/output.txt", "w", stdout);
#define SET(a,v) memset(a,v,sizeof(a))
#define pii pair<int,int>
#define pll pair <ll, ll>
#define debug cout <<"#########\n";
#define nl cout << "\n";
#define sp cout << " ";
#define sl(n) scanf("%lld", &n)
#define sf(n) scanf("%lf", &n)
#define si(n) scanf("%d", &n)
#define ss(n) scanf("%s", n)
#define pf(n) scanf("%d", n)
#define pfl(n) scanf("%lld", n)
#define all(v) v.begin(), v.end()
#define Pow2(x) ((x)*(x))
#define Mod(x, m) ((((x) % (m)) + (m)) % (m))
#define Max3(a, b, c) max(a, max(b, c))
#define Min3(a, b, c) min(a, min(b, c))
#define pb push_back
#define mk make_pair
#define MAX 100005
#define INF 1000000000
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
template <typename T>
std::string NumberToString ( T Number ) {
std::ostringstream ss;
ss << Number;
return ss.str();
}
ll lcm (ll a, ll b) {
return a * b / __gcd (a, b);
}
/************************************ Code Start Here ******************************************************/
int n;
ll dp[20][2][2][2];
ll dpNum[20][2][2];
vector<int>A, B;
ll makeNumber (int pos, int isChoto, int isBoro) {
if (pos == n) {
return dpNum[pos][isChoto][isBoro] = 1;
}
if (dpNum[pos][isChoto][isBoro] != -1) {
return dpNum[pos][isChoto][isBoro];
}
int low = 0, high = 9;
if (isChoto == 0) {
high = B[pos];
}
if (isBoro == 0) {
low = A[pos];
}
ll ans = 0;
for (int i = low; i <= high; i++) {
int new_isChoto = isChoto;
int new_isBoro = isBoro;
if (i < high) {
new_isChoto = 1;
}
if (i > low) {
new_isBoro = 1;
}
ans += makeNumber (pos + 1, new_isChoto, new_isBoro);
}
return dpNum[pos][isChoto][isBoro] = ans;
}
ll digitDP (int pos, int isChoto, int isBoro, int isSuru) {
if (pos == n) return 0;
if (dp[pos][isChoto][isBoro][isSuru] != -1) {
return dp[pos][isChoto][isBoro][isSuru];
}
ll ans = 0;
int low = 0, high = 9;
if (isChoto == 0) {
high = B[pos];
}
if (isBoro == 0) {
low = A[pos];
}
for (int i = low; i <= high; i++) {
int new_isChoto = isChoto;
int new_isBoro = isBoro;
int new_isSuru = isSuru;
ll cnt = 0;
if (i < high) {
new_isChoto = 1;
}
if (i > low) {
new_isBoro = 1;
}
if (i > 0) {
new_isSuru = 1;
}
if (i == 0 && isSuru == 1) {
//~ cnt = makeNumber (pos + 1, new_isChoto, new_isBoro);
cnt = dpNum[pos + 1][new_isChoto][new_isBoro];
}
ans += cnt + digitDP (pos + 1, new_isChoto, new_isBoro, new_isSuru);
}
return dp[pos][isChoto][isBoro][isSuru] = ans;
}
ll solve (ll a, ll b) {
A.clear(), B.clear();
while (b > 0) {
int rem = b % 10;
B.pb (rem);
b /= 10;
}
reverse (all (B) );
while (a > 0) {
int rem = a % 10;
A.pb (rem);
a /= 10;
}
n = (int) B.size();
while ( (int) A.size() < n) {
A.pb (0);
}
reverse (all (A) );
SET (dpNum, -1);
makeNumber (0, 0, 0);
SET (dp, -1);
ll ans = digitDP (0, 0, 0, 0);
return ans;
}
int main () {
//~ __FastIO;
int tc;
cin >> tc;
for (int t = 1; t <= tc; t++) {
ll a, b;
cin >> a >> b;
ll ans = solve (a, b);
if (a == 0) ans++;
cout << "Case " << t << ": " << ans << "\n";
}
return 0;
}
|
#include "test_utils.h"
#include "variant/variant_header_builder.h"
#include "missing.h"
#include <set>
#include <boost/test/unit_test.hpp>
using namespace std;
using namespace gamgee;
template<class T>
void check_fields(T actual, T truth) {
std::sort(actual.begin(), actual.end());
std::sort(truth.begin(), truth.end());
BOOST_CHECK_EQUAL(actual.size(), truth.size());
BOOST_CHECK(actual == truth);
}
const auto samples = vector<string>{"S1", "S292", "S30034"};
const auto sample_indices = vector<int32_t>{0, 1, 2};
const auto chromosomes = vector<string>{"chr1", "chr2", "chr3", "chr4"};
const auto filters = vector<string>{"LOW_QUAL", "PASS", "VQSR_FAILED"};
const auto filter_indices = vector<int32_t>{1, 0, 2};
const auto shareds = vector<string>{"DP", "MQ", "RankSum"};
const auto shareds_indices = vector<int32_t>{3,4,5}; // looks arbitrary but these are the indices of the shared fields because the filters get 0, 1 and 2.
const auto individuals = vector<string>{"GQ", "PL", "DP"};
const auto individuals_indices = vector<int32_t>{6,7,3}; // the last index gets the same number as the info index. Weird, but that's how htslib deals with this.
void variant_header_builder_checks(const VariantHeader& vh) {
check_fields(vh.chromosomes(), chromosomes);
check_fields(vh.samples(), samples);
check_fields(vh.filters(), filters);
check_fields(vh.shared_fields(), shareds);
check_fields(vh.individual_fields(), individuals);
BOOST_CHECK(vh.has_filter("PASS"));
BOOST_CHECK(vh.has_filter(vh.field_index("PASS")));
BOOST_CHECK(vh.has_filter("LOW_QUAL"));
BOOST_CHECK(vh.has_filter(vh.field_index("LOW_QUAL")));
BOOST_CHECK(vh.has_filter("VQSR_FAILED"));
BOOST_CHECK(vh.has_filter(vh.field_index("VQSR_FAILED")));
BOOST_CHECK(! vh.has_filter("BLAH"));
BOOST_CHECK(! vh.has_filter(vh.field_index("BLAH")));
BOOST_CHECK(! vh.has_filter("DP"));
BOOST_CHECK(! vh.has_filter(vh.field_index("DP")));
BOOST_CHECK(! vh.has_filter("GQ"));
BOOST_CHECK(! vh.has_filter(vh.field_index("GQ")));
BOOST_CHECK(! vh.has_filter(20));
BOOST_CHECK(vh.has_shared_field("DP"));
BOOST_CHECK(vh.has_shared_field(vh.field_index("DP")));
BOOST_CHECK(vh.has_shared_field("MQ"));
BOOST_CHECK(vh.has_shared_field(vh.field_index("MQ")));
BOOST_CHECK(vh.has_shared_field("RankSum"));
BOOST_CHECK(vh.has_shared_field(vh.field_index("RankSum")));
BOOST_CHECK(! vh.has_shared_field("BLAH"));
BOOST_CHECK(! vh.has_shared_field(vh.field_index("BLAH")));
BOOST_CHECK(! vh.has_shared_field("LOW_QUAL"));
BOOST_CHECK(! vh.has_shared_field(vh.field_index("LOW_QUAL")));
BOOST_CHECK(! vh.has_shared_field("GQ"));
BOOST_CHECK(! vh.has_shared_field(vh.field_index("GQ")));
BOOST_CHECK(! vh.has_shared_field(20));
BOOST_CHECK(vh.has_individual_field("GQ"));
BOOST_CHECK(vh.has_individual_field(vh.field_index("GQ")));
BOOST_CHECK(vh.has_individual_field("PL"));
BOOST_CHECK(vh.has_individual_field(vh.field_index("PL")));
BOOST_CHECK(vh.has_individual_field("DP"));
BOOST_CHECK(vh.has_individual_field(vh.field_index("DP")));
BOOST_CHECK(! vh.has_individual_field("BLAH"));
BOOST_CHECK(! vh.has_individual_field(vh.field_index("BLAH")));
BOOST_CHECK(! vh.has_individual_field("MQ"));
BOOST_CHECK(! vh.has_individual_field(vh.field_index("MQ")));
BOOST_CHECK(! vh.has_individual_field("LOW_QUAL"));
BOOST_CHECK(! vh.has_individual_field(vh.field_index("LOW_QUAL")));
BOOST_CHECK(! vh.has_individual_field(20));
// Also test API functions that take an explicit field category as a parameter (BCF_HL_INFO, etc.)
BOOST_CHECK(vh.has_field("MQ", BCF_HL_INFO));
BOOST_CHECK(vh.has_field(vh.field_index("MQ"), BCF_HL_INFO));
BOOST_CHECK(! vh.has_field("BLAH", BCF_HL_INFO));
BOOST_CHECK(! vh.has_field(vh.field_index("BLAH"), BCF_HL_INFO));
BOOST_CHECK(vh.has_field("GQ", BCF_HL_FMT));
BOOST_CHECK(vh.has_field(vh.field_index("GQ"), BCF_HL_FMT));
BOOST_CHECK(! vh.has_field("BLAH", BCF_HL_FMT));
BOOST_CHECK(! vh.has_field(vh.field_index("BLAH"), BCF_HL_FMT));
// Test type-querying functions (note: these assume that you've already checked field existence)
BOOST_CHECK_EQUAL(vh.shared_field_type("MQ"), BCF_HT_INT);
BOOST_CHECK_EQUAL(vh.shared_field_type(vh.field_index("MQ")), BCF_HT_INT);
BOOST_CHECK_EQUAL(vh.field_type("MQ", BCF_HL_INFO), BCF_HT_INT);
BOOST_CHECK_EQUAL(vh.field_type(vh.field_index("MQ"), BCF_HL_INFO), BCF_HT_INT);
BOOST_CHECK_EQUAL(vh.individual_field_type("PL"), BCF_HT_REAL);
BOOST_CHECK_EQUAL(vh.individual_field_type(vh.field_index("PL")), BCF_HT_REAL);
BOOST_CHECK_EQUAL(vh.field_type("PL", BCF_HL_FMT), BCF_HT_REAL);
BOOST_CHECK_EQUAL(vh.field_type(vh.field_index("PL"), BCF_HL_FMT), BCF_HT_REAL);
BOOST_CHECK(vh.has_sample("S1"));
BOOST_CHECK(vh.has_sample(vh.sample_index("S1")));
BOOST_CHECK(vh.has_sample("S292"));
BOOST_CHECK(vh.has_sample(vh.sample_index("S292")));
BOOST_CHECK(vh.has_sample("S30034"));
BOOST_CHECK(vh.has_sample(vh.sample_index("S30034")));
BOOST_CHECK(! vh.has_sample("BLAH"));
BOOST_CHECK(! vh.has_sample(vh.sample_index("BLAH")));
BOOST_CHECK(! vh.has_sample("DP"));
BOOST_CHECK(! vh.has_sample(vh.sample_index("DP")));
BOOST_CHECK(! vh.has_sample(20));
for (auto i = 0u; i != filters.size(); ++i)
BOOST_CHECK_EQUAL(filter_indices[i], vh.field_index(filters[i]));
for (auto i = 0u; i != shareds.size(); ++i)
BOOST_CHECK_EQUAL(shareds_indices[i], vh.field_index(shareds[i]));
for (auto i = 0u; i != individuals.size(); ++i)
BOOST_CHECK_EQUAL(individuals_indices[i], vh.field_index(individuals[i]));
for (auto i = 0u; i != samples.size(); ++i)
BOOST_CHECK_EQUAL(sample_indices[i], vh.sample_index(samples[i]));
BOOST_CHECK(missing(vh.field_index("MISSING")));
BOOST_CHECK(missing(vh.sample_index("MISSING")));
}
VariantHeaderBuilder simple_builder() {
auto builder = VariantHeaderBuilder{};
builder.add_source("Gamgee api test");
builder.advanced_add_arbitrary_line("##unused=<XX=AA,Description=\"Unused generic\">");
for (const auto& chromosome : chromosomes)
builder.add_chromosome(chromosome, "234");
for (const auto& sample : samples)
builder.add_sample(sample);
for (const auto& filter : filters)
builder.add_filter(filter, "anything", "deer=vanison");
for (const auto& shared : shareds)
builder.add_shared_field(shared, "43", "Integer", "something", "the_source", "3.4", "cow=beef");
for (const auto& individual : individuals)
builder.add_individual_field(individual, "13", "Float", "nothing", "goat=shank");
return builder;
}
BOOST_AUTO_TEST_CASE( variant_header_builder_simple_building ) {
auto builder = simple_builder();
variant_header_builder_checks(builder.build());
}
BOOST_AUTO_TEST_CASE( variant_header_builder_reuse ) {
auto builder = simple_builder();
const auto header1 = builder.build();
variant_header_builder_checks(header1);
builder.add_filter("BLAH", "anything", "deer=vanison");
builder.add_shared_field("BLAH", "43", "Integer", "something", "the_source", "3.4", "cow=beef");
builder.add_individual_field("BLAH", "13", "Float", "nothing", "goat=shank");
const auto header2 = builder.build();
BOOST_CHECK(header2.has_filter("BLAH"));
BOOST_CHECK(header2.has_shared_field("BLAH"));
BOOST_CHECK(header2.has_individual_field("BLAH"));
// these check for the absence of the "BLAH" fields added above
variant_header_builder_checks(header1);
}
BOOST_AUTO_TEST_CASE( variant_header_builder_one_time_build ) {
auto builder = simple_builder();
const auto header = builder.one_time_build();
variant_header_builder_checks(header);
}
BOOST_AUTO_TEST_CASE( variant_header_builder_move ) {
auto builder1 = simple_builder();
auto builder2 = check_move_constructor(builder1);
variant_header_builder_checks(builder2.build());
}
BOOST_AUTO_TEST_CASE( variant_header_builder_chained ) {
auto builder = VariantHeaderBuilder{};
builder
.add_source("Gamgee api test")
.advanced_add_arbitrary_line("##unused=<XX=AA,Description=\"Unused generic\">")
.add_chromosome("chr1", "234")
.add_chromosome("chr2", "234")
.add_chromosome("chr3", "234");
// verify that the chain can be broken and resumed
builder
.add_chromosome("chr4", "234")
.add_sample("S1")
.add_sample("S292")
.add_sample("S30034")
.add_filter("LOW_QUAL", "anything", "deer=vanison")
.add_filter("PASS", "anything", "deer=vanison")
.add_filter("VQSR_FAILED", "anything", "deer=vanison")
.add_shared_field("DP", "43", "Integer", "something", "the_source", "3.4", "cow=beef")
.add_shared_field("MQ", "43", "Integer", "something", "the_source", "3.4", "cow=beef")
.add_shared_field("RankSum", "43", "Integer", "something", "the_source", "3.4", "cow=beef")
.add_individual_field("GQ", "13", "Float", "nothing", "goat=shank")
.add_individual_field("PL", "13", "Float", "nothing", "goat=shank")
.add_individual_field("DP", "13", "Float", "nothing", "goat=shank");
for (const auto& sample : samples)
builder.add_sample(sample);
for (const auto& filter : filters)
builder.add_filter(filter, "anything", "deer=vanison");
for (const auto& shared : shareds)
builder.add_shared_field(shared, "43", "Integer", "something", "the_source", "3.4", "cow=beef");
for (const auto& individual : individuals)
builder.add_individual_field(individual, "13", "Float", "nothing", "goat=shank");
variant_header_builder_checks(builder.build());
}
const auto merge_file_1 = "testdata/var_hdr_merge/test1.vcf";
const auto merge_file_2 = "testdata/var_hdr_merge/test2.vcf";
const auto merge_file_3 = "testdata/var_hdr_merge/test3.vcf";
BOOST_AUTO_TEST_CASE( variant_header_merge_test ) {
auto header1 = SingleVariantReader{merge_file_1}.header();
auto header2 = SingleVariantReader{merge_file_2}.header();
auto header3 = SingleVariantReader{merge_file_3}.header();
BOOST_CHECK(header1 != header2);
BOOST_CHECK(header1 != header3);
BOOST_CHECK(header2 != header3);
// header 3 = the contents of header 1 and header 2 combined
auto builder = VariantHeaderBuilder{header1};
builder.merge(header2);
auto built = builder.build();
BOOST_CHECK(built != header1);
BOOST_CHECK(built != header2);
BOOST_CHECK(built == header3);
// the contents of header 3 are already present so it should do nothing
built = builder.merge(header3).build();
BOOST_CHECK(built == header3);
}
BOOST_AUTO_TEST_CASE( variant_header_file_and_construct ) {
auto header1 = SingleVariantReader{merge_file_1}.header();
auto header2 = SingleVariantReader{merge_file_2}.header();
auto header3 = SingleVariantReader{merge_file_3}.header();
// start with header1 contents
auto builder_from_header = VariantHeaderBuilder{header1};
// add header2 contents
builder_from_header
.add_chromosome("20", "64000000")
.add_chromosome("22", "120000000")
.add_sample("SAMPLE2")
.add_sample("SAMPLE3")
.add_filter("LOW_QUAL", "Low quality call", "")
.add_filter("MISSED", "Missed by the variant caller", "")
.add_shared_field("AN", "1", "Integer", "Total number of alleles in called genotypes", "", "", "")
.add_shared_field("VALIDATED", "0", "Flag", "Validated By Follow-up Experiment", "", "", "")
.add_individual_field("GQ", "1", "Integer", "Genotype quality", "")
.add_individual_field("PL", "G", "Integer", "Phred scaled relative Likelihoods of the genotypes", "");
BOOST_CHECK(builder_from_header.build() == header3);
// start with header1 contents
auto builder_from_scratch = VariantHeaderBuilder{};
builder_from_scratch
.add_chromosome("1", "300000000")
.add_sample("SAMPLE1")
.add_filter("PASS", "All filters passed", "")
// need to escape the quotes because the text contains commas
.add_shared_field("AF", "A", "Float", "\"Allele Frequency, for each ALT allele, in the same order as listed\"", "", "", "")
.add_individual_field("GT", "1", "String", "Genotype", "");
// add header2 contents
builder_from_scratch.merge(header2);
BOOST_CHECK(builder_from_scratch.build() == header3);
}
const auto filter_truth = vector<bool> { true, true, true, false, false, false, false, false };
const auto shared_truth = vector<bool> { false, false, false, true, true, true, false, false };
const auto individual_truth = vector<bool> { false, false, false, true, false, false, true, true };
// remove duplicate names: assign the same index
void add_to_index_names(const vector<string>& new_names, set<string>& index_name_set, vector<string>& index_name_vector) {
for (const auto& name : new_names) {
const auto& finder = index_name_set.find(name);
if (finder == index_name_set.end()) {
index_name_set.insert(name);
index_name_vector.push_back(name);
}
}
}
BOOST_AUTO_TEST_CASE( variant_header_field_index_iteration ) {
auto header = simple_builder().build();
auto index_name_set = set<string>{};
auto index_name_vector = vector<string>{};
// the PASS filter is always index 0
add_to_index_names({"PASS"}, index_name_set, index_name_vector);
add_to_index_names(filters, index_name_set, index_name_vector);
add_to_index_names(shareds, index_name_set, index_name_vector);
add_to_index_names(individuals, index_name_set, index_name_vector);
const auto& name_truth = index_name_vector;
const auto end_truth = index_name_vector.size();
BOOST_CHECK_EQUAL(header.field_index_end(), end_truth);
for (auto idx = 0u; idx < header.field_index_end(); ++idx) {
BOOST_CHECK_EQUAL(header.has_filter(idx), filter_truth[idx]);
BOOST_CHECK_EQUAL(header.has_shared_field(idx), shared_truth[idx]);
BOOST_CHECK_EQUAL(header.has_individual_field(idx), individual_truth[idx]);
BOOST_CHECK_EQUAL(header.get_field_name(idx), name_truth[idx]);
}
}
|
#ifndef CAFFE_DATA_LAYERS_HPP_
#define CAFFE_DATA_LAYERS_HPP_
#include <vector>
#include <mutex>
#include "caffe/common.hpp"
#include "caffe/blob.hpp"
#include "caffe/data_transformer.hpp"
#include "caffe/batch_transformer.hpp"
#include "caffe/internal_thread.hpp"
#include "caffe/layer.hpp"
#include "caffe/proto/caffe.pb.h"
#include "caffe/util/blocking_queue.hpp"
namespace caffe {
/**
* @brief Provides base for data layers that feed blobs to the Net.
*
* TODO(dox): thorough documentation for Forward and proto params.
*/
template<typename Ftype, typename Btype>
class BaseDataLayer : public Layer<Ftype, Btype> {
public:
BaseDataLayer(const LayerParameter& param, size_t transf_num);
virtual ~BaseDataLayer() {}
// LayerSetUp: implements common data layer setup functionality, and calls
// DataLayerSetUp to do special data layer setup for individual layer types.
// This method may not be overridden except by the BasePrefetchingDataLayer.
void LayerSetUp(const vector<Blob*>& bottom, const vector<Blob*>& top) override;
virtual void DataLayerSetUp(const vector<Blob*>& bottom, const vector<Blob*>& top) = 0;
// Data layers should be shared by multiple solvers in parallel
bool ShareInParallel() const override { return true; }
// Data layers have no bottoms, so reshaping is trivial.
void Reshape(const vector<Blob*>& bottom, const vector<Blob*>& top) override {}
void Backward_cpu(const vector<Blob*>& top, const vector<bool>& propagate_down,
const vector<Blob*>& bottom) override {}
void Backward_gpu(const vector<Blob*>& top, const vector<bool>& propagate_down,
const vector<Blob*>& bottom) override {}
virtual bool is_gpu_transform() const { return false; }
protected:
TransformationParameter transform_param_;
bool output_labels_;
};
template<typename Ftype, typename Btype>
class BasePrefetchingDataLayer : public BaseDataLayer<Ftype, Btype>, public InternalThread {
public:
BasePrefetchingDataLayer(const LayerParameter& param, size_t solver_rank);
virtual ~BasePrefetchingDataLayer();
// LayerSetUp: implements common data layer setup functionality, and calls
// DataLayerSetUp to do special data layer setup for individual layer types.
// This method may not be overridden.
void LayerSetUp(const vector<Blob*>& bottom, const vector<Blob*>& top) override;
void Forward_cpu(const vector<Blob*>& bottom, const vector<Blob*>& top) override;
void Forward_gpu(const vector<Blob*>& bottom, const vector<Blob*>& top) override;
DataTransformer<Btype>* bdt(int id) {
return bwd_data_transformers_.at(id).get();
}
DataTransformer<Ftype>* fdt(int id) {
return fwd_data_transformers_.at(id).get();
}
bool is_gpu_transform() const override {
// If user omitted this setting we deduce it from Ftype
const bool use_gpu = this->transform_param_.use_gpu_transform();
const bool use_rand_resize =
this->transform_param_.has_img_rand_resize_lower() ||
this->transform_param_.has_img_rand_resize_upper() ||
this->transform_param_.has_rand_resize_ratio_lower() ||
this->transform_param_.has_rand_resize_ratio_upper() ||
this->transform_param_.has_vertical_stretch_lower() ||
this->transform_param_.has_vertical_stretch_upper() ||
this->transform_param_.has_horizontal_stretch_lower() ||
this->transform_param_.has_horizontal_stretch_upper();
return use_gpu && Caffe::mode() == Caffe::GPU && !use_rand_resize;
}
int batch_size() const {
return batch_size_;
}
protected:
void InternalThreadEntry() override;
void InternalThreadEntryN(size_t thread_id) override;
virtual void ResizeQueues();
virtual void InitializePrefetch();
virtual bool load_batch(Batch* batch, int thread_id, size_t queue_id) = 0;
virtual void start_reading() = 0;
virtual size_t queue_id(size_t thread_id) const {
return thread_id;
}
virtual bool auto_mode() const {
return auto_mode_;
}
size_t batch_id(int thread_id) {
size_t id = batch_ids_[thread_id];
batch_ids_[thread_id] += this->threads_num();
return id;
}
static size_t threads(const LayerParameter& param);
static size_t parser_threads(const LayerParameter& param);
static bool auto_mode(const LayerParameter& param);
std::vector<size_t> batch_ids_;
bool auto_mode_;
size_t parsers_num_, transf_num_, queues_num_;
// These two are for delayed init only
std::vector<Blob*> bottom_init_;
std::vector<Blob*> top_init_;
// Use Btype as a transformer type (i.e. better float 32)
// since data layers don't have bottom channels
std::vector<shared_ptr<DataTransformer<Btype>>> bwd_data_transformers_;
// TransformGPU may do this in-place
std::vector<shared_ptr<DataTransformer<Ftype>>> fwd_data_transformers_;
shared_ptr<BatchTransformer<Ftype, Btype>> batch_transformer_;
std::vector<int> last_shape_;
int batch_size_;
Flag iter0_;
bool precache_;
};
} // namespace caffe
#endif // CAFFE_DATA_LAYERS_HPP_
|
#include "Camera.h"
#include <glm/ext.hpp>
void SimpleCamera::MoveForward(float Scale)
{
ForwardScale = Scale;
}
void SimpleCamera::MoveRight(float Scale)
{
RightScale = Scale;
}
void SimpleCamera::MouseMove(float X, float Y)
{
if (bEnableMouseMovement)
{
glm::vec2 CurrentCursor{ X, Y };
glm::vec2 Delta = (CurrentCursor - PreviousCursor) / 10.0f;
if (glm::length(Delta) < 5.0f)
{
glm::vec3 Right = glm::cross(Direction, Up);
glm::mat4 RotationRight = glm::rotate(glm::identity<glm::mat4>(), glm::radians(-Delta.y), Right);
glm::mat4 RotationUp = glm::rotate(glm::identity<glm::mat4>(), glm::radians(-Delta.x), Up);
glm::mat4 Rotation = RotationRight * RotationUp;
Up = Rotation * glm::vec4{ Up, 0.0f };
Direction = Rotation * glm::vec4{ Direction, 0.0f };
}
PreviousCursor = CurrentCursor;
}
}
void SimpleCamera::Update(float DeltaTime)
{
glm::vec3 Right = glm::cross(Direction, Up);
Location += Direction * ForwardScale * DeltaTime;
Location += Right * RightScale * DeltaTime;
}
glm::mat4 SimpleCamera::GetView()
{
return glm::lookAt(Location, Location + Direction, Up);
}
glm::mat4 SimpleCamera::GetViewProjection()
{
glm::mat4 View = GetView();
glm::mat4 Projection = glm::perspective(FieldOfView, AspectRatio, Near, Far);
return Projection * View;
}
|
/*
** EPITECH PROJECT, 2019
** GBEmulator
** File description:
** Test_isVBlankInterrupt.cpp
*/
#include <criterion/criterion.h>
#include <iostream>
#include "../communism.hpp"
#include "../TestComponents.hpp"
Test(isVBlankInterrupt, no_interrupt)
{
Tests::GBTest gb;
gb.cpu._gpu._control = 0x80;
gb.cpu._gpu._cycles = 0;
cr_assert(!gb.cpu._gpu._isVBlankInterrupt());
}
Test(isVBlankInterrupt, one_interrupt)
{
Tests::GBTest gb;
gb.cpu._gpu._control = 0x80;
gb.cpu._gpu._cycles = 69000;
cr_assert(gb.cpu._gpu._isVBlankInterrupt());
}
Test(isVBlankIntrrupt, multiple_calls)
{
Tests::GBTest gb;
gb.cpu._gpu._control = 0x80;
gb.cpu._gpu._cycles = 69000;
cr_assert(gb.cpu._gpu._isVBlankInterrupt());
cr_assert(!gb.cpu._gpu._isVBlankInterrupt());
}
|
// Tencent is pleased to support the open source community by making UnLua available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// 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 "UnLuaEx.h"
#include "LuaLib_Math.h"
static int32 FVector2D_New(lua_State *L)
{
void *Userdata = NewTypedUserdata(L, FVector2D);
FVector2D *V = new(Userdata) FVector2D(0.0f, 0.0f);
UnLua::TFieldSetter2<float>::Set(L, lua_gettop(L), &V->X);
return 1;
}
static int32 FVector2D_Set(lua_State *L)
{
int32 NumParams = lua_gettop(L);
if (NumParams < 1)
{
UE_LOG(LogUnLua, Log, TEXT("%s: Invalid parameters!"), ANSI_TO_TCHAR(__FUNCTION__));
return 0;
}
FVector2D *V = (FVector2D*)GetCppInstanceFast(L, 1);
if (!V)
{
UE_LOG(LogUnLua, Log, TEXT("%s: Invalid FVector2D!"), ANSI_TO_TCHAR(__FUNCTION__));
return 0;
}
UnLua::TFieldSetter2<float>::Set(L, NumParams, &V->X);
return 0;
}
static int32 FVector2D_Normalize(lua_State *L)
{
int32 NumParams = lua_gettop(L);
if (NumParams != 1)
{
UE_LOG(LogUnLua, Log, TEXT("%s: Invalid parameters!"), ANSI_TO_TCHAR(__FUNCTION__));
return 0;
}
FVector2D *V = (FVector2D*)GetCppInstanceFast(L, 1);
if (!V)
{
UE_LOG(LogUnLua, Log, TEXT("%s: Invalid FVector2D!"), ANSI_TO_TCHAR(__FUNCTION__));
return 0;
}
V->Normalize();
return 0;
}
static int32 FVector2D_IsNormalized(lua_State *L)
{
int32 NumParams = lua_gettop(L);
if (NumParams != 1)
{
UE_LOG(LogUnLua, Log, TEXT("%s: Invalid parameters!"), ANSI_TO_TCHAR(__FUNCTION__));
return 0;
}
FVector2D *V = (FVector2D*)GetCppInstanceFast(L, 1);
if (!V)
{
UE_LOG(LogUnLua, Log, TEXT("%s: Invalid FVector2D!"), ANSI_TO_TCHAR(__FUNCTION__));
return 0;
}
lua_pushboolean(L, FMath::Abs(1.f - V->SizeSquared()) < THRESH_VECTOR_NORMALIZED);
return 1;
}
static int32 FVector2D_UNM(lua_State *L)
{
FVector2D *V = (FVector2D*)GetCppInstanceFast(L, 1);
if (!V)
{
UE_LOG(LogUnLua, Log, TEXT("%s: Invalid FVector2D!"), ANSI_TO_TCHAR(__FUNCTION__));
return 0;
}
void *Userdata = NewTypedUserdata(L, FVector2D);
new(Userdata) FVector2D(-(*V));
return 1;
}
static const luaL_Reg FVector2DLib[] =
{
{ "Set", FVector2D_Set },
{ "Normalize", FVector2D_Normalize },
{ "IsNormalized", FVector2D_IsNormalized },
{ "Add", UnLua::TMathCalculation<FVector2D, UnLua::TAdd<float>, true>::Calculate },
{ "Sub", UnLua::TMathCalculation<FVector2D, UnLua::TSub<float>, true>::Calculate },
{ "Mul", UnLua::TMathCalculation<FVector2D, UnLua::TMul<float>, true>::Calculate },
{ "Div", UnLua::TMathCalculation<FVector2D, UnLua::TDiv<float>, true>::Calculate },
{ "__add", UnLua::TMathCalculation<FVector2D, UnLua::TAdd<float>>::Calculate },
{ "__sub", UnLua::TMathCalculation<FVector2D, UnLua::TSub<float>>::Calculate },
{ "__mul", UnLua::TMathCalculation<FVector2D, UnLua::TMul<float>>::Calculate },
{ "__div", UnLua::TMathCalculation<FVector2D, UnLua::TDiv<float>>::Calculate },
{ "__unm", FVector2D_UNM },
{ "__call", FVector2D_New },
{ nullptr, nullptr }
};
BEGIN_EXPORT_REFLECTED_CLASS(FVector2D)
ADD_CONST_FUNCTION_EX("Dot", float, operator|, const FVector2D&)
ADD_CONST_FUNCTION_EX("Cross", float, operator^, const FVector2D&)
ADD_FUNCTION(Size)
ADD_FUNCTION(SizeSquared)
ADD_STATIC_FUNCTION_EX("Dist", float, Distance, const FVector2D&, const FVector2D&)
ADD_STATIC_FUNCTION(DistSquared)
ADD_NAMED_FUNCTION("__tostring", ToString)
ADD_LIB(FVector2DLib)
END_EXPORT_CLASS()
IMPLEMENT_EXPORTED_CLASS(FVector2D)
|
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
// This source code is licensed under both the GPLv2 (found in the
// COPYING file in the root directory) and Apache 2.0 License
// (found in the LICENSE.Apache file in the root directory).
#include <memory>
#include <string>
#include "db/db_test_util.h"
#include "db/memtable.h"
#include "db/range_del_aggregator.h"
#include "port/stack_trace.h"
#include "rocksdb/memtablerep.h"
#include "rocksdb/slice_transform.h"
namespace ROCKSDB_NAMESPACE {
class DBMemTableTest : public DBTestBase {
public:
DBMemTableTest() : DBTestBase("/db_memtable_test", /*env_do_fsync=*/true) {}
};
class MockMemTableRep : public MemTableRep {
public:
explicit MockMemTableRep(Allocator* allocator, MemTableRep* rep)
: MemTableRep(allocator), rep_(rep), num_insert_with_hint_(0) {}
KeyHandle Allocate(const size_t len, char** buf) override {
return rep_->Allocate(len, buf);
}
void Insert(KeyHandle handle) override { rep_->Insert(handle); }
void InsertWithHint(KeyHandle handle, void** hint) override {
num_insert_with_hint_++;
EXPECT_NE(nullptr, hint);
last_hint_in_ = *hint;
rep_->InsertWithHint(handle, hint);
last_hint_out_ = *hint;
}
bool Contains(const char* key) const override { return rep_->Contains(key); }
void Get(const LookupKey& k, void* callback_args,
bool (*callback_func)(void* arg, const char* entry)) override {
rep_->Get(k, callback_args, callback_func);
}
size_t ApproximateMemoryUsage() override {
return rep_->ApproximateMemoryUsage();
}
Iterator* GetIterator(Arena* arena) override {
return rep_->GetIterator(arena);
}
void* last_hint_in() { return last_hint_in_; }
void* last_hint_out() { return last_hint_out_; }
int num_insert_with_hint() { return num_insert_with_hint_; }
private:
std::unique_ptr<MemTableRep> rep_;
void* last_hint_in_;
void* last_hint_out_;
int num_insert_with_hint_;
};
class MockMemTableRepFactory : public MemTableRepFactory {
public:
MemTableRep* CreateMemTableRep(const MemTableRep::KeyComparator& cmp,
Allocator* allocator,
const SliceTransform* transform,
Logger* logger) override {
SkipListFactory factory;
MemTableRep* skiplist_rep =
factory.CreateMemTableRep(cmp, allocator, transform, logger);
mock_rep_ = new MockMemTableRep(allocator, skiplist_rep);
return mock_rep_;
}
MemTableRep* CreateMemTableRep(const MemTableRep::KeyComparator& cmp,
Allocator* allocator,
const SliceTransform* transform,
Logger* logger,
uint32_t column_family_id) override {
last_column_family_id_ = column_family_id;
return CreateMemTableRep(cmp, allocator, transform, logger);
}
const char* Name() const override { return "MockMemTableRepFactory"; }
MockMemTableRep* rep() { return mock_rep_; }
bool IsInsertConcurrentlySupported() const override { return false; }
uint32_t GetLastColumnFamilyId() { return last_column_family_id_; }
private:
MockMemTableRep* mock_rep_;
// workaround since there's no port::kMaxUint32 yet.
uint32_t last_column_family_id_ = static_cast<uint32_t>(-1);
};
class TestPrefixExtractor : public SliceTransform {
public:
const char* Name() const override { return "TestPrefixExtractor"; }
Slice Transform(const Slice& key) const override {
const char* p = separator(key);
if (p == nullptr) {
return Slice();
}
return Slice(key.data(), p - key.data() + 1);
}
bool InDomain(const Slice& key) const override {
return separator(key) != nullptr;
}
bool InRange(const Slice& /*key*/) const override { return false; }
private:
const char* separator(const Slice& key) const {
return reinterpret_cast<const char*>(memchr(key.data(), '_', key.size()));
}
};
// Test that ::Add properly returns false when inserting duplicate keys
TEST_F(DBMemTableTest, DuplicateSeq) {
SequenceNumber seq = 123;
std::string value;
MergeContext merge_context;
Options options;
InternalKeyComparator ikey_cmp(options.comparator);
ReadRangeDelAggregator range_del_agg(&ikey_cmp,
kMaxSequenceNumber /* upper_bound */);
// Create a MemTable
InternalKeyComparator cmp(BytewiseComparator());
auto factory = std::make_shared<SkipListFactory>();
options.memtable_factory = factory;
ImmutableCFOptions ioptions(options);
WriteBufferManager wb(options.db_write_buffer_size);
MemTable* mem = new MemTable(cmp, ioptions, MutableCFOptions(options), &wb,
kMaxSequenceNumber, 0 /* column_family_id */);
// Write some keys and make sure it returns false on duplicates
ASSERT_OK(
mem->Add(seq, kTypeValue, "key", "value2", nullptr /* kv_prot_info */));
ASSERT_TRUE(
mem->Add(seq, kTypeValue, "key", "value2", nullptr /* kv_prot_info */)
.IsTryAgain());
// Changing the type should still cause the duplicatae key
ASSERT_TRUE(
mem->Add(seq, kTypeMerge, "key", "value2", nullptr /* kv_prot_info */)
.IsTryAgain());
// Changing the seq number will make the key fresh
ASSERT_OK(mem->Add(seq + 1, kTypeMerge, "key", "value2",
nullptr /* kv_prot_info */));
// Test with different types for duplicate keys
ASSERT_TRUE(
mem->Add(seq, kTypeDeletion, "key", "", nullptr /* kv_prot_info */)
.IsTryAgain());
ASSERT_TRUE(
mem->Add(seq, kTypeSingleDeletion, "key", "", nullptr /* kv_prot_info */)
.IsTryAgain());
// Test the duplicate keys under stress
for (int i = 0; i < 10000; i++) {
bool insert_dup = i % 10 == 1;
if (!insert_dup) {
seq++;
}
Status s = mem->Add(seq, kTypeValue, "foo", "value" + ToString(seq),
nullptr /* kv_prot_info */);
if (insert_dup) {
ASSERT_TRUE(s.IsTryAgain());
} else {
ASSERT_OK(s);
}
}
delete mem;
// Test with InsertWithHint
options.memtable_insert_with_hint_prefix_extractor.reset(
new TestPrefixExtractor()); // which uses _ to extract the prefix
ioptions = ImmutableCFOptions(options);
mem = new MemTable(cmp, ioptions, MutableCFOptions(options), &wb,
kMaxSequenceNumber, 0 /* column_family_id */);
// Insert a duplicate key with _ in it
ASSERT_OK(
mem->Add(seq, kTypeValue, "key_1", "value", nullptr /* kv_prot_info */));
ASSERT_TRUE(
mem->Add(seq, kTypeValue, "key_1", "value", nullptr /* kv_prot_info */)
.IsTryAgain());
delete mem;
// Test when InsertConcurrently will be invoked
options.allow_concurrent_memtable_write = true;
ioptions = ImmutableCFOptions(options);
mem = new MemTable(cmp, ioptions, MutableCFOptions(options), &wb,
kMaxSequenceNumber, 0 /* column_family_id */);
MemTablePostProcessInfo post_process_info;
ASSERT_OK(mem->Add(seq, kTypeValue, "key", "value",
nullptr /* kv_prot_info */, true, &post_process_info));
ASSERT_TRUE(mem->Add(seq, kTypeValue, "key", "value",
nullptr /* kv_prot_info */, true, &post_process_info)
.IsTryAgain());
delete mem;
}
// A simple test to verify that the concurrent merge writes is functional
TEST_F(DBMemTableTest, ConcurrentMergeWrite) {
int num_ops = 1000;
std::string value;
MergeContext merge_context;
Options options;
// A merge operator that is not sensitive to concurrent writes since in this
// test we don't order the writes.
options.merge_operator = MergeOperators::CreateUInt64AddOperator();
// Create a MemTable
InternalKeyComparator cmp(BytewiseComparator());
auto factory = std::make_shared<SkipListFactory>();
options.memtable_factory = factory;
options.allow_concurrent_memtable_write = true;
ImmutableCFOptions ioptions(options);
WriteBufferManager wb(options.db_write_buffer_size);
MemTable* mem = new MemTable(cmp, ioptions, MutableCFOptions(options), &wb,
kMaxSequenceNumber, 0 /* column_family_id */);
// Put 0 as the base
PutFixed64(&value, static_cast<uint64_t>(0));
ASSERT_OK(mem->Add(0, kTypeValue, "key", value, nullptr /* kv_prot_info */));
value.clear();
// Write Merge concurrently
ROCKSDB_NAMESPACE::port::Thread write_thread1([&]() {
MemTablePostProcessInfo post_process_info1;
std::string v1;
for (int seq = 1; seq < num_ops / 2; seq++) {
PutFixed64(&v1, seq);
ASSERT_OK(mem->Add(seq, kTypeMerge, "key", v1, nullptr /* kv_prot_info */,
true, &post_process_info1));
v1.clear();
}
});
ROCKSDB_NAMESPACE::port::Thread write_thread2([&]() {
MemTablePostProcessInfo post_process_info2;
std::string v2;
for (int seq = num_ops / 2; seq < num_ops; seq++) {
PutFixed64(&v2, seq);
ASSERT_OK(mem->Add(seq, kTypeMerge, "key", v2, nullptr /* kv_prot_info */,
true, &post_process_info2));
v2.clear();
}
});
write_thread1.join();
write_thread2.join();
Status status;
ReadOptions roptions;
SequenceNumber max_covering_tombstone_seq = 0;
LookupKey lkey("key", kMaxSequenceNumber);
bool res = mem->Get(lkey, &value, /*timestamp=*/nullptr, &status,
&merge_context, &max_covering_tombstone_seq, roptions);
ASSERT_OK(status);
ASSERT_TRUE(res);
uint64_t ivalue = DecodeFixed64(Slice(value).data());
uint64_t sum = 0;
for (int seq = 0; seq < num_ops; seq++) {
sum += seq;
}
ASSERT_EQ(ivalue, sum);
delete mem;
}
TEST_F(DBMemTableTest, InsertWithHint) {
Options options;
options.allow_concurrent_memtable_write = false;
options.create_if_missing = true;
options.memtable_factory.reset(new MockMemTableRepFactory());
options.memtable_insert_with_hint_prefix_extractor.reset(
new TestPrefixExtractor());
options.env = env_;
Reopen(options);
MockMemTableRep* rep =
reinterpret_cast<MockMemTableRepFactory*>(options.memtable_factory.get())
->rep();
ASSERT_OK(Put("foo_k1", "foo_v1"));
ASSERT_EQ(nullptr, rep->last_hint_in());
void* hint_foo = rep->last_hint_out();
ASSERT_OK(Put("foo_k2", "foo_v2"));
ASSERT_EQ(hint_foo, rep->last_hint_in());
ASSERT_EQ(hint_foo, rep->last_hint_out());
ASSERT_OK(Put("foo_k3", "foo_v3"));
ASSERT_EQ(hint_foo, rep->last_hint_in());
ASSERT_EQ(hint_foo, rep->last_hint_out());
ASSERT_OK(Put("bar_k1", "bar_v1"));
ASSERT_EQ(nullptr, rep->last_hint_in());
void* hint_bar = rep->last_hint_out();
ASSERT_NE(hint_foo, hint_bar);
ASSERT_OK(Put("bar_k2", "bar_v2"));
ASSERT_EQ(hint_bar, rep->last_hint_in());
ASSERT_EQ(hint_bar, rep->last_hint_out());
ASSERT_EQ(5, rep->num_insert_with_hint());
ASSERT_OK(Put("NotInPrefixDomain", "vvv"));
ASSERT_EQ(5, rep->num_insert_with_hint());
ASSERT_EQ("foo_v1", Get("foo_k1"));
ASSERT_EQ("foo_v2", Get("foo_k2"));
ASSERT_EQ("foo_v3", Get("foo_k3"));
ASSERT_EQ("bar_v1", Get("bar_k1"));
ASSERT_EQ("bar_v2", Get("bar_k2"));
ASSERT_EQ("vvv", Get("NotInPrefixDomain"));
}
TEST_F(DBMemTableTest, ColumnFamilyId) {
// Verifies MemTableRepFactory is told the right column family id.
Options options;
options.env = CurrentOptions().env;
options.allow_concurrent_memtable_write = false;
options.create_if_missing = true;
options.memtable_factory.reset(new MockMemTableRepFactory());
DestroyAndReopen(options);
CreateAndReopenWithCF({"pikachu"}, options);
for (uint32_t cf = 0; cf < 2; ++cf) {
ASSERT_OK(Put(cf, "key", "val"));
ASSERT_OK(Flush(cf));
ASSERT_EQ(
cf, static_cast<MockMemTableRepFactory*>(options.memtable_factory.get())
->GetLastColumnFamilyId());
}
}
} // namespace ROCKSDB_NAMESPACE
int main(int argc, char** argv) {
ROCKSDB_NAMESPACE::port::InstallStackTraceHandler();
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
/*
* PROGRAM: Client/Server Common Code
* MODULE: ClumpletWriter.cpp
* DESCRIPTION: Secure handling of clumplet buffers
*
* The contents of this file are subject to the Initial
* Developer's Public License Version 1.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.ibphoenix.com/main.nfs?a=ibphoenix&page=ibp_idpl.
*
* Software distributed under the License is distributed AS IS,
* WITHOUT WARRANTY OF ANY KIND, either express or implied.
* See the License for the specific language governing rights
* and limitations under the License.
*
* The Original Code was created by Nickolay Samofatov
* for the Firebird Open Source RDBMS project.
*
* Copyright (c) 2004 Nickolay Samofatov <nickolay@broadviewsoftware.com>
* and all contributors signed below.
*
* All Rights Reserved.
* Contributor(s): ______________________________________.
*
*
*/
#include "firebird.h"
#include "../common/classes/ClumpletWriter.h"
#include "../common/classes/MetaName.h"
#include "fb_exception.h"
#include "ibase.h"
namespace Firebird {
ClumpletWriter::ClumpletWriter(Kind k, FB_SIZE_T limit, UCHAR tag) :
ClumpletReader(k, NULL, 0), sizeLimit(limit), kindList(NULL), dynamic_buffer(getPool())
{
initNewBuffer(tag);
rewind();
}
ClumpletWriter::ClumpletWriter(MemoryPool& given_pool, Kind k, FB_SIZE_T limit, UCHAR tag) :
ClumpletReader(given_pool, k, NULL, 0), sizeLimit(limit), kindList(NULL), dynamic_buffer(getPool())
{
initNewBuffer(tag);
rewind();
}
const UCHAR* ClumpletWriter::getBuffer() const
{
return dynamic_buffer.begin();
}
const UCHAR* ClumpletWriter::getBufferEnd() const
{
return dynamic_buffer.end();
}
void ClumpletWriter::initNewBuffer(UCHAR tag)
{
switch (kind)
{
case SpbAttach:
if (tag != isc_spb_version1)
{
dynamic_buffer.push(isc_spb_version);
}
// fall down ....
case Tagged:
case Tpb:
case WideTagged:
dynamic_buffer.push(tag);
break;
default:
fb_assert(tag == 0);
break;
}
}
ClumpletWriter::ClumpletWriter(Kind k, FB_SIZE_T limit, const UCHAR* buffer, FB_SIZE_T buffLen, UCHAR tag)
: ClumpletReader(k, NULL, 0), sizeLimit(limit), kindList(NULL), dynamic_buffer(getPool())
{
create(buffer, buffLen, tag);
}
ClumpletWriter::ClumpletWriter(MemoryPool& pool, const KindList* kl, FB_SIZE_T limit,
const UCHAR* buffer, FB_SIZE_T buffLen)
: ClumpletReader(pool, kl, buffer, buffLen), sizeLimit(limit),
kindList(kl), dynamic_buffer(getPool())
{
create(buffer, buffLen, kl->tag);
}
ClumpletWriter::ClumpletWriter(const KindList* kl, FB_SIZE_T limit, const UCHAR* buffer, FB_SIZE_T buffLen)
: ClumpletReader(kl, buffer, buffLen), sizeLimit(limit), kindList(kl), dynamic_buffer(getPool())
{
create(buffer, buffLen, kl->tag);
}
ClumpletWriter::ClumpletWriter(MemoryPool& pool, const KindList* kl, FB_SIZE_T limit)
: ClumpletReader(pool, kl, NULL, 0), sizeLimit(limit),
kindList(kl), dynamic_buffer(getPool())
{
create(NULL, 0, kl->tag);
}
ClumpletWriter::ClumpletWriter(const KindList* kl, FB_SIZE_T limit)
: ClumpletReader(kl, NULL, 0), sizeLimit(limit), kindList(kl), dynamic_buffer(getPool())
{
create(NULL, 0, kl->tag);
}
ClumpletWriter::ClumpletWriter(MemoryPool& pool, const ClumpletWriter& from)
: ClumpletReader(pool, from), sizeLimit(from.sizeLimit), kindList(NULL), dynamic_buffer(getPool())
{
create(from.getBuffer(), from.getBufferEnd() - from.getBuffer(), from.isTagged() ? from.getBufferTag() : 0);
}
ClumpletWriter::ClumpletWriter(const ClumpletWriter& from)
: ClumpletReader(from), sizeLimit(from.sizeLimit), kindList(NULL), dynamic_buffer(getPool())
{
create(from.getBuffer(), from.getBufferEnd() - from.getBuffer(), from.isTagged() ? from.getBufferTag() : 0);
}
void ClumpletWriter::create(const UCHAR* buffer, FB_SIZE_T buffLen, UCHAR tag)
{
if (buffer && buffLen) {
dynamic_buffer.push(buffer, buffLen);
}
else {
initNewBuffer(tag);
}
rewind();
}
ClumpletWriter::ClumpletWriter(MemoryPool& given_pool, Kind k, FB_SIZE_T limit,
const UCHAR* buffer, FB_SIZE_T buffLen, UCHAR tag) :
ClumpletReader(given_pool, k, NULL, 0), sizeLimit(limit), dynamic_buffer(getPool())
{
if (buffer && buffLen) {
dynamic_buffer.push(buffer, buffLen);
}
else {
initNewBuffer(tag);
}
rewind();
}
void ClumpletWriter::reset(UCHAR tag)
{
if (kindList)
{
for (const KindList* kl = kindList; kl->kind != EndOfList; ++kl)
{
if (tag == kl->tag)
{
kind = kl->kind;
dynamic_buffer.shrink(0);
initNewBuffer(tag);
rewind();
return;
}
}
invalid_structure("Unknown tag value - missing in the list of possible");
}
dynamic_buffer.shrink(0);
initNewBuffer(tag);
rewind();
}
void ClumpletWriter::reset(const UCHAR* buffer, const FB_SIZE_T buffLen)
{
dynamic_buffer.clear();
if (buffer && buffLen) {
dynamic_buffer.push(buffer, buffLen);
}
else
{
UCHAR tag = (kind == SpbStart || kind == UnTagged || kind == WideUnTagged) ? 0 : getBufferTag();
initNewBuffer(tag);
}
rewind();
}
void ClumpletWriter::size_overflow()
{
fatal_exception::raise("Clumplet buffer size limit reached");
}
void ClumpletWriter::toVaxInteger(UCHAR* ptr, FB_SIZE_T length, const SINT64 value)
{
fb_assert(ptr && length > 0 && length < 9); // We can't handle numbers bigger than int64.
int shift = 0;
while (length--)
{
*ptr++ = (UCHAR) (value >> shift);
shift += 8;
}
}
void ClumpletWriter::insertInt(UCHAR tag, const SLONG value)
{
UCHAR bytes[sizeof(SLONG)];
toVaxInteger(bytes, sizeof(bytes), value);
insertBytesLengthCheck(tag, bytes, sizeof(bytes));
}
void ClumpletWriter::insertBigInt(UCHAR tag, const SINT64 value)
{
UCHAR bytes[sizeof(SINT64)];
toVaxInteger(bytes, sizeof(bytes), value);
insertBytesLengthCheck(tag, bytes, sizeof(bytes));
}
void ClumpletWriter::insertDouble(UCHAR tag, const double value)
{
union {
double temp_double;
SLONG temp_long[2];
} temp;
fb_assert(sizeof(double) == sizeof(temp));
temp.temp_double = value;
UCHAR bytes[sizeof(double)];
toVaxInteger(bytes, sizeof(SLONG), temp.temp_long[FB_LONG_DOUBLE_FIRST]);
toVaxInteger(bytes + sizeof(SLONG), sizeof(SLONG), temp.temp_long[FB_LONG_DOUBLE_SECOND]);
insertBytesLengthCheck(tag, bytes, sizeof(bytes));
}
void ClumpletWriter::insertTimeStamp(UCHAR tag, const ISC_TIMESTAMP value)
{
UCHAR bytes[sizeof(ISC_TIMESTAMP)];
toVaxInteger(bytes, sizeof(SLONG), value.timestamp_date);
toVaxInteger(bytes + sizeof(SLONG), sizeof(SLONG), value.timestamp_time);
insertBytesLengthCheck(tag, bytes, sizeof(bytes));
}
void ClumpletWriter::insertString(UCHAR tag, const AbstractString& str)
{
insertString(tag, str.c_str(), str.length());
}
void ClumpletWriter::insertString(UCHAR tag, const MetaName& str)
{
insertString(tag, str.c_str(), str.length());
}
void ClumpletWriter::insertString(UCHAR tag, const char* str)
{
insertString(tag, str, strlen(str));
}
void ClumpletWriter::insertString(UCHAR tag, const char* str, FB_SIZE_T length)
{
insertBytesLengthCheck(tag, str, length);
}
void ClumpletWriter::insertData(UCHAR tag, const UCharBuffer& data)
{
insertBytesLengthCheck(tag, data.begin(), data.getCount());
}
void ClumpletWriter::insertBytes(UCHAR tag, const void* bytes, FB_SIZE_T length)
{
insertBytesLengthCheck(tag, bytes, length);
}
void ClumpletWriter::insertByte(UCHAR tag, const UCHAR byte)
{
insertBytesLengthCheck(tag, &byte, 1);
}
void ClumpletWriter::insertBytesLengthCheck(UCHAR tag, const void* bytes, const FB_SIZE_T length)
{
// Check that we're not beyond the end of buffer.
// We get there when we set end marker.
if (cur_offset > dynamic_buffer.getCount())
{
usage_mistake("write past EOF");
return;
}
UCHAR lenSize = 0;
// Check length according to clumplet type
// Perform structure upgrade when needed and possible
for(;;)
{
const ClumpletType t = getClumpletType(tag);
string m;
switch (t)
{
case Wide:
if (length > MAX_ULONG)
{
m.printf("attempt to store %d bytes in a clumplet", length);
break;
}
lenSize = 4;
break;
case TraditionalDpb:
if (length > MAX_UCHAR)
{
m.printf("attempt to store %d bytes in a clumplet with maximum size 255 bytes", length);
break;
}
lenSize = 1;
break;
case SingleTpb:
if (length > 0)
{
m.printf("attempt to store data in dataless clumplet");
}
break;
case StringSpb:
if (length > MAX_USHORT)
{
m.printf("attempt to store %d bytes in a clumplet", length);
break;
}
lenSize = 2;
break;
case IntSpb:
if (length != 4)
{
m.printf("attempt to store %d bytes in a clumplet, need 4", length);
}
break;
case BigIntSpb:
if (length != 8)
{
m.printf("attempt to store %d bytes in a clumplet, need 8", length);
}
break;
case ByteSpb:
if (length != 1)
{
m.printf("attempt to store %d bytes in a clumplet, need 1", length);
}
break;
}
if (m.isEmpty())
{
// OK, no errors
break;
}
if (!upgradeVersion())
{
// can't upgrade - report failure
usage_mistake(m.c_str());
return;
}
}
// Check that resulting data doesn't overflow size limit
if (dynamic_buffer.getCount() + length + lenSize + 1 > sizeLimit) {
size_overflow();
}
// Insert the data
const FB_SIZE_T saved_offset = cur_offset;
dynamic_buffer.insert(cur_offset++, tag);
switch (lenSize)
{
case 1:
dynamic_buffer.insert(cur_offset++, static_cast<UCHAR>(length));
break;
case 2:
{
UCHAR b[2];
toVaxInteger(b, sizeof(b), length);
dynamic_buffer.insert(cur_offset, b, sizeof(b));
cur_offset += 2;
}
break;
case 4:
{
UCHAR b[4];
toVaxInteger(b, sizeof(b), length);
dynamic_buffer.insert(cur_offset, b, sizeof(b));
cur_offset += 4;
}
break;
}
dynamic_buffer.insert(cur_offset, static_cast<const UCHAR*>(bytes), length);
const FB_SIZE_T new_offset = cur_offset + length;
cur_offset = saved_offset;
adjustSpbState();
cur_offset = new_offset;
}
void ClumpletWriter::insertTag(UCHAR tag)
{
insertBytesLengthCheck(tag, 0, 0);
}
void ClumpletWriter::insertEndMarker(UCHAR tag)
{
// Check that we're not beyond the end of buffer.
// We get there when we set end marker.
if (cur_offset > dynamic_buffer.getCount())
{
usage_mistake("write past EOF");
return;
}
// Check that resulting data doesn't overflow size limit
if (cur_offset + 1 > sizeLimit) {
size_overflow();
}
dynamic_buffer.shrink(cur_offset);
dynamic_buffer.push(tag);
cur_offset += 2; // Go past EOF to indicate we set the marker
}
void ClumpletWriter::deleteClumplet()
{
const UCHAR* clumplet = getBuffer() + cur_offset;
const UCHAR* buffer_end = getBufferEnd();
// Check for EOF
if (clumplet >= buffer_end)
{
usage_mistake("write past EOF");
return;
}
if (buffer_end - clumplet < 2)
{
// It appears we're erasing EOF marker
dynamic_buffer.shrink(cur_offset);
}
else {
dynamic_buffer.removeCount(cur_offset, getClumpletSize(true, true, true));
}
}
bool ClumpletWriter::deleteWithTag(UCHAR tag)
{
bool rc = false;
while (find(tag))
{
rc = true;
deleteClumplet();
}
return rc;
}
bool ClumpletWriter::upgradeVersion()
{
// Sanity check
if (!kindList)
{
return false;
}
// Check for required version - use highmost one
const KindList* newest = kindList;
for (const KindList* itr = kindList; itr->tag != EndOfList; ++itr)
{
if (itr->tag > newest->tag)
{
newest = itr;
}
}
if (getBufferLength() && newest->tag <= getBufferTag())
{
return false;
}
// Copy data to new clumplet writer
FB_SIZE_T newPos = 0;
ClumpletWriter newPb(newest->kind, sizeLimit, newest->tag);
const FB_SIZE_T currentPosition = cur_offset;
for(rewind(); !isEof(); moveNext())
{
if (currentPosition == cur_offset)
{
newPos = newPb.cur_offset;
}
newPb.insertClumplet(getClumplet());
newPb.moveNext();
}
// Return it to current clumplet writer in new format
dynamic_buffer.clear();
kind = newest->kind;
dynamic_buffer.push(newPb.dynamic_buffer.begin(), newPb.dynamic_buffer.getCount());
// Set pointer to correct position
if (newPos)
{
cur_offset = newPos;
}
else
{
rewind();
}
return true;
}
void ClumpletWriter::insertClumplet(const SingleClumplet& clumplet)
{
insertBytes(clumplet.tag, clumplet.data, clumplet.size);
}
void ClumpletWriter::clear()
{
reset(isTagged() ? getBufferTag() : 0);
}
} // namespace
|
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2021-2021 ArangoDB GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Michael Hackstein
////////////////////////////////////////////////////////////////////////////////
#include "FixedOutputExecutionBlockMock.h"
#include "Aql/AqlCallStack.h"
#include "Basics/voc-errors.h"
using namespace arangodb;
using namespace arangodb::aql;
using namespace arangodb::tests::aql;
namespace {
// NOTE copy pasted from Waiting ExecutionBlock mock
static auto blocksToInfos(std::deque<SharedAqlItemBlockPtr> const& blocks)
-> RegisterInfos {
// If there are no blocks injected, we have nothing to analyze.
// This Mock does only work with predefined data output.
TRI_ASSERT(!blocks.empty());
auto readInput = RegIdSet{};
auto writeOutput = RegIdSet{};
RegIdSet toClear{};
RegIdSetStack toKeep{{}};
RegisterCount regs = 1;
for (auto const& b : blocks) {
if (b != nullptr) {
// Find the first non-nullptr block
regs = b->numRegisters();
break;
}
}
for (RegisterId::value_t r = 0; r < regs; ++r) {
toKeep.back().emplace(r);
}
return {readInput, writeOutput, regs, regs, toClear, toKeep};
}
} // namespace
FixedOutputExecutionBlockMock::FixedOutputExecutionBlockMock(
ExecutionEngine* engine, ExecutionNode const* node,
std::deque<SharedAqlItemBlockPtr>&& data)
: ExecutionBlock(engine, node),
_infos{::blocksToInfos(data)},
_blockData{std::move(data)} {}
std::pair<ExecutionState, arangodb::Result>
FixedOutputExecutionBlockMock::initializeCursor(InputAqlItemRow const& input) {
// Nothing to do
return {ExecutionState::DONE, TRI_ERROR_NO_ERROR};
}
std::tuple<ExecutionState, SkipResult, SharedAqlItemBlockPtr>
FixedOutputExecutionBlockMock::execute(AqlCallStack const& stack) {
SkipResult skipped{};
for (size_t i = 1; i < stack.subqueryLevel(); ++i) {
// For every additional subquery level we need to increase the skipped
// subquery level
skipped.incrementSubquery();
}
if (_blockData.empty()) {
return {ExecutionState::DONE, skipped, nullptr};
}
// This Block is very dump, it does NOT care what you ask it for. it will just
// deliver what it has in the queue
auto block = _blockData.front();
_blockData.pop_front();
ExecutionState state =
_blockData.empty() ? ExecutionState::DONE : ExecutionState::HASMORE;
return {state, skipped, block};
}
|
// Copyright 2020 The IREE Authors
//
// Licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include <utility>
#include "iree/compiler/Dialect/Flow/IR/FlowDialect.h"
#include "iree/compiler/Dialect/Flow/IR/FlowOps.h"
#include "iree/compiler/Dialect/Flow/Transforms/PassDetail.h"
#include "iree/compiler/Dialect/Flow/Transforms/Passes.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/Builders.h"
#include "mlir/Pass/Pass.h"
namespace mlir {
namespace iree_compiler {
namespace IREE {
namespace Flow {
class StripAndSplatConstantVariablesPass
: public StripAndSplatConstantVariablesBase<
StripAndSplatConstantVariablesPass> {
public:
StripAndSplatConstantVariablesPass() = default;
void getDependentDialects(DialectRegistry ®istry) const override {
registry.insert<IREE::Flow::FlowDialect>();
}
void runOnOperation() override {
auto moduleOp = getOperation();
auto builder = OpBuilder::atBlockBegin(moduleOp.getBody());
// Use a heuristic to space out splat values in hopes of avoiding NaN and
// INF values at runtime:
// floats: 1/1, 1/2, 1/3, ...
// ints: 1, 2, 3, 4, ...
// TODO(scotttodd): flags to control numbers used (all 0, all 1, increasing)
int replaceIndex = 1;
moduleOp.walk([&](VariableOp op) {
// Only strip constant variables.
if (op.is_mutable()) {
return;
}
// Only strip tensor type constants (to replace with dense<>).
if (!op.type().isa<TensorType>()) {
return;
}
auto tensorType = op.type().cast<TensorType>();
auto elementType = tensorType.getElementType();
DenseElementsAttr newValue;
if (elementType.isa<FloatType>()) {
newValue = DenseElementsAttr::get(
tensorType, FloatAttr::get(elementType, 1.0 / replaceIndex));
} else {
newValue = DenseElementsAttr::get(
tensorType, IntegerAttr::get(elementType, replaceIndex));
}
builder.setInsertionPointAfter(op);
auto newOp = builder.create<VariableOp>(
op.getLoc(), op.sym_name(), op.is_mutable(), op.type(), newValue);
newOp.setVisibility(op.getVisibility());
newOp->setAttr("noinline", UnitAttr::get(builder.getContext()));
op.erase();
replaceIndex++;
});
}
};
std::unique_ptr<OperationPass<ModuleOp>>
createStripAndSplatConstantVariablesPass() {
return std::make_unique<StripAndSplatConstantVariablesPass>();
}
} // namespace Flow
} // namespace IREE
} // namespace iree_compiler
} // namespace mlir
|
/*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 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 <AK/Function.h>
#include <AK/JsonArray.h>
#include <AK/JsonObject.h>
#include <AK/JsonParser.h>
#include <AK/JsonValue.h>
#include <AK/StringBuilder.h>
namespace AK {
JsonValue::JsonValue(Type type)
: m_type(type)
{
}
JsonValue::JsonValue(const JsonValue& other)
{
copy_from(other);
}
JsonValue& JsonValue::operator=(const JsonValue& other)
{
if (this != &other) {
clear();
copy_from(other);
}
return *this;
}
void JsonValue::copy_from(const JsonValue& other)
{
m_type = other.m_type;
switch (m_type) {
case Type::String:
ASSERT(!m_value.as_string);
m_value.as_string = other.m_value.as_string;
m_value.as_string->ref();
break;
case Type::Object:
m_value.as_object = new JsonObject(*other.m_value.as_object);
break;
case Type::Array:
m_value.as_array = new JsonArray(*other.m_value.as_array);
break;
default:
m_value.as_string = other.m_value.as_string;
break;
}
}
JsonValue::JsonValue(JsonValue&& other)
{
m_type = exchange(other.m_type, Type::Undefined);
m_value.as_string = exchange(other.m_value.as_string, nullptr);
}
JsonValue& JsonValue::operator=(JsonValue&& other)
{
if (this != &other) {
clear();
m_type = exchange(other.m_type, Type::Undefined);
m_value.as_string = exchange(other.m_value.as_string, nullptr);
}
return *this;
}
JsonValue::JsonValue(i32 value)
: m_type(Type::Int32)
{
m_value.as_i32 = value;
}
JsonValue::JsonValue(u32 value)
: m_type(Type::UnsignedInt32)
{
m_value.as_u32 = value;
}
JsonValue::JsonValue(i64 value)
: m_type(Type::Int64)
{
m_value.as_i64 = value;
}
JsonValue::JsonValue(u64 value)
: m_type(Type::UnsignedInt64)
{
m_value.as_u64 = value;
}
JsonValue::JsonValue(const char* cstring)
: JsonValue(String(cstring))
{
}
#ifndef KERNEL
JsonValue::JsonValue(double value)
: m_type(Type::Double)
{
m_value.as_double = value;
}
#endif
JsonValue::JsonValue(bool value)
: m_type(Type::Bool)
{
m_value.as_bool = value;
}
JsonValue::JsonValue(const String& value)
{
if (value.is_null()) {
m_type = Type::Null;
} else {
m_type = Type::String;
m_value.as_string = const_cast<StringImpl*>(value.impl());
m_value.as_string->ref();
}
}
JsonValue::JsonValue(const IPv4Address& value)
: JsonValue(value.to_string())
{
}
JsonValue::JsonValue(const JsonObject& value)
: m_type(Type::Object)
{
m_value.as_object = new JsonObject(value);
}
JsonValue::JsonValue(const JsonArray& value)
: m_type(Type::Array)
{
m_value.as_array = new JsonArray(value);
}
JsonValue::JsonValue(JsonObject&& value)
: m_type(Type::Object)
{
m_value.as_object = new JsonObject(move(value));
}
JsonValue::JsonValue(JsonArray&& value)
: m_type(Type::Array)
{
m_value.as_array = new JsonArray(move(value));
}
void JsonValue::clear()
{
switch (m_type) {
case Type::String:
m_value.as_string->deref();
break;
case Type::Object:
delete m_value.as_object;
break;
case Type::Array:
delete m_value.as_array;
break;
default:
break;
}
m_type = Type::Undefined;
m_value.as_string = nullptr;
}
JsonValue JsonValue::from_string(const StringView& input)
{
return JsonParser(input).parse();
}
}
|
// Copyright (C) 2013 Davis E. King (davis@dlib.net)
// License: Boost Software License See LICENSE.txt for the full license.
#include "opaque_types.h"
#include <dlib/python.h>
#include <dlib/matrix.h>
#include <dlib/geometry.h>
#include <dlib/image_transforms.h>
#include <pybind11/stl_bind.h>
#include "indexing.h"
using namespace dlib;
using namespace std;
typedef matrix<double,0,1> cv;
void cv_set_size(cv& m, long s)
{
m.set_size(s);
m = 0;
}
double dotprod ( const cv& a, const cv& b)
{
return dot(a,b);
}
string cv__str__(const cv& v)
{
ostringstream sout;
for (long i = 0; i < v.size(); ++i)
{
sout << v(i);
if (i+1 < v.size())
sout << "\n";
}
return sout.str();
}
string cv__repr__ (const cv& v)
{
std::ostringstream sout;
sout << "dlib.vector([";
for (long i = 0; i < v.size(); ++i)
{
sout << v(i);
if (i+1 < v.size())
sout << ", ";
}
sout << "])";
return sout.str();
}
std::shared_ptr<cv> cv_from_object(py::object obj)
{
try {
long nr = obj.cast<long>();
auto temp = std::make_shared<cv>(nr);
*temp = 0;
return temp;
} catch(py::cast_error&) {
py::list li = obj.cast<py::list>();
const long nr = len(obj);
auto temp = std::make_shared<cv>(nr);
for ( long r = 0; r < nr; ++r)
{
(*temp)(r) = li[r].cast<double>();
}
return temp;
}
}
long cv__len__(cv& c)
{
return c.size();
}
void cv__setitem__(cv& c, long p, double val)
{
if (p < 0) {
p = c.size() + p; // negative index
}
if (p > c.size()-1) {
PyErr_SetString( PyExc_IndexError, "index out of range"
);
throw py::error_already_set();
}
c(p) = val;
}
double cv__getitem__(cv& m, long r)
{
if (r < 0) {
r = m.size() + r; // negative index
}
if (r > m.size()-1 || r < 0) {
PyErr_SetString( PyExc_IndexError, "index out of range"
);
throw py::error_already_set();
}
return m(r);
}
cv cv__getitem2__(cv& m, py::slice r)
{
size_t start, stop, step, slicelength;
if (!r.compute(m.size(), &start, &stop, &step, &slicelength))
throw py::error_already_set();
cv temp(slicelength);
for (size_t i = 0; i < slicelength; ++i) {
temp(i) = m(start); start += step;
}
return temp;
}
py::tuple cv_get_matrix_size(cv& m)
{
return py::make_tuple(m.nr(), m.nc());
}
// ----------------------------------------------------------------------------------------
string point_transform_projective__repr__ (const point_transform_projective& tform)
{
std::ostringstream sout;
sout << "point_transform_projective(\n" << csv << tform.get_m() << ")";
return sout.str();
}
string point_transform_projective__str__(const point_transform_projective& tform)
{
std::ostringstream sout;
sout << "(" << csv << tform.get_m() << ")";
return sout.str();
}
point_transform_projective init_point_transform_projective (
const numpy_image<double>& m_
)
{
const_image_view<numpy_image<double>> m(m_);
DLIB_CASSERT(m.nr() == 3 && m.nc() == 3,
"The matrix used to construct a point_transform_projective object must be 3x3.");
return point_transform_projective(mat(m));
}
// ----------------------------------------------------------------------------------------
string point__repr__ (const point& p)
{
std::ostringstream sout;
sout << "point(" << p.x() << ", " << p.y() << ")";
return sout.str();
}
string point__str__(const point& p)
{
std::ostringstream sout;
sout << "(" << p.x() << ", " << p.y() << ")";
return sout.str();
}
string dpoint__repr__ (const dpoint& p)
{
std::ostringstream sout;
sout << "dpoint(" << p.x() << ", " << p.y() << ")";
return sout.str();
}
string dpoint__str__(const dpoint& p)
{
std::ostringstream sout;
sout << "(" << p.x() << ", " << p.y() << ")";
return sout.str();
}
long point_x(const point& p) { return p.x(); }
long point_y(const point& p) { return p.y(); }
double dpoint_x(const dpoint& p) { return p.x(); }
double dpoint_y(const dpoint& p) { return p.y(); }
// ----------------------------------------------------------------------------------------
template <typename T>
dlib::vector<T,2> numpy_to_dlib_vect (
const py::array_t<T>& v
)
/*!
ensures
- converts a numpy array with 2 elements into a dlib::vector<T,2>
!*/
{
DLIB_CASSERT(v.size() == 2, "You can only convert a numpy array to a dlib point or dpoint if it has just 2 elements.");
DLIB_CASSERT(v.ndim() == 1 || v.ndim() == 2, "The input needs to be interpretable as a row or column vector.");
dpoint temp;
if (v.ndim() == 1)
{
temp.x() = v.at(0);
temp.y() = v.at(1);
}
else if (v.shape(0) == 2)
{
temp.x() = v.at(0,0);
temp.y() = v.at(1,0);
}
else
{
temp.x() = v.at(0,0);
temp.y() = v.at(0,1);
}
return temp;
}
// ----------------------------------------------------------------------------------------
point_transform_projective py_find_projective_transform (
const std::vector<dpoint>& from_points,
const std::vector<dpoint>& to_points
)
{
DLIB_CASSERT(from_points.size() == to_points.size(),
"from_points and to_points must have the same number of points.");
DLIB_CASSERT(from_points.size() >= 4,
"You need at least 4 points to find a projective transform.");
return find_projective_transform(from_points, to_points);
}
template <typename T>
point_transform_projective py_find_projective_transform2 (
const numpy_image<T>& from_points_,
const numpy_image<T>& to_points_
)
{
const_image_view<numpy_image<T>> from_points(from_points_);
const_image_view<numpy_image<T>> to_points(to_points_);
DLIB_CASSERT(from_points.nc() == 2 && to_points.nc() == 2,
"Both from_points and to_points must be arrays with 2 columns.");
DLIB_CASSERT(from_points.nr() == to_points.nr(),
"from_points and to_points must have the same number of rows.");
DLIB_CASSERT(from_points.nr() >= 4,
"You need at least 4 rows in the input matrices to find a projective transform.");
std::vector<dpoint> from, to;
for (long r = 0; r < from_points.nr(); ++r)
{
from.push_back(dpoint(from_points[r][0], from_points[r][1]));
to.push_back(dpoint(to_points[r][0], to_points[r][1]));
}
return find_projective_transform(from, to);
}
// ----------------------------------------------------------------------------------------
void register_point_transform_projective(
py::module& m
)
{
py::class_<point_transform_projective>(m, "point_transform_projective",
"This is an object that takes 2D points and applies a projective transformation to them.")
.def(py::init<>(),
"ensures \n\
- This object will perform the identity transform. That is, given a point \n\
as input it will return the same point as output. Therefore, self.m == a 3x3 identity matrix."
/*!
ensures
- This object will perform the identity transform. That is, given a point
as input it will return the same point as output. Therefore, self.m == a 3x3 identity matrix.
!*/
)
.def(py::init<>(&init_point_transform_projective), py::arg("m"),
"ensures \n\
- self.m == m"
)
.def("__repr__", &point_transform_projective__repr__)
.def("__str__", &point_transform_projective__str__)
.def("__call__", [](const point_transform_projective& tform, const dpoint& p){return tform(p);}, py::arg("p"),
"ensures \n\
- Applies the projective transformation defined by this object's constructor \n\
to p and returns the result. To define this precisely: \n\
- let p_h == the point p in homogeneous coordinates. That is: \n\
- p_h.x == p.x \n\
- p_h.y == p.y \n\
- p_h.z == 1 \n\
- let x == m*p_h \n\
- Then this function returns the value x/x.z"
/*!
ensures
- Applies the projective transformation defined by this object's constructor
to p and returns the result. To define this precisely:
- let p_h == the point p in homogeneous coordinates. That is:
- p_h.x == p.x
- p_h.y == p.y
- p_h.z == 1
- let x == m*p_h
- Then this function returns the value x/x.z
!*/
)
.def_property_readonly("m", [](const point_transform_projective& tform){numpy_image<double> tmp; assign_image(tmp,tform.get_m()); return tmp;},
"m is the 3x3 matrix that defines the projective transformation.")
.def(py::pickle(&getstate<point_transform_projective>, &setstate<point_transform_projective>));
m.def("inv", [](const point_transform_projective& tform){return inv(tform); }, py::arg("trans"),
"ensures \n\
- If trans is an invertible transformation then this function returns a new \n\
transformation that is the inverse of trans. "
/*!
ensures
- If trans is an invertible transformation then this function returns a new
transformation that is the inverse of trans.
!*/
);
m.def("find_projective_transform", &py_find_projective_transform, py::arg("from_points"), py::arg("to_points"),
"requires \n\
- len(from_points) == len(to_points) \n\
- len(from_points) >= 4 \n\
ensures \n\
- returns a point_transform_projective object, T, such that for all valid i: \n\
length(T(from_points[i]) - to_points[i]) \n\
is minimized as often as possible. That is, this function finds the projective \n\
transform that maps points in from_points to points in to_points. If no \n\
projective transform exists which performs this mapping exactly then the one \n\
which minimizes the mean squared error is selected. "
/*!
requires
- len(from_points) == len(to_points)
- len(from_points) >= 4
ensures
- returns a point_transform_projective object, T, such that for all valid i:
length(T(from_points[i]) - to_points[i])
is minimized as often as possible. That is, this function finds the projective
transform that maps points in from_points to points in to_points. If no
projective transform exists which performs this mapping exactly then the one
which minimizes the mean squared error is selected.
!*/
);
const char* docs =
"requires \n\
- from_points and to_points have two columns and the same number of rows. \n\
Moreover, they have at least 4 rows. \n\
ensures \n\
- returns a point_transform_projective object, T, such that for all valid i: \n\
length(T(dpoint(from_points[i])) - dpoint(to_points[i])) \n\
is minimized as often as possible. That is, this function finds the projective \n\
transform that maps points in from_points to points in to_points. If no \n\
projective transform exists which performs this mapping exactly then the one \n\
which minimizes the mean squared error is selected. ";
/*!
requires
- from_points and to_points have two columns and the same number of rows.
Moreover, they have at least 4 rows.
ensures
- returns a point_transform_projective object, T, such that for all valid i:
length(T(dpoint(from_points[i])) - dpoint(to_points[i]))
is minimized as often as possible. That is, this function finds the projective
transform that maps points in from_points to points in to_points. If no
projective transform exists which performs this mapping exactly then the one
which minimizes the mean squared error is selected.
!*/
m.def("find_projective_transform", &py_find_projective_transform2<float>, py::arg("from_points"), py::arg("to_points"), docs);
m.def("find_projective_transform", &py_find_projective_transform2<double>, py::arg("from_points"), py::arg("to_points"), docs);
}
// ----------------------------------------------------------------------------------------
double py_polygon_area(
const std::vector<dpoint>& pts
)
{
return polygon_area(pts);
}
double py_polygon_area2(
const py::list& pts
)
{
std::vector<dpoint> temp(len(pts));
for (size_t i = 0; i < temp.size(); ++i)
temp[i] = pts[i].cast<dpoint>();
return polygon_area(temp);
}
// ----------------------------------------------------------------------------------------
void bind_vector(py::module& m)
{
{
py::class_<cv, std::shared_ptr<cv>>(m, "vector", "This object represents the mathematical idea of a column vector.")
.def(py::init())
.def("set_size", &cv_set_size)
.def("resize", &cv_set_size)
.def(py::init(&cv_from_object))
.def("__repr__", &cv__repr__)
.def("__str__", &cv__str__)
.def("__len__", &cv__len__)
.def("__getitem__", &cv__getitem__)
.def("__getitem__", &cv__getitem2__)
.def("__setitem__", &cv__setitem__)
.def_property_readonly("shape", &cv_get_matrix_size)
.def(py::pickle(&getstate<cv>, &setstate<cv>));
m.def("dot", &dotprod, "Compute the dot product between two dense column vectors.");
}
{
typedef point type;
py::class_<type>(m, "point", "This object represents a single point of integer coordinates that maps directly to a dlib::point.")
.def(py::init<long,long>(), py::arg("x"), py::arg("y"))
.def(py::init<dpoint>(), py::arg("p"))
.def(py::init<>(&numpy_to_dlib_vect<long>), py::arg("v"))
.def(py::init<>(&numpy_to_dlib_vect<float>), py::arg("v"))
.def(py::init<>(&numpy_to_dlib_vect<double>), py::arg("v"))
.def("__repr__", &point__repr__)
.def("__str__", &point__str__)
.def(py::self + py::self)
.def(py::self - py::self)
.def(py::self / double())
.def(py::self * double())
.def(double() * py::self)
.def("normalize", &type::normalize, "Returns a unit normalized copy of this vector.")
.def_property("x", &point_x, [](point& p, long x){p.x()=x;}, "The x-coordinate of the point.")
.def_property("y", &point_y, [](point& p, long y){p.x()=y;}, "The y-coordinate of the point.")
.def(py::pickle(&getstate<type>, &setstate<type>));
}
{
typedef std::vector<point> type;
py::bind_vector<type>(m, "points", "An array of point objects.")
.def(py::init<size_t>(), py::arg("initial_size"))
.def("clear", &type::clear)
.def("resize", resize<type>)
.def("extend", extend_vector_with_python_list<point>)
.def(py::pickle(&getstate<type>, &setstate<type>));
}
{
typedef dpoint type;
py::class_<type>(m, "dpoint", "This object represents a single point of floating point coordinates that maps directly to a dlib::dpoint.")
.def(py::init<double,double>(), py::arg("x"), py::arg("y"))
.def(py::init<point>(), py::arg("p"))
.def(py::init<>(&numpy_to_dlib_vect<long>), py::arg("v"))
.def(py::init<>(&numpy_to_dlib_vect<float>), py::arg("v"))
.def(py::init<>(&numpy_to_dlib_vect<double>), py::arg("v"))
.def("__repr__", &dpoint__repr__)
.def("__str__", &dpoint__str__)
.def("normalize", &type::normalize, "Returns a unit normalized copy of this vector.")
.def_property("x", &dpoint_x, [](dpoint& p, double x){p.x()=x;}, "The x-coordinate of the dpoint.")
.def_property("y", &dpoint_y, [](dpoint& p, double y){p.x()=y;}, "The y-coordinate of the dpoint.")
.def(py::self + py::self)
.def(py::self - py::self)
.def(py::self / double())
.def(py::self * double())
.def(double() * py::self)
.def(py::pickle(&getstate<type>, &setstate<type>));
}
{
typedef std::vector<dpoint> type;
py::bind_vector<type>(m, "dpoints", "An array of dpoint objects.")
.def(py::init<size_t>(), py::arg("initial_size"))
.def("clear", &type::clear)
.def("resize", resize<type>)
.def("extend", extend_vector_with_python_list<dpoint>)
.def(py::pickle(&getstate<type>, &setstate<type>));
}
m.def("length", [](const point& p){return length(p); },
"returns the distance from p to the origin, i.e. the L2 norm of p.", py::arg("p"));
m.def("length", [](const dpoint& p){return length(p); },
"returns the distance from p to the origin, i.e. the L2 norm of p.", py::arg("p"));
m.def("dot", [](const point& a, const point& b){return dot(a,b); }, "Returns the dot product of the points a and b.", py::arg("a"), py::arg("b"));
m.def("dot", [](const dpoint& a, const dpoint& b){return dot(a,b); }, "Returns the dot product of the points a and b.", py::arg("a"), py::arg("b"));
register_point_transform_projective(m);
m.def("polygon_area", &py_polygon_area, py::arg("pts"));
m.def("polygon_area", &py_polygon_area2, py::arg("pts"),
"ensures \n\
- If you walk the points pts in order to make a closed polygon, what is its \n\
area? This function returns that area. It uses the shoelace formula to \n\
compute the result and so works for general non-self-intersecting polygons."
/*!
ensures
- If you walk the points pts in order to make a closed polygon, what is its
area? This function returns that area. It uses the shoelace formula to
compute the result and so works for general non-self-intersecting polygons.
!*/
);
}
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: UnityEngine.MonoBehaviour
#include "UnityEngine/MonoBehaviour.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
}
// Forward declaring namespace: UnityEngine::UI
namespace UnityEngine::UI {
// Forward declaring type: Button
class Button;
}
// Forward declaring namespace: System::Collections
namespace System::Collections {
// Forward declaring type: IEnumerator
class IEnumerator;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Forward declaring type: ClickButtonWithCommandArgument
class ClickButtonWithCommandArgument;
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(GlobalNamespace::ClickButtonWithCommandArgument);
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::ClickButtonWithCommandArgument*, "", "ClickButtonWithCommandArgument");
// Type namespace:
namespace GlobalNamespace {
// Size: 0x28
#pragma pack(push, 1)
// Autogenerated type: ClickButtonWithCommandArgument
// [TokenAttribute] Offset: FFFFFFFF
class ClickButtonWithCommandArgument : public UnityEngine::MonoBehaviour {
public:
// Nested type: GlobalNamespace::ClickButtonWithCommandArgument::$Start$d__2
class $Start$d__2;
#ifdef USE_CODEGEN_FIELDS
public:
#else
protected:
#endif
// private System.String _argument
// Size: 0x8
// Offset: 0x18
::Il2CppString* argument;
// Field size check
static_assert(sizeof(::Il2CppString*) == 0x8);
// private UnityEngine.UI.Button _button
// Size: 0x8
// Offset: 0x20
UnityEngine::UI::Button* button;
// Field size check
static_assert(sizeof(UnityEngine::UI::Button*) == 0x8);
public:
// Deleting conversion operator: operator System::IntPtr
constexpr operator System::IntPtr() const noexcept = delete;
// Get instance field reference: private System.String _argument
::Il2CppString*& dyn__argument();
// Get instance field reference: private UnityEngine.UI.Button _button
UnityEngine::UI::Button*& dyn__button();
// protected System.Collections.IEnumerator Start()
// Offset: 0x135E1B8
System::Collections::IEnumerator* Start();
// public System.Void .ctor()
// Offset: 0x135E254
// Implemented from: UnityEngine.MonoBehaviour
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static ClickButtonWithCommandArgument* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::ClickButtonWithCommandArgument::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<ClickButtonWithCommandArgument*, creationType>()));
}
}; // ClickButtonWithCommandArgument
#pragma pack(pop)
static check_size<sizeof(ClickButtonWithCommandArgument), 32 + sizeof(UnityEngine::UI::Button*)> __GlobalNamespace_ClickButtonWithCommandArgumentSizeCheck;
static_assert(sizeof(ClickButtonWithCommandArgument) == 0x28);
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: GlobalNamespace::ClickButtonWithCommandArgument::Start
// Il2CppName: Start
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::Collections::IEnumerator* (GlobalNamespace::ClickButtonWithCommandArgument::*)()>(&GlobalNamespace::ClickButtonWithCommandArgument::Start)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::ClickButtonWithCommandArgument*), "Start", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: GlobalNamespace::ClickButtonWithCommandArgument::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
|
// RUN: %clang_cc1 -verify -fopenmp -ferror-limit 150 -o - %s -Wuninitialized
// RUN: %clang_cc1 -verify -fopenmp -std=c++98 -ferror-limit 150 -o - %s -Wuninitialized
// RUN: %clang_cc1 -verify -fopenmp -std=c++11 -ferror-limit 150 -o - %s -Wuninitialized
// RUN: %clang_cc1 -verify -fopenmp-simd -ferror-limit 150 -o - %s -Wuninitialized
// RUN: %clang_cc1 -verify -fopenmp-simd -std=c++98 -ferror-limit 150 -o - %s -Wuninitialized
// RUN: %clang_cc1 -verify -fopenmp-simd -std=c++11 -ferror-limit 150 -o - %s -Wuninitialized
typedef void **omp_allocator_handle_t;
extern const omp_allocator_handle_t omp_null_allocator;
extern const omp_allocator_handle_t omp_default_mem_alloc;
extern const omp_allocator_handle_t omp_large_cap_mem_alloc;
extern const omp_allocator_handle_t omp_const_mem_alloc;
extern const omp_allocator_handle_t omp_high_bw_mem_alloc;
extern const omp_allocator_handle_t omp_low_lat_mem_alloc;
extern const omp_allocator_handle_t omp_cgroup_mem_alloc;
extern const omp_allocator_handle_t omp_pteam_mem_alloc;
extern const omp_allocator_handle_t omp_thread_mem_alloc;
void foo() {
}
bool foobool(int argc) {
return argc;
}
void foobar(int &ref) {
#pragma omp taskgroup task_reduction(+:ref)
#pragma omp taskloop simd in_reduction(+:ref)
for (int i = 0; i < 10; ++i)
foo();
}
void foobar1(int &ref) {
#pragma omp taskgroup task_reduction(+:ref)
#pragma omp taskloop simd in_reduction(-:ref)
for (int i = 0; i < 10; ++i)
foo();
}
#pragma omp declare reduction (red:int:omp_out += omp_in)
void foobar2(int &ref) {
#pragma omp taskgroup task_reduction(+:ref) // expected-note {{previously marked as task_reduction with different reduction operation}}
#pragma omp taskloop simd in_reduction(red:ref) // expected-error{{in_reduction variable must have the same reduction operation as in a task_reduction clause}}
for (int i = 0; i < 10; ++i)
foo();
}
void foobar3(int &ref) {
#pragma omp taskgroup task_reduction(red:ref) // expected-note {{previously marked as task_reduction with different reduction operation}}
#pragma omp taskloop simd in_reduction(min:ref) // expected-error{{in_reduction variable must have the same reduction operation as in a task_reduction clause}}
for (int i = 0; i < 10; ++i)
foo();
}
void foobar4(int &ref) {
#pragma omp taskloop simd in_reduction(min:ref)
for (int i = 0; i < 10; ++i)
foo();
}
struct S1; // expected-note {{declared here}} expected-note 4 {{forward declaration of 'S1'}}
extern S1 a;
class S2 {
mutable int a;
S2 &operator+(const S2 &arg) { return (*this); } // expected-note 3 {{implicitly declared private here}}
public:
S2() : a(0) {}
S2(S2 &s2) : a(s2.a) {}
static float S2s; // expected-note 2 {{static data member is predetermined as shared}}
static const float S2sc; // expected-note 2 {{'S2sc' declared here}}
};
const float S2::S2sc = 0;
S2 b; // expected-note 3 {{'b' defined here}}
const S2 ba[5]; // expected-note 2 {{'ba' defined here}}
class S3 {
int a;
public:
int b;
S3() : a(0) {}
S3(const S3 &s3) : a(s3.a) {}
S3 operator+(const S3 &arg1) { return arg1; }
};
int operator+(const S3 &arg1, const S3 &arg2) { return 5; }
S3 c; // expected-note 3 {{'c' defined here}}
const S3 ca[5]; // expected-note 2 {{'ca' defined here}}
extern const int f; // expected-note 4 {{'f' declared here}}
class S4 {
int a;
S4(); // expected-note {{implicitly declared private here}}
S4(const S4 &s4);
S4 &operator+(const S4 &arg) { return (*this); }
public:
S4(int v) : a(v) {}
};
S4 &operator&=(S4 &arg1, S4 &arg2) { return arg1; }
class S5 {
int a;
S5() : a(0) {} // expected-note {{implicitly declared private here}}
S5(const S5 &s5) : a(s5.a) {}
S5 &operator+(const S5 &arg);
public:
S5(int v) : a(v) {}
};
class S6 { // expected-note 3 {{candidate function (the implicit copy assignment operator) not viable: no known conversion from 'int' to 'const S6' for 1st argument}}
#if __cplusplus >= 201103L // C++11 or later
// expected-note@-2 3 {{candidate function (the implicit move assignment operator) not viable}}
#endif
int a;
public:
S6() : a(6) {}
operator int() { return 6; }
} o;
S3 h, k;
#pragma omp threadprivate(h) // expected-note 2 {{defined as threadprivate or thread local}}
template <class T> // expected-note {{declared here}}
T tmain(T argc) {
const T d = T(); // expected-note 4 {{'d' defined here}}
const T da[5] = {T()}; // expected-note 2 {{'da' defined here}}
T qa[5] = {T()};
T i, z;
T &j = i; // expected-note 2 {{'j' defined here}}
S3 &p = k; // expected-note 2 {{'p' defined here}}
const T &r = da[(int)i]; // expected-note 2 {{'r' defined here}}
T &q = qa[(int)i];
T fl;
#pragma omp taskgroup task_reduction(+:argc)
#pragma omp taskloop simd in_reduction // expected-error {{expected '(' after 'in_reduction'}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskgroup task_reduction(+:argc)
#pragma omp taskloop simd in_reduction + // expected-error {{expected '(' after 'in_reduction'}} expected-warning {{extra tokens at the end of '#pragma omp taskloop simd' are ignored}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskgroup task_reduction(+:argc)
#pragma omp taskloop simd in_reduction( // expected-error {{expected unqualified-id}} expected-warning {{missing ':' after reduction identifier - ignoring}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskgroup task_reduction(+:argc)
#pragma omp taskloop simd in_reduction(- // expected-warning {{missing ':' after reduction identifier - ignoring}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskgroup task_reduction(+:argc)
#pragma omp taskloop simd in_reduction() // expected-error {{expected unqualified-id}} expected-warning {{missing ':' after reduction identifier - ignoring}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskgroup task_reduction(+:argc)
#pragma omp taskloop simd in_reduction(*) // expected-warning {{missing ':' after reduction identifier - ignoring}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskgroup task_reduction(+:argc)
#pragma omp taskloop simd in_reduction(\) // expected-error {{expected unqualified-id}} expected-warning {{missing ':' after reduction identifier - ignoring}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskgroup task_reduction(&:argc) // expected-error {{invalid operands to binary expression ('float' and 'float')}}
#pragma omp taskloop simd in_reduction(& : argc // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{invalid operands to binary expression ('float' and 'float')}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskgroup task_reduction(|:z) // expected-error {{invalid operands to binary expression ('float' and 'float')}}
#pragma omp taskloop simd in_reduction(| : z, // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{invalid operands to binary expression ('float' and 'float')}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskloop simd in_reduction(|| : argc ? i : argc) // expected-error 2 {{expected variable name, array element or array section}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskloop simd in_reduction(foo : argc) //expected-error {{incorrect reduction identifier, expected one of '+', '-', '*', '&', '|', '^', '&&', '||', 'min' or 'max' or declare reduction for type 'float'}} expected-error {{incorrect reduction identifier, expected one of '+', '-', '*', '&', '|', '^', '&&', '||', 'min' or 'max' or declare reduction for type 'int'}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskgroup task_reduction(&&:argc)
#pragma omp taskloop simd in_reduction(&& : argc) allocate , allocate(, allocate(omp_default , allocate(omp_default_mem_alloc, allocate(omp_default_mem_alloc:, allocate(omp_default_mem_alloc: argc, allocate(omp_default_mem_alloc: argv), allocate(argv) // expected-error {{expected '(' after 'allocate'}} expected-error 2 {{expected expression}} expected-error 2 {{expected ')'}} expected-error {{use of undeclared identifier 'omp_default'}} expected-note 2 {{to match this '('}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskloop simd in_reduction(^ : T) // expected-error {{'T' does not refer to a value}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskgroup task_reduction(+:c)
#pragma omp taskloop simd in_reduction(+ : a, b, c, d, f) // expected-error {{a reduction list item with incomplete type 'S1'}} expected-error 3 {{const-qualified variable cannot be in_reduction}} expected-error 2 {{'operator+' is a private member of 'S2'}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskloop simd in_reduction(min : a, b, c, d, f) // expected-error {{a reduction list item with incomplete type 'S1'}} expected-error 4 {{arguments of OpenMP clause 'in_reduction' for 'min' or 'max' must be of arithmetic type}} expected-error 3 {{const-qualified variable cannot be in_reduction}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskloop simd in_reduction(max : h.b) // expected-error {{expected variable name, array element or array section}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskloop simd in_reduction(+ : ba) // expected-error {{const-qualified variable cannot be in_reduction}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskloop simd in_reduction(* : ca) // expected-error {{const-qualified variable cannot be in_reduction}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskloop simd in_reduction(- : da) // expected-error {{const-qualified variable cannot be in_reduction}} expected-error {{const-qualified variable cannot be in_reduction}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskloop simd in_reduction(^ : fl) // expected-error {{invalid operands to binary expression ('float' and 'float')}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskloop simd in_reduction(&& : S2::S2s) // expected-error {{shared variable cannot be reduction}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskloop simd in_reduction(&& : S2::S2sc) // expected-error {{const-qualified variable cannot be in_reduction}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskgroup task_reduction(+:k)
#pragma omp taskloop simd in_reduction(+ : h, k) // expected-error {{threadprivate or thread local variable cannot be reduction}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskloop simd in_reduction(+ : o) // expected-error 2 {{no viable overloaded '='}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp parallel private(k)
#pragma omp taskloop simd in_reduction(+ : p), in_reduction(+ : p) // expected-error 2 {{argument of OpenMP clause 'in_reduction' must reference the same object in all threads}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskgroup task_reduction(+:p)
#pragma omp taskloop simd in_reduction(+ : p), in_reduction(+ : p) // expected-error 2 {{variable can appear only once in OpenMP 'in_reduction' clause}} expected-note 2 {{previously referenced here}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskloop simd in_reduction(+ : r) // expected-error 2 {{const-qualified variable cannot be in_reduction}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp parallel shared(i)
#pragma omp parallel reduction(min : i)
#pragma omp taskloop simd in_reduction(max : j) // expected-error 2 {{argument of OpenMP clause 'in_reduction' must reference the same object in all threads}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskgroup task_reduction(+:fl)
{
#pragma omp taskloop simd allocate(omp_thread_mem_alloc: fl) in_reduction(+ : fl) // expected-warning 2 {{allocator with the 'thread' trait access has unspecified behavior on 'taskloop simd' directive}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskgroup task_reduction(*:fl) // expected-note 2 {{previously marked as task_reduction with different reduction operation}}
{
#pragma omp taskloop simd in_reduction(+ : fl) // expected-error 2 {{in_reduction variable must have the same reduction operation as in a task_reduction clause}}
for (int i = 0; i < 10; ++i)
foo();
}
}
#pragma omp parallel
#pragma omp for reduction(- : fl)
for (int i = 0; i < 10; ++i)
#pragma omp taskgroup task_reduction(+:fl)
#pragma omp taskloop simd in_reduction(+ : fl)
for (int j = 0; j < 10; ++j)
foo();
return T();
}
namespace A {
double x;
#pragma omp threadprivate(x) // expected-note {{defined as threadprivate or thread local}}
}
namespace B {
using A::x;
}
int main(int argc, char **argv) {
const int d = 5; // expected-note 2 {{'d' defined here}}
const int da[5] = {0}; // expected-note {{'da' defined here}}
int qa[5] = {0};
S4 e(4);
S5 g(5);
int i, z;
int &j = i; // expected-note {{'j' defined here}}
S3 &p = k; // expected-note 2 {{'p' defined here}}
const int &r = da[i]; // expected-note {{'r' defined here}}
int &q = qa[i];
float fl;
#pragma omp taskloop simd in_reduction // expected-error {{expected '(' after 'in_reduction'}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskloop simd in_reduction + // expected-error {{expected '(' after 'in_reduction'}} expected-warning {{extra tokens at the end of '#pragma omp taskloop simd' are ignored}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskloop simd in_reduction( // expected-error {{expected unqualified-id}} expected-warning {{missing ':' after reduction identifier - ignoring}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskloop simd in_reduction(- // expected-warning {{missing ':' after reduction identifier - ignoring}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskloop simd in_reduction() // expected-error {{expected unqualified-id}} expected-warning {{missing ':' after reduction identifier - ignoring}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskloop simd in_reduction(*) // expected-warning {{missing ':' after reduction identifier - ignoring}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskloop simd in_reduction(\) // expected-error {{expected unqualified-id}} expected-warning {{missing ':' after reduction identifier - ignoring}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskloop simd in_reduction(foo : argc // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-error {{incorrect reduction identifier, expected one of '+', '-', '*', '&', '|', '^', '&&', '||', 'min' or 'max'}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskgroup task_reduction(|:argc)
#pragma omp taskloop simd in_reduction(| : argc, // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskloop simd in_reduction(|| : argc > 0 ? argv[1] : argv[2]) // expected-error {{expected variable name, array element or array section}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskloop simd in_reduction(~ : argc) // expected-error {{expected unqualified-id}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskgroup task_reduction(&&:argc, z)
#pragma omp taskloop simd in_reduction(&& : argc, z)
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskloop simd in_reduction(^ : S1) // expected-error {{'S1' does not refer to a value}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskgroup task_reduction(+:c)
#pragma omp taskloop simd in_reduction(+ : a, b, c, d, f) // expected-error {{a reduction list item with incomplete type 'S1'}} expected-error 2 {{const-qualified variable cannot be in_reduction}} expected-error {{'operator+' is a private member of 'S2'}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskloop simd in_reduction(min : a, b, c, d, f) // expected-error {{a reduction list item with incomplete type 'S1'}} expected-error 2 {{arguments of OpenMP clause 'in_reduction' for 'min' or 'max' must be of arithmetic type}} expected-error 2 {{const-qualified variable cannot be in_reduction}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskloop simd in_reduction(max : h.b) // expected-error {{expected variable name, array element or array section}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskloop simd in_reduction(+ : ba) // expected-error {{const-qualified variable cannot be in_reduction}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskloop simd in_reduction(* : ca) // expected-error {{const-qualified variable cannot be in_reduction}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskloop simd in_reduction(- : da) // expected-error {{const-qualified variable cannot be in_reduction}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskloop simd in_reduction(^ : fl) // expected-error {{invalid operands to binary expression ('float' and 'float')}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskloop simd in_reduction(&& : S2::S2s) // expected-error {{shared variable cannot be reduction}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskloop simd in_reduction(&& : S2::S2sc) // expected-error {{const-qualified variable cannot be in_reduction}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskloop simd in_reduction(& : e, g) // expected-error {{calling a private constructor of class 'S4'}} expected-error {{calling a private constructor of class 'S5'}} expected-error {{invalid operands to binary expression ('S5' and 'S5')}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskgroup task_reduction(+:k)
#pragma omp taskloop simd in_reduction(+ : h, k, B::x) // expected-error 2 {{threadprivate or thread local variable cannot be reduction}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskloop simd in_reduction(+ : o) // expected-error {{no viable overloaded '='}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp parallel private(k)
#pragma omp taskloop simd in_reduction(+ : p), in_reduction(+ : p) // expected-error 2 {{argument of OpenMP clause 'in_reduction' must reference the same object in all threads}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskgroup task_reduction(+:p)
#pragma omp taskloop simd in_reduction(+ : p), in_reduction(+ : p) // expected-error {{variable can appear only once in OpenMP 'in_reduction' clause}} expected-note {{previously referenced here}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp taskloop simd in_reduction(+ : r) // expected-error {{const-qualified variable cannot be in_reduction}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp parallel shared(i)
#pragma omp parallel reduction(min : i)
#pragma omp taskloop simd in_reduction(max : j) // expected-error {{argument of OpenMP clause 'in_reduction' must reference the same object in all threads}}
for (int i = 0; i < 10; ++i)
foo();
#pragma omp parallel
#pragma omp for private(fl)
for (int i = 0; i < 10; ++i)
#pragma omp taskgroup task_reduction(+:fl)
#pragma omp taskloop simd in_reduction(+ : fl)
for (int j = 0; j < 10; ++j)
foo();
#pragma omp taskgroup task_reduction(+:fl)
#pragma omp taskloop simd in_reduction(+ : fl)
for (int i = 0; i < 10; ++i)
foo();
static int m;
#pragma omp taskgroup task_reduction(+:m)
#pragma omp taskloop simd in_reduction(+ : m) // OK
for (int i = 0; i < 10; ++i)
m++;
return tmain(argc) + tmain(fl); // expected-note {{in instantiation of function template specialization 'tmain<int>' requested here}} expected-note {{in instantiation of function template specialization 'tmain<float>' requested here}}
}
|
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/storage/blobfs/directory.h"
#include <fuchsia/device/c/fidl.h>
#include <lib/fidl-utils/bind.h>
#include <lib/sync/completion.h>
#include <stdlib.h>
#include <string.h>
#include <zircon/device/vfs.h>
#include <zircon/status.h>
#include <zircon/syscalls.h>
#include <string_view>
#include <utility>
#include <vector>
#include <fbl/ref_ptr.h>
#include "src/lib/digest/digest.h"
#include "src/lib/storage/vfs/cpp/metrics/events.h"
#include "src/storage/blobfs/blob.h"
#include "src/storage/blobfs/blobfs.h"
#include "src/storage/blobfs/metrics.h"
namespace blobfs {
Directory::Directory(Blobfs* bs) : blobfs_(bs) {}
BlobCache& Directory::GetCache() { return blobfs_->GetCache(); }
Directory::~Directory() = default;
zx_status_t Directory::GetNodeInfoForProtocol([[maybe_unused]] fs::VnodeProtocol protocol,
[[maybe_unused]] fs::Rights rights,
fs::VnodeRepresentation* info) {
*info = fs::VnodeRepresentation::Directory();
return ZX_OK;
}
fs::VnodeProtocolSet Directory::GetProtocols() const { return fs::VnodeProtocol::kDirectory; }
zx_status_t Directory::Readdir(fs::VdirCookie* cookie, void* dirents, size_t len,
size_t* out_actual) {
return blobfs_->Readdir(cookie, dirents, len, out_actual);
}
zx_status_t Directory::Read(void* data, size_t len, size_t off, size_t* out_actual) {
return ZX_ERR_NOT_FILE;
}
zx_status_t Directory::Write(const void* data, size_t len, size_t offset, size_t* out_actual) {
return ZX_ERR_NOT_FILE;
}
zx_status_t Directory::Append(const void* data, size_t len, size_t* out_end, size_t* out_actual) {
return ZX_ERR_NOT_FILE;
}
zx_status_t Directory::Lookup(std::string_view name, fbl::RefPtr<fs::Vnode>* out) {
TRACE_DURATION("blobfs", "Directory::Lookup", "name", name);
auto event = blobfs_->GetMetrics()->NewLatencyEvent(fs_metrics::Event::kLookUp);
assert(memchr(name.data(), '/', name.length()) == nullptr);
if (name == ".") {
// Special case: Accessing root directory via '.'
*out = fbl::RefPtr<Directory>(this);
return ZX_OK;
}
zx_status_t status;
Digest digest;
if ((status = digest.Parse(name.data(), name.length())) != ZX_OK) {
return status;
}
fbl::RefPtr<CacheNode> cache_node;
if ((status = GetCache().Lookup(digest, &cache_node)) != ZX_OK) {
return status;
}
auto vnode = fbl::RefPtr<Blob>::Downcast(std::move(cache_node));
blobfs_->GetMetrics()->UpdateLookup(vnode->SizeData());
*out = std::move(vnode);
return ZX_OK;
}
zx_status_t Directory::GetAttributes(fs::VnodeAttributes* a) {
*a = fs::VnodeAttributes();
a->mode = V_TYPE_DIR | V_IRUSR;
a->inode = fuchsia_io::wire::kInoUnknown;
a->content_size = 0;
a->storage_size = 0;
a->link_count = 1;
a->creation_time = 0;
a->modification_time = 0;
return ZX_OK;
}
zx_status_t Directory::Create(std::string_view name, uint32_t mode, fbl::RefPtr<fs::Vnode>* out) {
TRACE_DURATION("blobfs", "Directory::Create", "name", name, "mode", mode);
auto event = blobfs_->GetMetrics()->NewLatencyEvent(fs_metrics::Event::kCreate);
assert(memchr(name.data(), '/', name.length()) == nullptr);
Digest digest;
zx_status_t status;
if ((status = digest.Parse(name.data(), name.length())) != ZX_OK) {
return status;
}
fbl::RefPtr<Blob> vn = fbl::AdoptRef(new Blob(blobfs_, std::move(digest)));
if ((status = GetCache().Add(vn)) != ZX_OK) {
return status;
}
if ((status = vn->OpenValidating(fs::VnodeConnectionOptions(), nullptr)) != ZX_OK) {
return status;
}
*out = std::move(vn);
return ZX_OK;
}
#ifdef __Fuchsia__
zx_status_t Directory::QueryFilesystem(fuchsia_io::wire::FilesystemInfo* info) {
blobfs_->GetFilesystemInfo(info);
return ZX_OK;
}
zx_status_t Directory::GetDevicePath(size_t buffer_len, char* out_name, size_t* out_len) {
return blobfs_->Device()->GetDevicePath(buffer_len, out_name, out_len);
}
#endif // __Fuchsia__
zx_status_t Directory::Unlink(std::string_view name, bool must_be_dir) {
TRACE_DURATION("blobfs", "Directory::Unlink", "name", name, "must_be_dir", must_be_dir);
auto event = blobfs_->GetMetrics()->NewLatencyEvent(fs_metrics::Event::kUnlink);
assert(memchr(name.data(), '/', name.length()) == nullptr);
zx_status_t status;
Digest digest;
if ((status = digest.Parse(name.data(), name.length())) != ZX_OK) {
return status;
}
fbl::RefPtr<CacheNode> cache_node;
if ((status = GetCache().Lookup(digest, &cache_node)) != ZX_OK) {
return status;
}
auto vnode = fbl::RefPtr<Blob>::Downcast(std::move(cache_node));
blobfs_->GetMetrics()->UpdateLookup(vnode->SizeData());
return vnode->QueueUnlink();
}
void Directory::Sync(SyncCallback closure) {
blobfs_->Sync([this, cb = std::move(closure)](zx_status_t status) mutable {
// This callback will be issued on the journal thread in the normal case. This is important
// because the flush must happen there or it will block the main thread which would block
// processing other requests.
//
// If called during shutdown this may get issued on the main thread but then the flush
// transaction should be a no-op.
if (status == ZX_OK) {
status = blobfs_->Flush();
}
cb(status);
});
}
#ifdef __Fuchsia__
void Directory::HandleFsSpecificMessage(fidl::IncomingMessage& msg, fidl::Transaction* txn) {
fidl::WireDispatch<fuchsia_blobfs::Blobfs>(this, std::move(msg), txn);
}
void Directory::GetAllocatedRegions(GetAllocatedRegionsRequestView request,
GetAllocatedRegionsCompleter::Sync& completer) {
static_assert(sizeof(fuchsia_blobfs::wire::BlockRegion) == sizeof(BlockRegion));
static_assert(offsetof(fuchsia_blobfs::wire::BlockRegion, offset) ==
offsetof(BlockRegion, offset));
static_assert(offsetof(fuchsia_blobfs::wire::BlockRegion, length) ==
offsetof(BlockRegion, length));
zx::vmo vmo;
zx_status_t status = ZX_OK;
std::vector<BlockRegion> buffer = blobfs_->GetAllocator()->GetAllocatedRegions();
uint64_t allocations = buffer.size();
if (allocations != 0) {
status = zx::vmo::create(sizeof(BlockRegion) * allocations, 0, &vmo);
if (status == ZX_OK) {
status = vmo.write(buffer.data(), 0, sizeof(BlockRegion) * allocations);
}
}
if (status == ZX_OK) {
completer.Reply(ZX_OK, std::move(vmo), allocations);
} else {
completer.Reply(status, zx::vmo(), 0);
}
}
void Directory::SetCorruptBlobHandler(SetCorruptBlobHandlerRequestView request,
SetCorruptBlobHandlerCompleter::Sync& completer) {
blobfs_->SetCorruptBlobHandler(std::move(request->handler));
completer.Reply(ZX_OK);
}
#endif // __Fuchsia__
} // namespace blobfs
|
#include "EditableModelView.hpp"
#include <QAbstractTableModel>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QPushButton>
#include <QTableView>
#include <QVBoxLayout>
namespace chatterino {
EditableModelView::EditableModelView(QAbstractTableModel *model)
: tableView_(new QTableView(this))
, model_(model)
{
this->model_->setParent(this);
this->tableView_->setModel(model);
this->tableView_->setSelectionMode(QAbstractItemView::ExtendedSelection);
this->tableView_->setSelectionBehavior(QAbstractItemView::SelectRows);
this->tableView_->verticalHeader()->hide();
// create layout
QVBoxLayout *vbox = new QVBoxLayout(this);
vbox->setMargin(0);
// create button layout
QHBoxLayout *buttons = new QHBoxLayout(this);
this->buttons_ = buttons;
vbox->addLayout(buttons);
// add
QPushButton *add = new QPushButton("Add");
buttons->addWidget(add);
QObject::connect(add, &QPushButton::clicked,
[this] { this->addButtonPressed.invoke(); });
// remove
QPushButton *remove = new QPushButton("Remove");
buttons->addWidget(remove);
QObject::connect(remove, &QPushButton::clicked, [this] {
QModelIndexList list;
while ((list = this->getTableView()->selectionModel()->selectedRows(0))
.length() > 0)
{
model_->removeRow(list[0].row());
}
});
buttons->addStretch();
// add tableview
vbox->addWidget(this->tableView_);
// finish button layout
buttons->addStretch(1);
}
void EditableModelView::setTitles(std::initializer_list<QString> titles)
{
int i = 0;
for (const QString &title : titles)
{
if (this->model_->columnCount() == i)
{
break;
}
this->model_->setHeaderData(i++, Qt::Horizontal, title,
Qt::DisplayRole);
}
}
QTableView *EditableModelView::getTableView()
{
return this->tableView_;
}
QAbstractTableModel *EditableModelView::getModel()
{
return this->model_;
}
void EditableModelView::addCustomButton(QWidget *widget)
{
this->buttons_->addWidget(widget);
}
void EditableModelView::addRegexHelpLink()
{
auto regexHelpLabel =
new QLabel("<a href='https://chatterino.com/help/regex'><span "
"style='color:#99f'>regex info</span></a>");
regexHelpLabel->setOpenExternalLinks(true);
this->addCustomButton(regexHelpLabel);
}
} // namespace chatterino
|
// Copyright 2020 modio. All Rights Reserved.
// Released under MIT.
#include "BlueprintCallbackProxies/CallbackProxy_DownloadModfilesById.h"
#include "ModioSubsystem.h"
#include "Engine/Engine.h"
UCallbackProxy_DownloadModfilesById::UCallbackProxy_DownloadModfilesById(const FObjectInitializer &ObjectInitializer)
: Super(ObjectInitializer)
{
}
UCallbackProxy_DownloadModfilesById *UCallbackProxy_DownloadModfilesById::DownloadModfilesById( UObject *WorldContext, const TArray<int32> &ModIds )
{
UCallbackProxy_DownloadModfilesById *Proxy = NewObject<UCallbackProxy_DownloadModfilesById>();
Proxy->SetFlags(RF_StrongRefOnFrame);
Proxy->ModIds = ModIds;
Proxy->WorldContextObject = WorldContext;
return Proxy;
}
void UCallbackProxy_DownloadModfilesById::Activate()
{
UWorld* World = GEngine->GetWorldFromContextObject( WorldContextObject, EGetWorldErrorMode::LogAndReturnNull );
FModioSubsystemPtr Modio = FModioSubsystem::Get( World );
if( Modio.IsValid() )
{
Modio->DownloadModfilesById( ModIds, FModioBooleanDelegate::CreateUObject( this, &UCallbackProxy_DownloadModfilesById::OnDownloadModfilesByIdDelegate ) );
}
else
{
// @todonow: Make something more pretty than this
FModioResponse Response;
OnFailure.Broadcast( Response, false );
}
}
void UCallbackProxy_DownloadModfilesById::OnDownloadModfilesByIdDelegate(FModioResponse Response, bool ModsAreUpdated)
{
if (Response.Code >= 200 && Response.Code < 300)
{
OnSuccess.Broadcast(Response, ModsAreUpdated);
}
else
{
OnFailure.Broadcast(Response, ModsAreUpdated);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.