hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0028ca152d609c7911fa1dbf0f266d8c7ff5441c
| 210
|
cpp
|
C++
|
Zerojudge/d493.cpp
|
w181496/OJ
|
67d1d32770376865eba8a9dd1767e97dae68989a
|
[
"MIT"
] | 9
|
2017-10-08T16:22:03.000Z
|
2021-08-20T09:32:17.000Z
|
Zerojudge/d493.cpp
|
w181496/OJ
|
67d1d32770376865eba8a9dd1767e97dae68989a
|
[
"MIT"
] | null | null | null |
Zerojudge/d493.cpp
|
w181496/OJ
|
67d1d32770376865eba8a9dd1767e97dae68989a
|
[
"MIT"
] | 2
|
2018-01-15T16:35:44.000Z
|
2019-03-21T18:30:04.000Z
|
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
long long int a,b,sum;
while(cin >> a >> b)
{
sum=pow(a,b);
cout<<sum<<endl;
}
return 0;
}
| 15
| 27
| 0.490476
|
w181496
|
002aefd2d03a44b50c728831e5c33f7bcfd0986c
| 58,550
|
cpp
|
C++
|
src/prod/ktl/src/src/kbitmap.cpp
|
vishnuk007/service-fabric
|
d0afdea185ae932cc3c9eacf179692e6fddbc630
|
[
"MIT"
] | 1
|
2020-06-15T04:33:36.000Z
|
2020-06-15T04:33:36.000Z
|
src/prod/ktl/src/src/kbitmap.cpp
|
vishnuk007/service-fabric
|
d0afdea185ae932cc3c9eacf179692e6fddbc630
|
[
"MIT"
] | null | null | null |
src/prod/ktl/src/src/kbitmap.cpp
|
vishnuk007/service-fabric
|
d0afdea185ae932cc3c9eacf179692e6fddbc630
|
[
"MIT"
] | null | null | null |
/*++
Module Name:
kbitmap.cpp
Abstract:
This file contains the user mode and kernel mode implementations of a KBitmap object.
Author:
Norbert P. Kusters (norbertk) 7-Oct-2010
Environment:
Kernel mode and User mode
Notes:
Revision History:
--*/
#include <ktl.h>
/*++
Note:
Bits are read starting with the lowest-order bit 0x1 as the first bit position.
Warning:
Mask(Bits) has undefined behavior at Bits >= 64.
RangeMask(Start, Length) has undefined behavior at Length <= 0.
--*/
#define Mask(Bits) ((1ULL << Bits) - 1ULL)
#define RangeMask(Start, Length) ((ULONGLONG_MAX >> (64 - Length)) << Start)
#define NumberOfBytes(Bits) (Bits / CHAR_BIT)
#define RemainderBits(Bits) (Bits & (CHAR_BIT - 1))
typedef ULONGLONG KBitmapChunkType;
static const ULONG g_BytesPerChunk = sizeof(KBitmapChunkType);
static const ULONG g_BitsPerChunk = g_BytesPerChunk * CHAR_BIT;
ULONG
KBitmap::QueryRequiredBufferSize(
__in ULONG NumberOfBits
)
/*++
Routine Description:
This routine returns the required buffer size, according to the internal alignment requirement.
Arguments:
NumberOfBits - Supplies the number of bits in the bitmap.
Return Value:
The minimum size of the bitmap, in bytes.
--*/
{
return ((NumberOfBits + g_BitsPerChunk - 1)/g_BitsPerChunk)*g_BytesPerChunk;
}
KBitmap::~KBitmap(
)
{
}
KBitmap::KBitmap(
)
{
_Buffer = NULL;
_BufferSize = 0;
_Bits = 0;
}
KBitmap::KBitmap(
__inout_bcount(BitmapBufferSize) VOID* BitmapBuffer,
__in ULONG BitmapBufferSize,
__in ULONG NumberOfBits
)
{
SetConstructorStatus(Reuse(BitmapBuffer, BitmapBufferSize, NumberOfBits));
}
NTSTATUS
KBitmap::Reuse(
__inout_bcount(BitmapBufferSize) VOID* BitmapBuffer,
__in ULONG BitmapBufferSize,
__in ULONG NumberOfBits
)
/*++
Routine Description:
This routine initializes a bitmap.
Arguments:
BitmapBuffer - Supplies the bitmap buffer. This buffer should be at least aligned to sizeof(ULONGLONG).
BitmapBufferSize - Supplies the size, in bytes, of the bitmap buffer. This should be a multiple of sizeof(ULONGLONG).
NumberOfBits - Supplies the number of bits in the bitmap. This needs to fit within the buffer supplied.
Return Value:
NTSTATUS
--*/
{
ULONG_PTR bitmapPointerValue;
ULONG neededBufferSize;
bitmapPointerValue = (ULONG_PTR) BitmapBuffer;
if (bitmapPointerValue % g_BytesPerChunk) {
//
// Bitmap buffer must be aligned to chunk size (64 bits, or 8 bytes).
//
KAssert(FALSE);
return STATUS_INVALID_PARAMETER;
}
neededBufferSize = QueryRequiredBufferSize(NumberOfBits);
if (BitmapBufferSize < neededBufferSize) {
KAssert(FALSE);
return STATUS_INVALID_PARAMETER;
}
_Buffer = reinterpret_cast<PUCHAR>(BitmapBuffer);
_BufferSize = BitmapBufferSize;
_Bits = NumberOfBits;
return STATUS_SUCCESS;
}
VOID*
KBitmap::GetBuffer(
)
{
return _Buffer;
}
ULONG
KBitmap::QueryBufferSize(
)
{
return _BufferSize;
}
ULONG
KBitmap::QueryNumberOfBits(
)
{
return _Bits;
}
VOID
KBitmap::ClearBits(
__in ULONG StartingBit,
__in ULONG NumberOfBits
)
{
KInvariant(StartingBit < _Bits);
KInvariant(NumberOfBits <= _Bits - StartingBit);
PUCHAR CurrentPosition = _Buffer + NumberOfBytes(StartingBit);
StartingBit = RemainderBits(StartingBit);
//
// If only updating one byte, clear the bits and exit.
//
if (StartingBit + NumberOfBits <= CHAR_BIT) {
if (NumberOfBits > 0) {
*CurrentPosition &= ~RangeMask(StartingBit, NumberOfBits);
}
return;
}
//
// We are now handling multiple bytes.
// If the starting bit is not byte-aligned, mask and clear the first byte separately.
//
if (StartingBit > 0) {
*CurrentPosition &= Mask(StartingBit);
++CurrentPosition;
NumberOfBits -= CHAR_BIT - StartingBit;
}
//
// Clear the full bytes in the middle.
//
if (NumberOfBits > CHAR_BIT) {
ULONG NumberOfBytes = NumberOfBytes(NumberOfBits);
memset(CurrentPosition, 0, NumberOfBytes);
CurrentPosition += NumberOfBytes;
NumberOfBits = RemainderBits(NumberOfBits);
}
//
// Clear any trailing bits.
//
if (NumberOfBits > 0) {
*CurrentPosition &= ~Mask(NumberOfBits);
}
}
VOID
KBitmap::SetBits(
__in ULONG StartingBit,
__in ULONG NumberOfBits
)
{
KInvariant(StartingBit < _Bits);
KInvariant(NumberOfBits <= _Bits - StartingBit);
PUCHAR CurrentPosition = _Buffer + (NumberOfBytes(StartingBit));
StartingBit = RemainderBits(StartingBit);
//
// If only updating one byte, set the bits and exit.
//
if (StartingBit + NumberOfBits <= CHAR_BIT) {
if (NumberOfBits > 0) {
*CurrentPosition |= RangeMask(StartingBit, NumberOfBits);
}
return;
}
//
// If the starting bit is not byte-aligned, mask and set the partial byte.
//
if (StartingBit > 0) {
*CurrentPosition |= ~Mask(StartingBit);
++CurrentPosition;
NumberOfBits -= CHAR_BIT - StartingBit;
}
//
// Set the full bytes in the middle.
//
if (NumberOfBits > CHAR_BIT) {
ULONG NumberOfBytes = NumberOfBytes(NumberOfBits);
memset(CurrentPosition, 0xFF, NumberOfBytes);
CurrentPosition += NumberOfBytes;
NumberOfBits = RemainderBits(NumberOfBits);
}
//
// Set any trailing bits.
//
if (NumberOfBits > 0) {
*CurrentPosition |= Mask(NumberOfBits);
}
}
BOOLEAN
KBitmap::CheckBit(
__in ULONG BitNumber
)
{
KInvariant(BitNumber < _Bits);
return (_Buffer[NumberOfBytes(BitNumber)] & (1 << RemainderBits(BitNumber))) != 0;
}
VOID
KBitmap::ClearAllBits(
)
{
ClearBits(0, _Bits);
}
VOID
KBitmap::SetAllBits(
)
{
SetBits(0, _Bits);
}
ULONG
KBitmap::QueryNumberOfSetBits(
)
{
//
// Look-up table of the Hamming weight for every byte-size bit combination.
//
static const UCHAR SetBitsMap[] = {
0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 };
volatile PUCHAR CurrentPosition;
PUCHAR EndPosition;
KBitmapChunkType Chunk;
ULONG NumberOfChunks = _Bits / g_BitsPerChunk;
ULONG TrailingBytes = NumberOfBytes(_Bits) - (NumberOfChunks * g_BytesPerChunk);
ULONG TrailingBits = RemainderBits(_Bits);
ULONG TotalSet = 0;
//
// Count the number of set bits for every full chunk.
//
CurrentPosition = _Buffer;
EndPosition = CurrentPosition + (NumberOfChunks * g_BytesPerChunk);
while (CurrentPosition != EndPosition) {
Chunk = *(reinterpret_cast<volatile KBitmapChunkType*>(CurrentPosition));
CurrentPosition += g_BytesPerChunk;
TotalSet += SetBitsMap[Chunk & 0xFF] +
SetBitsMap[(Chunk >> 8) & 0xFF] +
SetBitsMap[(Chunk >> 16) & 0xFF] +
SetBitsMap[(Chunk >> 24) & 0xFF] +
SetBitsMap[(Chunk >> 32) & 0xFF] +
SetBitsMap[(Chunk >> 40) & 0xFF] +
SetBitsMap[(Chunk >> 48) & 0xFF] +
SetBitsMap[Chunk >> 56];
}
//
// If there are no tail bits to count, return the result.
//
if (TrailingBytes + TrailingBits == 0) {
return TotalSet;
}
//
// Count the number of set bits for every full byte.
//
EndPosition += TrailingBytes;
while (CurrentPosition != EndPosition) {
TotalSet += SetBitsMap[*CurrentPosition++];
}
//
// Count the number of set bits in the trailing partial byte, if any.
//
if (TrailingBits > 0) {
TotalSet += SetBitsMap[*CurrentPosition & Mask(TrailingBits)];
}
return TotalSet;
}
FORCEINLINE
BOOLEAN
AreBitsOkay(
__in PULONGLONG BitMapBuffer,
__in ULONG BitMapSize,
__in ULONG StartingIndex,
__in ULONG NumberOfBits,
__in BOOLEAN Set
)
{
KBitmapChunkType * CurrentChunk = BitMapBuffer + (StartingIndex / g_BitsPerChunk);
KBitmapChunkType * LastChunk = BitMapBuffer + ((StartingIndex + NumberOfBits) / g_BitsPerChunk) - 1;
KBitmapChunkType ChunkMask;
KBitmapChunkType Expected;
KBitmapChunkType Actual;
ULONG EndingIndex = StartingIndex + NumberOfBits;
//
// Make sure that the specified range is contained within the bitmap,
// and that the EndingIndex did not overflow.
//
if (BitMapSize < EndingIndex ||
EndingIndex < StartingIndex) {
return FALSE;
}
//
// KAllocationBitMap fix.
//
if (NumberOfBits == 0) {
return FALSE;
}
//
// Trim the chunk indices. We only need the chunk offsets now.
//
StartingIndex &= (g_BitsPerChunk - 1);
EndingIndex &= (g_BitsPerChunk - 1);
//
// If there is a single chunk, mask and test the chunk and return the result.
//
if (StartingIndex + NumberOfBits <= g_BitsPerChunk) {
ChunkMask = RangeMask(StartingIndex, NumberOfBits);
Expected = Set ? ChunkMask : 0;
Actual = *CurrentChunk & ChunkMask;
return Actual == Expected;
}
//
// Mask and test the first chunk.
//
ChunkMask = ~Mask(StartingIndex);
Expected = Set ? ChunkMask : 0;
Actual = *CurrentChunk & ChunkMask;
if (Actual != Expected) {
return FALSE;
}
//
// Test the middle chunks.
//
++CurrentChunk;
ChunkMask = ULONGLONG_MAX;
Expected = Set ? ChunkMask : 0;
for (; CurrentChunk <= LastChunk; ++CurrentChunk) {
Actual = *CurrentChunk & ChunkMask;
if (Actual != Expected) {
return FALSE;
}
}
//
// Mask and test the last chunk.
//
ChunkMask = Mask(EndingIndex);
Expected = Set ? ChunkMask : 0;
Actual = *CurrentChunk & ChunkMask;
return Actual == Expected;
}
BOOLEAN
KBitmap::AreBitsClear(
__in ULONG StartingBit,
__in ULONG NumberOfBits
)
{
return AreBitsOkay(reinterpret_cast<PULONGLONG>(_Buffer), _Bits, StartingBit, NumberOfBits, FALSE);
}
BOOLEAN
KBitmap::AreBitsSet(
__in ULONG StartingBit,
__in ULONG NumberOfBits
)
{
return AreBitsOkay(reinterpret_cast<PULONGLONG>(_Buffer), _Bits, StartingBit, NumberOfBits, TRUE);
}
ULONG
KBitmap::QueryRunLength(
__in ULONG StartingBit,
__out BOOLEAN& BitValue,
__in_opt ULONG MaxRunLength
)
/*++
Routine Description:
This routine will return the length and type of the run at the given starting bit.
Arguments:
StartingBit - Supplies the bit number to query the run length of.
BitValue - Returns whether the run is a run of zeros or a run of ones.
MaxRunLength - Supplies, optionally, the maximum run length that this function will return.
Return Value:
The number of bits in the run.
--*/
{
ULONG r = 0;
ULONG runLengthLimit;
ULONG numBitsInFirstChunk;
ULONG startChunk;
KBitmapChunkType fullBits;
KBitmapChunkType* p;
ULONG i;
if (StartingBit >= _Bits) {
//
// The start bit is out of range. The run length is zero.
//
return 0;
}
//
// Compute the largest possible answer and set that into 'MaxRunLength'.
//
runLengthLimit = _Bits - StartingBit;
if (MaxRunLength) {
if (MaxRunLength > runLengthLimit) {
MaxRunLength = runLengthLimit;
}
} else {
MaxRunLength = runLengthLimit;
}
//
// Figure out how many bits to individually check in the first chunk.
//
numBitsInFirstChunk = StartingBit%g_BitsPerChunk;
if (numBitsInFirstChunk) {
numBitsInFirstChunk = g_BitsPerChunk - numBitsInFirstChunk;
}
//
// Check the first chunk bit by bit.
//
BitValue = CheckBit(StartingBit);
for (i = 0; i < numBitsInFirstChunk; i++) {
if (CheckBit(StartingBit + i) != BitValue) {
return r;
}
r++;
if (r >= MaxRunLength) {
return MaxRunLength;
}
}
//
// Figure the index of the first whole chunk that will be checked.
//
startChunk = (StartingBit + g_BitsPerChunk - 1)/g_BitsPerChunk;
//
// Set up the loop by getting a chunk pointer to the bitmap and by knowing the type of the run that will be returned.
//
p = (KBitmapChunkType*) _Buffer;
//
// Check for whole chunks.
//
if (BitValue) {
fullBits = MAXULONGLONG;
} else {
fullBits = 0;
}
for (i = startChunk; ; i++) {
if (p[i] != fullBits) {
break;
}
r += g_BitsPerChunk;
if (r >= MaxRunLength) {
return MaxRunLength;
}
}
//
// The final chunk that was checked was mixed. Check it again, bit by bit.
//
StartingBit = i*g_BitsPerChunk;
for (i = 0; i < g_BitsPerChunk; i++) {
if (CheckBit(StartingBit + i) != BitValue) {
break;
}
r++;
if (r >= MaxRunLength) {
return MaxRunLength;
}
}
return r;
}
ULONG
KBitmap::QueryPrecedingRunLength(
__in ULONG StartingBit,
__out BOOLEAN& BitValue,
__in_opt ULONG MaxRunLength
)
/*++
Routine Description:
This routine will return the length and type of the run that immediately precedes the given starting bit, going backwards.
Arguments:
StartingBit - Supplies the bit number. The run returned immediately precedes this bit.
BitValue - Returns whether the run is a run of zeros or a run of ones.
MaxRunLength - Supplies, optionally, the maximum run length that this function will return.
Return Value:
The number of bits in the run that immediately precedes the given start bit.
--*/
{
ULONG r = 0;
ULONG runLengthLimit;
ULONG numBitsInFirstChunk;
ULONG i;
ULONG startChunk;
KBitmapChunkType* p;
KBitmapChunkType fullBits;
if (StartingBit > _Bits) {
//
// The start bit is out of range. The run length is zero.
//
return 0;
}
if (!StartingBit) {
//
// There aren't any bits that precedes this one.
//
return 0;
}
//
// Compute the largest possible answer and set that into 'MaxRunLength'.
//
runLengthLimit = StartingBit;
if (MaxRunLength) {
if (MaxRunLength > runLengthLimit) {
MaxRunLength = runLengthLimit;
}
} else {
MaxRunLength = runLengthLimit;
}
//
// Figure out how many bits to individually check in the first chunk.
//
numBitsInFirstChunk = StartingBit%g_BitsPerChunk;
//
// Check the first chunk bit by bit.
//
BitValue = CheckBit(StartingBit - 1);
for (i = 1; i <= numBitsInFirstChunk; i++) {
if (CheckBit(StartingBit - i) != BitValue) {
return r;
}
r++;
if (r >= MaxRunLength) {
return MaxRunLength;
}
}
//
// Figure the index of the first whole chunk that will be checked.
//
startChunk = StartingBit/g_BitsPerChunk - 1;
//
// Set up the loop by getting a chunk pointer to the bitmap and by knowing the type of the run that will be returned.
//
p = (KBitmapChunkType*) _Buffer;
//
// Check for whole chunks.
//
if (BitValue) {
fullBits = MAXULONGLONG;
} else {
fullBits = 0;
}
for (i = startChunk; ; i--) {
if (p[i] != fullBits) {
break;
}
r += g_BitsPerChunk;
if (r >= MaxRunLength) {
return MaxRunLength;
}
}
//
// The final chunk that was checked was mixed. Check it again, bit by bit.
//
StartingBit = (i + 1)*g_BitsPerChunk;
for (i = 1; i <= g_BitsPerChunk; i++) {
if (CheckBit(StartingBit - i) != BitValue) {
break;
}
r++;
if (r >= MaxRunLength) {
return MaxRunLength;
}
}
return r;
}
KAllocationBitmap::~KAllocationBitmap(
)
{
Cleanup();
}
KAllocationBitmap::KAllocationBitmap(
__in ULONG NumberOfBits,
__in ULONG AllocationTag
) :
_FreeList(FIELD_OFFSET(BitmapRun, ListEntry)),
_StartCompare(&KAllocationBitmap::StartCompare),
_LengthCompare(&KAllocationBitmap::LengthCompare),
_StartSorted(FIELD_OFFSET(BitmapRun, StartSort), _StartCompare),
_LengthSorted(FIELD_OFFSET(BitmapRun, LengthSort), _LengthCompare)
{
Zero();
SetConstructorStatus(Initialize(NumberOfBits, AllocationTag));
}
KAllocationBitmap::KAllocationBitmap(
__in ULONG NumberOfBits,
__inout KIoBufferElement& IoBufferElement,
__in ULONG AllocationTag
) :
_FreeList(FIELD_OFFSET(BitmapRun, ListEntry)),
_StartCompare(&KAllocationBitmap::StartCompare),
_LengthCompare(&KAllocationBitmap::LengthCompare),
_StartSorted(FIELD_OFFSET(BitmapRun, StartSort), _StartCompare),
_LengthSorted(FIELD_OFFSET(BitmapRun, LengthSort), _LengthCompare)
{
Zero();
SetConstructorStatus(Initialize(NumberOfBits, IoBufferElement, AllocationTag));
}
NTSTATUS
KAllocationBitmap::Create(
__in ULONG NumberOfBits,
__out KAllocationBitmap::SPtr& AllocatorBitmap,
__in KAllocator& Allocator,
__in ULONG AllocationTag
)
{
KAllocationBitmap* bitmap;
NTSTATUS status;
bitmap = _new(AllocationTag, Allocator) KAllocationBitmap(NumberOfBits, AllocationTag);
if (!bitmap) {
return STATUS_INSUFFICIENT_RESOURCES;
}
status = bitmap->Status();
if (!NT_SUCCESS(status)) {
_delete(bitmap);
return status;
}
AllocatorBitmap = bitmap;
return STATUS_SUCCESS;
}
NTSTATUS
KAllocationBitmap::CreateFromIoBufferElement(
__in ULONG NumberOfBits,
__inout KIoBufferElement& IoBufferElement,
__out KAllocationBitmap::SPtr& AllocatorBitmap,
__in KAllocator& Allocator,
__in ULONG AllocationTag
)
{
KAllocationBitmap* bitmap;
NTSTATUS status;
bitmap = _new(AllocationTag, Allocator) KAllocationBitmap(NumberOfBits, IoBufferElement, AllocationTag);
if (!bitmap) {
return STATUS_INSUFFICIENT_RESOURCES;
}
status = bitmap->Status();
if (!NT_SUCCESS(status)) {
_delete(bitmap);
return status;
}
AllocatorBitmap = bitmap;
return STATUS_SUCCESS;
}
ULONG
KAllocationBitmap::QueryNumberOfBits(
)
{
return _Bitmap.QueryNumberOfBits();
}
BOOLEAN
KAllocationBitmap::Allocate(
__in ULONG NumberOfBits,
__out ULONG& StartBit
)
/*++
Routine Description:
This routine allocates a run of bits of the given length. The basic invariant of the list is maintained.
The invariant states that the first run in the list is the first free run in the bitmap.
Every successive entry in the points to a run that is the first run that is strictly greater than its
predecessory. Finally, the 'largestgap' field demarks the largest run between this run and the successor run.
Therefore we have the following invariants to maintain for all runs r(i) in the list:
1. r(i)->Start < r(i+1)->Start, for all i in [1,n)
2. r(i)->Length < r(i+1)->Length, for all i in [1,n) *and* r(1)->Length > 0
3. r(i)->LargestGapLength <= r(i)->Length, for all i in [1, n]
4. r(i)->LargestGapLength is exactly the length of the largest run in (r(i)->Start + r(i)->Length, r(i+1)->Start)
Arguments:
NumberOfBits - Supplies the number of bits to allocate.
StartBit - Returns the first bit of the allocation.
Return Value:
FALSE - The allocation failed. There isn't sufficient free space for this allocation.
TRUE - The allocation succeeded.
--*/
{
BitmapRun searchKey;
BitmapRun* run;
BitmapRun* prev;
ULONG prevLength;
ULONG prevGap;
ULONG largest;
StartBit = 0;
if (!NumberOfBits) {
//
// Allocating 0 bits always succeeds.
//
return TRUE;
}
//
// Find a run that is sufficiently large for the request.
//
searchKey.Length = NumberOfBits;
run = _LengthSorted.LookupEqualOrNext(searchKey);
if (!run) {
//
// There isn't a run that will accomodate this allocation request. Quit.
//
return FALSE;
}
//
// Capture that allocation from this run and modify the length of the run accordingly.
//
StartBit = run->Start;
run->Start += NumberOfBits;
run->Length -= NumberOfBits;
_Bitmap.SetBits(StartBit, NumberOfBits);
_FreeBits -= NumberOfBits;
//
// Now do the fixup of the list. Consider all the cases.
//
prev = _LengthSorted.Previous(*run);
prevLength = prev ? prev->Length : 0;
prevGap = prev ? prev->LargestGapLength : 0;
if (prevLength >= run->Length) {
//
// In this case, this run must be taken out of the list because its length is not longer than its predecessor which
// violates invariant #2 above.
//
_LengthSorted.Remove(*run);
_StartSorted.Remove(*run);
_FreeList.InsertHead(run);
//
// The known largest gap between prev and next is the max of prev->LargestGapLength, run->Length, and
// run->LargestGapLength.
//
largest = prevGap;
if (largest < run->Length) {
largest = run->Length;
}
if (largest < run->LargestGapLength) {
largest = run->LargestGapLength;
}
if (largest > prevLength) {
//
// In this case invariant #3 is violated. We must scan the (run, next) range runs that are larger than prev->Length.
// To set this up properly, first set the correct 'LargestGapLength' on 'prev' to cover the range (prev, run].
//
if (prev && prevGap < run->Length) {
prev->LargestGapLength = run->Length;
}
//
// Now, scan (run, next). The largest possible run in this range is known to be 'run->LargestGapLength'.
//
SetupRunsList(prev, run->Start + run->Length, run->LargestGapLength);
} else {
//
// Otherwise no scan is required, just set the correct largest gap length field.
//
if (prev) {
prev->LargestGapLength = largest;
}
}
} else if (run->LargestGapLength > run->Length) {
//
// In this case Invariant #2 is fine. But invariant #3 is violated. To fix this we must scan (run, next) for
// runs that are larger than run->Length and insert them. We happen to know that the largest run in this range is
// of length 'run->LargestGapLength'.
//
largest = run->LargestGapLength;
run->LargestGapLength = 0;
SetupRunsList(run, run->Start + run->Length, largest);
} else {
//
// In this case Invariant #2 is fine and invariant #3 is fine. Nothing to do.
//
}
// KAssert(Verify());
return TRUE;
}
VOID
KAllocationBitmap::Free(
__in ULONG StartBit,
__in ULONG NumberOfBits
)
/*++
Routine Description:
This routine frees the given range of bits.
Arguments:
StartBit - Supplies the beginning of the range to free.
NumberOfBits - Supplies the number of bits to free.
Return Value:
None.
--*/
{
FreeWorker(StartBit, NumberOfBits, FALSE);
}
VOID
KAllocationBitmap::SetAsAllocated(
__in ULONG StartBit,
__in ULONG NumberOfBits
)
/*++
Routine Description:
This routine will sets the given bits as 'allocated', regardless of their current state.
Arguments:
StartBit - Supplies the beginning of the range.
NumberOfBits - Supplies the number of bits in the range.
Return Value:
None.
--*/
{
ULONG i;
ULONG length;
BOOLEAN bit;
if (StartBit >= _Bitmap.QueryNumberOfBits()) {
//
// A call that start outside of the range is only valid if it doesn't affect any bits.
//
KAssert(!NumberOfBits);
return;
}
if (_Bitmap.QueryNumberOfBits() - StartBit < NumberOfBits) {
//
// This request starts in range, but then goes out of range. Such a call is invalid.
//
KAssert(FALSE);
NumberOfBits = _Bitmap.QueryNumberOfBits() - StartBit;
}
//
// Iterate through all of the runs in the given range and call 'SetAllocatedAsFree' on those runs that are set.
//
i = 0;
while (i < NumberOfBits) {
length = _Bitmap.QueryRunLength(StartBit + i, bit, NumberOfBits - i);
KInvariant(length);
if (!bit) {
//
// This range is marked as free, make it allocated.
//
SetFreeAsAllocated(StartBit + i, length);
}
i += length;
}
}
VOID
KAllocationBitmap::SetAsFree(
__in ULONG StartBit,
__in ULONG NumberOfBits
)
/*++
Routine Description:
This routine will sets the given bits as 'free', regardless of their current state.
Arguments:
StartBit - Supplies the beginning of the range.
NumberOfBits - Supplies the number of bits in the range.
Return Value:
None.
--*/
{
FreeWorker(StartBit, NumberOfBits, TRUE);
}
BOOLEAN
KAllocationBitmap::CheckIfFree(
__in ULONG StartBit,
__in ULONG NumberOfBits
)
/*++
Routine Description:
This routine figures out whether or not the given range of bits are free.
Arguments:
StartBit - Supplies the beginning of the range to check.
NumberOfBits - Supplies the number of bits to check.
Return Value:
FALSE - Some of the bits are not free.
TRUE - All of the bits are free.
--*/
{
return _Bitmap.AreBitsClear(StartBit, NumberOfBits);
}
BOOLEAN
KAllocationBitmap::CheckIfAllocated(
__in ULONG StartBit,
__in ULONG NumberOfBits
)
/*++
Routine Description:
This routine figures out whether or not the given range of bits are allocated.
Arguments:
StartBit - Supplies the beginning of the range to check.
NumberOfBits - Supplies the number of bits to check.
Return Value:
FALSE - Some of the bits are not allocated.
TRUE - All of the bits are allocated.
--*/
{
return _Bitmap.AreBitsSet(StartBit, NumberOfBits);
}
ULONG
KAllocationBitmap::QueryNumFreeBits(
)
/*++
Routine Description:
This routine returns the number of free bits.
Arguments:
None.
Return Value:
The number of free bits.
--*/
{
return _FreeBits;
}
ULONG
KAllocationBitmap::QueryRunLength(
__in ULONG StartingBit,
__out BOOLEAN& IsAllocated,
__in_opt ULONG MaxRunLength
)
/*++
Routine Description:
This routine returns the run length of the run started by the given bit.
Arguments:
StartingBit - Supplies the start bit for the run.
IsAllocated - Returns whether or not the run is allocated or free.
MaxRunLength - Returns the maximum run length desired and that will be returned as the result of this function.
Return Value:
The run length.
--*/
{
return _Bitmap.QueryRunLength(StartingBit, IsAllocated, MaxRunLength);
}
ULONG
KAllocationBitmap::QueryPrecedingRunLength(
__in ULONG StartingBit,
__out BOOLEAN& IsAllocated,
__in_opt ULONG MaxRunLength
)
/*++
Routine Description:
This routine returns the run length of the run that precedes the given bit.
Arguments:
StartingBit - Supplies the start bit for the run.
IsAllocated - Returns whether or not the run is allocated or free.
MaxRunLength - Returns the maximum run length desired and that will be returned as the result of this function.
Return Value:
The run length.
--*/
{
return _Bitmap.QueryPrecedingRunLength(StartingBit, IsAllocated, MaxRunLength);
}
BOOLEAN
KAllocationBitmap::Verify(
)
/*++
Routine Description:
This routine ensures that the list is exactly correct for the current bitmap. A full bitmap scan is
made.
Arguments:
None.
Return Value:
FALSE - The list is not correct according to the bitmap.
TRUE - The list is correct.
--*/
{
BOOLEAN r = TRUE;
BitmapRun* run;
BitmapRunTable startSorted(FIELD_OFFSET(BitmapRun, StartSort), _StartCompare);
BOOLEAN b;
BitmapRun* newRun;
//
// Make sure that start-sorted and length-sorted are exactly the same.
//
run = _StartSorted.First();
newRun = _LengthSorted.First();
for (;;) {
if (run != newRun) {
KAssert(FALSE);
return FALSE;
}
if (!run) {
break;
}
newRun = _LengthSorted.Next(*run);
run = _StartSorted.Next(*run);
}
//
// As a first step save the current table to a local variable.
//
while ((run = _StartSorted.First()) != NULL) {
_StartSorted.Remove(*run);
_LengthSorted.Remove(*run);
b = startSorted.Insert(*run);
if (!b) {
KAssert(FALSE);
return FALSE;
}
}
//
// Setup the list from scratch.
//
SetupRunsList(NULL, 0, 0);
//
// Now go through and make sure that the lists are the same.
//
run = startSorted.First();
newRun = _StartSorted.First();
for (;;) {
if (!run) {
if (newRun) {
r = FALSE;
KAssert(FALSE);
}
break;
}
if (!newRun) {
r = FALSE;
KAssert(FALSE);
break;
}
if (run->Start != newRun->Start || run->Length != newRun->Length || run->LargestGapLength != newRun->LargestGapLength) {
r = FALSE;
KAssert(FALSE);
break;
}
run = startSorted.Next(*run);
newRun = _StartSorted.Next(*newRun);
}
//
// Return items to the free list.
//
while ((run = startSorted.First()) != NULL){
startSorted.Remove(*run);
_FreeList.InsertHead(run);
}
return r;
}
VOID
KAllocationBitmap::Zero(
)
{
_NumberOfFreeListBitmapRuns = 0;
_FreeListBitmapRuns = NULL;
_FreeBits = 0;
}
VOID
KAllocationBitmap::Cleanup(
)
{
BitmapRun* run;
for (;;) {
run = _FreeList.RemoveHead();
if (!run) {
break;
}
}
for (;;) {
run = _StartSorted.First();
if (!run) {
break;
}
_StartSorted.Remove(*run);
}
for (;;) {
run = _LengthSorted.First();
if (!run) {
break;
}
_LengthSorted.Remove(*run);
}
_deleteArray(_FreeListBitmapRuns);
}
NTSTATUS
KAllocationBitmap::Initialize(
__in ULONG NumberOfBits,
__in ULONG AllocationTag
)
/*++
Routine Description:
This routine initializes a new, completely free, bitmap of the given size.
Arguments:
NumberOfBits - Supplies the number of bits.
AllocationTag - Supplies the allocation tag.
Return Value:
NTSTATUS
--*/
{
ULONG bitmapSize;
NTSTATUS status;
//
// The bitmap size must be properly aligned.
//
bitmapSize = KBitmap::QueryRequiredBufferSize(NumberOfBits);
//
// Allocate an IO buffer element that is sufficiently large for the bitmap.
//
status = KBuffer::Create(bitmapSize, _Buffer, GetThisAllocator(), AllocationTag);
if (!NT_SUCCESS(status)) {
return status;
}
//
// Zero the memory.
//
_Buffer->Zero();
//
// Initialize the bitmap object.
//
_Bitmap.Reuse(_Buffer->GetBuffer(), bitmapSize, NumberOfBits);
//
// Create the free list for this bitmap.
//
status = CreateFreeList();
if (!NT_SUCCESS(status)) {
return status;
}
//
// Setup the runs list.
//
SetupRunsList(NULL, 0, 0);
//
// All of the bits are free.
//
_FreeBits = NumberOfBits;
return STATUS_SUCCESS;
}
NTSTATUS
KAllocationBitmap::Initialize(
__in ULONG NumberOfBits,
__inout KIoBufferElement& IoBufferElement,
__in ULONG AllocationTag
)
/*++
Routine Description:
This routine initializes a bitmap of the given size with the given initial state fas provided by the IO buffer element.
Arguments:
NumberOfBits - Supplies the number of bits.
IoBufferElement - Supplies the bitmap buffer to use with its given initial state.
AllocationTag - Supplies the allocation tag.
Return Value:
NTSTATUS
--*/
{
ULONG bitmapSize;
NTSTATUS status;
UNREFERENCED_PARAMETER(AllocationTag);
//
// The bitmap size must be properly aligned.
//
bitmapSize = KBitmap::QueryRequiredBufferSize(NumberOfBits);
//
// Make sure that the given buffer sufficiently large.
//
if (IoBufferElement.QuerySize() < bitmapSize) {
KAssert(FALSE);
return STATUS_INVALID_PARAMETER;
}
//
// Keep a reference to the IO buffer element.
//
_IoBufferElement = &IoBufferElement;
//
// Initialize the bitmap object.
//
_Bitmap.Reuse((VOID*) _IoBufferElement->GetBuffer(), bitmapSize, NumberOfBits);
//
// Create the free list for this bitmap.
//
status = CreateFreeList();
if (!NT_SUCCESS(status)) {
return status;
}
//
// Setup the runs list.
//
SetupRunsList(NULL, 0, 0);
//
// Compute the number of free bits.
//
_FreeBits = NumberOfBits - _Bitmap.QueryNumberOfSetBits();
return STATUS_SUCCESS;
}
NTSTATUS
KAllocationBitmap::CreateFreeList(
)
/*++
Routine Description:
This routine creates the list of free runs for use with this bitmap. The free list is created to be sufficiently large so
as to be enough for any bitmap pattern of the size of this bitmap. Given the invariants described in the comment block
for Allocate, you can show that the maximum number of runs 'r' needed for a bitmap with 'n' bits must be chosen so that:
1 + sum(i + 1, i=2..r) >= n
When solving yields:
(r + 1)(r + 2) >= 2n + 4
From there this routine allocates a single buffer that is sufficiently large and then carves out a free list.
Arguments:
None.
Return Value:
NTSTATUS
--*/
{
ULONGLONG target;
ULONGLONG r;
ULONGLONG source;
ULONG i;
target = _Bitmap.QueryNumberOfBits();
target *= 2;
target += 4;
//
// Double r until we get a value that is large enough.
//
r = 1;
for (;;) {
source = (r + 1)*(r + 2);
if (source >= target) {
break;
}
r *= 2;
}
//
// Allocate a single buffer of sufficient size. Double the required buffer size to accomodate 'Verify'.
//
// BUG: RLH Possible Overflow
_NumberOfFreeListBitmapRuns = (ULONG) r*2;
_FreeListBitmapRuns = _newArray<BitmapRun>(KTL_TAG_BITMAP, GetThisAllocator(), _NumberOfFreeListBitmapRuns);
if (!_FreeListBitmapRuns) {
return STATUS_INSUFFICIENT_RESOURCES;
}
//
// Carve out the needed free runs from that large buffer.
//
for (i = 0; i < _NumberOfFreeListBitmapRuns; i++) {
_FreeList.AppendTail(&_FreeListBitmapRuns[i]);
}
return STATUS_SUCCESS;
}
VOID
KAllocationBitmap::SetupRunsList(
__in_opt BitmapRun* ScanStartRun,
__in ULONG ScanStart,
__in ULONG KnownLargestRun
)
/*++
Routine Description:
This routine sets up the increasing runs list, between 2 points in the bitmap.
Arguments:
ScanStartRun - Supplies the run to start scanning from.
ScanStart - Supplies the bit number to start scanning from.
KnownLargestRun - Supplies the known largest run in the range up to the next run.
Return Value:
None.
--*/
{
BitmapRun* run;
ULONG end;
ULONG i;
ULONG length;
BOOLEAN bit;
BitmapRun* newRun;
BOOLEAN b;
if (ScanStartRun) {
run = _StartSorted.Next(*ScanStartRun);
} else {
run = _StartSorted.First();
}
if (run) {
end = run->Start;
} else {
end = _Bitmap.QueryNumberOfBits();
}
run = ScanStartRun;
i = ScanStart;
for (;;) {
if (run && KnownLargestRun && run->LargestGapLength == KnownLargestRun) {
//
// There are no runs greater than this to be found. We can exit.
//
break;
}
if (i >= end) {
//
// We're beyond the end of the scan. Exit.
//
break;
}
//
// Find the next free run, starting at i.
//
length = _Bitmap.QueryRunLength(i, bit, end - i);
KInvariant(length);
if (bit) {
//
// Skip over this allocated part.
//
i += length;
if (i >= end) {
//
// We're beyond the end of the scan. Exit.
//
break;
}
//
// Scan now for a free run.
//
length = _Bitmap.QueryRunLength(i, bit, end - i);
KInvariant(length);
KInvariant(!bit);
}
if (!run || length > run->Length) {
//
// We have a new run to add.
//
newRun = _FreeList.RemoveHead();
KInvariant(newRun);
newRun->Start = i;
newRun->Length = length;
newRun->LargestGapLength = 0;
b = _StartSorted.Insert(*newRun);
KInvariant(b);
b = _LengthSorted.Insert(*newRun);
KInvariant(b);
//
// Resume the scan with this new run as most recent.
//
run = newRun;
} else if (length > run->LargestGapLength) {
//
// A larger, largest-gap was found. Remember this new maximum.
//
run->LargestGapLength = length;
}
i += length;
}
}
VOID
KAllocationBitmap::FreeWorker(
__in ULONG StartBit,
__in ULONG NumberOfBits,
__in BOOLEAN BitsMayNotBeAllocated
)
/*++
Routine Description:
This routine frees the given set of bits. The routine will KAssert if the bits are not allocated and if 'BitsAreAllocated'
is set.
Arguments:
StartBit - Supplies the start of the run to mark as free.
NumberOfBits - Supplies the length of the run to mark as free.
BitsMayNotBeAllocated - Supplies that not all bits are necessarily allocated.
Return Value:
None.
--*/
{
ULONG i;
ULONG length;
BOOLEAN bit;
if (StartBit >= _Bitmap.QueryNumberOfBits()) {
//
// A call that start outside of the range is only valid if it doesn't affect any bits.
//
KAssert(!NumberOfBits);
return;
}
if (_Bitmap.QueryNumberOfBits() - StartBit < NumberOfBits) {
//
// This request starts in range, but then goes out of range. Such a call is invalid.
//
KAssert(FALSE);
NumberOfBits = _Bitmap.QueryNumberOfBits() - StartBit;
}
//
// Iterate through all of the runs in the given range and call 'SetAllocatedAsFree' on those runs that are set.
//
i = 0;
while (i < NumberOfBits) {
length = _Bitmap.QueryRunLength(StartBit + i, bit, NumberOfBits - i);
KInvariant(length);
if (bit) {
//
// This range is marked as allocated.
//
SetAllocatedAsFree(StartBit + i, length);
} else {
//
// There is a range that is not allocated here. Is this expected?
//
KInvariant(BitsMayNotBeAllocated);
}
i += length;
}
}
VOID
KAllocationBitmap::SetAllocatedAsFree(
__in ULONG StartBit,
__in ULONG NumberOfBits
)
/*++
Routine Description:
This routine marks allocated bits as free.
Arguments:
StartBit - Supplies the start of the run to mark as free.
NumberOfBits - Supplies the length of the run to mark as free.
Return Value:
None.
--*/
{
BitmapRun* pendingLengthInsert = NULL;
BitmapRun searchKey;
BitmapRun* run;
BitmapRun* prev;
ULONG start;
ULONG length;
BOOLEAN bit;
ULONG end;
ULONG delta;
ULONG n;
ULONG largestGap;
BitmapRun* newRun;
BitmapRun* next;
BOOLEAN b;
if (!NumberOfBits) {
//
// Nothing to do.
//
return;
}
//
// Start off by clearing the bits in the bitmap and adjusting the free bits count.
//
_Bitmap.ClearBits(StartBit, NumberOfBits);
_FreeBits += NumberOfBits;
//
// Look for the first run in the list that is greater than the run being freed. Since the run being
// freed was allocated, it could not be part of the list. So, lookup-equal-or-next can only return a greater value.
//
searchKey.Start = StartBit;
run = _StartSorted.LookupEqualOrNext(searchKey);
KInvariant(!run || run->Start > StartBit);
//
// Find the run that is the greatest one in the list that is less than the run being freed.
//
prev = run ? _StartSorted.Previous(*run) : _StartSorted.Last();
//
// Set 'start' to be the beginning of the free run formed by this free command.
//
if (!prev) {
//
// This free run comes before the formerly first free run. The beginning of the entire free run is simply the beginning
// of the run being freed.
//
start = StartBit;
} else if (prev->Start + prev->Length == StartBit) {
//
// In this case the run in the list is directly adjacent to this new free run, so the beginning
// of the entire free run is just the beginning of the free run in the list.
//
start = prev->Start;
} else {
//
// Otherwise scan backwards to find the beginning of the run.
//
start = StartBit;
if (start && !_Bitmap.CheckBit(start - 1)) {
length = _Bitmap.QueryPrecedingRunLength(start, bit);
KInvariant(!bit);
start -= length;
}
}
//
// Set 'end' to the end of the free run formed by this free command.
//
if (run && StartBit + NumberOfBits == run->Start) {
//
// In this case the new free joins the run that comes after it. And so the end of the free run formed by this free
// is just the end of the next run in the list.
//
end = run->Start + run->Length;
} else {
//
// Otherwise scan forwards to find the end of the run.
//
end = StartBit + NumberOfBits;
if (end < _Bitmap.QueryNumberOfBits() && !_Bitmap.CheckBit(end)) {
length = _Bitmap.QueryRunLength(end, bit);
KInvariant(!bit);
end += length;
}
}
//
// For this next part fix up the list and the 'largestgap' fields without necessarily keeping
// the list monotonic. So after this step Invariant #3 will be correct.
//
if (prev && prev->Start == start) {
//
// This is the case where the preceding run merges with the new run. Set the preceding length accordingly.
//
prev->Length = end - prev->Start;
if (run && run->Start < end) {
//
// This is the case where the next run also merges with the new run. We can take the next run out of the list.
// Also, the largest gap corresponds simply to the largest gap that came after the next run.
//
_StartSorted.Remove(*run);
_LengthSorted.Remove(*run);
_FreeList.InsertHead(run);
prev->LargestGapLength = run->LargestGapLength;
//
// Reset the next run pointer to the next run.
//
run = _StartSorted.Next(*prev);
} else {
//
// In this case the next run is separate from the new run. There is a case where the new end consumed a formerly
// largest gap. We need to rescan for this case to find the new largest gap, knowing that it is no larger than
// the former largest gap.
//
if (end - (StartBit + NumberOfBits) == prev->LargestGapLength && prev->LargestGapLength) {
prev->LargestGapLength = LongestRun(end, run ? run->Start : _Bitmap.QueryNumberOfBits(), prev->LargestGapLength);
}
}
} else if (run && run->Start < end) {
//
// In this case the new run merges with the next run, but is separate from the preceding run. Adjust the next run
// to include the freed run.
//
delta = run->Start - start;
run->Start -= delta;
run->Length += delta;
//
// There is a case where the new start consumed a formerly largest gap of the preceding run. We need to rescan
// to establish the new largest gap for the preceding run, knowing that it is no larger than the former largest gap.
//
if (prev && StartBit - start == prev->LargestGapLength && prev->LargestGapLength) {
prev->LargestGapLength = LongestRun(prev->Start + prev->Length, run->Start, prev->LargestGapLength);
}
//
// Now set the run that just consumed the new free as the preceding run.
//
prev = run;
run = _StartSorted.Next(*prev);
} else {
//
// In this case the new run does not merge with either the preceding run nor with the next run.
// Let 'n' be the length of the new run.
//
n = end - start;
if (!prev) {
//
// In this case there is no preceding run, which makes this run the first in the list. This also means
// that there are no free runs at all between this one and the next one in the list so we can set the
// 'largestgap' to 0.
//
prev = _FreeList.RemoveHead();
prev->Start = start;
prev->Length = n;
prev->LargestGapLength = 0;
b = _StartSorted.Insert(*prev);
KInvariant(b);
pendingLengthInsert = prev;
} else if (prev->Length < n) {
//
// In this case the length of the preceding run is less than the length of this run. So, we can do the insert.
// The largest gap for the preceding run may have been reduced because this run may end up being in the way
// of its formerly largest gap run.
//
largestGap = prev->LargestGapLength;
if (largestGap) {
prev->LargestGapLength = LongestRun(prev->Start + prev->Length, start, largestGap);
}
newRun = _FreeList.RemoveHead();
newRun->Start = start;
newRun->Length = n;
if (largestGap) {
newRun->LargestGapLength = LongestRun(end, run ? run->Start : _Bitmap.QueryNumberOfBits(), largestGap);
} else {
newRun->LargestGapLength = 0;
}
b = _StartSorted.Insert(*newRun);
KInvariant(b);
pendingLengthInsert = newRun;
prev = newRun;
} else if (prev->LargestGapLength < n) {
//
// This is the case where this free run will not be inserted into the list. But, the largest gap field of the
// preceding run is affected because a new longer free run has been created.
//
prev->LargestGapLength = n;
}
}
//
// At this point all gap fields are less than the length fields as required by invariant #3. We can just
// remove any runs that violate invariant #2.
//
while (run && run->Length <= prev->Length) {
if (run->Length > prev->LargestGapLength) {
prev->LargestGapLength = run->Length;
}
next = _StartSorted.Next(*run);
_StartSorted.Remove(*run);
_LengthSorted.Remove(*run);
_FreeList.InsertHead(run);
run = next;
}
//
// It may be that the insertion of 'prev' into the length table has been delayed until the length table was cleared
// of conflicting items. Check for that here and make the length table correct.
//
if (pendingLengthInsert) {
_LengthSorted.Insert(*pendingLengthInsert);
}
// KAssert(Verify());
}
ULONG
KAllocationBitmap::LongestRun(
__in ULONG Start,
__in ULONG End,
__in ULONG UpperBoundForLargestRun
)
/*++
Routine Description:
This routine finds the longest free run in the given range of the bitmap.
Arguments:
Start - Supplies the start position to start the search.
End - Supplies the end postion to end the search.
UpperBoundForLargestRun - Supplies a known maximum for the largest free run.
Return Value:
The length of the longest run.
--*/
{
ULONG r;
ULONG i;
ULONG length;
BOOLEAN bit;
r = 0;
i = Start;
while (i < End) {
length = _Bitmap.QueryRunLength(i, bit, End - i);
if (!bit && length > r) {
r = length;
if (r == UpperBoundForLargestRun) {
break;
}
}
i += length;
}
return r;
}
VOID
KAllocationBitmap::SetFreeAsAllocated(
__in ULONG StartBit,
__in ULONG NumberOfBits
)
/*++
Routine Description:
This routine marks free bits as allocated.
Arguments:
StartBit - Supplies the start of the run to mark as allocated.
NumberOfBits - Supplies the length of the run to mark as allocated.
Return Value:
None.
--*/
{
BOOLEAN intersectionFound = FALSE;
BitmapRun searchKey;
BitmapRun* run;
BitmapRun* prev;
ULONG scanStart;
ULONG oldEnd;
ULONG newEnd;
ULONG largest;
ULONG length;
BOOLEAN bit;
ULONG start;
ULONG end;
//
// Check to see if there is an intersection between what is going to be freed and one of the runs.
// Set 'prev' to the run that comes before the range being freed.
// Set 'run' to the run that comes after the range being freed or the intersecting run, if there is one.
//
searchKey.Start = StartBit;
run = _StartSorted.LookupEqualOrPrevious(searchKey);
if (run) {
if (StartBit >= run->Start + run->Length) {
prev = run;
run = _StartSorted.Next(*run);
} else {
prev = _StartSorted.Previous(*run);
intersectionFound = TRUE;
}
} else {
prev = NULL;
run = _StartSorted.First();
KInvariant(run);
}
//
// Set the bits the way they should go.
//
_Bitmap.SetBits(StartBit, NumberOfBits);
_FreeBits -= NumberOfBits;
//
// Consider both cases where the intersection was found and not found.
//
if (intersectionFound) {
if (StartBit == run->Start) {
//
// In this case the part being marked allocated coincides with the beginning of the run. The run must
// necessarily be at least as long as what is being freed. Reduce the length of the run. Remember
// that a scan is needed starting at the end of the run.
//
KInvariant(run->Length >= NumberOfBits);
run->Length -= NumberOfBits;
run->Start += NumberOfBits;
scanStart = run->Start + run->Length;
} else {
//
// In this case the run keeps its beginning and then might be split. The start of the allocate is necessarily
// greater than the start of the run. The end of the allocate is necessarily within the run. Remember the
// old end of the run and the new end of the run. Allow that the run's largest gap might be greater now that
// a free part of the original run has been split off into the space between this run and the next run.
// Remember that the scan is needed starting at the end of allocation.
//
KInvariant(StartBit > run->Start);
KInvariant(StartBit + NumberOfBits <= run->Start + run->Length);
oldEnd = run->Start + run->Length;
run->Length = StartBit - run->Start;
newEnd = run->Start + run->Length;
KInvariant(oldEnd > newEnd);
largest = oldEnd - newEnd;
KInvariant(largest >= NumberOfBits);
largest -= NumberOfBits;
if (largest > run->LargestGapLength) {
run->LargestGapLength = largest;
}
scanStart = StartBit + NumberOfBits;
}
if ((prev && prev->Length >= run->Length) || (!prev && run->Length == 0)) {
//
// In this case, 'run' is not correctly ordered any more. So, take it out of the tables. Do the scan up to the
// next run.
//
_StartSorted.Remove(*run);
_LengthSorted.Remove(*run);
_FreeList.InsertHead(run);
//
// The scan will start after the run, so consider the run for the prev->LargestGap field.
//
if (prev && prev->LargestGapLength < run->Length) {
prev->LargestGapLength = run->Length;
}
//
// Now figure out what the largest gap is between the start of a scan and the next run.
//
largest = prev ? prev->LargestGapLength : 0;
if (largest < run->LargestGapLength) {
largest = run->LargestGapLength;
}
//
// If the largest gap is larger than the existing length then scan, otherwise just remember the largest gap.
//
if (largest > (prev ? prev->Length : 0)) {
SetupRunsList(prev, scanStart, largest);
} else if (prev) {
prev->LargestGapLength = largest;
}
} else if (run->Length < run->LargestGapLength) {
//
// In this case the length is larger than its predecessor, but there is still a run in between this run and
// the next that needs to be added to the list.
//
largest = run->LargestGapLength;
run->LargestGapLength = 0;
SetupRunsList(run, scanStart, largest);
}
} else {
//
// In this case there is no intersection. We cannot come before the first free run.
//
KInvariant(prev);
//
// Find the 'start' and 'end' of the free run that contains this new allocation.
//
start = StartBit;
if (start && !_Bitmap.CheckBit(start - 1)) {
length = _Bitmap.QueryPrecedingRunLength(start, bit);
KInvariant(!bit);
KInvariant(length);
KInvariant(length <= StartBit);
start -= length;
}
end = StartBit + NumberOfBits;
if (end < _Bitmap.QueryNumberOfBits() && !_Bitmap.CheckBit(end)) {
length = _Bitmap.QueryRunLength(end, bit);
KInvariant(!bit);
KInvariant(length);
end += length;
KInvariant(end <= _Bitmap.QueryNumberOfBits());
}
//
// If this former run was greater or equal to the largest gap, then it may be that the largest gap is smaller now.
//
if (end - start >= prev->LargestGapLength) {
largest = prev->LargestGapLength;
prev->LargestGapLength = 0;
SetupRunsList(prev, prev->Start + prev->Length, largest);
}
}
// KAssert(Verify());
}
LONG
KAllocationBitmap::StartCompare(
__in BitmapRun& First,
__in BitmapRun& Second
)
/*++
Routine Description:
This routine compares the 2 bitmap runs by start value.
Arguments:
First - Supplies the first run to compare.
Second - Supplies the second run to compare.
Return Value:
<0 - The first run's start value is less than the second's.
0 - Both runs have equal start values.
>0 - The first run's start value is greater than the second's.
--*/
{
if (First.Start < Second.Start) {
return -1;
}
if (First.Start > Second.Start) {
return 1;
}
return 0;
}
LONG
KAllocationBitmap::LengthCompare(
__in BitmapRun& First,
__in BitmapRun& Second
)
/*++
Routine Description:
This routine compares the 2 bitmap runs by length value.
Arguments:
First - Supplies the first run to compare.
Second - Supplies the second run to compare.
Return Value:
<0 - The first run's length value is less than the second's.
0 - Both runs have equal length values.
>0 - The first run's length value is greater than the second's.
--*/
{
if (First.Length < Second.Length) {
return -1;
}
if (First.Length > Second.Length) {
return 1;
}
return 0;
}
| 22.407195
| 129
| 0.591631
|
vishnuk007
|
002c5adea58d6ee8209c2dd80bb3a6fda007dedd
| 6,438
|
cxx
|
C++
|
vtkm/filter/testing/UnitTestContourFilterCustomPolicy.cxx
|
yisyuanliou/VTK-m
|
cc483c8c2319a78b58b3ab849da8ca448e896220
|
[
"BSD-3-Clause"
] | null | null | null |
vtkm/filter/testing/UnitTestContourFilterCustomPolicy.cxx
|
yisyuanliou/VTK-m
|
cc483c8c2319a78b58b3ab849da8ca448e896220
|
[
"BSD-3-Clause"
] | null | null | null |
vtkm/filter/testing/UnitTestContourFilterCustomPolicy.cxx
|
yisyuanliou/VTK-m
|
cc483c8c2319a78b58b3ab849da8ca448e896220
|
[
"BSD-3-Clause"
] | null | null | null |
//============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
//
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//============================================================================
#include <vtkm/Math.h>
#include <vtkm/cont/ArrayHandleUniformPointCoordinates.h>
#include <vtkm/cont/CellSetSingleType.h>
#include <vtkm/cont/DataSet.h>
#include <vtkm/cont/DataSetBuilderUniform.h>
#include <vtkm/cont/DataSetFieldAdd.h>
#include <vtkm/cont/testing/Testing.h>
#include <vtkm/filter/Contour.h>
#include <vtkm/filter/Contour.hxx>
namespace vtkm_ut_mc_policy
{
class EuclideanNorm
{
public:
VTKM_EXEC_CONT
EuclideanNorm()
: Reference(0., 0., 0.)
{
}
VTKM_EXEC_CONT
EuclideanNorm(vtkm::Vec3f_32 reference)
: Reference(reference)
{
}
VTKM_EXEC_CONT
vtkm::Float32 operator()(vtkm::Vec3f_32 v) const
{
vtkm::Vec3f_32 d(
v[0] - this->Reference[0], v[1] - this->Reference[1], v[2] - this->Reference[2]);
return vtkm::Magnitude(d);
}
private:
vtkm::Vec3f_32 Reference;
};
class CubeGridConnectivity
{
public:
VTKM_EXEC_CONT
CubeGridConnectivity()
: Dimension(1)
, DimSquared(1)
, DimPlus1Squared(4)
{
}
VTKM_EXEC_CONT
CubeGridConnectivity(vtkm::Id dim)
: Dimension(dim)
, DimSquared(dim * dim)
, DimPlus1Squared((dim + 1) * (dim + 1))
{
}
VTKM_EXEC_CONT
vtkm::Id operator()(vtkm::Id vertex) const
{
using HexTag = vtkm::CellShapeTagHexahedron;
using HexTraits = vtkm::CellTraits<HexTag>;
vtkm::Id cellId = vertex / HexTraits::NUM_POINTS;
vtkm::Id localId = vertex % HexTraits::NUM_POINTS;
vtkm::Id globalId =
(cellId + cellId / this->Dimension + (this->Dimension + 1) * (cellId / (this->DimSquared)));
switch (localId)
{
case 0:
break;
case 1:
globalId += 1;
break;
case 2:
globalId += this->Dimension + 2;
break;
case 3:
globalId += this->Dimension + 1;
break;
case 4:
globalId += this->DimPlus1Squared;
break;
case 5:
globalId += this->DimPlus1Squared + 1;
break;
case 6:
globalId += this->Dimension + this->DimPlus1Squared + 2;
break;
case 7:
globalId += this->Dimension + this->DimPlus1Squared + 1;
break;
}
return globalId;
}
private:
vtkm::Id Dimension;
vtkm::Id DimSquared;
vtkm::Id DimPlus1Squared;
};
class MakeRadiantDataSet
{
public:
using CoordinateArrayHandle = vtkm::cont::ArrayHandleUniformPointCoordinates;
using DataArrayHandle =
vtkm::cont::ArrayHandleTransform<vtkm::cont::ArrayHandleUniformPointCoordinates, EuclideanNorm>;
using ConnectivityArrayHandle =
vtkm::cont::ArrayHandleTransform<vtkm::cont::ArrayHandleCounting<vtkm::Id>,
CubeGridConnectivity>;
using CellSet = vtkm::cont::CellSetSingleType<
vtkm::cont::ArrayHandleTransform<vtkm::cont::ArrayHandleCounting<vtkm::Id>,
CubeGridConnectivity>::StorageTag>;
vtkm::cont::DataSet Make3DRadiantDataSet(vtkm::IdComponent dim = 5);
};
class PolicyRadiantDataSet : public vtkm::filter::PolicyBase<PolicyRadiantDataSet>
{
public:
using TypeListRadiantCellSetTypes = vtkm::List<MakeRadiantDataSet::CellSet>;
using AllCellSetList = TypeListRadiantCellSetTypes;
};
inline vtkm::cont::DataSet MakeRadiantDataSet::Make3DRadiantDataSet(vtkm::IdComponent dim)
{
// create a cube from -.5 to .5 in x,y,z, consisting of <dim> cells on each
// axis, with point values equal to the Euclidean distance from the origin.
vtkm::cont::DataSet dataSet;
using HexTag = vtkm::CellShapeTagHexahedron;
using HexTraits = vtkm::CellTraits<HexTag>;
using CoordType = vtkm::Vec3f_32;
const vtkm::IdComponent nCells = dim * dim * dim;
vtkm::Float32 spacing = vtkm::Float32(1. / dim);
CoordinateArrayHandle coordinates(vtkm::Id3(dim + 1, dim + 1, dim + 1),
CoordType(-.5, -.5, -.5),
CoordType(spacing, spacing, spacing));
DataArrayHandle distanceToOrigin(coordinates);
DataArrayHandle distanceToOther(coordinates, EuclideanNorm(CoordType(1., 1., 1.)));
ConnectivityArrayHandle connectivity(
vtkm::cont::ArrayHandleCounting<vtkm::Id>(0, 1, nCells * HexTraits::NUM_POINTS),
CubeGridConnectivity(dim));
dataSet.AddCoordinateSystem(vtkm::cont::CoordinateSystem("coordinates", coordinates));
//Set point scalar
dataSet.AddField(vtkm::cont::Field(
"distanceToOrigin", vtkm::cont::Field::Association::POINTS, distanceToOrigin));
dataSet.AddField(
vtkm::cont::Field("distanceToOther", vtkm::cont::Field::Association::POINTS, distanceToOther));
CellSet cellSet;
cellSet.Fill(coordinates.GetNumberOfValues(), HexTag::Id, HexTraits::NUM_POINTS, connectivity);
dataSet.SetCellSet(cellSet);
return dataSet;
}
void TestContourCustomPolicy()
{
std::cout << "Testing Contour filter with custom field and cellset" << std::endl;
using DataSetGenerator = MakeRadiantDataSet;
DataSetGenerator dataSetGenerator;
const vtkm::IdComponent Dimension = 10;
vtkm::cont::DataSet dataSet = dataSetGenerator.Make3DRadiantDataSet(Dimension);
vtkm::filter::Contour mc;
mc.SetGenerateNormals(false);
mc.SetIsoValue(0, 0.45);
mc.SetIsoValue(1, 0.45);
mc.SetIsoValue(2, 0.45);
mc.SetIsoValue(3, 0.45);
//We specify a custom execution policy here, since the "distanceToOrigin" is a
//custom field type
mc.SetActiveField("distanceToOrigin");
mc.SetFieldsToPass({ "distanceToOrigin", "distanceToOther" });
vtkm::cont::DataSet outputData = mc.Execute(dataSet, PolicyRadiantDataSet{});
VTKM_TEST_ASSERT(outputData.GetNumberOfFields() == 2,
"Wrong number of fields in the output dataset");
vtkm::cont::CoordinateSystem coords = outputData.GetCoordinateSystem();
VTKM_TEST_ASSERT(coords.GetNumberOfPoints() == (414 * 4), "Should have some coordinates");
}
} // namespace
int UnitTestContourFilterCustomPolicy(int argc, char* argv[])
{
return vtkm::cont::testing::Testing::Run(vtkm_ut_mc_policy::TestContourCustomPolicy, argc, argv);
}
| 29.39726
| 100
| 0.671326
|
yisyuanliou
|
002e71675b73e01f5ac02992f28b0ce56542690f
| 3,280
|
hpp
|
C++
|
include/radix/Entity.hpp
|
atkurtul/RadixEngine
|
0eb1c176a25aa9430f54d5a20ce5749360c51381
|
[
"Zlib"
] | 163
|
2016-08-28T23:24:05.000Z
|
2022-03-31T04:51:51.000Z
|
include/radix/Entity.hpp
|
atkurtul/RadixEngine
|
0eb1c176a25aa9430f54d5a20ce5749360c51381
|
[
"Zlib"
] | 144
|
2016-09-10T08:40:06.000Z
|
2020-12-03T17:20:03.000Z
|
include/radix/Entity.hpp
|
atkurtul/RadixEngine
|
0eb1c176a25aa9430f54d5a20ce5749360c51381
|
[
"Zlib"
] | 88
|
2016-02-22T08:34:49.000Z
|
2022-03-05T12:29:19.000Z
|
#ifndef RADIX_ENTITY_HPP
#define RADIX_ENTITY_HPP
#include <array>
#include <memory>
#include <stdexcept>
#include <type_traits>
#include <vector>
#include <RadixEntity/Entity.hpp>
#include <radix/Transform.hpp>
#include <radix/core/event/Event.hpp>
#include <radix/core/types/TimeDelta.hpp>
#include <radix/env/Util.hpp>
#include <radix/util/NullReference.hpp>
namespace radix {
class World;
using EntityId = uint32_t;
namespace entities {
class Trait;
}
/** \class Entity
* It is created like this:
* @snippet source/data/map/XmlMapLoader.cpp Creating an Entity
*/
class Entity : public entity::Entity, protected Transform {
private:
friend class EntityManager;
Entity(Entity&) = delete;
Entity& operator=(Entity&) = delete;
Entity(Entity&&) = delete;
Entity& operator=(Entity&&) = delete;
void init();
/**
* Entity's name. Used to find a specific entity from the @ref World entity list.
*/
std::string m_name;
protected:
/**
* List of traits contained within this entity instance.
*/
std::vector<entities::Trait*> m_traits;
Entity() :
world(util::NullReference<World>) {
throw std::invalid_argument("You forgot to properly instantiate the Entity base");
}
public:
struct NameChangedEvent : public Event {
radix_event_declare("radix/Entity:NameChanged")
Entity &entity;
const std::string oldName;
NameChangedEvent(Entity &e, const std::string &o) :
entity(e), oldName(o) {}
};
World &world;
struct CreationParams {
World &world;
EntityId id;
CreationParams(World &world, EntityId id) :
world(world),
id(id) {
}
};
Entity(const CreationParams &cp);
virtual ~Entity();
/**
* Entity (instance) identifier.
* @note IDs are stable and may be used as permanent access keys, but consider using @ref getName
* when not referring to a particular unique instance but rather any entity that has.
*/
EntityId id;
inline bool operator==(const Entity &o) const {
return id == o.id;
}
inline bool operator!=(const Entity &o) const {
return id != o.id;
}
inline void privSetPosition(const Vector3f &v) {
position = v;
}
inline void privSetScale(const Vector3f &v) {
scale = v;
}
inline void privSetOrientation(const Quaternion &v) {
orientation = v;
}
inline const Vector3f& getPosition() const {
return position;
}
virtual void setPosition(const Vector3f&);
inline const Vector3f& getScale() const {
return scale;
}
virtual void setScale(const Vector3f&);
inline const Quaternion& getOrientation() const {
return orientation;
}
virtual void setOrientation(const Quaternion&);
using Transform::getModelMtx;
using Transform::applyModelMtx;
using Transform::operator btTransform;
inline const Transform& transform() const {
return *static_cast<const Transform*>(this);
}
std::string name() const {
return m_name;
}
void setName(const std::string&);
virtual void onNameChange(const std::string &newName) {}
void remove();
virtual void onRemove() {}
virtual std::string fullClassName() const = 0;
virtual std::string className() const = 0;
virtual void tick(TDelta) {}
};
} /* namespace radix */
#endif /* RADIX_ENTITY_HPP */
| 22.013423
| 99
| 0.685671
|
atkurtul
|
002f7ba7fa2063fecad5d66bf479f7fa0c9b35dc
| 3,294
|
hpp
|
C++
|
src/dataStructure/big_set.hpp
|
today2098/algorithm
|
b180355635d3d1ea0a8c3dff40ae1c9bac636f95
|
[
"MIT"
] | null | null | null |
src/dataStructure/big_set.hpp
|
today2098/algorithm
|
b180355635d3d1ea0a8c3dff40ae1c9bac636f95
|
[
"MIT"
] | null | null | null |
src/dataStructure/big_set.hpp
|
today2098/algorithm
|
b180355635d3d1ea0a8c3dff40ae1c9bac636f95
|
[
"MIT"
] | null | null | null |
#ifndef ALGORITHM_BIG_SET_HPP
#define ALGORITHM_BIG_SET_HPP 1
#include <cassert>
#include <iostream>
#include <iterator>
#include <set>
#include <utility>
namespace algorithm {
// 連続した整数列の集合を管理するデータ構造.
template <typename T>
class BigSet {
std::set<std::pair<T, T> > s; // s:=(整数の集合). 連続する整数列[l,r)をpair(l,r)で表現する.
T inf;
public:
// constructor.
explicit BigSet(T inf_ = 1e9) : inf(inf_) {
s.emplace(-inf, -inf + 1); // 番兵.
s.emplace(inf, inf + 1); // 〃
}
T infinity() const { return inf; }
bool insert(T x) { return insert(x, x + 1); } // 整数xを挿入する.
bool insert(T l, T r) { // 整数列[l,r)を挿入する. O(logN).
assert(-inf < l and l < r and r <= inf);
auto itr1 = std::prev(s.lower_bound(std::pair<T, T>(l + 1, l + 2)));
auto [l1, r1] = *itr1;
if(r <= r1) return false; // 集合に完全に含まれている場合.
auto itr3 = s.lower_bound(std::pair<T, T>(r, r + 1));
auto itr2 = std::prev(itr3);
auto [l2, r2] = *itr2;
auto [l3, r3] = *itr3;
if(l <= r1) {
if(l3 <= r) {
s.erase(itr1, ++itr3);
s.emplace(l1, r3);
} else {
s.erase(itr1, itr3);
if(r <= r2)
s.emplace(l1, r2);
else
s.emplace(l1, r);
}
} else {
itr1++;
if(l3 <= r) {
s.erase(itr1, ++itr3);
s.emplace(l, r3);
} else {
s.erase(itr1, itr3);
if(r <= r2)
s.emplace(l, r2);
else
s.emplace(l, r);
}
}
return true;
}
bool erase(T x) { return erase(x, x + 1); } // 整数xを削除する.
bool erase(T l, T r) { // 範囲[l,r)の整数列を削除する. O(logN).
assert(-inf < l and l < r and r <= inf);
auto itr1 = std::prev(s.lower_bound(std::pair<T, T>(l + 1, l + 2)));
auto itr3 = s.lower_bound(std::pair<T, T>(r, r + 1));
auto itr2 = std::prev(itr3);
auto [l1, r1] = *itr1;
auto [l2, r2] = *itr2;
if(r1 <= l and itr1 == itr2) return false; // 集合に全く含まれていない場合.
if(l1 <= l and l < r1) {
s.erase(itr1, itr3);
if(l1 < l) s.emplace(l1, l);
} else {
s.erase(++itr1, itr3);
}
if(r < r2) s.emplace(r, r2);
return true;
}
bool contains(T x) const { return contains(x, x + 1); } // 整数xが集合に含まれるか判定する.
bool contains(T l, T r) const { // 整数列[l,r)が集合に完全に含まれるか判定する. (logN).
assert(-inf < l and l < r and r <= inf);
const auto &[ignore, pr] = *std::prev(s.lower_bound(std::pair<T, T>(l + 1, l + 2)));
return r <= pr;
}
T mex(T x) const { // 集合に含まれないx以上の整数の中で最小のもの(MEX:Minimum Excluded Value)を求める. O(logN).
const auto &[ignore, r] = *std::prev(s.lower_bound(std::pair<T, T>(x + 1, x + 2)));
return (x < r ? r : x);
}
friend std::ostream &operator<<(std::ostream &os, const BigSet<T> &ob) {
for(const auto &[l, r] : s) os << "[" << l << ", " << r << ") ";
os << std::endl;
}
};
} // namespace algorithm
#endif // ALGORITHM_BIG_SET_HPP
| 32.94
| 97
| 0.459016
|
today2098
|
00325fc6952883dd7de40dbae4232db7d602f424
| 8,314
|
hpp
|
C++
|
include/VROSC/EffectsPanel.hpp
|
v0idp/virtuoso-codegen
|
6f560f04822c67f092d438a3f484249072c1d21d
|
[
"Unlicense"
] | null | null | null |
include/VROSC/EffectsPanel.hpp
|
v0idp/virtuoso-codegen
|
6f560f04822c67f092d438a3f484249072c1d21d
|
[
"Unlicense"
] | null | null | null |
include/VROSC/EffectsPanel.hpp
|
v0idp/virtuoso-codegen
|
6f560f04822c67f092d438a3f484249072c1d21d
|
[
"Unlicense"
] | 1
|
2022-03-30T21:07:35.000Z
|
2022-03-30T21:07:35.000Z
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: UnityEngine.MonoBehaviour
#include "UnityEngine/MonoBehaviour.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
#include "beatsaber-hook/shared/utils/typedefs-array.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: VROSC
namespace VROSC {
// Forward declaring type: ArpeggiatorWrapper
class ArpeggiatorWrapper;
// Forward declaring type: AnimatedPanel
class AnimatedPanel;
// Forward declaring type: ParameterController
class ParameterController;
// Forward declaring type: ParametricPositionSignalGenerator
class ParametricPositionSignalGenerator;
// Forward declaring type: SynthController
class SynthController;
}
// Completed forward declares
// Type namespace: VROSC
namespace VROSC {
// Forward declaring type: EffectsPanel
class EffectsPanel;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::VROSC::EffectsPanel);
DEFINE_IL2CPP_ARG_TYPE(::VROSC::EffectsPanel*, "VROSC", "EffectsPanel");
// Type namespace: VROSC
namespace VROSC {
// Size: 0x40
#pragma pack(push, 1)
// Autogenerated type: VROSC.EffectsPanel
// [TokenAttribute] Offset: FFFFFFFF
class EffectsPanel : public ::UnityEngine::MonoBehaviour {
public:
public:
// private VROSC.ArpeggiatorWrapper _arpeggiatorWrapper
// Size: 0x8
// Offset: 0x18
::VROSC::ArpeggiatorWrapper* arpeggiatorWrapper;
// Field size check
static_assert(sizeof(::VROSC::ArpeggiatorWrapper*) == 0x8);
// private VROSC.AnimatedPanel _animation
// Size: 0x8
// Offset: 0x20
::VROSC::AnimatedPanel* animation;
// Field size check
static_assert(sizeof(::VROSC::AnimatedPanel*) == 0x8);
// private VROSC.ParameterController[] _parameterControllers
// Size: 0x8
// Offset: 0x28
::ArrayW<::VROSC::ParameterController*> parameterControllers;
// Field size check
static_assert(sizeof(::ArrayW<::VROSC::ParameterController*>) == 0x8);
// private VROSC.ParametricPositionSignalGenerator[] _parametricPositionSignalGenerators
// Size: 0x8
// Offset: 0x30
::ArrayW<::VROSC::ParametricPositionSignalGenerator*> parametricPositionSignalGenerators;
// Field size check
static_assert(sizeof(::ArrayW<::VROSC::ParametricPositionSignalGenerator*>) == 0x8);
// private VROSC.SynthController _instrument
// Size: 0x8
// Offset: 0x38
::VROSC::SynthController* instrument;
// Field size check
static_assert(sizeof(::VROSC::SynthController*) == 0x8);
public:
// Deleting conversion operator: operator ::System::IntPtr
constexpr operator ::System::IntPtr() const noexcept = delete;
// Get instance field reference: private VROSC.ArpeggiatorWrapper _arpeggiatorWrapper
[[deprecated("Use field access instead!")]] ::VROSC::ArpeggiatorWrapper*& dyn__arpeggiatorWrapper();
// Get instance field reference: private VROSC.AnimatedPanel _animation
[[deprecated("Use field access instead!")]] ::VROSC::AnimatedPanel*& dyn__animation();
// Get instance field reference: private VROSC.ParameterController[] _parameterControllers
[[deprecated("Use field access instead!")]] ::ArrayW<::VROSC::ParameterController*>& dyn__parameterControllers();
// Get instance field reference: private VROSC.ParametricPositionSignalGenerator[] _parametricPositionSignalGenerators
[[deprecated("Use field access instead!")]] ::ArrayW<::VROSC::ParametricPositionSignalGenerator*>& dyn__parametricPositionSignalGenerators();
// Get instance field reference: private VROSC.SynthController _instrument
[[deprecated("Use field access instead!")]] ::VROSC::SynthController*& dyn__instrument();
// public System.Void .ctor()
// Offset: 0x8EB2C0
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static EffectsPanel* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::VROSC::EffectsPanel::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<EffectsPanel*, creationType>()));
}
// public System.Void Setup(VROSC.SynthController synthController)
// Offset: 0x8EADA4
void Setup(::VROSC::SynthController* synthController);
// private System.Void ResetPanel()
// Offset: 0x8EB068
void ResetPanel();
// private System.Void SynthesizerChanged(System.Boolean useExternal)
// Offset: 0x8EB0EC
void SynthesizerChanged(bool useExternal);
// public System.Void SetActive(System.Boolean shouldBeOpen, System.Boolean animate)
// Offset: 0x8EB014
void SetActive(bool shouldBeOpen, bool animate);
// protected System.Void OnDestroy()
// Offset: 0x8EB114
void OnDestroy();
}; // VROSC.EffectsPanel
#pragma pack(pop)
static check_size<sizeof(EffectsPanel), 56 + sizeof(::VROSC::SynthController*)> __VROSC_EffectsPanelSizeCheck;
static_assert(sizeof(EffectsPanel) == 0x40);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: VROSC::EffectsPanel::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: VROSC::EffectsPanel::Setup
// Il2CppName: Setup
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::EffectsPanel::*)(::VROSC::SynthController*)>(&VROSC::EffectsPanel::Setup)> {
static const MethodInfo* get() {
static auto* synthController = &::il2cpp_utils::GetClassFromName("VROSC", "SynthController")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(VROSC::EffectsPanel*), "Setup", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{synthController});
}
};
// Writing MetadataGetter for method: VROSC::EffectsPanel::ResetPanel
// Il2CppName: ResetPanel
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::EffectsPanel::*)()>(&VROSC::EffectsPanel::ResetPanel)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(VROSC::EffectsPanel*), "ResetPanel", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: VROSC::EffectsPanel::SynthesizerChanged
// Il2CppName: SynthesizerChanged
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::EffectsPanel::*)(bool)>(&VROSC::EffectsPanel::SynthesizerChanged)> {
static const MethodInfo* get() {
static auto* useExternal = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(VROSC::EffectsPanel*), "SynthesizerChanged", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{useExternal});
}
};
// Writing MetadataGetter for method: VROSC::EffectsPanel::SetActive
// Il2CppName: SetActive
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::EffectsPanel::*)(bool, bool)>(&VROSC::EffectsPanel::SetActive)> {
static const MethodInfo* get() {
static auto* shouldBeOpen = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* animate = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(VROSC::EffectsPanel*), "SetActive", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{shouldBeOpen, animate});
}
};
// Writing MetadataGetter for method: VROSC::EffectsPanel::OnDestroy
// Il2CppName: OnDestroy
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::EffectsPanel::*)()>(&VROSC::EffectsPanel::OnDestroy)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(VROSC::EffectsPanel*), "OnDestroy", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
| 49.784431
| 168
| 0.73719
|
v0idp
|
00380314333c94863d928f3086bfdcd7c7aecd91
| 154
|
hh
|
C++
|
src/elle/reactor/http/fwd.hh
|
infinitio/elle
|
d9bec976a1217137436db53db39cda99e7024ce4
|
[
"Apache-2.0"
] | 521
|
2016-02-14T00:39:01.000Z
|
2022-03-01T22:39:25.000Z
|
src/elle/reactor/http/fwd.hh
|
infinitio/elle
|
d9bec976a1217137436db53db39cda99e7024ce4
|
[
"Apache-2.0"
] | 8
|
2017-02-21T11:47:33.000Z
|
2018-11-01T09:37:14.000Z
|
src/elle/reactor/http/fwd.hh
|
infinitio/elle
|
d9bec976a1217137436db53db39cda99e7024ce4
|
[
"Apache-2.0"
] | 48
|
2017-02-21T10:18:13.000Z
|
2022-03-25T02:35:20.000Z
|
#pragma once
namespace elle
{
namespace reactor
{
namespace http
{
class Client;
class Request;
class Service;
}
}
}
| 10.266667
| 20
| 0.564935
|
infinitio
|
003bf79c856e9edef356039aa65ac45b45adafa1
| 7,568
|
cc
|
C++
|
xic/src/gtkxic/gtkasmprog.cc
|
bernardventer/xictools
|
4ea72c118679caed700dab3d49a8d36445acaec3
|
[
"Apache-2.0"
] | 3
|
2020-01-26T14:18:52.000Z
|
2020-12-09T20:07:22.000Z
|
xic/src/gtkxic/gtkasmprog.cc
|
chris-ayala/xictools
|
4ea72c118679caed700dab3d49a8d36445acaec3
|
[
"Apache-2.0"
] | null | null | null |
xic/src/gtkxic/gtkasmprog.cc
|
chris-ayala/xictools
|
4ea72c118679caed700dab3d49a8d36445acaec3
|
[
"Apache-2.0"
] | 2
|
2020-01-26T14:19:02.000Z
|
2021-08-14T16:33:28.000Z
|
/*========================================================================*
* *
* Distributed by Whiteley Research Inc., Sunnyvale, California, USA *
* http://wrcad.com *
* Copyright (C) 2017 Whiteley Research Inc., all rights reserved. *
* Author: Stephen R. Whiteley, except as indicated. *
* *
* As fully as possible recognizing licensing terms and conditions *
* imposed by earlier work from which this work was derived, if any, *
* this work is released under the Apache License, Version 2.0 (the *
* "License"). You may not use this file except in compliance with *
* the License, and compliance with inherited licenses which are *
* specified in a sub-header below this one if applicable. A copy *
* of the License is provided with this distribution, or you may *
* obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* See the License for the specific language governing permissions *
* and limitations under the License. *
* *
* 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 NON- *
* INFRINGEMENT. IN NO EVENT SHALL WHITELEY RESEARCH INCORPORATED *
* OR STEPHEN R. WHITELEY 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. *
* *
*========================================================================*
* XicTools Integrated Circuit Design System *
* *
* Xic Integrated Circuit Layout and Schematic Editor *
* *
*========================================================================*
$Id:$
*========================================================================*/
#include "main.h"
#include "cvrt.h"
#include "fio.h"
#include "gtkmain.h"
#include "gtkasm.h"
//-----------------------------------------------------------------------------
// Progress Monitor Pop-Up
sAsmPrg::sAsmPrg()
{
prg_refptr = 0;
prg_shell = gtk_NewPopup(0, "Progress", prg_cancel_proc, this);
GtkWidget *form = gtk_table_new(1, 1, false);
gtk_widget_show(form);
gtk_container_add(GTK_CONTAINER(prg_shell), form);
GtkWidget *frame = gtk_frame_new("Input");
gtk_widget_show(frame);
prg_inp_label = gtk_label_new("");
gtk_widget_show(prg_inp_label);
gtk_container_add(GTK_CONTAINER(frame), prg_inp_label);
gtk_widget_set_usize(prg_inp_label, 240, 20);
int row = 0;
gtk_table_attach(GTK_TABLE(form), frame, 0, 1, row, row + 1,
(GtkAttachOptions)(GTK_EXPAND | GTK_FILL | GTK_SHRINK),
(GtkAttachOptions)0, 2, 2);
frame = gtk_frame_new("Output");
gtk_widget_show(frame);
prg_out_label = gtk_label_new("");
gtk_widget_show(prg_out_label);
gtk_container_add(GTK_CONTAINER(frame), prg_out_label);
gtk_widget_set_usize(prg_out_label, 240, 20);
gtk_table_attach(GTK_TABLE(form), frame, 1, 2, row, row + 1,
(GtkAttachOptions)(GTK_EXPAND | GTK_FILL | GTK_SHRINK),
(GtkAttachOptions)0, 2, 2);
row++;
frame = gtk_frame_new("Info");
gtk_widget_show(frame);
prg_info_label = gtk_label_new("");
gtk_widget_show(prg_info_label);
gtk_container_add(GTK_CONTAINER(frame), prg_info_label);
gtk_widget_set_usize(prg_info_label, -1, 40);
gtk_table_attach(GTK_TABLE(form), frame, 0, 2, row, row + 1,
(GtkAttachOptions)(GTK_EXPAND | GTK_FILL | GTK_SHRINK),
(GtkAttachOptions)(GTK_EXPAND | GTK_FILL), 2, 2);
row++;
frame = gtk_frame_new(0);
gtk_widget_show(frame);
prg_cname_label = gtk_label_new("");
gtk_widget_show(prg_cname_label);
gtk_container_add(GTK_CONTAINER(frame), prg_cname_label);
gtk_widget_set_usize(prg_cname_label, -1, 40);
gtk_table_attach(GTK_TABLE(form), frame, 0, 2, row, row + 1,
(GtkAttachOptions)(GTK_EXPAND | GTK_FILL | GTK_SHRINK),
(GtkAttachOptions)(GTK_EXPAND | GTK_FILL), 2, 2);
row++;
GtkWidget *hbox = gtk_hbox_new(false, 2);
gtk_widget_show(hbox);
GtkWidget *button = gtk_button_new_with_label("Abort");
gtk_widget_show(button);
gtk_signal_connect(GTK_OBJECT(button), "clicked",
GTK_SIGNAL_FUNC(prg_abort_proc), this);
gtk_box_pack_start(GTK_BOX(hbox), button, true, true, 0);
button = gtk_button_new_with_label("Dismiss");
gtk_widget_show(button);
gtk_signal_connect(GTK_OBJECT(button), "clicked",
GTK_SIGNAL_FUNC(prg_cancel_proc), this);
gtk_box_pack_start(GTK_BOX(hbox), button, true, true, 0);
gtk_table_attach(GTK_TABLE(form), hbox, 0, 1, row, row + 1,
(GtkAttachOptions)(GTK_EXPAND | GTK_FILL | GTK_SHRINK),
(GtkAttachOptions)0, 2, 2);
GtkAdjustment *adj =
(GtkAdjustment*)gtk_adjustment_new(0, 1, 100, 0, 0, 0);
prg_pbar = gtk_progress_bar_new_with_adjustment(adj);
gtk_widget_show(prg_pbar);
gtk_progress_bar_set_bar_style(GTK_PROGRESS_BAR(prg_pbar),
GTK_PROGRESS_CONTINUOUS);
gtk_progress_set_activity_mode(GTK_PROGRESS(prg_pbar), true);
gtk_table_attach(GTK_TABLE(form), prg_pbar, 1, 2, row, row + 1,
(GtkAttachOptions)(GTK_EXPAND | GTK_FILL | GTK_SHRINK),
(GtkAttachOptions)0, 2, 2);
row++;
gtk_widget_set_usize(prg_shell, 500, -1);
}
sAsmPrg::~sAsmPrg()
{
if (prg_refptr)
*prg_refptr = 0;
gtk_signal_disconnect_by_func(GTK_OBJECT(prg_shell),
GTK_SIGNAL_FUNC(prg_cancel_proc), this);
gtk_widget_destroy(prg_shell);
}
void
sAsmPrg::update(const char *msg, ASMcode code)
{
double new_val =
gtk_progress_get_value(GTK_PROGRESS(prg_pbar)) + 2;
gtk_progress_set_value(GTK_PROGRESS(prg_pbar), new_val);
char *str = lstring::copy(msg);
char *s = str + strlen(str) - 1;
while (s >= str && isspace(*s))
*s-- = 0;
if (code == ASM_INFO)
gtk_label_set_text(GTK_LABEL(prg_info_label), str);
else if (code == ASM_READ)
gtk_label_set_text(GTK_LABEL(prg_inp_label), str);
else if (code == ASM_WRITE)
gtk_label_set_text(GTK_LABEL(prg_out_label), str);
else if (code == ASM_CNAME)
gtk_label_set_text(GTK_LABEL(prg_cname_label), str);
delete [] str;
}
// Static function.
void
sAsmPrg::prg_cancel_proc(GtkWidget*, void *arg)
{
sAsmPrg *ptr = static_cast<sAsmPrg*>(arg);
delete ptr;
}
// Static function.
void
sAsmPrg::prg_abort_proc(GtkWidget*, void *arg)
{
sAsmPrg *ptr = static_cast<sAsmPrg*>(arg);
ptr->prg_abort = true;
}
| 38.416244
| 79
| 0.570825
|
bernardventer
|
003d0d2f7df3a720b416c60edb66deac7c713153
| 16,883
|
cpp
|
C++
|
P1/cwcreator.cpp
|
Revuj/CrossWord-Puzzle
|
16348b76ffa9a7ecf1b5a159264fbfd284f5e8d4
|
[
"MIT"
] | null | null | null |
P1/cwcreator.cpp
|
Revuj/CrossWord-Puzzle
|
16348b76ffa9a7ecf1b5a159264fbfd284f5e8d4
|
[
"MIT"
] | null | null | null |
P1/cwcreator.cpp
|
Revuj/CrossWord-Puzzle
|
16348b76ffa9a7ecf1b5a159264fbfd284f5e8d4
|
[
"MIT"
] | null | null | null |
#include <sstream>
#include <string>
#include <map>
#include <algorithm>
#include <iomanip>
#include "Board.h"
#include "Dictionary.h"
using namespace std;
void option();
//==============================================================================================//
//==============================================================================================//
/*
Sends the board to be saved on a file
@param board - board, to be saved, to be resumed later
@param dic_name - name of the dictionary associated to the board
@param moves - map with the positions and the respective words of the board
*/
void saveToResume(const Board& board, const string& dic_name, map<string, string> &moves, int &num_board)
{
ostringstream ss;
ss << setw(3) << setfill('0') << num_board;
string outfile_name(ss.str());
outfile_name = "b" + outfile_name + ".txt";
ifstream infile;
infile.open(outfile_name);
string name = outfile_name;
while (!infile.fail()) //if the file already exists, increase the number of the board
{
infile.close();
num_board++;
ostringstream nameoss;
nameoss << setw(3) << setfill('0') << num_board;
name = nameoss.str();
name = "b" + name + ".txt";
infile.open(name);
}
infile.close();
ofstream outfile;
outfile.open(name);
outfile << dic_name << endl;
board.sendtofile(outfile, moves);
outfile << endl;
outfile.close();
cout << "Crossword puzzle saved in " << name << " ...\n";
cout << endl;
option();
}
//==============================================================================================//
//==============================================================================================//
/*
Ensures that the board is completly valid before being saved
@param board - board that the user wants to save
@param dic - dictionary associated to the board
@param lines - number of lines of the board
@param columns - number of colums of the board
@function return valid - true if the board is ready to be saved
*/
bool valid_board(const Board &board, const Dictionary& dic, size_t lines, size_t columns)
{
for (size_t i = 0; i < lines; i++) //loop that reads all the words in a line and checks if they are valid;
{
string s = board.get_line((char)(65 + i));
string::iterator begin = s.begin();
for (string::iterator it = begin; it != s.end(); ++it)
{
if ((it == begin && *it != '.' && *it != '#') || (*it != '.' && *it != '#' && (*(it - 1) == '.' || *(it - 1) == '#')))
begin = it;
if ((it == (s.end() - 1) && *it != '.' && *it != '#') || (*it != '.' && *it != '#' && (*(it + 1) == '.' || *(it + 1) == '#')))
{
string word(begin, it + 1);
if (!word.empty())
{
if (word.length() != 1 && !dic.valid_word(word))
{
int index = static_cast<int>(i);
cout << "Invalid word at " << char(index + 65) << char(distance(s.begin(), begin) + 97) << "H" << endl;
return false;
}
}
}
}
}
cout << endl;
for (size_t i = 0; i < columns; i++) // loop that checks all the words in a column and checks if they are valid
{
string s = board.get_column((char)(97 + i));
string::iterator begin = s.begin();
for (string::iterator it = begin; it != s.end(); ++it)
{
if ((it == begin && *it != '.' && *it != '#') || (*it != '.' && *it != '#' && (*(it - 1) == '.' || *(it - 1) == '#')))
begin = it;
if ((it == (s.end() - 1) && *it != '.' && *it != '#') || (*it != '.' && *it != '#' && (*(it + 1) == '.' || *(it + 1) == '#')))
{
string word(begin, it + 1);
if (!word.empty())
{
if (word.length() != 1 && !dic.valid_word(word)) //we do not consider a word with only one letter invalid
{
int index = static_cast<int>(i);
cout << "Invalid word at " << char(distance(s.begin(), begin) + 65) << char(index + 97) << "V" << endl;
return false;
}
}
}
}
}
return true;
}
//==============================================================================================//
//==============================================================================================//
/*
Sends the board to be saved on a file
@param board - finished board, to be saved
@param dic_name - name of the dictionary associated to the board
@param moves - map with the positions and the respective words of the board
@param dic - dic associated to the board
@param num_board - number of the board to be saved
*/
void saveFinished(const Board& board, const string& dic_name, map<string, string> &moves, Dictionary &dic, int &num_board)
{
size_t lines = board.get_line('A').length();
size_t columns = board.get_column('a').length();
if (!valid_board(board, dic, lines, columns))
{
cout << "You need to change some things..." << endl;
board.showBoard();
}
else
{
ostringstream ss;
ss << setw(3) << setfill('0') << num_board;
string outfile_name(ss.str());
outfile_name = "b" + outfile_name + ".txt";
ifstream infile;
infile.open(outfile_name);
string name = outfile_name;
while (!infile.fail()) //if the file already exists, increase the number of the board
{
infile.close();
num_board++;
ostringstream nameoss;
nameoss << setw(3) << setfill('0') << num_board;
name = nameoss.str();
name = "b" + name + ".txt";
infile.open(name);
}
infile.close();
ofstream outfile;
outfile.open(name);
outfile << dic_name << endl;
board.sendtofile_finished(outfile, moves);
outfile << endl;
outfile.close();
cout << "Crossword puzzle saved in " << name << " ...\n";
cout << endl;
option();
}
}
//==============================================================================================//
//==============================================================================================//
/*
Displays a menu where the user can chose how he wants to save the board
@param board - board to be saved
@param dic_name - name of the dictionary associated to the board
@param moves - map with the positions and the respective words of the board
@param dic - dic associated to the board
@param num_board - number of the board to be saved
*/
void saveMenu(Board &board, string &dic_name, Dictionary &dic, map<string, string> &moves, int &num_board)
{
cin.clear();
char s;
while (cout << "Do you want to save the board and resume later ( S ) or to finish ( F ) ? " && !(cin >> s))
{
cin.clear();
cin.ignore(100000, '\n');
cout << "Invalid input, please re-enter\n";
}
toupper(s);
if (s == 'S')
saveToResume(board, dic_name, moves, num_board);
else if (s == 'F')
saveFinished(board, dic_name, moves, dic, num_board);
}
//==============================================================================================//
//==============================================================================================//
/*
Helps the user by displaying the words that can be placed in a specified position
@param board - board where the word is to be placed
@param dic - dictionary associated to the board
@param line - line where the user wants to place a word
@param column - column where the user wants to place a word
@param direction - direction of the word to be placed
*/
void userNeedsHelp(Board &board, Dictionary &dic, char line, char column, char direction)
{
vector<string> possible_words;
if (direction == 'H')
{
string token = board.get_line(line);
token.erase(0, column - 97);
dic.help(possible_words, token, token.size());
}
if (direction == 'V')
{
string token = board.get_column(column);
token.erase(0, line - 65);
dic.help(possible_words, token, token.size());
}
if (possible_words.size() != 0)
{
for (size_t m = 0; m < possible_words.size(); m++)
{
if (board.can_be_placed(line, column, direction, possible_words[m]) == 4)
cout << possible_words[m] << endl;
}
}
else cout << "None of the dictionary words can be placed\n";
board.showBoard();
}
//==============================================================================================//
//==============================================================================================//
/*
itsAWord is called if the input was not "-" , "+", or "?" and calls the function that checks if the word can be placed, displaying a message depending of the situation
@param board - board where the word is to be placed
@param dic - dictionary associated to the board
@param line_column_direction - string that contains the position of the word to be placed
@param word - word to be placed
*/
void itsAWord(Board &board, Dictionary &dic, map<string, string> &moves, string &line_column_direction, string &word)
{
char line, column, direction;
istringstream iss(line_column_direction);
iss >> line >> column >> direction;
transform(word.begin(), word.end(), word.begin(), toupper);
if (dic.valid_word(word) && board.can_be_placed(line, column, direction, word) == 4)
{
board.insertword(line, column, direction, word);
moves.insert(pair<string, string>(line_column_direction, word));
}
else if (board.can_be_placed(line, column, direction, word) == 5)
cout << "Word already introduced\n";
else if (board.can_be_placed(line, column, direction, word) == 1)
cout << "This word doesn't fit on the board\n";
else if (board.can_be_placed(line, column, direction, word) == 2)
cout << "Invalid interseption of words\n";
else if (!dic.valid_word(word))
cout << "Invalid word\n";
board.showBoard();
}
//==============================================================================================//
//==============================================================================================//
/*
Depending of the user input, edit_board calls the respective functions that are needed to edit the bord
@param board - board where the word is to be placed
@param dic - dictionary associated to the board
@param moves - map with the positions and the respective words of the board
@param word - input word that can be "+", "-", "?" or a word to be placed on the board
@param line_column_direction - string that contains the position of the word to be placed
*/
void edit_board(Board &board, Dictionary &dic, map<string, string> &moves, string &word, string &line_column_direction)
{
char line, column, direction;
istringstream iss(line_column_direction);
iss >> line >> column >> direction;
if (word == "+")
{
string s = board.get_word(line, column, direction);
if (!dic.valid_word(s))
cout << "The word is invalid." << endl;
else
cout << "The word is valid!" << endl;
}
else if (word == "-")
{
board.removeword(line, column, direction);
map<string, string>::iterator it = moves.find(line_column_direction);
if (it != moves.end())
moves.erase(line_column_direction);
board.showBoard();
}
else if (word == "?")
userNeedsHelp(board, dic, line, column, direction);
else
itsAWord(board, dic, moves, line_column_direction, word);
}
//==============================================================================================//
//==============================================================================================//
/*
Allows the user to input
@param board - board where the word is to be placed
@param dic - dictionary associated to the board
@param moves - map with the positions and the respective words of the board
@param dictionary_name - name of the dictionary associated with the board
@param num_board - number of the board
*/
void userInputs(Board &board, Dictionary &dic, map<string, string> &moves, string &dictionary_name, int& num_board)
{
string line_column_direction;
while (cout << "\nPosition ( LCD / CTRL-Z = stop ) ? " && !(cin >> line_column_direction) && !cin.eof())
{
cin.clear();
cin.ignore(100000, '\n');
cout << "Invalid input, please re-enter\n";
}
if (cin.eof())
{
saveMenu(board, dictionary_name, dic, moves, num_board);
return;
}
char line, column, direction;
istringstream iss(line_column_direction);
iss >> line >> column >> direction;
while (line_column_direction.length() != 3 || (direction != 'H' && direction != 'V') || islower(line) || isupper(column))
{
cout << "LCD ( L-uppercase , C-lowercase , D-H or V ) ? ";
cin >> line_column_direction;
istringstream iss(line_column_direction);
iss >> line >> column >> direction;
}
string word;
while (cout << "Word ( - = remove / + = check if word is valid / ? = help ) ? " && !(cin >> word))
{
cin.clear();
cin.ignore(100000, '\n');
cout << "Invalid input, please re-enter\n";
}
edit_board(board, dic, moves, word, line_column_direction);
}
//==============================================================================================//
//==============================================================================================//
/*
Displays a menu that allows the user to creat a Puzzle
*/
void createPuzzle()
{
string dictionary_name;
cout << "----------------------------------------\n";
cout << "CREATE PUZZLE\n";
cout << "----------------------------------------\n";
cout << "Dictionary file name ? ";
cin >> dictionary_name;
ifstream dictionaryFile;
dictionaryFile.open(dictionary_name);
while (dictionaryFile.fail())
{
cout << "Dictionary not found!\n";
cout << endl << "Dictionary file name ? ";
cin >> dictionary_name;
dictionaryFile.open(dictionary_name);
}
cout << "Loading Dictionary..." << endl;
Dictionary dic(dictionary_name);
int lines, columns;
while (cout << "Board size (lines columns) ? " && !(cin >> lines >> columns))
{
cin.clear();
cin.ignore(100000, '\n');
cout << "Invalid input, please re-enter\n";
}
Board board(lines, columns);
int num_board = 1;
cout << endl;
board.showBoard();
string line_column_direction;
map<string, string> moves;
while (!board.finished())
userInputs(board, dic, moves, dictionary_name, num_board);
ostringstream ss;
ss << setw(3) << setfill('0') << num_board;
string outfile_name(ss.str());
outfile_name = "b" + outfile_name + ".txt";
ofstream outfile;
outfile.open(outfile_name);
outfile << dictionary_name << endl;
board.sendtofile_finished(outfile, moves);
outfile << endl;
outfile.close();
cout << "Crossword puzzle saved in " << outfile_name << " ...\n";
cout << endl;
option();
}
//==============================================================================================//
//==============================================================================================//
/*
Allows the user to write the name of the board that he wants to resume
*/
void resumePuzzle()
{
cout << "----------------------------------------\n";
cout << "RESUME PUZZLE\n";
cout << "----------------------------------------\n";
string board_name;
int num_board = 1;
cout << "Board file name ? ";
cin >> board_name;
ifstream boardFile;
boardFile.open(board_name);
if (boardFile.fail())
{
cerr << "Board not found!\n";
exit(1);
}
string dictionary_name;
getline(boardFile, dictionary_name);
cout << "Loading dictionary..." << endl;
Dictionary dic(dictionary_name);
map<string, string> moves;
Board board(boardFile, moves);
board.showBoard();
string line_column_direction;
while (!board.finished())
userInputs(board, dic, moves, dictionary_name, num_board);
ostringstream ss;
ss << setw(3) << setfill('0') << num_board;
string outfile_name(ss.str());
outfile_name = "b" + outfile_name + ".txt";
ofstream outfile;
outfile.open(outfile_name);
outfile << dictionary_name << endl;
board.sendtofile_finished(outfile, moves);
outfile << endl;
outfile.close();
cout << "Crossword puzzle saved in " << outfile_name << " ...\n";
cout << endl;
option();
}
//==============================================================================================//
//==============================================================================================//
/*
Allows the user to chose between create,resume a puzzle or to exit
*/
void option()
{
cin.clear();
int option;
cout << "----------------------------------------\n";
cout << "Options:\n";
cout << "1 - Create puzzle\n";
cout << "2 - Resume puzzle\n";
cout << "0 - Exit\n";
cout << "----------------------------------------\n";
while (cout << "Option ? " && (!(cin >> option) || option < 0 || option > 2))
{
cin.clear();
cin.ignore(100000, '\n');
cout << "Invalid input, please re-enter\n";
}
switch (option)
{
case 0:
cout << "Bye!!\n";
exit(0);
break;
case 1:
createPuzzle();
break;
case 2:
resumePuzzle();
break;
}
}
//==============================================================================================//
//==============================================================================================//
int main()
{
cout << "CROSSWORDS PUZZLE CREATOR\n";
cout << "========================================\n";
cout << "\n" << "INSTRUCTIONS:\n";
cout << "Position ( LCD / CTRL-Z = stop to save)\n";
cout << "LCD ( L - uppercase , C - lowercase , D- H or V )\n\n";
option();
return 0;
}
| 31.794727
| 167
| 0.54623
|
Revuj
|
004295d992bccea82c5e73d964e055ba7c050d3a
| 234
|
cpp
|
C++
|
03Section6/coding_ex4/main.cpp
|
barisCanCoskun/Cpp-Programming
|
640a87db75dd9d31bb2dccf248b403e8b6713e1f
|
[
"MIT"
] | null | null | null |
03Section6/coding_ex4/main.cpp
|
barisCanCoskun/Cpp-Programming
|
640a87db75dd9d31bb2dccf248b403e8b6713e1f
|
[
"MIT"
] | null | null | null |
03Section6/coding_ex4/main.cpp
|
barisCanCoskun/Cpp-Programming
|
640a87db75dd9d31bb2dccf248b403e8b6713e1f
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include<string.h>
using namespace std;
int main ()
{
double hourly_wage{23.50};
int age;
string name;
cin >> name >> age ;
cout << name << " " << age << " " << hourly_wage << endl;
}
| 16.714286
| 61
| 0.538462
|
barisCanCoskun
|
0046668f0ece068fa7b05468aa046c5ae8726b38
| 4,915
|
cpp
|
C++
|
s32v234_sdk/kernels/apu/sample_feature_detection_kernels/src/harris_apu.cpp
|
intesight/Panorama4AIWAYS
|
46e1988e54a5155be3b3b47c486b3f722be00b5c
|
[
"WTFPL"
] | null | null | null |
s32v234_sdk/kernels/apu/sample_feature_detection_kernels/src/harris_apu.cpp
|
intesight/Panorama4AIWAYS
|
46e1988e54a5155be3b3b47c486b3f722be00b5c
|
[
"WTFPL"
] | null | null | null |
s32v234_sdk/kernels/apu/sample_feature_detection_kernels/src/harris_apu.cpp
|
intesight/Panorama4AIWAYS
|
46e1988e54a5155be3b3b47c486b3f722be00b5c
|
[
"WTFPL"
] | 2
|
2021-01-21T02:06:16.000Z
|
2021-01-28T10:47:37.000Z
|
/*****************************************************************************
*
* Freescale Confidential Proprietary
*
* Copyright (c) 2013 Freescale Semiconductor;
* Copyright (c) 2017 NXP
* All Rights Reserved
*
*****************************************************************************
*
* THIS SOFTWARE IS PROVIDED BY FREESCALE "AS IS" AND ANY EXPRESSED 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 FREESCALE OR ITS 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 harris_apu.cpp
* \brief harris corner detector implementation for APEX
* \author Igor Aleksandrowicz
* \version
* \date
****************************************************************************/
#ifdef ACF_KERNEL_IMPLEMENTATION
#include "harris_apu.h"
/*****************************************************************************
* functions
*****************************************************************************/
static int computeLog2(int aNr)
{
int lLog2 = 0;
while ((aNr >>= 1) > 0) {
lLog2++;
}
return lLog2;
}
void apuHarrisResponse(vec16u* apResponse,
vec16s* apGradX, vec16s* apGradY, vec16s* apGradXSqrTmp, vec16s* apGradYSqrTmp, vec16s* apGradXYTmp,
int aBlockWidth, int aBlockHeight, int aStride, int k, int responseBitShift, int aWindowSize, int thresh, bool isFirstSlice)
{
int startRow = isFirstSlice ? -aWindowSize : aWindowSize;
// this is the divisor after forming the sum. It is the log2(area of the summing window)
static int lLog2Wnd = 1;
// from [-wnd, wnd]
if (isFirstSlice)
{
lLog2Wnd = (1 + computeLog2(aWindowSize)) << 1;// because we have (2*aWindowSize)^2 elements to sum up.
}
//from [wnd, h-wnd]
vec16s *gradX = apGradX + -aWindowSize* aStride
, *gradY = apGradY + -aWindowSize* aStride;
vec16s* gradX2 = apGradXSqrTmp + aWindowSize;
vec16s* gradY2 = apGradYSqrTmp + aWindowSize;
vec16s* gradXY = apGradXYTmp + aWindowSize;
// compute square directly on inputs
for (int y = -aWindowSize; y < aBlockHeight + aWindowSize ; ++y)
{
for (int x = -aWindowSize; x < aBlockWidth + aWindowSize; ++x)
{
vec16s gx = gradX[x] >> 1; // take half, to avoid overflow
vec16s gy = gradY[x] >> 1;
gradXY[x] = gx*gy;
gradX2[x] = gx*gx;
gradY2[x] = gy*gy;
}
gradX2 += aStride;
gradY2 += aStride;
gradXY += aStride;
gradX += aStride;
gradY += aStride;
}
//rewind
gradX2 = apGradXSqrTmp + aWindowSize + aWindowSize* aStride;
gradY2 = apGradYSqrTmp + aWindowSize + aWindowSize* aStride;
gradXY = apGradXYTmp + aWindowSize + aWindowSize* aStride;
vec32s vthresh = thresh;
vec16u *out = apResponse;
for (int y = 0; y < aBlockHeight; ++y)
{
for (int x = 0; x < aBlockWidth; ++x)
{
vec32u sumGx2 = 0;
vec32u sumGy2 = 0;
vec32s sumGxy = 0;
int index = (y - aWindowSize) * aStride + x;
vec16s* crtGX2 = gradX2 + index ;
vec16s* crtGY2 = gradY2 + index ;
vec16s* crtGXY = gradXY + index ;
// sum over the window
for (int wy = -aWindowSize; wy < aWindowSize; ++wy)
{
for (int wx = -aWindowSize; wx < aWindowSize; ++wx)
{
vec32u tx = (vec32u)((vec16u)crtGX2[wx]);
vec32u ty = (vec32u)((vec16u)crtGY2[wx]);
sumGx2 += tx;
sumGy2 += ty;
sumGxy += (vec32s)crtGXY[wx];
}
crtGX2 += aStride;
crtGY2 += aStride;
crtGXY += aStride;
}
sumGxy >>= lLog2Wnd;
sumGx2 >>= lLog2Wnd;
sumGy2 >>= lLog2Wnd;
vec32u trace = (sumGx2 + sumGy2) >> 1; //Trace is T/2, trace^2 will be /256
vec32s det = (vec32s)(sumGx2 * sumGy2 ) - (vec32s)(sumGxy * sumGxy);
vec32s response = det - (vec32s)((k * trace * trace) >> 6 ); // shifted to the right, in order to have integer k=[10,42]
response >>= responseBitShift;
const vec32s upperBnd = 65535;
const vec32s zeros = 0;
response = vselect((vec32s)response, zeros, response > zeros);
response = vselect((vec32s)response, zeros, response > vthresh);
response = vselect((vec32s)response, upperBnd, response < upperBnd);
out[x] = (vec16u)response;
}
out += aBlockWidth;
}
}
#endif //#ifdef ACF_KERNEL_IMPLEMENTATION
| 31.50641
| 127
| 0.58352
|
intesight
|
00488a8503ab9dbb45110a432a2e92a420aeb0fd
| 55
|
cpp
|
C++
|
lib/libB/src/LibB.cpp
|
arnesor/gtest-template
|
a95911b34a04545a902db209197b23a6a2f00174
|
[
"MIT"
] | null | null | null |
lib/libB/src/LibB.cpp
|
arnesor/gtest-template
|
a95911b34a04545a902db209197b23a6a2f00174
|
[
"MIT"
] | null | null | null |
lib/libB/src/LibB.cpp
|
arnesor/gtest-template
|
a95911b34a04545a902db209197b23a6a2f00174
|
[
"MIT"
] | null | null | null |
#include "LibB.h"
LibB::LibB()
{
}
LibB::~LibB()
{
}
| 5.5
| 17
| 0.509091
|
arnesor
|
004b2c0b81968c7ae99f6f55391561b5d752696a
| 4,357
|
cpp
|
C++
|
src/Orientations.cpp
|
kberryUSGS/SpiceRefactor
|
1875bf6c873f084296004397ecf8f90ee5df7cef
|
[
"Unlicense"
] | null | null | null |
src/Orientations.cpp
|
kberryUSGS/SpiceRefactor
|
1875bf6c873f084296004397ecf8f90ee5df7cef
|
[
"Unlicense"
] | null | null | null |
src/Orientations.cpp
|
kberryUSGS/SpiceRefactor
|
1875bf6c873f084296004397ecf8f90ee5df7cef
|
[
"Unlicense"
] | null | null | null |
#include "ale/Orientations.h"
#include "ale/InterpUtils.h"
namespace ale {
Orientations::Orientations(
const std::vector<Rotation> &rotations,
const std::vector<double> ×,
const std::vector<Vec3d> &avs,
const Rotation &const_rot,
const std::vector<int> const_frames,
const std::vector<int> time_dependent_frames
) :
m_rotations(rotations), m_avs(avs), m_times(times), m_timeDepFrames(time_dependent_frames), m_constFrames(const_frames), m_constRotation(const_rot) {
if (m_rotations.size() < 2 || m_times.size() < 2) {
throw std::invalid_argument("There must be at least two rotations and times.");
}
if (m_rotations.size() != m_times.size()) {
throw std::invalid_argument("The number of rotations and times must be the same.");
}
if ( !m_avs.empty() && (m_avs.size() != m_times.size()) ) {
throw std::invalid_argument("The number of angular velocities and times must be the same.");
}
}
std::vector<Rotation> Orientations::getRotations() const {
return m_rotations;
}
std::vector<Vec3d> Orientations::getAngularVelocities() const {
return m_avs;
}
std::vector<double> Orientations::getTimes() const {
return m_times;
}
std::vector<int> Orientations::getTimeDependentFrames() const {
return m_timeDepFrames;
}
std::vector<int> Orientations::getConstantFrames() const {
return m_constFrames;
}
Rotation Orientations::getConstantRotation() const {
return m_constRotation;
}
Rotation Orientations::interpolate(
double time,
RotationInterpolation interpType
) const {
int interpIndex = interpolationIndex(m_times, time);
double t = (time - m_times[interpIndex]) / (m_times[interpIndex + 1] - m_times[interpIndex]);
return m_constRotation * m_rotations[interpIndex].interpolate(m_rotations[interpIndex + 1], t, interpType);
}
Vec3d Orientations::interpolateAV(double time) const {
int interpIndex = interpolationIndex(m_times, time);
double t = (time - m_times[interpIndex]) / (m_times[interpIndex + 1] - m_times[interpIndex]);
Vec3d interpAv = Vec3d(linearInterpolate(m_avs[interpIndex], m_avs[interpIndex + 1], t));
return interpAv;
}
Vec3d Orientations::rotateVectorAt(
double time,
const Vec3d &vector,
RotationInterpolation interpType,
bool invert
) const {
Rotation interpRot = interpolate(time, interpType);
if (invert) {
interpRot = interpRot.inverse();
}
return interpRot(vector);
}
State Orientations::rotateStateAt(
double time,
const State &state,
RotationInterpolation interpType,
bool invert
) const {
Rotation interpRot = interpolate(time, interpType);
Vec3d av(0.0, 0.0, 0.0);
if (!m_avs.empty()) {
av = interpolateAV(time);
}
if (invert) {
Vec3d negAv = interpRot(av);
av = {-negAv.x, -negAv.y, -negAv.z};
interpRot = interpRot.inverse();
}
return interpRot(state, av);
}
Orientations &Orientations::operator*=(const Orientations &rhs) {
std::vector<double> mergedTimes = orderedVecMerge(m_times, rhs.m_times);
std::vector<Rotation> mergedRotations;
std::vector<Vec3d> mergedAvs;
for (double time: mergedTimes) {
// interpolate includes the constant rotation, so invert it to undo that
Rotation inverseConst = m_constRotation.inverse();
Rotation rhsRot = rhs.interpolate(time);
mergedRotations.push_back(inverseConst*interpolate(time)*rhsRot);
Vec3d combinedAv = rhsRot.inverse()(interpolateAV(time));
Vec3d rhsAv = rhs.interpolateAV(time);
combinedAv.x += rhsAv.x;
combinedAv.y += rhsAv.y;
combinedAv.z += rhsAv.z;
mergedAvs.push_back(combinedAv);
}
m_times = mergedTimes;
m_rotations = mergedRotations;
m_avs = mergedAvs;
return *this;
}
Orientations &Orientations::operator*=(const Rotation &rhs) {
std::vector<Rotation> updatedRotations;
for (size_t i = 0; i < m_rotations.size(); i++) {
updatedRotations.push_back(m_rotations[i]*rhs);
}
Rotation inverseRhs = rhs.inverse();
std::vector<Vec3d> updatedAvs;
for (size_t i = 0; i < m_avs.size(); i++) {
updatedAvs.push_back(inverseRhs(m_avs[i]));
}
m_rotations = updatedRotations;
m_avs = updatedAvs;
return *this;
}
}
| 29.439189
| 153
| 0.676153
|
kberryUSGS
|
004caa9de0b32d3f2e67f03660f47e8c1433b8b7
| 3,506
|
cpp
|
C++
|
util/SingleWriterValueListTest.cpp
|
denistsoi/yoga
|
a2aa1b7fca7e3573fba3d1978b29403fc0820da6
|
[
"MIT"
] | 28
|
2019-08-01T10:47:42.000Z
|
2022-01-05T13:01:15.000Z
|
util/SingleWriterValueListTest.cpp
|
denistsoi/yoga
|
a2aa1b7fca7e3573fba3d1978b29403fc0820da6
|
[
"MIT"
] | 5
|
2021-03-09T15:17:53.000Z
|
2022-02-12T19:15:11.000Z
|
util/SingleWriterValueListTest.cpp
|
denistsoi/yoga
|
a2aa1b7fca7e3573fba3d1978b29403fc0820da6
|
[
"MIT"
] | 7
|
2019-12-31T01:01:52.000Z
|
2021-11-23T17:18:52.000Z
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*/
#include <gtest/gtest.h>
#include <yoga/util/SingleWriterValueList.h>
#include <numeric>
#include <type_traits>
#include <unordered_set>
namespace facebook {
namespace yoga {
static_assert(
!std::is_copy_constructible<SingleWriterValueList<int>>::value,
"SingleWriterValueList must not be copyable");
static_assert(
!std::is_copy_assignable<SingleWriterValueList<int>>::value,
"SingleWriterValueList must not be copyable");
static_assert(
!std::is_copy_constructible<SingleWriterValueList<int>::Borrowed>::value,
"SingleWriterValueList::Borrowed must not be copyable");
static_assert(
!std::is_copy_assignable<SingleWriterValueList<int>::Borrowed>::value,
"SingleWriterValueList::Borrowed must not be copyable");
static_assert(
std::is_move_constructible<SingleWriterValueList<int>::Borrowed>::value,
"SingleWriterValueList::Borrowed must be movable");
static_assert(
std::is_move_assignable<SingleWriterValueList<int>::Borrowed>::value,
"SingleWriterValueList::Borrowed must be movable");
TEST(SingleWriterValueList, borrowsAreExclusive) {
SingleWriterValueList<int> x{};
auto a = x.borrow();
auto b = x.borrow();
ASSERT_NE(&a.get(), &b.get());
}
TEST(SingleWriterValueList, borrowsSupportDereference) {
SingleWriterValueList<int> x{};
auto a = x.borrow();
*a = 123;
ASSERT_EQ(*a, 123);
}
TEST(SingleWriterValueList, borrowsHaveGetMethod) {
SingleWriterValueList<int> x{};
auto a = x.borrow();
a.get() = 123;
ASSERT_EQ(a.get(), 123);
}
TEST(SingleWriterValueList, exposesBorrowsViaIterator) {
SingleWriterValueList<int> x{};
auto a = x.borrow();
auto b = x.borrow();
*a = 12;
*b = 34;
int sum = 0;
for (auto& i : x) {
sum += i;
}
ASSERT_EQ(sum, 12 + 34);
}
TEST(SingleWriterValueList, exposesBorrowsViaConstIterator) {
SingleWriterValueList<int> x{};
auto a = x.borrow();
auto b = x.borrow();
*a = 12;
*b = 34;
ASSERT_EQ(std::accumulate(x.cbegin(), x.cend(), 0), 12 + 34);
}
TEST(SingleWriterValueList, doesNotDeallocateReturnedBorrows) {
SingleWriterValueList<int> x{};
std::unordered_set<const int*> values;
{
auto a = x.borrow();
auto b = x.borrow();
values.insert(&a.get());
values.insert(&b.get());
}
auto it = x.begin();
ASSERT_NE(it, x.end());
ASSERT_NE(values.find(&*it), values.end());
ASSERT_NE(++it, x.end());
ASSERT_NE(values.find(&*it), values.end());
}
TEST(SingleWriterValueList, reusesReturnedBorrows) {
SingleWriterValueList<int> x{};
int* firstBorrow;
{
auto a = x.borrow();
firstBorrow = &a.get();
}
auto b = x.borrow();
ASSERT_EQ(&b.get(), firstBorrow);
}
TEST(SingleWriterValueList, keepsValuesAfterReturning) {
SingleWriterValueList<int> x{};
{
auto a = x.borrow();
*a = 123;
}
ASSERT_EQ(*x.begin(), 123);
}
static void addOne(int& v) {
v += 1;
}
TEST(SingleWriterValueList, allowsCustomReturnPolicy) {
SingleWriterValueList<int, addOne> x{};
{
auto a = x.borrow();
*a = 123;
}
ASSERT_EQ(*x.begin(), 124);
}
TEST(SingleWriterValueList, hasConvenienceResetPolicy) {
SingleWriterValueList<int, SingleWriterValueList<int>::resetPolicy> x{};
{
auto a = x.borrow();
*a = 123;
}
ASSERT_EQ(*x.begin(), 0);
}
} // namespace yoga
} // namespace facebook
| 21.378049
| 77
| 0.680548
|
denistsoi
|
004d47bf2920f6201d6d4e30ddd895c44330c971
| 2,615
|
hpp
|
C++
|
src/Switch.System.Windows.Forms/include/Switch/System/Windows/Forms/FormBorderStyle.hpp
|
victor-timoshin/Switch
|
8e8e687a8bdc4f79d482680da3968e9b3e464b8b
|
[
"MIT"
] | 4
|
2020-02-11T13:22:58.000Z
|
2022-02-24T00:37:43.000Z
|
src/Switch.System.Windows.Forms/include/Switch/System/Windows/Forms/FormBorderStyle.hpp
|
sgf/Switch
|
8e8e687a8bdc4f79d482680da3968e9b3e464b8b
|
[
"MIT"
] | null | null | null |
src/Switch.System.Windows.Forms/include/Switch/System/Windows/Forms/FormBorderStyle.hpp
|
sgf/Switch
|
8e8e687a8bdc4f79d482680da3968e9b3e464b8b
|
[
"MIT"
] | 2
|
2020-02-01T02:19:01.000Z
|
2021-12-30T06:44:00.000Z
|
/// @file
/// @brief Contains Switch::System::Windows::Forms::BorderStyle enum.
#pragma once
#include <Switch/System/Enum.hpp>
/// @brief The Switch namespace contains all fundamental classes to access Hardware, Os, System, and more.
namespace Switch {
/// @brief The Switch::System namespace contains fundamental classes and base classes that define commonly-used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions.
namespace System {
/// @brief The Switch::System::Windows namespaces including animation clients, user interface controls, data binding, and type conversion. Switch::System::Windows::Forms and its child namespaces are used for developing Windows Forms applications.
namespace Windows {
/// @brief The Switch::System::Windows::Forms namespace contains classes for creating Windows-based applications that take full advantage of the rich user interface features available in the Microsoft Windows operating system, Apple macOS and Linux like Ubuntu operating system.
namespace Forms {
/// @brief Specifies the border styles for a form.
/// @par Library
/// Switch.System.Windows.Forms
enum class FormBorderStyle {
/// @brief No border.
None,
/// @brief A fixed, single-line border.
FixedSingle,
/// @brief A fixed, three-dimensional border.
Fixed3D,
/// @brief A thick, fixed dialog-style border.
FixedDialog = 3,
/// @brief A resizable border.
Sizable = 4,
/// @brief A tool window border
FixedToolWindow = 5,
/// @brief A resizable tool window border.
SizableToolWindow = 6,
};
}
}
}
}
/// @cond
template<>
struct EnumRegister<System::Windows::Forms::FormBorderStyle> {
void operator()(System::Collections::Generic::IDictionary<System::Windows::Forms::FormBorderStyle, string>& values, bool& flags) {
values[System::Windows::Forms::FormBorderStyle::None] = "None";
values[System::Windows::Forms::FormBorderStyle::FixedSingle] = "FixedSingle";
values[System::Windows::Forms::FormBorderStyle::Fixed3D] = "Fixed3D";
values[System::Windows::Forms::FormBorderStyle::FixedDialog] = "FixedDialog";
values[System::Windows::Forms::FormBorderStyle::Sizable] = "Sizable";
values[System::Windows::Forms::FormBorderStyle::FixedToolWindow] = "FixedToolWindow";
values[System::Windows::Forms::FormBorderStyle::Fixed3D] = "SizableToolWindow";
flags = false;
}
};
/// @endcond
using namespace Switch;
| 46.696429
| 284
| 0.690631
|
victor-timoshin
|
005220553f1bdd10ea6b7953baec3e9a829eca3d
| 1,505
|
cpp
|
C++
|
src/homework/04_iteration/main.cpp
|
acc-cosc-1337-spring-2022/acc-cosc-1337-spring-2022-AndrewGraz
|
9d00dc54b0c12faf7543fefbca6830ecd6494a2b
|
[
"MIT"
] | null | null | null |
src/homework/04_iteration/main.cpp
|
acc-cosc-1337-spring-2022/acc-cosc-1337-spring-2022-AndrewGraz
|
9d00dc54b0c12faf7543fefbca6830ecd6494a2b
|
[
"MIT"
] | null | null | null |
src/homework/04_iteration/main.cpp
|
acc-cosc-1337-spring-2022/acc-cosc-1337-spring-2022-AndrewGraz
|
9d00dc54b0c12faf7543fefbca6830ecd6494a2b
|
[
"MIT"
] | null | null | null |
//write include statements
#include<iostream>
#include "dna.h"
//write using statements
using std::cout; using std::cin;
/*
Write code that prompts user to enter 1 for Get GC Content,
or 2 for Get DNA Complement. The program will prompt user for a
DNA string and call either get gc content or get dna complement
function and display the result. Program runs as long as
user enters a y or Y.
*/
int main()
{
char yesser = 'n';
int option;
do
{
display_menu();
option = menu_runner();
switch (option)
{
case 1:
int num;
int sum;
cout << "Please enter a number. \n";
cin >> num;
sum = factorial(num);
cout<< sum << "\n";
yesser = 'y';
break;
case 2:
int out;
int num1;
int num2;
cout << "Please enter the first number. \n";
cin >> num1;
cout << "Please enter the second number number. \n";
cin >> num2;
out = gcd(num1, num2);
cout << out << "\n";
yesser = 'y';
break;
case 3:
cout << "Do you want to end this program? (Enter y for yes)\n";
cin >> yesser;
if (yesser == 'y')
{
cout << "The program is now exisiting. \n";
yesser = 'n';
}
else
{
cout << "Please enter a option. \n";
cin >> option;
yesser = 'y';
}
}
} while (yesser != 'n');
return 0;
}
| 22.132353
| 76
| 0.501661
|
acc-cosc-1337-spring-2022
|
0052539f301eb8e184530ec7b295e93e2ad86b3c
| 1,260
|
hpp
|
C++
|
implementations/Vulkan/buffer.hpp
|
rsayers/abstract-gpu
|
48176fcb88bde7d56de662c9e49d3d0e562819e1
|
[
"MIT"
] | 41
|
2016-03-25T18:14:37.000Z
|
2022-01-20T11:16:52.000Z
|
implementations/Vulkan/buffer.hpp
|
rsayers/abstract-gpu
|
48176fcb88bde7d56de662c9e49d3d0e562819e1
|
[
"MIT"
] | 4
|
2016-05-05T22:08:01.000Z
|
2021-12-10T13:06:55.000Z
|
implementations/Vulkan/buffer.hpp
|
rsayers/abstract-gpu
|
48176fcb88bde7d56de662c9e49d3d0e562819e1
|
[
"MIT"
] | 9
|
2016-05-23T01:51:25.000Z
|
2021-08-21T15:32:37.000Z
|
#ifndef AGPU_VULKAN_BUFFER_HPP
#define AGPU_VULKAN_BUFFER_HPP
#include "device.hpp"
#include "../Common/spinlock.hpp"
namespace AgpuVulkan
{
using AgpuCommon::Spinlock;
class AVkBuffer : public agpu::buffer
{
public:
AVkBuffer(const agpu::device_ref &device);
~AVkBuffer();
static agpu::buffer_ref create(const agpu::device_ref &device, agpu_buffer_description* description, agpu_pointer initial_data);
virtual agpu_pointer mapBuffer(agpu_mapping_access flags) override;
virtual agpu_error unmapBuffer() override;
virtual agpu_error getDescription(agpu_buffer_description* description) override;
virtual agpu_error uploadBufferData(agpu_size offset, agpu_size size, agpu_pointer data) override;
virtual agpu_error readBufferData(agpu_size offset, agpu_size size, agpu_pointer data) override;
virtual agpu_error flushWholeBuffer() override;
virtual agpu_error invalidateWholeBuffer() override;
agpu::device_weakref weakDevice;
AVkDeviceSharedContextPtr sharedContext;
agpu_buffer_description description;
VkBuffer handle;
VmaAllocation allocation;
Spinlock mappingLock;
void *mappedPointer;
uint32_t mapCount;
};
} // End of namespace AgpuVulkan
#endif //AGPU_VULKAN_BUFFER_HPP
| 29.302326
| 132
| 0.785714
|
rsayers
|
005f668e5878d2fb936b25bdd75c3a7f2aacd444
| 1,968
|
cpp
|
C++
|
source/solver/solution_finder.cpp
|
GreenLightning/circuit500_solver
|
b4e01c67beb36a98ea84aaf1c316b50315f497b1
|
[
"MIT"
] | 1
|
2015-12-01T07:15:04.000Z
|
2015-12-01T07:15:04.000Z
|
source/solver/solution_finder.cpp
|
GreenLightning/circuit500_solver
|
b4e01c67beb36a98ea84aaf1c316b50315f497b1
|
[
"MIT"
] | null | null | null |
source/solver/solution_finder.cpp
|
GreenLightning/circuit500_solver
|
b4e01c67beb36a98ea84aaf1c316b50315f497b1
|
[
"MIT"
] | null | null | null |
#include "board.hpp"
#include "configuration.hpp"
#include "solution_list.hpp"
#include "solution_finder.hpp"
Solution_Finder::Solution_Finder(int max_taps) :
max_taps(max_taps), solutions_checked(0) {}
void Solution_Finder::find(const Configuration& configuration, Board_Position start) {
++solutions_checked;
state.update(configuration.board);
if (state.is_solved()) {
list.append(configuration);
} else if (configuration.tap_count < max_taps && (list.empty() || configuration.action_count <= list.get_action_count())) {
if (configuration.board.has_gap()) {
Board_Position gap = configuration.board.get_gap();
if (gap.has_up() && gap.get_up() < start) {
Board_Position pos = gap.get_up();
Tap_Result result = with_tap(configuration, pos);
find(result.config, pos.has_up() ? pos.get_up() : Board_Position());
}
if (gap.has_down() && gap.get_down() < start) {
Tap_Result result = with_tap(configuration, gap.get_down());
find(result.config, gap.has_up() ? gap.get_up() : Board_Position());
}
if (gap.has_left() && gap.get_left() < start) {
Board_Position pos = gap.get_left();
Tap_Result result = with_tap(configuration, pos);
find(result.config, pos.has_up() ? pos.get_up() : Board_Position());
}
if (gap.has_right() && gap.get_right() < start) {
Tap_Result result = with_tap(configuration, gap.get_right());
find(result.config, gap.has_up() ? gap.get_up() : Board_Position());
}
}
for (Board_Position position = start; position < board_size; ++position) {
Tap_Result result = with_tap(configuration, position);
if (result.changed) {
Board_Position new_start = position;
if (result.moved) new_start = result.top.has_up() ? result.top.get_up() : Board_Position();
find(result.config, new_start);
}
}
}
}
long long int Solution_Finder::get_solutions_checked() {
return solutions_checked;
}
Solution_List Solution_Finder::get_solution_list() {
return list;
}
| 35.781818
| 124
| 0.700203
|
GreenLightning
|
0063a8fff51b0a6b5dd2e041d5e6a37f6aea5742
| 5,674
|
cpp
|
C++
|
CommonModules/RenderStatesManager.cpp
|
AlexWIN32/SSAODemo
|
56bee973b5b8fb9483918042c11ee107a262babc
|
[
"MIT"
] | null | null | null |
CommonModules/RenderStatesManager.cpp
|
AlexWIN32/SSAODemo
|
56bee973b5b8fb9483918042c11ee107a262babc
|
[
"MIT"
] | null | null | null |
CommonModules/RenderStatesManager.cpp
|
AlexWIN32/SSAODemo
|
56bee973b5b8fb9483918042c11ee107a262babc
|
[
"MIT"
] | 1
|
2019-12-30T10:53:35.000Z
|
2019-12-30T10:53:35.000Z
|
/*******************************************************************************
Author: Alexey Frolov (alexwin32@mail.ru)
This software is distributed freely under the terms of the MIT License.
See "LICENSE" or "http://copyfree.org/content/standard/licenses/mit/license.txt".
*******************************************************************************/
#include <RenderStatesManager.h>
#include <DeviceKeeper.h>
RenderStatesManager *RenderStatesManager::instance = NULL;
void RenderStatesManager::CreateRenderState(const std::string &StateName, const DepthStencilDescription &DepthStencilDesc) throw (Exception)
{
if(blendStates.find(StateName) != blendStates.end() ||
depthStencilStates.find(StateName) != depthStencilStates.end() ||
rasteriserStates.find(StateName) != rasteriserStates.end())
throw RenderStatesManagerException("State " + StateName + " is used");
DepthStencilData depthStencilData;
depthStencilData.ref = DepthStencilDesc.stencilRef;
HR(DeviceKeeper::GetDevice()->CreateDepthStencilState(&DepthStencilDesc.stencilDescription, &depthStencilData.state));
depthStencilStates.insert(std::make_pair(StateName, depthStencilData));
}
void RenderStatesManager::CreateRenderState(const std::string &StateName, const BlendStateDescription &BlendDesc) throw (Exception)
{
if(blendStates.find(StateName) != blendStates.end() ||
depthStencilStates.find(StateName) != depthStencilStates.end() ||
rasteriserStates.find(StateName) != rasteriserStates.end())
throw RenderStatesManagerException("State " + StateName + " is used");
BlendData blendData;
memcpy(blendData.blendFactor, BlendDesc.blendFactor, sizeof(blendData.blendFactor));
blendData.sampleMask = BlendDesc.sampleMask;
HR(DeviceKeeper::GetDevice()->CreateBlendState(&BlendDesc.blendDescription, &blendData.state));
blendStates.insert(std::make_pair(StateName, blendData));
}
void RenderStatesManager::CreateRenderState(const std::string &StateName, const D3D11_RASTERIZER_DESC &RasteriserDesc) throw (Exception)
{
if(blendStates.find(StateName) != blendStates.end() ||
depthStencilStates.find(StateName) != depthStencilStates.end() ||
rasteriserStates.find(StateName) != rasteriserStates.end())
throw RenderStatesManagerException("State " + StateName + " is used");
ID3D11RasterizerState *rasterState = NULL;
HR(DeviceKeeper::GetDevice()->CreateRasterizerState(&RasteriserDesc, &rasterState), []{ return D3DException("cant create rasteriser state");});
rasteriserStates.insert({StateName, rasterState});
}
void RenderStatesManager::RemoveRenderState(const std::string &StateName)
{
auto bsIt = blendStates.find(StateName);
if(bsIt != blendStates.end()){
ReleaseCOM(bsIt->second.state);
blendStates.erase(bsIt);
ResetBlendState();
return;
}
auto dsIt = depthStencilStates.find(StateName);
if(dsIt != depthStencilStates.end()){
ReleaseCOM(dsIt->second.state);
depthStencilStates.erase(dsIt);
ResetDepthStencilState();
return;
}
auto rsIt = rasteriserStates.find(StateName);
if(rsIt != rasteriserStates.end()){
ReleaseCOM(rsIt->second);
rasteriserStates.erase(rsIt);
ResetRasteriserState();
}
}
RenderStatesManager::RenderStateType RenderStatesManager::ApplyState(const std::string &StateName) throw (Exception)
{
BlendStatesStorage::const_iterator bsCi = blendStates.find(StateName);
if(bsCi != blendStates.end()){
const BlendData &blendData = bsCi->second;
DeviceKeeper::GetDeviceContext()->OMSetBlendState(blendData.state, blendData.blendFactor, blendData.sampleMask);
return RS_TYPE_BLEND;
}
DepthStencilStatesStorage::const_iterator dsCi = depthStencilStates.find(StateName);
if(dsCi != depthStencilStates.end()){
DeviceKeeper::GetDeviceContext()->OMSetDepthStencilState(dsCi->second.state, dsCi->second.ref);
return RS_TYPE_DEPTH_STENCIL;
}
RasteriserStatesStorage::const_iterator rsCi = rasteriserStates.find(StateName);
if(rsCi != rasteriserStates.end()){
DeviceKeeper::GetDeviceContext()->RSSetState(rsCi->second);
return RS_TYPE_RASTERIZER;
}
throw RenderStatesManagerException("State " + StateName + " not found");
}
void RenderStatesManager::ResetBlendState()
{
DeviceKeeper::GetDeviceContext()->OMSetBlendState(NULL, NULL, 0xffffffff);
}
void RenderStatesManager::ResetDepthStencilState()
{
DeviceKeeper::GetDeviceContext()->OMSetDepthStencilState(NULL, 0);
}
void RenderStatesManager::ResetRasteriserState()
{
DeviceKeeper::GetDeviceContext()->RSSetState(NULL);
}
void RenderStatesManager::ProcessWithStates(const NamesStorage &StatesNames, const Procedure &Proc) throw (Exception)
{
bool depthStateChanged = false, rasterizerStateChanged = false, blendStateChanged = false;
for(const std::string &name : StatesNames){
RenderStateType res = ApplyState(name);
if(res == RS_TYPE_BLEND)
blendStateChanged = true;
else if(res == RS_TYPE_DEPTH_STENCIL)
depthStateChanged = true;
else if(res == RS_TYPE_RASTERIZER)
rasterizerStateChanged = true;
}
Proc();
if(depthStateChanged)
ResetDepthStencilState();
if(rasterizerStateChanged)
ResetRasteriserState();
if(blendStateChanged)
ResetBlendState();
}
RenderStatesManager::~RenderStatesManager()
{
for(auto &bs : blendStates)
ReleaseCOM(bs.second.state);
for(auto &ds : depthStencilStates)
ReleaseCOM(ds.second.state);
for(auto &rs : rasteriserStates)
ReleaseCOM(rs.second);
}
| 35.4625
| 144
| 0.711315
|
AlexWIN32
|
0069695e6b14339141f04d64e60be300b2ad228a
| 747
|
cpp
|
C++
|
test.cpp
|
Nk125/CppMimeTypes
|
3274ba025427e34561253a3564a7bfae8deb5ae3
|
[
"MIT"
] | 1
|
2022-03-04T22:42:14.000Z
|
2022-03-04T22:42:14.000Z
|
test.cpp
|
Nk125/CppMimeTypes
|
3274ba025427e34561253a3564a7bfae8deb5ae3
|
[
"MIT"
] | null | null | null |
test.cpp
|
Nk125/CppMimeTypes
|
3274ba025427e34561253a3564a7bfae8deb5ae3
|
[
"MIT"
] | null | null | null |
// Requires: https://github.com/renatoGarcia/icecream-cpp
#include "icecream.hpp"
#include "MimeTypes.hpp"
#include <string>
#include <vector>
int main() {
std::string buf;
std::vector<std::string> exts;
try {
buf = nk125::MimeTypes::getType(".txt");
IC(buf);
buf = nk125::MimeTypes::getType("txt");
IC(buf);
buf = nk125::MimeTypes::getType("asdjaksd.txt");
IC(buf);
buf = nk125::MimeTypes::getType("\\\\.\\C:\\file.txt");
IC(buf);
buf = nk125::MimeTypes::getType("/usr/file.TXt");
IC(buf);
exts = nk125::MimeTypes::getExtentions("text/plain");
IC(exts);
}
catch (std::exception& e) {
std::cerr << e.what();
}
}
| 21.970588
| 63
| 0.546185
|
Nk125
|
007883a84982a529b7496176e975b6127de42d76
| 1,963
|
cpp
|
C++
|
Misc/UnusedCode/graphics/rojue_BitmapFont.cpp
|
RobinSchmidt/RS-MET-Preliminary
|
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
|
[
"FTL"
] | 34
|
2017-04-19T18:26:02.000Z
|
2022-02-15T17:47:26.000Z
|
Misc/UnusedCode/graphics/rojue_BitmapFont.cpp
|
RobinSchmidt/RS-MET-Preliminary
|
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
|
[
"FTL"
] | 307
|
2017-05-04T21:45:01.000Z
|
2022-02-03T00:59:01.000Z
|
Misc/UnusedCode/graphics/rojue_BitmapFont.cpp
|
RobinSchmidt/RS-MET-Preliminary
|
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
|
[
"FTL"
] | 4
|
2017-09-05T17:04:31.000Z
|
2021-12-15T21:24:28.000Z
|
#include "rojue_BitmapFont.h"
using namespace rojue;
//-------------------------------------------------------------------------------------------------
// construction/destruction:
//BitmapFont* BitmapFont::instance = NULL;
BitmapFont::BitmapFont()
{
ascent = 0;
descent = 0;
defaultKerning = 1;
for(int g=0; g<numGlyphs; g++)
{
glyphBitmaps[g] = NULL;
glyphWidths[g] = 0;
}
createGlyphBitmaps();
}
BitmapFont::~BitmapFont()
{
for(int g=0; g<numGlyphs; g++)
{
if( glyphBitmaps[g] != NULL )
{
delete glyphBitmaps[g];
glyphBitmaps[g] = NULL;
}
}
}
//-------------------------------------------------------------------------------------------------
// setup:
//-------------------------------------------------------------------------------------------------
// inquiry:
int BitmapFont::getTextPixelWidth(const juce::String &text, int kerning) const
{
int result = 0;
tchar c;
for(int i=0; i<text.length(); i++)
{
c = text[i];
result += getGlyphWidth(c) + kerning;
}
return result - kerning; // we added one too much in the loop
}
int BitmapFont::glyphIndexToX(const juce::String &text, int index, int kerning) const
{
jassert( index < text.length() ); // index is out of range
if( index >= text.length() )
return 0;
int result = 0;
tchar c;
for(int i=0; i<index; i++)
{
c = text[i];
result += getGlyphWidth(c) + kerning;
}
return result;
}
int BitmapFont::xToGlyphIndex(const String &text, int xToFindGlyphIndexAt, int kerning) const
{
int x = 0;
int index = 0;
tchar c;
while( x < xToFindGlyphIndexAt && index < text.length() )
{
c = text[index];
x += getGlyphWidth(c) + kerning;
index++;
}
return index;
}
//-------------------------------------------------------------------------------------------------
// internal functions:
void BitmapFont::createGlyphBitmaps()
{
}
| 19.828283
| 99
| 0.479368
|
RobinSchmidt
|
007afd58d99200af5a4f9ccc4712f87ee47a6a49
| 3,157
|
cpp
|
C++
|
SampleOSXCocoaPodsProject/Pods/BRCLucene/src/core/CLucene/queryParser/FastCharStream.cpp
|
zaubara/BRFullTextSearch
|
e742f223a1c203eacb576711dd57b1187aee3deb
|
[
"Apache-2.0"
] | 151
|
2015-01-17T06:29:38.000Z
|
2022-02-17T11:27:38.000Z
|
SampleOSXCocoaPodsProject/Pods/BRCLucene/src/core/CLucene/queryParser/FastCharStream.cpp
|
yonglam/BRFullTextSearch
|
e742f223a1c203eacb576711dd57b1187aee3deb
|
[
"Apache-2.0"
] | 28
|
2015-03-01T20:14:42.000Z
|
2019-07-22T09:23:54.000Z
|
SampleOSXCocoaPodsProject/Pods/BRCLucene/src/core/CLucene/queryParser/FastCharStream.cpp
|
yonglam/BRFullTextSearch
|
e742f223a1c203eacb576711dd57b1187aee3deb
|
[
"Apache-2.0"
] | 28
|
2015-03-05T13:24:12.000Z
|
2022-03-26T09:16:29.000Z
|
/*------------------------------------------------------------------------------
* Copyright (C) 2003-2006 Ben van Klinken and the CLucene Team
*
* Distributable under the terms of either the Apache License (Version 2.0) or
* the GNU Lesser General Public License, as specified in the COPYING file.
------------------------------------------------------------------------------*/
#include "CLucene/_ApiHeader.h"
#include "_CharStream.h"
#include "_FastCharStream.h"
#include "CLucene/util/CLStreams.h"
CL_NS_DEF(queryParser)
FastCharStream::FastCharStream(CL_NS(util)::Reader* r, bool ownsReader) :
buffer(NULL),
_bufferSize(0),
bufferLength(0),
bufferPosition(0),
tokenStart(0),
bufferStart(0),
input(r),
_ownsReader(ownsReader)
{
}
FastCharStream::~FastCharStream()
{
if (_ownsReader ){
_CLLDELETE(input);
}
_CLDELETE_LCARRAY(buffer);
}
TCHAR FastCharStream::readChar() {
if (bufferPosition >= bufferLength)
refill();
return buffer[bufferPosition++];
}
void FastCharStream::refill() {
int32_t newPosition = bufferLength - tokenStart;
if (tokenStart == 0) { // token won't fit in buffer
if (buffer == NULL) { // first time: alloc buffer
buffer = _CL_NEWARRAY(TCHAR, 2048);
_bufferSize = 2048;
} else if (bufferLength == _bufferSize) { // grow buffer
_bufferSize *= 2;
TCHAR* newBuffer = _CL_NEWARRAY(TCHAR, _bufferSize);
_tcsncpy(newBuffer, buffer, bufferLength);
_CLDELETE_LCARRAY(buffer);
buffer = newBuffer;
}
} else { // shift token to front
_tcsncpy(buffer, buffer+tokenStart,newPosition);
}
bufferLength = newPosition; // update state
bufferPosition = newPosition;
bufferStart += tokenStart;
tokenStart = 0;
const TCHAR* charBuf = NULL;
int32_t charsRead = // fill space in buffer
input->read(charBuf, newPosition, _bufferSize-newPosition);
if (charsRead == -1){
_CLTHROWA(CL_ERR_IO, "read past eof");
}
else {
memcpy(buffer, charBuf, charsRead * sizeof(TCHAR)); // TODO: Can we use the reader buffer instead of copying to our own?
bufferLength += charsRead;
}
}
void FastCharStream::backup(const int32_t amount) {
bufferPosition -= amount;
}
TCHAR* FastCharStream::GetImage() {
size_t len = bufferPosition - tokenStart;
TCHAR* ret = _CL_NEWARRAY(TCHAR, len + 1);
_tcsncpy(ret, buffer+tokenStart, len);
ret[len] = 0; // NULL terminated string
return ret;
}
TCHAR* FastCharStream::GetSuffix(const int32_t len) {
TCHAR* value = _CL_NEWARRAY(TCHAR, len + 1);
_tcsncpy(value, buffer+(bufferPosition - len), len);
value[len] = 0; // NULL terminated string
return value;
}
void FastCharStream::Done() {
}
TCHAR FastCharStream::BeginToken() {
tokenStart = bufferPosition;
return readChar();
}
int32_t FastCharStream::getColumn() const {
return bufferStart + bufferPosition;
}
int32_t FastCharStream::getLine() const {
return 1;
}
int32_t FastCharStream::getEndColumn() const {
return bufferStart + bufferPosition;
}
int32_t FastCharStream::getEndLine() const {
return 1;
}
int32_t FastCharStream::getBeginColumn() const {
return bufferStart + tokenStart;
}
int32_t FastCharStream::getBeginLine() const {
return 1;
}
CL_NS_END
| 25.877049
| 122
| 0.682293
|
zaubara
|
00823012cf52f37b295ed5462487eca23b4cf665
| 1,107
|
cpp
|
C++
|
Triangle.cpp
|
hyper1423/SomeFPS
|
dcd353124d58e2696be7eaf44cddec17d6259629
|
[
"BSD-3-Clause"
] | null | null | null |
Triangle.cpp
|
hyper1423/SomeFPS
|
dcd353124d58e2696be7eaf44cddec17d6259629
|
[
"BSD-3-Clause"
] | null | null | null |
Triangle.cpp
|
hyper1423/SomeFPS
|
dcd353124d58e2696be7eaf44cddec17d6259629
|
[
"BSD-3-Clause"
] | null | null | null |
#include "triangle.hpp"
VertexArray::TypeVertices Triangle::getVertices() const {
VertexArray::TypeVertices vertices = {
{ 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.000000f, 1.000000f },
{ -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.000000f, 0.000000f },
{ -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 1.000000f, 1.000000f },
{ 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 1.000000f, 0.000000f },
{ 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.000000f, 1.000000f },
{ -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.000000f, 0.000000f },
{ -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 1.000000f, 1.000000f },
{ 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 1.000000f, 0.000000f },
};
return vertices;
}
Transformation Triangle::getTransformation() const {
return glm::rotate(glm::mat4({
{ 1.0f, 0.0f, 0.0f, 0.0f },
{ 0.0f, 1.0f, 0.0f, 0.0f },
{ 0.0f, 0.0f, 1.0f, 0.0f },
{ 0.0f, 0.0f, 0.0f, 1.0f },
}), 1.0f, glm::vec3(1, 0, 0));
}
VertexArray::TypeIndices Triangle::getIndices() const {
return VertexArray::TypeIndices({
{ 0, 1, 2 }
});
}
void Triangle::bindRenderingResources() const { }
| 34.59375
| 67
| 0.563686
|
hyper1423
|
0a58bb686bb8392a17c1e7aff1e3a89a485141c3
| 250
|
hpp
|
C++
|
src/testprog/cube/cube_scene.hpp
|
degarashi/revenant
|
9e671320a5c8790f6bdd1b14934f81c37819f7b3
|
[
"MIT"
] | null | null | null |
src/testprog/cube/cube_scene.hpp
|
degarashi/revenant
|
9e671320a5c8790f6bdd1b14934f81c37819f7b3
|
[
"MIT"
] | null | null | null |
src/testprog/cube/cube_scene.hpp
|
degarashi/revenant
|
9e671320a5c8790f6bdd1b14934f81c37819f7b3
|
[
"MIT"
] | null | null | null |
#pragma once
#include "../scenebase_obj.hpp"
#include "../fpcamera.hpp"
namespace rev::test {
class CubeScene :
public TestSceneObj<CubeScene>
{
private:
FPCamera _fpc;
HDObj _cube;
struct St_Default;
public:
CubeScene();
};
}
| 14.705882
| 32
| 0.672
|
degarashi
|
0a5b43e9e46a0e027d33a70f9867371f7dcf2d1d
| 505
|
cpp
|
C++
|
BASIC c++/managing_console_i/o_operation/formatting_with_manipulators.cpp
|
jattramesh/Learning_git
|
5191ecc6c0c11b69b9786f2a8bdd3db7228987d6
|
[
"MIT"
] | null | null | null |
BASIC c++/managing_console_i/o_operation/formatting_with_manipulators.cpp
|
jattramesh/Learning_git
|
5191ecc6c0c11b69b9786f2a8bdd3db7228987d6
|
[
"MIT"
] | null | null | null |
BASIC c++/managing_console_i/o_operation/formatting_with_manipulators.cpp
|
jattramesh/Learning_git
|
5191ecc6c0c11b69b9786f2a8bdd3db7228987d6
|
[
"MIT"
] | null | null | null |
//
// Created by rahul on 9/8/19.
//
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout.setf(ios::showpos);
cout<<setw(5)<<"n"<<setw(15)<<"inverse of n"<<setw(15)<<"sum of terms "<<endl;
double term,sum=0;
for(int i=1;i<=10;i++)
{
term=1.0/float(i);
sum=sum+term;
cout<<setw(5)<<i;
cout<<setw(14)<<setprecision(4)<<setiosflags(ios::scientific)<<term<<setw(13)<<resetiosflags(ios::scientific)<<sum<<endl;
}
return 0;
}
| 24.047619
| 129
| 0.578218
|
jattramesh
|
0a5c7a9bf054784f8ddbf36cd14abc6fe4dbd40b
| 2,153
|
cpp
|
C++
|
Romulus/src/Engine/Math/Vector.cpp
|
AlanBuechner/Romulus
|
20e798ac1ebe3a8b4ae9764412e6f5f8b2c6fc70
|
[
"Apache-2.0"
] | null | null | null |
Romulus/src/Engine/Math/Vector.cpp
|
AlanBuechner/Romulus
|
20e798ac1ebe3a8b4ae9764412e6f5f8b2c6fc70
|
[
"Apache-2.0"
] | null | null | null |
Romulus/src/Engine/Math/Vector.cpp
|
AlanBuechner/Romulus
|
20e798ac1ebe3a8b4ae9764412e6f5f8b2c6fc70
|
[
"Apache-2.0"
] | null | null | null |
#include <pch.h>
#include "Vector.h"
namespace Engine::Math
{
float Length(const Vector2& v)
{
return glm::length(v);
}
float Length(const Vector3& v)
{
return glm::length(v);
}
float Length(const Vector4& v)
{
return glm::length(v);
}
float LengthSqr(const Vector2& v)
{
return (v.x * v.x) + (v.y * v.y);
}
float LengthSqr(const Vector3& v)
{
return (v.x * v.x) + (v.y * v.y) + (v.z * v.z);
}
float LengthSqr(const Vector4& v)
{
return (v.x * v.x) + (v.y * v.y) + (v.z * v.z) + (v.w * v.w);
}
float Distance(const Vector2& v1, const Vector2& v2)
{
return Length(v2 - v1);
}
float Distance(const Vector3& v1, const Vector3& v2)
{
return Length(v2 - v1);
}
float Distance(const Vector4& v1, const Vector4& v2)
{
return Length(v2 - v1);
}
float DistanceSqr(const Vector2& v1, const Vector2& v2)
{
return LengthSqr(v2 - v1);
}
float DistanceSqr(const Vector3& v1, const Vector3& v2)
{
return LengthSqr(v2 - v1);
}
float DistanceSqr(const Vector4& v1, const Vector4& v2)
{
return LengthSqr(v2 - v1);
}
float Dot(const Vector2& v1, const Vector2& v2)
{
return glm::dot(v1, v2);
}
float Dot(const Vector3& v1, const Vector3& v2)
{
return glm::dot(v1, v2);
}
float Dot(const Vector4& v1, const Vector4& v2)
{
return glm::dot(v1, v2);
}
Vector3 Cross(const Vector3& v1, const Vector3& v2)
{
return glm::cross(v1, v2);
}
Vector2 Normalized(const Vector2& v)
{
return glm::normalize(v);
}
Vector3 Normalized(const Vector3& v)
{
return glm::normalize(v);
}
Vector4 Normalized(const Vector4& v)
{
return glm::normalize(v);
}
Vector2& Normalize(Vector2& v)
{
return v = glm::normalize(v);
}
Vector3& Normalize(Vector3& v)
{
return v = glm::normalize(v);
}
Vector4& Normalize(Vector4& v)
{
return v = glm::normalize(v);
}
Vector2 Lerp(const Vector2& v1, const Vector2& v2, float a)
{
return (v1 * a) + v2 * (1.f - a);
}
Vector3 Lerp(const Vector3& v1, const Vector3& v2, float a)
{
return (v1 * a) + v2 * (1.f - a);
}
Vector4 Lerp(const Vector4& v1, const Vector4& v2, float a)
{
return (v1 * a) + v2 * (1.f - a);
}
}
| 16.561538
| 63
| 0.617278
|
AlanBuechner
|
0a5e609dae1dc24a9d28598580eef0720af21eea
| 51
|
hpp
|
C++
|
src/boost_random_geometric_distribution.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 10
|
2018-03-17T00:58:42.000Z
|
2021-07-06T02:48:49.000Z
|
src/boost_random_geometric_distribution.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 2
|
2021-03-26T15:17:35.000Z
|
2021-05-20T23:55:08.000Z
|
src/boost_random_geometric_distribution.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 4
|
2019-05-28T21:06:37.000Z
|
2021-07-06T03:06:52.000Z
|
#include <boost/random/geometric_distribution.hpp>
| 25.5
| 50
| 0.843137
|
miathedev
|
0a64c45ad183ca059d52f8ba451cf78c09a61dea
| 13,378
|
cpp
|
C++
|
Blizzlike/ArcEmu/C++/World/LogonCommHandler.cpp
|
499453466/Lua-Other
|
43fd2b72405faf3f2074fd2a2706ef115d16faa6
|
[
"Unlicense"
] | 2
|
2015-06-23T16:26:32.000Z
|
2019-06-27T07:45:59.000Z
|
Blizzlike/ArcEmu/C++/World/LogonCommHandler.cpp
|
Eduardo-Silla/Lua-Other
|
db610f946dbcaf81b3de9801f758e11a7bf2753f
|
[
"Unlicense"
] | null | null | null |
Blizzlike/ArcEmu/C++/World/LogonCommHandler.cpp
|
Eduardo-Silla/Lua-Other
|
db610f946dbcaf81b3de9801f758e11a7bf2753f
|
[
"Unlicense"
] | 3
|
2015-01-10T18:22:59.000Z
|
2021-04-27T21:28:28.000Z
|
/*
* ArcEmu MMORPG Server
* Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/>
* Copyright (C) 2008-2011 <http://www.ArcEmu.org/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "StdAfx.h"
initialiseSingleton(LogonCommHandler);
LogonCommHandler::LogonCommHandler()
{
idhigh = 1;
next_request = 1;
pings = !Config.MainConfig.GetBoolDefault("LogonServer", "DisablePings", false);
string logon_pass = Config.MainConfig.GetStringDefault("LogonServer", "RemotePassword", "r3m0t3");
// sha1 hash it
Sha1Hash hash;
hash.UpdateData(logon_pass);
hash.Finalize();
memset(sql_passhash, 0, 20);
memcpy(sql_passhash, hash.GetDigest(), 20);
// player limit
pLimit = Config.MainConfig.GetIntDefault("Server", "PlayerLimit", 500);
if(pLimit == 0) pLimit = 1;
server_population = 0;
// cleanup
servers.clear();
realms.clear();
}
LogonCommHandler::~LogonCommHandler()
{
for(set<LogonServer*>::iterator i = servers.begin(); i != servers.end(); ++i)
delete(*i);
for(set<Realm*>::iterator i = realms.begin(); i != realms.end(); ++i)
delete(*i);
}
LogonCommClientSocket* LogonCommHandler::ConnectToLogon(string Address, uint32 Port)
{
LogonCommClientSocket* conn = ConnectTCPSocket<LogonCommClientSocket>(Address.c_str(), static_cast<u_short>(Port));
return conn;
}
void LogonCommHandler::RequestAddition(LogonCommClientSocket* Socket)
{
set<Realm*>::iterator itr = realms.begin();
for(; itr != realms.end(); ++itr)
{
WorldPacket data(RCMSG_REGISTER_REALM, 100);
// Add realm to the packet
Realm* realm = *itr;
data << realm->Name;
data << realm->Address;
data << realm->flags;
data << realm->Icon;
data << realm->TimeZone;
data << float(realm->Population);
data << uint8(realm->Lock);
Socket->SendPacket(&data, false);
}
}
class LogonCommWatcherThread : public ThreadBase
{
bool running;
Arcemu::Threading::ConditionVariable cond;
public:
LogonCommWatcherThread()
{
running = true;
}
~LogonCommWatcherThread()
{
}
void OnShutdown()
{
running = false;
cond.Signal();
}
bool run()
{
sLogonCommHandler.ConnectAll();
while(running)
{
sLogonCommHandler.UpdateSockets();
cond.Wait(5000);
}
return true;
}
};
void LogonCommHandler::Startup()
{
// Try to connect to all logons.
LoadRealmConfiguration();
Log.Notice("LogonCommClient", "Loading forced permission strings...");
QueryResult* result = CharacterDatabase.Query("SELECT * FROM account_forced_permissions");
if(result != NULL)
{
do
{
string acct = result->Fetch()[0].GetString();
string perm = result->Fetch()[1].GetString();
arcemu_TOUPPER(acct);
forced_permissions.insert(make_pair(acct, perm));
}
while(result->NextRow());
delete result;
}
ThreadPool.ExecuteTask(new LogonCommWatcherThread());
}
void LogonCommHandler::ConnectAll()
{
Log.Success("LogonCommClient", "Attempting to connect to logon server...");
for(set<LogonServer*>::iterator itr = servers.begin(); itr != servers.end(); ++itr)
Connect(*itr);
}
const string* LogonCommHandler::GetForcedPermissions(string & username)
{
ForcedPermissionMap::iterator itr = forced_permissions.find(username);
if(itr == forced_permissions.end())
return NULL;
return &itr->second;
}
void LogonCommHandler::Connect(LogonServer* server)
{
if(sMaster.m_ShutdownEvent == true && sMaster.m_ShutdownTimer <= 120000) // 2minutes
return;
server->RetryTime = (uint32)UNIXTIME + 10;
server->Registered = false;
LogonCommClientSocket* conn = ConnectToLogon(server->Address, server->Port);
logons[server] = conn;
if(conn == 0)
{
Log.Error("LogonCommClient", "Connection failed. Will try again in 10 seconds.");
return;
}
Log.Success("LogonCommClient", "Authenticating...");
uint32 tt = (uint32)UNIXTIME + 10;
conn->SendChallenge();
while(!conn->authenticated)
{
if((uint32)UNIXTIME >= tt)
{
Log.Error("LogonCommClient", "Authentication timed out.");
conn->Disconnect();
logons[server] = NULL;
return;
}
Arcemu::Sleep(50);
}
if(conn->authenticated != 1)
{
Log.Error("LogonCommClient", "Authentication failed.");
logons[server] = 0;
conn->Disconnect();
return;
}
Log.Success("LogonCommClient", "Authentication OK.");
Log.Notice("LogonCommClient", "Logonserver was connected on [%s:%u].", server->Address.c_str(), server->Port);
// Send the initial ping
conn->SendPing();
Log.Notice("LogonCommClient", "Registering Realms...");
conn->_id = server->ID;
RequestAddition(conn);
uint32 st = (uint32)UNIXTIME + 10;
// Wait for register ACK
while(server->Registered == false)
{
// Don't wait more than.. like 10 seconds for a registration
if((uint32)UNIXTIME >= st)
{
Log.Error("LogonCommClient", "Realm registration timed out.");
logons[server] = 0;
conn->Disconnect();
break;
}
Arcemu::Sleep(50);
}
if(!server->Registered)
return;
// Wait for all realms to register
Arcemu::Sleep(200);
Log.Success("LogonCommClient", "Logonserver latency is %ums.", conn->latency);
}
void LogonCommHandler::AdditionAck(uint32 ID, uint32 ServID)
{
map<LogonServer*, LogonCommClientSocket*>::iterator itr = logons.begin();
for(; itr != logons.end(); ++itr)
{
if(itr->first->ID == ID)
{
itr->first->ServerID = ServID;
itr->first->Registered = true;
return;
}
}
}
void LogonCommHandler::UpdateSockets()
{
mapLock.Acquire();
map<LogonServer*, LogonCommClientSocket*>::iterator itr = logons.begin();
LogonCommClientSocket* cs;
uint32 t = (uint32)UNIXTIME;
for(; itr != logons.end(); ++itr)
{
cs = itr->second;
if(cs != 0)
{
if(!pings) continue;
if(cs->IsDeleted() || !cs->IsConnected())
{
cs->_id = 0;
itr->second = 0;
continue;
}
if(cs->last_pong < t && ((t - cs->last_pong) > 60))
{
// no pong for 60 seconds -> remove the socket
LOG_DETAIL(" >> realm id %u connection dropped due to pong timeout.", (unsigned int)itr->first->ID);
cs->_id = 0;
cs->Disconnect();
itr->second = 0;
continue;
}
if((t - cs->last_ping) > 15)
{
// send a ping packet.
cs->SendPing();
}
}
else
{
// check retry time
if(t >= itr->first->RetryTime)
{
Connect(itr->first);
}
}
}
mapLock.Release();
}
void LogonCommHandler::ConnectionDropped(uint32 ID)
{
mapLock.Acquire();
map<LogonServer*, LogonCommClientSocket*>::iterator itr = logons.begin();
for(; itr != logons.end(); ++itr)
{
if(itr->first->ID == ID && itr->second != 0)
{
LOG_ERROR(" >> realm id %u connection was dropped unexpectedly. reconnecting next loop.", ID);
itr->second = 0;
break;
}
}
mapLock.Release();
}
uint32 LogonCommHandler::ClientConnected(string AccountName, WorldSocket* Socket)
{
uint32 request_id = next_request++;
size_t i = 0;
const char* acct = AccountName.c_str();
LOG_DEBUG(" >> sending request for account information: `%s` (request %u).", AccountName.c_str(), request_id);
// Send request packet to server.
map<LogonServer*, LogonCommClientSocket*>::iterator itr = logons.begin();
if(logons.size() == 0)
{
// No valid logonserver is connected.
return (uint32) - 1;
}
LogonCommClientSocket* s = itr->second;
if(s == NULL)
return (uint32) - 1;
pendingLock.Acquire();
WorldPacket data(RCMSG_REQUEST_SESSION, 100);
data << request_id;
// strip the shitty hash from it
for(; acct[i] != '#' && acct[i] != '\0'; ++i)
data.append(&acct[i], 1);
data.append("\0", 1);
s->SendPacket(&data, false);
pending_logons[request_id] = Socket;
pendingLock.Release();
RefreshRealmPop();
return request_id;
}
void LogonCommHandler::UnauthedSocketClose(uint32 id)
{
pendingLock.Acquire();
pending_logons.erase(id);
pendingLock.Release();
}
void LogonCommHandler::RemoveUnauthedSocket(uint32 id)
{
pending_logons.erase(id);
}
void LogonCommHandler::LoadRealmConfiguration()
{
LogonServer* ls = new LogonServer;
ls->ID = idhigh++;
ls->Name = Config.RealmConfig.GetStringDefault("LogonServer", "Name", "UnkLogon");
ls->Address = Config.RealmConfig.GetStringDefault("LogonServer", "Address", "127.0.0.1");
ls->Port = Config.RealmConfig.GetIntDefault("LogonServer", "Port", 8093);
servers.insert(ls);
uint32 realmcount = Config.RealmConfig.GetIntDefault("LogonServer", "RealmCount", 1);
if(realmcount == 0)
{
LOG_ERROR(" >> no realms found. this server will not be online anywhere!");
}
else
{
for(uint32 i = 1; i < realmcount + 1; ++i)
{
Realm* realm = new Realm;
realm->Name = Config.RealmConfig.GetStringVA("Name", "SomeRealm", "Realm%u", i);
realm->Address = Config.RealmConfig.GetStringVA("Address", "127.0.0.1:8129", "Realm%u", i);
realm->flags = 0;
realm->TimeZone = Config.RealmConfig.GetIntVA("TimeZone", 1, "Realm%u", i);
realm->Population = Config.RealmConfig.GetFloatVA("Population", 0, "Realm%u", i);
realm->Lock = static_cast<uint8>(Config.RealmConfig.GetIntVA("Lock", 0, "Realm%u", i));
string rt = Config.RealmConfig.GetStringVA("Icon", "Normal", "Realm%u", i);
uint32 type;
// process realm type
if(stricmp(rt.c_str(), "pvp") == 0)
type = REALMTYPE_PVP;
else if(stricmp(rt.c_str(), "rp") == 0)
type = REALMTYPE_RP;
else if(stricmp(rt.c_str(), "rppvp") == 0)
type = REALMTYPE_RPPVP;
else
type = REALMTYPE_NORMAL;
_realmType = type;
realm->Icon = type;
realms.insert(realm);
}
}
}
void LogonCommHandler::UpdateAccountCount(uint32 account_id, uint8 add)
{
// Send request packet to server.
map<LogonServer*, LogonCommClientSocket*>::iterator itr = logons.begin();
if(logons.size() == 0 || itr->second == 0)
{
// No valid logonserver is connected.
return;
}
itr->second->UpdateAccountCount(account_id, add);
}
void LogonCommHandler::TestConsoleLogon(string & username, string & password, uint32 requestnum)
{
string newuser = username;
string newpass = password;
string srpstr;
arcemu_TOUPPER(newuser);
arcemu_TOUPPER(newpass);
srpstr = newuser + ":" + newpass;
// Send request packet to server.
map<LogonServer*, LogonCommClientSocket*>::iterator itr = logons.begin();
if(logons.size() == 0 || itr->second == 0)
{
// No valid logonserver is connected.
return;
}
Sha1Hash hash;
hash.UpdateData(srpstr);
hash.Finalize();
WorldPacket data(RCMSG_TEST_CONSOLE_LOGIN, 100);
data << requestnum;
data << newuser;
data.append(hash.GetDigest(), 20);
itr->second->SendPacket(&data, false);
}
// db funcs
void LogonCommHandler::Account_SetBanned(const char* account, uint32 banned, const char* reason)
{
map<LogonServer*, LogonCommClientSocket*>::iterator itr = logons.begin();
if(logons.size() == 0 || itr->second == 0)
{
// No valid logonserver is connected.
return;
}
WorldPacket data(RCMSG_MODIFY_DATABASE, 300);
data << uint32(1); // 1 = ban
data << account;
data << banned;
data << reason;
itr->second->SendPacket(&data, false);
}
void LogonCommHandler::Account_SetGM(const char* account, const char* flags)
{
map<LogonServer*, LogonCommClientSocket*>::iterator itr = logons.begin();
if(logons.size() == 0 || itr->second == 0)
{
// No valid logonserver is connected.
return;
}
WorldPacket data(RCMSG_MODIFY_DATABASE, 50);
data << uint32(2); // 2 = set gm
data << account;
data << flags;
itr->second->SendPacket(&data, false);
}
void LogonCommHandler::Account_SetMute(const char* account, uint32 muted)
{
map<LogonServer*, LogonCommClientSocket*>::iterator itr = logons.begin();
if(logons.size() == 0 || itr->second == 0)
{
// No valid logonserver is connected.
return;
}
WorldPacket data(RCMSG_MODIFY_DATABASE, 50);
data << uint32(3); // 3 = mute
data << account;
data << muted;
itr->second->SendPacket(&data, false);
}
void LogonCommHandler::IPBan_Add(const char* ip, uint32 duration, const char* reason)
{
map<LogonServer*, LogonCommClientSocket*>::iterator itr = logons.begin();
if(logons.size() == 0 || itr->second == 0)
{
// No valid logonserver is connected.
return;
}
WorldPacket data(RCMSG_MODIFY_DATABASE, 300);
data << uint32(4); // 4 = ipban add
data << ip;
data << duration;
data << reason;
itr->second->SendPacket(&data, false);
}
void LogonCommHandler::IPBan_Remove(const char* ip)
{
map<LogonServer*, LogonCommClientSocket*>::iterator itr = logons.begin();
if(logons.size() == 0 || itr->second == 0)
{
// No valid logonserver is connected.
return;
}
WorldPacket data(RCMSG_MODIFY_DATABASE, 50);
data << uint32(5); // 5 = ipban remove
data << ip;
itr->second->SendPacket(&data, false);
}
void LogonCommHandler::RefreshRealmPop()
{
// Get realm player limit, it's better that we get the player limit once and save it! <-done
// Calc pop: 0 >= low, 1 >= med, 2 >= hig, 3 >= full
server_population = sWorld.getPlayerCount() * 3.0f / pLimit;
}
| 24.546789
| 116
| 0.680147
|
499453466
|
0a65f1532563645c6a9189cef39fadbffcb42509
| 620
|
hpp
|
C++
|
src/db/Statement.hpp
|
sielenk/furnace
|
092f047322ac8e6874f19a801f6e8e773801fad6
|
[
"MIT"
] | null | null | null |
src/db/Statement.hpp
|
sielenk/furnace
|
092f047322ac8e6874f19a801f6e8e773801fad6
|
[
"MIT"
] | null | null | null |
src/db/Statement.hpp
|
sielenk/furnace
|
092f047322ac8e6874f19a801f6e8e773801fad6
|
[
"MIT"
] | null | null | null |
// (C) 2016 Marvin Sielenkemper
#pragma once
#include "MySql.hpp"
#include <boost/any.hpp>
#include <vector>
#include <memory>
namespace db {
class ResultSet;
class Bindings;
class Statement : boost::noncopyable {
public:
Statement(MySql& mysql, std::string const& statement);
~Statement();
ResultSet execute();
ResultSet execute(Bindings& parameterBindings);
operator MYSQL_STMT*() const;
private:
struct Deleter {
void operator()(MYSQL_STMT*) const;
};
typedef std::unique_ptr<MYSQL_STMT, Deleter> StatementPtr;
StatementPtr const m_statementPtr;
};
}
| 16.756757
| 62
| 0.683871
|
sielenk
|
0a6bee03e47084017e8b5390611c94f6182cc3cd
| 32,022
|
cpp
|
C++
|
hi_dsp/modules/MidiPlayer.cpp
|
Levitanus/HISE
|
8ef678ec2fcae0973cc269163404b1f9df967733
|
[
"Intel"
] | 9
|
2020-04-16T01:17:27.000Z
|
2022-02-25T14:13:10.000Z
|
hi_dsp/modules/MidiPlayer.cpp
|
Levitanus/HISE
|
8ef678ec2fcae0973cc269163404b1f9df967733
|
[
"Intel"
] | null | null | null |
hi_dsp/modules/MidiPlayer.cpp
|
Levitanus/HISE
|
8ef678ec2fcae0973cc269163404b1f9df967733
|
[
"Intel"
] | 6
|
2020-05-11T22:23:15.000Z
|
2022-02-24T16:52:44.000Z
|
/* ===========================================================================
*
* This file is part of HISE.
* Copyright 2016 Christoph Hart
*
* HISE is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HISE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HISE. If not, see <http://www.gnu.org/licenses/>.
*
* Commercial licenses for using HISE in an closed source project are
* available on request. Please visit the project's website to get more
* information about commercial licensing:
*
* http://www.hise.audio/
*
* HISE is based on the JUCE library,
* which must be separately licensed for closed source applications:
*
* http://www.juce.com
*
* ===========================================================================
*/
namespace hise {
using namespace juce;
struct MidiPlayerHelpers
{
static double samplesToSeconds(double samples, double sr)
{
return samples / sr;
}
static double samplesToTicks(double samples, double bpm, double sr)
{
auto samplesPerQuarter = (double)TempoSyncer::getTempoInSamples(bpm, sr, TempoSyncer::Quarter);
return (double)HiseMidiSequence::TicksPerQuarter * samples / samplesPerQuarter;
}
static double secondsToTicks(double seconds, double bpm, double sr)
{
auto samples = secondsToSamples(seconds, sr);
return samplesToTicks(samples, bpm, sr);
}
static double secondsToSamples(double seconds, double sr)
{
return seconds * sr;
}
static double ticksToSamples(double ticks, double bpm, double sr)
{
auto samplesPerQuarter = (double)TempoSyncer::getTempoInSamples(bpm, sr, TempoSyncer::Quarter);
return samplesPerQuarter * ticks / HiseMidiSequence::TicksPerQuarter;
}
};
HiseMidiSequence::SimpleReadWriteLock::ScopedReadLock::ScopedReadLock(SimpleReadWriteLock &lock_) :
lock(lock_)
{
for (int i = 20; --i >= 0;)
if (!lock.isBeingWritten)
break;
while (lock.isBeingWritten)
Thread::yield();
lock.numReadLocks++;
}
HiseMidiSequence::SimpleReadWriteLock::ScopedReadLock::~ScopedReadLock()
{
lock.numReadLocks--;
}
HiseMidiSequence::SimpleReadWriteLock::ScopedWriteLock::ScopedWriteLock(SimpleReadWriteLock &lock_) :
lock(lock_)
{
if (lock.isBeingWritten)
{
// jassertfalse;
return;
}
for (int i = 100; --i >= 0;)
if (lock.numReadLocks == 0)
break;
while (lock.numReadLocks > 0)
Thread::yield();
lock.isBeingWritten = true;
}
HiseMidiSequence::SimpleReadWriteLock::ScopedWriteLock::~ScopedWriteLock()
{
lock.isBeingWritten = false;
}
HiseMidiSequence::HiseMidiSequence()
{
}
juce::ValueTree HiseMidiSequence::exportAsValueTree() const
{
ValueTree v("MidiFile");
v.setProperty("ID", id.toString(), nullptr);
MemoryOutputStream mos;
MidiFile currentFile;
for (auto t : sequences)
currentFile.addTrack(*t);
currentFile.writeTo(mos);
auto data = mos.getMemoryBlock();
zstd::ZDefaultCompressor compressor;
compressor.compressInplace(data);
v.setProperty("Data", data.toBase64Encoding(), nullptr);
return v;
}
void HiseMidiSequence::restoreFromValueTree(const ValueTree &v)
{
id = v.getProperty("ID").toString();
// This property isn't used in this class, but if you want to
// have any kind of connection to a pooled MidiFile, you will
// need to add this externally (see MidiPlayer::exportAsValueTree())
jassert(v.hasProperty("FileName"));
String encodedState = v.getProperty("Data");
MemoryBlock mb;
if (mb.fromBase64Encoding(encodedState))
{
zstd::ZDefaultCompressor compressor;
compressor.expandInplace(mb);
MemoryInputStream mis(mb, false);
MidiFile mf;
mf.readFrom(mis);
loadFrom(mf);
}
}
juce::MidiMessage* HiseMidiSequence::getNextEvent(Range<double> rangeToLookForTicks)
{
SimpleReadWriteLock::ScopedReadLock sl(swapLock);
auto nextIndex = lastPlayedIndex + 1;
if (auto seq = getReadPointer(currentTrackIndex))
{
if (nextIndex >= seq->getNumEvents())
{
lastPlayedIndex = -1;
nextIndex = 0;
}
if (auto nextEvent = seq->getEventPointer(nextIndex))
{
auto timestamp = nextEvent->message.getTimeStamp();
auto maxLength = getLength();
if (rangeToLookForTicks.contains(timestamp))
{
lastPlayedIndex = nextIndex;
return &nextEvent->message;
}
else if (rangeToLookForTicks.contains(maxLength))
{
auto rangeAtBeginning = rangeToLookForTicks.getEnd() - maxLength;
if (timestamp < rangeAtBeginning)
{
lastPlayedIndex = nextIndex;
return &nextEvent->message;
}
}
}
}
return nullptr;
}
juce::MidiMessage* HiseMidiSequence::getMatchingNoteOffForCurrentEvent()
{
if (auto noteOff = getReadPointer(currentTrackIndex)->getEventPointer(lastPlayedIndex)->noteOffObject)
return ¬eOff->message;
return nullptr;
}
double HiseMidiSequence::getLength() const
{
SimpleReadWriteLock::ScopedReadLock sl(swapLock);
if (artificialLengthInQuarters != -1.0)
return artificialLengthInQuarters * (double)TicksPerQuarter;
double maxLength = 0.0;
for (auto seq : sequences)
maxLength = jmax(maxLength, seq->getEndTime());
return maxLength;
}
double HiseMidiSequence::getLengthInQuarters()
{
SimpleReadWriteLock::ScopedReadLock sl(swapLock);
if (artificialLengthInQuarters != -1.0)
return artificialLengthInQuarters;
if (auto currentSequence = sequences.getFirst())
return currentSequence->getEndTime() / (double)TicksPerQuarter;
return 0.0;
}
void HiseMidiSequence::setLengthInQuarters(double newLength)
{
artificialLengthInQuarters = newLength;
}
void HiseMidiSequence::loadFrom(const MidiFile& file)
{
OwnedArray<MidiMessageSequence> newSequences;
MidiFile normalisedFile;
for (int i = 0; i < file.getNumTracks(); i++)
{
ScopedPointer<MidiMessageSequence> newSequence = new MidiMessageSequence(*file.getTrack(i));
newSequence->deleteSysExMessages();
DBG("Track " + String(i + 1));
for (int j = 0; j < newSequence->getNumEvents(); j++)
{
if (newSequence->getEventPointer(j)->message.isMetaEvent())
newSequence->deleteEvent(j--, false);
}
if(newSequence->getNumEvents() > 0)
normalisedFile.addTrack(*newSequence);
}
normalisedFile.setTicksPerQuarterNote(TicksPerQuarter);
for (int i = 0; i < normalisedFile.getNumTracks(); i++)
{
ScopedPointer<MidiMessageSequence> newSequence = new MidiMessageSequence(*normalisedFile.getTrack(i));
newSequences.add(newSequence.release());
}
{
SimpleReadWriteLock::ScopedWriteLock sl(swapLock);
newSequences.swapWith(sequences);
}
}
void HiseMidiSequence::createEmptyTrack()
{
ScopedPointer<MidiMessageSequence> newTrack = new MidiMessageSequence();
{
SimpleReadWriteLock::ScopedWriteLock sl(swapLock);
sequences.add(newTrack.release());
currentTrackIndex = sequences.size() - 1;
lastPlayedIndex = -1;
}
}
juce::File HiseMidiSequence::writeToTempFile()
{
MidiFile f;
for (int i = 0; i < sequences.size(); i++)
{
f.addTrack(*sequences[i]);
}
auto tmp = File::getSpecialLocation(File::SpecialLocationType::tempDirectory).getNonexistentChildFile(id.toString(), ".mid");
tmp.create();
FileOutputStream fos(tmp);
f.writeTo(fos);
return tmp;
}
void HiseMidiSequence::setId(const Identifier& newId)
{
id = newId;
}
const juce::MidiMessageSequence* HiseMidiSequence::getReadPointer(int trackIndex) const
{
if (trackIndex == -1)
return sequences[currentTrackIndex];
return sequences[trackIndex];
}
juce::MidiMessageSequence* HiseMidiSequence::getWritePointer(int trackIndex)
{
if (trackIndex == -1)
return sequences[currentTrackIndex];
return sequences[trackIndex];
}
int HiseMidiSequence::getNumEvents() const
{
if(isPositiveAndBelow(currentTrackIndex, sequences.size()))
return sequences[currentTrackIndex]->getNumEvents();
return 0;
}
void HiseMidiSequence::setCurrentTrackIndex(int index)
{
if (isPositiveAndBelow(index, sequences.size()) && index != currentTrackIndex)
{
double lastTimestamp = 0.0;
SimpleReadWriteLock::ScopedReadLock sl(swapLock);
if (lastPlayedIndex != -1)
lastTimestamp = getReadPointer(currentTrackIndex)->getEventPointer(lastPlayedIndex)->message.getTimeStamp();
currentTrackIndex = jlimit<int>(0, sequences.size()-1, index);
if (lastPlayedIndex != -1)
lastPlayedIndex = getReadPointer(currentTrackIndex)->getNextIndexAtTime(lastTimestamp);
}
}
void HiseMidiSequence::resetPlayback()
{
lastPlayedIndex = -1;
}
void HiseMidiSequence::setPlaybackPosition(double normalisedPosition)
{
SimpleReadWriteLock::ScopedReadLock sl(swapLock);
if (auto s = getReadPointer(currentTrackIndex))
{
auto currentTimestamp = getLength() * normalisedPosition;
lastPlayedIndex = s->getNextIndexAtTime(currentTimestamp) - 1;
}
}
juce::RectangleList<float> HiseMidiSequence::getRectangleList(Rectangle<float> targetBounds) const
{
if (getLength() == 0.0)
return {};
SimpleReadWriteLock::ScopedReadLock sl(swapLock);
RectangleList<float> list;
if (auto s = getReadPointer(currentTrackIndex))
{
for (auto e : *s)
{
if (e->message.isNoteOn() && e->noteOffObject != nullptr)
{
auto x = (float)(e->message.getTimeStamp() / getLength());
auto w = (float)(e->noteOffObject->message.getTimeStamp() / getLength()) - x;
auto y = (float)(127 - e->message.getNoteNumber()) / 128.0f;
auto h = 1.0f / 128.0f;
list.add({ x, y, w, h });
}
}
}
if (!targetBounds.isEmpty())
{
auto scaler = AffineTransform::scale(targetBounds.getWidth(), targetBounds.getHeight());
list.transformAll(scaler);
}
return list;
}
Array<HiseEvent> HiseMidiSequence::getEventList(double sampleRate, double bpm)
{
Array<HiseEvent> newBuffer;
newBuffer.ensureStorageAllocated(getNumEvents());
Range<double> range = { 0.0, getLength() };
auto samplePerQuarter = (double)TempoSyncer::getTempoInSamples(bpm, sampleRate, TempoSyncer::Quarter);
uint16 eventIds[127];
uint16 currentEventId = 1;
memset(eventIds, 0, sizeof(uint16) * 127);
if (auto mSeq = getReadPointer())
{
for (const auto& ev : *mSeq)
{
auto m = ev->message;
auto timeStamp = (int)(samplePerQuarter * m.getTimeStamp() / (double)HiseMidiSequence::TicksPerQuarter);
HiseEvent newEvent(m);
newEvent.setTimeStamp(timeStamp);
if (newEvent.isNoteOn())
{
newEvent.setEventId(currentEventId);
eventIds[newEvent.getNoteNumber()] = currentEventId++;
}
if (newEvent.isNoteOff())
newEvent.setEventId(eventIds[newEvent.getNoteNumber()]);
newBuffer.add(newEvent);
}
}
return newBuffer;
}
void HiseMidiSequence::swapCurrentSequence(MidiMessageSequence* sequenceToSwap)
{
ScopedPointer<MidiMessageSequence> oldSequence = sequences[currentTrackIndex];
{
SimpleReadWriteLock::ScopedWriteLock sl(swapLock);
sequences.set(currentTrackIndex, sequenceToSwap, false);
}
oldSequence = nullptr;
}
MidiPlayer::EditAction::EditAction(WeakReference<MidiPlayer> currentPlayer_, const Array<HiseEvent>& newContent, double sampleRate_, double bpm_) :
UndoableAction(),
currentPlayer(currentPlayer_),
newEvents(newContent),
sampleRate(sampleRate_),
bpm(bpm_)
{
if (auto seq = currentPlayer->getCurrentSequence())
oldEvents = seq->getEventList(sampleRate, bpm);
if (currentPlayer == nullptr)
return;
if (auto seq = currentPlayer->getCurrentSequence())
sequenceId = seq->getId();
}
bool MidiPlayer::EditAction::perform()
{
if (currentPlayer != nullptr && currentPlayer->getSequenceId() == sequenceId)
{
writeArrayToSequence(currentPlayer->getCurrentSequence(),
newEvents,
currentPlayer->getMainController()->getBpm(),
currentPlayer->getSampleRate());
currentPlayer->updatePositionInCurrentSequence();
currentPlayer->sendSequenceUpdateMessage(sendNotificationAsync);
return true;
}
return false;
}
bool MidiPlayer::EditAction::undo()
{
if (currentPlayer != nullptr && currentPlayer->getSequenceId() == sequenceId)
{
writeArrayToSequence(currentPlayer->getCurrentSequence(),
oldEvents,
currentPlayer->getMainController()->getBpm(),
currentPlayer->getSampleRate());
currentPlayer->updatePositionInCurrentSequence();
currentPlayer->sendSequenceUpdateMessage(sendNotificationAsync);
return true;
}
return false;
}
void MidiPlayer::EditAction::writeArrayToSequence(HiseMidiSequence::Ptr destination, const Array<HiseEvent>& arrayToWrite, double bpm, double sampleRate)
{
if (destination == nullptr)
return;
ScopedPointer<MidiMessageSequence> newSeq = new MidiMessageSequence();
auto samplePerQuarter = (double)TempoSyncer::getTempoInSamples(bpm, sampleRate, TempoSyncer::Quarter);
for (const auto& e : arrayToWrite)
{
if (e.isEmpty())
continue;
auto timeStamp = ((double)e.getTimeStamp() / samplePerQuarter) * (double)HiseMidiSequence::TicksPerQuarter;
auto m = e.toMidiMesage();
m.setTimeStamp(timeStamp);
newSeq->addEvent(m);
}
newSeq->sort();
newSeq->updateMatchedPairs();
destination->swapCurrentSequence(newSeq.release());
}
MidiPlayer::MidiPlayer(MainController *mc, const String &id, ModulatorSynth* ) :
MidiProcessor(mc, id),
undoManager(new UndoManager())
{
addAttributeID(Stop);
addAttributeID(Play);
addAttributeID(Record);
addAttributeID(CurrentPosition);
addAttributeID(CurrentSequence);
addAttributeID(CurrentTrack);
addAttributeID(ClearSequences);
mc->addTempoListener(this);
}
MidiPlayer::~MidiPlayer()
{
getMainController()->removeTempoListener(this);
}
void MidiPlayer::tempoChanged(double newTempo)
{
ticksPerSample = MidiPlayerHelpers::samplesToTicks(1, newTempo, getSampleRate());
}
juce::ValueTree MidiPlayer::exportAsValueTree() const
{
ValueTree v = MidiProcessor::exportAsValueTree();
saveID(CurrentSequence);
saveID(CurrentTrack);
saveID(LoopEnabled);
ValueTree seq("MidiFiles");
for (int i = 0; i < currentSequences.size(); i++)
{
auto s = currentSequences[i]->exportAsValueTree();
s.setProperty("FileName", currentlyLoadedFiles[i].getReferenceString(), nullptr);
seq.addChild(s, -1, nullptr);
}
v.addChild(seq, -1, nullptr);
return v;
}
void MidiPlayer::restoreFromValueTree(const ValueTree &v)
{
MidiProcessor::restoreFromValueTree(v);
ValueTree seq = v.getChildWithName("MidiFiles");
clearSequences(dontSendNotification);
if (seq.isValid())
{
for (const auto& s : seq)
{
HiseMidiSequence::Ptr newSequence = new HiseMidiSequence();
newSequence->restoreFromValueTree(s);
PoolReference ref(getMainController(), s.getProperty("FileName", ""), FileHandlerBase::MidiFiles);
currentlyLoadedFiles.add(ref);
addSequence(newSequence, false);
}
}
loadID(CurrentSequence);
loadID(CurrentTrack);
loadID(LoopEnabled);
}
void MidiPlayer::addSequence(HiseMidiSequence::Ptr newSequence, bool select)
{
currentSequences.add(newSequence);
if (select)
{
currentSequenceIndex = currentSequences.size() - 1;
sendChangeMessage();
}
sendSequenceUpdateMessage(sendNotificationAsync);
}
void MidiPlayer::clearSequences(NotificationType notifyListeners)
{
if (undoManager != nullptr)
undoManager->clearUndoHistory();
currentSequences.clear();
currentlyLoadedFiles.clear();
currentSequenceIndex = -1;
currentlyRecordedEvents.clear();
recordState.store(RecordState::Idle);
if (notifyListeners != dontSendNotification)
{
for (auto l : sequenceListeners)
{
if (l != nullptr)
l->sequencesCleared();
}
}
}
hise::ProcessorEditorBody * MidiPlayer::createEditor(ProcessorEditor *parentEditor)
{
#if USE_BACKEND
return new MidiPlayerEditor(parentEditor);
#else
ignoreUnused(parentEditor);
jassertfalse;
return nullptr;
#endif
}
float MidiPlayer::getAttribute(int index) const
{
auto s = (SpecialParameters)index;
switch (s)
{
case CurrentPosition: return (float)getPlaybackPosition();
case CurrentSequence: return (float)(currentSequenceIndex + 1);
case CurrentTrack: return (float)(currentTrackIndex + 1);
case LoopEnabled: return loopEnabled ? 1.0f : 0.0f;
default:
break;
}
return 0.0f;
}
void MidiPlayer::setInternalAttribute(int index, float newAmount)
{
auto s = (SpecialParameters)index;
switch (s)
{
case CurrentPosition:
{
currentPosition = jlimit<double>(0.0, 1.0, (double)newAmount);
updatePositionInCurrentSequence();
break;
}
case CurrentSequence:
{
double lastLength = 0.0f;
if (auto seq = getCurrentSequence())
lastLength = seq->getLengthInQuarters();
currentSequenceIndex = jlimit<int>(-1, currentSequences.size(), (int)(newAmount - 1));
currentlyRecordedEvents.clear();
recordState.store(RecordState::Idle);
if (auto seq = getCurrentSequence())
{
double newLength = seq->getLengthInQuarters();
if (newLength > 0.0 && currentPosition >= 0.0)
{
double ratio = lastLength / newLength;
currentPosition = currentPosition * ratio;
updatePositionInCurrentSequence();
}
}
break;
}
case CurrentTrack:
{
currentTrackIndex = jmax<int>(0, (int)(newAmount - 1));
if(auto seq = getCurrentSequence())
seq->setCurrentTrackIndex(currentTrackIndex);
currentlyRecordedEvents.clear();
recordState.store(RecordState::Idle);
break;
}
case LoopEnabled: loopEnabled = newAmount > 0.5f; break;
default:
break;
}
}
void MidiPlayer::loadMidiFile(PoolReference reference)
{
PooledMidiFile newContent;
#if HISE_ENABLE_EXPANSIONS
if (auto e = getMainController()->getExpansionHandler().getExpansionForWildcardReference(reference.getReferenceString()))
newContent = e->pool->getMidiFilePool().loadFromReference(reference, PoolHelpers::LoadAndCacheWeak);
else
newContent = getMainController()->getCurrentMidiFilePool()->loadFromReference(reference, PoolHelpers::LoadAndCacheWeak);
#else
newContent = getMainController()->getCurrentMidiFilePool()->loadFromReference(reference, PoolHelpers::LoadAndCacheWeak);
#endif
if (newContent.get() != nullptr)
{
currentlyLoadedFiles.add(reference);
HiseMidiSequence::Ptr newSequence = new HiseMidiSequence();
newSequence->loadFrom(newContent->data.getFile());
//newSequence->setId(reference.getFile().getFileNameWithoutExtension());
addSequence(newSequence);
}
else
jassertfalse;
}
void MidiPlayer::prepareToPlay(double sampleRate_, int samplesPerBlock_)
{
MidiProcessor::prepareToPlay(sampleRate_, samplesPerBlock_);
tempoChanged(getMainController()->getBpm());
}
void MidiPlayer::preprocessBuffer(HiseEventBuffer& buffer, int numSamples)
{
lastBlockSize = numSamples;
if (currentSequenceIndex >= 0 && currentPosition != -1.0)
{
if (currentPosition > 1.0 && !loopEnabled)
{
stop();
return;
}
if (isRecording() && (currentPosition - recordStart) > 1.0)
{
finishRecording();
playState = PlayState::Play;
sendAllocationFreeChangeMessage();
}
auto seq = getCurrentSequence();
seq->setCurrentTrackIndex(currentTrackIndex);
auto tickThisTime = (numSamples - timeStampForNextCommand) * ticksPerSample;
auto lengthInTicks = seq->getLength();
if (lengthInTicks == 0.0)
return;
auto positionInTicks = getPlaybackPosition() * lengthInTicks;
auto delta = tickThisTime / lengthInTicks;
Range<double> currentRange;
if(loopEnabled)
currentRange = { positionInTicks, positionInTicks + tickThisTime };
else
currentRange = { positionInTicks, jmin<double>(lengthInTicks, positionInTicks + tickThisTime) };
while (auto e = seq->getNextEvent(currentRange))
{
auto timeStampInThisBuffer = e->getTimeStamp() - positionInTicks;
if (timeStampInThisBuffer < 0.0)
timeStampInThisBuffer += lengthInTicks;
auto timeStamp = (int)MidiPlayerHelpers::ticksToSamples(timeStampInThisBuffer, getMainController()->getBpm(), getSampleRate());
timeStamp += timeStampForNextCommand;
jassert(isPositiveAndBelow(timeStamp, numSamples));
HiseEvent newEvent(*e);
newEvent.setTimeStamp(timeStamp);
newEvent.setArtificial();
if (newEvent.isNoteOn() && !isBypassed())
{
getMainController()->getEventHandler().pushArtificialNoteOn(newEvent);
buffer.addEvent(newEvent);
if (auto noteOff = seq->getMatchingNoteOffForCurrentEvent())
{
HiseEvent newNoteOff(*noteOff);
newNoteOff.setArtificial();
auto noteOffTimeStampInBuffer = noteOff->getTimeStamp() - positionInTicks;
if (noteOffTimeStampInBuffer < 0.0)
noteOffTimeStampInBuffer += lengthInTicks;
timeStamp += timeStampForNextCommand;
auto noteOffTimeStamp = (int)MidiPlayerHelpers::ticksToSamples(noteOffTimeStampInBuffer, getMainController()->getBpm(), getSampleRate());
auto on_id = getMainController()->getEventHandler().getEventIdForNoteOff(newNoteOff);
jassert(newEvent.getEventId() == on_id);
newNoteOff.setEventId(on_id);
newNoteOff.setTimeStamp(noteOffTimeStamp);
if (noteOffTimeStamp < numSamples)
buffer.addEvent(newNoteOff);
else
addHiseEventToBuffer(newNoteOff);
}
}
}
timeStampForNextCommand = 0;
currentPosition += delta;
}
}
void MidiPlayer::processHiseEvent(HiseEvent &m) noexcept
{
currentTimestampInBuffer = m.getTimeStamp();
if (isBypassed())
return;
if (isRecording() && !m.isArtificial() && recordState == RecordState::Prepared)
{
if (auto seq = getCurrentSequence())
{
if (useNextNoteAsRecordStartPos)
{
recordStart = currentPosition;
useNextNoteAsRecordStartPos = false;
}
auto lengthInQuarters = seq->getLengthInQuarters() * getPlaybackPosition();
auto ticks = lengthInQuarters * HiseMidiSequence::TicksPerQuarter;
auto timestampSamples = (int)MidiPlayerHelpers::ticksToSamples(ticks, getMainController()->getBpm(), getSampleRate());
// This will be processed after the position has advanced so we need to subtract the last blocksize and add the message's timestamp.
timestampSamples -= lastBlockSize;
timestampSamples += currentTimestampInBuffer;
HiseEvent copy(m);
copy.setTimeStamp(timestampSamples);
currentlyRecordedEvents.add(copy);
}
}
}
void MidiPlayer::addSequenceListener(SequenceListener* newListener)
{
sequenceListeners.addIfNotAlreadyThere(newListener);
}
void MidiPlayer::removeSequenceListener(SequenceListener* listenerToRemove)
{
sequenceListeners.removeAllInstancesOf(listenerToRemove);
}
void MidiPlayer::sendSequenceUpdateMessage(NotificationType notification)
{
auto update = [this]()
{
for (auto l : sequenceListeners)
{
if (l != nullptr)
l->sequenceLoaded(getCurrentSequence());
}
};
if (notification == sendNotificationAsync)
MessageManager::callAsync(update);
else
update();
}
void MidiPlayer::changeTransportState(PlayState newState)
{
switch (newState)
{ // Supposed to be immediately...
case PlayState::Play: play(0); return;
case PlayState::Stop: stop(0); return;
case PlayState::Record: record(0); return;
}
}
hise::HiseMidiSequence* MidiPlayer::getCurrentSequence() const
{
return currentSequences[currentSequenceIndex].get();
}
juce::Identifier MidiPlayer::getSequenceId(int index) const
{
if (index == -1)
index = currentSequenceIndex;
if (auto s = currentSequences[index])
{
return s->getId();
}
return {};
}
double MidiPlayer::getPlaybackPosition() const
{
return fmod(currentPosition, 1.0);
}
void MidiPlayer::swapCurrentSequence(MidiMessageSequence* newSequence)
{
getCurrentSequence()->swapCurrentSequence(newSequence);
updatePositionInCurrentSequence();
sendSequenceUpdateMessage(sendNotificationAsync);
}
void MidiPlayer::setEnableUndoManager(bool shouldBeEnabled)
{
bool isEnabled = undoManager != nullptr;
if (isEnabled != shouldBeEnabled)
{
undoManager = nullptr;
if (isEnabled)
undoManager = new UndoManager();
}
}
void MidiPlayer::flushEdit(const Array<HiseEvent>& newEvents)
{
ScopedPointer<EditAction> newAction = new EditAction(this, newEvents, getSampleRate(), getMainController()->getBpm());
if (undoManager != nullptr)
{
undoManager->beginNewTransaction();
undoManager->perform(newAction.release());
}
else
newAction->perform();
}
void MidiPlayer::clearCurrentSequence()
{
currentlyRecordedEvents.clear();
flushEdit({});
}
void MidiPlayer::resetCurrentSequence()
{
if (auto seq = getCurrentSequence())
{
auto original = getMainController()->getCurrentMidiFilePool()->loadFromReference(currentlyLoadedFiles[currentSequenceIndex], PoolHelpers::LoadAndCacheWeak);
ScopedPointer<HiseMidiSequence> tempSeq = new HiseMidiSequence();
tempSeq->loadFrom(original->data.getFile());
auto l = tempSeq->getEventList(getSampleRate(), getMainController()->getBpm());
flushEdit(l);
}
}
hise::PoolReference MidiPlayer::getPoolReference(int index /*= -1*/)
{
if (index == -1)
index = currentSequenceIndex;
return currentlyLoadedFiles[index];
}
bool MidiPlayer::play(int timestamp)
{
sendAllocationFreeChangeMessage();
if (auto seq = getCurrentSequence())
{
if (isRecording())
finishRecording();
else
{
// This allows switching from record to play while maintaining the position
currentPosition = 0.0;
seq->resetPlayback();
}
playState = PlayState::Play;
timeStampForNextCommand = timestamp;
return true;
}
return false;
}
bool MidiPlayer::stop(int timestamp)
{
sendAllocationFreeChangeMessage();
if (auto seq = getCurrentSequence())
{
if (isRecording())
finishRecording();
seq->resetPlayback();
playState = PlayState::Stop;
timeStampForNextCommand = timestamp;
currentPosition = -1.0;
return true;
}
return false;
}
bool MidiPlayer::record(int timestamp)
{
sendAllocationFreeChangeMessage();
if (playState == PlayState::Stop)
{
currentPosition = 0.0;
if(auto seq = getCurrentSequence())
seq->resetPlayback();
}
playState = PlayState::Record;
timeStampForNextCommand = timestamp;
currentPosition = fmod(currentPosition, 1.0);
useNextNoteAsRecordStartPos = true;
if (recordState == RecordState::Idle)
prepareForRecording(true);
return false;
}
void MidiPlayer::prepareForRecording(bool copyExistingEvents/*=true*/)
{
auto f = [copyExistingEvents](Processor* p)
{
auto mp = static_cast<MidiPlayer*>(p);
Array<HiseEvent> newEvents;
if (auto seq = mp->getCurrentSequence())
{
if (copyExistingEvents)
{
auto newList = seq->getEventList(p->getSampleRate(), p->getMainController()->getBpm());
newEvents.swapWith(newList);
}
}
newEvents.ensureStorageAllocated(2048);
mp->currentlyRecordedEvents.swapWith(newEvents);
mp->recordState.store(RecordState::Prepared);
return SafeFunctionCall::OK;
};
recordState.store(RecordState::PreparationPending);
getMainController()->getSampleManager().addDeferredFunction(this, f);
}
void MidiPlayer::finishRecording()
{
auto f = [](Processor* p)
{
auto mp = static_cast<MidiPlayer*>(p);
auto& l = mp->currentlyRecordedEvents;
int lastTimestamp = (int)MidiPlayerHelpers::ticksToSamples(mp->getCurrentSequence()->getLength(), mp->getMainController()->getBpm(), mp->getSampleRate()) - 1;
for (int i = 0; i < l.size(); i++)
{
auto currentEvent = l[i];
if (currentEvent.isNoteOn())
{
bool found = false;
for (int j = 0; j < l.size(); j++)
{
if (l[j].isNoteOff() && l[j].getEventId() == currentEvent.getEventId())
{
if (l[j].getTimeStamp() < currentEvent.getTimeStamp())
{
l.getReference(j).setTimeStamp(lastTimestamp);
}
found = true;
break;
}
}
if (!found)
{
HiseEvent artificialNoteOff(HiseEvent::Type::NoteOff, (uint8)currentEvent.getNoteNumber(), 1, (uint8)currentEvent.getChannel());
artificialNoteOff.setTimeStamp(lastTimestamp);
artificialNoteOff.setEventId(currentEvent.getEventId());
l.add(artificialNoteOff);
}
}
if (currentEvent.isNoteOff())
{
bool found = false;
for (int j = 0; j < l.size(); j++)
{
if (l[j].isNoteOn() && currentEvent.getEventId() == l[j].getEventId())
{
found = true;
break;
}
}
if (!found)
l.remove(i--);
}
}
mp->flushEdit(mp->currentlyRecordedEvents);
// This is a shortcut because the preparation would just fill it with the current sequence.
mp->recordState.store(RecordState::Prepared);
return SafeFunctionCall::OK;
};
getMainController()->getSampleManager().addDeferredFunction(this, f);
recordState.store(RecordState::FlushPending);
}
hise::HiseMidiSequence::Ptr MidiPlayer::getListOfCurrentlyRecordedEvents()
{
HiseMidiSequence::Ptr recordedList = new HiseMidiSequence();
recordedList->createEmptyTrack();
EditAction::writeArrayToSequence(recordedList, currentlyRecordedEvents, getMainController()->getBpm(), getSampleRate());
return recordedList;
}
bool MidiPlayer::saveAsMidiFile(const String& fileName, int trackIndex)
{
trackIndex -= 1;
if (getCurrentSequence() == nullptr)
return false;
if (auto track = getCurrentSequence()->getReadPointer(currentTrackIndex))
{
PoolReference r(getMainController(), fileName, FileHandlerBase::MidiFiles);
auto pool = getMainController()->getCurrentMidiFilePool();
if (r.getFile().existsAsFile())
{
if (auto mf = pool->loadFromReference(r, PoolHelpers::ForceReloadStrong))
{
MidiFile& existingFile = mf->data.getFile();
if (trackIndex < existingFile.getNumTracks())
{
MidiFile copy;
for (int i = 0; i < existingFile.getNumTracks(); i++)
copy.addTrack(i == trackIndex ? *track : *existingFile.getTrack(i));
r.getFile().deleteFile();
r.getFile().create();
FileOutputStream fos(r.getFile());
bool ok = copy.writeTo(fos);
pool->loadFromReference(r, PoolHelpers::ForceReloadStrong);
return ok;
}
else
{
for (int i = existingFile.getNumTracks(); i < trackIndex; i++)
{
MidiMessageSequence empty;
empty.addEvent(MidiMessage::pitchWheel(1, 8192));
existingFile.addTrack(empty);
}
existingFile.addTrack(*track);
r.getFile().deleteFile();
r.getFile().create();
FileOutputStream fos(r.getFile());
bool ok = existingFile.writeTo(fos);
pool->loadFromReference(r, PoolHelpers::ForceReloadStrong);
return ok;
}
}
}
else
{
MidiFile newFile;
for (int i = 0; i < trackIndex; i++)
{
MidiMessageSequence empty;
empty.addEvent(MidiMessage::tempoMetaEvent(HiseMidiSequence::TicksPerQuarter));
newFile.addTrack(empty);
}
newFile.addTrack(*track);
r.getFile().create();
FileOutputStream fos(r.getFile());
bool ok = newFile.writeTo(fos);
pool->loadFromReference(r, PoolHelpers::ForceReloadStrong);
return ok;
}
}
return false;
}
void MidiPlayer::updatePositionInCurrentSequence()
{
if (auto seq = getCurrentSequence())
{
seq->setPlaybackPosition(getPlaybackPosition());
}
}
MidiPlayerBaseType::~MidiPlayerBaseType()
{
if (player != nullptr)
{
player->removeSequenceListener(this);
player->removeChangeListener(this);
}
}
MidiPlayerBaseType::MidiPlayerBaseType(MidiPlayer* player_) :
player(player_),
font(GLOBAL_BOLD_FONT())
{
initMidiPlayer(player);
}
void MidiPlayerBaseType::initMidiPlayer(MidiPlayer* newPlayer)
{
player = newPlayer;
if (player != nullptr)
{
player->addSequenceListener(this);
player->addChangeListener(this);
}
}
void MidiPlayerBaseType::changeListenerCallback(SafeChangeBroadcaster* )
{
int thisSequence = (int)getPlayer()->getAttribute(MidiPlayer::CurrentSequence);
if (thisSequence != lastSequenceIndex)
{
lastSequenceIndex = thisSequence;
sequenceIndexChanged();
}
int trackIndex = (int)getPlayer()->getAttribute(MidiPlayer::CurrentTrack);
if (trackIndex != lastTrackIndex)
{
lastTrackIndex = trackIndex;
trackIndexChanged();
}
}
}
| 23.545588
| 160
| 0.721129
|
Levitanus
|
0a6e05730321c02eba15a1d170ee46a9d3b094bd
| 280
|
cc
|
C++
|
string_literal.cc
|
micahcc/ctest
|
af2a789a8c610f83a7e6ef55c371c64a41492e85
|
[
"MIT"
] | null | null | null |
string_literal.cc
|
micahcc/ctest
|
af2a789a8c610f83a7e6ef55c371c64a41492e85
|
[
"MIT"
] | null | null | null |
string_literal.cc
|
micahcc/ctest
|
af2a789a8c610f83a7e6ef55c371c64a41492e85
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <string>
template <int N>
void foo(const char input[N]) {
std::cerr << input << std::endl;
}
int main() {
// char* str1 = "str1";
std::string str2 = "str2";
const auto str3 = "str3";
// foo(str1);
// foo(str2.c_str());
// foo(str3);
}
| 16.470588
| 34
| 0.571429
|
micahcc
|
0a6e69cb2fed7c9e54171ae2dee701196e9e2aa6
| 3,048
|
cpp
|
C++
|
main.cpp
|
subite/Profiler
|
18dcaca864af8be75baf53adad6b2b572a8d1c4c
|
[
"WTFPL"
] | null | null | null |
main.cpp
|
subite/Profiler
|
18dcaca864af8be75baf53adad6b2b572a8d1c4c
|
[
"WTFPL"
] | null | null | null |
main.cpp
|
subite/Profiler
|
18dcaca864af8be75baf53adad6b2b572a8d1c4c
|
[
"WTFPL"
] | null | null | null |
#include <iostream>
#include "Profiler.h"
#include "ProfilerUtils.h"
#include <chrono>
#include <thread>
#include <random>
#include <fstream>
using namespace std::chrono_literals;
using namespace Profiler;
namespace {
std::random_device rd_fun;
std::mt19937 gen_fun(rd_fun());
std::uniform_int_distribution<> dis_fun(1, 10);
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(1, 100);
void func_1();
void func_2();
void func_3();
void func_4();
void func_5();
void func_6();
void func_7();
void func_8();
void func_9();
void func_1() {
PTimePoint all("func_1");
std::this_thread::sleep_for(std::chrono::milliseconds(dis(gen)));
int r = dis_fun(gen_fun);
if (r <= 1)
func_9();
}
void func_2() {
PTimePoint all("func_2");
std::this_thread::sleep_for(std::chrono::milliseconds(dis(gen)));
int r = dis_fun(gen_fun);
if (r <= 2)
func_1();
}
void func_3() {
PTimePoint all("func_3");
std::this_thread::sleep_for(std::chrono::milliseconds(dis(gen)));
int r = dis_fun(gen_fun);
if (r <= 3)
func_2();
}
void func_4() {
PTimePoint all("func_4");
std::this_thread::sleep_for(std::chrono::milliseconds(dis(gen)));
int r = dis_fun(gen_fun);
if (r <= 4)
func_3();
}
void func_5() {
PTimePoint all("func_5");
std::this_thread::sleep_for(std::chrono::milliseconds(dis(gen)));
int r = dis_fun(gen_fun);
if (r <= 5)
func_4();
}
void func_6() {
PTimePoint all("func_6");
std::this_thread::sleep_for(std::chrono::milliseconds(dis(gen)));
int r = dis_fun(gen_fun);
if (r <= 6)
func_5();
}
void func_7() {
PTimePoint all("func_7");
std::this_thread::sleep_for(std::chrono::milliseconds(dis(gen)));
int r = dis_fun(gen_fun);
if (r <= 7)
func_6();
}
void func_8() {
PTimePoint all("func_8");
std::this_thread::sleep_for(std::chrono::milliseconds(dis(gen)));
int r = dis_fun(gen_fun);
if (r <= 8)
func_7();
}
void func_9() {
PTimePoint all("func_9");
std::this_thread::sleep_for(std::chrono::milliseconds(dis(gen)));
int r = dis_fun(gen_fun);
if (r <= 9)
func_8();
}
}
struct RealTimeConfig {
typedef typename std::chrono::system_clock clock;
typedef typename std::chrono::duration<uint32_t, std::micro> duration;
};
int main() {
Profiler::PTimeline<RealTimeConfig, 1000> timeline("MainStart");
{
PTimePoint all("Global scope");
for (int i = 1; i < 100; ++i) {
int r = dis_fun(gen_fun);
switch(r) {
case 1: func_1(); break;
case 2: func_2(); break;
case 3: func_3(); break;
case 4: func_4(); break;
case 5: func_5(); break;
case 6: func_6(); break;
case 7: func_7(); break;
case 8: func_8(); break;
default: func_9(); break;
}
//PTimePoint loop("Inner scope");
//std::this_thread::sleep_for(std::chrono::milliseconds(dis(gen)));
}
}
timeline.stop();
std::ofstream file;
file.open ("timeline.json");
toChromeTracingFormat(file, timeline);
file.flush();
file.close();
return 0;
}
| 21.771429
| 73
| 0.634186
|
subite
|
0a6f7e39a93cf14eae67224eb8b7309525cb499b
| 1,610
|
cpp
|
C++
|
CSES/GraphAlgorithms/building_roads.cpp
|
PranavReddyP16/DSA-Templates
|
cb68b1ced5fd4990a413ce88cdb741fdcaa6e89b
|
[
"MIT"
] | null | null | null |
CSES/GraphAlgorithms/building_roads.cpp
|
PranavReddyP16/DSA-Templates
|
cb68b1ced5fd4990a413ce88cdb741fdcaa6e89b
|
[
"MIT"
] | null | null | null |
CSES/GraphAlgorithms/building_roads.cpp
|
PranavReddyP16/DSA-Templates
|
cb68b1ced5fd4990a413ce88cdb741fdcaa6e89b
|
[
"MIT"
] | null | null | null |
#include "bits/stdc++.h"
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
using namespace std::chrono;
#define ll long long
#define ld long double
#define sz(c) ((ll)c.size())
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
#define int ll
const ll inf = 1e18;
const int mod = 1e9 + 7;
const int mod2 = 998244353;
high_resolution_clock::time_point curTime() { return high_resolution_clock::now(); }
#define rep(i,n) for(int i=0;i<n;i++)
vector<int> parent;
vector<int> siz;
int root(int u)
{
while(parent[u]!=u) u = parent[u];
return u;
}
void merge(int u, int v)
{
u = root(u);
v = root(v);
if(u==v) return;
if(siz[u]<siz[v]) swap(u,v);
parent[v] = u;
siz[u] += siz[v];
}
signed main()
{
ios_base :: sync_with_stdio(false);
cin.tie(NULL);
auto startTime = curTime();
int n,m;
cin>>n>>m;
parent.resize(n);
siz.resize(n,1);
for(int i=0;i<n;i++) parent[i] = i;
for(int i=0;i<m;i++)
{
int u,v;
cin>>u>>v;
u--;v--;
merge(u,v);
}
set<int> nodes;
for(int i=0;i<n;i++) nodes.insert(root(i));
vector<int> ans;
for(int x : nodes) ans.push_back(x+1);
cout<<sz(ans)-1<<endl;
for(int i=0;i<sz(ans)-1;i++)
{
cout<<ans[i]<<" "<<ans[i+1]<<endl;
}
auto stopTime = curTime();
auto duration = duration_cast<microseconds>(stopTime - startTime);
//cout<<"Program ran for "<<(ld)duration.count()/1e6<<" "<<"seconds"<<endl;
}
| 19.634146
| 97
| 0.59441
|
PranavReddyP16
|
0a70427ff033d54a99ca6629a224bd9379aeb86e
| 6,582
|
cpp
|
C++
|
samples/threat_level/src/HudDirector.cpp
|
fallahn/crogine
|
f6cf3ade1f4e5de610d52e562bf43e852344bca0
|
[
"FTL",
"Zlib"
] | 41
|
2017-08-29T12:14:36.000Z
|
2022-02-04T23:49:48.000Z
|
samples/threat_level/src/HudDirector.cpp
|
fallahn/crogine
|
f6cf3ade1f4e5de610d52e562bf43e852344bca0
|
[
"FTL",
"Zlib"
] | 11
|
2017-09-02T15:32:45.000Z
|
2021-12-27T13:34:56.000Z
|
samples/threat_level/src/HudDirector.cpp
|
fallahn/crogine
|
f6cf3ade1f4e5de610d52e562bf43e852344bca0
|
[
"FTL",
"Zlib"
] | 5
|
2020-01-25T17:51:45.000Z
|
2022-03-01T05:20:30.000Z
|
/*-----------------------------------------------------------------------
Matt Marchant 2017
http://trederia.blogspot.com
crogine test application - Zlib license.
This software is provided 'as-is', without any express or
implied warranty.In no event will the authors be held
liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute
it freely, subject to the following restrictions :
1. The origin of this software must not be misrepresented;
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but
is not required.
2. Altered source versions must be plainly marked as such,
and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any
source distribution.
-----------------------------------------------------------------------*/
#include "HudDirector.hpp"
#include "HudItems.hpp"
#include "Messages.hpp"
#include "ItemSystem.hpp"
#include "ResourceIDs.hpp"
#include <crogine/ecs/components/Sprite.hpp>
#include <crogine/ecs/components/Transform.hpp>
#include <crogine/ecs/components/Callback.hpp>
#include <crogine/ecs/components/Model.hpp>
#include <crogine/ecs/systems/CommandSystem.hpp>
#include <crogine/ecs/Scene.hpp>
#include <crogine/core/Clock.hpp>
HudDirector::HudDirector()
: m_fireMode(0)
{
}
//public
void HudDirector::handleEvent(const cro::Event&)
{
}
void HudDirector::handleMessage(const cro::Message& msg)
{
if (msg.id == MessageID::PlayerMessage)
{
const auto& data = msg.getData<PlayerEvent>();
switch (data.type)
{
default:break;
case PlayerEvent::CollectedItem:
if (data.itemID == CollectableItem::Bomb ||
data.itemID == CollectableItem::EMP)
{
auto id = data.itemID;
cro::Command cmd;
cmd.targetFlags = CommandID::HudElement;
cmd.action = [&, id](cro::Entity entity, float)
{
const auto& hudItem = entity.getComponent<HudItem>();
if ((hudItem.type == HudItem::Type::Bomb && id == CollectableItem::Bomb) ||
(hudItem.type == HudItem::Type::Emp && id == CollectableItem::EMP))
{
entity.getComponent<cro::Sprite>().setColour(cro::Colour::Cyan);
if (hudItem.type == HudItem::Type::Emp)
{
auto childEnt = hudItem.child;
childEnt.getComponent<cro::Callback>().active = true;
}
}
};
sendCommand(cmd);
}
break;
case PlayerEvent::Died:
{
cro::Command cmd;
cmd.targetFlags = CommandID::HudElement;
cmd.action = [&](cro::Entity entity, float)
{
const auto& hudItem = entity.getComponent<HudItem>();
if (hudItem.type == HudItem::Type::Emp)
{
entity.getComponent<cro::Sprite>().setColour(cro::Colour::White);
auto childEnt = hudItem.child;
childEnt.getComponent<cro::Callback>().active = false;
childEnt.getComponent<cro::Model>().setMaterialProperty(0, "u_time", 0.f);
}
};
sendCommand(cmd);
}
//yes, this is meant to fall through.
case PlayerEvent::GotLife:
{
std::int32_t lives = static_cast<std::int32_t>(data.value);
cro::Command cmd;
cmd.targetFlags = CommandID::HudElement;
cmd.action = [lives](cro::Entity entity, float)
{
const auto& hudItem = entity.getComponent<HudItem>();
if (hudItem.type == HudItem::Type::Life)
{
if (hudItem.value < lives)
{
entity.getComponent<cro::Sprite>().setColour(cro::Colour::Cyan);
}
else
{
entity.getComponent<cro::Sprite>().setColour(cro::Colour::White);
}
}
};
sendCommand(cmd);
if (data.type != PlayerEvent::Died)
{
//do a popup
cmd.targetFlags = CommandID::MeatMan;
cmd.action = [](cro::Entity entity, float)
{
entity.getComponent<cro::Callback>().active = true;
};
sendCommand(cmd);
}
}
break;
case PlayerEvent::FiredEmp:
{
cro::Command cmd;
cmd.targetFlags = CommandID::HudElement;
cmd.action = [&](cro::Entity entity, float)
{
const auto& hudItem = entity.getComponent<HudItem>();
if (hudItem.type == HudItem::Type::Emp)
{
entity.getComponent<cro::Sprite>().setColour(cro::Colour::White);
auto childEnt = hudItem.child;
childEnt.getComponent<cro::Callback>().active = false;
childEnt.getComponent<cro::Model>().setMaterialProperty(0, "u_time", 0.f);
}
};
sendCommand(cmd);
}
break;
}
}
else if (msg.id == MessageID::WeaponMessage)
{
const auto& data = msg.getData<WeaponEvent>();
if (data.fireMode != m_fireMode)
{
auto mode = data.fireMode + 1;
cro::Command cmd;
cmd.targetFlags = CommandID::HudElement;
cmd.action = [mode](cro::Entity entity, float)
{
if (entity.getComponent<HudItem>().type == HudItem::Type::TimerIcon)
{
auto& sprite = entity.getComponent<cro::Sprite>();
auto subrect = sprite.getTextureRect();
auto size = sprite.getSize();
subrect.left = mode * size.x;
sprite.setTextureRect(subrect);
}
};
sendCommand(cmd);
m_fireMode = data.fireMode;
}
}
}
void HudDirector::process(float)
{
}
| 34.825397
| 95
| 0.520207
|
fallahn
|
0a7d538c60008cbb21ab8cba7e37d547cb0aa318
| 357
|
hpp
|
C++
|
cpp/pong/src/ceiling_floor.hpp
|
prakhar-s-srivastava/gdnative-demos
|
83ed7e1248e69b63df256757434a7b74f9c32e51
|
[
"MIT"
] | 83
|
2020-07-06T16:26:13.000Z
|
2022-03-28T22:43:30.000Z
|
cpp/pong/src/ceiling_floor.hpp
|
prakhar-s-srivastava/gdnative-demos
|
83ed7e1248e69b63df256757434a7b74f9c32e51
|
[
"MIT"
] | 25
|
2020-06-28T02:43:41.000Z
|
2022-02-24T10:05:01.000Z
|
cpp/pong/src/ceiling_floor.hpp
|
prakhar-s-srivastava/gdnative-demos
|
83ed7e1248e69b63df256757434a7b74f9c32e51
|
[
"MIT"
] | 31
|
2020-07-10T13:51:22.000Z
|
2022-03-07T19:40:34.000Z
|
#ifndef CEILING_FLOOR_H
#define CEILING_FLOOR_H
#include <Area2D.hpp>
#include <Godot.hpp>
#include "ball.hpp"
class CeilingFloor : public godot::Area2D {
GODOT_CLASS(CeilingFloor, godot::Area2D)
public:
int bounce_direction = 1;
void _init() {}
void _on_area_entered(Ball *p_ball);
static void _register_methods();
};
#endif // CEILING_FLOOR_H
| 16.227273
| 43
| 0.747899
|
prakhar-s-srivastava
|
0a9020ca8071483a6f7f444d60257dfc5b8624bf
| 768
|
hpp
|
C++
|
include/managers/event_manager.hpp
|
zedrex/algosketch
|
ff0f759f9e7e0e4ff040cf6c84334aceac47adae
|
[
"MIT"
] | 16
|
2021-03-27T06:20:42.000Z
|
2022-03-31T16:30:37.000Z
|
include/managers/event_manager.hpp
|
zedrex/Algo-Plus-Plus
|
ff0f759f9e7e0e4ff040cf6c84334aceac47adae
|
[
"MIT"
] | 1
|
2021-07-13T07:57:41.000Z
|
2021-07-13T07:57:41.000Z
|
include/managers/event_manager.hpp
|
zedrex/Algo-Plus-Plus
|
ff0f759f9e7e0e4ff040cf6c84334aceac47adae
|
[
"MIT"
] | 3
|
2021-04-03T02:58:56.000Z
|
2021-06-04T18:23:49.000Z
|
#pragma once
#include <SFML/Graphics.hpp>
// Forward declaration of StateManager
class StateManager;
class EventManager
{
public:
EventManager(StateManager *applicationStateManager);
~EventManager();
void update();
sf::Vector2i getMousePosition();
bool isLeftKeyPressed();
bool isLeftKeyReleased();
bool isLeftKeyHeld();
bool isRightKeyPressed();
bool isRightKeyReleased();
bool isRightKeyHeld();
std::string getCurrentKey();
private:
StateManager *stateManager;
std::string lastKey;
bool leftButtonPressed;
bool leftButtonReleased;
bool leftButtonHeld;
bool rightButtonPressed;
bool rightButtonReleased;
bool rightButtonHeld;
sf::Clock inputClock;
static float inputDelay;
};
| 20.210526
| 56
| 0.716146
|
zedrex
|
0a916cd4d0abf471e6f945802d8fe3afbd6ef2b7
| 1,892
|
cpp
|
C++
|
S3DR/lib/src/operator/camera_operator.cpp
|
tdenis8/S3DR
|
fb8f4c0c98b5571abb12a51e03229978115b099b
|
[
"MIT"
] | 1
|
2019-07-10T04:25:45.000Z
|
2019-07-10T04:25:45.000Z
|
S3DR/lib/src/operator/camera_operator.cpp
|
tdenis8/S3DR
|
fb8f4c0c98b5571abb12a51e03229978115b099b
|
[
"MIT"
] | null | null | null |
S3DR/lib/src/operator/camera_operator.cpp
|
tdenis8/S3DR
|
fb8f4c0c98b5571abb12a51e03229978115b099b
|
[
"MIT"
] | null | null | null |
#include "camera_operator.hpp"
#include "view/view.hpp"
#include "view/camera.hpp"
#include <glm/gtc/matrix_transform.hpp>
CameraOperator::CameraOperator(View& view) : Operator(view)
{
}
CameraOperator::~CameraOperator()
{
}
int CameraOperator::OnLeftButtonDownAndMove(const MouseEventInfo& info)
{
auto& camera = view.GetCamera();
camera.RotateCamera(info.YDelta() / 10.0f, glm::vec3(1.0f, 0.0f, 0.0f));
camera.RotateCamera(info.XDelta() / 10.0f, glm::vec3(0.0f, 1.0f, 0.0f));
return 1;
}
int CameraOperator::OnRightButtonDownAndMove(const MouseEventInfo& info)
{
auto& camera = view.GetCamera();
camera.MoveCamera(info.XDelta() / 10.0f, info.YDelta() / 10.f);
return 1;
}
#include <iostream>
int CameraOperator::OnMouseWheel(const MouseEventInfo& info)
{
auto& camera = view.GetCamera();
camera.ChangeFieldOfView(info.WheelDelta());
// float width = projection.Width();
// float height = projection.Height();
// auto & camera = view.GetCamera();
// std::cout<<"Mx: "<< ((width/2.0)-info.X())/20.0f<<std::endl;
// std::cout<<"My: "<< ((height/2.0)-info.Y())/20.f<<std::endl;
// camera.MoveCamera(-((width/2.0)-info.X())/20.0f, -((height/2.0)-info.Y())/20.f);
return 1;
}
// Utility functions
glm::vec3 CameraOperator::MousePosition(const MouseEventInfo& info) const
{
auto& camera = view.GetCamera();
float width = camera.GetWidth();
float height = camera.GetHeight();
int screen_x = info.X();
int screen_y = info.Y();
float screen_z = view.ScreenDepthAt(screen_x, screen_y);
if (1 - screen_z < 1e-7)
{
screen_z = 0.05;
}
glm::vec3 world_positon = glm::unProject(glm::vec3(screen_x, height - screen_y - 1, screen_z), camera.GetViewMatrix(),
camera.GetProjectionMatrix(), glm::vec4(0.0f, 0.0f, width, height));
return world_positon;
}
| 27.823529
| 121
| 0.649577
|
tdenis8
|
0a92228a652f950e7845de791f6285f519e51153
| 37
|
cpp
|
C++
|
src/fifo.cpp
|
abwilson/LowLatency
|
cefc780eccb0426f8fe99f5f59dce347c98f13aa
|
[
"MIT"
] | 31
|
2015-06-26T16:38:18.000Z
|
2022-03-01T03:28:08.000Z
|
src/fifo.cpp
|
abwilson/LowLatency
|
cefc780eccb0426f8fe99f5f59dce347c98f13aa
|
[
"MIT"
] | 1
|
2015-07-25T22:36:40.000Z
|
2015-07-25T22:36:40.000Z
|
src/fifo.cpp
|
abwilson/LowLatency
|
cefc780eccb0426f8fe99f5f59dce347c98f13aa
|
[
"MIT"
] | 9
|
2015-06-26T18:44:31.000Z
|
2019-09-04T15:13:31.000Z
|
#include <../include/L3/util/fifo.h>
| 18.5
| 36
| 0.675676
|
abwilson
|
0a95d2a57fc5b505a897d74485e79173b8b16250
| 961
|
tcc
|
C++
|
raftinc/klayer.tcc
|
mr-j0nes/RaftLib
|
19b2b5401365ba13788044bfbcca0820f48b650a
|
[
"Apache-2.0"
] | 2
|
2019-08-27T11:08:18.000Z
|
2021-09-06T12:05:23.000Z
|
raftinc/klayer.tcc
|
Myicefrog/RaftLib
|
5ff105293bc851ed73bdfd8966b15d0cadb45eb0
|
[
"Apache-2.0"
] | null | null | null |
raftinc/klayer.tcc
|
Myicefrog/RaftLib
|
5ff105293bc851ed73bdfd8966b15d0cadb45eb0
|
[
"Apache-2.0"
] | 1
|
2021-07-31T15:07:06.000Z
|
2021-07-31T15:07:06.000Z
|
/**
* klayer.tcc - wrapper class around K types of kernels, meant to
* form a single layer within a streaming graph. The syntax will
* look something like this:
*
* map += a <= raft::klayer( b, ... , y ) >= z;
*
* @author: Jonathan Beard
* @version: Tue Mar 8 04:25:20 2016
*
* Copyright 2016 Jonathan Beard
*
* 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 _KLAYER_TCC_
#define _KLAYER_TCC_ 1
#endif /* END _KLAYER_TCC_ */
| 33.137931
| 75
| 0.706556
|
mr-j0nes
|
0a9803f2bf5871a591c573c466fbc847401b6d2e
| 704
|
cpp
|
C++
|
test17_31_32.cpp
|
chenshiyang/C-Primer-5ed-solution
|
54ce8670e7ad6d82bf62c18523a5be175325276d
|
[
"Apache-2.0"
] | null | null | null |
test17_31_32.cpp
|
chenshiyang/C-Primer-5ed-solution
|
54ce8670e7ad6d82bf62c18523a5be175325276d
|
[
"Apache-2.0"
] | null | null | null |
test17_31_32.cpp
|
chenshiyang/C-Primer-5ed-solution
|
54ce8670e7ad6d82bf62c18523a5be175325276d
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
#include <random>
#include <string>
using namespace std;
bool play(bool first) {
static default_random_engine e;
static bernoulli_distribution b;
return b(e);
}
int main() {
string resp;
static default_random_engine e;
static bernoulli_distribution b;
do {
bool first = b(e);
cout << first << endl;
cout << (first ? "We go first"
: "You get to go first") << endl;
cout << (play(first) ? "Sorry, you lost"
: "Congrats, you won") << endl;
cout << "Play again? Enter 'yes' or 'no'" << endl;
} while(cin >> resp && resp[0] == 'y');
return 0;
}
| 23.466667
| 59
| 0.53125
|
chenshiyang
|
0aa8826329ef8e407e59421393abeac931606a14
| 821
|
cpp
|
C++
|
editor/graph/voxel_graph_editor_node_preview.cpp
|
swimming92404/godot_voxel
|
d4b1178d610c7ba0c63c668431524ec320842c57
|
[
"MIT"
] | null | null | null |
editor/graph/voxel_graph_editor_node_preview.cpp
|
swimming92404/godot_voxel
|
d4b1178d610c7ba0c63c668431524ec320842c57
|
[
"MIT"
] | null | null | null |
editor/graph/voxel_graph_editor_node_preview.cpp
|
swimming92404/godot_voxel
|
d4b1178d610c7ba0c63c668431524ec320842c57
|
[
"MIT"
] | null | null | null |
#include "voxel_graph_editor_node_preview.h"
#include <scene/gui/texture_rect.h>
namespace zylann::voxel {
VoxelGraphEditorNodePreview::VoxelGraphEditorNodePreview() {
_image.instantiate();
_image->create(RESOLUTION, RESOLUTION, false, Image::FORMAT_L8);
_texture.instantiate();
update_texture();
_texture_rect = memnew(TextureRect);
_texture_rect->set_stretch_mode(TextureRect::STRETCH_SCALE);
_texture_rect->set_custom_minimum_size(Vector2(RESOLUTION, RESOLUTION));
_texture_rect->set_texture(_texture);
_texture_rect->set_texture_filter(CanvasItem::TEXTURE_FILTER_NEAREST);
add_child(_texture_rect);
}
Ref<Image> VoxelGraphEditorNodePreview::get_image() const {
return _image;
}
void VoxelGraphEditorNodePreview::update_texture() {
_texture->create_from_image(_image);
}
} // namespace zylann::voxel
| 28.310345
| 73
| 0.806334
|
swimming92404
|
0ab157a468b081b04c23b7875ddbe694aaecd9e0
| 735
|
cpp
|
C++
|
Plugins/SPCRJointDynamics/Source/SPCRJointDynamics/Private/Log/SPCRJointDynamicsLog.cpp
|
ianmage/SPCRJointDynamicsUE4
|
590dc8c9e94470edbc401f80eee5fe4e93b53746
|
[
"MIT"
] | null | null | null |
Plugins/SPCRJointDynamics/Source/SPCRJointDynamics/Private/Log/SPCRJointDynamicsLog.cpp
|
ianmage/SPCRJointDynamicsUE4
|
590dc8c9e94470edbc401f80eee5fe4e93b53746
|
[
"MIT"
] | null | null | null |
Plugins/SPCRJointDynamics/Source/SPCRJointDynamics/Private/Log/SPCRJointDynamicsLog.cpp
|
ianmage/SPCRJointDynamicsUE4
|
590dc8c9e94470edbc401f80eee5fe4e93b53746
|
[
"MIT"
] | null | null | null |
//======================================================================================
// Copyright (c) 2019 SPARK CREATIVE Inc.
// All rights reserved.
//======================================================================================
#include "Log/SPCRJointDynamicsLog.h"
#include "SPCRJointDynamicsModulePCH.h"
//======================================================================================
//
//======================================================================================
DEFINE_LOG_CATEGORY(LogSPCRJointDynamics);
//======================================================================================
// EOF
//======================================================================================
| 45.9375
| 88
| 0.209524
|
ianmage
|
0ab56830794a6d5d45c5e42a96adb90e1a5fb441
| 4,622
|
cpp
|
C++
|
WLMatrix/src/wlmatrix/sockets/MSNClient.cpp
|
aeoncl/wlmatrix
|
da936eaec37f06f0e379c6009962dc69bfe07eb3
|
[
"MIT"
] | null | null | null |
WLMatrix/src/wlmatrix/sockets/MSNClient.cpp
|
aeoncl/wlmatrix
|
da936eaec37f06f0e379c6009962dc69bfe07eb3
|
[
"MIT"
] | null | null | null |
WLMatrix/src/wlmatrix/sockets/MSNClient.cpp
|
aeoncl/wlmatrix
|
da936eaec37f06f0e379c6009962dc69bfe07eb3
|
[
"MIT"
] | null | null | null |
#include "MSNClient.h"
#include "StringUtils.h"
#include <iostream>
#include "MSNPCommandHandlerFactory.h"
#include "MSNPCommandParser.h"
#include "MatrixBackend.h"
#include <chrono>
#include "PresenceEvent.h"
#include "MSNPILN.h"
#include "MSNUtils.h"
#include "PresenceUpdateTask.h"
#include <future>
#include "NewMessageTask.h"
#include "SharedThreadPool.h"
#include "StatusConverter.h"
#include "DirectRoomsUpdateTask.h"
#include "ExpressionProfileUpdateTask.h"
using namespace wlmatrix;
//TODO don't forget to SET MSN CLIENT IP & PORT IN CLIENT INFO.
//USED FOR HOTMAIL NOTIFICATION
//CREATE A MATRIX REPOSITORY AND SUBSCRIBE WITH A CALLBACK FUNCTION TO GET THE SYNCS
MSNClient::MSNClient(std::shared_ptr<ClientInfo> info, ITransport *transport, std::string transportID) : _clientInfo(info), _transport(transport), _transportID(transportID){};
MSNClient::~MSNClient()
{
_matrixSyncLoopExitSignal.set_value();
};
void MSNClient::startMatrixLoop(int initialPresenceTrid, std::shared_ptr<ClientInfo> clientInfo, std::future<void> exitSignal)
{
auto threadPool = SharedThreadPool::getInstance().getThreadPool();
MatrixBackend matrix(_clientInfo->getMatrixServerUrl(), _clientInfo->getMatrixToken());
const std::chrono::milliseconds timeout = std::chrono::milliseconds{1000};
SyncResponse previousResponse;
while (exitSignal.wait_for(std::chrono::milliseconds(1)) == std::future_status::timeout)
{
bool isInitial = previousResponse.getNextBatch().empty();
int usableTrid = isInitial ? initialPresenceTrid : -1;
auto status = clientInfo->getStatus();
previousResponse = matrix.sync(previousResponse.getNextBatch(), StatusConverter::convertBack(status), "", 5000);
//auto expressionProfileUpdateTask = threadPool->submit([previousResponse, clientInfo]
// { return ExpressionProfileUpdateTask::execute(previousResponse, clientInfo); });
auto directRoomsUpdatePromise = threadPool->submit([previousResponse, clientInfo]
{ return DirectRoomsUpdateTask::execute(previousResponse, clientInfo); });
//expressionProfileUpdateTask.get();
directRoomsUpdatePromise.get();
auto presenceUpdatePromise = threadPool->submit([previousResponse, clientInfo, usableTrid]
{ return PresenceUpdateTask::execute(previousResponse, clientInfo, usableTrid); });
auto newMessageTaskPromise = threadPool->submit([previousResponse, clientInfo, isInitial]
{ return NewMessageTask::execute(previousResponse, clientInfo, isInitial); });
this->sendMessages(presenceUpdatePromise.get());
this->sendMessages(newMessageTaskPromise.get());
}
};
/**
* Start main notification loop with matrix server.
* */
void MSNClient::onClientReady(int initialPresenceTrid)
{
_clientReady = true;
auto threadPool = SharedThreadPool::getInstance().getThreadPool();
threadPool->submit([this, initialPresenceTrid]
{ startMatrixLoop(initialPresenceTrid, this->_clientInfo, this->_matrixSyncLoopExitSignal.get_future()); });
}
std::shared_ptr<ClientInfo> MSNClient::getClientInfo()
{
return _clientInfo;
}
/**
* @brief Sends message back to the client.
*
* @param message
*/
void MSNClient::sendMessage(std::string message)
{
_transport->sendMessage(_transportID, message);
};
/**
* @brief Sends message back to the client.
*
* @param message
*/
void MSNClient::sendMessages(std::vector<std::string> messages)
{
for (auto message : messages)
{
_transport->sendMessage(_transportID, message);
}
};
/* Private Methods */
/**
* @brief Called when we have received new messages from the client to be process
*/
/* Callback */
void MSNClient::onMessageReceived(std::string message)
{
//Called when a message is received
auto commands = MSNPCommandParser::parseMessage(message);
for (auto command : commands)
{
std::cout << ">> " << command.toString() << std::endl;
//TODO DEGUEU
if (command.getOperand() == "CHG" && !_clientReady)
{
this->onClientReady(11);
}
auto commandHandler = MSNPCommandHandlerFactory::getCommand(command.getOperand());
auto responses = commandHandler->executeCommand(command.getCommand(), _clientInfo, -1);
if (command.getOperand() != "OUT")
{
this->sendMessages(responses);
}
}
}
| 36.109375
| 175
| 0.680009
|
aeoncl
|
0ab8200386478cf2b037ab9e1324d6029c746cce
| 618
|
hpp
|
C++
|
src/amqpAnalyze/IpDissector.hpp
|
kpvdr/amqpAnalyze
|
f1d3a073836191fd9d9a6e6f10a8d6ef2f060cf6
|
[
"Apache-2.0"
] | 1
|
2019-04-02T23:03:23.000Z
|
2019-04-02T23:03:23.000Z
|
src/amqpAnalyze/IpDissector.hpp
|
kpvdr/amqpAnalyze
|
f1d3a073836191fd9d9a6e6f10a8d6ef2f060cf6
|
[
"Apache-2.0"
] | 30
|
2017-04-17T11:21:41.000Z
|
2018-01-09T19:21:44.000Z
|
src/amqpAnalyze/IpDissector.hpp
|
kpvdr/amqpAnalyze
|
f1d3a073836191fd9d9a6e6f10a8d6ef2f060cf6
|
[
"Apache-2.0"
] | null | null | null |
/*
* IpDissector.hpp
*
* Created on: Apr 3, 2017
* Author: kpvdr
*/
#ifndef SRC_AMQPANALYZE_IPDISSECTOR_HPP_
#define SRC_AMQPANALYZE_IPDISSECTOR_HPP_
#include <amqpAnalyze/Dissector.hpp>
namespace amqpAnalyze
{
class IpDissector: public Dissector
{
public:
IpDissector(Packet* packetPtr, uint32_t packetOffs);
virtual ~IpDissector();
virtual std::string sourceAddrStr() const = 0;
virtual std::string destinationAddrStr() const = 0;
virtual bool isIp6() const = 0;
};
} /* namespace amqpAnalyze */
#endif /* SRC_AMQPANALYZE_IPDISSECTOR_HPP_ */
| 20.6
| 60
| 0.68123
|
kpvdr
|
0ab9068edadec73f0c06c1350ec6aea5141952c8
| 463
|
cpp
|
C++
|
src/vector2D.cpp
|
KPO-2020-2021/zad5_3-kgliwinski
|
302d567d68d8e26c7395f9607632df266d7b7df9
|
[
"Unlicense"
] | null | null | null |
src/vector2D.cpp
|
KPO-2020-2021/zad5_3-kgliwinski
|
302d567d68d8e26c7395f9607632df266d7b7df9
|
[
"Unlicense"
] | null | null | null |
src/vector2D.cpp
|
KPO-2020-2021/zad5_3-kgliwinski
|
302d567d68d8e26c7395f9607632df266d7b7df9
|
[
"Unlicense"
] | null | null | null |
#pragma once
#include"vector2D.cpp"
template <>
inline Vector<double, 2> Vector<double, 2>::rotate(const double &theta) const
{
Vector2D rotated;
Matrix2D transformation;
transformation.rotation_matrix(theta);
rotated = transformation * *this;
return rotated;
}
template <>
inline double Vector<double,2>::get_slope_angle() const
{
double angle;
angle = atan2(size[1], size[0]);
angle *= 180 / PI;
return angle;
}
| 18.52
| 77
| 0.667387
|
KPO-2020-2021
|
0abc94aea5ce094365c33f551c6c0e73dbc0fd53
| 1,230
|
hpp
|
C++
|
src/netlayer.hpp
|
hongsenliu/cloudland
|
81a9394f6e74658141ee66557731985f80a9f6ab
|
[
"Apache-2.0"
] | 69
|
2019-04-17T04:03:31.000Z
|
2021-11-08T10:29:54.000Z
|
src/netlayer.hpp
|
hongsenliu/cloudland
|
81a9394f6e74658141ee66557731985f80a9f6ab
|
[
"Apache-2.0"
] | 113
|
2019-04-13T06:46:32.000Z
|
2021-11-02T01:45:06.000Z
|
src/netlayer.hpp
|
hongsenliu/cloudland
|
81a9394f6e74658141ee66557731985f80a9f6ab
|
[
"Apache-2.0"
] | 46
|
2019-04-17T04:03:36.000Z
|
2021-09-26T13:11:37.000Z
|
#ifndef _NETLAYER_HPP
#define _NETLAYER_HPP
#include <string>
#include <sci.h>
#include <vector>
#include <map>
#define SCHEDULE_FILTER 1
#define SCHEDULE_SO_FILE "/opt/cloudland/lib64/scheduler.so"
#include <pthread.h>
using namespace std;
class RpcWorker;
struct groupDesc {
sci_group_t group;
string desc;
};
typedef map<string, groupDesc> GROUP_MAP;
class NetLayer {
private:
sci_info_t sciInfo;
string bePath;
string hFile;
pthread_mutex_t mtx;
pthread_mutex_t ser;
GROUP_MAP groupMap;
vector<string> string2Array(const string& str, char splitter);
public:
NetLayer();
int initFE(char *backend, char *hostfile, RpcWorker *rpcWorker);
int sendMessage(char *message, int length, char *grpName = NULL, bool useFilter = true);
int sendMessage(int beID, char *message, int length);
int createGroup(char *grpDesc);
int freeGroup(char *grpName);
void terminate();
void lock();
void unlock();
void serialize();
void deserialize();
int groupMessage(char *message, int length, char *grpDesc);
string listGroup();
~NetLayer();
};
#endif
| 23.207547
| 96
| 0.644715
|
hongsenliu
|
0ac04ef889b060e2e430ce66bf28b24bb9279267
| 1,775
|
cpp
|
C++
|
06/assembler_implementation/code.cpp
|
ashiroji/Nand2Tetris
|
1eba908d0134ecbc7c6e8e252558caa8725ed70c
|
[
"MIT"
] | null | null | null |
06/assembler_implementation/code.cpp
|
ashiroji/Nand2Tetris
|
1eba908d0134ecbc7c6e8e252558caa8725ed70c
|
[
"MIT"
] | null | null | null |
06/assembler_implementation/code.cpp
|
ashiroji/Nand2Tetris
|
1eba908d0134ecbc7c6e8e252558caa8725ed70c
|
[
"MIT"
] | null | null | null |
#include "code.h"
code::code()
{
this->destMap["null"] = "000";
this->destMap["M"] = "001";
this->destMap["D"] = "010";
this->destMap["MD"] = "011";
this->destMap["A"] = "100";
this->destMap["AM"] = "101";
this->destMap["AD"] = "110";
this->destMap["AMD"] = "111";
this->compMap["0"] = "0101010";
this->compMap["1"] = "0111111";
this->compMap["-1"] = "0111010";
this->compMap["D"] = "0001100";
this->compMap["A"] = "0110000";
this->compMap["!D"] = "0001101";
this->compMap["!A"] = "0110001";
this->compMap["-D"] = "0001111";
this->compMap["-A"] = "0110011";
this->compMap["D+1"] = "0011111";
this->compMap["A+1"] = "0110111";
this->compMap["D-1"] = "0001110";
this->compMap["A-1"] = "0110010";
this->compMap["D+A"] = "0000010";
this->compMap["D-A"] = "0010011";
this->compMap["A-D"] = "0000111";
this->compMap["D&A"] = "0000000";
this->compMap["D|A"] = "0010101";
this->compMap["M"] = "1110000";
this->compMap["!M"] = "1110001";
this->compMap["-M"] = "1110011";
this->compMap["M+1"] = "1110111";
this->compMap["M-1"] = "1110010";
this->compMap["D+M"] = "1000010";
this->compMap["D-M"] = "1010011";
this->compMap["M-D"] = "1000111";
this->compMap["D&M"] = "1000000";
this->compMap["D|M"] = "1010101";
this->jumpMap["null"] = "000";
this->jumpMap["JGT"] = "001";
this->jumpMap["JEQ"] = "010";
this->jumpMap["JGE"] = "011";
this->jumpMap["JLT"] = "100";
this->jumpMap["JNE"] = "101";
this->jumpMap["JLE"] = "110";
this->jumpMap["JMP"] = "111";
}
std::string code::dest(const std::string& d)
{
return(this->destMap[d]);
}
std::string code::comp(const std::string& c)
{
std::string result = this->compMap[c];
return(result);
}
std::string code::jump(const std::string& j)
{
return(this->jumpMap[j]);
}
code::~code()
{
}
| 23.355263
| 44
| 0.570141
|
ashiroji
|
0ac23932147e699b2438ab194c8a879e2700931b
| 377
|
cpp
|
C++
|
tools/console/source/CommandCreateProject.cpp
|
GrimshawA/Nephilim
|
1e69df544078b55fdaf58a04db963e20094f27a9
|
[
"Zlib"
] | 19
|
2015-12-19T11:15:57.000Z
|
2022-03-09T11:22:11.000Z
|
tools/console/source/CommandCreateProject.cpp
|
DevilWithin/Nephilim
|
1e69df544078b55fdaf58a04db963e20094f27a9
|
[
"Zlib"
] | 1
|
2017-05-17T09:31:10.000Z
|
2017-05-19T17:01:31.000Z
|
tools/console/source/CommandCreateProject.cpp
|
GrimshawA/Nephilim
|
1e69df544078b55fdaf58a04db963e20094f27a9
|
[
"Zlib"
] | 3
|
2015-12-14T17:40:26.000Z
|
2021-02-25T00:42:42.000Z
|
#include "CommandCreateProject.h"
#include "CommandCreateProjectDataSheet.h"
#include <iostream>
using namespace std;
void CommandCreateProject::execute(String command)
{
CommandCreateProjectDataSheet* program = static_cast<CommandCreateProjectDataSheet*>(Info::nativeActions["datasheet"]);
if(program)
{
program->execute("");
}
FileSystem::makeDirectory("assets");
}
| 23.5625
| 120
| 0.782493
|
GrimshawA
|
0ac42481f2ac8aa5fb6ce6366900a6b85bd231d8
| 4,637
|
hpp
|
C++
|
libs/fnd/serialization/include/bksge/fnd/serialization/detail/save_dispatch.hpp
|
myoukaku/bksge
|
0f8b60e475a3f1709723906e4796b5e60decf06e
|
[
"MIT"
] | 4
|
2018-06-10T13:35:32.000Z
|
2021-06-03T14:27:41.000Z
|
libs/fnd/serialization/include/bksge/fnd/serialization/detail/save_dispatch.hpp
|
myoukaku/bksge
|
0f8b60e475a3f1709723906e4796b5e60decf06e
|
[
"MIT"
] | 566
|
2017-01-31T05:36:09.000Z
|
2022-02-09T05:04:37.000Z
|
libs/fnd/serialization/include/bksge/fnd/serialization/detail/save_dispatch.hpp
|
myoukaku/bksge
|
0f8b60e475a3f1709723906e4796b5e60decf06e
|
[
"MIT"
] | 1
|
2018-07-05T04:40:53.000Z
|
2018-07-05T04:40:53.000Z
|
/**
* @file save_dispatch.hpp
*
* @brief save_dispatch の定義
*
* @author myoukaku
*/
#ifndef BKSGE_FND_SERIALIZATION_DETAIL_SAVE_DISPATCH_HPP
#define BKSGE_FND_SERIALIZATION_DETAIL_SAVE_DISPATCH_HPP
#include <bksge/fnd/serialization/detail/serialize_dispatch.hpp>
#include <bksge/fnd/serialization/version.hpp>
#include <bksge/fnd/serialization/nvp.hpp>
#include <bksge/fnd/type_traits/bool_constant.hpp>
#include <bksge/fnd/type_traits/is_null_pointer.hpp>
#include <bksge/fnd/type_traits/is_array.hpp>
#include <bksge/fnd/type_traits/is_arithmetic.hpp>
#include <bksge/fnd/type_traits/is_enum.hpp>
#include <bksge/fnd/type_traits/is_pointer.hpp>
#include <bksge/fnd/type_traits/conditional.hpp>
#include <utility>
namespace bksge
{
namespace serialization
{
namespace detail
{
class save_dispatch
{
private:
template <typename Archive, typename T>
struct is_save_version_free_invocable
{
private:
template <typename A2, typename T2>
static auto test(int) -> decltype(
save(std::declval<A2&>(), std::declval<T2 const&>(), std::declval<bksge::serialization::version_t>()),
bksge::true_type());
template <typename A2, typename T2>
static auto test(...)->bksge::false_type;
using type = decltype(test<Archive, T>(0));
public:
static const bool value = type::value;
};
template <typename Archive, typename T>
struct is_save_free_invocable
{
private:
template <typename A2, typename T2>
static auto test(int) -> decltype(
save(std::declval<A2&>(), std::declval<T2 const&>()),
bksge::true_type());
template <typename A2, typename T2>
static auto test(...)->bksge::false_type;
using type = decltype(test<Archive, T>(0));
public:
static const bool value = type::value;
};
struct save_array
{
template <typename Archive, typename T>
static void invoke(Archive& ar, T const& t)
{
ar.save_array(t);
}
};
struct save_arithmetic
{
template <typename Archive, typename T>
static void invoke(Archive& ar, T const& t)
{
ar.save_arithmetic(t);
}
};
struct save_enum
{
template <typename Archive, typename T>
static void invoke(Archive& ar, T const& t)
{
ar.save_enum(t);
}
};
struct save_pointer
{
template <typename Archive, typename T>
static void invoke(Archive& ar, T const& t)
{
ar.save_pointer(t);
}
};
struct save_null_pointer
{
template <typename Archive, typename T>
static void invoke(Archive&, T const&)
{
}
};
struct save_nvp
{
template <typename Archive, typename T>
static void invoke(Archive& ar, T const& t)
{
ar.save_nvp(t);
}
};
struct save_version_free
{
template <typename Archive, typename T>
static void invoke(Archive& ar, T const& t, bksge::serialization::version_t version)
{
save(ar, t, version);
}
};
struct save_free
{
template <typename Archive, typename T>
static void invoke(Archive& ar, T const& t, bksge::serialization::version_t)
{
save(ar, t);
}
};
struct save_object
{
template <typename Archive, typename T>
static void invoke(Archive& ar, T const& t)
{
using type =
bksge::conditional_t<
access::is_save_version_memfun_invocable<Archive, T>::value,
access::save_version_memfun,
bksge::conditional_t<
access::is_save_memfun_invocable<Archive, T>::value,
access::save_memfun,
bksge::conditional_t<
is_save_version_free_invocable<Archive, T>::value,
save_version_free,
bksge::conditional_t<
is_save_free_invocable<Archive, T>::value,
save_free,
serialize_dispatch
>>>>;
auto const version = detail::Version<T>::value;
ar.save(version);
type::invoke(ar, t, version);
}
};
public:
template <typename Archive, typename T>
static void invoke(Archive& ar, T const& t)
{
using type =
bksge::conditional_t<
bksge::is_array<T>::value,
save_array,
bksge::conditional_t<
bksge::is_arithmetic<T>::value,
save_arithmetic,
bksge::conditional_t<
bksge::is_enum<T>::value,
save_enum,
bksge::conditional_t<
bksge::is_pointer<T>::value,
save_pointer,
bksge::conditional_t<
bksge::is_null_pointer<T>::value,
save_null_pointer,
bksge::conditional_t<
is_nvp<T>::value,
save_nvp,
save_object
>>>>>>;
type::invoke(ar, t);
}
};
} // namespace detail
} // namespace serialization
} // namespace bksge
#endif // BKSGE_FND_SERIALIZATION_DETAIL_SAVE_DISPATCH_HPP
| 21.368664
| 106
| 0.664654
|
myoukaku
|
0ac58623b137717c6414b8b44e9c131743261339
| 11,895
|
cpp
|
C++
|
platform/windows/Corona.Simulator/Rtt/Rtt_WinConnection.cpp
|
sekodev/corona
|
b9a559d0cc68f5d9048444d710161fc5b778d981
|
[
"MIT"
] | null | null | null |
platform/windows/Corona.Simulator/Rtt/Rtt_WinConnection.cpp
|
sekodev/corona
|
b9a559d0cc68f5d9048444d710161fc5b778d981
|
[
"MIT"
] | null | null | null |
platform/windows/Corona.Simulator/Rtt/Rtt_WinConnection.cpp
|
sekodev/corona
|
b9a559d0cc68f5d9048444d710161fc5b778d981
|
[
"MIT"
] | null | null | null |
//////////////////////////////////////////////////////////////////////////////
//
// This file is part of the Corona game engine.
// For overview and more information on licensing please refer to README.md
// Home page: https://github.com/coronalabs/corona
// Contact: support@coronalabs.com
//
//////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "Core/Rtt_Build.h"
#include <WinInet.h>
#include "WinString.h"
#include "TimXmlRpc.h" // downloaded from http://sourceforge.net/projects/xmlrpcc4win/
#include "Rtt_WinConnection.h"
#include "Rtt_MPlatformServices.h"
#include "Rtt_WinDictionaryWrapper.h"
#include <string.h>
#include <time.h>
#include "SimulatorView.h"
#include "WinGlobalProperties.h"
// ----------------------------------------------------------------------------
namespace Rtt
{
static String &
DictionaryToString( const KeyValuePair *pairs, int numPairs, int indent = 0 )
{
static String output;
char buf[1024];
output.Set(" {\n");
for ( int i = 0; i < numPairs; i++ )
{
const KeyValuePair& item = pairs[i];
String str;
if ( item.type <= 0 )
{
switch( item.type )
{
case kStringValueType:
if (item.value != NULL && strlen((const char *)item.value) > 1024)
{
snprintf(buf, 1024, "\"%s\" = <%d bytes of data elided>", item.key, strlen((const char *)item.value));
}
else
{
snprintf(buf, 1024, "\"%s\" = \"%s\"", item.key, (item.value != NULL ? (const char *)item.value : "(null)"));
}
break;
case kIntegerValueType:
snprintf(buf, 1024, "\"%s\" = %d", item.key, (S32)item.value);
break;
default:
Rtt_ASSERT_NOT_REACHED();
break;
}
if (indent > 0)
{
for (int in = 0; in < (indent * 4); in++)
{
output.Append(" ");
}
}
output.Append(buf);
output.Append("\n");
}
else // value is an array/struct of values
{
output.Append(DictionaryToString( (const KeyValuePair*)item.value, item.type, ++indent ).GetString());
}
}
output.Append("}\n");
return output;
}
// ----------------------------------------------------------------------------
WinConnection::WinConnection( const MPlatformServices& platform, const char* url )
: Super( platform ),
m_sUrl( NULL ),
m_sError( NULL ),
m_connection( NULL ),
m_hInternetFile( NULL )
{
int length = strlen(url) + 1;
m_sUrl = new char [ length ];
strcpy_s( m_sUrl, length, url );
String prefVal;
fPlatform.GetPreference("debugWebServices", &prefVal);
if (! prefVal.IsEmpty())
{
fDebugWebServices = (int) strtol(prefVal.GetString(), (char **)NULL, 10);
}
else
{
fDebugWebServices = 0;
}
}
WinConnection::~WinConnection()
{
if( m_sUrl )
delete m_sUrl;
if( m_sError )
delete m_sError;
}
// Caller responsible for deleting returned value
PlatformDictionaryWrapper*
WinConnection::Call( const char* method, const KeyValuePair* pairs, int numPairs )
{
time_t startTime = 0;
m_connection = new XmlRpcClient(m_sUrl);
// m_connection.setIgnoreCertificateAuthority(); // TODO: need this?
m_connection->setIgnoreCookies(true); // Cookies cause login problems.
XmlRpcValue *pResult = new XmlRpcValue; // deleted by caller
XmlRpcValue *pParams = CreateDictionary( pairs, numPairs ); // deleted below
PlatformDictionaryWrapper *pWrapper = NULL;
if (fDebugWebServices > 0)
{
Rtt_LogException("WebServices: Call: %s %s", method, ((numPairs == 0 && fDebugWebServices > 1) ? "(no params)" : ""));
if (numPairs > 0 && fDebugWebServices > 1)
{
Rtt_LogException(" params: %s", DictionaryToString(pairs, numPairs, 1).GetString());
}
startTime = time(NULL);
}
if ( ! m_connection->execute( method, *pParams, *pResult ) )
{
std::string sErr = m_connection->getError();
m_sError = new char [sErr.size()+1];
strcpy_s(m_sError, sErr.size()+1, sErr.c_str());
Rtt_LogException("WebServices: Call %s failed in %lld seconds: %s", method, (time(NULL) - startTime), m_sError);
Rtt_LogException(" params: %s", DictionaryToString(pairs, numPairs, 1).GetString());
delete pResult; // will return NULL to signal error
}
else
{
if (pResult != NULL)
{
if (fDebugWebServices > 2)
{
std::ostringstream ostr;
pResult->buildCall(method, ostr);
if (ostr.str().size() > 2048)
{
Rtt_LogException("WebServices: Response received in %lld seconds: <%d bytes of data elided>",
(time(NULL) - startTime), ostr.str().size());
}
else
{
Rtt_LogException("WebServices: Response received in %lld seconds: %s", (time(NULL) - startTime), ostr.str().c_str());
}
}
else if (fDebugWebServices > 0)
{
Rtt_LogException("WebServices: Response received in %lld seconds", (time(NULL) - startTime));
}
pWrapper = new WinDictionaryWrapper( pResult );
}
else
{
Rtt_LogException("WebServices: Unexpected NULL response from XMLRPC");
}
}
delete pParams;
delete m_connection;
m_connection = NULL;
return pWrapper;
}
void
WinConnection::CloseConnection()
{
if (m_connection != NULL)
{
// Stop any active XML request
m_connection->closeConnection();
}
if (m_hInternetFile != NULL)
{
// Stop any active download
InternetCloseHandle(m_hInternetFile);
}
}
// Function needs to return an allocated value because it can be called recursively
// for nested values.
// Caller is responsible for deleting returned object.
XmlRpcValue *
WinConnection::CreateDictionary( const KeyValuePair *pairs, int numPairs )
{
XmlRpcValue *pParams = new XmlRpcValue; // type will be array of (unnamed) values
// XmlRpc code expects "Type invalid" (uninitialized) param structure if no params.
if( numPairs == 0 )
{
return pParams;
}
Rtt_ASSERT( numPairs > 0 );
pParams->setSize( numPairs ); // array of size numPairs
// iterate through KeyValuePair array and translate to XmlRpcValue array
// keys are ignored
for ( int i = 0; i < numPairs; i++ )
{
const KeyValuePair& item = pairs[i];
if ( item.type <= 0 )
{
switch( item.type )
{
case kStringValueType:
(*pParams)[i] = (const char *)item.value;
break;
case kIntegerValueType:
(*pParams)[i] = (S32)item.value;
break;
default:
Rtt_ASSERT_NOT_REACHED();
(*pParams)[i] = "";
break;
}
}
else // value is an array/struct of values
{
(*pParams)[i] = * CreateDictionary( (const KeyValuePair*)item.value, item.type );
}
}
return pParams;
}
const char*
WinConnection::Error() const
{
return m_sError;
}
const char*
WinConnection::Url() const
{
return m_sUrl;
}
void
WinConnection::ReportError(const char *mesg)
{
auto errorCode = ::GetLastError();
std::string message(mesg);
if (errorCode != ERROR_SUCCESS)
{
LPWSTR utf16Buffer = nullptr;
HMODULE hModule = NULL; // default to system source
DWORD dwFormatFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_IGNORE_INSERTS |
FORMAT_MESSAGE_FROM_SYSTEM;
// If dwLastError is in the network range, grab the WinINET message source
if (errorCode >= INTERNET_ERROR_BASE && errorCode <= INTERNET_ERROR_LAST)
{
DWORD flags =
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT;
::GetModuleHandleExW(flags, (LPCWSTR)InternetOpenUrl, &hModule);
if (hModule != NULL)
{
dwFormatFlags |= FORMAT_MESSAGE_FROM_HMODULE;
}
}
DWORD dwResult = FormatMessageW(
dwFormatFlags,
hModule,
errorCode,
0, // MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPWSTR) &utf16Buffer,
0,
nullptr);
if (utf16Buffer != nullptr)
{
WinString stringConverter;
stringConverter.SetUTF16(utf16Buffer);
message.append(": ");
message.append(stringConverter.GetUTF8());
::LocalFree(utf16Buffer);
}
}
m_sError = _strdup(message.c_str());
Rtt_LogException("%s", message.c_str());
}
bool
WinConnection::Download(const char *urlStr, const char *filename)
{
WinString urlWinString = urlStr;
WinString filenameWinString = filename;
DWORD numberOfBytesToRead = (BUFSIZ * 8);
BYTE buf[BUFSIZ * 8];
DWORD numberOfBytesRead = 0;
DWORD numberOfBytesWritten = 0;
DWORD totalBytesReceived = 0;
time_t startTime = time(NULL);
HWND progressHWnd = GetForegroundWindow();
if (fDebugWebServices > 1)
{
Rtt_LogException("WebServices: download request: %s", urlStr);
Rtt_LogException("WebServices: to file: %s", filename);
}
else
{
Rtt_LogException("WebServices: downloading build");
}
HINTERNET hInternetRoot = InternetOpen(
TEXT("UserAgent"), // _In_ LPCTSTR lpszAgent,
INTERNET_OPEN_TYPE_PRECONFIG, // _In_ DWORD dwAccessType,
NULL, // _In_ LPCTSTR lpszProxyName,
NULL, // _In_ LPCTSTR lpszProxyBypass,
0 // _In_ DWORD dwFlags
);
if (hInternetRoot == NULL)
{
ReportError("ERROR: download failed to initialize network");
return false;
}
m_hInternetFile = InternetOpenUrl(
hInternetRoot, // _In_ HINTERNET hInternet,
urlWinString.GetTCHAR(), // _In_ LPCTSTR lpszUrl,
NULL, // _In_ LPCTSTR lpszHeaders,
-1L, // _In_ DWORD dwHeadersLength,
INTERNET_FLAG_HYPERLINK | INTERNET_FLAG_NO_CACHE_WRITE, // _In_ DWORD dwFlags,
NULL // _In_ DWORD_PTR dwContext
);
if (m_hInternetFile == NULL)
{
ReportError("ERROR: download failed to open URL");
return false;
}
HANDLE hOut = CreateFile(filenameWinString.GetTCHAR(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, NULL, NULL);
if (hOut == INVALID_HANDLE_VALUE)
{
InternetCloseHandle(m_hInternetFile);
InternetCloseHandle(hInternetRoot);
return false;
}
if (m_hInternetFile == NULL)
{
ReportError("ERROR: download failed to open output file");
return false;
}
DWORD contentLength = 0;
DWORD bufSize = sizeof(DWORD);
if (HttpQueryInfo(m_hInternetFile, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &contentLength, &bufSize, 0))
{
if (fDebugWebServices > 1)
{
Rtt_Log("WebServices: downloading %d bytes", contentLength);
}
if (progressHWnd != NULL)
{
::SendMessage(progressHWnd, WMU_DOWNLOAD_PROGRESS_UPDATE, 0, contentLength);
}
}
do
{
if ( !InternetReadFile(
m_hInternetFile, // _In_ HINTERNET hFile,
buf, // _Out_ LPVOID lpBuffer,
numberOfBytesToRead, // _In_ DWORD dwNumberOfBytesToRead,
&numberOfBytesRead // _Out_ LPDWORD lpdwNumberOfBytesRead
))
{
ReportError("ERROR: download failed to read data");
CloseHandle(hOut);
InternetCloseHandle(m_hInternetFile);
InternetCloseHandle(hInternetRoot);
return false;
}
WriteFile(hOut, &buf[0], numberOfBytesRead, &numberOfBytesWritten, NULL);
if (numberOfBytesWritten != numberOfBytesRead)
{
ReportError("ERROR: download failed to write data");
CloseHandle(hOut);
InternetCloseHandle(m_hInternetFile);
InternetCloseHandle(hInternetRoot);
return false;
}
totalBytesReceived += numberOfBytesRead;
if (progressHWnd != NULL)
{
::SendMessage(progressHWnd, WMU_DOWNLOAD_PROGRESS_UPDATE, 1, totalBytesReceived);
}
} while (numberOfBytesRead > 0);
CloseHandle(hOut);
InternetCloseHandle(m_hInternetFile);
m_hInternetFile = NULL;
InternetCloseHandle(hInternetRoot);
if (fDebugWebServices > 0)
{
time_t totalTime = time(NULL) - startTime;
double MBps = ((double)totalBytesReceived / totalTime) / (1024 * 1024);
Rtt_LogException("WebServices: Download of %ld bytes complete in %lld second%s (%.2fMB/s)",
totalBytesReceived, totalTime, (totalTime == 1 ? "" : "s"), MBps);
totalBytesReceived = 0;
}
return true;
}
// ----------------------------------------------------------------------------
} // namespace Rtt
// ----------------------------------------------------------------------------
| 24.678423
| 140
| 0.649685
|
sekodev
|
0ac9aa16f5782fddd46f31adb798cf5c829e5e76
| 20,513
|
cpp
|
C++
|
level_editor/main.cpp
|
xiroV/game-tools
|
01b7d4f0269cfdcb70901ed07705d1467ed66f37
|
[
"MIT"
] | 1
|
2021-11-05T10:06:16.000Z
|
2021-11-05T10:06:16.000Z
|
level_editor/main.cpp
|
xiroV/game-tools
|
01b7d4f0269cfdcb70901ed07705d1467ed66f37
|
[
"MIT"
] | 24
|
2021-10-03T15:33:16.000Z
|
2021-11-29T22:24:57.000Z
|
level_editor/main.cpp
|
xiroV/game-tools
|
01b7d4f0269cfdcb70901ed07705d1467ed66f37
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <string>
#include <sstream>
#include <typeinfo>
#include <vector>
#include <fstream>
#include "editor.hpp"
#include "export/cpp.hpp"
#include "export/lvl.hpp"
#include "export/swift.hpp"
#ifndef RAYGUI
#define RAYGUI
#define RAYGUI_IMPLEMENTATION
#include "lib/raygui/src/raygui.h"
#endif
#include "lib/raylib/src/raylib.h"
#include "window/export.cpp"
#include "window/exit.cpp"
#include "window/block_type_editor.cpp"
#include "window/key_value_editor.cpp"
using namespace std;
constexpr int MOVE_INTERVAL = 10;
constexpr int MOVE_DELAY = 5;
constexpr int MOVE_HOLD_DELAY = 40;
constexpr int ROTATION_INTERVAL = 15;
constexpr int RESIZE_INTERVAL = 50;
constexpr int CAMERA_MOVE_SPEED = 5;
constexpr int GRID_DISTANCE = 50;
float cameraZoom = 1.0f;
float timeSinceLastMove = 0;
float timeSinceLastMovePress = 0;
int exitWindowSelectedOption = 0;
struct Windows {
ExportWindow exportWindow;
ExitWindow exitWindow;
BlockTypeEditorWindow blockTypeEditorWindow;
KeyValueEditorWindow keyValueEditorWindow;
};
string filename = "";
void addMessage(Editor *editor, std::string message, float expiration, MessageType type) {
editor->messages.emplace_back(EditorMessage{message, expiration, type});
}
void loadLevel(Editor *editor) {
int version = 0;
string fileLine;
ifstream levelFile;
levelFile.open(filename);
editor->objectTypes = {};
if (levelFile.is_open()) {
// Read version
getline(levelFile, fileLine);
if (fileLine[0] == '#') {
version = stoi(fileLine.substr(string("#version ").length(), fileLine.length()));
};
if (version > editor->version) {
cout << endl << "Version of file read is newer than this binary supports. Will try its best to parse the input file." << endl << endl;
}
// Only one version currently, so nothing special to do
while (getline(levelFile, fileLine)) {
string element;
vector<int> lineElements;
istringstream line(fileLine);
int objectFieldCount = 0;
while (objectFieldCount < 5 && getline(line, element, editor->outputDelimiter)) {
lineElements.push_back(stoi(element));
objectFieldCount++;
}
getline(line, element, editor->outputDelimiter);
string typeName = element;
int typeId = -1;
for (unsigned int i = 0; i < editor->objectTypes.size(); i++) {
if (editor->objectTypes[i].name == typeName) {
typeId = i;
}
}
Color color = (Color) {
static_cast<unsigned char>(GetRandomValue(0,255)),
static_cast<unsigned char>(GetRandomValue(0, 255)),
static_cast<unsigned char>(GetRandomValue(0,255)),
255
};
if (typeId < 0) {
editor->objectTypes.push_back((ObjectType){typeName, color});
typeId = editor->objectTypes.size() - 1;
}
Object obj = {lineElements[0], lineElements[1], lineElements[2], lineElements[3], lineElements[4], typeId};
while (getline(line, element, editor->outputDelimiter)) {
istringstream keyValuePair = istringstream(element);
string key;
string value;
getline(keyValuePair, key, '=');
getline(keyValuePair, value, editor->outputDelimiter);
obj.data.push_back({key, value});
}
editor->objects.push_back(obj);
}
} else {
addMessage(editor, "Unable to open file\n", 5, ERROR);
}
levelFile.close();
char buffer[50];
sprintf(buffer, "Loaded %lu objects\n", editor->objects.size());
addMessage(editor, buffer, 5, SUCCESS);
}
bool isElementSelected(Editor *editor) {
return editor->selectedObject >= 0 && editor->selectedObject < (int) editor->objects.size();
}
void copyBlock(Editor *editor) {
if (isElementSelected(editor)) {
const auto selectedObject = editor->objects[editor->selectedObject];
Object obj = {selectedObject.x, selectedObject.y, selectedObject.width, selectedObject.height, selectedObject.rotation};
obj.data = selectedObject.data;
editor->objects.push_back(obj);
editor->selectedObject = editor->objects.size() - 1;
addMessage(editor, "Block copied\n", 3, SUCCESS);
} else {
addMessage(editor, "No block selected\n", 3, ERROR);
}
}
void control(Editor *editor, Windows *windows, vector<Exporter*> exporters) {
if (IsKeyDown(KEY_LEFT_ALT) && IsKeyDown(KEY_F4)) {
if (isElementSelected(editor)) {
editor->selectedObject = -1;
} else {
editor->state = EditorState::Closing;
}
}
if (WindowShouldClose()) {
editor->state = EditorState::Closing;
}
if (IsKeyPressed(KEY_F10)) {
editor->showFPS = !editor->showFPS;
}
switch (editor->state) {
case EditorState::Closing: {
windows->exitWindow.control();
break;
}
case EditorState::Export: {
windows->exportWindow.control();
break;
}
case EditorState::KeyValueEditor: {
windows->keyValueEditorWindow.control();
break;
}
case EditorState::BlockTypeEditor: {
windows->blockTypeEditorWindow.control();
break;
}
case EditorState::Editing: {
if (IsKeyPressed(KEY_ESCAPE)) {
if (editor->selectedObject >= 0) {
editor->selectedObject = -1;
} else {
editor->state = EditorState::Closing;
}
}
if (IsKeyPressed(KEY_M)) {
editor->state = EditorState::Export;
}
if (IsKeyPressed(KEY_PAGE_UP)) {
cameraZoom += 0.5;
}
if (IsKeyPressed(KEY_PAGE_DOWN)) {
cameraZoom -= 0.5;
}
if (IsKeyPressed(KEY_Y)) {
editor->state = EditorState::BlockTypeEditor;
}
if (IsKeyPressed(KEY_G)) {
editor->showGrid = !editor->showGrid;
}
// NEW OBJECT
if (IsKeyPressed(KEY_N)) {
Object obj = {(int) editor->windowWidth/2-50, (int) editor->windowHeight/2-50, 100, 100, 0};
editor->objects.push_back(obj);
editor->selectedObject = editor->objects.size()-1;
}
// SWITCH SELECTED
if (IsKeyPressed(KEY_TAB)) {
if (editor->selectedObject + 1 < (int) editor->objects.size()) {
editor->selectedObject += 1;
} else {
if (editor->objects.size() > 0) {
editor->selectedObject = 0;
} else {
editor->selectedObject = -1;
}
}
}
if (IsKeyPressed(KEY_C)) {
copyBlock(editor);
}
if (isElementSelected(editor)) {
bool upPressed = IsKeyPressed(KEY_UP);
bool downPressed = IsKeyPressed(KEY_DOWN);
bool leftPressed = IsKeyPressed(KEY_LEFT);
bool rightPressed = IsKeyPressed(KEY_RIGHT);
bool isMoveDown = IsKeyDown(KEY_UP) || IsKeyDown(KEY_DOWN) ||
IsKeyDown(KEY_LEFT) || IsKeyDown(KEY_RIGHT);
// MOVEMENT
if (upPressed) {
editor->objects[editor->selectedObject].y -= MOVE_INTERVAL;
timeSinceLastMovePress = 0;
}
if (downPressed) {
editor->objects[editor->selectedObject].y += MOVE_INTERVAL;
timeSinceLastMovePress = 0;
}
if (leftPressed) {
editor->objects[editor->selectedObject].x -= MOVE_INTERVAL;
timeSinceLastMovePress = 0;
}
if (rightPressed) {
editor->objects[editor->selectedObject].x += MOVE_INTERVAL;
timeSinceLastMovePress = 0;
}
if (timeSinceLastMovePress > MOVE_HOLD_DELAY) {
if (IsKeyDown(KEY_UP) && !upPressed) {
if (timeSinceLastMove > MOVE_DELAY) {
editor->objects[editor->selectedObject].y -= MOVE_INTERVAL;
}
}
if (IsKeyDown(KEY_DOWN) && !downPressed) {
if (timeSinceLastMove > MOVE_DELAY) {
editor->objects[editor->selectedObject].y += MOVE_INTERVAL;
}
}
if (IsKeyDown(KEY_LEFT) && !leftPressed) {
if (timeSinceLastMove > MOVE_DELAY) {
editor->objects[editor->selectedObject].x -= MOVE_INTERVAL;
}
}
if (IsKeyDown(KEY_RIGHT) && !rightPressed) {
if (timeSinceLastMove > MOVE_DELAY) {
editor->objects[editor->selectedObject].x += MOVE_INTERVAL;
}
}
}
if (isMoveDown) {
timeSinceLastMovePress += GetFrameTime() * 100;
if (timeSinceLastMove > MOVE_DELAY) {
timeSinceLastMove = 0;
} else {
timeSinceLastMove += GetFrameTime() * 100;
}
} else {
timeSinceLastMove = 0;
}
// RESIZING
if (IsKeyPressed(KEY_S)) {
editor->objects[editor->selectedObject].height += RESIZE_INTERVAL;
}
if (IsKeyPressed(KEY_W)) {
if (editor->objects[editor->selectedObject].height >= RESIZE_INTERVAL) {
editor->objects[editor->selectedObject].height -= RESIZE_INTERVAL;
}
}
if (IsKeyPressed(KEY_A)) {
if (editor->objects[editor->selectedObject].width >= RESIZE_INTERVAL) {
editor->objects[editor->selectedObject].width -= RESIZE_INTERVAL;
}
}
if (IsKeyPressed(KEY_D)) {
editor->objects[editor->selectedObject].width += RESIZE_INTERVAL;
}
// ROTATE
if (IsKeyPressed(KEY_Q)) {
editor->objects[editor->selectedObject].rotation = (editor->objects[editor->selectedObject].rotation - ROTATION_INTERVAL) % 360;
}
if (IsKeyPressed(KEY_E)) {
editor->objects[editor->selectedObject].rotation = (editor->objects[editor->selectedObject].rotation + ROTATION_INTERVAL) % 360;
}
// DELETE
if (IsKeyPressed(KEY_DELETE)) {
editor->objects.erase(editor->objects.begin() + editor->selectedObject);
if (editor->objects.size() > 0) {
editor->selectedObject = 0;
} else {
editor->selectedObject = -1;
}
}
// CHANGE TYPE
if (IsKeyPressed(KEY_T)) {
if (editor->objects[editor->selectedObject].type+1 >= (int) editor->objectTypes.size()) {
editor->objects[editor->selectedObject].type = 0;
} else {
editor->objects[editor->selectedObject].type += 1;
}
}
// OPEN KEY VALUE WINDOW
if (IsKeyPressed(KEY_V)) {
editor->state = EditorState::KeyValueEditor;
}
} else {
// MOVEMENT
if (IsKeyDown(KEY_UP)) {
editor->cameraTarget.y -= CAMERA_MOVE_SPEED;
}
if (IsKeyDown(KEY_DOWN)) {
editor->cameraTarget.y += CAMERA_MOVE_SPEED;
}
if (IsKeyDown(KEY_LEFT)) {
editor->cameraTarget.x -= CAMERA_MOVE_SPEED;
}
if (IsKeyDown(KEY_RIGHT)) {
editor->cameraTarget.x += CAMERA_MOVE_SPEED;
}
}
break;
}
}
}
void drawRect(float x, float y, float width, float height, float rotation, Color color) {
DrawRectanglePro(
Rectangle {x + width / 2.0f,y + height / 2.0f,width,height},
Vector2 {width / 2.0f, height / 2.0f},
rotation,
color
);
}
void drawHelp(Editor *editor) {
int xpos = editor->windowWidth-editor->fontSize*8-30;
static std::array<const char*, 14> entries = {{
"[n] new",
"[tab] cycle objects",
"[arrows] move",
"[wasd] resize",
"[del] delete",
"[t] switch type",
"[page/up] zoom",
"[y] edit types",
"[v] key/values",
"[m] export",
"[g] toggle grid",
"[c] copy block",
"[esc] deselect/exit",
"[F10] toggle FPS"
}};
if (editor->showHelp) {
editor->showHelp = !GuiWindowBox({(float) xpos - 50, 10, 230, 432}, "Help");
int ypos = 50;
for (unsigned int i = 0; i < entries.size(); i++) {
GuiLabel({(float) xpos-40, (float) ypos, 100, 20}, entries[i]);
ypos += 8 + editor->fontSize;
}
} else {
editor->showHelp = GuiButton({(float) xpos + 150, 10, 30, 30}, "?");
}
if (isElementSelected(editor)) {
DrawText(
editor->objectTypes[editor->objects[editor->selectedObject].type].name.c_str(),
20, editor->windowHeight - 30, editor->fontSize,
editor->objectTypes[editor->objects[editor->selectedObject].type].color
);
}
}
void drawObjects(Camera2D *camera, Editor *editor) {
if (isElementSelected(editor)) {
auto &selectedObject = editor->objects[editor->selectedObject];
if (selectedObject.width == 0 && selectedObject.height == 0) {
DrawCircleLines(
selectedObject.x,
selectedObject.y,
5.0f,
GREEN
);
} else {
drawRect(selectedObject.x - 1, selectedObject.y - 1, selectedObject.width + 2, selectedObject.height + 2, selectedObject.rotation, GREEN);
}
}
for (unsigned int i = 0; i < editor->objects.size(); i++) {
auto &object = editor->objects[i];
if (object.width == 0 && object.height == 0) {
DrawCircle(object.x, object.y, 5, editor->objectTypes[object.type].color);
} else {
drawRect(object.x, object.y, object.width == 0 ? 1.0f : object.width, object.height == 0 ? 1.0f : object.height, object.rotation, editor->objectTypes[object.type].color);
}
}
}
void drawWindows(Editor *editor, Windows *windows, vector<Exporter*> exporters) {
switch (editor->state) {
case EditorState::Closing: {
windows->exitWindow.draw();
break;
}
case EditorState::Export: {
windows->exportWindow.draw();
break;
}
case EditorState::BlockTypeEditor: {
windows->blockTypeEditorWindow.draw();
break;
}
case EditorState::KeyValueEditor: {
windows->keyValueEditorWindow.draw();
break;
}
default: {}
}
}
void drawGrid(Editor &editor, Camera2D &camera) {
Color color = { 255, 255, 255, 20 };
if (editor.showGrid) {
int yOffset = ((int) camera.target.y) % GRID_DISTANCE;
for (int i = 0; i < editor.windowHeight + yOffset; i += GRID_DISTANCE) {
DrawLine(0, i - yOffset, editor.windowWidth, i- yOffset, color);
}
int xOffset = ((int) camera.target.x) % GRID_DISTANCE;
for (int j = 0; j < editor.windowWidth + xOffset; j += GRID_DISTANCE) {
DrawLine(j - xOffset, 0, j - xOffset, editor.windowHeight, color);
}
}
}
void updateEditor(Editor *editor) {
const auto delta = GetFrameTime();
for (int i = editor->messages.size() - 1; i >= 0; i--) {
editor->messages[i].expiration -= delta;
if (editor->messages[i].expiration < 0) {
editor->messages.erase(editor->messages.begin() + i);
}
}
}
Color colorFromType(MessageType type) {
switch (type) {
case SUCCESS:
return GREEN;
case ERROR:
return RED;
case INFO:
return WHITE;
default:
return WHITE;
}
}
void drawMessages(Editor *editor) {
int offsetY = 20;
for (int i = editor->messages.size() - 1; i >= 0; i--) {
auto c = colorFromType(editor->messages[i].type);
DrawText(
editor->messages[i].message.c_str(),
20,
editor->windowHeight - 30 - offsetY,
editor->fontSize,
c
);
offsetY += 20;
}
}
int main(int argc, char **argv) {
CppExporter cppExport;
LvlExporter lvlExport;
SwiftExporter swiftExport;
Editor editor = {};
editor.version = 1;
editor.outputDelimiter = ';';
editor.state = EditorState::Editing;
editor.keyOrValue = KeyOrValue::Key;
editor.selectedObject = -1;
editor.editKeyValueIndex = -1;
editor.editBlockTypeIndex = -1;
editor.selectedExporter = 0;
editor.windowWidth = 1600;
editor.windowHeight = 1000;
editor.fontSize = 20;
editor.cameraTarget = {editor.windowWidth/2.0f, editor.windowHeight/2.0f};
editor.closeEditor = false;
editor.showGrid = true;
editor.showHelp = false;
editor.showFPS = false;
InitWindow((int) editor.windowWidth, (int) editor.windowHeight, "Level Editor");
SetTargetFPS(60);
// So ESCAPE isn't eaten by ShouldWindowClose();
SetExitKey(KEY_NULL);
Font fontDefault = LoadFontEx("assets/fonts/OverpassMono/OverpassMono-Regular.ttf", editor.fontSize, 0, 0);
SetTextureFilter(fontDefault.texture, TEXTURE_FILTER_BILINEAR);
GuiSetFont(fontDefault);
vector<Exporter*> exporters = {
&lvlExport,
&cppExport,
&swiftExport
};
if (argc > 1) {
filename = argv[1];
loadLevel(&editor);
} else {
filename = "TestLevel1.lvl";
loadLevel(&editor);
}
Windows windows = {
ExportWindow(&editor, exporters),
ExitWindow(&editor, exporters[0]),
BlockTypeEditorWindow(&editor),
KeyValueEditorWindow(&editor)
};
Camera2D camera = {};
camera.target = Vector2{editor.windowWidth/2.0f, editor.windowHeight/2.0f};
camera.offset = Vector2{editor.windowWidth/2.0f, editor.windowHeight/2.0f};
camera.rotation = 0.0f;
camera.zoom = 1.0f;
if (editor.objects.size() > 0) {
editor.cameraTarget = Vector2 {(float) editor.objects[0].x, (float) editor.objects[0].y};
}
while (!editor.closeEditor) {
control(&editor, &windows, exporters);
camera.zoom += cameraZoom;
if (camera.zoom > 2.0f) {
cameraZoom = 2.0f;
camera.zoom = cameraZoom;
}
else if (camera.zoom < 0.5f) {
cameraZoom = 0.5f;
camera.zoom = cameraZoom;
}
camera.target = editor.cameraTarget;
BeginDrawing();
ClearBackground(DARKGRAY);
drawGrid(editor, camera);
BeginMode2D(camera);
drawObjects(&camera, &editor);
EndMode2D();
drawHelp(&editor);
drawWindows(&editor, &windows, exporters);
if (editor.showFPS) DrawFPS(20, 20);
drawMessages(&editor);
EndDrawing();
camera.zoom = 0;
updateEditor(&editor);
}
CloseWindow();
return 0;
}
| 32.508716
| 182
| 0.529664
|
xiroV
|
bd5693aa30a8df5f2c691591556eccac3bde1108
| 329
|
cpp
|
C++
|
ConsoleApplication1/ConsoleApplication1.cpp
|
yg88/class2017
|
c5b40a48f91a5676a4f07c3404e09d50a49f2bd2
|
[
"MIT"
] | null | null | null |
ConsoleApplication1/ConsoleApplication1.cpp
|
yg88/class2017
|
c5b40a48f91a5676a4f07c3404e09d50a49f2bd2
|
[
"MIT"
] | 1
|
2019-01-05T11:53:18.000Z
|
2019-01-05T11:53:18.000Z
|
ConsoleApplication1/ConsoleApplication1.cpp
|
yg88/class2017
|
c5b40a48f91a5676a4f07c3404e09d50a49f2bd2
|
[
"MIT"
] | 1
|
2017-11-23T08:05:38.000Z
|
2017-11-23T08:05:38.000Z
|
// ConsoleApplication1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
int main()
{
std::cout << "Please input two numbers:\n";
int a, b;
std::cin >> a >> b;
std::cout << "Sum of " << a << " and " << b << " is " << a + b << std::endl;
return 0;
}
| 19.352941
| 82
| 0.544073
|
yg88
|
bd63bb462efc0b64939b0393ddca60ab515ecc9a
| 845
|
cpp
|
C++
|
exp2/2_4/2_4.cpp
|
Zerdd/OS-Coding-EXP
|
b46d92fa40d9383838443629b05dd80c4f87f5e1
|
[
"Apache-2.0"
] | null | null | null |
exp2/2_4/2_4.cpp
|
Zerdd/OS-Coding-EXP
|
b46d92fa40d9383838443629b05dd80c4f87f5e1
|
[
"Apache-2.0"
] | null | null | null |
exp2/2_4/2_4.cpp
|
Zerdd/OS-Coding-EXP
|
b46d92fa40d9383838443629b05dd80c4f87f5e1
|
[
"Apache-2.0"
] | null | null | null |
#include "pluginController.h"
#include "pluginCounter.h"
#include <string.h>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
// 检查参数
if (argc != 2)
{
cout << "Please input correct argc!" << endl;
return 0;
}
// 实例化一个插件控制器
pct_t pc;
// 初始化插件控制器
if (pc.InitController() == false)
{
cout << "Init plugin controller error!" << endl;
return 0;
}
// 执行help()
if (strcmp(argv[1], "help") == 0)
{
if (pc.ProcessHelp() == false)
{
cout << "ProcessHelp() error!" << endl;
return 0;
}
}
// 根据ID选择对应插件进行print
else
{
int FuncID = atoi(argv[1]); // 转换整型
pc.ProcessPrint(FuncID);
}
// 卸载所有的动态库
pc.UninitController();
return 0;
}
| 17.604167
| 56
| 0.497041
|
Zerdd
|
bd658a964c1c208807102cace239467fbd80dd77
| 59,568
|
cxx
|
C++
|
osprey/be/lno/array_bounds.cxx
|
sharugupta/OpenUH
|
daddd76858a53035f5d713f648d13373c22506e8
|
[
"BSD-2-Clause"
] | null | null | null |
osprey/be/lno/array_bounds.cxx
|
sharugupta/OpenUH
|
daddd76858a53035f5d713f648d13373c22506e8
|
[
"BSD-2-Clause"
] | null | null | null |
osprey/be/lno/array_bounds.cxx
|
sharugupta/OpenUH
|
daddd76858a53035f5d713f648d13373c22506e8
|
[
"BSD-2-Clause"
] | null | null | null |
/*
Copyright (C) 2000, 2001 Silicon Graphics, Inc. All Rights Reserved.
This program is free software; you can redistribute it and/or modify it
under the terms of version 2 of the GNU General Public License as
published by the Free Software Foundation.
This program is distributed in the hope that it would be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Further, this software is distributed without any warranty that it is
free of the rightful claim of any third person regarding infringement
or the like. Any license provided herein, whether implied or
otherwise, applies only to this software file. Patent licenses, if
any, provided herein do not apply to combinations of this program with
other software, or any other product whatsoever.
You should have received a copy of the GNU General Public License along
with this program; if not, write the Free Software Foundation, Inc., 59
Temple Place - Suite 330, Boston MA 02111-1307, USA.
Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky,
Mountain View, CA 94043, or:
http://www.sgi.com
For further information regarding this notice, see:
http://oss.sgi.com/projects/GenInfo/NoticeExplan
*/
#ifdef USE_PCH
#include "lno_pch.h"
#endif // USE_PCH
#pragma hdrstop
#include <sys/types.h>
#include "lnopt_main.h"
#include "config.h"
#include "config_lno.h"
#include "strtab.h"
#include "stab.h"
#include "targ_const.h"
#include "lnoutils.h"
#include "wn_simp.h"
#include "stdlib.h"
#include "lwn_util.h"
#include "optimizer.h"
#include "opt_du.h"
#include "name.h"
#include "wintrinsic.h"
#include "lno_bv.h"
#include "dep_graph.h"
#include "debug.h"
#include "scalar_expand.h"
#include "cxx_memory.h"
#include "reduc.h"
#include "fiz_fuse.h"
#include "snl_utils.h"
#include "forward.h"
#include "minvariant.h"
#include "cond.h"
#include "move.h"
#include "ipl_lno_util.h"
#define MAX_NAME_SIZE 75
#define HMB_ABS_CODE_EXPANSION 1000
#define HMB_REL_CODE_EXPANSION 3
static INT preg_counter = 0;
enum HMB_BOUND {HMB_LEFT, HMB_RIGHT, HMB_NONE};
//-----------------------------------------------------------------------
// NAME: HMB_Invariant_In_Loop
// FUNCTION: Returns TRUE if all of the elements in 'wn_exp' are
// invariant with respect to loop 'wn_loop', FALSE otherwise.
//-----------------------------------------------------------------------
static BOOL HMB_Invariant_In_Loop(WN* wn_exp,
WN* wn_loop)
{
DU_MANAGER* du = Du_Mgr;
ARRAY_DIRECTED_GRAPH16* dg = Array_Dependence_Graph;
LWN_ITER* itr = LWN_WALK_TreeIter(wn_exp);
for (; itr != NULL; itr = LWN_WALK_TreeNext(itr)) {
WN* wn = itr->wn;
if (WN_operator(wn) == OPR_ILOAD) {
VINDEX16 v = dg->Get_Vertex(wn);
if (v == 0)
continue;
EINDEX16 e = 0;
for (e = dg->Get_In_Edge(v); e != 0; e = dg->Get_Next_In_Edge(e)) {
WN* wn_source = dg->Get_Wn(dg->Get_Source(e));
if (Wn_Is_Inside(wn_source, wn_loop))
return FALSE;
}
for (e = dg->Get_Out_Edge(v); e != 0; e = dg->Get_Next_Out_Edge(e)) {
WN* wn_sink = dg->Get_Wn(dg->Get_Sink(e));
if (Wn_Is_Inside(wn_sink, wn_loop))
return FALSE;
}
} else if (WN_operator(wn) == OPR_LDID
|| WN_operator(wn) == OPR_PARM) {
DEF_LIST* def_list = du->Ud_Get_Def(wn);
DEF_LIST_ITER iter(def_list);
const DU_NODE* node = NULL;
for (node = iter.First(); !iter.Is_Empty(); node = iter.Next()) {
WN* wn_def = node->Wn();
if (Wn_Is_Inside(wn_def, wn_loop))
return FALSE;
}
}
}
return TRUE;
}
//-----------------------------------------------------------------------
// NAME: HMB_Copy_Array_Deps
// FUNCTION: Copy the array dependences for the node 'wn_orig' to those in
// 'wn_copy', updating them as appropriate because their locations in the
// program unit tree are slightly different. The boolean 'inside_loop'
// indicates if the nodes in the expression 'wn_copy' are inside a loop.
//-----------------------------------------------------------------------
static void HMB_Copy_Array_Deps(WN* wn_orig,
WN* wn_copy,
BOOL inside_loop,
LS_IN_LOOP* loop_ls)
{
ARRAY_DIRECTED_GRAPH16* dg = Array_Dependence_Graph;
DOLOOP_STACK copy_stack(&LNO_local_pool);
Build_Doloop_Stack(wn_copy, ©_stack);
LNO_Build_Access(WN_kid0(wn_copy), ©_stack, &LNO_default_pool);
if (!inside_loop)
return;
VINDEX16 v = dg->Get_Vertex(wn_orig);
if (v == 0)
return;
STACK<WN*> wn_stack(&LNO_local_pool);
EINDEX16 e = 0;
INT node_position = loop_ls->In(wn_orig);
for (e = dg->Get_In_Edge(v); e != 0; e = dg->Get_Next_In_Edge(e)) {
WN* wn_source = dg->Get_Wn(dg->Get_Source(e));
INT i;
for (i = 0; i < wn_stack.Elements(); i++)
if (wn_stack.Bottom_nth(i) == wn_source)
break;
if (i == wn_stack.Elements())
wn_stack.Push(wn_source);
}
for (e = dg->Get_Out_Edge(v); e != 0; e = dg->Get_Next_Out_Edge(e)) {
WN* wn_sink = dg->Get_Wn(dg->Get_Sink(e));
INT i;
for (i = 0; i < wn_stack.Elements(); i++)
if (wn_stack.Bottom_nth(i) == wn_sink)
break;
if (i == wn_stack.Elements())
wn_stack.Push(wn_sink);
}
dg->Add_Vertex(wn_copy);
DOLOOP_STACK other_stack(&LNO_local_pool);
INT i;
for (i = 0; i < wn_stack.Elements(); i++) {
WN* wn_other = wn_stack.Bottom_nth(i);
Build_Doloop_Stack(wn_other, &other_stack);
if (!dg->Add_Edge(wn_copy, ©_stack, wn_other, &other_stack,
node_position < loop_ls->In(wn_other))) {
LNO_Erase_Dg_From_Here_In(wn_other, dg);
}
other_stack.Clear();
}
}
//-----------------------------------------------------------------------
// NAME: HMB_Copy_Array_Deps_Exp
// FUNCTION: Copy the array dependences from the nodes in the expression
// rooted at 'wn_orig' to those in 'wn_copy', updating them as appro-
// priate because their locations in the program unit tree are slightly
// different. The boolean 'inside_loop' indicates if the nodes in the
// expression 'wn_copy' are inside a loop.
//-----------------------------------------------------------------------
static void HMB_Copy_Array_Deps_Exp(WN* wn_orig,
WN* wn_copy,
BOOL inside_loop,
LS_IN_LOOP* loop_ls)
{
ARRAY_DIRECTED_GRAPH16* dg = Array_Dependence_Graph;
if (WN_operator(wn_orig) == OPR_ILOAD)
HMB_Copy_Array_Deps(wn_orig, wn_copy, inside_loop, loop_ls);
for (INT i = 0; i < WN_kid_count(wn_orig); i++) {
WN* wn_orig_kid = WN_kid(wn_orig, i);
WN* wn_copy_kid = WN_kid(wn_copy, i);
HMB_Copy_Array_Deps_Exp(wn_orig_kid, wn_copy_kid, inside_loop, loop_ls);
}
}
//-----------------------------------------------------------------------
// NAME: HMB_Replace_Messy_Bounds
// FUNCTION: Replaces the expression 'wn_exp' with an LDID and defines
// that LDID outside the 'wn_hoist_loop' with an STID. The LDID and STID
// are both given the name 'name'.
//-----------------------------------------------------------------------
static void HMB_Replace_Messy_Bounds(WN* wn_exp,
WN* wn_hoist_loop,
HMB_BOUND bnd_type,
WN* wn_guard,
LS_IN_LOOP* loop_ls,
char name[],
WN* wn_bound)
{
if (LNO_Verbose) {
fprintf(stdout, " HMB: Replacing Messy Bound for Loop 0x%p\n",
wn_hoist_loop);
fprintf(TFile, " HMB: Replacing Messy Bound for Loop 0x%p\n",
wn_hoist_loop);
}
DU_MANAGER* du = Du_Mgr;
ARRAY_DIRECTED_GRAPH16* dg = Array_Dependence_Graph;
TYPE_ID type = WN_rtype(wn_exp);
#ifdef KEY //Bug 11381: retain the original type for messy loop bounds
//TODO: should unfold CVT
if(WN_opcode(wn_exp)==OPC_U4U8CVT || WN_opcode(wn_exp)==OPC_U4I8CVT){
TYPE_ID dtype = WN_desc(WN_kid0(wn_exp));
if(WN_operator(WN_kid0(wn_exp)) == OPR_ILOAD && dtype == MTYPE_I4)
type = MTYPE_I4;
}
#endif
OPCODE preg_s_opcode = OPCODE_make_op(OPR_STID, MTYPE_V, type);
OPCODE preg_l_opcode = OPCODE_make_op(OPR_LDID,
Promote_Type(OPCODE_desc(preg_s_opcode)), OPCODE_desc(preg_s_opcode));
if (wn_bound != NULL) {
WN* wn_ldid = LWN_CreateLdid(preg_l_opcode, wn_bound);
du->Add_Def_Use(wn_bound, wn_ldid);
WN* wn_parent = LWN_Get_Parent(wn_exp);
INT i;
for (i = 0; i < WN_kid_count(wn_parent); i++)
if (WN_kid(wn_parent, i) == wn_exp)
break;
LWN_Set_Parent(wn_ldid, wn_parent);
WN_kid(wn_parent, i) = wn_ldid;
LWN_Delete_Tree(wn_exp);
} else {
WN* wn_exp_copy = LWN_Copy_Tree(wn_exp);
LWN_Copy_Def_Use(wn_exp, wn_exp_copy, du);
#ifdef _NEW_SYMTAB
WN_OFFSET preg_num = Create_Preg(type, name);
#else
WN_OFFSET preg_num = Create_Preg(type, name, NULL);
#endif
ST* preg_st = MTYPE_To_PREG(type);
WN* wn_stid = LWN_CreateStid(preg_s_opcode, preg_num, preg_st,
Be_Type_Tbl(type), wn_exp_copy);
INT inside_loop = Do_Loop_Depth(wn_hoist_loop) > 0;
WN* wn_loop = wn_hoist_loop;
DO_LOOP_INFO* dli = Get_Do_Loop_Info(wn_loop);
WN* wn_insert = (bnd_type != HMB_NONE && wn_guard != NULL)
? wn_guard : wn_loop;
LWN_Insert_Block_Before(LWN_Get_Parent(wn_insert), wn_insert, wn_stid);
HMB_Copy_Array_Deps_Exp(wn_exp, wn_exp_copy, inside_loop, loop_ls);
WN* wn_ldid_copy = LWN_CreateLdid(preg_l_opcode, wn_stid);
WN* wn_ldid = Replace_Wnexp_With_Exp_Copy(wn_exp, wn_ldid_copy, du);
du->Add_Def_Use(wn_stid, wn_ldid);
if (bnd_type != HMB_NONE && wn_guard != NULL) {
WN* wn_guard_exp = bnd_type == HMB_LEFT
? WN_kid0(WN_if_test(wn_guard)) : WN_kid1(WN_if_test(wn_guard));
WN* wn_ldid = Replace_Wnexp_With_Exp_Copy(wn_guard_exp, wn_ldid_copy, du);
du->Add_Def_Use(wn_stid, wn_ldid);
}
LWN_Delete_Tree(wn_ldid_copy);
}
}
//-----------------------------------------------------------------------
// NAME: HMB_Has_Messy_Left_Bound
// FUNCTION: Returns TRUE if WN_start(wn_loop) gives rise to a messy
// bound. Returns FALSE otherwise.
//-----------------------------------------------------------------------
static BOOL HMB_Has_Messy_Left_Bound(WN* wn_loop)
{
DO_LOOP_INFO* dli = Get_Do_Loop_Info(wn_loop);
return (dli->Step->Const_Offset > 0)
? Bound_Is_Too_Messy(dli->LB) : Bound_Is_Too_Messy(dli->UB);
}
//-----------------------------------------------------------------------
// NAME: HMB_Has_Messy_Right_Bound
// FUNCTION: Returns TRUE if WN_end(wn_loop) gives rise to a messy
// bound. Returns FALSE otherwise.
//-----------------------------------------------------------------------
static BOOL HMB_Has_Messy_Right_Bound(WN* wn_loop)
{
DO_LOOP_INFO* dli = Get_Do_Loop_Info(wn_loop);
return (dli->Step->Const_Offset > 0)
? Bound_Is_Too_Messy(dli->UB) : Bound_Is_Too_Messy(dli->LB);
}
//-----------------------------------------------------------------------
// NAME: Bound_Exists
// FUNCTION: Return the index of a bound identical to 'wn_bound' in
// 'stk_bounds', if it exists, otherwise return NULL.
//-----------------------------------------------------------------------
static INT Bound_Exists(STACK<WN*>* stk_bounds,
WN* wn_bound)
{
for (INT i = 0; i < stk_bounds->Elements(); i++)
if (WN_Simp_Compare_Trees(WN_kid0(stk_bounds->Bottom_nth(i)),
wn_bound) == 0)
return i;
return -1;
}
//-----------------------------------------------------------------------
// NAME: Unique_Definition
// FUNCTION: Return the unique definition of 'wn_ldid' according to DU
// information. Assert if there is not a unique definition.
//-----------------------------------------------------------------------
static WN* Unique_Definition(WN* wn_ldid)
{
DU_MANAGER* du = Du_Mgr;
DEF_LIST *def_list = du->Ud_Get_Def(wn_ldid);
DEF_LIST_ITER iter(def_list);
INT count = 0;
WN* wn_stid = NULL;
const DU_NODE* node = NULL;
for (node = iter.First(); !iter.Is_Empty(); node = iter.Next()) {
wn_stid = node->Wn();
count++;
}
FmtAssert(count == 1, ("Unique_Definition: Def not Unique"));
return wn_stid;
}
//-----------------------------------------------------------------------
// NAME: HMB_Replace_Messy_Bounds_Loop
// FUNCTION: Replace all of the messy bounds of the loop 'wn_loop' with
// LDIDs and define those LDIDs outside the 'wn_hoist_loop' with STIDs.
//-----------------------------------------------------------------------
static void HMB_Replace_Messy_Bounds_Loop(WN* wn_loop,
WN* wn_hoist_loop,
WN* wn_guard,
STACK<WN*>* stk_bounds,
LS_IN_LOOP* loop_ls)
{
FmtAssert(WN_opcode(wn_loop) == OPC_DO_LOOP,
("HMB_Replace_Messy_Bounds_Loop: First arg must be do loop"));
FmtAssert(WN_opcode(wn_hoist_loop) == OPC_DO_LOOP,
("HMB_Replace_Messy_Bounds_Loop: Second arg must be do loop"));
FmtAssert(Do_Loop_Depth(wn_loop) >= Do_Loop_Depth(wn_hoist_loop),
("HMB_Replace_Messy_Bounds_Loop: Loop must be inside hoist loop"));
char buffer[MAX_NAME_SIZE];
DOLOOP_STACK stack(&LNO_local_pool);
if (HMB_Has_Messy_Left_Bound(wn_loop)) {
INT stk_number = Bound_Exists(stk_bounds, WN_kid0(WN_start(wn_loop)));
if (stk_number >= 0) {
sprintf(buffer, "_ab%d", stk_number);
HMB_Replace_Messy_Bounds(WN_kid0(WN_start(wn_loop)), wn_hoist_loop,
HMB_RIGHT, wn_guard, loop_ls, buffer,
stk_bounds->Bottom_nth(stk_number));
} else {
sprintf(buffer, "_ab%d", preg_counter++);
HMB_Replace_Messy_Bounds(WN_kid0(WN_start(wn_loop)), wn_hoist_loop,
HMB_RIGHT, wn_guard, loop_ls, buffer, NULL);
stk_bounds->Push(Unique_Definition(WN_kid0(WN_start(wn_loop))));
}
Build_Doloop_Stack(LWN_Get_Parent(wn_loop), &stack);
LNO_Build_Do_Access(wn_loop, &stack);
stack.Clear();
}
if (HMB_Has_Messy_Right_Bound(wn_loop)) {
INT stk_number = Bound_Exists(stk_bounds, UBexp(WN_end(wn_loop)));
if (stk_number >= 0) {
sprintf(buffer, "_ab%d", stk_number);
HMB_Replace_Messy_Bounds(UBexp(WN_end(wn_loop)), wn_hoist_loop,
HMB_LEFT, wn_guard, loop_ls, buffer,
stk_bounds->Bottom_nth(stk_number));
} else {
sprintf(buffer, "_ab%d", preg_counter++);
HMB_Replace_Messy_Bounds(UBexp(WN_end(wn_loop)), wn_hoist_loop,
HMB_LEFT, wn_guard, loop_ls, buffer, NULL);
stk_bounds->Push(Unique_Definition(WN_kid1(WN_end(wn_loop))));
}
Build_Doloop_Stack(LWN_Get_Parent(wn_loop), &stack);
LNO_Build_Do_Access(wn_loop, &stack);
stack.Clear();
}
}
//-----------------------------------------------------------------------
// NAME: Code_Expansion_Limit_Loop
// FUNCTION: For the innermost SNL of loops with outermost loop 'wn_outer'
// determine the outermost loop for which we can perform messy bounds
// hoisting without exceeding the allowed code expansion limit.
//-----------------------------------------------------------------------
static WN* Code_Expansion_Limit_Loop(WN* wn_outer)
{
INT nloops = SNL_Loop_Count(wn_outer);
WN* wn_inner = SNL_Get_Inner_Snl_Loop(wn_outer, nloops);
INT outer_depth = Do_Loop_Depth(wn_outer);
INT inner_depth = Do_Loop_Depth(wn_inner);
INT* node_counts = CXX_NEW_ARRAY(INT, inner_depth + 1, &LNO_local_pool);
WN* wn_loop = wn_outer;
INT i;
for (i = outer_depth; i <= inner_depth; i++) {
node_counts[i] = 1;
node_counts[i] += Node_Count(WN_index(wn_loop));
node_counts[i] += Node_Count(WN_start(wn_loop));
node_counts[i] += Node_Count(WN_end(wn_loop));
node_counts[i] += Node_Count(WN_step(wn_loop));
node_counts[i]++;
WN* wn_first = WN_first(WN_do_body(wn_loop));
for (WN* wn = wn_first; wn != NULL; wn = WN_next(wn)) {
if (WN_opcode(wn) == OPC_DO_LOOP)
continue;
node_counts[i] += Node_Count(wn);
}
wn_loop = Find_Next_Innermost_Do(wn_loop);
}
WN* wn_result = NULL;
wn_loop = wn_inner;
for (i = inner_depth; i >= outer_depth; i--) {
INT old_count = 0;
INT new_count = 0;
INT factor = inner_depth - i + 1;
old_count += node_counts[i];
new_count += factor * node_counts[i];
FmtAssert(new_count >= old_count,
("Code_Expansion_Limit_Loop: Code Expansion must be >= 1"));
if (new_count > HMB_REL_CODE_EXPANSION * old_count
&& new_count > HMB_ABS_CODE_EXPANSION)
break;
wn_result = wn_loop;
if (wn_result == wn_outer)
break;
wn_loop = Enclosing_Do_Loop(LWN_Get_Parent(wn_loop));
}
return wn_result;
}
//-----------------------------------------------------------------------
// NAME: HMB_Maximum_Point
// FUNCTION: Returns the loop within the singly nested loop nest 'wn_snl'
// which has the following properties:
// (1) All loops enclosed by this loop and the loop itself have their
// bounds in standard form, as determined by Upper_Bound_Standardize()
// (2) All loops have constant step. (This is ensured by preopt, but
// we are checking again, just to be sure.)
// (3) All array elements in the bounds of loops enclosed by this loop
// are invariant with respect to this loop.
// Returns NULL if none of the loops in the singly nested loop nest
// 'wn_snl' meets both criteria above.
//-----------------------------------------------------------------------
static WN* HMB_Maximum_Point(WN* wn_snl)
{
WN* wn_last = NULL;
// Find innermost loop
WN* wnn = NULL;
WN* wn = 0;
for (wn = wn_snl; wn != NULL; wnn = wn, wn = Find_Next_Innermost_Do(wn));
WN* wn_inner = wnn;
// Ensure that no loop has gotos
for (wn = wn_inner; wn != LWN_Get_Parent(wn_snl); wn = LWN_Get_Parent(wn)) {
if (WN_opcode(wn) != OPC_DO_LOOP)
continue;
DO_LOOP_INFO* dli = Get_Do_Loop_Info(wn);
if (dli->Has_Gotos)
break;
wn_last = wn;
}
if (wn_last == NULL)
return NULL;
// Ensure that Upper_Bound_Standardize() is TRUE for all loops
WN* wn_max = wn_last;
wn_last = NULL;
WN* wn_final = LWN_Get_Parent(wn_max);
for (wn = wn_inner; wn != wn_final; wn = LWN_Get_Parent(wn)) {
if (WN_opcode(wn) != OPC_DO_LOOP)
continue;
if (!Upper_Bound_Standardize(WN_end(wn), TRUE))
break;
wn_last = wn;
}
if (wn_last == NULL)
return NULL;
// Ensure all loops have constant step
wn_max = wn_last;
wn_last = NULL;
wn_final = LWN_Get_Parent(wn_max);
for (wn = wn_inner; wn != wn_final; wn = LWN_Get_Parent(wn)) {
if (WN_opcode(wn) != OPC_DO_LOOP)
continue;
DO_LOOP_INFO* dli = Get_Do_Loop_Info(wn);
if (!dli->Step->Is_Const())
break;
wn_last = wn;
}
if (wn_last == NULL)
return NULL;
// Ensure that all arrays in bounds are nest invariant and that all
// bounds are promotable through non-invariant loops
wn_max = wn_last;
wn_last = NULL;
DOLOOP_STACK stk_loop(&LNO_local_pool);
Build_Doloop_Stack(wn_inner, &stk_loop);
for (WN* wn_try = wn_inner; wn_try != LWN_Get_Parent(wn_max);
wn_try = LWN_Get_Parent(wn_try)) {
if (WN_opcode(wn_try) != OPC_DO_LOOP)
continue;
for (wn = wn_inner; wn != wn_try; wn = LWN_Get_Parent(wn)) {
if (WN_opcode(wn) != OPC_DO_LOOP)
continue;
if (!HMB_Invariant_In_Loop(WN_kid0(WN_start(wn)), wn_try))
break;
if (!HMB_Invariant_In_Loop(UBexp(WN_end(wn)), wn_try))
break;
}
if (wn != wn_try)
return wn_last;
wn_last = wn_try;
}
return wn_last;
}
//-----------------------------------------------------------------------
// NAME: Tree_Has_Regions
// FUNCTION: Returns TRUE if the tree rooted at 'wn_tree' has a REGION
// node, FALSE otherwise.
//-----------------------------------------------------------------------
extern BOOL Tree_Has_Regions(WN* wn_tree)
{
if (WN_opcode(wn_tree) == OPC_REGION)
return TRUE;
if (WN_opcode(wn_tree) == OPC_BLOCK) {
for (WN* wn = WN_first(wn_tree); wn != NULL; wn = WN_next(wn))
if (Tree_Has_Regions(wn))
return TRUE;
} else {
for (INT i = 0; i < WN_kid_count(wn_tree); i++)
if (Tree_Has_Regions(WN_kid(wn_tree, i)))
return TRUE;
}
return FALSE;
}
//-----------------------------------------------------------------------
// NAME: Guard_Test_Redundant
// FUNCTION: Returns TRUE if the guard test for the loop 'wn_loop' is
// provably redundant. Returns FALSE if it is not or we can't tell.
//-----------------------------------------------------------------------
static BOOL Guard_Test_Redundant(WN* wn_loop,
WN* wn_guards[],
INT depth)
{
DU_MANAGER* du = Du_Mgr;
BOOL return_value = FALSE;
WN* wn_parent = LWN_Get_Parent(wn_loop);
COND_BOUNDS_INFO *info =
CXX_NEW(COND_BOUNDS_INFO(&LNO_local_pool), &LNO_local_pool);
info->Collect_Outer_Info(wn_parent);
WN* wn_test = LWN_Copy_Tree(WN_end(wn_loop));
LWN_Copy_Def_Use(WN_end(wn_loop), wn_test, du);
Replace_Ldid_With_Exp_Copy(SYMBOL(WN_start(wn_loop)), wn_test,
WN_kid0(WN_start(wn_loop)), du);
WN* wn_if = LWN_CreateIf(wn_test, WN_CreateBlock(), WN_CreateBlock());
LWN_Insert_Block_Before(LWN_Get_Parent(wn_loop), wn_loop, wn_if);
LWN_Extract_From_Block(wn_loop);
LWN_Insert_Block_After(WN_then(wn_if), NULL, wn_loop);
IF_INFO *ii = CXX_NEW(IF_INFO(&LNO_default_pool, TRUE,
Tree_Has_Regions(wn_loop)), &LNO_default_pool);
WN_MAP_Set(LNO_Info_Map, wn_if, (void *) ii);
return_value = Redundant_Condition(info, wn_test, wn_if);
Forward_Substitute_Ldids(wn_test, du);
wn_guards[depth] = LWN_Copy_Tree(wn_test);
LWN_Copy_Def_Use(wn_test, wn_guards[depth], du);
LWN_Extract_From_Block(wn_loop);
LWN_Insert_Block_Before(LWN_Get_Parent(wn_if), wn_if, wn_loop);
LWN_Extract_From_Block(wn_if);
LWN_Delete_Tree(wn_if);
if (return_value == FALSE) {
for (INT i = 0; i < depth; i++) {
if (wn_guards[i] != NULL
&& WN_Simp_Compare_Trees(wn_guards[i], wn_guards[depth]) == 0) {
return_value = TRUE;
break;
}
}
}
return return_value;
}
//-----------------------------------------------------------------------
// NAME: HMB_Add_Guard_Condition
// FUNCTION: For the loop 'wn_loop' in the SNL 'wn_snl' for which we are
// creating the guard test 'wn_if', compute a guard condition corres-
// ponding to 'wn_loop' and .CAND. it with any existing conditions
// already present in 'WN_if_test(wn_if)'.
//-----------------------------------------------------------------------
static void HMB_Add_Guard_Condition(WN* wn_loop,
WN* wn_snl,
WN* wn_if,
LS_IN_LOOP* loop_ls)
{
DU_MANAGER* du = Du_Mgr;
OPCODE op_cand = OPCODE_make_op(OPR_CAND, Boolean_type, MTYPE_V);
WN* wn_upper_bound = LWN_Copy_Tree(UBexp(WN_end(wn_loop)));
LWN_Copy_Def_Use(UBexp(WN_end(wn_loop)), wn_upper_bound, du);
WN* wn_lower_bound = LWN_Copy_Tree(WN_kid0(WN_start(wn_loop)));
LWN_Copy_Def_Use(WN_kid0(WN_start(wn_loop)), wn_lower_bound, du);
BOOL saved_fold_enable = WN_Simplifier_Enable(FALSE);
OPCODE op_cond = OPCODE_make_op(OPR_GE, Boolean_type,
WN_rtype(wn_upper_bound));
WN* wn_cond = LWN_CreateExp2(op_cond, wn_upper_bound, wn_lower_bound);
if (WN_if_test(wn_if) == NULL)
WN_if_test(wn_if) = wn_cond;
else
WN_if_test(wn_if) = LWN_CreateExp2(op_cand, WN_if_test(wn_if), wn_cond); LWN_Set_Parent(WN_if_test(wn_if), wn_if);
BOOL inside_loop = Do_Loop_Depth(wn_snl) > 0;
HMB_Copy_Array_Deps_Exp(UBexp(WN_end(wn_loop)), wn_upper_bound,
inside_loop, loop_ls);
HMB_Copy_Array_Deps_Exp(WN_kid0(WN_start(wn_loop)), wn_lower_bound,
inside_loop, loop_ls);
WN_Simplifier_Enable(saved_fold_enable);
}
//-----------------------------------------------------------------------
// NAME: HMB_Simple_Guard_Test
// FUNCTION: Returns an IF node with a guard test for the loop 'wn_loop'
// in the SNL 'wn_snl'. The guard test is inserted into the program
// tree around the loop 'wn_snl'.
//-----------------------------------------------------------------------
static WN* HMB_Simple_Guard_Test(WN* wn_loop,
WN* wn_snl,
LS_IN_LOOP* loop_ls)
{
WN* wn_if = LWN_CreateIf(NULL, WN_CreateBlock(), WN_CreateBlock());
WN_Set_Linenum(wn_if, WN_Get_Linenum(wn_snl));
LWN_Insert_Block_After(LWN_Get_Parent(wn_snl), wn_snl, wn_if);
LWN_Extract_From_Block(wn_snl);
LWN_Insert_Block_After(WN_then(wn_if), NULL, wn_snl);
HMB_Add_Guard_Condition(wn_loop, wn_snl, wn_if, loop_ls);
IF_INFO *ii = CXX_NEW(IF_INFO(&LNO_default_pool, TRUE,
Tree_Has_Regions(wn_snl)), &LNO_default_pool);
WN_MAP_Set(LNO_Info_Map, wn_if, (void *) ii);
DOLOOP_STACK stack(&LNO_local_pool);
Build_Doloop_Stack(wn_if, &stack);
LNO_Build_If_Access(wn_if, &stack);
return wn_if;
}
//-----------------------------------------------------------------------
// NAME: HMB_Compound_Guard_Test
// FUNCTION: Returns an IF node with a guard test for the SNL 'wn_snl'.
// The 'guard_mask' has a bit set for each loop in the SNL for which
// we must generate a guard. The guard test is inserted into the program
// tree around the loop 'wn_snl'.
//-----------------------------------------------------------------------
static WN* HMB_Compound_Guard_Test(WN* wn_snl,
INT guard_mask,
LS_IN_LOOP* loop_ls)
{
if (guard_mask == 0)
return NULL;
INT nloops = SNL_Loop_Count(wn_snl);
INT outer_depth = Do_Loop_Depth(wn_snl);
INT inner_depth = outer_depth + nloops - 1;
INT test_guard_mask = guard_mask;
WN* wn_if = LWN_CreateIf(NULL, WN_CreateBlock(), WN_CreateBlock());
WN_Set_Linenum(wn_if, WN_Get_Linenum(wn_snl));
LWN_Insert_Block_After(LWN_Get_Parent(wn_snl), wn_snl, wn_if);
LWN_Extract_From_Block(wn_snl);
LWN_Insert_Block_After(WN_then(wn_if), NULL, wn_snl);
OPCODE op_cand = OPCODE_make_op(OPR_CAND, Boolean_type, MTYPE_V);
WN* wn_loop = wn_snl;
for (INT i = outer_depth; i <= inner_depth; i++) {
if (guard_mask & (1 << i))
HMB_Add_Guard_Condition(wn_loop, wn_snl, wn_if, loop_ls);
wn_loop = Find_Next_Innermost_Do(wn_loop);
}
IF_INFO *ii = CXX_NEW(IF_INFO(&LNO_default_pool, TRUE,
Tree_Has_Regions(wn_snl)), &LNO_default_pool);
WN_MAP_Set(LNO_Info_Map, wn_if, (void *) ii);
DOLOOP_STACK stack(&LNO_local_pool);
Build_Doloop_Stack(wn_if, &stack);
LNO_Build_If_Access(wn_if, &stack);
return wn_if;
}
//-----------------------------------------------------------------------
// NAME: Has_Code_At_Depth
// FUNCTION: Returns TRUE if there is sandwiched code in the SNL 'wn_snl'
// at the given 'depth'. Returns FALSE otherwise.
//-----------------------------------------------------------------------
static BOOL Has_Code_At_Depth(WN* wn_snl,
INT nloops,
INT depth)
{
INT outer_depth = Do_Loop_Depth(wn_snl);
INT inner_depth = outer_depth + nloops - 1;
FmtAssert(depth >= outer_depth && depth <= inner_depth,
("Has_Code_At_Depth: Illegal depth"));
if (depth == inner_depth)
return TRUE;
WN* wn_inner = SNL_Get_Inner_Snl_Loop(wn_snl, depth - outer_depth + 2);
WN* wn = 0;
for (wn = WN_prev(wn_inner); wn != NULL; wn = WN_prev(wn))
if (!OPCODE_is_not_executable(WN_opcode(wn)))
return TRUE;
for (wn = WN_next(wn_inner); wn != NULL; wn = WN_next(wn))
if (!OPCODE_is_not_executable(WN_opcode(wn)))
return TRUE;
return FALSE;
}
//-----------------------------------------------------------------------
// NAME: Contains_Index_Variable
// FUNCTION: Returns TRUE if 'wn_tree' contains an index variable,
// FALSE otherwise.
//-----------------------------------------------------------------------
static BOOL Contains_Index_Variable(WN* wn_tree)
{
if (WN_operator(wn_tree) == OPR_LDID) {
WN* wn = 0;
for (wn = wn_tree; wn != NULL; wn = LWN_Get_Parent(wn))
if (WN_opcode(wn) == OPC_DO_LOOP
&& SYMBOL(WN_index(wn)) == SYMBOL(wn_tree))
break;
if (wn != NULL)
return TRUE;
}
for (INT i = 0; i < WN_kid_count(wn_tree); i++)
if (Contains_Index_Variable(WN_kid(wn_tree, i)))
return TRUE;
return FALSE;
}
//-----------------------------------------------------------------------
// NAME: Contains_Vertex
// FUNCTION: Returns TRUE if the expression 'wn_exp' has a dependence
// graph vertex (or should). Returns FALSE otherwise.
//-----------------------------------------------------------------------
static BOOL Contains_Vertex(WN* wn_exp)
{
ARRAY_DIRECTED_GRAPH16* dg = Array_Dependence_Graph;
LWN_ITER* itr = LWN_WALK_TreeIter(wn_exp);
for (; itr != NULL; itr = LWN_WALK_TreeNext(itr))
if (OPCODE_is_load(WN_opcode(itr->wn))
&& (WN_operator(itr->wn) == OPR_ILOAD
|| dg->Get_Vertex(itr->wn)))
return TRUE;
return FALSE;
}
//-----------------------------------------------------------------------
// NAME: Is_Messy_Expression
// FUNCTION: Returns TRUE if 'wn_tree' is a candidate expression for
// hoisting. If 'need_safe' is TRUE, it must be statically safe for
// hoisting or it is not a candidate.
//-----------------------------------------------------------------------
static BOOL Is_Messy_Expression(WN* wn_tree,
BOOL need_safe)
{
OPERATOR opr = WN_operator(wn_tree);
return WN_kid_count(wn_tree) > 0 && (opr != OPR_ADD && opr != OPR_SUB
&& opr != OPR_MPY && opr != OPR_NEG)
&& (!need_safe || Statically_Safe_Exp(wn_tree))
&& !Contains_Index_Variable(wn_tree) && !Contains_Vertex(wn_tree);
}
//-----------------------------------------------------------------------
// NAME: HMB_Push_Messy_Expressions
// FUNCTION: Scan 'wn_tree' for expressions which are messy, do not contain
// index variables or dependence graph vertices, and push them on the
// stack 'stk_messy'. If 'need_safe' only push those which are safe
// to speculate.
//-----------------------------------------------------------------------
static void HMB_Push_Messy_Expressions(WN* wn_tree,
BOOL need_safe,
STACK<WN*>* stk_messy)
{
DU_MANAGER* du = Du_Mgr;
INT i;
for (i = 0; i < WN_kid_count(wn_tree); i++)
HMB_Push_Messy_Expressions(WN_kid(wn_tree, i), need_safe, stk_messy);
if (Is_Messy_Expression(wn_tree, need_safe)
&& Hoistable_Statement(wn_tree, du) < Loop_Depth(wn_tree)) {
INT i;
for (i = 0; i < stk_messy->Elements(); i++)
if (stk_messy->Bottom_nth(i) == wn_tree)
break;
if (i == stk_messy->Elements())
stk_messy->Push(wn_tree);
}
}
//-----------------------------------------------------------------------
// NAME: HMB_Find_Messy_Subscripts
// FUNCTION: For the SNL 'wn_loop', find the messy expressions which are
// candidates for hoisting in 'wn_loop' and push them on 'stk_messy'.
// If 'need_safe', only include those which are safe to speculate.
//-----------------------------------------------------------------------
static void HMB_Find_Messy_Subscripts(WN* wn_loop,
BOOL need_safe,
STACK<WN*>* stk_messy)
{
DU_MANAGER* du = Du_Mgr;
STACK<WN*>* stk_subs = CXX_NEW(STACK<WN*>(&LNO_local_pool), &LNO_local_pool);
LWN_ITER* itr = LWN_WALK_TreeIter(wn_loop);
for (; itr != NULL; itr = LWN_WALK_TreeNext(itr)) {
WN* wn_array = itr->wn;
if (WN_operator(wn_array) == OPR_ARRAY) {
ACCESS_ARRAY* aa = (ACCESS_ARRAY*) WN_MAP_Get(LNO_Info_Map, wn_array);
FmtAssert(aa != NULL,
("HMB_Find_Messy_Subscripts: Missing access array on OPR_ARRAY node"));
if (Bound_Is_Too_Messy(aa))
HMB_Push_Messy_Expressions(wn_array, need_safe, stk_messy);
}
}
}
//-----------------------------------------------------------------------
// NAME: HMB_Hoist_Messy_Subscripts
// FUNCTION: For the SNL 'wn_loop', hoist each of the expressions in the
// list 'stk_messy'.
//-----------------------------------------------------------------------
static void HMB_Hoist_Messy_Subscripts(WN* wn_loop,
STACK<WN*>* stk_messy,
STACK<WN*>* stk_bounds,
LS_IN_LOOP* loop_ls)
{
DU_MANAGER* du = Du_Mgr;
ARRAY_DIRECTED_GRAPH16* dg = Array_Dependence_Graph;
char buffer[MAX_NAME_SIZE];
DYN_ARRAY<WN*> new_uses(&LNO_local_pool);
DYN_ARRAY<WN*> parent_uses(&LNO_local_pool);
for (INT j = 0; j < stk_messy->Elements(); j++) {
WN* wn_messy_kid = stk_messy->Bottom_nth(j);
WN* wn_messy = LWN_Get_Parent(wn_messy_kid);
// Don't copy any expression without first updating the dependences
// for any new expressions inside it.
for (INT k = new_uses.Elements() - 1; k >= 0; k--) {
WN* wn_use = new_uses[k];
for (WN* wn = wn_use; wn != NULL; wn = LWN_Get_Parent(wn)) {
if (wn == wn_messy) {
parent_uses.AddElement(wn_use);
for (INT m = k + 1; m < new_uses.Elements(); m++)
new_uses[m-1] = new_uses[m];
new_uses.Decidx();
}
}
}
if (parent_uses.Elements() > 0) {
MIR_Update_Dependences(wn_loop, &parent_uses);
parent_uses.Resetidx();
}
INT hoist_level = Hoistable_Statement(wn_messy_kid, du);
WN* wn = 0;
for (wn = wn_messy_kid; wn != NULL; wn = LWN_Get_Parent(wn))
if (WN_opcode(wn) == OPC_DO_LOOP
&& Do_Loop_Depth(wn) == hoist_level + 1)
break;
WN* wn_hoist_loop = wn;
FmtAssert(wn_hoist_loop != NULL,
("HMB_Hoist_Messy_Subscripts: Could not find hoist loop"));
INT stk_number = Bound_Exists(stk_bounds, wn_messy_kid);
if (stk_number >= 0) {
sprintf(buffer, "_ab%d", stk_number);
HMB_Replace_Messy_Bounds(wn_messy_kid, wn_hoist_loop, HMB_NONE,
NULL, loop_ls, buffer, stk_bounds->Bottom_nth(stk_number));
} else {
sprintf(buffer, "_ab%d", preg_counter++);
WN* wn_parent = LWN_Get_Parent(wn_messy_kid);
INT i;
for (i = 0; i < WN_kid_count(wn_parent); i++)
if (WN_kid(wn_parent, i) == wn_messy_kid)
break;
INT kid = i;
HMB_Replace_Messy_Bounds(wn_messy_kid, wn_hoist_loop, HMB_NONE,
NULL, loop_ls, buffer, NULL);
stk_bounds->Push(Unique_Definition(WN_kid(wn_parent, kid)));
}
for (wn = wn_messy; wn != NULL; wn = LWN_Get_Parent(wn))
if (WN_operator(wn) == OPR_ARRAY)
break;
WN* wn_rebuild = wn;
DOLOOP_STACK do_stack(&LNO_local_pool);
Build_Doloop_Stack(LWN_Get_Parent(wn_rebuild), &do_stack);
LNO_Build_Access(wn_rebuild, &do_stack, &LNO_default_pool);
INT i;
for (i = 0; i < new_uses.Elements(); i++)
if (new_uses[i] == wn_messy)
break;
if (i == new_uses.Elements())
new_uses.AddElement(wn_messy);
}
MIR_Update_Dependences(wn_loop, &new_uses);
}
//-----------------------------------------------------------------------
// NAME: HMB_Find_and_Hoist_Messy_Subscripts
// FUNCTION: For the SNL 'wn_loop' find and hoist messy expressions in
// array subscripts that are hoistable. If 'need_safe', only do those
// which are safe to speculate.
//-----------------------------------------------------------------------
static void HMB_Find_and_Hoist_Messy_Subscripts(WN* wn_loop,
STACK<WN*>* stk_bounds,
BOOL need_safe,
LS_IN_LOOP* loop_ls)
{
STACK<WN*>* stk_messy = CXX_NEW(STACK<WN*>(&LNO_local_pool),
&LNO_local_pool);
while (TRUE) {
stk_messy->Clear();
HMB_Find_Messy_Subscripts(wn_loop, need_safe, stk_messy);
if (stk_messy->Elements() == 0)
return;
HMB_Hoist_Messy_Subscripts(wn_loop, stk_messy, stk_bounds, loop_ls);
}
}
//-----------------------------------------------------------------------
// NAME: HMB_Similar_Group
// FUNCTION: Remove a group of expressions containing divides each of
// which has the same value from 'stk_messy' and place them in
// 'stk_group'.
//-----------------------------------------------------------------------
static void HMB_Similar_Group(STACK<WN*>* stk_messy,
STACK<WN*>* stk_group)
{
STACK<WN*> local_stack(&LNO_local_pool);
WN* wn_pattern = stk_messy->Pop();
stk_group->Push(wn_pattern);
while (stk_messy->Elements() > 0) {
WN* wn_trial = stk_messy->Pop();
if (WN_Simp_Compare_Trees(wn_pattern, wn_trial) == 0)
stk_group->Push(wn_trial);
else
local_stack.Push(wn_trial);
}
while (local_stack.Elements() > 0)
stk_messy->Push(local_stack.Pop());
}
//-----------------------------------------------------------------------
// NAME: HMB_Hoist_Expressions
// FUNCTION: Hoist all of the expressions on 'stk_messy'.
//-----------------------------------------------------------------------
static void HMB_Hoist_Expressions(WN* wn_loop,
STACK<WN*>* stk_messy)
{
DU_MANAGER* du = Du_Mgr;
char buffer[MAX_NAME_SIZE];
STACK<WN*> stk_group(&LNO_local_pool);
while (stk_messy->Elements() > 0) {
sprintf(buffer, "_mb%d", preg_counter++);
HMB_Similar_Group(stk_messy, &stk_group);
WN* wn_pattern = stk_group.Bottom_nth(0);
TYPE_ID type = WN_rtype(wn_pattern);
OPCODE preg_l_opcode = OPCODE_make_op(OPR_LDID, Promote_Type(type), type);
OPCODE preg_s_opcode = OPCODE_make_op(OPR_STID, MTYPE_V, type);
#ifdef _NEW_SYMTAB
WN_OFFSET preg_num = Create_Preg(type, buffer);
#else
WN_OFFSET preg_num = Create_Preg(type, buffer, NULL);
#endif
ST* preg_st = MTYPE_To_PREG(type);
WN* wn_hoist_place = Hoistable_Place(wn_pattern, du);
WN* wn_parent = LWN_Get_Parent(wn_pattern);
WN* wn_stid = LWN_CreateStid(preg_s_opcode, preg_num, preg_st,
Be_Type_Tbl(type), wn_pattern);
WN* wn_ldid = LWN_CreateLdid(preg_l_opcode, wn_stid);
INT j;
for (j = 0; j < WN_kid_count(wn_parent); j++)
if (WN_kid(wn_parent, j) == wn_pattern)
break;
FmtAssert(j < WN_kid_count(wn_parent),
("Could not find kid for parent."));
INT kid = j;
WN_kid(wn_parent, kid) = wn_ldid;
LWN_Set_Parent(wn_ldid, wn_parent);
du->Add_Def_Use(wn_stid, wn_ldid);
LWN_Insert_Block_Before(LWN_Get_Parent(wn_hoist_place),
wn_hoist_place, wn_stid);
INT i;
for (i = 1; i < stk_group.Elements(); i++) {
WN* wn_div_exp = stk_group.Bottom_nth(i);
WN* wn_parent = LWN_Get_Parent(wn_div_exp);
WN* wn_ldid = LWN_CreateLdid(preg_l_opcode, wn_stid);
INT j;
for (j = 0; j < WN_kid_count(wn_parent); j++)
if (WN_kid(wn_parent, j) == wn_div_exp)
break;
FmtAssert(j < WN_kid_count(wn_parent),
("Could not find kid for parent."));
INT kid = j;
WN_kid(wn_parent, kid) = wn_ldid;
LWN_Set_Parent(wn_ldid, wn_parent);
du->Add_Def_Use(wn_stid, wn_ldid);
LWN_Delete_Tree(wn_div_exp);
}
}
DOLOOP_STACK rebuild_stack(&LNO_local_pool);
Build_Doloop_Stack(LWN_Get_Parent(wn_loop), &rebuild_stack);
LNO_Build_Access(wn_loop, &rebuild_stack, &LNO_default_pool);
}
//-----------------------------------------------------------------------
// NAME: HMB_Compound_Guard_And_Hoist
// FUNCTION: Given the 'version_count' new versions of the code
// 'wn_version[i]' and 'guard_mask[i]' which tells us for each version
// of the code which loops in 'wn_version[i]' must be guarded, modify
// each 'wn_version[i]' to generate guards for each of the indicated
// loops, then hoist the messy bounds of in each version out of the
// loop nests and hoist subscripted array references out of the loops
// when possible.
//-----------------------------------------------------------------------
static void HMB_Compound_Guard_And_Hoist(WN* wn_version[],
INT guard_mask[],
INT version_count,
STACK<WN*>* stk_bounds,
LS_IN_LOOP* loop_ls,
BOOL no_messy_hoist)
{
// Create guard tests for each of the versions
WN* wn_nest = NULL;
WN* wn_last_nest = NULL;
INT i;
for (i = 0; i < version_count; i++) {
WN* wn_guard = HMB_Compound_Guard_Test(wn_version[i], guard_mask[i],
loop_ls);
wn_nest = wn_guard != NULL ? wn_guard : wn_version[i];
if (wn_last_nest != NULL) {
LWN_Extract_From_Block(wn_nest);
LWN_Insert_Block_After(WN_else(wn_last_nest), NULL, wn_nest);
}
wn_last_nest = wn_nest;
}
// Replace the messy and array subscripts in each version that needs
// them replaced.
for (i = 0; i < version_count; i++) {
INT stack_count = stk_bounds->Elements();
INT version_nloops = SNL_Loop_Count(wn_version[i]);
for (INT j = 1; j <= version_nloops; j++) {
WN* wn_loop = SNL_Get_Inner_Snl_Loop(wn_version[i], j);
HMB_Replace_Messy_Bounds_Loop(wn_loop, wn_version[i], NULL,
stk_bounds, loop_ls);
if (!no_messy_hoist)
MIR_Hoist_Messy_Subscripts(wn_version[i]);
}
HMB_Find_and_Hoist_Messy_Subscripts(wn_version[i], stk_bounds,
TRUE, loop_ls);
while (stk_bounds->Elements() > stack_count)
(void) stk_bounds->Pop();
}
}
//-----------------------------------------------------------------------
// NAME: HAB_Copy_Array_Deps
// FUNCTION: Copy the array dependences for the node 'wn_orig' to those in
// 'wn_copy', updating them as appropriate because their locations in the
// program unit tree are slightly different. The boolean 'inside_loop'
// indicates if the nodes in the expression 'wn_copy' are inside a loop.
//-----------------------------------------------------------------------
static void HAB_Copy_Array_Deps(WN* wn_orig,
WN* wn_copy,
BOOL inside_loop,
LS_IN_LOOP* loop_ls)
{
if (!inside_loop)
return;
ARRAY_DIRECTED_GRAPH16* dg = Array_Dependence_Graph;
DOLOOP_STACK copy_stack(&LNO_local_pool);
Build_Doloop_Stack(wn_copy, ©_stack);
LNO_Build_Access(WN_kid0(wn_copy), ©_stack, &LNO_default_pool);
VINDEX16 v = dg->Get_Vertex(wn_orig);
if (v == 0)
return;
STACK<WN*> wn_stack(&LNO_local_pool);
EINDEX16 e = 0;
INT node_position = loop_ls->In(wn_orig);
for (e = dg->Get_In_Edge(v); e != 0; e = dg->Get_Next_In_Edge(e)) {
WN* wn_source = dg->Get_Wn(dg->Get_Source(e));
INT i;
for (i = 0; i < wn_stack.Elements(); i++)
if (wn_stack.Bottom_nth(i) == wn_source)
break;
if (i == wn_stack.Elements())
wn_stack.Push(wn_source);
}
for (e = dg->Get_Out_Edge(v); e != 0; e = dg->Get_Next_Out_Edge(e)) {
WN* wn_sink = dg->Get_Wn(dg->Get_Sink(e));
INT i;
for (i = 0; i < wn_stack.Elements(); i++)
if (wn_stack.Bottom_nth(i) == wn_sink)
break;
if (i == wn_stack.Elements())
wn_stack.Push(wn_sink);
}
dg->Add_Vertex(wn_copy);
DOLOOP_STACK other_stack(&LNO_local_pool);
for (INT i = 0; i < wn_stack.Elements(); i++) {
WN* wn_other = wn_stack.Bottom_nth(i);
Build_Doloop_Stack(wn_other, &other_stack);
if (!dg->Add_Edge(wn_copy, ©_stack, wn_other, &other_stack,
node_position < loop_ls->In(wn_other))) {
LNO_Erase_Dg_From_Here_In(wn_other, dg);
}
other_stack.Clear();
}
}
//-----------------------------------------------------------------------
// NAME: HAB_Copy_Array_Deps_Exp
// FUNCTION: Copy the array dependences from the nodes in the expression
// rooted at 'wn_orig' to those in 'wn_copy', updating them as appro-
// priate because their locations in the program unit tree are slightly
// different. The boolean 'inside_loop' indicates if the nodes in the
// expression 'wn_copy' are inside a loop.
//-----------------------------------------------------------------------
static void HAB_Copy_Array_Deps_Exp(WN* wn_orig,
WN* wn_copy,
BOOL inside_loop,
LS_IN_LOOP* loop_ls)
{
if (WN_operator(wn_orig) == OPR_ILOAD)
HAB_Copy_Array_Deps(wn_orig, wn_copy, inside_loop, loop_ls);
for (INT i = 0; i < WN_kid_count(wn_orig); i++) {
WN* wn_orig_kid = WN_kid(wn_orig, i);
WN* wn_copy_kid = WN_kid(wn_copy, i);
HAB_Copy_Array_Deps_Exp(wn_orig_kid, wn_copy_kid, inside_loop, loop_ls);
}
}
//-----------------------------------------------------------------------
// NAME: HMB_Simple_Guard_And_Hoist
// FUNCTION: Given the new version of the code 'wn_version' and 'guard_mask'
// which tells us which loops in 'wn_version' must be guarded, modify
// 'wn_version' to generate guards for each of the indicated loops,
// then hoist the messy bounds out of 'wn_version' and hoist subscripted
// array references out of 'wn_version' when possible.
//-----------------------------------------------------------------------
static void HMB_Simple_Guard_And_Hoist(WN* wn_version,
INT guard_mask,
STACK<WN*>* stk_bounds,
LS_IN_LOOP* loop_ls,
BOOL no_messy_hoist)
{
INT nloops = SNL_Loop_Count(wn_version);
INT outer_depth = Do_Loop_Depth(wn_version);
INT inner_depth = outer_depth + nloops - 1;
WN** wn_guard = CXX_NEW_ARRAY(WN*, inner_depth + 1, &LNO_local_pool);
INT i;
for (i = 0; i < inner_depth + 1; i++)
wn_guard[i] = NULL;
WN* wn = 0;
for (wn = wn_version; wn != NULL; wn = Find_Next_Innermost_Do(wn)) {
INT current_depth = Do_Loop_Depth(wn);
if (guard_mask & (1 << current_depth)) {
WN* wn_guard_test = HMB_Simple_Guard_Test(wn, wn_version, loop_ls);
wn_guard[current_depth] = wn_guard_test;
}
}
for (wn = wn_version; wn != NULL; wn = Find_Next_Innermost_Do(wn)) {
INT current_depth = Do_Loop_Depth(wn);
HMB_Replace_Messy_Bounds_Loop(wn, wn_version, wn_guard[current_depth],
stk_bounds, loop_ls);
if (wn_guard[current_depth] != NULL)
LWN_Simplify_Tree(WN_if_test(wn_guard[current_depth]));
}
HMB_Find_and_Hoist_Messy_Subscripts(wn_version, stk_bounds, TRUE, loop_ls);
if (!no_messy_hoist)
MIR_Hoist_Messy_Subscripts(wn_version);
}
//-----------------------------------------------------------------------
// NAME: HMB_Has_Messy_Subscript
// FUNCTION: For the SNL 'wn_loop' which has candidate hoistable refer-
// ences on 'stk_messy', set the values of the arrays 'can_hoist[]' and
// 'lowest_depth[]'. The 'can_hoist[depth]' is the number of references
// which can be hoisted at loop depth 'depth'. The 'lowest_depth[depth]'
// is the lowest depth to which some hoistable array reference at loop
// depth 'depth' can be hoisted. If 'initialize', we initialize the
// 'can_hoist[]' and 'lowest_depth[]' arrays.
//-----------------------------------------------------------------------
static void HMB_Has_Messy_Subscript(WN* wn_loop,
STACK<WN*>* stk_messy,
INT can_hoist[],
INT lowest_depth[],
BOOL initialize)
{
DU_MANAGER* du = Du_Mgr;
STACK<WN*> local_stack(&LNO_local_pool);
if (initialize) {
INT count = SNL_Loop_Count(wn_loop);
WN* wn_inner = SNL_Get_Inner_Snl_Loop(wn_loop, count);
INT inner_depth = Do_Loop_Depth(wn_inner);
for (INT i = 0; i <= inner_depth; i++) {
can_hoist[i] = 0;
lowest_depth[i] = i;
}
}
for (INT i = 0; i < stk_messy->Elements(); i++) {
WN* wn = stk_messy->Bottom_nth(i);
INT depth = Loop_Depth(wn);
WN* wn_hoist = Hoistable_Place(wn, du);
INT hoist_depth = Loop_Depth(wn_hoist);
if (hoist_depth < depth) {
local_stack.Push(wn);
can_hoist[depth]++;
if (hoist_depth < lowest_depth[depth])
lowest_depth[depth] = hoist_depth;
}
}
stk_messy->Clear();
while (local_stack.Elements() > 0)
stk_messy->Push(local_stack.Pop());
}
//-----------------------------------------------------------------------
// NAME: HMB_Hoist_Messy_Bounds
// FUNCTION: Hoist messy bounds for the perfectly nested loop 'wn_snl'
// adding guard tests where appropriate.
//-----------------------------------------------------------------------
static void HMB_Hoist_Messy_Bounds(WN* wn_snl,
STACK<WN*>* stk_bounds,
LS_IN_LOOP* loop_ls)
{
ARRAY_DIRECTED_GRAPH16* dg = Array_Dependence_Graph;
REDUCTION_MANAGER* rm = red_manager;
// Skip out if there are no messy bounds to process.
WN* wn_inner = NULL;
WN* wn = 0;
for (wn = wn_snl; wn != NULL; wn = Find_Next_Innermost_Do(wn))
wn_inner = wn;
INT outer_depth = Do_Loop_Depth(wn_snl);
INT inner_depth = Do_Loop_Depth(wn_inner);
INT nloops = inner_depth - outer_depth + 1;
// Get basic information needed for hoisting analysis.
INT* has_code = CXX_NEW_ARRAY(INT, inner_depth + 1, &LNO_local_pool);
INT* has_messy_bound = CXX_NEW_ARRAY(INT, inner_depth + 1, &LNO_local_pool);
INT* guard_test_true = CXX_NEW_ARRAY(INT, inner_depth + 1, &LNO_local_pool);
INT* can_hoist = CXX_NEW_ARRAY(INT, inner_depth + 1, &LNO_local_pool);
INT* lowest_depth = CXX_NEW_ARRAY(INT, inner_depth + 1, &LNO_local_pool);
WN** wn_guards = CXX_NEW_ARRAY(WN*, inner_depth + 1, &LNO_local_pool);
INT i;
for (i = 0; i <= inner_depth; i++) {
has_code[i] = 0;
has_messy_bound[i] = 0;
guard_test_true[i] = 0;
wn_guards[i] = NULL;
}
for (i = outer_depth; i <= inner_depth; i++)
has_code[i] = Has_Code_At_Depth(wn_snl, nloops, i);
for (i = outer_depth; i <= inner_depth; i++) {
WN* wn = SNL_Get_Inner_Snl_Loop(wn_snl, i - outer_depth + 1);
if (HMB_Has_Messy_Left_Bound(wn) || HMB_Has_Messy_Right_Bound(wn))
has_messy_bound[i] = TRUE;
guard_test_true[i] = Guard_Test_Redundant(wn, wn_guards, i);
}
for (i = outer_depth; i <= inner_depth; i++)
LWN_Delete_Tree(wn_guards[i]);
STACK<WN*> stk_safe_messy(&LNO_local_pool);
HMB_Find_Messy_Subscripts(wn_snl, TRUE, &stk_safe_messy);
STACK<WN*> stk_unsafe_messy(&LNO_local_pool);
MIR_Has_Messy_Subscript(wn_snl, can_hoist, lowest_depth, TRUE);
// Give up on messy subscript hoisting if we must hoist across
// non-invariant guards
BOOL no_messy_hoist = FALSE;
DOLOOP_STACK stk_loop(&LNO_local_pool);
Build_Doloop_Stack(wn_inner, &stk_loop);
for (i = outer_depth; !no_messy_hoist && i <= inner_depth; i++)
if (can_hoist[i])
for (INT j = lowest_depth[i]; !no_messy_hoist && j < inner_depth; j++)
for (INT k = j + 1; !no_messy_hoist && k <= inner_depth; k++)
if (!SNL_Is_Invariant(&stk_loop, j, k))
no_messy_hoist = TRUE;
if (no_messy_hoist)
for (i = outer_depth; i <= inner_depth; i++)
can_hoist[i] = 0;
// Give up if there is nothing to do
for (i = outer_depth; i <= inner_depth; i++)
if (has_messy_bound[i] || can_hoist[i])
break;
if (i > inner_depth && stk_safe_messy.Elements() == 0)
return;
// Indicate that SNL is being transformed.
if (LNO_Verbose) {
fprintf(stdout, "HMB: Transforming SNL %s at 0x%p\n",
WB_Whirl_Symbol(wn_snl), wn_snl);
fprintf(TFile, "HMB: Transforming SNL %s at 0x%p\n",
WB_Whirl_Symbol(wn_snl), wn_snl);
}
// Determine the guards and the loops which will be placed in each version.
INT* guard_mask = CXX_NEW_ARRAY(INT, inner_depth + 1, &LNO_local_pool);
INT* last_loop = CXX_NEW_ARRAY(INT, inner_depth + 1, &LNO_local_pool);
for (i = 0; i <= inner_depth; i++) {
last_loop[i] = 0;
guard_mask[i] = 0;
}
INT inside_depth = inner_depth;
INT version_count;
for (version_count = 0; inside_depth >= outer_depth; version_count++) {
last_loop[version_count] = inside_depth;
for (INT i = inside_depth; i >= outer_depth; i--) {
if (i > outer_depth && has_messy_bound[i]) {
for (INT j = outer_depth; j < i; j++)
if (!guard_test_true[j])
guard_mask[version_count] |= 1 << j;
}
if (can_hoist[i]) {
for (INT j = lowest_depth[i]; j <= i; j++)
if (!guard_test_true[j])
guard_mask[version_count] |= 1 << j;
}
}
if (guard_mask[version_count] == 0) {
version_count++;
break;
}
for (inside_depth--; inside_depth >= outer_depth
&& !has_code[inside_depth]; inside_depth--);
}
// Create version_count copies of the SNL
WN* wn_array[2];
wn_array[0] = wn_snl;
WN* wn_insert = wn_snl;
WN** wn_version = CXX_NEW_ARRAY(WN*, version_count, &LNO_local_pool);
for (i = 0; i < version_count; i++)
wn_version[i] = NULL;
for (i = 0; i < version_count; i++) {
WN_MAP version_map = WN_MAP_Create(&LNO_local_pool);
wn_version[i] = LWN_Copy_Tree(wn_snl, TRUE, LNO_Info_Map, TRUE,
version_map);
BOOL all_internal = WN_Rename_Duplicate_Labels(wn_snl, wn_version[i],
Current_Func_Node, &LNO_local_pool);
Is_True(all_internal, ("external labels renamed"));
wn_array[1] = wn_version[i];
Unrolled_DU_Update(wn_array, 2, Do_Loop_Depth(wn_snl) - 1, TRUE, FALSE);
dg->Versioned_Dependences_Update(wn_snl, wn_version[i],
outer_depth, version_map);
WN_MAP_Delete(version_map);
if (rm != NULL)
rm->Unroll_Update(wn_array, 2);
LWN_Insert_Block_After(LWN_Get_Parent(wn_insert), wn_insert,
wn_version[i]);
if (i > 0) {
WN* wn_new_inner = SNL_Get_Inner_Snl_Loop(wn_version[i],
last_loop[i] - outer_depth + 1);
DO_LOOP_INFO* dli_new_inner = Get_Do_Loop_Info(wn_new_inner);
dli_new_inner->Is_Inner = TRUE;
WN* wn_tree = SNL_Get_Inner_Snl_Loop(wn_version[i],
last_loop[i] - outer_depth + 2);
LWN_Extract_From_Block(wn_tree);
LWN_Delete_Tree(wn_tree);
}
wn_insert = wn_version[i];
}
if (version_count > 1 || Get_Trace(TP_LNOPT2, TT_HMB_FORCE_VERSIONS))
HMB_Compound_Guard_And_Hoist(wn_version, guard_mask, version_count,
stk_bounds, loop_ls, no_messy_hoist);
else
HMB_Simple_Guard_And_Hoist(wn_version[0], guard_mask[0], stk_bounds,
loop_ls, no_messy_hoist);
// Get rid of the original version
LWN_Extract_From_Block(wn_snl);
LWN_Delete_Tree(wn_snl);
}
//-----------------------------------------------------------------------
// NAME: Forward_Substitute_SNL_Bounds
// FUNCTION: Forward substitute the bounds of all loops in the SNL 'wn_loop'
//-----------------------------------------------------------------------
static void Forward_Substitute_SNL_Bounds(WN* wn_loop)
{
DU_MANAGER* du = Du_Mgr;
INT nloops = SNL_Loop_Count(wn_loop);
WN* wn_inner = SNL_Get_Inner_Snl_Loop(wn_loop, nloops);
for (WN* wn = wn_inner; wn != NULL; wn = LWN_Get_Parent(wn)) {
if (WN_opcode(wn) != OPC_DO_LOOP)
continue;
Forward_Substitute_Ldids(WN_kid0(WN_start(wn)), du);
Forward_Substitute_Ldids(WN_end(wn), du);
if (wn == wn_loop)
break;
}
}
//-----------------------------------------------------------------------
// NAME: SNL_Finalize_Index_Variables
// FUNCTION: Finalize the index variables in the SNL 'wn_loop' which are
// live on exit.
//-----------------------------------------------------------------------
static void SNL_Finalize_Index_Variables(WN* wn_loop)
{
for (WN* wn = wn_loop; wn != NULL; wn = Find_Next_Innermost_Do(wn))
if (Index_Variable_Live_At_Exit(wn))
Finalize_Index_Variable(wn, TRUE, TRUE);
}
//-----------------------------------------------------------------------
// NAME: Has_Statically_Safe_Messy_Bounds
// FUNCTION: Returns TRUE if there is at least one messy bound in 'wn_loop'
// and all of the messy bounds in 'wn_loop' are statically safe for
// hoisting.
//-----------------------------------------------------------------------
static BOOL Has_Statically_Safe_Messy_Bounds(WN* wn_loop)
{
BOOL found_messy_bound = FALSE;
if (HMB_Has_Messy_Left_Bound(wn_loop)) {
found_messy_bound = TRUE;
if (!Statically_Safe_Exp(WN_kid0(WN_start(wn_loop))))
return FALSE;
}
if (HMB_Has_Messy_Right_Bound(wn_loop)) {
found_messy_bound = TRUE;
if (!Statically_Safe_Exp(UBexp(WN_end(wn_loop))))
return FALSE;
}
return found_messy_bound;
}
//-----------------------------------------------------------------------
// NAME: HMB_Hoist_Easy_Messy_Bounds
// FUNCTION: For the innermost SNL 'wn_loop' whose nodes are described
// by 'ls_loop', hoist out the messy bounds of those loops for which
// the hoisting is always statically safe.
//-----------------------------------------------------------------------
static void HMB_Hoist_Easy_Messy_Bounds(WN* wn_loop,
STACK<WN*>* stk_bounds,
LS_IN_LOOP* loop_ls)
{
DU_MANAGER* du = Du_Mgr;
ARRAY_DIRECTED_GRAPH16* dg = Array_Dependence_Graph;
INT nloops = SNL_Loop_Count(wn_loop);
WN* wn_inner = SNL_Get_Inner_Snl_Loop(wn_loop, nloops);
WN* wn_final = LWN_Get_Parent(wn_loop);
for (WN* wn = wn_inner; wn != wn_final; wn = LWN_Get_Parent(wn))
if (WN_opcode(wn) == OPC_DO_LOOP
&& Has_Statically_Safe_Messy_Bounds(wn))
HMB_Replace_Messy_Bounds_Loop(wn, wn_loop, NULL, stk_bounds,
loop_ls);
}
//-----------------------------------------------------------------------
// NAME: HMB_Hoist_Easy_Messy_Subscripts
// FUNCTION: Hoist the messy subscripts out of 'wn_loop' if they are all
// statically safe.
//-----------------------------------------------------------------------
static void HMB_Hoist_Easy_Messy_Subscripts(WN* wn_loop)
{
INT messy_count = 0;
LWN_ITER* itr = LWN_WALK_TreeIter(wn_loop);
for (; itr != NULL; itr = LWN_WALK_TreeNext(itr)) {
WN* wn_array = itr->wn;
WN* wn_messy = Messy_Subscript(wn_array);
if (wn_messy != NULL) {
messy_count++;
if (!Statically_Safe_Exp(wn_messy))
return;
}
}
if (messy_count > 0)
MIR_Hoist_Messy_Subscripts(wn_loop);
}
//-----------------------------------------------------------------------
// NAME: SNL_Hoist_Messy_Bounds
// FUNCTION: Hoist the array elements in the bounds of the singly nested
// loop nest 'wn_snl', adding guard tests where needed.
//-----------------------------------------------------------------------
static void SNL_Hoist_Messy_Bounds(WN* wn_snl)
{
DU_MANAGER* du = Du_Mgr;
ARRAY_DIRECTED_GRAPH16* dg = Array_Dependence_Graph;
REDUCTION_MANAGER* rm = red_manager;
if (!LNO_Hoist_Messy_Bounds)
return;
WN* wn_outer = wn_snl;
Forward_Substitute_SNL_Bounds(wn_snl);
for (WN* wn = wn_outer; wn != NULL; wn = LWN_Get_Parent(wn))
if (WN_opcode(wn) == OPC_DO_LOOP)
wn_outer = wn;
WN* wn_max = HMB_Maximum_Point(wn_snl);
if (wn_max == NULL)
return;
STACK<WN*>* stk_bounds = CXX_NEW(STACK<WN*>(&LNO_local_pool),
&LNO_local_pool);
LS_IN_LOOP* loop_ls = CXX_NEW(LS_IN_LOOP(wn_outer, dg, &LNO_local_pool,
TRUE), &LNO_local_pool);
HMB_Hoist_Easy_Messy_Bounds(wn_max, stk_bounds, loop_ls);
HMB_Hoist_Easy_Messy_Subscripts(wn_max);
wn_max = Code_Expansion_Limit_Loop(wn_max);
HMB_Replace_Messy_Bounds_Loop(wn_max, wn_max, NULL, stk_bounds, loop_ls);
SNL_Finalize_Index_Variables(wn_max);
HMB_Hoist_Messy_Bounds(wn_max, stk_bounds, loop_ls);
}
//-----------------------------------------------------------------------
// NAME: Hoist_Messy_Bounds
// FUNCTION: Hoist the array elements in loop bounds for all SNLs in the
// tree 'func_nd', introducing appropriate guard tests where needed to
// avoid speculation.
//-----------------------------------------------------------------------
extern void Hoist_Messy_Bounds(WN* func_nd)
{
if (!LNO_Hoist_Messy_Bounds)
return;
FIZ_FUSE_INFO* ffi=
CXX_NEW(FIZ_FUSE_INFO(&LNO_local_pool), &LNO_local_pool);
ffi->Build(func_nd);
for (INT i = 0; i < ffi->Num_Snl(); i++) {
if (ffi->Get_Depth(i) < 1 || ffi->Get_Type(i) != Inner)
continue;
SNL_Hoist_Messy_Bounds(ffi->Get_Wn(i));
}
}
| 37.653603
| 123
| 0.611771
|
sharugupta
|
bd65f206fe352f3861578766a3caeed46c813abe
| 50,509
|
hpp
|
C++
|
ext/hmsJNI.hpp
|
bg-sniffer/hermes
|
e9d2be3d0600926cd99190cebd65dd1d077164aa
|
[
"Zlib"
] | null | null | null |
ext/hmsJNI.hpp
|
bg-sniffer/hermes
|
e9d2be3d0600926cd99190cebd65dd1d077164aa
|
[
"Zlib"
] | null | null | null |
ext/hmsJNI.hpp
|
bg-sniffer/hermes
|
e9d2be3d0600926cd99190cebd65dd1d077164aa
|
[
"Zlib"
] | null | null | null |
// Copyright (C) 2017-2020 Grupa Pracuj Sp. z o.o.
// This file is part of the "Hermes" library.
// For conditions of distribution and use, see copyright notice in license.txt.
#ifndef _HMS_JNI_HPP_
#define _HMS_JNI_HPP_
#include <jni.h>
#include <array>
#include <cassert>
#include <memory>
#include <string>
#include <utility>
extern "C" JNIEXPORT void JNICALL Java_pl_grupapracuj_hermes_ext_jni_ObjectNative_nativeDestroy(JNIEnv* pEnvironment, jobject pObject, jlong pPointer);
namespace hms
{
class DataBuffer;
namespace ext
{
class ModuleShared;
namespace jni
{
class Reference
{
public:
Reference(jobject pObject, JNIEnv* pEnvironment);
Reference(const Reference& pOther) = delete;
Reference(Reference&& pOther);
~Reference();
Reference& operator=(const Reference& pOther) = delete;
Reference& operator=(Reference&& pOther);
jobject object() const;
JNIEnv* environment() const;
private:
jobject mObject;
JavaVM* mVM;
};
class ReferenceWeak
{
public:
ReferenceWeak(jobject pObject, JNIEnv* pEnvironment);
ReferenceWeak(const ReferenceWeak& pOther) = delete;
ReferenceWeak(ReferenceWeak&& pOther);
~ReferenceWeak();
ReferenceWeak& operator=(const ReferenceWeak& pOther) = delete;
ReferenceWeak& operator=(ReferenceWeak&& pOther);
jobject objectWeak() const;
JNIEnv* environment() const;
private:
jobject mObjectWeak;
JavaVM* mVM;
};
class ObjectNative
{
public:
ObjectNative() = delete;
ObjectNative(const ObjectNative& pOther) = delete;
ObjectNative(ObjectNative&& pOther) = delete;
ObjectNative& operator=(const ObjectNative& pOther) = delete;
ObjectNative& operator=(ObjectNative&& pOther) = delete;
template<typename T>
static jobject create(T pObject, JNIEnv* pEnvironment, jclass pClass = nullptr)
{
auto container = new Container<T>();
container->mObject = std::move(pObject);
auto result = object(reinterpret_cast<jlong>(container), pEnvironment, pClass);
if (result == nullptr)
delete container;
return result;
}
template<typename T>
static T& get(jobject pObject, JNIEnv* pEnvironment)
{
return get<T>(pointer(pObject, pEnvironment));
}
template<typename T>
static T& get(jlong pPointer)
{
if (pPointer <= 0)
throw std::invalid_argument("hmsJNI: parameter is null");
auto container = reinterpret_cast<Container<T>*>(pPointer);
return container->mObject;
}
private:
friend void ::Java_pl_grupapracuj_hermes_ext_jni_ObjectNative_nativeDestroy(JNIEnv* pEnvironment, jobject pObject, jlong pPointer);
class ContainerGeneric
{
public:
ContainerGeneric() = default;
virtual ~ContainerGeneric() = default;
};
template<typename T>
class Container : public ContainerGeneric
{
public:
T mObject;
};
static jobject object(jlong pPointer, JNIEnv* pEnvironment, jclass pClass);
static jlong pointer(jobject pObject, JNIEnv* pEnvironment);
};
template <typename T>
class ObjectNativeWrapper
{
public:
ObjectNativeWrapper(T pData) : mData(std::move(pData))
{
}
T mData;
};
class Utility
{
public:
Utility() = delete;
Utility(const Utility& pOther) = delete;
Utility(Utility&& pOther) = delete;
Utility& operator=(const Utility& pOther) = delete;
Utility& operator=(Utility&& pOther) = delete;
template <typename T>
struct is_pair : std::false_type {};
template <typename T, typename U>
struct is_pair<std::pair<T, U>> : std::true_type {};
template <typename T>
struct is_tuple : std::false_type {};
template <typename... T>
struct is_tuple<std::tuple<T...>> : std::true_type {};
static void initialize(JNIEnv* pEnvironment, jobject pClassLoader);
static JavaVM* javaVM();
static void javaVM(JavaVM* pJavaVM);
template<typename T = Utility, typename... Arguments>
static jboolean methodBoolean(std::shared_ptr<hms::ext::jni::ReferenceWeak> pObjectWeakRef, std::string pMethod, std::string pSignature, Arguments&&... pArguments)
{
assert(pObjectWeakRef != nullptr && pMethod.size() > 0 && pSignature.size() > 2);
jboolean result = static_cast<jboolean>(false);
JNIEnv* environment = pObjectWeakRef->environment();
jobject strongObject = environment->NewGlobalRef(pObjectWeakRef->objectWeak());
if (strongObject != nullptr)
{
jclass jClass = environment->GetObjectClass(strongObject);
jmethodID jMethod = environment->GetMethodID(jClass, pMethod.c_str(), pSignature.c_str());
result = methodBooleanCall(environment, strongObject, jMethod, T::template convert<T>(environment, std::forward<Arguments>(pArguments))...);
environment->DeleteLocalRef(jClass);
environment->DeleteGlobalRef(strongObject);
}
return result;
}
template<typename T = Utility, typename... Arguments>
static jbyte methodByte(std::shared_ptr<hms::ext::jni::ReferenceWeak> pObjectWeakRef, std::string pMethod, std::string pSignature, Arguments&&... pArguments)
{
assert(pObjectWeakRef != nullptr && pMethod.size() > 0 && pSignature.size() > 2);
jbyte result = '\0';
JNIEnv* environment = pObjectWeakRef->environment();
jobject strongObject = environment->NewGlobalRef(pObjectWeakRef->objectWeak());
if (strongObject != nullptr)
{
jclass jClass = environment->GetObjectClass(strongObject);
jmethodID jMethod = environment->GetMethodID(jClass, pMethod.c_str(), pSignature.c_str());
result = methodByteCall(environment, strongObject, jMethod, T::template convert<T>(environment, std::forward<Arguments>(pArguments))...);
environment->DeleteLocalRef(jClass);
environment->DeleteGlobalRef(strongObject);
}
return result;
}
template<typename T = Utility, typename... Arguments>
static jchar methodChar(std::shared_ptr<hms::ext::jni::ReferenceWeak> pObjectWeakRef, std::string pMethod, std::string pSignature, Arguments&&... pArguments)
{
assert(pObjectWeakRef != nullptr && pMethod.size() > 0 && pSignature.size() > 2);
jchar result = '\0';
JNIEnv* environment = pObjectWeakRef->environment();
jobject strongObject = environment->NewGlobalRef(pObjectWeakRef->objectWeak());
if (strongObject != nullptr)
{
jclass jClass = environment->GetObjectClass(strongObject);
jmethodID jMethod = environment->GetMethodID(jClass, pMethod.c_str(), pSignature.c_str());
result = methodCharCall(environment, strongObject, jMethod, T::template convert<T>(environment, std::forward<Arguments>(pArguments))...);
environment->DeleteLocalRef(jClass);
environment->DeleteGlobalRef(strongObject);
}
return result;
}
template<typename T = Utility, typename... Arguments>
static jdouble methodDouble(std::shared_ptr<hms::ext::jni::ReferenceWeak> pObjectWeakRef, std::string pMethod, std::string pSignature, Arguments&&... pArguments)
{
assert(pObjectWeakRef != nullptr && pMethod.size() > 0 && pSignature.size() > 2);
jdouble result = 0.0;
JNIEnv* environment = pObjectWeakRef->environment();
jobject strongObject = environment->NewGlobalRef(pObjectWeakRef->objectWeak());
if (strongObject != nullptr)
{
jclass jClass = environment->GetObjectClass(strongObject);
jmethodID jMethod = environment->GetMethodID(jClass, pMethod.c_str(), pSignature.c_str());
result = methodDoubleCall(environment, strongObject, jMethod, T::template convert<T>(environment, std::forward<Arguments>(pArguments))...);
environment->DeleteLocalRef(jClass);
environment->DeleteGlobalRef(strongObject);
}
return result;
}
template<typename T = Utility, typename... Arguments>
static jfloat methodFloat(std::shared_ptr<hms::ext::jni::ReferenceWeak> pObjectWeakRef, std::string pMethod, std::string pSignature, Arguments&&... pArguments)
{
assert(pObjectWeakRef != nullptr && pMethod.size() > 0 && pSignature.size() > 2);
jfloat result = 0.f;
JNIEnv* environment = pObjectWeakRef->environment();
jobject strongObject = environment->NewGlobalRef(pObjectWeakRef->objectWeak());
if (strongObject != nullptr)
{
jclass jClass = environment->GetObjectClass(strongObject);
jmethodID jMethod = environment->GetMethodID(jClass, pMethod.c_str(), pSignature.c_str());
result = methodFloatCall(environment, strongObject, jMethod, T::template convert<T>(environment, std::forward<Arguments>(pArguments))...);
environment->DeleteLocalRef(jClass);
environment->DeleteGlobalRef(strongObject);
}
return result;
}
template<typename T = Utility, typename... Arguments>
static jint methodInt(std::shared_ptr<hms::ext::jni::ReferenceWeak> pObjectWeakRef, std::string pMethod, std::string pSignature, Arguments&&... pArguments)
{
assert(pObjectWeakRef != nullptr && pMethod.size() > 0 && pSignature.size() > 2);
jint result = 0;
JNIEnv* environment = pObjectWeakRef->environment();
jobject strongObject = environment->NewGlobalRef(pObjectWeakRef->objectWeak());
if (strongObject != nullptr)
{
jclass jClass = environment->GetObjectClass(strongObject);
jmethodID jMethod = environment->GetMethodID(jClass, pMethod.c_str(), pSignature.c_str());
result = methodIntCall(environment, strongObject, jMethod, T::template convert<T>(environment, std::forward<Arguments>(pArguments))...);
environment->DeleteLocalRef(jClass);
environment->DeleteGlobalRef(strongObject);
}
return result;
}
template<typename T = Utility, typename... Arguments>
static jlong methodLong(std::shared_ptr<hms::ext::jni::ReferenceWeak> pObjectWeakRef, std::string pMethod, std::string pSignature, Arguments&&... pArguments)
{
assert(pObjectWeakRef != nullptr && pMethod.size() > 0 && pSignature.size() > 2);
jlong result = 0;
JNIEnv* environment = pObjectWeakRef->environment();
jobject strongObject = environment->NewGlobalRef(pObjectWeakRef->objectWeak());
if (strongObject != nullptr)
{
jclass jClass = environment->GetObjectClass(strongObject);
jmethodID jMethod = environment->GetMethodID(jClass, pMethod.c_str(), pSignature.c_str());
result = methodLongCall(environment, strongObject, jMethod, T::template convert<T>(environment, std::forward<Arguments>(pArguments))...);
environment->DeleteLocalRef(jClass);
environment->DeleteGlobalRef(strongObject);
}
return result;
}
template<typename T = Utility, typename... Arguments>
static jobject methodObject(std::shared_ptr<hms::ext::jni::ReferenceWeak> pObjectWeakRef, std::string pMethod, std::string pSignature, Arguments&&... pArguments)
{
assert(pObjectWeakRef != nullptr && pMethod.size() > 0 && pSignature.size() > 2);
jobject result = nullptr;
JNIEnv* environment = pObjectWeakRef->environment();
jobject strongObject = environment->NewGlobalRef(pObjectWeakRef->objectWeak());
if (strongObject != nullptr)
{
jclass jClass = environment->GetObjectClass(strongObject);
jmethodID jMethod = environment->GetMethodID(jClass, pMethod.c_str(), pSignature.c_str());
result = methodObjectCall(environment, strongObject, jMethod, T::template convert<T>(environment, std::forward<Arguments>(pArguments))...);
environment->DeleteLocalRef(jClass);
environment->DeleteGlobalRef(strongObject);
}
return result;
}
template<typename T = Utility, typename... Arguments>
static jshort methodShort(std::shared_ptr<hms::ext::jni::ReferenceWeak> pObjectWeakRef, std::string pMethod, std::string pSignature, Arguments&&... pArguments)
{
assert(pObjectWeakRef != nullptr && pMethod.size() > 0 && pSignature.size() > 2);
jshort result = 0;
JNIEnv* environment = pObjectWeakRef->environment();
jobject strongObject = environment->NewGlobalRef(pObjectWeakRef->objectWeak());
if (strongObject != nullptr)
{
jclass jClass = environment->GetObjectClass(strongObject);
jmethodID jMethod = environment->GetMethodID(jClass, pMethod.c_str(), pSignature.c_str());
result = methodShortCall(environment, strongObject, jMethod, T::template convert<T>(environment, std::forward<Arguments>(pArguments))...);
environment->DeleteLocalRef(jClass);
environment->DeleteGlobalRef(strongObject);
}
return result;
}
template<typename T = Utility, typename... Arguments>
static void methodVoid(std::shared_ptr<hms::ext::jni::ReferenceWeak> pObjectWeakRef, std::string pMethod, std::string pSignature, Arguments&&... pArguments)
{
assert(pObjectWeakRef != nullptr && pMethod.size() > 0 && pSignature.size() > 2);
JNIEnv* environment = pObjectWeakRef->environment();
jobject strongObject = environment->NewGlobalRef(pObjectWeakRef->objectWeak());
if (strongObject != nullptr)
{
jclass jClass = environment->GetObjectClass(strongObject);
jmethodID jMethod = environment->GetMethodID(jClass, pMethod.c_str(), pSignature.c_str());
methodVoidCall(environment, strongObject, jMethod, T::template convert<T>(environment, std::forward<Arguments>(pArguments))...);
environment->DeleteLocalRef(jClass);
environment->DeleteGlobalRef(strongObject);
}
}
template <typename T>
static std::shared_ptr<T> module(jlong pPointer, typename std::enable_if_t<std::is_base_of<hms::ext::ModuleShared, T>::value>* = nullptr)
{
std::shared_ptr<T> result = nullptr;
try
{
if (pPointer > 0)
result = std::static_pointer_cast<T>(hms::ext::jni::ObjectNative::get<std::weak_ptr<hms::ext::ModuleShared>>(pPointer).lock());
}
catch (const std::exception& lpException) {}
return result;
}
template <typename C = Utility, typename T>
static auto convert(JNIEnv* pEnvironment, T pValue, typename std::enable_if_t<std::is_pointer_v<std::decay_t<T>>>* = nullptr)
{
return pValue != nullptr ? C::convert(pEnvironment, *pValue) : nullptr;
}
template <typename C = Utility, typename T>
static jobject convert(JNIEnv* pEnvironment, hms::ext::jni::ObjectNativeWrapper<T>&& pValue)
{
jobject result = nullptr;
try
{
result = hms::ext::jni::ObjectNative::create<T>(std::move(pValue.mData), pEnvironment, mClasses[static_cast<size_t>(EClass::pl_grupapracuj_hermes_ext_jni_ObjectNative)].first);
}
catch (const std::exception& lpException) {}
return result;
}
template <typename C = Utility, typename T>
static jobject convert(JNIEnv* pEnvironment, const hms::ext::jni::ObjectNativeWrapper<T>& pValue)
{
jobject result = nullptr;
try
{
result = hms::ext::jni::ObjectNative::create<T>(pValue.mData, pEnvironment, mClasses[static_cast<size_t>(EClass::pl_grupapracuj_hermes_ext_jni_ObjectNative)].first);
}
catch (const std::exception& lpException) {}
return result;
}
template <typename C = Utility, typename T>
static jobject convert(JNIEnv* pEnvironment, T&& pValue, typename std::enable_if_t<is_pair<std::decay_t<T>>::value>* = nullptr)
{
jobject jFirst = C::template objectCreate<C>(pEnvironment, std::move(pValue.first));
jobject jSecond = C::template objectCreate<C>(pEnvironment, std::move(pValue.second));
jobject jObject = pEnvironment->NewObject(mClasses[static_cast<size_t>(EClass::pl_grupapracuj_pracuj_ext_tuple_Pair)].first, mMethodIds[static_cast<size_t>(EMethodId::pl_grupapracuj_pracuj_ext_tuple_Pair_init)], jFirst, jSecond);
localRefDelete(pEnvironment, jFirst);
localRefDelete(pEnvironment, jSecond);
return jObject;
}
template <typename C = Utility, typename T>
static jobject convert(JNIEnv* pEnvironment, T&& pValue, typename std::enable_if_t<is_tuple<std::decay_t<T>>::value && std::tuple_size<std::decay_t<T>>::value == 2>* = nullptr)
{
jobject jFirst = C::template objectCreate<C>(pEnvironment, std::move(std::get<0>(pValue)));
jobject jSecond = C::template objectCreate<C>(pEnvironment, std::move(std::get<1>(pValue)));
jobject jObject = pEnvironment->NewObject(mClasses[static_cast<size_t>(EClass::pl_grupapracuj_pracuj_ext_tuple_Pair)].first, mMethodIds[static_cast<size_t>(EMethodId::pl_grupapracuj_pracuj_ext_tuple_Pair_init)], jFirst, jSecond);
localRefDelete(pEnvironment, jFirst);
localRefDelete(pEnvironment, jSecond);
return jObject;
}
template <typename C = Utility, typename T>
static jobject convert(JNIEnv* pEnvironment, T&& pValue, typename std::enable_if_t<is_tuple<std::decay_t<T>>::value && std::tuple_size<std::decay_t<T>>::value == 3>* = nullptr)
{
jobject jFirst = C::template objectCreate<C>(pEnvironment, std::move(std::get<0>(pValue)));
jobject jSecond = C::template objectCreate<C>(pEnvironment, std::move(std::get<1>(pValue)));
jobject jThird = C::template objectCreate<C>(pEnvironment, std::move(std::get<2>(pValue)));
jobject jObject = pEnvironment->NewObject(mClasses[static_cast<size_t>(EClass::pl_grupapracuj_pracuj_ext_tuple_Triple)].first, mMethodIds[static_cast<size_t>(EMethodId::pl_grupapracuj_pracuj_ext_tuple_Triple_init)], jFirst, jSecond, jThird);
localRefDelete(pEnvironment, jFirst);
localRefDelete(pEnvironment, jSecond);
localRefDelete(pEnvironment, jThird);
return jObject;
}
template <typename C = Utility, typename T>
static jobject convert(JNIEnv* pEnvironment, T&& pValue, typename std::enable_if_t<is_tuple<std::decay_t<T>>::value && std::tuple_size<std::decay_t<T>>::value == 4>* = nullptr)
{
jobject jFirst = C::template objectCreate<C>(pEnvironment, std::move(std::get<0>(pValue)));
jobject jSecond = C::template objectCreate<C>(pEnvironment, std::move(std::get<1>(pValue)));
jobject jThird = C::template objectCreate<C>(pEnvironment, std::move(std::get<2>(pValue)));
jobject jFourth = C::template objectCreate<C>(pEnvironment, std::move(std::get<3>(pValue)));
jobject jObject = pEnvironment->NewObject(mClasses[static_cast<size_t>(EClass::pl_grupapracuj_pracuj_ext_tuple_Quadruple)].first, mMethodIds[static_cast<size_t>(EMethodId::pl_grupapracuj_pracuj_ext_tuple_Quadruple_init)], jFirst, jSecond, jThird, jFourth);
localRefDelete(pEnvironment, jFirst);
localRefDelete(pEnvironment, jSecond);
localRefDelete(pEnvironment, jThird);
localRefDelete(pEnvironment, jFourth);
return jObject;
}
template <typename C = Utility, typename T>
static jobject convert(JNIEnv* pEnvironment, T&& pValue, typename std::enable_if_t<is_tuple<std::decay_t<T>>::value && std::tuple_size<std::decay_t<T>>::value == 5>* = nullptr)
{
jobject jFirst = C::template objectCreate<C>(pEnvironment, std::move(std::get<0>(pValue)));
jobject jSecond = C::template objectCreate<C>(pEnvironment, std::move(std::get<1>(pValue)));
jobject jThird = C::template objectCreate<C>(pEnvironment, std::move(std::get<2>(pValue)));
jobject jFourth = C::template objectCreate<C>(pEnvironment, std::move(std::get<3>(pValue)));
jobject jFifth = C::template objectCreate<C>(pEnvironment, std::move(std::get<4>(pValue)));
jobject jObject = pEnvironment->NewObject(mClasses[static_cast<size_t>(EClass::pl_grupapracuj_pracuj_ext_tuple_Quintuple)].first, mMethodIds[static_cast<size_t>(EMethodId::pl_grupapracuj_pracuj_ext_tuple_Quintuple_init)], jFirst, jSecond, jThird, jFourth, jFifth);
localRefDelete(pEnvironment, jFirst);
localRefDelete(pEnvironment, jSecond);
localRefDelete(pEnvironment, jThird);
localRefDelete(pEnvironment, jFourth);
localRefDelete(pEnvironment, jFifth);
return jObject;
}
template <typename C = Utility, typename T>
static jobject convert(JNIEnv* pEnvironment, T&& pValue, typename std::enable_if_t<is_tuple<std::decay_t<T>>::value && std::tuple_size<std::decay_t<T>>::value == 6>* = nullptr)
{
jobject jFirst = C::template objectCreate<C>(pEnvironment, std::move(std::get<0>(pValue)));
jobject jSecond = C::template objectCreate<C>(pEnvironment, std::move(std::get<1>(pValue)));
jobject jThird = C::template objectCreate<C>(pEnvironment, std::move(std::get<2>(pValue)));
jobject jFourth = C::template objectCreate<C>(pEnvironment, std::move(std::get<3>(pValue)));
jobject jFifth = C::template objectCreate<C>(pEnvironment, std::move(std::get<4>(pValue)));
jobject jSixth = C::template objectCreate<C>(pEnvironment, std::move(std::get<5>(pValue)));
jobject jObject = pEnvironment->NewObject(mClasses[static_cast<size_t>(EClass::pl_grupapracuj_pracuj_ext_tuple_Sextuple)].first, mMethodIds[static_cast<size_t>(EMethodId::pl_grupapracuj_pracuj_ext_tuple_Sextuple_init)], jFirst, jSecond, jThird, jFourth, jFifth, jSixth);
localRefDelete(pEnvironment, jFirst);
localRefDelete(pEnvironment, jSecond);
localRefDelete(pEnvironment, jThird);
localRefDelete(pEnvironment, jFourth);
localRefDelete(pEnvironment, jFifth);
localRefDelete(pEnvironment, jSixth);
return jObject;
}
template <typename C = Utility, typename T>
static jobject convert(JNIEnv* pEnvironment, T&& pValue, typename std::enable_if_t<is_tuple<std::decay_t<T>>::value && std::tuple_size<std::decay_t<T>>::value == 7>* = nullptr)
{
jobject jFirst = C::template objectCreate<C>(pEnvironment, std::move(std::get<0>(pValue)));
jobject jSecond = C::template objectCreate<C>(pEnvironment, std::move(std::get<1>(pValue)));
jobject jThird = C::template objectCreate<C>(pEnvironment, std::move(std::get<2>(pValue)));
jobject jFourth = C::template objectCreate<C>(pEnvironment, std::move(std::get<3>(pValue)));
jobject jFifth = C::template objectCreate<C>(pEnvironment, std::move(std::get<4>(pValue)));
jobject jSixth = C::template objectCreate<C>(pEnvironment, std::move(std::get<5>(pValue)));
jobject jSeventh = C::template objectCreate<C>(pEnvironment, std::move(std::get<6>(pValue)));
jobject jObject = pEnvironment->NewObject(mClasses[static_cast<size_t>(EClass::pl_grupapracuj_pracuj_ext_tuple_Septuple)].first, mMethodIds[static_cast<size_t>(EMethodId::pl_grupapracuj_pracuj_ext_tuple_Septuple_init)], jFirst, jSecond, jThird, jFourth, jFifth, jSixth, jSeventh);
localRefDelete(pEnvironment, jFirst);
localRefDelete(pEnvironment, jSecond);
localRefDelete(pEnvironment, jThird);
localRefDelete(pEnvironment, jFourth);
localRefDelete(pEnvironment, jFifth);
localRefDelete(pEnvironment, jSixth);
localRefDelete(pEnvironment, jSeventh);
return jObject;
}
template <typename C = Utility, typename T>
static jobject convert(JNIEnv* pEnvironment, T&& pValue, typename std::enable_if_t<is_tuple<std::decay_t<T>>::value && std::tuple_size<std::decay_t<T>>::value == 8>* = nullptr)
{
jobject jFirst = C::template objectCreate<C>(pEnvironment, std::move(std::get<0>(pValue)));
jobject jSecond = C::template objectCreate<C>(pEnvironment, std::move(std::get<1>(pValue)));
jobject jThird = C::template objectCreate<C>(pEnvironment, std::move(std::get<2>(pValue)));
jobject jFourth = C::template objectCreate<C>(pEnvironment, std::move(std::get<3>(pValue)));
jobject jFifth = C::template objectCreate<C>(pEnvironment, std::move(std::get<4>(pValue)));
jobject jSixth = C::template objectCreate<C>(pEnvironment, std::move(std::get<5>(pValue)));
jobject jSeventh = C::template objectCreate<C>(pEnvironment, std::move(std::get<6>(pValue)));
jobject jEighth = C::template objectCreate<C>(pEnvironment, std::move(std::get<7>(pValue)));
jobject jObject = pEnvironment->NewObject(mClasses[static_cast<size_t>(EClass::pl_grupapracuj_pracuj_ext_tuple_Octuple)].first, mMethodIds[static_cast<size_t>(EMethodId::pl_grupapracuj_pracuj_ext_tuple_Octuple_init)], jFirst, jSecond, jThird, jFourth, jFifth, jSixth, jSeventh, jEighth);
localRefDelete(pEnvironment, jFirst);
localRefDelete(pEnvironment, jSecond);
localRefDelete(pEnvironment, jThird);
localRefDelete(pEnvironment, jFourth);
localRefDelete(pEnvironment, jFifth);
localRefDelete(pEnvironment, jSixth);
localRefDelete(pEnvironment, jSeventh);
localRefDelete(pEnvironment, jEighth);
return jObject;
}
template <typename C = Utility, typename T>
static jobject convert(JNIEnv* pEnvironment, T&& pValue, typename std::enable_if_t<is_tuple<std::decay_t<T>>::value && std::tuple_size<std::decay_t<T>>::value == 9>* = nullptr)
{
jobject jFirst = C::template objectCreate<C>(pEnvironment, std::move(std::get<0>(pValue)));
jobject jSecond = C::template objectCreate<C>(pEnvironment, std::move(std::get<1>(pValue)));
jobject jThird = C::template objectCreate<C>(pEnvironment, std::move(std::get<2>(pValue)));
jobject jFourth = C::template objectCreate<C>(pEnvironment, std::move(std::get<3>(pValue)));
jobject jFifth = C::template objectCreate<C>(pEnvironment, std::move(std::get<4>(pValue)));
jobject jSixth = C::template objectCreate<C>(pEnvironment, std::move(std::get<5>(pValue)));
jobject jSeventh = C::template objectCreate<C>(pEnvironment, std::move(std::get<6>(pValue)));
jobject jEighth = C::template objectCreate<C>(pEnvironment, std::move(std::get<7>(pValue)));
jobject jNinth = C::template objectCreate<C>(pEnvironment, std::move(std::get<8>(pValue)));
jobject jObject = pEnvironment->NewObject(mClasses[static_cast<size_t>(EClass::pl_grupapracuj_pracuj_ext_tuple_Nontuple)].first, mMethodIds[static_cast<size_t>(EMethodId::pl_grupapracuj_pracuj_ext_tuple_Nontuple_init)], jFirst, jSecond, jThird, jFourth, jFifth, jSixth, jSeventh, jEighth, jNinth);
localRefDelete(pEnvironment, jFirst);
localRefDelete(pEnvironment, jSecond);
localRefDelete(pEnvironment, jThird);
localRefDelete(pEnvironment, jFourth);
localRefDelete(pEnvironment, jFifth);
localRefDelete(pEnvironment, jSixth);
localRefDelete(pEnvironment, jSeventh);
localRefDelete(pEnvironment, jEighth);
localRefDelete(pEnvironment, jNinth);
return jObject;
}
template <typename C = Utility, typename T>
static jobject convert(JNIEnv* pEnvironment, T&& pValue, typename std::enable_if_t<std::is_same_v<std::decay_t<T>, std::string>>* = nullptr)
{
return pEnvironment->NewStringUTF(pValue.c_str());
}
template <typename C = Utility, typename T>
static jbyteArray convert(JNIEnv* pEnvironment, T&& pValue, typename std::enable_if_t<std::is_same_v<std::decay_t<T>, hms::DataBuffer>>* = nullptr)
{
return convertHmsDataBuffer(pEnvironment, pValue);
}
template <typename C = Utility, typename T>
static jintArray convert(JNIEnv* pEnvironment, const std::vector<T>& pValue, typename std::enable_if_t<sizeof(T) == sizeof(jint) && (std::is_same_v<T, jint> || std::is_same_v<T, int32_t> || std::is_same_v<T, uint32_t> || std::is_enum_v<T>)>* = nullptr)
{
jintArray jArray = pEnvironment->NewIntArray(static_cast<jsize>(pValue.size()));
pEnvironment->SetIntArrayRegion(jArray, 0, static_cast<jsize>(pValue.size()), reinterpret_cast<const jint*>(pValue.data()));
return jArray;
}
template <typename C = Utility, typename T>
static jlongArray convert(JNIEnv* pEnvironment, const std::vector<T>& pValue, typename std::enable_if_t<sizeof(T) == sizeof(jlong) && (std::is_same_v<T, jlong> || std::is_same_v<T, int64_t> || std::is_same_v<T, uint64_t>)>* = nullptr)
{
jlongArray jArray = pEnvironment->NewLongArray(static_cast<jsize>(pValue.size()));
pEnvironment->SetLongArrayRegion(jArray, 0, static_cast<jsize>(pValue.size()), reinterpret_cast<const jlong*>(pValue.data()));
return jArray;
}
template <typename C = Utility, typename T>
static jobjectArray convert(JNIEnv* pEnvironment, std::vector<T>&& pValue, typename std::enable_if_t<std::is_same_v<T, std::string> || std::is_same_v<T, hms::DataBuffer> || is_pair<T>::value || is_tuple<T>::value>* = nullptr)
{
jclass jClass = nullptr;
if constexpr(std::is_same<T, std::string>::value)
{
jClass = mClasses[static_cast<size_t>(EClass::java_lang_String)].first;
}
else if constexpr(std::is_same<T, hms::DataBuffer>::value)
{
jClass = mClasses[static_cast<size_t>(EClass::java_lang_arrayByte)].first;
}
else if constexpr(is_pair<T>::value)
{
jClass = mClasses[static_cast<size_t>(EClass::pl_grupapracuj_pracuj_ext_tuple_Pair)].first;
}
else if constexpr(is_tuple<T>::value)
{
assert(std::tuple_size<T>::value < 10);
if constexpr(std::tuple_size<T>::value == 2)
jClass = mClasses[static_cast<size_t>(EClass::pl_grupapracuj_pracuj_ext_tuple_Pair)].first;
else if constexpr(std::tuple_size<T>::value == 3)
jClass = mClasses[static_cast<size_t>(EClass::pl_grupapracuj_pracuj_ext_tuple_Triple)].first;
else if constexpr(std::tuple_size<T>::value == 4)
jClass = mClasses[static_cast<size_t>(EClass::pl_grupapracuj_pracuj_ext_tuple_Quadruple)].first;
else if constexpr(std::tuple_size<T>::value == 5)
jClass = mClasses[static_cast<size_t>(EClass::pl_grupapracuj_pracuj_ext_tuple_Quintuple)].first;
else if constexpr(std::tuple_size<T>::value == 6)
jClass = mClasses[static_cast<size_t>(EClass::pl_grupapracuj_pracuj_ext_tuple_Sextuple)].first;
else if constexpr(std::tuple_size<T>::value == 7)
jClass = mClasses[static_cast<size_t>(EClass::pl_grupapracuj_pracuj_ext_tuple_Septuple)].first;
else if constexpr(std::tuple_size<T>::value == 8)
jClass = mClasses[static_cast<size_t>(EClass::pl_grupapracuj_pracuj_ext_tuple_Octuple)].first;
else if constexpr(std::tuple_size<T>::value == 9)
jClass = mClasses[static_cast<size_t>(EClass::pl_grupapracuj_pracuj_ext_tuple_Nontuple)].first;
}
return arrayObjectCreate(pEnvironment, std::move(pValue), jClass);
}
template <typename C = Utility, typename T>
static jobjectArray convert(JNIEnv* pEnvironment, const std::vector<T>& pValue, typename std::enable_if_t<std::is_same_v<T, std::string> || std::is_same_v<T, hms::DataBuffer> || is_pair<T>::value || is_tuple<T>::value>* = nullptr)
{
jclass jClass = nullptr;
if constexpr(std::is_same<T, std::string>::value)
{
jClass = mClasses[static_cast<size_t>(EClass::java_lang_String)].first;
}
else if constexpr(std::is_same<T, hms::DataBuffer>::value)
{
jClass = mClasses[static_cast<size_t>(EClass::java_lang_arrayByte)].first;
}
else if constexpr(is_pair<T>::value)
{
jClass = mClasses[static_cast<size_t>(EClass::pl_grupapracuj_pracuj_ext_tuple_Pair)].first;
}
else if constexpr(is_tuple<T>::value)
{
assert(std::tuple_size<T>::value < 10);
if constexpr(std::tuple_size<T>::value == 2)
jClass = mClasses[static_cast<size_t>(EClass::pl_grupapracuj_pracuj_ext_tuple_Pair)].first;
else if constexpr(std::tuple_size<T>::value == 3)
jClass = mClasses[static_cast<size_t>(EClass::pl_grupapracuj_pracuj_ext_tuple_Triple)].first;
else if constexpr(std::tuple_size<T>::value == 4)
jClass = mClasses[static_cast<size_t>(EClass::pl_grupapracuj_pracuj_ext_tuple_Quadruple)].first;
else if constexpr(std::tuple_size<T>::value == 5)
jClass = mClasses[static_cast<size_t>(EClass::pl_grupapracuj_pracuj_ext_tuple_Quintuple)].first;
else if constexpr(std::tuple_size<T>::value == 6)
jClass = mClasses[static_cast<size_t>(EClass::pl_grupapracuj_pracuj_ext_tuple_Sextuple)].first;
else if constexpr(std::tuple_size<T>::value == 7)
jClass = mClasses[static_cast<size_t>(EClass::pl_grupapracuj_pracuj_ext_tuple_Septuple)].first;
else if constexpr(std::tuple_size<T>::value == 8)
jClass = mClasses[static_cast<size_t>(EClass::pl_grupapracuj_pracuj_ext_tuple_Octuple)].first;
else if constexpr(std::tuple_size<T>::value == 9)
jClass = mClasses[static_cast<size_t>(EClass::pl_grupapracuj_pracuj_ext_tuple_Nontuple)].first;
}
return arrayObjectCreate(pEnvironment, pValue, jClass);
}
static std::string jconvert(JNIEnv* pEnvironment, jstring pValue);
protected:
static bool classLoad(JNIEnv* pEnvironment, jobject pClassLoader, std::pair<jclass, bool>* pClasses, std::string* pSignatures, size_t pCount);
template <typename C = Utility, typename T>
static jboolean convert(JNIEnv* pEnvironment, T pValue, typename std::enable_if_t<std::is_same_v<std::decay_t<T>, jboolean> || std::is_same_v<std::decay_t<T>, bool>>* = nullptr)
{
return pValue;
}
template <typename C = Utility, typename T>
static jbyte convert(JNIEnv* pEnvironment, T pValue, typename std::enable_if_t<std::is_same_v<std::decay_t<T>, jbyte>>* = nullptr)
{
return pValue;
}
template <typename C = Utility, typename T>
static jchar convert(JNIEnv* pEnvironment, T pValue, typename std::enable_if_t<std::is_same_v<std::decay_t<T>, jchar>>* = nullptr)
{
return pValue;
}
template <typename C = Utility, typename T>
static jdouble convert(JNIEnv* pEnvironment, T pValue, typename std::enable_if_t<std::is_same_v<std::decay_t<T>, jdouble> || std::is_same_v<std::decay_t<T>, double>>* = nullptr)
{
return pValue;
}
template <typename C = Utility, typename T>
static jfloat convert(JNIEnv* pEnvironment, T pValue, typename std::enable_if_t<std::is_same_v<std::decay_t<T>, jfloat> || std::is_same_v<std::decay_t<T>, float>>* = nullptr)
{
return pValue;
}
template <typename C = Utility, typename T>
static jint convert(JNIEnv* pEnvironment, T pValue, typename std::enable_if_t<std::is_same_v<std::decay_t<T>, jint> || std::is_same_v<std::decay_t<T>, int32_t> || std::is_same_v<std::decay_t<T>, uint32_t> || std::is_same_v<std::decay_t<T>, size_t> || std::is_enum_v<std::decay_t<T>>>* = nullptr)
{
return pValue;
}
template <typename C = Utility, typename T>
static jlong convert(JNIEnv* pEnvironment, T pValue, typename std::enable_if_t<std::is_same_v<std::decay_t<T>, jlong>>* = nullptr)
{
return pValue;
}
template <typename C = Utility, typename T>
static jshort convert(JNIEnv* pEnvironment, T pValue, typename std::enable_if_t<std::is_same_v<std::decay_t<T>, jshort>>* = nullptr)
{
return pValue;
}
template <typename C = Utility, typename T>
static jobjectArray arrayObjectCreate(JNIEnv* pEnvironment, std::vector<T>&& pValue, jclass pClass)
{
assert(pClass != nullptr);
jobjectArray jArray = pEnvironment->NewObjectArray(static_cast<jsize>(pValue.size()), pClass, nullptr);
for (size_t i = 0; i < pValue.size(); ++i)
{
auto jValue = C::template objectCreate<C>(pEnvironment, std::move(pValue[i]));
pEnvironment->SetObjectArrayElement(jArray, static_cast<jsize>(i), static_cast<jobject>(jValue));
localRefDelete(pEnvironment, jValue);
}
return jArray;
}
template <typename C = Utility, typename T>
static jobjectArray arrayObjectCreate(JNIEnv* pEnvironment, const std::vector<T>& pValue, jclass pClass)
{
assert(pClass != nullptr);
jobjectArray jArray = pEnvironment->NewObjectArray(static_cast<jsize>(pValue.size()), pClass, nullptr);
for (size_t i = 0; i < pValue.size(); ++i)
{
auto jValue = C::template objectCreate<C>(pEnvironment, pValue[i]);
pEnvironment->SetObjectArrayElement(jArray, static_cast<jsize>(i), static_cast<jobject>(jValue));
localRefDelete(pEnvironment, jValue);
}
return jArray;
}
template <typename C = Utility, typename T>
static auto objectCreate(JNIEnv* pEnvironment, T pValue, typename std::enable_if_t<std::is_pointer_v<std::decay_t<T>>>* = nullptr)
{
return pValue != nullptr ? C::template objectCreate<C>(pEnvironment, *pValue) : nullptr;
}
template <typename C = Utility, typename T>
static jobject objectCreate(JNIEnv* pEnvironment, T pValue, typename std::enable_if_t<std::is_same_v<std::decay_t<T>, jboolean> || std::is_same_v<std::decay_t<T>, bool>>* = nullptr)
{
return pEnvironment->NewObject(mClasses[static_cast<size_t>(EClass::java_lang_Boolean)].first, mMethodIds[static_cast<size_t>(EMethodId::java_lang_Boolean_init)], pValue);
}
template <typename C = Utility, typename T>
static jobject objectCreate(JNIEnv* pEnvironment, T pValue, typename std::enable_if_t<std::is_same_v<std::decay_t<T>, jbyte>>* = nullptr)
{
return pEnvironment->NewObject(mClasses[static_cast<size_t>(EClass::java_lang_Byte)].first, mMethodIds[static_cast<size_t>(EMethodId::java_lang_Byte_init)], pValue);
}
template <typename C = Utility, typename T>
static jobject objectCreate(JNIEnv* pEnvironment, T pValue, typename std::enable_if_t<std::is_same_v<std::decay_t<T>, jdouble> || std::is_same_v<std::decay_t<T>, double>>* = nullptr)
{
return pEnvironment->NewObject(mClasses[static_cast<size_t>(EClass::java_lang_Double)].first, mMethodIds[static_cast<size_t>(EMethodId::java_lang_Double_init)], pValue);
}
template <typename C = Utility, typename T>
static jobject objectCreate(JNIEnv* pEnvironment, T pValue, typename std::enable_if_t<std::is_same_v<std::decay_t<T>, jfloat> || std::is_same_v<std::decay_t<T>, float>>* = nullptr)
{
return pEnvironment->NewObject(mClasses[static_cast<size_t>(EClass::java_lang_Float)].first, mMethodIds[static_cast<size_t>(EMethodId::java_lang_Float_init)], pValue);
}
template <typename C = Utility, typename T>
static jobject objectCreate(JNIEnv* pEnvironment, T pValue, typename std::enable_if_t<std::is_same_v<std::decay_t<T>, jint> || std::is_same_v<std::decay_t<T>, int32_t> || std::is_same_v<std::decay_t<T>, uint32_t> || std::is_same_v<std::decay_t<T>, size_t> || std::is_enum_v<std::decay_t<T>>>* = nullptr)
{
return pEnvironment->NewObject(mClasses[static_cast<size_t>(EClass::java_lang_Integer)].first, mMethodIds[static_cast<size_t>(EMethodId::java_lang_Integer_init)], static_cast<jint>(pValue));
}
template <typename C = Utility, typename T>
static jobject objectCreate(JNIEnv* pEnvironment, T pValue, typename std::enable_if_t<std::is_same_v<std::decay_t<T>, jlong>>* = nullptr)
{
return pEnvironment->NewObject(mClasses[static_cast<size_t>(EClass::java_lang_Long)].first, mMethodIds[static_cast<size_t>(EMethodId::java_lang_Long_init)], pValue);
}
template <typename C = Utility, typename T>
static jobject objectCreate(JNIEnv* pEnvironment, T pValue, typename std::enable_if_t<std::is_same_v<std::decay_t<T>, jshort>>* = nullptr)
{
return pEnvironment->NewObject(mClasses[static_cast<size_t>(EClass::java_lang_Short)].first, mMethodIds[static_cast<size_t>(EMethodId::java_lang_Short_init)], pValue);
}
template <typename C = Utility, typename T>
static auto objectCreate(JNIEnv* pEnvironment, T&& pValue, typename std::enable_if_t<!std::is_pod_v<std::decay_t<T>>>* = nullptr)
{
return C::template convert<C>(pEnvironment, std::forward<T>(pValue));
}
template <typename T>
static void localRefDelete(JNIEnv* pEnvironment, T&& pObject, typename std::enable_if_t<!std::is_convertible_v<std::decay_t<T>, jobject>>* = nullptr)
{
}
template <typename T>
static void localRefDelete(JNIEnv* pEnvironment, T&& pObject, typename std::enable_if_t<std::is_convertible_v<std::decay_t<T>, jobject>>* = nullptr)
{
if (pObject != nullptr)
pEnvironment->DeleteLocalRef(pObject);
}
template <typename... T>
static jboolean methodBooleanCall(JNIEnv* pEnvironment, jobject pObject, jmethodID pMethod, T&&... pParameters)
{
jboolean result = pEnvironment->CallBooleanMethod(pObject, pMethod, std::forward<T>(pParameters)...);
(void)std::initializer_list<int32_t>{(localRefDelete(pEnvironment, std::forward<T>(pParameters)), 0)...};
return result;
}
template <typename... T>
static jbyte methodByteCall(JNIEnv* pEnvironment, jobject pObject, jmethodID pMethod, T&&... pParameters)
{
jbyte result = pEnvironment->CallByteMethod(pObject, pMethod, std::forward<T>(pParameters)...);
(void)std::initializer_list<int32_t>{(localRefDelete(pEnvironment, std::forward<T>(pParameters)), 0)...};
return result;
}
template <typename... T>
static jchar methodCharCall(JNIEnv* pEnvironment, jobject pObject, jmethodID pMethod, T&&... pParameters)
{
jchar result = pEnvironment->CallCharMethod(pObject, pMethod, std::forward<T>(pParameters)...);
(void)std::initializer_list<int32_t>{(localRefDelete(pEnvironment, std::forward<T>(pParameters)), 0)...};
return result;
}
template <typename... T>
static jdouble methodDoubleCall(JNIEnv* pEnvironment, jobject pObject, jmethodID pMethod, T&&... pParameters)
{
jdouble result = pEnvironment->CallDoubleMethod(pObject, pMethod, std::forward<T>(pParameters)...);
(void)std::initializer_list<int32_t>{(localRefDelete(pEnvironment, std::forward<T>(pParameters)), 0)...};
return result;
}
template <typename... T>
static jfloat methodFloatCall(JNIEnv* pEnvironment, jobject pObject, jmethodID pMethod, T&&... pParameters)
{
jfloat result = pEnvironment->CallFloatMethod(pObject, pMethod, std::forward<T>(pParameters)...);
(void)std::initializer_list<int32_t>{(localRefDelete(pEnvironment, std::forward<T>(pParameters)), 0)...};
return result;
}
template <typename... T>
static jint methodIntCall(JNIEnv* pEnvironment, jobject pObject, jmethodID pMethod, T&&... pParameters)
{
jint result = pEnvironment->CallIntMethod(pObject, pMethod, std::forward<T>(pParameters)...);
(void)std::initializer_list<int32_t>{(localRefDelete(pEnvironment, std::forward<T>(pParameters)), 0)...};
return result;
}
template <typename... T>
static jlong methodLongCall(JNIEnv* pEnvironment, jobject pObject, jmethodID pMethod, T&&... pParameters)
{
jlong result = pEnvironment->CallLongMethod(pObject, pMethod, std::forward<T>(pParameters)...);
(void)std::initializer_list<int32_t>{(localRefDelete(pEnvironment, std::forward<T>(pParameters)), 0)...};
return result;
}
template <typename... T>
static jobject methodObjectCall(JNIEnv* pEnvironment, jobject pObject, jmethodID pMethod, T&&... pParameters)
{
jobject result = pEnvironment->CallObjectMethod(pObject, pMethod, std::forward<T>(pParameters)...);
(void)std::initializer_list<int32_t>{(localRefDelete(pEnvironment, std::forward<T>(pParameters)), 0)...};
return result;
}
template <typename... T>
static jshort methodShortCall(JNIEnv* pEnvironment, jobject pObject, jmethodID pMethod, T&&... pParameters)
{
jshort result = pEnvironment->CallShortMethod(pObject, pMethod, std::forward<T>(pParameters)...);
(void)std::initializer_list<int32_t>{(localRefDelete(pEnvironment, std::forward<T>(pParameters)), 0)...};
return result;
}
template <typename... T>
static void methodVoidCall(JNIEnv* pEnvironment, jobject pObject, jmethodID pMethod, T&&... pParameters)
{
pEnvironment->CallVoidMethod(pObject, pMethod, std::forward<T>(pParameters)...);
(void)std::initializer_list<int32_t>{(localRefDelete(pEnvironment, std::forward<T>(pParameters)), 0)...};
}
static jbyteArray convertHmsDataBuffer(JNIEnv* pEnvironment, const hms::DataBuffer& pValue);
private:
enum class EClass : size_t
{
java_lang_Boolean = 0,
java_lang_Byte,
java_lang_Double,
java_lang_Float,
java_lang_Integer,
java_lang_Long,
java_lang_Short,
java_lang_String,
java_lang_arrayByte,
pl_grupapracuj_hermes_ext_jni_ObjectNative,
pl_grupapracuj_pracuj_ext_tuple_Nontuple,
pl_grupapracuj_pracuj_ext_tuple_Octuple,
pl_grupapracuj_pracuj_ext_tuple_Pair,
pl_grupapracuj_pracuj_ext_tuple_Quadruple,
pl_grupapracuj_pracuj_ext_tuple_Quintuple,
pl_grupapracuj_pracuj_ext_tuple_Septuple,
pl_grupapracuj_pracuj_ext_tuple_Sextuple,
pl_grupapracuj_pracuj_ext_tuple_Triple,
COUNT
};
enum class EMethodId : size_t
{
java_lang_Boolean_init = 0,
java_lang_Byte_init,
java_lang_Double_init,
java_lang_Float_init,
java_lang_Integer_init,
java_lang_Long_init,
java_lang_Short_init,
pl_grupapracuj_pracuj_ext_tuple_Nontuple_init,
pl_grupapracuj_pracuj_ext_tuple_Octuple_init,
pl_grupapracuj_pracuj_ext_tuple_Pair_init,
pl_grupapracuj_pracuj_ext_tuple_Quadruple_init,
pl_grupapracuj_pracuj_ext_tuple_Quintuple_init,
pl_grupapracuj_pracuj_ext_tuple_Septuple_init,
pl_grupapracuj_pracuj_ext_tuple_Sextuple_init,
pl_grupapracuj_pracuj_ext_tuple_Triple_init,
COUNT
};
static std::array<std::pair<jclass, bool>, static_cast<size_t>(EClass::COUNT)> mClasses;
static std::array<jmethodID, static_cast<size_t>(EMethodId::COUNT)> mMethodIds;
static JavaVM* mJavaVM;
};
}
}
}
#endif
| 51.592441
| 311
| 0.636362
|
bg-sniffer
|
bd66012eb5e67142f44f98eaa63c0119954e1296
| 3,059
|
cpp
|
C++
|
test/gbelib_tests/cpu/operation/bytealuoperation_tests.cpp
|
johannes51/GBEmu
|
bb85debc8191d7eaa3917c2d441172f97731374c
|
[
"MIT"
] | null | null | null |
test/gbelib_tests/cpu/operation/bytealuoperation_tests.cpp
|
johannes51/GBEmu
|
bb85debc8191d7eaa3917c2d441172f97731374c
|
[
"MIT"
] | null | null | null |
test/gbelib_tests/cpu/operation/bytealuoperation_tests.cpp
|
johannes51/GBEmu
|
bb85debc8191d7eaa3917c2d441172f97731374c
|
[
"MIT"
] | null | null | null |
#include "gtest/gtest.h"
#include "cpu/cpuregisters.h"
#include "cpu/operation/bytealuoperation.h"
#include "location/location.h"
#include "mem/rambank.h"
#include "location/variablebyte.h"
TEST(ByteAluOperationTest, Xor)
{
ByteAluOperation xorOp { ByteAluFunction::Xor, Source::Register };
xorOp.setRegister(ByteRegister::B);
ASSERT_TRUE(xorOp.isComplete());
CpuRegisters r;
EXPECT_EQ(1, xorOp.cycles(r));
auto a = r.get(ByteRegister::A);
a.set(0x9); // 1001
ASSERT_EQ(0x9, a.get());
auto b = r.get(ByteRegister::B);
b.set(0x5); // 0101
ASSERT_EQ(0x5, b.get());
IMemoryViewSP m;
xorOp.execute(r, *m);
EXPECT_EQ(0xC, r.get(ByteRegister::A).get()); // 1100
}
TEST(ByteAluOperationTest, AddImmediate)
{
ByteAluOperation addOp { ByteAluFunction::Add, Source::Immediate };
ASSERT_FALSE(addOp.isComplete());
ASSERT_NO_THROW(addOp.nextOpcode(variableLocation(0x4D)));
ASSERT_TRUE(addOp.isComplete());
ASSERT_ANY_THROW(addOp.nextOpcode(variableLocation(0x4D)));
CpuRegisters r;
EXPECT_EQ(2, addOp.cycles(r));
r.get(ByteRegister::A).set(0x05);
IMemoryViewSP m;
addOp.execute(r, *m);
EXPECT_EQ(0x52, r.get(ByteRegister::A).get());
}
TEST(ByteAluOperationTest, Inc)
{
ByteAluOperation decOp { ByteAluFunction::Inc, Source::None };
decOp.setRegister(ByteRegister::B);
ASSERT_TRUE(decOp.isComplete());
CpuRegisters r;
EXPECT_EQ(1, decOp.cycles(r));
auto b = r.get(ByteRegister::B);
b.set(0x1); // 0001
ASSERT_EQ(0x1, b.get());
IMemoryViewSP m;
decOp.execute(r, *m);
EXPECT_EQ(0x2, r.get(ByteRegister::B).get()); // 0010
}
TEST(ByteAluOperationTest, IncIndirect)
{
ByteAluOperation decOp { ByteAluFunction::Inc, Source::Indirect };
ASSERT_TRUE(decOp.isComplete());
CpuRegisters r;
EXPECT_EQ(3, decOp.cycles(r));
r.get(WordRegister::HL).set(0x0100);
RamBank m { { 0x0100, 0x0101 } };
m.getByte(0x0100).set(0x13);
decOp.execute(r, m);
EXPECT_EQ(0x14, m.getByte(0x0100).get());
}
TEST(ByteAluOperationTest, Dec)
{
ByteAluOperation decOp { ByteAluFunction::Dec, Source::None };
decOp.setRegister(ByteRegister::B);
ASSERT_TRUE(decOp.isComplete());
CpuRegisters r;
EXPECT_EQ(1, decOp.cycles(r));
auto b = r.get(ByteRegister::B);
b.set(0x1); // 0001
ASSERT_EQ(0x1, b.get());
IMemoryViewSP m;
decOp.execute(r, *m);
EXPECT_EQ(0x0, r.get(ByteRegister::B).get()); // 0000
}
TEST(ByteAluOperationTest, DecIndirect)
{
ByteAluOperation decOp { ByteAluFunction::Dec, Source::Indirect };
ASSERT_TRUE(decOp.isComplete());
CpuRegisters r;
EXPECT_EQ(3, decOp.cycles(r));
r.get(WordRegister::HL).set(0x0100);
RamBank m { { 0x0100, 0x0101 } };
m.getByte(0x0100).set(0x13);
decOp.execute(r, m);
EXPECT_EQ(0x12, m.getByte(0x0100).get());
}
TEST(ByteAluOperationTest, Throws)
{
CpuRegisters r;
IMemoryViewSP m;
ByteAluOperation decOp { ByteAluFunction::Add, Source::Register };
EXPECT_ANY_THROW(decOp.execute(r, *m));
ByteAluOperation decOp2 { ByteAluFunction::Add, Source::None };
EXPECT_ANY_THROW(decOp2.execute(r, *m));
}
| 23.898438
| 69
| 0.700883
|
johannes51
|
bd68d98daaf17c23a342f2fd30f744f9bd7a3cc9
| 320
|
cpp
|
C++
|
demos/demo.cpp
|
RyanDraves/CPPurses
|
19cbdae2d18e702144659187ec989c486c714a0f
|
[
"MIT"
] | null | null | null |
demos/demo.cpp
|
RyanDraves/CPPurses
|
19cbdae2d18e702144659187ec989c486c714a0f
|
[
"MIT"
] | null | null | null |
demos/demo.cpp
|
RyanDraves/CPPurses
|
19cbdae2d18e702144659187ec989c486c714a0f
|
[
"MIT"
] | null | null | null |
#include <cppurses/system/focus.hpp>
#include <cppurses/system/system.hpp>
#include <cppurses/widget/widgets/menu.hpp>
#include "main_menu.hpp"
using namespace cppurses;
int main()
{
System sys;
demos::Main_menu demo_menu;
System::set_initial_focus(&demo_menu.main_menu);
return sys.run(demo_menu);
}
| 20
| 52
| 0.7375
|
RyanDraves
|
bd6c1b8ac9a435830d89f076329aadded96b0b79
| 604
|
cpp
|
C++
|
t2/main.cpp
|
vinthony/Learning-Graphics
|
9c20c8f1d9378a7fb2e9be7eef8042a9c6d4a2be
|
[
"MIT"
] | null | null | null |
t2/main.cpp
|
vinthony/Learning-Graphics
|
9c20c8f1d9378a7fb2e9be7eef8042a9c6d4a2be
|
[
"MIT"
] | null | null | null |
t2/main.cpp
|
vinthony/Learning-Graphics
|
9c20c8f1d9378a7fb2e9be7eef8042a9c6d4a2be
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <GL/glew.h>
#include <GLUT/GLUT.h>
void render(){
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);
glutSwapBuffers();
glFlush();
}
int main (int argc,char ** argv)
{
glutInit(&argc, argv);
glutInitWindowSize(800,600);
glutInitWindowPosition(100, 100);
glutCreateWindow("t1");
// glutDisplayFunc(void);
GLenum res = glewInit();
if(res != GLEW_OK)
{
fprintf(stderr,"ERROR: %s\n",glewGetErrorString(res));
return 1;
}
glutDisplayFunc(render);
glutMainLoop();
}
| 18.30303
| 62
| 0.602649
|
vinthony
|
bd6e74a7a395183f5a3db25fcab72429fccd81b1
| 686
|
cpp
|
C++
|
src/DefaultPropertyProcessors/ProjectionProcessor.cpp
|
Megaxela/HGEngineReloadedEditor
|
be79b6089985da1bf811be8a6d06ce25f71236b1
|
[
"MIT"
] | null | null | null |
src/DefaultPropertyProcessors/ProjectionProcessor.cpp
|
Megaxela/HGEngineReloadedEditor
|
be79b6089985da1bf811be8a6d06ce25f71236b1
|
[
"MIT"
] | null | null | null |
src/DefaultPropertyProcessors/ProjectionProcessor.cpp
|
Megaxela/HGEngineReloadedEditor
|
be79b6089985da1bf811be8a6d06ce25f71236b1
|
[
"MIT"
] | 1
|
2020-03-12T04:39:14.000Z
|
2020-03-12T04:39:14.000Z
|
// Editor
#include <DefaultPropertyProcessors/ProjectionProcessor.hpp>
// HG::Rendering::Base
#include <HG/Rendering/Base/Camera.hpp>
// ImGui
#include <imgui.h>
void HG::Editor::PropertyProcessors::ProjectionProcessor::perform(const std::string &name, const HG::Core::Behaviour::Property &property)
{
auto value = static_cast<int>(property.getGetter<HG::Rendering::Base::Camera::Projection>()());
const char* items[] = {"Perspective", "Orthogonal"};
if (ImGui::Combo(name.c_str(), &value, items, 2))
{
property.getSetter<HG::Rendering::Base::Camera::Projection>()(
static_cast<HG::Rendering::Base::Camera::Projection>(value)
);
}
}
| 29.826087
| 137
| 0.680758
|
Megaxela
|
bd6ec19d8e0654361314d02e95a35c368add952e
| 2,181
|
cc
|
C++
|
src/windows/libraries/ws2_32/functions/connect.cc
|
srpape/IntroVirt
|
fe553221c40b8ef71f06e79c9d54d9e123a06c89
|
[
"Apache-2.0"
] | null | null | null |
src/windows/libraries/ws2_32/functions/connect.cc
|
srpape/IntroVirt
|
fe553221c40b8ef71f06e79c9d54d9e123a06c89
|
[
"Apache-2.0"
] | null | null | null |
src/windows/libraries/ws2_32/functions/connect.cc
|
srpape/IntroVirt
|
fe553221c40b8ef71f06e79c9d54d9e123a06c89
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2021 Assured Information Security, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <introvirt/core/exception/InvalidMethodException.hh>
#include <introvirt/windows/libraries/ws2_32/functions/connect.hh>
#include <boost/io/ios_state.hpp>
namespace introvirt {
namespace windows {
namespace ws2_32 {
/* Input arguments */
SOCKET connect::s() const { return s_; }
void connect::s(SOCKET s) {
set_argument(0, s);
s_ = s;
}
GuestVirtualAddress connect::pName() const { return pName_; }
void connect::pName(const GuestVirtualAddress& gva) {
set_address_argument(1, gva);
pName_ = gva;
}
int32_t connect::namelen() const { return namelen_; }
void connect::namelen(int32_t namelen) {
set_argument(2, namelen);
namelen_ = namelen;
}
/* Helpers */
const SOCKADDR* connect::name() const {
if (!name_ && pName_) {
name_ = SOCKADDR::make_unique(pName(), x64());
}
return name_.get();
}
SOCKADDR* connect::name() {
const auto* const_this = this;
return const_cast<SOCKADDR*>(const_this->name());
}
int32_t connect::result() const { return raw_return_value(); }
const std::string& connect::function_name() const { return FunctionName; }
const std::string& connect::library_name() const { return LibraryName; }
void connect::write(std::ostream& os) const {
boost::io::ios_flags_saver ifs(os);
// TODO
}
connect::connect(Event& event) : WindowsFunctionCall(event, ArgumentCount) {
s_ = get_argument(0);
pName_ = get_address_argument(1);
namelen_ = get_argument(2);
}
connect::~connect() = default;
} // namespace ws2_32
} // namespace windows
} // namespace introvirt
| 29.08
| 76
| 0.707015
|
srpape
|
bd703d247c722445b2495fcd5d339ad5288ccde2
| 1,185
|
cpp
|
C++
|
SDDD/pitchui.cpp
|
hux8/SDD-Project
|
1d589f88655f5a565f0c2efb5d60a3dd8ccc5c06
|
[
"MIT"
] | null | null | null |
SDDD/pitchui.cpp
|
hux8/SDD-Project
|
1d589f88655f5a565f0c2efb5d60a3dd8ccc5c06
|
[
"MIT"
] | 1
|
2019-03-15T01:59:20.000Z
|
2019-03-15T17:36:01.000Z
|
SDDD/pitchui.cpp
|
hux8/SDD-Project
|
1d589f88655f5a565f0c2efb5d60a3dd8ccc5c06
|
[
"MIT"
] | 5
|
2018-10-25T23:14:30.000Z
|
2018-11-05T18:43:46.000Z
|
#include "pitchui.h"
#include "ui_pitchui.h"
PitchUI::PitchUI(QWidget *parent) :
QWidget(parent),
ui(new Ui::PitchUI)
{
ui->setupUi(this);
ui->description->setReadOnly(true);
}
PitchUI::~PitchUI()
{
delete ui;
}
void PitchUI::setAccess(bool b)
{
ui->bdelete->setVisible(b);
ui->bmodifyDescription->setVisible(b);
}
void PitchUI::setUp(int i, int date, QString t, QString d)
{
id=i;
ui->description->setText(d);
ui->title->setText(t);
setWindowTitle(t);
QString da=QString::number(date);
ui->date->setText(da.left(4)+"/"+da.mid(4,2)+"/"+da.right(2));
}
void PitchUI::toConfirm()
{
ConfirmDialog* c=new ConfirmDialog();
connect(c,SIGNAL(confirmed()),this,SLOT(toDelete()));
c->show();
}
void PitchUI::modifyDescription()
{
if(ui->description->isReadOnly())
{
ui->description->setReadOnly(false);
ui->bmodifyDescription->setText("Confirm");
}
else
{
ui->description->setReadOnly(true);
ui->bmodifyDescription->setText("Modify");
emit modify(id, 0,ui->description->toPlainText());
}
}
void PitchUI::toDelete()
{
emit deletePitch(id);
close();
}
| 19.42623
| 66
| 0.621941
|
hux8
|
bd73b6e8988b8ab0ec5874f3e76506051b98e365
| 13,845
|
cpp
|
C++
|
src/q65_main.cpp
|
alexander-sholohov/msk144decoder
|
f89fdcf9ec72f6f3d197380a3046c486a251f768
|
[
"MIT"
] | null | null | null |
src/q65_main.cpp
|
alexander-sholohov/msk144decoder
|
f89fdcf9ec72f6f3d197380a3046c486a251f768
|
[
"MIT"
] | null | null | null |
src/q65_main.cpp
|
alexander-sholohov/msk144decoder
|
f89fdcf9ec72f6f3d197380a3046c486a251f768
|
[
"MIT"
] | null | null | null |
//
// Author: Alexander Sholohov <ra9yer@yahoo.com>
//
// License: MIT
//
#include "wavfile.h"
#include "q65_context.h"
#include "report_tasks.h"
#include "utils.h"
#include "http_reporter.h"
#include "decode_result.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sched.h>
#include <unistd.h>
#include <getopt.h>
#if __GNUC__ > 7
#include <cstddef>
typedef size_t fortran_charlen_t;
#else
typedef int fortran_charlen_t;
#endif
#include <string>
#include <vector>
#include <iostream>
#include <thread>
#include <sstream>
#include <algorithm>
#define MY_FALSE (0)
#define MY_TRUE (1)
enum class WORKING_MODE
{
IDLE,
COLLECTING,
};
// GFortran interop trick.
struct GFortranContext
{
void* data0 = &fortran_working_area[0];
void* data1 = 0;
std::vector<DecodeResult> decode_results;
size_t fortran_working_area[16];
};
extern "C" {
// --- Fortran routines ---
void __q65_decode_MOD_decode(
void* me,
void* callback,
const short int iwave[], // Raw data, i*2
int* nutc, // UTC for time-tagging the decode
int* ntrperiod, // T/R sequence length (s)
int* nsubmode, // Tone-spacing indicator, 0-4 for A-E
int* nfqso, // Target signal frequency (Hz)
int* ntol, // Search range around nfqso (Hz)
int* ndepth, // Optional decoding level
int* nfa0, // 200?
int* nfb0, // 4000?
int* lclearave, // bool. Flag to clear the message-averaging arrays
int* single_decode, // bool.
int* lagain, // bool.
int* lnewdat0, // bool.
int* emedelay, // Sync search extended to cover EME delays
char* mycall,
char* hiscall,
char* hisgrid,
int* nQSOprogress, // Auto-sequencing state for the present QSO
int* ncontest, // Supported contest type
int* lapcqonly, // bool. Flag to use AP only for CQ calls
int* navg0, // output?
fortran_charlen_t, fortran_charlen_t, fortran_charlen_t);
}
extern "C" void q65_decode_callback(
GFortranContext * me,
int* nutc,
float* snr1,
int* nsnr,
float* dt,
float* freq,
char* decoded, // size of 37
int* idec,
int* nused,
int* ntrperiod)
{
std::ostringstream info;
info << "nutc=" << *nutc
<< " snr1=" << *snr1
<< " nsnr=" << *nsnr
<< " dt=" << *dt
<< " freq=" << *freq
<< " decod=" << decoded
<< " idec=" << *idec
<< " nused=" << *nused
<< " ntrperiod=" << *ntrperiod
<< std::endl;
if (*idec > -1)
{
DecodeResult dr;
dr.initFromParams(*snr1, *dt, *freq, *nutc, rtrim_copy(decoded), info.str());
me->decode_results.emplace_back(dr);
}
std::cout << "*** " << info.str() << std::endl;
}
//-----------------------------------------------------------------------------------
static void call_q65_decoder(std::vector<short> stream, Q65Context const& ctx, int utc_hhmm)
{
int ntrperiod = ctx.tr_interval_in_seconds;
int nsubmode = ctx.q65_submode;
int nfqso = 200; //
int ntol = 0;
int ndepth = ctx.q65_depth;
int nfa0 = 200;
int nfb0 = 4000;
int lclearave = MY_FALSE; //
int single_decode = MY_FALSE;
int lagain = MY_FALSE;
int lnewdat0 = MY_FALSE;
int emedelay = 0;
char mycall[12];
char hiscall[12];
char hisgrid[6];
int nQSOprogress = 0;
int ncontest = 0;
int lapcqonly = MY_FALSE;
int navg0 = 0; // output
memset(mycall, 0, sizeof(mycall));
memset(hiscall, 0, sizeof(hiscall));
memset(hisgrid, 0, sizeof(hisgrid));
GFortranContext fortranContext;
void* callback = (void*)&q65_decode_callback;
__q65_decode_MOD_decode(
&fortranContext,
callback,
&stream[0], // Raw data, i*2
&utc_hhmm, // UTC for time-tagging the decode
&ntrperiod, // T/R sequence length (s)
&nsubmode, // Tone-spacing indicator, 0-4 for A-E
&nfqso, // Target signal frequency (Hz)
&ntol, // Search range around nfqso (Hz)
&ndepth, // Optional decoding level
&nfa0, //
&nfb0, //
&lclearave, // Flag to clear the message-averaging arrays
&single_decode, //
&lagain,
&lnewdat0,
&emedelay, // Sync search extended to cover EME delays
mycall,
hiscall,
hisgrid,
&nQSOprogress, // Auto-sequencing state for the present QSO
&ncontest, // Supported contest type
&lapcqonly, // Flag to use AP only for CQ calls
&navg0,
12/* mycall */, 12 /* hiscall */, 6 /* hisgrid */);
size_t seq_no = 0;
for (DecodeResult const& dr : fortranContext.decode_results)
{
if (dr.isValid())
{
// call as normal function, not a thread
report_tasks(ctx, std::move(stream), dr, seq_no);
seq_no++;
}
}
}
//-------------------------------------------------------------------
int utc_as_wsjt_int_by_tr_interval(int tr_interval)
{
return (tr_interval >= 60) ? utc_as_wsjt_int_hhmm() : utc_as_wsjt_int_hhmmss();
}
//-------------------------------------------------------------------
static void usage(void)
{
std::ostringstream buf;
buf << "\nq65decoder - q65 digital mode stream decoder. Accepts audio stream - 16 bits signed, 12000 samples per second, mono.\n\n";
buf << "Usage:\t[--spot-reporter-url= Address of spot reporter service. (default: http://192.168.1.200:9000/spotter/default/populate_spot ]\n";
buf << "\t[--spot-reporter-enable= Enable or not http report. true or 1 to enable (default: false)]\n";
buf << "\t[--file-log-enable= Enable or not file logging. true or 1 to enable (default: false)]\n";
buf << "\t[--file-log-workdir= Directory name where put file logs into. (default: \".\")]\n";
buf << "\t[--q65-submode= Submode 0,1,2,3,4 means A,B,C,D,E (default: 0)]\n";
buf << "\t[--tr-interval= T/R interval in seconds (default: 60)]\n";
buf << "\t[--depth= Deep of analysis. (default: 3)]\n";
buf << "\t[--immediate-read Read stream until buffer full, run decoder and exit.]\n";
buf << "\t[--help this text]\n";
std::cout << buf.str() << std::endl;
exit(1);
}
//------------------------------------------------------------
static bool str2bool(const char* str)
{
if (strcmp(str, "true") == 0)
return true;
if (strcmp(str, "1") == 0)
return true;
return false;
}
//------------------------------------------------------------
int main(int argc, char** argv)
{
Q65Context ctx;
static struct option long_options[] = {
{"help", no_argument, 0, 0}, // 0
{"sport-reporter-src", required_argument, 0, 0}, // 1
{"spot-reporter-url", required_argument, 0, 0}, // 2
{"spot-reporter-magic-key", required_argument, 0, 0}, // 3
{"spot-reporter-enable", required_argument, 0, 0}, // 4
{"file-log-enable", required_argument, 0, 0}, // 5
{"file_log_workdir", required_argument, 0, 0}, // 6
{"q65-submode", required_argument, 0, 0}, // 7
{"tr-interval", required_argument, 0, 0}, // 8
{"depth", required_argument, 0, 0}, // 9
{"immediate-read", no_argument, 0, 0}, // 10
{0, 0, 0, 0}
};
while (true)
{
int option_index = 0;
int c = getopt_long(argc, argv, "", long_options, &option_index);
if (c == -1)
break;
if (c == 0)
{
switch (option_index)
{
case 0:
usage();
break;
case 1:
ctx.sport_reporter_src = optarg;
break;
case 2:
ctx.spot_reporter_url = optarg;
break;
case 3:
ctx.spot_reporter_magic_key = optarg;
break;
case 4:
ctx.sport_reporter_enabled = str2bool(optarg);
break;
case 5:
ctx.file_log_enabled = str2bool(optarg);
break;
case 6:
ctx.file_log_workdir = optarg;
break;
case 7:
ctx.q65_submode = atoi(optarg);
break;
case 8:
ctx.tr_interval_in_seconds = atoi(optarg);
break;
case 9:
ctx.q65_depth = atoi(optarg);
break;
case 10:
ctx.immediate_read = true;
break;
default:
usage();
}
}
}
// print Context info to stdout
std::cout << ctx.asString() << std::endl;
std::vector<int> valid_tr_interval = { 15, 30, 60, 120, 300 };
if (std::find(valid_tr_interval.begin(), valid_tr_interval.end(), ctx.tr_interval_in_seconds) == valid_tr_interval.end())
{
std::cerr << "Wrong T/R interval." << std::endl;
return -1;
}
const size_t IDLE_READ_SIZE = 1024;
std::vector<short> idle_buffer(IDLE_READ_SIZE);
const size_t COLLECTING_READ_SIZE = 1024;
const size_t sample_rate = 12000;
const size_t target_num_samples = sample_rate * ctx.tr_interval_in_seconds;
std::vector<short> collecting_buffer(target_num_samples);
size_t collecting_pos = 0;
std::cout << "Q65 decoder started." << std::endl;
// ----- Short Stream Mode --------
if (ctx.immediate_read)
{
while (true)
{
if (feof(stdin))
{
std::cerr << "Got EOF" << std::endl;
break;
}
if (collecting_pos + COLLECTING_READ_SIZE > collecting_buffer.size())
{
std::cout << "Read done" << std::endl;
break;
}
else
{
// consume samples to buffer
int rc = fread(&collecting_buffer[collecting_pos], sizeof(short), COLLECTING_READ_SIZE, stdin);
if (rc != IDLE_READ_SIZE) { std::cout << "Incomplete read. rc=" << rc << std::endl; break; }
collecting_pos += COLLECTING_READ_SIZE;
}
}
if (collecting_pos)
{
std::cout << "Start decoding ..." << std::endl;
// fill rest by zeroes
std::fill(collecting_buffer.begin() + collecting_pos, collecting_buffer.end(), 0);
int utc = utc_as_wsjt_int_by_tr_interval(ctx.tr_interval_in_seconds); //
std::thread t(call_q65_decoder, collecting_buffer, ctx, utc);
t.join();
}
std::cout << "Q65 decoder immediate read normal exit." << std::endl;
return 0;
}
WORKING_MODE working_mode = WORKING_MODE::IDLE;
int prev_seconds_to_launch = ctx.tr_interval_in_seconds;
int limit_num_samples_extra = 0; // 0 - means no extra limit
// --- Normal Stream Mode ---
while(true)
{
if (feof(stdin))
{
std::cerr << "Got EOF" << std::endl;
break;
}
if (working_mode == WORKING_MODE::IDLE)
{
// wait moment to start
int s = seconds_to_next_launch(ctx.tr_interval_in_seconds);
bool need_launch = false;
// basic condition to start
if (s == 0)
{
need_launch = true;
limit_num_samples_extra = 0;
}
// in case we missed launch moment somehow
if (!need_launch && s > prev_seconds_to_launch)
{
int passed = seconds_since_launch(ctx.tr_interval_in_seconds);
limit_num_samples_extra = (ctx.tr_interval_in_seconds - passed - 1) * sample_rate;
if (limit_num_samples_extra > 0)
{
need_launch = true;
}
}
prev_seconds_to_launch = s;
if (need_launch)
{
working_mode = WORKING_MODE::COLLECTING;
collecting_pos = 0;
}
}
if (working_mode == WORKING_MODE::COLLECTING)
{
if (collecting_pos + COLLECTING_READ_SIZE > collecting_buffer.size()
|| ((limit_num_samples_extra != 0) && collecting_pos + COLLECTING_READ_SIZE > limit_num_samples_extra))
{
working_mode = WORKING_MODE::IDLE;
prev_seconds_to_launch = ctx.tr_interval_in_seconds;
// fill rest by zeroes
std::fill(collecting_buffer.begin() + collecting_pos, collecting_buffer.end(), 0);
int utc = utc_as_wsjt_int_by_tr_interval(ctx.tr_interval_in_seconds);
std::thread t(call_q65_decoder, collecting_buffer, ctx, utc);
t.detach();
}
else
{
// consume samples to buffer
int rc = fread(&collecting_buffer[collecting_pos], sizeof(short), COLLECTING_READ_SIZE, stdin);
if (rc != IDLE_READ_SIZE) { std::cerr << "Incomplete read error. rc=" << rc << std::endl; break; }
collecting_pos += COLLECTING_READ_SIZE;
}
}
else
{
// reading idle samples for nothing
int rc = fread(&idle_buffer[0], sizeof(short), IDLE_READ_SIZE, stdin);
if (rc != IDLE_READ_SIZE) { std::cerr << "Incomplete read error. rc=" << rc << std::endl; break; }
}
sched_yield(); // Force give time to OS. Probably not very necessary.
}
::usleep(1000 * 1000); // just 1 second delay before exit.
std::cout << "Q65 decoder exit." << std::endl;
return 0;
}
| 30.295405
| 147
| 0.536439
|
alexander-sholohov
|
bd76fa768bc0df07079bc388d6a245db00721053
| 1,770
|
hpp
|
C++
|
CodeGeneration/core/ValidationHandler.hpp
|
tedi21/SisypheReview
|
f7c05bad1ccc036f45870535149d9685e1120c2c
|
[
"Unlicense"
] | null | null | null |
CodeGeneration/core/ValidationHandler.hpp
|
tedi21/SisypheReview
|
f7c05bad1ccc036f45870535149d9685e1120c2c
|
[
"Unlicense"
] | null | null | null |
CodeGeneration/core/ValidationHandler.hpp
|
tedi21/SisypheReview
|
f7c05bad1ccc036f45870535149d9685e1120c2c
|
[
"Unlicense"
] | null | null | null |
#ifndef _VALIDATION_HANDLER_HPP_
#define _VALIDATION_HANDLER_HPP_
#include <xercesc/sax/ErrorHandler.hpp>
#include <xercesc/sax/SAXParseException.hpp>
#include "xstring.hpp"
using namespace log4cpp;
using namespace xercesc;
using namespace enc;
namespace dsg {
#define X(str) encode<ansi,xml>(str).c_str()
#define C(str) encode<xml,ansi>(str).c_str()
class ValidationHandler
: public ErrorHandler
{
private:
bool mIsValid;
Category* m_logger;
public:
ValidationHandler()
{
m_logger = &Category::getInstance(LOGNAME);
mIsValid = true;
}
virtual ~ValidationHandler()
{}
virtual void warning (const SAXParseException &e)
{
m_logger->warnStream() << "XML DTD warning ("
<< e.getLineNumber() << ") : "
<< C(e.getMessage());
}
virtual void error (const SAXParseException &e)
{
mIsValid = false;
m_logger->errorStream() << "XML DTD error ("
<< e.getLineNumber() << ") : "
<< C(e.getMessage());
}
virtual void fatalError (const SAXParseException &e)
{
mIsValid = false;
m_logger->fatalStream() << "XML DTD fatal error ("
<< e.getLineNumber() << ") : "
<< C(e.getMessage());
}
virtual void resetErrors ()
{
mIsValid = true;
}
bool IsValid()
{
return mIsValid;
}
};
#undef X
#undef C
}
#endif // _VALIDATION_HANDLER_HPP_
| 24.246575
| 67
| 0.49209
|
tedi21
|
bd78b6e7608b8181e7e40a27ebd3c9d9fe3d16ac
| 1,146
|
cpp
|
C++
|
src/ConnectorInfos.cpp
|
flagarde/YAODAQ
|
851df4aa32b8695c4706bb3ec9f353f4461c9cad
|
[
"MIT"
] | null | null | null |
src/ConnectorInfos.cpp
|
flagarde/YAODAQ
|
851df4aa32b8695c4706bb3ec9f353f4461c9cad
|
[
"MIT"
] | 11
|
2021-05-14T19:50:27.000Z
|
2022-03-31T07:19:41.000Z
|
src/ConnectorInfos.cpp
|
flagarde/YAODAQ
|
851df4aa32b8695c4706bb3ec9f353f4461c9cad
|
[
"MIT"
] | 5
|
2021-05-11T13:30:30.000Z
|
2021-05-26T19:57:22.000Z
|
#include "ConnectorInfos.hpp"
#include "toml.hpp"
#include <iostream>
namespace yaodaq
{
ConnectorInfos::ConnectorInfos(const toml::value& params, const bool& isShared, const int& id): m_Parameters(params), m_IsSharedConnector(isShared), m_ID(id) {}
int ConnectorInfos::getID()
{
return m_ID;
}
int ConnectorInfos::getID() const
{
return m_ID;
}
bool ConnectorInfos::isSharedConnector()
{
return m_IsSharedConnector;
}
bool ConnectorInfos::isSharedConnector() const
{
return m_IsSharedConnector;
}
toml::value& ConnectorInfos::getParameters()
{
return m_Parameters;
}
toml::value ConnectorInfos::getParameters() const
{
return m_Parameters;
}
void ConnectorInfos::printParameters()
{
std::cout << m_Parameters << std::endl;
}
void ConnectorInfos::printParameters() const
{
std::cout << m_Parameters << std::endl;
}
void ConnectorInfos::setHandle(const std::int32_t& handle)
{
m_Handle = handle;
}
void ConnectorInfos::addBoardConnected()
{
++m_BoardConnected;
}
void ConnectorInfos::removeBoardConnected()
{
--m_BoardConnected;
}
int ConnectorInfos::getNumberBoardConnected()
{
return m_BoardConnected;
}
}
| 16.140845
| 160
| 0.744328
|
flagarde
|
bd7ab0133ba818c899f7ea555fdf93a2cb127f03
| 317
|
cc
|
C++
|
cpp/sort/selection.cc
|
eryue0220/teach-myself-algorithm
|
1b4d79a2a9bc6b9850deec70bcdccf7f05b9052d
|
[
"MIT"
] | null | null | null |
cpp/sort/selection.cc
|
eryue0220/teach-myself-algorithm
|
1b4d79a2a9bc6b9850deec70bcdccf7f05b9052d
|
[
"MIT"
] | null | null | null |
cpp/sort/selection.cc
|
eryue0220/teach-myself-algorithm
|
1b4d79a2a9bc6b9850deec70bcdccf7f05b9052d
|
[
"MIT"
] | null | null | null |
#include <algorithm>
#include "sort.h"
using namespace std;
template <typename T>
void selectionSort( T arr[], int n ) {
for ( int i = 0; i < n; i++ ) {
int minIndex = i;
for ( int j = i + 1; j < n; j++ )
if ( arr[j] < arr[minIndex] )
minIndex = j;
swap( arr[i], arr[minIndex] );
}
}
| 19.8125
| 38
| 0.526814
|
eryue0220
|
bd80fb0cd67c0d424a1ce2a4a2e8db9303a0ff56
| 1,446
|
hpp
|
C++
|
include/boost/document/detail/ms_api/ms_sheet.hpp
|
anuragxel/generic-document-library
|
e7d0f53f47ab85709968c91f0f4ca423796bc4cd
|
[
"BSL-1.0"
] | null | null | null |
include/boost/document/detail/ms_api/ms_sheet.hpp
|
anuragxel/generic-document-library
|
e7d0f53f47ab85709968c91f0f4ca423796bc4cd
|
[
"BSL-1.0"
] | null | null | null |
include/boost/document/detail/ms_api/ms_sheet.hpp
|
anuragxel/generic-document-library
|
e7d0f53f47ab85709968c91f0f4ca423796bc4cd
|
[
"BSL-1.0"
] | null | null | null |
#ifndef _MS_SHEET_HPP
#define _MS_SHEET_HPP
// Copyright Anurag Ghosh 2015.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <string>
#include <iostream>
#include <cstdlib>
#include <windows.h>
#include <ole2.h>
#include <objbase.h>
#include <boost/filesystem.hpp>
#include <boost/throw_exception.hpp>
#include <boost/document/detail/document_file_format.hpp>
#include <boost/document/detail/document_exception.hpp>
namespace boost { namespace doc { namespace ms_sheet {
void get_sheets_of_document(IDispatch*& sheets_ptr, IDispatch*& book_ptr);
void rename_sheet(IDispatch* sheet_ptr, const std::string& str);
void insert_new_sheet(IDispatch *sheets_ptr, const std::string& sheet_name, IDispatch*& sheet_ptr);
void get_sheet_by_name(IDispatch *sheets_ptr, const std::string& sheet_name, IDispatch*& sheet_ptr);
void get_sheet_by_index(IDispatch *sheets_ptr, int sheet_index, IDispatch*& sheet_ptr);
void get_active_sheet(IDispatch *sheets_ptr, IDispatch*& sheet_ptr);
void activate_sheet(IDispatch* sheet_ptr);
void delete_sheet_by_name(IDispatch *sheets_ptr, const std::string& str);
void delete_sheet_by_index(IDispatch *sheets_ptr, int index);
int get_sheet_count(IDispatch *sheets_ptr);
std::string get_sheet_name(IDispatch *sheet_ptr);
int get_sheet_index(IDispatch *sheet_ptr);
}}}
#endif
| 32.133333
| 100
| 0.782158
|
anuragxel
|
bd81feb53f212e2506a309fb42ed6b82464e97fc
| 1,250
|
cpp
|
C++
|
Graph Algorithms/Giant Pizza.cpp
|
DecSP/cses-downloader
|
12a8f37665a33f6f790bd2c355f84dea8a0e332c
|
[
"MIT"
] | 2
|
2022-02-12T12:30:13.000Z
|
2022-02-12T13:59:20.000Z
|
Graph Algorithms/Giant Pizza.cpp
|
DecSP/cses-downloader
|
12a8f37665a33f6f790bd2c355f84dea8a0e332c
|
[
"MIT"
] | 2
|
2022-02-12T11:09:41.000Z
|
2022-02-12T11:55:49.000Z
|
Graph Algorithms/Giant Pizza.cpp
|
DecSP/cses-downloader
|
12a8f37665a33f6f790bd2c355f84dea8a0e332c
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
int n,q;
vector<vector<int>> neg,pos;
vector<int> ans1,ans2;
bool dfs(int cur, bool isPos,vector<int>&ans){
bool re=true;
if (ans[cur]) return (ans[cur]>0&&isPos)||(ans[cur]<0&&!isPos);
ans[cur]=(isPos)?1:-1;
if (isPos) {
for(int &v:pos[cur]){
if (v>0) re=re&&dfs(v-1,true,ans);
else re=re&&dfs(abs(v)-1,false,ans);
}
}
else {
for(int &v:neg[cur]){
if (v>0) re=re&&dfs(v-1,true,ans);
else re=re&&dfs(abs(v)-1,false,ans);
}
}
return re;
}
int main(){
ios::sync_with_stdio(false);cin.tie(NULL);
cin>>q>>n;
neg.assign(n,vector<int>());
pos.assign(n,vector<int>());
for (int i=0;i<q;++i){
int a,b;char ca,cb;
cin>>ca>>a>>cb>>b;
a=a*((ca=='-')*-2+1);
b=b*((cb=='-')*-2+1);
if (b<0) pos[-b-1].push_back(a);
else neg[b-1].push_back(a);
if (a<0) pos[-a-1].push_back(b);
else neg[a-1].push_back(b);
}
ans1.assign(n,0);
ans2.assign(n,0);
vector<int> ans(n,0);
for (int i=0;i<n;++i){
if (ans[i]) continue;
if(dfs(i,true,ans1))
dfs(i,true,ans);
else if (dfs(i,false,ans2))
dfs(i,false,ans);
else {
cout<<"IMPOSSIBLE\n";
return 0;
}
}
for (int i=0;i<n;++i){
if (ans[i]>0) cout<<"+ ";
else cout<<"- ";
}
cout<<'\n';
return 0;
}
| 19.53125
| 64
| 0.556
|
DecSP
|
bd8326ae819c6b64466633fbabb82becd94278be
| 309
|
cpp
|
C++
|
docs/atl/codesnippet/CPP/catllist-class_3.cpp
|
bobbrow/cpp-docs
|
769b186399141c4ea93400863a7d8463987bf667
|
[
"CC-BY-4.0",
"MIT"
] | 965
|
2017-06-25T23:57:11.000Z
|
2022-03-31T14:17:32.000Z
|
docs/atl/codesnippet/CPP/catllist-class_3.cpp
|
bobbrow/cpp-docs
|
769b186399141c4ea93400863a7d8463987bf667
|
[
"CC-BY-4.0",
"MIT"
] | 3,272
|
2017-06-24T00:26:34.000Z
|
2022-03-31T22:14:07.000Z
|
docs/atl/codesnippet/CPP/catllist-class_3.cpp
|
bobbrow/cpp-docs
|
769b186399141c4ea93400863a7d8463987bf667
|
[
"CC-BY-4.0",
"MIT"
] | 951
|
2017-06-25T12:36:14.000Z
|
2022-03-26T22:49:06.000Z
|
// Define the list
CAtlList<int> myList;
// Add elements to the tail
myList.AddTail(1);
myList.AddTail(2);
myList.AddTail(3);
// Confirm the current head of the list
ATLASSERT(myList.GetHead() == 1);
// Confirm the current tail of the list
ATLASSERT(myList.GetTail() == 3);
| 23.769231
| 42
| 0.640777
|
bobbrow
|
bd84651ba8b5ecbfee2e5e6f3e067b1cbf25c9a6
| 4,702
|
cc
|
C++
|
code/foundation/core/debug/stringatompagehandler.cc
|
Nechrito/nebula
|
6c7ef27ab1374d3f751d866500729524f72a0c87
|
[
"BSD-2-Clause"
] | null | null | null |
code/foundation/core/debug/stringatompagehandler.cc
|
Nechrito/nebula
|
6c7ef27ab1374d3f751d866500729524f72a0c87
|
[
"BSD-2-Clause"
] | null | null | null |
code/foundation/core/debug/stringatompagehandler.cc
|
Nechrito/nebula
|
6c7ef27ab1374d3f751d866500729524f72a0c87
|
[
"BSD-2-Clause"
] | null | null | null |
//------------------------------------------------------------------------------
// stringatompagehandler.cc
// (C) 2009 Radon Labs GmbH
// (C) 2013-2020 Individual contributors, see AUTHORS file
//------------------------------------------------------------------------------
#include "foundation/stdneb.h"
#include "core/debug/stringatompagehandler.h"
#include "http/html/htmlpagewriter.h"
#include "util/globalstringatomtable.h"
#include "math/scalar.h"
namespace Debug
{
__ImplementClass(Debug::StringAtomPageHandler, 'SAPH', Http::HttpRequestHandler);
using namespace IO;
using namespace Http;
using namespace Util;
using namespace Math;
//------------------------------------------------------------------------------
/**
*/
StringAtomPageHandler::StringAtomPageHandler()
{
this->SetName("StringAtoms");
this->SetDesc("show debug information about StringAtom system");
this->SetRootLocation("stringatom");
}
//------------------------------------------------------------------------------
/**
*/
void
StringAtomPageHandler::HandleRequest(const Ptr<HttpRequest>& request)
{
n_assert(HttpMethod::Get == request->GetMethod());
Dictionary<String,String> query = request->GetURI().ParseQuery();
// configure a HTML page writer
Ptr<HtmlPageWriter> htmlWriter = HtmlPageWriter::Create();
htmlWriter->SetStream(request->GetResponseContentStream());
htmlWriter->SetTitle("Nebula StringAtom Info");
if (htmlWriter->Open())
{
htmlWriter->Element(HtmlElement::Heading1, "StringAtom System");
htmlWriter->AddAttr("href", "/index.html");
htmlWriter->Element(HtmlElement::Anchor, "Home");
// get the current string atom table content, and overall string size
GlobalStringAtomTable::DebugInfo debugInfo = GlobalStringAtomTable::Instance()->GetDebugInfo();
htmlWriter->Element(HtmlElement::Heading3, "String Atom Table Info:");
htmlWriter->Begin(HtmlElement::Table);
htmlWriter->TableRow2("Number of strings: ", String::FromSize(debugInfo.strings.Size()));
htmlWriter->TableRow2("Chunk Size: ", String::FromSize(debugInfo.chunkSize));
htmlWriter->TableRow2("Num chunks: ", String::FromSize(debugInfo.numChunks));
htmlWriter->TableRow2("Alloc size: ", String::FromSize(debugInfo.allocSize));
htmlWriter->TableRow2("Used size: ", String::FromSize(debugInfo.usedSize));
htmlWriter->TableRow2("Growth enabled: ", debugInfo.growthEnabled ? "yes" : "no");
htmlWriter->End(HtmlElement::Table);
// dump string atom table
htmlWriter->Element(HtmlElement::Heading3, "String Atom Table Dump:");
const SizeT maxElementsInTable = 100;
IndexT minIndex = 0;
IndexT maxIndex = n_min(debugInfo.strings.Size(), maxElementsInTable);
if (query.Contains("min"))
{
minIndex = n_max(query["min"].AsInt(), 0);
}
if (query.Contains("max"))
{
maxIndex = n_min(query["max"].AsInt(), debugInfo.strings.Size());
}
// write prev/next links
if (minIndex > 0)
{
String str;
str.Format("/stringatom?min=%d&max=%d", minIndex - maxElementsInTable, minIndex);
htmlWriter->AddAttr("href", str);
htmlWriter->Element(HtmlElement::Anchor, "<< prev|");
}
if (maxIndex < debugInfo.strings.Size())
{
String str;
str.Format("/stringatom?min=%d&max=%d", maxIndex, maxIndex + maxElementsInTable);
htmlWriter->AddAttr("href", str);
htmlWriter->Element(HtmlElement::Anchor, "|next >>");
}
htmlWriter->LineBreak();
htmlWriter->AddAttr("border", "1");
htmlWriter->AddAttr("rules", "cols");
htmlWriter->Begin(HtmlElement::Table);
htmlWriter->AddAttr("bgcolor", "lightsteelblue");
htmlWriter->Begin(HtmlElement::TableRow);
htmlWriter->Element(HtmlElement::TableHeader, "Index");
htmlWriter->Element(HtmlElement::TableHeader, "StringAtom");
htmlWriter->End(HtmlElement::TableRow);
IndexT i;
for (i = minIndex; i < maxIndex; i++)
{
htmlWriter->Begin(HtmlElement::TableRow);
htmlWriter->TableRow2(String::FromInt(i), debugInfo.strings[i]);
htmlWriter->End(HtmlElement::TableRow);
}
htmlWriter->End(HtmlElement::Table);
htmlWriter->Close();
request->SetStatus(HttpStatus::OK);
}
else
{
request->SetStatus(HttpStatus::InternalServerError);
}
}
} // namespace Debug
| 39.847458
| 103
| 0.589749
|
Nechrito
|
bd87cd35f1df4fca4c6610ccf11a4fed5769c42d
| 2,092
|
hpp
|
C++
|
modules/cli/src/basic_interactive_terminal.hpp
|
perfkitpp/perfkit
|
19b691c8337b47594ed6be28051b3a5ee31af389
|
[
"MIT"
] | null | null | null |
modules/cli/src/basic_interactive_terminal.hpp
|
perfkitpp/perfkit
|
19b691c8337b47594ed6be28051b3a5ee31af389
|
[
"MIT"
] | 6
|
2021-10-14T15:38:06.000Z
|
2022-01-08T12:55:04.000Z
|
modules/cli/src/basic_interactive_terminal.hpp
|
perfkitpp/perfkit
|
19b691c8337b47594ed6be28051b3a5ee31af389
|
[
"MIT"
] | null | null | null |
// MIT License
//
// Copyright (c) 2021-2022. Seungwoo Kang
//
// 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.
//
// project home: https://github.com/perfkitpp
//
// Created by Seungwoo on 2021-09-25.
//
#pragma once
#include <future>
#include <list>
#include "cpph/circular_queue.hxx"
#include "perfkit/detail/commands.hpp"
#include "perfkit/terminal.h"
namespace perfkit {
class basic_interactive_terminal : public if_terminal
{
public:
basic_interactive_terminal();
public:
std::optional<std::string> fetch_command(milliseconds timeout) override;
void write(std::string_view str) override;
void push_command(std::string_view command) override;
private:
void _register_autocomplete();
void _unregister_autocomplete();
private:
std::shared_ptr<spdlog::sinks::sink> _sink;
std::future<std::string> _cmd;
circular_queue<std::string> _cmd_history{16};
size_t _cmd_counter = 0;
std::mutex _cmd_queue_lock;
std::list<std::string> _cmd_queued;
std::string _prompt = "$ ";
};
} // namespace perfkit
| 32.184615
| 81
| 0.738528
|
perfkitpp
|
bd8b9acdaeb02e467ce715a2a11dde531971d344
| 633
|
cpp
|
C++
|
src/Front/GeneralTextEdit/undoredotext.cpp
|
Igisid/Breeks-desktop
|
0dfaa6ea64d1d2912a4aed9e1febb537b9a9eec6
|
[
"Apache-2.0"
] | 10
|
2020-12-20T15:32:20.000Z
|
2021-07-12T18:09:57.000Z
|
src/Front/GeneralTextEdit/undoredotext.cpp
|
Igisid/Breeks-desktop
|
0dfaa6ea64d1d2912a4aed9e1febb537b9a9eec6
|
[
"Apache-2.0"
] | 2
|
2022-01-04T12:51:00.000Z
|
2022-01-04T14:40:19.000Z
|
src/Front/GeneralTextEdit/undoredotext.cpp
|
Igisid/Breeks-desktop
|
0dfaa6ea64d1d2912a4aed9e1febb537b9a9eec6
|
[
"Apache-2.0"
] | 3
|
2020-12-22T02:50:11.000Z
|
2021-02-24T01:58:11.000Z
|
#include "undoredotext.h"
UndoRedoText::UndoRedoText()
{}
//-----UNDO
bool UndoRedoText::isUndoEmpty() {
return undoStack.isEmpty();
}
void UndoRedoText::pushUndoCommand(const commandInfo_t command) {
undoStack.push(command);
}
void UndoRedoText::popUndoCommand(commandInfo_t& command) {
command = undoStack.top();
undoStack.pop();
}
//-----REDO
bool UndoRedoText::isRedoEmpty() {
return redoStack.isEmpty();
}
void UndoRedoText::pushRedoCommand(const commandInfo_t command) {
redoStack.push(command);
}
void UndoRedoText::popRedoCommand(commandInfo_t& command) {
command = redoStack.top();
redoStack.pop();
}
| 19.181818
| 65
| 0.733017
|
Igisid
|
bd8d2151294acd433e4832a4710a1ec9040c6100
| 9,120
|
hpp
|
C++
|
include/codegen/include/System/Xml/TextUtf8RawTextWriter.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 1
|
2021-11-12T09:29:31.000Z
|
2021-11-12T09:29:31.000Z
|
include/codegen/include/System/Xml/TextUtf8RawTextWriter.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | null | null | null |
include/codegen/include/System/Xml/TextUtf8RawTextWriter.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 2
|
2021-10-03T02:14:20.000Z
|
2021-11-12T09:29:36.000Z
|
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:19 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: System.Xml.XmlUtf8RawTextWriter
#include "System/Xml/XmlUtf8RawTextWriter.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::IO
namespace System::IO {
// Forward declaring type: Stream
class Stream;
}
// Forward declaring namespace: System::Xml
namespace System::Xml {
// Forward declaring type: XmlWriterSettings
class XmlWriterSettings;
// Skipping declaration: XmlStandalone because it is already included!
}
// Completed forward declares
// Type namespace: System.Xml
namespace System::Xml {
// Autogenerated type: System.Xml.TextUtf8RawTextWriter
class TextUtf8RawTextWriter : public System::Xml::XmlUtf8RawTextWriter {
public:
// public System.Void .ctor(System.IO.Stream stream, System.Xml.XmlWriterSettings settings)
// Offset: 0x118A808
// Implemented from: System.Xml.XmlUtf8RawTextWriter
// Base method: System.Void XmlUtf8RawTextWriter::.ctor(System.IO.Stream stream, System.Xml.XmlWriterSettings settings)
static TextUtf8RawTextWriter* New_ctor(System::IO::Stream* stream, System::Xml::XmlWriterSettings* settings);
// override System.Void WriteXmlDeclaration(System.Xml.XmlStandalone standalone)
// Offset: 0x118A80C
// Implemented from: System.Xml.XmlUtf8RawTextWriter
// Base method: System.Void XmlUtf8RawTextWriter::WriteXmlDeclaration(System.Xml.XmlStandalone standalone)
void WriteXmlDeclaration(System::Xml::XmlStandalone standalone);
// override System.Void WriteXmlDeclaration(System.String xmldecl)
// Offset: 0x118A810
// Implemented from: System.Xml.XmlUtf8RawTextWriter
// Base method: System.Void XmlUtf8RawTextWriter::WriteXmlDeclaration(System.String xmldecl)
void WriteXmlDeclaration(::Il2CppString* xmldecl);
// public override System.Void WriteDocType(System.String name, System.String pubid, System.String sysid, System.String subset)
// Offset: 0x118A814
// Implemented from: System.Xml.XmlUtf8RawTextWriter
// Base method: System.Void XmlUtf8RawTextWriter::WriteDocType(System.String name, System.String pubid, System.String sysid, System.String subset)
void WriteDocType(::Il2CppString* name, ::Il2CppString* pubid, ::Il2CppString* sysid, ::Il2CppString* subset);
// public override System.Void WriteStartElement(System.String prefix, System.String localName, System.String ns)
// Offset: 0x118A818
// Implemented from: System.Xml.XmlUtf8RawTextWriter
// Base method: System.Void XmlUtf8RawTextWriter::WriteStartElement(System.String prefix, System.String localName, System.String ns)
void WriteStartElement(::Il2CppString* prefix, ::Il2CppString* localName, ::Il2CppString* ns);
// override System.Void WriteEndElement(System.String prefix, System.String localName, System.String ns)
// Offset: 0x118A81C
// Implemented from: System.Xml.XmlUtf8RawTextWriter
// Base method: System.Void XmlUtf8RawTextWriter::WriteEndElement(System.String prefix, System.String localName, System.String ns)
void WriteEndElement(::Il2CppString* prefix, ::Il2CppString* localName, ::Il2CppString* ns);
// override System.Void WriteFullEndElement(System.String prefix, System.String localName, System.String ns)
// Offset: 0x118A820
// Implemented from: System.Xml.XmlUtf8RawTextWriter
// Base method: System.Void XmlUtf8RawTextWriter::WriteFullEndElement(System.String prefix, System.String localName, System.String ns)
void WriteFullEndElement(::Il2CppString* prefix, ::Il2CppString* localName, ::Il2CppString* ns);
// override System.Void StartElementContent()
// Offset: 0x118A824
// Implemented from: System.Xml.XmlUtf8RawTextWriter
// Base method: System.Void XmlUtf8RawTextWriter::StartElementContent()
void StartElementContent();
// public override System.Void WriteStartAttribute(System.String prefix, System.String localName, System.String ns)
// Offset: 0x118A828
// Implemented from: System.Xml.XmlUtf8RawTextWriter
// Base method: System.Void XmlUtf8RawTextWriter::WriteStartAttribute(System.String prefix, System.String localName, System.String ns)
void WriteStartAttribute(::Il2CppString* prefix, ::Il2CppString* localName, ::Il2CppString* ns);
// public override System.Void WriteEndAttribute()
// Offset: 0x118A834
// Implemented from: System.Xml.XmlUtf8RawTextWriter
// Base method: System.Void XmlUtf8RawTextWriter::WriteEndAttribute()
void WriteEndAttribute();
// override System.Void WriteNamespaceDeclaration(System.String prefix, System.String ns)
// Offset: 0x118A83C
// Implemented from: System.Xml.XmlUtf8RawTextWriter
// Base method: System.Void XmlUtf8RawTextWriter::WriteNamespaceDeclaration(System.String prefix, System.String ns)
void WriteNamespaceDeclaration(::Il2CppString* prefix, ::Il2CppString* ns);
// override System.Boolean get_SupportsNamespaceDeclarationInChunks()
// Offset: 0x118A840
// Implemented from: System.Xml.XmlUtf8RawTextWriter
// Base method: System.Boolean XmlUtf8RawTextWriter::get_SupportsNamespaceDeclarationInChunks()
bool get_SupportsNamespaceDeclarationInChunks();
// public override System.Void WriteCData(System.String text)
// Offset: 0x118A848
// Implemented from: System.Xml.XmlUtf8RawTextWriter
// Base method: System.Void XmlUtf8RawTextWriter::WriteCData(System.String text)
void WriteCData(::Il2CppString* text);
// public override System.Void WriteComment(System.String text)
// Offset: 0x118A898
// Implemented from: System.Xml.XmlUtf8RawTextWriter
// Base method: System.Void XmlUtf8RawTextWriter::WriteComment(System.String text)
void WriteComment(::Il2CppString* text);
// public override System.Void WriteProcessingInstruction(System.String name, System.String text)
// Offset: 0x118A89C
// Implemented from: System.Xml.XmlUtf8RawTextWriter
// Base method: System.Void XmlUtf8RawTextWriter::WriteProcessingInstruction(System.String name, System.String text)
void WriteProcessingInstruction(::Il2CppString* name, ::Il2CppString* text);
// public override System.Void WriteEntityRef(System.String name)
// Offset: 0x118A8A0
// Implemented from: System.Xml.XmlUtf8RawTextWriter
// Base method: System.Void XmlUtf8RawTextWriter::WriteEntityRef(System.String name)
void WriteEntityRef(::Il2CppString* name);
// public override System.Void WriteCharEntity(System.Char ch)
// Offset: 0x118A8A4
// Implemented from: System.Xml.XmlUtf8RawTextWriter
// Base method: System.Void XmlUtf8RawTextWriter::WriteCharEntity(System.Char ch)
void WriteCharEntity(::Il2CppChar ch);
// public override System.Void WriteSurrogateCharEntity(System.Char lowChar, System.Char highChar)
// Offset: 0x118A8A8
// Implemented from: System.Xml.XmlUtf8RawTextWriter
// Base method: System.Void XmlUtf8RawTextWriter::WriteSurrogateCharEntity(System.Char lowChar, System.Char highChar)
void WriteSurrogateCharEntity(::Il2CppChar lowChar, ::Il2CppChar highChar);
// public override System.Void WriteWhitespace(System.String ws)
// Offset: 0x118A8AC
// Implemented from: System.Xml.XmlUtf8RawTextWriter
// Base method: System.Void XmlUtf8RawTextWriter::WriteWhitespace(System.String ws)
void WriteWhitespace(::Il2CppString* ws);
// public override System.Void WriteString(System.String textBlock)
// Offset: 0x118A8BC
// Implemented from: System.Xml.XmlUtf8RawTextWriter
// Base method: System.Void XmlUtf8RawTextWriter::WriteString(System.String textBlock)
void WriteString(::Il2CppString* textBlock);
// public override System.Void WriteChars(System.Char[] buffer, System.Int32 index, System.Int32 count)
// Offset: 0x118A8CC
// Implemented from: System.Xml.XmlUtf8RawTextWriter
// Base method: System.Void XmlUtf8RawTextWriter::WriteChars(System.Char[] buffer, System.Int32 index, System.Int32 count)
void WriteChars(::Array<::Il2CppChar>* buffer, int index, int count);
// public override System.Void WriteRaw(System.Char[] buffer, System.Int32 index, System.Int32 count)
// Offset: 0x118A930
// Implemented from: System.Xml.XmlUtf8RawTextWriter
// Base method: System.Void XmlUtf8RawTextWriter::WriteRaw(System.Char[] buffer, System.Int32 index, System.Int32 count)
void WriteRaw(::Array<::Il2CppChar>* buffer, int index, int count);
// public override System.Void WriteRaw(System.String data)
// Offset: 0x118A940
// Implemented from: System.Xml.XmlUtf8RawTextWriter
// Base method: System.Void XmlUtf8RawTextWriter::WriteRaw(System.String data)
void WriteRaw(::Il2CppString* data);
}; // System.Xml.TextUtf8RawTextWriter
}
DEFINE_IL2CPP_ARG_TYPE(System::Xml::TextUtf8RawTextWriter*, "System.Xml", "TextUtf8RawTextWriter");
#pragma pack(pop)
| 61.208054
| 150
| 0.758114
|
Futuremappermydud
|
bd965819647db2ecc4e60fea3589b06e06c61cd8
| 1,664
|
cpp
|
C++
|
gateway/afm/common/src/GenericSystem.cpp
|
milligan22963/radar
|
d4b053509d1e65b385e9337f3eab7dfc4aae412a
|
[
"MIT"
] | null | null | null |
gateway/afm/common/src/GenericSystem.cpp
|
milligan22963/radar
|
d4b053509d1e65b385e9337f3eab7dfc4aae412a
|
[
"MIT"
] | null | null | null |
gateway/afm/common/src/GenericSystem.cpp
|
milligan22963/radar
|
d4b053509d1e65b385e9337f3eab7dfc4aae412a
|
[
"MIT"
] | null | null | null |
/*--------------------------------------
GenericSystem
Company: AFM Software
Copyright: 2018
--------------------------------------*/
#include <fstream>
#include <string.h>
#include "GenericSystem.h"
namespace afm
{
namespace common
{
static const std::string sc_serialNumberPath = "/sys/class/dmi/id/product_serial";
static const std::string sc_secondarySerialNumberPath = "/sys/class/dmi/id/board_serial";
GenericSystem::GenericSystem()
{
}
GenericSystem::~GenericSystem()
{
}
bool GenericSystem::Initialize()
{
bool success = false;
success = ProcessSerialNumberFile(sc_serialNumberPath);
if (success == false) {
success = ProcessSerialNumberFile(sc_secondarySerialNumberPath);
}
return success;
}
std::string GenericSystem::GetSerialNumber() const
{
return m_serialNumber;
}
bool GenericSystem::ProcessSerialNumberFile(const std::string &fileName)
{
bool success = false;
std::ifstream serialNumberFile;
serialNumberFile.open(fileName, std::ios_base::in);
if (serialNumberFile.is_open() == true) {
char serialNumber[128];
serialNumberFile.getline(serialNumber, 128);
if (strlen(serialNumber) > 0) {
m_serialNumber = serialNumber;
success = true;
}
serialNumberFile.close();
}
return success;
}
}
}
| 25.212121
| 97
| 0.52524
|
milligan22963
|
bd97c9e5bff3eb3a7110af64bb0582e5db5c88af
| 1,922
|
hpp
|
C++
|
Programming Guide/Headers/Siv3D/QR.hpp
|
Reputeless/Siv3D-Reference
|
d58e92885241d11612007fb9187ce0289a7ee9cb
|
[
"MIT"
] | 38
|
2016-01-14T13:51:13.000Z
|
2021-12-29T01:49:30.000Z
|
Programming Guide/Headers/Siv3D/QR.hpp
|
Reputeless/Siv3D-Reference
|
d58e92885241d11612007fb9187ce0289a7ee9cb
|
[
"MIT"
] | null | null | null |
Programming Guide/Headers/Siv3D/QR.hpp
|
Reputeless/Siv3D-Reference
|
d58e92885241d11612007fb9187ce0289a7ee9cb
|
[
"MIT"
] | 16
|
2016-01-15T11:07:51.000Z
|
2021-12-29T01:49:37.000Z
|
//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (C) 2008-2016 Ryo Suzuki
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
# include "Fwd.hpp"
# include "Unspecified.hpp"
# include "String.hpp"
# include "ByteArray.hpp"
# include "Image.hpp"
# include "Quad.hpp"
namespace s3d
{
/// <summary>
/// QR のエンコーディングモード
/// </summary>
enum class QREncodingMode
{
Numeric,
/// <remarks>
/// 0-9, A-Z, $ % * + - . / : と半角スペース
/// 小文字と大文字は区別されない
/// </remarks>
Alnum,
Binary,
Kanji,
Unknown,
};
/// <summary>
/// QR のエラー訂正レベル
/// </summary>
enum class QRECLevel
{
Low,
Medium,
Quartile,
High,
};
struct QRData
{
/// <summary>
/// フレーム画像内のマーカーの領域
/// </summary>
Quad quad;
String text;
ByteArray data;
QREncodingMode mode;
int32 version;
QRECLevel ecLevel;
};
namespace QR
{
Optional<int32> MinimumVersion(const String& string, QREncodingMode mode = QREncodingMode::Binary, QRECLevel ec = QRECLevel::Low);
Optional<int32> MinimumVersion(const void* data, size_t size, QRECLevel ec = QRECLevel::Low);
inline Optional<int32> MinimumVersion(const ByteArray& data, QRECLevel ec = QRECLevel::Low)
{
return MinimumVersion(data.data(), static_cast<size_t>(data.size()), ec);
}
Image Encode(const String& string, QREncodingMode mode = QREncodingMode::Binary, QRECLevel ec = QRECLevel::Low, const Optional<int32>& version = unspecified);
Image Encode(const void* data, size_t size, QRECLevel ec = QRECLevel::Low, const Optional<int32>& version = unspecified);
inline Image Encode(const ByteArray& data, QRECLevel ec = QRECLevel::Low, const Optional<int32>& version = unspecified)
{
return Encode(data.data(), static_cast<size_t>(data.size()), ec, version);
}
bool Decode(const Image& image, QRData& data);
}
}
| 20.020833
| 160
| 0.636837
|
Reputeless
|
bd999c5db004219039245fac4eca68a96f993646
| 844
|
cpp
|
C++
|
Sudogu CLT/models/solver.cpp
|
vijayiyer97/Sudoku-Solver
|
9ac8712108b8c0b70d29919f122023916260b01f
|
[
"MIT"
] | null | null | null |
Sudogu CLT/models/solver.cpp
|
vijayiyer97/Sudoku-Solver
|
9ac8712108b8c0b70d29919f122023916260b01f
|
[
"MIT"
] | null | null | null |
Sudogu CLT/models/solver.cpp
|
vijayiyer97/Sudoku-Solver
|
9ac8712108b8c0b70d29919f122023916260b01f
|
[
"MIT"
] | null | null | null |
//
// solver.cpp
// Sudogu CLT
//
// Created by Vijay Iyer on 12/7/19.
// Copyright © 2019 Bananna Companay. All rights reserved.
//
#include "solver.hpp"
Solver::Solver(Sudoku other): sudoku(other) { }
Solver::Solver(int** const vals, int rows, int cols, int cells): sudoku(vals, rows, cols, cells) { }
Sudoku Solver::convertToSudoku(Solution solution) {
Sudoku solved{ sudoku };
for (auto id: solution) {
solved.setCell(id);
}
return solved;
}
Result Solver::search(int limit) {
Result result{ };
Constraint* constraint = &sudoku;
DLX dlx{ constraint, sudoku.cells };
Solutions solutions = dlx.run(limit);
for (auto solution: solutions) {
Sudoku solved{ convertToSudoku(solution) };
result.solutions.push_back(solved);
++result.size;
}
return result;
}
| 24.114286
| 100
| 0.643365
|
vijayiyer97
|
bd9f3ca33aeab9692f5ce58b6b759a342f2ff9d1
| 14,379
|
cpp
|
C++
|
src/GLFWFramework.cpp
|
PucklaMotzer09/JohnnyEngine
|
b804f6b3ffa7434576caa77fc76fbe6b101565db
|
[
"Zlib"
] | 5
|
2017-10-08T18:14:49.000Z
|
2022-03-19T10:25:24.000Z
|
src/GLFWFramework.cpp
|
PucklaMotzer09/JohnnyEngine
|
b804f6b3ffa7434576caa77fc76fbe6b101565db
|
[
"Zlib"
] | null | null | null |
src/GLFWFramework.cpp
|
PucklaMotzer09/JohnnyEngine
|
b804f6b3ffa7434576caa77fc76fbe6b101565db
|
[
"Zlib"
] | null | null | null |
#ifdef USE_GLFW
#include "../include/GLFWFramework.h"
#include "../include/Settings.h"
#include "../include/MainClass.h"
#include "../include/Texture.h"
#include "../include/ResourceManager.h"
#include "../include/LogManager.h"
#include "../include/Events.h"
namespace Johnny
{
std::string GLFWFramework::errorString = "";
bool GLFWFramework::wasEvent = false;
bool GLFWFramework::polledEvents = false;
std::queue<Event> GLFWFramework::events;
Vector2d GLFWFramework::m_prevMousePos;
bool GLFWFramework::init(FrameworkInitFlags flags)
{
glfwSetErrorCallback(onError);
if (!glfwInit())
return false;
return true;
}
bool GLFWFramework::quit()
{
glfwTerminate();
return true;
}
bool GLFWFramework::initWindow()
{
glfwWindowHint(GLFW_DOUBLEBUFFER, 1);
if (Settings::getb(SettingName::MSAA))
{
glfwWindowHint(GLFW_SAMPLES, Settings::geti(SettingName::MSAA_SAMPLES));
}
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
return true;
}
bool GLFWFramework::initGraphics()
{
if (Settings::getb(SettingName::VSYNC))
{
glfwSwapInterval(-1);
}
return true;
}
bool GLFWFramework::createOpenGLContext()
{
glfwMakeContextCurrent((GLFWwindow*)MainClass::getInstance()->getWindow()->getHandle());
return true;
}
Window* GLFWFramework::createWindow(const std::string& title, unsigned int x, unsigned int y, unsigned int w, unsigned int h, WindowFlags flags)
{
Window* window = nullptr;
GLFWwindow* handle = nullptr;
glfwWindowHint(GLFW_RESIZABLE, flags & FlagsWindow::Resizeable ? GLFW_TRUE : GLFW_FALSE);
glfwWindowHint(GLFW_VISIBLE, flags & FlagsWindow::Shown ? GLFW_TRUE : GLFW_FALSE);
glfwWindowHint(GLFW_DECORATED, flags & FlagsWindow::Borderless ? GLFW_FALSE : GLFW_TRUE);
glfwWindowHint(GLFW_FOCUSED, flags & FlagsWindow::Input_Focus ? GLFW_TRUE : GLFW_FALSE);
handle = glfwCreateWindow(w, h, title.c_str(),(flags & FlagsWindow::Fullscreen) ? glfwGetPrimaryMonitor() : nullptr, nullptr);
if (handle == nullptr)
return nullptr;
window = new Window(handle);
window->setPosition(x, y);
glfwSetKeyCallback(handle, onKey);
glfwSetWindowSizeCallback(handle, onResize);
glfwSetCursorPosCallback(handle,onMouseMove);
glfwSetMouseButtonCallback(handle,onMouseButton);
return window;
}
bool GLFWFramework::swapWindow(Window * window)
{
glfwSwapBuffers((GLFWwindow*)window->getHandle());
return true;
}
bool GLFWFramework::destroyWindow(Window * window)
{
glfwDestroyWindow((GLFWwindow*)window->getHandle());
return false;
}
std::string GLFWFramework::getError()
{
return errorString;
}
bool GLFWFramework::pollEvent()
{
wasEvent = false;
if (!polledEvents)
{
glfwPollEvents();
if (glfwWindowShouldClose((GLFWwindow*)MainClass::getInstance()->getWindow()->getHandle()))
{
Event event;
event.type = EventType::Quit;
events.push(event);
}
polledEvents = true;
}
if (!events.empty())
{
event = events.front();
events.pop();
wasEvent = true;
}
else
{
polledEvents = false;
}
glfwGetCursorPos((GLFWwindow*)MainClass::getInstance()->getWindow()->getHandle(),&m_prevMousePos.x,&m_prevMousePos.y);
return wasEvent;
}
bool GLFWFramework::setWindowTitle(Window * window, const std::string & title)
{
glfwSetWindowTitle((GLFWwindow*)window->getHandle(), title.c_str());
return true;
}
bool GLFWFramework::setWindowResolution(Window * window, const Vector2i & res)
{
glfwSetWindowSize((GLFWwindow*)window->getHandle(), res.width, res.height);
return true;
}
bool GLFWFramework::setWindowPosition(Window * window, const Vector2i & pos)
{
glfwSetWindowPos((GLFWwindow*)window->getHandle(), pos.x, pos.y);
return true;
}
bool GLFWFramework::setWindowFullscreen(Window * window, bool fullscreen, bool desktop)
{
Vector2i monitorRes;
Vector2i pos;
Vector2i res = window->getResolution();
glfwGetWindowPos((GLFWwindow*)window->getHandle(), &pos.x, &pos.y);
const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor());
glfwSetWindowMonitor((GLFWwindow*)window->getHandle(), fullscreen ? glfwGetPrimaryMonitor() : nullptr,fullscreen ? 0 : 150,fullscreen ? 0 : 150,fullscreen ? mode->width : res.width,fullscreen ? mode->height : res.height, mode->refreshRate);
return true;
}
bool GLFWFramework::setWindowBorderless(Window * window, bool borderless)
{
return false;
}
bool GLFWFramework::setWindowIcon(Window * window, Texture * tex, GLenum target, GLenum format, GLenum type)
{
GLubyte* pixels = tex->readPixels(target, format, type);
GLFWimage img;
img.width = tex->getWidth();
img.height = tex->getHeight();
img.pixels = pixels;
glfwSetWindowIcon((GLFWwindow*)window->getHandle(), 1, &img);
delete pixels;
return true;
}
bool GLFWFramework::setWindowIcon(Window * window, TextureData * texdata)
{
GLFWimage img;
img.width = texdata->width;
img.height = texdata->height;
img.pixels = texdata->data;
glfwSetWindowIcon((GLFWwindow*)window->getHandle(), 1, &img);
return true;
}
std::string GLFWFramework::getWindowTitle(Window * window)
{
return "GLFW can't get the title";
}
Vector2i GLFWFramework::getWindowResolution(Window * window)
{
Vector2i res;
glfwGetWindowSize((GLFWwindow*)window->getHandle(), &res.width, &res.height);
return res;
}
Vector2i GLFWFramework::getScreenResolution()
{
const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor());
return Vector2i(mode->width,mode->height);
}
bool GLFWFramework::isWindowFullscreen(Window * window)
{
return glfwGetWindowMonitor((GLFWwindow*)window->getHandle());
}
bool GLFWFramework::isWindowBorderless(Window * window)
{
return glfwGetWindowAttrib((GLFWwindow*)window->getHandle(),GLFW_DECORATED) == GLFW_FALSE;
}
int GLFWFramework::getControllerID(void * handle)
{
return 0;
}
bool GLFWFramework::isSameController(void * handle1, void * handle2)
{
return false;
}
void * GLFWFramework::openController(int id)
{
return nullptr;
}
void GLFWFramework::closeController(void * handle)
{
}
bool GLFWFramework::isAttachedController(void * handle)
{
return false;
}
void GLFWFramework::lockAndHideCursor()
{
glfwSetInputMode((GLFWwindow*)MainClass::getInstance()->getWindow()->getHandle(),GLFW_CURSOR,GLFW_CURSOR_DISABLED);
}
void GLFWFramework::hideCursor()
{
glfwSetInputMode((GLFWwindow*)MainClass::getInstance()->getWindow()->getHandle(),GLFW_CURSOR,GLFW_CURSOR_HIDDEN);
}
void GLFWFramework::showCursor()
{
glfwSetInputMode((GLFWwindow*)MainClass::getInstance()->getWindow()->getHandle(),GLFW_CURSOR,GLFW_CURSOR_NORMAL);
}
bool GLFWFramework::isCursorHidden()
{
return glfwGetInputMode((GLFWwindow*)MainClass::getInstance()->getWindow()->getHandle(),GLFW_CURSOR) != GLFW_CURSOR_NORMAL;
}
void GLFWFramework::onError(int error, const char* description)
{
errorString = description;
//LogManager::error(std::string("An error accoured: ") + to_string(error) + std::string(": ") + std::string(description));
}
void GLFWFramework::onKey(GLFWwindow* window, int key, int scancode, int action, int mods)
{
Event e;
e.type = action == GLFW_PRESS ? EventType::KeyDown : (action == GLFW_RELEASE ? EventType::KeyUp : EventType::Undefined);
e.key.type = action == GLFW_PRESS ? EventType::KeyDown : (action == GLFW_RELEASE ? EventType::KeyUp : EventType::Undefined);
e.key.state = action == GLFW_PRESS ? 1 : (action == GLFW_RELEASE ? 0 : 2);
e.key.windowID = 0;
e.key.repeat = action == GLFW_REPEAT ? 1 : 0;
e.key.key = toJohnnyKeys(key);
events.push(e);
wasEvent = true;
}
void GLFWFramework::onResize(GLFWwindow * window, int width, int height)
{
MainClass::getInstance()->onResize(width, height);
}
void GLFWFramework::onMouseMove(GLFWwindow* window, double xpos, double ypos)
{
Event e;
e.type = EventType::MouseMotion;
e.motion.x = (int)xpos;
e.motion.y = (int)ypos;
e.motion.xrel = (int)(xpos - m_prevMousePos.x);
e.motion.yrel = (int)(ypos - m_prevMousePos.y);
events.push(e);
wasEvent = true;
}
void GLFWFramework::onMouseButton(GLFWwindow* window, int button, int action, int mods)
{
Event e;
e.type = action == GLFW_PRESS ? EventType::MouseButtonDown : (action == GLFW_RELEASE ? EventType::MouseButtonUp : EventType::Undefined);
e.button.button = button == GLFW_MOUSE_BUTTON_LEFT ? Keys::MS_LEFT : (button == GLFW_MOUSE_BUTTON_RIGHT ? Keys::MS_RIGHT : Keys::MS_MIDDLE);
events.push(e);
wasEvent = true;
}
Keys GLFWFramework::toJohnnyKeys(int key)
{
switch (key)
{
case GLFW_KEY_SPACE: return Keys::SPACE;
case GLFW_KEY_APOSTROPHE: return Keys::ASTERISK;
case GLFW_KEY_COMMA: return Keys::COMMA;
case GLFW_KEY_MINUS: return Keys::MINUS;
case GLFW_KEY_PERIOD: return Keys::PERIOD;
case GLFW_KEY_SLASH: return Keys::SLASH;
case GLFW_KEY_0: return Keys::_0;
case GLFW_KEY_1: return Keys::_1;
case GLFW_KEY_2: return Keys::_2;
case GLFW_KEY_3: return Keys::_3;
case GLFW_KEY_4: return Keys::_4;
case GLFW_KEY_5: return Keys::_5;
case GLFW_KEY_6: return Keys::_6;
case GLFW_KEY_7: return Keys::_7;
case GLFW_KEY_8: return Keys::_8;
case GLFW_KEY_9: return Keys::_9;
case GLFW_KEY_SEMICOLON: return Keys::SEMICOLON;
case GLFW_KEY_EQUAL: return Keys::EQUALS;
case GLFW_KEY_A: return Keys::A;
case GLFW_KEY_B: return Keys::B;
case GLFW_KEY_C: return Keys::C;
case GLFW_KEY_D: return Keys::D;
case GLFW_KEY_E: return Keys::E;
case GLFW_KEY_F: return Keys::F;
case GLFW_KEY_G: return Keys::G;
case GLFW_KEY_H: return Keys::H;
case GLFW_KEY_I: return Keys::I;
case GLFW_KEY_J: return Keys::J;
case GLFW_KEY_K: return Keys::K;
case GLFW_KEY_L: return Keys::L;
case GLFW_KEY_M: return Keys::M;
case GLFW_KEY_N: return Keys::N;
case GLFW_KEY_O: return Keys::O;
case GLFW_KEY_P: return Keys::P;
case GLFW_KEY_Q: return Keys::Q;
case GLFW_KEY_R: return Keys::R;
case GLFW_KEY_S: return Keys::S;
case GLFW_KEY_T: return Keys::T;
case GLFW_KEY_U: return Keys::U;
case GLFW_KEY_V: return Keys::V;
case GLFW_KEY_W: return Keys::W;
case GLFW_KEY_X: return Keys::X;
case GLFW_KEY_Y: return Keys::Y;
case GLFW_KEY_Z: return Keys::Z;
case GLFW_KEY_LEFT_BRACKET: return Keys::LEFTBRACKET;
case GLFW_KEY_BACKSLASH: return Keys::BACKSLASH;
case GLFW_KEY_RIGHT_BRACKET: return Keys::RIGHTBRACKET;
case GLFW_KEY_GRAVE_ACCENT: return Keys::BACKQUOTE;
case GLFW_KEY_WORLD_1: return Keys::UNDEFINED;
case GLFW_KEY_WORLD_2: return Keys::UNDEFINED;
case GLFW_KEY_ESCAPE: return Keys::ESCAPE;
case GLFW_KEY_ENTER: return Keys::RETURN;
case GLFW_KEY_TAB: return Keys::TAB;
case GLFW_KEY_BACKSPACE: return Keys::BACKSPACE;
case GLFW_KEY_INSERT: return Keys::INSERT;
case GLFW_KEY_DELETE: return Keys::_DELETE;
case GLFW_KEY_RIGHT: return Keys::RIGHT;
case GLFW_KEY_LEFT: return Keys::LEFT;
case GLFW_KEY_DOWN: return Keys::DOWN;
case GLFW_KEY_UP: return Keys::UP;
case GLFW_KEY_PAGE_UP: return Keys::PAGEUP;
case GLFW_KEY_PAGE_DOWN: return Keys::PAGEDOWN;
case GLFW_KEY_HOME: return Keys::HOME;
case GLFW_KEY_END: return Keys::END;
case GLFW_KEY_CAPS_LOCK: return Keys::CAPSLOCK;
case GLFW_KEY_SCROLL_LOCK: return Keys::SCROLLLOCK;
case GLFW_KEY_NUM_LOCK: return Keys::NUMLOCKCLEAR;
case GLFW_KEY_PRINT_SCREEN: return Keys::PRINTSCREEN;
case GLFW_KEY_PAUSE: return Keys::PAUSE;
case GLFW_KEY_F1: return Keys::F1;
case GLFW_KEY_F2: return Keys::F2;
case GLFW_KEY_F3: return Keys::F3;
case GLFW_KEY_F4: return Keys::F4;
case GLFW_KEY_F5: return Keys::F5;
case GLFW_KEY_F6: return Keys::F6;
case GLFW_KEY_F7: return Keys::F7;
case GLFW_KEY_F8: return Keys::F8;
case GLFW_KEY_F9: return Keys::F9;
case GLFW_KEY_F10: return Keys::F10;
case GLFW_KEY_F11: return Keys::F11;
case GLFW_KEY_F12: return Keys::F12;
case GLFW_KEY_F13: return Keys::F13;
case GLFW_KEY_F14: return Keys::F14;
case GLFW_KEY_F15: return Keys::F15;
case GLFW_KEY_F16: return Keys::F16;
case GLFW_KEY_F17: return Keys::F17;
case GLFW_KEY_F18: return Keys::F18;
case GLFW_KEY_F19: return Keys::F19;
case GLFW_KEY_F20: return Keys::F20;
case GLFW_KEY_F21: return Keys::F21;
case GLFW_KEY_F22: return Keys::F22;
case GLFW_KEY_F23: return Keys::F23;
case GLFW_KEY_F24: return Keys::F24;
case GLFW_KEY_F25: return Keys::UNDEFINED;
case GLFW_KEY_KP_0: return Keys::KP_0;
case GLFW_KEY_KP_1: return Keys::KP_1;
case GLFW_KEY_KP_2: return Keys::KP_2;
case GLFW_KEY_KP_3: return Keys::KP_3;
case GLFW_KEY_KP_4: return Keys::KP_4;
case GLFW_KEY_KP_5: return Keys::KP_5;
case GLFW_KEY_KP_6: return Keys::KP_6;
case GLFW_KEY_KP_7: return Keys::KP_7;
case GLFW_KEY_KP_8: return Keys::KP_8;
case GLFW_KEY_KP_9: return Keys::KP_9;
case GLFW_KEY_KP_DECIMAL: return Keys::KP_DECIMAL;
case GLFW_KEY_KP_DIVIDE: return Keys::KP_DIVIDE;
case GLFW_KEY_KP_MULTIPLY: return Keys::KP_MULTIPLY;
case GLFW_KEY_KP_SUBTRACT: return Keys::KP_MEMSUBTRACT;
case GLFW_KEY_KP_ADD: return Keys::KP_MEMADD;
case GLFW_KEY_KP_ENTER: return Keys::KP_ENTER;
case GLFW_KEY_KP_EQUAL: return Keys::KP_EQUALS;
case GLFW_KEY_LEFT_SHIFT: return Keys::LSHIFT;
case GLFW_KEY_LEFT_CONTROL: return Keys::LCTRL;
case GLFW_KEY_LEFT_ALT: return Keys::LALT;
case GLFW_KEY_LEFT_SUPER: return Keys::UNDEFINED;
case GLFW_KEY_RIGHT_SHIFT: return Keys::RSHIFT;
case GLFW_KEY_RIGHT_CONTROL: return Keys::RCTRL;
case GLFW_KEY_RIGHT_ALT: return Keys::RALT;
case GLFW_KEY_RIGHT_SUPER: return Keys::UNDEFINED;
case GLFW_KEY_MENU: return Keys::MENU;
default: return Keys::UNDEFINED;
}
}
}
#endif
| 33.595794
| 243
| 0.700118
|
PucklaMotzer09
|
bda102ea6fd1449e03f7b725c8405c922d6682aa
| 6,901
|
cc
|
C++
|
tc/autotuner/cuda/autotuner.cc
|
LoopTactics/tc-cim
|
ff5f7140ea355cb95798827b17ebf3a83f3774ea
|
[
"Apache-2.0"
] | 1
|
2021-06-25T08:21:11.000Z
|
2021-06-25T08:21:11.000Z
|
tc/autotuner/cuda/autotuner.cc
|
LoopTactics/tc-cim
|
ff5f7140ea355cb95798827b17ebf3a83f3774ea
|
[
"Apache-2.0"
] | null | null | null |
tc/autotuner/cuda/autotuner.cc
|
LoopTactics/tc-cim
|
ff5f7140ea355cb95798827b17ebf3a83f3774ea
|
[
"Apache-2.0"
] | null | null | null |
/**
* Copyright (c) 2017-present, Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "tc/autotuner/autotuner.h"
#include <atomic>
#include <chrono>
#include <numeric>
#include <thread>
#include <cuda_runtime_api.h>
#include <glog/stl_logging.h>
#include "tc/autotuner/utils.h"
#include "tc/core/compiler.h"
#include "tc/core/cuda/cuda.h"
#include "tc/core/cuda/cuda_mapping_options_cpp_printer.h"
#include "tc/core/cuda/cuda_tc_executor.h"
#include "tc/core/flags.h"
#include "tc/core/polyhedral/cuda/mapping_types.h"
#include "tc/core/scope_guard.h"
#include "tc/core/tensor.h"
#include "tc/core/utils/math.h"
#include "tc/lang/canonicalize.h"
namespace tc {
namespace autotune {
namespace detail {
using CudaTuningHarness = class TuningHarness<tc::CudaBackend>;
template <>
typename CudaBackend::MappingOptionsType makeOptions<CudaBackend>(
const typename CudaBackend::MappingOptionsType& baseMapping,
const CandidateConfiguration& c) {
auto options = baseMapping;
c.configuration.applyToCudaMappingOptions(options);
return options;
}
template <>
TuningConfiguration makeTuningConfiguration<CudaBackend>(
const typename CudaBackend::MappingOptionsType& options,
const TuningConfiguration& configuration) {
TuningConfiguration conf = configuration;
conf.fromCudaMappingOptions(options);
conf.addValidator([](const TuningConfiguration& conf) {
auto b0v = conf.blockParams.dims.at(0).value();
auto b1v = conf.blockParams.dims.at(1).value();
auto b2v = conf.blockParams.dims.at(2).value();
if (b0v <= 0 or b0v > 1024 or b1v <= 0 or b1v > 1024 or b2v <= 0 or
b2v > 64) {
return false;
}
auto blockProduct = [&]() {
switch (conf.blockParams.numberDims.value()) {
case 3:
return b0v * b1v * b2v;
case 2:
return b0v * b1v;
case 1:
return b0v;
default:
TC_CHECK(false) << "Must have (1-3) block dims, got: "
<< conf.blockParams.numberDims.value();
}
return b0v;
}();
if (blockProduct < 32 or blockProduct > 512) {
return false;
}
return true;
});
return conf;
}
// This function is run on a single pre-determined GPU, in a single thread
// It takes the input/output DLTensor objects that reside on that GPU
//
// We pass the bestTimeSoFar as an option to avoid taking locks in this
// function. This trades off a bit of conservativeness for code sanity.
//
// The function returns true if pruning is possible and we can skip poorly
// performing versions early.
template <>
bool skipExecutionOrWarmup<CudaBackend>(
typename CudaBackend::ExecutorType& executor,
const std::vector<const DLTensor*>& outputs,
const std::vector<const DLConstTensor*>& inputs,
Duration bestTimeSoFar) {
// 1. Prune based on the number of threads: if you don't hit at least k warps
// (default k = 8; 256 total threads, controlled by
// FLAGS_tuner_min_launch_total_threads) then it's likely the kernel is not
// performing great.
// This may be completely off but is a good first initial rule of thumb
// for stress-testing autotuning.
auto debugTuner = FLAGS_debug_tuner;
auto minThreads = FLAGS_tuner_min_launch_total_threads;
USING_MAPPING_SHORT_NAMES(BX, BY, BZ, TX, TY, TZ);
auto block = executor.block();
auto nThreads =
TX.mappingSize(block) * TY.mappingSize(block) * TZ.mappingSize(block);
auto grid = executor.grid();
auto nBlocks =
BX.mappingSize(grid) * BY.mappingSize(grid) * BZ.mappingSize(grid);
if (nBlocks * nThreads < minThreads) {
LOG_IF(INFO, debugTuner)
<< "Skip configuration: too few threads " << grid << " / " << block;
return true;
} else {
LOG_IF(INFO, debugTuner)
<< "Run configuration launch bounds blocks: " << grid
<< " and threads: " << block << "\n";
}
// 2. Perform a first run which may have one of 2 behaviors:
// 2.a. return a very slow first execution time, we should stop
// early. This is akin to pruning but in this case we have run once,
// 2.b. return a reasonable execution time, in which case we proceed with
// warmup.
auto timings = executor.profile(inputs, outputs);
// 2.a.
constexpr size_t kCatastrophicPerfFactor = 100;
if (bestTimeSoFar < Duration::max() and
timings.kernelRuntime >= bestTimeSoFar * kCatastrophicPerfFactor) {
return true;
}
// 2.b. during autotuning we don't want to spend too much time executing,
// use a reduced number of iterations for warmup.
constexpr int kReducedWarmupIterations = 2;
for (size_t i = 1; i < kReducedWarmupIterations - 1; ++i) {
executor.profile(inputs, outputs);
}
// 3. After reasonable warmup, look at the performance and prune if
// catastrophically bad.
constexpr int kEarlyPruneFactor = 5;
timings = executor.profile(inputs, outputs);
if (bestTimeSoFar < Duration::max() and
timings.kernelRuntime >= bestTimeSoFar * kEarlyPruneFactor) {
return true;
}
// 4. If we get here then the kernel is good to be benchmarked
return false;
}
template <>
void handleDeviceRuntimeError<CudaBackend>(
size_t device,
typename CudaBackend::MappingOptionsType& options) {
while (cudaGetLastError() != cudaSuccess) {
// In case of errors in the generated, we cannot rely on deviceReset to
// set the device in a clean state. So instead we just pop and discard
// all the errors accumulated on the device until we get to a clean
// state (i.e. cudaSuccess).
}
try {
// Some errors, such as illegal memory access, cannot be recovered from
// without a cudaDeviceReset (i.e. because user protection)
// In those cases we have no choice than to fail hard.
TC_CUDA_RUNTIMEAPI_ENFORCE(cudaDeviceSynchronize());
} catch (const std::exception& e) {
LOG(FATAL) << "[FATAL] cuda error on device " << device << ": " << e.what()
<< "\n"
<< CudaBackend::MappingOptionsAsCpp(options);
}
}
template <>
std::vector<size_t> parseDevices<CudaBackend>(const std::string& devices) {
std::stringstream ss(devices);
size_t device;
std::vector<size_t> res;
while (ss >> device) {
res.push_back(device);
if (ss.peek() == ',') {
ss.ignore();
}
}
return res;
}
} // namespace detail
} // namespace autotune
} // namespace tc
| 34.333333
| 79
| 0.688451
|
LoopTactics
|
bda217b2aa339caf0e76ca3b5deb7dc1e9c7c579
| 599
|
hpp
|
C++
|
include/oglplus/ext/NV_path_rendering/transform_type.hpp
|
Extrunder/oglplus
|
c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791
|
[
"BSL-1.0"
] | 459
|
2016-03-16T04:11:37.000Z
|
2022-03-31T08:05:21.000Z
|
include/oglplus/ext/NV_path_rendering/transform_type.hpp
|
Extrunder/oglplus
|
c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791
|
[
"BSL-1.0"
] | 55
|
2015-01-06T16:42:55.000Z
|
2020-07-09T04:21:41.000Z
|
include/oglplus/ext/NV_path_rendering/transform_type.hpp
|
Extrunder/oglplus
|
c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791
|
[
"BSL-1.0"
] | 57
|
2015-01-07T18:35:49.000Z
|
2022-03-22T05:32:04.000Z
|
/**
* @file oglplus/ext/NV_path_rendering/transform_type.hpp
* @brief Wrapper for the NV_path_rendering transform type enumeration
*
* @author Matus Chochlik
*
* Copyright 2010-2015 Matus Chochlik. 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)
*/
#pragma once
#ifndef OGLPLUS_EXT_NV_PATH_RENDERING_TRANSFORM_TYPE_1203031902_HPP
#define OGLPLUS_EXT_NV_PATH_RENDERING_TRANSFORM_TYPE_1203031902_HPP
#include <oglplus/enums/ext/nv_path_transform_type.hpp>
#endif // include guard
| 31.526316
| 71
| 0.797997
|
Extrunder
|
bda4f27160bd902b6e182fc1fae9e0ce7d37cae6
| 1,231
|
hpp
|
C++
|
include/RawlogHelper.hpp
|
dzunigan/extrinsic_calib
|
aec3747aeb6baecc7bc6202fc0832a113a1bc528
|
[
"BSD-3-Clause"
] | 5
|
2018-10-24T02:14:54.000Z
|
2019-05-11T12:36:01.000Z
|
include/RawlogHelper.hpp
|
dzunigan/extrinsic_calib
|
aec3747aeb6baecc7bc6202fc0832a113a1bc528
|
[
"BSD-3-Clause"
] | null | null | null |
include/RawlogHelper.hpp
|
dzunigan/extrinsic_calib
|
aec3747aeb6baecc7bc6202fc0832a113a1bc528
|
[
"BSD-3-Clause"
] | 1
|
2021-06-30T01:12:49.000Z
|
2021-06-30T01:12:49.000Z
|
//STL
#include <string>
#include <cstddef>
//MRPT
#include <mrpt/obs/CRawlog.h>
#include <mrpt/obs/CObservation3DRangeScan.h>
#include "ObservationPair.hpp"
#include "Parameters.hpp"
class RawlogHelper
{
public:
RawlogHelper(const ParametersPtr ¶ms);
//Retrieves next rawlog observation and updates last_obs accordingly
//Returns true iif rawlog contains a new CObservation3DRangeScan;
// false when no more observation can be retrieved (i.e. hasFinished = true)
bool getNextObservation(mrpt::obs::CObservation3DRangeScanPtr &obs);
//Retrieves next synch observation pair (two CObservation3DRangeScan taken from different sensors and less time difference than dt)
//Returns true iif rawlog contains a new synch observation pair (as defined above)
// false when no more synch observation pair can be retrieved
//Note: assumes rawlog observations are timestamp ordered (taken with rawlog-grabber)
bool getNextPair(ObservationPair &obs2);
bool hasFinished();
int m; //TODO: debug only
protected:
float max_time_diff;
bool verbose;
mrpt::obs::CRawlog rawlog;
std::size_t n;
mrpt::obs::CObservation3DRangeScanPtr last_obs;
};
| 26.191489
| 135
| 0.729488
|
dzunigan
|
bda76d1a1f9905b87ab20e6c5e52e97ff711ac80
| 2,641
|
cpp
|
C++
|
lib/lane/src/Utils/Logger.cpp
|
calhewitt/LANE
|
412c3d465e6a459714f7a4a7ca4de30e571e0220
|
[
"BSD-2-Clause"
] | null | null | null |
lib/lane/src/Utils/Logger.cpp
|
calhewitt/LANE
|
412c3d465e6a459714f7a4a7ca4de30e571e0220
|
[
"BSD-2-Clause"
] | null | null | null |
lib/lane/src/Utils/Logger.cpp
|
calhewitt/LANE
|
412c3d465e6a459714f7a4a7ca4de30e571e0220
|
[
"BSD-2-Clause"
] | null | null | null |
///////////////////////////////////////////////////////////////////////////////
/// \file Logger.cpp
/// \author Hector Stalker <hstalker0@gmail.com>
/// \version 0.1
///
/// \brief A logger class which manages active logging sinks
///
/// \copyright Copyright (c) 2014, Hector Stalker. All rights reserved.
/// This file is under the Simplified (2-clause) BSD license
/// For conditions of distribution and use, see:
/// http://opensource.org/licenses/BSD-2-Clause
/// or read the 'LICENSE.md' file distributed with this code
// TODO: Add positional format string support over the top of the log method
#include <vector>
#include <mutex>
#include <thread>
#include <algorithm>
#include <memory>
#include <string>
#include <sstream>
#include <chrono>
#include <ctime>
#include "Utils/Logger.hpp"
#include "Utils/LoggerSink.hpp"
#include "Utils/Misc.hpp"
namespace lane {
namespace utils {
std::string severityToString(const SeverityLevel level) noexcept {
switch (level) {
case SeverityLevel::Warning:
return "Warning";
break;
case SeverityLevel::Error:
return "Error";
break;
case SeverityLevel::Debug:
return "Debug";
break;
default:
return "Unknown";
break;
}
}
Logger::Logger() = default;
Logger::~Logger() = default;
Logger::Logger(Logger&& other) {
std::lock_guard<std::mutex> lock(sinksMutex_);
std::swap(sinks_, other.sinks_);
}
Logger& Logger::operator=(Logger&& other) {
if (this != &other) {
std::lock_guard<std::mutex> lock(sinksMutex_);
std::swap(sinks_, other.sinks_);
}
return *this;
}
void Logger::removeAllSinks() noexcept {
std::lock_guard<std::mutex> lock(sinksMutex_);
sinks_.clear();
}
void Logger::log(const SeverityLevel level, const std::string& message) {
#ifdef NDEBUG
if (level == SeverityLevel::Debug) {
return;
}
#endif
std::stringstream finalMessage;
// Go through some hoops to get a timestamp
auto now = std::chrono::system_clock::now();
std::stringstream dateTime;
auto timeT = std::chrono::system_clock::to_time_t(now);
dateTime << std::ctime(&timeT);
std::string dateString = dateTime.str().substr(0, dateTime.str().length() - 1);
// Construct the final message to log
finalMessage << severityToString(level) << " -- " << dateString << " | " << message << std::endl;
std::lock_guard<std::mutex> lock(sinksMutex_);
// Write the message to every registered logging sink
for (const auto& sink : sinks_) {
sink->write(finalMessage.str());
}
}
} // utils
} // lane
| 26.41
| 101
| 0.631579
|
calhewitt
|
bda837e821a0b01d2a91b980514d38aa6409547c
| 548
|
inl
|
C++
|
src/nn/Threshold.h.inl
|
rodrigovb96/cpp-torch
|
8ce7edb687b174bd114a96c0758e8379c8c77c1d
|
[
"Apache-2.0"
] | 55
|
2016-10-26T16:10:18.000Z
|
2021-01-26T00:44:35.000Z
|
src/nn/Threshold.h.inl
|
rodrigovb96/cpp-torch
|
8ce7edb687b174bd114a96c0758e8379c8c77c1d
|
[
"Apache-2.0"
] | 10
|
2017-04-17T12:31:54.000Z
|
2018-11-23T10:49:07.000Z
|
src/nn/Threshold.h.inl
|
rodrigovb96/cpp-torch
|
8ce7edb687b174bd114a96c0758e8379c8c77c1d
|
[
"Apache-2.0"
] | 25
|
2016-10-06T13:49:24.000Z
|
2021-05-01T16:36:02.000Z
|
#pragma once
#include "../../include/nn/Threshold.h"
template<typename T, GPUFlag F>
cpptorch::Tensor<T, F> cpptorch::nn::Threshold<T, F>::forward(const cpptorch::Tensor<T, F> &input) const
{
// validate parameters
if (inplace_)
{
asserter(val_ <= threshold_) << "in-place processing requires value (" << val_ << ") not exceed threshold (" << threshold_ << ")";
}
cpptorch::Tensor<T, F> output(true);
cpptorch::th::NN<T, F>::Threshold_updateOutput(input, output, threshold_, val_, inplace_);
return output;
}
| 30.444444
| 138
| 0.64781
|
rodrigovb96
|
bda8984b80a715a7fed3c7300df11872d2c49f33
| 3,638
|
cpp
|
C++
|
scripts/xUps/src/x725button.cpp
|
eswierk/libpanda
|
6540181edcf7df3e4ec1ee530456fff741176257
|
[
"MIT"
] | 11
|
2020-12-02T00:12:25.000Z
|
2022-03-31T07:38:32.000Z
|
scripts/xUps/src/x725button.cpp
|
eswierk/libpanda
|
6540181edcf7df3e4ec1ee530456fff741176257
|
[
"MIT"
] | 29
|
2021-07-15T23:03:38.000Z
|
2021-10-08T22:02:29.000Z
|
scripts/xUps/src/x725button.cpp
|
eswierk/libpanda
|
6540181edcf7df3e4ec1ee530456fff741176257
|
[
"MIT"
] | 7
|
2021-07-15T21:09:23.000Z
|
2022-02-04T04:06:25.000Z
|
/*
Author: Matt Bunting
Copyright (c) 2020 Arizona Board of Regents
All rights reserved.
Permission is hereby granted, without written agreement and without
license or royalty fees, to use, copy, modify, and distribute this
software and its documentation for any purpose, provided that the
above copyright notice and the following two paragraphs appear in
all copies of this software.
IN NO EVENT SHALL THE ARIZONA BOARD OF REGENTS BE LIABLE TO ANY PARTY
FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
THE ARIZONA BOARD OF REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER
IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION
TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "rpigpio.h"
#define X725_SHUTDOWN (4)
#define X725_BUTTON (18)
#define X725_BOOT (17)
#define X728_SHUTDOWN (5)
#define X728_BUTTON (13)
#define X728_BOOT (12)
#define X_BUTTON X728_BUTTON
#define X_SHUTDOWN X728_SHUTDOWN
#define X_BOOT X728_BOOT
int main(int argc, char **argv)
{
fprintf(stderr,"Running %s\n", argv[0]);
int g;
// Set up gpi pointer for direct register access
GpioHandler *gpio = setup_io();
// Switch GPIO 7..11 to output mode
/************************************************************************\
* You are about to change the GPIO settings of your computer. *
* Mess this up and it will stop working! *
* It might be a good idea to 'sync' before running this program *
* so at least you still have your code changes written to the SD-card! *
\************************************************************************/
// Set GPIO pins 7-11 to output
/* for (g=7; g<=11; g++)
{
setOutput( gpio, g );
}
*/
setOutput( gpio, X_BOOT ); // BOOT
setGpio(gpio, 1 << X_BOOT);
setInput( gpio, X_SHUTDOWN); // x725 power button
bool onMode = true;
bool currentlyTimingButton = false;
double totalTime = 0;
double buttonDelayMs = 200;
bool buttonState = 0;
while(1) {
usleep(1000.0 * buttonDelayMs);
buttonState = readButton(gpio, X_SHUTDOWN);
// fprintf(stderr, "Button State: %d\n", buttonState);
if (buttonState) {
if (currentlyTimingButton == false) {
fprintf(stderr,"Button Pressed!\n");
currentlyTimingButton = true;
buttonDelayMs = 20;
}
totalTime += buttonDelayMs;
if (totalTime >= 600) {
totalTime = 0;
fprintf(stderr,"Shutting system down now...\n");
#ifdef POWERCTL
system("poweroff");
exit(0);
#endif
}
} else {
if (currentlyTimingButton == true) {
fprintf(stderr,"Button was released! Time pressed: %0.2f\n", totalTime);
currentlyTimingButton = false;
buttonDelayMs = 200;
if ((totalTime >= 200) && (totalTime <= 600)) {
fprintf(stderr,"System rebooting now...\n");
#ifdef POWERCTL
system("reboot");
exit(0);
#endif
} else {
fprintf(stderr, "Press was too fast, doing nothing...\n");
}
totalTime = 0;
}
}
// Status in HW LEDs:
/* if (onMode) {
if(g <= 11) {
setGpio(gpio, 1<<g++);
} else {
g = 7;
onMode = false;
}
} else {
if(g <= 11) {
clearGpio(gpio, 1<<g++);
} else {
g = 7;
onMode = true;
}
}
*/
}
return 0;
} // main
| 24.917808
| 77
| 0.643211
|
eswierk
|
bda8dc41ab5ab0c7be842bc4dad5b8ca914bf05f
| 3,525
|
cpp
|
C++
|
structured_light-master/point_cloud.cpp
|
1395724712/StructureLight_712
|
ced5d22f4a81c516e2898f2c5bf287be5afe354c
|
[
"MIT"
] | 2
|
2021-12-09T15:07:32.000Z
|
2022-01-21T09:28:14.000Z
|
structured_light-master/point_cloud.cpp
|
1395724712/StructureLight_712
|
ced5d22f4a81c516e2898f2c5bf287be5afe354c
|
[
"MIT"
] | null | null | null |
structured_light-master/point_cloud.cpp
|
1395724712/StructureLight_712
|
ced5d22f4a81c516e2898f2c5bf287be5afe354c
|
[
"MIT"
] | 3
|
2020-07-31T02:55:34.000Z
|
2022-01-21T09:28:10.000Z
|
#include <GL/gl.h>
#include <GL/glut.h>
#include <stdlib.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <cv.h>
#include <highgui.h>
IplImage *frame = 0;
int render_detail = 5;
int height,width,step;
float alpha = 0.8;
float angle = 0.0f;
float phi=0.0f;
float pad=0.0f;
int nwaves = 5;
CvCapture* capture;
void changeSize(int w, int h) {
// Prevent a divide by zero, when window is too short
// (you cant make a window of zero width).
if (h == 0)
h = 1;
float ratio = w * 1.0 / h;
// Use the Projection Matrix
glMatrixMode(GL_PROJECTION);
// Reset Matrix
glLoadIdentity();
// Set the viewport to be the entire window
glViewport(0, 0, w, h);
// Set the correct perspective.
gluPerspective(45.0f, ratio, 1.0f, 100.0f);
// Get Back to the Modelview
glMatrixMode(GL_MODELVIEW);
}
void renderScene(void) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// get new frame from camera
frame = cvQueryFrame(capture);
glLoadIdentity();
gluLookAt( 0.0,0.0,-2.0,
0.0,0.0,0.0,
0.0,1.0,0.0);
// glTranslatef( -0.2,-0.5,0.0);
// glRotatef(angle,1.0f,0.0f,0.0f);
// glTranslatef( 0.2,0.5,0.0);
float x,y,z,w,h,dist;
float centerX = width/2;
float centerY = height/2;
w = 1.0f;
h = height/(float)width;
glRotatef(180.f,0.f,0.f,1.f);
glRotatef(angle,0.f,1.f,0.f);
glTranslatef(-w/2,-h/2,0.f);
uchar * framePtr = (uchar*) frame->imageData;
uchar cr,cb,cg;
z = 0.0f;
// sinwave
float alpha = w/20;
float period = 1.0f/(nwaves);
float omega = 2*M_PI/period;
glPointSize(1.5);
glBegin(GL_POINTS);
for(int i=0;i<height;i+=render_detail)
for(int j=0;j<width;j+=render_detail) {
x = pad+(float)j/width;
y = pad+(float)i/width;
dist = sqrt(pow(x-(w/2),2)+pow(y-(h/2),2));
z = exp(-2*dist)*cos(omega*sqrt(pow(x-(w/2),2)+pow(y-(h/2),2))+phi)*alpha;
if(x==centerX && y == centerY) {
printf("z=%.2f\n",z);
}
cb = (uchar)framePtr[i*step+j*3];
cg = (uchar)framePtr[i*step+j*3+1];
cr = (uchar)framePtr[i*step+j*3+2];
// printf("color = (%d,%d,%d)\n",cr,cg,cb);
glColor4ub(cr,cg,cb,0);
// draw vertex
glVertex3f(x,y,z);
}
glEnd();
angle+=2.f;
phi+=0.5f;
glutSwapBuffers();
}
int main(int argc, char **argv) {
/*if(argc < 2 ) {
printf("Usage: %s <image>\n",argv[0]);
}*/
//frame = cvLoadImage(argv[1],CV_LOAD_IMAGE_COLOR);
/*if(!frame) {
printf("Could not load image %s\n", argv[1]);
exit(0);
}*/
capture = cvCreateCameraCapture(0) ;
frame = cvQueryFrame( capture );
height = frame->height;
width = frame->width;
step = frame->widthStep;
printf("Loading image:\n\twidth:%d\n\theight:%d\n\tchannels:%d\n",width,height,frame->nChannels);
// init GLUT
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_DEPTH|GLUT_DOUBLE|GLUT_RGBA);
glutInitWindowPosition(800,600);
glutInitWindowSize(800,600);
glutCreateWindow("Point Cloud Visualization");
glEnable(GL_POINT_SMOOTH|GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE);
glutDisplayFunc(renderScene);
glutReshapeFunc(changeSize);
glutIdleFunc(renderScene);
glutMainLoop();
return 0;
}
| 21.759259
| 101
| 0.580426
|
1395724712
|
bda9dfc4479715a1c83c76f382bdd60b1a6c8093
| 19,498
|
cpp
|
C++
|
src/test/zealot/zealot_test_fmtstr.cpp
|
sailzeng/zcelib
|
88e14ab436f1b40e8071e15ef6d9fae396efc3b4
|
[
"Apache-2.0"
] | 72
|
2015-01-08T05:01:48.000Z
|
2021-12-28T06:13:03.000Z
|
src/test/zealot/zealot_test_fmtstr.cpp
|
sailzeng/zcelib
|
88e14ab436f1b40e8071e15ef6d9fae396efc3b4
|
[
"Apache-2.0"
] | 4
|
2016-01-18T12:24:59.000Z
|
2019-10-12T07:19:15.000Z
|
src/test/zealot/zealot_test_fmtstr.cpp
|
sailzeng/zcelib
|
88e14ab436f1b40e8071e15ef6d9fae396efc3b4
|
[
"Apache-2.0"
] | 40
|
2015-01-26T06:49:18.000Z
|
2021-07-20T08:11:48.000Z
|
#include "zealot_predefine.h"
int test_foo_snprintf()
{
char out_buffer[1024 + 1];
size_t cur_len = 0;
size_t buf_max_len = 1024;
zce::foo_snprintf(out_buffer, buf_max_len, cur_len, "int_data=## bool_data=## Haha!\n");
printf("%s", out_buffer);
int int_data = 123456;
bool bool_data = false;
zce::foo_snprintf(out_buffer, buf_max_len, cur_len, "int_data=%? bool_data=%? Haha!\n", int_data, bool_data);
printf("%s", out_buffer);
zce::foo_snprintf(out_buffer, buf_max_len, cur_len, "int_data=%? bool_data= Haha!\n", int_data, bool_data);
printf("%s", out_buffer);
zce::foo_snprintf(out_buffer, 10, cur_len, "int_data=%? bool_data= %? Haha!\n", int_data, bool_data);
std::cout << (out_buffer) << std::endl;
zce::foo_snprintf(out_buffer, 15, cur_len, "int_data=%? bool_data= %? Haha!\n", int_data, bool_data);
std::cout << (out_buffer) << std::endl;
zce::foo_snprintf(out_buffer, 20, cur_len, "int_data=%? bool_data= %? Haha!\n", int_data, bool_data);
std::cout << (out_buffer) << std::endl;
zce::foo_snprintf(out_buffer, 30, cur_len, "int_data=%? bool_data= %? Haha!\n", int_data, bool_data);
std::cout << (out_buffer) << std::endl;
double double_data = 123456789012.1234f;
zce::foo_snprintf(out_buffer, buf_max_len, cur_len, "int_data=%? bool_data= %? double_data = %?Haha!\n",
int_data,
bool_data,
double_data);
std::cout << (out_buffer) << std::endl;
return 0;
}
int test_printf_int()
{
printf("+-----------------------------------------------------------+\n");
int int_data = 123456;
printf("[%d]\n", -1 * int_data);
printf("[%+d]\n", int_data);
printf("[%25.8u]\n", int_data);
printf("[%+25.8d]\n", int_data);
printf("[%25.8u]\n", int_data);
printf("[%25.0d]\n", int_data);
printf("[%#25.0x]\n", int_data);
printf("[%#025x]\n", int_data);
printf("[%25.8x]\n", int_data);
printf("[%.8d]\n", int_data);
printf("[%.0d]\n", int_data);
printf("+-----------------------------------------------------------+\n");
char out_buffer[1024 + 1];
size_t cur_len = 0;
size_t buf_max_len = 1024;
zce::fmt_int64(out_buffer, buf_max_len, cur_len, int_data, zce::BASE_DECIMAL, 0, size_t(-1));
printf("[%.*s]\n", (int)cur_len, out_buffer);
zce::fmt_int64(out_buffer, buf_max_len, cur_len, int_data, zce::BASE_DECIMAL, 0, size_t(-1), zce::FMT_PLUS);
printf("[%.*s]\n", (int)cur_len, out_buffer);
zce::fmt_int64(out_buffer, buf_max_len, cur_len, int_data, zce::BASE_DECIMAL, 25, 8, zce::FMT_UNSIGNED);
printf("[%.*s]\n", (int)cur_len, out_buffer);
zce::fmt_int64(out_buffer, buf_max_len, cur_len, int_data, zce::BASE_DECIMAL, 25, 8, zce::FMT_PLUS);
printf("[%.*s]\n", (int)cur_len, out_buffer);
zce::fmt_int64(out_buffer, buf_max_len, cur_len, int_data, zce::BASE_DECIMAL, 25, 8, zce::FMT_PLUS | zce::FMT_UNSIGNED);
printf("[%.*s]\n", (int)cur_len, out_buffer);
zce::fmt_int64(out_buffer, buf_max_len, cur_len, int_data, zce::BASE_DECIMAL, 25, 0, zce::FMT_PLUS | zce::FMT_UNSIGNED);
printf("[%.*s]\n", (int)cur_len, out_buffer);
zce::fmt_int64(out_buffer, buf_max_len, cur_len, int_data, zce::BASE_HEXADECIMAL, 25, 0, zce::FMT_PREFIX);
printf("[%.*s]\n", (int)cur_len, out_buffer);
zce::fmt_int64(out_buffer, buf_max_len, cur_len, int_data, zce::BASE_HEXADECIMAL, 25, 0, zce::FMT_PREFIX | zce::FMT_ZERO);
printf("[%.*s]\n", (int)cur_len, out_buffer);
zce::fmt_int64(out_buffer, buf_max_len, cur_len, int_data, zce::BASE_HEXADECIMAL, 25, 8, zce::FMT_ZERO);
printf("[%.*s]\n", (int)cur_len, out_buffer);
zce::fmt_int64(out_buffer, buf_max_len, cur_len, int_data, zce::BASE_DECIMAL, 0, 8, 0);
printf("[%.*s]\n", (int)cur_len, out_buffer);
zce::fmt_int64(out_buffer, buf_max_len, cur_len, int_data, zce::BASE_DECIMAL, 0, 0, 0);
printf("[%.*s]\n", (int)cur_len, out_buffer);
printf("+-----------------------------------------------------------+\n");
return 0;
}
int test_fmt_splice(int /*argc*/, char * /*argv*/[])
{
const size_t BUFFER_LEN = 1023;
size_t use_len = 0;
char buffer[BUFFER_LEN + 1] = {0};
zce::foo_strnsplice(buffer, BUFFER_LEN, use_len, '|', "ABC", "efghi");
std::cout << buffer << std::endl;
double double_data = 123.45678;
std::string str_data = "I love hongkong.";
zce::foo_strnsplice(buffer, BUFFER_LEN, use_len,
' ',
zce::Double_Out_Helper(double_data, 16, 3),
"ABC",
"efghi",
str_data);
std::cout << buffer << std::endl;
return 0;
}
int printf_double()
{
char out_buffer[1024 + 1];
size_t cur_len = 0;
size_t buf_max_len = 1024;
//double test_double = 123456789012.123456789;
double test_double = 123456789012.8;
//fmtfp(out_buffer,&cur_len,buf_max_len,test_double,0,0,0);
out_buffer[cur_len] = '\0';
printf("%s\n", out_buffer);
int dec, sign;
test_double = 1.000000000;
zce::fcvt_r(test_double,
5,
&dec,
&sign,
out_buffer,
1024
);
test_double = 0.000000000;
zce::ecvt_r(
test_double,
5,
&dec,
&sign,
out_buffer,
1024
);
#ifdef ZCE_OS_WINDOWS
_gcvt_s(out_buffer,
1024,
test_double,
5
);
#endif
test_double = 0.000000012345678912;
zce::fcvt_r(
test_double,
10,
&dec,
&sign,
out_buffer,
1024
);
zce::ecvt_r(
test_double,
5,
&dec,
&sign,
out_buffer,
1024
);
#ifdef ZCE_OS_WINDOWS
_gcvt_s(out_buffer,
1024,
test_double,
5
);
#endif
cur_len = 0;
test_double = -1.12345678e+100;
zce::fmt_double(out_buffer,
buf_max_len,
cur_len,
test_double,
10,
5,
0);
zce::fmt_double(out_buffer,
buf_max_len,
cur_len,
test_double,
20,
5,
zce::FMT_EXPONENT | zce::FMT_MINUS);
test_double = 1.0000000;
zce::fmt_double(out_buffer,
buf_max_len,
cur_len,
test_double,
10,
5,
0);
printf ("%s\n", out_buffer);
printf ("%10.5f\n", test_double);
zce::fmt_double(out_buffer,
buf_max_len,
cur_len,
test_double,
20,
5,
zce::FMT_EXPONENT | zce::FMT_LEFT_ALIGN | zce::FMT_UP | zce::FMT_PLUS);
printf ("%s\n", out_buffer);
printf ("%-+20.5E\n", test_double);
printf ("-------------------------------------------------------------\n");
test_double = -0.0000000123456;
zce::fmt_double(out_buffer,
buf_max_len,
cur_len,
test_double,
20,
9,
0);
printf ("%s\n", out_buffer);
printf ("%20.9f\n", test_double);
zce::fmt_double(out_buffer,
buf_max_len,
cur_len,
test_double,
20,
5,
zce::FMT_EXPONENT | zce::FMT_LEFT_ALIGN | zce::FMT_UP | zce::FMT_PLUS);
printf ("%s\n", out_buffer);
printf ("%-+20.5E\n", test_double);
printf ("-------------------------------------------------------------\n");
printf ("-------------------------------------------------------------\n");
return 0;
}
int test_cpp_log_out(int /*argc*/, char * /*argv*/[])
{
ZCE_LogTrace_Plus::instance()->foo_write_logmsg(RS_DEBUG, "my love=%? ", "ABCDEFG");
ZCE_LogTrace_Plus::instance()->foo_write_logmsg(RS_DEBUG, "my love=%? you love=%?", "ABCDEFG", 1234567890);
ZCE_LogTrace_Plus::instance()->foo_write_logmsg(RS_DEBUG, "one love=%? two love= %? three love=%?",
"ABCDEFG",
1.1,
12345);
return 0;
}
char out_buffer[1024 + 1];
size_t cur_len = 0;
size_t buf_max_len = 1024;
const size_t A_TEST_TIMES = 1024 * 1000;
const size_t B_TEST_TIMES = 1024 * 1000;
const size_t STR_TIME_LEN = 256;
char str_time[STR_TIME_LEN];
int int_data = 123456;
bool bool_data = false;
double double_data = 123456789012.1234f;
const char cstr_data[] = "I love you.";
std::string stdstr_data = "You love me.";
int test_out_buffer(int /*argc*/, char * /*argv*/[])
{
const std::string def("You love me.");
zce::String_Out_Helper abc(def);
ZCE_Progress_Timer progress_timer;
progress_timer.restart();
ZCE_TRACE_FILELINE(RS_DEBUG);
for (size_t i = 0; i < A_TEST_TIMES; ++i)
{
zce::foo_snprintf(out_buffer, buf_max_len, cur_len, "int_data=%? bool_data=%? double_data=%? cstr_data=%? stdstr_data=%? Haha!\n",
int_data,
bool_data,
double_data,
cstr_data,
stdstr_data
);
}
progress_timer.end();
std::cout << "out string:[" << out_buffer << "]" << std::endl;
std::cout << "foo_snprintf use " << progress_timer.elapsed_sec() << " sec ." << std::endl;
progress_timer.restart();
for (size_t i = 0; i < A_TEST_TIMES; ++i)
{
zce::foo_snprintf(out_buffer, buf_max_len, cur_len, "int_data=%? bool_data=%? double_data=%? cstr_data=%? stdstr_data=%? Haha!\n",
int_data,
bool_data,
double_data,
cstr_data,
stdstr_data
);
}
progress_timer.end();
std::cout << "out string:[" << out_buffer << "]" << std::endl;
std::cout << "foo_snprintf use " << progress_timer.elapsed_sec() << " sec ." << std::endl;
progress_timer.restart();
for (size_t i = 0; i < A_TEST_TIMES; ++i)
{
snprintf(out_buffer, buf_max_len, "int_data=%d bool_data=%s double_data=%e cstr_data=%s stdstr_data=%s Haha!\n",
int_data,
bool_data ? "TRUE" : "FALSE",
double_data,
cstr_data,
stdstr_data.c_str());
}
progress_timer.end();
std::cout << "out string:[" << out_buffer << "]" << std::endl;
std::cout << "snprintf use " << progress_timer.elapsed_sec() << " sec ." << std::endl;
progress_timer.restart();
std::ostringstream ostr_stream;
for (size_t i = 0; i < A_TEST_TIMES; ++i)
{
ostr_stream.str("");
ostr_stream << "int_data="
<< int_data
<< " bool_data="
<< (bool_data ? "TRUE" : "FALSE")
<< " double_data="
<< double_data
<< " cstr_data="
<< cstr_data
<< " stdstr_data="
<< stdstr_data
<< " Haha!\n";
}
progress_timer.end();
std::cout << "out string:[" << ostr_stream.str() << "]" << std::endl;
std::cout << "ostringstream use " << progress_timer.elapsed_sec() << " sec ." << std::endl;
progress_timer.restart();
for (size_t i = 0; i < A_TEST_TIMES; ++i)
{
zce::foo_snprintf(out_buffer, buf_max_len, cur_len, "int_data=%? bool_data=%? double_data=%? cstr_data=%? stdstr_data=%? Haha!\n",
zce::Int_Out_Helper(int_data, 32, zce::FMT_ZERO, zce::BASE_HEXADECIMAL),
bool_data,
zce::Double_Out_Helper(double_data, 16, 3),
zce::String_Out_Helper(cstr_data, 30),
zce::String_Out_Helper(stdstr_data.c_str(), stdstr_data.length())
);
}
progress_timer.end();
std::cout << "out string:[" << out_buffer << "]" << std::endl;
std::cout << "foo_snprintf format use " << progress_timer.elapsed_sec() << " sec ." << std::endl;
progress_timer.restart();
for (size_t i = 0; i < A_TEST_TIMES; ++i)
{
zce::foo_snprintf(out_buffer, buf_max_len, cur_len, "int_data=%? bool_data=%? double_data=%? cstr_data=%? stdstr_data=%? Haha!\n",
zce::Int_Out_Helper(int_data, 32, zce::FMT_ZERO, zce::BASE_HEXADECIMAL),
bool_data,
zce::Double_Out_Helper(double_data, 16, 3),
zce::String_Out_Helper(cstr_data, 30),
zce::String_Out_Helper(stdstr_data.c_str(), 28)
);
}
progress_timer.end();
std::cout << "out string:[" << out_buffer << "]" << std::endl;
std::cout << "foo_snprintf format use " << progress_timer.elapsed_sec() << " sec ." << std::endl;
progress_timer.restart();
for (size_t i = 0; i < A_TEST_TIMES; ++i)
{
snprintf(out_buffer, buf_max_len, "int_data=%032x bool_data=%s double_data=%16.3f cstr_data=%30s stdstr_data=%28s Haha!\n",
int_data,
bool_data ? "TRUE" : "FALSE",
double_data,
cstr_data,
stdstr_data.c_str());
}
progress_timer.end();
std::cout << "out string:[" << out_buffer << "]" << std::endl;
std::cout << "snprintf format use " << progress_timer.elapsed_sec() << " sec ." << std::endl;
progress_timer.restart();
for (size_t i = 0; i < A_TEST_TIMES; ++i)
{
ostr_stream.str("");
ostr_stream << "int_data="
<< std::setw(32) << std::hex << std::setfill('0')
<< int_data
<< " bool_data="
<< (bool_data ? "TRUE" : "FALSE")
<< " double_data="
<< std::fixed << std::setw(16) << std::setprecision(3) << std::setfill(' ')
<< double_data
<< " cstr_data="
<< std::setw(30)
<< cstr_data
<< " stdstr_data="
<< std::setw(28)
<< stdstr_data
<< " Haha!\n";
}
progress_timer.end();
std::cout << "out string:[" << ostr_stream.str() << "]" << std::endl;
std::cout << "ostringstream format use " << progress_timer.elapsed_sec() << " sec ." << std::endl;
return 0;
}
int test_out_file()
{
ZCE_Progress_Timer progress_timer;
progress_timer.restart();
std::ofstream of_stream_1("FILE_A1.txt", std::ios::trunc | std::ios::ate);
for (size_t i = 0; i < B_TEST_TIMES; ++i)
{
zce::foo_snprintf(out_buffer, buf_max_len, cur_len, "int_data=%? bool_data=%? double_data=%? cstr_data=%? stdstr_data=%? Haha!\n",
int_data,
bool_data,
double_data,
cstr_data,
stdstr_data
);
of_stream_1.write(out_buffer, cur_len);
}
of_stream_1.close();
progress_timer.end();
std::cout << "foo_snprintf with ofstream use " << progress_timer.elapsed_sec() << " sec ." << std::endl;
progress_timer.restart();
FILE *file_p = fopen("FILE_A2.txt", "wb");
for (size_t i = 0; i < B_TEST_TIMES; ++i)
{
fprintf(file_p, "int_data=%d bool_data=%s double_data=%e cstr_data=%s stdstr_data=%s Haha!\n",
int_data,
bool_data ? "TRUE" : "FALSE",
double_data,
cstr_data,
stdstr_data.c_str());
}
fclose(file_p);
progress_timer.end();
std::cout << "fprintf use " << progress_timer.elapsed_sec() << " sec ." << std::endl;
progress_timer.restart();
std::ofstream of_stream("FILE_A3.txt", std::ios::trunc | std::ios::ate);
for (size_t i = 0; i < B_TEST_TIMES; ++i)
{
of_stream << "int_data="
<< int_data
<< " bool_data="
<< (bool_data ? "TRUE" : "FALSE")
<< " double_data="
<< double_data
<< " cstr_data="
<< cstr_data
<< " stdstr_data="
<< stdstr_data
<< " Haha!\n";
}
of_stream.close();
progress_timer.end();
std::cout << "ofstream use " << progress_timer.elapsed_sec() << " sec ." << std::endl;
return 0;
}
int test_out_file_stream()
{
ZCE_Progress_Timer progress_timer;
progress_timer.restart();
std::ofstream of_stream_1("FILE_B1.txt", std::ios::trunc | std::ios::ate);
for (size_t i = 0; i < B_TEST_TIMES; ++i)
{
zce::foo_snprintf(out_buffer, buf_max_len, cur_len, "int_data=%? bool_data=%? double_data=%? cstr_data=%? stdstr_data=%? Haha!\n",
int_data,
bool_data,
double_data,
cstr_data,
stdstr_data
);
of_stream_1.write(out_buffer, cur_len);
}
of_stream_1.close();
progress_timer.end();
std::cout << "foo_snprintf with ofstream use " << progress_timer.elapsed_sec() << " sec ." << std::endl;
progress_timer.restart();
ZCE_HANDLE file_handle = zce::open("FILE_B2.txt", O_CREAT | O_TRUNC | O_RDWR | O_APPEND, S_IWRITE | S_IREAD);
for (size_t i = 0; i < B_TEST_TIMES; ++i)
{
zce::foo_snprintf(out_buffer, buf_max_len, cur_len, "int_data=%? bool_data=%? double_data=%? cstr_data=%? stdstr_data=%? Haha!\n",
int_data,
bool_data,
double_data,
cstr_data,
stdstr_data
);
zce::write(file_handle, out_buffer, cur_len);
}
zce::close(file_handle);
progress_timer.end();
std::cout << "foo_snprintf with zce::write use" << progress_timer.elapsed_sec() << " sec ." << std::endl;
progress_timer.restart();
std::ofstream of_stream_3("FILE_B3.txt", std::ios::trunc | std::ios::ate);
for (size_t i = 0; i < B_TEST_TIMES; ++i)
{
of_stream_3 << "int_data="
<< int_data
<< " bool_data="
<< (bool_data ? "TRUE" : "FALSE")
<< " double_data= "
<< double_data
<< " cstr_data="
<< cstr_data
<< " stdstr_data="
<< stdstr_data
<< " Haha!\n";
}
of_stream_3.close();
progress_timer.end();
std::cout << "ofstream use " << progress_timer.elapsed_sec() << " sec ." << std::endl;
return 0;
}
int test_log_debug(int, char *[])
{
ZCE_BACKTRACE_STACK(RS_DEBUG);
unsigned char dbg_ptr[916];
memset(dbg_ptr, 0x68, 916);
ZCE_TRACE_POINTER_DATA(RS_DEBUG, dbg_ptr, 916);
return 0;
}
| 34.14711
| 138
| 0.509027
|
sailzeng
|
bda9f8327160a932908fda96b2625bbd68a1aec7
| 983
|
cc
|
C++
|
cpp/RemoveNthNodeFromEndOfList.cc
|
speedfirst/leetcode
|
a4d95cf8d75f3cd4d1247ea66efebfb6a848ab51
|
[
"BSD-3-Clause"
] | null | null | null |
cpp/RemoveNthNodeFromEndOfList.cc
|
speedfirst/leetcode
|
a4d95cf8d75f3cd4d1247ea66efebfb6a848ab51
|
[
"BSD-3-Clause"
] | null | null | null |
cpp/RemoveNthNodeFromEndOfList.cc
|
speedfirst/leetcode
|
a4d95cf8d75f3cd4d1247ea66efebfb6a848ab51
|
[
"BSD-3-Clause"
] | null | null | null |
// https://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/
namespace RemoveNthNodeFromEndOfList {
class Solution {
public:
ListNode *removeNthFromEnd(ListNode *head, int n) {
if (head == NULL) {
return NULL;
}
// first loop to the nth node
ListNode * cur = head;
while (cur != NULL && n > 0) {
cur = cur->next;
n--;
}
if (n > 0) {
return NULL;
}
// loop to the end
ListNode dummy(-1);
dummy.next = head;
ListNode * prev = &dummy;
while (cur != NULL) {
cur = cur->next;
prev = prev->next;
}
// remove the node
prev->next = prev->next->next;
return dummy.next;
}
};
}
| 25.868421
| 69
| 0.385554
|
speedfirst
|
bdb572b5b6ef49817023b4d30c695ba93ab12d49
| 2,160
|
cpp
|
C++
|
test/core/test_read_steepest_descent_simulator.cpp
|
yutakasi634/Mjolnir
|
ab7a29a47f994111e8b889311c44487463f02116
|
[
"MIT"
] | 12
|
2017-02-01T08:28:38.000Z
|
2018-08-25T15:47:51.000Z
|
test/core/test_read_steepest_descent_simulator.cpp
|
Mjolnir-MD/Mjolnir
|
043df4080720837042c6b67a5495ecae198bc2b3
|
[
"MIT"
] | 60
|
2019-01-14T08:11:33.000Z
|
2021-07-29T08:26:36.000Z
|
test/core/test_read_steepest_descent_simulator.cpp
|
yutakasi634/Mjolnir
|
ab7a29a47f994111e8b889311c44487463f02116
|
[
"MIT"
] | 8
|
2019-01-13T11:03:31.000Z
|
2021-08-01T11:38:00.000Z
|
#define BOOST_TEST_MODULE "test_read_steepest_descent_simulator"
#ifdef BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#else
#include <boost/test/included/unit_test.hpp>
#endif
#include <test/util/make_empty_input.hpp>
#include <mjolnir/input/read_simulator.hpp>
BOOST_AUTO_TEST_CASE(read_steepest_descent_simulator)
{
mjolnir::LoggerManager::set_default_logger("test_read_steepest_descent_simulator.log");
using real_type = double;
using traits_type = mjolnir::SimulatorTraits<real_type, mjolnir::UnlimitedBoundary>;
auto root = mjolnir::test::make_empty_input();
using namespace toml::literals;
const auto v = u8R"(
type = "SteepestDescent"
precision = "double"
boundary_type = "Unlimited"
delta = 0.1
step_limit = 100
save_step = 10
threshold = 0.0
)"_toml;
root.as_table()["simulator"] = v;
{
const auto sim = mjolnir::read_integrator_type<traits_type>(root, v);
BOOST_TEST(static_cast<bool>(sim));
const auto sdsim = dynamic_cast<
mjolnir::SteepestDescentSimulator<traits_type>*>(sim.get());
BOOST_TEST(static_cast<bool>(sdsim));
sim->initialize();
for(std::size_t i=0; i<99; ++i)
{
BOOST_TEST(sim->step()); // check it can step
}
// at the last (100-th) step, it returns false to stop the simulation.
BOOST_TEST(!sim->step());
sim->finalize();
}
{
const auto sim = mjolnir::read_simulator<traits_type,
mjolnir::VelocityVerletIntegrator<traits_type>>(root, v);
BOOST_TEST(static_cast<bool>(sim));
const auto sdsim = dynamic_cast<
mjolnir::SteepestDescentSimulator<traits_type>*>(sim.get());
BOOST_TEST(static_cast<bool>(sdsim));
sim->initialize();
for(std::size_t i=0; i<99; ++i)
{
BOOST_TEST(sim->step()); // check it can step
}
// at the last (100-th) step, it returns false to stop the simulation.
BOOST_TEST(!sim->step());
sim->finalize();
}
}
| 31.764706
| 91
| 0.618519
|
yutakasi634
|
bdb64ea47a50e3e88ad6f73c4df9ed521282ae2b
| 22,643
|
cpp
|
C++
|
qws/src/network/QUdpSocket_DhClass.cpp
|
keera-studios/hsQt
|
8aa71a585cbec40005354d0ee43bce9794a55a9a
|
[
"BSD-2-Clause"
] | 42
|
2015-02-16T19:29:16.000Z
|
2021-07-25T11:09:03.000Z
|
qws/src/network/QUdpSocket_DhClass.cpp
|
keera-studios/hsQt
|
8aa71a585cbec40005354d0ee43bce9794a55a9a
|
[
"BSD-2-Clause"
] | 1
|
2017-11-23T12:49:25.000Z
|
2017-11-23T12:49:25.000Z
|
qws/src/network/QUdpSocket_DhClass.cpp
|
keera-studios/hsQt
|
8aa71a585cbec40005354d0ee43bce9794a55a9a
|
[
"BSD-2-Clause"
] | 5
|
2015-10-15T21:25:30.000Z
|
2017-11-22T13:18:24.000Z
|
/////////////////////////////////////////////////////////////////////////////
//
// File : QUdpSocket_DhClass.cpp
// Copyright : (c) David Harley 2010
// Project : qtHaskell
// Version : 1.1.4
// Modified : 2010-09-02 17:01:56
//
// Warning : this file is machine generated - do not modify.
//
/////////////////////////////////////////////////////////////////////////////
#include <network/QUdpSocket_DhClass.h>
void DhQUdpSocket::userDefined(int x1) const {
void* ro_ptr;
void* rf_ptr;
if(handlerSetud(x1,(void*&)ro_ptr,(void*&)rf_ptr,0)) (*(void(*)(void*))rf_ptr)(ro_ptr);
}
QVariant* DhQUdpSocket::userDefinedVariant(int x1, QVariant* x2) const {
void* ro_ptr;
void* rf_ptr;
if(handlerSetud(x1,(void*&)ro_ptr,(void*&)rf_ptr,1)) return (QVariant*)(*(void*(*)(void*,void*))rf_ptr)(ro_ptr, (void*)x2);
return NULL
;}
bool DhQUdpSocket::atEnd() const {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(0,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(bool(*)(void*))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr))));
return QAbstractSocket::atEnd();
}
bool DhQUdpSocket::DhatEnd() const {
return QAbstractSocket::atEnd();
}
bool DhQUdpSocket::DvhatEnd() const {
return atEnd();
}
qint64 DhQUdpSocket::bytesAvailable() const {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(1,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(long long int(*)(void*))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr))));
return QAbstractSocket::bytesAvailable();
}
qint64 DhQUdpSocket::DhbytesAvailable() const {
return QAbstractSocket::bytesAvailable();
}
qint64 DhQUdpSocket::DvhbytesAvailable() const {
return bytesAvailable();
}
qint64 DhQUdpSocket::bytesToWrite() const {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(2,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(long long int(*)(void*))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr))));
return QAbstractSocket::bytesToWrite();
}
qint64 DhQUdpSocket::DhbytesToWrite() const {
return QAbstractSocket::bytesToWrite();
}
qint64 DhQUdpSocket::DvhbytesToWrite() const {
return bytesToWrite();
}
bool DhQUdpSocket::canReadLine() const {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(3,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(bool(*)(void*))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr))));
return QAbstractSocket::canReadLine();
}
bool DhQUdpSocket::DhcanReadLine() const {
return QAbstractSocket::canReadLine();
}
bool DhQUdpSocket::DvhcanReadLine() const {
return canReadLine();
}
void DhQUdpSocket::close() {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(4,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(void(*)(void*))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr))));
return QAbstractSocket::close();
}
void DhQUdpSocket::Dhclose() {
return QAbstractSocket::close();
}
void DhQUdpSocket::Dvhclose() {
return close();
}
void DhQUdpSocket::connectToHostImplementation(const QString& x1, quint16 x2) {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(5,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(void(*)(void*,void*,unsigned short))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr))), (void*)(new QString(x1)), (unsigned short)x2);
return QAbstractSocket::connectToHostImplementation(x1, x2);
}
void DhQUdpSocket::DhconnectToHostImplementation(const QString& x1, quint16 x2) {
return QAbstractSocket::connectToHostImplementation(x1, x2);
}
void DhQUdpSocket::DvhconnectToHostImplementation(const QString& x1, quint16 x2) {
return connectToHostImplementation(x1, x2);
}
void DhQUdpSocket::connectToHostImplementation(const QString& x1, quint16 x2, QIODevice::OpenMode x3) {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(6,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(void(*)(void*,void*,unsigned short,long))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr))), (void*)(new QString(x1)), (unsigned short)x2, (long)x3);
return QAbstractSocket::connectToHostImplementation(x1, x2, x3);
}
void DhQUdpSocket::DhconnectToHostImplementation(const QString& x1, quint16 x2, long x3) {
return QAbstractSocket::connectToHostImplementation(x1, x2, (QIODevice::OpenMode)x3);
}
void DhQUdpSocket::DvhconnectToHostImplementation(const QString& x1, quint16 x2, long x3) {
return connectToHostImplementation(x1, x2, (QIODevice::OpenMode)x3);
}
void DhQUdpSocket::disconnectFromHostImplementation() {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(7,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(void(*)(void*))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr))));
return QAbstractSocket::disconnectFromHostImplementation();
}
void DhQUdpSocket::DhdisconnectFromHostImplementation() {
return QAbstractSocket::disconnectFromHostImplementation();
}
void DhQUdpSocket::DvhdisconnectFromHostImplementation() {
return disconnectFromHostImplementation();
}
bool DhQUdpSocket::isSequential() const {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(8,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(bool(*)(void*))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr))));
return QAbstractSocket::isSequential();
}
bool DhQUdpSocket::DhisSequential() const {
return QAbstractSocket::isSequential();
}
bool DhQUdpSocket::DvhisSequential() const {
return isSequential();
}
void DhQUdpSocket::setLocalAddress(const QHostAddress& x1) {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(9,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(void(*)(void*,void*))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr))), (void*)&x1);
return QAbstractSocket::setLocalAddress(x1);
}
void DhQUdpSocket::DhsetLocalAddress(const QHostAddress& x1) {
return QAbstractSocket::setLocalAddress(x1);
}
void DhQUdpSocket::DvhsetLocalAddress(const QHostAddress& x1) {
return setLocalAddress(x1);
}
void DhQUdpSocket::setLocalPort(quint16 x1) {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(10,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(void(*)(void*,unsigned short))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr))), (unsigned short)x1);
return QAbstractSocket::setLocalPort(x1);
}
void DhQUdpSocket::DhsetLocalPort(quint16 x1) {
return QAbstractSocket::setLocalPort(x1);
}
void DhQUdpSocket::DvhsetLocalPort(quint16 x1) {
return setLocalPort(x1);
}
void DhQUdpSocket::setPeerAddress(const QHostAddress& x1) {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(11,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(void(*)(void*,void*))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr))), (void*)&x1);
return QAbstractSocket::setPeerAddress(x1);
}
void DhQUdpSocket::DhsetPeerAddress(const QHostAddress& x1) {
return QAbstractSocket::setPeerAddress(x1);
}
void DhQUdpSocket::DvhsetPeerAddress(const QHostAddress& x1) {
return setPeerAddress(x1);
}
void DhQUdpSocket::setPeerName(const QString& x1) {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(12,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(void(*)(void*,void*))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr))), (void*)(new QString(x1)));
return QAbstractSocket::setPeerName(x1);
}
void DhQUdpSocket::DhsetPeerName(const QString& x1) {
return QAbstractSocket::setPeerName(x1);
}
void DhQUdpSocket::DvhsetPeerName(const QString& x1) {
return setPeerName(x1);
}
void DhQUdpSocket::setPeerPort(quint16 x1) {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(13,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(void(*)(void*,unsigned short))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr))), (unsigned short)x1);
return QAbstractSocket::setPeerPort(x1);
}
void DhQUdpSocket::DhsetPeerPort(quint16 x1) {
return QAbstractSocket::setPeerPort(x1);
}
void DhQUdpSocket::DvhsetPeerPort(quint16 x1) {
return setPeerPort(x1);
}
void DhQUdpSocket::setSocketError(QAbstractSocket::SocketError x1) {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(14,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(void(*)(void*,long))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr))), (long)x1);
return QAbstractSocket::setSocketError(x1);
}
void DhQUdpSocket::DhsetSocketError(long x1) {
return QAbstractSocket::setSocketError((QAbstractSocket::SocketError)x1);
}
void DhQUdpSocket::DvhsetSocketError(long x1) {
return setSocketError((QAbstractSocket::SocketError)x1);
}
void DhQUdpSocket::setSocketState(QAbstractSocket::SocketState x1) {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(15,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(void(*)(void*,long))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr))), (long)x1);
return QAbstractSocket::setSocketState(x1);
}
void DhQUdpSocket::DhsetSocketState(long x1) {
return QAbstractSocket::setSocketState((QAbstractSocket::SocketState)x1);
}
void DhQUdpSocket::DvhsetSocketState(long x1) {
return setSocketState((QAbstractSocket::SocketState)x1);
}
bool DhQUdpSocket::waitForBytesWritten() {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(16,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(bool(*)(void*))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr))));
return QAbstractSocket::waitForBytesWritten();
}
bool DhQUdpSocket::DhwaitForBytesWritten() {
return QAbstractSocket::waitForBytesWritten();
}
bool DhQUdpSocket::DvhwaitForBytesWritten() {
return waitForBytesWritten();
}
bool DhQUdpSocket::waitForBytesWritten(int x1) {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(17,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(bool(*)(void*,int))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr))), x1);
return QAbstractSocket::waitForBytesWritten(x1);
}
bool DhQUdpSocket::DhwaitForBytesWritten(int x1) {
return QAbstractSocket::waitForBytesWritten(x1);
}
bool DhQUdpSocket::DvhwaitForBytesWritten(int x1) {
return waitForBytesWritten(x1);
}
bool DhQUdpSocket::waitForReadyRead() {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(18,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(bool(*)(void*))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr))));
return QAbstractSocket::waitForReadyRead();
}
bool DhQUdpSocket::DhwaitForReadyRead() {
return QAbstractSocket::waitForReadyRead();
}
bool DhQUdpSocket::DvhwaitForReadyRead() {
return waitForReadyRead();
}
bool DhQUdpSocket::waitForReadyRead(int x1) {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(19,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(bool(*)(void*,int))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr))), x1);
return QAbstractSocket::waitForReadyRead(x1);
}
bool DhQUdpSocket::DhwaitForReadyRead(int x1) {
return QAbstractSocket::waitForReadyRead(x1);
}
bool DhQUdpSocket::DvhwaitForReadyRead(int x1) {
return waitForReadyRead(x1);
}
qint64 DhQUdpSocket::writeData(const char* x1, qint64 x2) {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(20,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(long long int(*)(void*,void*,long long int))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr))), (void*)(new QString(x1)), (long long int)x2);
return QAbstractSocket::writeData(x1, x2);
}
qint64 DhQUdpSocket::DhwriteData(const char* x1, qint64 x2) {
return QAbstractSocket::writeData(x1, x2);
}
qint64 DhQUdpSocket::DvhwriteData(const char* x1, qint64 x2) {
return writeData(x1, x2);
}
bool DhQUdpSocket::open(QIODevice::OpenMode x1) {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(21,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(bool(*)(void*,long))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr))), (long)x1);
return QIODevice::open(x1);
}
bool DhQUdpSocket::Dhopen(long x1) {
return QIODevice::open((QIODevice::OpenMode)x1);
}
bool DhQUdpSocket::Dvhopen(long x1) {
return open((QIODevice::OpenMode)x1);
}
qint64 DhQUdpSocket::pos() const {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(22,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(long long int(*)(void*))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr))));
return QIODevice::pos();
}
qint64 DhQUdpSocket::Dhpos() const {
return QIODevice::pos();
}
qint64 DhQUdpSocket::Dvhpos() const {
return pos();
}
bool DhQUdpSocket::reset() {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(23,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(bool(*)(void*))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr))));
return QIODevice::reset();
}
bool DhQUdpSocket::Dhreset() {
return QIODevice::reset();
}
bool DhQUdpSocket::Dvhreset() {
return reset();
}
bool DhQUdpSocket::seek(qint64 x1) {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(24,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(bool(*)(void*,long long int))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr))), (long long int)x1);
return QIODevice::seek(x1);
}
bool DhQUdpSocket::Dhseek(qint64 x1) {
return QIODevice::seek(x1);
}
bool DhQUdpSocket::Dvhseek(qint64 x1) {
return seek(x1);
}
void DhQUdpSocket::setErrorString(const QString& x1) {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(25,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(void(*)(void*,void*))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr))), (void*)(new QString(x1)));
return QIODevice::setErrorString(x1);
}
void DhQUdpSocket::DhsetErrorString(const QString& x1) {
return QIODevice::setErrorString(x1);
}
void DhQUdpSocket::DvhsetErrorString(const QString& x1) {
return setErrorString(x1);
}
void DhQUdpSocket::setOpenMode(QIODevice::OpenMode x1) {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(26,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(void(*)(void*,long))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr))), (long)x1);
return QIODevice::setOpenMode(x1);
}
void DhQUdpSocket::DhsetOpenMode(long x1) {
return QIODevice::setOpenMode((QIODevice::OpenMode)x1);
}
void DhQUdpSocket::DvhsetOpenMode(long x1) {
return setOpenMode((QIODevice::OpenMode)x1);
}
qint64 DhQUdpSocket::size() const {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(27,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(long long int(*)(void*))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr))));
return QIODevice::size();
}
qint64 DhQUdpSocket::Dhsize() const {
return QIODevice::size();
}
qint64 DhQUdpSocket::Dvhsize() const {
return size();
}
void DhQUdpSocket::childEvent(QChildEvent* x1) {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(28,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(void(*)(void*,void*))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr))), (void*)x1);
return QObject::childEvent(x1);
}
void DhQUdpSocket::DhchildEvent(QChildEvent* x1) {
return QObject::childEvent(x1);
}
void DhQUdpSocket::DvhchildEvent(QChildEvent* x1) {
return childEvent(x1);
}
void DhQUdpSocket::connectNotify(const char* x1) {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(29,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(void(*)(void*,void*))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr))), (void*)(new QString(x1)));
return QObject::connectNotify(x1);
}
void DhQUdpSocket::DhconnectNotify(const char* x1) {
return QObject::connectNotify(x1);
}
void DhQUdpSocket::DvhconnectNotify(const char* x1) {
return connectNotify(x1);
}
void DhQUdpSocket::customEvent(QEvent* x1) {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(30,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(void(*)(void*,void*))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr))), (void*)x1);
return QObject::customEvent(x1);
}
void DhQUdpSocket::DhcustomEvent(QEvent* x1) {
return QObject::customEvent(x1);
}
void DhQUdpSocket::DvhcustomEvent(QEvent* x1) {
return customEvent(x1);
}
void DhQUdpSocket::disconnectNotify(const char* x1) {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(31,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(void(*)(void*,void*))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr))), (void*)(new QString(x1)));
return QObject::disconnectNotify(x1);
}
void DhQUdpSocket::DhdisconnectNotify(const char* x1) {
return QObject::disconnectNotify(x1);
}
void DhQUdpSocket::DvhdisconnectNotify(const char* x1) {
return disconnectNotify(x1);
}
bool DhQUdpSocket::event(QEvent* x1) {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(32,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(bool(*)(void*,void*))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr))), (void*)x1);
return QObject::event(x1);
}
bool DhQUdpSocket::Dhevent(QEvent* x1) {
return QObject::event(x1);
}
bool DhQUdpSocket::Dvhevent(QEvent* x1) {
return event(x1);
}
bool DhQUdpSocket::eventFilter(QObject* x1, QEvent* x2) {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(33,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(bool(*)(void*,void*,void*))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr))), (void*)(new QPointer<QObject>((QObject*)x1)), (void*)x2);
return QObject::eventFilter(x1, x2);
}
bool DhQUdpSocket::DheventFilter(QObject* x1, QEvent* x2) {
return QObject::eventFilter(x1, x2);
}
bool DhQUdpSocket::DvheventFilter(QObject* x1, QEvent* x2) {
return eventFilter(x1, x2);
}
int DhQUdpSocket::receivers(const char* x1) const {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(34,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(int(*)(void*,void*))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr))), (void*)(new QString(x1)));
return QObject::receivers(x1);
}
int DhQUdpSocket::Dhreceivers(const char* x1) const {
return QObject::receivers(x1);
}
int DhQUdpSocket::Dvhreceivers(const char* x1) const {
return receivers(x1);
}
QObject* DhQUdpSocket::sender() const {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(35,(void*&)ro_ptr,(void*&)rf_ptr)) {
QObject * tr = *((QPointer<QObject>*)(*(void*(*)(void*))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr)))));
return (QObject*)tr;
}
return QObject::sender();
}
QObject* DhQUdpSocket::Dhsender() const {
return QObject::sender();
}
QObject* DhQUdpSocket::Dvhsender() const {
return sender();
}
void DhQUdpSocket::timerEvent(QTimerEvent* x1) {
void* ro_ptr;
void* rf_ptr;
if(handlerSet(36,(void*&)ro_ptr,(void*&)rf_ptr)) return (*(void(*)(void*,void*))rf_ptr)((void*)(new QPointer<QObject>(*((QPointer<QObject>*)ro_ptr))), (void*)x1);
return QObject::timerEvent(x1);
}
void DhQUdpSocket::DhtimerEvent(QTimerEvent* x1) {
return QObject::timerEvent(x1);
}
void DhQUdpSocket::DvhtimerEvent(QTimerEvent* x1) {
return timerEvent(x1);
}
QHash <QByteArray, int> DhQUdpSocket::initXhHash() {
QHash <QByteArray, int> txh;
txh[QMetaObject::normalizedSignature("(bool)atEnd()")] = 0;
txh[QMetaObject::normalizedSignature("(qint64)bytesAvailable()")] = 1;
txh[QMetaObject::normalizedSignature("(qint64)bytesToWrite()")] = 2;
txh[QMetaObject::normalizedSignature("(bool)canReadLine()")] = 3;
txh[QMetaObject::normalizedSignature("close()")] = 4;
txh[QMetaObject::normalizedSignature("connectToHostImplementation(const QString&,quint16)")] = 5;
txh[QMetaObject::normalizedSignature("connectToHostImplementation(const QString&,quint16,QIODevice::OpenMode)")] = 6;
txh[QMetaObject::normalizedSignature("disconnectFromHostImplementation()")] = 7;
txh[QMetaObject::normalizedSignature("(bool)isSequential()")] = 8;
txh[QMetaObject::normalizedSignature("setLocalAddress(const QHostAddress&)")] = 9;
txh[QMetaObject::normalizedSignature("setLocalPort(quint16)")] = 10;
txh[QMetaObject::normalizedSignature("setPeerAddress(const QHostAddress&)")] = 11;
txh[QMetaObject::normalizedSignature("setPeerName(const QString&)")] = 12;
txh[QMetaObject::normalizedSignature("setPeerPort(quint16)")] = 13;
txh[QMetaObject::normalizedSignature("setSocketError(QAbstractSocket::SocketError)")] = 14;
txh[QMetaObject::normalizedSignature("setSocketState(QAbstractSocket::SocketState)")] = 15;
txh[QMetaObject::normalizedSignature("(bool)waitForBytesWritten()")] = 16;
txh[QMetaObject::normalizedSignature("(bool)waitForBytesWritten(int)")] = 17;
txh[QMetaObject::normalizedSignature("(bool)waitForReadyRead()")] = 18;
txh[QMetaObject::normalizedSignature("(bool)waitForReadyRead(int)")] = 19;
txh[QMetaObject::normalizedSignature("(qint64)writeData(const char*,qint64)")] = 20;
txh[QMetaObject::normalizedSignature("(bool)open(QIODevice::OpenMode)")] = 21;
txh[QMetaObject::normalizedSignature("(qint64)pos()")] = 22;
txh[QMetaObject::normalizedSignature("(bool)reset()")] = 23;
txh[QMetaObject::normalizedSignature("(bool)seek(qint64)")] = 24;
txh[QMetaObject::normalizedSignature("setErrorString(const QString&)")] = 25;
txh[QMetaObject::normalizedSignature("setOpenMode(QIODevice::OpenMode)")] = 26;
txh[QMetaObject::normalizedSignature("(qint64)size()")] = 27;
txh[QMetaObject::normalizedSignature("childEvent(QChildEvent*)")] = 28;
txh[QMetaObject::normalizedSignature("connectNotify(const char*)")] = 29;
txh[QMetaObject::normalizedSignature("customEvent(QEvent*)")] = 30;
txh[QMetaObject::normalizedSignature("disconnectNotify(const char*)")] = 31;
txh[QMetaObject::normalizedSignature("(bool)event(QEvent*)")] = 32;
txh[QMetaObject::normalizedSignature("(bool)eventFilter(QObject*,QEvent*)")] = 33;
txh[QMetaObject::normalizedSignature("(int)receivers(const char*)")] = 34;
txh[QMetaObject::normalizedSignature("(QObject*)sender()")] = 35;
txh[QMetaObject::normalizedSignature("timerEvent(QTimerEvent*)")] = 36;
return txh;
}
QHash <QByteArray, int> DhQUdpSocket::xhHash = DhQUdpSocket::initXhHash();
bool DhQUdpSocket::setDynamicQHandler(void * ro_ptr, char * eventId, void * rf_ptr, void * st_ptr, void * df_ptr) {
QByteArray theHandler = QMetaObject::normalizedSignature(eventId);
if (xhHash.contains(theHandler)) {
int thir = xhHash.value(theHandler);
return isetDynamicQHandler(ro_ptr, thir, rf_ptr, st_ptr, df_ptr);
}
return false;
}
bool DhQUdpSocket::setDynamicQHandlerud(int udtyp, void * ro_ptr, int eventId, void * rf_ptr, void * st_ptr, void * df_ptr) {
if ((udtyp < 0) || (udtyp > 2)) {
return false;
}
return isetDynamicQHandlerud(ro_ptr, eventId, rf_ptr, st_ptr, df_ptr, udtyp);
}
bool DhQUdpSocket::unSetDynamicQHandler(char * eventId) {
QByteArray theHandler = QMetaObject::normalizedSignature(eventId);
if (xhHash.contains(theHandler)) {
int thir = xhHash.value(theHandler);
return iunSetDynamicQHandler(thir);
}
return false;
}
bool DhQUdpSocket::unSetDynamicQHandlerud(int udtyp, int eventId) {
if ((udtyp < 0) || (udtyp > 2)) {
return false;
}
return iunSetDynamicQHandlerud(eventId, udtyp);
}
| 34.203927
| 228
| 0.709932
|
keera-studios
|
bdb7aefa3e950bf166eaedd7820f3081d7444e85
| 340
|
cpp
|
C++
|
src/configuration/is_last.cpp
|
Damdoshi/LibLapin
|
800e0f17ed8f3c47797c48feea4c280bb0e4bdc9
|
[
"BSD-3-Clause"
] | 38
|
2016-07-30T09:35:19.000Z
|
2022-03-04T10:13:48.000Z
|
src/configuration/is_last.cpp
|
Elania-Marvers/LibLapin
|
800e0f17ed8f3c47797c48feea4c280bb0e4bdc9
|
[
"BSD-3-Clause"
] | 15
|
2017-02-12T19:20:52.000Z
|
2021-06-09T09:30:52.000Z
|
src/configuration/is_last.cpp
|
Elania-Marvers/LibLapin
|
800e0f17ed8f3c47797c48feea4c280bb0e4bdc9
|
[
"BSD-3-Clause"
] | 12
|
2016-10-06T09:06:59.000Z
|
2022-03-04T10:14:00.000Z
|
// Jason Brillante "Damdoshi"
// Hanged Bunny Studio 2014-2018
//
// Lapin library
#include "lapin_private.h"
bool bunny_configuration_is_last(t_bunny_configuration *cnf)
{
std::map<std::string, SmallConf*>::iterator it;
SmallConf *conf = (SmallConf*)cnf;
it = conf->father->iterator;
return (++it == conf->father->End());
}
| 21.25
| 62
| 0.691176
|
Damdoshi
|
bdb9221391a7b30f333a66535c58bcde6c7905b3
| 819
|
cpp
|
C++
|
dijkstra.cpp
|
nmdis1999/Templates
|
7c5a9d48581a72a55c73083b865187a81b743c21
|
[
"MIT"
] | null | null | null |
dijkstra.cpp
|
nmdis1999/Templates
|
7c5a9d48581a72a55c73083b865187a81b743c21
|
[
"MIT"
] | null | null | null |
dijkstra.cpp
|
nmdis1999/Templates
|
7c5a9d48581a72a55c73083b865187a81b743c21
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
const int INF = 2147483647;
const int MAX = 5005;
int D[MAX], N; // Keeps minimum distance to each node
vector<pair<int,int>> gr[MAX]; // Adjacency list
void dijkstra()
{
for(int i = 1; i <= N; i++) D[i] = INF;
D[1] = 0;
priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> q;
q.push({0,1});
while(!q.empty())
{
pair<int,int> p = q.top();
q.pop();
int u = p.second, dist = p.first;
if(dist > D[u]) continue;
for(pair<int,int> pr : gr[u])
{
int v = pr.first;
int next_dist = dist + pr.second;
if(next_dist < D[v])
{
D[v] = next_dist;
q.push({next_dist,v});
}
}
}
}
| 22.75
| 81
| 0.483516
|
nmdis1999
|
bdbece02fc48f977abe9e8e4eff1ddcbdfe69d3a
| 7,572
|
cpp
|
C++
|
src/intel_hex.cpp
|
ciguard/p-star
|
0be844f60d02cb67796d364d740d5fc53d8bc24e
|
[
"MIT"
] | null | null | null |
src/intel_hex.cpp
|
ciguard/p-star
|
0be844f60d02cb67796d364d740d5fc53d8bc24e
|
[
"MIT"
] | null | null | null |
src/intel_hex.cpp
|
ciguard/p-star
|
0be844f60d02cb67796d364d740d5fc53d8bc24e
|
[
"MIT"
] | null | null | null |
/* intel_hex.cpp:
* Simple library for reading Intel hex (.ihx or .hex) files.
*/
#include "intel_hex.h"
#include <cassert>
#include <sstream>
#include <iomanip>
#include <algorithm>
#include <typeinfo>
#include <stdexcept>
using namespace IntelHex;
static int hexDigitValue(unsigned char c)
{
if (c >= 'a' && c <= 'f') { return c - 'a' + 10; }
if (c >= 'A' && c <= 'F') { return c - 'A' + 10; }
if (c >= '0' && c <= '9') { return c - '0'; }
return -1;
}
static uint8_t readHexByte(std::istream & s)
{
std::istream::sentry sentry(s, true);
if (sentry)
{
char c1 = 0, c2 = 0;
s.get(c1);
s.get(c2);
if (s.fail())
{
if (s.eof())
{
throw std::runtime_error("Unexpected end of line.");
}
else
{
throw std::runtime_error("Failed to read hex digit.");
}
}
int v1 = hexDigitValue(c1);
int v2 = hexDigitValue(c2);
if (v1 < 0 || v2 < 0)
{
throw std::runtime_error("Invalid hex digit.");
}
return v1 * 16 + v2;
}
return 0;
}
static uint16_t readHexShort(std::istream & s)
{
uint16_t r = readHexByte(s) << 8;
return r + readHexByte(s);
}
// Returns true if the line indicates the HEX file is done.
static void processLine(std::istream & file,
std::vector<IntelHex::Entry> & entries,
uint16_t & addressHigh,
bool & done)
{
std::string lineString;
std::getline(file, lineString);
if (file.fail())
{
if (file.eof())
{
throw std::runtime_error("Unexpected end of file.");
}
else
{
throw std::runtime_error("Failed to read HEX file line.");
}
}
std::istringstream lineStream(lineString);
char start;
lineStream.get(start);
if (start != ':')
{
throw std::runtime_error("Hex line does not start with colon (:).");
}
// Read the indentifying information of the line.
uint8_t byteCount = readHexByte(lineStream);
uint16_t addressLow = readHexShort(lineStream);
uint8_t recordType = readHexByte(lineStream);
// Read the data
std::vector<uint8_t> data(byteCount);
for(uint32_t i = 0; i < byteCount; i++)
{
data[i] = readHexByte(lineStream);
}
// Read the checksum.
uint8_t checksum = readHexByte(lineStream);
// Check the checksum.
uint8_t sum = byteCount + (addressLow & 0xFF) + (addressLow >> 8) + recordType;
for(uint32_t i = 0; i < byteCount; i++)
{
sum += data[i];
}
uint8_t expected_checksum = -sum;
if (checksum != expected_checksum)
{
std::ostringstream message;
message << std::hex << std::uppercase << std::setfill('0') << std::right;
message << "Incorrect checksum, expected \"";
message << std::setw(2) << (unsigned int)expected_checksum;
message << "\".";
throw std::runtime_error(message.str());
}
// Check for extra stuff at the end of the line.
if (lineStream.get() != EOF)
{
throw std::runtime_error("Extra data after checksum.");
}
switch(recordType)
{
default:
throw std::runtime_error("Unrecognized record type.");
case 4: // Extended Linear Address Record (sets high 16 bits)
if (byteCount != 2)
{
throw std::runtime_error("Extended Linear Address record has "
"wrong number of bytes (expected 2).");
}
addressHigh = (data[0] << 8) + data[1];
break;
case 2: // Extended Segment Address Record (basically sets bits 4-20 of the address)
case 5: // Start Linear Address Record (sets a 32-bit address)
throw std::runtime_error("Unimplemented record type.");
case 0: // Data record
{
uint32_t address = addressLow + (addressHigh << 16);
entries.push_back(Entry(address, data));
break;
}
case 3: // Start Segment Address Record (specific to 80x86 processors)
// Ignore this type.
break;
case 1: // End of File record
done = true;
break;
}
}
void IntelHex::Data::readFromFile(std::istream & file,
const char * fileName, uint32_t * lineNumber)
{
// Assume the high 16 bits of the address are zero initially.
uint16_t addressHigh = 0;
assert(fileName != NULL);
uint32_t internalLineNumber = 0;
if (lineNumber == NULL)
{
lineNumber = &internalLineNumber;
}
try
{
while(1)
{
(*lineNumber)++;
bool done = false;
processLine(file, entries, addressHigh, done);
if (done) { break; }
}
}
catch(const std::runtime_error & e)
{
throw std::runtime_error(
std::string(fileName) + ":" +
std::to_string(*lineNumber) + ": " +
std::string(e.what()));
}
}
std::vector<uint8_t> IntelHex::Data::getImage(uint32_t startAddress, uint32_t size) const
{
// Initialize the image to have all bytes set to 0xFF.
std::vector<uint8_t> image(size, 0xFF);
for (const Entry & entry : entries)
{
uint32_t start = std::max(startAddress, entry.address);
uint32_t end = std::min(startAddress + size,
(uint32_t)(entry.address + entry.data.size()));
for(uint32_t a = start; a < end; a++)
{
image[a - startAddress] = entry.data[a - entry.address];
}
}
return image;
}
void IntelHex::Data::setImage(uint32_t startAddress,
std::vector<uint8_t> image, const uint32_t blockSize)
{
const uint32_t endAddress = startAddress + image.size();
// The next address to write to.
uint32_t address = startAddress;
while(address < endAddress)
{
uint32_t entrySize = blockSize;
if (address + entrySize > endAddress)
{
entrySize = endAddress - address;
}
std::vector<uint8_t> data(entrySize);
for (uint32_t i = 0; i < entrySize; i++)
{
data[i] = image[address - startAddress + i];
}
entries.push_back(Entry(address, data));
address += entrySize;
}
}
static void writeHexLine(std::ostream & file, uint8_t recordType,
uint16_t addressLow, const std::vector<uint8_t> & data)
{
assert(data.size() <= 0xFF);
file << ':';
file << std::setw(2) << data.size();
file << std::setw(4) << addressLow;
file << std::setw(2) << (unsigned int)recordType;
uint8_t sum = data.size() + (addressLow >> 8) + addressLow + recordType;
for(uint8_t dataByte : data)
{
file << std::setw(2) << (unsigned int)dataByte;
sum += dataByte;
}
uint8_t checksum = -sum;
file << std::setw(2) << (unsigned int)checksum;
file << std::endl;
}
void IntelHex::Data::writeToFile(std::ostream & file) const
{
uint32_t lastAddress = 0;
file << std::uppercase;
file << std::hex << std::setfill('0') << std::right;
for(const Entry & entry : entries)
{
uint32_t address = entry.address;
if ((address >> 16) != (lastAddress >> 16))
{
// Emit an extended linear address record because the high 16 bits changed.
writeHexLine(file, 4, 0, {(uint8_t)(address >> 24), (uint8_t)(address >> 16)});
}
writeHexLine(file, 0, address & 0xFFFF, entry.data);
lastAddress = address;
}
writeHexLine(file, 1, 0, {}); // End of file.
}
| 26.110345
| 91
| 0.565372
|
ciguard
|
bdc4f6fe98d276f00693320c8e7f891158bc9738
| 277
|
cpp
|
C++
|
vr/vr_rt/src/vr/version.cpp
|
vladium/vrt
|
57394a630c306b7529dbe4574036ea71420d00cf
|
[
"MIT"
] | 4
|
2019-09-09T22:08:40.000Z
|
2021-05-17T13:43:31.000Z
|
vr/vr_rt/src/vr/version.cpp
|
vladium/vrt
|
57394a630c306b7529dbe4574036ea71420d00cf
|
[
"MIT"
] | null | null | null |
vr/vr_rt/src/vr/version.cpp
|
vladium/vrt
|
57394a630c306b7529dbe4574036ea71420d00cf
|
[
"MIT"
] | 1
|
2019-09-09T15:46:20.000Z
|
2019-09-09T15:46:20.000Z
|
#include "vr/version.h"
//----------------------------------------------------------------------------
char const * _ __attribute__((visibility ("internal"))) = "vr_version: " VR_BUILD_VERSION;
//----------------------------------------------------------------------------
| 30.777778
| 90
| 0.303249
|
vladium
|
bdca1028459ae995ab28e4221fead23c7457b109
| 5,353
|
cpp
|
C++
|
Cbc/Cbc/src/CbcGenMessages.cpp
|
fadi-alkhoury/coin-or-cbc-with-cmake
|
b4a216118d8e773b694b44c5f27cd75a251cc2cb
|
[
"MIT"
] | null | null | null |
Cbc/Cbc/src/CbcGenMessages.cpp
|
fadi-alkhoury/coin-or-cbc-with-cmake
|
b4a216118d8e773b694b44c5f27cd75a251cc2cb
|
[
"MIT"
] | null | null | null |
Cbc/Cbc/src/CbcGenMessages.cpp
|
fadi-alkhoury/coin-or-cbc-with-cmake
|
b4a216118d8e773b694b44c5f27cd75a251cc2cb
|
[
"MIT"
] | null | null | null |
/*! \legal
Copyright (C) 2007
Lou Hafer, International Business Machines Corporation and others. All
Rights Reserved.
This code is licensed under the terms of the Eclipse Public License (EPL).
$Id: CbcGenMessages.cpp 2465 2019-01-03 19:26:52Z unxusr $
*/
/*
This file is part of cbc-generic.
*/
#include "CbcGenMessages.hpp"
#include "CbcGenCtlBlk.hpp"
namespace {
char svnid[] = "$Id: CbcGenMessages.cpp 2465 2019-01-03 19:26:52Z unxusr $";
}
/*
Begin file local namespace
*/
namespace {
/*
Message definitions.
The precise form isn't important here, so long as the method that loads them
into a CoinMessages object can come up with values for external ID,
detail level, and format string. The use of an enum to provide an internal ID
for each message is mainly useful with the internationalisation feature. It
makes it easy to slap the same ID on alternate versions of a message.
*/
typedef struct {
CbcGenMsgCode inID;
int exID;
int lvl;
const char *fmt;
} MsgDefn;
static MsgDefn us_en_defns[] = {
// informational (0 -- 2999)
{ CBCGEN_TEST_MSG, 1, 2, "This is the us_en test message, eh." },
{ CBCGEN_NEW_SOLVER, 2, 2, "Solver is now \"%s\"." },
// warning (3000 -- 5999)
// Non-fatal errors (6000 -- 8999)
// Fatal errors (9000 and up)
{ CBCGEN_CONFUSION, 9001, 1, "Internal confusion, line %d." },
{ CBCGEN_DUMMY_END, 999999, 0, "" }
};
/*
We seem to need a dummy CoinMessages object to prevent the compiler from
complaining that CoinMessages::Language is unintialised.
const CoinMessages dummy(0) ;
*/
/*
The author is Canadian, eh. But we'll go with us_en anyways.
*/
const CoinMessages::Language default_language = CoinMessages::us_en;
} /* End file local namespace */
/*!
This function constructs a CoinMessages object filled with a default set of
messages, overlaid with whatever is available for the specified language.
It is used to establish the initial set of messages, and is also called
whenever the language is changed. The latter, because there's no way of
guaranteeing that the message sets for alternate languages will all
replace the same messages. This approach guarantees that the set of
messages is always composed of the default language overlaid with any
messages for an alternate language.
The default for lang is us_en, specified up in CbcGenCtlBlk.hpp. If you want
to change the default language, change the declaration there. That said,
you'll also have to provide the necessary message definitions and augment the
case statements below.
*/
void CbcGenCtlBlk::setMessages(CoinMessages::Language lang)
{
/*
If messages exist, in the correct language, we have nothing more to do.
*/
if (msgs_ && cur_lang_ == lang) {
return;
}
/*
Otherwise, we need to do a wholesale rebuild. Create a new object of the
appropriate size.
*/
CoinMessages *msgs = new CoinMessages(sizeof(us_en_defns) / sizeof(MsgDefn));
msgs->setLanguage(lang);
strcpy(msgs->source_, "CbcG");
/*
Yes, this is gloriously redundant, but it's set up in anticipation of
future extensions.
*/
MsgDefn *msgdefn;
switch (lang) {
case CoinMessages::us_en: {
msgdefn = us_en_defns;
break;
}
default: {
msgdefn = us_en_defns;
break;
}
}
/*
Open a loop to create and load the messages.
*/
while (msgdefn->inID != CBCGEN_DUMMY_END) {
CoinOneMessage msg(msgdefn->exID, msgdefn->lvl, msgdefn->fmt);
msgs->addMessage(msgdefn->inID, msg);
msgdefn++;
}
/*
Now, if the local language differs from the default language, load any
overrides. Again, useless now, but maybe in the future ...
*/
if (lang != cur_lang_) {
switch (lang) {
case CoinMessages::us_en: {
msgdefn = us_en_defns;
break;
}
default: {
msgdefn = us_en_defns;
break;
}
}
while (msgdefn->inID != CBCGEN_DUMMY_END) {
msgs->replaceMessage(msgdefn->inID, msgdefn->fmt);
msgdefn++;
}
}
/*
Each CoinOneMessage has a fixed-length array to hold the message; by default
this is 400 chars. Convert to `compressed' CoinOneMessage objects where the
array is only as large as necessary. Any attempt to replace a message, or the
message text, will automatically trigger a decompress operation before doing
the replacement, but the messages will *not* be automatically recompressed.
*/
msgs->toCompact();
msgs_ = msgs;
return;
}
/*
Replaces the current message handler with the handler supplied as a
parameter. If ourMsgHandler_ is true, the existing handler is destroyed.
*/
void CbcGenCtlBlk::passInMessageHandler(CoinMessageHandler *newMsgHandler)
{
if (msgHandler_ && ourMsgHandler_) {
delete msgHandler_;
}
msgHandler_ = newMsgHandler;
ourMsgHandler_ = false;
return;
}
/*
Start a message. This routine buries the whole business of locating the
message handler and messages, getting the log level right, etc. If, by some
chance, messages are not yet loaded, do so.
*/
CoinMessageHandler &CbcGenCtlBlk::message(CbcGenMsgCode inID)
{
if (!msgs_) {
setMessages();
}
msgHandler_->setLogLevel(logLvl_);
msgHandler_->message(inID, *msgs_);
return (*msgHandler_);
}
/* vi: softtabstop=2 shiftwidth=2 expandtab tabstop=2
*/
| 26.899497
| 83
| 0.69886
|
fadi-alkhoury
|
bdcc3e895626c1d323cdb5457068c885fe86badb
| 4,411
|
cpp
|
C++
|
server/core/TaskManager.cpp
|
hotgloupi/zhttpd
|
0437ac2e34dde89abab26665df9cbee1777f1d44
|
[
"BSD-3-Clause"
] | 2
|
2015-01-29T17:23:23.000Z
|
2015-09-21T17:45:22.000Z
|
server/core/TaskManager.cpp
|
hotgloupi/zhttpd
|
0437ac2e34dde89abab26665df9cbee1777f1d44
|
[
"BSD-3-Clause"
] | null | null | null |
server/core/TaskManager.cpp
|
hotgloupi/zhttpd
|
0437ac2e34dde89abab26665df9cbee1777f1d44
|
[
"BSD-3-Clause"
] | null | null | null |
#include "utils/Timer.hpp"
#include "utils/Logger.hpp"
#include "utils/SmartPtr.hpp"
#include "utils/macros.hpp"
#include "ModuleTask.hpp"
#include "TaskManager.hpp"
#include "ServerState.hpp"
#include "RequestManager.hpp"
#include "SessionManager.hpp"
using namespace zhttpd;
TaskManager::TaskManager() : _thread_pool(4)
{
}
TaskManager::~TaskManager()
{
LOG_INFO("Pending add: " +Logger::toString(this->_pending_add_requests.size()));
LOG_INFO("Pending del: " +Logger::toString(this->_pending_del_requests.size()));
LOG_INFO("Current: " +Logger::toString(this->_requests.size()));
unsigned int attempts = 0;
while (true)
{
api::size_t left_task = 0;
request_set_t::iterator it = this->_requests.begin();
request_set_t::iterator end = this->_requests.end();
for (; it != end; ++it)
{
if ((*it)->isQueued())
left_task++;
}
if (left_task == 0 || attempts > 10)
break ;
else
LOG_INFO("Waiting for " + Logger::toString(left_task) + " tasks left");
++attempts;
Timer::sleep(500);
}
request_set_t::iterator it = this->_requests.begin();
request_set_t::iterator end = this->_requests.end();
for (; it != end; ++it)
RequestManager::getInstance()->endRequest(*it);
}
void TaskManager::notifyEndTask(Request& request)
{
/* ZHTTPD_LOCK(this->_being_processed_mutex);
this->_being_processed.erase(&request);
ZHTTPD_UNLOCK(this->_being_processed_mutex);
*/
request.setQueued(false);
}
void TaskManager::startRequest(Request& request)
{
ZHTTPD_LOCK(this->_pending_add_requests_mutex);
this->_pending_add_requests.insert(&request);
ZHTTPD_UNLOCK(this->_pending_add_requests_mutex);
}
api::size_t TaskManager::_giveWork()
{
request_set_t::iterator it = this->_requests.begin();
request_set_t::iterator end = this->_requests.end();
api::size_t count = 0;
for (; it != end; ++it)
{
Request* request = *it;
if (!request->isQueued())
{
RequestTasks& tasks = request->getRequestTasks();
if (tasks.hasWork())
{
request->setQueued(true);
SmartPtr<ModuleTask> task = request->getRequestTasks().getNextTask();
this->_thread_pool.queueTask(task);
++count;
}
else if (!tasks.hasPendingEvent())
{
if (!tasks.hasError() &&
request->getRequestHeader("Connection") != "close" &&
request->getResponseHeader("Connection") != "close")
{
Socket& s = request->getServerSession().popServerSocket();
SessionManager::getInstance()->handleNewSession(&s, request->getSession().getPort());
}
this->_pending_del_requests.insert(request);
}
}
}
return count;
}
api::size_t TaskManager::_addPendingRequests()
{
ZHTTPD_LOCK(this->_pending_add_requests_mutex);
request_set_t::iterator it = this->_pending_add_requests.begin();
request_set_t::iterator end = this->_pending_add_requests.end();
api::size_t count = this->_pending_add_requests.size();
for (; it != end; ++it)
this->_requests.insert(*it);
this->_pending_add_requests.clear();
ZHTTPD_UNLOCK(this->_pending_add_requests_mutex);
return count;
}
api::size_t TaskManager::_delPendingRequests()
{
request_set_t::iterator it = this->_pending_del_requests.begin();
request_set_t::iterator end = this->_pending_del_requests.end();
api::size_t count = this->_pending_del_requests.size();
for (; it != end; ++it)
{
this->_requests.erase(*it);
RequestManager::getInstance()->endRequest(*it);
}
this->_pending_del_requests.clear();
return count;
}
void TaskManager::run()
{
ServerState* sv = ServerState::getInstance();
bool should_sleep;
LOG_INFO("TaskManager is up");
while (sv->getState() == ServerState::RUNNING)
{
should_sleep = (this->_giveWork() == 0);
should_sleep = (this->_delPendingRequests() == 0) && should_sleep;
should_sleep = (this->_addPendingRequests() == 0) && should_sleep;
if (should_sleep)
Timer::sleep(1);
}
LOG_INFO("TaskManager is down");
}
| 29.804054
| 105
| 0.6146
|
hotgloupi
|
bdd2e937705624ee8a8384a7be827c849f56c84c
| 3,469
|
cpp
|
C++
|
c++/algorithms_&_data_structure/binary_search/main.cpp
|
AAS-WT/Linux
|
994e50439e5ff83858ec33ba2398935df26bcb39
|
[
"MIT"
] | null | null | null |
c++/algorithms_&_data_structure/binary_search/main.cpp
|
AAS-WT/Linux
|
994e50439e5ff83858ec33ba2398935df26bcb39
|
[
"MIT"
] | null | null | null |
c++/algorithms_&_data_structure/binary_search/main.cpp
|
AAS-WT/Linux
|
994e50439e5ff83858ec33ba2398935df26bcb39
|
[
"MIT"
] | null | null | null |
#include <algorithm>
#include <iostream>
void SortingChoice(int *pArray, unsigned int ArraySize);
int *BinarySearch_1(int *pArray, unsigned int ArraySize, int SearchValue);
int BinarySearch_2(int *pArray, unsigned int ArraySize, int SearchValue);
int main(int argc, char *argv[]) {
unsigned int ArraySize;
std::cout << "\r\nSet the size of the array: ";
std::cin >> ArraySize;
int *Array = new int[ArraySize];
std::cout << "\r\nEnter the values of the array elements" << std::endl;
for (auto Iterator = &Array[0]; Iterator != (&Array[0] + ArraySize);
Iterator++) {
std::cin >> *Iterator;
}
SortingChoice(Array, ArraySize);
std::cout << "\r\nSorted array by choice method" << std::endl;
for (auto Iterator = &Array[0]; Iterator != (&Array[0] + ArraySize);
Iterator++) {
std::cout << "" << *Iterator << " ";
}
std::cout << std::endl;
int SearchValue;
std::cout << "\r\nEnter the desired value: ";
std::cin >> SearchValue;
int *SearchMemoryAddress = BinarySearch_1(Array, ArraySize, SearchValue);
if (SearchMemoryAddress != nullptr) {
std::cout << "BinarySearch_1: for number " << SearchValue
<< " memory address " << SearchMemoryAddress << std::endl;
} else {
std::cout << "BinarySearch_1: " << SearchValue
<< " was not found in the list" << std::endl;
}
int SearchIndex = BinarySearch_2(Array, ArraySize, SearchValue);
if (SearchIndex != -1) {
std::cout << "BinarySearch_2: for number " << SearchValue << " index "
<< SearchIndex << std::endl;
} else {
std::cout << "BinarySearch_2: " << SearchValue
<< " was not found in the list" << std::endl;
}
delete[] Array;
return 0;
}
/*!
* @brief The sort method of the choice
*
* @param pArray Pointer to the object
* @param ArraySize Size object
*/
void SortingChoice(int *pArray, unsigned int ArraySize) {
for (auto Iterator = pArray; Iterator != (pArray + ArraySize); Iterator++) {
for (auto It = Iterator; It != (pArray + ArraySize); It++) {
if (*Iterator > *It) {
std::swap(*Iterator, *It);
}
}
}
}
/*!
* @brief The binary search method 1
*
* @param pArray Pointer to the object
* @param ArraySize Size object
* @param SearchValue Search value in massive
* @return Pointer to the search object
*/
int *BinarySearch_1(int *pArray, unsigned int ArraySize, int SearchValue) {
auto FirstIndex = pArray, LastIndex = pArray + ArraySize - 1;
while (FirstIndex <= LastIndex) {
auto AverageIndex = FirstIndex + (LastIndex - FirstIndex) / 2;
if (*AverageIndex == SearchValue)
return AverageIndex;
*AverageIndex > SearchValue ? LastIndex = AverageIndex - 1
: FirstIndex = AverageIndex + 1;
}
return nullptr;
}
/*!
* @brief The binary search method 2
*
* @param pArray Pointer to the object
* @param ArraySize Size object
* @param SearchValue Search value in massive
* @return Index to the search object
*/
int BinarySearch_2(int *pArray, unsigned int ArraySize, int SearchValue) {
int FirstIndex = 0, LastIndex = ArraySize - 1;
while (FirstIndex <= LastIndex) {
auto AverageIndex = (FirstIndex + LastIndex) / 2;
if (pArray[AverageIndex] == SearchValue)
return AverageIndex;
pArray[AverageIndex] > SearchValue ? LastIndex = AverageIndex - 1
: FirstIndex = AverageIndex + 1;
}
return -1;
}
| 33.355769
| 78
| 0.631306
|
AAS-WT
|
bdd50f4b5c287e55900fe6ed10c3da007bbe85da
| 5,480
|
hpp
|
C++
|
misc/debug.hpp
|
prince776/CodeBook
|
874fc7f94011ad1d25a55bcd91fecd2a11eb5a9b
|
[
"CC0-1.0"
] | 17
|
2021-01-25T12:07:17.000Z
|
2022-02-26T17:20:31.000Z
|
misc/debug.hpp
|
NavneelSinghal/CodeBook
|
ff60ace9107dd19ef8ba81e175003f567d2a9070
|
[
"CC0-1.0"
] | null | null | null |
misc/debug.hpp
|
NavneelSinghal/CodeBook
|
ff60ace9107dd19ef8ba81e175003f567d2a9070
|
[
"CC0-1.0"
] | 4
|
2021-02-28T11:13:44.000Z
|
2021-11-20T12:56:20.000Z
|
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>
namespace Debug {
// clang-format off
#define DEBUG_RED "\x1B[0m\x1B[31m"
#define DEBUG_GREEN "\x1B[0m\x1B[32m"
#define DEBUG_YELLOW "\x1B[0m\x1B[33m"
#define DEBUG_BLUE "\x1B[0m\x1B[34m"
#define DEBUG_MAGENTA "\x1B[0m\x1B[35m"
#define DEBUG_CYAN "\x1B[0m\x1B[36m"
#define DEBUG_WHITE "\x1B[0m\x1B[37m"
#define DEBUG_RESET "\x1B[0m"
#define DEBUG_BOLD_GREEN "\x1B[0m\x1B[32;1m"
#define DEBUG_BOLD_YELLOW "\x1B[0m\x1B[33;1m"
#define DEBUG_BOLD_BLUE "\x1B[0m\x1B[34;1m"
#define DEBUG_BOLD_MAGENTA "\x1B[0m\x1B[35;1m"
#define DEBUG_BOLD_CYAN "\x1B[0m\x1B[36;1m"
#define DEBUG_BOLD_WHITE "\x1B[0m\x1B[37;1m"
#define DEBUG_UNDERLINE "\x1B[4m"
#define DEBUG_BODY DEBUG_BOLD_CYAN
#define DEBUG_VAR DEBUG_RED
#define DEBUG_PAREN DEBUG_YELLOW
#define DEBUG_BRAC DEBUG_GREEN
#define DEBUG_COMMA DEBUG_BOLD_MAGENTA
#define DEBUG_CONTENT DEBUG_BODY DEBUG_UNDERLINE
#define DEBUG_LINE DEBUG_BOLD_YELLOW
#define DEBUG_LINENUM DEBUG_BOLD_BLUE
// clang-format on
#define SFINAE(x, ...) \
template <class, class = void> \
struct x : std::false_type {}; \
template <class T> \
struct x<T, std::void_t<__VA_ARGS__>> : std::true_type {}
SFINAE(DefaultIO, decltype(std::cout << std::declval<T &>()));
SFINAE(IsTuple, typename std::tuple_size<T>::type);
SFINAE(Iterable, decltype(std::begin(std::declval<T>())));
template <auto &os>
struct Writer {
static constexpr auto lbrac = DEBUG_BRAC "[";
static constexpr auto rbrac = DEBUG_BRAC "]";
static constexpr auto lparen = DEBUG_PAREN "(";
static constexpr auto rparen = DEBUG_PAREN ")";
static constexpr auto comma = DEBUG_COMMA ", ";
template <class T>
void Impl(T const &t) const {
if constexpr (DefaultIO<T>::value) {
os << DEBUG_CONTENT << t;
} else if constexpr (Iterable<T>::value) {
int i = 0;
os << lbrac;
for (auto &&x : t) ((i++) ? (os << comma, Impl(x)) : Impl(x));
os << rbrac;
} else if constexpr (IsTuple<T>::value) {
os << lparen;
std::apply(
[this](auto const &... args) {
int i = 0;
(((i++) ? (os << comma, Impl(args)) : Impl(args)), ...);
},
t);
os << rparen;
} else
static_assert(IsTuple<T>::value, "No matching type for print");
}
template <class F, class... Ts>
auto &operator()(F const &f, Ts const &... ts) const {
return Impl(f), ((os << comma, Impl(ts)), ...), os << '\n', *this;
}
};
template <auto &is>
struct Reader {
template <class T>
auto &Rd(T &t) const {
if constexpr (DefaultIO<T>::value)
is >> t;
else if constexpr (Iterable<T>::value)
for (auto &x : t) Rd(x);
else if constexpr (IsTuple<T>::value)
std::apply([this](auto &... args) { (Rd(args), ...); }, t);
else
static_assert(IsTuple<T>::value, "No matching type for read");
return *this;
}
template <class T>
auto operator()(T t) const {
Rd(t);
return t;
}
};
#ifdef DEBUG
#define debug(args...) \
{ \
std::string _s = #args; \
std::replace(_s.begin(), _s.end(), ',', ' '); \
std::stringstream _ss(_s); \
std::istream_iterator<std::string> _it(_ss); \
Debug::location_stats(__LINE__); \
Debug::err(_it, args); \
Debug::clear_colours(); \
}
void location_stats(int line) {
std::cerr << DEBUG_LINE << "Line " << DEBUG_LINENUM << line << "\n"
<< DEBUG_RESET;
}
void clear_colours() { std::cerr << DEBUG_RESET; }
void err(std::istream_iterator<std::string> it) { std::ignore = it; }
template <typename T, typename... Args>
void err(std::istream_iterator<std::string> it, T a, Args... args) {
std::cerr << DEBUG_VAR << *it << " = ";
Writer<std::cerr>{}(a);
err(++it, args...);
}
#define ASSERT(...) \
if (not(__VA_ARGS__)) throw runtime_error(#__VA_ARGS__)
#else
#define debug(...) 0
#define ASSERT(...) 0
#endif
#undef DEBUG_RED
#undef DEBUG_GREEN
#undef DEBUG_YELLOW
#undef DEBUG_BLUE
#undef DEBUG_MAGENTA
#undef DEBUG_CYAN
#undef DEBUG_WHITE
#undef DEBUG_RESET
#undef DEBUG_BOLD_GREEN
#undef DEBUG_BOLD_YELLOW
#undef DEBUG_BOLD_BLUE
#undef DEBUG_BOLD_MAGENTA
#undef DEBUG_BOLD_CYAN
#undef DEBUG_BOLD_WHITE
#undef DEBUG_UNDERLINE
#undef DEBUG_BODY
#undef DEBUG_VAR
#undef DEBUG_PAREN
#undef DEBUG_BRAC
#undef DEBUG_COMMA
#undef DEBUG_CONTENT
#undef DEBUG_LINE
#undef DEBUG_LINENUM
} // namespace Debug
| 33.82716
| 80
| 0.535219
|
prince776
|
7524f71ce73d2a2a200f0c1c43754493694e75c6
| 29
|
hpp
|
C++
|
src/boost_vmd_vmd.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 10
|
2018-03-17T00:58:42.000Z
|
2021-07-06T02:48:49.000Z
|
src/boost_vmd_vmd.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 2
|
2021-03-26T15:17:35.000Z
|
2021-05-20T23:55:08.000Z
|
src/boost_vmd_vmd.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 4
|
2019-05-28T21:06:37.000Z
|
2021-07-06T03:06:52.000Z
|
#include <boost/vmd/vmd.hpp>
| 14.5
| 28
| 0.724138
|
miathedev
|
752a49d9ebc8a22b592323e349d672f723d1784b
| 9,389
|
cpp
|
C++
|
ProgramUI.fld/ProgramUI.cpp
|
depaulo/OrganizerCpp
|
9847cb2d117bd493e127fb499bdbf9112cf388b1
|
[
"MIT"
] | null | null | null |
ProgramUI.fld/ProgramUI.cpp
|
depaulo/OrganizerCpp
|
9847cb2d117bd493e127fb499bdbf9112cf388b1
|
[
"MIT"
] | null | null | null |
ProgramUI.fld/ProgramUI.cpp
|
depaulo/OrganizerCpp
|
9847cb2d117bd493e127fb499bdbf9112cf388b1
|
[
"MIT"
] | null | null | null |
// generated by Fast Light User Interface Designer (fluid) version 1.0305
#include "ProgramUI.h"
Fl_Menu_Item MainWindow::menu_[] = {
{"Manage account", 0, 0, 0, 64, (uchar)FL_NORMAL_LABEL, 0, 15, 0},
{"Create account", 0, (Fl_Callback*)CreateAcc_cb, 0, 0, (uchar)FL_NORMAL_LABEL, 0, 13, 0},
{"Save", 0, (Fl_Callback*)SaveAcc_cb, 0, 0, (uchar)FL_NORMAL_LABEL, 0, 13, 0},
{"Delete Acc", 0, (Fl_Callback*)CreateAcc_cb, 0, 0, (uchar)FL_NORMAL_LABEL, 0, 13, 0},
{0,0,0,0,0,0,0,0,0},
{"Help", 0, (Fl_Callback*)Help_cb, 0, 0, (uchar)FL_NORMAL_LABEL, 0, 15, 0},
{0,0,0,0,0,0,0,0,0}
};
void MainWindow::hide() {
mainwindow->hide();
}
void MainWindow::show() {
mainwindow->show();
}
/**
function that creates the window,
i put a function to show in the end,
so i dont need to ask to show in the main file.
*/
Fl_Double_Window* MainWindow::make() {
{ mainwindow = new Fl_Double_Window(1015, 655, "My Organizer");
mainwindow->tooltip("App for keeping your life organized.");
mainwindow->callback((Fl_Callback*)WinQuit_cb, (void*)(this));
mainwindow->align(Fl_Align(FL_ALIGN_TOP_LEFT));
{ Fl_Menu_Bar* o = new Fl_Menu_Bar(0, 0, 1455, 40);
o->labelsize(11);
o->textsize(11);
o->menu(menu_);
} // Fl_Menu_Bar* o
{ Fl_Tabs* o = new Fl_Tabs(25, 215, 965, 430);
o->labeltype(FL_ENGRAVED_LABEL);
o->labelsize(32);
o->align(Fl_Align(FL_ALIGN_TOP_RIGHT));
{ Fl_Group* o = new Fl_Group(25, 255, 960, 375, "Calendar");
o->labelsize(15);
o->hide();
{ Fl_Button* o = new Fl_Button(105, 365, 290, 115, "button 1");
o->labelsize(32);
o->callback((Fl_Callback*)CButton1_cb);
} // Fl_Button* o
o->end();
} // Fl_Group* o
{ Fl_Group* o = new Fl_Group(25, 255, 965, 375, "To do list");
o->box(FL_BORDER_BOX);
o->labelsize(15);
o->align(Fl_Align(FL_ALIGN_TOP_RIGHT));
{ Display = new Fl_Text_Display(55, 280, 900, 255);
buff = new Fl_Text_Buffer;
Display->buffer(buff);
} // Fl_Text_Display* Display
{ Fl_Button* o = new Fl_Button(365, 560, 140, 45, "Add");
o->labelsize(20);
o->callback((Fl_Callback*)TDAdd_cb);
} // Fl_Button* o
{ Fl_Button* o = new Fl_Button(575, 560, 140, 45, "Edit");
o->labelsize(20);
o->callback((Fl_Callback*)TDEdit_cb);
} // Fl_Button* o
{ Fl_Button* o = new Fl_Button(790, 560, 140, 45, "Delete");
o->labelsize(20);
o->callback((Fl_Callback*)TDDelete_cb);
} // Fl_Button* o
{ ToDoNumber = new Fl_Value_Input(165, 571, 175, 24, "ToDo number");
} // Fl_Value_Input* ToDoNumber
o->end();
} // Fl_Group* o
{ Fl_Group* o = new Fl_Group(25, 255, 965, 390, "Finances");
o->box(FL_BORDER_BOX);
o->labelsize(15);
o->align(Fl_Align(FL_ALIGN_TOP_RIGHT));
o->hide();
{ Fl_Button* o = new Fl_Button(735, 500, 215, 95, "button 3");
o->labelsize(32);
o->callback((Fl_Callback*)FButton3_cb);
} // Fl_Button* o
o->end();
Fl_Group::current()->resizable(o);
} // Fl_Group* o
o->end();
Fl_Group::current()->resizable(o);
} // Fl_Tabs* o
mainwindow->end();
} // Fl_Double_Window* mainwindow
mainwindow->show();
return mainwindow;
}
void CreateAccountWindow::hide() {
createaccountwindow->hide();
}
void CreateAccountWindow::show() {
createaccountwindow->show();
}
/**
function that creates the window,
i put a function to show in the end,
so i dont need to ask to show in the main file.
*/
Fl_Double_Window* CreateAccountWindow::make() {
{ createaccountwindow = new Fl_Double_Window(575, 470, "Create Account");
createaccountwindow->tooltip("Enter your data");
createaccountwindow->user_data((void*)(this));
createaccountwindow->align(Fl_Align(FL_ALIGN_TOP_LEFT));
{ Display = new Fl_Text_Display(105, 20, 365, 135);
Fl_Group::current()->resizable(Display);
buff = new Fl_Text_Buffer;
Display->buffer(buff);
} // Fl_Text_Display* Display
{ Fl_Group* o = new Fl_Group(10, 175, 550, 225, "Account details");
{ NameIn = new Fl_Input(72, 195, 175, 24, "Name:");
NameIn->tooltip("Enter your name");
} // Fl_Input* NameIn
{ BirthdayIn = new Fl_Input(72, 235, 175, 24, "Birthday:");
BirthdayIn->tooltip("Birthday dd/mm/yyyy");
} // Fl_Input* BirthdayIn
{ PasswordIn = new Fl_Input(345, 196, 175, 24, "Password:");
PasswordIn->tooltip("six caracters");
} // Fl_Input* PasswordIn
{ MoneyIn = new Fl_Value_Input(345, 236, 175, 24, "Money");
} // Fl_Value_Input* MoneyIn
{ FinanceHorizonIn = new Fl_Value_Input(235, 276, 110, 23, "Finance Horizon");
FinanceHorizonIn->tooltip("How many months you want to save money");
} // Fl_Value_Input* FinanceHorizonIn
{ Fl_Group* o = new Fl_Group(70, 325, 415, 75, "Choose the functionalities you want to use");
{ FinancesCB = new Fl_Check_Button(90, 345, 70, 15, "Finances");
FinancesCB->down_box(FL_DOWN_BOX);
FinancesCB->callback((Fl_Callback*)CheckButton_cb, (void*)(1));
} // Fl_Check_Button* FinancesCB
{ ToDoListCB = new Fl_Check_Button(215, 345, 70, 15, "To do List");
ToDoListCB->down_box(FL_DOWN_BOX);
ToDoListCB->callback((Fl_Callback*)CheckButton_cb, (void*)(2));
} // Fl_Check_Button* ToDoListCB
{ CalendarCB = new Fl_Check_Button(345, 345, 70, 15, "Calendar");
CalendarCB->down_box(FL_DOWN_BOX);
CalendarCB->callback((Fl_Callback*)CheckButton_cb, (void*)(3));
} // Fl_Check_Button* CalendarCB
o->end();
} // Fl_Group* o
o->end();
} // Fl_Group* o
{ Ok = new Fl_Return_Button(465, 415, 92, 35, "Ok");
Ok->callback((Fl_Callback*)CAButtonOK_cb);
} // Fl_Return_Button* Ok
createaccountwindow->end();
} // Fl_Double_Window* createaccountwindow
createaccountwindow->show();
return createaccountwindow;
}
void ToDoWindow::hide() {
ToDoWindow->hide();
}
void ToDoWindow::show() {
ToDoWindow->show();
}
/**
function that creates the window,
i put a function to show in the end,
so i dont need to ask to show in the main file.
*/
Fl_Double_Window* ToDoWindow::make() {
{ ToDoWindow = new Fl_Double_Window(575, 470, "To Do Window");
ToDoWindow->tooltip("Enter your data");
ToDoWindow->user_data((void*)(this));
ToDoWindow->align(Fl_Align(69));
{ Ok = new Fl_Return_Button(465, 415, 92, 35, "Ok");
Ok->callback((Fl_Callback*)TDWButtonOK_cb);
} // Fl_Return_Button* Ok
{ Date = new Fl_Input(120, 281, 120, 23, "Date:");
Date->tooltip("Date you want the iten to be done");
} // Fl_Input* Date
{ Display = new Fl_Text_Editor(25, 20, 520, 245);
buff = new Fl_Text_Buffer;
Display->buffer(buff);
} // Fl_Text_Editor* Display
{ StatusCB = new Fl_Check_Button(105, 410, 135, 20, "Completed?");
StatusCB->down_box(FL_DOWN_BOX);
StatusCB->callback((Fl_Callback*)CheckButton_cb, (void*)(4));
} // Fl_Check_Button* StatusCB
{ Name = new Fl_Input(120, 314, 120, 23, "Name:");
Name->tooltip("Person in Charge of the To Do");
} // Fl_Input* Name
{ Importance = new Fl_Input_Choice(120, 352, 180, 23, "Importance");
Importance->add("Very Important");
Importance->add("Important");
Importance->add("Normal");
Importance->add("Not Important");
} // Fl_Input_Choice* Importance
{ Tag = new Fl_Input(375, 282, 120, 23, "Tag");
Tag->tooltip("Tag, only one tag for now");
} // Fl_Input* Tag
{ Periocity = new Fl_Input_Choice(375, 312, 180, 23, "Periocity");
Periocity->tooltip("Set the periocit for this To Do");
Periocity->add("Once");
Periocity->add("Weekly");
Periocity->add("Montly");
Periocity->add("Yearly");
} // Fl_Input_Choice* Periocity
ToDoWindow->end();
ToDoWindow->resizable(ToDoWindow);
} // Fl_Double_Window* ToDoWindow
ToDoWindow->show();
return ToDoWindow;
}
void PasswordWindow::hide() {
PasswordWindow->hide();
}
void PasswordWindow::show() {
PasswordWindow->show();
}
/**
function that creates the window,
i put a function to show in the end,
so i dont need to ask to show in the main file.
*/
Fl_Double_Window* PasswordWindow::make() {
{ PassordWindow = new Fl_Double_Window(455, 235, "Password Manager");
PassordWindow->tooltip("Enter your data");
PassordWindow->user_data((void*)(this));
PassordWindow->align(Fl_Align(69));
{ Ok = new Fl_Return_Button(345, 185, 92, 35, "Ok");
Ok->callback((Fl_Callback*)PWButtonOK_cb);
} // Fl_Return_Button* Ok
{ NameChoice = new Fl_Input_Choice(150, 37, 180, 23, "User Name:");
} // Fl_Input_Choice* NameChoice
{ PasswordInput = new Fl_Input(150, 72, 120, 23, "Password:");
PasswordInput->tooltip("Tag, only one tag for now");
} // Fl_Input* PasswordInput
{ CreateUserButton = new Fl_Button(30, 190, 100, 30, "Create User");
CreateUserButton->callback((Fl_Callback*)CreateAcc_cb);
} // Fl_Button* CreateUserButton
PassordWindow->end();
PassordWindow->resizable(PassordWindow);
} // Fl_Double_Window* PassordWindow
PassordWindow->show();
return PassordWindow;
}
| 37.110672
| 99
| 0.626478
|
depaulo
|
752cf616666cc4a2985e357281b37b61d3eb4bb8
| 1,039
|
cpp
|
C++
|
codes/chap05/code_5_8.cpp
|
tokuhira/book_algorithm_solution
|
a24b68c5ef57a88e906991bbaf026bf17b5faab9
|
[
"CC0-1.0"
] | null | null | null |
codes/chap05/code_5_8.cpp
|
tokuhira/book_algorithm_solution
|
a24b68c5ef57a88e906991bbaf026bf17b5faab9
|
[
"CC0-1.0"
] | null | null | null |
codes/chap05/code_5_8.cpp
|
tokuhira/book_algorithm_solution
|
a24b68c5ef57a88e906991bbaf026bf17b5faab9
|
[
"CC0-1.0"
] | null | null | null |
#include <iostream>
#include <string>
#include <vector>
using namespace std;
template<class T> void chmin(T& a, T b) {
if (a > b) {
a = b;
}
}
const int INF = 1 << 29; // 十分大きな値 (ここでは 2^29 とする)
int main() {
// 入力
string S, T;
cin >> S >> T;
// DP テーブル定義
vector<vector<int>> dp(S.size() + 1, vector<int>(T.size() + 1, INF));
// DP 初期条件
dp[0][0] = 0;
// DPループ
for (int i = 0; i <= S.size(); ++i) {
for (int j = 0; j <= T.size(); ++j) {
// 変更操作
if (i > 0 && j > 0) {
if (S[i - 1] == T[j - 1]) {
chmin(dp[i][j], dp[i - 1][j - 1]);
}
else {
chmin(dp[i][j], dp[i - 1][j - 1] + 1);
}
}
// 削除操作
if (i > 0) chmin(dp[i][j], dp[i - 1][j] + 1);
// 挿入操作
if (j > 0) chmin(dp[i][j], dp[i][j - 1] + 1);
}
}
// 答えの出力
cout << dp[S.size()][T.size()] << endl;
}
| 21.204082
| 73
| 0.348412
|
tokuhira
|
752d5a6b7539b8ad641826b062f1c4cf4b0b3faa
| 5,014
|
cpp
|
C++
|
src/ColorConverterLib.cpp
|
luisllamasbinaburo/Arduino-RGBConverter
|
a6c0fc27218b23c0fb31bf55bd41afb2f075a19f
|
[
"Apache-2.0"
] | 9
|
2018-07-01T13:24:05.000Z
|
2022-02-17T00:30:58.000Z
|
src/ColorConverterLib.cpp
|
luisllamasbinaburo/Arduino-RGBConverter
|
a6c0fc27218b23c0fb31bf55bd41afb2f075a19f
|
[
"Apache-2.0"
] | 4
|
2018-06-04T21:34:43.000Z
|
2021-06-06T23:50:39.000Z
|
src/ColorConverterLib.cpp
|
luisllamasbinaburo/Arduino-RGBConverter
|
a6c0fc27218b23c0fb31bf55bd41afb2f075a19f
|
[
"Apache-2.0"
] | 4
|
2019-11-14T19:27:41.000Z
|
2022-02-17T00:31:01.000Z
|
/***************************************************
Copyright (c) 2017 Luis Llamas
(www.luisllamas.es)
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 "ColorConverterLib.h"
void ColorConverter::RgbToHsv(uint8_t red, uint8_t green, uint8_t blue, double& hue, double& saturation, double& value)
{
auto rd = static_cast<double>(red) / 255;
auto gd = static_cast<double>(green) / 255;
auto bd = static_cast<double>(blue) / 255;
auto max = threeway_max(rd, gd, bd), min = threeway_min(rd, gd, bd);
value = max;
auto d = max - min;
saturation = max == 0 ? 0 : d / max;
hue = 0;
if (max != min)
{
if (max == rd)
{
hue = (gd - bd) / d + (gd < bd ? 6 : 0);
}
else if (max == gd)
{
hue = (bd - rd) / d + 2;
}
else if (max == bd)
{
hue = (rd - gd) / d + 4;
}
hue /= 6;
}
}
void ColorConverter::RgbToHsl(uint8_t red, uint8_t green, uint8_t blue, double& hue, double& saturation, double& lighting)
{
auto rd = static_cast<double>(red) / 255;
auto gd = static_cast<double>(green) / 255;
auto bd = static_cast<double>(blue) / 255;
auto max = threeway_max(rd, gd, bd);
auto min = threeway_min(rd, gd, bd);
double h, s, l = (max + min) / 2;
if (max == min)
{
h = s = 0; // achromatic
}
else
{
auto d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
if (max == rd)
{
h = (gd - bd) / d + (gd < bd ? 6 : 0);
}
else if (max == gd)
{
h = (bd - rd) / d + 2;
}
else if (max == bd)
{
h = (rd - gd) / d + 4;
}
h /= 6;
}
hue = h;
saturation = s;
lighting = l;
}
void ColorConverter::HsvToRgb(double hue, double saturation, double value, uint8_t& red, uint8_t& green, uint8_t& blue)
{
double r, g, b;
auto i = static_cast<int>(hue * 6);
auto f = hue * 6 - i;
auto p = value * (1 - saturation);
auto q = value * (1 - f * saturation);
auto t = value * (1 - (1 - f) * saturation);
switch (i % 6)
{
case 0: r = value , g = t , b = p;
break;
case 1: r = q , g = value , b = p;
break;
case 2: r = p , g = value , b = t;
break;
case 3: r = p , g = q , b = value;
break;
case 4: r = t , g = p , b = value;
break;
case 5: r = value , g = p , b = q;
break;
}
red = static_cast<uint8_t>(r * 255);
green = static_cast<uint8_t>(g * 255);
blue = static_cast<uint8_t>(b * 255);
}
void ColorConverter::HslToRgb(double hue, double saturation, double lightness, uint8_t& red, uint8_t& green, uint8_t& blue)
{
double r, g, b;
if (saturation == 0)
{
r = g = b = lightness; // achromatic
}
else
{
auto q = lightness < 0.5 ? lightness * (1 + saturation) : lightness + saturation - lightness * saturation;
auto p = 2 * lightness - q;
r = hue2rgb(p, q, hue + 1 / 3.0);
g = hue2rgb(p, q, hue);
b = hue2rgb(p, q, hue - 1 / 3.0);
}
red = static_cast<uint8_t>(r * 255);
green = static_cast<uint8_t>(g * 255);
blue = static_cast<uint8_t>(b * 255);
}
void ColorConverter::TemperatureToRgb(int kelvin, uint8_t& red, uint8_t& green, uint8_t& blue)
{
auto temp = kelvin / 100;
if (temp <= 66)
{
red = 255;
green = 99.4708025861 * log(temp) - 161.1195681661;
if (temp <= 19)
{
blue = 0;
}
else
{
blue = 138.5177312231 * log(temp - 10) - 305.0447927307;
}
}
else
{
red = 329.698727446 * pow(temp - 60, -0.1332047592);
green = 288.1221695283 * pow(temp - 60, -0.0755148492);
blue = 255;
}
}
void ColorConverter::HexToRgb(String hex, uint8_t& red, uint8_t& green, uint8_t& blue)
{
long number;
if(hex[0] == '#') number = strtol(&hex[1], nullptr, 16);
else number = strtol(&hex[0], nullptr, 16);
red = number >> 16;
green = number >> 8 & 0xFF;
blue = number & 0xFF;
}
void ColorConverter::RgbToHex(uint8_t red, uint8_t green, uint8_t blue, String &hex)
{
char hexArray[6] = { 0 };
sprintf(hexArray, "%02X%02X%02X", red, green, blue);
hex = hexArray;
}
double inline ColorConverter::threeway_max(double a, double b, double c)
{
return max(a, max(b, c));
}
double inline ColorConverter::threeway_min(double a, double b, double c)
{
return min(a, min(b, c));
}
double ColorConverter::hue2rgb(double p, double q, double t)
{
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1 / 6.0) return p + (q - p) * 6 * t;
if (t < 1 / 2.0) return q;
if (t < 2 / 3.0) return p + (q - p) * (2 / 3.0 - t) * 6;
return p;
}
| 24.945274
| 305
| 0.566813
|
luisllamasbinaburo
|
75323464428f84ff8cebc3b1049684733a9aec29
| 4,453
|
cpp
|
C++
|
scripting/test/Coding/CodingTest.cpp
|
hhsaez/crimild
|
e3efee09489939338df55e8af9a1f9ddc01301f7
|
[
"BSD-3-Clause"
] | 36
|
2015-03-12T10:42:36.000Z
|
2022-01-12T04:20:40.000Z
|
scripting/test/Coding/CodingTest.cpp
|
hhsaez/crimild
|
e3efee09489939338df55e8af9a1f9ddc01301f7
|
[
"BSD-3-Clause"
] | 1
|
2015-12-17T00:25:43.000Z
|
2016-02-20T12:00:57.000Z
|
scripting/test/Coding/CodingTest.cpp
|
hhsaez/crimild
|
e3efee09489939338df55e8af9a1f9ddc01301f7
|
[
"BSD-3-Clause"
] | 6
|
2017-06-17T07:57:53.000Z
|
2019-04-09T21:11:24.000Z
|
/*
* Copyright (c) 2013, Hernan Saez
* 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 <organization> 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 "Coding/Codable.hpp"
#include "Coding/Encoder.hpp"
#include "Coding/Decoder.hpp"
#include "Coding/LuaEncoder.hpp"
#include "Coding/LuaDecoder.hpp"
#include "SceneGraph/Node.hpp"
#include "Foundation/ObjectFactory.hpp"
#include "gtest/gtest.h"
namespace crimild {
class CodableNode : public Node {
CRIMILD_IMPLEMENT_RTTI( crimild::CodableNode )
public:
explicit CodableNode( std::string name = "" ) : Node( name ) { }
virtual ~CodableNode( void ) { }
containers::Array< int > &getValues( void ) { return _values; }
containers::Array< SharedPointer< CodableNode > > &getChildren( void ) { return _children; }
private:
containers::Array< int > _values;
containers::Array< SharedPointer< CodableNode >> _children;
public:
virtual void encode( coding::Encoder &encoder ) override
{
Node::encode( encoder );
encoder.encode( "values", _values );
encoder.encode( "children", _children );
}
virtual void decode( coding::Decoder &decoder ) override
{
Node::decode( decoder );
decoder.decode( "values", _values );
decoder.decode( "children", _children );
}
};
}
using namespace crimild;
TEST( LuaCodableTest, codingEncoding )
{
CRIMILD_REGISTER_OBJECT_BUILDER( crimild::CodableNode )
auto n = crimild::alloc< crimild::CodableNode >( "a scene" );
n->getValues() = { 1, 2, 3, 4, 5 };
n->local().setTranslate( 10, 20, 30 );
n->world().setTranslate( 50, 70, 90 );
n->setWorldIsCurrent( true );
n->getChildren().add( crimild::alloc< crimild::CodableNode >( "child 1" ) );
n->getChildren().add( crimild::alloc< crimild::CodableNode >( "child 2" ) );
n->getChildren().add( crimild::alloc< crimild::CodableNode >( "child 3" ) );
auto encoder = crimild::alloc< crimild::coding::LuaEncoder >();
encoder->encode( n );
auto encoded = "scene = " + encoder->getEncodedString();
auto decoder = crimild::alloc< crimild::coding::LuaDecoder >();
decoder->parse( encoded );
auto n2 = decoder->getObjectAt< crimild::CodableNode >( 0 );
EXPECT_TRUE( n2 != nullptr );
EXPECT_EQ( n->getName(), n2->getName() );
EXPECT_EQ( n->getValues(), n2->getValues() );
EXPECT_EQ( n->getLocal().getTranslate(), n2->getLocal().getTranslate() );
EXPECT_EQ( n->getWorld().getTranslate(), n2->getWorld().getTranslate() );
EXPECT_EQ( n->worldIsCurrent(), n2->worldIsCurrent() );
EXPECT_EQ( n->getChildren().size(), n2->getChildren().size() );
EXPECT_EQ( n->getChildren()[ 0 ]->getName(), n2->getChildren()[ 0 ]->getName() );
EXPECT_EQ( n->getChildren()[ 1 ]->getName(), n2->getChildren()[ 1 ]->getName() );
EXPECT_EQ( n->getChildren()[ 2 ]->getName(), n2->getChildren()[ 2 ]->getName() );
}
| 39.40708
| 94
| 0.666742
|
hhsaez
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.